Debian Codegraph @

clang/lib/Serialization/ASTReader.cpp

raw
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 "TemplateArgumentHasher.h"
16 #include "clang/AST/ASTConsumer.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/ASTMutationListener.h"
19 #include "clang/AST/ASTStructuralEquivalence.h"
20 #include "clang/AST/ASTUnresolvedSet.h"
21 #include "clang/AST/AbstractTypeReader.h"
22 #include "clang/AST/Decl.h"
23 #include "clang/AST/DeclBase.h"
24 #include "clang/AST/DeclCXX.h"
25 #include "clang/AST/DeclFriend.h"
26 #include "clang/AST/DeclGroup.h"
27 #include "clang/AST/DeclObjC.h"
28 #include "clang/AST/DeclTemplate.h"
29 #include "clang/AST/DeclarationName.h"
30 #include "clang/AST/Expr.h"
31 #include "clang/AST/ExprCXX.h"
32 #include "clang/AST/ExternalASTSource.h"
33 #include "clang/AST/NestedNameSpecifier.h"
34 #include "clang/AST/ODRDiagsEmitter.h"
35 #include "clang/AST/OpenACCClause.h"
36 #include "clang/AST/OpenMPClause.h"
37 #include "clang/AST/RawCommentList.h"
38 #include "clang/AST/TemplateBase.h"
39 #include "clang/AST/TemplateName.h"
40 #include "clang/AST/Type.h"
41 #include "clang/AST/TypeLoc.h"
42 #include "clang/AST/TypeLocVisitor.h"
43 #include "clang/AST/UnresolvedSet.h"
44 #include "clang/Basic/ASTSourceDescriptor.h"
45 #include "clang/Basic/CommentOptions.h"
46 #include "clang/Basic/Diagnostic.h"
47 #include "clang/Basic/DiagnosticIDs.h"
48 #include "clang/Basic/DiagnosticOptions.h"
49 #include "clang/Basic/DiagnosticSema.h"
50 #include "clang/Basic/FileManager.h"
51 #include "clang/Basic/FileSystemOptions.h"
52 #include "clang/Basic/IdentifierTable.h"
53 #include "clang/Basic/LLVM.h"
54 #include "clang/Basic/LangOptions.h"
55 #include "clang/Basic/Module.h"
56 #include "clang/Basic/ObjCRuntime.h"
57 #include "clang/Basic/OpenACCKinds.h"
58 #include "clang/Basic/OpenMPKinds.h"
59 #include "clang/Basic/OperatorKinds.h"
60 #include "clang/Basic/PragmaKinds.h"
61 #include "clang/Basic/Sanitizers.h"
62 #include "clang/Basic/SourceLocation.h"
63 #include "clang/Basic/SourceManager.h"
64 #include "clang/Basic/SourceManagerInternals.h"
65 #include "clang/Basic/Specifiers.h"
66 #include "clang/Basic/TargetInfo.h"
67 #include "clang/Basic/TargetOptions.h"
68 #include "clang/Basic/TokenKinds.h"
69 #include "clang/Basic/Version.h"
70 #include "clang/Lex/HeaderSearch.h"
71 #include "clang/Lex/HeaderSearchOptions.h"
72 #include "clang/Lex/MacroInfo.h"
73 #include "clang/Lex/ModuleMap.h"
74 #include "clang/Lex/PreprocessingRecord.h"
75 #include "clang/Lex/Preprocessor.h"
76 #include "clang/Lex/PreprocessorOptions.h"
77 #include "clang/Lex/Token.h"
78 #include "clang/Sema/ObjCMethodList.h"
79 #include "clang/Sema/Scope.h"
80 #include "clang/Sema/Sema.h"
81 #include "clang/Sema/SemaCUDA.h"
82 #include "clang/Sema/SemaObjC.h"
83 #include "clang/Sema/Weak.h"
84 #include "clang/Serialization/ASTBitCodes.h"
85 #include "clang/Serialization/ASTDeserializationListener.h"
86 #include "clang/Serialization/ASTRecordReader.h"
87 #include "clang/Serialization/ContinuousRangeMap.h"
88 #include "clang/Serialization/GlobalModuleIndex.h"
89 #include "clang/Serialization/InMemoryModuleCache.h"
90 #include "clang/Serialization/ModuleCache.h"
91 #include "clang/Serialization/ModuleFile.h"
92 #include "clang/Serialization/ModuleFileExtension.h"
93 #include "clang/Serialization/ModuleManager.h"
94 #include "clang/Serialization/PCHContainerOperations.h"
95 #include "clang/Serialization/SerializationDiagnostic.h"
96 #include "llvm/ADT/APFloat.h"
97 #include "llvm/ADT/APInt.h"
98 #include "llvm/ADT/ArrayRef.h"
99 #include "llvm/ADT/DenseMap.h"
100 #include "llvm/ADT/FoldingSet.h"
101 #include "llvm/ADT/IntrusiveRefCntPtr.h"
102 #include "llvm/ADT/STLExtras.h"
103 #include "llvm/ADT/ScopeExit.h"
104 #include "llvm/ADT/Sequence.h"
105 #include "llvm/ADT/SmallPtrSet.h"
106 #include "llvm/ADT/SmallVector.h"
107 #include "llvm/ADT/StringExtras.h"
108 #include "llvm/ADT/StringMap.h"
109 #include "llvm/ADT/StringRef.h"
110 #include "llvm/ADT/iterator_range.h"
111 #include "llvm/Bitstream/BitstreamReader.h"
112 #include "llvm/Support/Compiler.h"
113 #include "llvm/Support/Compression.h"
114 #include "llvm/Support/DJB.h"
115 #include "llvm/Support/Endian.h"
116 #include "llvm/Support/Error.h"
117 #include "llvm/Support/ErrorHandling.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 ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
155 return First->ReadFullVersionInformation(FullVersion) ||
156 Second->ReadFullVersionInformation(FullVersion);
157 }
158
159 void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
160 First->ReadModuleName(ModuleName);
161 Second->ReadModuleName(ModuleName);
162 }
163
164 void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
165 First->ReadModuleMapFile(ModuleMapPath);
166 Second->ReadModuleMapFile(ModuleMapPath);
167 }
168
169 bool ChainedASTReaderListener::ReadLanguageOptions(
170 const LangOptions &LangOpts, StringRef ModuleFilename, bool Complain,
171 bool AllowCompatibleDifferences) {
172 return First->ReadLanguageOptions(LangOpts, ModuleFilename, Complain,
173 AllowCompatibleDifferences) ||
174 Second->ReadLanguageOptions(LangOpts, ModuleFilename, Complain,
175 AllowCompatibleDifferences);
176 }
177
178 bool ChainedASTReaderListener::ReadCodeGenOptions(
179 const CodeGenOptions &CGOpts, StringRef ModuleFilename, bool Complain,
180 bool AllowCompatibleDifferences) {
181 return First->ReadCodeGenOptions(CGOpts, ModuleFilename, Complain,
182 AllowCompatibleDifferences) ||
183 Second->ReadCodeGenOptions(CGOpts, ModuleFilename, Complain,
184 AllowCompatibleDifferences);
185 }
186
187 bool ChainedASTReaderListener::ReadTargetOptions(
188 const TargetOptions &TargetOpts, StringRef ModuleFilename, bool Complain,
189 bool AllowCompatibleDifferences) {
190 return First->ReadTargetOptions(TargetOpts, ModuleFilename, Complain,
191 AllowCompatibleDifferences) ||
192 Second->ReadTargetOptions(TargetOpts, ModuleFilename, Complain,
193 AllowCompatibleDifferences);
194 }
195
196 bool ChainedASTReaderListener::ReadDiagnosticOptions(
197 DiagnosticOptions &DiagOpts, StringRef ModuleFilename, bool Complain) {
198 return First->ReadDiagnosticOptions(DiagOpts, ModuleFilename, Complain) ||
199 Second->ReadDiagnosticOptions(DiagOpts, ModuleFilename, Complain);
200 }
201
202 bool
203 ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
204 bool Complain) {
205 return First->ReadFileSystemOptions(FSOpts, Complain) ||
206 Second->ReadFileSystemOptions(FSOpts, Complain);
207 }
208
209 bool ChainedASTReaderListener::ReadHeaderSearchOptions(
210 const HeaderSearchOptions &HSOpts, StringRef ModuleFilename,
211 StringRef SpecificModuleCachePath, bool Complain) {
212 return First->ReadHeaderSearchOptions(HSOpts, ModuleFilename,
213 SpecificModuleCachePath, Complain) ||
214 Second->ReadHeaderSearchOptions(HSOpts, ModuleFilename,
215 SpecificModuleCachePath, Complain);
216 }
217
218 bool ChainedASTReaderListener::ReadPreprocessorOptions(
219 const PreprocessorOptions &PPOpts, StringRef ModuleFilename,
220 bool ReadMacros, bool Complain, std::string &SuggestedPredefines) {
221 return First->ReadPreprocessorOptions(PPOpts, ModuleFilename, ReadMacros,
222 Complain, SuggestedPredefines) ||
223 Second->ReadPreprocessorOptions(PPOpts, ModuleFilename, ReadMacros,
224 Complain, SuggestedPredefines);
225 }
226
227 void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
228 uint32_t Value) {
229 First->ReadCounter(M, Value);
230 Second->ReadCounter(M, Value);
231 }
232
233 bool ChainedASTReaderListener::needsInputFileVisitation() {
234 return First->needsInputFileVisitation() ||
235 Second->needsInputFileVisitation();
236 }
237
238 bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
239 return First->needsSystemInputFileVisitation() ||
240 Second->needsSystemInputFileVisitation();
241 }
242
243 void ChainedASTReaderListener::visitModuleFile(StringRef Filename,
244 ModuleKind Kind) {
245 First->visitModuleFile(Filename, Kind);
246 Second->visitModuleFile(Filename, Kind);
247 }
248
249 bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
250 bool isSystem,
251 bool isOverridden,
252 bool isExplicitModule) {
253 bool Continue = false;
254 if (First->needsInputFileVisitation() &&
255 (!isSystem || First->needsSystemInputFileVisitation()))
256 Continue |= First->visitInputFile(Filename, isSystem, isOverridden,
257 isExplicitModule);
258 if (Second->needsInputFileVisitation() &&
259 (!isSystem || Second->needsSystemInputFileVisitation()))
260 Continue |= Second->visitInputFile(Filename, isSystem, isOverridden,
261 isExplicitModule);
262 return Continue;
263 }
264
265 void ChainedASTReaderListener::readModuleFileExtension(
266 const ModuleFileExtensionMetadata &Metadata) {
267 First->readModuleFileExtension(Metadata);
268 Second->readModuleFileExtension(Metadata);
269 }
270
271 //===----------------------------------------------------------------------===//
272 // PCH validator implementation
273 //===----------------------------------------------------------------------===//
274
275 ASTReaderListener::~ASTReaderListener() = default;
276
277 /// Compare the given set of language options against an existing set of
278 /// language options.
279 ///
280 /// \param Diags If non-NULL, diagnostics will be emitted via this engine.
281 /// \param AllowCompatibleDifferences If true, differences between compatible
282 /// language options will be permitted.
283 ///
284 /// \returns true if the languagae options mis-match, false otherwise.
285 static bool checkLanguageOptions(const LangOptions &LangOpts,
286 const LangOptions &ExistingLangOpts,
287 StringRef ModuleFilename,
288 DiagnosticsEngine *Diags,
289 bool AllowCompatibleDifferences = true) {
290 // FIXME: Replace with C++20 `using enum LangOptions::CompatibilityKind`.
291 using CK = LangOptions::CompatibilityKind;
292
293 #define LANGOPT(Name, Bits, Default, Compatibility, Description) \
294 if constexpr (CK::Compatibility != CK::Benign) { \
295 if ((CK::Compatibility == CK::NotCompatible) || \
296 (CK::Compatibility == CK::Compatible && \
297 !AllowCompatibleDifferences)) { \
298 if (ExistingLangOpts.Name != LangOpts.Name) { \
299 if (Diags) { \
300 if (Bits == 1) \
301 Diags->Report(diag::err_ast_file_langopt_mismatch) \
302 << Description << LangOpts.Name << ExistingLangOpts.Name \
303 << ModuleFilename; \
304 else \
305 Diags->Report(diag::err_ast_file_langopt_value_mismatch) \
306 << Description << ModuleFilename; \
307 } \
308 return true; \
309 } \
310 } \
311 }
312
313 #define VALUE_LANGOPT(Name, Bits, Default, Compatibility, Description) \
314 if constexpr (CK::Compatibility != CK::Benign) { \
315 if ((CK::Compatibility == CK::NotCompatible) || \
316 (CK::Compatibility == CK::Compatible && \
317 !AllowCompatibleDifferences)) { \
318 if (ExistingLangOpts.Name != LangOpts.Name) { \
319 if (Diags) \
320 Diags->Report(diag::err_ast_file_langopt_value_mismatch) \
321 << Description << ModuleFilename; \
322 return true; \
323 } \
324 } \
325 }
326
327 #define ENUM_LANGOPT(Name, Type, Bits, Default, Compatibility, Description) \
328 if constexpr (CK::Compatibility != CK::Benign) { \
329 if ((CK::Compatibility == CK::NotCompatible) || \
330 (CK::Compatibility == CK::Compatible && \
331 !AllowCompatibleDifferences)) { \
332 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
333 if (Diags) \
334 Diags->Report(diag::err_ast_file_langopt_value_mismatch) \
335 << Description << ModuleFilename; \
336 return true; \
337 } \
338 } \
339 }
340
341 #include "clang/Basic/LangOptions.def"
342
343 if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) {
344 if (Diags)
345 Diags->Report(diag::err_ast_file_langopt_value_mismatch)
346 << "module features" << ModuleFilename;
347 return true;
348 }
349
350 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
351 if (Diags)
352 Diags->Report(diag::err_ast_file_langopt_value_mismatch)
353 << "target Objective-C runtime" << ModuleFilename;
354 return true;
355 }
356
357 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
358 LangOpts.CommentOpts.BlockCommandNames) {
359 if (Diags)
360 Diags->Report(diag::err_ast_file_langopt_value_mismatch)
361 << "block command names" << ModuleFilename;
362 return true;
363 }
364
365 // Sanitizer feature mismatches are treated as compatible differences. If
366 // compatible differences aren't allowed, we still only want to check for
367 // mismatches of non-modular sanitizers (the only ones which can affect AST
368 // generation).
369 if (!AllowCompatibleDifferences) {
370 SanitizerMask ModularSanitizers = getPPTransparentSanitizers();
371 SanitizerSet ExistingSanitizers = ExistingLangOpts.Sanitize;
372 SanitizerSet ImportedSanitizers = LangOpts.Sanitize;
373 ExistingSanitizers.clear(ModularSanitizers);
374 ImportedSanitizers.clear(ModularSanitizers);
375 if (ExistingSanitizers.Mask != ImportedSanitizers.Mask) {
376 const std::string Flag = "-fsanitize=";
377 if (Diags) {
378 #define SANITIZER(NAME, ID) \
379 { \
380 bool InExistingModule = ExistingSanitizers.has(SanitizerKind::ID); \
381 bool InImportedModule = ImportedSanitizers.has(SanitizerKind::ID); \
382 if (InExistingModule != InImportedModule) \
383 Diags->Report(diag::err_ast_file_targetopt_feature_mismatch) \
384 << InExistingModule << ModuleFilename << (Flag + NAME); \
385 }
386 #include "clang/Basic/Sanitizers.def"
387 }
388 return true;
389 }
390 }
391
392 return false;
393 }
394
395 static bool checkCodegenOptions(const CodeGenOptions &CGOpts,
396 const CodeGenOptions &ExistingCGOpts,
397 StringRef ModuleFilename,
398 DiagnosticsEngine *Diags,
399 bool AllowCompatibleDifferences = true) {
400 // FIXME: Specify and print a description for each option instead of the name.
401 // FIXME: Replace with C++20 `using enum CodeGenOptions::CompatibilityKind`.
402 using CK = CodeGenOptions::CompatibilityKind;
403 #define CODEGENOPT(Name, Bits, Default, Compatibility) \
404 if constexpr (CK::Compatibility != CK::Benign) { \
405 if ((CK::Compatibility == CK::NotCompatible) || \
406 (CK::Compatibility == CK::Compatible && \
407 !AllowCompatibleDifferences)) { \
408 if (ExistingCGOpts.Name != CGOpts.Name) { \
409 if (Diags) { \
410 if (Bits == 1) \
411 Diags->Report(diag::err_ast_file_codegenopt_mismatch) \
412 << #Name << CGOpts.Name << ExistingCGOpts.Name \
413 << ModuleFilename; \
414 else \
415 Diags->Report(diag::err_ast_file_codegenopt_value_mismatch) \
416 << #Name << ModuleFilename; \
417 } \
418 return true; \
419 } \
420 } \
421 }
422
423 #define VALUE_CODEGENOPT(Name, Bits, Default, Compatibility) \
424 if constexpr (CK::Compatibility != CK::Benign) { \
425 if ((CK::Compatibility == CK::NotCompatible) || \
426 (CK::Compatibility == CK::Compatible && \
427 !AllowCompatibleDifferences)) { \
428 if (ExistingCGOpts.Name != CGOpts.Name) { \
429 if (Diags) \
430 Diags->Report(diag::err_ast_file_codegenopt_value_mismatch) \
431 << #Name << ModuleFilename; \
432 return true; \
433 } \
434 } \
435 }
436 #define ENUM_CODEGENOPT(Name, Type, Bits, Default, Compatibility) \
437 if constexpr (CK::Compatibility != CK::Benign) { \
438 if ((CK::Compatibility == CK::NotCompatible) || \
439 (CK::Compatibility == CK::Compatible && \
440 !AllowCompatibleDifferences)) { \
441 if (ExistingCGOpts.get##Name() != CGOpts.get##Name()) { \
442 if (Diags) \
443 Diags->Report(diag::err_ast_file_codegenopt_value_mismatch) \
444 << #Name << ModuleFilename; \
445 return true; \
446 } \
447 } \
448 }
449 #define DEBUGOPT(Name, Bits, Default, Compatibility)
450 #define VALUE_DEBUGOPT(Name, Bits, Default, Compatibility)
451 #define ENUM_DEBUGOPT(Name, Type, Bits, Default, Compatibility)
452 #include "clang/Basic/CodeGenOptions.def"
453
454 return false;
455 }
456
457 /// Compare the given set of target options against an existing set of
458 /// target options.
459 ///
460 /// \param Diags If non-NULL, diagnostics will be emitted via this engine.
461 ///
462 /// \returns true if the target options mis-match, false otherwise.
463 static bool checkTargetOptions(const TargetOptions &TargetOpts,
464 const TargetOptions &ExistingTargetOpts,
465 StringRef ModuleFilename,
466 DiagnosticsEngine *Diags,
467 bool AllowCompatibleDifferences = true) {
468 #define CHECK_TARGET_OPT(Field, Name) \
469 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
470 if (Diags) \
471 Diags->Report(diag::err_ast_file_targetopt_mismatch) \
472 << ModuleFilename << Name << TargetOpts.Field \
473 << ExistingTargetOpts.Field; \
474 return true; \
475 }
476
477 // The triple and ABI must match exactly.
478 CHECK_TARGET_OPT(Triple, "target");
479 CHECK_TARGET_OPT(ABI, "target ABI");
480
481 // We can tolerate different CPUs in many cases, notably when one CPU
482 // supports a strict superset of another. When allowing compatible
483 // differences skip this check.
484 if (!AllowCompatibleDifferences) {
485 CHECK_TARGET_OPT(CPU, "target CPU");
486 CHECK_TARGET_OPT(TuneCPU, "tune CPU");
487 }
488
489 #undef CHECK_TARGET_OPT
490
491 // Compare feature sets.
492 SmallVector<StringRef, 4> ExistingFeatures(
493 ExistingTargetOpts.FeaturesAsWritten.begin(),
494 ExistingTargetOpts.FeaturesAsWritten.end());
495 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
496 TargetOpts.FeaturesAsWritten.end());
497 llvm::sort(ExistingFeatures);
498 llvm::sort(ReadFeatures);
499
500 // We compute the set difference in both directions explicitly so that we can
501 // diagnose the differences differently.
502 SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
503 std::set_difference(
504 ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
505 ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
506 std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
507 ExistingFeatures.begin(), ExistingFeatures.end(),
508 std::back_inserter(UnmatchedReadFeatures));
509
510 // If we are allowing compatible differences and the read feature set is
511 // a strict subset of the existing feature set, there is nothing to diagnose.
512 if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
513 return false;
514
515 if (Diags) {
516 for (StringRef Feature : UnmatchedReadFeatures)
517 Diags->Report(diag::err_ast_file_targetopt_feature_mismatch)
518 << /* is-existing-feature */ false << ModuleFilename << Feature;
519 for (StringRef Feature : UnmatchedExistingFeatures)
520 Diags->Report(diag::err_ast_file_targetopt_feature_mismatch)
521 << /* is-existing-feature */ true << ModuleFilename << Feature;
522 }
523
524 return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
525 }
526
527 bool PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
528 StringRef ModuleFilename, bool Complain,
529 bool AllowCompatibleDifferences) {
530 const LangOptions &ExistingLangOpts = PP.getLangOpts();
531 return checkLanguageOptions(LangOpts, ExistingLangOpts, ModuleFilename,
532 Complain ? &Reader.Diags : nullptr,
533 AllowCompatibleDifferences);
534 }
535
536 bool PCHValidator::ReadCodeGenOptions(const CodeGenOptions &CGOpts,
537 StringRef ModuleFilename, bool Complain,
538 bool AllowCompatibleDifferences) {
539 const CodeGenOptions &ExistingCGOpts = Reader.getCodeGenOpts();
540 return checkCodegenOptions(ExistingCGOpts, CGOpts, ModuleFilename,
541 Complain ? &Reader.Diags : nullptr,
542 AllowCompatibleDifferences);
543 }
544
545 bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
546 StringRef ModuleFilename, bool Complain,
547 bool AllowCompatibleDifferences) {
548 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
549 return checkTargetOptions(TargetOpts, ExistingTargetOpts, ModuleFilename,
550 Complain ? &Reader.Diags : nullptr,
551 AllowCompatibleDifferences);
552 }
553
554 namespace {
555
556 using MacroDefinitionsMap =
557 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>;
558 using DeclsMap = llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8>>;
559
560 } // namespace
561
562 static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
563 DiagnosticsEngine &Diags,
564 StringRef ModuleFilename,
565 bool Complain) {
566 using Level = DiagnosticsEngine::Level;
567
568 // Check current mappings for new -Werror mappings, and the stored mappings
569 // for cases that were explicitly mapped to *not* be errors that are now
570 // errors because of options like -Werror.
571 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
572
573 for (DiagnosticsEngine *MappingSource : MappingSources) {
574 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
575 diag::kind DiagID = DiagIDMappingPair.first;
576 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
577 if (CurLevel < DiagnosticsEngine::Error)
578 continue; // not significant
579 Level StoredLevel =
580 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
581 if (StoredLevel < DiagnosticsEngine::Error) {
582 if (Complain)
583 Diags.Report(diag::err_ast_file_diagopt_mismatch)
584 << "-Werror=" + Diags.getDiagnosticIDs()
585 ->getWarningOptionForDiag(DiagID)
586 .str()
587 << ModuleFilename;
588 return true;
589 }
590 }
591 }
592
593 return false;
594 }
595
596 static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
597 diag::Severity Ext = Diags.getExtensionHandlingBehavior();
598 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
599 return true;
600 return Ext >= diag::Severity::Error;
601 }
602
603 static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
604 DiagnosticsEngine &Diags,
605 StringRef ModuleFilename, bool IsSystem,
606 bool SystemHeaderWarningsInModule,
607 bool Complain) {
608 // Top-level options
609 if (IsSystem) {
610 if (Diags.getSuppressSystemWarnings())
611 return false;
612 // If -Wsystem-headers was not enabled before, and it was not explicit,
613 // be conservative
614 if (StoredDiags.getSuppressSystemWarnings() &&
615 !SystemHeaderWarningsInModule) {
616 if (Complain)
617 Diags.Report(diag::err_ast_file_diagopt_mismatch)
618 << "-Wsystem-headers" << ModuleFilename;
619 return true;
620 }
621 }
622
623 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
624 if (Complain)
625 Diags.Report(diag::err_ast_file_diagopt_mismatch)
626 << "-Werror" << ModuleFilename;
627 return true;
628 }
629
630 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
631 !StoredDiags.getEnableAllWarnings()) {
632 if (Complain)
633 Diags.Report(diag::err_ast_file_diagopt_mismatch)
634 << "-Weverything -Werror" << ModuleFilename;
635 return true;
636 }
637
638 if (isExtHandlingFromDiagsError(Diags) &&
639 !isExtHandlingFromDiagsError(StoredDiags)) {
640 if (Complain)
641 Diags.Report(diag::err_ast_file_diagopt_mismatch)
642 << "-pedantic-errors" << ModuleFilename;
643 return true;
644 }
645
646 return checkDiagnosticGroupMappings(StoredDiags, Diags, ModuleFilename,
647 Complain);
648 }
649
650 /// Return the top import module if it is implicit, nullptr otherwise.
651 static Module *getTopImportImplicitModule(ModuleManager &ModuleMgr,
652 Preprocessor &PP) {
653 // If the original import came from a file explicitly generated by the user,
654 // don't check the diagnostic mappings.
655 // FIXME: currently this is approximated by checking whether this is not a
656 // module import of an implicitly-loaded module file.
657 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
658 // the transitive closure of its imports, since unrelated modules cannot be
659 // imported until after this module finishes validation.
660 ModuleFile *TopImport = &*ModuleMgr.rbegin();
661 while (!TopImport->ImportedBy.empty())
662 TopImport = TopImport->ImportedBy[0];
663 if (TopImport->Kind != MK_ImplicitModule)
664 return nullptr;
665
666 StringRef ModuleName = TopImport->ModuleName;
667 assert(!ModuleName.empty() && "diagnostic options read before module name");
668
669 Module *M =
670 PP.getHeaderSearchInfo().lookupModule(ModuleName, TopImport->ImportLoc);
671 assert(M && "missing module");
672 return M;
673 }
674
675 bool PCHValidator::ReadDiagnosticOptions(DiagnosticOptions &DiagOpts,
676 StringRef ModuleFilename,
677 bool Complain) {
678 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
679 IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
680 auto Diags = llvm::makeIntrusiveRefCnt<DiagnosticsEngine>(DiagIDs, DiagOpts);
681 // This should never fail, because we would have processed these options
682 // before writing them to an ASTFile.
683 ProcessWarningOptions(*Diags, DiagOpts,
684 PP.getFileManager().getVirtualFileSystem(),
685 /*Report*/ false);
686
687 ModuleManager &ModuleMgr = Reader.getModuleManager();
688 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
689
690 Module *TopM = getTopImportImplicitModule(ModuleMgr, PP);
691 if (!TopM)
692 return false;
693
694 Module *Importer = PP.getCurrentModule();
695
696 DiagnosticOptions &ExistingOpts = ExistingDiags.getDiagnosticOptions();
697 bool SystemHeaderWarningsInModule =
698 Importer && llvm::is_contained(ExistingOpts.SystemHeaderWarningsModules,
699 Importer->Name);
700
701 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
702 // contains the union of their flags.
703 return checkDiagnosticMappings(*Diags, ExistingDiags, ModuleFilename,
704 TopM->IsSystem, SystemHeaderWarningsInModule,
705 Complain);
706 }
707
708 /// Collect the macro definitions provided by the given preprocessor
709 /// options.
710 static void
711 collectMacroDefinitions(const PreprocessorOptions &PPOpts,
712 MacroDefinitionsMap &Macros,
713 SmallVectorImpl<StringRef> *MacroNames = nullptr) {
714 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
715 StringRef Macro = PPOpts.Macros[I].first;
716 bool IsUndef = PPOpts.Macros[I].second;
717
718 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
719 StringRef MacroName = MacroPair.first;
720 StringRef MacroBody = MacroPair.second;
721
722 // For an #undef'd macro, we only care about the name.
723 if (IsUndef) {
724 auto [It, Inserted] = Macros.try_emplace(MacroName);
725 if (MacroNames && Inserted)
726 MacroNames->push_back(MacroName);
727
728 It->second = std::make_pair("", true);
729 continue;
730 }
731
732 // For a #define'd macro, figure out the actual definition.
733 if (MacroName.size() == Macro.size())
734 MacroBody = "1";
735 else {
736 // Note: GCC drops anything following an end-of-line character.
737 StringRef::size_type End = MacroBody.find_first_of("\n\r");
738 MacroBody = MacroBody.substr(0, End);
739 }
740
741 auto [It, Inserted] = Macros.try_emplace(MacroName);
742 if (MacroNames && Inserted)
743 MacroNames->push_back(MacroName);
744 It->second = std::make_pair(MacroBody, false);
745 }
746 }
747
748 enum OptionValidation {
749 OptionValidateNone,
750 OptionValidateContradictions,
751 OptionValidateStrictMatches,
752 };
753
754 /// Check the preprocessor options deserialized from the control block
755 /// against the preprocessor options in an existing preprocessor.
756 ///
757 /// \param Diags If non-null, produce diagnostics for any mismatches incurred.
758 /// \param Validation If set to OptionValidateNone, ignore differences in
759 /// preprocessor options. If set to OptionValidateContradictions,
760 /// require that options passed both in the AST file and on the command
761 /// line (-D or -U) match, but tolerate options missing in one or the
762 /// other. If set to OptionValidateContradictions, require that there
763 /// are no differences in the options between the two.
764 static bool checkPreprocessorOptions(
765 const PreprocessorOptions &PPOpts,
766 const PreprocessorOptions &ExistingPPOpts, StringRef ModuleFilename,
767 bool ReadMacros, DiagnosticsEngine *Diags, FileManager &FileMgr,
768 std::string &SuggestedPredefines, const LangOptions &LangOpts,
769 OptionValidation Validation = OptionValidateContradictions) {
770 if (ReadMacros) {
771 // Check macro definitions.
772 MacroDefinitionsMap ASTFileMacros;
773 collectMacroDefinitions(PPOpts, ASTFileMacros);
774 MacroDefinitionsMap ExistingMacros;
775 SmallVector<StringRef, 4> ExistingMacroNames;
776 collectMacroDefinitions(ExistingPPOpts, ExistingMacros,
777 &ExistingMacroNames);
778
779 // Use a line marker to enter the <command line> file, as the defines and
780 // undefines here will have come from the command line.
781 SuggestedPredefines += "# 1 \"<command line>\" 1\n";
782
783 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
784 // Dig out the macro definition in the existing preprocessor options.
785 StringRef MacroName = ExistingMacroNames[I];
786 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
787
788 // Check whether we know anything about this macro name or not.
789 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>::iterator Known =
790 ASTFileMacros.find(MacroName);
791 if (Validation == OptionValidateNone || Known == ASTFileMacros.end()) {
792 if (Validation == OptionValidateStrictMatches) {
793 // If strict matches are requested, don't tolerate any extra defines
794 // on the command line that are missing in the AST file.
795 if (Diags) {
796 Diags->Report(diag::err_ast_file_macro_def_undef)
797 << MacroName << true << ModuleFilename;
798 }
799 return true;
800 }
801 // FIXME: Check whether this identifier was referenced anywhere in the
802 // AST file. If so, we should reject the AST file. Unfortunately, this
803 // information isn't in the control block. What shall we do about it?
804
805 if (Existing.second) {
806 SuggestedPredefines += "#undef ";
807 SuggestedPredefines += MacroName.str();
808 SuggestedPredefines += '\n';
809 } else {
810 SuggestedPredefines += "#define ";
811 SuggestedPredefines += MacroName.str();
812 SuggestedPredefines += ' ';
813 SuggestedPredefines += Existing.first.str();
814 SuggestedPredefines += '\n';
815 }
816 continue;
817 }
818
819 // If the macro was defined in one but undef'd in the other, we have a
820 // conflict.
821 if (Existing.second != Known->second.second) {
822 if (Diags) {
823 Diags->Report(diag::err_ast_file_macro_def_undef)
824 << MacroName << Known->second.second << ModuleFilename;
825 }
826 return true;
827 }
828
829 // If the macro was #undef'd in both, or if the macro bodies are
830 // identical, it's fine.
831 if (Existing.second || Existing.first == Known->second.first) {
832 ASTFileMacros.erase(Known);
833 continue;
834 }
835
836 // The macro bodies differ; complain.
837 if (Diags) {
838 Diags->Report(diag::err_ast_file_macro_def_conflict)
839 << MacroName << Known->second.first << Existing.first
840 << ModuleFilename;
841 }
842 return true;
843 }
844
845 // Leave the <command line> file and return to <built-in>.
846 SuggestedPredefines += "# 1 \"<built-in>\" 2\n";
847
848 if (Validation == OptionValidateStrictMatches) {
849 // If strict matches are requested, don't tolerate any extra defines in
850 // the AST file that are missing on the command line.
851 for (const auto &MacroName : ASTFileMacros.keys()) {
852 if (Diags) {
853 Diags->Report(diag::err_ast_file_macro_def_undef)
854 << MacroName << false << ModuleFilename;
855 }
856 return true;
857 }
858 }
859 }
860
861 // Check whether we're using predefines.
862 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines &&
863 Validation != OptionValidateNone) {
864 if (Diags) {
865 Diags->Report(diag::err_ast_file_undef)
866 << ExistingPPOpts.UsePredefines << ModuleFilename;
867 }
868 return true;
869 }
870
871 // Detailed record is important since it is used for the module cache hash.
872 if (LangOpts.Modules &&
873 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord &&
874 Validation != OptionValidateNone) {
875 if (Diags) {
876 Diags->Report(diag::err_ast_file_pp_detailed_record)
877 << PPOpts.DetailedRecord << ModuleFilename;
878 }
879 return true;
880 }
881
882 // Compute the #include and #include_macros lines we need.
883 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
884 StringRef File = ExistingPPOpts.Includes[I];
885
886 if (!ExistingPPOpts.ImplicitPCHInclude.empty() &&
887 !ExistingPPOpts.PCHThroughHeader.empty()) {
888 // In case the through header is an include, we must add all the includes
889 // to the predefines so the start point can be determined.
890 SuggestedPredefines += "#include \"";
891 SuggestedPredefines += File;
892 SuggestedPredefines += "\"\n";
893 continue;
894 }
895
896 if (File == ExistingPPOpts.ImplicitPCHInclude)
897 continue;
898
899 if (llvm::is_contained(PPOpts.Includes, File))
900 continue;
901
902 SuggestedPredefines += "#include \"";
903 SuggestedPredefines += File;
904 SuggestedPredefines += "\"\n";
905 }
906
907 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
908 StringRef File = ExistingPPOpts.MacroIncludes[I];
909 if (llvm::is_contained(PPOpts.MacroIncludes, File))
910 continue;
911
912 SuggestedPredefines += "#__include_macros \"";
913 SuggestedPredefines += File;
914 SuggestedPredefines += "\"\n##\n";
915 }
916
917 return false;
918 }
919
920 bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
921 StringRef ModuleFilename,
922 bool ReadMacros, bool Complain,
923 std::string &SuggestedPredefines) {
924 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
925
926 return checkPreprocessorOptions(
927 PPOpts, ExistingPPOpts, ModuleFilename, ReadMacros,
928 Complain ? &Reader.Diags : nullptr, PP.getFileManager(),
929 SuggestedPredefines, PP.getLangOpts());
930 }
931
932 bool SimpleASTReaderListener::ReadPreprocessorOptions(
933 const PreprocessorOptions &PPOpts, StringRef ModuleFilename,
934 bool ReadMacros, bool Complain, std::string &SuggestedPredefines) {
935 return checkPreprocessorOptions(PPOpts, PP.getPreprocessorOpts(),
936 ModuleFilename, ReadMacros, nullptr,
937 PP.getFileManager(), SuggestedPredefines,
938 PP.getLangOpts(), OptionValidateNone);
939 }
940
941 /// Check that the specified and the existing module cache paths are equivalent.
942 ///
943 /// \param Diags If non-null, produce diagnostics for any mismatches incurred.
944 /// \returns true when the module cache paths differ.
945 static bool checkModuleCachePath(
946 llvm::vfs::FileSystem &VFS, StringRef SpecificModuleCachePath,
947 StringRef ExistingModuleCachePath, StringRef ASTFilename,
948 DiagnosticsEngine *Diags, const LangOptions &LangOpts,
949 const PreprocessorOptions &PPOpts, const HeaderSearchOptions &HSOpts,
950 const HeaderSearchOptions &ASTFileHSOpts) {
951 if (!LangOpts.Modules || PPOpts.AllowPCHWithDifferentModulesCachePath ||
952 SpecificModuleCachePath == ExistingModuleCachePath)
953 return false;
954 auto EqualOrErr =
955 VFS.equivalent(SpecificModuleCachePath, ExistingModuleCachePath);
956 if (EqualOrErr && *EqualOrErr)
957 return false;
958 if (Diags) {
959 // If the module cache arguments provided from the command line are the
960 // same, the mismatch must come from other arguments of the configuration
961 // and not directly the cache path.
962 EqualOrErr =
963 VFS.equivalent(ASTFileHSOpts.ModuleCachePath, HSOpts.ModuleCachePath);
964 if (EqualOrErr && *EqualOrErr)
965 Diags->Report(clang::diag::warn_ast_file_config_mismatch) << ASTFilename;
966 else
967 Diags->Report(diag::err_ast_file_modulecache_mismatch)
968 << SpecificModuleCachePath << ExistingModuleCachePath << ASTFilename;
969 }
970 return true;
971 }
972
973 bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
974 StringRef ASTFilename,
975 StringRef SpecificModuleCachePath,
976 bool Complain) {
977 const HeaderSearch &HeaderSearchInfo = PP.getHeaderSearchInfo();
978 return checkModuleCachePath(
979 Reader.getFileManager().getVirtualFileSystem(), SpecificModuleCachePath,
980 HeaderSearchInfo.getModuleCachePath(), ASTFilename,
981 Complain ? &Reader.Diags : nullptr, PP.getLangOpts(),
982 PP.getPreprocessorOpts(), HeaderSearchInfo.getHeaderSearchOpts(), HSOpts);
983 }
984
985 void PCHValidator::ReadCounter(const ModuleFile &M, uint32_t Value) {
986 PP.setCounterValue(Value);
987 }
988
989 //===----------------------------------------------------------------------===//
990 // AST reader implementation
991 //===----------------------------------------------------------------------===//
992
993 static uint64_t readULEB(const unsigned char *&P) {
994 unsigned Length = 0;
995 const char *Error = nullptr;
996
997 uint64_t Val = llvm::decodeULEB128(P, &Length, nullptr, &Error);
998 if (Error)
999 llvm::report_fatal_error(Error);
1000 P += Length;
1001 return Val;
1002 }
1003
1004 /// Read ULEB-encoded key length and data length.
1005 static std::pair<unsigned, unsigned>
1006 readULEBKeyDataLength(const unsigned char *&P) {
1007 unsigned KeyLen = readULEB(P);
1008 if ((unsigned)KeyLen != KeyLen)
1009 llvm::report_fatal_error("key too large");
1010
1011 unsigned DataLen = readULEB(P);
1012 if ((unsigned)DataLen != DataLen)
1013 llvm::report_fatal_error("data too large");
1014
1015 return std::make_pair(KeyLen, DataLen);
1016 }
1017
1018 void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
1019 bool TakeOwnership) {
1020 DeserializationListener = Listener;
1021 OwnsDeserializationListener = TakeOwnership;
1022 }
1023
1024 unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
1025 return serialization::ComputeHash(Sel);
1026 }
1027
1028 LocalDeclID LocalDeclID::get(ASTReader &Reader, ModuleFile &MF, DeclID Value) {
1029 LocalDeclID ID(Value);
1030 #ifndef NDEBUG
1031 if (!MF.ModuleOffsetMap.empty())
1032 Reader.ReadModuleOffsetMap(MF);
1033
1034 unsigned ModuleFileIndex = ID.getModuleFileIndex();
1035 unsigned LocalDeclID = ID.getLocalDeclIndex();
1036
1037 assert(ModuleFileIndex <= MF.TransitiveImports.size());
1038
1039 ModuleFile *OwningModuleFile =
1040 ModuleFileIndex == 0 ? &MF : MF.TransitiveImports[ModuleFileIndex - 1];
1041 assert(OwningModuleFile);
1042
1043 unsigned LocalNumDecls = OwningModuleFile->LocalNumDecls;
1044
1045 if (!ModuleFileIndex)
1046 LocalNumDecls += NUM_PREDEF_DECL_IDS;
1047
1048 assert(LocalDeclID < LocalNumDecls);
1049 #endif
1050 (void)Reader;
1051 (void)MF;
1052 return ID;
1053 }
1054
1055 LocalDeclID LocalDeclID::get(ASTReader &Reader, ModuleFile &MF,
1056 unsigned ModuleFileIndex, unsigned LocalDeclID) {
1057 DeclID Value = (DeclID)ModuleFileIndex << 32 | (DeclID)LocalDeclID;
1058 return LocalDeclID::get(Reader, MF, Value);
1059 }
1060
1061 std::pair<unsigned, unsigned>
1062 ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
1063 return readULEBKeyDataLength(d);
1064 }
1065
1066 ASTSelectorLookupTrait::internal_key_type
1067 ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
1068 using namespace llvm::support;
1069
1070 SelectorTable &SelTable = Reader.getContext().Selectors;
1071 unsigned N = endian::readNext<uint16_t, llvm::endianness::little>(d);
1072 const IdentifierInfo *FirstII = Reader.getLocalIdentifier(
1073 F, endian::readNext<IdentifierID, llvm::endianness::little>(d));
1074 if (N == 0)
1075 return SelTable.getNullarySelector(FirstII);
1076 else if (N == 1)
1077 return SelTable.getUnarySelector(FirstII);
1078
1079 SmallVector<const IdentifierInfo *, 16> Args;
1080 Args.push_back(FirstII);
1081 for (unsigned I = 1; I != N; ++I)
1082 Args.push_back(Reader.getLocalIdentifier(
1083 F, endian::readNext<IdentifierID, llvm::endianness::little>(d)));
1084
1085 return SelTable.getSelector(N, Args.data());
1086 }
1087
1088 ASTSelectorLookupTrait::data_type
1089 ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
1090 unsigned DataLen) {
1091 using namespace llvm::support;
1092
1093 data_type Result;
1094
1095 Result.ID = Reader.getGlobalSelectorID(
1096 F, endian::readNext<uint32_t, llvm::endianness::little>(d));
1097 unsigned FullInstanceBits =
1098 endian::readNext<uint16_t, llvm::endianness::little>(d);
1099 unsigned FullFactoryBits =
1100 endian::readNext<uint16_t, llvm::endianness::little>(d);
1101 Result.InstanceBits = FullInstanceBits & 0x3;
1102 Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
1103 Result.FactoryBits = FullFactoryBits & 0x3;
1104 Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
1105 unsigned NumInstanceMethods = FullInstanceBits >> 3;
1106 unsigned NumFactoryMethods = FullFactoryBits >> 3;
1107
1108 // Load instance methods
1109 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
1110 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
1111 F, LocalDeclID::get(
1112 Reader, F,
1113 endian::readNext<DeclID, llvm::endianness::little>(d))))
1114 Result.Instance.push_back(Method);
1115 }
1116
1117 // Load factory methods
1118 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
1119 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
1120 F, LocalDeclID::get(
1121 Reader, F,
1122 endian::readNext<DeclID, llvm::endianness::little>(d))))
1123 Result.Factory.push_back(Method);
1124 }
1125
1126 return Result;
1127 }
1128
1129 unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
1130 return llvm::djbHash(a);
1131 }
1132
1133 std::pair<unsigned, unsigned>
1134 ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
1135 return readULEBKeyDataLength(d);
1136 }
1137
1138 ASTIdentifierLookupTraitBase::internal_key_type
1139 ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
1140 assert(n >= 2 && d[n-1] == '\0');
1141 return StringRef((const char*) d, n-1);
1142 }
1143
1144 /// Whether the given identifier is "interesting".
1145 static bool isInterestingIdentifier(ASTReader &Reader, const IdentifierInfo &II,
1146 bool IsModule) {
1147 bool IsInteresting =
1148 II.getNotableIdentifierID() != tok::NotableIdentifierKind::not_notable ||
1149 II.getBuiltinID() != Builtin::ID::NotBuiltin ||
1150 II.getObjCKeywordID() != tok::ObjCKeywordKind::objc_not_keyword;
1151 return II.hadMacroDefinition() || II.isPoisoned() ||
1152 (!IsModule && IsInteresting) || II.hasRevertedTokenIDToIdentifier() ||
1153 (!(IsModule && Reader.getPreprocessor().getLangOpts().CPlusPlus) &&
1154 II.getFETokenInfo());
1155 }
1156
1157 static bool readBit(unsigned &Bits) {
1158 bool Value = Bits & 0x1;
1159 Bits >>= 1;
1160 return Value;
1161 }
1162
1163 IdentifierID ASTIdentifierLookupTrait::ReadIdentifierID(const unsigned char *d) {
1164 using namespace llvm::support;
1165
1166 IdentifierID RawID =
1167 endian::readNext<IdentifierID, llvm::endianness::little>(d);
1168 return Reader.getGlobalIdentifierID(F, RawID >> 1);
1169 }
1170
1171 static void markIdentifierFromAST(ASTReader &Reader, IdentifierInfo &II,
1172 bool IsModule) {
1173 if (!II.isFromAST()) {
1174 II.setIsFromAST();
1175 if (isInterestingIdentifier(Reader, II, IsModule))
1176 II.setChangedSinceDeserialization();
1177 }
1178 }
1179
1180 IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
1181 const unsigned char* d,
1182 unsigned DataLen) {
1183 using namespace llvm::support;
1184
1185 IdentifierID RawID =
1186 endian::readNext<IdentifierID, llvm::endianness::little>(d);
1187 bool IsInteresting = RawID & 0x01;
1188
1189 DataLen -= sizeof(IdentifierID);
1190
1191 // Wipe out the "is interesting" bit.
1192 RawID = RawID >> 1;
1193
1194 // Build the IdentifierInfo and link the identifier ID with it.
1195 IdentifierInfo *II = KnownII;
1196 if (!II) {
1197 II = &Reader.getIdentifierTable().getOwn(k);
1198 KnownII = II;
1199 }
1200 bool IsModule = Reader.getPreprocessor().getCurrentModule() != nullptr;
1201 markIdentifierFromAST(Reader, *II, IsModule);
1202 Reader.markIdentifierUpToDate(II);
1203
1204 IdentifierID ID = Reader.getGlobalIdentifierID(F, RawID);
1205 if (!IsInteresting) {
1206 // For uninteresting identifiers, there's nothing else to do. Just notify
1207 // the reader that we've finished loading this identifier.
1208 Reader.SetIdentifierInfo(ID, II);
1209 return II;
1210 }
1211
1212 unsigned ObjCOrBuiltinID =
1213 endian::readNext<uint16_t, llvm::endianness::little>(d);
1214 unsigned Bits = endian::readNext<uint16_t, llvm::endianness::little>(d);
1215 bool CPlusPlusOperatorKeyword = readBit(Bits);
1216 bool HasRevertedTokenIDToIdentifier = readBit(Bits);
1217 bool Poisoned = readBit(Bits);
1218 bool ExtensionToken = readBit(Bits);
1219 bool HasMacroDefinition = readBit(Bits);
1220
1221 assert(Bits == 0 && "Extra bits in the identifier?");
1222 DataLen -= sizeof(uint16_t) * 2;
1223
1224 // Set or check the various bits in the IdentifierInfo structure.
1225 // Token IDs are read-only.
1226 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
1227 II->revertTokenIDToIdentifier();
1228 if (!F.isModule())
1229 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
1230 assert(II->isExtensionToken() == ExtensionToken &&
1231 "Incorrect extension token flag");
1232 (void)ExtensionToken;
1233 if (Poisoned)
1234 II->setIsPoisoned(true);
1235 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
1236 "Incorrect C++ operator keyword flag");
1237 (void)CPlusPlusOperatorKeyword;
1238
1239 // If this identifier has a macro definition, deserialize it or notify the
1240 // visitor the actual definition is in a different module.
1241 if (HasMacroDefinition) {
1242 uint32_t MacroDirectivesOffset =
1243 endian::readNext<uint32_t, llvm::endianness::little>(d);
1244 DataLen -= 4;
1245
1246 if (MacroDirectivesOffset)
1247 Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
1248 else
1249 hasMacroDefinitionInDependencies = true;
1250 }
1251
1252 Reader.SetIdentifierInfo(ID, II);
1253
1254 // Read all of the declarations visible at global scope with this
1255 // name.
1256 if (DataLen > 0) {
1257 SmallVector<GlobalDeclID, 4> DeclIDs;
1258 for (; DataLen > 0; DataLen -= sizeof(DeclID))
1259 DeclIDs.push_back(Reader.getGlobalDeclID(
1260 F, LocalDeclID::get(
1261 Reader, F,
1262 endian::readNext<DeclID, llvm::endianness::little>(d))));
1263 Reader.SetGloballyVisibleDecls(II, DeclIDs);
1264 }
1265
1266 return II;
1267 }
1268
1269 DeclarationNameKey::DeclarationNameKey(DeclarationName Name)
1270 : Kind(Name.getNameKind()) {
1271 switch (Kind) {
1272 case DeclarationName::Identifier:
1273 Data = (uint64_t)Name.getAsIdentifierInfo();
1274 break;
1275 case DeclarationName::ObjCZeroArgSelector:
1276 case DeclarationName::ObjCOneArgSelector:
1277 case DeclarationName::ObjCMultiArgSelector:
1278 Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
1279 break;
1280 case DeclarationName::CXXOperatorName:
1281 Data = Name.getCXXOverloadedOperator();
1282 break;
1283 case DeclarationName::CXXLiteralOperatorName:
1284 Data = (uint64_t)Name.getCXXLiteralIdentifier();
1285 break;
1286 case DeclarationName::CXXDeductionGuideName:
1287 Data = (uint64_t)Name.getCXXDeductionGuideTemplate()
1288 ->getDeclName().getAsIdentifierInfo();
1289 break;
1290 case DeclarationName::CXXConstructorName:
1291 case DeclarationName::CXXDestructorName:
1292 case DeclarationName::CXXConversionFunctionName:
1293 case DeclarationName::CXXUsingDirective:
1294 Data = 0;
1295 break;
1296 }
1297 }
1298
1299 unsigned DeclarationNameKey::getHash() const {
1300 llvm::FoldingSetNodeID ID;
1301 ID.AddInteger(Kind);
1302
1303 switch (Kind) {
1304 case DeclarationName::Identifier:
1305 case DeclarationName::CXXLiteralOperatorName:
1306 case DeclarationName::CXXDeductionGuideName:
1307 ID.AddString(((IdentifierInfo*)Data)->getName());
1308 break;
1309 case DeclarationName::ObjCZeroArgSelector:
1310 case DeclarationName::ObjCOneArgSelector:
1311 case DeclarationName::ObjCMultiArgSelector:
1312 ID.AddInteger(serialization::ComputeHash(Selector(Data)));
1313 break;
1314 case DeclarationName::CXXOperatorName:
1315 ID.AddInteger((OverloadedOperatorKind)Data);
1316 break;
1317 case DeclarationName::CXXConstructorName:
1318 case DeclarationName::CXXDestructorName:
1319 case DeclarationName::CXXConversionFunctionName:
1320 case DeclarationName::CXXUsingDirective:
1321 break;
1322 }
1323
1324 return ID.computeStableHash();
1325 }
1326
1327 ModuleFile *
1328 ASTDeclContextNameLookupTraitBase::ReadFileRef(const unsigned char *&d) {
1329 using namespace llvm::support;
1330
1331 uint32_t ModuleFileID =
1332 endian::readNext<uint32_t, llvm::endianness::little>(d);
1333 return Reader.getLocalModuleFile(F, ModuleFileID);
1334 }
1335
1336 std::pair<unsigned, unsigned>
1337 ASTDeclContextNameLookupTraitBase::ReadKeyDataLength(const unsigned char *&d) {
1338 return readULEBKeyDataLength(d);
1339 }
1340
1341 DeclarationNameKey
1342 ASTDeclContextNameLookupTraitBase::ReadKeyBase(const unsigned char *&d) {
1343 using namespace llvm::support;
1344
1345 auto Kind = (DeclarationName::NameKind)*d++;
1346 uint64_t Data;
1347 switch (Kind) {
1348 case DeclarationName::Identifier:
1349 case DeclarationName::CXXLiteralOperatorName:
1350 case DeclarationName::CXXDeductionGuideName:
1351 Data = (uint64_t)Reader.getLocalIdentifier(
1352 F, endian::readNext<IdentifierID, llvm::endianness::little>(d));
1353 break;
1354 case DeclarationName::ObjCZeroArgSelector:
1355 case DeclarationName::ObjCOneArgSelector:
1356 case DeclarationName::ObjCMultiArgSelector:
1357 Data = (uint64_t)Reader
1358 .getLocalSelector(
1359 F, endian::readNext<uint32_t, llvm::endianness::little>(d))
1360 .getAsOpaquePtr();
1361 break;
1362 case DeclarationName::CXXOperatorName:
1363 Data = *d++; // OverloadedOperatorKind
1364 break;
1365 case DeclarationName::CXXConstructorName:
1366 case DeclarationName::CXXDestructorName:
1367 case DeclarationName::CXXConversionFunctionName:
1368 case DeclarationName::CXXUsingDirective:
1369 Data = 0;
1370 break;
1371 }
1372
1373 return DeclarationNameKey(Kind, Data);
1374 }
1375
1376 ASTDeclContextNameLookupTrait::internal_key_type
1377 ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
1378 return ReadKeyBase(d);
1379 }
1380
1381 void ASTDeclContextNameLookupTraitBase::ReadDataIntoImpl(
1382 const unsigned char *d, unsigned DataLen, data_type_builder &Val) {
1383 using namespace llvm::support;
1384
1385 for (unsigned NumDecls = DataLen / sizeof(DeclID); NumDecls; --NumDecls) {
1386 LocalDeclID ID = LocalDeclID::get(
1387 Reader, F, endian::readNext<DeclID, llvm::endianness::little>(d));
1388 Val.insert(Reader.getGlobalDeclID(F, ID));
1389 }
1390 }
1391
1392 void ASTDeclContextNameLookupTrait::ReadDataInto(internal_key_type,
1393 const unsigned char *d,
1394 unsigned DataLen,
1395 data_type_builder &Val) {
1396 ReadDataIntoImpl(d, DataLen, Val);
1397 }
1398
1399 ModuleLocalNameLookupTrait::hash_value_type
1400 ModuleLocalNameLookupTrait::ComputeHash(const internal_key_type &Key) {
1401 llvm::FoldingSetNodeID ID;
1402 ID.AddInteger(Key.first.getHash());
1403 ID.AddInteger(Key.second);
1404 return ID.computeStableHash();
1405 }
1406
1407 ModuleLocalNameLookupTrait::internal_key_type
1408 ModuleLocalNameLookupTrait::GetInternalKey(const external_key_type &Key) {
1409 DeclarationNameKey Name(Key.first);
1410
1411 UnsignedOrNone ModuleHash = getPrimaryModuleHash(Key.second);
1412 if (!ModuleHash)
1413 return {Name, 0};
1414
1415 return {Name, *ModuleHash};
1416 }
1417
1418 ModuleLocalNameLookupTrait::internal_key_type
1419 ModuleLocalNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
1420 DeclarationNameKey Name = ReadKeyBase(d);
1421 unsigned PrimaryModuleHash =
1422 llvm::support::endian::readNext<uint32_t, llvm::endianness::little>(d);
1423 return {Name, PrimaryModuleHash};
1424 }
1425
1426 void ModuleLocalNameLookupTrait::ReadDataInto(internal_key_type,
1427 const unsigned char *d,
1428 unsigned DataLen,
1429 data_type_builder &Val) {
1430 ReadDataIntoImpl(d, DataLen, Val);
1431 }
1432
1433 ModuleFile *
1434 LazySpecializationInfoLookupTrait::ReadFileRef(const unsigned char *&d) {
1435 using namespace llvm::support;
1436
1437 uint32_t ModuleFileID =
1438 endian::readNext<uint32_t, llvm::endianness::little, unaligned>(d);
1439 return Reader.getLocalModuleFile(F, ModuleFileID);
1440 }
1441
1442 LazySpecializationInfoLookupTrait::internal_key_type
1443 LazySpecializationInfoLookupTrait::ReadKey(const unsigned char *d, unsigned) {
1444 using namespace llvm::support;
1445 return endian::readNext<uint32_t, llvm::endianness::little, unaligned>(d);
1446 }
1447
1448 std::pair<unsigned, unsigned>
1449 LazySpecializationInfoLookupTrait::ReadKeyDataLength(const unsigned char *&d) {
1450 return readULEBKeyDataLength(d);
1451 }
1452
1453 void LazySpecializationInfoLookupTrait::ReadDataInto(internal_key_type,
1454 const unsigned char *d,
1455 unsigned DataLen,
1456 data_type_builder &Val) {
1457 using namespace llvm::support;
1458
1459 for (unsigned NumDecls =
1460 DataLen / sizeof(serialization::reader::LazySpecializationInfo);
1461 NumDecls; --NumDecls) {
1462 LocalDeclID LocalID = LocalDeclID::get(
1463 Reader, F,
1464 endian::readNext<DeclID, llvm::endianness::little, unaligned>(d));
1465 Val.insert(Reader.getGlobalDeclID(F, LocalID));
1466 }
1467 }
1468
1469 bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
1470 BitstreamCursor &Cursor,
1471 uint64_t Offset,
1472 DeclContext *DC) {
1473 assert(Offset != 0);
1474
1475 SavedStreamPosition SavedPosition(Cursor);
1476 if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1477 Error(std::move(Err));
1478 return true;
1479 }
1480
1481 RecordData Record;
1482 StringRef Blob;
1483 Expected<unsigned> MaybeCode = Cursor.ReadCode();
1484 if (!MaybeCode) {
1485 Error(MaybeCode.takeError());
1486 return true;
1487 }
1488 unsigned Code = MaybeCode.get();
1489
1490 Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
1491 if (!MaybeRecCode) {
1492 Error(MaybeRecCode.takeError());
1493 return true;
1494 }
1495 unsigned RecCode = MaybeRecCode.get();
1496 if (RecCode != DECL_CONTEXT_LEXICAL) {
1497 Error("Expected lexical block");
1498 return true;
1499 }
1500
1501 assert(!isa<TranslationUnitDecl>(DC) &&
1502 "expected a TU_UPDATE_LEXICAL record for TU");
1503 // If we are handling a C++ class template instantiation, we can see multiple
1504 // lexical updates for the same record. It's important that we select only one
1505 // of them, so that field numbering works properly. Just pick the first one we
1506 // see.
1507 auto &Lex = LexicalDecls[DC];
1508 if (!Lex.first) {
1509 Lex = std::make_pair(
1510 &M, llvm::ArrayRef(
1511 reinterpret_cast<const unaligned_decl_id_t *>(Blob.data()),
1512 Blob.size() / sizeof(DeclID)));
1513 }
1514 DC->setHasExternalLexicalStorage(true);
1515 return false;
1516 }
1517
1518 bool ASTReader::ReadVisibleDeclContextStorage(
1519 ModuleFile &M, BitstreamCursor &Cursor, uint64_t Offset, GlobalDeclID ID,
1520 ASTReader::VisibleDeclContextStorageKind VisibleKind) {
1521 assert(Offset != 0);
1522
1523 SavedStreamPosition SavedPosition(Cursor);
1524 if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1525 Error(std::move(Err));
1526 return true;
1527 }
1528
1529 RecordData Record;
1530 StringRef Blob;
1531 Expected<unsigned> MaybeCode = Cursor.ReadCode();
1532 if (!MaybeCode) {
1533 Error(MaybeCode.takeError());
1534 return true;
1535 }
1536 unsigned Code = MaybeCode.get();
1537
1538 Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
1539 if (!MaybeRecCode) {
1540 Error(MaybeRecCode.takeError());
1541 return true;
1542 }
1543 unsigned RecCode = MaybeRecCode.get();
1544 switch (VisibleKind) {
1545 case VisibleDeclContextStorageKind::GenerallyVisible:
1546 if (RecCode != DECL_CONTEXT_VISIBLE) {
1547 Error("Expected visible lookup table block");
1548 return true;
1549 }
1550 break;
1551 case VisibleDeclContextStorageKind::ModuleLocalVisible:
1552 if (RecCode != DECL_CONTEXT_MODULE_LOCAL_VISIBLE) {
1553 Error("Expected module local visible lookup table block");
1554 return true;
1555 }
1556 break;
1557 case VisibleDeclContextStorageKind::TULocalVisible:
1558 if (RecCode != DECL_CONTEXT_TU_LOCAL_VISIBLE) {
1559 Error("Expected TU local lookup table block");
1560 return true;
1561 }
1562 break;
1563 }
1564
1565 // We can't safely determine the primary context yet, so delay attaching the
1566 // lookup table until we're done with recursive deserialization.
1567 auto *Data = (const unsigned char*)Blob.data();
1568 switch (VisibleKind) {
1569 case VisibleDeclContextStorageKind::GenerallyVisible:
1570 PendingVisibleUpdates[ID].push_back(UpdateData{&M, Data});
1571 break;
1572 case VisibleDeclContextStorageKind::ModuleLocalVisible:
1573 PendingModuleLocalVisibleUpdates[ID].push_back(UpdateData{&M, Data});
1574 break;
1575 case VisibleDeclContextStorageKind::TULocalVisible:
1576 if (M.Kind == MK_MainFile)
1577 TULocalUpdates[ID].push_back(UpdateData{&M, Data});
1578 break;
1579 }
1580 return false;
1581 }
1582
1583 void ASTReader::AddSpecializations(const Decl *D, const unsigned char *Data,
1584 ModuleFile &M, bool IsPartial) {
1585 D = D->getCanonicalDecl();
1586 auto &SpecLookups =
1587 IsPartial ? PartialSpecializationsLookups : SpecializationsLookups;
1588 SpecLookups[D].Table.add(&M, Data,
1589 reader::LazySpecializationInfoLookupTrait(*this, M));
1590 }
1591
1592 bool ASTReader::ReadSpecializations(ModuleFile &M, BitstreamCursor &Cursor,
1593 uint64_t Offset, Decl *D, bool IsPartial) {
1594 assert(Offset != 0);
1595
1596 SavedStreamPosition SavedPosition(Cursor);
1597 if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1598 Error(std::move(Err));
1599 return true;
1600 }
1601
1602 RecordData Record;
1603 StringRef Blob;
1604 Expected<unsigned> MaybeCode = Cursor.ReadCode();
1605 if (!MaybeCode) {
1606 Error(MaybeCode.takeError());
1607 return true;
1608 }
1609 unsigned Code = MaybeCode.get();
1610
1611 Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
1612 if (!MaybeRecCode) {
1613 Error(MaybeRecCode.takeError());
1614 return true;
1615 }
1616 unsigned RecCode = MaybeRecCode.get();
1617 if (RecCode != DECL_SPECIALIZATIONS &&
1618 RecCode != DECL_PARTIAL_SPECIALIZATIONS) {
1619 Error("Expected decl specs block");
1620 return true;
1621 }
1622
1623 auto *Data = (const unsigned char *)Blob.data();
1624 AddSpecializations(D, Data, M, IsPartial);
1625 return false;
1626 }
1627
1628 void ASTReader::Error(StringRef Msg) const {
1629 Error(diag::err_fe_ast_file_malformed, Msg);
1630 if (PP.getLangOpts().Modules &&
1631 !PP.getHeaderSearchInfo().getModuleCachePath().empty()) {
1632 Diag(diag::note_module_cache_path)
1633 << PP.getHeaderSearchInfo().getModuleCachePath();
1634 }
1635 }
1636
1637 void ASTReader::Error(unsigned DiagID, StringRef Arg1, StringRef Arg2,
1638 StringRef Arg3) const {
1639 Diag(DiagID) << Arg1 << Arg2 << Arg3;
1640 }
1641
1642 namespace {
1643 struct AlreadyReportedDiagnosticError
1644 : llvm::ErrorInfo<AlreadyReportedDiagnosticError> {
1645 static char ID;
1646
1647 void log(raw_ostream &OS) const override {
1648 llvm_unreachable("reporting an already-reported diagnostic error");
1649 }
1650
1651 std::error_code convertToErrorCode() const override {
1652 return llvm::inconvertibleErrorCode();
1653 }
1654 };
1655
1656 char AlreadyReportedDiagnosticError::ID = 0;
1657 } // namespace
1658
1659 void ASTReader::Error(llvm::Error &&Err) const {
1660 handleAllErrors(
1661 std::move(Err), [](AlreadyReportedDiagnosticError &) {},
1662 [&](llvm::ErrorInfoBase &E) { return Error(E.message()); });
1663 }
1664
1665 //===----------------------------------------------------------------------===//
1666 // Source Manager Deserialization
1667 //===----------------------------------------------------------------------===//
1668
1669 /// Read the line table in the source manager block.
1670 void ASTReader::ParseLineTable(ModuleFile &F, const RecordData &Record) {
1671 unsigned Idx = 0;
1672 LineTableInfo &LineTable = SourceMgr.getLineTable();
1673
1674 // Parse the file names
1675 std::map<int, int> FileIDs;
1676 FileIDs[-1] = -1; // For unspecified filenames.
1677 for (unsigned I = 0; Record[Idx]; ++I) {
1678 // Extract the file name
1679 auto Filename = ReadPath(F, Record, Idx);
1680 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1681 }
1682 ++Idx;
1683
1684 // Parse the line entries
1685 std::vector<LineEntry> Entries;
1686 while (Idx < Record.size()) {
1687 FileID FID = ReadFileID(F, Record, Idx);
1688
1689 // Extract the line entries
1690 unsigned NumEntries = Record[Idx++];
1691 assert(NumEntries && "no line entries for file ID");
1692 Entries.clear();
1693 Entries.reserve(NumEntries);
1694 for (unsigned I = 0; I != NumEntries; ++I) {
1695 unsigned FileOffset = Record[Idx++];
1696 unsigned LineNo = Record[Idx++];
1697 int FilenameID = FileIDs[Record[Idx++]];
1698 SrcMgr::CharacteristicKind FileKind
1699 = (SrcMgr::CharacteristicKind)Record[Idx++];
1700 unsigned IncludeOffset = Record[Idx++];
1701 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1702 FileKind, IncludeOffset));
1703 }
1704 LineTable.AddEntry(FID, Entries);
1705 }
1706 }
1707
1708 /// Read a source manager block
1709 llvm::Error ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1710 using namespace SrcMgr;
1711
1712 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
1713
1714 // Set the source-location entry cursor to the current position in
1715 // the stream. This cursor will be used to read the contents of the
1716 // source manager block initially, and then lazily read
1717 // source-location entries as needed.
1718 SLocEntryCursor = F.Stream;
1719
1720 // The stream itself is going to skip over the source manager block.
1721 if (llvm::Error Err = F.Stream.SkipBlock())
1722 return Err;
1723
1724 // Enter the source manager block.
1725 if (llvm::Error Err = SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID))
1726 return Err;
1727 F.SourceManagerBlockStartOffset = SLocEntryCursor.GetCurrentBitNo();
1728
1729 RecordData Record;
1730 while (true) {
1731 Expected<llvm::BitstreamEntry> MaybeE =
1732 SLocEntryCursor.advanceSkippingSubblocks();
1733 if (!MaybeE)
1734 return MaybeE.takeError();
1735 llvm::BitstreamEntry E = MaybeE.get();
1736
1737 switch (E.Kind) {
1738 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1739 case llvm::BitstreamEntry::Error:
1740 return llvm::createStringError(std::errc::illegal_byte_sequence,
1741 "malformed block record in AST file");
1742 case llvm::BitstreamEntry::EndBlock:
1743 return llvm::Error::success();
1744 case llvm::BitstreamEntry::Record:
1745 // The interesting case.
1746 break;
1747 }
1748
1749 // Read a record.
1750 Record.clear();
1751 StringRef Blob;
1752 Expected<unsigned> MaybeRecord =
1753 SLocEntryCursor.readRecord(E.ID, Record, &Blob);
1754 if (!MaybeRecord)
1755 return MaybeRecord.takeError();
1756 switch (MaybeRecord.get()) {
1757 default: // Default behavior: ignore.
1758 break;
1759
1760 case SM_SLOC_FILE_ENTRY:
1761 case SM_SLOC_BUFFER_ENTRY:
1762 case SM_SLOC_EXPANSION_ENTRY:
1763 // Once we hit one of the source location entries, we're done.
1764 return llvm::Error::success();
1765 }
1766 }
1767 }
1768
1769 llvm::Expected<SourceLocation::UIntTy>
1770 ASTReader::readSLocOffset(ModuleFile *F, unsigned Index) {
1771 BitstreamCursor &Cursor = F->SLocEntryCursor;
1772 SavedStreamPosition SavedPosition(Cursor);
1773 if (llvm::Error Err = Cursor.JumpToBit(F->SLocEntryOffsetsBase +
1774 F->SLocEntryOffsets[Index]))
1775 return std::move(Err);
1776
1777 Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
1778 if (!MaybeEntry)
1779 return MaybeEntry.takeError();
1780
1781 llvm::BitstreamEntry Entry = MaybeEntry.get();
1782 if (Entry.Kind != llvm::BitstreamEntry::Record)
1783 return llvm::createStringError(
1784 std::errc::illegal_byte_sequence,
1785 "incorrectly-formatted source location entry in AST file");
1786
1787 RecordData Record;
1788 StringRef Blob;
1789 Expected<unsigned> MaybeSLOC = Cursor.readRecord(Entry.ID, Record, &Blob);
1790 if (!MaybeSLOC)
1791 return MaybeSLOC.takeError();
1792
1793 switch (MaybeSLOC.get()) {
1794 default:
1795 return llvm::createStringError(
1796 std::errc::illegal_byte_sequence,
1797 "incorrectly-formatted source location entry in AST file");
1798 case SM_SLOC_FILE_ENTRY:
1799 case SM_SLOC_BUFFER_ENTRY:
1800 case SM_SLOC_EXPANSION_ENTRY:
1801 return F->SLocEntryBaseOffset + Record[0];
1802 }
1803 }
1804
1805 int ASTReader::getSLocEntryID(SourceLocation::UIntTy SLocOffset) {
1806 auto SLocMapI =
1807 GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset - SLocOffset - 1);
1808 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
1809 "Corrupted global sloc offset map");
1810 ModuleFile *F = SLocMapI->second;
1811
1812 bool Invalid = false;
1813
1814 auto It = llvm::upper_bound(
1815 llvm::index_range(0, F->LocalNumSLocEntries), SLocOffset,
1816 [&](SourceLocation::UIntTy Offset, std::size_t LocalIndex) {
1817 int ID = F->SLocEntryBaseID + LocalIndex;
1818 std::size_t Index = -ID - 2;
1819 if (!SourceMgr.SLocEntryOffsetLoaded[Index]) {
1820 assert(!SourceMgr.SLocEntryLoaded[Index]);
1821 auto MaybeEntryOffset = readSLocOffset(F, LocalIndex);
1822 if (!MaybeEntryOffset) {
1823 Error(MaybeEntryOffset.takeError());
1824 Invalid = true;
1825 return true;
1826 }
1827 SourceMgr.LoadedSLocEntryTable[Index] =
1828 SrcMgr::SLocEntry::getOffsetOnly(*MaybeEntryOffset);
1829 SourceMgr.SLocEntryOffsetLoaded[Index] = true;
1830 }
1831 return Offset < SourceMgr.LoadedSLocEntryTable[Index].getOffset();
1832 });
1833
1834 if (Invalid)
1835 return 0;
1836
1837 // The iterator points to the first entry with start offset greater than the
1838 // offset of interest. The previous entry must contain the offset of interest.
1839 return F->SLocEntryBaseID + *std::prev(It);
1840 }
1841
1842 bool ASTReader::ReadSLocEntry(int ID) {
1843 if (ID == 0)
1844 return false;
1845
1846 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1847 Error("source location entry ID out-of-range for AST file");
1848 return true;
1849 }
1850
1851 // Local helper to read the (possibly-compressed) buffer data following the
1852 // entry record.
1853 auto ReadBuffer = [this](
1854 BitstreamCursor &SLocEntryCursor,
1855 StringRef Name) -> std::unique_ptr<llvm::MemoryBuffer> {
1856 RecordData Record;
1857 StringRef Blob;
1858 Expected<unsigned> MaybeCode = SLocEntryCursor.ReadCode();
1859 if (!MaybeCode) {
1860 Error(MaybeCode.takeError());
1861 return nullptr;
1862 }
1863 unsigned Code = MaybeCode.get();
1864
1865 Expected<unsigned> MaybeRecCode =
1866 SLocEntryCursor.readRecord(Code, Record, &Blob);
1867 if (!MaybeRecCode) {
1868 Error(MaybeRecCode.takeError());
1869 return nullptr;
1870 }
1871 unsigned RecCode = MaybeRecCode.get();
1872
1873 if (RecCode == SM_SLOC_BUFFER_BLOB_COMPRESSED) {
1874 // Inspect the first byte to differentiate zlib (\x78) and zstd
1875 // (little-endian 0xFD2FB528).
1876 const llvm::compression::Format F =
1877 Blob.size() > 0 && Blob.data()[0] == 0x78
1878 ? llvm::compression::Format::Zlib
1879 : llvm::compression::Format::Zstd;
1880 if (const char *Reason = llvm::compression::getReasonIfUnsupported(F)) {
1881 Error(Reason);
1882 return nullptr;
1883 }
1884 SmallVector<uint8_t, 0> Decompressed;
1885 if (llvm::Error E = llvm::compression::decompress(
1886 F, llvm::arrayRefFromStringRef(Blob), Decompressed, Record[0])) {
1887 Error("could not decompress embedded file contents: " +
1888 llvm::toString(std::move(E)));
1889 return nullptr;
1890 }
1891 return llvm::MemoryBuffer::getMemBufferCopy(
1892 llvm::toStringRef(Decompressed), Name);
1893 } else if (RecCode == SM_SLOC_BUFFER_BLOB) {
1894 return llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name, true);
1895 } else {
1896 Error("AST record has invalid code");
1897 return nullptr;
1898 }
1899 };
1900
1901 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1902 if (llvm::Error Err = F->SLocEntryCursor.JumpToBit(
1903 F->SLocEntryOffsetsBase +
1904 F->SLocEntryOffsets[ID - F->SLocEntryBaseID])) {
1905 Error(std::move(Err));
1906 return true;
1907 }
1908
1909 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
1910 SourceLocation::UIntTy BaseOffset = F->SLocEntryBaseOffset;
1911
1912 ++NumSLocEntriesRead;
1913 Expected<llvm::BitstreamEntry> MaybeEntry = SLocEntryCursor.advance();
1914 if (!MaybeEntry) {
1915 Error(MaybeEntry.takeError());
1916 return true;
1917 }
1918 llvm::BitstreamEntry Entry = MaybeEntry.get();
1919
1920 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1921 Error("incorrectly-formatted source location entry in AST file");
1922 return true;
1923 }
1924
1925 RecordData Record;
1926 StringRef Blob;
1927 Expected<unsigned> MaybeSLOC =
1928 SLocEntryCursor.readRecord(Entry.ID, Record, &Blob);
1929 if (!MaybeSLOC) {
1930 Error(MaybeSLOC.takeError());
1931 return true;
1932 }
1933 switch (MaybeSLOC.get()) {
1934 default:
1935 Error("incorrectly-formatted source location entry in AST file");
1936 return true;
1937
1938 case SM_SLOC_FILE_ENTRY: {
1939 // We will detect whether a file changed and return 'Failure' for it, but
1940 // we will also try to fail gracefully by setting up the SLocEntry.
1941 unsigned InputID = Record[4];
1942 InputFile IF = getInputFile(*F, InputID);
1943 OptionalFileEntryRef File = IF.getFile();
1944 bool OverriddenBuffer = IF.isOverridden();
1945
1946 // Note that we only check if a File was returned. If it was out-of-date
1947 // we have complained but we will continue creating a FileID to recover
1948 // gracefully.
1949 if (!File)
1950 return true;
1951
1952 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1953 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1954 // This is the module's main file.
1955 IncludeLoc = getImportLocation(F);
1956 }
1957 SrcMgr::CharacteristicKind
1958 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1959 FileID FID = SourceMgr.createFileID(*File, IncludeLoc, FileCharacter, ID,
1960 BaseOffset + Record[0]);
1961 SrcMgr::FileInfo &FileInfo = SourceMgr.getSLocEntry(FID).getFile();
1962 FileInfo.NumCreatedFIDs = Record[5];
1963 if (Record[3])
1964 FileInfo.setHasLineDirectives();
1965
1966 unsigned NumFileDecls = Record[7];
1967 if (NumFileDecls && ContextObj) {
1968 const unaligned_decl_id_t *FirstDecl = F->FileSortedDecls + Record[6];
1969 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1970 FileDeclIDs[FID] =
1971 FileDeclsInfo(F, llvm::ArrayRef(FirstDecl, NumFileDecls));
1972 }
1973
1974 const SrcMgr::ContentCache &ContentCache =
1975 SourceMgr.getOrCreateContentCache(*File, isSystem(FileCharacter));
1976 if (OverriddenBuffer && !ContentCache.BufferOverridden &&
1977 ContentCache.ContentsEntry == ContentCache.OrigEntry &&
1978 !ContentCache.getBufferIfLoaded()) {
1979 auto Buffer = ReadBuffer(SLocEntryCursor, File->getName());
1980 if (!Buffer)
1981 return true;
1982 SourceMgr.overrideFileContents(*File, std::move(Buffer));
1983 }
1984
1985 break;
1986 }
1987
1988 case SM_SLOC_BUFFER_ENTRY: {
1989 const char *Name = Blob.data();
1990 unsigned Offset = Record[0];
1991 SrcMgr::CharacteristicKind
1992 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1993 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1994 if (IncludeLoc.isInvalid() && F->isModule()) {
1995 IncludeLoc = getImportLocation(F);
1996 }
1997
1998 auto Buffer = ReadBuffer(SLocEntryCursor, Name);
1999 if (!Buffer)
2000 return true;
2001 FileID FID = SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
2002 BaseOffset + Offset, IncludeLoc);
2003 if (Record[3]) {
2004 auto &FileInfo = SourceMgr.getSLocEntry(FID).getFile();
2005 FileInfo.setHasLineDirectives();
2006 }
2007 break;
2008 }
2009
2010 case SM_SLOC_EXPANSION_ENTRY: {
2011 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
2012 SourceLocation ExpansionBegin = ReadSourceLocation(*F, Record[2]);
2013 SourceLocation ExpansionEnd = ReadSourceLocation(*F, Record[3]);
2014 SourceMgr.createExpansionLoc(SpellingLoc, ExpansionBegin, ExpansionEnd,
2015 Record[5], Record[4], ID,
2016 BaseOffset + Record[0]);
2017 break;
2018 }
2019 }
2020
2021 return false;
2022 }
2023
2024 std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
2025 if (ID == 0)
2026 return std::make_pair(SourceLocation(), "");
2027
2028 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
2029 Error("source location entry ID out-of-range for AST file");
2030 return std::make_pair(SourceLocation(), "");
2031 }
2032
2033 // Find which module file this entry lands in.
2034 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
2035 if (!M->isModule())
2036 return std::make_pair(SourceLocation(), "");
2037
2038 // FIXME: Can we map this down to a particular submodule? That would be
2039 // ideal.
2040 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
2041 }
2042
2043 /// Find the location where the module F is imported.
2044 SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
2045 if (F->ImportLoc.isValid())
2046 return F->ImportLoc;
2047
2048 // Otherwise we have a PCH. It's considered to be "imported" at the first
2049 // location of its includer.
2050 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
2051 // Main file is the importer.
2052 assert(SourceMgr.getMainFileID().isValid() && "missing main file");
2053 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
2054 }
2055 return F->ImportedBy[0]->FirstLoc;
2056 }
2057
2058 /// Enter a subblock of the specified BlockID with the specified cursor. Read
2059 /// the abbreviations that are at the top of the block and then leave the cursor
2060 /// pointing into the block.
2061 llvm::Error ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor,
2062 unsigned BlockID,
2063 uint64_t *StartOfBlockOffset) {
2064 if (llvm::Error Err = Cursor.EnterSubBlock(BlockID))
2065 return Err;
2066
2067 if (StartOfBlockOffset)
2068 *StartOfBlockOffset = Cursor.GetCurrentBitNo();
2069
2070 while (true) {
2071 uint64_t Offset = Cursor.GetCurrentBitNo();
2072 Expected<unsigned> MaybeCode = Cursor.ReadCode();
2073 if (!MaybeCode)
2074 return MaybeCode.takeError();
2075 unsigned Code = MaybeCode.get();
2076
2077 // We expect all abbrevs to be at the start of the block.
2078 if (Code != llvm::bitc::DEFINE_ABBREV) {
2079 if (llvm::Error Err = Cursor.JumpToBit(Offset))
2080 return Err;
2081 return llvm::Error::success();
2082 }
2083 if (llvm::Error Err = Cursor.ReadAbbrevRecord())
2084 return Err;
2085 }
2086 }
2087
2088 Token ASTReader::ReadToken(ModuleFile &M, const RecordDataImpl &Record,
2089 unsigned &Idx) {
2090 Token Tok;
2091 Tok.startToken();
2092 Tok.setLocation(ReadSourceLocation(M, Record, Idx));
2093 Tok.setKind((tok::TokenKind)Record[Idx++]);
2094 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
2095
2096 if (Tok.isAnnotation()) {
2097 Tok.setAnnotationEndLoc(ReadSourceLocation(M, Record, Idx));
2098 switch (Tok.getKind()) {
2099 case tok::annot_pragma_loop_hint: {
2100 auto *Info = new (PP.getPreprocessorAllocator()) PragmaLoopHintInfo;
2101 Info->PragmaName = ReadToken(M, Record, Idx);
2102 Info->Option = ReadToken(M, Record, Idx);
2103 unsigned NumTokens = Record[Idx++];
2104 SmallVector<Token, 4> Toks;
2105 Toks.reserve(NumTokens);
2106 for (unsigned I = 0; I < NumTokens; ++I)
2107 Toks.push_back(ReadToken(M, Record, Idx));
2108 Info->Toks = llvm::ArrayRef(Toks).copy(PP.getPreprocessorAllocator());
2109 Tok.setAnnotationValue(static_cast<void *>(Info));
2110 break;
2111 }
2112 case tok::annot_pragma_pack: {
2113 auto *Info = new (PP.getPreprocessorAllocator()) Sema::PragmaPackInfo;
2114 Info->Action = static_cast<Sema::PragmaMsStackAction>(Record[Idx++]);
2115 auto SlotLabel = ReadString(Record, Idx);
2116 Info->SlotLabel =
2117 llvm::StringRef(SlotLabel).copy(PP.getPreprocessorAllocator());
2118 Info->Alignment = ReadToken(M, Record, Idx);
2119 Tok.setAnnotationValue(static_cast<void *>(Info));
2120 break;
2121 }
2122 // Some annotation tokens do not use the PtrData field.
2123 case tok::annot_pragma_openmp:
2124 case tok::annot_pragma_openmp_end:
2125 case tok::annot_pragma_unused:
2126 case tok::annot_pragma_openacc:
2127 case tok::annot_pragma_openacc_end:
2128 case tok::annot_repl_input_end:
2129 break;
2130 default:
2131 llvm_unreachable("missing deserialization code for annotation token");
2132 }
2133 } else {
2134 Tok.setLength(Record[Idx++]);
2135 if (IdentifierInfo *II = getLocalIdentifier(M, Record[Idx++]))
2136 Tok.setIdentifierInfo(II);
2137 }
2138 return Tok;
2139 }
2140
2141 MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
2142 BitstreamCursor &Stream = F.MacroCursor;
2143
2144 // Keep track of where we are in the stream, then jump back there
2145 // after reading this macro.
2146 SavedStreamPosition SavedPosition(Stream);
2147
2148 if (llvm::Error Err = Stream.JumpToBit(Offset)) {
2149 // FIXME this drops errors on the floor.
2150 consumeError(std::move(Err));
2151 return nullptr;
2152 }
2153 RecordData Record;
2154 SmallVector<IdentifierInfo*, 16> MacroParams;
2155 MacroInfo *Macro = nullptr;
2156 llvm::MutableArrayRef<Token> MacroTokens;
2157
2158 while (true) {
2159 // Advance to the next record, but if we get to the end of the block, don't
2160 // pop it (removing all the abbreviations from the cursor) since we want to
2161 // be able to reseek within the block and read entries.
2162 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
2163 Expected<llvm::BitstreamEntry> MaybeEntry =
2164 Stream.advanceSkippingSubblocks(Flags);
2165 if (!MaybeEntry) {
2166 Error(MaybeEntry.takeError());
2167 return Macro;
2168 }
2169 llvm::BitstreamEntry Entry = MaybeEntry.get();
2170
2171 switch (Entry.Kind) {
2172 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
2173 case llvm::BitstreamEntry::Error:
2174 Error("malformed block record in AST file");
2175 return Macro;
2176 case llvm::BitstreamEntry::EndBlock:
2177 return Macro;
2178 case llvm::BitstreamEntry::Record:
2179 // The interesting case.
2180 break;
2181 }
2182
2183 // Read a record.
2184 Record.clear();
2185 PreprocessorRecordTypes RecType;
2186 if (Expected<unsigned> MaybeRecType = Stream.readRecord(Entry.ID, Record))
2187 RecType = (PreprocessorRecordTypes)MaybeRecType.get();
2188 else {
2189 Error(MaybeRecType.takeError());
2190 return Macro;
2191 }
2192 switch (RecType) {
2193 case PP_MODULE_MACRO:
2194 case PP_MACRO_DIRECTIVE_HISTORY:
2195 return Macro;
2196
2197 case PP_MACRO_OBJECT_LIKE:
2198 case PP_MACRO_FUNCTION_LIKE: {
2199 // If we already have a macro, that means that we've hit the end
2200 // of the definition of the macro we were looking for. We're
2201 // done.
2202 if (Macro)
2203 return Macro;
2204
2205 unsigned NextIndex = 1; // Skip identifier ID.
2206 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
2207 MacroInfo *MI = PP.AllocateMacroInfo(Loc);
2208 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
2209 MI->setIsUsed(Record[NextIndex++]);
2210 MI->setUsedForHeaderGuard(Record[NextIndex++]);
2211 MacroTokens = MI->allocateTokens(Record[NextIndex++],
2212 PP.getPreprocessorAllocator());
2213 if (RecType == PP_MACRO_FUNCTION_LIKE) {
2214 // Decode function-like macro info.
2215 bool isC99VarArgs = Record[NextIndex++];
2216 bool isGNUVarArgs = Record[NextIndex++];
2217 bool hasCommaPasting = Record[NextIndex++];
2218 MacroParams.clear();
2219 unsigned NumArgs = Record[NextIndex++];
2220 for (unsigned i = 0; i != NumArgs; ++i)
2221 MacroParams.push_back(getLocalIdentifier(F, Record[NextIndex++]));
2222
2223 // Install function-like macro info.
2224 MI->setIsFunctionLike();
2225 if (isC99VarArgs) MI->setIsC99Varargs();
2226 if (isGNUVarArgs) MI->setIsGNUVarargs();
2227 if (hasCommaPasting) MI->setHasCommaPasting();
2228 MI->setParameterList(MacroParams, PP.getPreprocessorAllocator());
2229 }
2230
2231 // Remember that we saw this macro last so that we add the tokens that
2232 // form its body to it.
2233 Macro = MI;
2234
2235 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
2236 Record[NextIndex]) {
2237 // We have a macro definition. Register the association
2238 PreprocessedEntityID
2239 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
2240 unsigned Index = translatePreprocessedEntityIDToIndex(GlobalID);
2241 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
2242 PreprocessingRecord::PPEntityID PPID =
2243 PPRec.getPPEntityID(Index, /*isLoaded=*/true);
2244 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
2245 PPRec.getPreprocessedEntity(PPID));
2246 if (PPDef)
2247 PPRec.RegisterMacroDefinition(Macro, PPDef);
2248 }
2249
2250 ++NumMacrosRead;
2251 break;
2252 }
2253
2254 case PP_TOKEN: {
2255 // If we see a TOKEN before a PP_MACRO_*, then the file is
2256 // erroneous, just pretend we didn't see this.
2257 if (!Macro) break;
2258 if (MacroTokens.empty()) {
2259 Error("unexpected number of macro tokens for a macro in AST file");
2260 return Macro;
2261 }
2262
2263 unsigned Idx = 0;
2264 MacroTokens[0] = ReadToken(F, Record, Idx);
2265 MacroTokens = MacroTokens.drop_front();
2266 break;
2267 }
2268 }
2269 }
2270 }
2271
2272 PreprocessedEntityID
2273 ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M,
2274 PreprocessedEntityID LocalID) const {
2275 if (!M.ModuleOffsetMap.empty())
2276 ReadModuleOffsetMap(M);
2277
2278 unsigned ModuleFileIndex = LocalID >> 32;
2279 LocalID &= llvm::maskTrailingOnes<PreprocessedEntityID>(32);
2280 ModuleFile *MF =
2281 ModuleFileIndex ? M.TransitiveImports[ModuleFileIndex - 1] : &M;
2282 assert(MF && "malformed identifier ID encoding?");
2283
2284 if (!ModuleFileIndex) {
2285 assert(LocalID >= NUM_PREDEF_PP_ENTITY_IDS);
2286 LocalID -= NUM_PREDEF_PP_ENTITY_IDS;
2287 }
2288
2289 return (static_cast<PreprocessedEntityID>(MF->Index + 1) << 32) | LocalID;
2290 }
2291
2292 OptionalFileEntryRef
2293 HeaderFileInfoTrait::getFile(const internal_key_type &Key) {
2294 FileManager &FileMgr = Reader.getFileManager();
2295 if (!Key.Imported)
2296 return FileMgr.getOptionalFileRef(Key.Filename);
2297
2298 auto Resolved =
2299 ASTReader::ResolveImportedPath(Reader.getPathBuf(), Key.Filename, M);
2300 return FileMgr.getOptionalFileRef(*Resolved);
2301 }
2302
2303 unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
2304 uint8_t buf[sizeof(ikey.Size) + sizeof(ikey.ModTime)];
2305 memcpy(buf, &ikey.Size, sizeof(ikey.Size));
2306 memcpy(buf + sizeof(ikey.Size), &ikey.ModTime, sizeof(ikey.ModTime));
2307 return llvm::xxh3_64bits(buf);
2308 }
2309
2310 HeaderFileInfoTrait::internal_key_type
2311 HeaderFileInfoTrait::GetInternalKey(external_key_type ekey) {
2312 internal_key_type ikey = {ekey.getSize(),
2313 M.HasTimestamps ? ekey.getModificationTime() : 0,
2314 ekey.getName(), /*Imported*/ false};
2315 return ikey;
2316 }
2317
2318 bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
2319 if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime))
2320 return false;
2321
2322 if (llvm::sys::path::is_absolute(a.Filename) && a.Filename == b.Filename)
2323 return true;
2324
2325 // Determine whether the actual files are equivalent.
2326 OptionalFileEntryRef FEA = getFile(a);
2327 OptionalFileEntryRef FEB = getFile(b);
2328 return FEA && FEA == FEB;
2329 }
2330
2331 std::pair<unsigned, unsigned>
2332 HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
2333 return readULEBKeyDataLength(d);
2334 }
2335
2336 HeaderFileInfoTrait::internal_key_type
2337 HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
2338 using namespace llvm::support;
2339
2340 internal_key_type ikey;
2341 ikey.Size = off_t(endian::readNext<uint64_t, llvm::endianness::little>(d));
2342 ikey.ModTime =
2343 time_t(endian::readNext<uint64_t, llvm::endianness::little>(d));
2344 ikey.Filename = (const char *)d;
2345 ikey.Imported = true;
2346 return ikey;
2347 }
2348
2349 HeaderFileInfoTrait::data_type
2350 HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
2351 unsigned DataLen) {
2352 using namespace llvm::support;
2353
2354 const unsigned char *End = d + DataLen;
2355 HeaderFileInfo HFI;
2356 unsigned Flags = *d++;
2357
2358 OptionalFileEntryRef FE;
2359 bool Included = (Flags >> 6) & 0x01;
2360 if (Included)
2361 if ((FE = getFile(key)))
2362 // Not using \c Preprocessor::markIncluded(), since that would attempt to
2363 // deserialize this header file info again.
2364 Reader.getPreprocessor().getIncludedFiles().insert(*FE);
2365
2366 // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
2367 HFI.isImport |= (Flags >> 5) & 0x01;
2368 HFI.isPragmaOnce |= (Flags >> 4) & 0x01;
2369 HFI.DirInfo = (Flags >> 1) & 0x07;
2370 HFI.LazyControllingMacro = Reader.getGlobalIdentifierID(
2371 M, endian::readNext<IdentifierID, llvm::endianness::little>(d));
2372
2373 assert((End - d) % 4 == 0 &&
2374 "Wrong data length in HeaderFileInfo deserialization");
2375 while (d != End) {
2376 uint32_t LocalSMID =
2377 endian::readNext<uint32_t, llvm::endianness::little>(d);
2378 auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 7);
2379 LocalSMID >>= 3;
2380
2381 // This header is part of a module. Associate it with the module to enable
2382 // implicit module import.
2383 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
2384 Module *Mod = Reader.getSubmodule(GlobalSMID);
2385 ModuleMap &ModMap =
2386 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
2387
2388 if (FE || (FE = getFile(key))) {
2389 // FIXME: NameAsWritten
2390 Module::Header H = {std::string(key.Filename), "", *FE};
2391 ModMap.addHeader(Mod, H, HeaderRole, /*Imported=*/true);
2392 }
2393 HFI.mergeModuleMembership(HeaderRole);
2394 }
2395
2396 // This HeaderFileInfo was externally loaded.
2397 HFI.External = true;
2398 HFI.IsValid = true;
2399 return HFI;
2400 }
2401
2402 void ASTReader::addPendingMacro(IdentifierInfo *II, ModuleFile *M,
2403 uint32_t MacroDirectivesOffset) {
2404 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
2405 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
2406 }
2407
2408 void ASTReader::ReadDefinedMacros() {
2409 // Note that we are loading defined macros.
2410 Deserializing Macros(this);
2411
2412 for (ModuleFile &I : llvm::reverse(ModuleMgr)) {
2413 BitstreamCursor &MacroCursor = I.MacroCursor;
2414
2415 // If there was no preprocessor block, skip this file.
2416 if (MacroCursor.getBitcodeBytes().empty())
2417 continue;
2418
2419 BitstreamCursor Cursor = MacroCursor;
2420 if (llvm::Error Err = Cursor.JumpToBit(I.MacroStartOffset)) {
2421 Error(std::move(Err));
2422 return;
2423 }
2424
2425 RecordData Record;
2426 while (true) {
2427 Expected<llvm::BitstreamEntry> MaybeE = Cursor.advanceSkippingSubblocks();
2428 if (!MaybeE) {
2429 Error(MaybeE.takeError());
2430 return;
2431 }
2432 llvm::BitstreamEntry E = MaybeE.get();
2433
2434 switch (E.Kind) {
2435 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
2436 case llvm::BitstreamEntry::Error:
2437 Error("malformed block record in AST file");
2438 return;
2439 case llvm::BitstreamEntry::EndBlock:
2440 goto NextCursor;
2441
2442 case llvm::BitstreamEntry::Record: {
2443 Record.clear();
2444 Expected<unsigned> MaybeRecord = Cursor.readRecord(E.ID, Record);
2445 if (!MaybeRecord) {
2446 Error(MaybeRecord.takeError());
2447 return;
2448 }
2449 switch (MaybeRecord.get()) {
2450 default: // Default behavior: ignore.
2451 break;
2452
2453 case PP_MACRO_OBJECT_LIKE:
2454 case PP_MACRO_FUNCTION_LIKE: {
2455 IdentifierInfo *II = getLocalIdentifier(I, Record[0]);
2456 if (II->isOutOfDate())
2457 updateOutOfDateIdentifier(*II);
2458 break;
2459 }
2460
2461 case PP_TOKEN:
2462 // Ignore tokens.
2463 break;
2464 }
2465 break;
2466 }
2467 }
2468 }
2469 NextCursor: ;
2470 }
2471 }
2472
2473 namespace {
2474
2475 /// Visitor class used to look up identifirs in an AST file.
2476 class IdentifierLookupVisitor {
2477 StringRef Name;
2478 unsigned NameHash;
2479 unsigned PriorGeneration;
2480 unsigned &NumIdentifierLookups;
2481 unsigned &NumIdentifierLookupHits;
2482 IdentifierInfo *Found = nullptr;
2483
2484 public:
2485 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
2486 unsigned &NumIdentifierLookups,
2487 unsigned &NumIdentifierLookupHits)
2488 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
2489 PriorGeneration(PriorGeneration),
2490 NumIdentifierLookups(NumIdentifierLookups),
2491 NumIdentifierLookupHits(NumIdentifierLookupHits) {}
2492
2493 bool operator()(ModuleFile &M) {
2494 // If we've already searched this module file, skip it now.
2495 if (M.Generation <= PriorGeneration)
2496 return true;
2497
2498 ASTIdentifierLookupTable *IdTable
2499 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
2500 if (!IdTable)
2501 return false;
2502
2503 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
2504 Found);
2505 ++NumIdentifierLookups;
2506 ASTIdentifierLookupTable::iterator Pos =
2507 IdTable->find_hashed(Name, NameHash, &Trait);
2508 if (Pos == IdTable->end())
2509 return false;
2510
2511 // Dereferencing the iterator has the effect of building the
2512 // IdentifierInfo node and populating it with the various
2513 // declarations it needs.
2514 ++NumIdentifierLookupHits;
2515 Found = *Pos;
2516 if (Trait.hasMoreInformationInDependencies()) {
2517 // Look for the identifier in extra modules as they contain more info.
2518 return false;
2519 }
2520 return true;
2521 }
2522
2523 // Retrieve the identifier info found within the module
2524 // files.
2525 IdentifierInfo *getIdentifierInfo() const { return Found; }
2526 };
2527
2528 } // namespace
2529
2530 void ASTReader::updateOutOfDateIdentifier(const IdentifierInfo &II) {
2531 // Note that we are loading an identifier.
2532 Deserializing AnIdentifier(this);
2533
2534 unsigned PriorGeneration = 0;
2535 if (getContext().getLangOpts().Modules)
2536 PriorGeneration = IdentifierGeneration[&II];
2537
2538 // If there is a global index, look there first to determine which modules
2539 // provably do not have any results for this identifier.
2540 GlobalModuleIndex::HitSet Hits;
2541 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
2542 if (!loadGlobalIndex()) {
2543 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
2544 HitsPtr = &Hits;
2545 }
2546 }
2547
2548 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
2549 NumIdentifierLookups,
2550 NumIdentifierLookupHits);
2551 ModuleMgr.visit(Visitor, HitsPtr);
2552 markIdentifierUpToDate(&II);
2553 }
2554
2555 void ASTReader::markIdentifierUpToDate(const IdentifierInfo *II) {
2556 if (!II)
2557 return;
2558
2559 const_cast<IdentifierInfo *>(II)->setOutOfDate(false);
2560
2561 // Update the generation for this identifier.
2562 if (getContext().getLangOpts().Modules)
2563 IdentifierGeneration[II] = getGeneration();
2564 }
2565
2566 MacroID ASTReader::ReadMacroID(ModuleFile &F, const RecordDataImpl &Record,
2567 unsigned &Idx) {
2568 uint64_t ModuleFileIndex = Record[Idx++] << 32;
2569 uint64_t LocalIndex = Record[Idx++];
2570 return getGlobalMacroID(F, (ModuleFileIndex | LocalIndex));
2571 }
2572
2573 void ASTReader::resolvePendingMacro(IdentifierInfo *II,
2574 const PendingMacroInfo &PMInfo) {
2575 ModuleFile &M = *PMInfo.M;
2576
2577 BitstreamCursor &Cursor = M.MacroCursor;
2578 SavedStreamPosition SavedPosition(Cursor);
2579 if (llvm::Error Err =
2580 Cursor.JumpToBit(M.MacroOffsetsBase + PMInfo.MacroDirectivesOffset)) {
2581 Error(std::move(Err));
2582 return;
2583 }
2584
2585 struct ModuleMacroRecord {
2586 SubmoduleID SubModID;
2587 MacroInfo *MI;
2588 SmallVector<SubmoduleID, 8> Overrides;
2589 };
2590 llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
2591
2592 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
2593 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
2594 // macro histroy.
2595 RecordData Record;
2596 while (true) {
2597 Expected<llvm::BitstreamEntry> MaybeEntry =
2598 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
2599 if (!MaybeEntry) {
2600 Error(MaybeEntry.takeError());
2601 return;
2602 }
2603 llvm::BitstreamEntry Entry = MaybeEntry.get();
2604
2605 if (Entry.Kind != llvm::BitstreamEntry::Record) {
2606 Error("malformed block record in AST file");
2607 return;
2608 }
2609
2610 Record.clear();
2611 Expected<unsigned> MaybePP = Cursor.readRecord(Entry.ID, Record);
2612 if (!MaybePP) {
2613 Error(MaybePP.takeError());
2614 return;
2615 }
2616 switch ((PreprocessorRecordTypes)MaybePP.get()) {
2617 case PP_MACRO_DIRECTIVE_HISTORY:
2618 break;
2619
2620 case PP_MODULE_MACRO: {
2621 ModuleMacros.push_back(ModuleMacroRecord());
2622 auto &Info = ModuleMacros.back();
2623 unsigned Idx = 0;
2624 Info.SubModID = getGlobalSubmoduleID(M, Record[Idx++]);
2625 Info.MI = getMacro(ReadMacroID(M, Record, Idx));
2626 for (int I = Idx, N = Record.size(); I != N; ++I)
2627 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
2628 continue;
2629 }
2630
2631 default:
2632 Error("malformed block record in AST file");
2633 return;
2634 }
2635
2636 // We found the macro directive history; that's the last record
2637 // for this macro.
2638 break;
2639 }
2640
2641 // Module macros are listed in reverse dependency order.
2642 {
2643 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
2644 llvm::SmallVector<ModuleMacro*, 8> Overrides;
2645 for (auto &MMR : ModuleMacros) {
2646 Overrides.clear();
2647 for (unsigned ModID : MMR.Overrides) {
2648 Module *Mod = getSubmodule(ModID);
2649 auto *Macro = PP.getModuleMacro(Mod, II);
2650 assert(Macro && "missing definition for overridden macro");
2651 Overrides.push_back(Macro);
2652 }
2653
2654 bool Inserted = false;
2655 Module *Owner = getSubmodule(MMR.SubModID);
2656 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
2657 }
2658 }
2659
2660 // Don't read the directive history for a module; we don't have anywhere
2661 // to put it.
2662 if (M.isModule())
2663 return;
2664
2665 // Deserialize the macro directives history in reverse source-order.
2666 MacroDirective *Latest = nullptr, *Earliest = nullptr;
2667 unsigned Idx = 0, N = Record.size();
2668 while (Idx < N) {
2669 MacroDirective *MD = nullptr;
2670 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
2671 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
2672 switch (K) {
2673 case MacroDirective::MD_Define: {
2674 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
2675 MD = PP.AllocateDefMacroDirective(MI, Loc);
2676 break;
2677 }
2678 case MacroDirective::MD_Undefine:
2679 MD = PP.AllocateUndefMacroDirective(Loc);
2680 break;
2681 case MacroDirective::MD_Visibility:
2682 bool isPublic = Record[Idx++];
2683 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
2684 break;
2685 }
2686
2687 if (!Latest)
2688 Latest = MD;
2689 if (Earliest)
2690 Earliest->setPrevious(MD);
2691 Earliest = MD;
2692 }
2693
2694 if (Latest)
2695 PP.setLoadedMacroDirective(II, Earliest, Latest);
2696 }
2697
2698 bool ASTReader::shouldDisableValidationForFile(
2699 const serialization::ModuleFile &M) const {
2700 if (DisableValidationKind == DisableValidationForModuleKind::None)
2701 return false;
2702
2703 // If a PCH is loaded and validation is disabled for PCH then disable
2704 // validation for the PCH and the modules it loads.
2705 ModuleKind K = CurrentDeserializingModuleKind.value_or(M.Kind);
2706
2707 switch (K) {
2708 case MK_MainFile:
2709 case MK_Preamble:
2710 case MK_PCH:
2711 return bool(DisableValidationKind & DisableValidationForModuleKind::PCH);
2712 case MK_ImplicitModule:
2713 case MK_ExplicitModule:
2714 case MK_PrebuiltModule:
2715 return bool(DisableValidationKind & DisableValidationForModuleKind::Module);
2716 }
2717
2718 return false;
2719 }
2720
2721 static std::pair<StringRef, StringRef>
2722 getUnresolvedInputFilenames(const ASTReader::RecordData &Record,
2723 const StringRef InputBlob) {
2724 uint16_t AsRequestedLength = Record[7];
2725 return {InputBlob.substr(0, AsRequestedLength),
2726 InputBlob.substr(AsRequestedLength)};
2727 }
2728
2729 InputFileInfo ASTReader::getInputFileInfo(ModuleFile &F, unsigned ID) {
2730 // If this ID is bogus, just return an empty input file.
2731 if (ID == 0 || ID > F.InputFileInfosLoaded.size())
2732 return InputFileInfo();
2733
2734 // If we've already loaded this input file, return it.
2735 if (F.InputFileInfosLoaded[ID - 1].isValid())
2736 return F.InputFileInfosLoaded[ID - 1];
2737
2738 // Go find this input file.
2739 BitstreamCursor &Cursor = F.InputFilesCursor;
2740 SavedStreamPosition SavedPosition(Cursor);
2741 if (llvm::Error Err = Cursor.JumpToBit(F.InputFilesOffsetBase +
2742 F.InputFileOffsets[ID - 1])) {
2743 // FIXME this drops errors on the floor.
2744 consumeError(std::move(Err));
2745 }
2746
2747 Expected<unsigned> MaybeCode = Cursor.ReadCode();
2748 if (!MaybeCode) {
2749 // FIXME this drops errors on the floor.
2750 consumeError(MaybeCode.takeError());
2751 }
2752 unsigned Code = MaybeCode.get();
2753 RecordData Record;
2754 StringRef Blob;
2755
2756 if (Expected<unsigned> Maybe = Cursor.readRecord(Code, Record, &Blob))
2757 assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE &&
2758 "invalid record type for input file");
2759 else {
2760 // FIXME this drops errors on the floor.
2761 consumeError(Maybe.takeError());
2762 }
2763
2764 assert(Record[0] == ID && "Bogus stored ID or offset");
2765 InputFileInfo R;
2766 R.StoredSize = static_cast<off_t>(Record[1]);
2767 R.StoredTime = static_cast<time_t>(Record[2]);
2768 R.Overridden = static_cast<bool>(Record[3]);
2769 R.Transient = static_cast<bool>(Record[4]);
2770 R.TopLevel = static_cast<bool>(Record[5]);
2771 R.ModuleMap = static_cast<bool>(Record[6]);
2772 auto [UnresolvedFilenameAsRequested, UnresolvedFilename] =
2773 getUnresolvedInputFilenames(Record, Blob);
2774 R.UnresolvedImportedFilenameAsRequested = UnresolvedFilenameAsRequested;
2775 R.UnresolvedImportedFilename = UnresolvedFilename.empty()
2776 ? UnresolvedFilenameAsRequested
2777 : UnresolvedFilename;
2778
2779 Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
2780 if (!MaybeEntry) // FIXME this drops errors on the floor.
2781 consumeError(MaybeEntry.takeError());
2782 llvm::BitstreamEntry Entry = MaybeEntry.get();
2783 assert(Entry.Kind == llvm::BitstreamEntry::Record &&
2784 "expected record type for input file hash");
2785
2786 Record.clear();
2787 if (Expected<unsigned> Maybe = Cursor.readRecord(Entry.ID, Record))
2788 assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE_HASH &&
2789 "invalid record type for input file hash");
2790 else {
2791 // FIXME this drops errors on the floor.
2792 consumeError(Maybe.takeError());
2793 }
2794 R.ContentHash = (static_cast<uint64_t>(Record[1]) << 32) |
2795 static_cast<uint64_t>(Record[0]);
2796
2797 // Note that we've loaded this input file info.
2798 F.InputFileInfosLoaded[ID - 1] = R;
2799 return R;
2800 }
2801
2802 static unsigned moduleKindForDiagnostic(ModuleKind Kind);
2803 InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
2804 // If this ID is bogus, just return an empty input file.
2805 if (ID == 0 || ID > F.InputFilesLoaded.size())
2806 return InputFile();
2807
2808 // If we've already loaded this input file, return it.
2809 if (F.InputFilesLoaded[ID-1].getFile())
2810 return F.InputFilesLoaded[ID-1];
2811
2812 if (F.InputFilesLoaded[ID-1].isNotFound())
2813 return InputFile();
2814
2815 // Go find this input file.
2816 BitstreamCursor &Cursor = F.InputFilesCursor;
2817 SavedStreamPosition SavedPosition(Cursor);
2818 if (llvm::Error Err = Cursor.JumpToBit(F.InputFilesOffsetBase +
2819 F.InputFileOffsets[ID - 1])) {
2820 // FIXME this drops errors on the floor.
2821 consumeError(std::move(Err));
2822 }
2823
2824 InputFileInfo FI = getInputFileInfo(F, ID);
2825 off_t StoredSize = FI.StoredSize;
2826 time_t StoredTime = FI.StoredTime;
2827 bool Overridden = FI.Overridden;
2828 bool Transient = FI.Transient;
2829 auto Filename =
2830 ResolveImportedPath(PathBuf, FI.UnresolvedImportedFilenameAsRequested, F);
2831 uint64_t StoredContentHash = FI.ContentHash;
2832
2833 // For standard C++ modules, we don't need to check the inputs.
2834 bool SkipChecks = F.StandardCXXModule;
2835
2836 const HeaderSearchOptions &HSOpts =
2837 PP.getHeaderSearchInfo().getHeaderSearchOpts();
2838
2839 // The option ForceCheckCXX20ModulesInputFiles is only meaningful for C++20
2840 // modules.
2841 if (F.StandardCXXModule && HSOpts.ForceCheckCXX20ModulesInputFiles) {
2842 SkipChecks = false;
2843 Overridden = false;
2844 }
2845
2846 auto File = FileMgr.getOptionalFileRef(*Filename, /*OpenFile=*/false);
2847
2848 // For an overridden file, create a virtual file with the stored
2849 // size/timestamp.
2850 if ((Overridden || Transient || SkipChecks) && !File)
2851 File = FileMgr.getVirtualFileRef(*Filename, StoredSize, StoredTime);
2852
2853 if (!File) {
2854 if (Complain) {
2855 std::string ErrorStr = "could not find file '";
2856 ErrorStr += *Filename;
2857 ErrorStr += "' referenced by AST file '";
2858 ErrorStr += F.FileName;
2859 ErrorStr += "'";
2860 Error(ErrorStr);
2861 }
2862 // Record that we didn't find the file.
2863 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
2864 return InputFile();
2865 }
2866
2867 // Check if there was a request to override the contents of the file
2868 // that was part of the precompiled header. Overriding such a file
2869 // can lead to problems when lexing using the source locations from the
2870 // PCH.
2871 SourceManager &SM = getSourceManager();
2872 // FIXME: Reject if the overrides are different.
2873 if ((!Overridden && !Transient) && !SkipChecks &&
2874 SM.isFileOverridden(*File)) {
2875 if (Complain)
2876 Error(diag::err_fe_pch_file_overridden, *Filename);
2877
2878 // After emitting the diagnostic, bypass the overriding file to recover
2879 // (this creates a separate FileEntry).
2880 File = SM.bypassFileContentsOverride(*File);
2881 if (!File) {
2882 F.InputFilesLoaded[ID - 1] = InputFile::getNotFound();
2883 return InputFile();
2884 }
2885 }
2886
2887 struct Change {
2888 enum ModificationKind {
2889 Size,
2890 ModTime,
2891 Content,
2892 None,
2893 } Kind;
2894 std::optional<int64_t> Old = std::nullopt;
2895 std::optional<int64_t> New = std::nullopt;
2896 };
2897 auto HasInputContentChanged = [&](Change OriginalChange) {
2898 assert(ValidateASTInputFilesContent &&
2899 "We should only check the content of the inputs with "
2900 "ValidateASTInputFilesContent enabled.");
2901
2902 if (StoredContentHash == 0)
2903 return OriginalChange;
2904
2905 auto MemBuffOrError = FileMgr.getBufferForFile(*File);
2906 if (!MemBuffOrError) {
2907 if (!Complain)
2908 return OriginalChange;
2909 std::string ErrorStr = "could not get buffer for file '";
2910 ErrorStr += File->getName();
2911 ErrorStr += "'";
2912 Error(ErrorStr);
2913 return OriginalChange;
2914 }
2915
2916 auto ContentHash = xxh3_64bits(MemBuffOrError.get()->getBuffer());
2917 if (StoredContentHash == static_cast<uint64_t>(ContentHash))
2918 return Change{Change::None};
2919
2920 return Change{Change::Content};
2921 };
2922 auto HasInputFileChanged = [&]() {
2923 if (StoredSize != File->getSize())
2924 return Change{Change::Size, StoredSize, File->getSize()};
2925 if (!shouldDisableValidationForFile(F) && StoredTime &&
2926 StoredTime != File->getModificationTime()) {
2927 Change MTimeChange = {Change::ModTime, StoredTime,
2928 File->getModificationTime()};
2929
2930 // In case the modification time changes but not the content,
2931 // accept the cached file as legit.
2932 if (ValidateASTInputFilesContent)
2933 return HasInputContentChanged(MTimeChange);
2934
2935 return MTimeChange;
2936 }
2937 return Change{Change::None};
2938 };
2939
2940 bool IsOutOfDate = false;
2941 auto FileChange = SkipChecks ? Change{Change::None} : HasInputFileChanged();
2942 // When ForceCheckCXX20ModulesInputFiles and ValidateASTInputFilesContent
2943 // enabled, it is better to check the contents of the inputs. Since we can't
2944 // get correct modified time information for inputs from overriden inputs.
2945 if (HSOpts.ForceCheckCXX20ModulesInputFiles && ValidateASTInputFilesContent &&
2946 F.StandardCXXModule && FileChange.Kind == Change::None)
2947 FileChange = HasInputContentChanged(FileChange);
2948
2949 // When we have StoredTime equal to zero and ValidateASTInputFilesContent,
2950 // it is better to check the content of the input files because we cannot rely
2951 // on the file modification time, which will be the same (zero) for these
2952 // files.
2953 if (!StoredTime && ValidateASTInputFilesContent &&
2954 FileChange.Kind == Change::None)
2955 FileChange = HasInputContentChanged(FileChange);
2956
2957 // For an overridden file, there is nothing to validate.
2958 if (!Overridden && FileChange.Kind != Change::None) {
2959 if (Complain) {
2960 // Build a list of the PCH imports that got us here (in reverse).
2961 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2962 while (!ImportStack.back()->ImportedBy.empty())
2963 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
2964
2965 // The top-level AST file is stale.
2966 StringRef TopLevelASTFileName(ImportStack.back()->FileName);
2967 Diag(diag::err_fe_ast_file_modified)
2968 << *Filename << moduleKindForDiagnostic(ImportStack.back()->Kind)
2969 << TopLevelASTFileName << FileChange.Kind
2970 << (FileChange.Old && FileChange.New)
2971 << llvm::itostr(FileChange.Old.value_or(0))
2972 << llvm::itostr(FileChange.New.value_or(0));
2973
2974 // Print the import stack.
2975 if (ImportStack.size() > 1) {
2976 Diag(diag::note_ast_file_required_by)
2977 << *Filename << ImportStack[0]->FileName;
2978 for (unsigned I = 1; I < ImportStack.size(); ++I)
2979 Diag(diag::note_ast_file_required_by)
2980 << ImportStack[I - 1]->FileName << ImportStack[I]->FileName;
2981 }
2982
2983 Diag(diag::note_ast_file_rebuild_required) << TopLevelASTFileName;
2984 }
2985
2986 IsOutOfDate = true;
2987 }
2988 // FIXME: If the file is overridden and we've already opened it,
2989 // issue an error (or split it into a separate FileEntry).
2990
2991 InputFile IF = InputFile(*File, Overridden || Transient, IsOutOfDate);
2992
2993 // Note that we've loaded this input file.
2994 F.InputFilesLoaded[ID-1] = IF;
2995 return IF;
2996 }
2997
2998 ASTReader::TemporarilyOwnedStringRef
2999 ASTReader::ResolveImportedPath(SmallString<0> &Buf, StringRef Path,
3000 ModuleFile &ModF) {
3001 return ResolveImportedPath(Buf, Path, ModF.BaseDirectory);
3002 }
3003
3004 ASTReader::TemporarilyOwnedStringRef
3005 ASTReader::ResolveImportedPath(SmallString<0> &Buf, StringRef Path,
3006 StringRef Prefix) {
3007 assert(Buf.capacity() != 0 && "Overlapping ResolveImportedPath calls");
3008
3009 if (Prefix.empty() || Path.empty() || llvm::sys::path::is_absolute(Path) ||
3010 Path == "<built-in>" || Path == "<command line>")
3011 return {Path, Buf};
3012
3013 Buf.clear();
3014 llvm::sys::path::append(Buf, Prefix, Path);
3015 StringRef ResolvedPath{Buf.data(), Buf.size()};
3016 return {ResolvedPath, Buf};
3017 }
3018
3019 std::string ASTReader::ResolveImportedPathAndAllocate(SmallString<0> &Buf,
3020 StringRef P,
3021 ModuleFile &ModF) {
3022 return ResolveImportedPathAndAllocate(Buf, P, ModF.BaseDirectory);
3023 }
3024
3025 std::string ASTReader::ResolveImportedPathAndAllocate(SmallString<0> &Buf,
3026 StringRef P,
3027 StringRef Prefix) {
3028 auto ResolvedPath = ResolveImportedPath(Buf, P, Prefix);
3029 return ResolvedPath->str();
3030 }
3031
3032 static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
3033 switch (ARR) {
3034 case ASTReader::Failure: return true;
3035 case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
3036 case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
3037 case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch);
3038 case ASTReader::ConfigurationMismatch:
3039 return !(Caps & ASTReader::ARR_ConfigurationMismatch);
3040 case ASTReader::HadErrors: return true;
3041 case ASTReader::Success: return false;
3042 }
3043
3044 llvm_unreachable("unknown ASTReadResult");
3045 }
3046
3047 ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(
3048 BitstreamCursor &Stream, StringRef Filename,
3049 unsigned ClientLoadCapabilities, bool AllowCompatibleConfigurationMismatch,
3050 ASTReaderListener &Listener, std::string &SuggestedPredefines) {
3051 if (llvm::Error Err = Stream.EnterSubBlock(OPTIONS_BLOCK_ID)) {
3052 // FIXME this drops errors on the floor.
3053 consumeError(std::move(Err));
3054 return Failure;
3055 }
3056
3057 // Read all of the records in the options block.
3058 RecordData Record;
3059 ASTReadResult Result = Success;
3060 while (true) {
3061 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
3062 if (!MaybeEntry) {
3063 // FIXME this drops errors on the floor.
3064 consumeError(MaybeEntry.takeError());
3065 return Failure;
3066 }
3067 llvm::BitstreamEntry Entry = MaybeEntry.get();
3068
3069 switch (Entry.Kind) {
3070 case llvm::BitstreamEntry::Error:
3071 case llvm::BitstreamEntry::SubBlock:
3072 return Failure;
3073
3074 case llvm::BitstreamEntry::EndBlock:
3075 return Result;
3076
3077 case llvm::BitstreamEntry::Record:
3078 // The interesting case.
3079 break;
3080 }
3081
3082 // Read and process a record.
3083 Record.clear();
3084 Expected<unsigned> MaybeRecordType = Stream.readRecord(Entry.ID, Record);
3085 if (!MaybeRecordType) {
3086 // FIXME this drops errors on the floor.
3087 consumeError(MaybeRecordType.takeError());
3088 return Failure;
3089 }
3090 switch ((OptionsRecordTypes)MaybeRecordType.get()) {
3091 case LANGUAGE_OPTIONS: {
3092 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
3093 if (ParseLanguageOptions(Record, Filename, Complain, Listener,
3094 AllowCompatibleConfigurationMismatch))
3095 Result = ConfigurationMismatch;
3096 break;
3097 }
3098
3099 case CODEGEN_OPTIONS: {
3100 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
3101 if (ParseCodeGenOptions(Record, Filename, Complain, Listener,
3102 AllowCompatibleConfigurationMismatch))
3103 Result = ConfigurationMismatch;
3104 break;
3105 }
3106
3107 case TARGET_OPTIONS: {
3108 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
3109 if (ParseTargetOptions(Record, Filename, Complain, Listener,
3110 AllowCompatibleConfigurationMismatch))
3111 Result = ConfigurationMismatch;
3112 break;
3113 }
3114
3115 case FILE_SYSTEM_OPTIONS: {
3116 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
3117 if (!AllowCompatibleConfigurationMismatch &&
3118 ParseFileSystemOptions(Record, Complain, Listener))
3119 Result = ConfigurationMismatch;
3120 break;
3121 }
3122
3123 case HEADER_SEARCH_OPTIONS: {
3124 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
3125 if (!AllowCompatibleConfigurationMismatch &&
3126 ParseHeaderSearchOptions(Record, Filename, Complain, Listener))
3127 Result = ConfigurationMismatch;
3128 break;
3129 }
3130
3131 case PREPROCESSOR_OPTIONS:
3132 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
3133 if (!AllowCompatibleConfigurationMismatch &&
3134 ParsePreprocessorOptions(Record, Filename, Complain, Listener,
3135 SuggestedPredefines))
3136 Result = ConfigurationMismatch;
3137 break;
3138 }
3139 }
3140 }
3141
3142 ASTReader::ASTReadResult
3143 ASTReader::ReadControlBlock(ModuleFile &F,
3144 SmallVectorImpl<ImportedModule> &Loaded,
3145 const ModuleFile *ImportedBy,
3146 unsigned ClientLoadCapabilities) {
3147 BitstreamCursor &Stream = F.Stream;
3148
3149 if (llvm::Error Err = Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
3150 Error(std::move(Err));
3151 return Failure;
3152 }
3153
3154 // Lambda to read the unhashed control block the first time it's called.
3155 //
3156 // For PCM files, the unhashed control block cannot be read until after the
3157 // MODULE_NAME record. However, PCH files have no MODULE_NAME, and yet still
3158 // need to look ahead before reading the IMPORTS record. For consistency,
3159 // this block is always read somehow (see BitstreamEntry::EndBlock).
3160 bool HasReadUnhashedControlBlock = false;
3161 auto readUnhashedControlBlockOnce = [&]() {
3162 if (!HasReadUnhashedControlBlock) {
3163 HasReadUnhashedControlBlock = true;
3164 if (ASTReadResult Result =
3165 readUnhashedControlBlock(F, ImportedBy, ClientLoadCapabilities))
3166 return Result;
3167 }
3168 return Success;
3169 };
3170
3171 bool DisableValidation = shouldDisableValidationForFile(F);
3172
3173 // Read all of the records and blocks in the control block.
3174 RecordData Record;
3175 unsigned NumInputs = 0;
3176 unsigned NumUserInputs = 0;
3177 StringRef BaseDirectoryAsWritten;
3178 while (true) {
3179 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
3180 if (!MaybeEntry) {
3181 Error(MaybeEntry.takeError());
3182 return Failure;
3183 }
3184 llvm::BitstreamEntry Entry = MaybeEntry.get();
3185
3186 switch (Entry.Kind) {
3187 case llvm::BitstreamEntry::Error:
3188 Error("malformed block record in AST file");
3189 return Failure;
3190 case llvm::BitstreamEntry::EndBlock: {
3191 // Validate the module before returning. This call catches an AST with
3192 // no module name and no imports.
3193 if (ASTReadResult Result = readUnhashedControlBlockOnce())
3194 return Result;
3195
3196 // Validate input files.
3197 const HeaderSearchOptions &HSOpts =
3198 PP.getHeaderSearchInfo().getHeaderSearchOpts();
3199
3200 // All user input files reside at the index range [0, NumUserInputs), and
3201 // system input files reside at [NumUserInputs, NumInputs). For explicitly
3202 // loaded module files, ignore missing inputs.
3203 if (!DisableValidation && F.Kind != MK_ExplicitModule &&
3204 F.Kind != MK_PrebuiltModule) {
3205 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
3206
3207 // If we are reading a module, we will create a verification timestamp,
3208 // so we verify all input files. Otherwise, verify only user input
3209 // files.
3210
3211 unsigned N = ValidateSystemInputs ? NumInputs : NumUserInputs;
3212 if (HSOpts.ModulesValidateOncePerBuildSession &&
3213 F.InputFilesValidationTimestamp > HSOpts.BuildSessionTimestamp &&
3214 F.Kind == MK_ImplicitModule)
3215 N = ForceValidateUserInputs ? NumUserInputs : 0;
3216
3217 if (N != 0)
3218 Diag(diag::remark_module_validation)
3219 << N << F.ModuleName << F.FileName;
3220
3221 for (unsigned I = 0; I < N; ++I) {
3222 InputFile IF = getInputFile(F, I+1, Complain);
3223 if (!IF.getFile() || IF.isOutOfDate())
3224 return OutOfDate;
3225 }
3226 }
3227
3228 if (Listener)
3229 Listener->visitModuleFile(F.FileName, F.Kind);
3230
3231 if (Listener && Listener->needsInputFileVisitation()) {
3232 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
3233 : NumUserInputs;
3234 for (unsigned I = 0; I < N; ++I) {
3235 bool IsSystem = I >= NumUserInputs;
3236 InputFileInfo FI = getInputFileInfo(F, I + 1);
3237 auto FilenameAsRequested = ResolveImportedPath(
3238 PathBuf, FI.UnresolvedImportedFilenameAsRequested, F);
3239 Listener->visitInputFile(
3240 *FilenameAsRequested, IsSystem, FI.Overridden,
3241 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule);
3242 }
3243 }
3244
3245 return Success;
3246 }
3247
3248 case llvm::BitstreamEntry::SubBlock:
3249 switch (Entry.ID) {
3250 case INPUT_FILES_BLOCK_ID:
3251 F.InputFilesCursor = Stream;
3252 if (llvm::Error Err = Stream.SkipBlock()) {
3253 Error(std::move(Err));
3254 return Failure;
3255 }
3256 if (ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
3257 Error("malformed block record in AST file");
3258 return Failure;
3259 }
3260 F.InputFilesOffsetBase = F.InputFilesCursor.GetCurrentBitNo();
3261 continue;
3262
3263 case OPTIONS_BLOCK_ID:
3264 // If we're reading the first module for this group, check its options
3265 // are compatible with ours. For modules it imports, no further checking
3266 // is required, because we checked them when we built it.
3267 if (Listener && !ImportedBy) {
3268 // Should we allow the configuration of the module file to differ from
3269 // the configuration of the current translation unit in a compatible
3270 // way?
3271 //
3272 // FIXME: Allow this for files explicitly specified with -include-pch.
3273 bool AllowCompatibleConfigurationMismatch =
3274 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
3275
3276 ASTReadResult Result =
3277 ReadOptionsBlock(Stream, F.FileName, ClientLoadCapabilities,
3278 AllowCompatibleConfigurationMismatch, *Listener,
3279 SuggestedPredefines);
3280 if (Result == Failure) {
3281 Error("malformed block record in AST file");
3282 return Result;
3283 }
3284
3285 if (DisableValidation ||
3286 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
3287 Result = Success;
3288
3289 // If we can't load the module, exit early since we likely
3290 // will rebuild the module anyway. The stream may be in the
3291 // middle of a block.
3292 if (Result != Success)
3293 return Result;
3294 } else if (llvm::Error Err = Stream.SkipBlock()) {
3295 Error(std::move(Err));
3296 return Failure;
3297 }
3298 continue;
3299
3300 default:
3301 if (llvm::Error Err = Stream.SkipBlock()) {
3302 Error(std::move(Err));
3303 return Failure;
3304 }
3305 continue;
3306 }
3307
3308 case llvm::BitstreamEntry::Record:
3309 // The interesting case.
3310 break;
3311 }
3312
3313 // Read and process a record.
3314 Record.clear();
3315 StringRef Blob;
3316 Expected<unsigned> MaybeRecordType =
3317 Stream.readRecord(Entry.ID, Record, &Blob);
3318 if (!MaybeRecordType) {
3319 Error(MaybeRecordType.takeError());
3320 return Failure;
3321 }
3322 switch ((ControlRecordTypes)MaybeRecordType.get()) {
3323 case METADATA: {
3324 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
3325 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
3326 Diag(Record[0] < VERSION_MAJOR ? diag::err_ast_file_version_too_old
3327 : diag::err_ast_file_version_too_new)
3328 << moduleKindForDiagnostic(F.Kind) << F.FileName;
3329 return VersionMismatch;
3330 }
3331
3332 bool hasErrors = Record[7];
3333 if (hasErrors && !DisableValidation) {
3334 // If requested by the caller and the module hasn't already been read
3335 // or compiled, mark modules on error as out-of-date.
3336 if ((ClientLoadCapabilities & ARR_TreatModuleWithErrorsAsOutOfDate) &&
3337 canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
3338 return OutOfDate;
3339
3340 if (!AllowASTWithCompilerErrors) {
3341 Diag(diag::err_ast_file_with_compiler_errors)
3342 << moduleKindForDiagnostic(F.Kind) << F.FileName;
3343 return HadErrors;
3344 }
3345 }
3346 if (hasErrors) {
3347 Diags.ErrorOccurred = true;
3348 Diags.UncompilableErrorOccurred = true;
3349 Diags.UnrecoverableErrorOccurred = true;
3350 }
3351
3352 F.RelocatablePCH = Record[4];
3353 // Relative paths in a relocatable PCH are relative to our sysroot.
3354 if (F.RelocatablePCH)
3355 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
3356
3357 F.StandardCXXModule = Record[5];
3358
3359 F.HasTimestamps = Record[6];
3360
3361 const std::string &CurBranch = getClangFullRepositoryVersion();
3362 StringRef ASTBranch = Blob;
3363 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
3364 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
3365 Diag(diag::err_ast_file_different_branch)
3366 << moduleKindForDiagnostic(F.Kind) << F.FileName << ASTBranch
3367 << CurBranch;
3368 return VersionMismatch;
3369 }
3370 break;
3371 }
3372
3373 case IMPORT: {
3374 // Validate the AST before processing any imports (otherwise, untangling
3375 // them can be error-prone and expensive). A module will have a name and
3376 // will already have been validated, but this catches the PCH case.
3377 if (ASTReadResult Result = readUnhashedControlBlockOnce())
3378 return Result;
3379
3380 unsigned Idx = 0;
3381 // Read information about the AST file.
3382 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
3383
3384 // The import location will be the local one for now; we will adjust
3385 // all import locations of module imports after the global source
3386 // location info are setup, in ReadAST.
3387 auto [ImportLoc, ImportModuleFileIndex] =
3388 ReadUntranslatedSourceLocation(Record[Idx++]);
3389 // The import location must belong to the current module file itself.
3390 assert(ImportModuleFileIndex == 0);
3391
3392 StringRef ImportedName = ReadStringBlob(Record, Idx, Blob);
3393
3394 bool IsImportingStdCXXModule = Record[Idx++];
3395
3396 off_t StoredSize = 0;
3397 time_t StoredModTime = 0;
3398 ASTFileSignature StoredSignature;
3399 std::string ImportedFile;
3400 std::string StoredFile;
3401 bool IgnoreImportedByNote = false;
3402
3403 // For prebuilt and explicit modules first consult the file map for
3404 // an override. Note that here we don't search prebuilt module
3405 // directories if we're not importing standard c++ module, only the
3406 // explicit name to file mappings. Also, we will still verify the
3407 // size/signature making sure it is essentially the same file but
3408 // perhaps in a different location.
3409 if (ImportedKind == MK_PrebuiltModule || ImportedKind == MK_ExplicitModule)
3410 ImportedFile = PP.getHeaderSearchInfo().getPrebuiltModuleFileName(
3411 ImportedName, /*FileMapOnly*/ !IsImportingStdCXXModule);
3412
3413 if (IsImportingStdCXXModule && ImportedFile.empty()) {
3414 Diag(diag::err_failed_to_find_module_file) << ImportedName;
3415 return Missing;
3416 }
3417
3418 if (!IsImportingStdCXXModule) {
3419 StoredSize = (off_t)Record[Idx++];
3420 StoredModTime = (time_t)Record[Idx++];
3421
3422 StringRef SignatureBytes = Blob.substr(0, ASTFileSignature::size);
3423 StoredSignature = ASTFileSignature::create(SignatureBytes.begin(),
3424 SignatureBytes.end());
3425 Blob = Blob.substr(ASTFileSignature::size);
3426
3427 // Use BaseDirectoryAsWritten to ensure we use the same path in the
3428 // ModuleCache as when writing.
3429 StoredFile = ReadPathBlob(BaseDirectoryAsWritten, Record, Idx, Blob);
3430 if (ImportedFile.empty()) {
3431 ImportedFile = StoredFile;
3432 } else if (!getDiags().isIgnored(
3433 diag::warn_module_file_mapping_mismatch,
3434 CurrentImportLoc)) {
3435 auto ImportedFileRef =
3436 PP.getFileManager().getOptionalFileRef(ImportedFile);
3437 auto StoredFileRef =
3438 PP.getFileManager().getOptionalFileRef(StoredFile);
3439 if ((ImportedFileRef && StoredFileRef) &&
3440 (*ImportedFileRef != *StoredFileRef)) {
3441 Diag(diag::warn_module_file_mapping_mismatch)
3442 << ImportedFile << StoredFile;
3443 Diag(diag::note_module_file_imported_by)
3444 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
3445 IgnoreImportedByNote = true;
3446 }
3447 }
3448 }
3449
3450 // If our client can't cope with us being out of date, we can't cope with
3451 // our dependency being missing.
3452 unsigned Capabilities = ClientLoadCapabilities;
3453 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3454 Capabilities &= ~ARR_Missing;
3455
3456 // Load the AST file.
3457 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
3458 Loaded, StoredSize, StoredModTime,
3459 StoredSignature, Capabilities);
3460
3461 // Check the AST we just read from ImportedFile contains a different
3462 // module than we expected (ImportedName). This can occur for C++20
3463 // Modules when given a mismatch via -fmodule-file=<name>=<file>
3464 if (IsImportingStdCXXModule) {
3465 if (const auto *Imported =
3466 getModuleManager().lookupByFileName(ImportedFile);
3467 Imported != nullptr && Imported->ModuleName != ImportedName) {
3468 Diag(diag::err_failed_to_find_module_file) << ImportedName;
3469 Result = Missing;
3470 }
3471 }
3472
3473 // If we diagnosed a problem, produce a backtrace.
3474 bool recompilingFinalized = Result == OutOfDate &&
3475 (Capabilities & ARR_OutOfDate) &&
3476 getModuleManager()
3477 .getModuleCache()
3478 .getInMemoryModuleCache()
3479 .isPCMFinal(F.FileName);
3480 if (!IgnoreImportedByNote &&
3481 (isDiagnosedResult(Result, Capabilities) || recompilingFinalized))
3482 Diag(diag::note_module_file_imported_by)
3483 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
3484
3485 switch (Result) {
3486 case Failure: return Failure;
3487 // If we have to ignore the dependency, we'll have to ignore this too.
3488 case Missing:
3489 case OutOfDate: return OutOfDate;
3490 case VersionMismatch: return VersionMismatch;
3491 case ConfigurationMismatch: return ConfigurationMismatch;
3492 case HadErrors: return HadErrors;
3493 case Success: break;
3494 }
3495 break;
3496 }
3497
3498 case ORIGINAL_FILE:
3499 F.OriginalSourceFileID = FileID::get(Record[0]);
3500 F.ActualOriginalSourceFileName = std::string(Blob);
3501 F.OriginalSourceFileName = ResolveImportedPathAndAllocate(
3502 PathBuf, F.ActualOriginalSourceFileName, F);
3503 break;
3504
3505 case ORIGINAL_FILE_ID:
3506 F.OriginalSourceFileID = FileID::get(Record[0]);
3507 break;
3508
3509 case MODULE_NAME:
3510 F.ModuleName = std::string(Blob);
3511 Diag(diag::remark_module_import)
3512 << F.ModuleName << F.FileName << (ImportedBy ? true : false)
3513 << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());
3514 if (Listener)
3515 Listener->ReadModuleName(F.ModuleName);
3516
3517 // Validate the AST as soon as we have a name so we can exit early on
3518 // failure.
3519 if (ASTReadResult Result = readUnhashedControlBlockOnce())
3520 return Result;
3521
3522 break;
3523
3524 case MODULE_DIRECTORY: {
3525 // Save the BaseDirectory as written in the PCM for computing the module
3526 // filename for the ModuleCache.
3527 BaseDirectoryAsWritten = Blob;
3528 assert(!F.ModuleName.empty() &&
3529 "MODULE_DIRECTORY found before MODULE_NAME");
3530 F.BaseDirectory = std::string(Blob);
3531 if (!PP.getPreprocessorOpts().ModulesCheckRelocated)
3532 break;
3533 // If we've already loaded a module map file covering this module, we may
3534 // have a better path for it (relative to the current build).
3535 Module *M = PP.getHeaderSearchInfo().lookupModule(
3536 F.ModuleName, SourceLocation(), /*AllowSearch*/ true,
3537 /*AllowExtraModuleMapSearch*/ true);
3538 if (M && M->Directory) {
3539 // If we're implicitly loading a module, the base directory can't
3540 // change between the build and use.
3541 // Don't emit module relocation error if we have -fno-validate-pch
3542 if (!bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation &
3543 DisableValidationForModuleKind::Module) &&
3544 F.Kind != MK_ExplicitModule && F.Kind != MK_PrebuiltModule) {
3545 auto BuildDir = PP.getFileManager().getOptionalDirectoryRef(Blob);
3546 if (!BuildDir || *BuildDir != M->Directory) {
3547 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
3548 Diag(diag::err_imported_module_relocated)
3549 << F.ModuleName << Blob << M->Directory->getName();
3550 return OutOfDate;
3551 }
3552 }
3553 F.BaseDirectory = std::string(M->Directory->getName());
3554 }
3555 break;
3556 }
3557
3558 case MODULE_MAP_FILE:
3559 if (ASTReadResult Result =
3560 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
3561 return Result;
3562 break;
3563
3564 case INPUT_FILE_OFFSETS:
3565 NumInputs = Record[0];
3566 NumUserInputs = Record[1];
3567 F.InputFileOffsets =
3568 (const llvm::support::unaligned_uint64_t *)Blob.data();
3569 F.InputFilesLoaded.resize(NumInputs);
3570 F.InputFileInfosLoaded.resize(NumInputs);
3571 F.NumUserInputFiles = NumUserInputs;
3572 break;
3573 }
3574 }
3575 }
3576
3577 llvm::Error ASTReader::ReadASTBlock(ModuleFile &F,
3578 unsigned ClientLoadCapabilities) {
3579 BitstreamCursor &Stream = F.Stream;
3580
3581 if (llvm::Error Err = Stream.EnterSubBlock(AST_BLOCK_ID))
3582 return Err;
3583 F.ASTBlockStartOffset = Stream.GetCurrentBitNo();
3584
3585 // Read all of the records and blocks for the AST file.
3586 RecordData Record;
3587 while (true) {
3588 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
3589 if (!MaybeEntry)
3590 return MaybeEntry.takeError();
3591 llvm::BitstreamEntry Entry = MaybeEntry.get();
3592
3593 switch (Entry.Kind) {
3594 case llvm::BitstreamEntry::Error:
3595 return llvm::createStringError(
3596 std::errc::illegal_byte_sequence,
3597 "error at end of module block in AST file");
3598 case llvm::BitstreamEntry::EndBlock:
3599 // Outside of C++, we do not store a lookup map for the translation unit.
3600 // Instead, mark it as needing a lookup map to be built if this module
3601 // contains any declarations lexically within it (which it always does!).
3602 // This usually has no cost, since we very rarely need the lookup map for
3603 // the translation unit outside C++.
3604 if (ASTContext *Ctx = ContextObj) {
3605 DeclContext *DC = Ctx->getTranslationUnitDecl();
3606 if (DC->hasExternalLexicalStorage() && !Ctx->getLangOpts().CPlusPlus)
3607 DC->setMustBuildLookupTable();
3608 }
3609
3610 return llvm::Error::success();
3611 case llvm::BitstreamEntry::SubBlock:
3612 switch (Entry.ID) {
3613 case DECLTYPES_BLOCK_ID:
3614 // We lazily load the decls block, but we want to set up the
3615 // DeclsCursor cursor to point into it. Clone our current bitcode
3616 // cursor to it, enter the block and read the abbrevs in that block.
3617 // With the main cursor, we just skip over it.
3618 F.DeclsCursor = Stream;
3619 if (llvm::Error Err = Stream.SkipBlock())
3620 return Err;
3621 if (llvm::Error Err = ReadBlockAbbrevs(
3622 F.DeclsCursor, DECLTYPES_BLOCK_ID, &F.DeclsBlockStartOffset))
3623 return Err;
3624 break;
3625
3626 case PREPROCESSOR_BLOCK_ID:
3627 F.MacroCursor = Stream;
3628 if (!PP.getExternalSource())
3629 PP.setExternalSource(this);
3630
3631 if (llvm::Error Err = Stream.SkipBlock())
3632 return Err;
3633 if (llvm::Error Err =
3634 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID))
3635 return Err;
3636 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
3637 break;
3638
3639 case PREPROCESSOR_DETAIL_BLOCK_ID:
3640 F.PreprocessorDetailCursor = Stream;
3641
3642 if (llvm::Error Err = Stream.SkipBlock()) {
3643 return Err;
3644 }
3645 if (llvm::Error Err = ReadBlockAbbrevs(F.PreprocessorDetailCursor,
3646 PREPROCESSOR_DETAIL_BLOCK_ID))
3647 return Err;
3648 F.PreprocessorDetailStartOffset
3649 = F.PreprocessorDetailCursor.GetCurrentBitNo();
3650
3651 if (!PP.getPreprocessingRecord())
3652 PP.createPreprocessingRecord();
3653 if (!PP.getPreprocessingRecord()->getExternalSource())
3654 PP.getPreprocessingRecord()->SetExternalSource(*this);
3655 break;
3656
3657 case SOURCE_MANAGER_BLOCK_ID:
3658 if (llvm::Error Err = ReadSourceManagerBlock(F))
3659 return Err;
3660 break;
3661
3662 case SUBMODULE_BLOCK_ID:
3663 if (llvm::Error Err = ReadSubmoduleBlock(F, ClientLoadCapabilities))
3664 return Err;
3665 break;
3666
3667 case COMMENTS_BLOCK_ID: {
3668 BitstreamCursor C = Stream;
3669
3670 if (llvm::Error Err = Stream.SkipBlock())
3671 return Err;
3672 if (llvm::Error Err = ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID))
3673 return Err;
3674 CommentsCursors.push_back(std::make_pair(C, &F));
3675 break;
3676 }
3677
3678 default:
3679 if (llvm::Error Err = Stream.SkipBlock())
3680 return Err;
3681 break;
3682 }
3683 continue;
3684
3685 case llvm::BitstreamEntry::Record:
3686 // The interesting case.
3687 break;
3688 }
3689
3690 // Read and process a record.
3691 Record.clear();
3692 StringRef Blob;
3693 Expected<unsigned> MaybeRecordType =
3694 Stream.readRecord(Entry.ID, Record, &Blob);
3695 if (!MaybeRecordType)
3696 return MaybeRecordType.takeError();
3697 ASTRecordTypes RecordType = (ASTRecordTypes)MaybeRecordType.get();
3698
3699 // If we're not loading an AST context, we don't care about most records.
3700 if (!ContextObj) {
3701 switch (RecordType) {
3702 case IDENTIFIER_TABLE:
3703 case IDENTIFIER_OFFSET:
3704 case INTERESTING_IDENTIFIERS:
3705 case STATISTICS:
3706 case PP_ASSUME_NONNULL_LOC:
3707 case PP_CONDITIONAL_STACK:
3708 case PP_COUNTER_VALUE:
3709 case SOURCE_LOCATION_OFFSETS:
3710 case MODULE_OFFSET_MAP:
3711 case SOURCE_MANAGER_LINE_TABLE:
3712 case PPD_ENTITIES_OFFSETS:
3713 case HEADER_SEARCH_TABLE:
3714 case IMPORTED_MODULES:
3715 case MACRO_OFFSET:
3716 break;
3717 default:
3718 continue;
3719 }
3720 }
3721
3722 switch (RecordType) {
3723 default: // Default behavior: ignore.
3724 break;
3725
3726 case TYPE_OFFSET: {
3727 if (F.LocalNumTypes != 0)
3728 return llvm::createStringError(
3729 std::errc::illegal_byte_sequence,
3730 "duplicate TYPE_OFFSET record in AST file");
3731 F.TypeOffsets = reinterpret_cast<const UnalignedUInt64 *>(Blob.data());
3732 F.LocalNumTypes = Record[0];
3733 F.BaseTypeIndex = getTotalNumTypes();
3734
3735 if (F.LocalNumTypes > 0)
3736 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
3737
3738 break;
3739 }
3740
3741 case DECL_OFFSET: {
3742 if (F.LocalNumDecls != 0)
3743 return llvm::createStringError(
3744 std::errc::illegal_byte_sequence,
3745 "duplicate DECL_OFFSET record in AST file");
3746 F.DeclOffsets = (const DeclOffset *)Blob.data();
3747 F.LocalNumDecls = Record[0];
3748 F.BaseDeclIndex = getTotalNumDecls();
3749
3750 if (F.LocalNumDecls > 0)
3751 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
3752
3753 break;
3754 }
3755
3756 case TU_UPDATE_LEXICAL: {
3757 DeclContext *TU = ContextObj->getTranslationUnitDecl();
3758 LexicalContents Contents(
3759 reinterpret_cast<const unaligned_decl_id_t *>(Blob.data()),
3760 static_cast<unsigned int>(Blob.size() / sizeof(DeclID)));
3761 TULexicalDecls.push_back(std::make_pair(&F, Contents));
3762 TU->setHasExternalLexicalStorage(true);
3763 break;
3764 }
3765
3766 case UPDATE_VISIBLE: {
3767 unsigned Idx = 0;
3768 GlobalDeclID ID = ReadDeclID(F, Record, Idx);
3769 auto *Data = (const unsigned char*)Blob.data();
3770 PendingVisibleUpdates[ID].push_back(UpdateData{&F, Data});
3771 // If we've already loaded the decl, perform the updates when we finish
3772 // loading this block.
3773 if (Decl *D = GetExistingDecl(ID))
3774 PendingUpdateRecords.push_back(
3775 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3776 break;
3777 }
3778
3779 case UPDATE_MODULE_LOCAL_VISIBLE: {
3780 unsigned Idx = 0;
3781 GlobalDeclID ID = ReadDeclID(F, Record, Idx);
3782 auto *Data = (const unsigned char *)Blob.data();
3783 PendingModuleLocalVisibleUpdates[ID].push_back(UpdateData{&F, Data});
3784 // If we've already loaded the decl, perform the updates when we finish
3785 // loading this block.
3786 if (Decl *D = GetExistingDecl(ID))
3787 PendingUpdateRecords.push_back(
3788 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3789 break;
3790 }
3791
3792 case UPDATE_TU_LOCAL_VISIBLE: {
3793 if (F.Kind != MK_MainFile)
3794 break;
3795 unsigned Idx = 0;
3796 GlobalDeclID ID = ReadDeclID(F, Record, Idx);
3797 auto *Data = (const unsigned char *)Blob.data();
3798 TULocalUpdates[ID].push_back(UpdateData{&F, Data});
3799 // If we've already loaded the decl, perform the updates when we finish
3800 // loading this block.
3801 if (Decl *D = GetExistingDecl(ID))
3802 PendingUpdateRecords.push_back(
3803 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3804 break;
3805 }
3806
3807 case CXX_ADDED_TEMPLATE_SPECIALIZATION: {
3808 unsigned Idx = 0;
3809 GlobalDeclID ID = ReadDeclID(F, Record, Idx);
3810 auto *Data = (const unsigned char *)Blob.data();
3811 PendingSpecializationsUpdates[ID].push_back(UpdateData{&F, Data});
3812 // If we've already loaded the decl, perform the updates when we finish
3813 // loading this block.
3814 if (Decl *D = GetExistingDecl(ID))
3815 PendingUpdateRecords.push_back(
3816 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3817 break;
3818 }
3819
3820 case CXX_ADDED_TEMPLATE_PARTIAL_SPECIALIZATION: {
3821 unsigned Idx = 0;
3822 GlobalDeclID ID = ReadDeclID(F, Record, Idx);
3823 auto *Data = (const unsigned char *)Blob.data();
3824 PendingPartialSpecializationsUpdates[ID].push_back(UpdateData{&F, Data});
3825 // If we've already loaded the decl, perform the updates when we finish
3826 // loading this block.
3827 if (Decl *D = GetExistingDecl(ID))
3828 PendingUpdateRecords.push_back(
3829 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3830 break;
3831 }
3832
3833 case IDENTIFIER_TABLE:
3834 F.IdentifierTableData =
3835 reinterpret_cast<const unsigned char *>(Blob.data());
3836 if (Record[0]) {
3837 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
3838 F.IdentifierTableData + Record[0],
3839 F.IdentifierTableData + sizeof(uint32_t),
3840 F.IdentifierTableData,
3841 ASTIdentifierLookupTrait(*this, F));
3842
3843 PP.getIdentifierTable().setExternalIdentifierLookup(this);
3844 }
3845 break;
3846
3847 case IDENTIFIER_OFFSET: {
3848 if (F.LocalNumIdentifiers != 0)
3849 return llvm::createStringError(
3850 std::errc::illegal_byte_sequence,
3851 "duplicate IDENTIFIER_OFFSET record in AST file");
3852 F.IdentifierOffsets = (const uint32_t *)Blob.data();
3853 F.LocalNumIdentifiers = Record[0];
3854 F.BaseIdentifierID = getTotalNumIdentifiers();
3855
3856 if (F.LocalNumIdentifiers > 0)
3857 IdentifiersLoaded.resize(IdentifiersLoaded.size()
3858 + F.LocalNumIdentifiers);
3859 break;
3860 }
3861
3862 case INTERESTING_IDENTIFIERS:
3863 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
3864 break;
3865
3866 case EAGERLY_DESERIALIZED_DECLS:
3867 // FIXME: Skip reading this record if our ASTConsumer doesn't care
3868 // about "interesting" decls (for instance, if we're building a module).
3869 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
3870 EagerlyDeserializedDecls.push_back(ReadDeclID(F, Record, I));
3871 break;
3872
3873 case MODULAR_CODEGEN_DECLS:
3874 // FIXME: Skip reading this record if our ASTConsumer doesn't care about
3875 // them (ie: if we're not codegenerating this module).
3876 if (F.Kind == MK_MainFile ||
3877 getContext().getLangOpts().BuildingPCHWithObjectFile)
3878 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
3879 EagerlyDeserializedDecls.push_back(ReadDeclID(F, Record, I));
3880 break;
3881
3882 case SPECIAL_TYPES:
3883 if (SpecialTypes.empty()) {
3884 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3885 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
3886 break;
3887 }
3888
3889 if (Record.empty())
3890 break;
3891
3892 if (SpecialTypes.size() != Record.size())
3893 return llvm::createStringError(std::errc::illegal_byte_sequence,
3894 "invalid special-types record");
3895
3896 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
3897 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
3898 if (!SpecialTypes[I])
3899 SpecialTypes[I] = ID;
3900 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
3901 // merge step?
3902 }
3903 break;
3904
3905 case STATISTICS:
3906 TotalNumStatements += Record[0];
3907 TotalNumMacros += Record[1];
3908 TotalLexicalDeclContexts += Record[2];
3909 TotalVisibleDeclContexts += Record[3];
3910 TotalModuleLocalVisibleDeclContexts += Record[4];
3911 TotalTULocalVisibleDeclContexts += Record[5];
3912 break;
3913
3914 case UNUSED_FILESCOPED_DECLS:
3915 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
3916 UnusedFileScopedDecls.push_back(ReadDeclID(F, Record, I));
3917 break;
3918
3919 case DELEGATING_CTORS:
3920 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
3921 DelegatingCtorDecls.push_back(ReadDeclID(F, Record, I));
3922 break;
3923
3924 case WEAK_UNDECLARED_IDENTIFIERS:
3925 if (Record.size() % 3 != 0)
3926 return llvm::createStringError(std::errc::illegal_byte_sequence,
3927 "invalid weak identifiers record");
3928
3929 // FIXME: Ignore weak undeclared identifiers from non-original PCH
3930 // files. This isn't the way to do it :)
3931 WeakUndeclaredIdentifiers.clear();
3932
3933 // Translate the weak, undeclared identifiers into global IDs.
3934 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
3935 WeakUndeclaredIdentifiers.push_back(
3936 getGlobalIdentifierID(F, Record[I++]));
3937 WeakUndeclaredIdentifiers.push_back(
3938 getGlobalIdentifierID(F, Record[I++]));
3939 WeakUndeclaredIdentifiers.push_back(
3940 ReadSourceLocation(F, Record, I).getRawEncoding());
3941 }
3942 break;
3943
3944 case SELECTOR_OFFSETS: {
3945 F.SelectorOffsets = (const uint32_t *)Blob.data();
3946 F.LocalNumSelectors = Record[0];
3947 unsigned LocalBaseSelectorID = Record[1];
3948 F.BaseSelectorID = getTotalNumSelectors();
3949
3950 if (F.LocalNumSelectors > 0) {
3951 // Introduce the global -> local mapping for selectors within this
3952 // module.
3953 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
3954
3955 // Introduce the local -> global mapping for selectors within this
3956 // module.
3957 F.SelectorRemap.insertOrReplace(
3958 std::make_pair(LocalBaseSelectorID,
3959 F.BaseSelectorID - LocalBaseSelectorID));
3960
3961 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
3962 }
3963 break;
3964 }
3965
3966 case METHOD_POOL:
3967 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
3968 if (Record[0])
3969 F.SelectorLookupTable
3970 = ASTSelectorLookupTable::Create(
3971 F.SelectorLookupTableData + Record[0],
3972 F.SelectorLookupTableData,
3973 ASTSelectorLookupTrait(*this, F));
3974 TotalNumMethodPoolEntries += Record[1];
3975 break;
3976
3977 case REFERENCED_SELECTOR_POOL:
3978 if (!Record.empty()) {
3979 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
3980 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
3981 Record[Idx++]));
3982 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
3983 getRawEncoding());
3984 }
3985 }
3986 break;
3987
3988 case PP_ASSUME_NONNULL_LOC: {
3989 unsigned Idx = 0;
3990 if (!Record.empty())
3991 PP.setPreambleRecordedPragmaAssumeNonNullLoc(
3992 ReadSourceLocation(F, Record, Idx));
3993 break;
3994 }
3995
3996 case PP_UNSAFE_BUFFER_USAGE: {
3997 if (!Record.empty()) {
3998 SmallVector<SourceLocation, 64> SrcLocs;
3999 unsigned Idx = 0;
4000 while (Idx < Record.size())
4001 SrcLocs.push_back(ReadSourceLocation(F, Record, Idx));
4002 PP.setDeserializedSafeBufferOptOutMap(SrcLocs);
4003 }
4004 break;
4005 }
4006
4007 case PP_CONDITIONAL_STACK:
4008 if (!Record.empty()) {
4009 unsigned Idx = 0, End = Record.size() - 1;
4010 bool ReachedEOFWhileSkipping = Record[Idx++];
4011 std::optional<Preprocessor::PreambleSkipInfo> SkipInfo;
4012 if (ReachedEOFWhileSkipping) {
4013 SourceLocation HashToken = ReadSourceLocation(F, Record, Idx);
4014 SourceLocation IfTokenLoc = ReadSourceLocation(F, Record, Idx);
4015 bool FoundNonSkipPortion = Record[Idx++];
4016 bool FoundElse = Record[Idx++];
4017 SourceLocation ElseLoc = ReadSourceLocation(F, Record, Idx);
4018 SkipInfo.emplace(HashToken, IfTokenLoc, FoundNonSkipPortion,
4019 FoundElse, ElseLoc);
4020 }
4021 SmallVector<PPConditionalInfo, 4> ConditionalStack;
4022 while (Idx < End) {
4023 auto Loc = ReadSourceLocation(F, Record, Idx);
4024 bool WasSkipping = Record[Idx++];
4025 bool FoundNonSkip = Record[Idx++];
4026 bool FoundElse = Record[Idx++];
4027 ConditionalStack.push_back(
4028 {Loc, WasSkipping, FoundNonSkip, FoundElse});
4029 }
4030 PP.setReplayablePreambleConditionalStack(ConditionalStack, SkipInfo);
4031 }
4032 break;
4033
4034 case PP_COUNTER_VALUE:
4035 if (!Record.empty() && Listener)
4036 Listener->ReadCounter(F, Record[0]);
4037 break;
4038
4039 case FILE_SORTED_DECLS:
4040 F.FileSortedDecls = (const unaligned_decl_id_t *)Blob.data();
4041 F.NumFileSortedDecls = Record[0];
4042 break;
4043
4044 case SOURCE_LOCATION_OFFSETS: {
4045 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
4046 F.LocalNumSLocEntries = Record[0];
4047 SourceLocation::UIntTy SLocSpaceSize = Record[1];
4048 F.SLocEntryOffsetsBase = Record[2] + F.SourceManagerBlockStartOffset;
4049 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
4050 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
4051 SLocSpaceSize);
4052 if (!F.SLocEntryBaseID) {
4053 Diags.Report(SourceLocation(), diag::remark_sloc_usage);
4054 SourceMgr.noteSLocAddressSpaceUsage(Diags);
4055 return llvm::createStringError(std::errc::invalid_argument,
4056 "ran out of source locations");
4057 }
4058 // Make our entry in the range map. BaseID is negative and growing, so
4059 // we invert it. Because we invert it, though, we need the other end of
4060 // the range.
4061 unsigned RangeStart =
4062 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
4063 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
4064 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
4065
4066 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
4067 assert((F.SLocEntryBaseOffset & SourceLocation::MacroIDBit) == 0);
4068 GlobalSLocOffsetMap.insert(
4069 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
4070 - SLocSpaceSize,&F));
4071
4072 TotalNumSLocEntries += F.LocalNumSLocEntries;
4073 break;
4074 }
4075
4076 case MODULE_OFFSET_MAP:
4077 F.ModuleOffsetMap = Blob;
4078 break;
4079
4080 case SOURCE_MANAGER_LINE_TABLE:
4081 ParseLineTable(F, Record);
4082 break;
4083
4084 case EXT_VECTOR_DECLS:
4085 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4086 ExtVectorDecls.push_back(ReadDeclID(F, Record, I));
4087 break;
4088
4089 case VTABLE_USES:
4090 if (Record.size() % 3 != 0)
4091 return llvm::createStringError(std::errc::illegal_byte_sequence,
4092 "Invalid VTABLE_USES record");
4093
4094 // Later tables overwrite earlier ones.
4095 // FIXME: Modules will have some trouble with this. This is clearly not
4096 // the right way to do this.
4097 VTableUses.clear();
4098
4099 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
4100 VTableUses.push_back(
4101 {ReadDeclID(F, Record, Idx),
4102 ReadSourceLocation(F, Record, Idx).getRawEncoding(),
4103 (bool)Record[Idx++]});
4104 }
4105 break;
4106
4107 case PENDING_IMPLICIT_INSTANTIATIONS:
4108
4109 if (Record.size() % 2 != 0)
4110 return llvm::createStringError(
4111 std::errc::illegal_byte_sequence,
4112 "Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
4113
4114 // For standard C++20 module, we will only reads the instantiations
4115 // if it is the main file.
4116 if (!F.StandardCXXModule || F.Kind == MK_MainFile) {
4117 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
4118 PendingInstantiations.push_back(
4119 {ReadDeclID(F, Record, I),
4120 ReadSourceLocation(F, Record, I).getRawEncoding()});
4121 }
4122 }
4123 break;
4124
4125 case SEMA_DECL_REFS:
4126 if (Record.size() != 3)
4127 return llvm::createStringError(std::errc::illegal_byte_sequence,
4128 "Invalid SEMA_DECL_REFS block");
4129 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4130 SemaDeclRefs.push_back(ReadDeclID(F, Record, I));
4131 break;
4132
4133 case PPD_ENTITIES_OFFSETS: {
4134 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
4135 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
4136 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
4137
4138 unsigned StartingID;
4139 if (!PP.getPreprocessingRecord())
4140 PP.createPreprocessingRecord();
4141 if (!PP.getPreprocessingRecord()->getExternalSource())
4142 PP.getPreprocessingRecord()->SetExternalSource(*this);
4143 StartingID
4144 = PP.getPreprocessingRecord()
4145 ->allocateLoadedEntities(F.NumPreprocessedEntities);
4146 F.BasePreprocessedEntityID = StartingID;
4147
4148 if (F.NumPreprocessedEntities > 0) {
4149 // Introduce the global -> local mapping for preprocessed entities in
4150 // this module.
4151 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
4152 }
4153
4154 break;
4155 }
4156
4157 case PPD_SKIPPED_RANGES: {
4158 F.PreprocessedSkippedRangeOffsets = (const PPSkippedRange*)Blob.data();
4159 assert(Blob.size() % sizeof(PPSkippedRange) == 0);
4160 F.NumPreprocessedSkippedRanges = Blob.size() / sizeof(PPSkippedRange);
4161
4162 if (!PP.getPreprocessingRecord())
4163 PP.createPreprocessingRecord();
4164 if (!PP.getPreprocessingRecord()->getExternalSource())
4165 PP.getPreprocessingRecord()->SetExternalSource(*this);
4166 F.BasePreprocessedSkippedRangeID = PP.getPreprocessingRecord()
4167 ->allocateSkippedRanges(F.NumPreprocessedSkippedRanges);
4168
4169 if (F.NumPreprocessedSkippedRanges > 0)
4170 GlobalSkippedRangeMap.insert(
4171 std::make_pair(F.BasePreprocessedSkippedRangeID, &F));
4172 break;
4173 }
4174
4175 case DECL_UPDATE_OFFSETS:
4176 if (Record.size() % 2 != 0)
4177 return llvm::createStringError(
4178 std::errc::illegal_byte_sequence,
4179 "invalid DECL_UPDATE_OFFSETS block in AST file");
4180 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/) {
4181 GlobalDeclID ID = ReadDeclID(F, Record, I);
4182 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I++]));
4183
4184 // If we've already loaded the decl, perform the updates when we finish
4185 // loading this block.
4186 if (Decl *D = GetExistingDecl(ID))
4187 PendingUpdateRecords.push_back(
4188 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
4189 }
4190 break;
4191
4192 case DELAYED_NAMESPACE_LEXICAL_VISIBLE_RECORD: {
4193 if (Record.size() % 5 != 0)
4194 return llvm::createStringError(
4195 std::errc::illegal_byte_sequence,
4196 "invalid DELAYED_NAMESPACE_LEXICAL_VISIBLE_RECORD block in AST "
4197 "file");
4198 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/) {
4199 GlobalDeclID ID = ReadDeclID(F, Record, I);
4200
4201 uint64_t BaseOffset = F.DeclsBlockStartOffset;
4202 assert(BaseOffset && "Invalid DeclsBlockStartOffset for module file!");
4203 uint64_t LocalLexicalOffset = Record[I++];
4204 uint64_t LexicalOffset =
4205 LocalLexicalOffset ? BaseOffset + LocalLexicalOffset : 0;
4206 uint64_t LocalVisibleOffset = Record[I++];
4207 uint64_t VisibleOffset =
4208 LocalVisibleOffset ? BaseOffset + LocalVisibleOffset : 0;
4209 uint64_t LocalModuleLocalOffset = Record[I++];
4210 uint64_t ModuleLocalOffset =
4211 LocalModuleLocalOffset ? BaseOffset + LocalModuleLocalOffset : 0;
4212 uint64_t TULocalLocalOffset = Record[I++];
4213 uint64_t TULocalOffset =
4214 TULocalLocalOffset ? BaseOffset + TULocalLocalOffset : 0;
4215
4216 DelayedNamespaceOffsetMap[ID] = {
4217 {VisibleOffset, ModuleLocalOffset, TULocalOffset}, LexicalOffset};
4218
4219 assert(!GetExistingDecl(ID) &&
4220 "We shouldn't load the namespace in the front of delayed "
4221 "namespace lexical and visible block");
4222 }
4223 break;
4224 }
4225
4226 case RELATED_DECLS_MAP:
4227 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/) {
4228 GlobalDeclID ID = ReadDeclID(F, Record, I);
4229 auto &RelatedDecls = RelatedDeclsMap[ID];
4230 unsigned NN = Record[I++];
4231 RelatedDecls.reserve(NN);
4232 for (unsigned II = 0; II < NN; II++)
4233 RelatedDecls.push_back(ReadDeclID(F, Record, I));
4234 }
4235 break;
4236
4237 case OBJC_CATEGORIES_MAP:
4238 if (F.LocalNumObjCCategoriesInMap != 0)
4239 return llvm::createStringError(
4240 std::errc::illegal_byte_sequence,
4241 "duplicate OBJC_CATEGORIES_MAP record in AST file");
4242
4243 F.LocalNumObjCCategoriesInMap = Record[0];
4244 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
4245 break;
4246
4247 case OBJC_CATEGORIES:
4248 F.ObjCCategories.swap(Record);
4249 break;
4250
4251 case CUDA_SPECIAL_DECL_REFS:
4252 // Later tables overwrite earlier ones.
4253 // FIXME: Modules will have trouble with this.
4254 CUDASpecialDeclRefs.clear();
4255 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4256 CUDASpecialDeclRefs.push_back(ReadDeclID(F, Record, I));
4257 break;
4258
4259 case HEADER_SEARCH_TABLE:
4260 F.HeaderFileInfoTableData = Blob.data();
4261 F.LocalNumHeaderFileInfos = Record[1];
4262 if (Record[0]) {
4263 F.HeaderFileInfoTable = HeaderFileInfoLookupTable::Create(
4264 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
4265 (const unsigned char *)F.HeaderFileInfoTableData,
4266 HeaderFileInfoTrait(*this, F));
4267
4268 PP.getHeaderSearchInfo().SetExternalSource(this);
4269 if (!PP.getHeaderSearchInfo().getExternalLookup())
4270 PP.getHeaderSearchInfo().SetExternalLookup(this);
4271 }
4272 break;
4273
4274 case FP_PRAGMA_OPTIONS:
4275 // Later tables overwrite earlier ones.
4276 FPPragmaOptions.swap(Record);
4277 break;
4278
4279 case DECLS_WITH_EFFECTS_TO_VERIFY:
4280 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4281 DeclsWithEffectsToVerify.push_back(ReadDeclID(F, Record, I));
4282 break;
4283
4284 case OPENCL_EXTENSIONS:
4285 for (unsigned I = 0, E = Record.size(); I != E; ) {
4286 auto Name = ReadString(Record, I);
4287 auto &OptInfo = OpenCLExtensions.OptMap[Name];
4288 OptInfo.Supported = Record[I++] != 0;
4289 OptInfo.Enabled = Record[I++] != 0;
4290 OptInfo.WithPragma = Record[I++] != 0;
4291 OptInfo.Avail = Record[I++];
4292 OptInfo.Core = Record[I++];
4293 OptInfo.Opt = Record[I++];
4294 }
4295 break;
4296
4297 case TENTATIVE_DEFINITIONS:
4298 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4299 TentativeDefinitions.push_back(ReadDeclID(F, Record, I));
4300 break;
4301
4302 case KNOWN_NAMESPACES:
4303 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4304 KnownNamespaces.push_back(ReadDeclID(F, Record, I));
4305 break;
4306
4307 case UNDEFINED_BUT_USED:
4308 if (Record.size() % 2 != 0)
4309 return llvm::createStringError(std::errc::illegal_byte_sequence,
4310 "invalid undefined-but-used record");
4311 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
4312 UndefinedButUsed.push_back(
4313 {ReadDeclID(F, Record, I),
4314 ReadSourceLocation(F, Record, I).getRawEncoding()});
4315 }
4316 break;
4317
4318 case DELETE_EXPRS_TO_ANALYZE:
4319 for (unsigned I = 0, N = Record.size(); I != N;) {
4320 DelayedDeleteExprs.push_back(ReadDeclID(F, Record, I).getRawValue());
4321 const uint64_t Count = Record[I++];
4322 DelayedDeleteExprs.push_back(Count);
4323 for (uint64_t C = 0; C < Count; ++C) {
4324 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
4325 bool IsArrayForm = Record[I++] == 1;
4326 DelayedDeleteExprs.push_back(IsArrayForm);
4327 }
4328 }
4329 break;
4330
4331 case VTABLES_TO_EMIT:
4332 if (F.Kind == MK_MainFile ||
4333 getContext().getLangOpts().BuildingPCHWithObjectFile)
4334 for (unsigned I = 0, N = Record.size(); I != N;)
4335 VTablesToEmit.push_back(ReadDeclID(F, Record, I));
4336 break;
4337
4338 case IMPORTED_MODULES:
4339 if (!F.isModule()) {
4340 // If we aren't loading a module (which has its own exports), make
4341 // all of the imported modules visible.
4342 // FIXME: Deal with macros-only imports.
4343 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
4344 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
4345 SourceLocation Loc = ReadSourceLocation(F, Record, I);
4346 if (GlobalID) {
4347 PendingImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
4348 if (DeserializationListener)
4349 DeserializationListener->ModuleImportRead(GlobalID, Loc);
4350 }
4351 }
4352 }
4353 break;
4354
4355 case MACRO_OFFSET: {
4356 if (F.LocalNumMacros != 0)
4357 return llvm::createStringError(
4358 std::errc::illegal_byte_sequence,
4359 "duplicate MACRO_OFFSET record in AST file");
4360 F.MacroOffsets = (const uint32_t *)Blob.data();
4361 F.LocalNumMacros = Record[0];
4362 F.MacroOffsetsBase = Record[1] + F.ASTBlockStartOffset;
4363 F.BaseMacroID = getTotalNumMacros();
4364
4365 if (F.LocalNumMacros > 0)
4366 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
4367 break;
4368 }
4369
4370 case LATE_PARSED_TEMPLATE:
4371 LateParsedTemplates.emplace_back(
4372 std::piecewise_construct, std::forward_as_tuple(&F),
4373 std::forward_as_tuple(Record.begin(), Record.end()));
4374 break;
4375
4376 case OPTIMIZE_PRAGMA_OPTIONS:
4377 if (Record.size() != 1)
4378 return llvm::createStringError(std::errc::illegal_byte_sequence,
4379 "invalid pragma optimize record");
4380 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
4381 break;
4382
4383 case MSSTRUCT_PRAGMA_OPTIONS:
4384 if (Record.size() != 1)
4385 return llvm::createStringError(std::errc::illegal_byte_sequence,
4386 "invalid pragma ms_struct record");
4387 PragmaMSStructState = Record[0];
4388 break;
4389
4390 case POINTERS_TO_MEMBERS_PRAGMA_OPTIONS:
4391 if (Record.size() != 2)
4392 return llvm::createStringError(
4393 std::errc::illegal_byte_sequence,
4394 "invalid pragma pointers to members record");
4395 PragmaMSPointersToMembersState = Record[0];
4396 PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]);
4397 break;
4398
4399 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
4400 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4401 UnusedLocalTypedefNameCandidates.push_back(ReadDeclID(F, Record, I));
4402 break;
4403
4404 case CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH:
4405 if (Record.size() != 1)
4406 return llvm::createStringError(std::errc::illegal_byte_sequence,
4407 "invalid cuda pragma options record");
4408 ForceHostDeviceDepth = Record[0];
4409 break;
4410
4411 case ALIGN_PACK_PRAGMA_OPTIONS: {
4412 if (Record.size() < 3)
4413 return llvm::createStringError(std::errc::illegal_byte_sequence,
4414 "invalid pragma pack record");
4415 PragmaAlignPackCurrentValue = ReadAlignPackInfo(Record[0]);
4416 PragmaAlignPackCurrentLocation = ReadSourceLocation(F, Record[1]);
4417 unsigned NumStackEntries = Record[2];
4418 unsigned Idx = 3;
4419 // Reset the stack when importing a new module.
4420 PragmaAlignPackStack.clear();
4421 for (unsigned I = 0; I < NumStackEntries; ++I) {
4422 PragmaAlignPackStackEntry Entry;
4423 Entry.Value = ReadAlignPackInfo(Record[Idx++]);
4424 Entry.Location = ReadSourceLocation(F, Record[Idx++]);
4425 Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]);
4426 PragmaAlignPackStrings.push_back(ReadString(Record, Idx));
4427 Entry.SlotLabel = PragmaAlignPackStrings.back();
4428 PragmaAlignPackStack.push_back(Entry);
4429 }
4430 break;
4431 }
4432
4433 case FLOAT_CONTROL_PRAGMA_OPTIONS: {
4434 if (Record.size() < 3)
4435 return llvm::createStringError(std::errc::illegal_byte_sequence,
4436 "invalid pragma float control record");
4437 FpPragmaCurrentValue = FPOptionsOverride::getFromOpaqueInt(Record[0]);
4438 FpPragmaCurrentLocation = ReadSourceLocation(F, Record[1]);
4439 unsigned NumStackEntries = Record[2];
4440 unsigned Idx = 3;
4441 // Reset the stack when importing a new module.
4442 FpPragmaStack.clear();
4443 for (unsigned I = 0; I < NumStackEntries; ++I) {
4444 FpPragmaStackEntry Entry;
4445 Entry.Value = FPOptionsOverride::getFromOpaqueInt(Record[Idx++]);
4446 Entry.Location = ReadSourceLocation(F, Record[Idx++]);
4447 Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]);
4448 FpPragmaStrings.push_back(ReadString(Record, Idx));
4449 Entry.SlotLabel = FpPragmaStrings.back();
4450 FpPragmaStack.push_back(Entry);
4451 }
4452 break;
4453 }
4454
4455 case DECLS_TO_CHECK_FOR_DEFERRED_DIAGS:
4456 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4457 DeclsToCheckForDeferredDiags.insert(ReadDeclID(F, Record, I));
4458 break;
4459
4460 case RISCV_VECTOR_INTRINSICS_PRAGMA: {
4461 unsigned NumRecords = Record.front();
4462 // Last record which is used to keep number of valid records.
4463 if (Record.size() - 1 != NumRecords)
4464 return llvm::createStringError(std::errc::illegal_byte_sequence,
4465 "invalid rvv intrinsic pragma record");
4466
4467 if (RISCVVecIntrinsicPragma.empty())
4468 RISCVVecIntrinsicPragma.append(NumRecords, 0);
4469 // There might be multiple precompiled modules imported, we need to union
4470 // them all.
4471 for (unsigned i = 0; i < NumRecords; ++i)
4472 RISCVVecIntrinsicPragma[i] |= Record[i + 1];
4473 break;
4474 }
4475 }
4476 }
4477 }
4478
4479 void ASTReader::ReadModuleOffsetMap(ModuleFile &F) const {
4480 assert(!F.ModuleOffsetMap.empty() && "no module offset map to read");
4481
4482 // Additional remapping information.
4483 const unsigned char *Data = (const unsigned char*)F.ModuleOffsetMap.data();
4484 const unsigned char *DataEnd = Data + F.ModuleOffsetMap.size();
4485 F.ModuleOffsetMap = StringRef();
4486
4487 using RemapBuilder = ContinuousRangeMap<uint32_t, int, 2>::Builder;
4488 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
4489 RemapBuilder SelectorRemap(F.SelectorRemap);
4490
4491 auto &ImportedModuleVector = F.TransitiveImports;
4492 assert(ImportedModuleVector.empty());
4493
4494 while (Data < DataEnd) {
4495 // FIXME: Looking up dependency modules by filename is horrible. Let's
4496 // start fixing this with prebuilt, explicit and implicit modules and see
4497 // how it goes...
4498 using namespace llvm::support;
4499 ModuleKind Kind = static_cast<ModuleKind>(
4500 endian::readNext<uint8_t, llvm::endianness::little>(Data));
4501 uint16_t Len = endian::readNext<uint16_t, llvm::endianness::little>(Data);
4502 StringRef Name = StringRef((const char*)Data, Len);
4503 Data += Len;
4504 ModuleFile *OM = (Kind == MK_PrebuiltModule || Kind == MK_ExplicitModule ||
4505 Kind == MK_ImplicitModule
4506 ? ModuleMgr.lookupByModuleName(Name)
4507 : ModuleMgr.lookupByFileName(Name));
4508 if (!OM) {
4509 std::string Msg = "refers to unknown module, cannot find ";
4510 Msg.append(std::string(Name));
4511 Error(Msg);
4512 return;
4513 }
4514
4515 ImportedModuleVector.push_back(OM);
4516
4517 uint32_t SubmoduleIDOffset =
4518 endian::readNext<uint32_t, llvm::endianness::little>(Data);
4519 uint32_t SelectorIDOffset =
4520 endian::readNext<uint32_t, llvm::endianness::little>(Data);
4521
4522 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
4523 RemapBuilder &Remap) {
4524 constexpr uint32_t None = std::numeric_limits<uint32_t>::max();
4525 if (Offset != None)
4526 Remap.insert(std::make_pair(Offset,
4527 static_cast<int>(BaseOffset - Offset)));
4528 };
4529
4530 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
4531 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
4532 }
4533 }
4534
4535 ASTReader::ASTReadResult
4536 ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
4537 const ModuleFile *ImportedBy,
4538 unsigned ClientLoadCapabilities) {
4539 unsigned Idx = 0;
4540 F.ModuleMapPath = ReadPath(F, Record, Idx);
4541
4542 // Try to resolve ModuleName in the current header search context and
4543 // verify that it is found in the same module map file as we saved. If the
4544 // top-level AST file is a main file, skip this check because there is no
4545 // usable header search context.
4546 assert(!F.ModuleName.empty() &&
4547 "MODULE_NAME should come before MODULE_MAP_FILE");
4548 if (PP.getPreprocessorOpts().ModulesCheckRelocated &&
4549 F.Kind == MK_ImplicitModule && ModuleMgr.begin()->Kind != MK_MainFile) {
4550 // An implicitly-loaded module file should have its module listed in some
4551 // module map file that we've already loaded.
4552 Module *M =
4553 PP.getHeaderSearchInfo().lookupModule(F.ModuleName, F.ImportLoc);
4554 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
4555 OptionalFileEntryRef ModMap =
4556 M ? Map.getModuleMapFileForUniquing(M) : std::nullopt;
4557 // Don't emit module relocation error if we have -fno-validate-pch
4558 if (!bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation &
4559 DisableValidationForModuleKind::Module) &&
4560 !ModMap) {
4561 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities)) {
4562 if (auto ASTFE = M ? M->getASTFile() : std::nullopt) {
4563 // This module was defined by an imported (explicit) module.
4564 Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
4565 << ASTFE->getName();
4566 // TODO: Add a note with the module map paths if they differ.
4567 } else {
4568 // This module was built with a different module map.
4569 Diag(diag::err_imported_module_not_found)
4570 << F.ModuleName << F.FileName
4571 << (ImportedBy ? ImportedBy->FileName : "") << F.ModuleMapPath
4572 << !ImportedBy;
4573 // In case it was imported by a PCH, there's a chance the user is
4574 // just missing to include the search path to the directory containing
4575 // the modulemap.
4576 if (ImportedBy && ImportedBy->Kind == MK_PCH)
4577 Diag(diag::note_imported_by_pch_module_not_found)
4578 << llvm::sys::path::parent_path(F.ModuleMapPath);
4579 }
4580 }
4581 return OutOfDate;
4582 }
4583
4584 assert(M && M->Name == F.ModuleName && "found module with different name");
4585
4586 // Check the primary module map file.
4587 auto StoredModMap = FileMgr.getOptionalFileRef(F.ModuleMapPath);
4588 if (!StoredModMap || *StoredModMap != ModMap) {
4589 assert(ModMap && "found module is missing module map file");
4590 assert((ImportedBy || F.Kind == MK_ImplicitModule) &&
4591 "top-level import should be verified");
4592 bool NotImported = F.Kind == MK_ImplicitModule && !ImportedBy;
4593 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4594 Diag(diag::err_imported_module_modmap_changed)
4595 << F.ModuleName << (NotImported ? F.FileName : ImportedBy->FileName)
4596 << ModMap->getName() << F.ModuleMapPath << NotImported;
4597 return OutOfDate;
4598 }
4599
4600 ModuleMap::AdditionalModMapsSet AdditionalStoredMaps;
4601 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
4602 // FIXME: we should use input files rather than storing names.
4603 std::string Filename = ReadPath(F, Record, Idx);
4604 auto SF = FileMgr.getOptionalFileRef(Filename, false, false);
4605 if (!SF) {
4606 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4607 Error("could not find file '" + Filename +"' referenced by AST file");
4608 return OutOfDate;
4609 }
4610 AdditionalStoredMaps.insert(*SF);
4611 }
4612
4613 // Check any additional module map files (e.g. module.private.modulemap)
4614 // that are not in the pcm.
4615 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
4616 for (FileEntryRef ModMap : *AdditionalModuleMaps) {
4617 // Remove files that match
4618 // Note: SmallPtrSet::erase is really remove
4619 if (!AdditionalStoredMaps.erase(ModMap)) {
4620 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4621 Diag(diag::err_module_different_modmap)
4622 << F.ModuleName << /*new*/0 << ModMap.getName();
4623 return OutOfDate;
4624 }
4625 }
4626 }
4627
4628 // Check any additional module map files that are in the pcm, but not
4629 // found in header search. Cases that match are already removed.
4630 for (FileEntryRef ModMap : AdditionalStoredMaps) {
4631 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4632 Diag(diag::err_module_different_modmap)
4633 << F.ModuleName << /*not new*/1 << ModMap.getName();
4634 return OutOfDate;
4635 }
4636 }
4637
4638 if (Listener)
4639 Listener->ReadModuleMapFile(F.ModuleMapPath);
4640 return Success;
4641 }
4642
4643 /// Move the given method to the back of the global list of methods.
4644 static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
4645 // Find the entry for this selector in the method pool.
4646 SemaObjC::GlobalMethodPool::iterator Known =
4647 S.ObjC().MethodPool.find(Method->getSelector());
4648 if (Known == S.ObjC().MethodPool.end())
4649 return;
4650
4651 // Retrieve the appropriate method list.
4652 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
4653 : Known->second.second;
4654 bool Found = false;
4655 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
4656 if (!Found) {
4657 if (List->getMethod() == Method) {
4658 Found = true;
4659 } else {
4660 // Keep searching.
4661 continue;
4662 }
4663 }
4664
4665 if (List->getNext())
4666 List->setMethod(List->getNext()->getMethod());
4667 else
4668 List->setMethod(Method);
4669 }
4670 }
4671
4672 void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
4673 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
4674 for (Decl *D : Names) {
4675 bool wasHidden = !D->isUnconditionallyVisible();
4676 D->setVisibleDespiteOwningModule();
4677
4678 if (wasHidden && SemaObj) {
4679 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
4680 moveMethodToBackOfGlobalList(*SemaObj, Method);
4681 }
4682 }
4683 }
4684 }
4685
4686 void ASTReader::makeModuleVisible(Module *Mod,
4687 Module::NameVisibilityKind NameVisibility,
4688 SourceLocation ImportLoc) {
4689 llvm::SmallPtrSet<Module *, 4> Visited;
4690 SmallVector<Module *, 4> Stack;
4691 Stack.push_back(Mod);
4692 while (!Stack.empty()) {
4693 Mod = Stack.pop_back_val();
4694
4695 if (NameVisibility <= Mod->NameVisibility) {
4696 // This module already has this level of visibility (or greater), so
4697 // there is nothing more to do.
4698 continue;
4699 }
4700
4701 if (Mod->isUnimportable()) {
4702 // Modules that aren't importable cannot be made visible.
4703 continue;
4704 }
4705
4706 // Update the module's name visibility.
4707 Mod->NameVisibility = NameVisibility;
4708
4709 // If we've already deserialized any names from this module,
4710 // mark them as visible.
4711 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
4712 if (Hidden != HiddenNamesMap.end()) {
4713 auto HiddenNames = std::move(*Hidden);
4714 HiddenNamesMap.erase(Hidden);
4715 makeNamesVisible(HiddenNames.second, HiddenNames.first);
4716 assert(!HiddenNamesMap.contains(Mod) &&
4717 "making names visible added hidden names");
4718 }
4719
4720 // Push any exported modules onto the stack to be marked as visible.
4721 SmallVector<Module *, 16> Exports;
4722 Mod->getExportedModules(Exports);
4723 for (SmallVectorImpl<Module *>::iterator
4724 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
4725 Module *Exported = *I;
4726 if (Visited.insert(Exported).second)
4727 Stack.push_back(Exported);
4728 }
4729 }
4730 }
4731
4732 /// We've merged the definition \p MergedDef into the existing definition
4733 /// \p Def. Ensure that \p Def is made visible whenever \p MergedDef is made
4734 /// visible.
4735 void ASTReader::mergeDefinitionVisibility(NamedDecl *Def,
4736 NamedDecl *MergedDef) {
4737 if (!Def->isUnconditionallyVisible()) {
4738 // If MergedDef is visible or becomes visible, make the definition visible.
4739 if (MergedDef->isUnconditionallyVisible())
4740 Def->setVisibleDespiteOwningModule();
4741 else {
4742 getContext().mergeDefinitionIntoModule(
4743 Def, MergedDef->getImportedOwningModule(),
4744 /*NotifyListeners*/ false);
4745 PendingMergedDefinitionsToDeduplicate.insert(Def);
4746 }
4747 }
4748 }
4749
4750 bool ASTReader::loadGlobalIndex() {
4751 if (GlobalIndex)
4752 return false;
4753
4754 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
4755 !PP.getLangOpts().Modules)
4756 return true;
4757
4758 // Try to load the global index.
4759 TriedLoadingGlobalIndex = true;
4760 StringRef ModuleCachePath
4761 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
4762 std::pair<GlobalModuleIndex *, llvm::Error> Result =
4763 GlobalModuleIndex::readIndex(ModuleCachePath);
4764 if (llvm::Error Err = std::move(Result.second)) {
4765 assert(!Result.first);
4766 consumeError(std::move(Err)); // FIXME this drops errors on the floor.
4767 return true;
4768 }
4769
4770 GlobalIndex.reset(Result.first);
4771 ModuleMgr.setGlobalIndex(GlobalIndex.get());
4772 return false;
4773 }
4774
4775 bool ASTReader::isGlobalIndexUnavailable() const {
4776 return PP.getLangOpts().Modules && UseGlobalIndex &&
4777 !hasGlobalIndex() && TriedLoadingGlobalIndex;
4778 }
4779
4780 /// Given a cursor at the start of an AST file, scan ahead and drop the
4781 /// cursor into the start of the given block ID, returning false on success and
4782 /// true on failure.
4783 static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
4784 while (true) {
4785 Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
4786 if (!MaybeEntry) {
4787 // FIXME this drops errors on the floor.
4788 consumeError(MaybeEntry.takeError());
4789 return true;
4790 }
4791 llvm::BitstreamEntry Entry = MaybeEntry.get();
4792
4793 switch (Entry.Kind) {
4794 case llvm::BitstreamEntry::Error:
4795 case llvm::BitstreamEntry::EndBlock:
4796 return true;
4797
4798 case llvm::BitstreamEntry::Record:
4799 // Ignore top-level records.
4800 if (Expected<unsigned> Skipped = Cursor.skipRecord(Entry.ID))
4801 break;
4802 else {
4803 // FIXME this drops errors on the floor.
4804 consumeError(Skipped.takeError());
4805 return true;
4806 }
4807
4808 case llvm::BitstreamEntry::SubBlock:
4809 if (Entry.ID == BlockID) {
4810 if (llvm::Error Err = Cursor.EnterSubBlock(BlockID)) {
4811 // FIXME this drops the error on the floor.
4812 consumeError(std::move(Err));
4813 return true;
4814 }
4815 // Found it!
4816 return false;
4817 }
4818
4819 if (llvm::Error Err = Cursor.SkipBlock()) {
4820 // FIXME this drops the error on the floor.
4821 consumeError(std::move(Err));
4822 return true;
4823 }
4824 }
4825 }
4826 }
4827
4828 ASTReader::ASTReadResult ASTReader::ReadAST(StringRef FileName, ModuleKind Type,
4829 SourceLocation ImportLoc,
4830 unsigned ClientLoadCapabilities,
4831 ModuleFile **NewLoadedModuleFile) {
4832 llvm::TimeTraceScope scope("ReadAST", FileName);
4833
4834 llvm::SaveAndRestore SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
4835 llvm::SaveAndRestore<std::optional<ModuleKind>> SetCurModuleKindRAII(
4836 CurrentDeserializingModuleKind, Type);
4837
4838 // Defer any pending actions until we get to the end of reading the AST file.
4839 Deserializing AnASTFile(this);
4840
4841 // Bump the generation number.
4842 unsigned PreviousGeneration = 0;
4843 if (ContextObj)
4844 PreviousGeneration = incrementGeneration(*ContextObj);
4845
4846 unsigned NumModules = ModuleMgr.size();
4847 SmallVector<ImportedModule, 4> Loaded;
4848 if (ASTReadResult ReadResult =
4849 ReadASTCore(FileName, Type, ImportLoc,
4850 /*ImportedBy=*/nullptr, Loaded, 0, 0, ASTFileSignature(),
4851 ClientLoadCapabilities)) {
4852 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules);
4853
4854 // If we find that any modules are unusable, the global index is going
4855 // to be out-of-date. Just remove it.
4856 GlobalIndex.reset();
4857 ModuleMgr.setGlobalIndex(nullptr);
4858 return ReadResult;
4859 }
4860
4861 if (NewLoadedModuleFile && !Loaded.empty())
4862 *NewLoadedModuleFile = Loaded.back().Mod;
4863
4864 // Here comes stuff that we only do once the entire chain is loaded. Do *not*
4865 // remove modules from this point. Various fields are updated during reading
4866 // the AST block and removing the modules would result in dangling pointers.
4867 // They are generally only incidentally dereferenced, ie. a binary search
4868 // runs over `GlobalSLocEntryMap`, which could cause an invalid module to
4869 // be dereferenced but it wouldn't actually be used.
4870
4871 // Load the AST blocks of all of the modules that we loaded. We can still
4872 // hit errors parsing the ASTs at this point.
4873 for (ImportedModule &M : Loaded) {
4874 ModuleFile &F = *M.Mod;
4875 llvm::TimeTraceScope Scope2("Read Loaded AST", F.ModuleName);
4876
4877 // Read the AST block.
4878 if (llvm::Error Err = ReadASTBlock(F, ClientLoadCapabilities)) {
4879 Error(std::move(Err));
4880 return Failure;
4881 }
4882
4883 // The AST block should always have a definition for the main module.
4884 if (F.isModule() && !F.DidReadTopLevelSubmodule) {
4885 Error(diag::err_module_file_missing_top_level_submodule, F.FileName);
4886 return Failure;
4887 }
4888
4889 // Read the extension blocks.
4890 while (!SkipCursorToBlock(F.Stream, EXTENSION_BLOCK_ID)) {
4891 if (llvm::Error Err = ReadExtensionBlock(F)) {
4892 Error(std::move(Err));
4893 return Failure;
4894 }
4895 }
4896
4897 // Once read, set the ModuleFile bit base offset and update the size in
4898 // bits of all files we've seen.
4899 F.GlobalBitOffset = TotalModulesSizeInBits;
4900 TotalModulesSizeInBits += F.SizeInBits;
4901 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
4902 }
4903
4904 // Preload source locations and interesting indentifiers.
4905 for (ImportedModule &M : Loaded) {
4906 ModuleFile &F = *M.Mod;
4907
4908 // Map the original source file ID into the ID space of the current
4909 // compilation.
4910 if (F.OriginalSourceFileID.isValid())
4911 F.OriginalSourceFileID = TranslateFileID(F, F.OriginalSourceFileID);
4912
4913 for (auto Offset : F.PreloadIdentifierOffsets) {
4914 const unsigned char *Data = F.IdentifierTableData + Offset;
4915
4916 ASTIdentifierLookupTrait Trait(*this, F);
4917 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
4918 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
4919
4920 IdentifierInfo *II;
4921 if (!PP.getLangOpts().CPlusPlus) {
4922 // Identifiers present in both the module file and the importing
4923 // instance are marked out-of-date so that they can be deserialized
4924 // on next use via ASTReader::updateOutOfDateIdentifier().
4925 // Identifiers present in the module file but not in the importing
4926 // instance are ignored for now, preventing growth of the identifier
4927 // table. They will be deserialized on first use via ASTReader::get().
4928 auto It = PP.getIdentifierTable().find(Key);
4929 if (It == PP.getIdentifierTable().end())
4930 continue;
4931 II = It->second;
4932 } else {
4933 // With C++ modules, not many identifiers are considered interesting.
4934 // All identifiers in the module file can be placed into the identifier
4935 // table of the importing instance and marked as out-of-date. This makes
4936 // ASTReader::get() a no-op, and deserialization will take place on
4937 // first/next use via ASTReader::updateOutOfDateIdentifier().
4938 II = &PP.getIdentifierTable().getOwn(Key);
4939 }
4940
4941 II->setOutOfDate(true);
4942
4943 // Mark this identifier as being from an AST file so that we can track
4944 // whether we need to serialize it.
4945 markIdentifierFromAST(*this, *II, /*IsModule=*/true);
4946
4947 // Associate the ID with the identifier so that the writer can reuse it.
4948 auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
4949 SetIdentifierInfo(ID, II);
4950 }
4951 }
4952
4953 // Builtins and library builtins have already been initialized. Mark all
4954 // identifiers as out-of-date, so that they are deserialized on first use.
4955 if (Type == MK_PCH || Type == MK_Preamble || Type == MK_MainFile)
4956 for (auto &Id : PP.getIdentifierTable())
4957 Id.second->setOutOfDate(true);
4958
4959 // Mark selectors as out of date.
4960 for (const auto &Sel : SelectorGeneration)
4961 SelectorOutOfDate[Sel.first] = true;
4962
4963 // Setup the import locations and notify the module manager that we've
4964 // committed to these module files.
4965 for (ImportedModule &M : Loaded) {
4966 ModuleFile &F = *M.Mod;
4967
4968 ModuleMgr.moduleFileAccepted(&F);
4969
4970 // Set the import location.
4971 F.DirectImportLoc = ImportLoc;
4972 // FIXME: We assume that locations from PCH / preamble do not need
4973 // any translation.
4974 if (!M.ImportedBy)
4975 F.ImportLoc = M.ImportLoc;
4976 else
4977 F.ImportLoc = TranslateSourceLocation(*M.ImportedBy, M.ImportLoc);
4978 }
4979
4980 // Resolve any unresolved module exports.
4981 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
4982 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
4983 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
4984 Module *ResolvedMod = getSubmodule(GlobalID);
4985
4986 switch (Unresolved.Kind) {
4987 case UnresolvedModuleRef::Conflict:
4988 if (ResolvedMod) {
4989 Module::Conflict Conflict;
4990 Conflict.Other = ResolvedMod;
4991 Conflict.Message = Unresolved.String.str();
4992 Unresolved.Mod->Conflicts.push_back(Conflict);
4993 }
4994 continue;
4995
4996 case UnresolvedModuleRef::Import:
4997 if (ResolvedMod)
4998 Unresolved.Mod->Imports.insert(ResolvedMod);
4999 continue;
5000
5001 case UnresolvedModuleRef::Affecting:
5002 if (ResolvedMod)
5003 Unresolved.Mod->AffectingClangModules.insert(ResolvedMod);
5004 continue;
5005
5006 case UnresolvedModuleRef::Export:
5007 if (ResolvedMod || Unresolved.IsWildcard)
5008 Unresolved.Mod->Exports.push_back(
5009 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
5010 continue;
5011 }
5012 }
5013 UnresolvedModuleRefs.clear();
5014
5015 // FIXME: How do we load the 'use'd modules? They may not be submodules.
5016 // Might be unnecessary as use declarations are only used to build the
5017 // module itself.
5018
5019 if (ContextObj)
5020 InitializeContext();
5021
5022 if (SemaObj)
5023 UpdateSema();
5024
5025 if (DeserializationListener)
5026 DeserializationListener->ReaderInitialized(this);
5027
5028 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
5029 if (PrimaryModule.OriginalSourceFileID.isValid()) {
5030 // If this AST file is a precompiled preamble, then set the
5031 // preamble file ID of the source manager to the file source file
5032 // from which the preamble was built.
5033 if (Type == MK_Preamble) {
5034 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
5035 } else if (Type == MK_MainFile) {
5036 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
5037 }
5038 }
5039
5040 // For any Objective-C class definitions we have already loaded, make sure
5041 // that we load any additional categories.
5042 if (ContextObj) {
5043 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
5044 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
5045 ObjCClassesLoaded[I], PreviousGeneration);
5046 }
5047 }
5048
5049 const HeaderSearchOptions &HSOpts =
5050 PP.getHeaderSearchInfo().getHeaderSearchOpts();
5051 if (HSOpts.ModulesValidateOncePerBuildSession) {
5052 // Now we are certain that the module and all modules it depends on are
5053 // up-to-date. For implicitly-built module files, ensure the corresponding
5054 // timestamp files are up-to-date in this build session.
5055 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
5056 ImportedModule &M = Loaded[I];
5057 if (M.Mod->Kind == MK_ImplicitModule &&
5058 M.Mod->InputFilesValidationTimestamp < HSOpts.BuildSessionTimestamp)
5059 getModuleManager().getModuleCache().updateModuleTimestamp(
5060 M.Mod->FileName);
5061 }
5062 }
5063
5064 return Success;
5065 }
5066
5067 static ASTFileSignature readASTFileSignature(StringRef PCH);
5068
5069 /// Whether \p Stream doesn't start with the AST file magic number 'CPCH'.
5070 static llvm::Error doesntStartWithASTFileMagic(BitstreamCursor &Stream) {
5071 // FIXME checking magic headers is done in other places such as
5072 // SerializedDiagnosticReader and GlobalModuleIndex, but error handling isn't
5073 // always done the same. Unify it all with a helper.
5074 if (!Stream.canSkipToPos(4))
5075 return llvm::createStringError(
5076 std::errc::illegal_byte_sequence,
5077 "file too small to contain precompiled file magic");
5078 for (unsigned C : {'C', 'P', 'C', 'H'})
5079 if (Expected<llvm::SimpleBitstreamCursor::word_t> Res = Stream.Read(8)) {
5080 if (Res.get() != C)
5081 return llvm::createStringError(
5082 std::errc::illegal_byte_sequence,
5083 "file doesn't start with precompiled file magic");
5084 } else
5085 return Res.takeError();
5086 return llvm::Error::success();
5087 }
5088
5089 static unsigned moduleKindForDiagnostic(ModuleKind Kind) {
5090 switch (Kind) {
5091 case MK_PCH:
5092 return 0; // PCH
5093 case MK_ImplicitModule:
5094 case MK_ExplicitModule:
5095 case MK_PrebuiltModule:
5096 return 1; // module
5097 case MK_MainFile:
5098 case MK_Preamble:
5099 return 2; // main source file
5100 }
5101 llvm_unreachable("unknown module kind");
5102 }
5103
5104 ASTReader::ASTReadResult
5105 ASTReader::ReadASTCore(StringRef FileName,
5106 ModuleKind Type,
5107 SourceLocation ImportLoc,
5108 ModuleFile *ImportedBy,
5109 SmallVectorImpl<ImportedModule> &Loaded,
5110 off_t ExpectedSize, time_t ExpectedModTime,
5111 ASTFileSignature ExpectedSignature,
5112 unsigned ClientLoadCapabilities) {
5113 ModuleFile *M;
5114 std::string ErrorStr;
5115 ModuleManager::AddModuleResult AddResult
5116 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
5117 getGeneration(), ExpectedSize, ExpectedModTime,
5118 ExpectedSignature, readASTFileSignature,
5119 M, ErrorStr);
5120
5121 switch (AddResult) {
5122 case ModuleManager::AlreadyLoaded:
5123 Diag(diag::remark_module_import)
5124 << M->ModuleName << M->FileName << (ImportedBy ? true : false)
5125 << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());
5126 return Success;
5127
5128 case ModuleManager::NewlyLoaded:
5129 // Load module file below.
5130 break;
5131
5132 case ModuleManager::Missing:
5133 // The module file was missing; if the client can handle that, return
5134 // it.
5135 if (ClientLoadCapabilities & ARR_Missing)
5136 return Missing;
5137
5138 // Otherwise, return an error.
5139 Diag(diag::err_ast_file_not_found)
5140 << moduleKindForDiagnostic(Type) << FileName << !ErrorStr.empty()
5141 << ErrorStr;
5142 return Failure;
5143
5144 case ModuleManager::OutOfDate:
5145 // We couldn't load the module file because it is out-of-date. If the
5146 // client can handle out-of-date, return it.
5147 if (ClientLoadCapabilities & ARR_OutOfDate)
5148 return OutOfDate;
5149
5150 // Otherwise, return an error.
5151 Diag(diag::err_ast_file_out_of_date)
5152 << moduleKindForDiagnostic(Type) << FileName << !ErrorStr.empty()
5153 << ErrorStr;
5154 return Failure;
5155 }
5156
5157 assert(M && "Missing module file");
5158
5159 bool ShouldFinalizePCM = false;
5160 llvm::scope_exit FinalizeOrDropPCM([&]() {
5161 auto &MC = getModuleManager().getModuleCache().getInMemoryModuleCache();
5162 if (ShouldFinalizePCM)
5163 MC.finalizePCM(FileName);
5164 else
5165 MC.tryToDropPCM(FileName);
5166 });
5167 ModuleFile &F = *M;
5168 BitstreamCursor &Stream = F.Stream;
5169 Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(*F.Buffer));
5170 F.SizeInBits = F.Buffer->getBufferSize() * 8;
5171
5172 // Sniff for the signature.
5173 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5174 Diag(diag::err_ast_file_invalid)
5175 << moduleKindForDiagnostic(Type) << FileName << std::move(Err);
5176 return Failure;
5177 }
5178
5179 // This is used for compatibility with older PCH formats.
5180 bool HaveReadControlBlock = false;
5181 while (true) {
5182 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5183 if (!MaybeEntry) {
5184 Error(MaybeEntry.takeError());
5185 return Failure;
5186 }
5187 llvm::BitstreamEntry Entry = MaybeEntry.get();
5188
5189 switch (Entry.Kind) {
5190 case llvm::BitstreamEntry::Error:
5191 case llvm::BitstreamEntry::Record:
5192 case llvm::BitstreamEntry::EndBlock:
5193 Error("invalid record at top-level of AST file");
5194 return Failure;
5195
5196 case llvm::BitstreamEntry::SubBlock:
5197 break;
5198 }
5199
5200 switch (Entry.ID) {
5201 case CONTROL_BLOCK_ID:
5202 HaveReadControlBlock = true;
5203 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
5204 case Success:
5205 // Check that we didn't try to load a non-module AST file as a module.
5206 //
5207 // FIXME: Should we also perform the converse check? Loading a module as
5208 // a PCH file sort of works, but it's a bit wonky.
5209 if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule ||
5210 Type == MK_PrebuiltModule) &&
5211 F.ModuleName.empty()) {
5212 auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
5213 if (Result != OutOfDate ||
5214 (ClientLoadCapabilities & ARR_OutOfDate) == 0)
5215 Diag(diag::err_module_file_not_module) << FileName;
5216 return Result;
5217 }
5218 break;
5219
5220 case Failure: return Failure;
5221 case Missing: return Missing;
5222 case OutOfDate: return OutOfDate;
5223 case VersionMismatch: return VersionMismatch;
5224 case ConfigurationMismatch: return ConfigurationMismatch;
5225 case HadErrors: return HadErrors;
5226 }
5227 break;
5228
5229 case AST_BLOCK_ID:
5230 if (!HaveReadControlBlock) {
5231 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
5232 Diag(diag::err_ast_file_version_too_old)
5233 << moduleKindForDiagnostic(Type) << FileName;
5234 return VersionMismatch;
5235 }
5236
5237 // Record that we've loaded this module.
5238 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
5239 ShouldFinalizePCM = true;
5240 return Success;
5241
5242 default:
5243 if (llvm::Error Err = Stream.SkipBlock()) {
5244 Error(std::move(Err));
5245 return Failure;
5246 }
5247 break;
5248 }
5249 }
5250
5251 llvm_unreachable("unexpected break; expected return");
5252 }
5253
5254 ASTReader::ASTReadResult
5255 ASTReader::readUnhashedControlBlock(ModuleFile &F, bool WasImportedBy,
5256 unsigned ClientLoadCapabilities) {
5257 const HeaderSearchOptions &HSOpts =
5258 PP.getHeaderSearchInfo().getHeaderSearchOpts();
5259 bool AllowCompatibleConfigurationMismatch =
5260 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
5261 bool DisableValidation = shouldDisableValidationForFile(F);
5262
5263 ASTReadResult Result = readUnhashedControlBlockImpl(
5264 &F, F.Data, F.FileName, ClientLoadCapabilities,
5265 AllowCompatibleConfigurationMismatch, Listener.get(),
5266 WasImportedBy ? false : HSOpts.ModulesValidateDiagnosticOptions);
5267
5268 // If F was directly imported by another module, it's implicitly validated by
5269 // the importing module.
5270 if (DisableValidation || WasImportedBy ||
5271 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
5272 return Success;
5273
5274 if (Result == Failure) {
5275 Error("malformed block record in AST file");
5276 return Failure;
5277 }
5278
5279 if (Result == OutOfDate && F.Kind == MK_ImplicitModule) {
5280 // If this module has already been finalized in the ModuleCache, we're stuck
5281 // with it; we can only load a single version of each module.
5282 //
5283 // This can happen when a module is imported in two contexts: in one, as a
5284 // user module; in another, as a system module (due to an import from
5285 // another module marked with the [system] flag). It usually indicates a
5286 // bug in the module map: this module should also be marked with [system].
5287 //
5288 // If -Wno-system-headers (the default), and the first import is as a
5289 // system module, then validation will fail during the as-user import,
5290 // since -Werror flags won't have been validated. However, it's reasonable
5291 // to treat this consistently as a system module.
5292 //
5293 // If -Wsystem-headers, the PCM on disk was built with
5294 // -Wno-system-headers, and the first import is as a user module, then
5295 // validation will fail during the as-system import since the PCM on disk
5296 // doesn't guarantee that -Werror was respected. However, the -Werror
5297 // flags were checked during the initial as-user import.
5298 if (getModuleManager().getModuleCache().getInMemoryModuleCache().isPCMFinal(
5299 F.FileName)) {
5300 Diag(diag::warn_module_system_bit_conflict) << F.FileName;
5301 return Success;
5302 }
5303 }
5304
5305 return Result;
5306 }
5307
5308 ASTReader::ASTReadResult ASTReader::readUnhashedControlBlockImpl(
5309 ModuleFile *F, llvm::StringRef StreamData, StringRef Filename,
5310 unsigned ClientLoadCapabilities, bool AllowCompatibleConfigurationMismatch,
5311 ASTReaderListener *Listener, bool ValidateDiagnosticOptions) {
5312 // Initialize a stream.
5313 BitstreamCursor Stream(StreamData);
5314
5315 // Sniff for the signature.
5316 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5317 // FIXME this drops the error on the floor.
5318 consumeError(std::move(Err));
5319 return Failure;
5320 }
5321
5322 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
5323 if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
5324 return Failure;
5325
5326 // Read all of the records in the options block.
5327 RecordData Record;
5328 ASTReadResult Result = Success;
5329 while (true) {
5330 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5331 if (!MaybeEntry) {
5332 // FIXME this drops the error on the floor.
5333 consumeError(MaybeEntry.takeError());
5334 return Failure;
5335 }
5336 llvm::BitstreamEntry Entry = MaybeEntry.get();
5337
5338 switch (Entry.Kind) {
5339 case llvm::BitstreamEntry::Error:
5340 case llvm::BitstreamEntry::SubBlock:
5341 return Failure;
5342
5343 case llvm::BitstreamEntry::EndBlock:
5344 return Result;
5345
5346 case llvm::BitstreamEntry::Record:
5347 // The interesting case.
5348 break;
5349 }
5350
5351 // Read and process a record.
5352 Record.clear();
5353 StringRef Blob;
5354 Expected<unsigned> MaybeRecordType =
5355 Stream.readRecord(Entry.ID, Record, &Blob);
5356 if (!MaybeRecordType) {
5357 // FIXME this drops the error.
5358 return Failure;
5359 }
5360 switch ((UnhashedControlBlockRecordTypes)MaybeRecordType.get()) {
5361 case SIGNATURE:
5362 if (F) {
5363 F->Signature = ASTFileSignature::create(Blob.begin(), Blob.end());
5364 assert(F->Signature != ASTFileSignature::createDummy() &&
5365 "Dummy AST file signature not backpatched in ASTWriter.");
5366 }
5367 break;
5368 case AST_BLOCK_HASH:
5369 if (F) {
5370 F->ASTBlockHash = ASTFileSignature::create(Blob.begin(), Blob.end());
5371 assert(F->ASTBlockHash != ASTFileSignature::createDummy() &&
5372 "Dummy AST block hash not backpatched in ASTWriter.");
5373 }
5374 break;
5375 case DIAGNOSTIC_OPTIONS: {
5376 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
5377 if (Listener && ValidateDiagnosticOptions &&
5378 !AllowCompatibleConfigurationMismatch &&
5379 ParseDiagnosticOptions(Record, Filename, Complain, *Listener))
5380 Result = OutOfDate; // Don't return early. Read the signature.
5381 break;
5382 }
5383 case HEADER_SEARCH_PATHS: {
5384 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
5385 if (Listener && !AllowCompatibleConfigurationMismatch &&
5386 ParseHeaderSearchPaths(Record, Complain, *Listener))
5387 Result = ConfigurationMismatch;
5388 break;
5389 }
5390 case DIAG_PRAGMA_MAPPINGS:
5391 if (!F)
5392 break;
5393 if (F->PragmaDiagMappings.empty())
5394 F->PragmaDiagMappings.swap(Record);
5395 else
5396 F->PragmaDiagMappings.insert(F->PragmaDiagMappings.end(),
5397 Record.begin(), Record.end());
5398 break;
5399 case HEADER_SEARCH_ENTRY_USAGE:
5400 if (F)
5401 F->SearchPathUsage = ReadBitVector(Record, Blob);
5402 break;
5403 case VFS_USAGE:
5404 if (F)
5405 F->VFSUsage = ReadBitVector(Record, Blob);
5406 break;
5407 }
5408 }
5409 }
5410
5411 /// Parse a record and blob containing module file extension metadata.
5412 static bool parseModuleFileExtensionMetadata(
5413 const SmallVectorImpl<uint64_t> &Record,
5414 StringRef Blob,
5415 ModuleFileExtensionMetadata &Metadata) {
5416 if (Record.size() < 4) return true;
5417
5418 Metadata.MajorVersion = Record[0];
5419 Metadata.MinorVersion = Record[1];
5420
5421 unsigned BlockNameLen = Record[2];
5422 unsigned UserInfoLen = Record[3];
5423
5424 if (BlockNameLen + UserInfoLen > Blob.size()) return true;
5425
5426 Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
5427 Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,
5428 Blob.data() + BlockNameLen + UserInfoLen);
5429 return false;
5430 }
5431
5432 llvm::Error ASTReader::ReadExtensionBlock(ModuleFile &F) {
5433 BitstreamCursor &Stream = F.Stream;
5434
5435 RecordData Record;
5436 while (true) {
5437 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5438 if (!MaybeEntry)
5439 return MaybeEntry.takeError();
5440 llvm::BitstreamEntry Entry = MaybeEntry.get();
5441
5442 switch (Entry.Kind) {
5443 case llvm::BitstreamEntry::SubBlock:
5444 if (llvm::Error Err = Stream.SkipBlock())
5445 return Err;
5446 continue;
5447 case llvm::BitstreamEntry::EndBlock:
5448 return llvm::Error::success();
5449 case llvm::BitstreamEntry::Error:
5450 return llvm::createStringError(std::errc::illegal_byte_sequence,
5451 "malformed block record in AST file");
5452 case llvm::BitstreamEntry::Record:
5453 break;
5454 }
5455
5456 Record.clear();
5457 StringRef Blob;
5458 Expected<unsigned> MaybeRecCode =
5459 Stream.readRecord(Entry.ID, Record, &Blob);
5460 if (!MaybeRecCode)
5461 return MaybeRecCode.takeError();
5462 switch (MaybeRecCode.get()) {
5463 case EXTENSION_METADATA: {
5464 ModuleFileExtensionMetadata Metadata;
5465 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
5466 return llvm::createStringError(
5467 std::errc::illegal_byte_sequence,
5468 "malformed EXTENSION_METADATA in AST file");
5469
5470 // Find a module file extension with this block name.
5471 auto Known = ModuleFileExtensions.find(Metadata.BlockName);
5472 if (Known == ModuleFileExtensions.end()) break;
5473
5474 // Form a reader.
5475 if (auto Reader = Known->second->createExtensionReader(Metadata, *this,
5476 F, Stream)) {
5477 F.ExtensionReaders.push_back(std::move(Reader));
5478 }
5479
5480 break;
5481 }
5482 }
5483 }
5484
5485 llvm_unreachable("ReadExtensionBlock should return from while loop");
5486 }
5487
5488 void ASTReader::InitializeContext() {
5489 assert(ContextObj && "no context to initialize");
5490 ASTContext &Context = *ContextObj;
5491
5492 // If there's a listener, notify them that we "read" the translation unit.
5493 if (DeserializationListener)
5494 DeserializationListener->DeclRead(
5495 GlobalDeclID(PREDEF_DECL_TRANSLATION_UNIT_ID),
5496 Context.getTranslationUnitDecl());
5497
5498 // FIXME: Find a better way to deal with collisions between these
5499 // built-in types. Right now, we just ignore the problem.
5500
5501 // Load the special types.
5502 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
5503 if (TypeID String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
5504 if (!Context.CFConstantStringTypeDecl)
5505 Context.setCFConstantStringType(GetType(String));
5506 }
5507
5508 if (TypeID File = SpecialTypes[SPECIAL_TYPE_FILE]) {
5509 QualType FileType = GetType(File);
5510 if (FileType.isNull()) {
5511 Error("FILE type is NULL");
5512 return;
5513 }
5514
5515 if (!Context.FILEDecl) {
5516 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
5517 Context.setFILEDecl(Typedef->getDecl());
5518 else {
5519 const TagType *Tag = FileType->getAs<TagType>();
5520 if (!Tag) {
5521 Error("Invalid FILE type in AST file");
5522 return;
5523 }
5524 Context.setFILEDecl(Tag->getDecl());
5525 }
5526 }
5527 }
5528
5529 if (TypeID Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
5530 QualType Jmp_bufType = GetType(Jmp_buf);
5531 if (Jmp_bufType.isNull()) {
5532 Error("jmp_buf type is NULL");
5533 return;
5534 }
5535
5536 if (!Context.jmp_bufDecl) {
5537 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
5538 Context.setjmp_bufDecl(Typedef->getDecl());
5539 else {
5540 const TagType *Tag = Jmp_bufType->getAs<TagType>();
5541 if (!Tag) {
5542 Error("Invalid jmp_buf type in AST file");
5543 return;
5544 }
5545 Context.setjmp_bufDecl(Tag->getDecl());
5546 }
5547 }
5548 }
5549
5550 if (TypeID Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
5551 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
5552 if (Sigjmp_bufType.isNull()) {
5553 Error("sigjmp_buf type is NULL");
5554 return;
5555 }
5556
5557 if (!Context.sigjmp_bufDecl) {
5558 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
5559 Context.setsigjmp_bufDecl(Typedef->getDecl());
5560 else {
5561 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
5562 assert(Tag && "Invalid sigjmp_buf type in AST file");
5563 Context.setsigjmp_bufDecl(Tag->getDecl());
5564 }
5565 }
5566 }
5567
5568 if (TypeID ObjCIdRedef = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
5569 if (Context.ObjCIdRedefinitionType.isNull())
5570 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
5571 }
5572
5573 if (TypeID ObjCClassRedef =
5574 SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
5575 if (Context.ObjCClassRedefinitionType.isNull())
5576 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
5577 }
5578
5579 if (TypeID ObjCSelRedef =
5580 SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
5581 if (Context.ObjCSelRedefinitionType.isNull())
5582 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
5583 }
5584
5585 if (TypeID Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
5586 QualType Ucontext_tType = GetType(Ucontext_t);
5587 if (Ucontext_tType.isNull()) {
5588 Error("ucontext_t type is NULL");
5589 return;
5590 }
5591
5592 if (!Context.ucontext_tDecl) {
5593 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
5594 Context.setucontext_tDecl(Typedef->getDecl());
5595 else {
5596 const TagType *Tag = Ucontext_tType->getAs<TagType>();
5597 assert(Tag && "Invalid ucontext_t type in AST file");
5598 Context.setucontext_tDecl(Tag->getDecl());
5599 }
5600 }
5601 }
5602 }
5603
5604 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
5605
5606 // If there were any CUDA special declarations, deserialize them.
5607 if (!CUDASpecialDeclRefs.empty()) {
5608 assert(CUDASpecialDeclRefs.size() == 3 && "More decl refs than expected!");
5609 Context.setcudaConfigureCallDecl(
5610 cast_or_null<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
5611 Context.setcudaGetParameterBufferDecl(
5612 cast_or_null<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[1])));
5613 Context.setcudaLaunchDeviceDecl(
5614 cast_or_null<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[2])));
5615 }
5616
5617 // Re-export any modules that were imported by a non-module AST file.
5618 // FIXME: This does not make macro-only imports visible again.
5619 for (auto &Import : PendingImportedModules) {
5620 if (Module *Imported = getSubmodule(Import.ID)) {
5621 makeModuleVisible(Imported, Module::AllVisible,
5622 /*ImportLoc=*/Import.ImportLoc);
5623 if (Import.ImportLoc.isValid())
5624 PP.makeModuleVisible(Imported, Import.ImportLoc);
5625 // This updates visibility for Preprocessor only. For Sema, which can be
5626 // nullptr here, we do the same later, in UpdateSema().
5627 }
5628 }
5629
5630 // Hand off these modules to Sema.
5631 PendingImportedModulesSema.append(PendingImportedModules);
5632 PendingImportedModules.clear();
5633 }
5634
5635 void ASTReader::finalizeForWriting() {
5636 // Nothing to do for now.
5637 }
5638
5639 /// Reads and return the signature record from \p PCH's control block, or
5640 /// else returns 0.
5641 static ASTFileSignature readASTFileSignature(StringRef PCH) {
5642 BitstreamCursor Stream(PCH);
5643 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5644 // FIXME this drops the error on the floor.
5645 consumeError(std::move(Err));
5646 return ASTFileSignature();
5647 }
5648
5649 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
5650 if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
5651 return ASTFileSignature();
5652
5653 // Scan for SIGNATURE inside the diagnostic options block.
5654 ASTReader::RecordData Record;
5655 while (true) {
5656 Expected<llvm::BitstreamEntry> MaybeEntry =
5657 Stream.advanceSkippingSubblocks();
5658 if (!MaybeEntry) {
5659 // FIXME this drops the error on the floor.
5660 consumeError(MaybeEntry.takeError());
5661 return ASTFileSignature();
5662 }
5663 llvm::BitstreamEntry Entry = MaybeEntry.get();
5664
5665 if (Entry.Kind != llvm::BitstreamEntry::Record)
5666 return ASTFileSignature();
5667
5668 Record.clear();
5669 StringRef Blob;
5670 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);
5671 if (!MaybeRecord) {
5672 // FIXME this drops the error on the floor.
5673 consumeError(MaybeRecord.takeError());
5674 return ASTFileSignature();
5675 }
5676 if (SIGNATURE == MaybeRecord.get()) {
5677 auto Signature = ASTFileSignature::create(Blob.begin(), Blob.end());
5678 assert(Signature != ASTFileSignature::createDummy() &&
5679 "Dummy AST file signature not backpatched in ASTWriter.");
5680 return Signature;
5681 }
5682 }
5683 }
5684
5685 /// Retrieve the name of the original source file name
5686 /// directly from the AST file, without actually loading the AST
5687 /// file.
5688 std::string ASTReader::getOriginalSourceFile(
5689 const std::string &ASTFileName, FileManager &FileMgr,
5690 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
5691 // Open the AST file.
5692 auto Buffer = FileMgr.getBufferForFile(ASTFileName, /*IsVolatile=*/false,
5693 /*RequiresNullTerminator=*/false,
5694 /*MaybeLimit=*/std::nullopt,
5695 /*IsText=*/false);
5696 if (!Buffer) {
5697 Diags.Report(diag::err_fe_unable_to_read_pch_file)
5698 << ASTFileName << Buffer.getError().message();
5699 return std::string();
5700 }
5701
5702 // Initialize the stream
5703 BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer));
5704
5705 // Sniff for the signature.
5706 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5707 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName << std::move(Err);
5708 return std::string();
5709 }
5710
5711 // Scan for the CONTROL_BLOCK_ID block.
5712 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
5713 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
5714 return std::string();
5715 }
5716
5717 // Scan for ORIGINAL_FILE inside the control block.
5718 RecordData Record;
5719 while (true) {
5720 Expected<llvm::BitstreamEntry> MaybeEntry =
5721 Stream.advanceSkippingSubblocks();
5722 if (!MaybeEntry) {
5723 // FIXME this drops errors on the floor.
5724 consumeError(MaybeEntry.takeError());
5725 return std::string();
5726 }
5727 llvm::BitstreamEntry Entry = MaybeEntry.get();
5728
5729 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
5730 return std::string();
5731
5732 if (Entry.Kind != llvm::BitstreamEntry::Record) {
5733 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
5734 return std::string();
5735 }
5736
5737 Record.clear();
5738 StringRef Blob;
5739 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);
5740 if (!MaybeRecord) {
5741 // FIXME this drops the errors on the floor.
5742 consumeError(MaybeRecord.takeError());
5743 return std::string();
5744 }
5745 if (ORIGINAL_FILE == MaybeRecord.get())
5746 return Blob.str();
5747 }
5748 }
5749
5750 namespace {
5751
5752 class SimplePCHValidator : public ASTReaderListener {
5753 const LangOptions &ExistingLangOpts;
5754 const CodeGenOptions &ExistingCGOpts;
5755 const TargetOptions &ExistingTargetOpts;
5756 const PreprocessorOptions &ExistingPPOpts;
5757 const HeaderSearchOptions &ExistingHSOpts;
5758 std::string ExistingModuleCachePath;
5759 FileManager &FileMgr;
5760 bool StrictOptionMatches;
5761
5762 public:
5763 SimplePCHValidator(const LangOptions &ExistingLangOpts,
5764 const CodeGenOptions &ExistingCGOpts,
5765 const TargetOptions &ExistingTargetOpts,
5766 const PreprocessorOptions &ExistingPPOpts,
5767 const HeaderSearchOptions &ExistingHSOpts,
5768 StringRef ExistingModuleCachePath, FileManager &FileMgr,
5769 bool StrictOptionMatches)
5770 : ExistingLangOpts(ExistingLangOpts), ExistingCGOpts(ExistingCGOpts),
5771 ExistingTargetOpts(ExistingTargetOpts),
5772 ExistingPPOpts(ExistingPPOpts), ExistingHSOpts(ExistingHSOpts),
5773 ExistingModuleCachePath(ExistingModuleCachePath), FileMgr(FileMgr),
5774 StrictOptionMatches(StrictOptionMatches) {}
5775
5776 bool ReadLanguageOptions(const LangOptions &LangOpts,
5777 StringRef ModuleFilename, bool Complain,
5778 bool AllowCompatibleDifferences) override {
5779 return checkLanguageOptions(ExistingLangOpts, LangOpts, ModuleFilename,
5780 nullptr, AllowCompatibleDifferences);
5781 }
5782
5783 bool ReadCodeGenOptions(const CodeGenOptions &CGOpts,
5784 StringRef ModuleFilename, bool Complain,
5785 bool AllowCompatibleDifferences) override {
5786 return checkCodegenOptions(ExistingCGOpts, CGOpts, ModuleFilename,
5787 nullptr, AllowCompatibleDifferences);
5788 }
5789
5790 bool ReadTargetOptions(const TargetOptions &TargetOpts,
5791 StringRef ModuleFilename, bool Complain,
5792 bool AllowCompatibleDifferences) override {
5793 return checkTargetOptions(ExistingTargetOpts, TargetOpts, ModuleFilename,
5794 nullptr, AllowCompatibleDifferences);
5795 }
5796
5797 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
5798 StringRef ASTFilename,
5799 StringRef SpecificModuleCachePath,
5800 bool Complain) override {
5801 return checkModuleCachePath(
5802 FileMgr.getVirtualFileSystem(), SpecificModuleCachePath,
5803 ExistingModuleCachePath, ASTFilename, nullptr, ExistingLangOpts,
5804 ExistingPPOpts, ExistingHSOpts, HSOpts);
5805 }
5806
5807 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
5808 StringRef ModuleFilename, bool ReadMacros,
5809 bool Complain,
5810 std::string &SuggestedPredefines) override {
5811 return checkPreprocessorOptions(
5812 PPOpts, ExistingPPOpts, ModuleFilename, ReadMacros, /*Diags=*/nullptr,
5813 FileMgr, SuggestedPredefines, ExistingLangOpts,
5814 StrictOptionMatches ? OptionValidateStrictMatches
5815 : OptionValidateContradictions);
5816 }
5817 };
5818
5819 } // namespace
5820
5821 bool ASTReader::readASTFileControlBlock(
5822 StringRef Filename, FileManager &FileMgr, const ModuleCache &ModCache,
5823 const PCHContainerReader &PCHContainerRdr, bool FindModuleFileExtensions,
5824 ASTReaderListener &Listener, bool ValidateDiagnosticOptions,
5825 unsigned ClientLoadCapabilities) {
5826 // Open the AST file.
5827 std::unique_ptr<llvm::MemoryBuffer> OwnedBuffer;
5828 llvm::MemoryBuffer *Buffer =
5829 ModCache.getInMemoryModuleCache().lookupPCM(Filename);
5830 if (!Buffer) {
5831 // FIXME: We should add the pcm to the InMemoryModuleCache if it could be
5832 // read again later, but we do not have the context here to determine if it
5833 // is safe to change the result of InMemoryModuleCache::getPCMState().
5834
5835 // FIXME: This allows use of the VFS; we do not allow use of the
5836 // VFS when actually loading a module.
5837 auto Entry =
5838 Filename == "-" ? FileMgr.getSTDIN() : FileMgr.getFileRef(Filename);
5839 if (!Entry) {
5840 llvm::consumeError(Entry.takeError());
5841 return true;
5842 }
5843 auto BufferOrErr = FileMgr.getBufferForFile(*Entry);
5844 if (!BufferOrErr)
5845 return true;
5846 OwnedBuffer = std::move(*BufferOrErr);
5847 Buffer = OwnedBuffer.get();
5848 }
5849
5850 // Initialize the stream
5851 StringRef Bytes = PCHContainerRdr.ExtractPCH(*Buffer);
5852 BitstreamCursor Stream(Bytes);
5853
5854 // Sniff for the signature.
5855 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5856 consumeError(std::move(Err)); // FIXME this drops errors on the floor.
5857 return true;
5858 }
5859
5860 // Scan for the CONTROL_BLOCK_ID block.
5861 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
5862 return true;
5863
5864 bool NeedsInputFiles = Listener.needsInputFileVisitation();
5865 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
5866 bool NeedsImports = Listener.needsImportVisitation();
5867 BitstreamCursor InputFilesCursor;
5868 uint64_t InputFilesOffsetBase = 0;
5869
5870 RecordData Record;
5871 std::string ModuleDir;
5872 bool DoneWithControlBlock = false;
5873 SmallString<0> PathBuf;
5874 PathBuf.reserve(256);
5875 // Additional path buffer to use when multiple paths need to be resolved.
5876 // For example, when deserializing input files that contains a path that was
5877 // resolved from a vfs overlay and an external location.
5878 SmallString<0> AdditionalPathBuf;
5879 AdditionalPathBuf.reserve(256);
5880 while (!DoneWithControlBlock) {
5881 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5882 if (!MaybeEntry) {
5883 // FIXME this drops the error on the floor.
5884 consumeError(MaybeEntry.takeError());
5885 return true;
5886 }
5887 llvm::BitstreamEntry Entry = MaybeEntry.get();
5888
5889 switch (Entry.Kind) {
5890 case llvm::BitstreamEntry::SubBlock: {
5891 switch (Entry.ID) {
5892 case OPTIONS_BLOCK_ID: {
5893 std::string IgnoredSuggestedPredefines;
5894 if (ReadOptionsBlock(Stream, Filename, ClientLoadCapabilities,
5895 /*AllowCompatibleConfigurationMismatch*/ false,
5896 Listener, IgnoredSuggestedPredefines) != Success)
5897 return true;
5898 break;
5899 }
5900
5901 case INPUT_FILES_BLOCK_ID:
5902 InputFilesCursor = Stream;
5903 if (llvm::Error Err = Stream.SkipBlock()) {
5904 // FIXME this drops the error on the floor.
5905 consumeError(std::move(Err));
5906 return true;
5907 }
5908 if (NeedsInputFiles &&
5909 ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID))
5910 return true;
5911 InputFilesOffsetBase = InputFilesCursor.GetCurrentBitNo();
5912 break;
5913
5914 default:
5915 if (llvm::Error Err = Stream.SkipBlock()) {
5916 // FIXME this drops the error on the floor.
5917 consumeError(std::move(Err));
5918 return true;
5919 }
5920 break;
5921 }
5922
5923 continue;
5924 }
5925
5926 case llvm::BitstreamEntry::EndBlock:
5927 DoneWithControlBlock = true;
5928 break;
5929
5930 case llvm::BitstreamEntry::Error:
5931 return true;
5932
5933 case llvm::BitstreamEntry::Record:
5934 break;
5935 }
5936
5937 if (DoneWithControlBlock) break;
5938
5939 Record.clear();
5940 StringRef Blob;
5941 Expected<unsigned> MaybeRecCode =
5942 Stream.readRecord(Entry.ID, Record, &Blob);
5943 if (!MaybeRecCode) {
5944 // FIXME this drops the error.
5945 return Failure;
5946 }
5947 switch ((ControlRecordTypes)MaybeRecCode.get()) {
5948 case METADATA:
5949 if (Record[0] != VERSION_MAJOR)
5950 return true;
5951 if (Listener.ReadFullVersionInformation(Blob))
5952 return true;
5953 break;
5954 case MODULE_NAME:
5955 Listener.ReadModuleName(Blob);
5956 break;
5957 case MODULE_DIRECTORY:
5958 ModuleDir = std::string(Blob);
5959 break;
5960 case MODULE_MAP_FILE: {
5961 unsigned Idx = 0;
5962 std::string PathStr = ReadString(Record, Idx);
5963 auto Path = ResolveImportedPath(PathBuf, PathStr, ModuleDir);
5964 Listener.ReadModuleMapFile(*Path);
5965 break;
5966 }
5967 case INPUT_FILE_OFFSETS: {
5968 if (!NeedsInputFiles)
5969 break;
5970
5971 unsigned NumInputFiles = Record[0];
5972 unsigned NumUserFiles = Record[1];
5973 const llvm::support::unaligned_uint64_t *InputFileOffs =
5974 (const llvm::support::unaligned_uint64_t *)Blob.data();
5975 for (unsigned I = 0; I != NumInputFiles; ++I) {
5976 // Go find this input file.
5977 bool isSystemFile = I >= NumUserFiles;
5978
5979 if (isSystemFile && !NeedsSystemInputFiles)
5980 break; // the rest are system input files
5981
5982 BitstreamCursor &Cursor = InputFilesCursor;
5983 SavedStreamPosition SavedPosition(Cursor);
5984 if (llvm::Error Err =
5985 Cursor.JumpToBit(InputFilesOffsetBase + InputFileOffs[I])) {
5986 // FIXME this drops errors on the floor.
5987 consumeError(std::move(Err));
5988 }
5989
5990 Expected<unsigned> MaybeCode = Cursor.ReadCode();
5991 if (!MaybeCode) {
5992 // FIXME this drops errors on the floor.
5993 consumeError(MaybeCode.takeError());
5994 }
5995 unsigned Code = MaybeCode.get();
5996
5997 RecordData Record;
5998 StringRef Blob;
5999 bool shouldContinue = false;
6000 Expected<unsigned> MaybeRecordType =
6001 Cursor.readRecord(Code, Record, &Blob);
6002 if (!MaybeRecordType) {
6003 // FIXME this drops errors on the floor.
6004 consumeError(MaybeRecordType.takeError());
6005 }
6006 switch ((InputFileRecordTypes)MaybeRecordType.get()) {
6007 case INPUT_FILE_HASH:
6008 break;
6009 case INPUT_FILE:
6010 time_t StoredTime = static_cast<time_t>(Record[2]);
6011 bool Overridden = static_cast<bool>(Record[3]);
6012 auto [UnresolvedFilenameAsRequested, UnresolvedFilename] =
6013 getUnresolvedInputFilenames(Record, Blob);
6014 auto FilenameAsRequestedBuf = ResolveImportedPath(
6015 PathBuf, UnresolvedFilenameAsRequested, ModuleDir);
6016 StringRef Filename;
6017 if (UnresolvedFilename.empty())
6018 Filename = *FilenameAsRequestedBuf;
6019 else {
6020 auto FilenameBuf = ResolveImportedPath(
6021 AdditionalPathBuf, UnresolvedFilename, ModuleDir);
6022 Filename = *FilenameBuf;
6023 }
6024 shouldContinue = Listener.visitInputFileAsRequested(
6025 *FilenameAsRequestedBuf, Filename, isSystemFile, Overridden,
6026 StoredTime, /*IsExplicitModule=*/false);
6027 break;
6028 }
6029 if (!shouldContinue)
6030 break;
6031 }
6032 break;
6033 }
6034
6035 case IMPORT: {
6036 if (!NeedsImports)
6037 break;
6038
6039 unsigned Idx = 0;
6040 // Read information about the AST file.
6041
6042 // Skip Kind
6043 Idx++;
6044
6045 // Skip ImportLoc
6046 Idx++;
6047
6048 StringRef ModuleName = ReadStringBlob(Record, Idx, Blob);
6049
6050 bool IsStandardCXXModule = Record[Idx++];
6051
6052 // In C++20 Modules, we don't record the path to imported
6053 // modules in the BMI files.
6054 if (IsStandardCXXModule) {
6055 Listener.visitImport(ModuleName, /*Filename=*/"");
6056 continue;
6057 }
6058
6059 // Skip Size and ModTime.
6060 Idx += 1 + 1;
6061 // Skip signature.
6062 Blob = Blob.substr(ASTFileSignature::size);
6063
6064 StringRef FilenameStr = ReadStringBlob(Record, Idx, Blob);
6065 auto Filename = ResolveImportedPath(PathBuf, FilenameStr, ModuleDir);
6066 Listener.visitImport(ModuleName, *Filename);
6067 break;
6068 }
6069
6070 default:
6071 // No other validation to perform.
6072 break;
6073 }
6074 }
6075
6076 // Look for module file extension blocks, if requested.
6077 if (FindModuleFileExtensions) {
6078 BitstreamCursor SavedStream = Stream;
6079 while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {
6080 bool DoneWithExtensionBlock = false;
6081 while (!DoneWithExtensionBlock) {
6082 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
6083 if (!MaybeEntry) {
6084 // FIXME this drops the error.
6085 return true;
6086 }
6087 llvm::BitstreamEntry Entry = MaybeEntry.get();
6088
6089 switch (Entry.Kind) {
6090 case llvm::BitstreamEntry::SubBlock:
6091 if (llvm::Error Err = Stream.SkipBlock()) {
6092 // FIXME this drops the error on the floor.
6093 consumeError(std::move(Err));
6094 return true;
6095 }
6096 continue;
6097
6098 case llvm::BitstreamEntry::EndBlock:
6099 DoneWithExtensionBlock = true;
6100 continue;
6101
6102 case llvm::BitstreamEntry::Error:
6103 return true;
6104
6105 case llvm::BitstreamEntry::Record:
6106 break;
6107 }
6108
6109 Record.clear();
6110 StringRef Blob;
6111 Expected<unsigned> MaybeRecCode =
6112 Stream.readRecord(Entry.ID, Record, &Blob);
6113 if (!MaybeRecCode) {
6114 // FIXME this drops the error.
6115 return true;
6116 }
6117 switch (MaybeRecCode.get()) {
6118 case EXTENSION_METADATA: {
6119 ModuleFileExtensionMetadata Metadata;
6120 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
6121 return true;
6122
6123 Listener.readModuleFileExtension(Metadata);
6124 break;
6125 }
6126 }
6127 }
6128 }
6129 Stream = std::move(SavedStream);
6130 }
6131
6132 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
6133 if (readUnhashedControlBlockImpl(
6134 nullptr, Bytes, Filename, ClientLoadCapabilities,
6135 /*AllowCompatibleConfigurationMismatch*/ false, &Listener,
6136 ValidateDiagnosticOptions) != Success)
6137 return true;
6138
6139 return false;
6140 }
6141
6142 bool ASTReader::isAcceptableASTFile(
6143 StringRef Filename, FileManager &FileMgr, const ModuleCache &ModCache,
6144 const PCHContainerReader &PCHContainerRdr, const LangOptions &LangOpts,
6145 const CodeGenOptions &CGOpts, const TargetOptions &TargetOpts,
6146 const PreprocessorOptions &PPOpts, const HeaderSearchOptions &HSOpts,
6147 StringRef ExistingModuleCachePath, bool RequireStrictOptionMatches) {
6148 SimplePCHValidator validator(LangOpts, CGOpts, TargetOpts, PPOpts, HSOpts,
6149 ExistingModuleCachePath, FileMgr,
6150 RequireStrictOptionMatches);
6151 return !readASTFileControlBlock(Filename, FileMgr, ModCache, PCHContainerRdr,
6152 /*FindModuleFileExtensions=*/false, validator,
6153 /*ValidateDiagnosticOptions=*/true);
6154 }
6155
6156 llvm::Error ASTReader::ReadSubmoduleBlock(ModuleFile &F,
6157 unsigned ClientLoadCapabilities) {
6158 // Enter the submodule block.
6159 if (llvm::Error Err = F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID))
6160 return Err;
6161
6162 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
6163 bool KnowsTopLevelModule = ModMap.findModule(F.ModuleName) != nullptr;
6164 // If we don't know the top-level module, there's no point in doing qualified
6165 // lookup of its submodules; it won't find anything anywhere within this tree.
6166 // Let's skip that and avoid some string lookups.
6167 auto CreateModule = !KnowsTopLevelModule
6168 ? &ModuleMap::createModule
6169 : &ModuleMap::findOrCreateModuleFirst;
6170
6171 bool First = true;
6172 Module *CurrentModule = nullptr;
6173 RecordData Record;
6174 while (true) {
6175 Expected<llvm::BitstreamEntry> MaybeEntry =
6176 F.Stream.advanceSkippingSubblocks();
6177 if (!MaybeEntry)
6178 return MaybeEntry.takeError();
6179 llvm::BitstreamEntry Entry = MaybeEntry.get();
6180
6181 switch (Entry.Kind) {
6182 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
6183 case llvm::BitstreamEntry::Error:
6184 return llvm::createStringError(std::errc::illegal_byte_sequence,
6185 "malformed block record in AST file");
6186 case llvm::BitstreamEntry::EndBlock:
6187 return llvm::Error::success();
6188 case llvm::BitstreamEntry::Record:
6189 // The interesting case.
6190 break;
6191 }
6192
6193 // Read a record.
6194 StringRef Blob;
6195 Record.clear();
6196 Expected<unsigned> MaybeKind = F.Stream.readRecord(Entry.ID, Record, &Blob);
6197 if (!MaybeKind)
6198 return MaybeKind.takeError();
6199 unsigned Kind = MaybeKind.get();
6200
6201 if ((Kind == SUBMODULE_METADATA) != First)
6202 return llvm::createStringError(
6203 std::errc::illegal_byte_sequence,
6204 "submodule metadata record should be at beginning of block");
6205 First = false;
6206
6207 // Submodule information is only valid if we have a current module.
6208 // FIXME: Should we error on these cases?
6209 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
6210 Kind != SUBMODULE_DEFINITION)
6211 continue;
6212
6213 switch (Kind) {
6214 default: // Default behavior: ignore.
6215 break;
6216
6217 case SUBMODULE_DEFINITION: {
6218 if (Record.size() < 13)
6219 return llvm::createStringError(std::errc::illegal_byte_sequence,
6220 "malformed module definition");
6221
6222 StringRef Name = Blob;
6223 unsigned Idx = 0;
6224 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
6225 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
6226 Module::ModuleKind Kind = (Module::ModuleKind)Record[Idx++];
6227 SourceLocation DefinitionLoc = ReadSourceLocation(F, Record[Idx++]);
6228 FileID InferredAllowedBy = ReadFileID(F, Record, Idx);
6229 bool IsFramework = Record[Idx++];
6230 bool IsExplicit = Record[Idx++];
6231 bool IsSystem = Record[Idx++];
6232 bool IsExternC = Record[Idx++];
6233 bool InferSubmodules = Record[Idx++];
6234 bool InferExplicitSubmodules = Record[Idx++];
6235 bool InferExportWildcard = Record[Idx++];
6236 bool ConfigMacrosExhaustive = Record[Idx++];
6237 bool ModuleMapIsPrivate = Record[Idx++];
6238 bool NamedModuleHasInit = Record[Idx++];
6239
6240 Module *ParentModule = nullptr;
6241 if (Parent)
6242 ParentModule = getSubmodule(Parent);
6243
6244 CurrentModule = std::invoke(CreateModule, &ModMap, Name, ParentModule,
6245 IsFramework, IsExplicit);
6246
6247 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
6248 if (GlobalIndex >= SubmodulesLoaded.size() ||
6249 SubmodulesLoaded[GlobalIndex])
6250 return llvm::createStringError(std::errc::invalid_argument,
6251 "too many submodules");
6252
6253 if (!ParentModule) {
6254 if (OptionalFileEntryRef CurFile = CurrentModule->getASTFile()) {
6255 // Don't emit module relocation error if we have -fno-validate-pch
6256 if (!bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation &
6257 DisableValidationForModuleKind::Module)) {
6258 assert(CurFile != F.File && "ModuleManager did not de-duplicate");
6259
6260 Diag(diag::err_module_file_conflict)
6261 << CurrentModule->getTopLevelModuleName() << CurFile->getName()
6262 << F.File.getName();
6263
6264 auto CurModMapFile =
6265 ModMap.getContainingModuleMapFile(CurrentModule);
6266 auto ModMapFile = FileMgr.getOptionalFileRef(F.ModuleMapPath);
6267 if (CurModMapFile && ModMapFile && CurModMapFile != ModMapFile)
6268 Diag(diag::note_module_file_conflict)
6269 << CurModMapFile->getName() << ModMapFile->getName();
6270
6271 return llvm::make_error<AlreadyReportedDiagnosticError>();
6272 }
6273 }
6274
6275 F.DidReadTopLevelSubmodule = true;
6276 CurrentModule->setASTFile(F.File);
6277 CurrentModule->PresumedModuleMapFile = F.ModuleMapPath;
6278 }
6279
6280 CurrentModule->Kind = Kind;
6281 // Note that we may be rewriting an existing location and it is important
6282 // to keep doing that. In particular, we would like to prefer a
6283 // `DefinitionLoc` loaded from the module file instead of the location
6284 // created in the current source manager, because it allows the new
6285 // location to be marked as "unaffecting" when writing and avoid creating
6286 // duplicate locations for the same module map file.
6287 CurrentModule->DefinitionLoc = DefinitionLoc;
6288 CurrentModule->Signature = F.Signature;
6289 CurrentModule->IsFromModuleFile = true;
6290 if (InferredAllowedBy.isValid())
6291 ModMap.setInferredModuleAllowedBy(CurrentModule, InferredAllowedBy);
6292 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
6293 CurrentModule->IsExternC = IsExternC;
6294 CurrentModule->InferSubmodules = InferSubmodules;
6295 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
6296 CurrentModule->InferExportWildcard = InferExportWildcard;
6297 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
6298 CurrentModule->ModuleMapIsPrivate = ModuleMapIsPrivate;
6299 CurrentModule->NamedModuleHasInit = NamedModuleHasInit;
6300 if (DeserializationListener)
6301 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
6302
6303 SubmodulesLoaded[GlobalIndex] = CurrentModule;
6304
6305 // Clear out data that will be replaced by what is in the module file.
6306 CurrentModule->LinkLibraries.clear();
6307 CurrentModule->ConfigMacros.clear();
6308 CurrentModule->UnresolvedConflicts.clear();
6309 CurrentModule->Conflicts.clear();
6310
6311 // The module is available unless it's missing a requirement; relevant
6312 // requirements will be (re-)added by SUBMODULE_REQUIRES records.
6313 // Missing headers that were present when the module was built do not
6314 // make it unavailable -- if we got this far, this must be an explicitly
6315 // imported module file.
6316 CurrentModule->Requirements.clear();
6317 CurrentModule->MissingHeaders.clear();
6318 CurrentModule->IsUnimportable =
6319 ParentModule && ParentModule->IsUnimportable;
6320 CurrentModule->IsAvailable = !CurrentModule->IsUnimportable;
6321 break;
6322 }
6323
6324 case SUBMODULE_UMBRELLA_HEADER: {
6325 // FIXME: This doesn't work for framework modules as `Filename` is the
6326 // name as written in the module file and does not include
6327 // `Headers/`, so this path will never exist.
6328 auto Filename = ResolveImportedPath(PathBuf, Blob, F);
6329 if (auto Umbrella = PP.getFileManager().getOptionalFileRef(*Filename)) {
6330 if (!CurrentModule->getUmbrellaHeaderAsWritten()) {
6331 // FIXME: NameAsWritten
6332 ModMap.setUmbrellaHeaderAsWritten(CurrentModule, *Umbrella, Blob, "");
6333 }
6334 // Note that it's too late at this point to return out of date if the
6335 // name from the PCM doesn't match up with the one in the module map,
6336 // but also quite unlikely since we will have already checked the
6337 // modification time and size of the module map file itself.
6338 }
6339 break;
6340 }
6341
6342 case SUBMODULE_HEADER:
6343 case SUBMODULE_EXCLUDED_HEADER:
6344 case SUBMODULE_PRIVATE_HEADER:
6345 // We lazily associate headers with their modules via the HeaderInfo table.
6346 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
6347 // of complete filenames or remove it entirely.
6348 break;
6349
6350 case SUBMODULE_TEXTUAL_HEADER:
6351 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
6352 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
6353 // them here.
6354 break;
6355
6356 case SUBMODULE_TOPHEADER: {
6357 auto HeaderName = ResolveImportedPath(PathBuf, Blob, F);
6358 CurrentModule->addTopHeaderFilename(*HeaderName);
6359 break;
6360 }
6361
6362 case SUBMODULE_UMBRELLA_DIR: {
6363 // See comments in SUBMODULE_UMBRELLA_HEADER
6364 auto Dirname = ResolveImportedPath(PathBuf, Blob, F);
6365 if (auto Umbrella =
6366 PP.getFileManager().getOptionalDirectoryRef(*Dirname)) {
6367 if (!CurrentModule->getUmbrellaDirAsWritten()) {
6368 // FIXME: NameAsWritten
6369 ModMap.setUmbrellaDirAsWritten(CurrentModule, *Umbrella, Blob, "");
6370 }
6371 }
6372 break;
6373 }
6374
6375 case SUBMODULE_METADATA: {
6376 F.BaseSubmoduleID = getTotalNumSubmodules();
6377 F.LocalNumSubmodules = Record[0];
6378 unsigned LocalBaseSubmoduleID = Record[1];
6379 if (F.LocalNumSubmodules > 0) {
6380 // Introduce the global -> local mapping for submodules within this
6381 // module.
6382 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
6383
6384 // Introduce the local -> global mapping for submodules within this
6385 // module.
6386 F.SubmoduleRemap.insertOrReplace(
6387 std::make_pair(LocalBaseSubmoduleID,
6388 F.BaseSubmoduleID - LocalBaseSubmoduleID));
6389
6390 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
6391 }
6392 break;
6393 }
6394
6395 case SUBMODULE_IMPORTS:
6396 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
6397 UnresolvedModuleRef Unresolved;
6398 Unresolved.File = &F;
6399 Unresolved.Mod = CurrentModule;
6400 Unresolved.ID = Record[Idx];
6401 Unresolved.Kind = UnresolvedModuleRef::Import;
6402 Unresolved.IsWildcard = false;
6403 UnresolvedModuleRefs.push_back(Unresolved);
6404 }
6405 break;
6406
6407 case SUBMODULE_AFFECTING_MODULES:
6408 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
6409 UnresolvedModuleRef Unresolved;
6410 Unresolved.File = &F;
6411 Unresolved.Mod = CurrentModule;
6412 Unresolved.ID = Record[Idx];
6413 Unresolved.Kind = UnresolvedModuleRef::Affecting;
6414 Unresolved.IsWildcard = false;
6415 UnresolvedModuleRefs.push_back(Unresolved);
6416 }
6417 break;
6418
6419 case SUBMODULE_EXPORTS:
6420 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
6421 UnresolvedModuleRef Unresolved;
6422 Unresolved.File = &F;
6423 Unresolved.Mod = CurrentModule;
6424 Unresolved.ID = Record[Idx];
6425 Unresolved.Kind = UnresolvedModuleRef::Export;
6426 Unresolved.IsWildcard = Record[Idx + 1];
6427 UnresolvedModuleRefs.push_back(Unresolved);
6428 }
6429
6430 // Once we've loaded the set of exports, there's no reason to keep
6431 // the parsed, unresolved exports around.
6432 CurrentModule->UnresolvedExports.clear();
6433 break;
6434
6435 case SUBMODULE_REQUIRES:
6436 CurrentModule->addRequirement(Blob, Record[0], PP.getLangOpts(),
6437 PP.getTargetInfo());
6438 break;
6439
6440 case SUBMODULE_LINK_LIBRARY:
6441 ModMap.resolveLinkAsDependencies(CurrentModule);
6442 CurrentModule->LinkLibraries.push_back(
6443 Module::LinkLibrary(std::string(Blob), Record[0]));
6444 break;
6445
6446 case SUBMODULE_CONFIG_MACRO:
6447 CurrentModule->ConfigMacros.push_back(Blob.str());
6448 break;
6449
6450 case SUBMODULE_CONFLICT: {
6451 UnresolvedModuleRef Unresolved;
6452 Unresolved.File = &F;
6453 Unresolved.Mod = CurrentModule;
6454 Unresolved.ID = Record[0];
6455 Unresolved.Kind = UnresolvedModuleRef::Conflict;
6456 Unresolved.IsWildcard = false;
6457 Unresolved.String = Blob;
6458 UnresolvedModuleRefs.push_back(Unresolved);
6459 break;
6460 }
6461
6462 case SUBMODULE_INITIALIZERS: {
6463 if (!ContextObj)
6464 break;
6465 // Standard C++ module has its own way to initialize variables.
6466 if (!F.StandardCXXModule || F.Kind == MK_MainFile) {
6467 SmallVector<GlobalDeclID, 16> Inits;
6468 for (unsigned I = 0; I < Record.size(); /*in loop*/)
6469 Inits.push_back(ReadDeclID(F, Record, I));
6470 ContextObj->addLazyModuleInitializers(CurrentModule, Inits);
6471 }
6472 break;
6473 }
6474
6475 case SUBMODULE_EXPORT_AS:
6476 CurrentModule->ExportAsModule = Blob.str();
6477 ModMap.addLinkAsDependency(CurrentModule);
6478 break;
6479 }
6480 }
6481 }
6482
6483 /// Parse the record that corresponds to a LangOptions data
6484 /// structure.
6485 ///
6486 /// This routine parses the language options from the AST file and then gives
6487 /// them to the AST listener if one is set.
6488 ///
6489 /// \returns true if the listener deems the file unacceptable, false otherwise.
6490 bool ASTReader::ParseLanguageOptions(const RecordData &Record,
6491 StringRef ModuleFilename, bool Complain,
6492 ASTReaderListener &Listener,
6493 bool AllowCompatibleDifferences) {
6494 LangOptions LangOpts;
6495 unsigned Idx = 0;
6496 #define LANGOPT(Name, Bits, Default, Compatibility, Description) \
6497 LangOpts.Name = Record[Idx++];
6498 #define ENUM_LANGOPT(Name, Type, Bits, Default, Compatibility, Description) \
6499 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
6500 #include "clang/Basic/LangOptions.def"
6501 #define SANITIZER(NAME, ID) \
6502 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
6503 #include "clang/Basic/Sanitizers.def"
6504
6505 for (unsigned N = Record[Idx++]; N; --N)
6506 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
6507
6508 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
6509 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
6510 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
6511
6512 LangOpts.CurrentModule = ReadString(Record, Idx);
6513
6514 // Comment options.
6515 for (unsigned N = Record[Idx++]; N; --N) {
6516 LangOpts.CommentOpts.BlockCommandNames.push_back(
6517 ReadString(Record, Idx));
6518 }
6519 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
6520
6521 // OpenMP offloading options.
6522 for (unsigned N = Record[Idx++]; N; --N) {
6523 LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx)));
6524 }
6525
6526 LangOpts.OMPHostIRFile = ReadString(Record, Idx);
6527
6528 return Listener.ReadLanguageOptions(LangOpts, ModuleFilename, Complain,
6529 AllowCompatibleDifferences);
6530 }
6531
6532 bool ASTReader::ParseCodeGenOptions(const RecordData &Record,
6533 StringRef ModuleFilename, bool Complain,
6534 ASTReaderListener &Listener,
6535 bool AllowCompatibleDifferences) {
6536 unsigned Idx = 0;
6537 CodeGenOptions CGOpts;
6538 using CK = CodeGenOptions::CompatibilityKind;
6539 #define CODEGENOPT(Name, Bits, Default, Compatibility) \
6540 if constexpr (CK::Compatibility != CK::Benign) \
6541 CGOpts.Name = static_cast<unsigned>(Record[Idx++]);
6542 #define ENUM_CODEGENOPT(Name, Type, Bits, Default, Compatibility) \
6543 if constexpr (CK::Compatibility != CK::Benign) \
6544 CGOpts.set##Name(static_cast<clang::CodeGenOptions::Type>(Record[Idx++]));
6545 #define DEBUGOPT(Name, Bits, Default, Compatibility)
6546 #define VALUE_DEBUGOPT(Name, Bits, Default, Compatibility)
6547 #define ENUM_DEBUGOPT(Name, Type, Bits, Default, Compatibility)
6548 #include "clang/Basic/CodeGenOptions.def"
6549
6550 return Listener.ReadCodeGenOptions(CGOpts, ModuleFilename, Complain,
6551 AllowCompatibleDifferences);
6552 }
6553
6554 bool ASTReader::ParseTargetOptions(const RecordData &Record,
6555 StringRef ModuleFilename, bool Complain,
6556 ASTReaderListener &Listener,
6557 bool AllowCompatibleDifferences) {
6558 unsigned Idx = 0;
6559 TargetOptions TargetOpts;
6560 TargetOpts.Triple = ReadString(Record, Idx);
6561 TargetOpts.CPU = ReadString(Record, Idx);
6562 TargetOpts.TuneCPU = ReadString(Record, Idx);
6563 TargetOpts.ABI = ReadString(Record, Idx);
6564 for (unsigned N = Record[Idx++]; N; --N) {
6565 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
6566 }
6567 for (unsigned N = Record[Idx++]; N; --N) {
6568 TargetOpts.Features.push_back(ReadString(Record, Idx));
6569 }
6570
6571 return Listener.ReadTargetOptions(TargetOpts, ModuleFilename, Complain,
6572 AllowCompatibleDifferences);
6573 }
6574
6575 bool ASTReader::ParseDiagnosticOptions(const RecordData &Record,
6576 StringRef ModuleFilename, bool Complain,
6577 ASTReaderListener &Listener) {
6578 DiagnosticOptions DiagOpts;
6579 unsigned Idx = 0;
6580 #define DIAGOPT(Name, Bits, Default) DiagOpts.Name = Record[Idx++];
6581 #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
6582 DiagOpts.set##Name(static_cast<Type>(Record[Idx++]));
6583 #include "clang/Basic/DiagnosticOptions.def"
6584
6585 for (unsigned N = Record[Idx++]; N; --N)
6586 DiagOpts.Warnings.push_back(ReadString(Record, Idx));
6587 for (unsigned N = Record[Idx++]; N; --N)
6588 DiagOpts.Remarks.push_back(ReadString(Record, Idx));
6589
6590 return Listener.ReadDiagnosticOptions(DiagOpts, ModuleFilename, Complain);
6591 }
6592
6593 bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
6594 ASTReaderListener &Listener) {
6595 FileSystemOptions FSOpts;
6596 unsigned Idx = 0;
6597 FSOpts.WorkingDir = ReadString(Record, Idx);
6598 return Listener.ReadFileSystemOptions(FSOpts, Complain);
6599 }
6600
6601 bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
6602 StringRef ModuleFilename,
6603 bool Complain,
6604 ASTReaderListener &Listener) {
6605 HeaderSearchOptions HSOpts;
6606 unsigned Idx = 0;
6607 HSOpts.Sysroot = ReadString(Record, Idx);
6608
6609 HSOpts.ResourceDir = ReadString(Record, Idx);
6610 HSOpts.ModuleCachePath = ReadString(Record, Idx);
6611 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
6612 HSOpts.DisableModuleHash = Record[Idx++];
6613 HSOpts.ImplicitModuleMaps = Record[Idx++];
6614 HSOpts.ModuleMapFileHomeIsCwd = Record[Idx++];
6615 HSOpts.EnablePrebuiltImplicitModules = Record[Idx++];
6616 HSOpts.UseBuiltinIncludes = Record[Idx++];
6617 HSOpts.UseStandardSystemIncludes = Record[Idx++];
6618 HSOpts.UseStandardCXXIncludes = Record[Idx++];
6619 HSOpts.UseLibcxx = Record[Idx++];
6620 std::string SpecificModuleCachePath = ReadString(Record, Idx);
6621
6622 return Listener.ReadHeaderSearchOptions(HSOpts, ModuleFilename,
6623 SpecificModuleCachePath, Complain);
6624 }
6625
6626 bool ASTReader::ParseHeaderSearchPaths(const RecordData &Record, bool Complain,
6627 ASTReaderListener &Listener) {
6628 HeaderSearchOptions HSOpts;
6629 unsigned Idx = 0;
6630
6631 // Include entries.
6632 for (unsigned N = Record[Idx++]; N; --N) {
6633 std::string Path = ReadString(Record, Idx);
6634 frontend::IncludeDirGroup Group
6635 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
6636 bool IsFramework = Record[Idx++];
6637 bool IgnoreSysRoot = Record[Idx++];
6638 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
6639 IgnoreSysRoot);
6640 }
6641
6642 // System header prefixes.
6643 for (unsigned N = Record[Idx++]; N; --N) {
6644 std::string Prefix = ReadString(Record, Idx);
6645 bool IsSystemHeader = Record[Idx++];
6646 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
6647 }
6648
6649 // VFS overlay files.
6650 for (unsigned N = Record[Idx++]; N; --N) {
6651 std::string VFSOverlayFile = ReadString(Record, Idx);
6652 HSOpts.VFSOverlayFiles.emplace_back(std::move(VFSOverlayFile));
6653 }
6654
6655 return Listener.ReadHeaderSearchPaths(HSOpts, Complain);
6656 }
6657
6658 bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
6659 StringRef ModuleFilename,
6660 bool Complain,
6661 ASTReaderListener &Listener,
6662 std::string &SuggestedPredefines) {
6663 PreprocessorOptions PPOpts;
6664 unsigned Idx = 0;
6665
6666 // Macro definitions/undefs
6667 bool ReadMacros = Record[Idx++];
6668 if (ReadMacros) {
6669 for (unsigned N = Record[Idx++]; N; --N) {
6670 std::string Macro = ReadString(Record, Idx);
6671 bool IsUndef = Record[Idx++];
6672 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
6673 }
6674 }
6675
6676 // Includes
6677 for (unsigned N = Record[Idx++]; N; --N) {
6678 PPOpts.Includes.push_back(ReadString(Record, Idx));
6679 }
6680
6681 // Macro Includes
6682 for (unsigned N = Record[Idx++]; N; --N) {
6683 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
6684 }
6685
6686 PPOpts.UsePredefines = Record[Idx++];
6687 PPOpts.DetailedRecord = Record[Idx++];
6688 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
6689 PPOpts.ObjCXXARCStandardLibrary =
6690 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
6691 SuggestedPredefines.clear();
6692 return Listener.ReadPreprocessorOptions(PPOpts, ModuleFilename, ReadMacros,
6693 Complain, SuggestedPredefines);
6694 }
6695
6696 std::pair<ModuleFile *, unsigned>
6697 ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
6698 GlobalPreprocessedEntityMapType::iterator
6699 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
6700 assert(I != GlobalPreprocessedEntityMap.end() &&
6701 "Corrupted global preprocessed entity map");
6702 ModuleFile *M = I->second;
6703 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
6704 return std::make_pair(M, LocalIndex);
6705 }
6706
6707 llvm::iterator_range<PreprocessingRecord::iterator>
6708 ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
6709 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
6710 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
6711 Mod.NumPreprocessedEntities);
6712
6713 return llvm::make_range(PreprocessingRecord::iterator(),
6714 PreprocessingRecord::iterator());
6715 }
6716
6717 bool ASTReader::canRecoverFromOutOfDate(StringRef ModuleFileName,
6718 unsigned int ClientLoadCapabilities) {
6719 return ClientLoadCapabilities & ARR_OutOfDate &&
6720 !getModuleManager()
6721 .getModuleCache()
6722 .getInMemoryModuleCache()
6723 .isPCMFinal(ModuleFileName);
6724 }
6725
6726 llvm::iterator_range<ASTReader::ModuleDeclIterator>
6727 ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
6728 return llvm::make_range(
6729 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
6730 ModuleDeclIterator(this, &Mod,
6731 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
6732 }
6733
6734 SourceRange ASTReader::ReadSkippedRange(unsigned GlobalIndex) {
6735 auto I = GlobalSkippedRangeMap.find(GlobalIndex);
6736 assert(I != GlobalSkippedRangeMap.end() &&
6737 "Corrupted global skipped range map");
6738 ModuleFile *M = I->second;
6739 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedSkippedRangeID;
6740 assert(LocalIndex < M->NumPreprocessedSkippedRanges);
6741 PPSkippedRange RawRange = M->PreprocessedSkippedRangeOffsets[LocalIndex];
6742 SourceRange Range(ReadSourceLocation(*M, RawRange.getBegin()),
6743 ReadSourceLocation(*M, RawRange.getEnd()));
6744 assert(Range.isValid());
6745 return Range;
6746 }
6747
6748 unsigned
6749 ASTReader::translatePreprocessedEntityIDToIndex(PreprocessedEntityID ID) const {
6750 unsigned ModuleFileIndex = ID >> 32;
6751 assert(ModuleFileIndex && "not translating loaded MacroID?");
6752 assert(getModuleManager().size() > ModuleFileIndex - 1);
6753 ModuleFile &MF = getModuleManager()[ModuleFileIndex - 1];
6754
6755 ID &= llvm::maskTrailingOnes<PreprocessedEntityID>(32);
6756 return MF.BasePreprocessedEntityID + ID;
6757 }
6758
6759 PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
6760 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
6761 ModuleFile &M = *PPInfo.first;
6762 unsigned LocalIndex = PPInfo.second;
6763 PreprocessedEntityID PPID =
6764 (static_cast<PreprocessedEntityID>(M.Index + 1) << 32) | LocalIndex;
6765 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
6766
6767 if (!PP.getPreprocessingRecord()) {
6768 Error("no preprocessing record");
6769 return nullptr;
6770 }
6771
6772 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
6773 if (llvm::Error Err = M.PreprocessorDetailCursor.JumpToBit(
6774 M.MacroOffsetsBase + PPOffs.getOffset())) {
6775 Error(std::move(Err));
6776 return nullptr;
6777 }
6778
6779 Expected<llvm::BitstreamEntry> MaybeEntry =
6780 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
6781 if (!MaybeEntry) {
6782 Error(MaybeEntry.takeError());
6783 return nullptr;
6784 }
6785 llvm::BitstreamEntry Entry = MaybeEntry.get();
6786
6787 if (Entry.Kind != llvm::BitstreamEntry::Record)
6788 return nullptr;
6789
6790 // Read the record.
6791 SourceRange Range(ReadSourceLocation(M, PPOffs.getBegin()),
6792 ReadSourceLocation(M, PPOffs.getEnd()));
6793 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
6794 StringRef Blob;
6795 RecordData Record;
6796 Expected<unsigned> MaybeRecType =
6797 M.PreprocessorDetailCursor.readRecord(Entry.ID, Record, &Blob);
6798 if (!MaybeRecType) {
6799 Error(MaybeRecType.takeError());
6800 return nullptr;
6801 }
6802 switch ((PreprocessorDetailRecordTypes)MaybeRecType.get()) {
6803 case PPD_MACRO_EXPANSION: {
6804 bool isBuiltin = Record[0];
6805 IdentifierInfo *Name = nullptr;
6806 MacroDefinitionRecord *Def = nullptr;
6807 if (isBuiltin)
6808 Name = getLocalIdentifier(M, Record[1]);
6809 else {
6810 PreprocessedEntityID GlobalID =
6811 getGlobalPreprocessedEntityID(M, Record[1]);
6812 unsigned Index = translatePreprocessedEntityIDToIndex(GlobalID);
6813 Def =
6814 cast<MacroDefinitionRecord>(PPRec.getLoadedPreprocessedEntity(Index));
6815 }
6816
6817 MacroExpansion *ME;
6818 if (isBuiltin)
6819 ME = new (PPRec) MacroExpansion(Name, Range);
6820 else
6821 ME = new (PPRec) MacroExpansion(Def, Range);
6822
6823 return ME;
6824 }
6825
6826 case PPD_MACRO_DEFINITION: {
6827 // Decode the identifier info and then check again; if the macro is
6828 // still defined and associated with the identifier,
6829 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
6830 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
6831
6832 if (DeserializationListener)
6833 DeserializationListener->MacroDefinitionRead(PPID, MD);
6834
6835 return MD;
6836 }
6837
6838 case PPD_INCLUSION_DIRECTIVE: {
6839 const char *FullFileNameStart = Blob.data() + Record[0];
6840 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
6841 OptionalFileEntryRef File;
6842 if (!FullFileName.empty())
6843 File = PP.getFileManager().getOptionalFileRef(FullFileName);
6844
6845 // FIXME: Stable encoding
6846 InclusionDirective::InclusionKind Kind
6847 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
6848 InclusionDirective *ID
6849 = new (PPRec) InclusionDirective(PPRec, Kind,
6850 StringRef(Blob.data(), Record[0]),
6851 Record[1], Record[3],
6852 File,
6853 Range);
6854 return ID;
6855 }
6856 }
6857
6858 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
6859 }
6860
6861 /// Find the next module that contains entities and return the ID
6862 /// of the first entry.
6863 ///
6864 /// \param SLocMapI points at a chunk of a module that contains no
6865 /// preprocessed entities or the entities it contains are not the ones we are
6866 /// looking for.
6867 unsigned ASTReader::findNextPreprocessedEntity(
6868 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
6869 ++SLocMapI;
6870 for (GlobalSLocOffsetMapType::const_iterator
6871 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
6872 ModuleFile &M = *SLocMapI->second;
6873 if (M.NumPreprocessedEntities)
6874 return M.BasePreprocessedEntityID;
6875 }
6876
6877 return getTotalNumPreprocessedEntities();
6878 }
6879
6880 namespace {
6881
6882 struct PPEntityComp {
6883 const ASTReader &Reader;
6884 ModuleFile &M;
6885
6886 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) {}
6887
6888 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
6889 SourceLocation LHS = getLoc(L);
6890 SourceLocation RHS = getLoc(R);
6891 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6892 }
6893
6894 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
6895 SourceLocation LHS = getLoc(L);
6896 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6897 }
6898
6899 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
6900 SourceLocation RHS = getLoc(R);
6901 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6902 }
6903
6904 SourceLocation getLoc(const PPEntityOffset &PPE) const {
6905 return Reader.ReadSourceLocation(M, PPE.getBegin());
6906 }
6907 };
6908
6909 } // namespace
6910
6911 unsigned ASTReader::findPreprocessedEntity(SourceLocation Loc,
6912 bool EndsAfter) const {
6913 if (SourceMgr.isLocalSourceLocation(Loc))
6914 return getTotalNumPreprocessedEntities();
6915
6916 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
6917 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
6918 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
6919 "Corrupted global sloc offset map");
6920
6921 if (SLocMapI->second->NumPreprocessedEntities == 0)
6922 return findNextPreprocessedEntity(SLocMapI);
6923
6924 ModuleFile &M = *SLocMapI->second;
6925
6926 using pp_iterator = const PPEntityOffset *;
6927
6928 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
6929 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
6930
6931 size_t Count = M.NumPreprocessedEntities;
6932 size_t Half;
6933 pp_iterator First = pp_begin;
6934 pp_iterator PPI;
6935
6936 if (EndsAfter) {
6937 PPI = std::upper_bound(pp_begin, pp_end, Loc,
6938 PPEntityComp(*this, M));
6939 } else {
6940 // Do a binary search manually instead of using std::lower_bound because
6941 // The end locations of entities may be unordered (when a macro expansion
6942 // is inside another macro argument), but for this case it is not important
6943 // whether we get the first macro expansion or its containing macro.
6944 while (Count > 0) {
6945 Half = Count / 2;
6946 PPI = First;
6947 std::advance(PPI, Half);
6948 if (SourceMgr.isBeforeInTranslationUnit(
6949 ReadSourceLocation(M, PPI->getEnd()), Loc)) {
6950 First = PPI;
6951 ++First;
6952 Count = Count - Half - 1;
6953 } else
6954 Count = Half;
6955 }
6956 }
6957
6958 if (PPI == pp_end)
6959 return findNextPreprocessedEntity(SLocMapI);
6960
6961 return M.BasePreprocessedEntityID + (PPI - pp_begin);
6962 }
6963
6964 /// Returns a pair of [Begin, End) indices of preallocated
6965 /// preprocessed entities that \arg Range encompasses.
6966 std::pair<unsigned, unsigned>
6967 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
6968 if (Range.isInvalid())
6969 return std::make_pair(0,0);
6970 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
6971
6972 unsigned BeginID = findPreprocessedEntity(Range.getBegin(), false);
6973 unsigned EndID = findPreprocessedEntity(Range.getEnd(), true);
6974 return std::make_pair(BeginID, EndID);
6975 }
6976
6977 /// Optionally returns true or false if the preallocated preprocessed
6978 /// entity with index \arg Index came from file \arg FID.
6979 std::optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
6980 FileID FID) {
6981 if (FID.isInvalid())
6982 return false;
6983
6984 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
6985 ModuleFile &M = *PPInfo.first;
6986 unsigned LocalIndex = PPInfo.second;
6987 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
6988
6989 SourceLocation Loc = ReadSourceLocation(M, PPOffs.getBegin());
6990 if (Loc.isInvalid())
6991 return false;
6992
6993 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
6994 return true;
6995 else
6996 return false;
6997 }
6998
6999 namespace {
7000
7001 /// Visitor used to search for information about a header file.
7002 class HeaderFileInfoVisitor {
7003 FileEntryRef FE;
7004 std::optional<HeaderFileInfo> HFI;
7005
7006 public:
7007 explicit HeaderFileInfoVisitor(FileEntryRef FE) : FE(FE) {}
7008
7009 bool operator()(ModuleFile &M) {
7010 HeaderFileInfoLookupTable *Table
7011 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
7012 if (!Table)
7013 return false;
7014
7015 // Look in the on-disk hash table for an entry for this file name.
7016 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
7017 if (Pos == Table->end())
7018 return false;
7019
7020 HFI = *Pos;
7021 return true;
7022 }
7023
7024 std::optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
7025 };
7026
7027 } // namespace
7028
7029 HeaderFileInfo ASTReader::GetHeaderFileInfo(FileEntryRef FE) {
7030 HeaderFileInfoVisitor Visitor(FE);
7031 ModuleMgr.visit(Visitor);
7032 if (std::optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
7033 return *HFI;
7034
7035 return HeaderFileInfo();
7036 }
7037
7038 void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
7039 using DiagState = DiagnosticsEngine::DiagState;
7040 SmallVector<DiagState *, 32> DiagStates;
7041
7042 for (ModuleFile &F : ModuleMgr) {
7043 unsigned Idx = 0;
7044 auto &Record = F.PragmaDiagMappings;
7045 if (Record.empty())
7046 continue;
7047
7048 DiagStates.clear();
7049
7050 auto ReadDiagState = [&](const DiagState &BasedOn,
7051 bool IncludeNonPragmaStates) {
7052 unsigned BackrefID = Record[Idx++];
7053 if (BackrefID != 0)
7054 return DiagStates[BackrefID - 1];
7055
7056 // A new DiagState was created here.
7057 Diag.DiagStates.push_back(BasedOn);
7058 DiagState *NewState = &Diag.DiagStates.back();
7059 DiagStates.push_back(NewState);
7060 unsigned Size = Record[Idx++];
7061 assert(Idx + Size * 2 <= Record.size() &&
7062 "Invalid data, not enough diag/map pairs");
7063 while (Size--) {
7064 unsigned DiagID = Record[Idx++];
7065 DiagnosticMapping NewMapping =
7066 DiagnosticMapping::deserialize(Record[Idx++]);
7067 if (!NewMapping.isPragma() && !IncludeNonPragmaStates)
7068 continue;
7069
7070 DiagnosticMapping &Mapping = NewState->getOrAddMapping(DiagID);
7071
7072 // If this mapping was specified as a warning but the severity was
7073 // upgraded due to diagnostic settings, simulate the current diagnostic
7074 // settings (and use a warning).
7075 if (NewMapping.wasUpgradedFromWarning() && !Mapping.isErrorOrFatal()) {
7076 NewMapping.setSeverity(diag::Severity::Warning);
7077 NewMapping.setUpgradedFromWarning(false);
7078 }
7079
7080 Mapping = NewMapping;
7081 }
7082 return NewState;
7083 };
7084
7085 // Read the first state.
7086 DiagState *FirstState;
7087 if (F.Kind == MK_ImplicitModule) {
7088 // Implicitly-built modules are reused with different diagnostic
7089 // settings. Use the initial diagnostic state from Diag to simulate this
7090 // compilation's diagnostic settings.
7091 FirstState = Diag.DiagStatesByLoc.FirstDiagState;
7092 DiagStates.push_back(FirstState);
7093
7094 // Skip the initial diagnostic state from the serialized module.
7095 assert(Record[1] == 0 &&
7096 "Invalid data, unexpected backref in initial state");
7097 Idx = 3 + Record[2] * 2;
7098 assert(Idx < Record.size() &&
7099 "Invalid data, not enough state change pairs in initial state");
7100 } else if (F.isModule()) {
7101 // For an explicit module, preserve the flags from the module build
7102 // command line (-w, -Weverything, -Werror, ...) along with any explicit
7103 // -Wblah flags.
7104 unsigned Flags = Record[Idx++];
7105 DiagState Initial(*Diag.getDiagnosticIDs());
7106 Initial.SuppressSystemWarnings = Flags & 1; Flags >>= 1;
7107 Initial.ErrorsAsFatal = Flags & 1; Flags >>= 1;
7108 Initial.WarningsAsErrors = Flags & 1; Flags >>= 1;
7109 Initial.EnableAllWarnings = Flags & 1; Flags >>= 1;
7110 Initial.IgnoreAllWarnings = Flags & 1; Flags >>= 1;
7111 Initial.ExtBehavior = (diag::Severity)Flags;
7112 FirstState = ReadDiagState(Initial, true);
7113
7114 assert(F.OriginalSourceFileID.isValid());
7115
7116 // Set up the root buffer of the module to start with the initial
7117 // diagnostic state of the module itself, to cover files that contain no
7118 // explicit transitions (for which we did not serialize anything).
7119 Diag.DiagStatesByLoc.Files[F.OriginalSourceFileID]
7120 .StateTransitions.push_back({FirstState, 0});
7121 } else {
7122 // For prefix ASTs, start with whatever the user configured on the
7123 // command line.
7124 Idx++; // Skip flags.
7125 FirstState = ReadDiagState(*Diag.DiagStatesByLoc.CurDiagState, false);
7126 }
7127
7128 // Read the state transitions.
7129 unsigned NumLocations = Record[Idx++];
7130 while (NumLocations--) {
7131 assert(Idx < Record.size() &&
7132 "Invalid data, missing pragma diagnostic states");
7133 FileID FID = ReadFileID(F, Record, Idx);
7134 assert(FID.isValid() && "invalid FileID for transition");
7135 unsigned Transitions = Record[Idx++];
7136
7137 // Note that we don't need to set up Parent/ParentOffset here, because
7138 // we won't be changing the diagnostic state within imported FileIDs
7139 // (other than perhaps appending to the main source file, which has no
7140 // parent).
7141 auto &F = Diag.DiagStatesByLoc.Files[FID];
7142 F.StateTransitions.reserve(F.StateTransitions.size() + Transitions);
7143 for (unsigned I = 0; I != Transitions; ++I) {
7144 unsigned Offset = Record[Idx++];
7145 auto *State = ReadDiagState(*FirstState, false);
7146 F.StateTransitions.push_back({State, Offset});
7147 }
7148 }
7149
7150 // Read the final state.
7151 assert(Idx < Record.size() &&
7152 "Invalid data, missing final pragma diagnostic state");
7153 SourceLocation CurStateLoc = ReadSourceLocation(F, Record[Idx++]);
7154 auto *CurState = ReadDiagState(*FirstState, false);
7155
7156 if (!F.isModule()) {
7157 Diag.DiagStatesByLoc.CurDiagState = CurState;
7158 Diag.DiagStatesByLoc.CurDiagStateLoc = CurStateLoc;
7159
7160 // Preserve the property that the imaginary root file describes the
7161 // current state.
7162 FileID NullFile;
7163 auto &T = Diag.DiagStatesByLoc.Files[NullFile].StateTransitions;
7164 if (T.empty())
7165 T.push_back({CurState, 0});
7166 else
7167 T[0].State = CurState;
7168 }
7169
7170 // Don't try to read these mappings again.
7171 Record.clear();
7172 }
7173 }
7174
7175 /// Get the correct cursor and offset for loading a type.
7176 ASTReader::RecordLocation ASTReader::TypeCursorForIndex(TypeID ID) {
7177 auto [M, Index] = translateTypeIDToIndex(ID);
7178 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex].get() +
7179 M->DeclsBlockStartOffset);
7180 }
7181
7182 static std::optional<Type::TypeClass> getTypeClassForCode(TypeCode code) {
7183 switch (code) {
7184 #define TYPE_BIT_CODE(CLASS_ID, CODE_ID, CODE_VALUE) \
7185 case TYPE_##CODE_ID: return Type::CLASS_ID;
7186 #include "clang/Serialization/TypeBitCodes.def"
7187 default:
7188 return std::nullopt;
7189 }
7190 }
7191
7192 /// Read and return the type with the given index..
7193 ///
7194 /// The index is the type ID, shifted and minus the number of predefs. This
7195 /// routine actually reads the record corresponding to the type at the given
7196 /// location. It is a helper routine for GetType, which deals with reading type
7197 /// IDs.
7198 QualType ASTReader::readTypeRecord(TypeID ID) {
7199 assert(ContextObj && "reading type with no AST context");
7200 ASTContext &Context = *ContextObj;
7201 RecordLocation Loc = TypeCursorForIndex(ID);
7202 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
7203
7204 // Keep track of where we are in the stream, then jump back there
7205 // after reading this type.
7206 SavedStreamPosition SavedPosition(DeclsCursor);
7207
7208 ReadingKindTracker ReadingKind(Read_Type, *this);
7209
7210 // Note that we are loading a type record.
7211 Deserializing AType(this);
7212
7213 if (llvm::Error Err = DeclsCursor.JumpToBit(Loc.Offset)) {
7214 Error(std::move(Err));
7215 return QualType();
7216 }
7217 Expected<unsigned> RawCode = DeclsCursor.ReadCode();
7218 if (!RawCode) {
7219 Error(RawCode.takeError());
7220 return QualType();
7221 }
7222
7223 ASTRecordReader Record(*this, *Loc.F);
7224 Expected<unsigned> Code = Record.readRecord(DeclsCursor, RawCode.get());
7225 if (!Code) {
7226 Error(Code.takeError());
7227 return QualType();
7228 }
7229 if (Code.get() == TYPE_EXT_QUAL) {
7230 QualType baseType = Record.readQualType();
7231 Qualifiers quals = Record.readQualifiers();
7232 return Context.getQualifiedType(baseType, quals);
7233 }
7234
7235 auto maybeClass = getTypeClassForCode((TypeCode) Code.get());
7236 if (!maybeClass) {
7237 Error("Unexpected code for type");
7238 return QualType();
7239 }
7240
7241 serialization::AbstractTypeReader<ASTRecordReader> TypeReader(Record);
7242 return TypeReader.read(*maybeClass);
7243 }
7244
7245 namespace clang {
7246
7247 class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
7248 ASTRecordReader &Reader;
7249
7250 SourceLocation readSourceLocation() { return Reader.readSourceLocation(); }
7251 SourceRange readSourceRange() { return Reader.readSourceRange(); }
7252
7253 TypeSourceInfo *GetTypeSourceInfo() {
7254 return Reader.readTypeSourceInfo();
7255 }
7256
7257 NestedNameSpecifierLoc ReadNestedNameSpecifierLoc() {
7258 return Reader.readNestedNameSpecifierLoc();
7259 }
7260
7261 Attr *ReadAttr() {
7262 return Reader.readAttr();
7263 }
7264
7265 public:
7266 TypeLocReader(ASTRecordReader &Reader) : Reader(Reader) {}
7267
7268 // We want compile-time assurance that we've enumerated all of
7269 // these, so unfortunately we have to declare them first, then
7270 // define them out-of-line.
7271 #define ABSTRACT_TYPELOC(CLASS, PARENT)
7272 #define TYPELOC(CLASS, PARENT) \
7273 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
7274 #include "clang/AST/TypeLocNodes.def"
7275
7276 void VisitFunctionTypeLoc(FunctionTypeLoc);
7277 void VisitArrayTypeLoc(ArrayTypeLoc);
7278 void VisitTagTypeLoc(TagTypeLoc TL);
7279 };
7280
7281 } // namespace clang
7282
7283 void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
7284 // nothing to do
7285 }
7286
7287 void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
7288 TL.setBuiltinLoc(readSourceLocation());
7289 if (TL.needsExtraLocalData()) {
7290 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Reader.readInt()));
7291 TL.setWrittenSignSpec(static_cast<TypeSpecifierSign>(Reader.readInt()));
7292 TL.setWrittenWidthSpec(static_cast<TypeSpecifierWidth>(Reader.readInt()));
7293 TL.setModeAttr(Reader.readInt());
7294 }
7295 }
7296
7297 void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
7298 TL.setNameLoc(readSourceLocation());
7299 }
7300
7301 void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
7302 TL.setStarLoc(readSourceLocation());
7303 }
7304
7305 void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
7306 // nothing to do
7307 }
7308
7309 void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
7310 // nothing to do
7311 }
7312
7313 void TypeLocReader::VisitArrayParameterTypeLoc(ArrayParameterTypeLoc TL) {
7314 // nothing to do
7315 }
7316
7317 void TypeLocReader::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
7318 TL.setExpansionLoc(readSourceLocation());
7319 }
7320
7321 void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
7322 TL.setCaretLoc(readSourceLocation());
7323 }
7324
7325 void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
7326 TL.setAmpLoc(readSourceLocation());
7327 }
7328
7329 void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
7330 TL.setAmpAmpLoc(readSourceLocation());
7331 }
7332
7333 void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
7334 TL.setStarLoc(readSourceLocation());
7335 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
7336 }
7337
7338 void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
7339 TL.setLBracketLoc(readSourceLocation());
7340 TL.setRBracketLoc(readSourceLocation());
7341 if (Reader.readBool())
7342 TL.setSizeExpr(Reader.readExpr());
7343 else
7344 TL.setSizeExpr(nullptr);
7345 }
7346
7347 void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
7348 VisitArrayTypeLoc(TL);
7349 }
7350
7351 void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
7352 VisitArrayTypeLoc(TL);
7353 }
7354
7355 void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
7356 VisitArrayTypeLoc(TL);
7357 }
7358
7359 void TypeLocReader::VisitDependentSizedArrayTypeLoc(
7360 DependentSizedArrayTypeLoc TL) {
7361 VisitArrayTypeLoc(TL);
7362 }
7363
7364 void TypeLocReader::VisitDependentAddressSpaceTypeLoc(
7365 DependentAddressSpaceTypeLoc TL) {
7366
7367 TL.setAttrNameLoc(readSourceLocation());
7368 TL.setAttrOperandParensRange(readSourceRange());
7369 TL.setAttrExprOperand(Reader.readExpr());
7370 }
7371
7372 void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
7373 DependentSizedExtVectorTypeLoc TL) {
7374 TL.setNameLoc(readSourceLocation());
7375 }
7376
7377 void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
7378 TL.setNameLoc(readSourceLocation());
7379 }
7380
7381 void TypeLocReader::VisitDependentVectorTypeLoc(
7382 DependentVectorTypeLoc TL) {
7383 TL.setNameLoc(readSourceLocation());
7384 }
7385
7386 void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
7387 TL.setNameLoc(readSourceLocation());
7388 }
7389
7390 void TypeLocReader::VisitConstantMatrixTypeLoc(ConstantMatrixTypeLoc TL) {
7391 TL.setAttrNameLoc(readSourceLocation());
7392 TL.setAttrOperandParensRange(readSourceRange());
7393 TL.setAttrRowOperand(Reader.readExpr());
7394 TL.setAttrColumnOperand(Reader.readExpr());
7395 }
7396
7397 void TypeLocReader::VisitDependentSizedMatrixTypeLoc(
7398 DependentSizedMatrixTypeLoc TL) {
7399 TL.setAttrNameLoc(readSourceLocation());
7400 TL.setAttrOperandParensRange(readSourceRange());
7401 TL.setAttrRowOperand(Reader.readExpr());
7402 TL.setAttrColumnOperand(Reader.readExpr());
7403 }
7404
7405 void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
7406 TL.setLocalRangeBegin(readSourceLocation());
7407 TL.setLParenLoc(readSourceLocation());
7408 TL.setRParenLoc(readSourceLocation());
7409 TL.setExceptionSpecRange(readSourceRange());
7410 TL.setLocalRangeEnd(readSourceLocation());
7411 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
7412 TL.setParam(i, Reader.readDeclAs<ParmVarDecl>());
7413 }
7414 }
7415
7416 void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
7417 VisitFunctionTypeLoc(TL);
7418 }
7419
7420 void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
7421 VisitFunctionTypeLoc(TL);
7422 }
7423
7424 void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
7425 SourceLocation ElaboratedKeywordLoc = readSourceLocation();
7426 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc();
7427 SourceLocation NameLoc = readSourceLocation();
7428 TL.set(ElaboratedKeywordLoc, QualifierLoc, NameLoc);
7429 }
7430
7431 void TypeLocReader::VisitUsingTypeLoc(UsingTypeLoc TL) {
7432 SourceLocation ElaboratedKeywordLoc = readSourceLocation();
7433 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc();
7434 SourceLocation NameLoc = readSourceLocation();
7435 TL.set(ElaboratedKeywordLoc, QualifierLoc, NameLoc);
7436 }
7437
7438 void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
7439 SourceLocation ElaboratedKeywordLoc = readSourceLocation();
7440 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc();
7441 SourceLocation NameLoc = readSourceLocation();
7442 TL.set(ElaboratedKeywordLoc, QualifierLoc, NameLoc);
7443 }
7444
7445 void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
7446 TL.setTypeofLoc(readSourceLocation());
7447 TL.setLParenLoc(readSourceLocation());
7448 TL.setRParenLoc(readSourceLocation());
7449 }
7450
7451 void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
7452 TL.setTypeofLoc(readSourceLocation());
7453 TL.setLParenLoc(readSourceLocation());
7454 TL.setRParenLoc(readSourceLocation());
7455 TL.setUnmodifiedTInfo(GetTypeSourceInfo());
7456 }
7457
7458 void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
7459 TL.setDecltypeLoc(readSourceLocation());
7460 TL.setRParenLoc(readSourceLocation());
7461 }
7462
7463 void TypeLocReader::VisitPackIndexingTypeLoc(PackIndexingTypeLoc TL) {
7464 TL.setEllipsisLoc(readSourceLocation());
7465 }
7466
7467 void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
7468 TL.setKWLoc(readSourceLocation());
7469 TL.setLParenLoc(readSourceLocation());
7470 TL.setRParenLoc(readSourceLocation());
7471 TL.setUnderlyingTInfo(GetTypeSourceInfo());
7472 }
7473
7474 ConceptReference *ASTRecordReader::readConceptReference() {
7475 auto NNS = readNestedNameSpecifierLoc();
7476 auto TemplateKWLoc = readSourceLocation();
7477 auto ConceptNameLoc = readDeclarationNameInfo();
7478 auto FoundDecl = readDeclAs<NamedDecl>();
7479 auto NamedConcept = readDeclAs<ConceptDecl>();
7480 auto *CR = ConceptReference::Create(
7481 getContext(), NNS, TemplateKWLoc, ConceptNameLoc, FoundDecl, NamedConcept,
7482 (readBool() ? readASTTemplateArgumentListInfo() : nullptr));
7483 return CR;
7484 }
7485
7486 void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
7487 TL.setNameLoc(readSourceLocation());
7488 if (Reader.readBool())
7489 TL.setConceptReference(Reader.readConceptReference());
7490 if (Reader.readBool())
7491 TL.setRParenLoc(readSourceLocation());
7492 }
7493
7494 void TypeLocReader::VisitDeducedTemplateSpecializationTypeLoc(
7495 DeducedTemplateSpecializationTypeLoc TL) {
7496 TL.setElaboratedKeywordLoc(readSourceLocation());
7497 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
7498 TL.setTemplateNameLoc(readSourceLocation());
7499 }
7500
7501 void TypeLocReader::VisitTagTypeLoc(TagTypeLoc TL) {
7502 TL.setElaboratedKeywordLoc(readSourceLocation());
7503 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
7504 TL.setNameLoc(readSourceLocation());
7505 }
7506
7507 void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
7508 VisitTagTypeLoc(TL);
7509 }
7510
7511 void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
7512 VisitTagTypeLoc(TL);
7513 }
7514
7515 void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) { VisitTagTypeLoc(TL); }
7516
7517 void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
7518 TL.setAttr(ReadAttr());
7519 }
7520
7521 void TypeLocReader::VisitCountAttributedTypeLoc(CountAttributedTypeLoc TL) {
7522 // Nothing to do
7523 }
7524
7525 void TypeLocReader::VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) {
7526 // Nothing to do.
7527 }
7528
7529 void TypeLocReader::VisitHLSLAttributedResourceTypeLoc(
7530 HLSLAttributedResourceTypeLoc TL) {
7531 // Nothing to do.
7532 }
7533
7534 void TypeLocReader::VisitHLSLInlineSpirvTypeLoc(HLSLInlineSpirvTypeLoc TL) {
7535 // Nothing to do.
7536 }
7537
7538 void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
7539 TL.setNameLoc(readSourceLocation());
7540 }
7541
7542 void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
7543 SubstTemplateTypeParmTypeLoc TL) {
7544 TL.setNameLoc(readSourceLocation());
7545 }
7546
7547 void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
7548 SubstTemplateTypeParmPackTypeLoc TL) {
7549 TL.setNameLoc(readSourceLocation());
7550 }
7551
7552 void TypeLocReader::VisitSubstBuiltinTemplatePackTypeLoc(
7553 SubstBuiltinTemplatePackTypeLoc TL) {
7554 TL.setNameLoc(readSourceLocation());
7555 }
7556
7557 void TypeLocReader::VisitTemplateSpecializationTypeLoc(
7558 TemplateSpecializationTypeLoc TL) {
7559 SourceLocation ElaboratedKeywordLoc = readSourceLocation();
7560 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc();
7561 SourceLocation TemplateKeywordLoc = readSourceLocation();
7562 SourceLocation NameLoc = readSourceLocation();
7563 SourceLocation LAngleLoc = readSourceLocation();
7564 SourceLocation RAngleLoc = readSourceLocation();
7565 TL.set(ElaboratedKeywordLoc, QualifierLoc, TemplateKeywordLoc, NameLoc,
7566 LAngleLoc, RAngleLoc);
7567 MutableArrayRef<TemplateArgumentLocInfo> Args = TL.getArgLocInfos();
7568 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
7569 Args[I] = Reader.readTemplateArgumentLocInfo(
7570 TL.getTypePtr()->template_arguments()[I].getKind());
7571 }
7572
7573 void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
7574 TL.setLParenLoc(readSourceLocation());
7575 TL.setRParenLoc(readSourceLocation());
7576 }
7577
7578 void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
7579 TL.setElaboratedKeywordLoc(readSourceLocation());
7580 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
7581 TL.setNameLoc(readSourceLocation());
7582 }
7583
7584 void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
7585 TL.setEllipsisLoc(readSourceLocation());
7586 }
7587
7588 void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
7589 TL.setNameLoc(readSourceLocation());
7590 TL.setNameEndLoc(readSourceLocation());
7591 }
7592
7593 void TypeLocReader::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
7594 if (TL.getNumProtocols()) {
7595 TL.setProtocolLAngleLoc(readSourceLocation());
7596 TL.setProtocolRAngleLoc(readSourceLocation());
7597 }
7598 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
7599 TL.setProtocolLoc(i, readSourceLocation());
7600 }
7601
7602 void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
7603 TL.setHasBaseTypeAsWritten(Reader.readBool());
7604 TL.setTypeArgsLAngleLoc(readSourceLocation());
7605 TL.setTypeArgsRAngleLoc(readSourceLocation());
7606 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
7607 TL.setTypeArgTInfo(i, GetTypeSourceInfo());
7608 TL.setProtocolLAngleLoc(readSourceLocation());
7609 TL.setProtocolRAngleLoc(readSourceLocation());
7610 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
7611 TL.setProtocolLoc(i, readSourceLocation());
7612 }
7613
7614 void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
7615 TL.setStarLoc(readSourceLocation());
7616 }
7617
7618 void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
7619 TL.setKWLoc(readSourceLocation());
7620 TL.setLParenLoc(readSourceLocation());
7621 TL.setRParenLoc(readSourceLocation());
7622 }
7623
7624 void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) {
7625 TL.setKWLoc(readSourceLocation());
7626 }
7627
7628 void TypeLocReader::VisitBitIntTypeLoc(clang::BitIntTypeLoc TL) {
7629 TL.setNameLoc(readSourceLocation());
7630 }
7631
7632 void TypeLocReader::VisitDependentBitIntTypeLoc(
7633 clang::DependentBitIntTypeLoc TL) {
7634 TL.setNameLoc(readSourceLocation());
7635 }
7636
7637 void TypeLocReader::VisitPredefinedSugarTypeLoc(PredefinedSugarTypeLoc TL) {
7638 // Nothing to do.
7639 }
7640
7641 void ASTRecordReader::readTypeLoc(TypeLoc TL) {
7642 TypeLocReader TLR(*this);
7643 for (; !TL.isNull(); TL = TL.getNextTypeLoc())
7644 TLR.Visit(TL);
7645 }
7646
7647 TypeSourceInfo *ASTRecordReader::readTypeSourceInfo() {
7648 QualType InfoTy = readType();
7649 if (InfoTy.isNull())
7650 return nullptr;
7651
7652 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
7653 readTypeLoc(TInfo->getTypeLoc());
7654 return TInfo;
7655 }
7656
7657 static unsigned getIndexForTypeID(serialization::TypeID ID) {
7658 return (ID & llvm::maskTrailingOnes<TypeID>(32)) >> Qualifiers::FastWidth;
7659 }
7660
7661 static unsigned getModuleFileIndexForTypeID(serialization::TypeID ID) {
7662 return ID >> 32;
7663 }
7664
7665 static bool isPredefinedType(serialization::TypeID ID) {
7666 // We don't need to erase the higher bits since if these bits are not 0,
7667 // it must be larger than NUM_PREDEF_TYPE_IDS.
7668 return (ID >> Qualifiers::FastWidth) < NUM_PREDEF_TYPE_IDS;
7669 }
7670
7671 std::pair<ModuleFile *, unsigned>
7672 ASTReader::translateTypeIDToIndex(serialization::TypeID ID) const {
7673 assert(!isPredefinedType(ID) &&
7674 "Predefined type shouldn't be in TypesLoaded");
7675 unsigned ModuleFileIndex = getModuleFileIndexForTypeID(ID);
7676 assert(ModuleFileIndex && "Untranslated Local Decl?");
7677
7678 ModuleFile *OwningModuleFile = &getModuleManager()[ModuleFileIndex - 1];
7679 assert(OwningModuleFile &&
7680 "untranslated type ID or local type ID shouldn't be in TypesLoaded");
7681
7682 return {OwningModuleFile,
7683 OwningModuleFile->BaseTypeIndex + getIndexForTypeID(ID)};
7684 }
7685
7686 QualType ASTReader::GetType(TypeID ID) {
7687 assert(ContextObj && "reading type with no AST context");
7688 ASTContext &Context = *ContextObj;
7689
7690 unsigned FastQuals = ID & Qualifiers::FastMask;
7691
7692 if (isPredefinedType(ID)) {
7693 QualType T;
7694 unsigned Index = getIndexForTypeID(ID);
7695 switch ((PredefinedTypeIDs)Index) {
7696 case PREDEF_TYPE_LAST_ID:
7697 // We should never use this one.
7698 llvm_unreachable("Invalid predefined type");
7699 break;
7700 case PREDEF_TYPE_NULL_ID:
7701 return QualType();
7702 case PREDEF_TYPE_VOID_ID:
7703 T = Context.VoidTy;
7704 break;
7705 case PREDEF_TYPE_BOOL_ID:
7706 T = Context.BoolTy;
7707 break;
7708 case PREDEF_TYPE_CHAR_U_ID:
7709 case PREDEF_TYPE_CHAR_S_ID:
7710 // FIXME: Check that the signedness of CharTy is correct!
7711 T = Context.CharTy;
7712 break;
7713 case PREDEF_TYPE_UCHAR_ID:
7714 T = Context.UnsignedCharTy;
7715 break;
7716 case PREDEF_TYPE_USHORT_ID:
7717 T = Context.UnsignedShortTy;
7718 break;
7719 case PREDEF_TYPE_UINT_ID:
7720 T = Context.UnsignedIntTy;
7721 break;
7722 case PREDEF_TYPE_ULONG_ID:
7723 T = Context.UnsignedLongTy;
7724 break;
7725 case PREDEF_TYPE_ULONGLONG_ID:
7726 T = Context.UnsignedLongLongTy;
7727 break;
7728 case PREDEF_TYPE_UINT128_ID:
7729 T = Context.UnsignedInt128Ty;
7730 break;
7731 case PREDEF_TYPE_SCHAR_ID:
7732 T = Context.SignedCharTy;
7733 break;
7734 case PREDEF_TYPE_WCHAR_ID:
7735 T = Context.WCharTy;
7736 break;
7737 case PREDEF_TYPE_SHORT_ID:
7738 T = Context.ShortTy;
7739 break;
7740 case PREDEF_TYPE_INT_ID:
7741 T = Context.IntTy;
7742 break;
7743 case PREDEF_TYPE_LONG_ID:
7744 T = Context.LongTy;
7745 break;
7746 case PREDEF_TYPE_LONGLONG_ID:
7747 T = Context.LongLongTy;
7748 break;
7749 case PREDEF_TYPE_INT128_ID:
7750 T = Context.Int128Ty;
7751 break;
7752 case PREDEF_TYPE_BFLOAT16_ID:
7753 T = Context.BFloat16Ty;
7754 break;
7755 case PREDEF_TYPE_HALF_ID:
7756 T = Context.HalfTy;
7757 break;
7758 case PREDEF_TYPE_FLOAT_ID:
7759 T = Context.FloatTy;
7760 break;
7761 case PREDEF_TYPE_DOUBLE_ID:
7762 T = Context.DoubleTy;
7763 break;
7764 case PREDEF_TYPE_LONGDOUBLE_ID:
7765 T = Context.LongDoubleTy;
7766 break;
7767 case PREDEF_TYPE_SHORT_ACCUM_ID:
7768 T = Context.ShortAccumTy;
7769 break;
7770 case PREDEF_TYPE_ACCUM_ID:
7771 T = Context.AccumTy;
7772 break;
7773 case PREDEF_TYPE_LONG_ACCUM_ID:
7774 T = Context.LongAccumTy;
7775 break;
7776 case PREDEF_TYPE_USHORT_ACCUM_ID:
7777 T = Context.UnsignedShortAccumTy;
7778 break;
7779 case PREDEF_TYPE_UACCUM_ID:
7780 T = Context.UnsignedAccumTy;
7781 break;
7782 case PREDEF_TYPE_ULONG_ACCUM_ID:
7783 T = Context.UnsignedLongAccumTy;
7784 break;
7785 case PREDEF_TYPE_SHORT_FRACT_ID:
7786 T = Context.ShortFractTy;
7787 break;
7788 case PREDEF_TYPE_FRACT_ID:
7789 T = Context.FractTy;
7790 break;
7791 case PREDEF_TYPE_LONG_FRACT_ID:
7792 T = Context.LongFractTy;
7793 break;
7794 case PREDEF_TYPE_USHORT_FRACT_ID:
7795 T = Context.UnsignedShortFractTy;
7796 break;
7797 case PREDEF_TYPE_UFRACT_ID:
7798 T = Context.UnsignedFractTy;
7799 break;
7800 case PREDEF_TYPE_ULONG_FRACT_ID:
7801 T = Context.UnsignedLongFractTy;
7802 break;
7803 case PREDEF_TYPE_SAT_SHORT_ACCUM_ID:
7804 T = Context.SatShortAccumTy;
7805 break;
7806 case PREDEF_TYPE_SAT_ACCUM_ID:
7807 T = Context.SatAccumTy;
7808 break;
7809 case PREDEF_TYPE_SAT_LONG_ACCUM_ID:
7810 T = Context.SatLongAccumTy;
7811 break;
7812 case PREDEF_TYPE_SAT_USHORT_ACCUM_ID:
7813 T = Context.SatUnsignedShortAccumTy;
7814 break;
7815 case PREDEF_TYPE_SAT_UACCUM_ID:
7816 T = Context.SatUnsignedAccumTy;
7817 break;
7818 case PREDEF_TYPE_SAT_ULONG_ACCUM_ID:
7819 T = Context.SatUnsignedLongAccumTy;
7820 break;
7821 case PREDEF_TYPE_SAT_SHORT_FRACT_ID:
7822 T = Context.SatShortFractTy;
7823 break;
7824 case PREDEF_TYPE_SAT_FRACT_ID:
7825 T = Context.SatFractTy;
7826 break;
7827 case PREDEF_TYPE_SAT_LONG_FRACT_ID:
7828 T = Context.SatLongFractTy;
7829 break;
7830 case PREDEF_TYPE_SAT_USHORT_FRACT_ID:
7831 T = Context.SatUnsignedShortFractTy;
7832 break;
7833 case PREDEF_TYPE_SAT_UFRACT_ID:
7834 T = Context.SatUnsignedFractTy;
7835 break;
7836 case PREDEF_TYPE_SAT_ULONG_FRACT_ID:
7837 T = Context.SatUnsignedLongFractTy;
7838 break;
7839 case PREDEF_TYPE_FLOAT16_ID:
7840 T = Context.Float16Ty;
7841 break;
7842 case PREDEF_TYPE_FLOAT128_ID:
7843 T = Context.Float128Ty;
7844 break;
7845 case PREDEF_TYPE_IBM128_ID:
7846 T = Context.Ibm128Ty;
7847 break;
7848 case PREDEF_TYPE_OVERLOAD_ID:
7849 T = Context.OverloadTy;
7850 break;
7851 case PREDEF_TYPE_UNRESOLVED_TEMPLATE:
7852 T = Context.UnresolvedTemplateTy;
7853 break;
7854 case PREDEF_TYPE_BOUND_MEMBER:
7855 T = Context.BoundMemberTy;
7856 break;
7857 case PREDEF_TYPE_PSEUDO_OBJECT:
7858 T = Context.PseudoObjectTy;
7859 break;
7860 case PREDEF_TYPE_DEPENDENT_ID:
7861 T = Context.DependentTy;
7862 break;
7863 case PREDEF_TYPE_UNKNOWN_ANY:
7864 T = Context.UnknownAnyTy;
7865 break;
7866 case PREDEF_TYPE_NULLPTR_ID:
7867 T = Context.NullPtrTy;
7868 break;
7869 case PREDEF_TYPE_CHAR8_ID:
7870 T = Context.Char8Ty;
7871 break;
7872 case PREDEF_TYPE_CHAR16_ID:
7873 T = Context.Char16Ty;
7874 break;
7875 case PREDEF_TYPE_CHAR32_ID:
7876 T = Context.Char32Ty;
7877 break;
7878 case PREDEF_TYPE_OBJC_ID:
7879 T = Context.ObjCBuiltinIdTy;
7880 break;
7881 case PREDEF_TYPE_OBJC_CLASS:
7882 T = Context.ObjCBuiltinClassTy;
7883 break;
7884 case PREDEF_TYPE_OBJC_SEL:
7885 T = Context.ObjCBuiltinSelTy;
7886 break;
7887 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7888 case PREDEF_TYPE_##Id##_ID: \
7889 T = Context.SingletonId; \
7890 break;
7891 #include "clang/Basic/OpenCLImageTypes.def"
7892 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
7893 case PREDEF_TYPE_##Id##_ID: \
7894 T = Context.Id##Ty; \
7895 break;
7896 #include "clang/Basic/OpenCLExtensionTypes.def"
7897 case PREDEF_TYPE_SAMPLER_ID:
7898 T = Context.OCLSamplerTy;
7899 break;
7900 case PREDEF_TYPE_EVENT_ID:
7901 T = Context.OCLEventTy;
7902 break;
7903 case PREDEF_TYPE_CLK_EVENT_ID:
7904 T = Context.OCLClkEventTy;
7905 break;
7906 case PREDEF_TYPE_QUEUE_ID:
7907 T = Context.OCLQueueTy;
7908 break;
7909 case PREDEF_TYPE_RESERVE_ID_ID:
7910 T = Context.OCLReserveIDTy;
7911 break;
7912 case PREDEF_TYPE_AUTO_DEDUCT:
7913 T = Context.getAutoDeductType();
7914 break;
7915 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
7916 T = Context.getAutoRRefDeductType();
7917 break;
7918 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
7919 T = Context.ARCUnbridgedCastTy;
7920 break;
7921 case PREDEF_TYPE_BUILTIN_FN:
7922 T = Context.BuiltinFnTy;
7923 break;
7924 case PREDEF_TYPE_INCOMPLETE_MATRIX_IDX:
7925 T = Context.IncompleteMatrixIdxTy;
7926 break;
7927 case PREDEF_TYPE_ARRAY_SECTION:
7928 T = Context.ArraySectionTy;
7929 break;
7930 case PREDEF_TYPE_OMP_ARRAY_SHAPING:
7931 T = Context.OMPArrayShapingTy;
7932 break;
7933 case PREDEF_TYPE_OMP_ITERATOR:
7934 T = Context.OMPIteratorTy;
7935 break;
7936 #define SVE_TYPE(Name, Id, SingletonId) \
7937 case PREDEF_TYPE_##Id##_ID: \
7938 T = Context.SingletonId; \
7939 break;
7940 #include "clang/Basic/AArch64ACLETypes.def"
7941 #define PPC_VECTOR_TYPE(Name, Id, Size) \
7942 case PREDEF_TYPE_##Id##_ID: \
7943 T = Context.Id##Ty; \
7944 break;
7945 #include "clang/Basic/PPCTypes.def"
7946 #define RVV_TYPE(Name, Id, SingletonId) \
7947 case PREDEF_TYPE_##Id##_ID: \
7948 T = Context.SingletonId; \
7949 break;
7950 #include "clang/Basic/RISCVVTypes.def"
7951 #define WASM_TYPE(Name, Id, SingletonId) \
7952 case PREDEF_TYPE_##Id##_ID: \
7953 T = Context.SingletonId; \
7954 break;
7955 #include "clang/Basic/WebAssemblyReferenceTypes.def"
7956 #define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) \
7957 case PREDEF_TYPE_##Id##_ID: \
7958 T = Context.SingletonId; \
7959 break;
7960 #include "clang/Basic/AMDGPUTypes.def"
7961 #define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
7962 case PREDEF_TYPE_##Id##_ID: \
7963 T = Context.SingletonId; \
7964 break;
7965 #include "clang/Basic/HLSLIntangibleTypes.def"
7966 }
7967
7968 assert(!T.isNull() && "Unknown predefined type");
7969 return T.withFastQualifiers(FastQuals);
7970 }
7971
7972 unsigned Index = translateTypeIDToIndex(ID).second;
7973
7974 assert(Index < TypesLoaded.size() && "Type index out-of-range");
7975 if (TypesLoaded[Index].isNull()) {
7976 TypesLoaded[Index] = readTypeRecord(ID);
7977 if (TypesLoaded[Index].isNull())
7978 return QualType();
7979
7980 TypesLoaded[Index]->setFromAST();
7981 if (DeserializationListener)
7982 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
7983 TypesLoaded[Index]);
7984 }
7985
7986 return TypesLoaded[Index].withFastQualifiers(FastQuals);
7987 }
7988
7989 QualType ASTReader::getLocalType(ModuleFile &F, LocalTypeID LocalID) {
7990 return GetType(getGlobalTypeID(F, LocalID));
7991 }
7992
7993 serialization::TypeID ASTReader::getGlobalTypeID(ModuleFile &F,
7994 LocalTypeID LocalID) const {
7995 if (isPredefinedType(LocalID))
7996 return LocalID;
7997
7998 if (!F.ModuleOffsetMap.empty())
7999 ReadModuleOffsetMap(F);
8000
8001 unsigned ModuleFileIndex = getModuleFileIndexForTypeID(LocalID);
8002 LocalID &= llvm::maskTrailingOnes<TypeID>(32);
8003
8004 if (ModuleFileIndex == 0)
8005 LocalID -= NUM_PREDEF_TYPE_IDS << Qualifiers::FastWidth;
8006
8007 ModuleFile &MF =
8008 ModuleFileIndex ? *F.TransitiveImports[ModuleFileIndex - 1] : F;
8009 ModuleFileIndex = MF.Index + 1;
8010 return ((uint64_t)ModuleFileIndex << 32) | LocalID;
8011 }
8012
8013 TemplateArgumentLocInfo
8014 ASTRecordReader::readTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind) {
8015 switch (Kind) {
8016 case TemplateArgument::Expression:
8017 return readExpr();
8018 case TemplateArgument::Type:
8019 return readTypeSourceInfo();
8020 case TemplateArgument::Template:
8021 case TemplateArgument::TemplateExpansion: {
8022 SourceLocation TemplateKWLoc = readSourceLocation();
8023 NestedNameSpecifierLoc QualifierLoc = readNestedNameSpecifierLoc();
8024 SourceLocation TemplateNameLoc = readSourceLocation();
8025 SourceLocation EllipsisLoc = Kind == TemplateArgument::TemplateExpansion
8026 ? readSourceLocation()
8027 : SourceLocation();
8028 return TemplateArgumentLocInfo(getASTContext(), TemplateKWLoc, QualifierLoc,
8029 TemplateNameLoc, EllipsisLoc);
8030 }
8031 case TemplateArgument::Null:
8032 case TemplateArgument::Integral:
8033 case TemplateArgument::Declaration:
8034 case TemplateArgument::NullPtr:
8035 case TemplateArgument::StructuralValue:
8036 case TemplateArgument::Pack:
8037 // FIXME: Is this right?
8038 return TemplateArgumentLocInfo();
8039 }
8040 llvm_unreachable("unexpected template argument loc");
8041 }
8042
8043 TemplateArgumentLoc ASTRecordReader::readTemplateArgumentLoc() {
8044 TemplateArgument Arg = readTemplateArgument();
8045
8046 if (Arg.getKind() == TemplateArgument::Expression) {
8047 if (readBool()) // bool InfoHasSameExpr.
8048 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
8049 }
8050 return TemplateArgumentLoc(Arg, readTemplateArgumentLocInfo(Arg.getKind()));
8051 }
8052
8053 void ASTRecordReader::readTemplateArgumentListInfo(
8054 TemplateArgumentListInfo &Result) {
8055 Result.setLAngleLoc(readSourceLocation());
8056 Result.setRAngleLoc(readSourceLocation());
8057 unsigned NumArgsAsWritten = readInt();
8058 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
8059 Result.addArgument(readTemplateArgumentLoc());
8060 }
8061
8062 const ASTTemplateArgumentListInfo *
8063 ASTRecordReader::readASTTemplateArgumentListInfo() {
8064 TemplateArgumentListInfo Result;
8065 readTemplateArgumentListInfo(Result);
8066 return ASTTemplateArgumentListInfo::Create(getContext(), Result);
8067 }
8068
8069 Decl *ASTReader::GetExternalDecl(GlobalDeclID ID) { return GetDecl(ID); }
8070
8071 void ASTReader::CompleteRedeclChain(const Decl *D) {
8072 if (NumCurrentElementsDeserializing) {
8073 // We arrange to not care about the complete redeclaration chain while we're
8074 // deserializing. Just remember that the AST has marked this one as complete
8075 // but that it's not actually complete yet, so we know we still need to
8076 // complete it later.
8077 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
8078 return;
8079 }
8080
8081 if (!D->getDeclContext()) {
8082 assert(isa<TranslationUnitDecl>(D) && "Not a TU?");
8083 return;
8084 }
8085
8086 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
8087
8088 // If this is a named declaration, complete it by looking it up
8089 // within its context.
8090 //
8091 // FIXME: Merging a function definition should merge
8092 // all mergeable entities within it.
8093 if (isa<TranslationUnitDecl, NamespaceDecl, RecordDecl, EnumDecl>(DC)) {
8094 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
8095 if (!getContext().getLangOpts().CPlusPlus &&
8096 isa<TranslationUnitDecl>(DC)) {
8097 // Outside of C++, we don't have a lookup table for the TU, so update
8098 // the identifier instead. (For C++ modules, we don't store decls
8099 // in the serialized identifier table, so we do the lookup in the TU.)
8100 auto *II = Name.getAsIdentifierInfo();
8101 assert(II && "non-identifier name in C?");
8102 if (II->isOutOfDate())
8103 updateOutOfDateIdentifier(*II);
8104 } else
8105 DC->lookup(Name);
8106 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
8107 // Find all declarations of this kind from the relevant context.
8108 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
8109 auto *DC = cast<DeclContext>(DCDecl);
8110 SmallVector<Decl*, 8> Decls;
8111 FindExternalLexicalDecls(
8112 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
8113 }
8114 }
8115 }
8116
8117 RedeclarableTemplateDecl *Template = nullptr;
8118 ArrayRef<TemplateArgument> Args;
8119 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
8120 Template = CTSD->getSpecializedTemplate();
8121 Args = CTSD->getTemplateArgs().asArray();
8122 } else if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D)) {
8123 Template = VTSD->getSpecializedTemplate();
8124 Args = VTSD->getTemplateArgs().asArray();
8125 } else if (auto *FD = dyn_cast<FunctionDecl>(D)) {
8126 if (auto *Tmplt = FD->getPrimaryTemplate()) {
8127 Template = Tmplt;
8128 Args = FD->getTemplateSpecializationArgs()->asArray();
8129 }
8130 }
8131
8132 if (Template) {
8133 // For partitial specialization, load all the specializations for safety.
8134 if (isa<ClassTemplatePartialSpecializationDecl,
8135 VarTemplatePartialSpecializationDecl>(D))
8136 Template->loadLazySpecializationsImpl();
8137 else
8138 Template->loadLazySpecializationsImpl(Args);
8139 }
8140 }
8141
8142 CXXCtorInitializer **
8143 ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
8144 RecordLocation Loc = getLocalBitOffset(Offset);
8145 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
8146 SavedStreamPosition SavedPosition(Cursor);
8147 if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {
8148 Error(std::move(Err));
8149 return nullptr;
8150 }
8151 ReadingKindTracker ReadingKind(Read_Decl, *this);
8152 Deserializing D(this);
8153
8154 Expected<unsigned> MaybeCode = Cursor.ReadCode();
8155 if (!MaybeCode) {
8156 Error(MaybeCode.takeError());
8157 return nullptr;
8158 }
8159 unsigned Code = MaybeCode.get();
8160
8161 ASTRecordReader Record(*this, *Loc.F);
8162 Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code);
8163 if (!MaybeRecCode) {
8164 Error(MaybeRecCode.takeError());
8165 return nullptr;
8166 }
8167 if (MaybeRecCode.get() != DECL_CXX_CTOR_INITIALIZERS) {
8168 Error("malformed AST file: missing C++ ctor initializers");
8169 return nullptr;
8170 }
8171
8172 return Record.readCXXCtorInitializers();
8173 }
8174
8175 CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
8176 assert(ContextObj && "reading base specifiers with no AST context");
8177 ASTContext &Context = *ContextObj;
8178
8179 RecordLocation Loc = getLocalBitOffset(Offset);
8180 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
8181 SavedStreamPosition SavedPosition(Cursor);
8182 if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {
8183 Error(std::move(Err));
8184 return nullptr;
8185 }
8186 ReadingKindTracker ReadingKind(Read_Decl, *this);
8187 Deserializing D(this);
8188
8189 Expected<unsigned> MaybeCode = Cursor.ReadCode();
8190 if (!MaybeCode) {
8191 Error(MaybeCode.takeError());
8192 return nullptr;
8193 }
8194 unsigned Code = MaybeCode.get();
8195
8196 ASTRecordReader Record(*this, *Loc.F);
8197 Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code);
8198 if (!MaybeRecCode) {
8199 Error(MaybeCode.takeError());
8200 return nullptr;
8201 }
8202 unsigned RecCode = MaybeRecCode.get();
8203
8204 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
8205 Error("malformed AST file: missing C++ base specifiers");
8206 return nullptr;
8207 }
8208
8209 unsigned NumBases = Record.readInt();
8210 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
8211 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
8212 for (unsigned I = 0; I != NumBases; ++I)
8213 Bases[I] = Record.readCXXBaseSpecifier();
8214 return Bases;
8215 }
8216
8217 GlobalDeclID ASTReader::getGlobalDeclID(ModuleFile &F,
8218 LocalDeclID LocalID) const {
8219 if (LocalID < NUM_PREDEF_DECL_IDS)
8220 return GlobalDeclID(LocalID.getRawValue());
8221
8222 unsigned OwningModuleFileIndex = LocalID.getModuleFileIndex();
8223 DeclID ID = LocalID.getLocalDeclIndex();
8224
8225 if (!F.ModuleOffsetMap.empty())
8226 ReadModuleOffsetMap(F);
8227
8228 ModuleFile *OwningModuleFile =
8229 OwningModuleFileIndex == 0
8230 ? &F
8231 : F.TransitiveImports[OwningModuleFileIndex - 1];
8232
8233 if (OwningModuleFileIndex == 0)
8234 ID -= NUM_PREDEF_DECL_IDS;
8235
8236 uint64_t NewModuleFileIndex = OwningModuleFile->Index + 1;
8237 return GlobalDeclID(NewModuleFileIndex, ID);
8238 }
8239
8240 bool ASTReader::isDeclIDFromModule(GlobalDeclID ID, ModuleFile &M) const {
8241 // Predefined decls aren't from any module.
8242 if (ID < NUM_PREDEF_DECL_IDS)
8243 return false;
8244
8245 unsigned ModuleFileIndex = ID.getModuleFileIndex();
8246 return M.Index == ModuleFileIndex - 1;
8247 }
8248
8249 ModuleFile *ASTReader::getOwningModuleFile(GlobalDeclID ID) const {
8250 // Predefined decls aren't from any module.
8251 if (ID < NUM_PREDEF_DECL_IDS)
8252 return nullptr;
8253
8254 uint64_t ModuleFileIndex = ID.getModuleFileIndex();
8255 assert(ModuleFileIndex && "Untranslated Local Decl?");
8256
8257 return &getModuleManager()[ModuleFileIndex - 1];
8258 }
8259
8260 ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) const {
8261 if (!D->isFromASTFile())
8262 return nullptr;
8263
8264 return getOwningModuleFile(D->getGlobalID());
8265 }
8266
8267 SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
8268 if (ID < NUM_PREDEF_DECL_IDS)
8269 return SourceLocation();
8270
8271 if (Decl *D = GetExistingDecl(ID))
8272 return D->getLocation();
8273
8274 SourceLocation Loc;
8275 DeclCursorForID(ID, Loc);
8276 return Loc;
8277 }
8278
8279 Decl *ASTReader::getPredefinedDecl(PredefinedDeclIDs ID) {
8280 assert(ContextObj && "reading predefined decl without AST context");
8281 ASTContext &Context = *ContextObj;
8282 Decl *NewLoaded = nullptr;
8283 switch (ID) {
8284 case PREDEF_DECL_NULL_ID:
8285 return nullptr;
8286
8287 case PREDEF_DECL_TRANSLATION_UNIT_ID:
8288 return Context.getTranslationUnitDecl();
8289
8290 case PREDEF_DECL_OBJC_ID_ID:
8291 if (Context.ObjCIdDecl)
8292 return Context.ObjCIdDecl;
8293 NewLoaded = Context.getObjCIdDecl();
8294 break;
8295
8296 case PREDEF_DECL_OBJC_SEL_ID:
8297 if (Context.ObjCSelDecl)
8298 return Context.ObjCSelDecl;
8299 NewLoaded = Context.getObjCSelDecl();
8300 break;
8301
8302 case PREDEF_DECL_OBJC_CLASS_ID:
8303 if (Context.ObjCClassDecl)
8304 return Context.ObjCClassDecl;
8305 NewLoaded = Context.getObjCClassDecl();
8306 break;
8307
8308 case PREDEF_DECL_OBJC_PROTOCOL_ID:
8309 if (Context.ObjCProtocolClassDecl)
8310 return Context.ObjCProtocolClassDecl;
8311 NewLoaded = Context.getObjCProtocolDecl();
8312 break;
8313
8314 case PREDEF_DECL_INT_128_ID:
8315 if (Context.Int128Decl)
8316 return Context.Int128Decl;
8317 NewLoaded = Context.getInt128Decl();
8318 break;
8319
8320 case PREDEF_DECL_UNSIGNED_INT_128_ID:
8321 if (Context.UInt128Decl)
8322 return Context.UInt128Decl;
8323 NewLoaded = Context.getUInt128Decl();
8324 break;
8325
8326 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
8327 if (Context.ObjCInstanceTypeDecl)
8328 return Context.ObjCInstanceTypeDecl;
8329 NewLoaded = Context.getObjCInstanceTypeDecl();
8330 break;
8331
8332 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
8333 if (Context.BuiltinVaListDecl)
8334 return Context.BuiltinVaListDecl;
8335 NewLoaded = Context.getBuiltinVaListDecl();
8336 break;
8337
8338 case PREDEF_DECL_VA_LIST_TAG:
8339 if (Context.VaListTagDecl)
8340 return Context.VaListTagDecl;
8341 NewLoaded = Context.getVaListTagDecl();
8342 break;
8343
8344 case PREDEF_DECL_BUILTIN_MS_VA_LIST_ID:
8345 if (Context.BuiltinMSVaListDecl)
8346 return Context.BuiltinMSVaListDecl;
8347 NewLoaded = Context.getBuiltinMSVaListDecl();
8348 break;
8349
8350 case PREDEF_DECL_BUILTIN_MS_GUID_ID:
8351 // ASTContext::getMSGuidTagDecl won't create MSGuidTagDecl conditionally.
8352 return Context.getMSGuidTagDecl();
8353
8354 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
8355 if (Context.ExternCContext)
8356 return Context.ExternCContext;
8357 NewLoaded = Context.getExternCContextDecl();
8358 break;
8359
8360 case PREDEF_DECL_CF_CONSTANT_STRING_ID:
8361 if (Context.CFConstantStringTypeDecl)
8362 return Context.CFConstantStringTypeDecl;
8363 NewLoaded = Context.getCFConstantStringDecl();
8364 break;
8365
8366 case PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID:
8367 if (Context.CFConstantStringTagDecl)
8368 return Context.CFConstantStringTagDecl;
8369 NewLoaded = Context.getCFConstantStringTagDecl();
8370 break;
8371
8372 case PREDEF_DECL_BUILTIN_MS_TYPE_INFO_TAG_ID:
8373 return Context.getMSTypeInfoTagDecl();
8374
8375 #define BuiltinTemplate(BTName) \
8376 case PREDEF_DECL##BTName##_ID: \
8377 if (Context.Decl##BTName) \
8378 return Context.Decl##BTName; \
8379 NewLoaded = Context.get##BTName##Decl(); \
8380 break;
8381 #include "clang/Basic/BuiltinTemplates.inc"
8382
8383 case NUM_PREDEF_DECL_IDS:
8384 llvm_unreachable("Invalid decl ID");
8385 break;
8386 }
8387
8388 assert(NewLoaded && "Failed to load predefined decl?");
8389
8390 if (DeserializationListener)
8391 DeserializationListener->PredefinedDeclBuilt(ID, NewLoaded);
8392
8393 return NewLoaded;
8394 }
8395
8396 unsigned ASTReader::translateGlobalDeclIDToIndex(GlobalDeclID GlobalID) const {
8397 ModuleFile *OwningModuleFile = getOwningModuleFile(GlobalID);
8398 if (!OwningModuleFile) {
8399 assert(GlobalID < NUM_PREDEF_DECL_IDS && "Untransalted Global ID?");
8400 return GlobalID.getRawValue();
8401 }
8402
8403 return OwningModuleFile->BaseDeclIndex + GlobalID.getLocalDeclIndex();
8404 }
8405
8406 Decl *ASTReader::GetExistingDecl(GlobalDeclID ID) {
8407 assert(ContextObj && "reading decl with no AST context");
8408
8409 if (ID < NUM_PREDEF_DECL_IDS) {
8410 Decl *D = getPredefinedDecl((PredefinedDeclIDs)ID);
8411 if (D) {
8412 // Track that we have merged the declaration with ID \p ID into the
8413 // pre-existing predefined declaration \p D.
8414 auto &Merged = KeyDecls[D->getCanonicalDecl()];
8415 if (Merged.empty())
8416 Merged.push_back(ID);
8417 }
8418 return D;
8419 }
8420
8421 unsigned Index = translateGlobalDeclIDToIndex(ID);
8422
8423 if (Index >= DeclsLoaded.size()) {
8424 assert(0 && "declaration ID out-of-range for AST file");
8425 Error("declaration ID out-of-range for AST file");
8426 return nullptr;
8427 }
8428
8429 return DeclsLoaded[Index];
8430 }
8431
8432 Decl *ASTReader::GetDecl(GlobalDeclID ID) {
8433 if (ID < NUM_PREDEF_DECL_IDS)
8434 return GetExistingDecl(ID);
8435
8436 unsigned Index = translateGlobalDeclIDToIndex(ID);
8437
8438 if (Index >= DeclsLoaded.size()) {
8439 assert(0 && "declaration ID out-of-range for AST file");
8440 Error("declaration ID out-of-range for AST file");
8441 return nullptr;
8442 }
8443
8444 if (!DeclsLoaded[Index]) {
8445 ReadDeclRecord(ID);
8446 if (DeserializationListener)
8447 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
8448 }
8449
8450 return DeclsLoaded[Index];
8451 }
8452
8453 LocalDeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
8454 GlobalDeclID GlobalID) {
8455 if (GlobalID < NUM_PREDEF_DECL_IDS)
8456 return LocalDeclID::get(*this, M, GlobalID.getRawValue());
8457
8458 if (!M.ModuleOffsetMap.empty())
8459 ReadModuleOffsetMap(M);
8460
8461 ModuleFile *Owner = getOwningModuleFile(GlobalID);
8462 DeclID ID = GlobalID.getLocalDeclIndex();
8463
8464 if (Owner == &M) {
8465 ID += NUM_PREDEF_DECL_IDS;
8466 return LocalDeclID::get(*this, M, ID);
8467 }
8468
8469 uint64_t OrignalModuleFileIndex = 0;
8470 for (unsigned I = 0; I < M.TransitiveImports.size(); I++)
8471 if (M.TransitiveImports[I] == Owner) {
8472 OrignalModuleFileIndex = I + 1;
8473 break;
8474 }
8475
8476 if (!OrignalModuleFileIndex)
8477 return LocalDeclID();
8478
8479 return LocalDeclID::get(*this, M, OrignalModuleFileIndex, ID);
8480 }
8481
8482 GlobalDeclID ASTReader::ReadDeclID(ModuleFile &F, const RecordDataImpl &Record,
8483 unsigned &Idx) {
8484 if (Idx >= Record.size()) {
8485 Error("Corrupted AST file");
8486 return GlobalDeclID(0);
8487 }
8488
8489 return getGlobalDeclID(F, LocalDeclID::get(*this, F, Record[Idx++]));
8490 }
8491
8492 /// Resolve the offset of a statement into a statement.
8493 ///
8494 /// This operation will read a new statement from the external
8495 /// source each time it is called, and is meant to be used via a
8496 /// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
8497 Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
8498 // Switch case IDs are per Decl.
8499 ClearSwitchCaseIDs();
8500
8501 // Offset here is a global offset across the entire chain.
8502 RecordLocation Loc = getLocalBitOffset(Offset);
8503 if (llvm::Error Err = Loc.F->DeclsCursor.JumpToBit(Loc.Offset)) {
8504 Error(std::move(Err));
8505 return nullptr;
8506 }
8507 assert(NumCurrentElementsDeserializing == 0 &&
8508 "should not be called while already deserializing");
8509 Deserializing D(this);
8510 return ReadStmtFromStream(*Loc.F);
8511 }
8512
8513 bool ASTReader::LoadExternalSpecializationsImpl(SpecLookupTableTy &SpecLookups,
8514 const Decl *D) {
8515 assert(D);
8516
8517 auto It = SpecLookups.find(D);
8518 if (It == SpecLookups.end())
8519 return false;
8520
8521 // Get Decl may violate the iterator from SpecializationsLookups so we store
8522 // the DeclIDs in ahead.
8523 llvm::SmallVector<serialization::reader::LazySpecializationInfo, 8> Infos =
8524 It->second.Table.findAll();
8525
8526 // Since we've loaded all the specializations, we can erase it from
8527 // the lookup table.
8528 SpecLookups.erase(It);
8529
8530 bool NewSpecsFound = false;
8531 Deserializing LookupResults(this);
8532 for (auto &Info : Infos) {
8533 if (GetExistingDecl(Info))
8534 continue;
8535 NewSpecsFound = true;
8536 GetDecl(Info);
8537 }
8538
8539 return NewSpecsFound;
8540 }
8541
8542 bool ASTReader::LoadExternalSpecializations(const Decl *D, bool OnlyPartial) {
8543 assert(D);
8544
8545 CompleteRedeclChain(D);
8546 bool NewSpecsFound =
8547 LoadExternalSpecializationsImpl(PartialSpecializationsLookups, D);
8548 if (OnlyPartial)
8549 return NewSpecsFound;
8550
8551 NewSpecsFound |= LoadExternalSpecializationsImpl(SpecializationsLookups, D);
8552 return NewSpecsFound;
8553 }
8554
8555 bool ASTReader::LoadExternalSpecializationsImpl(
8556 SpecLookupTableTy &SpecLookups, const Decl *D,
8557 ArrayRef<TemplateArgument> TemplateArgs) {
8558 assert(D);
8559
8560 reader::LazySpecializationInfoLookupTable *LookupTable = nullptr;
8561 if (auto It = SpecLookups.find(D); It != SpecLookups.end())
8562 LookupTable = &It->getSecond();
8563 if (!LookupTable)
8564 return false;
8565
8566 // NOTE: The getNameForDiagnostic usage in the lambda may mutate the
8567 // `SpecLookups` object.
8568 llvm::TimeTraceScope TimeScope("Load External Specializations for ", [&] {
8569 std::string Name;
8570 llvm::raw_string_ostream OS(Name);
8571 auto *ND = cast<NamedDecl>(D);
8572 ND->getNameForDiagnostic(OS, ND->getASTContext().getPrintingPolicy(),
8573 /*Qualified=*/true);
8574 return Name;
8575 });
8576
8577 Deserializing LookupResults(this);
8578 auto HashValue = StableHashForTemplateArguments(TemplateArgs);
8579
8580 // Get Decl may violate the iterator from SpecLookups
8581 llvm::SmallVector<serialization::reader::LazySpecializationInfo, 8> Infos =
8582 LookupTable->Table.find(HashValue);
8583
8584 bool NewSpecsFound = false;
8585 for (auto &Info : Infos) {
8586 if (GetExistingDecl(Info))
8587 continue;
8588 NewSpecsFound = true;
8589 GetDecl(Info);
8590 }
8591
8592 return NewSpecsFound;
8593 }
8594
8595 bool ASTReader::LoadExternalSpecializations(
8596 const Decl *D, ArrayRef<TemplateArgument> TemplateArgs) {
8597 assert(D);
8598
8599 bool NewDeclsFound = LoadExternalSpecializationsImpl(
8600 PartialSpecializationsLookups, D, TemplateArgs);
8601 NewDeclsFound |=
8602 LoadExternalSpecializationsImpl(SpecializationsLookups, D, TemplateArgs);
8603
8604 return NewDeclsFound;
8605 }
8606
8607 void ASTReader::FindExternalLexicalDecls(
8608 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
8609 SmallVectorImpl<Decl *> &Decls) {
8610 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
8611
8612 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
8613 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
8614 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
8615 auto K = (Decl::Kind)+LexicalDecls[I];
8616 if (!IsKindWeWant(K))
8617 continue;
8618
8619 auto ID = (DeclID) + LexicalDecls[I + 1];
8620
8621 // Don't add predefined declarations to the lexical context more
8622 // than once.
8623 if (ID < NUM_PREDEF_DECL_IDS) {
8624 if (PredefsVisited[ID])
8625 continue;
8626
8627 PredefsVisited[ID] = true;
8628 }
8629
8630 if (Decl *D = GetLocalDecl(*M, LocalDeclID::get(*this, *M, ID))) {
8631 assert(D->getKind() == K && "wrong kind for lexical decl");
8632 if (!DC->isDeclInLexicalTraversal(D))
8633 Decls.push_back(D);
8634 }
8635 }
8636 };
8637
8638 if (isa<TranslationUnitDecl>(DC)) {
8639 for (const auto &Lexical : TULexicalDecls)
8640 Visit(Lexical.first, Lexical.second);
8641 } else {
8642 auto I = LexicalDecls.find(DC);
8643 if (I != LexicalDecls.end())
8644 Visit(I->second.first, I->second.second);
8645 }
8646
8647 ++NumLexicalDeclContextsRead;
8648 }
8649
8650 namespace {
8651
8652 class UnalignedDeclIDComp {
8653 ASTReader &Reader;
8654 ModuleFile &Mod;
8655
8656 public:
8657 UnalignedDeclIDComp(ASTReader &Reader, ModuleFile &M)
8658 : Reader(Reader), Mod(M) {}
8659
8660 bool operator()(unaligned_decl_id_t L, unaligned_decl_id_t R) const {
8661 SourceLocation LHS = getLocation(L);
8662 SourceLocation RHS = getLocation(R);
8663 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
8664 }
8665
8666 bool operator()(SourceLocation LHS, unaligned_decl_id_t R) const {
8667 SourceLocation RHS = getLocation(R);
8668 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
8669 }
8670
8671 bool operator()(unaligned_decl_id_t L, SourceLocation RHS) const {
8672 SourceLocation LHS = getLocation(L);
8673 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
8674 }
8675
8676 SourceLocation getLocation(unaligned_decl_id_t ID) const {
8677 return Reader.getSourceManager().getFileLoc(
8678 Reader.getSourceLocationForDeclID(
8679 Reader.getGlobalDeclID(Mod, LocalDeclID::get(Reader, Mod, ID))));
8680 }
8681 };
8682
8683 } // namespace
8684
8685 void ASTReader::FindFileRegionDecls(FileID File,
8686 unsigned Offset, unsigned Length,
8687 SmallVectorImpl<Decl *> &Decls) {
8688 SourceManager &SM = getSourceManager();
8689
8690 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
8691 if (I == FileDeclIDs.end())
8692 return;
8693
8694 FileDeclsInfo &DInfo = I->second;
8695 if (DInfo.Decls.empty())
8696 return;
8697
8698 SourceLocation
8699 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
8700 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
8701
8702 UnalignedDeclIDComp DIDComp(*this, *DInfo.Mod);
8703 ArrayRef<unaligned_decl_id_t>::iterator BeginIt =
8704 llvm::lower_bound(DInfo.Decls, BeginLoc, DIDComp);
8705 if (BeginIt != DInfo.Decls.begin())
8706 --BeginIt;
8707
8708 // If we are pointing at a top-level decl inside an objc container, we need
8709 // to backtrack until we find it otherwise we will fail to report that the
8710 // region overlaps with an objc container.
8711 while (BeginIt != DInfo.Decls.begin() &&
8712 GetDecl(getGlobalDeclID(*DInfo.Mod,
8713 LocalDeclID::get(*this, *DInfo.Mod, *BeginIt)))
8714 ->isTopLevelDeclInObjCContainer())
8715 --BeginIt;
8716
8717 ArrayRef<unaligned_decl_id_t>::iterator EndIt =
8718 llvm::upper_bound(DInfo.Decls, EndLoc, DIDComp);
8719 if (EndIt != DInfo.Decls.end())
8720 ++EndIt;
8721
8722 for (ArrayRef<unaligned_decl_id_t>::iterator DIt = BeginIt; DIt != EndIt;
8723 ++DIt)
8724 Decls.push_back(GetDecl(getGlobalDeclID(
8725 *DInfo.Mod, LocalDeclID::get(*this, *DInfo.Mod, *DIt))));
8726 }
8727
8728 bool ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
8729 DeclarationName Name,
8730 const DeclContext *OriginalDC) {
8731 assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
8732 "DeclContext has no visible decls in storage");
8733 if (!Name)
8734 return false;
8735
8736 // Load the list of declarations.
8737 SmallVector<NamedDecl *, 64> Decls;
8738 llvm::SmallPtrSet<NamedDecl *, 8> Found;
8739
8740 auto Find = [&, this](auto &&Table, auto &&Key) {
8741 for (GlobalDeclID ID : Table.find(Key)) {
8742 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
8743 if (ND->getDeclName() == Name && Found.insert(ND).second)
8744 Decls.push_back(ND);
8745 }
8746 };
8747
8748 Deserializing LookupResults(this);
8749
8750 // FIXME: Clear the redundancy with templated lambda in C++20 when that's
8751 // available.
8752 if (auto It = Lookups.find(DC); It != Lookups.end()) {
8753 ++NumVisibleDeclContextsRead;
8754 Find(It->second.Table, Name);
8755 }
8756
8757 auto FindModuleLocalLookup = [&, this](Module *NamedModule) {
8758 if (auto It = ModuleLocalLookups.find(DC); It != ModuleLocalLookups.end()) {
8759 ++NumModuleLocalVisibleDeclContexts;
8760 Find(It->second.Table, std::make_pair(Name, NamedModule));
8761 }
8762 };
8763 if (auto *NamedModule =
8764 OriginalDC ? cast<Decl>(OriginalDC)->getTopLevelOwningNamedModule()
8765 : nullptr)
8766 FindModuleLocalLookup(NamedModule);
8767 // See clang/test/Modules/ModulesLocalNamespace.cppm for the motiviation case.
8768 // We're going to find a decl but the decl context of the lookup is
8769 // unspecified. In this case, the OriginalDC may be the decl context in other
8770 // module.
8771 if (ContextObj && ContextObj->getCurrentNamedModule())
8772 FindModuleLocalLookup(ContextObj->getCurrentNamedModule());
8773
8774 if (auto It = TULocalLookups.find(DC); It != TULocalLookups.end()) {
8775 ++NumTULocalVisibleDeclContexts;
8776 Find(It->second.Table, Name);
8777 }
8778
8779 SetExternalVisibleDeclsForName(DC, Name, Decls);
8780 return !Decls.empty();
8781 }
8782
8783 void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
8784 if (!DC->hasExternalVisibleStorage())
8785 return;
8786
8787 DeclsMap Decls;
8788
8789 auto findAll = [&](auto &LookupTables, unsigned &NumRead) {
8790 auto It = LookupTables.find(DC);
8791 if (It == LookupTables.end())
8792 return;
8793
8794 NumRead++;
8795
8796 for (GlobalDeclID ID : It->second.Table.findAll()) {
8797 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
8798 Decls[ND->getDeclName()].push_back(ND);
8799 }
8800
8801 // FIXME: Why a PCH test is failing if we remove the iterator after findAll?
8802 };
8803
8804 findAll(Lookups, NumVisibleDeclContextsRead);
8805 findAll(ModuleLocalLookups, NumModuleLocalVisibleDeclContexts);
8806 findAll(TULocalLookups, NumTULocalVisibleDeclContexts);
8807
8808 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
8809 SetExternalVisibleDeclsForName(DC, I->first, I->second);
8810 }
8811 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
8812 }
8813
8814 const serialization::reader::DeclContextLookupTable *
8815 ASTReader::getLoadedLookupTables(DeclContext *Primary) const {
8816 auto I = Lookups.find(Primary);
8817 return I == Lookups.end() ? nullptr : &I->second;
8818 }
8819
8820 const serialization::reader::ModuleLocalLookupTable *
8821 ASTReader::getModuleLocalLookupTables(DeclContext *Primary) const {
8822 auto I = ModuleLocalLookups.find(Primary);
8823 return I == ModuleLocalLookups.end() ? nullptr : &I->second;
8824 }
8825
8826 const serialization::reader::DeclContextLookupTable *
8827 ASTReader::getTULocalLookupTables(DeclContext *Primary) const {
8828 auto I = TULocalLookups.find(Primary);
8829 return I == TULocalLookups.end() ? nullptr : &I->second;
8830 }
8831
8832 serialization::reader::LazySpecializationInfoLookupTable *
8833 ASTReader::getLoadedSpecializationsLookupTables(const Decl *D, bool IsPartial) {
8834 assert(D->isCanonicalDecl());
8835 auto &LookupTable =
8836 IsPartial ? PartialSpecializationsLookups : SpecializationsLookups;
8837 auto I = LookupTable.find(D);
8838 return I == LookupTable.end() ? nullptr : &I->second;
8839 }
8840
8841 bool ASTReader::haveUnloadedSpecializations(const Decl *D) const {
8842 assert(D->isCanonicalDecl());
8843 return PartialSpecializationsLookups.contains(D) ||
8844 SpecializationsLookups.contains(D);
8845 }
8846
8847 /// Under non-PCH compilation the consumer receives the objc methods
8848 /// before receiving the implementation, and codegen depends on this.
8849 /// We simulate this by deserializing and passing to consumer the methods of the
8850 /// implementation before passing the deserialized implementation decl.
8851 static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
8852 ASTConsumer *Consumer) {
8853 assert(ImplD && Consumer);
8854
8855 for (auto *I : ImplD->methods())
8856 Consumer->HandleInterestingDecl(DeclGroupRef(I));
8857
8858 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
8859 }
8860
8861 void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
8862 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
8863 PassObjCImplDeclToConsumer(ImplD, Consumer);
8864 else
8865 Consumer->HandleInterestingDecl(DeclGroupRef(D));
8866 }
8867
8868 void ASTReader::PassVTableToConsumer(CXXRecordDecl *RD) {
8869 Consumer->HandleVTable(RD);
8870 }
8871
8872 void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
8873 this->Consumer = Consumer;
8874
8875 if (Consumer)
8876 PassInterestingDeclsToConsumer();
8877
8878 if (DeserializationListener)
8879 DeserializationListener->ReaderInitialized(this);
8880 }
8881
8882 void ASTReader::PrintStats() {
8883 std::fprintf(stderr, "*** AST File Statistics:\n");
8884
8885 unsigned NumTypesLoaded =
8886 TypesLoaded.size() - llvm::count(TypesLoaded.materialized(), QualType());
8887 unsigned NumDeclsLoaded =
8888 DeclsLoaded.size() -
8889 llvm::count(DeclsLoaded.materialized(), (Decl *)nullptr);
8890 unsigned NumIdentifiersLoaded =
8891 IdentifiersLoaded.size() -
8892 llvm::count(IdentifiersLoaded, (IdentifierInfo *)nullptr);
8893 unsigned NumMacrosLoaded =
8894 MacrosLoaded.size() - llvm::count(MacrosLoaded, (MacroInfo *)nullptr);
8895 unsigned NumSelectorsLoaded =
8896 SelectorsLoaded.size() - llvm::count(SelectorsLoaded, Selector());
8897
8898 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
8899 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
8900 NumSLocEntriesRead, TotalNumSLocEntries,
8901 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
8902 if (!TypesLoaded.empty())
8903 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
8904 NumTypesLoaded, (unsigned)TypesLoaded.size(),
8905 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
8906 if (!DeclsLoaded.empty())
8907 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
8908 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
8909 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
8910 if (!IdentifiersLoaded.empty())
8911 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
8912 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
8913 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
8914 if (!MacrosLoaded.empty())
8915 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
8916 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
8917 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
8918 if (!SelectorsLoaded.empty())
8919 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
8920 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
8921 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
8922 if (TotalNumStatements)
8923 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
8924 NumStatementsRead, TotalNumStatements,
8925 ((float)NumStatementsRead/TotalNumStatements * 100));
8926 if (TotalNumMacros)
8927 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
8928 NumMacrosRead, TotalNumMacros,
8929 ((float)NumMacrosRead/TotalNumMacros * 100));
8930 if (TotalLexicalDeclContexts)
8931 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
8932 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
8933 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
8934 * 100));
8935 if (TotalVisibleDeclContexts)
8936 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
8937 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
8938 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
8939 * 100));
8940 if (TotalModuleLocalVisibleDeclContexts)
8941 std::fprintf(
8942 stderr, " %u/%u module local visible declcontexts read (%f%%)\n",
8943 NumModuleLocalVisibleDeclContexts, TotalModuleLocalVisibleDeclContexts,
8944 ((float)NumModuleLocalVisibleDeclContexts /
8945 TotalModuleLocalVisibleDeclContexts * 100));
8946 if (TotalTULocalVisibleDeclContexts)
8947 std::fprintf(stderr, " %u/%u visible declcontexts in GMF read (%f%%)\n",
8948 NumTULocalVisibleDeclContexts, TotalTULocalVisibleDeclContexts,
8949 ((float)NumTULocalVisibleDeclContexts /
8950 TotalTULocalVisibleDeclContexts * 100));
8951 if (TotalNumMethodPoolEntries)
8952 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
8953 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
8954 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
8955 * 100));
8956 if (NumMethodPoolLookups)
8957 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
8958 NumMethodPoolHits, NumMethodPoolLookups,
8959 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
8960 if (NumMethodPoolTableLookups)
8961 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
8962 NumMethodPoolTableHits, NumMethodPoolTableLookups,
8963 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
8964 * 100.0));
8965 if (NumIdentifierLookupHits)
8966 std::fprintf(stderr,
8967 " %u / %u identifier table lookups succeeded (%f%%)\n",
8968 NumIdentifierLookupHits, NumIdentifierLookups,
8969 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
8970
8971 if (GlobalIndex) {
8972 std::fprintf(stderr, "\n");
8973 GlobalIndex->printStats();
8974 }
8975
8976 std::fprintf(stderr, "\n");
8977 dump();
8978 std::fprintf(stderr, "\n");
8979 }
8980
8981 template<typename Key, typename ModuleFile, unsigned InitialCapacity>
8982 LLVM_DUMP_METHOD static void
8983 dumpModuleIDMap(StringRef Name,
8984 const ContinuousRangeMap<Key, ModuleFile *,
8985 InitialCapacity> &Map) {
8986 if (Map.begin() == Map.end())
8987 return;
8988
8989 using MapType = ContinuousRangeMap<Key, ModuleFile *, InitialCapacity>;
8990
8991 llvm::errs() << Name << ":\n";
8992 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
8993 I != IEnd; ++I)
8994 llvm::errs() << " " << (DeclID)I->first << " -> " << I->second->FileName
8995 << "\n";
8996 }
8997
8998 LLVM_DUMP_METHOD void ASTReader::dump() {
8999 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
9000 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
9001 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
9002 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
9003 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
9004 dumpModuleIDMap("Global preprocessed entity map",
9005 GlobalPreprocessedEntityMap);
9006
9007 llvm::errs() << "\n*** PCH/Modules Loaded:";
9008 for (ModuleFile &M : ModuleMgr)
9009 M.dump();
9010 }
9011
9012 /// Return the amount of memory used by memory buffers, breaking down
9013 /// by heap-backed versus mmap'ed memory.
9014 void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
9015 for (ModuleFile &I : ModuleMgr) {
9016 if (llvm::MemoryBuffer *buf = I.Buffer) {
9017 size_t bytes = buf->getBufferSize();
9018 switch (buf->getBufferKind()) {
9019 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
9020 sizes.malloc_bytes += bytes;
9021 break;
9022 case llvm::MemoryBuffer::MemoryBuffer_MMap:
9023 sizes.mmap_bytes += bytes;
9024 break;
9025 }
9026 }
9027 }
9028 }
9029
9030 void ASTReader::InitializeSema(Sema &S) {
9031 SemaObj = &S;
9032 S.addExternalSource(this);
9033
9034 // Makes sure any declarations that were deserialized "too early"
9035 // still get added to the identifier's declaration chains.
9036 for (GlobalDeclID ID : PreloadedDeclIDs) {
9037 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
9038 pushExternalDeclIntoScope(D, D->getDeclName());
9039 }
9040 PreloadedDeclIDs.clear();
9041
9042 // FIXME: What happens if these are changed by a module import?
9043 if (!FPPragmaOptions.empty()) {
9044 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
9045 FPOptionsOverride NewOverrides =
9046 FPOptionsOverride::getFromOpaqueInt(FPPragmaOptions[0]);
9047 SemaObj->CurFPFeatures =
9048 NewOverrides.applyOverrides(SemaObj->getLangOpts());
9049 }
9050
9051 for (GlobalDeclID ID : DeclsWithEffectsToVerify) {
9052 Decl *D = GetDecl(ID);
9053 if (auto *FD = dyn_cast<FunctionDecl>(D))
9054 SemaObj->addDeclWithEffects(FD, FD->getFunctionEffects());
9055 else if (auto *BD = dyn_cast<BlockDecl>(D))
9056 SemaObj->addDeclWithEffects(BD, BD->getFunctionEffects());
9057 else
9058 llvm_unreachable("unexpected Decl type in DeclsWithEffectsToVerify");
9059 }
9060 DeclsWithEffectsToVerify.clear();
9061
9062 SemaObj->OpenCLFeatures = OpenCLExtensions;
9063
9064 UpdateSema();
9065 }
9066
9067 void ASTReader::UpdateSema() {
9068 assert(SemaObj && "no Sema to update");
9069
9070 // Load the offsets of the declarations that Sema references.
9071 // They will be lazily deserialized when needed.
9072 if (!SemaDeclRefs.empty()) {
9073 assert(SemaDeclRefs.size() % 3 == 0);
9074 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 3) {
9075 if (!SemaObj->StdNamespace)
9076 SemaObj->StdNamespace = SemaDeclRefs[I].getRawValue();
9077 if (!SemaObj->StdBadAlloc)
9078 SemaObj->StdBadAlloc = SemaDeclRefs[I + 1].getRawValue();
9079 if (!SemaObj->StdAlignValT)
9080 SemaObj->StdAlignValT = SemaDeclRefs[I + 2].getRawValue();
9081 }
9082 SemaDeclRefs.clear();
9083 }
9084
9085 // Update the state of pragmas. Use the same API as if we had encountered the
9086 // pragma in the source.
9087 if(OptimizeOffPragmaLocation.isValid())
9088 SemaObj->ActOnPragmaOptimize(/* On = */ false, OptimizeOffPragmaLocation);
9089 if (PragmaMSStructState != -1)
9090 SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState);
9091 if (PointersToMembersPragmaLocation.isValid()) {
9092 SemaObj->ActOnPragmaMSPointersToMembers(
9093 (LangOptions::PragmaMSPointersToMembersKind)
9094 PragmaMSPointersToMembersState,
9095 PointersToMembersPragmaLocation);
9096 }
9097 SemaObj->CUDA().ForceHostDeviceDepth = ForceHostDeviceDepth;
9098 if (!RISCVVecIntrinsicPragma.empty()) {
9099 assert(RISCVVecIntrinsicPragma.size() == 3 &&
9100 "Wrong number of RISCVVecIntrinsicPragma");
9101 SemaObj->RISCV().DeclareRVVBuiltins = RISCVVecIntrinsicPragma[0];
9102 SemaObj->RISCV().DeclareSiFiveVectorBuiltins = RISCVVecIntrinsicPragma[1];
9103 SemaObj->RISCV().DeclareAndesVectorBuiltins = RISCVVecIntrinsicPragma[2];
9104 }
9105
9106 if (PragmaAlignPackCurrentValue) {
9107 // The bottom of the stack might have a default value. It must be adjusted
9108 // to the current value to ensure that the packing state is preserved after
9109 // popping entries that were included/imported from a PCH/module.
9110 bool DropFirst = false;
9111 if (!PragmaAlignPackStack.empty() &&
9112 PragmaAlignPackStack.front().Location.isInvalid()) {
9113 assert(PragmaAlignPackStack.front().Value ==
9114 SemaObj->AlignPackStack.DefaultValue &&
9115 "Expected a default alignment value");
9116 SemaObj->AlignPackStack.Stack.emplace_back(
9117 PragmaAlignPackStack.front().SlotLabel,
9118 SemaObj->AlignPackStack.CurrentValue,
9119 SemaObj->AlignPackStack.CurrentPragmaLocation,
9120 PragmaAlignPackStack.front().PushLocation);
9121 DropFirst = true;
9122 }
9123 for (const auto &Entry :
9124 llvm::ArrayRef(PragmaAlignPackStack).drop_front(DropFirst ? 1 : 0)) {
9125 SemaObj->AlignPackStack.Stack.emplace_back(
9126 Entry.SlotLabel, Entry.Value, Entry.Location, Entry.PushLocation);
9127 }
9128 if (PragmaAlignPackCurrentLocation.isInvalid()) {
9129 assert(*PragmaAlignPackCurrentValue ==
9130 SemaObj->AlignPackStack.DefaultValue &&
9131 "Expected a default align and pack value");
9132 // Keep the current values.
9133 } else {
9134 SemaObj->AlignPackStack.CurrentValue = *PragmaAlignPackCurrentValue;
9135 SemaObj->AlignPackStack.CurrentPragmaLocation =
9136 PragmaAlignPackCurrentLocation;
9137 }
9138 }
9139 if (FpPragmaCurrentValue) {
9140 // The bottom of the stack might have a default value. It must be adjusted
9141 // to the current value to ensure that fp-pragma state is preserved after
9142 // popping entries that were included/imported from a PCH/module.
9143 bool DropFirst = false;
9144 if (!FpPragmaStack.empty() && FpPragmaStack.front().Location.isInvalid()) {
9145 assert(FpPragmaStack.front().Value ==
9146 SemaObj->FpPragmaStack.DefaultValue &&
9147 "Expected a default pragma float_control value");
9148 SemaObj->FpPragmaStack.Stack.emplace_back(
9149 FpPragmaStack.front().SlotLabel, SemaObj->FpPragmaStack.CurrentValue,
9150 SemaObj->FpPragmaStack.CurrentPragmaLocation,
9151 FpPragmaStack.front().PushLocation);
9152 DropFirst = true;
9153 }
9154 for (const auto &Entry :
9155 llvm::ArrayRef(FpPragmaStack).drop_front(DropFirst ? 1 : 0))
9156 SemaObj->FpPragmaStack.Stack.emplace_back(
9157 Entry.SlotLabel, Entry.Value, Entry.Location, Entry.PushLocation);
9158 if (FpPragmaCurrentLocation.isInvalid()) {
9159 assert(*FpPragmaCurrentValue == SemaObj->FpPragmaStack.DefaultValue &&
9160 "Expected a default pragma float_control value");
9161 // Keep the current values.
9162 } else {
9163 SemaObj->FpPragmaStack.CurrentValue = *FpPragmaCurrentValue;
9164 SemaObj->FpPragmaStack.CurrentPragmaLocation = FpPragmaCurrentLocation;
9165 }
9166 }
9167
9168 // For non-modular AST files, restore visiblity of modules.
9169 for (auto &Import : PendingImportedModulesSema) {
9170 if (Import.ImportLoc.isInvalid())
9171 continue;
9172 if (Module *Imported = getSubmodule(Import.ID)) {
9173 SemaObj->makeModuleVisible(Imported, Import.ImportLoc);
9174 }
9175 }
9176 PendingImportedModulesSema.clear();
9177 }
9178
9179 IdentifierInfo *ASTReader::get(StringRef Name) {
9180 // Note that we are loading an identifier.
9181 Deserializing AnIdentifier(this);
9182
9183 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
9184 NumIdentifierLookups,
9185 NumIdentifierLookupHits);
9186
9187 // We don't need to do identifier table lookups in C++ modules (we preload
9188 // all interesting declarations, and don't need to use the scope for name
9189 // lookups). Perform the lookup in PCH files, though, since we don't build
9190 // a complete initial identifier table if we're carrying on from a PCH.
9191 if (PP.getLangOpts().CPlusPlus) {
9192 for (auto *F : ModuleMgr.pch_modules())
9193 if (Visitor(*F))
9194 break;
9195 } else {
9196 // If there is a global index, look there first to determine which modules
9197 // provably do not have any results for this identifier.
9198 GlobalModuleIndex::HitSet Hits;
9199 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
9200 if (!loadGlobalIndex()) {
9201 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
9202 HitsPtr = &Hits;
9203 }
9204 }
9205
9206 ModuleMgr.visit(Visitor, HitsPtr);
9207 }
9208
9209 IdentifierInfo *II = Visitor.getIdentifierInfo();
9210 markIdentifierUpToDate(II);
9211 return II;
9212 }
9213
9214 namespace clang {
9215
9216 /// An identifier-lookup iterator that enumerates all of the
9217 /// identifiers stored within a set of AST files.
9218 class ASTIdentifierIterator : public IdentifierIterator {
9219 /// The AST reader whose identifiers are being enumerated.
9220 const ASTReader &Reader;
9221
9222 /// The current index into the chain of AST files stored in
9223 /// the AST reader.
9224 unsigned Index;
9225
9226 /// The current position within the identifier lookup table
9227 /// of the current AST file.
9228 ASTIdentifierLookupTable::key_iterator Current;
9229
9230 /// The end position within the identifier lookup table of
9231 /// the current AST file.
9232 ASTIdentifierLookupTable::key_iterator End;
9233
9234 /// Whether to skip any modules in the ASTReader.
9235 bool SkipModules;
9236
9237 public:
9238 explicit ASTIdentifierIterator(const ASTReader &Reader,
9239 bool SkipModules = false);
9240
9241 StringRef Next() override;
9242 };
9243
9244 } // namespace clang
9245
9246 ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader,
9247 bool SkipModules)
9248 : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) {
9249 }
9250
9251 StringRef ASTIdentifierIterator::Next() {
9252 while (Current == End) {
9253 // If we have exhausted all of our AST files, we're done.
9254 if (Index == 0)
9255 return StringRef();
9256
9257 --Index;
9258 ModuleFile &F = Reader.ModuleMgr[Index];
9259 if (SkipModules && F.isModule())
9260 continue;
9261
9262 ASTIdentifierLookupTable *IdTable =
9263 (ASTIdentifierLookupTable *)F.IdentifierLookupTable;
9264 Current = IdTable->key_begin();
9265 End = IdTable->key_end();
9266 }
9267
9268 // We have any identifiers remaining in the current AST file; return
9269 // the next one.
9270 StringRef Result = *Current;
9271 ++Current;
9272 return Result;
9273 }
9274
9275 namespace {
9276
9277 /// A utility for appending two IdentifierIterators.
9278 class ChainedIdentifierIterator : public IdentifierIterator {
9279 std::unique_ptr<IdentifierIterator> Current;
9280 std::unique_ptr<IdentifierIterator> Queued;
9281
9282 public:
9283 ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First,
9284 std::unique_ptr<IdentifierIterator> Second)
9285 : Current(std::move(First)), Queued(std::move(Second)) {}
9286
9287 StringRef Next() override {
9288 if (!Current)
9289 return StringRef();
9290
9291 StringRef result = Current->Next();
9292 if (!result.empty())
9293 return result;
9294
9295 // Try the queued iterator, which may itself be empty.
9296 Current.reset();
9297 std::swap(Current, Queued);
9298 return Next();
9299 }
9300 };
9301
9302 } // namespace
9303
9304 IdentifierIterator *ASTReader::getIdentifiers() {
9305 if (!loadGlobalIndex()) {
9306 std::unique_ptr<IdentifierIterator> ReaderIter(
9307 new ASTIdentifierIterator(*this, /*SkipModules=*/true));
9308 std::unique_ptr<IdentifierIterator> ModulesIter(
9309 GlobalIndex->createIdentifierIterator());
9310 return new ChainedIdentifierIterator(std::move(ReaderIter),
9311 std::move(ModulesIter));
9312 }
9313
9314 return new ASTIdentifierIterator(*this);
9315 }
9316
9317 namespace clang {
9318 namespace serialization {
9319
9320 class ReadMethodPoolVisitor {
9321 ASTReader &Reader;
9322 Selector Sel;
9323 unsigned PriorGeneration;
9324 unsigned InstanceBits = 0;
9325 unsigned FactoryBits = 0;
9326 bool InstanceHasMoreThanOneDecl = false;
9327 bool FactoryHasMoreThanOneDecl = false;
9328 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
9329 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
9330
9331 public:
9332 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
9333 unsigned PriorGeneration)
9334 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration) {}
9335
9336 bool operator()(ModuleFile &M) {
9337 if (!M.SelectorLookupTable)
9338 return false;
9339
9340 // If we've already searched this module file, skip it now.
9341 if (M.Generation <= PriorGeneration)
9342 return true;
9343
9344 ++Reader.NumMethodPoolTableLookups;
9345 ASTSelectorLookupTable *PoolTable
9346 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
9347 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
9348 if (Pos == PoolTable->end())
9349 return false;
9350
9351 ++Reader.NumMethodPoolTableHits;
9352 ++Reader.NumSelectorsRead;
9353 // FIXME: Not quite happy with the statistics here. We probably should
9354 // disable this tracking when called via LoadSelector.
9355 // Also, should entries without methods count as misses?
9356 ++Reader.NumMethodPoolEntriesRead;
9357 ASTSelectorLookupTrait::data_type Data = *Pos;
9358 if (Reader.DeserializationListener)
9359 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
9360
9361 // Append methods in the reverse order, so that later we can process them
9362 // in the order they appear in the source code by iterating through
9363 // the vector in the reverse order.
9364 InstanceMethods.append(Data.Instance.rbegin(), Data.Instance.rend());
9365 FactoryMethods.append(Data.Factory.rbegin(), Data.Factory.rend());
9366 InstanceBits = Data.InstanceBits;
9367 FactoryBits = Data.FactoryBits;
9368 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
9369 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
9370 return false;
9371 }
9372
9373 /// Retrieve the instance methods found by this visitor.
9374 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
9375 return InstanceMethods;
9376 }
9377
9378 /// Retrieve the instance methods found by this visitor.
9379 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
9380 return FactoryMethods;
9381 }
9382
9383 unsigned getInstanceBits() const { return InstanceBits; }
9384 unsigned getFactoryBits() const { return FactoryBits; }
9385
9386 bool instanceHasMoreThanOneDecl() const {
9387 return InstanceHasMoreThanOneDecl;
9388 }
9389
9390 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
9391 };
9392
9393 } // namespace serialization
9394 } // namespace clang
9395
9396 /// Add the given set of methods to the method list.
9397 static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
9398 ObjCMethodList &List) {
9399 for (ObjCMethodDecl *M : llvm::reverse(Methods))
9400 S.ObjC().addMethodToGlobalList(&List, M);
9401 }
9402
9403 void ASTReader::ReadMethodPool(Selector Sel) {
9404 // Get the selector generation and update it to the current generation.
9405 unsigned &Generation = SelectorGeneration[Sel];
9406 unsigned PriorGeneration = Generation;
9407 Generation = getGeneration();
9408 SelectorOutOfDate[Sel] = false;
9409
9410 // Search for methods defined with this selector.
9411 ++NumMethodPoolLookups;
9412 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
9413 ModuleMgr.visit(Visitor);
9414
9415 if (Visitor.getInstanceMethods().empty() &&
9416 Visitor.getFactoryMethods().empty())
9417 return;
9418
9419 ++NumMethodPoolHits;
9420
9421 if (!getSema())
9422 return;
9423
9424 Sema &S = *getSema();
9425 auto &Methods = S.ObjC().MethodPool[Sel];
9426
9427 Methods.first.setBits(Visitor.getInstanceBits());
9428 Methods.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
9429 Methods.second.setBits(Visitor.getFactoryBits());
9430 Methods.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
9431
9432 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
9433 // when building a module we keep every method individually and may need to
9434 // update hasMoreThanOneDecl as we add the methods.
9435 addMethodsToPool(S, Visitor.getInstanceMethods(), Methods.first);
9436 addMethodsToPool(S, Visitor.getFactoryMethods(), Methods.second);
9437 }
9438
9439 void ASTReader::updateOutOfDateSelector(Selector Sel) {
9440 if (SelectorOutOfDate[Sel])
9441 ReadMethodPool(Sel);
9442 }
9443
9444 void ASTReader::ReadKnownNamespaces(
9445 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
9446 Namespaces.clear();
9447
9448 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
9449 if (NamespaceDecl *Namespace
9450 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
9451 Namespaces.push_back(Namespace);
9452 }
9453 }
9454
9455 void ASTReader::ReadUndefinedButUsed(
9456 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {
9457 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
9458 UndefinedButUsedDecl &U = UndefinedButUsed[Idx++];
9459 NamedDecl *D = cast<NamedDecl>(GetDecl(U.ID));
9460 SourceLocation Loc = SourceLocation::getFromRawEncoding(U.RawLoc);
9461 Undefined.insert(std::make_pair(D, Loc));
9462 }
9463 UndefinedButUsed.clear();
9464 }
9465
9466 void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
9467 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
9468 Exprs) {
9469 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
9470 FieldDecl *FD =
9471 cast<FieldDecl>(GetDecl(GlobalDeclID(DelayedDeleteExprs[Idx++])));
9472 uint64_t Count = DelayedDeleteExprs[Idx++];
9473 for (uint64_t C = 0; C < Count; ++C) {
9474 SourceLocation DeleteLoc =
9475 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
9476 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
9477 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
9478 }
9479 }
9480 }
9481
9482 void ASTReader::ReadTentativeDefinitions(
9483 SmallVectorImpl<VarDecl *> &TentativeDefs) {
9484 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
9485 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
9486 if (Var)
9487 TentativeDefs.push_back(Var);
9488 }
9489 TentativeDefinitions.clear();
9490 }
9491
9492 void ASTReader::ReadUnusedFileScopedDecls(
9493 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
9494 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
9495 DeclaratorDecl *D
9496 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
9497 if (D)
9498 Decls.push_back(D);
9499 }
9500 UnusedFileScopedDecls.clear();
9501 }
9502
9503 void ASTReader::ReadDelegatingConstructors(
9504 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
9505 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
9506 CXXConstructorDecl *D
9507 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
9508 if (D)
9509 Decls.push_back(D);
9510 }
9511 DelegatingCtorDecls.clear();
9512 }
9513
9514 void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
9515 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
9516 TypedefNameDecl *D
9517 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
9518 if (D)
9519 Decls.push_back(D);
9520 }
9521 ExtVectorDecls.clear();
9522 }
9523
9524 void ASTReader::ReadUnusedLocalTypedefNameCandidates(
9525 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
9526 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
9527 ++I) {
9528 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
9529 GetDecl(UnusedLocalTypedefNameCandidates[I]));
9530 if (D)
9531 Decls.insert(D);
9532 }
9533 UnusedLocalTypedefNameCandidates.clear();
9534 }
9535
9536 void ASTReader::ReadDeclsToCheckForDeferredDiags(
9537 llvm::SmallSetVector<Decl *, 4> &Decls) {
9538 for (auto I : DeclsToCheckForDeferredDiags) {
9539 auto *D = dyn_cast_or_null<Decl>(GetDecl(I));
9540 if (D)
9541 Decls.insert(D);
9542 }
9543 DeclsToCheckForDeferredDiags.clear();
9544 }
9545
9546 void ASTReader::ReadReferencedSelectors(
9547 SmallVectorImpl<std::pair<Selector, SourceLocation>> &Sels) {
9548 if (ReferencedSelectorsData.empty())
9549 return;
9550
9551 // If there are @selector references added them to its pool. This is for
9552 // implementation of -Wselector.
9553 unsigned int DataSize = ReferencedSelectorsData.size()-1;
9554 unsigned I = 0;
9555 while (I < DataSize) {
9556 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
9557 SourceLocation SelLoc
9558 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
9559 Sels.push_back(std::make_pair(Sel, SelLoc));
9560 }
9561 ReferencedSelectorsData.clear();
9562 }
9563
9564 void ASTReader::ReadWeakUndeclaredIdentifiers(
9565 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo>> &WeakIDs) {
9566 if (WeakUndeclaredIdentifiers.empty())
9567 return;
9568
9569 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
9570 IdentifierInfo *WeakId
9571 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
9572 IdentifierInfo *AliasId
9573 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
9574 SourceLocation Loc =
9575 SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
9576 WeakInfo WI(AliasId, Loc);
9577 WeakIDs.push_back(std::make_pair(WeakId, WI));
9578 }
9579 WeakUndeclaredIdentifiers.clear();
9580 }
9581
9582 void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
9583 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
9584 ExternalVTableUse VT;
9585 VTableUse &TableInfo = VTableUses[Idx++];
9586 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(TableInfo.ID));
9587 VT.Location = SourceLocation::getFromRawEncoding(TableInfo.RawLoc);
9588 VT.DefinitionRequired = TableInfo.Used;
9589 VTables.push_back(VT);
9590 }
9591
9592 VTableUses.clear();
9593 }
9594
9595 void ASTReader::ReadPendingInstantiations(
9596 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation>> &Pending) {
9597 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
9598 PendingInstantiation &Inst = PendingInstantiations[Idx++];
9599 ValueDecl *D = cast<ValueDecl>(GetDecl(Inst.ID));
9600 SourceLocation Loc = SourceLocation::getFromRawEncoding(Inst.RawLoc);
9601
9602 Pending.push_back(std::make_pair(D, Loc));
9603 }
9604 PendingInstantiations.clear();
9605 }
9606
9607 void ASTReader::ReadLateParsedTemplates(
9608 llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>>
9609 &LPTMap) {
9610 for (auto &LPT : LateParsedTemplates) {
9611 ModuleFile *FMod = LPT.first;
9612 RecordDataImpl &LateParsed = LPT.second;
9613 for (unsigned Idx = 0, N = LateParsed.size(); Idx < N;
9614 /* In loop */) {
9615 FunctionDecl *FD = ReadDeclAs<FunctionDecl>(*FMod, LateParsed, Idx);
9616
9617 auto LT = std::make_unique<LateParsedTemplate>();
9618 LT->D = ReadDecl(*FMod, LateParsed, Idx);
9619 LT->FPO = FPOptions::getFromOpaqueInt(LateParsed[Idx++]);
9620
9621 ModuleFile *F = getOwningModuleFile(LT->D);
9622 assert(F && "No module");
9623
9624 unsigned TokN = LateParsed[Idx++];
9625 LT->Toks.reserve(TokN);
9626 for (unsigned T = 0; T < TokN; ++T)
9627 LT->Toks.push_back(ReadToken(*F, LateParsed, Idx));
9628
9629 LPTMap.insert(std::make_pair(FD, std::move(LT)));
9630 }
9631 }
9632
9633 LateParsedTemplates.clear();
9634 }
9635
9636 void ASTReader::AssignedLambdaNumbering(CXXRecordDecl *Lambda) {
9637 if (!Lambda->getLambdaContextDecl())
9638 return;
9639
9640 auto LambdaInfo =
9641 std::make_pair(Lambda->getLambdaContextDecl()->getCanonicalDecl(),
9642 Lambda->getLambdaIndexInContext());
9643
9644 // Handle the import and then include case for lambdas.
9645 if (auto Iter = LambdaDeclarationsForMerging.find(LambdaInfo);
9646 Iter != LambdaDeclarationsForMerging.end() &&
9647 Iter->second->isFromASTFile() && Lambda->getFirstDecl() == Lambda) {
9648 CXXRecordDecl *Previous =
9649 cast<CXXRecordDecl>(Iter->second)->getMostRecentDecl();
9650 Lambda->setPreviousDecl(Previous);
9651 return;
9652 }
9653
9654 // Keep track of this lambda so it can be merged with another lambda that
9655 // is loaded later.
9656 LambdaDeclarationsForMerging.insert({LambdaInfo, Lambda});
9657 }
9658
9659 void ASTReader::LoadSelector(Selector Sel) {
9660 // It would be complicated to avoid reading the methods anyway. So don't.
9661 ReadMethodPool(Sel);
9662 }
9663
9664 void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
9665 assert(ID && "Non-zero identifier ID required");
9666 unsigned Index = translateIdentifierIDToIndex(ID).second;
9667 assert(Index < IdentifiersLoaded.size() && "identifier ID out of range");
9668 IdentifiersLoaded[Index] = II;
9669 if (DeserializationListener)
9670 DeserializationListener->IdentifierRead(ID, II);
9671 }
9672
9673 /// Set the globally-visible declarations associated with the given
9674 /// identifier.
9675 ///
9676 /// If the AST reader is currently in a state where the given declaration IDs
9677 /// cannot safely be resolved, they are queued until it is safe to resolve
9678 /// them.
9679 ///
9680 /// \param II an IdentifierInfo that refers to one or more globally-visible
9681 /// declarations.
9682 ///
9683 /// \param DeclIDs the set of declaration IDs with the name @p II that are
9684 /// visible at global scope.
9685 ///
9686 /// \param Decls if non-null, this vector will be populated with the set of
9687 /// deserialized declarations. These declarations will not be pushed into
9688 /// scope.
9689 void ASTReader::SetGloballyVisibleDecls(
9690 IdentifierInfo *II, const SmallVectorImpl<GlobalDeclID> &DeclIDs,
9691 SmallVectorImpl<Decl *> *Decls) {
9692 if (NumCurrentElementsDeserializing && !Decls) {
9693 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
9694 return;
9695 }
9696
9697 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
9698 if (!SemaObj) {
9699 // Queue this declaration so that it will be added to the
9700 // translation unit scope and identifier's declaration chain
9701 // once a Sema object is known.
9702 PreloadedDeclIDs.push_back(DeclIDs[I]);
9703 continue;
9704 }
9705
9706 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
9707
9708 // If we're simply supposed to record the declarations, do so now.
9709 if (Decls) {
9710 Decls->push_back(D);
9711 continue;
9712 }
9713
9714 // Introduce this declaration into the translation-unit scope
9715 // and add it to the declaration chain for this identifier, so
9716 // that (unqualified) name lookup will find it.
9717 pushExternalDeclIntoScope(D, II);
9718 }
9719 }
9720
9721 std::pair<ModuleFile *, unsigned>
9722 ASTReader::translateIdentifierIDToIndex(IdentifierID ID) const {
9723 if (ID == 0)
9724 return {nullptr, 0};
9725
9726 unsigned ModuleFileIndex = ID >> 32;
9727 unsigned LocalID = ID & llvm::maskTrailingOnes<IdentifierID>(32);
9728
9729 assert(ModuleFileIndex && "not translating loaded IdentifierID?");
9730 assert(getModuleManager().size() > ModuleFileIndex - 1);
9731
9732 ModuleFile &MF = getModuleManager()[ModuleFileIndex - 1];
9733 assert(LocalID < MF.LocalNumIdentifiers);
9734 return {&MF, MF.BaseIdentifierID + LocalID};
9735 }
9736
9737 IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
9738 if (ID == 0)
9739 return nullptr;
9740
9741 if (IdentifiersLoaded.empty()) {
9742 Error("no identifier table in AST file");
9743 return nullptr;
9744 }
9745
9746 auto [M, Index] = translateIdentifierIDToIndex(ID);
9747 if (!IdentifiersLoaded[Index]) {
9748 assert(M != nullptr && "Untranslated Identifier ID?");
9749 assert(Index >= M->BaseIdentifierID);
9750 unsigned LocalIndex = Index - M->BaseIdentifierID;
9751 const unsigned char *Data =
9752 M->IdentifierTableData + M->IdentifierOffsets[LocalIndex];
9753
9754 ASTIdentifierLookupTrait Trait(*this, *M);
9755 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
9756 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
9757 auto &II = PP.getIdentifierTable().get(Key);
9758 IdentifiersLoaded[Index] = &II;
9759 bool IsModule = getPreprocessor().getCurrentModule() != nullptr;
9760 markIdentifierFromAST(*this, II, IsModule);
9761 if (DeserializationListener)
9762 DeserializationListener->IdentifierRead(ID, &II);
9763 }
9764
9765 return IdentifiersLoaded[Index];
9766 }
9767
9768 IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, uint64_t LocalID) {
9769 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
9770 }
9771
9772 IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, uint64_t LocalID) {
9773 if (LocalID < NUM_PREDEF_IDENT_IDS)
9774 return LocalID;
9775
9776 if (!M.ModuleOffsetMap.empty())
9777 ReadModuleOffsetMap(M);
9778
9779 unsigned ModuleFileIndex = LocalID >> 32;
9780 LocalID &= llvm::maskTrailingOnes<IdentifierID>(32);
9781 ModuleFile *MF =
9782 ModuleFileIndex ? M.TransitiveImports[ModuleFileIndex - 1] : &M;
9783 assert(MF && "malformed identifier ID encoding?");
9784
9785 if (!ModuleFileIndex)
9786 LocalID -= NUM_PREDEF_IDENT_IDS;
9787
9788 return ((IdentifierID)(MF->Index + 1) << 32) | LocalID;
9789 }
9790
9791 std::pair<ModuleFile *, unsigned>
9792 ASTReader::translateMacroIDToIndex(MacroID ID) const {
9793 if (ID == 0)
9794 return {nullptr, 0};
9795
9796 unsigned ModuleFileIndex = ID >> 32;
9797 assert(ModuleFileIndex && "not translating loaded MacroID?");
9798 assert(getModuleManager().size() > ModuleFileIndex - 1);
9799 ModuleFile &MF = getModuleManager()[ModuleFileIndex - 1];
9800
9801 unsigned LocalID = ID & llvm::maskTrailingOnes<MacroID>(32);
9802 assert(LocalID < MF.LocalNumMacros);
9803 return {&MF, MF.BaseMacroID + LocalID};
9804 }
9805
9806 MacroInfo *ASTReader::getMacro(MacroID ID) {
9807 if (ID == 0)
9808 return nullptr;
9809
9810 if (MacrosLoaded.empty()) {
9811 Error("no macro table in AST file");
9812 return nullptr;
9813 }
9814
9815 auto [M, Index] = translateMacroIDToIndex(ID);
9816 if (!MacrosLoaded[Index]) {
9817 assert(M != nullptr && "Untranslated Macro ID?");
9818 assert(Index >= M->BaseMacroID);
9819 unsigned LocalIndex = Index - M->BaseMacroID;
9820 uint64_t DataOffset = M->MacroOffsetsBase + M->MacroOffsets[LocalIndex];
9821 MacrosLoaded[Index] = ReadMacroRecord(*M, DataOffset);
9822
9823 if (DeserializationListener)
9824 DeserializationListener->MacroRead(ID, MacrosLoaded[Index]);
9825 }
9826
9827 return MacrosLoaded[Index];
9828 }
9829
9830 MacroID ASTReader::getGlobalMacroID(ModuleFile &M, MacroID LocalID) {
9831 if (LocalID < NUM_PREDEF_MACRO_IDS)
9832 return LocalID;
9833
9834 if (!M.ModuleOffsetMap.empty())
9835 ReadModuleOffsetMap(M);
9836
9837 unsigned ModuleFileIndex = LocalID >> 32;
9838 LocalID &= llvm::maskTrailingOnes<MacroID>(32);
9839 ModuleFile *MF =
9840 ModuleFileIndex ? M.TransitiveImports[ModuleFileIndex - 1] : &M;
9841 assert(MF && "malformed identifier ID encoding?");
9842
9843 if (!ModuleFileIndex) {
9844 assert(LocalID >= NUM_PREDEF_MACRO_IDS);
9845 LocalID -= NUM_PREDEF_MACRO_IDS;
9846 }
9847
9848 return (static_cast<MacroID>(MF->Index + 1) << 32) | LocalID;
9849 }
9850
9851 serialization::SubmoduleID
9852 ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) const {
9853 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
9854 return LocalID;
9855
9856 if (!M.ModuleOffsetMap.empty())
9857 ReadModuleOffsetMap(M);
9858
9859 ContinuousRangeMap<uint32_t, int, 2>::iterator I
9860 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
9861 assert(I != M.SubmoduleRemap.end()
9862 && "Invalid index into submodule index remap");
9863
9864 return LocalID + I->second;
9865 }
9866
9867 Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
9868 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
9869 assert(GlobalID == 0 && "Unhandled global submodule ID");
9870 return nullptr;
9871 }
9872
9873 if (GlobalID > SubmodulesLoaded.size()) {
9874 Error("submodule ID out of range in AST file");
9875 return nullptr;
9876 }
9877
9878 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
9879 }
9880
9881 Module *ASTReader::getModule(unsigned ID) {
9882 return getSubmodule(ID);
9883 }
9884
9885 ModuleFile *ASTReader::getLocalModuleFile(ModuleFile &M, unsigned ID) const {
9886 if (ID & 1) {
9887 // It's a module, look it up by submodule ID.
9888 auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(M, ID >> 1));
9889 return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
9890 } else {
9891 // It's a prefix (preamble, PCH, ...). Look it up by index.
9892 int IndexFromEnd = static_cast<int>(ID >> 1);
9893 assert(IndexFromEnd && "got reference to unknown module file");
9894 return getModuleManager().pch_modules().end()[-IndexFromEnd];
9895 }
9896 }
9897
9898 unsigned ASTReader::getModuleFileID(ModuleFile *M) {
9899 if (!M)
9900 return 1;
9901
9902 // For a file representing a module, use the submodule ID of the top-level
9903 // module as the file ID. For any other kind of file, the number of such
9904 // files loaded beforehand will be the same on reload.
9905 // FIXME: Is this true even if we have an explicit module file and a PCH?
9906 if (M->isModule())
9907 return ((M->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
9908
9909 auto PCHModules = getModuleManager().pch_modules();
9910 auto I = llvm::find(PCHModules, M);
9911 assert(I != PCHModules.end() && "emitting reference to unknown file");
9912 return std::distance(I, PCHModules.end()) << 1;
9913 }
9914
9915 std::optional<ASTSourceDescriptor> ASTReader::getSourceDescriptor(unsigned ID) {
9916 if (Module *M = getSubmodule(ID))
9917 return ASTSourceDescriptor(*M);
9918
9919 // If there is only a single PCH, return it instead.
9920 // Chained PCH are not supported.
9921 const auto &PCHChain = ModuleMgr.pch_modules();
9922 if (std::distance(std::begin(PCHChain), std::end(PCHChain))) {
9923 ModuleFile &MF = ModuleMgr.getPrimaryModule();
9924 StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName);
9925 StringRef FileName = llvm::sys::path::filename(MF.FileName);
9926 return ASTSourceDescriptor(ModuleName,
9927 llvm::sys::path::parent_path(MF.FileName),
9928 FileName, MF.Signature);
9929 }
9930 return std::nullopt;
9931 }
9932
9933 ExternalASTSource::ExtKind ASTReader::hasExternalDefinitions(const Decl *FD) {
9934 auto I = DefinitionSource.find(FD);
9935 if (I == DefinitionSource.end())
9936 return EK_ReplyHazy;
9937 return I->second ? EK_Never : EK_Always;
9938 }
9939
9940 bool ASTReader::wasThisDeclarationADefinition(const FunctionDecl *FD) {
9941 return ThisDeclarationWasADefinitionSet.contains(FD);
9942 }
9943
9944 Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
9945 return DecodeSelector(getGlobalSelectorID(M, LocalID));
9946 }
9947
9948 Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
9949 if (ID == 0)
9950 return Selector();
9951
9952 if (ID > SelectorsLoaded.size()) {
9953 Error("selector ID out of range in AST file");
9954 return Selector();
9955 }
9956
9957 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
9958 // Load this selector from the selector table.
9959 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
9960 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
9961 ModuleFile &M = *I->second;
9962 ASTSelectorLookupTrait Trait(*this, M);
9963 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
9964 SelectorsLoaded[ID - 1] =
9965 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
9966 if (DeserializationListener)
9967 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
9968 }
9969
9970 return SelectorsLoaded[ID - 1];
9971 }
9972
9973 Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
9974 return DecodeSelector(ID);
9975 }
9976
9977 uint32_t ASTReader::GetNumExternalSelectors() {
9978 // ID 0 (the null selector) is considered an external selector.
9979 return getTotalNumSelectors() + 1;
9980 }
9981
9982 serialization::SelectorID
9983 ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
9984 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
9985 return LocalID;
9986
9987 if (!M.ModuleOffsetMap.empty())
9988 ReadModuleOffsetMap(M);
9989
9990 ContinuousRangeMap<uint32_t, int, 2>::iterator I
9991 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
9992 assert(I != M.SelectorRemap.end()
9993 && "Invalid index into selector index remap");
9994
9995 return LocalID + I->second;
9996 }
9997
9998 DeclarationNameLoc
9999 ASTRecordReader::readDeclarationNameLoc(DeclarationName Name) {
10000 switch (Name.getNameKind()) {
10001 case DeclarationName::CXXConstructorName:
10002 case DeclarationName::CXXDestructorName:
10003 case DeclarationName::CXXConversionFunctionName:
10004 return DeclarationNameLoc::makeNamedTypeLoc(readTypeSourceInfo());
10005
10006 case DeclarationName::CXXOperatorName:
10007 return DeclarationNameLoc::makeCXXOperatorNameLoc(readSourceRange());
10008
10009 case DeclarationName::CXXLiteralOperatorName:
10010 return DeclarationNameLoc::makeCXXLiteralOperatorNameLoc(
10011 readSourceLocation());
10012
10013 case DeclarationName::Identifier:
10014 case DeclarationName::ObjCZeroArgSelector:
10015 case DeclarationName::ObjCOneArgSelector:
10016 case DeclarationName::ObjCMultiArgSelector:
10017 case DeclarationName::CXXUsingDirective:
10018 case DeclarationName::CXXDeductionGuideName:
10019 break;
10020 }
10021 return DeclarationNameLoc();
10022 }
10023
10024 DeclarationNameInfo ASTRecordReader::readDeclarationNameInfo() {
10025 DeclarationNameInfo NameInfo;
10026 NameInfo.setName(readDeclarationName());
10027 NameInfo.setLoc(readSourceLocation());
10028 NameInfo.setInfo(readDeclarationNameLoc(NameInfo.getName()));
10029 return NameInfo;
10030 }
10031
10032 TypeCoupledDeclRefInfo ASTRecordReader::readTypeCoupledDeclRefInfo() {
10033 return TypeCoupledDeclRefInfo(readDeclAs<ValueDecl>(), readBool());
10034 }
10035
10036 SpirvOperand ASTRecordReader::readHLSLSpirvOperand() {
10037 auto Kind = readInt();
10038 auto ResultType = readQualType();
10039 auto Value = readAPInt();
10040 SpirvOperand Op(SpirvOperand::SpirvOperandKind(Kind), ResultType, Value);
10041 assert(Op.isValid());
10042 return Op;
10043 }
10044
10045 void ASTRecordReader::readQualifierInfo(QualifierInfo &Info) {
10046 Info.QualifierLoc = readNestedNameSpecifierLoc();
10047 unsigned NumTPLists = readInt();
10048 Info.NumTemplParamLists = NumTPLists;
10049 if (NumTPLists) {
10050 Info.TemplParamLists =
10051 new (getContext()) TemplateParameterList *[NumTPLists];
10052 for (unsigned i = 0; i != NumTPLists; ++i)
10053 Info.TemplParamLists[i] = readTemplateParameterList();
10054 }
10055 }
10056
10057 TemplateParameterList *
10058 ASTRecordReader::readTemplateParameterList() {
10059 SourceLocation TemplateLoc = readSourceLocation();
10060 SourceLocation LAngleLoc = readSourceLocation();
10061 SourceLocation RAngleLoc = readSourceLocation();
10062
10063 unsigned NumParams = readInt();
10064 SmallVector<NamedDecl *, 16> Params;
10065 Params.reserve(NumParams);
10066 while (NumParams--)
10067 Params.push_back(readDeclAs<NamedDecl>());
10068
10069 bool HasRequiresClause = readBool();
10070 Expr *RequiresClause = HasRequiresClause ? readExpr() : nullptr;
10071
10072 TemplateParameterList *TemplateParams = TemplateParameterList::Create(
10073 getContext(), TemplateLoc, LAngleLoc, Params, RAngleLoc, RequiresClause);
10074 return TemplateParams;
10075 }
10076
10077 void ASTRecordReader::readTemplateArgumentList(
10078 SmallVectorImpl<TemplateArgument> &TemplArgs,
10079 bool Canonicalize) {
10080 unsigned NumTemplateArgs = readInt();
10081 TemplArgs.reserve(NumTemplateArgs);
10082 while (NumTemplateArgs--)
10083 TemplArgs.push_back(readTemplateArgument(Canonicalize));
10084 }
10085
10086 /// Read a UnresolvedSet structure.
10087 void ASTRecordReader::readUnresolvedSet(LazyASTUnresolvedSet &Set) {
10088 unsigned NumDecls = readInt();
10089 Set.reserve(getContext(), NumDecls);
10090 while (NumDecls--) {
10091 GlobalDeclID ID = readDeclID();
10092 AccessSpecifier AS = (AccessSpecifier) readInt();
10093 Set.addLazyDecl(getContext(), ID, AS);
10094 }
10095 }
10096
10097 CXXBaseSpecifier
10098 ASTRecordReader::readCXXBaseSpecifier() {
10099 bool isVirtual = readBool();
10100 bool isBaseOfClass = readBool();
10101 AccessSpecifier AS = static_cast<AccessSpecifier>(readInt());
10102 bool inheritConstructors = readBool();
10103 TypeSourceInfo *TInfo = readTypeSourceInfo();
10104 SourceRange Range = readSourceRange();
10105 SourceLocation EllipsisLoc = readSourceLocation();
10106 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
10107 EllipsisLoc);
10108 Result.setInheritConstructors(inheritConstructors);
10109 return Result;
10110 }
10111
10112 CXXCtorInitializer **
10113 ASTRecordReader::readCXXCtorInitializers() {
10114 ASTContext &Context = getContext();
10115 unsigned NumInitializers = readInt();
10116 assert(NumInitializers && "wrote ctor initializers but have no inits");
10117 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
10118 for (unsigned i = 0; i != NumInitializers; ++i) {
10119 TypeSourceInfo *TInfo = nullptr;
10120 bool IsBaseVirtual = false;
10121 FieldDecl *Member = nullptr;
10122 IndirectFieldDecl *IndirectMember = nullptr;
10123
10124 CtorInitializerType Type = (CtorInitializerType) readInt();
10125 switch (Type) {
10126 case CTOR_INITIALIZER_BASE:
10127 TInfo = readTypeSourceInfo();
10128 IsBaseVirtual = readBool();
10129 break;
10130
10131 case CTOR_INITIALIZER_DELEGATING:
10132 TInfo = readTypeSourceInfo();
10133 break;
10134
10135 case CTOR_INITIALIZER_MEMBER:
10136 Member = readDeclAs<FieldDecl>();
10137 break;
10138
10139 case CTOR_INITIALIZER_INDIRECT_MEMBER:
10140 IndirectMember = readDeclAs<IndirectFieldDecl>();
10141 break;
10142 }
10143
10144 SourceLocation MemberOrEllipsisLoc = readSourceLocation();
10145 Expr *Init = readExpr();
10146 SourceLocation LParenLoc = readSourceLocation();
10147 SourceLocation RParenLoc = readSourceLocation();
10148
10149 CXXCtorInitializer *BOMInit;
10150 if (Type == CTOR_INITIALIZER_BASE)
10151 BOMInit = new (Context)
10152 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
10153 RParenLoc, MemberOrEllipsisLoc);
10154 else if (Type == CTOR_INITIALIZER_DELEGATING)
10155 BOMInit = new (Context)
10156 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
10157 else if (Member)
10158 BOMInit = new (Context)
10159 CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc, LParenLoc,
10160 Init, RParenLoc);
10161 else
10162 BOMInit = new (Context)
10163 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
10164 LParenLoc, Init, RParenLoc);
10165
10166 if (/*IsWritten*/readBool()) {
10167 unsigned SourceOrder = readInt();
10168 BOMInit->setSourceOrder(SourceOrder);
10169 }
10170
10171 CtorInitializers[i] = BOMInit;
10172 }
10173
10174 return CtorInitializers;
10175 }
10176
10177 NestedNameSpecifierLoc
10178 ASTRecordReader::readNestedNameSpecifierLoc() {
10179 ASTContext &Context = getContext();
10180 unsigned N = readInt();
10181 NestedNameSpecifierLocBuilder Builder;
10182 for (unsigned I = 0; I != N; ++I) {
10183 auto Kind = readNestedNameSpecifierKind();
10184 switch (Kind) {
10185 case NestedNameSpecifier::Kind::Namespace: {
10186 auto *NS = readDeclAs<NamespaceBaseDecl>();
10187 SourceRange Range = readSourceRange();
10188 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
10189 break;
10190 }
10191
10192 case NestedNameSpecifier::Kind::Type: {
10193 TypeSourceInfo *T = readTypeSourceInfo();
10194 if (!T)
10195 return NestedNameSpecifierLoc();
10196 SourceLocation ColonColonLoc = readSourceLocation();
10197 Builder.Make(Context, T->getTypeLoc(), ColonColonLoc);
10198 break;
10199 }
10200
10201 case NestedNameSpecifier::Kind::Global: {
10202 SourceLocation ColonColonLoc = readSourceLocation();
10203 Builder.MakeGlobal(Context, ColonColonLoc);
10204 break;
10205 }
10206
10207 case NestedNameSpecifier::Kind::MicrosoftSuper: {
10208 CXXRecordDecl *RD = readDeclAs<CXXRecordDecl>();
10209 SourceRange Range = readSourceRange();
10210 Builder.MakeMicrosoftSuper(Context, RD, Range.getBegin(), Range.getEnd());
10211 break;
10212 }
10213
10214 case NestedNameSpecifier::Kind::Null:
10215 llvm_unreachable("unexpected null nested name specifier");
10216 }
10217 }
10218
10219 return Builder.getWithLocInContext(Context);
10220 }
10221
10222 SourceRange ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
10223 unsigned &Idx) {
10224 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
10225 SourceLocation end = ReadSourceLocation(F, Record, Idx);
10226 return SourceRange(beg, end);
10227 }
10228
10229 llvm::BitVector ASTReader::ReadBitVector(const RecordData &Record,
10230 const StringRef Blob) {
10231 unsigned Count = Record[0];
10232 const char *Byte = Blob.data();
10233 llvm::BitVector Ret = llvm::BitVector(Count, false);
10234 for (unsigned I = 0; I < Count; ++Byte)
10235 for (unsigned Bit = 0; Bit < 8 && I < Count; ++Bit, ++I)
10236 if (*Byte & (1 << Bit))
10237 Ret[I] = true;
10238 return Ret;
10239 }
10240
10241 /// Read a floating-point value
10242 llvm::APFloat ASTRecordReader::readAPFloat(const llvm::fltSemantics &Sem) {
10243 return llvm::APFloat(Sem, readAPInt());
10244 }
10245
10246 // Read a string
10247 std::string ASTReader::ReadString(const RecordDataImpl &Record, unsigned &Idx) {
10248 unsigned Len = Record[Idx++];
10249 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
10250 Idx += Len;
10251 return Result;
10252 }
10253
10254 StringRef ASTReader::ReadStringBlob(const RecordDataImpl &Record, unsigned &Idx,
10255 StringRef &Blob) {
10256 unsigned Len = Record[Idx++];
10257 StringRef Result = Blob.substr(0, Len);
10258 Blob = Blob.substr(Len);
10259 return Result;
10260 }
10261
10262 std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
10263 unsigned &Idx) {
10264 return ReadPath(F.BaseDirectory, Record, Idx);
10265 }
10266
10267 std::string ASTReader::ReadPath(StringRef BaseDirectory,
10268 const RecordData &Record, unsigned &Idx) {
10269 std::string Filename = ReadString(Record, Idx);
10270 return ResolveImportedPathAndAllocate(PathBuf, Filename, BaseDirectory);
10271 }
10272
10273 std::string ASTReader::ReadPathBlob(StringRef BaseDirectory,
10274 const RecordData &Record, unsigned &Idx,
10275 StringRef &Blob) {
10276 StringRef Filename = ReadStringBlob(Record, Idx, Blob);
10277 return ResolveImportedPathAndAllocate(PathBuf, Filename, BaseDirectory);
10278 }
10279
10280 VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
10281 unsigned &Idx) {
10282 unsigned Major = Record[Idx++];
10283 unsigned Minor = Record[Idx++];
10284 unsigned Subminor = Record[Idx++];
10285 if (Minor == 0)
10286 return VersionTuple(Major);
10287 if (Subminor == 0)
10288 return VersionTuple(Major, Minor - 1);
10289 return VersionTuple(Major, Minor - 1, Subminor - 1);
10290 }
10291
10292 CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
10293 const RecordData &Record,
10294 unsigned &Idx) {
10295 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
10296 return CXXTemporary::Create(getContext(), Decl);
10297 }
10298
10299 DiagnosticBuilder ASTReader::Diag(unsigned DiagID) const {
10300 return Diag(CurrentImportLoc, DiagID);
10301 }
10302
10303 DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) const {
10304 return Diags.Report(Loc, DiagID);
10305 }
10306
10307 void ASTReader::runWithSufficientStackSpace(SourceLocation Loc,
10308 llvm::function_ref<void()> Fn) {
10309 // When Sema is available, avoid duplicate errors.
10310 if (SemaObj) {
10311 SemaObj->runWithSufficientStackSpace(Loc, Fn);
10312 return;
10313 }
10314
10315 StackHandler.runWithSufficientStackSpace(Loc, Fn);
10316 }
10317
10318 /// Retrieve the identifier table associated with the
10319 /// preprocessor.
10320 IdentifierTable &ASTReader::getIdentifierTable() {
10321 return PP.getIdentifierTable();
10322 }
10323
10324 /// Record that the given ID maps to the given switch-case
10325 /// statement.
10326 void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
10327 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
10328 "Already have a SwitchCase with this ID");
10329 (*CurrSwitchCaseStmts)[ID] = SC;
10330 }
10331
10332 /// Retrieve the switch-case statement with the given ID.
10333 SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
10334 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
10335 return (*CurrSwitchCaseStmts)[ID];
10336 }
10337
10338 void ASTReader::ClearSwitchCaseIDs() {
10339 CurrSwitchCaseStmts->clear();
10340 }
10341
10342 void ASTReader::ReadComments() {
10343 ASTContext &Context = getContext();
10344 std::vector<RawComment *> Comments;
10345 for (SmallVectorImpl<std::pair<BitstreamCursor,
10346 serialization::ModuleFile *>>::iterator
10347 I = CommentsCursors.begin(),
10348 E = CommentsCursors.end();
10349 I != E; ++I) {
10350 Comments.clear();
10351 BitstreamCursor &Cursor = I->first;
10352 serialization::ModuleFile &F = *I->second;
10353 SavedStreamPosition SavedPosition(Cursor);
10354
10355 RecordData Record;
10356 while (true) {
10357 Expected<llvm::BitstreamEntry> MaybeEntry =
10358 Cursor.advanceSkippingSubblocks(
10359 BitstreamCursor::AF_DontPopBlockAtEnd);
10360 if (!MaybeEntry) {
10361 Error(MaybeEntry.takeError());
10362 return;
10363 }
10364 llvm::BitstreamEntry Entry = MaybeEntry.get();
10365
10366 switch (Entry.Kind) {
10367 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
10368 case llvm::BitstreamEntry::Error:
10369 Error("malformed block record in AST file");
10370 return;
10371 case llvm::BitstreamEntry::EndBlock:
10372 goto NextCursor;
10373 case llvm::BitstreamEntry::Record:
10374 // The interesting case.
10375 break;
10376 }
10377
10378 // Read a record.
10379 Record.clear();
10380 Expected<unsigned> MaybeComment = Cursor.readRecord(Entry.ID, Record);
10381 if (!MaybeComment) {
10382 Error(MaybeComment.takeError());
10383 return;
10384 }
10385 switch ((CommentRecordTypes)MaybeComment.get()) {
10386 case COMMENTS_RAW_COMMENT: {
10387 unsigned Idx = 0;
10388 SourceRange SR = ReadSourceRange(F, Record, Idx);
10389 RawComment::CommentKind Kind =
10390 (RawComment::CommentKind) Record[Idx++];
10391 bool IsTrailingComment = Record[Idx++];
10392 bool IsAlmostTrailingComment = Record[Idx++];
10393 Comments.push_back(new (Context) RawComment(
10394 SR, Kind, IsTrailingComment, IsAlmostTrailingComment));
10395 break;
10396 }
10397 }
10398 }
10399 NextCursor:
10400 for (RawComment *C : Comments) {
10401 SourceLocation CommentLoc = C->getBeginLoc();
10402 if (CommentLoc.isValid()) {
10403 FileIDAndOffset Loc = SourceMgr.getDecomposedLoc(CommentLoc);
10404 if (Loc.first.isValid())
10405 Context.Comments.OrderedComments[Loc.first].emplace(Loc.second, C);
10406 }
10407 }
10408 }
10409 }
10410
10411 void ASTReader::visitInputFileInfos(
10412 serialization::ModuleFile &MF, bool IncludeSystem,
10413 llvm::function_ref<void(const serialization::InputFileInfo &IFI,
10414 bool IsSystem)>
10415 Visitor) {
10416 unsigned NumUserInputs = MF.NumUserInputFiles;
10417 unsigned NumInputs = MF.InputFilesLoaded.size();
10418 assert(NumUserInputs <= NumInputs);
10419 unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
10420 for (unsigned I = 0; I < N; ++I) {
10421 bool IsSystem = I >= NumUserInputs;
10422 InputFileInfo IFI = getInputFileInfo(MF, I+1);
10423 Visitor(IFI, IsSystem);
10424 }
10425 }
10426
10427 void ASTReader::visitInputFiles(serialization::ModuleFile &MF,
10428 bool IncludeSystem, bool Complain,
10429 llvm::function_ref<void(const serialization::InputFile &IF,
10430 bool isSystem)> Visitor) {
10431 unsigned NumUserInputs = MF.NumUserInputFiles;
10432 unsigned NumInputs = MF.InputFilesLoaded.size();
10433 assert(NumUserInputs <= NumInputs);
10434 unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
10435 for (unsigned I = 0; I < N; ++I) {
10436 bool IsSystem = I >= NumUserInputs;
10437 InputFile IF = getInputFile(MF, I+1, Complain);
10438 Visitor(IF, IsSystem);
10439 }
10440 }
10441
10442 void ASTReader::visitTopLevelModuleMaps(
10443 serialization::ModuleFile &MF,
10444 llvm::function_ref<void(FileEntryRef FE)> Visitor) {
10445 unsigned NumInputs = MF.InputFilesLoaded.size();
10446 for (unsigned I = 0; I < NumInputs; ++I) {
10447 InputFileInfo IFI = getInputFileInfo(MF, I + 1);
10448 if (IFI.TopLevel && IFI.ModuleMap)
10449 if (auto FE = getInputFile(MF, I + 1).getFile())
10450 Visitor(*FE);
10451 }
10452 }
10453
10454 void ASTReader::finishPendingActions() {
10455 while (!PendingIdentifierInfos.empty() ||
10456 !PendingDeducedFunctionTypes.empty() ||
10457 !PendingDeducedVarTypes.empty() || !PendingDeclChains.empty() ||
10458 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
10459 !PendingUpdateRecords.empty() ||
10460 !PendingObjCExtensionIvarRedeclarations.empty()) {
10461 // If any identifiers with corresponding top-level declarations have
10462 // been loaded, load those declarations now.
10463 using TopLevelDeclsMap =
10464 llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2>>;
10465 TopLevelDeclsMap TopLevelDecls;
10466
10467 while (!PendingIdentifierInfos.empty()) {
10468 IdentifierInfo *II = PendingIdentifierInfos.back().first;
10469 SmallVector<GlobalDeclID, 4> DeclIDs =
10470 std::move(PendingIdentifierInfos.back().second);
10471 PendingIdentifierInfos.pop_back();
10472
10473 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
10474 }
10475
10476 // Load each function type that we deferred loading because it was a
10477 // deduced type that might refer to a local type declared within itself.
10478 for (unsigned I = 0; I != PendingDeducedFunctionTypes.size(); ++I) {
10479 auto *FD = PendingDeducedFunctionTypes[I].first;
10480 FD->setType(GetType(PendingDeducedFunctionTypes[I].second));
10481
10482 if (auto *DT = FD->getReturnType()->getContainedDeducedType()) {
10483 // If we gave a function a deduced return type, remember that we need to
10484 // propagate that along the redeclaration chain.
10485 if (DT->isDeduced()) {
10486 PendingDeducedTypeUpdates.insert(
10487 {FD->getCanonicalDecl(), FD->getReturnType()});
10488 continue;
10489 }
10490
10491 // The function has undeduced DeduceType return type. We hope we can
10492 // find the deduced type by iterating the redecls in other modules
10493 // later.
10494 PendingUndeducedFunctionDecls.push_back(FD);
10495 continue;
10496 }
10497 }
10498 PendingDeducedFunctionTypes.clear();
10499
10500 // Load each variable type that we deferred loading because it was a
10501 // deduced type that might refer to a local type declared within itself.
10502 for (unsigned I = 0; I != PendingDeducedVarTypes.size(); ++I) {
10503 auto *VD = PendingDeducedVarTypes[I].first;
10504 VD->setType(GetType(PendingDeducedVarTypes[I].second));
10505 }
10506 PendingDeducedVarTypes.clear();
10507
10508 // Load pending declaration chains.
10509 for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
10510 loadPendingDeclChain(PendingDeclChains[I].first,
10511 PendingDeclChains[I].second);
10512 PendingDeclChains.clear();
10513
10514 // Make the most recent of the top-level declarations visible.
10515 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
10516 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
10517 IdentifierInfo *II = TLD->first;
10518 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
10519 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
10520 }
10521 }
10522
10523 // Load any pending macro definitions.
10524 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
10525 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
10526 SmallVector<PendingMacroInfo, 2> GlobalIDs;
10527 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
10528 // Initialize the macro history from chained-PCHs ahead of module imports.
10529 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
10530 ++IDIdx) {
10531 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
10532 if (!Info.M->isModule())
10533 resolvePendingMacro(II, Info);
10534 }
10535 // Handle module imports.
10536 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
10537 ++IDIdx) {
10538 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
10539 if (Info.M->isModule())
10540 resolvePendingMacro(II, Info);
10541 }
10542 }
10543 PendingMacroIDs.clear();
10544
10545 // Wire up the DeclContexts for Decls that we delayed setting until
10546 // recursive loading is completed.
10547 while (!PendingDeclContextInfos.empty()) {
10548 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
10549 PendingDeclContextInfos.pop_front();
10550 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
10551 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
10552 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
10553 }
10554
10555 // Perform any pending declaration updates.
10556 while (!PendingUpdateRecords.empty()) {
10557 auto Update = PendingUpdateRecords.pop_back_val();
10558 ReadingKindTracker ReadingKind(Read_Decl, *this);
10559 loadDeclUpdateRecords(Update);
10560 }
10561
10562 while (!PendingObjCExtensionIvarRedeclarations.empty()) {
10563 auto ExtensionsPair = PendingObjCExtensionIvarRedeclarations.back().first;
10564 auto DuplicateIvars =
10565 PendingObjCExtensionIvarRedeclarations.back().second;
10566 StructuralEquivalenceContext::NonEquivalentDeclSet NonEquivalentDecls;
10567 StructuralEquivalenceContext Ctx(
10568 ContextObj->getLangOpts(), ExtensionsPair.first->getASTContext(),
10569 ExtensionsPair.second->getASTContext(), NonEquivalentDecls,
10570 StructuralEquivalenceKind::Default, /*StrictTypeSpelling =*/false,
10571 /*Complain =*/false,
10572 /*ErrorOnTagTypeMismatch =*/true);
10573 if (Ctx.IsEquivalent(ExtensionsPair.first, ExtensionsPair.second)) {
10574 // Merge redeclared ivars with their predecessors.
10575 for (auto IvarPair : DuplicateIvars) {
10576 ObjCIvarDecl *Ivar = IvarPair.first, *PrevIvar = IvarPair.second;
10577 // Change semantic DeclContext but keep the lexical one.
10578 Ivar->setDeclContextsImpl(PrevIvar->getDeclContext(),
10579 Ivar->getLexicalDeclContext(),
10580 getContext());
10581 getContext().setPrimaryMergedDecl(Ivar, PrevIvar->getCanonicalDecl());
10582 }
10583 // Invalidate duplicate extension and the cached ivar list.
10584 ExtensionsPair.first->setInvalidDecl();
10585 ExtensionsPair.second->getClassInterface()
10586 ->getDefinition()
10587 ->setIvarList(nullptr);
10588 } else {
10589 for (auto IvarPair : DuplicateIvars) {
10590 Diag(IvarPair.first->getLocation(),
10591 diag::err_duplicate_ivar_declaration)
10592 << IvarPair.first->getIdentifier();
10593 Diag(IvarPair.second->getLocation(), diag::note_previous_definition);
10594 }
10595 }
10596 PendingObjCExtensionIvarRedeclarations.pop_back();
10597 }
10598 }
10599
10600 // At this point, all update records for loaded decls are in place, so any
10601 // fake class definitions should have become real.
10602 assert(PendingFakeDefinitionData.empty() &&
10603 "faked up a class definition but never saw the real one");
10604
10605 // If we deserialized any C++ or Objective-C class definitions, any
10606 // Objective-C protocol definitions, or any redeclarable templates, make sure
10607 // that all redeclarations point to the definitions. Note that this can only
10608 // happen now, after the redeclaration chains have been fully wired.
10609 for (Decl *D : PendingDefinitions) {
10610 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
10611 if (auto *RD = dyn_cast<CXXRecordDecl>(TD)) {
10612 for (auto *R = getMostRecentExistingDecl(RD); R;
10613 R = R->getPreviousDecl()) {
10614 assert((R == D) ==
10615 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
10616 "declaration thinks it's the definition but it isn't");
10617 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
10618 }
10619 }
10620
10621 continue;
10622 }
10623
10624 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
10625 // Make sure that the ObjCInterfaceType points at the definition.
10626 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
10627 ->Decl = ID;
10628
10629 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
10630 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
10631
10632 continue;
10633 }
10634
10635 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
10636 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
10637 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
10638
10639 continue;
10640 }
10641
10642 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
10643 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
10644 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
10645 }
10646 PendingDefinitions.clear();
10647
10648 for (auto [D, Previous] : PendingWarningForDuplicatedDefsInModuleUnits) {
10649 auto hasDefinitionImpl = [this](Decl *D, auto hasDefinitionImpl) {
10650 if (auto *VD = dyn_cast<VarDecl>(D))
10651 return VD->isThisDeclarationADefinition() ||
10652 VD->isThisDeclarationADemotedDefinition();
10653
10654 if (auto *TD = dyn_cast<TagDecl>(D))
10655 return TD->isThisDeclarationADefinition() ||
10656 TD->isThisDeclarationADemotedDefinition();
10657
10658 if (auto *FD = dyn_cast<FunctionDecl>(D))
10659 return FD->isThisDeclarationADefinition() || PendingBodies.count(FD);
10660
10661 if (auto *RTD = dyn_cast<RedeclarableTemplateDecl>(D))
10662 return hasDefinitionImpl(RTD->getTemplatedDecl(), hasDefinitionImpl);
10663
10664 // Conservatively return false here.
10665 return false;
10666 };
10667
10668 auto hasDefinition = [&hasDefinitionImpl](Decl *D) {
10669 return hasDefinitionImpl(D, hasDefinitionImpl);
10670 };
10671
10672 // It is not good to prevent multiple declarations since the forward
10673 // declaration is common. Let's try to avoid duplicated definitions
10674 // only.
10675 if (!hasDefinition(D) || !hasDefinition(Previous))
10676 continue;
10677
10678 Module *PM = Previous->getOwningModule();
10679 Module *DM = D->getOwningModule();
10680 Diag(D->getLocation(), diag::warn_decls_in_multiple_modules)
10681 << cast<NamedDecl>(Previous) << PM->getTopLevelModuleName()
10682 << (DM ? DM->getTopLevelModuleName() : "global module");
10683 Diag(Previous->getLocation(), diag::note_also_found);
10684 }
10685 PendingWarningForDuplicatedDefsInModuleUnits.clear();
10686
10687 // Load the bodies of any functions or methods we've encountered. We do
10688 // this now (delayed) so that we can be sure that the declaration chains
10689 // have been fully wired up (hasBody relies on this).
10690 // FIXME: We shouldn't require complete redeclaration chains here.
10691 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
10692 PBEnd = PendingBodies.end();
10693 PB != PBEnd; ++PB) {
10694 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
10695 // FIXME: Check for =delete/=default?
10696 const FunctionDecl *Defn = nullptr;
10697 if (!getContext().getLangOpts().Modules || !FD->hasBody(Defn)) {
10698 FD->setLazyBody(PB->second);
10699 } else {
10700 auto *NonConstDefn = const_cast<FunctionDecl*>(Defn);
10701 mergeDefinitionVisibility(NonConstDefn, FD);
10702
10703 if (!FD->isLateTemplateParsed() &&
10704 !NonConstDefn->isLateTemplateParsed() &&
10705 // We only perform ODR checks for decls not in the explicit
10706 // global module fragment.
10707 !shouldSkipCheckingODR(FD) &&
10708 !shouldSkipCheckingODR(NonConstDefn) &&
10709 FD->getODRHash() != NonConstDefn->getODRHash()) {
10710 if (!isa<CXXMethodDecl>(FD)) {
10711 PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
10712 } else if (FD->getLexicalParent()->isFileContext() &&
10713 NonConstDefn->getLexicalParent()->isFileContext()) {
10714 // Only diagnose out-of-line method definitions. If they are
10715 // in class definitions, then an error will be generated when
10716 // processing the class bodies.
10717 PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
10718 }
10719 }
10720 }
10721 continue;
10722 }
10723
10724 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
10725 if (!getContext().getLangOpts().Modules || !MD->hasBody())
10726 MD->setLazyBody(PB->second);
10727 }
10728 PendingBodies.clear();
10729
10730 // Inform any classes that had members added that they now have more members.
10731 for (auto [RD, MD] : PendingAddedClassMembers) {
10732 RD->addedMember(MD);
10733 }
10734 PendingAddedClassMembers.clear();
10735
10736 // Do some cleanup.
10737 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
10738 getContext().deduplicateMergedDefinitionsFor(ND);
10739 PendingMergedDefinitionsToDeduplicate.clear();
10740
10741 // For each decl chain that we wanted to complete while deserializing, mark
10742 // it as "still needs to be completed".
10743 for (Decl *D : PendingIncompleteDeclChains)
10744 markIncompleteDeclChain(D);
10745 PendingIncompleteDeclChains.clear();
10746
10747 assert(PendingIdentifierInfos.empty() &&
10748 "Should be empty at the end of finishPendingActions");
10749 assert(PendingDeducedFunctionTypes.empty() &&
10750 "Should be empty at the end of finishPendingActions");
10751 assert(PendingDeducedVarTypes.empty() &&
10752 "Should be empty at the end of finishPendingActions");
10753 assert(PendingDeclChains.empty() &&
10754 "Should be empty at the end of finishPendingActions");
10755 assert(PendingMacroIDs.empty() &&
10756 "Should be empty at the end of finishPendingActions");
10757 assert(PendingDeclContextInfos.empty() &&
10758 "Should be empty at the end of finishPendingActions");
10759 assert(PendingUpdateRecords.empty() &&
10760 "Should be empty at the end of finishPendingActions");
10761 assert(PendingObjCExtensionIvarRedeclarations.empty() &&
10762 "Should be empty at the end of finishPendingActions");
10763 assert(PendingFakeDefinitionData.empty() &&
10764 "Should be empty at the end of finishPendingActions");
10765 assert(PendingDefinitions.empty() &&
10766 "Should be empty at the end of finishPendingActions");
10767 assert(PendingWarningForDuplicatedDefsInModuleUnits.empty() &&
10768 "Should be empty at the end of finishPendingActions");
10769 assert(PendingBodies.empty() &&
10770 "Should be empty at the end of finishPendingActions");
10771 assert(PendingAddedClassMembers.empty() &&
10772 "Should be empty at the end of finishPendingActions");
10773 assert(PendingMergedDefinitionsToDeduplicate.empty() &&
10774 "Should be empty at the end of finishPendingActions");
10775 assert(PendingIncompleteDeclChains.empty() &&
10776 "Should be empty at the end of finishPendingActions");
10777 }
10778
10779 void ASTReader::diagnoseOdrViolations() {
10780 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty() &&
10781 PendingRecordOdrMergeFailures.empty() &&
10782 PendingFunctionOdrMergeFailures.empty() &&
10783 PendingEnumOdrMergeFailures.empty() &&
10784 PendingObjCInterfaceOdrMergeFailures.empty() &&
10785 PendingObjCProtocolOdrMergeFailures.empty())
10786 return;
10787
10788 // Trigger the import of the full definition of each class that had any
10789 // odr-merging problems, so we can produce better diagnostics for them.
10790 // These updates may in turn find and diagnose some ODR failures, so take
10791 // ownership of the set first.
10792 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
10793 PendingOdrMergeFailures.clear();
10794 for (auto &Merge : OdrMergeFailures) {
10795 Merge.first->buildLookup();
10796 Merge.first->decls_begin();
10797 Merge.first->bases_begin();
10798 Merge.first->vbases_begin();
10799 for (auto &RecordPair : Merge.second) {
10800 auto *RD = RecordPair.first;
10801 RD->decls_begin();
10802 RD->bases_begin();
10803 RD->vbases_begin();
10804 }
10805 }
10806
10807 // Trigger the import of the full definition of each record in C/ObjC.
10808 auto RecordOdrMergeFailures = std::move(PendingRecordOdrMergeFailures);
10809 PendingRecordOdrMergeFailures.clear();
10810 for (auto &Merge : RecordOdrMergeFailures) {
10811 Merge.first->decls_begin();
10812 for (auto &D : Merge.second)
10813 D->decls_begin();
10814 }
10815
10816 // Trigger the import of the full interface definition.
10817 auto ObjCInterfaceOdrMergeFailures =
10818 std::move(PendingObjCInterfaceOdrMergeFailures);
10819 PendingObjCInterfaceOdrMergeFailures.clear();
10820 for (auto &Merge : ObjCInterfaceOdrMergeFailures) {
10821 Merge.first->decls_begin();
10822 for (auto &InterfacePair : Merge.second)
10823 InterfacePair.first->decls_begin();
10824 }
10825
10826 // Trigger the import of functions.
10827 auto FunctionOdrMergeFailures = std::move(PendingFunctionOdrMergeFailures);
10828 PendingFunctionOdrMergeFailures.clear();
10829 for (auto &Merge : FunctionOdrMergeFailures) {
10830 Merge.first->buildLookup();
10831 Merge.first->decls_begin();
10832 Merge.first->getBody();
10833 for (auto &FD : Merge.second) {
10834 FD->buildLookup();
10835 FD->decls_begin();
10836 FD->getBody();
10837 }
10838 }
10839
10840 // Trigger the import of enums.
10841 auto EnumOdrMergeFailures = std::move(PendingEnumOdrMergeFailures);
10842 PendingEnumOdrMergeFailures.clear();
10843 for (auto &Merge : EnumOdrMergeFailures) {
10844 Merge.first->decls_begin();
10845 for (auto &Enum : Merge.second) {
10846 Enum->decls_begin();
10847 }
10848 }
10849
10850 // Trigger the import of the full protocol definition.
10851 auto ObjCProtocolOdrMergeFailures =
10852 std::move(PendingObjCProtocolOdrMergeFailures);
10853 PendingObjCProtocolOdrMergeFailures.clear();
10854 for (auto &Merge : ObjCProtocolOdrMergeFailures) {
10855 Merge.first->decls_begin();
10856 for (auto &ProtocolPair : Merge.second)
10857 ProtocolPair.first->decls_begin();
10858 }
10859
10860 // For each declaration from a merged context, check that the canonical
10861 // definition of that context also contains a declaration of the same
10862 // entity.
10863 //
10864 // Caution: this loop does things that might invalidate iterators into
10865 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
10866 while (!PendingOdrMergeChecks.empty()) {
10867 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
10868
10869 // FIXME: Skip over implicit declarations for now. This matters for things
10870 // like implicitly-declared special member functions. This isn't entirely
10871 // correct; we can end up with multiple unmerged declarations of the same
10872 // implicit entity.
10873 if (D->isImplicit())
10874 continue;
10875
10876 DeclContext *CanonDef = D->getDeclContext();
10877
10878 bool Found = false;
10879 const Decl *DCanon = D->getCanonicalDecl();
10880
10881 for (auto *RI : D->redecls()) {
10882 if (RI->getLexicalDeclContext() == CanonDef) {
10883 Found = true;
10884 break;
10885 }
10886 }
10887 if (Found)
10888 continue;
10889
10890 // Quick check failed, time to do the slow thing. Note, we can't just
10891 // look up the name of D in CanonDef here, because the member that is
10892 // in CanonDef might not be found by name lookup (it might have been
10893 // replaced by a more recent declaration in the lookup table), and we
10894 // can't necessarily find it in the redeclaration chain because it might
10895 // be merely mergeable, not redeclarable.
10896 llvm::SmallVector<const NamedDecl*, 4> Candidates;
10897 for (auto *CanonMember : CanonDef->decls()) {
10898 if (CanonMember->getCanonicalDecl() == DCanon) {
10899 // This can happen if the declaration is merely mergeable and not
10900 // actually redeclarable (we looked for redeclarations earlier).
10901 //
10902 // FIXME: We should be able to detect this more efficiently, without
10903 // pulling in all of the members of CanonDef.
10904 Found = true;
10905 break;
10906 }
10907 if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
10908 if (ND->getDeclName() == D->getDeclName())
10909 Candidates.push_back(ND);
10910 }
10911
10912 if (!Found) {
10913 // The AST doesn't like TagDecls becoming invalid after they've been
10914 // completed. We only really need to mark FieldDecls as invalid here.
10915 if (!isa<TagDecl>(D))
10916 D->setInvalidDecl();
10917
10918 // Ensure we don't accidentally recursively enter deserialization while
10919 // we're producing our diagnostic.
10920 Deserializing RecursionGuard(this);
10921
10922 std::string CanonDefModule =
10923 ODRDiagsEmitter::getOwningModuleNameForDiagnostic(
10924 cast<Decl>(CanonDef));
10925 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
10926 << D << ODRDiagsEmitter::getOwningModuleNameForDiagnostic(D)
10927 << CanonDef << CanonDefModule.empty() << CanonDefModule;
10928
10929 if (Candidates.empty())
10930 Diag(cast<Decl>(CanonDef)->getLocation(),
10931 diag::note_module_odr_violation_no_possible_decls) << D;
10932 else {
10933 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
10934 Diag(Candidates[I]->getLocation(),
10935 diag::note_module_odr_violation_possible_decl)
10936 << Candidates[I];
10937 }
10938
10939 DiagnosedOdrMergeFailures.insert(CanonDef);
10940 }
10941 }
10942
10943 if (OdrMergeFailures.empty() && RecordOdrMergeFailures.empty() &&
10944 FunctionOdrMergeFailures.empty() && EnumOdrMergeFailures.empty() &&
10945 ObjCInterfaceOdrMergeFailures.empty() &&
10946 ObjCProtocolOdrMergeFailures.empty())
10947 return;
10948
10949 ODRDiagsEmitter DiagsEmitter(Diags, getContext(),
10950 getPreprocessor().getLangOpts());
10951
10952 // Issue any pending ODR-failure diagnostics.
10953 for (auto &Merge : OdrMergeFailures) {
10954 // If we've already pointed out a specific problem with this class, don't
10955 // bother issuing a general "something's different" diagnostic.
10956 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
10957 continue;
10958
10959 bool Diagnosed = false;
10960 CXXRecordDecl *FirstRecord = Merge.first;
10961 for (auto &RecordPair : Merge.second) {
10962 if (DiagsEmitter.diagnoseMismatch(FirstRecord, RecordPair.first,
10963 RecordPair.second)) {
10964 Diagnosed = true;
10965 break;
10966 }
10967 }
10968
10969 if (!Diagnosed) {
10970 // All definitions are updates to the same declaration. This happens if a
10971 // module instantiates the declaration of a class template specialization
10972 // and two or more other modules instantiate its definition.
10973 //
10974 // FIXME: Indicate which modules had instantiations of this definition.
10975 // FIXME: How can this even happen?
10976 Diag(Merge.first->getLocation(),
10977 diag::err_module_odr_violation_different_instantiations)
10978 << Merge.first;
10979 }
10980 }
10981
10982 // Issue any pending ODR-failure diagnostics for RecordDecl in C/ObjC. Note
10983 // that in C++ this is done as a part of CXXRecordDecl ODR checking.
10984 for (auto &Merge : RecordOdrMergeFailures) {
10985 // If we've already pointed out a specific problem with this class, don't
10986 // bother issuing a general "something's different" diagnostic.
10987 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
10988 continue;
10989
10990 RecordDecl *FirstRecord = Merge.first;
10991 bool Diagnosed = false;
10992 for (auto *SecondRecord : Merge.second) {
10993 if (DiagsEmitter.diagnoseMismatch(FirstRecord, SecondRecord)) {
10994 Diagnosed = true;
10995 break;
10996 }
10997 }
10998 (void)Diagnosed;
10999 assert(Diagnosed && "Unable to emit ODR diagnostic.");
11000 }
11001
11002 // Issue ODR failures diagnostics for functions.
11003 for (auto &Merge : FunctionOdrMergeFailures) {
11004 FunctionDecl *FirstFunction = Merge.first;
11005 bool Diagnosed = false;
11006 for (auto &SecondFunction : Merge.second) {
11007 if (DiagsEmitter.diagnoseMismatch(FirstFunction, SecondFunction)) {
11008 Diagnosed = true;
11009 break;
11010 }
11011 }
11012 (void)Diagnosed;
11013 assert(Diagnosed && "Unable to emit ODR diagnostic.");
11014 }
11015
11016 // Issue ODR failures diagnostics for enums.
11017 for (auto &Merge : EnumOdrMergeFailures) {
11018 // If we've already pointed out a specific problem with this enum, don't
11019 // bother issuing a general "something's different" diagnostic.
11020 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
11021 continue;
11022
11023 EnumDecl *FirstEnum = Merge.first;
11024 bool Diagnosed = false;
11025 for (auto &SecondEnum : Merge.second) {
11026 if (DiagsEmitter.diagnoseMismatch(FirstEnum, SecondEnum)) {
11027 Diagnosed = true;
11028 break;
11029 }
11030 }
11031 (void)Diagnosed;
11032 assert(Diagnosed && "Unable to emit ODR diagnostic.");
11033 }
11034
11035 for (auto &Merge : ObjCInterfaceOdrMergeFailures) {
11036 // If we've already pointed out a specific problem with this interface,
11037 // don't bother issuing a general "something's different" diagnostic.
11038 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
11039 continue;
11040
11041 bool Diagnosed = false;
11042 ObjCInterfaceDecl *FirstID = Merge.first;
11043 for (auto &InterfacePair : Merge.second) {
11044 if (DiagsEmitter.diagnoseMismatch(FirstID, InterfacePair.first,
11045 InterfacePair.second)) {
11046 Diagnosed = true;
11047 break;
11048 }
11049 }
11050 (void)Diagnosed;
11051 assert(Diagnosed && "Unable to emit ODR diagnostic.");
11052 }
11053
11054 for (auto &Merge : ObjCProtocolOdrMergeFailures) {
11055 // If we've already pointed out a specific problem with this protocol,
11056 // don't bother issuing a general "something's different" diagnostic.
11057 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
11058 continue;
11059
11060 ObjCProtocolDecl *FirstProtocol = Merge.first;
11061 bool Diagnosed = false;
11062 for (auto &ProtocolPair : Merge.second) {
11063 if (DiagsEmitter.diagnoseMismatch(FirstProtocol, ProtocolPair.first,
11064 ProtocolPair.second)) {
11065 Diagnosed = true;
11066 break;
11067 }
11068 }
11069 (void)Diagnosed;
11070 assert(Diagnosed && "Unable to emit ODR diagnostic.");
11071 }
11072 }
11073
11074 void ASTReader::StartedDeserializing() {
11075 if (llvm::Timer *T = ReadTimer.get();
11076 ++NumCurrentElementsDeserializing == 1 && T)
11077 ReadTimeRegion.emplace(T);
11078 }
11079
11080 void ASTReader::FinishedDeserializing() {
11081 assert(NumCurrentElementsDeserializing &&
11082 "FinishedDeserializing not paired with StartedDeserializing");
11083 if (NumCurrentElementsDeserializing == 1) {
11084 // We decrease NumCurrentElementsDeserializing only after pending actions
11085 // are finished, to avoid recursively re-calling finishPendingActions().
11086 finishPendingActions();
11087 }
11088 --NumCurrentElementsDeserializing;
11089
11090 if (NumCurrentElementsDeserializing == 0) {
11091 {
11092 // Guard variable to avoid recursively entering the process of passing
11093 // decls to consumer.
11094 SaveAndRestore GuardPassingDeclsToConsumer(CanPassDeclsToConsumer,
11095 /*NewValue=*/false);
11096
11097 // Propagate exception specification and deduced type updates along
11098 // redeclaration chains.
11099 //
11100 // We do this now rather than in finishPendingActions because we want to
11101 // be able to walk the complete redeclaration chains of the updated decls.
11102 while (!PendingExceptionSpecUpdates.empty() ||
11103 !PendingDeducedTypeUpdates.empty() ||
11104 !PendingUndeducedFunctionDecls.empty()) {
11105 auto ESUpdates = std::move(PendingExceptionSpecUpdates);
11106 PendingExceptionSpecUpdates.clear();
11107 for (auto Update : ESUpdates) {
11108 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
11109 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
11110 auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
11111 if (auto *Listener = getContext().getASTMutationListener())
11112 Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
11113 for (auto *Redecl : Update.second->redecls())
11114 getContext().adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
11115 }
11116
11117 auto DTUpdates = std::move(PendingDeducedTypeUpdates);
11118 PendingDeducedTypeUpdates.clear();
11119 for (auto Update : DTUpdates) {
11120 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
11121 // FIXME: If the return type is already deduced, check that it
11122 // matches.
11123 getContext().adjustDeducedFunctionResultType(Update.first,
11124 Update.second);
11125 }
11126
11127 auto UDTUpdates = std::move(PendingUndeducedFunctionDecls);
11128 PendingUndeducedFunctionDecls.clear();
11129 // We hope we can find the deduced type for the functions by iterating
11130 // redeclarations in other modules.
11131 for (FunctionDecl *UndeducedFD : UDTUpdates)
11132 (void)UndeducedFD->getMostRecentDecl();
11133 }
11134
11135 ReadTimeRegion.reset();
11136
11137 diagnoseOdrViolations();
11138 }
11139
11140 // We are not in recursive loading, so it's safe to pass the "interesting"
11141 // decls to the consumer.
11142 if (Consumer)
11143 PassInterestingDeclsToConsumer();
11144 }
11145 }
11146
11147 void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
11148 if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) {
11149 // Remove any fake results before adding any real ones.
11150 auto It = PendingFakeLookupResults.find(II);
11151 if (It != PendingFakeLookupResults.end()) {
11152 for (auto *ND : It->second)
11153 SemaObj->IdResolver.RemoveDecl(ND);
11154 // FIXME: this works around module+PCH performance issue.
11155 // Rather than erase the result from the map, which is O(n), just clear
11156 // the vector of NamedDecls.
11157 It->second.clear();
11158 }
11159 }
11160
11161 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
11162 SemaObj->TUScope->AddDecl(D);
11163 } else if (SemaObj->TUScope) {
11164 // Adding the decl to IdResolver may have failed because it was already in
11165 // (even though it was not added in scope). If it is already in, make sure
11166 // it gets in the scope as well.
11167 if (llvm::is_contained(SemaObj->IdResolver.decls(Name), D))
11168 SemaObj->TUScope->AddDecl(D);
11169 }
11170 }
11171
11172 ASTReader::ASTReader(Preprocessor &PP, ModuleCache &ModCache,
11173 ASTContext *Context,
11174 const PCHContainerReader &PCHContainerRdr,
11175 const CodeGenOptions &CodeGenOpts,
11176 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
11177 StringRef isysroot,
11178 DisableValidationForModuleKind DisableValidationKind,
11179 bool AllowASTWithCompilerErrors,
11180 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
11181 bool ForceValidateUserInputs,
11182 bool ValidateASTInputFilesContent, bool UseGlobalIndex,
11183 std::unique_ptr<llvm::Timer> ReadTimer)
11184 : Listener(bool(DisableValidationKind & DisableValidationForModuleKind::PCH)
11185 ? cast<ASTReaderListener>(new SimpleASTReaderListener(PP))
11186 : cast<ASTReaderListener>(new PCHValidator(PP, *this))),
11187 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
11188 PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()),
11189 StackHandler(Diags), PP(PP), ContextObj(Context),
11190 CodeGenOpts(CodeGenOpts),
11191 ModuleMgr(PP.getFileManager(), ModCache, PCHContainerRdr,
11192 PP.getHeaderSearchInfo()),
11193 DummyIdResolver(PP), ReadTimer(std::move(ReadTimer)), isysroot(isysroot),
11194 DisableValidationKind(DisableValidationKind),
11195 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
11196 AllowConfigurationMismatch(AllowConfigurationMismatch),
11197 ValidateSystemInputs(ValidateSystemInputs),
11198 ForceValidateUserInputs(ForceValidateUserInputs),
11199 ValidateASTInputFilesContent(ValidateASTInputFilesContent),
11200 UseGlobalIndex(UseGlobalIndex), CurrSwitchCaseStmts(&SwitchCaseStmts) {
11201 SourceMgr.setExternalSLocEntrySource(this);
11202
11203 PathBuf.reserve(256);
11204
11205 for (const auto &Ext : Extensions) {
11206 auto BlockName = Ext->getExtensionMetadata().BlockName;
11207 auto Known = ModuleFileExtensions.find(BlockName);
11208 if (Known != ModuleFileExtensions.end()) {
11209 Diags.Report(diag::warn_duplicate_module_file_extension)
11210 << BlockName;
11211 continue;
11212 }
11213
11214 ModuleFileExtensions.insert({BlockName, Ext});
11215 }
11216 }
11217
11218 ASTReader::~ASTReader() {
11219 if (OwnsDeserializationListener)
11220 delete DeserializationListener;
11221 }
11222
11223 IdentifierResolver &ASTReader::getIdResolver() {
11224 return SemaObj ? SemaObj->IdResolver : DummyIdResolver;
11225 }
11226
11227 Expected<unsigned> ASTRecordReader::readRecord(llvm::BitstreamCursor &Cursor,
11228 unsigned AbbrevID) {
11229 Idx = 0;
11230 Record.clear();
11231 return Cursor.readRecord(AbbrevID, Record);
11232 }
11233 //===----------------------------------------------------------------------===//
11234 //// OMPClauseReader implementation
11235 ////===----------------------------------------------------------------------===//
11236
11237 // This has to be in namespace clang because it's friended by all
11238 // of the OMP clauses.
11239 namespace clang {
11240
11241 class OMPClauseReader : public OMPClauseVisitor<OMPClauseReader> {
11242 ASTRecordReader &Record;
11243 ASTContext &Context;
11244
11245 public:
11246 OMPClauseReader(ASTRecordReader &Record)
11247 : Record(Record), Context(Record.getContext()) {}
11248 #define GEN_CLANG_CLAUSE_CLASS
11249 #define CLAUSE_CLASS(Enum, Str, Class) void Visit##Class(Class *C);
11250 #include "llvm/Frontend/OpenMP/OMP.inc"
11251 OMPClause *readClause();
11252 void VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C);
11253 void VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C);
11254 };
11255
11256 } // end namespace clang
11257
11258 OMPClause *ASTRecordReader::readOMPClause() {
11259 return OMPClauseReader(*this).readClause();
11260 }
11261
11262 OMPClause *OMPClauseReader::readClause() {
11263 OMPClause *C = nullptr;
11264 switch (llvm::omp::Clause(Record.readInt())) {
11265 case llvm::omp::OMPC_if:
11266 C = new (Context) OMPIfClause();
11267 break;
11268 case llvm::omp::OMPC_final:
11269 C = new (Context) OMPFinalClause();
11270 break;
11271 case llvm::omp::OMPC_num_threads:
11272 C = new (Context) OMPNumThreadsClause();
11273 break;
11274 case llvm::omp::OMPC_safelen:
11275 C = new (Context) OMPSafelenClause();
11276 break;
11277 case llvm::omp::OMPC_simdlen:
11278 C = new (Context) OMPSimdlenClause();
11279 break;
11280 case llvm::omp::OMPC_sizes: {
11281 unsigned NumSizes = Record.readInt();
11282 C = OMPSizesClause::CreateEmpty(Context, NumSizes);
11283 break;
11284 }
11285 case llvm::omp::OMPC_permutation: {
11286 unsigned NumLoops = Record.readInt();
11287 C = OMPPermutationClause::CreateEmpty(Context, NumLoops);
11288 break;
11289 }
11290 case llvm::omp::OMPC_full:
11291 C = OMPFullClause::CreateEmpty(Context);
11292 break;
11293 case llvm::omp::OMPC_partial:
11294 C = OMPPartialClause::CreateEmpty(Context);
11295 break;
11296 case llvm::omp::OMPC_looprange:
11297 C = OMPLoopRangeClause::CreateEmpty(Context);
11298 break;
11299 case llvm::omp::OMPC_allocator:
11300 C = new (Context) OMPAllocatorClause();
11301 break;
11302 case llvm::omp::OMPC_collapse:
11303 C = new (Context) OMPCollapseClause();
11304 break;
11305 case llvm::omp::OMPC_default:
11306 C = new (Context) OMPDefaultClause();
11307 break;
11308 case llvm::omp::OMPC_proc_bind:
11309 C = new (Context) OMPProcBindClause();
11310 break;
11311 case llvm::omp::OMPC_schedule:
11312 C = new (Context) OMPScheduleClause();
11313 break;
11314 case llvm::omp::OMPC_ordered:
11315 C = OMPOrderedClause::CreateEmpty(Context, Record.readInt());
11316 break;
11317 case llvm::omp::OMPC_nowait:
11318 C = new (Context) OMPNowaitClause();
11319 break;
11320 case llvm::omp::OMPC_untied:
11321 C = new (Context) OMPUntiedClause();
11322 break;
11323 case llvm::omp::OMPC_mergeable:
11324 C = new (Context) OMPMergeableClause();
11325 break;
11326 case llvm::omp::OMPC_threadset:
11327 C = new (Context) OMPThreadsetClause();
11328 break;
11329 case llvm::omp::OMPC_read:
11330 C = new (Context) OMPReadClause();
11331 break;
11332 case llvm::omp::OMPC_write:
11333 C = new (Context) OMPWriteClause();
11334 break;
11335 case llvm::omp::OMPC_update:
11336 C = OMPUpdateClause::CreateEmpty(Context, Record.readInt());
11337 break;
11338 case llvm::omp::OMPC_capture:
11339 C = new (Context) OMPCaptureClause();
11340 break;
11341 case llvm::omp::OMPC_compare:
11342 C = new (Context) OMPCompareClause();
11343 break;
11344 case llvm::omp::OMPC_fail:
11345 C = new (Context) OMPFailClause();
11346 break;
11347 case llvm::omp::OMPC_seq_cst:
11348 C = new (Context) OMPSeqCstClause();
11349 break;
11350 case llvm::omp::OMPC_acq_rel:
11351 C = new (Context) OMPAcqRelClause();
11352 break;
11353 case llvm::omp::OMPC_absent: {
11354 unsigned NumKinds = Record.readInt();
11355 C = OMPAbsentClause::CreateEmpty(Context, NumKinds);
11356 break;
11357 }
11358 case llvm::omp::OMPC_holds:
11359 C = new (Context) OMPHoldsClause();
11360 break;
11361 case llvm::omp::OMPC_contains: {
11362 unsigned NumKinds = Record.readInt();
11363 C = OMPContainsClause::CreateEmpty(Context, NumKinds);
11364 break;
11365 }
11366 case llvm::omp::OMPC_no_openmp:
11367 C = new (Context) OMPNoOpenMPClause();
11368 break;
11369 case llvm::omp::OMPC_no_openmp_routines:
11370 C = new (Context) OMPNoOpenMPRoutinesClause();
11371 break;
11372 case llvm::omp::OMPC_no_openmp_constructs:
11373 C = new (Context) OMPNoOpenMPConstructsClause();
11374 break;
11375 case llvm::omp::OMPC_no_parallelism:
11376 C = new (Context) OMPNoParallelismClause();
11377 break;
11378 case llvm::omp::OMPC_acquire:
11379 C = new (Context) OMPAcquireClause();
11380 break;
11381 case llvm::omp::OMPC_release:
11382 C = new (Context) OMPReleaseClause();
11383 break;
11384 case llvm::omp::OMPC_relaxed:
11385 C = new (Context) OMPRelaxedClause();
11386 break;
11387 case llvm::omp::OMPC_weak:
11388 C = new (Context) OMPWeakClause();
11389 break;
11390 case llvm::omp::OMPC_threads:
11391 C = new (Context) OMPThreadsClause();
11392 break;
11393 case llvm::omp::OMPC_simd:
11394 C = new (Context) OMPSIMDClause();
11395 break;
11396 case llvm::omp::OMPC_nogroup:
11397 C = new (Context) OMPNogroupClause();
11398 break;
11399 case llvm::omp::OMPC_unified_address:
11400 C = new (Context) OMPUnifiedAddressClause();
11401 break;
11402 case llvm::omp::OMPC_unified_shared_memory:
11403 C = new (Context) OMPUnifiedSharedMemoryClause();
11404 break;
11405 case llvm::omp::OMPC_reverse_offload:
11406 C = new (Context) OMPReverseOffloadClause();
11407 break;
11408 case llvm::omp::OMPC_dynamic_allocators:
11409 C = new (Context) OMPDynamicAllocatorsClause();
11410 break;
11411 case llvm::omp::OMPC_atomic_default_mem_order:
11412 C = new (Context) OMPAtomicDefaultMemOrderClause();
11413 break;
11414 case llvm::omp::OMPC_self_maps:
11415 C = new (Context) OMPSelfMapsClause();
11416 break;
11417 case llvm::omp::OMPC_at:
11418 C = new (Context) OMPAtClause();
11419 break;
11420 case llvm::omp::OMPC_severity:
11421 C = new (Context) OMPSeverityClause();
11422 break;
11423 case llvm::omp::OMPC_message:
11424 C = new (Context) OMPMessageClause();
11425 break;
11426 case llvm::omp::OMPC_private:
11427 C = OMPPrivateClause::CreateEmpty(Context, Record.readInt());
11428 break;
11429 case llvm::omp::OMPC_firstprivate:
11430 C = OMPFirstprivateClause::CreateEmpty(Context, Record.readInt());
11431 break;
11432 case llvm::omp::OMPC_lastprivate:
11433 C = OMPLastprivateClause::CreateEmpty(Context, Record.readInt());
11434 break;
11435 case llvm::omp::OMPC_shared:
11436 C = OMPSharedClause::CreateEmpty(Context, Record.readInt());
11437 break;
11438 case llvm::omp::OMPC_reduction: {
11439 unsigned N = Record.readInt();
11440 auto Modifier = Record.readEnum<OpenMPReductionClauseModifier>();
11441 C = OMPReductionClause::CreateEmpty(Context, N, Modifier);
11442 break;
11443 }
11444 case llvm::omp::OMPC_task_reduction:
11445 C = OMPTaskReductionClause::CreateEmpty(Context, Record.readInt());
11446 break;
11447 case llvm::omp::OMPC_in_reduction:
11448 C = OMPInReductionClause::CreateEmpty(Context, Record.readInt());
11449 break;
11450 case llvm::omp::OMPC_linear:
11451 C = OMPLinearClause::CreateEmpty(Context, Record.readInt());
11452 break;
11453 case llvm::omp::OMPC_aligned:
11454 C = OMPAlignedClause::CreateEmpty(Context, Record.readInt());
11455 break;
11456 case llvm::omp::OMPC_copyin:
11457 C = OMPCopyinClause::CreateEmpty(Context, Record.readInt());
11458 break;
11459 case llvm::omp::OMPC_copyprivate:
11460 C = OMPCopyprivateClause::CreateEmpty(Context, Record.readInt());
11461 break;
11462 case llvm::omp::OMPC_flush:
11463 C = OMPFlushClause::CreateEmpty(Context, Record.readInt());
11464 break;
11465 case llvm::omp::OMPC_depobj:
11466 C = OMPDepobjClause::CreateEmpty(Context);
11467 break;
11468 case llvm::omp::OMPC_depend: {
11469 unsigned NumVars = Record.readInt();
11470 unsigned NumLoops = Record.readInt();
11471 C = OMPDependClause::CreateEmpty(Context, NumVars, NumLoops);
11472 break;
11473 }
11474 case llvm::omp::OMPC_device:
11475 C = new (Context) OMPDeviceClause();
11476 break;
11477 case llvm::omp::OMPC_map: {
11478 OMPMappableExprListSizeTy Sizes;
11479 Sizes.NumVars = Record.readInt();
11480 Sizes.NumUniqueDeclarations = Record.readInt();
11481 Sizes.NumComponentLists = Record.readInt();
11482 Sizes.NumComponents = Record.readInt();
11483 C = OMPMapClause::CreateEmpty(Context, Sizes);
11484 break;
11485 }
11486 case llvm::omp::OMPC_num_teams:
11487 C = OMPNumTeamsClause::CreateEmpty(Context, Record.readInt());
11488 break;
11489 case llvm::omp::OMPC_thread_limit:
11490 C = OMPThreadLimitClause::CreateEmpty(Context, Record.readInt());
11491 break;
11492 case llvm::omp::OMPC_priority:
11493 C = new (Context) OMPPriorityClause();
11494 break;
11495 case llvm::omp::OMPC_grainsize:
11496 C = new (Context) OMPGrainsizeClause();
11497 break;
11498 case llvm::omp::OMPC_num_tasks:
11499 C = new (Context) OMPNumTasksClause();
11500 break;
11501 case llvm::omp::OMPC_hint:
11502 C = new (Context) OMPHintClause();
11503 break;
11504 case llvm::omp::OMPC_dist_schedule:
11505 C = new (Context) OMPDistScheduleClause();
11506 break;
11507 case llvm::omp::OMPC_defaultmap:
11508 C = new (Context) OMPDefaultmapClause();
11509 break;
11510 case llvm::omp::OMPC_to: {
11511 OMPMappableExprListSizeTy Sizes;
11512 Sizes.NumVars = Record.readInt();
11513 Sizes.NumUniqueDeclarations = Record.readInt();
11514 Sizes.NumComponentLists = Record.readInt();
11515 Sizes.NumComponents = Record.readInt();
11516 C = OMPToClause::CreateEmpty(Context, Sizes);
11517 break;
11518 }
11519 case llvm::omp::OMPC_from: {
11520 OMPMappableExprListSizeTy Sizes;
11521 Sizes.NumVars = Record.readInt();
11522 Sizes.NumUniqueDeclarations = Record.readInt();
11523 Sizes.NumComponentLists = Record.readInt();
11524 Sizes.NumComponents = Record.readInt();
11525 C = OMPFromClause::CreateEmpty(Context, Sizes);
11526 break;
11527 }
11528 case llvm::omp::OMPC_use_device_ptr: {
11529 OMPMappableExprListSizeTy Sizes;
11530 Sizes.NumVars = Record.readInt();
11531 Sizes.NumUniqueDeclarations = Record.readInt();
11532 Sizes.NumComponentLists = Record.readInt();
11533 Sizes.NumComponents = Record.readInt();
11534 C = OMPUseDevicePtrClause::CreateEmpty(Context, Sizes);
11535 break;
11536 }
11537 case llvm::omp::OMPC_use_device_addr: {
11538 OMPMappableExprListSizeTy Sizes;
11539 Sizes.NumVars = Record.readInt();
11540 Sizes.NumUniqueDeclarations = Record.readInt();
11541 Sizes.NumComponentLists = Record.readInt();
11542 Sizes.NumComponents = Record.readInt();
11543 C = OMPUseDeviceAddrClause::CreateEmpty(Context, Sizes);
11544 break;
11545 }
11546 case llvm::omp::OMPC_is_device_ptr: {
11547 OMPMappableExprListSizeTy Sizes;
11548 Sizes.NumVars = Record.readInt();
11549 Sizes.NumUniqueDeclarations = Record.readInt();
11550 Sizes.NumComponentLists = Record.readInt();
11551 Sizes.NumComponents = Record.readInt();
11552 C = OMPIsDevicePtrClause::CreateEmpty(Context, Sizes);
11553 break;
11554 }
11555 case llvm::omp::OMPC_has_device_addr: {
11556 OMPMappableExprListSizeTy Sizes;
11557 Sizes.NumVars = Record.readInt();
11558 Sizes.NumUniqueDeclarations = Record.readInt();
11559 Sizes.NumComponentLists = Record.readInt();
11560 Sizes.NumComponents = Record.readInt();
11561 C = OMPHasDeviceAddrClause::CreateEmpty(Context, Sizes);
11562 break;
11563 }
11564 case llvm::omp::OMPC_allocate:
11565 C = OMPAllocateClause::CreateEmpty(Context, Record.readInt());
11566 break;
11567 case llvm::omp::OMPC_nontemporal:
11568 C = OMPNontemporalClause::CreateEmpty(Context, Record.readInt());
11569 break;
11570 case llvm::omp::OMPC_inclusive:
11571 C = OMPInclusiveClause::CreateEmpty(Context, Record.readInt());
11572 break;
11573 case llvm::omp::OMPC_exclusive:
11574 C = OMPExclusiveClause::CreateEmpty(Context, Record.readInt());
11575 break;
11576 case llvm::omp::OMPC_order:
11577 C = new (Context) OMPOrderClause();
11578 break;
11579 case llvm::omp::OMPC_init:
11580 C = OMPInitClause::CreateEmpty(Context, Record.readInt());
11581 break;
11582 case llvm::omp::OMPC_use:
11583 C = new (Context) OMPUseClause();
11584 break;
11585 case llvm::omp::OMPC_destroy:
11586 C = new (Context) OMPDestroyClause();
11587 break;
11588 case llvm::omp::OMPC_novariants:
11589 C = new (Context) OMPNovariantsClause();
11590 break;
11591 case llvm::omp::OMPC_nocontext:
11592 C = new (Context) OMPNocontextClause();
11593 break;
11594 case llvm::omp::OMPC_detach:
11595 C = new (Context) OMPDetachClause();
11596 break;
11597 case llvm::omp::OMPC_uses_allocators:
11598 C = OMPUsesAllocatorsClause::CreateEmpty(Context, Record.readInt());
11599 break;
11600 case llvm::omp::OMPC_affinity:
11601 C = OMPAffinityClause::CreateEmpty(Context, Record.readInt());
11602 break;
11603 case llvm::omp::OMPC_filter:
11604 C = new (Context) OMPFilterClause();
11605 break;
11606 case llvm::omp::OMPC_bind:
11607 C = OMPBindClause::CreateEmpty(Context);
11608 break;
11609 case llvm::omp::OMPC_align:
11610 C = new (Context) OMPAlignClause();
11611 break;
11612 case llvm::omp::OMPC_ompx_dyn_cgroup_mem:
11613 C = new (Context) OMPXDynCGroupMemClause();
11614 break;
11615 case llvm::omp::OMPC_dyn_groupprivate:
11616 C = new (Context) OMPDynGroupprivateClause();
11617 break;
11618 case llvm::omp::OMPC_doacross: {
11619 unsigned NumVars = Record.readInt();
11620 unsigned NumLoops = Record.readInt();
11621 C = OMPDoacrossClause::CreateEmpty(Context, NumVars, NumLoops);
11622 break;
11623 }
11624 case llvm::omp::OMPC_ompx_attribute:
11625 C = new (Context) OMPXAttributeClause();
11626 break;
11627 case llvm::omp::OMPC_ompx_bare:
11628 C = new (Context) OMPXBareClause();
11629 break;
11630 #define OMP_CLAUSE_NO_CLASS(Enum, Str) \
11631 case llvm::omp::Enum: \
11632 break;
11633 #include "llvm/Frontend/OpenMP/OMPKinds.def"
11634 default:
11635 break;
11636 }
11637 assert(C && "Unknown OMPClause type");
11638
11639 Visit(C);
11640 C->setLocStart(Record.readSourceLocation());
11641 C->setLocEnd(Record.readSourceLocation());
11642
11643 return C;
11644 }
11645
11646 void OMPClauseReader::VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C) {
11647 C->setPreInitStmt(Record.readSubStmt(),
11648 static_cast<OpenMPDirectiveKind>(Record.readInt()));
11649 }
11650
11651 void OMPClauseReader::VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C) {
11652 VisitOMPClauseWithPreInit(C);
11653 C->setPostUpdateExpr(Record.readSubExpr());
11654 }
11655
11656 void OMPClauseReader::VisitOMPIfClause(OMPIfClause *C) {
11657 VisitOMPClauseWithPreInit(C);
11658 C->setNameModifier(static_cast<OpenMPDirectiveKind>(Record.readInt()));
11659 C->setNameModifierLoc(Record.readSourceLocation());
11660 C->setColonLoc(Record.readSourceLocation());
11661 C->setCondition(Record.readSubExpr());
11662 C->setLParenLoc(Record.readSourceLocation());
11663 }
11664
11665 void OMPClauseReader::VisitOMPFinalClause(OMPFinalClause *C) {
11666 VisitOMPClauseWithPreInit(C);
11667 C->setCondition(Record.readSubExpr());
11668 C->setLParenLoc(Record.readSourceLocation());
11669 }
11670
11671 void OMPClauseReader::VisitOMPNumThreadsClause(OMPNumThreadsClause *C) {
11672 VisitOMPClauseWithPreInit(C);
11673 C->setModifier(Record.readEnum<OpenMPNumThreadsClauseModifier>());
11674 C->setNumThreads(Record.readSubExpr());
11675 C->setModifierLoc(Record.readSourceLocation());
11676 C->setLParenLoc(Record.readSourceLocation());
11677 }
11678
11679 void OMPClauseReader::VisitOMPSafelenClause(OMPSafelenClause *C) {
11680 C->setSafelen(Record.readSubExpr());
11681 C->setLParenLoc(Record.readSourceLocation());
11682 }
11683
11684 void OMPClauseReader::VisitOMPSimdlenClause(OMPSimdlenClause *C) {
11685 C->setSimdlen(Record.readSubExpr());
11686 C->setLParenLoc(Record.readSourceLocation());
11687 }
11688
11689 void OMPClauseReader::VisitOMPSizesClause(OMPSizesClause *C) {
11690 for (Expr *&E : C->getSizesRefs())
11691 E = Record.readSubExpr();
11692 C->setLParenLoc(Record.readSourceLocation());
11693 }
11694
11695 void OMPClauseReader::VisitOMPPermutationClause(OMPPermutationClause *C) {
11696 for (Expr *&E : C->getArgsRefs())
11697 E = Record.readSubExpr();
11698 C->setLParenLoc(Record.readSourceLocation());
11699 }
11700
11701 void OMPClauseReader::VisitOMPFullClause(OMPFullClause *C) {}
11702
11703 void OMPClauseReader::VisitOMPPartialClause(OMPPartialClause *C) {
11704 C->setFactor(Record.readSubExpr());
11705 C->setLParenLoc(Record.readSourceLocation());
11706 }
11707
11708 void OMPClauseReader::VisitOMPLoopRangeClause(OMPLoopRangeClause *C) {
11709 C->setFirst(Record.readSubExpr());
11710 C->setCount(Record.readSubExpr());
11711 C->setLParenLoc(Record.readSourceLocation());
11712 C->setFirstLoc(Record.readSourceLocation());
11713 C->setCountLoc(Record.readSourceLocation());
11714 }
11715
11716 void OMPClauseReader::VisitOMPAllocatorClause(OMPAllocatorClause *C) {
11717 C->setAllocator(Record.readExpr());
11718 C->setLParenLoc(Record.readSourceLocation());
11719 }
11720
11721 void OMPClauseReader::VisitOMPCollapseClause(OMPCollapseClause *C) {
11722 C->setNumForLoops(Record.readSubExpr());
11723 C->setLParenLoc(Record.readSourceLocation());
11724 }
11725
11726 void OMPClauseReader::VisitOMPDefaultClause(OMPDefaultClause *C) {
11727 C->setDefaultKind(static_cast<llvm::omp::DefaultKind>(Record.readInt()));
11728 C->setLParenLoc(Record.readSourceLocation());
11729 C->setDefaultKindKwLoc(Record.readSourceLocation());
11730 C->setDefaultVariableCategory(
11731 Record.readEnum<OpenMPDefaultClauseVariableCategory>());
11732 C->setDefaultVariableCategoryLocation(Record.readSourceLocation());
11733 }
11734
11735 // Read the parameter of threadset clause. This will have been saved when
11736 // OMPClauseWriter is called.
11737 void OMPClauseReader::VisitOMPThreadsetClause(OMPThreadsetClause *C) {
11738 C->setLParenLoc(Record.readSourceLocation());
11739 SourceLocation ThreadsetKindLoc = Record.readSourceLocation();
11740 C->setThreadsetKindLoc(ThreadsetKindLoc);
11741 OpenMPThreadsetKind TKind =
11742 static_cast<OpenMPThreadsetKind>(Record.readInt());
11743 C->setThreadsetKind(TKind);
11744 }
11745
11746 void OMPClauseReader::VisitOMPProcBindClause(OMPProcBindClause *C) {
11747 C->setProcBindKind(static_cast<llvm::omp::ProcBindKind>(Record.readInt()));
11748 C->setLParenLoc(Record.readSourceLocation());
11749 C->setProcBindKindKwLoc(Record.readSourceLocation());
11750 }
11751
11752 void OMPClauseReader::VisitOMPScheduleClause(OMPScheduleClause *C) {
11753 VisitOMPClauseWithPreInit(C);
11754 C->setScheduleKind(
11755 static_cast<OpenMPScheduleClauseKind>(Record.readInt()));
11756 C->setFirstScheduleModifier(
11757 static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
11758 C->setSecondScheduleModifier(
11759 static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
11760 C->setChunkSize(Record.readSubExpr());
11761 C->setLParenLoc(Record.readSourceLocation());
11762 C->setFirstScheduleModifierLoc(Record.readSourceLocation());
11763 C->setSecondScheduleModifierLoc(Record.readSourceLocation());
11764 C->setScheduleKindLoc(Record.readSourceLocation());
11765 C->setCommaLoc(Record.readSourceLocation());
11766 }
11767
11768 void OMPClauseReader::VisitOMPOrderedClause(OMPOrderedClause *C) {
11769 C->setNumForLoops(Record.readSubExpr());
11770 for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
11771 C->setLoopNumIterations(I, Record.readSubExpr());
11772 for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
11773 C->setLoopCounter(I, Record.readSubExpr());
11774 C->setLParenLoc(Record.readSourceLocation());
11775 }
11776
11777 void OMPClauseReader::VisitOMPDetachClause(OMPDetachClause *C) {
11778 C->setEventHandler(Record.readSubExpr());
11779 C->setLParenLoc(Record.readSourceLocation());
11780 }
11781
11782 void OMPClauseReader::VisitOMPNowaitClause(OMPNowaitClause *C) {
11783 C->setCondition(Record.readSubExpr());
11784 C->setLParenLoc(Record.readSourceLocation());
11785 }
11786
11787 void OMPClauseReader::VisitOMPUntiedClause(OMPUntiedClause *) {}
11788
11789 void OMPClauseReader::VisitOMPMergeableClause(OMPMergeableClause *) {}
11790
11791 void OMPClauseReader::VisitOMPReadClause(OMPReadClause *) {}
11792
11793 void OMPClauseReader::VisitOMPWriteClause(OMPWriteClause *) {}
11794
11795 void OMPClauseReader::VisitOMPUpdateClause(OMPUpdateClause *C) {
11796 if (C->isExtended()) {
11797 C->setLParenLoc(Record.readSourceLocation());
11798 C->setArgumentLoc(Record.readSourceLocation());
11799 C->setDependencyKind(Record.readEnum<OpenMPDependClauseKind>());
11800 }
11801 }
11802
11803 void OMPClauseReader::VisitOMPCaptureClause(OMPCaptureClause *) {}
11804
11805 void OMPClauseReader::VisitOMPCompareClause(OMPCompareClause *) {}
11806
11807 // Read the parameter of fail clause. This will have been saved when
11808 // OMPClauseWriter is called.
11809 void OMPClauseReader::VisitOMPFailClause(OMPFailClause *C) {
11810 C->setLParenLoc(Record.readSourceLocation());
11811 SourceLocation FailParameterLoc = Record.readSourceLocation();
11812 C->setFailParameterLoc(FailParameterLoc);
11813 OpenMPClauseKind CKind = Record.readEnum<OpenMPClauseKind>();
11814 C->setFailParameter(CKind);
11815 }
11816
11817 void OMPClauseReader::VisitOMPAbsentClause(OMPAbsentClause *C) {
11818 unsigned Count = C->getDirectiveKinds().size();
11819 C->setLParenLoc(Record.readSourceLocation());
11820 llvm::SmallVector<OpenMPDirectiveKind, 4> DKVec;
11821 DKVec.reserve(Count);
11822 for (unsigned I = 0; I < Count; I++) {
11823 DKVec.push_back(Record.readEnum<OpenMPDirectiveKind>());
11824 }
11825 C->setDirectiveKinds(DKVec);
11826 }
11827
11828 void OMPClauseReader::VisitOMPHoldsClause(OMPHoldsClause *C) {
11829 C->setExpr(Record.readExpr());
11830 C->setLParenLoc(Record.readSourceLocation());
11831 }
11832
11833 void OMPClauseReader::VisitOMPContainsClause(OMPContainsClause *C) {
11834 unsigned Count = C->getDirectiveKinds().size();
11835 C->setLParenLoc(Record.readSourceLocation());
11836 llvm::SmallVector<OpenMPDirectiveKind, 4> DKVec;
11837 DKVec.reserve(Count);
11838 for (unsigned I = 0; I < Count; I++) {
11839 DKVec.push_back(Record.readEnum<OpenMPDirectiveKind>());
11840 }
11841 C->setDirectiveKinds(DKVec);
11842 }
11843
11844 void OMPClauseReader::VisitOMPNoOpenMPClause(OMPNoOpenMPClause *) {}
11845
11846 void OMPClauseReader::VisitOMPNoOpenMPRoutinesClause(
11847 OMPNoOpenMPRoutinesClause *) {}
11848
11849 void OMPClauseReader::VisitOMPNoOpenMPConstructsClause(
11850 OMPNoOpenMPConstructsClause *) {}
11851
11852 void OMPClauseReader::VisitOMPNoParallelismClause(OMPNoParallelismClause *) {}
11853
11854 void OMPClauseReader::VisitOMPSeqCstClause(OMPSeqCstClause *) {}
11855
11856 void OMPClauseReader::VisitOMPAcqRelClause(OMPAcqRelClause *) {}
11857
11858 void OMPClauseReader::VisitOMPAcquireClause(OMPAcquireClause *) {}
11859
11860 void OMPClauseReader::VisitOMPReleaseClause(OMPReleaseClause *) {}
11861
11862 void OMPClauseReader::VisitOMPRelaxedClause(OMPRelaxedClause *) {}
11863
11864 void OMPClauseReader::VisitOMPWeakClause(OMPWeakClause *) {}
11865
11866 void OMPClauseReader::VisitOMPThreadsClause(OMPThreadsClause *) {}
11867
11868 void OMPClauseReader::VisitOMPSIMDClause(OMPSIMDClause *) {}
11869
11870 void OMPClauseReader::VisitOMPNogroupClause(OMPNogroupClause *) {}
11871
11872 void OMPClauseReader::VisitOMPInitClause(OMPInitClause *C) {
11873 unsigned NumVars = C->varlist_size();
11874 SmallVector<Expr *, 16> Vars;
11875 Vars.reserve(NumVars);
11876 for (unsigned I = 0; I != NumVars; ++I)
11877 Vars.push_back(Record.readSubExpr());
11878 C->setVarRefs(Vars);
11879 C->setIsTarget(Record.readBool());
11880 C->setIsTargetSync(Record.readBool());
11881 C->setLParenLoc(Record.readSourceLocation());
11882 C->setVarLoc(Record.readSourceLocation());
11883 }
11884
11885 void OMPClauseReader::VisitOMPUseClause(OMPUseClause *C) {
11886 C->setInteropVar(Record.readSubExpr());
11887 C->setLParenLoc(Record.readSourceLocation());
11888 C->setVarLoc(Record.readSourceLocation());
11889 }
11890
11891 void OMPClauseReader::VisitOMPDestroyClause(OMPDestroyClause *C) {
11892 C->setInteropVar(Record.readSubExpr());
11893 C->setLParenLoc(Record.readSourceLocation());
11894 C->setVarLoc(Record.readSourceLocation());
11895 }
11896
11897 void OMPClauseReader::VisitOMPNovariantsClause(OMPNovariantsClause *C) {
11898 VisitOMPClauseWithPreInit(C);
11899 C->setCondition(Record.readSubExpr());
11900 C->setLParenLoc(Record.readSourceLocation());
11901 }
11902
11903 void OMPClauseReader::VisitOMPNocontextClause(OMPNocontextClause *C) {
11904 VisitOMPClauseWithPreInit(C);
11905 C->setCondition(Record.readSubExpr());
11906 C->setLParenLoc(Record.readSourceLocation());
11907 }
11908
11909 void OMPClauseReader::VisitOMPUnifiedAddressClause(OMPUnifiedAddressClause *) {}
11910
11911 void OMPClauseReader::VisitOMPUnifiedSharedMemoryClause(
11912 OMPUnifiedSharedMemoryClause *) {}
11913
11914 void OMPClauseReader::VisitOMPReverseOffloadClause(OMPReverseOffloadClause *) {}
11915
11916 void
11917 OMPClauseReader::VisitOMPDynamicAllocatorsClause(OMPDynamicAllocatorsClause *) {
11918 }
11919
11920 void OMPClauseReader::VisitOMPAtomicDefaultMemOrderClause(
11921 OMPAtomicDefaultMemOrderClause *C) {
11922 C->setAtomicDefaultMemOrderKind(
11923 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Record.readInt()));
11924 C->setLParenLoc(Record.readSourceLocation());
11925 C->setAtomicDefaultMemOrderKindKwLoc(Record.readSourceLocation());
11926 }
11927
11928 void OMPClauseReader::VisitOMPSelfMapsClause(OMPSelfMapsClause *) {}
11929
11930 void OMPClauseReader::VisitOMPAtClause(OMPAtClause *C) {
11931 C->setAtKind(static_cast<OpenMPAtClauseKind>(Record.readInt()));
11932 C->setLParenLoc(Record.readSourceLocation());
11933 C->setAtKindKwLoc(Record.readSourceLocation());
11934 }
11935
11936 void OMPClauseReader::VisitOMPSeverityClause(OMPSeverityClause *C) {
11937 C->setSeverityKind(static_cast<OpenMPSeverityClauseKind>(Record.readInt()));
11938 C->setLParenLoc(Record.readSourceLocation());
11939 C->setSeverityKindKwLoc(Record.readSourceLocation());
11940 }
11941
11942 void OMPClauseReader::VisitOMPMessageClause(OMPMessageClause *C) {
11943 VisitOMPClauseWithPreInit(C);
11944 C->setMessageString(Record.readSubExpr());
11945 C->setLParenLoc(Record.readSourceLocation());
11946 }
11947
11948 void OMPClauseReader::VisitOMPPrivateClause(OMPPrivateClause *C) {
11949 C->setLParenLoc(Record.readSourceLocation());
11950 unsigned NumVars = C->varlist_size();
11951 SmallVector<Expr *, 16> Vars;
11952 Vars.reserve(NumVars);
11953 for (unsigned i = 0; i != NumVars; ++i)
11954 Vars.push_back(Record.readSubExpr());
11955 C->setVarRefs(Vars);
11956 Vars.clear();
11957 for (unsigned i = 0; i != NumVars; ++i)
11958 Vars.push_back(Record.readSubExpr());
11959 C->setPrivateCopies(Vars);
11960 }
11961
11962 void OMPClauseReader::VisitOMPFirstprivateClause(OMPFirstprivateClause *C) {
11963 VisitOMPClauseWithPreInit(C);
11964 C->setLParenLoc(Record.readSourceLocation());
11965 unsigned NumVars = C->varlist_size();
11966 SmallVector<Expr *, 16> Vars;
11967 Vars.reserve(NumVars);
11968 for (unsigned i = 0; i != NumVars; ++i)
11969 Vars.push_back(Record.readSubExpr());
11970 C->setVarRefs(Vars);
11971 Vars.clear();
11972 for (unsigned i = 0; i != NumVars; ++i)
11973 Vars.push_back(Record.readSubExpr());
11974 C->setPrivateCopies(Vars);
11975 Vars.clear();
11976 for (unsigned i = 0; i != NumVars; ++i)
11977 Vars.push_back(Record.readSubExpr());
11978 C->setInits(Vars);
11979 }
11980
11981 void OMPClauseReader::VisitOMPLastprivateClause(OMPLastprivateClause *C) {
11982 VisitOMPClauseWithPostUpdate(C);
11983 C->setLParenLoc(Record.readSourceLocation());
11984 C->setKind(Record.readEnum<OpenMPLastprivateModifier>());
11985 C->setKindLoc(Record.readSourceLocation());
11986 C->setColonLoc(Record.readSourceLocation());
11987 unsigned NumVars = C->varlist_size();
11988 SmallVector<Expr *, 16> Vars;
11989 Vars.reserve(NumVars);
11990 for (unsigned i = 0; i != NumVars; ++i)
11991 Vars.push_back(Record.readSubExpr());
11992 C->setVarRefs(Vars);
11993 Vars.clear();
11994 for (unsigned i = 0; i != NumVars; ++i)
11995 Vars.push_back(Record.readSubExpr());
11996 C->setPrivateCopies(Vars);
11997 Vars.clear();
11998 for (unsigned i = 0; i != NumVars; ++i)
11999 Vars.push_back(Record.readSubExpr());
12000 C->setSourceExprs(Vars);
12001 Vars.clear();
12002 for (unsigned i = 0; i != NumVars; ++i)
12003 Vars.push_back(Record.readSubExpr());
12004 C->setDestinationExprs(Vars);
12005 Vars.clear();
12006 for (unsigned i = 0; i != NumVars; ++i)
12007 Vars.push_back(Record.readSubExpr());
12008 C->setAssignmentOps(Vars);
12009 }
12010
12011 void OMPClauseReader::VisitOMPSharedClause(OMPSharedClause *C) {
12012 C->setLParenLoc(Record.readSourceLocation());
12013 unsigned NumVars = C->varlist_size();
12014 SmallVector<Expr *, 16> Vars;
12015 Vars.reserve(NumVars);
12016 for (unsigned i = 0; i != NumVars; ++i)
12017 Vars.push_back(Record.readSubExpr());
12018 C->setVarRefs(Vars);
12019 }
12020
12021 void OMPClauseReader::VisitOMPReductionClause(OMPReductionClause *C) {
12022 VisitOMPClauseWithPostUpdate(C);
12023 C->setLParenLoc(Record.readSourceLocation());
12024 C->setModifierLoc(Record.readSourceLocation());
12025 C->setColonLoc(Record.readSourceLocation());
12026 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
12027 DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
12028 C->setQualifierLoc(NNSL);
12029 C->setNameInfo(DNI);
12030
12031 unsigned NumVars = C->varlist_size();
12032 SmallVector<Expr *, 16> Vars;
12033 Vars.reserve(NumVars);
12034 for (unsigned i = 0; i != NumVars; ++i)
12035 Vars.push_back(Record.readSubExpr());
12036 C->setVarRefs(Vars);
12037 Vars.clear();
12038 for (unsigned i = 0; i != NumVars; ++i)
12039 Vars.push_back(Record.readSubExpr());
12040 C->setPrivates(Vars);
12041 Vars.clear();
12042 for (unsigned i = 0; i != NumVars; ++i)
12043 Vars.push_back(Record.readSubExpr());
12044 C->setLHSExprs(Vars);
12045 Vars.clear();
12046 for (unsigned i = 0; i != NumVars; ++i)
12047 Vars.push_back(Record.readSubExpr());
12048 C->setRHSExprs(Vars);
12049 Vars.clear();
12050 for (unsigned i = 0; i != NumVars; ++i)
12051 Vars.push_back(Record.readSubExpr());
12052 C->setReductionOps(Vars);
12053 if (C->getModifier() == OMPC_REDUCTION_inscan) {
12054 Vars.clear();
12055 for (unsigned i = 0; i != NumVars; ++i)
12056 Vars.push_back(Record.readSubExpr());
12057 C->setInscanCopyOps(Vars);
12058 Vars.clear();
12059 for (unsigned i = 0; i != NumVars; ++i)
12060 Vars.push_back(Record.readSubExpr());
12061 C->setInscanCopyArrayTemps(Vars);
12062 Vars.clear();
12063 for (unsigned i = 0; i != NumVars; ++i)
12064 Vars.push_back(Record.readSubExpr());
12065 C->setInscanCopyArrayElems(Vars);
12066 }
12067 unsigned NumFlags = Record.readInt();
12068 SmallVector<bool, 16> Flags;
12069 Flags.reserve(NumFlags);
12070 for ([[maybe_unused]] unsigned I : llvm::seq<unsigned>(NumFlags))
12071 Flags.push_back(Record.readInt());
12072 C->setPrivateVariableReductionFlags(Flags);
12073 }
12074
12075 void OMPClauseReader::VisitOMPTaskReductionClause(OMPTaskReductionClause *C) {
12076 VisitOMPClauseWithPostUpdate(C);
12077 C->setLParenLoc(Record.readSourceLocation());
12078 C->setColonLoc(Record.readSourceLocation());
12079 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
12080 DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
12081 C->setQualifierLoc(NNSL);
12082 C->setNameInfo(DNI);
12083
12084 unsigned NumVars = C->varlist_size();
12085 SmallVector<Expr *, 16> Vars;
12086 Vars.reserve(NumVars);
12087 for (unsigned I = 0; I != NumVars; ++I)
12088 Vars.push_back(Record.readSubExpr());
12089 C->setVarRefs(Vars);
12090 Vars.clear();
12091 for (unsigned I = 0; I != NumVars; ++I)
12092 Vars.push_back(Record.readSubExpr());
12093 C->setPrivates(Vars);
12094 Vars.clear();
12095 for (unsigned I = 0; I != NumVars; ++I)
12096 Vars.push_back(Record.readSubExpr());
12097 C->setLHSExprs(Vars);
12098 Vars.clear();
12099 for (unsigned I = 0; I != NumVars; ++I)
12100 Vars.push_back(Record.readSubExpr());
12101 C->setRHSExprs(Vars);
12102 Vars.clear();
12103 for (unsigned I = 0; I != NumVars; ++I)
12104 Vars.push_back(Record.readSubExpr());
12105 C->setReductionOps(Vars);
12106 }
12107
12108 void OMPClauseReader::VisitOMPInReductionClause(OMPInReductionClause *C) {
12109 VisitOMPClauseWithPostUpdate(C);
12110 C->setLParenLoc(Record.readSourceLocation());
12111 C->setColonLoc(Record.readSourceLocation());
12112 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
12113 DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
12114 C->setQualifierLoc(NNSL);
12115 C->setNameInfo(DNI);
12116
12117 unsigned NumVars = C->varlist_size();
12118 SmallVector<Expr *, 16> Vars;
12119 Vars.reserve(NumVars);
12120 for (unsigned I = 0; I != NumVars; ++I)
12121 Vars.push_back(Record.readSubExpr());
12122 C->setVarRefs(Vars);
12123 Vars.clear();
12124 for (unsigned I = 0; I != NumVars; ++I)
12125 Vars.push_back(Record.readSubExpr());
12126 C->setPrivates(Vars);
12127 Vars.clear();
12128 for (unsigned I = 0; I != NumVars; ++I)
12129 Vars.push_back(Record.readSubExpr());
12130 C->setLHSExprs(Vars);
12131 Vars.clear();
12132 for (unsigned I = 0; I != NumVars; ++I)
12133 Vars.push_back(Record.readSubExpr());
12134 C->setRHSExprs(Vars);
12135 Vars.clear();
12136 for (unsigned I = 0; I != NumVars; ++I)
12137 Vars.push_back(Record.readSubExpr());
12138 C->setReductionOps(Vars);
12139 Vars.clear();
12140 for (unsigned I = 0; I != NumVars; ++I)
12141 Vars.push_back(Record.readSubExpr());
12142 C->setTaskgroupDescriptors(Vars);
12143 }
12144
12145 void OMPClauseReader::VisitOMPLinearClause(OMPLinearClause *C) {
12146 VisitOMPClauseWithPostUpdate(C);
12147 C->setLParenLoc(Record.readSourceLocation());
12148 C->setColonLoc(Record.readSourceLocation());
12149 C->setModifier(static_cast<OpenMPLinearClauseKind>(Record.readInt()));
12150 C->setModifierLoc(Record.readSourceLocation());
12151 unsigned NumVars = C->varlist_size();
12152 SmallVector<Expr *, 16> Vars;
12153 Vars.reserve(NumVars);
12154 for (unsigned i = 0; i != NumVars; ++i)
12155 Vars.push_back(Record.readSubExpr());
12156 C->setVarRefs(Vars);
12157 Vars.clear();
12158 for (unsigned i = 0; i != NumVars; ++i)
12159 Vars.push_back(Record.readSubExpr());
12160 C->setPrivates(Vars);
12161 Vars.clear();
12162 for (unsigned i = 0; i != NumVars; ++i)
12163 Vars.push_back(Record.readSubExpr());
12164 C->setInits(Vars);
12165 Vars.clear();
12166 for (unsigned i = 0; i != NumVars; ++i)
12167 Vars.push_back(Record.readSubExpr());
12168 C->setUpdates(Vars);
12169 Vars.clear();
12170 for (unsigned i = 0; i != NumVars; ++i)
12171 Vars.push_back(Record.readSubExpr());
12172 C->setFinals(Vars);
12173 C->setStep(Record.readSubExpr());
12174 C->setCalcStep(Record.readSubExpr());
12175 Vars.clear();
12176 for (unsigned I = 0; I != NumVars + 1; ++I)
12177 Vars.push_back(Record.readSubExpr());
12178 C->setUsedExprs(Vars);
12179 }
12180
12181 void OMPClauseReader::VisitOMPAlignedClause(OMPAlignedClause *C) {
12182 C->setLParenLoc(Record.readSourceLocation());
12183 C->setColonLoc(Record.readSourceLocation());
12184 unsigned NumVars = C->varlist_size();
12185 SmallVector<Expr *, 16> Vars;
12186 Vars.reserve(NumVars);
12187 for (unsigned i = 0; i != NumVars; ++i)
12188 Vars.push_back(Record.readSubExpr());
12189 C->setVarRefs(Vars);
12190 C->setAlignment(Record.readSubExpr());
12191 }
12192
12193 void OMPClauseReader::VisitOMPCopyinClause(OMPCopyinClause *C) {
12194 C->setLParenLoc(Record.readSourceLocation());
12195 unsigned NumVars = C->varlist_size();
12196 SmallVector<Expr *, 16> Exprs;
12197 Exprs.reserve(NumVars);
12198 for (unsigned i = 0; i != NumVars; ++i)
12199 Exprs.push_back(Record.readSubExpr());
12200 C->setVarRefs(Exprs);
12201 Exprs.clear();
12202 for (unsigned i = 0; i != NumVars; ++i)
12203 Exprs.push_back(Record.readSubExpr());
12204 C->setSourceExprs(Exprs);
12205 Exprs.clear();
12206 for (unsigned i = 0; i != NumVars; ++i)
12207 Exprs.push_back(Record.readSubExpr());
12208 C->setDestinationExprs(Exprs);
12209 Exprs.clear();
12210 for (unsigned i = 0; i != NumVars; ++i)
12211 Exprs.push_back(Record.readSubExpr());
12212 C->setAssignmentOps(Exprs);
12213 }
12214
12215 void OMPClauseReader::VisitOMPCopyprivateClause(OMPCopyprivateClause *C) {
12216 C->setLParenLoc(Record.readSourceLocation());
12217 unsigned NumVars = C->varlist_size();
12218 SmallVector<Expr *, 16> Exprs;
12219 Exprs.reserve(NumVars);
12220 for (unsigned i = 0; i != NumVars; ++i)
12221 Exprs.push_back(Record.readSubExpr());
12222 C->setVarRefs(Exprs);
12223 Exprs.clear();
12224 for (unsigned i = 0; i != NumVars; ++i)
12225 Exprs.push_back(Record.readSubExpr());
12226 C->setSourceExprs(Exprs);
12227 Exprs.clear();
12228 for (unsigned i = 0; i != NumVars; ++i)
12229 Exprs.push_back(Record.readSubExpr());
12230 C->setDestinationExprs(Exprs);
12231 Exprs.clear();
12232 for (unsigned i = 0; i != NumVars; ++i)
12233 Exprs.push_back(Record.readSubExpr());
12234 C->setAssignmentOps(Exprs);
12235 }
12236
12237 void OMPClauseReader::VisitOMPFlushClause(OMPFlushClause *C) {
12238 C->setLParenLoc(Record.readSourceLocation());
12239 unsigned NumVars = C->varlist_size();
12240 SmallVector<Expr *, 16> Vars;
12241 Vars.reserve(NumVars);
12242 for (unsigned i = 0; i != NumVars; ++i)
12243 Vars.push_back(Record.readSubExpr());
12244 C->setVarRefs(Vars);
12245 }
12246
12247 void OMPClauseReader::VisitOMPDepobjClause(OMPDepobjClause *C) {
12248 C->setDepobj(Record.readSubExpr());
12249 C->setLParenLoc(Record.readSourceLocation());
12250 }
12251
12252 void OMPClauseReader::VisitOMPDependClause(OMPDependClause *C) {
12253 C->setLParenLoc(Record.readSourceLocation());
12254 C->setModifier(Record.readSubExpr());
12255 C->setDependencyKind(
12256 static_cast<OpenMPDependClauseKind>(Record.readInt()));
12257 C->setDependencyLoc(Record.readSourceLocation());
12258 C->setColonLoc(Record.readSourceLocation());
12259 C->setOmpAllMemoryLoc(Record.readSourceLocation());
12260 unsigned NumVars = C->varlist_size();
12261 SmallVector<Expr *, 16> Vars;
12262 Vars.reserve(NumVars);
12263 for (unsigned I = 0; I != NumVars; ++I)
12264 Vars.push_back(Record.readSubExpr());
12265 C->setVarRefs(Vars);
12266 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
12267 C->setLoopData(I, Record.readSubExpr());
12268 }
12269
12270 void OMPClauseReader::VisitOMPDeviceClause(OMPDeviceClause *C) {
12271 VisitOMPClauseWithPreInit(C);
12272 C->setModifier(Record.readEnum<OpenMPDeviceClauseModifier>());
12273 C->setDevice(Record.readSubExpr());
12274 C->setModifierLoc(Record.readSourceLocation());
12275 C->setLParenLoc(Record.readSourceLocation());
12276 }
12277
12278 void OMPClauseReader::VisitOMPMapClause(OMPMapClause *C) {
12279 C->setLParenLoc(Record.readSourceLocation());
12280 bool HasIteratorModifier = false;
12281 for (unsigned I = 0; I < NumberOfOMPMapClauseModifiers; ++I) {
12282 C->setMapTypeModifier(
12283 I, static_cast<OpenMPMapModifierKind>(Record.readInt()));
12284 C->setMapTypeModifierLoc(I, Record.readSourceLocation());
12285 if (C->getMapTypeModifier(I) == OMPC_MAP_MODIFIER_iterator)
12286 HasIteratorModifier = true;
12287 }
12288 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
12289 C->setMapperIdInfo(Record.readDeclarationNameInfo());
12290 C->setMapType(
12291 static_cast<OpenMPMapClauseKind>(Record.readInt()));
12292 C->setMapLoc(Record.readSourceLocation());
12293 C->setColonLoc(Record.readSourceLocation());
12294 auto NumVars = C->varlist_size();
12295 auto UniqueDecls = C->getUniqueDeclarationsNum();
12296 auto TotalLists = C->getTotalComponentListNum();
12297 auto TotalComponents = C->getTotalComponentsNum();
12298
12299 SmallVector<Expr *, 16> Vars;
12300 Vars.reserve(NumVars);
12301 for (unsigned i = 0; i != NumVars; ++i)
12302 Vars.push_back(Record.readExpr());
12303 C->setVarRefs(Vars);
12304
12305 SmallVector<Expr *, 16> UDMappers;
12306 UDMappers.reserve(NumVars);
12307 for (unsigned I = 0; I < NumVars; ++I)
12308 UDMappers.push_back(Record.readExpr());
12309 C->setUDMapperRefs(UDMappers);
12310
12311 if (HasIteratorModifier)
12312 C->setIteratorModifier(Record.readExpr());
12313
12314 SmallVector<ValueDecl *, 16> Decls;
12315 Decls.reserve(UniqueDecls);
12316 for (unsigned i = 0; i < UniqueDecls; ++i)
12317 Decls.push_back(Record.readDeclAs<ValueDecl>());
12318 C->setUniqueDecls(Decls);
12319
12320 SmallVector<unsigned, 16> ListsPerDecl;
12321 ListsPerDecl.reserve(UniqueDecls);
12322 for (unsigned i = 0; i < UniqueDecls; ++i)
12323 ListsPerDecl.push_back(Record.readInt());
12324 C->setDeclNumLists(ListsPerDecl);
12325
12326 SmallVector<unsigned, 32> ListSizes;
12327 ListSizes.reserve(TotalLists);
12328 for (unsigned i = 0; i < TotalLists; ++i)
12329 ListSizes.push_back(Record.readInt());
12330 C->setComponentListSizes(ListSizes);
12331
12332 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12333 Components.reserve(TotalComponents);
12334 for (unsigned i = 0; i < TotalComponents; ++i) {
12335 Expr *AssociatedExprPr = Record.readExpr();
12336 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12337 Components.emplace_back(AssociatedExprPr, AssociatedDecl,
12338 /*IsNonContiguous=*/false);
12339 }
12340 C->setComponents(Components, ListSizes);
12341 }
12342
12343 void OMPClauseReader::VisitOMPAllocateClause(OMPAllocateClause *C) {
12344 C->setFirstAllocateModifier(Record.readEnum<OpenMPAllocateClauseModifier>());
12345 C->setSecondAllocateModifier(Record.readEnum<OpenMPAllocateClauseModifier>());
12346 C->setLParenLoc(Record.readSourceLocation());
12347 C->setColonLoc(Record.readSourceLocation());
12348 C->setAllocator(Record.readSubExpr());
12349 C->setAlignment(Record.readSubExpr());
12350 unsigned NumVars = C->varlist_size();
12351 SmallVector<Expr *, 16> Vars;
12352 Vars.reserve(NumVars);
12353 for (unsigned i = 0; i != NumVars; ++i)
12354 Vars.push_back(Record.readSubExpr());
12355 C->setVarRefs(Vars);
12356 }
12357
12358 void OMPClauseReader::VisitOMPNumTeamsClause(OMPNumTeamsClause *C) {
12359 VisitOMPClauseWithPreInit(C);
12360 C->setLParenLoc(Record.readSourceLocation());
12361 unsigned NumVars = C->varlist_size();
12362 SmallVector<Expr *, 16> Vars;
12363 Vars.reserve(NumVars);
12364 for (unsigned I = 0; I != NumVars; ++I)
12365 Vars.push_back(Record.readSubExpr());
12366 C->setVarRefs(Vars);
12367 }
12368
12369 void OMPClauseReader::VisitOMPThreadLimitClause(OMPThreadLimitClause *C) {
12370 VisitOMPClauseWithPreInit(C);
12371 C->setLParenLoc(Record.readSourceLocation());
12372 unsigned NumVars = C->varlist_size();
12373 SmallVector<Expr *, 16> Vars;
12374 Vars.reserve(NumVars);
12375 for (unsigned I = 0; I != NumVars; ++I)
12376 Vars.push_back(Record.readSubExpr());
12377 C->setVarRefs(Vars);
12378 }
12379
12380 void OMPClauseReader::VisitOMPPriorityClause(OMPPriorityClause *C) {
12381 VisitOMPClauseWithPreInit(C);
12382 C->setPriority(Record.readSubExpr());
12383 C->setLParenLoc(Record.readSourceLocation());
12384 }
12385
12386 void OMPClauseReader::VisitOMPGrainsizeClause(OMPGrainsizeClause *C) {
12387 VisitOMPClauseWithPreInit(C);
12388 C->setModifier(Record.readEnum<OpenMPGrainsizeClauseModifier>());
12389 C->setGrainsize(Record.readSubExpr());
12390 C->setModifierLoc(Record.readSourceLocation());
12391 C->setLParenLoc(Record.readSourceLocation());
12392 }
12393
12394 void OMPClauseReader::VisitOMPNumTasksClause(OMPNumTasksClause *C) {
12395 VisitOMPClauseWithPreInit(C);
12396 C->setModifier(Record.readEnum<OpenMPNumTasksClauseModifier>());
12397 C->setNumTasks(Record.readSubExpr());
12398 C->setModifierLoc(Record.readSourceLocation());
12399 C->setLParenLoc(Record.readSourceLocation());
12400 }
12401
12402 void OMPClauseReader::VisitOMPHintClause(OMPHintClause *C) {
12403 C->setHint(Record.readSubExpr());
12404 C->setLParenLoc(Record.readSourceLocation());
12405 }
12406
12407 void OMPClauseReader::VisitOMPDistScheduleClause(OMPDistScheduleClause *C) {
12408 VisitOMPClauseWithPreInit(C);
12409 C->setDistScheduleKind(
12410 static_cast<OpenMPDistScheduleClauseKind>(Record.readInt()));
12411 C->setChunkSize(Record.readSubExpr());
12412 C->setLParenLoc(Record.readSourceLocation());
12413 C->setDistScheduleKindLoc(Record.readSourceLocation());
12414 C->setCommaLoc(Record.readSourceLocation());
12415 }
12416
12417 void OMPClauseReader::VisitOMPDefaultmapClause(OMPDefaultmapClause *C) {
12418 C->setDefaultmapKind(
12419 static_cast<OpenMPDefaultmapClauseKind>(Record.readInt()));
12420 C->setDefaultmapModifier(
12421 static_cast<OpenMPDefaultmapClauseModifier>(Record.readInt()));
12422 C->setLParenLoc(Record.readSourceLocation());
12423 C->setDefaultmapModifierLoc(Record.readSourceLocation());
12424 C->setDefaultmapKindLoc(Record.readSourceLocation());
12425 }
12426
12427 void OMPClauseReader::VisitOMPToClause(OMPToClause *C) {
12428 C->setLParenLoc(Record.readSourceLocation());
12429 for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) {
12430 C->setMotionModifier(
12431 I, static_cast<OpenMPMotionModifierKind>(Record.readInt()));
12432 C->setMotionModifierLoc(I, Record.readSourceLocation());
12433 if (C->getMotionModifier(I) == OMPC_MOTION_MODIFIER_iterator)
12434 C->setIteratorModifier(Record.readExpr());
12435 }
12436 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
12437 C->setMapperIdInfo(Record.readDeclarationNameInfo());
12438 C->setColonLoc(Record.readSourceLocation());
12439 auto NumVars = C->varlist_size();
12440 auto UniqueDecls = C->getUniqueDeclarationsNum();
12441 auto TotalLists = C->getTotalComponentListNum();
12442 auto TotalComponents = C->getTotalComponentsNum();
12443
12444 SmallVector<Expr *, 16> Vars;
12445 Vars.reserve(NumVars);
12446 for (unsigned i = 0; i != NumVars; ++i)
12447 Vars.push_back(Record.readSubExpr());
12448 C->setVarRefs(Vars);
12449
12450 SmallVector<Expr *, 16> UDMappers;
12451 UDMappers.reserve(NumVars);
12452 for (unsigned I = 0; I < NumVars; ++I)
12453 UDMappers.push_back(Record.readSubExpr());
12454 C->setUDMapperRefs(UDMappers);
12455
12456 SmallVector<ValueDecl *, 16> Decls;
12457 Decls.reserve(UniqueDecls);
12458 for (unsigned i = 0; i < UniqueDecls; ++i)
12459 Decls.push_back(Record.readDeclAs<ValueDecl>());
12460 C->setUniqueDecls(Decls);
12461
12462 SmallVector<unsigned, 16> ListsPerDecl;
12463 ListsPerDecl.reserve(UniqueDecls);
12464 for (unsigned i = 0; i < UniqueDecls; ++i)
12465 ListsPerDecl.push_back(Record.readInt());
12466 C->setDeclNumLists(ListsPerDecl);
12467
12468 SmallVector<unsigned, 32> ListSizes;
12469 ListSizes.reserve(TotalLists);
12470 for (unsigned i = 0; i < TotalLists; ++i)
12471 ListSizes.push_back(Record.readInt());
12472 C->setComponentListSizes(ListSizes);
12473
12474 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12475 Components.reserve(TotalComponents);
12476 for (unsigned i = 0; i < TotalComponents; ++i) {
12477 Expr *AssociatedExprPr = Record.readSubExpr();
12478 bool IsNonContiguous = Record.readBool();
12479 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12480 Components.emplace_back(AssociatedExprPr, AssociatedDecl, IsNonContiguous);
12481 }
12482 C->setComponents(Components, ListSizes);
12483 }
12484
12485 void OMPClauseReader::VisitOMPFromClause(OMPFromClause *C) {
12486 C->setLParenLoc(Record.readSourceLocation());
12487 for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) {
12488 C->setMotionModifier(
12489 I, static_cast<OpenMPMotionModifierKind>(Record.readInt()));
12490 C->setMotionModifierLoc(I, Record.readSourceLocation());
12491 if (C->getMotionModifier(I) == OMPC_MOTION_MODIFIER_iterator)
12492 C->setIteratorModifier(Record.readExpr());
12493 }
12494 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
12495 C->setMapperIdInfo(Record.readDeclarationNameInfo());
12496 C->setColonLoc(Record.readSourceLocation());
12497 auto NumVars = C->varlist_size();
12498 auto UniqueDecls = C->getUniqueDeclarationsNum();
12499 auto TotalLists = C->getTotalComponentListNum();
12500 auto TotalComponents = C->getTotalComponentsNum();
12501
12502 SmallVector<Expr *, 16> Vars;
12503 Vars.reserve(NumVars);
12504 for (unsigned i = 0; i != NumVars; ++i)
12505 Vars.push_back(Record.readSubExpr());
12506 C->setVarRefs(Vars);
12507
12508 SmallVector<Expr *, 16> UDMappers;
12509 UDMappers.reserve(NumVars);
12510 for (unsigned I = 0; I < NumVars; ++I)
12511 UDMappers.push_back(Record.readSubExpr());
12512 C->setUDMapperRefs(UDMappers);
12513
12514 SmallVector<ValueDecl *, 16> Decls;
12515 Decls.reserve(UniqueDecls);
12516 for (unsigned i = 0; i < UniqueDecls; ++i)
12517 Decls.push_back(Record.readDeclAs<ValueDecl>());
12518 C->setUniqueDecls(Decls);
12519
12520 SmallVector<unsigned, 16> ListsPerDecl;
12521 ListsPerDecl.reserve(UniqueDecls);
12522 for (unsigned i = 0; i < UniqueDecls; ++i)
12523 ListsPerDecl.push_back(Record.readInt());
12524 C->setDeclNumLists(ListsPerDecl);
12525
12526 SmallVector<unsigned, 32> ListSizes;
12527 ListSizes.reserve(TotalLists);
12528 for (unsigned i = 0; i < TotalLists; ++i)
12529 ListSizes.push_back(Record.readInt());
12530 C->setComponentListSizes(ListSizes);
12531
12532 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12533 Components.reserve(TotalComponents);
12534 for (unsigned i = 0; i < TotalComponents; ++i) {
12535 Expr *AssociatedExprPr = Record.readSubExpr();
12536 bool IsNonContiguous = Record.readBool();
12537 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12538 Components.emplace_back(AssociatedExprPr, AssociatedDecl, IsNonContiguous);
12539 }
12540 C->setComponents(Components, ListSizes);
12541 }
12542
12543 void OMPClauseReader::VisitOMPUseDevicePtrClause(OMPUseDevicePtrClause *C) {
12544 C->setLParenLoc(Record.readSourceLocation());
12545 auto NumVars = C->varlist_size();
12546 auto UniqueDecls = C->getUniqueDeclarationsNum();
12547 auto TotalLists = C->getTotalComponentListNum();
12548 auto TotalComponents = C->getTotalComponentsNum();
12549
12550 SmallVector<Expr *, 16> Vars;
12551 Vars.reserve(NumVars);
12552 for (unsigned i = 0; i != NumVars; ++i)
12553 Vars.push_back(Record.readSubExpr());
12554 C->setVarRefs(Vars);
12555 Vars.clear();
12556 for (unsigned i = 0; i != NumVars; ++i)
12557 Vars.push_back(Record.readSubExpr());
12558 C->setPrivateCopies(Vars);
12559 Vars.clear();
12560 for (unsigned i = 0; i != NumVars; ++i)
12561 Vars.push_back(Record.readSubExpr());
12562 C->setInits(Vars);
12563
12564 SmallVector<ValueDecl *, 16> Decls;
12565 Decls.reserve(UniqueDecls);
12566 for (unsigned i = 0; i < UniqueDecls; ++i)
12567 Decls.push_back(Record.readDeclAs<ValueDecl>());
12568 C->setUniqueDecls(Decls);
12569
12570 SmallVector<unsigned, 16> ListsPerDecl;
12571 ListsPerDecl.reserve(UniqueDecls);
12572 for (unsigned i = 0; i < UniqueDecls; ++i)
12573 ListsPerDecl.push_back(Record.readInt());
12574 C->setDeclNumLists(ListsPerDecl);
12575
12576 SmallVector<unsigned, 32> ListSizes;
12577 ListSizes.reserve(TotalLists);
12578 for (unsigned i = 0; i < TotalLists; ++i)
12579 ListSizes.push_back(Record.readInt());
12580 C->setComponentListSizes(ListSizes);
12581
12582 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12583 Components.reserve(TotalComponents);
12584 for (unsigned i = 0; i < TotalComponents; ++i) {
12585 auto *AssociatedExprPr = Record.readSubExpr();
12586 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12587 Components.emplace_back(AssociatedExprPr, AssociatedDecl,
12588 /*IsNonContiguous=*/false);
12589 }
12590 C->setComponents(Components, ListSizes);
12591 }
12592
12593 void OMPClauseReader::VisitOMPUseDeviceAddrClause(OMPUseDeviceAddrClause *C) {
12594 C->setLParenLoc(Record.readSourceLocation());
12595 auto NumVars = C->varlist_size();
12596 auto UniqueDecls = C->getUniqueDeclarationsNum();
12597 auto TotalLists = C->getTotalComponentListNum();
12598 auto TotalComponents = C->getTotalComponentsNum();
12599
12600 SmallVector<Expr *, 16> Vars;
12601 Vars.reserve(NumVars);
12602 for (unsigned i = 0; i != NumVars; ++i)
12603 Vars.push_back(Record.readSubExpr());
12604 C->setVarRefs(Vars);
12605
12606 SmallVector<ValueDecl *, 16> Decls;
12607 Decls.reserve(UniqueDecls);
12608 for (unsigned i = 0; i < UniqueDecls; ++i)
12609 Decls.push_back(Record.readDeclAs<ValueDecl>());
12610 C->setUniqueDecls(Decls);
12611
12612 SmallVector<unsigned, 16> ListsPerDecl;
12613 ListsPerDecl.reserve(UniqueDecls);
12614 for (unsigned i = 0; i < UniqueDecls; ++i)
12615 ListsPerDecl.push_back(Record.readInt());
12616 C->setDeclNumLists(ListsPerDecl);
12617
12618 SmallVector<unsigned, 32> ListSizes;
12619 ListSizes.reserve(TotalLists);
12620 for (unsigned i = 0; i < TotalLists; ++i)
12621 ListSizes.push_back(Record.readInt());
12622 C->setComponentListSizes(ListSizes);
12623
12624 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12625 Components.reserve(TotalComponents);
12626 for (unsigned i = 0; i < TotalComponents; ++i) {
12627 Expr *AssociatedExpr = Record.readSubExpr();
12628 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12629 Components.emplace_back(AssociatedExpr, AssociatedDecl,
12630 /*IsNonContiguous*/ false);
12631 }
12632 C->setComponents(Components, ListSizes);
12633 }
12634
12635 void OMPClauseReader::VisitOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
12636 C->setLParenLoc(Record.readSourceLocation());
12637 auto NumVars = C->varlist_size();
12638 auto UniqueDecls = C->getUniqueDeclarationsNum();
12639 auto TotalLists = C->getTotalComponentListNum();
12640 auto TotalComponents = C->getTotalComponentsNum();
12641
12642 SmallVector<Expr *, 16> Vars;
12643 Vars.reserve(NumVars);
12644 for (unsigned i = 0; i != NumVars; ++i)
12645 Vars.push_back(Record.readSubExpr());
12646 C->setVarRefs(Vars);
12647 Vars.clear();
12648
12649 SmallVector<ValueDecl *, 16> Decls;
12650 Decls.reserve(UniqueDecls);
12651 for (unsigned i = 0; i < UniqueDecls; ++i)
12652 Decls.push_back(Record.readDeclAs<ValueDecl>());
12653 C->setUniqueDecls(Decls);
12654
12655 SmallVector<unsigned, 16> ListsPerDecl;
12656 ListsPerDecl.reserve(UniqueDecls);
12657 for (unsigned i = 0; i < UniqueDecls; ++i)
12658 ListsPerDecl.push_back(Record.readInt());
12659 C->setDeclNumLists(ListsPerDecl);
12660
12661 SmallVector<unsigned, 32> ListSizes;
12662 ListSizes.reserve(TotalLists);
12663 for (unsigned i = 0; i < TotalLists; ++i)
12664 ListSizes.push_back(Record.readInt());
12665 C->setComponentListSizes(ListSizes);
12666
12667 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12668 Components.reserve(TotalComponents);
12669 for (unsigned i = 0; i < TotalComponents; ++i) {
12670 Expr *AssociatedExpr = Record.readSubExpr();
12671 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12672 Components.emplace_back(AssociatedExpr, AssociatedDecl,
12673 /*IsNonContiguous=*/false);
12674 }
12675 C->setComponents(Components, ListSizes);
12676 }
12677
12678 void OMPClauseReader::VisitOMPHasDeviceAddrClause(OMPHasDeviceAddrClause *C) {
12679 C->setLParenLoc(Record.readSourceLocation());
12680 auto NumVars = C->varlist_size();
12681 auto UniqueDecls = C->getUniqueDeclarationsNum();
12682 auto TotalLists = C->getTotalComponentListNum();
12683 auto TotalComponents = C->getTotalComponentsNum();
12684
12685 SmallVector<Expr *, 16> Vars;
12686 Vars.reserve(NumVars);
12687 for (unsigned I = 0; I != NumVars; ++I)
12688 Vars.push_back(Record.readSubExpr());
12689 C->setVarRefs(Vars);
12690 Vars.clear();
12691
12692 SmallVector<ValueDecl *, 16> Decls;
12693 Decls.reserve(UniqueDecls);
12694 for (unsigned I = 0; I < UniqueDecls; ++I)
12695 Decls.push_back(Record.readDeclAs<ValueDecl>());
12696 C->setUniqueDecls(Decls);
12697
12698 SmallVector<unsigned, 16> ListsPerDecl;
12699 ListsPerDecl.reserve(UniqueDecls);
12700 for (unsigned I = 0; I < UniqueDecls; ++I)
12701 ListsPerDecl.push_back(Record.readInt());
12702 C->setDeclNumLists(ListsPerDecl);
12703
12704 SmallVector<unsigned, 32> ListSizes;
12705 ListSizes.reserve(TotalLists);
12706 for (unsigned i = 0; i < TotalLists; ++i)
12707 ListSizes.push_back(Record.readInt());
12708 C->setComponentListSizes(ListSizes);
12709
12710 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12711 Components.reserve(TotalComponents);
12712 for (unsigned I = 0; I < TotalComponents; ++I) {
12713 Expr *AssociatedExpr = Record.readSubExpr();
12714 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12715 Components.emplace_back(AssociatedExpr, AssociatedDecl,
12716 /*IsNonContiguous=*/false);
12717 }
12718 C->setComponents(Components, ListSizes);
12719 }
12720
12721 void OMPClauseReader::VisitOMPNontemporalClause(OMPNontemporalClause *C) {
12722 C->setLParenLoc(Record.readSourceLocation());
12723 unsigned NumVars = C->varlist_size();
12724 SmallVector<Expr *, 16> Vars;
12725 Vars.reserve(NumVars);
12726 for (unsigned i = 0; i != NumVars; ++i)
12727 Vars.push_back(Record.readSubExpr());
12728 C->setVarRefs(Vars);
12729 Vars.clear();
12730 Vars.reserve(NumVars);
12731 for (unsigned i = 0; i != NumVars; ++i)
12732 Vars.push_back(Record.readSubExpr());
12733 C->setPrivateRefs(Vars);
12734 }
12735
12736 void OMPClauseReader::VisitOMPInclusiveClause(OMPInclusiveClause *C) {
12737 C->setLParenLoc(Record.readSourceLocation());
12738 unsigned NumVars = C->varlist_size();
12739 SmallVector<Expr *, 16> Vars;
12740 Vars.reserve(NumVars);
12741 for (unsigned i = 0; i != NumVars; ++i)
12742 Vars.push_back(Record.readSubExpr());
12743 C->setVarRefs(Vars);
12744 }
12745
12746 void OMPClauseReader::VisitOMPExclusiveClause(OMPExclusiveClause *C) {
12747 C->setLParenLoc(Record.readSourceLocation());
12748 unsigned NumVars = C->varlist_size();
12749 SmallVector<Expr *, 16> Vars;
12750 Vars.reserve(NumVars);
12751 for (unsigned i = 0; i != NumVars; ++i)
12752 Vars.push_back(Record.readSubExpr());
12753 C->setVarRefs(Vars);
12754 }
12755
12756 void OMPClauseReader::VisitOMPUsesAllocatorsClause(OMPUsesAllocatorsClause *C) {
12757 C->setLParenLoc(Record.readSourceLocation());
12758 unsigned NumOfAllocators = C->getNumberOfAllocators();
12759 SmallVector<OMPUsesAllocatorsClause::Data, 4> Data;
12760 Data.reserve(NumOfAllocators);
12761 for (unsigned I = 0; I != NumOfAllocators; ++I) {
12762 OMPUsesAllocatorsClause::Data &D = Data.emplace_back();
12763 D.Allocator = Record.readSubExpr();
12764 D.AllocatorTraits = Record.readSubExpr();
12765 D.LParenLoc = Record.readSourceLocation();
12766 D.RParenLoc = Record.readSourceLocation();
12767 }
12768 C->setAllocatorsData(Data);
12769 }
12770
12771 void OMPClauseReader::VisitOMPAffinityClause(OMPAffinityClause *C) {
12772 C->setLParenLoc(Record.readSourceLocation());
12773 C->setModifier(Record.readSubExpr());
12774 C->setColonLoc(Record.readSourceLocation());
12775 unsigned NumOfLocators = C->varlist_size();
12776 SmallVector<Expr *, 4> Locators;
12777 Locators.reserve(NumOfLocators);
12778 for (unsigned I = 0; I != NumOfLocators; ++I)
12779 Locators.push_back(Record.readSubExpr());
12780 C->setVarRefs(Locators);
12781 }
12782
12783 void OMPClauseReader::VisitOMPOrderClause(OMPOrderClause *C) {
12784 C->setKind(Record.readEnum<OpenMPOrderClauseKind>());
12785 C->setModifier(Record.readEnum<OpenMPOrderClauseModifier>());
12786 C->setLParenLoc(Record.readSourceLocation());
12787 C->setKindKwLoc(Record.readSourceLocation());
12788 C->setModifierKwLoc(Record.readSourceLocation());
12789 }
12790
12791 void OMPClauseReader::VisitOMPFilterClause(OMPFilterClause *C) {
12792 VisitOMPClauseWithPreInit(C);
12793 C->setThreadID(Record.readSubExpr());
12794 C->setLParenLoc(Record.readSourceLocation());
12795 }
12796
12797 void OMPClauseReader::VisitOMPBindClause(OMPBindClause *C) {
12798 C->setBindKind(Record.readEnum<OpenMPBindClauseKind>());
12799 C->setLParenLoc(Record.readSourceLocation());
12800 C->setBindKindLoc(Record.readSourceLocation());
12801 }
12802
12803 void OMPClauseReader::VisitOMPAlignClause(OMPAlignClause *C) {
12804 C->setAlignment(Record.readExpr());
12805 C->setLParenLoc(Record.readSourceLocation());
12806 }
12807
12808 void OMPClauseReader::VisitOMPXDynCGroupMemClause(OMPXDynCGroupMemClause *C) {
12809 VisitOMPClauseWithPreInit(C);
12810 C->setSize(Record.readSubExpr());
12811 C->setLParenLoc(Record.readSourceLocation());
12812 }
12813
12814 void OMPClauseReader::VisitOMPDynGroupprivateClause(
12815 OMPDynGroupprivateClause *C) {
12816 VisitOMPClauseWithPreInit(C);
12817 C->setDynGroupprivateModifier(
12818 Record.readEnum<OpenMPDynGroupprivateClauseModifier>());
12819 C->setDynGroupprivateFallbackModifier(
12820 Record.readEnum<OpenMPDynGroupprivateClauseFallbackModifier>());
12821 C->setSize(Record.readSubExpr());
12822 C->setLParenLoc(Record.readSourceLocation());
12823 C->setDynGroupprivateModifierLoc(Record.readSourceLocation());
12824 C->setDynGroupprivateFallbackModifierLoc(Record.readSourceLocation());
12825 }
12826
12827 void OMPClauseReader::VisitOMPDoacrossClause(OMPDoacrossClause *C) {
12828 C->setLParenLoc(Record.readSourceLocation());
12829 C->setDependenceType(
12830 static_cast<OpenMPDoacrossClauseModifier>(Record.readInt()));
12831 C->setDependenceLoc(Record.readSourceLocation());
12832 C->setColonLoc(Record.readSourceLocation());
12833 unsigned NumVars = C->varlist_size();
12834 SmallVector<Expr *, 16> Vars;
12835 Vars.reserve(NumVars);
12836 for (unsigned I = 0; I != NumVars; ++I)
12837 Vars.push_back(Record.readSubExpr());
12838 C->setVarRefs(Vars);
12839 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
12840 C->setLoopData(I, Record.readSubExpr());
12841 }
12842
12843 void OMPClauseReader::VisitOMPXAttributeClause(OMPXAttributeClause *C) {
12844 AttrVec Attrs;
12845 Record.readAttributes(Attrs);
12846 C->setAttrs(Attrs);
12847 C->setLocStart(Record.readSourceLocation());
12848 C->setLParenLoc(Record.readSourceLocation());
12849 C->setLocEnd(Record.readSourceLocation());
12850 }
12851
12852 void OMPClauseReader::VisitOMPXBareClause(OMPXBareClause *C) {}
12853
12854 OMPTraitInfo *ASTRecordReader::readOMPTraitInfo() {
12855 OMPTraitInfo &TI = getContext().getNewOMPTraitInfo();
12856 TI.Sets.resize(readUInt32());
12857 for (auto &Set : TI.Sets) {
12858 Set.Kind = readEnum<llvm::omp::TraitSet>();
12859 Set.Selectors.resize(readUInt32());
12860 for (auto &Selector : Set.Selectors) {
12861 Selector.Kind = readEnum<llvm::omp::TraitSelector>();
12862 Selector.ScoreOrCondition = nullptr;
12863 if (readBool())
12864 Selector.ScoreOrCondition = readExprRef();
12865 Selector.Properties.resize(readUInt32());
12866 for (auto &Property : Selector.Properties)
12867 Property.Kind = readEnum<llvm::omp::TraitProperty>();
12868 }
12869 }
12870 return &TI;
12871 }
12872
12873 void ASTRecordReader::readOMPChildren(OMPChildren *Data) {
12874 if (!Data)
12875 return;
12876 if (Reader->ReadingKind == ASTReader::Read_Stmt) {
12877 // Skip NumClauses, NumChildren and HasAssociatedStmt fields.
12878 skipInts(3);
12879 }
12880 SmallVector<OMPClause *, 4> Clauses(Data->getNumClauses());
12881 for (unsigned I = 0, E = Data->getNumClauses(); I < E; ++I)
12882 Clauses[I] = readOMPClause();
12883 Data->setClauses(Clauses);
12884 if (Data->hasAssociatedStmt())
12885 Data->setAssociatedStmt(readStmt());
12886 for (unsigned I = 0, E = Data->getNumChildren(); I < E; ++I)
12887 Data->getChildren()[I] = readStmt();
12888 }
12889
12890 SmallVector<Expr *> ASTRecordReader::readOpenACCVarList() {
12891 unsigned NumVars = readInt();
12892 llvm::SmallVector<Expr *> VarList;
12893 for (unsigned I = 0; I < NumVars; ++I)
12894 VarList.push_back(readExpr());
12895 return VarList;
12896 }
12897
12898 SmallVector<Expr *> ASTRecordReader::readOpenACCIntExprList() {
12899 unsigned NumExprs = readInt();
12900 llvm::SmallVector<Expr *> ExprList;
12901 for (unsigned I = 0; I < NumExprs; ++I)
12902 ExprList.push_back(readSubExpr());
12903 return ExprList;
12904 }
12905
12906 OpenACCClause *ASTRecordReader::readOpenACCClause() {
12907 OpenACCClauseKind ClauseKind = readEnum<OpenACCClauseKind>();
12908 SourceLocation BeginLoc = readSourceLocation();
12909 SourceLocation EndLoc = readSourceLocation();
12910
12911 switch (ClauseKind) {
12912 case OpenACCClauseKind::Default: {
12913 SourceLocation LParenLoc = readSourceLocation();
12914 OpenACCDefaultClauseKind DCK = readEnum<OpenACCDefaultClauseKind>();
12915 return OpenACCDefaultClause::Create(getContext(), DCK, BeginLoc, LParenLoc,
12916 EndLoc);
12917 }
12918 case OpenACCClauseKind::If: {
12919 SourceLocation LParenLoc = readSourceLocation();
12920 Expr *CondExpr = readSubExpr();
12921 return OpenACCIfClause::Create(getContext(), BeginLoc, LParenLoc, CondExpr,
12922 EndLoc);
12923 }
12924 case OpenACCClauseKind::Self: {
12925 SourceLocation LParenLoc = readSourceLocation();
12926 bool isConditionExprClause = readBool();
12927 if (isConditionExprClause) {
12928 Expr *CondExpr = readBool() ? readSubExpr() : nullptr;
12929 return OpenACCSelfClause::Create(getContext(), BeginLoc, LParenLoc,
12930 CondExpr, EndLoc);
12931 }
12932 unsigned NumVars = readInt();
12933 llvm::SmallVector<Expr *> VarList;
12934 for (unsigned I = 0; I < NumVars; ++I)
12935 VarList.push_back(readSubExpr());
12936 return OpenACCSelfClause::Create(getContext(), BeginLoc, LParenLoc, VarList,
12937 EndLoc);
12938 }
12939 case OpenACCClauseKind::NumGangs: {
12940 SourceLocation LParenLoc = readSourceLocation();
12941 unsigned NumClauses = readInt();
12942 llvm::SmallVector<Expr *> IntExprs;
12943 for (unsigned I = 0; I < NumClauses; ++I)
12944 IntExprs.push_back(readSubExpr());
12945 return OpenACCNumGangsClause::Create(getContext(), BeginLoc, LParenLoc,
12946 IntExprs, EndLoc);
12947 }
12948 case OpenACCClauseKind::NumWorkers: {
12949 SourceLocation LParenLoc = readSourceLocation();
12950 Expr *IntExpr = readSubExpr();
12951 return OpenACCNumWorkersClause::Create(getContext(), BeginLoc, LParenLoc,
12952 IntExpr, EndLoc);
12953 }
12954 case OpenACCClauseKind::DeviceNum: {
12955 SourceLocation LParenLoc = readSourceLocation();
12956 Expr *IntExpr = readSubExpr();
12957 return OpenACCDeviceNumClause::Create(getContext(), BeginLoc, LParenLoc,
12958 IntExpr, EndLoc);
12959 }
12960 case OpenACCClauseKind::DefaultAsync: {
12961 SourceLocation LParenLoc = readSourceLocation();
12962 Expr *IntExpr = readSubExpr();
12963 return OpenACCDefaultAsyncClause::Create(getContext(), BeginLoc, LParenLoc,
12964 IntExpr, EndLoc);
12965 }
12966 case OpenACCClauseKind::VectorLength: {
12967 SourceLocation LParenLoc = readSourceLocation();
12968 Expr *IntExpr = readSubExpr();
12969 return OpenACCVectorLengthClause::Create(getContext(), BeginLoc, LParenLoc,
12970 IntExpr, EndLoc);
12971 }
12972 case OpenACCClauseKind::Private: {
12973 SourceLocation LParenLoc = readSourceLocation();
12974 llvm::SmallVector<Expr *> VarList = readOpenACCVarList();
12975
12976 llvm::SmallVector<OpenACCPrivateRecipe> RecipeList;
12977 for (unsigned I = 0; I < VarList.size(); ++I) {
12978 static_assert(sizeof(OpenACCPrivateRecipe) == 1 * sizeof(int *));
12979 VarDecl *Alloca = readDeclAs<VarDecl>();
12980 RecipeList.push_back({Alloca});
12981 }
12982
12983 return OpenACCPrivateClause::Create(getContext(), BeginLoc, LParenLoc,
12984 VarList, RecipeList, EndLoc);
12985 }
12986 case OpenACCClauseKind::Host: {
12987 SourceLocation LParenLoc = readSourceLocation();
12988 llvm::SmallVector<Expr *> VarList = readOpenACCVarList();
12989 return OpenACCHostClause::Create(getContext(), BeginLoc, LParenLoc, VarList,
12990 EndLoc);
12991 }
12992 case OpenACCClauseKind::Device: {
12993 SourceLocation LParenLoc = readSourceLocation();
12994 llvm::SmallVector<Expr *> VarList = readOpenACCVarList();
12995 return OpenACCDeviceClause::Create(getContext(), BeginLoc, LParenLoc,
12996 VarList, EndLoc);
12997 }
12998 case OpenACCClauseKind::FirstPrivate: {
12999 SourceLocation LParenLoc = readSourceLocation();
13000 llvm::SmallVector<Expr *> VarList = readOpenACCVarList();
13001 llvm::SmallVector<OpenACCFirstPrivateRecipe> RecipeList;
13002 for (unsigned I = 0; I < VarList.size(); ++I) {
13003 static_assert(sizeof(OpenACCFirstPrivateRecipe) == 2 * sizeof(int *));
13004 VarDecl *Recipe = readDeclAs<VarDecl>();
13005 VarDecl *RecipeTemp = readDeclAs<VarDecl>();
13006 RecipeList.push_back({Recipe, RecipeTemp});
13007 }
13008
13009 return OpenACCFirstPrivateClause::Create(getContext(), BeginLoc, LParenLoc,
13010 VarList, RecipeList, EndLoc);
13011 }
13012 case OpenACCClauseKind::Attach: {
13013 SourceLocation LParenLoc = readSourceLocation();
13014 llvm::SmallVector<Expr *> VarList = readOpenACCVarList();
13015 return OpenACCAttachClause::Create(getContext(), BeginLoc, LParenLoc,
13016 VarList, EndLoc);
13017 }
13018 case OpenACCClauseKind::Detach: {
13019 SourceLocation LParenLoc = readSourceLocation();
13020 llvm::SmallVector<Expr *> VarList = readOpenACCVarList();
13021 return OpenACCDetachClause::Create(getContext(), BeginLoc, LParenLoc,
13022 VarList, EndLoc);
13023 }
13024 case OpenACCClauseKind::Delete: {
13025 SourceLocation LParenLoc = readSourceLocation();
13026 llvm::SmallVector<Expr *> VarList = readOpenACCVarList();
13027 return OpenACCDeleteClause::Create(getContext(), BeginLoc, LParenLoc,
13028 VarList, EndLoc);
13029 }
13030 case OpenACCClauseKind::UseDevice: {
13031 SourceLocation LParenLoc = readSourceLocation();
13032 llvm::SmallVector<Expr *> VarList = readOpenACCVarList();
13033 return OpenACCUseDeviceClause::Create(getContext(), BeginLoc, LParenLoc,
13034 VarList, EndLoc);
13035 }
13036 case OpenACCClauseKind::DevicePtr: {
13037 SourceLocation LParenLoc = readSourceLocation();
13038 llvm::SmallVector<Expr *> VarList = readOpenACCVarList();
13039 return OpenACCDevicePtrClause::Create(getContext(), BeginLoc, LParenLoc,
13040 VarList, EndLoc);
13041 }
13042 case OpenACCClauseKind::NoCreate: {
13043 SourceLocation LParenLoc = readSourceLocation();
13044 llvm::SmallVector<Expr *> VarList = readOpenACCVarList();
13045 return OpenACCNoCreateClause::Create(getContext(), BeginLoc, LParenLoc,
13046 VarList, EndLoc);
13047 }
13048 case OpenACCClauseKind::Present: {
13049 SourceLocation LParenLoc = readSourceLocation();
13050 llvm::SmallVector<Expr *> VarList = readOpenACCVarList();
13051 return OpenACCPresentClause::Create(getContext(), BeginLoc, LParenLoc,
13052 VarList, EndLoc);
13053 }
13054 case OpenACCClauseKind::PCopy:
13055 case OpenACCClauseKind::PresentOrCopy:
13056 case OpenACCClauseKind::Copy: {
13057 SourceLocation LParenLoc = readSourceLocation();
13058 OpenACCModifierKind ModList = readEnum<OpenACCModifierKind>();
13059 llvm::SmallVector<Expr *> VarList = readOpenACCVarList();
13060 return OpenACCCopyClause::Create(getContext(), ClauseKind, BeginLoc,
13061 LParenLoc, ModList, VarList, EndLoc);
13062 }
13063 case OpenACCClauseKind::CopyIn:
13064 case OpenACCClauseKind::PCopyIn:
13065 case OpenACCClauseKind::PresentOrCopyIn: {
13066 SourceLocation LParenLoc = readSourceLocation();
13067 OpenACCModifierKind ModList = readEnum<OpenACCModifierKind>();
13068 llvm::SmallVector<Expr *> VarList = readOpenACCVarList();
13069 return OpenACCCopyInClause::Create(getContext(), ClauseKind, BeginLoc,
13070 LParenLoc, ModList, VarList, EndLoc);
13071 }
13072 case OpenACCClauseKind::CopyOut:
13073 case OpenACCClauseKind::PCopyOut:
13074 case OpenACCClauseKind::PresentOrCopyOut: {
13075 SourceLocation LParenLoc = readSourceLocation();
13076 OpenACCModifierKind ModList = readEnum<OpenACCModifierKind>();
13077 llvm::SmallVector<Expr *> VarList = readOpenACCVarList();
13078 return OpenACCCopyOutClause::Create(getContext(), ClauseKind, BeginLoc,
13079 LParenLoc, ModList, VarList, EndLoc);
13080 }
13081 case OpenACCClauseKind::Create:
13082 case OpenACCClauseKind::PCreate:
13083 case OpenACCClauseKind::PresentOrCreate: {
13084 SourceLocation LParenLoc = readSourceLocation();
13085 OpenACCModifierKind ModList = readEnum<OpenACCModifierKind>();
13086 llvm::SmallVector<Expr *> VarList = readOpenACCVarList();
13087 return OpenACCCreateClause::Create(getContext(), ClauseKind, BeginLoc,
13088 LParenLoc, ModList, VarList, EndLoc);
13089 }
13090 case OpenACCClauseKind::Async: {
13091 SourceLocation LParenLoc = readSourceLocation();
13092 Expr *AsyncExpr = readBool() ? readSubExpr() : nullptr;
13093 return OpenACCAsyncClause::Create(getContext(), BeginLoc, LParenLoc,
13094 AsyncExpr, EndLoc);
13095 }
13096 case OpenACCClauseKind::Wait: {
13097 SourceLocation LParenLoc = readSourceLocation();
13098 Expr *DevNumExpr = readBool() ? readSubExpr() : nullptr;
13099 SourceLocation QueuesLoc = readSourceLocation();
13100 llvm::SmallVector<Expr *> QueueIdExprs = readOpenACCIntExprList();
13101 return OpenACCWaitClause::Create(getContext(), BeginLoc, LParenLoc,
13102 DevNumExpr, QueuesLoc, QueueIdExprs,
13103 EndLoc);
13104 }
13105 case OpenACCClauseKind::DeviceType:
13106 case OpenACCClauseKind::DType: {
13107 SourceLocation LParenLoc = readSourceLocation();
13108 llvm::SmallVector<DeviceTypeArgument> Archs;
13109 unsigned NumArchs = readInt();
13110
13111 for (unsigned I = 0; I < NumArchs; ++I) {
13112 IdentifierInfo *Ident = readBool() ? readIdentifier() : nullptr;
13113 SourceLocation Loc = readSourceLocation();
13114 Archs.emplace_back(Loc, Ident);
13115 }
13116
13117 return OpenACCDeviceTypeClause::Create(getContext(), ClauseKind, BeginLoc,
13118 LParenLoc, Archs, EndLoc);
13119 }
13120 case OpenACCClauseKind::Reduction: {
13121 SourceLocation LParenLoc = readSourceLocation();
13122 OpenACCReductionOperator Op = readEnum<OpenACCReductionOperator>();
13123 llvm::SmallVector<Expr *> VarList = readOpenACCVarList();
13124 llvm::SmallVector<OpenACCReductionRecipeWithStorage> RecipeList;
13125
13126 for (unsigned I = 0; I < VarList.size(); ++I) {
13127 VarDecl *Recipe = readDeclAs<VarDecl>();
13128
13129 static_assert(sizeof(OpenACCReductionRecipe::CombinerRecipe) ==
13130 3 * sizeof(int *));
13131
13132 llvm::SmallVector<OpenACCReductionRecipe::CombinerRecipe> Combiners;
13133 unsigned NumCombiners = readInt();
13134 for (unsigned I = 0; I < NumCombiners; ++I) {
13135 VarDecl *LHS = readDeclAs<VarDecl>();
13136 VarDecl *RHS = readDeclAs<VarDecl>();
13137 Expr *Op = readExpr();
13138
13139 Combiners.push_back({LHS, RHS, Op});
13140 }
13141
13142 RecipeList.push_back({Recipe, Combiners});
13143 }
13144
13145 return OpenACCReductionClause::Create(getContext(), BeginLoc, LParenLoc, Op,
13146 VarList, RecipeList, EndLoc);
13147 }
13148 case OpenACCClauseKind::Seq:
13149 return OpenACCSeqClause::Create(getContext(), BeginLoc, EndLoc);
13150 case OpenACCClauseKind::NoHost:
13151 return OpenACCNoHostClause::Create(getContext(), BeginLoc, EndLoc);
13152 case OpenACCClauseKind::Finalize:
13153 return OpenACCFinalizeClause::Create(getContext(), BeginLoc, EndLoc);
13154 case OpenACCClauseKind::IfPresent:
13155 return OpenACCIfPresentClause::Create(getContext(), BeginLoc, EndLoc);
13156 case OpenACCClauseKind::Independent:
13157 return OpenACCIndependentClause::Create(getContext(), BeginLoc, EndLoc);
13158 case OpenACCClauseKind::Auto:
13159 return OpenACCAutoClause::Create(getContext(), BeginLoc, EndLoc);
13160 case OpenACCClauseKind::Collapse: {
13161 SourceLocation LParenLoc = readSourceLocation();
13162 bool HasForce = readBool();
13163 Expr *LoopCount = readSubExpr();
13164 return OpenACCCollapseClause::Create(getContext(), BeginLoc, LParenLoc,
13165 HasForce, LoopCount, EndLoc);
13166 }
13167 case OpenACCClauseKind::Tile: {
13168 SourceLocation LParenLoc = readSourceLocation();
13169 unsigned NumClauses = readInt();
13170 llvm::SmallVector<Expr *> SizeExprs;
13171 for (unsigned I = 0; I < NumClauses; ++I)
13172 SizeExprs.push_back(readSubExpr());
13173 return OpenACCTileClause::Create(getContext(), BeginLoc, LParenLoc,
13174 SizeExprs, EndLoc);
13175 }
13176 case OpenACCClauseKind::Gang: {
13177 SourceLocation LParenLoc = readSourceLocation();
13178 unsigned NumExprs = readInt();
13179 llvm::SmallVector<OpenACCGangKind> GangKinds;
13180 llvm::SmallVector<Expr *> Exprs;
13181 for (unsigned I = 0; I < NumExprs; ++I) {
13182 GangKinds.push_back(readEnum<OpenACCGangKind>());
13183 // Can't use `readSubExpr` because this is usable from a 'decl' construct.
13184 Exprs.push_back(readExpr());
13185 }
13186 return OpenACCGangClause::Create(getContext(), BeginLoc, LParenLoc,
13187 GangKinds, Exprs, EndLoc);
13188 }
13189 case OpenACCClauseKind::Worker: {
13190 SourceLocation LParenLoc = readSourceLocation();
13191 Expr *WorkerExpr = readBool() ? readSubExpr() : nullptr;
13192 return OpenACCWorkerClause::Create(getContext(), BeginLoc, LParenLoc,
13193 WorkerExpr, EndLoc);
13194 }
13195 case OpenACCClauseKind::Vector: {
13196 SourceLocation LParenLoc = readSourceLocation();
13197 Expr *VectorExpr = readBool() ? readSubExpr() : nullptr;
13198 return OpenACCVectorClause::Create(getContext(), BeginLoc, LParenLoc,
13199 VectorExpr, EndLoc);
13200 }
13201 case OpenACCClauseKind::Link: {
13202 SourceLocation LParenLoc = readSourceLocation();
13203 llvm::SmallVector<Expr *> VarList = readOpenACCVarList();
13204 return OpenACCLinkClause::Create(getContext(), BeginLoc, LParenLoc, VarList,
13205 EndLoc);
13206 }
13207 case OpenACCClauseKind::DeviceResident: {
13208 SourceLocation LParenLoc = readSourceLocation();
13209 llvm::SmallVector<Expr *> VarList = readOpenACCVarList();
13210 return OpenACCDeviceResidentClause::Create(getContext(), BeginLoc,
13211 LParenLoc, VarList, EndLoc);
13212 }
13213
13214 case OpenACCClauseKind::Bind: {
13215 SourceLocation LParenLoc = readSourceLocation();
13216 bool IsString = readBool();
13217 if (IsString)
13218 return OpenACCBindClause::Create(getContext(), BeginLoc, LParenLoc,
13219 cast<StringLiteral>(readExpr()), EndLoc);
13220 return OpenACCBindClause::Create(getContext(), BeginLoc, LParenLoc,
13221 readIdentifier(), EndLoc);
13222 }
13223 case OpenACCClauseKind::Shortloop:
13224 case OpenACCClauseKind::Invalid:
13225 llvm_unreachable("Clause serialization not yet implemented");
13226 }
13227 llvm_unreachable("Invalid Clause Kind");
13228 }
13229
13230 void ASTRecordReader::readOpenACCClauseList(
13231 MutableArrayRef<const OpenACCClause *> Clauses) {
13232 for (unsigned I = 0; I < Clauses.size(); ++I)
13233 Clauses[I] = readOpenACCClause();
13234 }
13235
13236 void ASTRecordReader::readOpenACCRoutineDeclAttr(OpenACCRoutineDeclAttr *A) {
13237 unsigned NumVars = readInt();
13238 A->Clauses.resize(NumVars);
13239 readOpenACCClauseList(A->Clauses);
13240 }
13241
13242 static unsigned getStableHashForModuleName(StringRef PrimaryModuleName) {
13243 // TODO: Maybe it is better to check PrimaryModuleName is a valid
13244 // module name?
13245 llvm::FoldingSetNodeID ID;
13246 ID.AddString(PrimaryModuleName);
13247 return ID.computeStableHash();
13248 }
13249
13250 UnsignedOrNone clang::getPrimaryModuleHash(const Module *M) {
13251 if (!M)
13252 return std::nullopt;
13253
13254 if (M->isHeaderLikeModule())
13255 return std::nullopt;
13256
13257 if (M->isGlobalModule())
13258 return std::nullopt;
13259
13260 StringRef PrimaryModuleName = M->getPrimaryModuleInterfaceName();
13261 return getStableHashForModuleName(PrimaryModuleName);
13262 }