clang 23.0.0git
ASTReader.cpp
Go to the documentation of this file.
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"
22#include "clang/AST/Attr.h"
23#include "clang/AST/Decl.h"
24#include "clang/AST/DeclBase.h"
25#include "clang/AST/DeclCXX.h"
27#include "clang/AST/DeclGroup.h"
28#include "clang/AST/DeclObjC.h"
31#include "clang/AST/Expr.h"
32#include "clang/AST/ExprCXX.h"
41#include "clang/AST/Type.h"
42#include "clang/AST/TypeLoc.h"
54#include "clang/Basic/LLVM.h"
56#include "clang/Basic/Module.h"
70#include "clang/Basic/Version.h"
73#include "clang/Lex/MacroInfo.h"
74#include "clang/Lex/ModuleMap.h"
78#include "clang/Lex/Token.h"
80#include "clang/Sema/Scope.h"
81#include "clang/Sema/Sema.h"
82#include "clang/Sema/SemaCUDA.h"
83#include "clang/Sema/SemaObjC.h"
84#include "clang/Sema/Weak.h"
97#include "llvm/ADT/APFloat.h"
98#include "llvm/ADT/APInt.h"
99#include "llvm/ADT/ArrayRef.h"
100#include "llvm/ADT/DenseMap.h"
101#include "llvm/ADT/FoldingSet.h"
102#include "llvm/ADT/IntrusiveRefCntPtr.h"
103#include "llvm/ADT/STLExtras.h"
104#include "llvm/ADT/ScopeExit.h"
105#include "llvm/ADT/Sequence.h"
106#include "llvm/ADT/SmallPtrSet.h"
107#include "llvm/ADT/SmallVector.h"
108#include "llvm/ADT/StringExtras.h"
109#include "llvm/ADT/StringMap.h"
110#include "llvm/ADT/StringRef.h"
111#include "llvm/ADT/iterator_range.h"
112#include "llvm/Bitstream/BitstreamReader.h"
113#include "llvm/Support/Compiler.h"
114#include "llvm/Support/Compression.h"
115#include "llvm/Support/DJB.h"
116#include "llvm/Support/Endian.h"
117#include "llvm/Support/Error.h"
118#include "llvm/Support/ErrorHandling.h"
119#include "llvm/Support/LEB128.h"
120#include "llvm/Support/MemoryBuffer.h"
121#include "llvm/Support/Path.h"
122#include "llvm/Support/SaveAndRestore.h"
123#include "llvm/Support/TimeProfiler.h"
124#include "llvm/Support/Timer.h"
125#include "llvm/Support/VersionTuple.h"
126#include "llvm/Support/raw_ostream.h"
127#include "llvm/TargetParser/Triple.h"
128#include <algorithm>
129#include <cassert>
130#include <cstddef>
131#include <cstdint>
132#include <cstdio>
133#include <ctime>
134#include <iterator>
135#include <limits>
136#include <map>
137#include <memory>
138#include <optional>
139#include <string>
140#include <system_error>
141#include <tuple>
142#include <utility>
143#include <vector>
144
145using namespace clang;
146using namespace clang::serialization;
147using namespace clang::serialization::reader;
148using llvm::BitstreamCursor;
149
150//===----------------------------------------------------------------------===//
151// ChainedASTReaderListener implementation
152//===----------------------------------------------------------------------===//
153
154bool
156 return First->ReadFullVersionInformation(FullVersion) ||
157 Second->ReadFullVersionInformation(FullVersion);
158}
159
161 First->ReadModuleName(ModuleName);
162 Second->ReadModuleName(ModuleName);
163}
164
165void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
166 First->ReadModuleMapFile(ModuleMapPath);
167 Second->ReadModuleMapFile(ModuleMapPath);
168}
169
171 const LangOptions &LangOpts, StringRef ModuleFilename, bool Complain,
172 bool AllowCompatibleDifferences) {
173 return First->ReadLanguageOptions(LangOpts, ModuleFilename, Complain,
174 AllowCompatibleDifferences) ||
175 Second->ReadLanguageOptions(LangOpts, ModuleFilename, Complain,
176 AllowCompatibleDifferences);
177}
178
180 const CodeGenOptions &CGOpts, StringRef ModuleFilename, bool Complain,
181 bool AllowCompatibleDifferences) {
182 return First->ReadCodeGenOptions(CGOpts, ModuleFilename, Complain,
183 AllowCompatibleDifferences) ||
184 Second->ReadCodeGenOptions(CGOpts, ModuleFilename, Complain,
185 AllowCompatibleDifferences);
186}
187
189 const TargetOptions &TargetOpts, StringRef ModuleFilename, bool Complain,
190 bool AllowCompatibleDifferences) {
191 return First->ReadTargetOptions(TargetOpts, ModuleFilename, Complain,
192 AllowCompatibleDifferences) ||
193 Second->ReadTargetOptions(TargetOpts, ModuleFilename, Complain,
194 AllowCompatibleDifferences);
195}
196
198 DiagnosticOptions &DiagOpts, StringRef ModuleFilename, bool Complain) {
199 return First->ReadDiagnosticOptions(DiagOpts, ModuleFilename, Complain) ||
200 Second->ReadDiagnosticOptions(DiagOpts, ModuleFilename, Complain);
201}
202
203bool
205 bool Complain) {
206 return First->ReadFileSystemOptions(FSOpts, Complain) ||
207 Second->ReadFileSystemOptions(FSOpts, Complain);
208}
209
211 const HeaderSearchOptions &HSOpts, StringRef ModuleFilename,
212 StringRef ContextHash, bool Complain) {
213 return First->ReadHeaderSearchOptions(HSOpts, ModuleFilename, ContextHash,
214 Complain) ||
215 Second->ReadHeaderSearchOptions(HSOpts, ModuleFilename, ContextHash,
216 Complain);
217}
218
220 const PreprocessorOptions &PPOpts, StringRef ModuleFilename,
221 bool ReadMacros, bool Complain, std::string &SuggestedPredefines) {
222 return First->ReadPreprocessorOptions(PPOpts, ModuleFilename, ReadMacros,
223 Complain, SuggestedPredefines) ||
224 Second->ReadPreprocessorOptions(PPOpts, ModuleFilename, ReadMacros,
225 Complain, SuggestedPredefines);
226}
227
229 uint32_t Value) {
230 First->ReadCounter(M, Value);
231 Second->ReadCounter(M, Value);
232}
233
235 return First->needsInputFileVisitation() ||
236 Second->needsInputFileVisitation();
237}
238
240 return First->needsSystemInputFileVisitation() ||
241 Second->needsSystemInputFileVisitation();
242}
243
245 ModuleKind Kind,
246 bool DirectlyImported) {
247 First->visitModuleFile(Filename, Kind, DirectlyImported);
248 Second->visitModuleFile(Filename, Kind, DirectlyImported);
249}
250
252 bool isSystem,
253 bool isOverridden,
254 bool isExplicitModule) {
255 bool Continue = false;
256 if (First->needsInputFileVisitation() &&
257 (!isSystem || First->needsSystemInputFileVisitation()))
258 Continue |= First->visitInputFile(Filename, isSystem, isOverridden,
259 isExplicitModule);
260 if (Second->needsInputFileVisitation() &&
261 (!isSystem || Second->needsSystemInputFileVisitation()))
262 Continue |= Second->visitInputFile(Filename, isSystem, isOverridden,
263 isExplicitModule);
264 return Continue;
265}
266
268 const ModuleFileExtensionMetadata &Metadata) {
269 First->readModuleFileExtension(Metadata);
270 Second->readModuleFileExtension(Metadata);
271}
272
273//===----------------------------------------------------------------------===//
274// PCH validator implementation
275//===----------------------------------------------------------------------===//
276
278
279/// Compare the given set of language options against an existing set of
280/// language options.
281///
282/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
283/// \param AllowCompatibleDifferences If true, differences between compatible
284/// language options will be permitted.
285///
286/// \returns true if the languagae options mis-match, false otherwise.
287static bool checkLanguageOptions(const LangOptions &LangOpts,
288 const LangOptions &ExistingLangOpts,
289 StringRef ModuleFilename,
290 DiagnosticsEngine *Diags,
291 bool AllowCompatibleDifferences = true) {
292 // FIXME: Replace with C++20 `using enum LangOptions::CompatibilityKind`.
294
295#define LANGOPT(Name, Bits, Default, Compatibility, Description) \
296 if constexpr (CK::Compatibility != CK::Benign) { \
297 if ((CK::Compatibility == CK::NotCompatible) || \
298 (CK::Compatibility == CK::Compatible && \
299 !AllowCompatibleDifferences)) { \
300 if (ExistingLangOpts.Name != LangOpts.Name) { \
301 if (Diags) { \
302 if (Bits == 1) \
303 Diags->Report(diag::err_ast_file_langopt_mismatch) \
304 << Description << LangOpts.Name << ExistingLangOpts.Name \
305 << ModuleFilename; \
306 else \
307 Diags->Report(diag::err_ast_file_langopt_value_mismatch) \
308 << Description << ModuleFilename; \
309 } \
310 return true; \
311 } \
312 } \
313 }
314
315#define VALUE_LANGOPT(Name, Bits, Default, Compatibility, Description) \
316 if constexpr (CK::Compatibility != CK::Benign) { \
317 if ((CK::Compatibility == CK::NotCompatible) || \
318 (CK::Compatibility == CK::Compatible && \
319 !AllowCompatibleDifferences)) { \
320 if (ExistingLangOpts.Name != LangOpts.Name) { \
321 if (Diags) \
322 Diags->Report(diag::err_ast_file_langopt_value_mismatch) \
323 << Description << ModuleFilename; \
324 return true; \
325 } \
326 } \
327 }
328
329#define ENUM_LANGOPT(Name, Type, Bits, Default, Compatibility, Description) \
330 if constexpr (CK::Compatibility != CK::Benign) { \
331 if ((CK::Compatibility == CK::NotCompatible) || \
332 (CK::Compatibility == CK::Compatible && \
333 !AllowCompatibleDifferences)) { \
334 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
335 if (Diags) \
336 Diags->Report(diag::err_ast_file_langopt_value_mismatch) \
337 << Description << ModuleFilename; \
338 return true; \
339 } \
340 } \
341 }
342
343#include "clang/Basic/LangOptions.def"
344
345 if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) {
346 if (Diags)
347 Diags->Report(diag::err_ast_file_langopt_value_mismatch)
348 << "module features" << ModuleFilename;
349 return true;
350 }
351
352 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
353 if (Diags)
354 Diags->Report(diag::err_ast_file_langopt_value_mismatch)
355 << "target Objective-C runtime" << ModuleFilename;
356 return true;
357 }
358
359 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
361 if (Diags)
362 Diags->Report(diag::err_ast_file_langopt_value_mismatch)
363 << "block command names" << ModuleFilename;
364 return true;
365 }
366
367 // Sanitizer feature mismatches are treated as compatible differences. If
368 // compatible differences aren't allowed, we still only want to check for
369 // mismatches of non-modular sanitizers (the only ones which can affect AST
370 // generation).
371 if (!AllowCompatibleDifferences) {
372 SanitizerMask ModularSanitizers = getPPTransparentSanitizers();
373 SanitizerSet ExistingSanitizers = ExistingLangOpts.Sanitize;
374 SanitizerSet ImportedSanitizers = LangOpts.Sanitize;
375 ExistingSanitizers.clear(ModularSanitizers);
376 ImportedSanitizers.clear(ModularSanitizers);
377 if (ExistingSanitizers.Mask != ImportedSanitizers.Mask) {
378 const std::string Flag = "-fsanitize=";
379 if (Diags) {
380#define SANITIZER(NAME, ID) \
381 { \
382 bool InExistingModule = ExistingSanitizers.has(SanitizerKind::ID); \
383 bool InImportedModule = ImportedSanitizers.has(SanitizerKind::ID); \
384 if (InExistingModule != InImportedModule) \
385 Diags->Report(diag::err_ast_file_targetopt_feature_mismatch) \
386 << InExistingModule << ModuleFilename << (Flag + NAME); \
387 }
388#include "clang/Basic/Sanitizers.def"
389 }
390 return true;
391 }
392 }
393
394 return false;
395}
396
397static bool checkCodegenOptions(const CodeGenOptions &CGOpts,
398 const CodeGenOptions &ExistingCGOpts,
399 StringRef ModuleFilename,
400 DiagnosticsEngine *Diags,
401 bool AllowCompatibleDifferences = true) {
402 // FIXME: Specify and print a description for each option instead of the name.
403 // FIXME: Replace with C++20 `using enum CodeGenOptions::CompatibilityKind`.
405#define CODEGENOPT(Name, Bits, Default, Compatibility) \
406 if constexpr (CK::Compatibility != CK::Benign) { \
407 if ((CK::Compatibility == CK::NotCompatible) || \
408 (CK::Compatibility == CK::Compatible && \
409 !AllowCompatibleDifferences)) { \
410 if (ExistingCGOpts.Name != CGOpts.Name) { \
411 if (Diags) { \
412 if (Bits == 1) \
413 Diags->Report(diag::err_ast_file_codegenopt_mismatch) \
414 << #Name << CGOpts.Name << ExistingCGOpts.Name \
415 << ModuleFilename; \
416 else \
417 Diags->Report(diag::err_ast_file_codegenopt_value_mismatch) \
418 << #Name << ModuleFilename; \
419 } \
420 return true; \
421 } \
422 } \
423 }
424
425#define VALUE_CODEGENOPT(Name, Bits, Default, Compatibility) \
426 if constexpr (CK::Compatibility != CK::Benign) { \
427 if ((CK::Compatibility == CK::NotCompatible) || \
428 (CK::Compatibility == CK::Compatible && \
429 !AllowCompatibleDifferences)) { \
430 if (ExistingCGOpts.Name != CGOpts.Name) { \
431 if (Diags) \
432 Diags->Report(diag::err_ast_file_codegenopt_value_mismatch) \
433 << #Name << ModuleFilename; \
434 return true; \
435 } \
436 } \
437 }
438#define ENUM_CODEGENOPT(Name, Type, Bits, Default, Compatibility) \
439 if constexpr (CK::Compatibility != CK::Benign) { \
440 if ((CK::Compatibility == CK::NotCompatible) || \
441 (CK::Compatibility == CK::Compatible && \
442 !AllowCompatibleDifferences)) { \
443 if (ExistingCGOpts.get##Name() != CGOpts.get##Name()) { \
444 if (Diags) \
445 Diags->Report(diag::err_ast_file_codegenopt_value_mismatch) \
446 << #Name << ModuleFilename; \
447 return true; \
448 } \
449 } \
450 }
451#define DEBUGOPT(Name, Bits, Default, Compatibility)
452#define VALUE_DEBUGOPT(Name, Bits, Default, Compatibility)
453#define ENUM_DEBUGOPT(Name, Type, Bits, Default, Compatibility)
454#include "clang/Basic/CodeGenOptions.def"
455
456 return false;
457}
458
459static std::vector<std::string>
460accumulateFeaturesAsWritten(std::vector<std::string> FeaturesAsWritten) {
461 llvm::erase_if(FeaturesAsWritten, [](const std::string &S) {
462 return S.empty() || (S[0] != '+' && S[0] != '-');
463 });
464 llvm::stable_sort(FeaturesAsWritten,
465 [](const std::string &A, const std::string &B) {
466 return A.substr(1) < B.substr(1);
467 });
468 auto NewRend =
469 std::unique(FeaturesAsWritten.rbegin(), FeaturesAsWritten.rend(),
470 [](const std::string &A, const std::string &B) {
471 return A.substr(1) == B.substr(1);
472 });
473 // Because we are operating on reverse iterators, the duplicate elements
474 // are actually at the beginning.
475 FeaturesAsWritten.erase(FeaturesAsWritten.begin(), NewRend.base());
476 return FeaturesAsWritten;
477}
478
479/// Compare the given set of target options against an existing set of
480/// target options.
481///
482/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
483///
484/// \returns true if the target options mis-match, false otherwise.
485static bool checkTargetOptions(const TargetOptions &TargetOpts,
486 const TargetOptions &ExistingTargetOpts,
487 StringRef ModuleFilename,
488 DiagnosticsEngine *Diags,
489 bool AllowCompatibleDifferences = true) {
490#define CHECK_TARGET_OPT(Field, Name) \
491 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
492 if (Diags) \
493 Diags->Report(diag::err_ast_file_targetopt_mismatch) \
494 << ModuleFilename << Name << TargetOpts.Field \
495 << ExistingTargetOpts.Field; \
496 return true; \
497 }
498
499 // The triple and ABI must match exactly.
500 CHECK_TARGET_OPT(Triple, "target");
501 CHECK_TARGET_OPT(ABI, "target ABI");
502
503 // We can tolerate different CPUs in many cases, notably when one CPU
504 // supports a strict superset of another. When allowing compatible
505 // differences skip this check.
506 if (!AllowCompatibleDifferences) {
507 CHECK_TARGET_OPT(CPU, "target CPU");
508 CHECK_TARGET_OPT(TuneCPU, "tune CPU");
509 }
510
511#undef CHECK_TARGET_OPT
512
513 // Compare feature sets.
514 // Alternatively, we could be diffing TargetOpts.Features, but that would
515 // clutter the output with implied features.
516 std::vector<std::string> ExistingFeatures =
518 std::vector<std::string> ReadFeatures =
520
521 // We compute the set difference in both directions explicitly so that we can
522 // diagnose the differences differently.
523 SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
524 std::set_difference(
525 ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
526 ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
527 std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
528 ExistingFeatures.begin(), ExistingFeatures.end(),
529 std::back_inserter(UnmatchedReadFeatures));
530
531 // If we are allowing compatible differences and the read feature set is
532 // a strict subset of the existing feature set, there is nothing to diagnose.
533 if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
534 return false;
535
536 if (Diags) {
537 for (StringRef Feature : UnmatchedReadFeatures)
538 Diags->Report(diag::err_ast_file_targetopt_feature_mismatch)
539 << /* is-existing-feature */ false << ModuleFilename << Feature;
540 for (StringRef Feature : UnmatchedExistingFeatures)
541 Diags->Report(diag::err_ast_file_targetopt_feature_mismatch)
542 << /* is-existing-feature */ true << ModuleFilename << Feature;
543 }
544
545 return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
546}
547
549 StringRef ModuleFilename, bool Complain,
550 bool AllowCompatibleDifferences) {
551 const LangOptions &ExistingLangOpts = PP.getLangOpts();
552 return checkLanguageOptions(LangOpts, ExistingLangOpts, ModuleFilename,
553 Complain ? &Reader.Diags : nullptr,
554 AllowCompatibleDifferences);
555}
556
558 StringRef ModuleFilename, bool Complain,
559 bool AllowCompatibleDifferences) {
560 const CodeGenOptions &ExistingCGOpts = Reader.getCodeGenOpts();
561 return checkCodegenOptions(ExistingCGOpts, CGOpts, ModuleFilename,
562 Complain ? &Reader.Diags : nullptr,
563 AllowCompatibleDifferences);
564}
565
567 StringRef ModuleFilename, bool Complain,
568 bool AllowCompatibleDifferences) {
569 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
570 return checkTargetOptions(TargetOpts, ExistingTargetOpts, ModuleFilename,
571 Complain ? &Reader.Diags : nullptr,
572 AllowCompatibleDifferences);
573}
574
575namespace {
576
577using MacroDefinitionsMap =
578 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>;
579
580class DeclsSet {
583
584public:
585 operator ArrayRef<NamedDecl *>() const { return Decls; }
586
587 bool empty() const { return Decls.empty(); }
588
589 bool insert(NamedDecl *ND) {
590 auto [_, Inserted] = Found.insert(ND);
591 if (Inserted)
592 Decls.push_back(ND);
593 return Inserted;
594 }
595};
596
597using DeclsMap = llvm::DenseMap<DeclarationName, DeclsSet>;
598
599} // namespace
600
602 DiagnosticsEngine &Diags,
603 StringRef ModuleFilename,
604 bool Complain) {
605 using Level = DiagnosticsEngine::Level;
606
607 // Check current mappings for new -Werror mappings, and the stored mappings
608 // for cases that were explicitly mapped to *not* be errors that are now
609 // errors because of options like -Werror.
610 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
611
612 for (DiagnosticsEngine *MappingSource : MappingSources) {
613 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
614 diag::kind DiagID = DiagIDMappingPair.first;
615 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
616 if (CurLevel < DiagnosticsEngine::Error)
617 continue; // not significant
618 Level StoredLevel =
619 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
620 if (StoredLevel < DiagnosticsEngine::Error) {
621 if (Complain)
622 Diags.Report(diag::err_ast_file_diagopt_mismatch)
623 << "-Werror=" + Diags.getDiagnosticIDs()
624 ->getWarningOptionForDiag(DiagID)
625 .str()
626 << ModuleFilename;
627 return true;
628 }
629 }
630 }
631
632 return false;
633}
634
637 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
638 return true;
639 return Ext >= diag::Severity::Error;
640}
641
643 DiagnosticsEngine &Diags,
644 StringRef ModuleFilename, bool IsSystem,
645 bool SystemHeaderWarningsInModule,
646 bool Complain) {
647 // Top-level options
648 if (IsSystem) {
649 if (Diags.getSuppressSystemWarnings())
650 return false;
651 // If -Wsystem-headers was not enabled before, and it was not explicit,
652 // be conservative
653 if (StoredDiags.getSuppressSystemWarnings() &&
654 !SystemHeaderWarningsInModule) {
655 if (Complain)
656 Diags.Report(diag::err_ast_file_diagopt_mismatch)
657 << "-Wsystem-headers" << ModuleFilename;
658 return true;
659 }
660 }
661
662 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
663 if (Complain)
664 Diags.Report(diag::err_ast_file_diagopt_mismatch)
665 << "-Werror" << ModuleFilename;
666 return true;
667 }
668
669 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
670 !StoredDiags.getEnableAllWarnings()) {
671 if (Complain)
672 Diags.Report(diag::err_ast_file_diagopt_mismatch)
673 << "-Weverything -Werror" << ModuleFilename;
674 return true;
675 }
676
677 if (isExtHandlingFromDiagsError(Diags) &&
678 !isExtHandlingFromDiagsError(StoredDiags)) {
679 if (Complain)
680 Diags.Report(diag::err_ast_file_diagopt_mismatch)
681 << "-pedantic-errors" << ModuleFilename;
682 return true;
683 }
684
685 return checkDiagnosticGroupMappings(StoredDiags, Diags, ModuleFilename,
686 Complain);
687}
688
689/// Return the top import module if it is implicit, nullptr otherwise.
691 Preprocessor &PP) {
692 // If the original import came from a file explicitly generated by the user,
693 // don't check the diagnostic mappings.
694 // FIXME: currently this is approximated by checking whether this is not a
695 // module import of an implicitly-loaded module file.
696 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
697 // the transitive closure of its imports, since unrelated modules cannot be
698 // imported until after this module finishes validation.
699 ModuleFile *TopImport = &*ModuleMgr.rbegin();
700 while (!TopImport->ImportedBy.empty())
701 TopImport = TopImport->ImportedBy[0];
702 if (TopImport->Kind != MK_ImplicitModule)
703 return nullptr;
704
705 StringRef ModuleName = TopImport->ModuleName;
706 assert(!ModuleName.empty() && "diagnostic options read before module name");
707
708 Module *M =
709 PP.getHeaderSearchInfo().lookupModule(ModuleName, TopImport->ImportLoc);
710 assert(M && "missing module");
711 return M;
712}
713
715 StringRef ModuleFilename,
716 bool Complain) {
717 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
719 auto Diags = llvm::makeIntrusiveRefCnt<DiagnosticsEngine>(DiagIDs, DiagOpts);
720 // This should never fail, because we would have processed these options
721 // before writing them to an ASTFile.
722 ProcessWarningOptions(*Diags, DiagOpts,
723 PP.getFileManager().getVirtualFileSystem(),
724 /*Report*/ false);
725
726 ModuleManager &ModuleMgr = Reader.getModuleManager();
727 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
728
729 Module *TopM = getTopImportImplicitModule(ModuleMgr, PP);
730 if (!TopM)
731 return false;
732
733 Module *Importer = PP.getCurrentModule();
734
735 DiagnosticOptions &ExistingOpts = ExistingDiags.getDiagnosticOptions();
736 bool SystemHeaderWarningsInModule =
737 Importer && llvm::is_contained(ExistingOpts.SystemHeaderWarningsModules,
738 Importer->Name);
739
740 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
741 // contains the union of their flags.
742 return checkDiagnosticMappings(*Diags, ExistingDiags, ModuleFilename,
743 TopM->IsSystem, SystemHeaderWarningsInModule,
744 Complain);
745}
746
747/// Collect the macro definitions provided by the given preprocessor
748/// options.
749static void
751 MacroDefinitionsMap &Macros,
752 SmallVectorImpl<StringRef> *MacroNames = nullptr) {
753 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
754 StringRef Macro = PPOpts.Macros[I].first;
755 bool IsUndef = PPOpts.Macros[I].second;
756
757 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
758 StringRef MacroName = MacroPair.first;
759 StringRef MacroBody = MacroPair.second;
760
761 // For an #undef'd macro, we only care about the name.
762 if (IsUndef) {
763 auto [It, Inserted] = Macros.try_emplace(MacroName);
764 if (MacroNames && Inserted)
765 MacroNames->push_back(MacroName);
766
767 It->second = std::make_pair("", true);
768 continue;
769 }
770
771 // For a #define'd macro, figure out the actual definition.
772 if (MacroName.size() == Macro.size())
773 MacroBody = "1";
774 else {
775 // Note: GCC drops anything following an end-of-line character.
776 StringRef::size_type End = MacroBody.find_first_of("\n\r");
777 MacroBody = MacroBody.substr(0, End);
778 }
779
780 auto [It, Inserted] = Macros.try_emplace(MacroName);
781 if (MacroNames && Inserted)
782 MacroNames->push_back(MacroName);
783 It->second = std::make_pair(MacroBody, false);
784 }
785}
786
792
793/// Check the preprocessor options deserialized from the control block
794/// against the preprocessor options in an existing preprocessor.
795///
796/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
797/// \param Validation If set to OptionValidateNone, ignore differences in
798/// preprocessor options. If set to OptionValidateContradictions,
799/// require that options passed both in the AST file and on the command
800/// line (-D or -U) match, but tolerate options missing in one or the
801/// other. If set to OptionValidateContradictions, require that there
802/// are no differences in the options between the two.
804 const PreprocessorOptions &PPOpts,
805 const PreprocessorOptions &ExistingPPOpts, StringRef ModuleFilename,
806 bool ReadMacros, DiagnosticsEngine *Diags, FileManager &FileMgr,
807 std::string &SuggestedPredefines, const LangOptions &LangOpts,
809 if (ReadMacros) {
810 // Check macro definitions.
811 MacroDefinitionsMap ASTFileMacros;
812 collectMacroDefinitions(PPOpts, ASTFileMacros);
813 MacroDefinitionsMap ExistingMacros;
814 SmallVector<StringRef, 4> ExistingMacroNames;
815 collectMacroDefinitions(ExistingPPOpts, ExistingMacros,
816 &ExistingMacroNames);
817
818 // Use a line marker to enter the <command line> file, as the defines and
819 // undefines here will have come from the command line.
820 SuggestedPredefines += "# 1 \"<command line>\" 1\n";
821
822 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
823 // Dig out the macro definition in the existing preprocessor options.
824 StringRef MacroName = ExistingMacroNames[I];
825 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
826
827 // Check whether we know anything about this macro name or not.
828 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>::iterator Known =
829 ASTFileMacros.find(MacroName);
830 if (Validation == OptionValidateNone || Known == ASTFileMacros.end()) {
831 if (Validation == OptionValidateStrictMatches) {
832 // If strict matches are requested, don't tolerate any extra defines
833 // on the command line that are missing in the AST file.
834 if (Diags) {
835 Diags->Report(diag::err_ast_file_macro_def_undef)
836 << MacroName << true << ModuleFilename;
837 }
838 return true;
839 }
840 // FIXME: Check whether this identifier was referenced anywhere in the
841 // AST file. If so, we should reject the AST file. Unfortunately, this
842 // information isn't in the control block. What shall we do about it?
843
844 if (Existing.second) {
845 SuggestedPredefines += "#undef ";
846 SuggestedPredefines += MacroName.str();
847 SuggestedPredefines += '\n';
848 } else {
849 SuggestedPredefines += "#define ";
850 SuggestedPredefines += MacroName.str();
851 SuggestedPredefines += ' ';
852 SuggestedPredefines += Existing.first.str();
853 SuggestedPredefines += '\n';
854 }
855 continue;
856 }
857
858 // If the macro was defined in one but undef'd in the other, we have a
859 // conflict.
860 if (Existing.second != Known->second.second) {
861 if (Diags) {
862 Diags->Report(diag::err_ast_file_macro_def_undef)
863 << MacroName << Known->second.second << ModuleFilename;
864 }
865 return true;
866 }
867
868 // If the macro was #undef'd in both, or if the macro bodies are
869 // identical, it's fine.
870 if (Existing.second || Existing.first == Known->second.first) {
871 ASTFileMacros.erase(Known);
872 continue;
873 }
874
875 // The macro bodies differ; complain.
876 if (Diags) {
877 Diags->Report(diag::err_ast_file_macro_def_conflict)
878 << MacroName << Known->second.first << Existing.first
879 << ModuleFilename;
880 }
881 return true;
882 }
883
884 // Leave the <command line> file and return to <built-in>.
885 SuggestedPredefines += "# 1 \"<built-in>\" 2\n";
886
887 if (Validation == OptionValidateStrictMatches) {
888 // If strict matches are requested, don't tolerate any extra defines in
889 // the AST file that are missing on the command line.
890 for (const auto &MacroName : ASTFileMacros.keys()) {
891 if (Diags) {
892 Diags->Report(diag::err_ast_file_macro_def_undef)
893 << MacroName << false << ModuleFilename;
894 }
895 return true;
896 }
897 }
898 }
899
900 // Check whether we're using predefines.
901 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines &&
902 Validation != OptionValidateNone) {
903 if (Diags) {
904 Diags->Report(diag::err_ast_file_undef)
905 << ExistingPPOpts.UsePredefines << ModuleFilename;
906 }
907 return true;
908 }
909
910 // Detailed record is important since it is used for the module cache hash.
911 if (LangOpts.Modules &&
912 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord &&
913 Validation != OptionValidateNone) {
914 if (Diags) {
915 Diags->Report(diag::err_ast_file_pp_detailed_record)
916 << PPOpts.DetailedRecord << ModuleFilename;
917 }
918 return true;
919 }
920
921 // Compute the #include and #include_macros lines we need.
922 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
923 StringRef File = ExistingPPOpts.Includes[I];
924
925 if (!ExistingPPOpts.ImplicitPCHInclude.empty() &&
926 !ExistingPPOpts.PCHThroughHeader.empty()) {
927 // In case the through header is an include, we must add all the includes
928 // to the predefines so the start point can be determined.
929 SuggestedPredefines += "#include \"";
930 SuggestedPredefines += File;
931 SuggestedPredefines += "\"\n";
932 continue;
933 }
934
935 if (File == ExistingPPOpts.ImplicitPCHInclude)
936 continue;
937
938 if (llvm::is_contained(PPOpts.Includes, File))
939 continue;
940
941 SuggestedPredefines += "#include \"";
942 SuggestedPredefines += File;
943 SuggestedPredefines += "\"\n";
944 }
945
946 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
947 StringRef File = ExistingPPOpts.MacroIncludes[I];
948 if (llvm::is_contained(PPOpts.MacroIncludes, File))
949 continue;
950
951 SuggestedPredefines += "#__include_macros \"";
952 SuggestedPredefines += File;
953 SuggestedPredefines += "\"\n##\n";
954 }
955
956 return false;
957}
958
960 StringRef ModuleFilename,
961 bool ReadMacros, bool Complain,
962 std::string &SuggestedPredefines) {
963 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
964
966 PPOpts, ExistingPPOpts, ModuleFilename, ReadMacros,
967 Complain ? &Reader.Diags : nullptr, PP.getFileManager(),
968 SuggestedPredefines, PP.getLangOpts());
969}
970
972 const PreprocessorOptions &PPOpts, StringRef ModuleFilename,
973 bool ReadMacros, bool Complain, std::string &SuggestedPredefines) {
974 return checkPreprocessorOptions(PPOpts, PP.getPreprocessorOpts(),
975 ModuleFilename, ReadMacros, nullptr,
976 PP.getFileManager(), SuggestedPredefines,
977 PP.getLangOpts(), OptionValidateNone);
978}
979
980/// Check that the specified and the existing module cache paths are equivalent.
981///
982/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
983/// \returns true when the module cache paths differ.
984static bool checkModuleCachePath(FileManager &FileMgr, StringRef ContextHash,
985 StringRef ExistingSpecificModuleCachePath,
986 StringRef ASTFilename,
987 DiagnosticsEngine *Diags,
988 const LangOptions &LangOpts,
989 const PreprocessorOptions &PPOpts,
990 const HeaderSearchOptions &HSOpts,
991 const HeaderSearchOptions &ASTFileHSOpts) {
992 std::string SpecificModuleCachePath = createSpecificModuleCachePath(
993 FileMgr, ASTFileHSOpts.ModuleCachePath, ASTFileHSOpts.DisableModuleHash,
994 std::string(ContextHash));
995
996 if (!LangOpts.Modules || PPOpts.AllowPCHWithDifferentModulesCachePath ||
997 SpecificModuleCachePath == ExistingSpecificModuleCachePath)
998 return false;
999 auto EqualOrErr = FileMgr.getVirtualFileSystem().equivalent(
1000 SpecificModuleCachePath, ExistingSpecificModuleCachePath);
1001 if (EqualOrErr && *EqualOrErr)
1002 return false;
1003 if (Diags) {
1004 // If the module cache arguments provided from the command line are the
1005 // same, the mismatch must come from other arguments of the configuration
1006 // and not directly the cache path.
1007 EqualOrErr = FileMgr.getVirtualFileSystem().equivalent(
1008 ASTFileHSOpts.ModuleCachePath, HSOpts.ModuleCachePath);
1009 if (EqualOrErr && *EqualOrErr)
1010 Diags->Report(clang::diag::warn_ast_file_config_mismatch) << ASTFilename;
1011 else
1012 Diags->Report(diag::err_ast_file_modulecache_mismatch)
1013 << SpecificModuleCachePath << ExistingSpecificModuleCachePath
1014 << ASTFilename;
1015 }
1016 return true;
1017}
1018
1020 StringRef ASTFilename,
1021 StringRef ContextHash,
1022 bool Complain) {
1023 const HeaderSearch &HeaderSearchInfo = PP.getHeaderSearchInfo();
1024 return checkModuleCachePath(Reader.getFileManager(), ContextHash,
1025 HeaderSearchInfo.getSpecificModuleCachePath(),
1026 ASTFilename, Complain ? &Reader.Diags : nullptr,
1027 PP.getLangOpts(), PP.getPreprocessorOpts(),
1028 HeaderSearchInfo.getHeaderSearchOpts(), HSOpts);
1029}
1030
1032 PP.setCounterValue(Value);
1033}
1034
1035//===----------------------------------------------------------------------===//
1036// AST reader implementation
1037//===----------------------------------------------------------------------===//
1038
1039static uint64_t readULEB(const unsigned char *&P) {
1040 unsigned Length = 0;
1041 const char *Error = nullptr;
1042
1043 uint64_t Val = llvm::decodeULEB128(P, &Length, nullptr, &Error);
1044 if (Error)
1045 llvm::report_fatal_error(Error);
1046 P += Length;
1047 return Val;
1048}
1049
1050/// Read ULEB-encoded key length and data length.
1051static std::pair<unsigned, unsigned>
1052readULEBKeyDataLength(const unsigned char *&P) {
1053 unsigned KeyLen = readULEB(P);
1054 if ((unsigned)KeyLen != KeyLen)
1055 llvm::report_fatal_error("key too large");
1056
1057 unsigned DataLen = readULEB(P);
1058 if ((unsigned)DataLen != DataLen)
1059 llvm::report_fatal_error("data too large");
1060
1061 return std::make_pair(KeyLen, DataLen);
1062}
1063
1065 bool TakeOwnership) {
1066 DeserializationListener = Listener;
1067 OwnsDeserializationListener = TakeOwnership;
1068}
1069
1073
1075 LocalDeclID ID(Value);
1076#ifndef NDEBUG
1077 if (!MF.ModuleOffsetMap.empty())
1078 Reader.ReadModuleOffsetMap(MF);
1079
1080 unsigned ModuleFileIndex = ID.getModuleFileIndex();
1081 unsigned LocalDeclID = ID.getLocalDeclIndex();
1082
1083 assert(ModuleFileIndex <= MF.TransitiveImports.size());
1084
1085 ModuleFile *OwningModuleFile =
1086 ModuleFileIndex == 0 ? &MF : MF.TransitiveImports[ModuleFileIndex - 1];
1087 assert(OwningModuleFile);
1088
1089 unsigned LocalNumDecls = OwningModuleFile->LocalNumDecls;
1090
1091 if (!ModuleFileIndex)
1092 LocalNumDecls += NUM_PREDEF_DECL_IDS;
1093
1094 assert(LocalDeclID < LocalNumDecls);
1095#endif
1096 (void)Reader;
1097 (void)MF;
1098 return ID;
1099}
1100
1101LocalDeclID LocalDeclID::get(ASTReader &Reader, ModuleFile &MF,
1102 unsigned ModuleFileIndex, unsigned LocalDeclID) {
1103 DeclID Value = (DeclID)ModuleFileIndex << 32 | (DeclID)LocalDeclID;
1104 return LocalDeclID::get(Reader, MF, Value);
1105}
1106
1107std::pair<unsigned, unsigned>
1109 return readULEBKeyDataLength(d);
1110}
1111
1113ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
1114 using namespace llvm::support;
1115
1116 SelectorTable &SelTable = Reader.getContext().Selectors;
1117 unsigned N = endian::readNext<uint16_t, llvm::endianness::little>(d);
1118 const IdentifierInfo *FirstII = Reader.getLocalIdentifier(
1119 F, endian::readNext<IdentifierID, llvm::endianness::little>(d));
1120 if (N == 0)
1121 return SelTable.getNullarySelector(FirstII);
1122 else if (N == 1)
1123 return SelTable.getUnarySelector(FirstII);
1124
1126 Args.push_back(FirstII);
1127 for (unsigned I = 1; I != N; ++I)
1128 Args.push_back(Reader.getLocalIdentifier(
1129 F, endian::readNext<IdentifierID, llvm::endianness::little>(d)));
1130
1131 return SelTable.getSelector(N, Args.data());
1132}
1133
1136 unsigned DataLen) {
1137 using namespace llvm::support;
1138
1140
1141 Result.ID = Reader.getGlobalSelectorID(
1142 F, endian::readNext<uint32_t, llvm::endianness::little>(d));
1143 unsigned FullInstanceBits =
1144 endian::readNext<uint16_t, llvm::endianness::little>(d);
1145 unsigned FullFactoryBits =
1146 endian::readNext<uint16_t, llvm::endianness::little>(d);
1147 Result.InstanceBits = FullInstanceBits & 0x3;
1148 Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
1149 Result.FactoryBits = FullFactoryBits & 0x3;
1150 Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
1151 unsigned NumInstanceMethods = FullInstanceBits >> 3;
1152 unsigned NumFactoryMethods = FullFactoryBits >> 3;
1153
1154 // Load instance methods
1155 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
1156 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
1158 Reader, F,
1159 endian::readNext<DeclID, llvm::endianness::little>(d))))
1160 Result.Instance.push_back(Method);
1161 }
1162
1163 // Load factory methods
1164 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
1165 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
1167 Reader, F,
1168 endian::readNext<DeclID, llvm::endianness::little>(d))))
1169 Result.Factory.push_back(Method);
1170 }
1171
1172 return Result;
1173}
1174
1176 return llvm::djbHash(a);
1177}
1178
1179std::pair<unsigned, unsigned>
1181 return readULEBKeyDataLength(d);
1182}
1183
1185ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
1186 assert(n >= 2 && d[n-1] == '\0');
1187 return StringRef((const char*) d, n-1);
1188}
1189
1190/// Whether the given identifier is "interesting".
1191static bool isInterestingIdentifier(ASTReader &Reader, const IdentifierInfo &II,
1192 bool IsModule) {
1193 bool IsInteresting =
1194 II.getNotableIdentifierID() != tok::NotableIdentifierKind::not_notable ||
1196 II.getObjCKeywordID() != tok::ObjCKeywordKind::objc_not_keyword;
1197 return II.hadMacroDefinition() || II.isPoisoned() ||
1198 (!IsModule && IsInteresting) || II.hasRevertedTokenIDToIdentifier() ||
1199 (!(IsModule && Reader.getPreprocessor().getLangOpts().CPlusPlus) &&
1200 II.getFETokenInfo());
1201}
1202
1203static bool readBit(unsigned &Bits) {
1204 bool Value = Bits & 0x1;
1205 Bits >>= 1;
1206 return Value;
1207}
1208
1210 using namespace llvm::support;
1211
1212 IdentifierID RawID =
1213 endian::readNext<IdentifierID, llvm::endianness::little>(d);
1214 return Reader.getGlobalIdentifierID(F, RawID >> 1);
1215}
1216
1218 bool IsModule) {
1219 if (!II.isFromAST()) {
1220 II.setIsFromAST();
1221 if (isInterestingIdentifier(Reader, II, IsModule))
1223 }
1224}
1225
1227 const unsigned char* d,
1228 unsigned DataLen) {
1229 using namespace llvm::support;
1230
1231 IdentifierID RawID =
1232 endian::readNext<IdentifierID, llvm::endianness::little>(d);
1233 bool IsInteresting = RawID & 0x01;
1234
1235 DataLen -= sizeof(IdentifierID);
1236
1237 // Wipe out the "is interesting" bit.
1238 RawID = RawID >> 1;
1239
1240 // Build the IdentifierInfo and link the identifier ID with it.
1241 IdentifierInfo *II = KnownII;
1242 if (!II) {
1243 II = &Reader.getIdentifierTable().getOwn(k);
1244 KnownII = II;
1245 }
1246 bool IsModule = Reader.getPreprocessor().getCurrentModule() != nullptr;
1247 markIdentifierFromAST(Reader, *II, IsModule);
1248 Reader.markIdentifierUpToDate(II);
1249
1250 IdentifierID ID = Reader.getGlobalIdentifierID(F, RawID);
1251 if (!IsInteresting) {
1252 // For uninteresting identifiers, there's nothing else to do. Just notify
1253 // the reader that we've finished loading this identifier.
1254 Reader.SetIdentifierInfo(ID, II);
1255 return II;
1256 }
1257
1258 unsigned ObjCOrBuiltinID =
1259 endian::readNext<uint16_t, llvm::endianness::little>(d);
1260 unsigned Bits = endian::readNext<uint16_t, llvm::endianness::little>(d);
1261 bool CPlusPlusOperatorKeyword = readBit(Bits);
1262 bool HasRevertedTokenIDToIdentifier = readBit(Bits);
1263 bool Poisoned = readBit(Bits);
1264 bool ExtensionToken = readBit(Bits);
1265 bool HasMacroDefinition = readBit(Bits);
1266
1267 assert(Bits == 0 && "Extra bits in the identifier?");
1268 DataLen -= sizeof(uint16_t) * 2;
1269
1270 // Set or check the various bits in the IdentifierInfo structure.
1271 // Token IDs are read-only.
1272 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
1274 if (!F.isModule())
1275 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
1276 assert(II->isExtensionToken() == ExtensionToken &&
1277 "Incorrect extension token flag");
1278 (void)ExtensionToken;
1279 if (Poisoned)
1280 II->setIsPoisoned(true);
1281 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
1282 "Incorrect C++ operator keyword flag");
1283 (void)CPlusPlusOperatorKeyword;
1284
1285 // If this identifier has a macro definition, deserialize it or notify the
1286 // visitor the actual definition is in a different module.
1287 if (HasMacroDefinition) {
1288 uint32_t MacroDirectivesOffset =
1289 endian::readNext<uint32_t, llvm::endianness::little>(d);
1290 DataLen -= 4;
1291
1292 if (MacroDirectivesOffset)
1293 Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
1294 else
1295 hasMacroDefinitionInDependencies = true;
1296 }
1297
1298 Reader.SetIdentifierInfo(ID, II);
1299
1300 // Read all of the declarations visible at global scope with this
1301 // name.
1302 if (DataLen > 0) {
1304 for (; DataLen > 0; DataLen -= sizeof(DeclID))
1305 DeclIDs.push_back(Reader.getGlobalDeclID(
1307 Reader, F,
1308 endian::readNext<DeclID, llvm::endianness::little>(d))));
1309 Reader.SetGloballyVisibleDecls(II, DeclIDs);
1310 }
1311
1312 return II;
1313}
1314
1316 : Kind(Name.getNameKind()) {
1317 switch (Kind) {
1319 Data = (uint64_t)Name.getAsIdentifierInfo();
1320 break;
1324 Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
1325 break;
1327 Data = Name.getCXXOverloadedOperator();
1328 break;
1330 Data = (uint64_t)Name.getCXXLiteralIdentifier();
1331 break;
1333 Data = (uint64_t)Name.getCXXDeductionGuideTemplate()
1335 break;
1340 Data = 0;
1341 break;
1342 }
1343}
1344
1346 llvm::FoldingSetNodeID ID;
1347 ID.AddInteger(Kind);
1348
1349 switch (Kind) {
1353 ID.AddString(((IdentifierInfo*)Data)->getName());
1354 break;
1358 ID.AddInteger(serialization::ComputeHash(Selector(Data)));
1359 break;
1361 ID.AddInteger((OverloadedOperatorKind)Data);
1362 break;
1367 break;
1368 }
1369
1370 return ID.computeStableHash();
1371}
1372
1373ModuleFile *
1375 using namespace llvm::support;
1376
1377 uint32_t ModuleFileID =
1378 endian::readNext<uint32_t, llvm::endianness::little>(d);
1379 return Reader.getLocalModuleFile(F, ModuleFileID);
1380}
1381
1382std::pair<unsigned, unsigned>
1386
1389 using namespace llvm::support;
1390
1391 auto Kind = (DeclarationName::NameKind)*d++;
1392 uint64_t Data;
1393 switch (Kind) {
1397 Data = (uint64_t)Reader.getLocalIdentifier(
1398 F, endian::readNext<IdentifierID, llvm::endianness::little>(d));
1399 break;
1403 Data = (uint64_t)Reader
1404 .getLocalSelector(
1405 F, endian::readNext<uint32_t, llvm::endianness::little>(d))
1406 .getAsOpaquePtr();
1407 break;
1409 Data = *d++; // OverloadedOperatorKind
1410 break;
1415 Data = 0;
1416 break;
1417 }
1418
1419 return DeclarationNameKey(Kind, Data);
1420}
1421
1423ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
1424 return ReadKeyBase(d);
1425}
1426
1428 const unsigned char *d, unsigned DataLen, data_type_builder &Val) {
1429 using namespace llvm::support;
1430
1431 for (unsigned NumDecls = DataLen / sizeof(DeclID); NumDecls; --NumDecls) {
1433 Reader, F, endian::readNext<DeclID, llvm::endianness::little>(d));
1434 Val.insert(Reader.getGlobalDeclID(F, ID));
1435 }
1436}
1437
1439 const unsigned char *d,
1440 unsigned DataLen,
1441 data_type_builder &Val) {
1442 ReadDataIntoImpl(d, DataLen, Val);
1443}
1444
1447 llvm::FoldingSetNodeID ID;
1448 ID.AddInteger(Key.first.getHash());
1449 ID.AddInteger(Key.second);
1450 return ID.computeStableHash();
1451}
1452
1455 DeclarationNameKey Name(Key.first);
1456
1457 UnsignedOrNone ModuleHash = getPrimaryModuleHash(Key.second);
1458 if (!ModuleHash)
1459 return {Name, 0};
1460
1461 return {Name, *ModuleHash};
1462}
1463
1465ModuleLocalNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
1467 unsigned PrimaryModuleHash =
1468 llvm::support::endian::readNext<uint32_t, llvm::endianness::little>(d);
1469 return {Name, PrimaryModuleHash};
1470}
1471
1473 const unsigned char *d,
1474 unsigned DataLen,
1475 data_type_builder &Val) {
1476 ReadDataIntoImpl(d, DataLen, Val);
1477}
1478
1479ModuleFile *
1481 using namespace llvm::support;
1482
1483 uint32_t ModuleFileID =
1484 endian::readNext<uint32_t, llvm::endianness::little, unaligned>(d);
1485 return Reader.getLocalModuleFile(F, ModuleFileID);
1486}
1487
1489LazySpecializationInfoLookupTrait::ReadKey(const unsigned char *d, unsigned) {
1490 using namespace llvm::support;
1491 return endian::readNext<uint32_t, llvm::endianness::little, unaligned>(d);
1492}
1493
1494std::pair<unsigned, unsigned>
1498
1500 const unsigned char *d,
1501 unsigned DataLen,
1502 data_type_builder &Val) {
1503 using namespace llvm::support;
1504
1505 for (unsigned NumDecls =
1507 NumDecls; --NumDecls) {
1508 LocalDeclID LocalID = LocalDeclID::get(
1509 Reader, F,
1510 endian::readNext<DeclID, llvm::endianness::little, unaligned>(d));
1511 Val.insert(Reader.getGlobalDeclID(F, LocalID));
1512 }
1513}
1514
1515bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
1516 BitstreamCursor &Cursor,
1517 uint64_t Offset,
1518 DeclContext *DC) {
1519 assert(Offset != 0);
1520
1521 SavedStreamPosition SavedPosition(Cursor);
1522 if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1523 Error(std::move(Err));
1524 return true;
1525 }
1526
1527 RecordData Record;
1528 StringRef Blob;
1529 Expected<unsigned> MaybeCode = Cursor.ReadCode();
1530 if (!MaybeCode) {
1531 Error(MaybeCode.takeError());
1532 return true;
1533 }
1534 unsigned Code = MaybeCode.get();
1535
1536 Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
1537 if (!MaybeRecCode) {
1538 Error(MaybeRecCode.takeError());
1539 return true;
1540 }
1541 unsigned RecCode = MaybeRecCode.get();
1542 if (RecCode != DECL_CONTEXT_LEXICAL) {
1543 Error("Expected lexical block");
1544 return true;
1545 }
1546
1547 assert(!isa<TranslationUnitDecl>(DC) &&
1548 "expected a TU_UPDATE_LEXICAL record for TU");
1549 // If we are handling a C++ class template instantiation, we can see multiple
1550 // lexical updates for the same record. It's important that we select only one
1551 // of them, so that field numbering works properly. Just pick the first one we
1552 // see.
1553 auto &Lex = LexicalDecls[DC];
1554 if (!Lex.first) {
1555 Lex = std::make_pair(
1556 &M, llvm::ArrayRef(
1557 reinterpret_cast<const unaligned_decl_id_t *>(Blob.data()),
1558 Blob.size() / sizeof(DeclID)));
1559 }
1561 return false;
1562}
1563
1564bool ASTReader::ReadVisibleDeclContextStorage(
1565 ModuleFile &M, BitstreamCursor &Cursor, uint64_t Offset, GlobalDeclID ID,
1566 ASTReader::VisibleDeclContextStorageKind VisibleKind) {
1567 assert(Offset != 0);
1568
1569 SavedStreamPosition SavedPosition(Cursor);
1570 if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1571 Error(std::move(Err));
1572 return true;
1573 }
1574
1575 RecordData Record;
1576 StringRef Blob;
1577 Expected<unsigned> MaybeCode = Cursor.ReadCode();
1578 if (!MaybeCode) {
1579 Error(MaybeCode.takeError());
1580 return true;
1581 }
1582 unsigned Code = MaybeCode.get();
1583
1584 Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
1585 if (!MaybeRecCode) {
1586 Error(MaybeRecCode.takeError());
1587 return true;
1588 }
1589 unsigned RecCode = MaybeRecCode.get();
1590 switch (VisibleKind) {
1591 case VisibleDeclContextStorageKind::GenerallyVisible:
1592 if (RecCode != DECL_CONTEXT_VISIBLE) {
1593 Error("Expected visible lookup table block");
1594 return true;
1595 }
1596 break;
1597 case VisibleDeclContextStorageKind::ModuleLocalVisible:
1598 if (RecCode != DECL_CONTEXT_MODULE_LOCAL_VISIBLE) {
1599 Error("Expected module local visible lookup table block");
1600 return true;
1601 }
1602 break;
1603 case VisibleDeclContextStorageKind::TULocalVisible:
1604 if (RecCode != DECL_CONTEXT_TU_LOCAL_VISIBLE) {
1605 Error("Expected TU local lookup table block");
1606 return true;
1607 }
1608 break;
1609 }
1610
1611 // We can't safely determine the primary context yet, so delay attaching the
1612 // lookup table until we're done with recursive deserialization.
1613 auto *Data = (const unsigned char*)Blob.data();
1614 switch (VisibleKind) {
1615 case VisibleDeclContextStorageKind::GenerallyVisible:
1616 PendingVisibleUpdates[ID].push_back(UpdateData{&M, Data});
1617 break;
1618 case VisibleDeclContextStorageKind::ModuleLocalVisible:
1619 PendingModuleLocalVisibleUpdates[ID].push_back(UpdateData{&M, Data});
1620 break;
1621 case VisibleDeclContextStorageKind::TULocalVisible:
1622 if (M.Kind == MK_MainFile)
1623 TULocalUpdates[ID].push_back(UpdateData{&M, Data});
1624 break;
1625 }
1626 return false;
1627}
1628
1629void ASTReader::AddSpecializations(const Decl *D, const unsigned char *Data,
1630 ModuleFile &M, bool IsPartial) {
1631 D = D->getCanonicalDecl();
1632 auto &SpecLookups =
1633 IsPartial ? PartialSpecializationsLookups : SpecializationsLookups;
1634 SpecLookups[D].Table.add(&M, Data,
1636}
1637
1638bool ASTReader::ReadSpecializations(ModuleFile &M, BitstreamCursor &Cursor,
1639 uint64_t Offset, Decl *D, bool IsPartial) {
1640 assert(Offset != 0);
1641
1642 SavedStreamPosition SavedPosition(Cursor);
1643 if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1644 Error(std::move(Err));
1645 return true;
1646 }
1647
1648 RecordData Record;
1649 StringRef Blob;
1650 Expected<unsigned> MaybeCode = Cursor.ReadCode();
1651 if (!MaybeCode) {
1652 Error(MaybeCode.takeError());
1653 return true;
1654 }
1655 unsigned Code = MaybeCode.get();
1656
1657 Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
1658 if (!MaybeRecCode) {
1659 Error(MaybeRecCode.takeError());
1660 return true;
1661 }
1662 unsigned RecCode = MaybeRecCode.get();
1663 if (RecCode != DECL_SPECIALIZATIONS &&
1664 RecCode != DECL_PARTIAL_SPECIALIZATIONS) {
1665 Error("Expected decl specs block");
1666 return true;
1667 }
1668
1669 auto *Data = (const unsigned char *)Blob.data();
1670 AddSpecializations(D, Data, M, IsPartial);
1671 return false;
1672}
1673
1674void ASTReader::Error(StringRef Msg) const {
1675 Error(diag::err_fe_ast_file_malformed, Msg);
1676 if (PP.getLangOpts().Modules &&
1677 !PP.getHeaderSearchInfo().getSpecificModuleCachePath().empty()) {
1678 Diag(diag::note_module_cache_path)
1679 << PP.getHeaderSearchInfo().getSpecificModuleCachePath();
1680 }
1681}
1682
1683void ASTReader::Error(unsigned DiagID, StringRef Arg1, StringRef Arg2,
1684 StringRef Arg3) const {
1685 Diag(DiagID) << Arg1 << Arg2 << Arg3;
1686}
1687
1688namespace {
1689struct AlreadyReportedDiagnosticError
1690 : llvm::ErrorInfo<AlreadyReportedDiagnosticError> {
1691 static char ID;
1692
1693 void log(raw_ostream &OS) const override {
1694 llvm_unreachable("reporting an already-reported diagnostic error");
1695 }
1696
1697 std::error_code convertToErrorCode() const override {
1698 return llvm::inconvertibleErrorCode();
1699 }
1700};
1701
1702char AlreadyReportedDiagnosticError::ID = 0;
1703} // namespace
1704
1705void ASTReader::Error(llvm::Error &&Err) const {
1706 handleAllErrors(
1707 std::move(Err), [](AlreadyReportedDiagnosticError &) {},
1708 [&](llvm::ErrorInfoBase &E) { return Error(E.message()); });
1709}
1710
1711//===----------------------------------------------------------------------===//
1712// Source Manager Deserialization
1713//===----------------------------------------------------------------------===//
1714
1715/// Read the line table in the source manager block.
1716void ASTReader::ParseLineTable(ModuleFile &F, const RecordData &Record) {
1717 unsigned Idx = 0;
1718 LineTableInfo &LineTable = SourceMgr.getLineTable();
1719
1720 // Parse the file names
1721 std::map<int, int> FileIDs;
1722 FileIDs[-1] = -1; // For unspecified filenames.
1723 for (unsigned I = 0; Record[Idx]; ++I) {
1724 // Extract the file name
1725 auto Filename = ReadPath(F, Record, Idx);
1726 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1727 }
1728 ++Idx;
1729
1730 // Parse the line entries
1731 std::vector<LineEntry> Entries;
1732 while (Idx < Record.size()) {
1733 FileID FID = ReadFileID(F, Record, Idx);
1734
1735 // Extract the line entries
1736 unsigned NumEntries = Record[Idx++];
1737 assert(NumEntries && "no line entries for file ID");
1738 Entries.clear();
1739 Entries.reserve(NumEntries);
1740 for (unsigned I = 0; I != NumEntries; ++I) {
1741 unsigned FileOffset = Record[Idx++];
1742 unsigned LineNo = Record[Idx++];
1743 int FilenameID = FileIDs[Record[Idx++]];
1746 unsigned IncludeOffset = Record[Idx++];
1747 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1748 FileKind, IncludeOffset));
1749 }
1750 LineTable.AddEntry(FID, Entries);
1751 }
1752}
1753
1754/// Read a source manager block
1755llvm::Error ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1756 using namespace SrcMgr;
1757
1758 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
1759
1760 // Set the source-location entry cursor to the current position in
1761 // the stream. This cursor will be used to read the contents of the
1762 // source manager block initially, and then lazily read
1763 // source-location entries as needed.
1764 SLocEntryCursor = F.Stream;
1765
1766 // The stream itself is going to skip over the source manager block.
1767 if (llvm::Error Err = F.Stream.SkipBlock())
1768 return Err;
1769
1770 // Enter the source manager block.
1771 if (llvm::Error Err = SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID))
1772 return Err;
1773 F.SourceManagerBlockStartOffset = SLocEntryCursor.GetCurrentBitNo();
1774
1775 RecordData Record;
1776 while (true) {
1777 Expected<llvm::BitstreamEntry> MaybeE =
1778 SLocEntryCursor.advanceSkippingSubblocks();
1779 if (!MaybeE)
1780 return MaybeE.takeError();
1781 llvm::BitstreamEntry E = MaybeE.get();
1782
1783 switch (E.Kind) {
1784 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1785 case llvm::BitstreamEntry::Error:
1786 return llvm::createStringError(std::errc::illegal_byte_sequence,
1787 "malformed block record in AST file");
1788 case llvm::BitstreamEntry::EndBlock:
1789 return llvm::Error::success();
1790 case llvm::BitstreamEntry::Record:
1791 // The interesting case.
1792 break;
1793 }
1794
1795 // Read a record.
1796 Record.clear();
1797 StringRef Blob;
1798 Expected<unsigned> MaybeRecord =
1799 SLocEntryCursor.readRecord(E.ID, Record, &Blob);
1800 if (!MaybeRecord)
1801 return MaybeRecord.takeError();
1802 switch (MaybeRecord.get()) {
1803 default: // Default behavior: ignore.
1804 break;
1805
1806 case SM_SLOC_FILE_ENTRY:
1809 // Once we hit one of the source location entries, we're done.
1810 return llvm::Error::success();
1811 }
1812 }
1813}
1814
1815llvm::Expected<SourceLocation::UIntTy>
1817 BitstreamCursor &Cursor = F->SLocEntryCursor;
1818 SavedStreamPosition SavedPosition(Cursor);
1819 if (llvm::Error Err = Cursor.JumpToBit(F->SLocEntryOffsetsBase +
1820 F->SLocEntryOffsets[Index]))
1821 return std::move(Err);
1822
1823 Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
1824 if (!MaybeEntry)
1825 return MaybeEntry.takeError();
1826
1827 llvm::BitstreamEntry Entry = MaybeEntry.get();
1828 if (Entry.Kind != llvm::BitstreamEntry::Record)
1829 return llvm::createStringError(
1830 std::errc::illegal_byte_sequence,
1831 "incorrectly-formatted source location entry in AST file");
1832
1834 StringRef Blob;
1835 Expected<unsigned> MaybeSLOC = Cursor.readRecord(Entry.ID, Record, &Blob);
1836 if (!MaybeSLOC)
1837 return MaybeSLOC.takeError();
1838
1839 switch (MaybeSLOC.get()) {
1840 default:
1841 return llvm::createStringError(
1842 std::errc::illegal_byte_sequence,
1843 "incorrectly-formatted source location entry in AST file");
1844 case SM_SLOC_FILE_ENTRY:
1847 return F->SLocEntryBaseOffset + Record[0];
1848 }
1849}
1850
1852 auto SLocMapI =
1853 GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset - SLocOffset - 1);
1854 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
1855 "Corrupted global sloc offset map");
1856 ModuleFile *F = SLocMapI->second;
1857
1858 bool Invalid = false;
1859
1860 auto It = llvm::upper_bound(
1861 llvm::index_range(0, F->LocalNumSLocEntries), SLocOffset,
1862 [&](SourceLocation::UIntTy Offset, std::size_t LocalIndex) {
1863 int ID = F->SLocEntryBaseID + LocalIndex;
1864 std::size_t Index = -ID - 2;
1865 if (!SourceMgr.SLocEntryOffsetLoaded[Index]) {
1866 assert(!SourceMgr.SLocEntryLoaded[Index]);
1867 auto MaybeEntryOffset = readSLocOffset(F, LocalIndex);
1868 if (!MaybeEntryOffset) {
1869 Error(MaybeEntryOffset.takeError());
1870 Invalid = true;
1871 return true;
1872 }
1873 SourceMgr.LoadedSLocEntryTable[Index] =
1874 SrcMgr::SLocEntry::getOffsetOnly(*MaybeEntryOffset);
1875 SourceMgr.SLocEntryOffsetLoaded[Index] = true;
1876 }
1877 return Offset < SourceMgr.LoadedSLocEntryTable[Index].getOffset();
1878 });
1879
1880 if (Invalid)
1881 return 0;
1882
1883 // The iterator points to the first entry with start offset greater than the
1884 // offset of interest. The previous entry must contain the offset of interest.
1885 return F->SLocEntryBaseID + *std::prev(It);
1886}
1887
1889 if (ID == 0)
1890 return false;
1891
1892 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1893 Error("source location entry ID out-of-range for AST file");
1894 return true;
1895 }
1896
1897 // Local helper to read the (possibly-compressed) buffer data following the
1898 // entry record.
1899 auto ReadBuffer = [this](
1900 BitstreamCursor &SLocEntryCursor,
1901 StringRef Name) -> std::unique_ptr<llvm::MemoryBuffer> {
1903 StringRef Blob;
1904 Expected<unsigned> MaybeCode = SLocEntryCursor.ReadCode();
1905 if (!MaybeCode) {
1906 Error(MaybeCode.takeError());
1907 return nullptr;
1908 }
1909 unsigned Code = MaybeCode.get();
1910
1911 Expected<unsigned> MaybeRecCode =
1912 SLocEntryCursor.readRecord(Code, Record, &Blob);
1913 if (!MaybeRecCode) {
1914 Error(MaybeRecCode.takeError());
1915 return nullptr;
1916 }
1917 unsigned RecCode = MaybeRecCode.get();
1918
1919 if (RecCode == SM_SLOC_BUFFER_BLOB_COMPRESSED) {
1920 // Inspect the first byte to differentiate zlib (\x78) and zstd
1921 // (little-endian 0xFD2FB528).
1922 const llvm::compression::Format F =
1923 Blob.size() > 0 && Blob.data()[0] == 0x78
1924 ? llvm::compression::Format::Zlib
1925 : llvm::compression::Format::Zstd;
1926 if (const char *Reason = llvm::compression::getReasonIfUnsupported(F)) {
1927 Error(Reason);
1928 return nullptr;
1929 }
1930 SmallVector<uint8_t, 0> Decompressed;
1931 if (llvm::Error E = llvm::compression::decompress(
1932 F, llvm::arrayRefFromStringRef(Blob), Decompressed, Record[0])) {
1933 Error("could not decompress embedded file contents: " +
1934 llvm::toString(std::move(E)));
1935 return nullptr;
1936 }
1937 return llvm::MemoryBuffer::getMemBufferCopy(
1938 llvm::toStringRef(Decompressed), Name);
1939 } else if (RecCode == SM_SLOC_BUFFER_BLOB) {
1940 return llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name, true);
1941 } else {
1942 Error("AST record has invalid code");
1943 return nullptr;
1944 }
1945 };
1946
1947 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1948 if (llvm::Error Err = F->SLocEntryCursor.JumpToBit(
1950 F->SLocEntryOffsets[ID - F->SLocEntryBaseID])) {
1951 Error(std::move(Err));
1952 return true;
1953 }
1954
1955 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
1957
1958 ++NumSLocEntriesRead;
1959 Expected<llvm::BitstreamEntry> MaybeEntry = SLocEntryCursor.advance();
1960 if (!MaybeEntry) {
1961 Error(MaybeEntry.takeError());
1962 return true;
1963 }
1964 llvm::BitstreamEntry Entry = MaybeEntry.get();
1965
1966 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1967 Error("incorrectly-formatted source location entry in AST file");
1968 return true;
1969 }
1970
1972 StringRef Blob;
1973 Expected<unsigned> MaybeSLOC =
1974 SLocEntryCursor.readRecord(Entry.ID, Record, &Blob);
1975 if (!MaybeSLOC) {
1976 Error(MaybeSLOC.takeError());
1977 return true;
1978 }
1979 switch (MaybeSLOC.get()) {
1980 default:
1981 Error("incorrectly-formatted source location entry in AST file");
1982 return true;
1983
1984 case SM_SLOC_FILE_ENTRY: {
1985 // We will detect whether a file changed and return 'Failure' for it, but
1986 // we will also try to fail gracefully by setting up the SLocEntry.
1987 unsigned InputID = Record[4];
1988 InputFile IF = getInputFile(*F, InputID);
1990 bool OverriddenBuffer = IF.isOverridden();
1991
1992 // Note that we only check if a File was returned. If it was out-of-date
1993 // we have complained but we will continue creating a FileID to recover
1994 // gracefully.
1995 if (!File)
1996 return true;
1997
1998 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1999 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
2000 // This is the module's main file.
2001 IncludeLoc = getImportLocation(F);
2002 }
2004 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
2005 FileID FID = SourceMgr.createFileID(*File, IncludeLoc, FileCharacter, ID,
2006 BaseOffset + Record[0]);
2007 SrcMgr::FileInfo &FileInfo = SourceMgr.getSLocEntry(FID).getFile();
2008 FileInfo.NumCreatedFIDs = Record[5];
2009 if (Record[3])
2010 FileInfo.setHasLineDirectives();
2011
2012 unsigned NumFileDecls = Record[7];
2013 if (NumFileDecls && ContextObj) {
2014 const unaligned_decl_id_t *FirstDecl = F->FileSortedDecls + Record[6];
2015 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
2016 FileDeclIDs[FID] =
2017 FileDeclsInfo(F, llvm::ArrayRef(FirstDecl, NumFileDecls));
2018 }
2019
2020 const SrcMgr::ContentCache &ContentCache =
2021 SourceMgr.getOrCreateContentCache(*File, isSystem(FileCharacter));
2022 if (OverriddenBuffer && !ContentCache.BufferOverridden &&
2023 ContentCache.ContentsEntry == ContentCache.OrigEntry &&
2024 !ContentCache.getBufferIfLoaded()) {
2025 auto Buffer = ReadBuffer(SLocEntryCursor, File->getName());
2026 if (!Buffer)
2027 return true;
2028 SourceMgr.overrideFileContents(*File, std::move(Buffer));
2029 }
2030
2031 break;
2032 }
2033
2034 case SM_SLOC_BUFFER_ENTRY: {
2035 const char *Name = Blob.data();
2036 unsigned Offset = Record[0];
2038 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
2039 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
2040 if (IncludeLoc.isInvalid() && F->isModule()) {
2041 IncludeLoc = getImportLocation(F);
2042 }
2043
2044 auto Buffer = ReadBuffer(SLocEntryCursor, Name);
2045 if (!Buffer)
2046 return true;
2047 FileID FID = SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
2048 BaseOffset + Offset, IncludeLoc);
2049 if (Record[3]) {
2050 auto &FileInfo = SourceMgr.getSLocEntry(FID).getFile();
2051 FileInfo.setHasLineDirectives();
2052 }
2053 break;
2054 }
2055
2057 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
2058 SourceLocation ExpansionBegin = ReadSourceLocation(*F, Record[2]);
2059 SourceLocation ExpansionEnd = ReadSourceLocation(*F, Record[3]);
2060 SourceMgr.createExpansionLoc(SpellingLoc, ExpansionBegin, ExpansionEnd,
2061 Record[5], Record[4], ID,
2062 BaseOffset + Record[0]);
2063 break;
2064 }
2065 }
2066
2067 return false;
2068}
2069
2070std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
2071 if (ID == 0)
2072 return std::make_pair(SourceLocation(), "");
2073
2074 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
2075 Error("source location entry ID out-of-range for AST file");
2076 return std::make_pair(SourceLocation(), "");
2077 }
2078
2079 // Find which module file this entry lands in.
2080 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
2081 if (!M->isModule())
2082 return std::make_pair(SourceLocation(), "");
2083
2084 // FIXME: Can we map this down to a particular submodule? That would be
2085 // ideal.
2086 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
2087}
2088
2089/// Find the location where the module F is imported.
2090SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
2091 if (F->ImportLoc.isValid())
2092 return F->ImportLoc;
2093
2094 // Otherwise we have a PCH. It's considered to be "imported" at the first
2095 // location of its includer.
2096 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
2097 // Main file is the importer.
2098 assert(SourceMgr.getMainFileID().isValid() && "missing main file");
2099 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
2100 }
2101 return F->ImportedBy[0]->FirstLoc;
2102}
2103
2104/// Enter a subblock of the specified BlockID with the specified cursor. Read
2105/// the abbreviations that are at the top of the block and then leave the cursor
2106/// pointing into the block.
2107llvm::Error ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor,
2108 unsigned BlockID,
2109 uint64_t *StartOfBlockOffset) {
2110 if (llvm::Error Err = Cursor.EnterSubBlock(BlockID))
2111 return Err;
2112
2113 if (StartOfBlockOffset)
2114 *StartOfBlockOffset = Cursor.GetCurrentBitNo();
2115
2116 while (true) {
2117 uint64_t Offset = Cursor.GetCurrentBitNo();
2118 Expected<unsigned> MaybeCode = Cursor.ReadCode();
2119 if (!MaybeCode)
2120 return MaybeCode.takeError();
2121 unsigned Code = MaybeCode.get();
2122
2123 // We expect all abbrevs to be at the start of the block.
2124 if (Code != llvm::bitc::DEFINE_ABBREV) {
2125 if (llvm::Error Err = Cursor.JumpToBit(Offset))
2126 return Err;
2127 return llvm::Error::success();
2128 }
2129 if (llvm::Error Err = Cursor.ReadAbbrevRecord())
2130 return Err;
2131 }
2132}
2133
2135 unsigned &Idx) {
2136 Token Tok;
2137 Tok.startToken();
2138 Tok.setLocation(ReadSourceLocation(M, Record, Idx));
2139 Tok.setKind((tok::TokenKind)Record[Idx++]);
2140 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
2141
2142 if (Tok.isAnnotation()) {
2143 Tok.setAnnotationEndLoc(ReadSourceLocation(M, Record, Idx));
2144 switch (Tok.getKind()) {
2145 case tok::annot_pragma_loop_hint: {
2146 auto *Info = new (PP.getPreprocessorAllocator()) PragmaLoopHintInfo;
2147 Info->PragmaName = ReadToken(M, Record, Idx);
2148 Info->Option = ReadToken(M, Record, Idx);
2149 unsigned NumTokens = Record[Idx++];
2151 Toks.reserve(NumTokens);
2152 for (unsigned I = 0; I < NumTokens; ++I)
2153 Toks.push_back(ReadToken(M, Record, Idx));
2154 Info->Toks = llvm::ArrayRef(Toks).copy(PP.getPreprocessorAllocator());
2155 Tok.setAnnotationValue(static_cast<void *>(Info));
2156 break;
2157 }
2158 case tok::annot_pragma_pack: {
2159 auto *Info = new (PP.getPreprocessorAllocator()) Sema::PragmaPackInfo;
2160 Info->Action = static_cast<Sema::PragmaMsStackAction>(Record[Idx++]);
2161 auto SlotLabel = ReadString(Record, Idx);
2162 Info->SlotLabel =
2163 llvm::StringRef(SlotLabel).copy(PP.getPreprocessorAllocator());
2164 Info->Alignment = ReadToken(M, Record, Idx);
2165 Tok.setAnnotationValue(static_cast<void *>(Info));
2166 break;
2167 }
2168 // Some annotation tokens do not use the PtrData field.
2169 case tok::annot_pragma_openmp:
2170 case tok::annot_pragma_openmp_end:
2171 case tok::annot_pragma_unused:
2172 case tok::annot_pragma_openacc:
2173 case tok::annot_pragma_openacc_end:
2174 case tok::annot_repl_input_end:
2175 break;
2176 default:
2177 llvm_unreachable("missing deserialization code for annotation token");
2178 }
2179 } else {
2180 Tok.setLength(Record[Idx++]);
2181 if (IdentifierInfo *II = getLocalIdentifier(M, Record[Idx++]))
2182 Tok.setIdentifierInfo(II);
2183 }
2184 return Tok;
2185}
2186
2188 BitstreamCursor &Stream = F.MacroCursor;
2189
2190 // Keep track of where we are in the stream, then jump back there
2191 // after reading this macro.
2192 SavedStreamPosition SavedPosition(Stream);
2193
2194 if (llvm::Error Err = Stream.JumpToBit(Offset)) {
2195 // FIXME this drops errors on the floor.
2196 consumeError(std::move(Err));
2197 return nullptr;
2198 }
2201 MacroInfo *Macro = nullptr;
2202 llvm::MutableArrayRef<Token> MacroTokens;
2203
2204 while (true) {
2205 // Advance to the next record, but if we get to the end of the block, don't
2206 // pop it (removing all the abbreviations from the cursor) since we want to
2207 // be able to reseek within the block and read entries.
2208 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
2210 Stream.advanceSkippingSubblocks(Flags);
2211 if (!MaybeEntry) {
2212 Error(MaybeEntry.takeError());
2213 return Macro;
2214 }
2215 llvm::BitstreamEntry Entry = MaybeEntry.get();
2216
2217 switch (Entry.Kind) {
2218 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
2219 case llvm::BitstreamEntry::Error:
2220 Error("malformed block record in AST file");
2221 return Macro;
2222 case llvm::BitstreamEntry::EndBlock:
2223 return Macro;
2224 case llvm::BitstreamEntry::Record:
2225 // The interesting case.
2226 break;
2227 }
2228
2229 // Read a record.
2230 Record.clear();
2232 if (Expected<unsigned> MaybeRecType = Stream.readRecord(Entry.ID, Record))
2233 RecType = (PreprocessorRecordTypes)MaybeRecType.get();
2234 else {
2235 Error(MaybeRecType.takeError());
2236 return Macro;
2237 }
2238 switch (RecType) {
2239 case PP_MODULE_MACRO:
2241 return Macro;
2242
2245 // If we already have a macro, that means that we've hit the end
2246 // of the definition of the macro we were looking for. We're
2247 // done.
2248 if (Macro)
2249 return Macro;
2250
2251 unsigned NextIndex = 1; // Skip identifier ID.
2252 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
2253 MacroInfo *MI = PP.AllocateMacroInfo(Loc);
2254 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
2255 MI->setIsUsed(Record[NextIndex++]);
2256 MI->setUsedForHeaderGuard(Record[NextIndex++]);
2257 MacroTokens = MI->allocateTokens(Record[NextIndex++],
2258 PP.getPreprocessorAllocator());
2259 if (RecType == PP_MACRO_FUNCTION_LIKE) {
2260 // Decode function-like macro info.
2261 bool isC99VarArgs = Record[NextIndex++];
2262 bool isGNUVarArgs = Record[NextIndex++];
2263 bool hasCommaPasting = Record[NextIndex++];
2264 MacroParams.clear();
2265 unsigned NumArgs = Record[NextIndex++];
2266 for (unsigned i = 0; i != NumArgs; ++i)
2267 MacroParams.push_back(getLocalIdentifier(F, Record[NextIndex++]));
2268
2269 // Install function-like macro info.
2270 MI->setIsFunctionLike();
2271 if (isC99VarArgs) MI->setIsC99Varargs();
2272 if (isGNUVarArgs) MI->setIsGNUVarargs();
2273 if (hasCommaPasting) MI->setHasCommaPasting();
2274 MI->setParameterList(MacroParams, PP.getPreprocessorAllocator());
2275 }
2276
2277 // Remember that we saw this macro last so that we add the tokens that
2278 // form its body to it.
2279 Macro = MI;
2280
2281 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
2282 Record[NextIndex]) {
2283 // We have a macro definition. Register the association
2285 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
2286 unsigned Index = translatePreprocessedEntityIDToIndex(GlobalID);
2287 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
2288 PreprocessingRecord::PPEntityID PPID =
2289 PPRec.getPPEntityID(Index, /*isLoaded=*/true);
2290 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
2291 PPRec.getPreprocessedEntity(PPID));
2292 if (PPDef)
2293 PPRec.RegisterMacroDefinition(Macro, PPDef);
2294 }
2295
2296 ++NumMacrosRead;
2297 break;
2298 }
2299
2300 case PP_TOKEN: {
2301 // If we see a TOKEN before a PP_MACRO_*, then the file is
2302 // erroneous, just pretend we didn't see this.
2303 if (!Macro) break;
2304 if (MacroTokens.empty()) {
2305 Error("unexpected number of macro tokens for a macro in AST file");
2306 return Macro;
2307 }
2308
2309 unsigned Idx = 0;
2310 MacroTokens[0] = ReadToken(F, Record, Idx);
2311 MacroTokens = MacroTokens.drop_front();
2312 break;
2313 }
2314 }
2315 }
2316}
2317
2320 PreprocessedEntityID LocalID) const {
2321 if (!M.ModuleOffsetMap.empty())
2322 ReadModuleOffsetMap(M);
2323
2324 unsigned ModuleFileIndex = LocalID >> 32;
2325 LocalID &= llvm::maskTrailingOnes<PreprocessedEntityID>(32);
2326 ModuleFile *MF =
2327 ModuleFileIndex ? M.TransitiveImports[ModuleFileIndex - 1] : &M;
2328 assert(MF && "malformed identifier ID encoding?");
2329
2330 if (!ModuleFileIndex) {
2331 assert(LocalID >= NUM_PREDEF_PP_ENTITY_IDS);
2332 LocalID -= NUM_PREDEF_PP_ENTITY_IDS;
2333 }
2334
2335 return (static_cast<PreprocessedEntityID>(MF->Index + 1) << 32) | LocalID;
2336}
2337
2339HeaderFileInfoTrait::getFile(const internal_key_type &Key) {
2340 FileManager &FileMgr = Reader.getFileManager();
2341 if (!Key.Imported)
2342 return FileMgr.getOptionalFileRef(Key.Filename);
2343
2344 auto Resolved =
2345 ASTReader::ResolveImportedPath(Reader.getPathBuf(), Key.Filename, M);
2346 return FileMgr.getOptionalFileRef(*Resolved);
2347}
2348
2350 uint8_t buf[sizeof(ikey.Size) + sizeof(ikey.ModTime)];
2351 memcpy(buf, &ikey.Size, sizeof(ikey.Size));
2352 memcpy(buf + sizeof(ikey.Size), &ikey.ModTime, sizeof(ikey.ModTime));
2353 return llvm::xxh3_64bits(buf);
2354}
2355
2358 internal_key_type ikey = {ekey.getSize(),
2359 M.HasTimestamps ? ekey.getModificationTime() : 0,
2360 ekey.getName(), /*Imported*/ false};
2361 return ikey;
2362}
2363
2365 if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime))
2366 return false;
2367
2368 if (llvm::sys::path::is_absolute(a.Filename) && a.Filename == b.Filename)
2369 return true;
2370
2371 // Determine whether the actual files are equivalent.
2372 OptionalFileEntryRef FEA = getFile(a);
2373 OptionalFileEntryRef FEB = getFile(b);
2374 return FEA && FEA == FEB;
2375}
2376
2377std::pair<unsigned, unsigned>
2379 return readULEBKeyDataLength(d);
2380}
2381
2383HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
2384 using namespace llvm::support;
2385
2386 internal_key_type ikey;
2387 ikey.Size = off_t(endian::readNext<uint64_t, llvm::endianness::little>(d));
2388 ikey.ModTime =
2389 time_t(endian::readNext<uint64_t, llvm::endianness::little>(d));
2390 ikey.Filename = (const char *)d;
2391 ikey.Imported = true;
2392 return ikey;
2393}
2394
2397 unsigned DataLen) {
2398 using namespace llvm::support;
2399
2400 const unsigned char *End = d + DataLen;
2401 HeaderFileInfo HFI;
2402 unsigned Flags = *d++;
2403
2405 bool Included = (Flags >> 6) & 0x01;
2406 if (Included)
2407 if ((FE = getFile(key)))
2408 // Not using \c Preprocessor::markIncluded(), since that would attempt to
2409 // deserialize this header file info again.
2410 Reader.getPreprocessor().getIncludedFiles().insert(*FE);
2411
2412 // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
2413 HFI.isImport |= (Flags >> 5) & 0x01;
2414 HFI.isPragmaOnce |= (Flags >> 4) & 0x01;
2415 HFI.DirInfo = (Flags >> 1) & 0x07;
2416 HFI.LazyControllingMacro = Reader.getGlobalIdentifierID(
2417 M, endian::readNext<IdentifierID, llvm::endianness::little>(d));
2418
2419 assert((End - d) % 4 == 0 &&
2420 "Wrong data length in HeaderFileInfo deserialization");
2421 while (d != End) {
2422 uint32_t LocalSMID =
2423 endian::readNext<uint32_t, llvm::endianness::little>(d);
2424 auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 7);
2425 LocalSMID >>= 3;
2426
2427 // This header is part of a module. Associate it with the module to enable
2428 // implicit module import.
2429 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
2430 Module *Mod = Reader.getSubmodule(GlobalSMID);
2431 ModuleMap &ModMap =
2432 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
2433
2434 if (FE || (FE = getFile(key))) {
2435 // FIXME: NameAsWritten
2436 Module::Header H = {std::string(key.Filename), "", *FE};
2437 ModMap.addHeader(Mod, H, HeaderRole, /*Imported=*/true);
2438 }
2439 HFI.mergeModuleMembership(HeaderRole);
2440 }
2441
2442 // This HeaderFileInfo was externally loaded.
2443 HFI.External = true;
2444 HFI.IsValid = true;
2445 return HFI;
2446}
2447
2449 uint32_t MacroDirectivesOffset) {
2450 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
2451 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
2452}
2453
2455 // Note that we are loading defined macros.
2456 Deserializing Macros(this);
2457
2458 for (ModuleFile &I : llvm::reverse(ModuleMgr)) {
2459 BitstreamCursor &MacroCursor = I.MacroCursor;
2460
2461 // If there was no preprocessor block, skip this file.
2462 if (MacroCursor.getBitcodeBytes().empty())
2463 continue;
2464
2465 BitstreamCursor Cursor = MacroCursor;
2466 if (llvm::Error Err = Cursor.JumpToBit(I.MacroStartOffset)) {
2467 Error(std::move(Err));
2468 return;
2469 }
2470
2472 while (true) {
2473 Expected<llvm::BitstreamEntry> MaybeE = Cursor.advanceSkippingSubblocks();
2474 if (!MaybeE) {
2475 Error(MaybeE.takeError());
2476 return;
2477 }
2478 llvm::BitstreamEntry E = MaybeE.get();
2479
2480 switch (E.Kind) {
2481 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
2482 case llvm::BitstreamEntry::Error:
2483 Error("malformed block record in AST file");
2484 return;
2485 case llvm::BitstreamEntry::EndBlock:
2486 goto NextCursor;
2487
2488 case llvm::BitstreamEntry::Record: {
2489 Record.clear();
2490 Expected<unsigned> MaybeRecord = Cursor.readRecord(E.ID, Record);
2491 if (!MaybeRecord) {
2492 Error(MaybeRecord.takeError());
2493 return;
2494 }
2495 switch (MaybeRecord.get()) {
2496 default: // Default behavior: ignore.
2497 break;
2498
2502 if (II->isOutOfDate())
2504 break;
2505 }
2506
2507 case PP_TOKEN:
2508 // Ignore tokens.
2509 break;
2510 }
2511 break;
2512 }
2513 }
2514 }
2515 NextCursor: ;
2516 }
2517}
2518
2519namespace {
2520
2521 /// Visitor class used to look up identifirs in an AST file.
2522 class IdentifierLookupVisitor {
2523 StringRef Name;
2524 unsigned NameHash;
2525 unsigned PriorGeneration;
2526 unsigned &NumIdentifierLookups;
2527 unsigned &NumIdentifierLookupHits;
2528 IdentifierInfo *Found = nullptr;
2529
2530 public:
2531 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
2532 unsigned &NumIdentifierLookups,
2533 unsigned &NumIdentifierLookupHits)
2534 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
2535 PriorGeneration(PriorGeneration),
2536 NumIdentifierLookups(NumIdentifierLookups),
2537 NumIdentifierLookupHits(NumIdentifierLookupHits) {}
2538
2539 bool operator()(ModuleFile &M) {
2540 // If we've already searched this module file, skip it now.
2541 if (M.Generation <= PriorGeneration)
2542 return true;
2543
2546 if (!IdTable)
2547 return false;
2548
2549 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
2550 Found);
2551 ++NumIdentifierLookups;
2552 ASTIdentifierLookupTable::iterator Pos =
2553 IdTable->find_hashed(Name, NameHash, &Trait);
2554 if (Pos == IdTable->end())
2555 return false;
2556
2557 // Dereferencing the iterator has the effect of building the
2558 // IdentifierInfo node and populating it with the various
2559 // declarations it needs.
2560 ++NumIdentifierLookupHits;
2561 Found = *Pos;
2562 if (Trait.hasMoreInformationInDependencies()) {
2563 // Look for the identifier in extra modules as they contain more info.
2564 return false;
2565 }
2566 return true;
2567 }
2568
2569 // Retrieve the identifier info found within the module
2570 // files.
2571 IdentifierInfo *getIdentifierInfo() const { return Found; }
2572 };
2573
2574} // namespace
2575
2577 // Note that we are loading an identifier.
2578 Deserializing AnIdentifier(this);
2579
2580 unsigned PriorGeneration = 0;
2581 if (getContext().getLangOpts().Modules)
2582 PriorGeneration = IdentifierGeneration[&II];
2583
2584 // If there is a global index, look there first to determine which modules
2585 // provably do not have any results for this identifier.
2587 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
2588 if (!loadGlobalIndex()) {
2589 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
2590 HitsPtr = &Hits;
2591 }
2592 }
2593
2594 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
2595 NumIdentifierLookups,
2596 NumIdentifierLookupHits);
2597 ModuleMgr.visit(Visitor, HitsPtr);
2599}
2600
2602 if (!II)
2603 return;
2604
2605 const_cast<IdentifierInfo *>(II)->setOutOfDate(false);
2606
2607 // Update the generation for this identifier.
2608 if (getContext().getLangOpts().Modules)
2609 IdentifierGeneration[II] = getGeneration();
2610}
2611
2613 unsigned &Idx) {
2614 uint64_t ModuleFileIndex = Record[Idx++] << 32;
2615 uint64_t LocalIndex = Record[Idx++];
2616 return getGlobalMacroID(F, (ModuleFileIndex | LocalIndex));
2617}
2618
2620 const PendingMacroInfo &PMInfo) {
2621 ModuleFile &M = *PMInfo.M;
2622
2623 BitstreamCursor &Cursor = M.MacroCursor;
2624 SavedStreamPosition SavedPosition(Cursor);
2625 if (llvm::Error Err =
2626 Cursor.JumpToBit(M.MacroOffsetsBase + PMInfo.MacroDirectivesOffset)) {
2627 Error(std::move(Err));
2628 return;
2629 }
2630
2631 struct ModuleMacroRecord {
2632 SubmoduleID SubModID;
2633 MacroInfo *MI;
2635 };
2637
2638 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
2639 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
2640 // macro histroy.
2642 while (true) {
2644 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
2645 if (!MaybeEntry) {
2646 Error(MaybeEntry.takeError());
2647 return;
2648 }
2649 llvm::BitstreamEntry Entry = MaybeEntry.get();
2650
2651 if (Entry.Kind != llvm::BitstreamEntry::Record) {
2652 Error("malformed block record in AST file");
2653 return;
2654 }
2655
2656 Record.clear();
2657 Expected<unsigned> MaybePP = Cursor.readRecord(Entry.ID, Record);
2658 if (!MaybePP) {
2659 Error(MaybePP.takeError());
2660 return;
2661 }
2662 switch ((PreprocessorRecordTypes)MaybePP.get()) {
2664 break;
2665
2666 case PP_MODULE_MACRO: {
2667 ModuleMacros.push_back(ModuleMacroRecord());
2668 auto &Info = ModuleMacros.back();
2669 unsigned Idx = 0;
2670 Info.SubModID = getGlobalSubmoduleID(M, Record[Idx++]);
2671 Info.MI = getMacro(ReadMacroID(M, Record, Idx));
2672 for (int I = Idx, N = Record.size(); I != N; ++I)
2673 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
2674 continue;
2675 }
2676
2677 default:
2678 Error("malformed block record in AST file");
2679 return;
2680 }
2681
2682 // We found the macro directive history; that's the last record
2683 // for this macro.
2684 break;
2685 }
2686
2687 // Module macros are listed in reverse dependency order.
2688 {
2689 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
2691 for (auto &MMR : ModuleMacros) {
2692 Overrides.clear();
2693 for (unsigned ModID : MMR.Overrides) {
2694 Module *Mod = getSubmodule(ModID);
2695 auto *Macro = PP.getModuleMacro(Mod, II);
2696 assert(Macro && "missing definition for overridden macro");
2697 Overrides.push_back(Macro);
2698 }
2699
2700 bool Inserted = false;
2701 Module *Owner = getSubmodule(MMR.SubModID);
2702 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
2703 }
2704 }
2705
2706 // Don't read the directive history for a module; we don't have anywhere
2707 // to put it.
2708 if (M.isModule())
2709 return;
2710
2711 // Deserialize the macro directives history in reverse source-order.
2712 MacroDirective *Latest = nullptr, *Earliest = nullptr;
2713 unsigned Idx = 0, N = Record.size();
2714 while (Idx < N) {
2715 MacroDirective *MD = nullptr;
2718 switch (K) {
2720 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
2721 MD = PP.AllocateDefMacroDirective(MI, Loc);
2722 break;
2723 }
2725 MD = PP.AllocateUndefMacroDirective(Loc);
2726 break;
2728 bool isPublic = Record[Idx++];
2729 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
2730 break;
2731 }
2732
2733 if (!Latest)
2734 Latest = MD;
2735 if (Earliest)
2736 Earliest->setPrevious(MD);
2737 Earliest = MD;
2738 }
2739
2740 if (Latest)
2741 PP.setLoadedMacroDirective(II, Earliest, Latest);
2742}
2743
2744bool ASTReader::shouldDisableValidationForFile(
2745 const serialization::ModuleFile &M) const {
2746 if (DisableValidationKind == DisableValidationForModuleKind::None)
2747 return false;
2748
2749 // If a PCH is loaded and validation is disabled for PCH then disable
2750 // validation for the PCH and the modules it loads.
2751 ModuleKind K = CurrentDeserializingModuleKind.value_or(M.Kind);
2752
2753 switch (K) {
2754 case MK_MainFile:
2755 case MK_Preamble:
2756 case MK_PCH:
2757 return bool(DisableValidationKind & DisableValidationForModuleKind::PCH);
2758 case MK_ImplicitModule:
2759 case MK_ExplicitModule:
2760 case MK_PrebuiltModule:
2761 return bool(DisableValidationKind & DisableValidationForModuleKind::Module);
2762 }
2763
2764 return false;
2765}
2766
2767static std::pair<StringRef, StringRef>
2769 const StringRef InputBlob) {
2770 uint16_t AsRequestedLength = Record[7];
2771 return {InputBlob.substr(0, AsRequestedLength),
2772 InputBlob.substr(AsRequestedLength)};
2773}
2774
2775InputFileInfo ASTReader::getInputFileInfo(ModuleFile &F, unsigned ID) {
2776 // If this ID is bogus, just return an empty input file.
2777 if (ID == 0 || ID > F.InputFileInfosLoaded.size())
2778 return InputFileInfo();
2779
2780 // If we've already loaded this input file, return it.
2781 if (F.InputFileInfosLoaded[ID - 1].isValid())
2782 return F.InputFileInfosLoaded[ID - 1];
2783
2784 // Go find this input file.
2785 BitstreamCursor &Cursor = F.InputFilesCursor;
2786 SavedStreamPosition SavedPosition(Cursor);
2787 if (llvm::Error Err = Cursor.JumpToBit(F.InputFilesOffsetBase +
2788 F.InputFileOffsets[ID - 1])) {
2789 // FIXME this drops errors on the floor.
2790 consumeError(std::move(Err));
2791 }
2792
2793 Expected<unsigned> MaybeCode = Cursor.ReadCode();
2794 if (!MaybeCode) {
2795 // FIXME this drops errors on the floor.
2796 consumeError(MaybeCode.takeError());
2797 }
2798 unsigned Code = MaybeCode.get();
2799 RecordData Record;
2800 StringRef Blob;
2801
2802 if (Expected<unsigned> Maybe = Cursor.readRecord(Code, Record, &Blob))
2803 assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE &&
2804 "invalid record type for input file");
2805 else {
2806 // FIXME this drops errors on the floor.
2807 consumeError(Maybe.takeError());
2808 }
2809
2810 assert(Record[0] == ID && "Bogus stored ID or offset");
2812 R.StoredSize = static_cast<off_t>(Record[1]);
2813 R.StoredTime = static_cast<time_t>(Record[2]);
2814 R.Overridden = static_cast<bool>(Record[3]);
2815 R.Transient = static_cast<bool>(Record[4]);
2816 R.TopLevel = static_cast<bool>(Record[5]);
2817 R.ModuleMap = static_cast<bool>(Record[6]);
2818 auto [UnresolvedFilenameAsRequested, UnresolvedFilename] =
2820 R.UnresolvedImportedFilenameAsRequested = UnresolvedFilenameAsRequested;
2821 R.UnresolvedImportedFilename = UnresolvedFilename.empty()
2822 ? UnresolvedFilenameAsRequested
2823 : UnresolvedFilename;
2824
2825 Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
2826 if (!MaybeEntry) // FIXME this drops errors on the floor.
2827 consumeError(MaybeEntry.takeError());
2828 llvm::BitstreamEntry Entry = MaybeEntry.get();
2829 assert(Entry.Kind == llvm::BitstreamEntry::Record &&
2830 "expected record type for input file hash");
2831
2832 Record.clear();
2833 if (Expected<unsigned> Maybe = Cursor.readRecord(Entry.ID, Record))
2834 assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE_HASH &&
2835 "invalid record type for input file hash");
2836 else {
2837 // FIXME this drops errors on the floor.
2838 consumeError(Maybe.takeError());
2839 }
2840 R.ContentHash = (static_cast<uint64_t>(Record[1]) << 32) |
2841 static_cast<uint64_t>(Record[0]);
2842
2843 // Note that we've loaded this input file info.
2844 F.InputFileInfosLoaded[ID - 1] = R;
2845 return R;
2846}
2847
2848static unsigned moduleKindForDiagnostic(ModuleKind Kind);
2849InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
2850 // If this ID is bogus, just return an empty input file.
2851 if (ID == 0 || ID > F.InputFilesLoaded.size())
2852 return InputFile();
2853
2854 // If we've already loaded this input file, return it.
2855 if (F.InputFilesLoaded[ID-1].getFile())
2856 return F.InputFilesLoaded[ID-1];
2857
2858 if (F.InputFilesLoaded[ID-1].isNotFound())
2859 return InputFile();
2860
2861 // Go find this input file.
2862 BitstreamCursor &Cursor = F.InputFilesCursor;
2863 SavedStreamPosition SavedPosition(Cursor);
2864 if (llvm::Error Err = Cursor.JumpToBit(F.InputFilesOffsetBase +
2865 F.InputFileOffsets[ID - 1])) {
2866 // FIXME this drops errors on the floor.
2867 consumeError(std::move(Err));
2868 }
2869
2870 InputFileInfo FI = getInputFileInfo(F, ID);
2871 off_t StoredSize = FI.StoredSize;
2872 time_t StoredTime = FI.StoredTime;
2873 bool Overridden = FI.Overridden;
2874 bool Transient = FI.Transient;
2875 auto Filename =
2876 ResolveImportedPath(PathBuf, FI.UnresolvedImportedFilenameAsRequested, F);
2877 uint64_t StoredContentHash = FI.ContentHash;
2878
2879 // For standard C++ modules, we don't need to check the inputs.
2880 bool SkipChecks = F.StandardCXXModule;
2881
2882 const HeaderSearchOptions &HSOpts =
2883 PP.getHeaderSearchInfo().getHeaderSearchOpts();
2884
2885 // The option ForceCheckCXX20ModulesInputFiles is only meaningful for C++20
2886 // modules.
2888 SkipChecks = false;
2889 Overridden = false;
2890 }
2891
2892 auto File = FileMgr.getOptionalFileRef(*Filename, /*OpenFile=*/false);
2893
2894 // For an overridden file, create a virtual file with the stored
2895 // size/timestamp.
2896 if ((Overridden || Transient || SkipChecks) && !File)
2897 File = FileMgr.getVirtualFileRef(*Filename, StoredSize, StoredTime);
2898
2899 if (!File) {
2900 if (Complain) {
2901 std::string ErrorStr = "could not find file '";
2902 ErrorStr += *Filename;
2903 ErrorStr += "' referenced by AST file '";
2904 ErrorStr += F.FileName.str();
2905 ErrorStr += "'";
2906 Error(ErrorStr);
2907 }
2908 // Record that we didn't find the file.
2910 return InputFile();
2911 }
2912
2913 // Check if there was a request to override the contents of the file
2914 // that was part of the precompiled header. Overriding such a file
2915 // can lead to problems when lexing using the source locations from the
2916 // PCH.
2917 SourceManager &SM = getSourceManager();
2918 // FIXME: Reject if the overrides are different.
2919 if ((!Overridden && !Transient) && !SkipChecks &&
2920 SM.isFileOverridden(*File)) {
2921 if (Complain)
2922 Error(diag::err_fe_pch_file_overridden, *Filename);
2923
2924 // After emitting the diagnostic, bypass the overriding file to recover
2925 // (this creates a separate FileEntry).
2926 File = SM.bypassFileContentsOverride(*File);
2927 if (!File) {
2929 return InputFile();
2930 }
2931 }
2932
2933 auto HasInputContentChanged = [&](Change OriginalChange) {
2934 assert(ValidateASTInputFilesContent &&
2935 "We should only check the content of the inputs with "
2936 "ValidateASTInputFilesContent enabled.");
2937
2938 if (StoredContentHash == 0)
2939 return OriginalChange;
2940
2941 auto MemBuffOrError = FileMgr.getBufferForFile(*File);
2942 if (!MemBuffOrError) {
2943 if (!Complain)
2944 return OriginalChange;
2945 std::string ErrorStr = "could not get buffer for file '";
2946 ErrorStr += File->getName();
2947 ErrorStr += "'";
2948 Error(ErrorStr);
2949 return OriginalChange;
2950 }
2951
2952 auto ContentHash = xxh3_64bits(MemBuffOrError.get()->getBuffer());
2953 if (StoredContentHash == static_cast<uint64_t>(ContentHash))
2954 return Change{Change::None};
2955
2956 return Change{Change::Content};
2957 };
2958 auto HasInputFileChanged = [&]() {
2959 if (StoredSize != File->getSize())
2960 return Change{Change::Size, StoredSize, File->getSize()};
2961 if (!shouldDisableValidationForFile(F) && StoredTime &&
2962 StoredTime != File->getModificationTime()) {
2963 Change MTimeChange = {Change::ModTime, StoredTime,
2964 File->getModificationTime()};
2965
2966 // In case the modification time changes but not the content,
2967 // accept the cached file as legit.
2968 if (ValidateASTInputFilesContent)
2969 return HasInputContentChanged(MTimeChange);
2970
2971 return MTimeChange;
2972 }
2973 return Change{Change::None};
2974 };
2975
2976 bool IsOutOfDate = false;
2977 auto FileChange = SkipChecks ? Change{Change::None} : HasInputFileChanged();
2978 // When ForceCheckCXX20ModulesInputFiles and ValidateASTInputFilesContent
2979 // enabled, it is better to check the contents of the inputs. Since we can't
2980 // get correct modified time information for inputs from overriden inputs.
2981 if (HSOpts.ForceCheckCXX20ModulesInputFiles && ValidateASTInputFilesContent &&
2982 F.StandardCXXModule && FileChange.Kind == Change::None)
2983 FileChange = HasInputContentChanged(FileChange);
2984
2985 // When we have StoredTime equal to zero and ValidateASTInputFilesContent,
2986 // it is better to check the content of the input files because we cannot rely
2987 // on the file modification time, which will be the same (zero) for these
2988 // files.
2989 if (!StoredTime && ValidateASTInputFilesContent &&
2990 FileChange.Kind == Change::None)
2991 FileChange = HasInputContentChanged(FileChange);
2992
2993 // For an overridden file, there is nothing to validate.
2994 if (!Overridden && FileChange.Kind != Change::None) {
2995 if (Complain) {
2996 // Build a list of the PCH imports that got us here (in reverse).
2997 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2998 while (!ImportStack.back()->ImportedBy.empty())
2999 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
3000
3001 // The top-level AST file is stale.
3002 StringRef TopLevelASTFileName(ImportStack.back()->FileName);
3003 Diag(diag::err_fe_ast_file_modified)
3004 << *Filename << moduleKindForDiagnostic(ImportStack.back()->Kind)
3005 << TopLevelASTFileName;
3006 Diag(diag::note_fe_ast_file_modified)
3007 << FileChange.Kind << (FileChange.Old && FileChange.New)
3008 << llvm::itostr(FileChange.Old.value_or(0))
3009 << llvm::itostr(FileChange.New.value_or(0));
3010
3011 // Print the import stack.
3012 if (ImportStack.size() > 1) {
3013 Diag(diag::note_ast_file_required_by)
3014 << *Filename << ImportStack[0]->FileName;
3015 for (unsigned I = 1; I < ImportStack.size(); ++I)
3016 Diag(diag::note_ast_file_required_by)
3017 << ImportStack[I - 1]->FileName << ImportStack[I]->FileName;
3018 }
3019
3021 Diag(diag::note_ast_file_rebuild_required) << TopLevelASTFileName;
3022 Diag(diag::note_ast_file_input_files_validation_status)
3024 }
3025
3026 IsOutOfDate = true;
3027 }
3028 // FIXME: If the file is overridden and we've already opened it,
3029 // issue an error (or split it into a separate FileEntry).
3030
3031 InputFile IF = InputFile(*File, Overridden || Transient, IsOutOfDate);
3032
3033 // Note that we've loaded this input file.
3034 F.InputFilesLoaded[ID-1] = IF;
3035 return IF;
3036}
3037
3038ASTReader::TemporarilyOwnedStringRef
3040 ModuleFile &ModF) {
3041 return ResolveImportedPath(Buf, Path, ModF.BaseDirectory);
3042}
3043
3044ASTReader::TemporarilyOwnedStringRef
3046 StringRef Prefix) {
3047 assert(Buf.capacity() != 0 && "Overlapping ResolveImportedPath calls");
3048
3049 if (Prefix.empty() || Path.empty() || llvm::sys::path::is_absolute(Path) ||
3050 Path == "<built-in>" || Path == "<command line>")
3051 return {Path, Buf};
3052
3053 Buf.clear();
3054 llvm::sys::path::append(Buf, Prefix, Path);
3055 StringRef ResolvedPath{Buf.data(), Buf.size()};
3056 return {ResolvedPath, Buf};
3057}
3058
3060 StringRef P,
3061 ModuleFile &ModF) {
3062 return ResolveImportedPathAndAllocate(Buf, P, ModF.BaseDirectory);
3063}
3064
3066 StringRef P,
3067 StringRef Prefix) {
3068 auto ResolvedPath = ResolveImportedPath(Buf, P, Prefix);
3069 return ResolvedPath->str();
3070}
3071
3072static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
3073 switch (ARR) {
3074 case ASTReader::Failure: return true;
3075 case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
3076 case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
3079 return !(Caps & ASTReader::ARR_ConfigurationMismatch);
3080 case ASTReader::HadErrors: return true;
3081 case ASTReader::Success: return false;
3082 }
3083
3084 llvm_unreachable("unknown ASTReadResult");
3085}
3086
3087ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(
3088 BitstreamCursor &Stream, StringRef Filename,
3089 unsigned ClientLoadCapabilities, bool AllowCompatibleConfigurationMismatch,
3090 ASTReaderListener &Listener, std::string &SuggestedPredefines) {
3091 if (llvm::Error Err = Stream.EnterSubBlock(OPTIONS_BLOCK_ID)) {
3092 // FIXME this drops errors on the floor.
3093 consumeError(std::move(Err));
3094 return Failure;
3095 }
3096
3097 // Read all of the records in the options block.
3098 RecordData Record;
3099 ASTReadResult Result = Success;
3100 while (true) {
3101 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
3102 if (!MaybeEntry) {
3103 // FIXME this drops errors on the floor.
3104 consumeError(MaybeEntry.takeError());
3105 return Failure;
3106 }
3107 llvm::BitstreamEntry Entry = MaybeEntry.get();
3108
3109 switch (Entry.Kind) {
3110 case llvm::BitstreamEntry::Error:
3111 case llvm::BitstreamEntry::SubBlock:
3112 return Failure;
3113
3114 case llvm::BitstreamEntry::EndBlock:
3115 return Result;
3116
3117 case llvm::BitstreamEntry::Record:
3118 // The interesting case.
3119 break;
3120 }
3121
3122 // Read and process a record.
3123 Record.clear();
3124 Expected<unsigned> MaybeRecordType = Stream.readRecord(Entry.ID, Record);
3125 if (!MaybeRecordType) {
3126 // FIXME this drops errors on the floor.
3127 consumeError(MaybeRecordType.takeError());
3128 return Failure;
3129 }
3130 switch ((OptionsRecordTypes)MaybeRecordType.get()) {
3131 case LANGUAGE_OPTIONS: {
3132 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
3133 if (ParseLanguageOptions(Record, Filename, Complain, Listener,
3134 AllowCompatibleConfigurationMismatch))
3135 Result = ConfigurationMismatch;
3136 break;
3137 }
3138
3139 case CODEGEN_OPTIONS: {
3140 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
3141 if (ParseCodeGenOptions(Record, Filename, Complain, Listener,
3142 AllowCompatibleConfigurationMismatch))
3143 Result = ConfigurationMismatch;
3144 break;
3145 }
3146
3147 case TARGET_OPTIONS: {
3148 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
3149 if (ParseTargetOptions(Record, Filename, Complain, Listener,
3150 AllowCompatibleConfigurationMismatch))
3151 Result = ConfigurationMismatch;
3152 break;
3153 }
3154
3155 case FILE_SYSTEM_OPTIONS: {
3156 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
3157 if (!AllowCompatibleConfigurationMismatch &&
3158 ParseFileSystemOptions(Record, Complain, Listener))
3159 Result = ConfigurationMismatch;
3160 break;
3161 }
3162
3163 case HEADER_SEARCH_OPTIONS: {
3164 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
3165 if (!AllowCompatibleConfigurationMismatch &&
3166 ParseHeaderSearchOptions(Record, Filename, Complain, Listener))
3167 Result = ConfigurationMismatch;
3168 break;
3169 }
3170
3172 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
3173 if (!AllowCompatibleConfigurationMismatch &&
3174 ParsePreprocessorOptions(Record, Filename, Complain, Listener,
3175 SuggestedPredefines))
3176 Result = ConfigurationMismatch;
3177 break;
3178 }
3179 }
3180}
3181
3182/// Returns {build-session validation applies, MF was validated this session}.
3183static std::pair<bool, bool>
3185 const HeaderSearchOptions &HSOpts) {
3186 const bool EnablesBSValidation =
3188 const bool WasValidated =
3189 EnablesBSValidation &&
3191 return {EnablesBSValidation, WasValidated};
3192}
3193
3194ASTReader::RelocationResult
3195ASTReader::getModuleForRelocationChecks(ModuleFile &F, bool DirectoryCheck) {
3196 // Don't emit module relocation errors if we have -fno-validate-pch.
3197 const bool IgnoreError =
3198 bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation &
3200
3201 if (!PP.getPreprocessorOpts().ModulesCheckRelocated)
3202 return {std::nullopt, IgnoreError};
3203
3204 const bool IsImplicitModule = F.Kind == MK_ImplicitModule;
3205
3206 if (!DirectoryCheck &&
3207 (!IsImplicitModule || ModuleMgr.begin()->Kind == MK_MainFile))
3208 return {std::nullopt, IgnoreError};
3209
3210 const HeaderSearchOptions &HSOpts =
3211 PP.getHeaderSearchInfo().getHeaderSearchOpts();
3212
3213 // When only validating modules once per build session,
3214 // Skip check if the timestamp is up to date or module was built in same build
3215 // session.
3216 auto [EnablesBSValidation, WasValidated] =
3217 wasValidatedInBuildSession(F, HSOpts);
3218 if (WasValidated)
3219 return {std::nullopt, IgnoreError};
3220 if (EnablesBSValidation &&
3221 static_cast<uint64_t>(F.ModTime) >= HSOpts.BuildSessionTimestamp)
3222 return {std::nullopt, IgnoreError};
3223
3224 Diag(diag::remark_module_check_relocation) << F.ModuleName << F.FileName;
3225
3226 // If we've already loaded a module map file covering this module, we may
3227 // have a better path for it (relative to the current build if doing directory
3228 // check).
3229 Module *M = PP.getHeaderSearchInfo().lookupModule(
3230 F.ModuleName, DirectoryCheck ? SourceLocation() : F.ImportLoc,
3231 /*AllowSearch=*/DirectoryCheck,
3232 /*AllowExtraModuleMapSearch=*/DirectoryCheck);
3233
3234 return {M, IgnoreError};
3235}
3236
3238ASTReader::ReadControlBlock(ModuleFile &F,
3239 SmallVectorImpl<ImportedModule> &Loaded,
3240 const ModuleFile *ImportedBy,
3241 unsigned ClientLoadCapabilities) {
3242 BitstreamCursor &Stream = F.Stream;
3243
3244 if (llvm::Error Err = Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
3245 Error(std::move(Err));
3246 return Failure;
3247 }
3248
3249 // Lambda to read the unhashed control block the first time it's called.
3250 //
3251 // For PCM files, the unhashed control block cannot be read until after the
3252 // MODULE_NAME record. However, PCH files have no MODULE_NAME, and yet still
3253 // need to look ahead before reading the IMPORTS record. For consistency,
3254 // this block is always read somehow (see BitstreamEntry::EndBlock).
3255 bool HasReadUnhashedControlBlock = false;
3256 auto readUnhashedControlBlockOnce = [&]() {
3257 if (!HasReadUnhashedControlBlock) {
3258 HasReadUnhashedControlBlock = true;
3259 if (ASTReadResult Result =
3260 readUnhashedControlBlock(F, ImportedBy, ClientLoadCapabilities))
3261 return Result;
3262 }
3263 return Success;
3264 };
3265
3266 bool DisableValidation = shouldDisableValidationForFile(F);
3267
3268 // Read all of the records and blocks in the control block.
3269 RecordData Record;
3270 unsigned NumInputs = 0;
3271 unsigned NumUserInputs = 0;
3272 StringRef BaseDirectoryAsWritten;
3273 while (true) {
3274 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
3275 if (!MaybeEntry) {
3276 Error(MaybeEntry.takeError());
3277 return Failure;
3278 }
3279 llvm::BitstreamEntry Entry = MaybeEntry.get();
3280
3281 switch (Entry.Kind) {
3282 case llvm::BitstreamEntry::Error:
3283 Error("malformed block record in AST file");
3284 return Failure;
3285 case llvm::BitstreamEntry::EndBlock: {
3286 // Validate the module before returning. This call catches an AST with
3287 // no module name and no imports.
3288 if (ASTReadResult Result = readUnhashedControlBlockOnce())
3289 return Result;
3290
3291 // Validate input files.
3292 const HeaderSearchOptions &HSOpts =
3293 PP.getHeaderSearchInfo().getHeaderSearchOpts();
3294
3295 // All user input files reside at the index range [0, NumUserInputs), and
3296 // system input files reside at [NumUserInputs, NumInputs). For explicitly
3297 // loaded module files, ignore missing inputs.
3298 if (!DisableValidation && F.Kind != MK_ExplicitModule &&
3299 F.Kind != MK_PrebuiltModule) {
3300 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
3301
3302 // If we are reading a module, we will create a verification timestamp,
3303 // so we verify all input files. Otherwise, verify only user input
3304 // files.
3305
3306 unsigned N = ValidateSystemInputs ? NumInputs : NumUserInputs;
3307 F.InputFilesValidationStatus = ValidateSystemInputs
3310 auto [_, WasValidated] = wasValidatedInBuildSession(F, HSOpts);
3311 if (WasValidated) {
3312 N = ForceValidateUserInputs ? NumUserInputs : 0;
3314 ForceValidateUserInputs
3317 }
3318
3319 if (N != 0)
3320 Diag(diag::remark_module_validation)
3321 << N << F.ModuleName << F.FileName;
3322
3323 for (unsigned I = 0; I < N; ++I) {
3324 InputFile IF = getInputFile(F, I+1, Complain);
3325 if (!IF.getFile() || IF.isOutOfDate())
3326 return OutOfDate;
3327 }
3328 } else {
3330 }
3331
3332 if (Listener)
3333 Listener->visitModuleFile(F.FileName, F.Kind, F.isDirectlyImported());
3334
3335 if (Listener && Listener->needsInputFileVisitation()) {
3336 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
3337 : NumUserInputs;
3338 for (unsigned I = 0; I < N; ++I) {
3339 bool IsSystem = I >= NumUserInputs;
3340 InputFileInfo FI = getInputFileInfo(F, I + 1);
3341 auto FilenameAsRequested = ResolveImportedPath(
3343 Listener->visitInputFile(
3344 *FilenameAsRequested, IsSystem, FI.Overridden,
3346 }
3347 }
3348
3349 return Success;
3350 }
3351
3352 case llvm::BitstreamEntry::SubBlock:
3353 switch (Entry.ID) {
3355 F.InputFilesCursor = Stream;
3356 if (llvm::Error Err = Stream.SkipBlock()) {
3357 Error(std::move(Err));
3358 return Failure;
3359 }
3360 if (ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
3361 Error("malformed block record in AST file");
3362 return Failure;
3363 }
3364 F.InputFilesOffsetBase = F.InputFilesCursor.GetCurrentBitNo();
3365 continue;
3366
3367 case OPTIONS_BLOCK_ID:
3368 // If we're reading the first module for this group, check its options
3369 // are compatible with ours. For modules it imports, no further checking
3370 // is required, because we checked them when we built it.
3371 if (Listener && !ImportedBy) {
3372 // Should we allow the configuration of the module file to differ from
3373 // the configuration of the current translation unit in a compatible
3374 // way?
3375 //
3376 // FIXME: Allow this for files explicitly specified with -include-pch.
3377 bool AllowCompatibleConfigurationMismatch =
3379
3380 ASTReadResult Result =
3381 ReadOptionsBlock(Stream, F.FileName, ClientLoadCapabilities,
3382 AllowCompatibleConfigurationMismatch, *Listener,
3383 SuggestedPredefines);
3384 if (Result == Failure) {
3385 Error("malformed block record in AST file");
3386 return Result;
3387 }
3388
3389 if (DisableValidation ||
3390 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
3391 Result = Success;
3392
3393 // If we can't load the module, exit early since we likely
3394 // will rebuild the module anyway. The stream may be in the
3395 // middle of a block.
3396 if (Result != Success)
3397 return Result;
3398 } else if (llvm::Error Err = Stream.SkipBlock()) {
3399 Error(std::move(Err));
3400 return Failure;
3401 }
3402 continue;
3403
3404 default:
3405 if (llvm::Error Err = Stream.SkipBlock()) {
3406 Error(std::move(Err));
3407 return Failure;
3408 }
3409 continue;
3410 }
3411
3412 case llvm::BitstreamEntry::Record:
3413 // The interesting case.
3414 break;
3415 }
3416
3417 // Read and process a record.
3418 Record.clear();
3419 StringRef Blob;
3420 Expected<unsigned> MaybeRecordType =
3421 Stream.readRecord(Entry.ID, Record, &Blob);
3422 if (!MaybeRecordType) {
3423 Error(MaybeRecordType.takeError());
3424 return Failure;
3425 }
3426 switch ((ControlRecordTypes)MaybeRecordType.get()) {
3427 case METADATA: {
3428 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
3429 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
3430 Diag(Record[0] < VERSION_MAJOR ? diag::err_ast_file_version_too_old
3431 : diag::err_ast_file_version_too_new)
3433 return VersionMismatch;
3434 }
3435
3436 bool hasErrors = Record[7];
3437 if (hasErrors && !DisableValidation) {
3438 // If requested by the caller and the module hasn't already been read
3439 // or compiled, mark modules on error as out-of-date.
3440 if ((ClientLoadCapabilities & ARR_TreatModuleWithErrorsAsOutOfDate) &&
3441 canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
3442 return OutOfDate;
3443
3444 if (!AllowASTWithCompilerErrors) {
3445 Diag(diag::err_ast_file_with_compiler_errors)
3447 return HadErrors;
3448 }
3449 }
3450 if (hasErrors) {
3451 Diags.ErrorOccurred = true;
3452 Diags.UncompilableErrorOccurred = true;
3453 Diags.UnrecoverableErrorOccurred = true;
3454 }
3455
3456 F.RelocatablePCH = Record[4];
3457 // Relative paths in a relocatable PCH are relative to our sysroot.
3458 if (F.RelocatablePCH)
3459 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
3460
3462
3463 F.HasTimestamps = Record[6];
3464
3465 const std::string &CurBranch = getClangFullRepositoryVersion();
3466 StringRef ASTBranch = Blob;
3467 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
3468 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
3469 Diag(diag::err_ast_file_different_branch)
3470 << moduleKindForDiagnostic(F.Kind) << F.FileName << ASTBranch
3471 << CurBranch;
3472 return VersionMismatch;
3473 }
3474 break;
3475 }
3476
3477 case IMPORT: {
3478 // Validate the AST before processing any imports (otherwise, untangling
3479 // them can be error-prone and expensive). A module will have a name and
3480 // will already have been validated, but this catches the PCH case.
3481 if (ASTReadResult Result = readUnhashedControlBlockOnce())
3482 return Result;
3483
3484 unsigned Idx = 0;
3485 // Read information about the AST file.
3486 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
3487
3488 // The import location will be the local one for now; we will adjust
3489 // all import locations of module imports after the global source
3490 // location info are setup, in ReadAST.
3491 auto [ImportLoc, ImportModuleFileIndex] =
3492 ReadUntranslatedSourceLocation(Record[Idx++]);
3493 // The import location must belong to the current module file itself.
3494 assert(ImportModuleFileIndex == 0);
3495
3496 StringRef ImportedName = ReadStringBlob(Record, Idx, Blob);
3497
3498 bool IsImportingStdCXXModule = Record[Idx++];
3499
3500 off_t StoredSize = 0;
3501 time_t StoredModTime = 0;
3502 unsigned FileNameKind = 0;
3503 ASTFileSignature StoredSignature;
3504 ModuleFileName ImportedFile;
3505 std::string StoredFile;
3506 bool IgnoreImportedByNote = false;
3507
3508 // For prebuilt and explicit modules first consult the file map for
3509 // an override. Note that here we don't search prebuilt module
3510 // directories if we're not importing standard c++ module, only the
3511 // explicit name to file mappings. Also, we will still verify the
3512 // size/signature making sure it is essentially the same file but
3513 // perhaps in a different location.
3514 if (ImportedKind == MK_PrebuiltModule || ImportedKind == MK_ExplicitModule)
3515 ImportedFile = PP.getHeaderSearchInfo().getPrebuiltModuleFileName(
3516 ImportedName, /*FileMapOnly*/ !IsImportingStdCXXModule);
3517
3518 if (IsImportingStdCXXModule && ImportedFile.empty()) {
3519 Diag(diag::err_failed_to_find_module_file) << ImportedName;
3520 return Missing;
3521 }
3522
3523 if (!IsImportingStdCXXModule) {
3524 StoredSize = (off_t)Record[Idx++];
3525 StoredModTime = (time_t)Record[Idx++];
3526 FileNameKind = (unsigned)Record[Idx++];
3527
3528 StringRef SignatureBytes = Blob.substr(0, ASTFileSignature::size);
3529 StoredSignature = ASTFileSignature::create(SignatureBytes.begin(),
3530 SignatureBytes.end());
3531 Blob = Blob.substr(ASTFileSignature::size);
3532
3533 StoredFile = ReadPathBlob(BaseDirectoryAsWritten, Record, Idx, Blob);
3534 if (ImportedFile.empty()) {
3535 ImportedFile = ModuleFileName::makeFromRaw(StoredFile, FileNameKind);
3536 } else if (!getDiags().isIgnored(
3537 diag::warn_module_file_mapping_mismatch,
3538 CurrentImportLoc)) {
3539 auto ImportedFileRef =
3540 PP.getFileManager().getOptionalFileRef(ImportedFile);
3541 auto StoredFileRef =
3542 PP.getFileManager().getOptionalFileRef(StoredFile);
3543 if ((ImportedFileRef && StoredFileRef) &&
3544 (*ImportedFileRef != *StoredFileRef)) {
3545 Diag(diag::warn_module_file_mapping_mismatch)
3546 << ImportedFile << StoredFile;
3547 Diag(diag::note_module_file_imported_by)
3548 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
3549 IgnoreImportedByNote = true;
3550 }
3551 }
3552 }
3553
3554 // If our client can't cope with us being out of date, we can't cope with
3555 // our dependency being missing.
3556 unsigned Capabilities = ClientLoadCapabilities;
3557 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3558 Capabilities &= ~ARR_Missing;
3559
3560 // Load the AST file.
3561 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
3562 Loaded, StoredSize, StoredModTime,
3563 StoredSignature, Capabilities);
3564
3565 // Check the AST we just read from ImportedFile contains a different
3566 // module than we expected (ImportedName). This can occur for C++20
3567 // Modules when given a mismatch via -fmodule-file=<name>=<file>
3568 if (IsImportingStdCXXModule) {
3569 if (const auto *Imported =
3570 getModuleManager().lookupByFileName(ImportedFile);
3571 Imported != nullptr && Imported->ModuleName != ImportedName) {
3572 Diag(diag::err_failed_to_find_module_file) << ImportedName;
3573 Result = Missing;
3574 }
3575 }
3576
3577 // If we diagnosed a problem, produce a backtrace.
3578 bool recompilingFinalized = Result == OutOfDate &&
3579 (Capabilities & ARR_OutOfDate) &&
3580 getModuleManager()
3581 .getModuleCache()
3582 .getInMemoryModuleCache()
3583 .isPCMFinal(F.FileName);
3584 if (!IgnoreImportedByNote &&
3585 (isDiagnosedResult(Result, Capabilities) || recompilingFinalized))
3586 Diag(diag::note_module_file_imported_by)
3587 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
3588
3589 switch (Result) {
3590 case Failure: return Failure;
3591 // If we have to ignore the dependency, we'll have to ignore this too.
3592 case Missing:
3593 case OutOfDate: return OutOfDate;
3594 case VersionMismatch: return VersionMismatch;
3595 case ConfigurationMismatch: return ConfigurationMismatch;
3596 case HadErrors: return HadErrors;
3597 case Success: break;
3598 }
3599 break;
3600 }
3601
3602 case ORIGINAL_FILE:
3603 F.OriginalSourceFileID = FileID::get(Record[0]);
3604 F.ActualOriginalSourceFileName = std::string(Blob);
3605 F.OriginalSourceFileName = ResolveImportedPathAndAllocate(
3606 PathBuf, F.ActualOriginalSourceFileName, F);
3607 break;
3608
3609 case ORIGINAL_FILE_ID:
3610 F.OriginalSourceFileID = FileID::get(Record[0]);
3611 break;
3612
3613 case MODULE_NAME:
3614 F.ModuleName = std::string(Blob);
3615 Diag(diag::remark_module_import)
3616 << F.ModuleName << F.FileName << (ImportedBy ? true : false)
3617 << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());
3618 if (Listener)
3619 Listener->ReadModuleName(F.ModuleName);
3620
3621 // Validate the AST as soon as we have a name so we can exit early on
3622 // failure.
3623 if (ASTReadResult Result = readUnhashedControlBlockOnce())
3624 return Result;
3625
3626 break;
3627
3628 case MODULE_DIRECTORY: {
3629 // Save the BaseDirectory as written in the PCM for computing the module
3630 // filename for the ModuleCache.
3631 BaseDirectoryAsWritten = Blob;
3632 assert(!F.ModuleName.empty() &&
3633 "MODULE_DIRECTORY found before MODULE_NAME");
3634 F.BaseDirectory = std::string(Blob);
3635
3636 auto [MaybeM, IgnoreError] =
3637 getModuleForRelocationChecks(F, /*DirectoryCheck=*/true);
3638 if (!MaybeM.has_value())
3639 break;
3640
3641 Module *M = MaybeM.value();
3642 if (!M || !M->Directory)
3643 break;
3644 if (IgnoreError) {
3645 F.BaseDirectory = std::string(M->Directory->getName());
3646 break;
3647 }
3648 if ((F.Kind == MK_ExplicitModule) || (F.Kind == MK_PrebuiltModule))
3649 break;
3650
3651 // If we're implicitly loading a module, the base directory can't
3652 // change between the build and use.
3653 auto BuildDir = PP.getFileManager().getOptionalDirectoryRef(Blob);
3654 if (BuildDir && (*BuildDir == M->Directory)) {
3655 F.BaseDirectory = std::string(M->Directory->getName());
3656 break;
3657 }
3658 Diag(diag::remark_module_relocated)
3659 << F.ModuleName << Blob << M->Directory->getName();
3660
3661 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
3662 Diag(diag::err_imported_module_relocated)
3663 << F.ModuleName << Blob << M->Directory->getName();
3664 return OutOfDate;
3665 }
3666
3667 case MODULE_MAP_FILE:
3668 if (ASTReadResult Result =
3669 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
3670 return Result;
3671 break;
3672
3673 case INPUT_FILE_OFFSETS:
3674 NumInputs = Record[0];
3675 NumUserInputs = Record[1];
3677 (const llvm::support::unaligned_uint64_t *)Blob.data();
3678 F.InputFilesLoaded.resize(NumInputs);
3679 F.InputFileInfosLoaded.resize(NumInputs);
3680 F.NumUserInputFiles = NumUserInputs;
3681 break;
3682 }
3683 }
3684}
3685
3686llvm::Error ASTReader::ReadASTBlock(ModuleFile &F,
3687 unsigned ClientLoadCapabilities) {
3688 BitstreamCursor &Stream = F.Stream;
3689
3690 if (llvm::Error Err = Stream.EnterSubBlock(AST_BLOCK_ID))
3691 return Err;
3692 F.ASTBlockStartOffset = Stream.GetCurrentBitNo();
3693
3694 // Read all of the records and blocks for the AST file.
3695 RecordData Record;
3696 while (true) {
3697 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
3698 if (!MaybeEntry)
3699 return MaybeEntry.takeError();
3700 llvm::BitstreamEntry Entry = MaybeEntry.get();
3701
3702 switch (Entry.Kind) {
3703 case llvm::BitstreamEntry::Error:
3704 return llvm::createStringError(
3705 std::errc::illegal_byte_sequence,
3706 "error at end of module block in AST file");
3707 case llvm::BitstreamEntry::EndBlock:
3708 // Outside of C++, we do not store a lookup map for the translation unit.
3709 // Instead, mark it as needing a lookup map to be built if this module
3710 // contains any declarations lexically within it (which it always does!).
3711 // This usually has no cost, since we very rarely need the lookup map for
3712 // the translation unit outside C++.
3713 if (ASTContext *Ctx = ContextObj) {
3714 DeclContext *DC = Ctx->getTranslationUnitDecl();
3715 if (DC->hasExternalLexicalStorage() && !Ctx->getLangOpts().CPlusPlus)
3717 }
3718
3719 return llvm::Error::success();
3720 case llvm::BitstreamEntry::SubBlock:
3721 switch (Entry.ID) {
3722 case DECLTYPES_BLOCK_ID:
3723 // We lazily load the decls block, but we want to set up the
3724 // DeclsCursor cursor to point into it. Clone our current bitcode
3725 // cursor to it, enter the block and read the abbrevs in that block.
3726 // With the main cursor, we just skip over it.
3727 F.DeclsCursor = Stream;
3728 if (llvm::Error Err = Stream.SkipBlock())
3729 return Err;
3730 if (llvm::Error Err = ReadBlockAbbrevs(
3732 return Err;
3733 break;
3734
3736 F.MacroCursor = Stream;
3737 if (!PP.getExternalSource())
3738 PP.setExternalSource(this);
3739
3740 if (llvm::Error Err = Stream.SkipBlock())
3741 return Err;
3742 if (llvm::Error Err =
3743 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID))
3744 return Err;
3745 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
3746 break;
3747
3749 F.PreprocessorDetailCursor = Stream;
3750
3751 if (llvm::Error Err = Stream.SkipBlock()) {
3752 return Err;
3753 }
3754 if (llvm::Error Err = ReadBlockAbbrevs(F.PreprocessorDetailCursor,
3756 return Err;
3758 = F.PreprocessorDetailCursor.GetCurrentBitNo();
3759
3760 if (!PP.getPreprocessingRecord())
3761 PP.createPreprocessingRecord();
3762 if (!PP.getPreprocessingRecord()->getExternalSource())
3763 PP.getPreprocessingRecord()->SetExternalSource(*this);
3764 break;
3765
3767 if (llvm::Error Err = ReadSourceManagerBlock(F))
3768 return Err;
3769 break;
3770
3771 case SUBMODULE_BLOCK_ID:
3772 F.SubmodulesCursor = Stream;
3773 if (llvm::Error Err = Stream.SkipBlock())
3774 return Err;
3775 if (llvm::Error Err =
3776 ReadBlockAbbrevs(F.SubmodulesCursor, SUBMODULE_BLOCK_ID))
3777 return Err;
3778 F.SubmodulesOffsetBase = F.SubmodulesCursor.GetCurrentBitNo();
3779 break;
3780
3781 case COMMENTS_BLOCK_ID: {
3782 BitstreamCursor C = Stream;
3783
3784 if (llvm::Error Err = Stream.SkipBlock())
3785 return Err;
3786 if (llvm::Error Err = ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID))
3787 return Err;
3788 CommentsCursors.push_back(std::make_pair(C, &F));
3789 break;
3790 }
3791
3792 default:
3793 if (llvm::Error Err = Stream.SkipBlock())
3794 return Err;
3795 break;
3796 }
3797 continue;
3798
3799 case llvm::BitstreamEntry::Record:
3800 // The interesting case.
3801 break;
3802 }
3803
3804 // Read and process a record.
3805 Record.clear();
3806 StringRef Blob;
3807 Expected<unsigned> MaybeRecordType =
3808 Stream.readRecord(Entry.ID, Record, &Blob);
3809 if (!MaybeRecordType)
3810 return MaybeRecordType.takeError();
3811 ASTRecordTypes RecordType = (ASTRecordTypes)MaybeRecordType.get();
3812
3813 // If we're not loading an AST context, we don't care about most records.
3814 if (!ContextObj) {
3815 switch (RecordType) {
3816 case IDENTIFIER_TABLE:
3817 case IDENTIFIER_OFFSET:
3819 case STATISTICS:
3822 case PP_COUNTER_VALUE:
3824 case MODULE_OFFSET_MAP:
3828 case IMPORTED_MODULES:
3829 case MACRO_OFFSET:
3830 case SUBMODULE_METADATA:
3831 break;
3832 default:
3833 continue;
3834 }
3835 }
3836
3837 switch (RecordType) {
3838 default: // Default behavior: ignore.
3839 break;
3840
3841 case SUBMODULE_METADATA: {
3842 F.BaseSubmoduleID = getTotalNumSubmodules();
3847 (const llvm::support::unaligned_uint64_t *)Blob.data();
3848 if (F.LocalNumSubmodules > 0) {
3849 // Introduce the global -> local mapping for submodules within this
3850 // module.
3851 GlobalSubmoduleMap.insert(
3852 std::make_pair(getTotalNumSubmodules() + 1, &F));
3853
3854 // Introduce the local -> global mapping for submodules within this
3855 // module.
3857 std::make_pair(F.LocalBaseSubmoduleID,
3859
3860 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
3861 }
3862
3863 auto ReadSubmodule = [&](unsigned LocalID) -> Module * {
3864 return getSubmodule(getGlobalSubmoduleID(F, LocalID));
3865 };
3866
3867 if (PP.getHeaderSearchInfo().getModuleMap().findModule(F.ModuleName)) {
3868 // If we already knew about this module, make sure to bring all
3869 // submodules up to date.
3870 for (unsigned Index = 0; Index != F.LocalNumSubmodules; ++Index) {
3871 unsigned LocalID =
3873 ReadSubmodule(LocalID);
3874 }
3875 } else {
3876 // If we didn't know this module, we loaded it transitively. Deserialize
3877 // just the top-level module to register it with ModuleMap, but load the
3878 // rest lazily.
3879 ReadSubmodule(F.LocalTopLevelSubmoduleID);
3880 }
3881
3882 break;
3883 }
3884
3885 case TYPE_OFFSET: {
3886 if (F.LocalNumTypes != 0)
3887 return llvm::createStringError(
3888 std::errc::illegal_byte_sequence,
3889 "duplicate TYPE_OFFSET record in AST file");
3890 F.TypeOffsets = reinterpret_cast<const UnalignedUInt64 *>(Blob.data());
3891 F.LocalNumTypes = Record[0];
3892 F.BaseTypeIndex = getTotalNumTypes();
3893
3894 if (F.LocalNumTypes > 0)
3895 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
3896
3897 break;
3898 }
3899
3900 case DECL_OFFSET: {
3901 if (F.LocalNumDecls != 0)
3902 return llvm::createStringError(
3903 std::errc::illegal_byte_sequence,
3904 "duplicate DECL_OFFSET record in AST file");
3905 F.DeclOffsets = (const DeclOffset *)Blob.data();
3906 F.LocalNumDecls = Record[0];
3907 F.BaseDeclIndex = getTotalNumDecls();
3908
3909 if (F.LocalNumDecls > 0)
3910 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
3911
3912 break;
3913 }
3914
3915 case TU_UPDATE_LEXICAL: {
3916 DeclContext *TU = ContextObj->getTranslationUnitDecl();
3917 LexicalContents Contents(
3918 reinterpret_cast<const unaligned_decl_id_t *>(Blob.data()),
3919 static_cast<unsigned int>(Blob.size() / sizeof(DeclID)));
3920 TULexicalDecls.push_back(std::make_pair(&F, Contents));
3922 break;
3923 }
3924
3925 case UPDATE_VISIBLE: {
3926 unsigned Idx = 0;
3927 GlobalDeclID ID = ReadDeclID(F, Record, Idx);
3928 auto *Data = (const unsigned char*)Blob.data();
3929 PendingVisibleUpdates[ID].push_back(UpdateData{&F, Data});
3930 // If we've already loaded the decl, perform the updates when we finish
3931 // loading this block.
3932 if (Decl *D = GetExistingDecl(ID))
3933 PendingUpdateRecords.push_back(
3934 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3935 break;
3936 }
3937
3939 unsigned Idx = 0;
3940 GlobalDeclID ID = ReadDeclID(F, Record, Idx);
3941 auto *Data = (const unsigned char *)Blob.data();
3942 PendingModuleLocalVisibleUpdates[ID].push_back(UpdateData{&F, Data});
3943 // If we've already loaded the decl, perform the updates when we finish
3944 // loading this block.
3945 if (Decl *D = GetExistingDecl(ID))
3946 PendingUpdateRecords.push_back(
3947 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3948 break;
3949 }
3950
3952 if (F.Kind != MK_MainFile)
3953 break;
3954 unsigned Idx = 0;
3955 GlobalDeclID ID = ReadDeclID(F, Record, Idx);
3956 auto *Data = (const unsigned char *)Blob.data();
3957 TULocalUpdates[ID].push_back(UpdateData{&F, Data});
3958 // If we've already loaded the decl, perform the updates when we finish
3959 // loading this block.
3960 if (Decl *D = GetExistingDecl(ID))
3961 PendingUpdateRecords.push_back(
3962 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3963 break;
3964 }
3965
3967 unsigned Idx = 0;
3968 GlobalDeclID ID = ReadDeclID(F, Record, Idx);
3969 auto *Data = (const unsigned char *)Blob.data();
3970 PendingSpecializationsUpdates[ID].push_back(UpdateData{&F, Data});
3971 // If we've already loaded the decl, perform the updates when we finish
3972 // loading this block.
3973 if (Decl *D = GetExistingDecl(ID))
3974 PendingUpdateRecords.push_back(
3975 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3976 break;
3977 }
3978
3980 unsigned Idx = 0;
3981 GlobalDeclID ID = ReadDeclID(F, Record, Idx);
3982 auto *Data = (const unsigned char *)Blob.data();
3983 PendingPartialSpecializationsUpdates[ID].push_back(UpdateData{&F, Data});
3984 // If we've already loaded the decl, perform the updates when we finish
3985 // loading this block.
3986 if (Decl *D = GetExistingDecl(ID))
3987 PendingUpdateRecords.push_back(
3988 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3989 break;
3990 }
3991
3992 case IDENTIFIER_TABLE:
3994 reinterpret_cast<const unsigned char *>(Blob.data());
3995 if (Record[0]) {
3996 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
3998 F.IdentifierTableData + sizeof(uint32_t),
4000 ASTIdentifierLookupTrait(*this, F));
4001
4002 PP.getIdentifierTable().setExternalIdentifierLookup(this);
4003 }
4004 break;
4005
4006 case IDENTIFIER_OFFSET: {
4007 if (F.LocalNumIdentifiers != 0)
4008 return llvm::createStringError(
4009 std::errc::illegal_byte_sequence,
4010 "duplicate IDENTIFIER_OFFSET record in AST file");
4011 F.IdentifierOffsets = (const uint32_t *)Blob.data();
4013 F.BaseIdentifierID = getTotalNumIdentifiers();
4014
4015 if (F.LocalNumIdentifiers > 0)
4016 IdentifiersLoaded.resize(IdentifiersLoaded.size()
4018 break;
4019 }
4020
4022 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
4023 break;
4024
4026 // FIXME: Skip reading this record if our ASTConsumer doesn't care
4027 // about "interesting" decls (for instance, if we're building a module).
4028 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4029 EagerlyDeserializedDecls.push_back(ReadDeclID(F, Record, I));
4030 break;
4031
4033 // FIXME: Skip reading this record if our ASTConsumer doesn't care about
4034 // them (ie: if we're not codegenerating this module).
4035 if (F.Kind == MK_MainFile ||
4036 getContext().getLangOpts().BuildingPCHWithObjectFile)
4037 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4038 EagerlyDeserializedDecls.push_back(ReadDeclID(F, Record, I));
4039 break;
4040
4041 case SPECIAL_TYPES:
4042 if (SpecialTypes.empty()) {
4043 for (unsigned I = 0, N = Record.size(); I != N; ++I)
4044 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
4045 break;
4046 }
4047
4048 if (Record.empty())
4049 break;
4050
4051 if (SpecialTypes.size() != Record.size())
4052 return llvm::createStringError(std::errc::illegal_byte_sequence,
4053 "invalid special-types record");
4054
4055 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
4056 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
4057 if (!SpecialTypes[I])
4058 SpecialTypes[I] = ID;
4059 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
4060 // merge step?
4061 }
4062 break;
4063
4064 case STATISTICS:
4065 TotalNumStatements += Record[0];
4066 TotalNumMacros += Record[1];
4067 TotalLexicalDeclContexts += Record[2];
4068 TotalVisibleDeclContexts += Record[3];
4069 TotalModuleLocalVisibleDeclContexts += Record[4];
4070 TotalTULocalVisibleDeclContexts += Record[5];
4071 break;
4072
4074 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4075 UnusedFileScopedDecls.push_back(ReadDeclID(F, Record, I));
4076 break;
4077
4078 case DELEGATING_CTORS:
4079 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4080 DelegatingCtorDecls.push_back(ReadDeclID(F, Record, I));
4081 break;
4082
4084 if (Record.size() % 3 != 0)
4085 return llvm::createStringError(std::errc::illegal_byte_sequence,
4086 "invalid weak identifiers record");
4087
4088 // FIXME: Ignore weak undeclared identifiers from non-original PCH
4089 // files. This isn't the way to do it :)
4090 WeakUndeclaredIdentifiers.clear();
4091
4092 // Translate the weak, undeclared identifiers into global IDs.
4093 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
4094 WeakUndeclaredIdentifiers.push_back(
4095 getGlobalIdentifierID(F, Record[I++]));
4096 WeakUndeclaredIdentifiers.push_back(
4097 getGlobalIdentifierID(F, Record[I++]));
4098 WeakUndeclaredIdentifiers.push_back(
4099 ReadSourceLocation(F, Record, I).getRawEncoding());
4100 }
4101 break;
4102
4104 if (Record.size() % 3 != 0)
4105 return llvm::createStringError(std::errc::illegal_byte_sequence,
4106 "invalid extname identifiers record");
4107
4108 // FIXME: Ignore #pragma redefine_extname'd, undeclared identifiers from
4109 // non-original PCH files. This isn't the way to do it :)
4110 ExtnameUndeclaredIdentifiers.clear();
4111
4112 // Translate the #pragma redefine_extname'd, undeclared identifiers into
4113 // global IDs.
4114 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
4115 ExtnameUndeclaredIdentifiers.push_back(
4116 getGlobalIdentifierID(F, Record[I++]));
4117 ExtnameUndeclaredIdentifiers.push_back(
4118 getGlobalIdentifierID(F, Record[I++]));
4119 ExtnameUndeclaredIdentifiers.push_back(
4120 ReadSourceLocation(F, Record, I).getRawEncoding());
4121 }
4122 break;
4123
4124 case SELECTOR_OFFSETS: {
4125 F.SelectorOffsets = (const uint32_t *)Blob.data();
4127 unsigned LocalBaseSelectorID = Record[1];
4128 F.BaseSelectorID = getTotalNumSelectors();
4129
4130 if (F.LocalNumSelectors > 0) {
4131 // Introduce the global -> local mapping for selectors within this
4132 // module.
4133 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
4134
4135 // Introduce the local -> global mapping for selectors within this
4136 // module.
4138 std::make_pair(LocalBaseSelectorID,
4139 F.BaseSelectorID - LocalBaseSelectorID));
4140
4141 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
4142 }
4143 break;
4144 }
4145
4146 case METHOD_POOL:
4147 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
4148 if (Record[0])
4150 = ASTSelectorLookupTable::Create(
4153 ASTSelectorLookupTrait(*this, F));
4154 TotalNumMethodPoolEntries += Record[1];
4155 break;
4156
4158 if (!Record.empty()) {
4159 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
4160 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
4161 Record[Idx++]));
4162 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
4163 getRawEncoding());
4164 }
4165 }
4166 break;
4167
4168 case PP_ASSUME_NONNULL_LOC: {
4169 unsigned Idx = 0;
4170 if (!Record.empty())
4171 PP.setPreambleRecordedPragmaAssumeNonNullLoc(
4172 ReadSourceLocation(F, Record, Idx));
4173 break;
4174 }
4175
4177 if (!Record.empty()) {
4178 SmallVector<SourceLocation, 64> SrcLocs;
4179 unsigned Idx = 0;
4180 while (Idx < Record.size())
4181 SrcLocs.push_back(ReadSourceLocation(F, Record, Idx));
4182 PP.setDeserializedSafeBufferOptOutMap(SrcLocs);
4183 }
4184 break;
4185 }
4186
4188 if (!Record.empty()) {
4189 unsigned Idx = 0, End = Record.size() - 1;
4190 bool ReachedEOFWhileSkipping = Record[Idx++];
4191 std::optional<Preprocessor::PreambleSkipInfo> SkipInfo;
4192 if (ReachedEOFWhileSkipping) {
4193 SourceLocation HashToken = ReadSourceLocation(F, Record, Idx);
4194 SourceLocation IfTokenLoc = ReadSourceLocation(F, Record, Idx);
4195 bool FoundNonSkipPortion = Record[Idx++];
4196 bool FoundElse = Record[Idx++];
4197 SourceLocation ElseLoc = ReadSourceLocation(F, Record, Idx);
4198 SkipInfo.emplace(HashToken, IfTokenLoc, FoundNonSkipPortion,
4199 FoundElse, ElseLoc);
4200 }
4201 SmallVector<PPConditionalInfo, 4> ConditionalStack;
4202 while (Idx < End) {
4203 auto Loc = ReadSourceLocation(F, Record, Idx);
4204 bool WasSkipping = Record[Idx++];
4205 bool FoundNonSkip = Record[Idx++];
4206 bool FoundElse = Record[Idx++];
4207 ConditionalStack.push_back(
4208 {Loc, WasSkipping, FoundNonSkip, FoundElse});
4209 }
4210 PP.setReplayablePreambleConditionalStack(ConditionalStack, SkipInfo);
4211 }
4212 break;
4213
4214 case PP_COUNTER_VALUE:
4215 if (!Record.empty() && Listener)
4216 Listener->ReadCounter(F, Record[0]);
4217 break;
4218
4219 case FILE_SORTED_DECLS:
4220 F.FileSortedDecls = (const unaligned_decl_id_t *)Blob.data();
4222 break;
4223
4225 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
4227 SourceLocation::UIntTy SLocSpaceSize = Record[1];
4229 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
4230 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
4231 SLocSpaceSize);
4232 if (!F.SLocEntryBaseID) {
4233 Diags.Report(SourceLocation(), diag::remark_sloc_usage);
4234 SourceMgr.noteSLocAddressSpaceUsage(Diags);
4235 return llvm::createStringError(std::errc::invalid_argument,
4236 "ran out of source locations");
4237 }
4238 // Make our entry in the range map. BaseID is negative and growing, so
4239 // we invert it. Because we invert it, though, we need the other end of
4240 // the range.
4241 unsigned RangeStart =
4242 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
4243 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
4245
4246 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
4247 assert((F.SLocEntryBaseOffset & SourceLocation::MacroIDBit) == 0);
4248 GlobalSLocOffsetMap.insert(
4249 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
4250 - SLocSpaceSize,&F));
4251
4252 TotalNumSLocEntries += F.LocalNumSLocEntries;
4253 break;
4254 }
4255
4256 case MODULE_OFFSET_MAP:
4257 F.ModuleOffsetMap = Blob;
4258 break;
4259
4261 ParseLineTable(F, Record);
4262 break;
4263
4264 case EXT_VECTOR_DECLS:
4265 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4266 ExtVectorDecls.push_back(ReadDeclID(F, Record, I));
4267 break;
4268
4269 case VTABLE_USES:
4270 if (Record.size() % 3 != 0)
4271 return llvm::createStringError(std::errc::illegal_byte_sequence,
4272 "Invalid VTABLE_USES record");
4273
4274 // Later tables overwrite earlier ones.
4275 // FIXME: Modules will have some trouble with this. This is clearly not
4276 // the right way to do this.
4277 VTableUses.clear();
4278
4279 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
4280 VTableUses.push_back(
4281 {ReadDeclID(F, Record, Idx),
4282 ReadSourceLocation(F, Record, Idx).getRawEncoding(),
4283 (bool)Record[Idx++]});
4284 }
4285 break;
4286
4288
4289 if (Record.size() % 2 != 0)
4290 return llvm::createStringError(
4291 std::errc::illegal_byte_sequence,
4292 "Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
4293
4294 // For standard C++20 module, we will only reads the instantiations
4295 // if it is the main file.
4296 if (!F.StandardCXXModule || F.Kind == MK_MainFile) {
4297 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
4298 PendingInstantiations.push_back(
4299 {ReadDeclID(F, Record, I),
4300 ReadSourceLocation(F, Record, I).getRawEncoding()});
4301 }
4302 }
4303 break;
4304
4305 case SEMA_DECL_REFS:
4306 if (Record.size() != 3)
4307 return llvm::createStringError(std::errc::illegal_byte_sequence,
4308 "Invalid SEMA_DECL_REFS block");
4309 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4310 SemaDeclRefs.push_back(ReadDeclID(F, Record, I));
4311 break;
4312
4313 case PPD_ENTITIES_OFFSETS: {
4314 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
4315 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
4316 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
4317
4318 unsigned StartingID;
4319 if (!PP.getPreprocessingRecord())
4320 PP.createPreprocessingRecord();
4321 if (!PP.getPreprocessingRecord()->getExternalSource())
4322 PP.getPreprocessingRecord()->SetExternalSource(*this);
4323 StartingID
4324 = PP.getPreprocessingRecord()
4325 ->allocateLoadedEntities(F.NumPreprocessedEntities);
4326 F.BasePreprocessedEntityID = StartingID;
4327
4328 if (F.NumPreprocessedEntities > 0) {
4329 // Introduce the global -> local mapping for preprocessed entities in
4330 // this module.
4331 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
4332 }
4333
4334 break;
4335 }
4336
4337 case PPD_SKIPPED_RANGES: {
4338 F.PreprocessedSkippedRangeOffsets = (const PPSkippedRange*)Blob.data();
4339 assert(Blob.size() % sizeof(PPSkippedRange) == 0);
4340 F.NumPreprocessedSkippedRanges = Blob.size() / sizeof(PPSkippedRange);
4341
4342 if (!PP.getPreprocessingRecord())
4343 PP.createPreprocessingRecord();
4344 if (!PP.getPreprocessingRecord()->getExternalSource())
4345 PP.getPreprocessingRecord()->SetExternalSource(*this);
4346 F.BasePreprocessedSkippedRangeID = PP.getPreprocessingRecord()
4347 ->allocateSkippedRanges(F.NumPreprocessedSkippedRanges);
4348
4350 GlobalSkippedRangeMap.insert(
4351 std::make_pair(F.BasePreprocessedSkippedRangeID, &F));
4352 break;
4353 }
4354
4356 if (Record.size() % 2 != 0)
4357 return llvm::createStringError(
4358 std::errc::illegal_byte_sequence,
4359 "invalid DECL_UPDATE_OFFSETS block in AST file");
4360 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/) {
4361 GlobalDeclID ID = ReadDeclID(F, Record, I);
4362 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I++]));
4363
4364 // If we've already loaded the decl, perform the updates when we finish
4365 // loading this block.
4366 if (Decl *D = GetExistingDecl(ID))
4367 PendingUpdateRecords.push_back(
4368 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
4369 }
4370 break;
4371
4373 if (Record.size() % 5 != 0)
4374 return llvm::createStringError(
4375 std::errc::illegal_byte_sequence,
4376 "invalid DELAYED_NAMESPACE_LEXICAL_VISIBLE_RECORD block in AST "
4377 "file");
4378 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/) {
4379 GlobalDeclID ID = ReadDeclID(F, Record, I);
4380
4381 uint64_t BaseOffset = F.DeclsBlockStartOffset;
4382 assert(BaseOffset && "Invalid DeclsBlockStartOffset for module file!");
4383 uint64_t LocalLexicalOffset = Record[I++];
4384 uint64_t LexicalOffset =
4385 LocalLexicalOffset ? BaseOffset + LocalLexicalOffset : 0;
4386 uint64_t LocalVisibleOffset = Record[I++];
4387 uint64_t VisibleOffset =
4388 LocalVisibleOffset ? BaseOffset + LocalVisibleOffset : 0;
4389 uint64_t LocalModuleLocalOffset = Record[I++];
4390 uint64_t ModuleLocalOffset =
4391 LocalModuleLocalOffset ? BaseOffset + LocalModuleLocalOffset : 0;
4392 uint64_t TULocalLocalOffset = Record[I++];
4393 uint64_t TULocalOffset =
4394 TULocalLocalOffset ? BaseOffset + TULocalLocalOffset : 0;
4395
4396 DelayedNamespaceOffsetMap[ID] = {
4397 {VisibleOffset, ModuleLocalOffset, TULocalOffset}, LexicalOffset};
4398
4399 assert(!GetExistingDecl(ID) &&
4400 "We shouldn't load the namespace in the front of delayed "
4401 "namespace lexical and visible block");
4402 }
4403 break;
4404 }
4405
4406 case RELATED_DECLS_MAP:
4407 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/) {
4408 GlobalDeclID ID = ReadDeclID(F, Record, I);
4409 auto &RelatedDecls = RelatedDeclsMap[ID];
4410 unsigned NN = Record[I++];
4411 RelatedDecls.reserve(NN);
4412 for (unsigned II = 0; II < NN; II++)
4413 RelatedDecls.push_back(ReadDeclID(F, Record, I));
4414 }
4415 break;
4416
4418 if (F.LocalNumObjCCategoriesInMap != 0)
4419 return llvm::createStringError(
4420 std::errc::illegal_byte_sequence,
4421 "duplicate OBJC_CATEGORIES_MAP record in AST file");
4422
4424 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
4425 break;
4426
4427 case OBJC_CATEGORIES:
4428 F.ObjCCategories.swap(Record);
4429 break;
4430
4432 // Later tables overwrite earlier ones.
4433 // FIXME: Modules will have trouble with this.
4434 CUDASpecialDeclRefs.clear();
4435 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4436 CUDASpecialDeclRefs.push_back(ReadDeclID(F, Record, I));
4437 break;
4438
4440 F.HeaderFileInfoTableData = Blob.data();
4442 if (Record[0]) {
4443 F.HeaderFileInfoTable = HeaderFileInfoLookupTable::Create(
4444 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
4445 (const unsigned char *)F.HeaderFileInfoTableData,
4446 HeaderFileInfoTrait(*this, F));
4447
4448 PP.getHeaderSearchInfo().SetExternalSource(this);
4449 if (!PP.getHeaderSearchInfo().getExternalLookup())
4450 PP.getHeaderSearchInfo().SetExternalLookup(this);
4451 }
4452 break;
4453
4454 case FP_PRAGMA_OPTIONS:
4455 // Later tables overwrite earlier ones.
4456 FPPragmaOptions.swap(Record);
4457 break;
4458
4460 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4461 DeclsWithEffectsToVerify.push_back(ReadDeclID(F, Record, I));
4462 break;
4463
4464 case OPENCL_EXTENSIONS:
4465 for (unsigned I = 0, E = Record.size(); I != E; ) {
4466 auto Name = ReadString(Record, I);
4467 auto &OptInfo = OpenCLExtensions.OptMap[Name];
4468 OptInfo.Supported = Record[I++] != 0;
4469 OptInfo.Enabled = Record[I++] != 0;
4470 OptInfo.WithPragma = Record[I++] != 0;
4471 OptInfo.Avail = Record[I++];
4472 OptInfo.Core = Record[I++];
4473 OptInfo.Opt = Record[I++];
4474 }
4475 break;
4476
4478 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4479 TentativeDefinitions.push_back(ReadDeclID(F, Record, I));
4480 break;
4481
4482 case KNOWN_NAMESPACES:
4483 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4484 KnownNamespaces.push_back(ReadDeclID(F, Record, I));
4485 break;
4486
4487 case UNDEFINED_BUT_USED:
4488 if (Record.size() % 2 != 0)
4489 return llvm::createStringError(std::errc::illegal_byte_sequence,
4490 "invalid undefined-but-used record");
4491 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
4492 UndefinedButUsed.push_back(
4493 {ReadDeclID(F, Record, I),
4494 ReadSourceLocation(F, Record, I).getRawEncoding()});
4495 }
4496 break;
4497
4499 for (unsigned I = 0, N = Record.size(); I != N;) {
4500 DelayedDeleteExprs.push_back(ReadDeclID(F, Record, I).getRawValue());
4501 const uint64_t Count = Record[I++];
4502 DelayedDeleteExprs.push_back(Count);
4503 for (uint64_t C = 0; C < Count; ++C) {
4504 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
4505 bool IsArrayForm = Record[I++] == 1;
4506 DelayedDeleteExprs.push_back(IsArrayForm);
4507 }
4508 }
4509 break;
4510
4511 case VTABLES_TO_EMIT:
4512 if (F.Kind == MK_MainFile ||
4513 getContext().getLangOpts().BuildingPCHWithObjectFile)
4514 for (unsigned I = 0, N = Record.size(); I != N;)
4515 VTablesToEmit.push_back(ReadDeclID(F, Record, I));
4516 break;
4517
4518 case IMPORTED_MODULES:
4519 if (!F.isModule()) {
4520 // If we aren't loading a module (which has its own exports), make
4521 // all of the imported modules visible.
4522 // FIXME: Deal with macros-only imports.
4523 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
4524 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
4525 SourceLocation Loc = ReadSourceLocation(F, Record, I);
4526 if (GlobalID) {
4527 PendingImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
4528 if (DeserializationListener)
4529 DeserializationListener->ModuleImportRead(GlobalID, Loc);
4530 }
4531 }
4532 }
4533 break;
4534
4535 case MACRO_OFFSET: {
4536 if (F.LocalNumMacros != 0)
4537 return llvm::createStringError(
4538 std::errc::illegal_byte_sequence,
4539 "duplicate MACRO_OFFSET record in AST file");
4540 F.MacroOffsets = (const uint32_t *)Blob.data();
4541 F.LocalNumMacros = Record[0];
4543 F.BaseMacroID = getTotalNumMacros();
4544
4545 if (F.LocalNumMacros > 0)
4546 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
4547 break;
4548 }
4549
4551 LateParsedTemplates.emplace_back(
4552 std::piecewise_construct, std::forward_as_tuple(&F),
4553 std::forward_as_tuple(Record.begin(), Record.end()));
4554 break;
4555
4557 if (Record.size() != 1)
4558 return llvm::createStringError(std::errc::illegal_byte_sequence,
4559 "invalid pragma optimize record");
4560 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
4561 break;
4562
4564 if (Record.size() != 1)
4565 return llvm::createStringError(std::errc::illegal_byte_sequence,
4566 "invalid pragma ms_struct record");
4567 PragmaMSStructState = Record[0];
4568 break;
4569
4571 if (Record.size() != 2)
4572 return llvm::createStringError(
4573 std::errc::illegal_byte_sequence,
4574 "invalid pragma pointers to members record");
4575 PragmaMSPointersToMembersState = Record[0];
4576 PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]);
4577 break;
4578
4580 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4581 UnusedLocalTypedefNameCandidates.push_back(ReadDeclID(F, Record, I));
4582 break;
4583
4585 if (Record.size() != 1)
4586 return llvm::createStringError(std::errc::illegal_byte_sequence,
4587 "invalid cuda pragma options record");
4588 ForceHostDeviceDepth = Record[0];
4589 break;
4590
4592 if (Record.size() < 3)
4593 return llvm::createStringError(std::errc::illegal_byte_sequence,
4594 "invalid pragma pack record");
4595 PragmaAlignPackCurrentValue = ReadAlignPackInfo(Record[0]);
4596 PragmaAlignPackCurrentLocation = ReadSourceLocation(F, Record[1]);
4597 unsigned NumStackEntries = Record[2];
4598 unsigned Idx = 3;
4599 // Reset the stack when importing a new module.
4600 PragmaAlignPackStack.clear();
4601 for (unsigned I = 0; I < NumStackEntries; ++I) {
4602 PragmaAlignPackStackEntry Entry;
4603 Entry.Value = ReadAlignPackInfo(Record[Idx++]);
4604 Entry.Location = ReadSourceLocation(F, Record[Idx++]);
4605 Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]);
4606 PragmaAlignPackStrings.push_back(ReadString(Record, Idx));
4607 Entry.SlotLabel = PragmaAlignPackStrings.back();
4608 PragmaAlignPackStack.push_back(Entry);
4609 }
4610 break;
4611 }
4612
4614 if (Record.size() < 3)
4615 return llvm::createStringError(std::errc::illegal_byte_sequence,
4616 "invalid pragma float control record");
4617 FpPragmaCurrentValue = FPOptionsOverride::getFromOpaqueInt(Record[0]);
4618 FpPragmaCurrentLocation = ReadSourceLocation(F, Record[1]);
4619 unsigned NumStackEntries = Record[2];
4620 unsigned Idx = 3;
4621 // Reset the stack when importing a new module.
4622 FpPragmaStack.clear();
4623 for (unsigned I = 0; I < NumStackEntries; ++I) {
4624 FpPragmaStackEntry Entry;
4625 Entry.Value = FPOptionsOverride::getFromOpaqueInt(Record[Idx++]);
4626 Entry.Location = ReadSourceLocation(F, Record[Idx++]);
4627 Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]);
4628 FpPragmaStrings.push_back(ReadString(Record, Idx));
4629 Entry.SlotLabel = FpPragmaStrings.back();
4630 FpPragmaStack.push_back(Entry);
4631 }
4632 break;
4633 }
4634
4636 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4637 DeclsToCheckForDeferredDiags.insert(ReadDeclID(F, Record, I));
4638 break;
4639
4641 unsigned NumRecords = Record.front();
4642 // Last record which is used to keep number of valid records.
4643 if (Record.size() - 1 != NumRecords)
4644 return llvm::createStringError(std::errc::illegal_byte_sequence,
4645 "invalid rvv intrinsic pragma record");
4646
4647 if (RISCVVecIntrinsicPragma.empty())
4648 RISCVVecIntrinsicPragma.append(NumRecords, 0);
4649 // There might be multiple precompiled modules imported, we need to union
4650 // them all.
4651 for (unsigned i = 0; i < NumRecords; ++i)
4652 RISCVVecIntrinsicPragma[i] |= Record[i + 1];
4653 break;
4654 }
4655 }
4656 }
4657}
4658
4659void ASTReader::ReadModuleOffsetMap(ModuleFile &F) const {
4660 assert(!F.ModuleOffsetMap.empty() && "no module offset map to read");
4661
4662 // Additional remapping information.
4663 const unsigned char *Data = (const unsigned char*)F.ModuleOffsetMap.data();
4664 const unsigned char *DataEnd = Data + F.ModuleOffsetMap.size();
4665 F.ModuleOffsetMap = StringRef();
4666
4668 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
4669 RemapBuilder SelectorRemap(F.SelectorRemap);
4670
4671 auto &ImportedModuleVector = F.TransitiveImports;
4672 assert(ImportedModuleVector.empty());
4673
4674 while (Data < DataEnd) {
4675 // FIXME: Looking up dependency modules by filename is horrible. Let's
4676 // start fixing this with prebuilt, explicit and implicit modules and see
4677 // how it goes...
4678 using namespace llvm::support;
4679 ModuleKind Kind = static_cast<ModuleKind>(
4680 endian::readNext<uint8_t, llvm::endianness::little>(Data));
4681 uint16_t Len = endian::readNext<uint16_t, llvm::endianness::little>(Data);
4682 StringRef Name = StringRef((const char*)Data, Len);
4683 Data += Len;
4684 ModuleFile *OM =
4687 ? ModuleMgr.lookupByModuleName(Name)
4688 : ModuleMgr.lookupByFileName(ModuleFileName::makeExplicit(Name)));
4689 if (!OM)
4690 OM = ModuleMgr.lookupByFileName(ModuleFileName::makeInMemory(Name));
4691 if (!OM) {
4692 std::string Msg = "refers to unknown module, cannot find ";
4693 Msg.append(std::string(Name));
4694 Error(Msg);
4695 return;
4696 }
4697
4698 ImportedModuleVector.push_back(OM);
4699
4700 uint32_t SubmoduleIDOffset =
4701 endian::readNext<uint32_t, llvm::endianness::little>(Data);
4702 uint32_t SelectorIDOffset =
4703 endian::readNext<uint32_t, llvm::endianness::little>(Data);
4704
4705 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
4706 RemapBuilder &Remap) {
4707 constexpr uint32_t None = std::numeric_limits<uint32_t>::max();
4708 if (Offset != None)
4709 Remap.insert(std::make_pair(Offset,
4710 static_cast<int>(BaseOffset - Offset)));
4711 };
4712
4713 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
4714 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
4715 }
4716}
4717
4719ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
4720 const ModuleFile *ImportedBy,
4721 unsigned ClientLoadCapabilities) {
4722 unsigned Idx = 0;
4723 F.ModuleMapPath = ReadPath(F, Record, Idx);
4724
4725 // Try to resolve ModuleName in the current header search context and
4726 // verify that it is found in the same module map file as we saved. If the
4727 // top-level AST file is a main file, skip this check because there is no
4728 // usable header search context.
4729 assert(!F.ModuleName.empty() &&
4730 "MODULE_NAME should come before MODULE_MAP_FILE");
4731 auto [MaybeM, IgnoreError] =
4732 getModuleForRelocationChecks(F, /*DirectoryCheck=*/false);
4733 if (MaybeM.has_value()) {
4734 // An implicitly-loaded module file should have its module listed in some
4735 // module map file that we've already loaded.
4736 Module *M = MaybeM.value();
4737 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
4738 OptionalFileEntryRef ModMap =
4739 M ? Map.getModuleMapFileForUniquing(M) : std::nullopt;
4740 if (!IgnoreError && !ModMap) {
4741 if (M && M->Directory)
4742 Diag(diag::remark_module_relocated)
4743 << F.ModuleName << F.BaseDirectory << M->Directory->getName();
4744
4745 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities)) {
4746 if (auto ASTFileName = M ? M->getASTFileName() : nullptr) {
4747 // This module was defined by an imported (explicit) module.
4748 Diag(diag::err_module_file_conflict)
4749 << F.ModuleName << F.FileName << *ASTFileName;
4750 // TODO: Add a note with the module map paths if they differ.
4751 } else {
4752 // This module was built with a different module map.
4753 Diag(diag::err_imported_module_not_found)
4754 << F.ModuleName << F.FileName
4755 << (ImportedBy ? ImportedBy->FileName.str() : "")
4756 << F.ModuleMapPath << !ImportedBy;
4757 // In case it was imported by a PCH, there's a chance the user is
4758 // just missing to include the search path to the directory containing
4759 // the modulemap.
4760 if (ImportedBy && ImportedBy->Kind == MK_PCH)
4761 Diag(diag::note_imported_by_pch_module_not_found)
4762 << llvm::sys::path::parent_path(F.ModuleMapPath);
4763 }
4764 }
4765 return OutOfDate;
4766 }
4767
4768 assert(M && M->Name == F.ModuleName && "found module with different name");
4769
4770 // Check the primary module map file.
4771 auto StoredModMap = FileMgr.getOptionalFileRef(F.ModuleMapPath);
4772 if (!StoredModMap || *StoredModMap != ModMap) {
4773 assert(ModMap && "found module is missing module map file");
4774 assert((ImportedBy || F.Kind == MK_ImplicitModule) &&
4775 "top-level import should be verified");
4776 bool NotImported = F.Kind == MK_ImplicitModule && !ImportedBy;
4777 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4778 Diag(diag::err_imported_module_modmap_changed)
4779 << F.ModuleName << (NotImported ? F.FileName : ImportedBy->FileName)
4780 << ModMap->getName() << F.ModuleMapPath << NotImported;
4781 return OutOfDate;
4782 }
4783
4784 ModuleMap::AdditionalModMapsSet AdditionalStoredMaps;
4785 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
4786 // FIXME: we should use input files rather than storing names.
4787 std::string Filename = ReadPath(F, Record, Idx);
4788 auto SF = FileMgr.getOptionalFileRef(Filename, false, false);
4789 if (!SF) {
4790 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4791 Error("could not find file '" + Filename +"' referenced by AST file");
4792 return OutOfDate;
4793 }
4794 AdditionalStoredMaps.insert(*SF);
4795 }
4796
4797 // Check any additional module map files (e.g. module.private.modulemap)
4798 // that are not in the pcm.
4799 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
4800 for (FileEntryRef ModMap : *AdditionalModuleMaps) {
4801 // Remove files that match
4802 // Note: SmallPtrSet::erase is really remove
4803 if (!AdditionalStoredMaps.erase(ModMap)) {
4804 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4805 Diag(diag::err_module_different_modmap)
4806 << F.ModuleName << /*new*/0 << ModMap.getName();
4807 return OutOfDate;
4808 }
4809 }
4810 }
4811
4812 // Check any additional module map files that are in the pcm, but not
4813 // found in header search. Cases that match are already removed.
4814 for (FileEntryRef ModMap : AdditionalStoredMaps) {
4815 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4816 Diag(diag::err_module_different_modmap)
4817 << F.ModuleName << /*not new*/1 << ModMap.getName();
4818 return OutOfDate;
4819 }
4820 }
4821
4822 if (Listener)
4823 Listener->ReadModuleMapFile(F.ModuleMapPath);
4824 return Success;
4825}
4826
4827/// Move the given method to the back of the global list of methods.
4829 // Find the entry for this selector in the method pool.
4830 SemaObjC::GlobalMethodPool::iterator Known =
4831 S.ObjC().MethodPool.find(Method->getSelector());
4832 if (Known == S.ObjC().MethodPool.end())
4833 return;
4834
4835 // Retrieve the appropriate method list.
4836 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
4837 : Known->second.second;
4838 bool Found = false;
4839 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
4840 if (!Found) {
4841 if (List->getMethod() == Method) {
4842 Found = true;
4843 } else {
4844 // Keep searching.
4845 continue;
4846 }
4847 }
4848
4849 if (List->getNext())
4850 List->setMethod(List->getNext()->getMethod());
4851 else
4852 List->setMethod(Method);
4853 }
4854}
4855
4856void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
4857 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
4858 for (Decl *D : Names) {
4859 bool wasHidden = !D->isUnconditionallyVisible();
4861
4862 if (wasHidden && SemaObj) {
4863 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
4865 }
4866 }
4867 }
4868}
4869
4871 Module::NameVisibilityKind NameVisibility,
4872 SourceLocation ImportLoc) {
4875 Stack.push_back(Mod);
4876 while (!Stack.empty()) {
4877 Mod = Stack.pop_back_val();
4878
4879 if (NameVisibility <= Mod->NameVisibility) {
4880 // This module already has this level of visibility (or greater), so
4881 // there is nothing more to do.
4882 continue;
4883 }
4884
4885 if (Mod->isUnimportable()) {
4886 // Modules that aren't importable cannot be made visible.
4887 continue;
4888 }
4889
4890 // Update the module's name visibility.
4891 Mod->NameVisibility = NameVisibility;
4892
4893 // If we've already deserialized any names from this module,
4894 // mark them as visible.
4895 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
4896 if (Hidden != HiddenNamesMap.end()) {
4897 auto HiddenNames = std::move(*Hidden);
4898 HiddenNamesMap.erase(Hidden);
4899 makeNamesVisible(HiddenNames.second, HiddenNames.first);
4900 assert(!HiddenNamesMap.contains(Mod) &&
4901 "making names visible added hidden names");
4902 }
4903
4904 // Push any exported modules onto the stack to be marked as visible.
4906 Mod->getExportedModules(Exports);
4908 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
4909 Module *Exported = *I;
4910 if (Visited.insert(Exported).second)
4911 Stack.push_back(Exported);
4912 }
4913 }
4914}
4915
4916/// We've merged the definition \p MergedDef into the existing definition
4917/// \p Def. Ensure that \p Def is made visible whenever \p MergedDef is made
4918/// visible.
4920 NamedDecl *MergedDef) {
4921 if (!Def->isUnconditionallyVisible()) {
4922 // If MergedDef is visible or becomes visible, make the definition visible.
4923 if (MergedDef->isUnconditionallyVisible())
4925 else {
4926 getContext().mergeDefinitionIntoModule(
4927 Def, MergedDef->getImportedOwningModule(),
4928 /*NotifyListeners*/ false);
4929 PendingMergedDefinitionsToDeduplicate.insert(Def);
4930 }
4931 }
4932}
4933
4935 if (GlobalIndex)
4936 return false;
4937
4938 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
4939 !PP.getLangOpts().Modules)
4940 return true;
4941
4942 // Try to load the global index.
4943 TriedLoadingGlobalIndex = true;
4944 StringRef SpecificModuleCachePath =
4945 getPreprocessor().getHeaderSearchInfo().getSpecificModuleCachePath();
4946 std::pair<GlobalModuleIndex *, llvm::Error> Result =
4947 GlobalModuleIndex::readIndex(SpecificModuleCachePath);
4948 if (llvm::Error Err = std::move(Result.second)) {
4949 assert(!Result.first);
4950 consumeError(std::move(Err)); // FIXME this drops errors on the floor.
4951 return true;
4952 }
4953
4954 GlobalIndex.reset(Result.first);
4955 ModuleMgr.setGlobalIndex(GlobalIndex.get());
4956 return false;
4957}
4958
4960 return PP.getLangOpts().Modules && UseGlobalIndex &&
4961 !hasGlobalIndex() && TriedLoadingGlobalIndex;
4962}
4963
4964/// Given a cursor at the start of an AST file, scan ahead and drop the
4965/// cursor into the start of the given block ID, returning false on success and
4966/// true on failure.
4967static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
4968 while (true) {
4969 Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
4970 if (!MaybeEntry) {
4971 // FIXME this drops errors on the floor.
4972 consumeError(MaybeEntry.takeError());
4973 return true;
4974 }
4975 llvm::BitstreamEntry Entry = MaybeEntry.get();
4976
4977 switch (Entry.Kind) {
4978 case llvm::BitstreamEntry::Error:
4979 case llvm::BitstreamEntry::EndBlock:
4980 return true;
4981
4982 case llvm::BitstreamEntry::Record:
4983 // Ignore top-level records.
4984 if (Expected<unsigned> Skipped = Cursor.skipRecord(Entry.ID))
4985 break;
4986 else {
4987 // FIXME this drops errors on the floor.
4988 consumeError(Skipped.takeError());
4989 return true;
4990 }
4991
4992 case llvm::BitstreamEntry::SubBlock:
4993 if (Entry.ID == BlockID) {
4994 if (llvm::Error Err = Cursor.EnterSubBlock(BlockID)) {
4995 // FIXME this drops the error on the floor.
4996 consumeError(std::move(Err));
4997 return true;
4998 }
4999 // Found it!
5000 return false;
5001 }
5002
5003 if (llvm::Error Err = Cursor.SkipBlock()) {
5004 // FIXME this drops the error on the floor.
5005 consumeError(std::move(Err));
5006 return true;
5007 }
5008 }
5009 }
5010}
5011
5014 SourceLocation ImportLoc,
5015 unsigned ClientLoadCapabilities,
5016 ModuleFile **NewLoadedModuleFile) {
5017 llvm::TimeTraceScope scope("ReadAST", FileName);
5018
5019 llvm::SaveAndRestore SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
5021 CurrentDeserializingModuleKind, Type);
5022
5023 // Defer any pending actions until we get to the end of reading the AST file.
5024 Deserializing AnASTFile(this);
5025
5026 // Bump the generation number.
5027 unsigned PreviousGeneration = 0;
5028 if (ContextObj)
5029 PreviousGeneration = incrementGeneration(*ContextObj);
5030
5031 unsigned NumModules = ModuleMgr.size();
5033 if (ASTReadResult ReadResult =
5034 ReadASTCore(FileName, Type, ImportLoc,
5035 /*ImportedBy=*/nullptr, Loaded, 0, 0, ASTFileSignature(),
5036 ClientLoadCapabilities)) {
5037 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules);
5038
5039 // If we find that any modules are unusable, the global index is going
5040 // to be out-of-date. Just remove it.
5041 GlobalIndex.reset();
5042 ModuleMgr.setGlobalIndex(nullptr);
5043 return ReadResult;
5044 }
5045
5046 if (NewLoadedModuleFile && !Loaded.empty())
5047 *NewLoadedModuleFile = Loaded.back().Mod;
5048
5049 // Here comes stuff that we only do once the entire chain is loaded. Do *not*
5050 // remove modules from this point. Various fields are updated during reading
5051 // the AST block and removing the modules would result in dangling pointers.
5052 // They are generally only incidentally dereferenced, ie. a binary search
5053 // runs over `GlobalSLocEntryMap`, which could cause an invalid module to
5054 // be dereferenced but it wouldn't actually be used.
5055
5056 // Load the AST blocks of all of the modules that we loaded. We can still
5057 // hit errors parsing the ASTs at this point.
5058 for (ImportedModule &M : Loaded) {
5059 ModuleFile &F = *M.Mod;
5060 llvm::TimeTraceScope Scope2("Read Loaded AST", F.ModuleName);
5061
5062 // Read the AST block.
5063 if (llvm::Error Err = ReadASTBlock(F, ClientLoadCapabilities)) {
5064 Error(std::move(Err));
5065 return Failure;
5066 }
5067
5068 // The AST block should always have a definition for the main module.
5069 if (F.isModule() && !F.DidReadTopLevelSubmodule) {
5070 Error(diag::err_module_file_missing_top_level_submodule, F.FileName);
5071 return Failure;
5072 }
5073
5074 // Read the extension blocks.
5076 if (llvm::Error Err = ReadExtensionBlock(F)) {
5077 Error(std::move(Err));
5078 return Failure;
5079 }
5080 }
5081
5082 // Once read, set the ModuleFile bit base offset and update the size in
5083 // bits of all files we've seen.
5084 F.GlobalBitOffset = TotalModulesSizeInBits;
5085 TotalModulesSizeInBits += F.SizeInBits;
5086 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
5087 }
5088
5089 // Preload source locations and interesting indentifiers.
5090 for (ImportedModule &M : Loaded) {
5091 ModuleFile &F = *M.Mod;
5092
5093 // Map the original source file ID into the ID space of the current
5094 // compilation.
5097
5098 for (auto Offset : F.PreloadIdentifierOffsets) {
5099 const unsigned char *Data = F.IdentifierTableData + Offset;
5100
5101 ASTIdentifierLookupTrait Trait(*this, F);
5102 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
5103 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
5104
5105 IdentifierInfo *II;
5106 if (!PP.getLangOpts().CPlusPlus) {
5107 // Identifiers present in both the module file and the importing
5108 // instance are marked out-of-date so that they can be deserialized
5109 // on next use via ASTReader::updateOutOfDateIdentifier().
5110 // Identifiers present in the module file but not in the importing
5111 // instance are ignored for now, preventing growth of the identifier
5112 // table. They will be deserialized on first use via ASTReader::get().
5113 auto It = PP.getIdentifierTable().find(Key);
5114 if (It == PP.getIdentifierTable().end())
5115 continue;
5116 II = It->second;
5117 } else {
5118 // With C++ modules, not many identifiers are considered interesting.
5119 // All identifiers in the module file can be placed into the identifier
5120 // table of the importing instance and marked as out-of-date. This makes
5121 // ASTReader::get() a no-op, and deserialization will take place on
5122 // first/next use via ASTReader::updateOutOfDateIdentifier().
5123 II = &PP.getIdentifierTable().getOwn(Key);
5124 }
5125
5126 II->setOutOfDate(true);
5127
5128 // Mark this identifier as being from an AST file so that we can track
5129 // whether we need to serialize it.
5130 markIdentifierFromAST(*this, *II, /*IsModule=*/true);
5131
5132 // Associate the ID with the identifier so that the writer can reuse it.
5133 auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
5134 SetIdentifierInfo(ID, II);
5135 }
5136 }
5137
5138 // Builtins and library builtins have already been initialized. Mark all
5139 // identifiers as out-of-date, so that they are deserialized on first use.
5140 if (Type == MK_PCH || Type == MK_Preamble || Type == MK_MainFile)
5141 for (auto &Id : PP.getIdentifierTable())
5142 Id.second->setOutOfDate(true);
5143
5144 // Mark selectors as out of date.
5145 for (const auto &Sel : SelectorGeneration)
5146 SelectorOutOfDate[Sel.first] = true;
5147
5148 // Setup the import locations and notify the module manager that we've
5149 // committed to these module files.
5150 for (ImportedModule &M : Loaded) {
5151 ModuleFile &F = *M.Mod;
5152
5153 ModuleMgr.moduleFileAccepted(&F);
5154
5155 // Set the import location.
5156 F.DirectImportLoc = ImportLoc;
5157 // FIXME: We assume that locations from PCH / preamble do not need
5158 // any translation.
5159 if (!M.ImportedBy)
5160 F.ImportLoc = M.ImportLoc;
5161 else
5162 F.ImportLoc = TranslateSourceLocation(*M.ImportedBy, M.ImportLoc);
5163 }
5164
5165 // FIXME: How do we load the 'use'd modules? They may not be submodules.
5166 // Might be unnecessary as use declarations are only used to build the
5167 // module itself.
5168
5169 if (ContextObj)
5171
5172 if (SemaObj)
5173 UpdateSema();
5174
5175 if (DeserializationListener)
5176 DeserializationListener->ReaderInitialized(this);
5177
5178 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
5179 if (PrimaryModule.OriginalSourceFileID.isValid()) {
5180 // If this AST file is a precompiled preamble, then set the
5181 // preamble file ID of the source manager to the file source file
5182 // from which the preamble was built.
5183 if (Type == MK_Preamble) {
5184 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
5185 } else if (Type == MK_MainFile) {
5186 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
5187 }
5188 }
5189
5190 // For any Objective-C class definitions we have already loaded, make sure
5191 // that we load any additional categories.
5192 if (ContextObj) {
5193 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
5194 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
5195 ObjCClassesLoaded[I], PreviousGeneration);
5196 }
5197 }
5198
5199 const HeaderSearchOptions &HSOpts =
5200 PP.getHeaderSearchInfo().getHeaderSearchOpts();
5202 // Now we are certain that the module and all modules it depends on are
5203 // up-to-date. For implicitly-built module files, ensure the corresponding
5204 // timestamp files are up-to-date in this build session.
5205 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
5206 ImportedModule &M = Loaded[I];
5207 if (M.Mod->Kind == MK_ImplicitModule &&
5209 getModuleManager().getModuleCache().updateModuleTimestamp(
5210 M.Mod->FileName);
5211 }
5212 }
5213
5214 return Success;
5215}
5216
5217static ASTFileSignature readASTFileSignature(StringRef PCH);
5218
5219/// Whether \p Stream doesn't start with the AST file magic number 'CPCH'.
5220static llvm::Error doesntStartWithASTFileMagic(BitstreamCursor &Stream) {
5221 // FIXME checking magic headers is done in other places such as
5222 // SerializedDiagnosticReader and GlobalModuleIndex, but error handling isn't
5223 // always done the same. Unify it all with a helper.
5224 if (!Stream.canSkipToPos(4))
5225 return llvm::createStringError(
5226 std::errc::illegal_byte_sequence,
5227 "file too small to contain precompiled file magic");
5228 for (unsigned C : {'C', 'P', 'C', 'H'})
5229 if (Expected<llvm::SimpleBitstreamCursor::word_t> Res = Stream.Read(8)) {
5230 if (Res.get() != C)
5231 return llvm::createStringError(
5232 std::errc::illegal_byte_sequence,
5233 "file doesn't start with precompiled file magic");
5234 } else
5235 return Res.takeError();
5236 return llvm::Error::success();
5237}
5238
5240 switch (Kind) {
5241 case MK_PCH:
5242 return 0; // PCH
5243 case MK_ImplicitModule:
5244 case MK_ExplicitModule:
5245 case MK_PrebuiltModule:
5246 return 1; // module
5247 case MK_MainFile:
5248 case MK_Preamble:
5249 return 2; // main source file
5250 }
5251 llvm_unreachable("unknown module kind");
5252}
5253
5256 ModuleFile *ImportedBy, SmallVectorImpl<ImportedModule> &Loaded,
5257 off_t ExpectedSize, time_t ExpectedModTime,
5258 ASTFileSignature ExpectedSignature, unsigned ClientLoadCapabilities) {
5259 auto Result = ModuleMgr.addModule(
5260 FileName, Type, ImportLoc, ImportedBy, getGeneration(), ExpectedSize,
5261 ExpectedModTime, ExpectedSignature, readASTFileSignature);
5262 ModuleFile *M = Result.getModule();
5263
5264 switch (Result.getKind()) {
5266 Diag(diag::remark_module_import)
5267 << M->ModuleName << M->FileName << (ImportedBy ? true : false)
5268 << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());
5269 return Success;
5270 }
5271
5273 // Load module file below.
5274 break;
5275
5277 // The module file was missing; if the client can handle that, return
5278 // it.
5279 if (ClientLoadCapabilities & ARR_Missing)
5280 return Missing;
5281
5282 // Otherwise, return an error.
5283 Diag(diag::err_ast_file_not_found)
5285 if (!Result.getBufferError().empty())
5286 Diag(diag::note_ast_file_buffer_failed) << Result.getBufferError();
5287 return Failure;
5288
5290 // We couldn't load the module file because it is out-of-date. If the
5291 // client can handle out-of-date, return it.
5292 if (ClientLoadCapabilities & ARR_OutOfDate)
5293 return OutOfDate;
5294
5295 // Otherwise, return an error.
5296 Diag(diag::err_ast_file_out_of_date)
5298 for (const auto &C : Result.getChanges()) {
5299 Diag(diag::note_fe_ast_file_modified)
5300 << C.Kind << (C.Old && C.New) << llvm::itostr(C.Old.value_or(0))
5301 << llvm::itostr(C.New.value_or(0));
5302 }
5303 Diag(diag::note_ast_file_input_files_validation_status)
5304 << Result.getValidationStatus();
5305 if (!Result.getSignatureError().empty())
5306 Diag(diag::note_ast_file_signature_failed) << Result.getSignatureError();
5307 return Failure;
5308
5310 llvm_unreachable("Unexpected value from adding module.");
5311 }
5312
5313 assert(M && "Missing module file");
5314
5315 bool ShouldFinalizePCM = false;
5316 llvm::scope_exit FinalizeOrDropPCM([&]() {
5317 auto &MC = getModuleManager().getModuleCache().getInMemoryModuleCache();
5318 if (ShouldFinalizePCM)
5319 MC.finalizePCM(FileName);
5320 else
5321 MC.tryToDropPCM(FileName);
5322 });
5323 ModuleFile &F = *M;
5324 BitstreamCursor &Stream = F.Stream;
5325 Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(*F.Buffer));
5326 F.SizeInBits = F.Buffer->getBufferSize() * 8;
5327
5328 // Sniff for the signature.
5329 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5330 Diag(diag::err_ast_file_invalid)
5331 << moduleKindForDiagnostic(Type) << FileName << std::move(Err);
5332 return Failure;
5333 }
5334
5335 // This is used for compatibility with older PCH formats.
5336 bool HaveReadControlBlock = false;
5337 while (true) {
5338 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5339 if (!MaybeEntry) {
5340 Error(MaybeEntry.takeError());
5341 return Failure;
5342 }
5343 llvm::BitstreamEntry Entry = MaybeEntry.get();
5344
5345 switch (Entry.Kind) {
5346 case llvm::BitstreamEntry::Error:
5347 case llvm::BitstreamEntry::Record:
5348 case llvm::BitstreamEntry::EndBlock:
5349 Error("invalid record at top-level of AST file");
5350 return Failure;
5351
5352 case llvm::BitstreamEntry::SubBlock:
5353 break;
5354 }
5355
5356 switch (Entry.ID) {
5357 case CONTROL_BLOCK_ID:
5358 HaveReadControlBlock = true;
5359 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
5360 case Success:
5361 // Check that we didn't try to load a non-module AST file as a module.
5362 //
5363 // FIXME: Should we also perform the converse check? Loading a module as
5364 // a PCH file sort of works, but it's a bit wonky.
5366 Type == MK_PrebuiltModule) &&
5367 F.ModuleName.empty()) {
5369 if (Result != OutOfDate ||
5370 (ClientLoadCapabilities & ARR_OutOfDate) == 0)
5371 Diag(diag::err_module_file_not_module) << FileName;
5372 return Result;
5373 }
5374 break;
5375
5376 case Failure: return Failure;
5377 case Missing: return Missing;
5378 case OutOfDate: return OutOfDate;
5379 case VersionMismatch: return VersionMismatch;
5381 case HadErrors: return HadErrors;
5382 }
5383 break;
5384
5385 case AST_BLOCK_ID:
5386 if (!HaveReadControlBlock) {
5387 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
5388 Diag(diag::err_ast_file_version_too_old)
5390 return VersionMismatch;
5391 }
5392
5393 // Record that we've loaded this module.
5394 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
5395 ShouldFinalizePCM = true;
5396 return Success;
5397
5398 default:
5399 if (llvm::Error Err = Stream.SkipBlock()) {
5400 Error(std::move(Err));
5401 return Failure;
5402 }
5403 break;
5404 }
5405 }
5406
5407 llvm_unreachable("unexpected break; expected return");
5408}
5409
5411ASTReader::readUnhashedControlBlock(ModuleFile &F, bool WasImportedBy,
5412 unsigned ClientLoadCapabilities) {
5413 const HeaderSearchOptions &HSOpts =
5414 PP.getHeaderSearchInfo().getHeaderSearchOpts();
5415 bool AllowCompatibleConfigurationMismatch =
5417 bool DisableValidation = shouldDisableValidationForFile(F);
5418
5419 ASTReadResult Result = readUnhashedControlBlockImpl(
5420 &F, F.Data, F.FileName, ClientLoadCapabilities,
5421 AllowCompatibleConfigurationMismatch, Listener.get(),
5422 WasImportedBy ? false : HSOpts.ModulesValidateDiagnosticOptions);
5423
5424 // If F was directly imported by another module, it's implicitly validated by
5425 // the importing module.
5426 if (DisableValidation || WasImportedBy ||
5427 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
5428 return Success;
5429
5430 if (Result == Failure) {
5431 Error("malformed block record in AST file");
5432 return Failure;
5433 }
5434
5435 if (Result == OutOfDate && F.Kind == MK_ImplicitModule) {
5436 // If this module has already been finalized in the ModuleCache, we're stuck
5437 // with it; we can only load a single version of each module.
5438 //
5439 // This can happen when a module is imported in two contexts: in one, as a
5440 // user module; in another, as a system module (due to an import from
5441 // another module marked with the [system] flag). It usually indicates a
5442 // bug in the module map: this module should also be marked with [system].
5443 //
5444 // If -Wno-system-headers (the default), and the first import is as a
5445 // system module, then validation will fail during the as-user import,
5446 // since -Werror flags won't have been validated. However, it's reasonable
5447 // to treat this consistently as a system module.
5448 //
5449 // If -Wsystem-headers, the PCM on disk was built with
5450 // -Wno-system-headers, and the first import is as a user module, then
5451 // validation will fail during the as-system import since the PCM on disk
5452 // doesn't guarantee that -Werror was respected. However, the -Werror
5453 // flags were checked during the initial as-user import.
5454 if (getModuleManager().getModuleCache().getInMemoryModuleCache().isPCMFinal(
5455 F.FileName)) {
5456 Diag(diag::warn_module_system_bit_conflict) << F.FileName;
5457 return Success;
5458 }
5459 }
5460
5461 return Result;
5462}
5463
5464ASTReader::ASTReadResult ASTReader::readUnhashedControlBlockImpl(
5465 ModuleFile *F, llvm::StringRef StreamData, StringRef Filename,
5466 unsigned ClientLoadCapabilities, bool AllowCompatibleConfigurationMismatch,
5467 ASTReaderListener *Listener, bool ValidateDiagnosticOptions) {
5468 // Initialize a stream.
5469 BitstreamCursor Stream(StreamData);
5470
5471 // Sniff for the signature.
5472 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5473 // FIXME this drops the error on the floor.
5474 consumeError(std::move(Err));
5475 return Failure;
5476 }
5477
5478 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
5480 return Failure;
5481
5482 // Read all of the records in the options block.
5483 RecordData Record;
5484 ASTReadResult Result = Success;
5485 while (true) {
5486 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5487 if (!MaybeEntry) {
5488 // FIXME this drops the error on the floor.
5489 consumeError(MaybeEntry.takeError());
5490 return Failure;
5491 }
5492 llvm::BitstreamEntry Entry = MaybeEntry.get();
5493
5494 switch (Entry.Kind) {
5495 case llvm::BitstreamEntry::Error:
5496 case llvm::BitstreamEntry::SubBlock:
5497 return Failure;
5498
5499 case llvm::BitstreamEntry::EndBlock:
5500 return Result;
5501
5502 case llvm::BitstreamEntry::Record:
5503 // The interesting case.
5504 break;
5505 }
5506
5507 // Read and process a record.
5508 Record.clear();
5509 StringRef Blob;
5510 Expected<unsigned> MaybeRecordType =
5511 Stream.readRecord(Entry.ID, Record, &Blob);
5512 if (!MaybeRecordType) {
5513 // FIXME this drops the error.
5514 return Failure;
5515 }
5516 switch ((UnhashedControlBlockRecordTypes)MaybeRecordType.get()) {
5517 case SIGNATURE:
5518 if (F) {
5519 F->Signature = ASTFileSignature::create(Blob.begin(), Blob.end());
5521 "Dummy AST file signature not backpatched in ASTWriter.");
5522 }
5523 break;
5524 case AST_BLOCK_HASH:
5525 if (F) {
5526 F->ASTBlockHash = ASTFileSignature::create(Blob.begin(), Blob.end());
5528 "Dummy AST block hash not backpatched in ASTWriter.");
5529 }
5530 break;
5531 case DIAGNOSTIC_OPTIONS: {
5532 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
5533 if (Listener && ValidateDiagnosticOptions &&
5534 !AllowCompatibleConfigurationMismatch &&
5535 ParseDiagnosticOptions(Record, Filename, Complain, *Listener))
5536 Result = OutOfDate; // Don't return early. Read the signature.
5537 break;
5538 }
5539 case HEADER_SEARCH_PATHS: {
5540 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
5541 if (Listener && !AllowCompatibleConfigurationMismatch &&
5542 ParseHeaderSearchPaths(Record, Complain, *Listener))
5543 Result = ConfigurationMismatch;
5544 break;
5545 }
5547 if (!F)
5548 break;
5549 if (F->PragmaDiagMappings.empty())
5550 F->PragmaDiagMappings.swap(Record);
5551 else
5552 F->PragmaDiagMappings.insert(F->PragmaDiagMappings.end(),
5553 Record.begin(), Record.end());
5554 break;
5556 if (F)
5557 F->SearchPathUsage = ReadBitVector(Record, Blob);
5558 break;
5559 case VFS_USAGE:
5560 if (F)
5561 F->VFSUsage = ReadBitVector(Record, Blob);
5562 break;
5563 }
5564 }
5565}
5566
5567/// Parse a record and blob containing module file extension metadata.
5570 StringRef Blob,
5571 ModuleFileExtensionMetadata &Metadata) {
5572 if (Record.size() < 4) return true;
5573
5574 Metadata.MajorVersion = Record[0];
5575 Metadata.MinorVersion = Record[1];
5576
5577 unsigned BlockNameLen = Record[2];
5578 unsigned UserInfoLen = Record[3];
5579
5580 if (BlockNameLen + UserInfoLen > Blob.size()) return true;
5581
5582 Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
5583 Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,
5584 Blob.data() + BlockNameLen + UserInfoLen);
5585 return false;
5586}
5587
5588llvm::Error ASTReader::ReadExtensionBlock(ModuleFile &F) {
5589 BitstreamCursor &Stream = F.Stream;
5590
5591 RecordData Record;
5592 while (true) {
5593 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5594 if (!MaybeEntry)
5595 return MaybeEntry.takeError();
5596 llvm::BitstreamEntry Entry = MaybeEntry.get();
5597
5598 switch (Entry.Kind) {
5599 case llvm::BitstreamEntry::SubBlock:
5600 if (llvm::Error Err = Stream.SkipBlock())
5601 return Err;
5602 continue;
5603 case llvm::BitstreamEntry::EndBlock:
5604 return llvm::Error::success();
5605 case llvm::BitstreamEntry::Error:
5606 return llvm::createStringError(std::errc::illegal_byte_sequence,
5607 "malformed block record in AST file");
5608 case llvm::BitstreamEntry::Record:
5609 break;
5610 }
5611
5612 Record.clear();
5613 StringRef Blob;
5614 Expected<unsigned> MaybeRecCode =
5615 Stream.readRecord(Entry.ID, Record, &Blob);
5616 if (!MaybeRecCode)
5617 return MaybeRecCode.takeError();
5618 switch (MaybeRecCode.get()) {
5619 case EXTENSION_METADATA: {
5620 ModuleFileExtensionMetadata Metadata;
5621 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
5622 return llvm::createStringError(
5623 std::errc::illegal_byte_sequence,
5624 "malformed EXTENSION_METADATA in AST file");
5625
5626 // Find a module file extension with this block name.
5627 auto Known = ModuleFileExtensions.find(Metadata.BlockName);
5628 if (Known == ModuleFileExtensions.end()) break;
5629
5630 // Form a reader.
5631 if (auto Reader = Known->second->createExtensionReader(Metadata, *this,
5632 F, Stream)) {
5633 F.ExtensionReaders.push_back(std::move(Reader));
5634 }
5635
5636 break;
5637 }
5638 }
5639 }
5640
5641 llvm_unreachable("ReadExtensionBlock should return from while loop");
5642}
5643
5645 assert(ContextObj && "no context to initialize");
5646 ASTContext &Context = *ContextObj;
5647
5648 // If there's a listener, notify them that we "read" the translation unit.
5649 if (DeserializationListener)
5650 DeserializationListener->DeclRead(
5652 Context.getTranslationUnitDecl());
5653
5654 // FIXME: Find a better way to deal with collisions between these
5655 // built-in types. Right now, we just ignore the problem.
5656
5657 // Load the special types.
5658 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
5659 if (TypeID String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
5660 if (!Context.CFConstantStringTypeDecl)
5661 Context.setCFConstantStringType(GetType(String));
5662 }
5663
5664 if (TypeID File = SpecialTypes[SPECIAL_TYPE_FILE]) {
5665 QualType FileType = GetType(File);
5666 if (FileType.isNull()) {
5667 Error("FILE type is NULL");
5668 return;
5669 }
5670
5671 if (!Context.FILEDecl) {
5672 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
5673 Context.setFILEDecl(Typedef->getDecl());
5674 else {
5675 const TagType *Tag = FileType->getAs<TagType>();
5676 if (!Tag) {
5677 Error("Invalid FILE type in AST file");
5678 return;
5679 }
5680 Context.setFILEDecl(Tag->getDecl());
5681 }
5682 }
5683 }
5684
5685 if (TypeID Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
5686 QualType Jmp_bufType = GetType(Jmp_buf);
5687 if (Jmp_bufType.isNull()) {
5688 Error("jmp_buf type is NULL");
5689 return;
5690 }
5691
5692 if (!Context.jmp_bufDecl) {
5693 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
5694 Context.setjmp_bufDecl(Typedef->getDecl());
5695 else {
5696 const TagType *Tag = Jmp_bufType->getAs<TagType>();
5697 if (!Tag) {
5698 Error("Invalid jmp_buf type in AST file");
5699 return;
5700 }
5701 Context.setjmp_bufDecl(Tag->getDecl());
5702 }
5703 }
5704 }
5705
5706 if (TypeID Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
5707 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
5708 if (Sigjmp_bufType.isNull()) {
5709 Error("sigjmp_buf type is NULL");
5710 return;
5711 }
5712
5713 if (!Context.sigjmp_bufDecl) {
5714 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
5715 Context.setsigjmp_bufDecl(Typedef->getDecl());
5716 else {
5717 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
5718 assert(Tag && "Invalid sigjmp_buf type in AST file");
5719 Context.setsigjmp_bufDecl(Tag->getDecl());
5720 }
5721 }
5722 }
5723
5724 if (TypeID ObjCIdRedef = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
5725 if (Context.ObjCIdRedefinitionType.isNull())
5726 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
5727 }
5728
5729 if (TypeID ObjCClassRedef =
5731 if (Context.ObjCClassRedefinitionType.isNull())
5732 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
5733 }
5734
5735 if (TypeID ObjCSelRedef =
5736 SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
5737 if (Context.ObjCSelRedefinitionType.isNull())
5738 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
5739 }
5740
5741 if (TypeID Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
5742 QualType Ucontext_tType = GetType(Ucontext_t);
5743 if (Ucontext_tType.isNull()) {
5744 Error("ucontext_t type is NULL");
5745 return;
5746 }
5747
5748 if (!Context.ucontext_tDecl) {
5749 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
5750 Context.setucontext_tDecl(Typedef->getDecl());
5751 else {
5752 const TagType *Tag = Ucontext_tType->getAs<TagType>();
5753 assert(Tag && "Invalid ucontext_t type in AST file");
5754 Context.setucontext_tDecl(Tag->getDecl());
5755 }
5756 }
5757 }
5758 }
5759
5760 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
5761
5762 // If there were any CUDA special declarations, deserialize them.
5763 if (!CUDASpecialDeclRefs.empty()) {
5764 assert(CUDASpecialDeclRefs.size() == 3 && "More decl refs than expected!");
5765 Context.setcudaConfigureCallDecl(
5766 cast_or_null<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
5767 Context.setcudaGetParameterBufferDecl(
5768 cast_or_null<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[1])));
5769 Context.setcudaLaunchDeviceDecl(
5770 cast_or_null<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[2])));
5771 }
5772
5773 // Re-export any modules that were imported by a non-module AST file.
5774 // FIXME: This does not make macro-only imports visible again.
5775 for (auto &Import : PendingImportedModules) {
5776 if (Module *Imported = getSubmodule(Import.ID)) {
5778 /*ImportLoc=*/Import.ImportLoc);
5779 if (Import.ImportLoc.isValid())
5780 PP.makeModuleVisible(Imported, Import.ImportLoc);
5781 // This updates visibility for Preprocessor only. For Sema, which can be
5782 // nullptr here, we do the same later, in UpdateSema().
5783 }
5784 }
5785
5786 // Hand off these modules to Sema.
5787 PendingImportedModulesSema.append(PendingImportedModules);
5788 PendingImportedModules.clear();
5789}
5790
5792 // Nothing to do for now.
5793}
5794
5795/// Reads and return the signature record from \p PCH's control block, or
5796/// else returns 0.
5798 BitstreamCursor Stream(PCH);
5799 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5800 // FIXME this drops the error on the floor.
5801 consumeError(std::move(Err));
5802 return ASTFileSignature();
5803 }
5804
5805 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
5807 return ASTFileSignature();
5808
5809 // Scan for SIGNATURE inside the diagnostic options block.
5811 while (true) {
5813 Stream.advanceSkippingSubblocks();
5814 if (!MaybeEntry) {
5815 // FIXME this drops the error on the floor.
5816 consumeError(MaybeEntry.takeError());
5817 return ASTFileSignature();
5818 }
5819 llvm::BitstreamEntry Entry = MaybeEntry.get();
5820
5821 if (Entry.Kind != llvm::BitstreamEntry::Record)
5822 return ASTFileSignature();
5823
5824 Record.clear();
5825 StringRef Blob;
5826 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);
5827 if (!MaybeRecord) {
5828 // FIXME this drops the error on the floor.
5829 consumeError(MaybeRecord.takeError());
5830 return ASTFileSignature();
5831 }
5832 if (SIGNATURE == MaybeRecord.get()) {
5833 auto Signature = ASTFileSignature::create(Blob.begin(), Blob.end());
5834 assert(Signature != ASTFileSignature::createDummy() &&
5835 "Dummy AST file signature not backpatched in ASTWriter.");
5836 return Signature;
5837 }
5838 }
5839}
5840
5841/// Retrieve the name of the original source file name
5842/// directly from the AST file, without actually loading the AST
5843/// file.
5845 const std::string &ASTFileName, FileManager &FileMgr,
5846 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
5847 // Open the AST file.
5848 auto Buffer = FileMgr.getBufferForFile(ASTFileName, /*IsVolatile=*/false,
5849 /*RequiresNullTerminator=*/false,
5850 /*MaybeLimit=*/std::nullopt,
5851 /*IsText=*/false);
5852 if (!Buffer) {
5853 Diags.Report(diag::err_fe_unable_to_read_pch_file)
5854 << ASTFileName << Buffer.getError().message();
5855 return std::string();
5856 }
5857
5858 // Initialize the stream
5859 BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer));
5860
5861 // Sniff for the signature.
5862 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5863 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName << std::move(Err);
5864 return std::string();
5865 }
5866
5867 // Scan for the CONTROL_BLOCK_ID block.
5868 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
5869 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
5870 return std::string();
5871 }
5872
5873 // Scan for ORIGINAL_FILE inside the control block.
5875 while (true) {
5877 Stream.advanceSkippingSubblocks();
5878 if (!MaybeEntry) {
5879 // FIXME this drops errors on the floor.
5880 consumeError(MaybeEntry.takeError());
5881 return std::string();
5882 }
5883 llvm::BitstreamEntry Entry = MaybeEntry.get();
5884
5885 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
5886 return std::string();
5887
5888 if (Entry.Kind != llvm::BitstreamEntry::Record) {
5889 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
5890 return std::string();
5891 }
5892
5893 Record.clear();
5894 StringRef Blob;
5895 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);
5896 if (!MaybeRecord) {
5897 // FIXME this drops the errors on the floor.
5898 consumeError(MaybeRecord.takeError());
5899 return std::string();
5900 }
5901 if (ORIGINAL_FILE == MaybeRecord.get())
5902 return Blob.str();
5903 }
5904}
5905
5906namespace {
5907
5908 class SimplePCHValidator : public ASTReaderListener {
5909 const LangOptions &ExistingLangOpts;
5910 const CodeGenOptions &ExistingCGOpts;
5911 const TargetOptions &ExistingTargetOpts;
5912 const PreprocessorOptions &ExistingPPOpts;
5913 const HeaderSearchOptions &ExistingHSOpts;
5914 std::string ExistingSpecificModuleCachePath;
5916 bool StrictOptionMatches;
5917
5918 public:
5919 SimplePCHValidator(const LangOptions &ExistingLangOpts,
5920 const CodeGenOptions &ExistingCGOpts,
5921 const TargetOptions &ExistingTargetOpts,
5922 const PreprocessorOptions &ExistingPPOpts,
5923 const HeaderSearchOptions &ExistingHSOpts,
5924 StringRef ExistingSpecificModuleCachePath,
5925 FileManager &FileMgr, bool StrictOptionMatches)
5926 : ExistingLangOpts(ExistingLangOpts), ExistingCGOpts(ExistingCGOpts),
5927 ExistingTargetOpts(ExistingTargetOpts),
5928 ExistingPPOpts(ExistingPPOpts), ExistingHSOpts(ExistingHSOpts),
5929 ExistingSpecificModuleCachePath(ExistingSpecificModuleCachePath),
5930 FileMgr(FileMgr), StrictOptionMatches(StrictOptionMatches) {}
5931
5932 bool ReadLanguageOptions(const LangOptions &LangOpts,
5933 StringRef ModuleFilename, bool Complain,
5934 bool AllowCompatibleDifferences) override {
5935 return checkLanguageOptions(ExistingLangOpts, LangOpts, ModuleFilename,
5936 nullptr, AllowCompatibleDifferences);
5937 }
5938
5939 bool ReadCodeGenOptions(const CodeGenOptions &CGOpts,
5940 StringRef ModuleFilename, bool Complain,
5941 bool AllowCompatibleDifferences) override {
5942 return checkCodegenOptions(ExistingCGOpts, CGOpts, ModuleFilename,
5943 nullptr, AllowCompatibleDifferences);
5944 }
5945
5946 bool ReadTargetOptions(const TargetOptions &TargetOpts,
5947 StringRef ModuleFilename, bool Complain,
5948 bool AllowCompatibleDifferences) override {
5949 return checkTargetOptions(TargetOpts, ExistingTargetOpts, ModuleFilename,
5950 nullptr, AllowCompatibleDifferences);
5951 }
5952
5953 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
5954 StringRef ASTFilename, StringRef ContextHash,
5955 bool Complain) override {
5956 return checkModuleCachePath(
5957 FileMgr, ContextHash, ExistingSpecificModuleCachePath, ASTFilename,
5958 nullptr, ExistingLangOpts, ExistingPPOpts, ExistingHSOpts, HSOpts);
5959 }
5960
5961 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
5962 StringRef ModuleFilename, bool ReadMacros,
5963 bool Complain,
5964 std::string &SuggestedPredefines) override {
5966 PPOpts, ExistingPPOpts, ModuleFilename, ReadMacros, /*Diags=*/nullptr,
5967 FileMgr, SuggestedPredefines, ExistingLangOpts,
5968 StrictOptionMatches ? OptionValidateStrictMatches
5970 }
5971 };
5972
5973} // namespace
5974
5976 StringRef Filename, FileManager &FileMgr, const ModuleCache &ModCache,
5977 const PCHContainerReader &PCHContainerRdr, bool FindModuleFileExtensions,
5978 ASTReaderListener &Listener, bool ValidateDiagnosticOptions,
5979 unsigned ClientLoadCapabilities) {
5980 // Open the AST file.
5981 off_t Size;
5982 time_t ModTime;
5983 std::unique_ptr<llvm::MemoryBuffer> OwnedBuffer;
5984 llvm::MemoryBuffer *Buffer =
5985 ModCache.getInMemoryModuleCache().lookupPCM(Filename, Size, ModTime);
5986 if (!Buffer) {
5987 // FIXME: We should add the pcm to the InMemoryModuleCache if it could be
5988 // read again later, but we do not have the context here to determine if it
5989 // is safe to change the result of InMemoryModuleCache::getPCMState().
5990
5991 // FIXME: This allows use of the VFS; we do not allow use of the
5992 // VFS when actually loading a module.
5993 auto Entry = Filename == "-" ? FileMgr.getSTDIN()
5994 : FileMgr.getFileRef(Filename,
5995 /*OpenFile=*/false,
5996 /*CacheFailure=*/true,
5997 /*IsText=*/false);
5998 if (!Entry) {
5999 llvm::consumeError(Entry.takeError());
6000 return true;
6001 }
6002 auto BufferOrErr =
6003 FileMgr.getBufferForFile(*Entry,
6004 /*IsVolatile=*/false,
6005 /*RequiresNullTerminator=*/false,
6006 /*MaybeLimit=*/std::nullopt,
6007 /*IsText=*/false);
6008 if (!BufferOrErr)
6009 return true;
6010 OwnedBuffer = std::move(*BufferOrErr);
6011 Buffer = OwnedBuffer.get();
6012 }
6013
6014 // Initialize the stream
6015 StringRef Bytes = PCHContainerRdr.ExtractPCH(*Buffer);
6016 BitstreamCursor Stream(Bytes);
6017
6018 // Sniff for the signature.
6019 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
6020 consumeError(std::move(Err)); // FIXME this drops errors on the floor.
6021 return true;
6022 }
6023
6024 // Scan for the CONTROL_BLOCK_ID block.
6026 return true;
6027
6028 bool NeedsInputFiles = Listener.needsInputFileVisitation();
6029 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
6030 bool NeedsImports = Listener.needsImportVisitation();
6031 BitstreamCursor InputFilesCursor;
6032 uint64_t InputFilesOffsetBase = 0;
6033
6035 std::string ModuleDir;
6036 bool DoneWithControlBlock = false;
6037 SmallString<0> PathBuf;
6038 PathBuf.reserve(256);
6039 // Additional path buffer to use when multiple paths need to be resolved.
6040 // For example, when deserializing input files that contains a path that was
6041 // resolved from a vfs overlay and an external location.
6042 SmallString<0> AdditionalPathBuf;
6043 AdditionalPathBuf.reserve(256);
6044 while (!DoneWithControlBlock) {
6045 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
6046 if (!MaybeEntry) {
6047 // FIXME this drops the error on the floor.
6048 consumeError(MaybeEntry.takeError());
6049 return true;
6050 }
6051 llvm::BitstreamEntry Entry = MaybeEntry.get();
6052
6053 switch (Entry.Kind) {
6054 case llvm::BitstreamEntry::SubBlock: {
6055 switch (Entry.ID) {
6056 case OPTIONS_BLOCK_ID: {
6057 std::string IgnoredSuggestedPredefines;
6058 if (ReadOptionsBlock(Stream, Filename, ClientLoadCapabilities,
6059 /*AllowCompatibleConfigurationMismatch*/ false,
6060 Listener, IgnoredSuggestedPredefines) != Success)
6061 return true;
6062 break;
6063 }
6064
6066 InputFilesCursor = Stream;
6067 if (llvm::Error Err = Stream.SkipBlock()) {
6068 // FIXME this drops the error on the floor.
6069 consumeError(std::move(Err));
6070 return true;
6071 }
6072 if (NeedsInputFiles &&
6073 ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID))
6074 return true;
6075 InputFilesOffsetBase = InputFilesCursor.GetCurrentBitNo();
6076 break;
6077
6078 default:
6079 if (llvm::Error Err = Stream.SkipBlock()) {
6080 // FIXME this drops the error on the floor.
6081 consumeError(std::move(Err));
6082 return true;
6083 }
6084 break;
6085 }
6086
6087 continue;
6088 }
6089
6090 case llvm::BitstreamEntry::EndBlock:
6091 DoneWithControlBlock = true;
6092 break;
6093
6094 case llvm::BitstreamEntry::Error:
6095 return true;
6096
6097 case llvm::BitstreamEntry::Record:
6098 break;
6099 }
6100
6101 if (DoneWithControlBlock) break;
6102
6103 Record.clear();
6104 StringRef Blob;
6105 Expected<unsigned> MaybeRecCode =
6106 Stream.readRecord(Entry.ID, Record, &Blob);
6107 if (!MaybeRecCode) {
6108 // FIXME this drops the error.
6109 return Failure;
6110 }
6111 switch ((ControlRecordTypes)MaybeRecCode.get()) {
6112 case METADATA:
6113 if (Record[0] != VERSION_MAJOR)
6114 return true;
6115 if (Listener.ReadFullVersionInformation(Blob))
6116 return true;
6117 break;
6118 case MODULE_NAME:
6119 Listener.ReadModuleName(Blob);
6120 break;
6121 case MODULE_DIRECTORY:
6122 ModuleDir = std::string(Blob);
6123 break;
6124 case MODULE_MAP_FILE: {
6125 unsigned Idx = 0;
6126 std::string PathStr = ReadString(Record, Idx);
6127 auto Path = ResolveImportedPath(PathBuf, PathStr, ModuleDir);
6128 Listener.ReadModuleMapFile(*Path);
6129 break;
6130 }
6131 case INPUT_FILE_OFFSETS: {
6132 if (!NeedsInputFiles)
6133 break;
6134
6135 unsigned NumInputFiles = Record[0];
6136 unsigned NumUserFiles = Record[1];
6137 const llvm::support::unaligned_uint64_t *InputFileOffs =
6138 (const llvm::support::unaligned_uint64_t *)Blob.data();
6139 for (unsigned I = 0; I != NumInputFiles; ++I) {
6140 // Go find this input file.
6141 bool isSystemFile = I >= NumUserFiles;
6142
6143 if (isSystemFile && !NeedsSystemInputFiles)
6144 break; // the rest are system input files
6145
6146 BitstreamCursor &Cursor = InputFilesCursor;
6147 SavedStreamPosition SavedPosition(Cursor);
6148 if (llvm::Error Err =
6149 Cursor.JumpToBit(InputFilesOffsetBase + InputFileOffs[I])) {
6150 // FIXME this drops errors on the floor.
6151 consumeError(std::move(Err));
6152 }
6153
6154 Expected<unsigned> MaybeCode = Cursor.ReadCode();
6155 if (!MaybeCode) {
6156 // FIXME this drops errors on the floor.
6157 consumeError(MaybeCode.takeError());
6158 }
6159 unsigned Code = MaybeCode.get();
6160
6162 StringRef Blob;
6163 bool shouldContinue = false;
6164 Expected<unsigned> MaybeRecordType =
6165 Cursor.readRecord(Code, Record, &Blob);
6166 if (!MaybeRecordType) {
6167 // FIXME this drops errors on the floor.
6168 consumeError(MaybeRecordType.takeError());
6169 }
6170 switch ((InputFileRecordTypes)MaybeRecordType.get()) {
6171 case INPUT_FILE_HASH:
6172 break;
6173 case INPUT_FILE:
6174 time_t StoredTime = static_cast<time_t>(Record[2]);
6175 bool Overridden = static_cast<bool>(Record[3]);
6176 auto [UnresolvedFilenameAsRequested, UnresolvedFilename] =
6178 auto FilenameAsRequestedBuf = ResolveImportedPath(
6179 PathBuf, UnresolvedFilenameAsRequested, ModuleDir);
6180 StringRef Filename;
6181 if (UnresolvedFilename.empty())
6182 Filename = *FilenameAsRequestedBuf;
6183 else {
6184 auto FilenameBuf = ResolveImportedPath(
6185 AdditionalPathBuf, UnresolvedFilename, ModuleDir);
6186 Filename = *FilenameBuf;
6187 }
6188 shouldContinue = Listener.visitInputFileAsRequested(
6189 *FilenameAsRequestedBuf, Filename, isSystemFile, Overridden,
6190 StoredTime, /*IsExplicitModule=*/false);
6191 break;
6192 }
6193 if (!shouldContinue)
6194 break;
6195 }
6196 break;
6197 }
6198
6199 case IMPORT: {
6200 if (!NeedsImports)
6201 break;
6202
6203 unsigned Idx = 0;
6204 // Read information about the AST file.
6205
6206 // Skip Kind
6207 Idx++;
6208
6209 // Skip ImportLoc
6210 Idx++;
6211
6212 StringRef ModuleName = ReadStringBlob(Record, Idx, Blob);
6213
6214 bool IsStandardCXXModule = Record[Idx++];
6215
6216 // In C++20 Modules, we don't record the path to imported
6217 // modules in the BMI files.
6218 if (IsStandardCXXModule) {
6219 Listener.visitImport(ModuleName, /*Filename=*/"");
6220 continue;
6221 }
6222
6223 // Skip Size, ModTime and ImplicitModuleSuffix.
6224 Idx += 1 + 1 + 1;
6225 // Skip signature.
6226 Blob = Blob.substr(ASTFileSignature::size);
6227
6228 StringRef FilenameStr = ReadStringBlob(Record, Idx, Blob);
6229 auto Filename = ResolveImportedPath(PathBuf, FilenameStr, ModuleDir);
6230 Listener.visitImport(ModuleName, *Filename);
6231 break;
6232 }
6233
6234 default:
6235 // No other validation to perform.
6236 break;
6237 }
6238 }
6239
6240 // Look for module file extension blocks, if requested.
6241 if (FindModuleFileExtensions) {
6242 BitstreamCursor SavedStream = Stream;
6243 while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {
6244 bool DoneWithExtensionBlock = false;
6245 while (!DoneWithExtensionBlock) {
6246 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
6247 if (!MaybeEntry) {
6248 // FIXME this drops the error.
6249 return true;
6250 }
6251 llvm::BitstreamEntry Entry = MaybeEntry.get();
6252
6253 switch (Entry.Kind) {
6254 case llvm::BitstreamEntry::SubBlock:
6255 if (llvm::Error Err = Stream.SkipBlock()) {
6256 // FIXME this drops the error on the floor.
6257 consumeError(std::move(Err));
6258 return true;
6259 }
6260 continue;
6261
6262 case llvm::BitstreamEntry::EndBlock:
6263 DoneWithExtensionBlock = true;
6264 continue;
6265
6266 case llvm::BitstreamEntry::Error:
6267 return true;
6268
6269 case llvm::BitstreamEntry::Record:
6270 break;
6271 }
6272
6273 Record.clear();
6274 StringRef Blob;
6275 Expected<unsigned> MaybeRecCode =
6276 Stream.readRecord(Entry.ID, Record, &Blob);
6277 if (!MaybeRecCode) {
6278 // FIXME this drops the error.
6279 return true;
6280 }
6281 switch (MaybeRecCode.get()) {
6282 case EXTENSION_METADATA: {
6284 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
6285 return true;
6286
6287 Listener.readModuleFileExtension(Metadata);
6288 break;
6289 }
6290 }
6291 }
6292 }
6293 Stream = std::move(SavedStream);
6294 }
6295
6296 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
6297 if (readUnhashedControlBlockImpl(
6298 nullptr, Bytes, Filename, ClientLoadCapabilities,
6299 /*AllowCompatibleConfigurationMismatch*/ false, &Listener,
6300 ValidateDiagnosticOptions) != Success)
6301 return true;
6302
6303 return false;
6304}
6305
6307 StringRef Filename, FileManager &FileMgr, const ModuleCache &ModCache,
6308 const PCHContainerReader &PCHContainerRdr, const LangOptions &LangOpts,
6309 const CodeGenOptions &CGOpts, const TargetOptions &TargetOpts,
6310 const PreprocessorOptions &PPOpts, const HeaderSearchOptions &HSOpts,
6311 StringRef SpecificModuleCachePath, bool RequireStrictOptionMatches) {
6312 SimplePCHValidator validator(LangOpts, CGOpts, TargetOpts, PPOpts, HSOpts,
6313 SpecificModuleCachePath, FileMgr,
6314 RequireStrictOptionMatches);
6315 return !readASTFileControlBlock(Filename, FileMgr, ModCache, PCHContainerRdr,
6316 /*FindModuleFileExtensions=*/false, validator,
6317 /*ValidateDiagnosticOptions=*/true);
6318}
6319
6320Module *ASTReader::getSubmodule(uint32_t GlobalID) {
6321 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
6322 assert(GlobalID == 0 && "Unhandled global submodule ID");
6323 return nullptr;
6324 }
6325
6326 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
6327 if (GlobalIndex >= SubmodulesLoaded.size()) {
6328 Error("submodule ID out of range in AST file");
6329 return nullptr;
6330 }
6331
6332 if (SubmodulesLoaded[GlobalIndex])
6333 return SubmodulesLoaded[GlobalIndex];
6334
6335 GlobalSubmoduleMapType::iterator It = GlobalSubmoduleMap.find(GlobalID);
6336 assert(It != GlobalSubmoduleMap.end());
6337 ModuleFile &F = *It->second;
6338 unsigned Index = GlobalID - F.BaseSubmoduleID - NUM_PREDEF_SUBMODULE_IDS;
6339 [[maybe_unused]] unsigned LocalID =
6341
6342 BitstreamCursor &Cursor = F.SubmodulesCursor;
6343 SavedStreamPosition SavedPosition(Cursor);
6344 unsigned Offset = F.SubmoduleOffsets[Index];
6345 if (llvm::Error Err = Cursor.JumpToBit(F.SubmodulesOffsetBase + Offset)) {
6346 Error(std::move(Err));
6347 return nullptr;
6348 }
6349
6350 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
6351 bool KnowsTopLevelModule = ModMap.findModule(F.ModuleName) != nullptr;
6352 // If we don't know the top-level module, there's no point in doing qualified
6353 // lookup of its submodules; it won't find anything anywhere within this tree.
6354 // Let's skip that and avoid some string lookups.
6355 auto CreateModule = !KnowsTopLevelModule
6358
6359 Module *CurrentModule = nullptr;
6361 while (true) {
6362 Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
6363 if (!MaybeEntry) {
6364 Error(MaybeEntry.takeError());
6365 return nullptr;
6366 }
6367 llvm::BitstreamEntry Entry = MaybeEntry.get();
6368
6369 switch (Entry.Kind) {
6370 case llvm::BitstreamEntry::SubBlock:
6371 case llvm::BitstreamEntry::Error:
6372 case llvm::BitstreamEntry::EndBlock: {
6373 Error(llvm::createStringError(std::errc::illegal_byte_sequence,
6374 "malformed block record in AST file"));
6375 return nullptr;
6376 }
6377 case llvm::BitstreamEntry::Record:
6378 // The interesting case.
6379 break;
6380 }
6381
6382 // Read a record.
6383 StringRef Blob;
6384 Record.clear();
6385 Expected<unsigned> MaybeKind = Cursor.readRecord(Entry.ID, Record, &Blob);
6386 if (!MaybeKind) {
6387 Error(MaybeKind.takeError());
6388 return nullptr;
6389 }
6390 auto Kind = static_cast<SubmoduleRecordTypes>(MaybeKind.get());
6391
6392 switch (Kind) {
6393 case SUBMODULE_END:
6394 if (!CurrentModule) {
6395 Error(llvm::createStringError(std::errc::illegal_byte_sequence,
6396 "malformed module definition"));
6397 return nullptr;
6398 }
6399 return CurrentModule;
6400
6401 case SUBMODULE_DEFINITION: {
6402 if (Record.size() < 13) {
6403 Error(llvm::createStringError(std::errc::illegal_byte_sequence,
6404 "malformed module definition"));
6405 return nullptr;
6406 }
6407
6408 StringRef Name = Blob;
6409 unsigned Idx = 0;
6410 [[maybe_unused]] unsigned ReadLocalID = Record[Idx++];
6411 assert(LocalID == ReadLocalID);
6412 assert(GlobalID == getGlobalSubmoduleID(F, ReadLocalID));
6413 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
6415 SourceLocation DefinitionLoc = ReadSourceLocation(F, Record[Idx++]);
6416 FileID InferredAllowedBy = ReadFileID(F, Record, Idx);
6417 bool IsFramework = Record[Idx++];
6418 bool IsExplicit = Record[Idx++];
6419 bool IsSystem = Record[Idx++];
6420 bool IsExternC = Record[Idx++];
6421 bool InferSubmodules = Record[Idx++];
6422 bool InferExplicitSubmodules = Record[Idx++];
6423 bool InferExportWildcard = Record[Idx++];
6424 bool ConfigMacrosExhaustive = Record[Idx++];
6425 bool ModuleMapIsPrivate = Record[Idx++];
6426 bool NamedModuleHasInit = Record[Idx++];
6427
6428 Module *ParentModule = nullptr;
6429 if (Parent) {
6430 ParentModule = getSubmodule(Parent);
6431 if (!ParentModule)
6432 return nullptr;
6433 }
6434
6435 CurrentModule = std::invoke(CreateModule, &ModMap, Name, ParentModule,
6436 IsFramework, IsExplicit);
6437
6438 if (!ParentModule) {
6439 if ([[maybe_unused]] const ModuleFileKey *CurFileKey =
6440 CurrentModule->getASTFileKey()) {
6441 // Don't emit module relocation error if we have -fno-validate-pch
6442 if (!bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation &
6444 assert(*CurFileKey != F.FileKey &&
6445 "ModuleManager did not de-duplicate");
6446
6447 Diag(diag::err_module_file_conflict)
6448 << CurrentModule->getTopLevelModuleName()
6449 << *CurrentModule->getASTFileName() << F.FileName;
6450
6451 auto CurModMapFile =
6452 ModMap.getContainingModuleMapFile(CurrentModule);
6453 auto ModMapFile = FileMgr.getOptionalFileRef(F.ModuleMapPath);
6454 if (CurModMapFile && ModMapFile && CurModMapFile != ModMapFile)
6455 Diag(diag::note_module_file_conflict)
6456 << CurModMapFile->getName() << ModMapFile->getName();
6457
6458 return nullptr;
6459 }
6460 }
6461
6462 F.DidReadTopLevelSubmodule = true;
6463 CurrentModule->setASTFileNameAndKey(F.FileName, F.FileKey);
6464 CurrentModule->PresumedModuleMapFile = F.ModuleMapPath;
6465 }
6466
6467 CurrentModule->Kind = Kind;
6468 // Note that we may be rewriting an existing location and it is important
6469 // to keep doing that. In particular, we would like to prefer a
6470 // `DefinitionLoc` loaded from the module file instead of the location
6471 // created in the current source manager, because it allows the new
6472 // location to be marked as "unaffecting" when writing and avoid creating
6473 // duplicate locations for the same module map file.
6474 CurrentModule->DefinitionLoc = DefinitionLoc;
6475 CurrentModule->Signature = F.Signature;
6476 CurrentModule->IsFromModuleFile = true;
6477 if (InferredAllowedBy.isValid())
6478 ModMap.setInferredModuleAllowedBy(CurrentModule, InferredAllowedBy);
6479 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
6480 CurrentModule->IsExternC = IsExternC;
6481 CurrentModule->InferSubmodules = InferSubmodules;
6482 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
6483 CurrentModule->InferExportWildcard = InferExportWildcard;
6484 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
6485 CurrentModule->ModuleMapIsPrivate = ModuleMapIsPrivate;
6486 CurrentModule->NamedModuleHasInit = NamedModuleHasInit;
6487
6488 if (!ParentModule && !F.BaseDirectory.empty()) {
6489 if (auto Dir = FileMgr.getOptionalDirectoryRef(F.BaseDirectory))
6490 CurrentModule->Directory = *Dir;
6491 } else if (ParentModule && ParentModule->Directory) {
6492 // Submodules inherit the directory from their parent.
6493 CurrentModule->Directory = ParentModule->Directory;
6494 }
6495
6496 if (DeserializationListener)
6497 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
6498
6499 SubmodulesLoaded[GlobalIndex] = CurrentModule;
6500
6501 // Clear out data that will be replaced by what is in the module file.
6502 CurrentModule->LinkLibraries.clear();
6503 CurrentModule->ConfigMacros.clear();
6504 CurrentModule->UnresolvedConflicts.clear();
6505 CurrentModule->Conflicts.clear();
6506
6507 // The module is available unless it's missing a requirement; relevant
6508 // requirements will be (re-)added by SUBMODULE_REQUIRES records.
6509 // Missing headers that were present when the module was built do not
6510 // make it unavailable -- if we got this far, this must be an explicitly
6511 // imported module file.
6512 CurrentModule->Requirements.clear();
6513 CurrentModule->MissingHeaders.clear();
6514 CurrentModule->IsUnimportable =
6515 ParentModule && ParentModule->IsUnimportable;
6516 CurrentModule->IsAvailable = !CurrentModule->IsUnimportable;
6517 break;
6518 }
6519
6521 SmallString<128> RelativePathName;
6522 if (auto Umbrella = ModMap.findUmbrellaHeaderForModule(
6523 CurrentModule, Blob.str(), RelativePathName)) {
6524 if (!CurrentModule->getUmbrellaHeaderAsWritten()) {
6525 ModMap.setUmbrellaHeaderAsWritten(CurrentModule, *Umbrella, Blob,
6526 RelativePathName);
6527 }
6528 // Note that it's too late at this point to return out of date if the
6529 // name from the PCM doesn't match up with the one in the module map,
6530 // but also quite unlikely since we will have already checked the
6531 // modification time and size of the module map file itself.
6532 }
6533 break;
6534 }
6535
6536 case SUBMODULE_HEADER:
6539 // We lazily associate headers with their modules via the HeaderInfo table.
6540 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
6541 // of complete filenames or remove it entirely.
6542 break;
6543
6546 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
6547 // them here.
6548 break;
6549
6550 case SUBMODULE_TOPHEADER: {
6551 auto HeaderName = ResolveImportedPath(PathBuf, Blob, F);
6552 CurrentModule->addTopHeaderFilename(*HeaderName);
6553 break;
6554 }
6555
6557 auto Dirname = ResolveImportedPath(PathBuf, Blob, F);
6558 if (auto Umbrella =
6559 PP.getFileManager().getOptionalDirectoryRef(*Dirname)) {
6560 if (!CurrentModule->getUmbrellaDirAsWritten()) {
6561 // FIXME: NameAsWritten
6562 ModMap.setUmbrellaDirAsWritten(CurrentModule, *Umbrella, Blob, "");
6563 }
6564 }
6565 break;
6566 }
6567
6568 case SUBMODULE_IMPORTS:
6569 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
6570 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx]);
6571 CurrentModule->Imports.push_back(ModuleRef(this, GlobalID));
6572 }
6573 break;
6574
6576 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
6577 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx]);
6578 CurrentModule->AffectingClangModules.push_back(
6579 ModuleRef(this, GlobalID));
6580 }
6581 break;
6582
6583 case SUBMODULE_EXPORTS:
6584 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
6585 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx]);
6586 bool IsWildcard = Record[Idx + 1];
6587 ModuleRef ExportedMod =
6588 GlobalID ? ModuleRef(this, GlobalID) : ModuleRef();
6589 if (ExportedMod || IsWildcard)
6590 CurrentModule->Exports.push_back({ExportedMod, IsWildcard});
6591 }
6592
6593 // Once we've loaded the set of exports, there's no reason to keep
6594 // the parsed, unresolved exports around.
6595 CurrentModule->UnresolvedExports.clear();
6596 break;
6597
6598 case SUBMODULE_REQUIRES:
6599 CurrentModule->addRequirement(Blob, Record[0], PP.getLangOpts(),
6600 PP.getTargetInfo());
6601 break;
6602
6604 ModMap.resolveLinkAsDependencies(CurrentModule);
6605 CurrentModule->LinkLibraries.push_back(
6606 Module::LinkLibrary(std::string(Blob), Record[0]));
6607 break;
6608
6610 CurrentModule->ConfigMacros.push_back(Blob.str());
6611 break;
6612
6613 case SUBMODULE_CONFLICT: {
6614 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[0]);
6615 Module::Conflict Conflict;
6616 Conflict.Other = ModuleRef(this, GlobalID);
6617 Conflict.Message = Blob.str();
6618 CurrentModule->Conflicts.push_back(Conflict);
6619 break;
6620 }
6621
6623 if (!ContextObj)
6624 break;
6625 // Standard C++ module has its own way to initialize variables.
6626 if (!F.StandardCXXModule || F.Kind == MK_MainFile) {
6628 for (unsigned I = 0; I < Record.size(); /*in loop*/)
6629 Inits.push_back(ReadDeclID(F, Record, I));
6630 ContextObj->addLazyModuleInitializers(CurrentModule, Inits);
6631 }
6632 break;
6633 }
6634
6636 CurrentModule->ExportAsModule = Blob.str();
6637 ModMap.addLinkAsDependency(CurrentModule);
6638 break;
6639
6640 case SUBMODULE_CHILD: {
6641 // Record a not-yet-loaded direct child for on-demand deserialization.
6642 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[0]);
6643 CurrentModule->addSubmodule(Blob, this, GlobalID);
6644 break;
6645 }
6646 }
6647 }
6648}
6649
6650/// Parse the record that corresponds to a LangOptions data
6651/// structure.
6652///
6653/// This routine parses the language options from the AST file and then gives
6654/// them to the AST listener if one is set.
6655///
6656/// \returns true if the listener deems the file unacceptable, false otherwise.
6657bool ASTReader::ParseLanguageOptions(const RecordData &Record,
6658 StringRef ModuleFilename, bool Complain,
6659 ASTReaderListener &Listener,
6660 bool AllowCompatibleDifferences) {
6661 LangOptions LangOpts;
6662 unsigned Idx = 0;
6663#define LANGOPT(Name, Bits, Default, Compatibility, Description) \
6664 LangOpts.Name = Record[Idx++];
6665#define ENUM_LANGOPT(Name, Type, Bits, Default, Compatibility, Description) \
6666 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
6667#include "clang/Basic/LangOptions.def"
6668#define SANITIZER(NAME, ID) \
6669 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
6670#include "clang/Basic/Sanitizers.def"
6671
6672 for (unsigned N = Record[Idx++]; N; --N)
6673 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
6674
6675 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
6676 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
6677 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
6678
6679 LangOpts.CurrentModule = ReadString(Record, Idx);
6680
6681 // Comment options.
6682 for (unsigned N = Record[Idx++]; N; --N) {
6683 LangOpts.CommentOpts.BlockCommandNames.push_back(
6684 ReadString(Record, Idx));
6685 }
6686 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
6687
6688 // OpenMP offloading options.
6689 for (unsigned N = Record[Idx++]; N; --N) {
6690 LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx)));
6691 }
6692
6693 LangOpts.OMPHostIRFile = ReadString(Record, Idx);
6694
6695 return Listener.ReadLanguageOptions(LangOpts, ModuleFilename, Complain,
6696 AllowCompatibleDifferences);
6697}
6698
6699bool ASTReader::ParseCodeGenOptions(const RecordData &Record,
6700 StringRef ModuleFilename, bool Complain,
6701 ASTReaderListener &Listener,
6702 bool AllowCompatibleDifferences) {
6703 unsigned Idx = 0;
6704 CodeGenOptions CGOpts;
6706#define CODEGENOPT(Name, Bits, Default, Compatibility) \
6707 if constexpr (CK::Compatibility != CK::Benign) \
6708 CGOpts.Name = static_cast<unsigned>(Record[Idx++]);
6709#define ENUM_CODEGENOPT(Name, Type, Bits, Default, Compatibility) \
6710 if constexpr (CK::Compatibility != CK::Benign) \
6711 CGOpts.set##Name(static_cast<clang::CodeGenOptions::Type>(Record[Idx++]));
6712#define DEBUGOPT(Name, Bits, Default, Compatibility)
6713#define VALUE_DEBUGOPT(Name, Bits, Default, Compatibility)
6714#define ENUM_DEBUGOPT(Name, Type, Bits, Default, Compatibility)
6715#include "clang/Basic/CodeGenOptions.def"
6716
6717 return Listener.ReadCodeGenOptions(CGOpts, ModuleFilename, Complain,
6718 AllowCompatibleDifferences);
6719}
6720
6721bool ASTReader::ParseTargetOptions(const RecordData &Record,
6722 StringRef ModuleFilename, bool Complain,
6723 ASTReaderListener &Listener,
6724 bool AllowCompatibleDifferences) {
6725 unsigned Idx = 0;
6726 TargetOptions TargetOpts;
6727 TargetOpts.Triple = ReadString(Record, Idx);
6728 TargetOpts.CPU = ReadString(Record, Idx);
6729 TargetOpts.TuneCPU = ReadString(Record, Idx);
6730 TargetOpts.ABI = ReadString(Record, Idx);
6731 for (unsigned N = Record[Idx++]; N; --N) {
6732 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
6733 }
6734 for (unsigned N = Record[Idx++]; N; --N) {
6735 TargetOpts.Features.push_back(ReadString(Record, Idx));
6736 }
6737
6738 return Listener.ReadTargetOptions(TargetOpts, ModuleFilename, Complain,
6739 AllowCompatibleDifferences);
6740}
6741
6742bool ASTReader::ParseDiagnosticOptions(const RecordData &Record,
6743 StringRef ModuleFilename, bool Complain,
6744 ASTReaderListener &Listener) {
6745 DiagnosticOptions DiagOpts;
6746 unsigned Idx = 0;
6747#define DIAGOPT(Name, Bits, Default) DiagOpts.Name = Record[Idx++];
6748#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
6749 DiagOpts.set##Name(static_cast<Type>(Record[Idx++]));
6750#include "clang/Basic/DiagnosticOptions.def"
6751
6752 for (unsigned N = Record[Idx++]; N; --N)
6753 DiagOpts.Warnings.push_back(ReadString(Record, Idx));
6754 for (unsigned N = Record[Idx++]; N; --N)
6755 DiagOpts.Remarks.push_back(ReadString(Record, Idx));
6756
6757 return Listener.ReadDiagnosticOptions(DiagOpts, ModuleFilename, Complain);
6758}
6759
6760bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
6761 ASTReaderListener &Listener) {
6762 FileSystemOptions FSOpts;
6763 unsigned Idx = 0;
6764 FSOpts.WorkingDir = ReadString(Record, Idx);
6765 return Listener.ReadFileSystemOptions(FSOpts, Complain);
6766}
6767
6768bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
6769 StringRef ModuleFilename,
6770 bool Complain,
6771 ASTReaderListener &Listener) {
6772 HeaderSearchOptions HSOpts;
6773 unsigned Idx = 0;
6774 HSOpts.Sysroot = ReadString(Record, Idx);
6775
6776 HSOpts.ResourceDir = ReadString(Record, Idx);
6777 HSOpts.ModuleCachePath = ReadString(Record, Idx);
6778 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
6779 HSOpts.DisableModuleHash = Record[Idx++];
6780 HSOpts.ImplicitModuleMaps = Record[Idx++];
6781 HSOpts.ModuleMapFileHomeIsCwd = Record[Idx++];
6782 HSOpts.EnablePrebuiltImplicitModules = Record[Idx++];
6783 HSOpts.UseBuiltinIncludes = Record[Idx++];
6784 HSOpts.UseStandardSystemIncludes = Record[Idx++];
6785 HSOpts.UseStandardCXXIncludes = Record[Idx++];
6786 HSOpts.UseLibcxx = Record[Idx++];
6787 std::string ContextHash = ReadString(Record, Idx);
6788
6789 return Listener.ReadHeaderSearchOptions(HSOpts, ModuleFilename, ContextHash,
6790 Complain);
6791}
6792
6793bool ASTReader::ParseHeaderSearchPaths(const RecordData &Record, bool Complain,
6794 ASTReaderListener &Listener) {
6795 HeaderSearchOptions HSOpts;
6796 unsigned Idx = 0;
6797
6798 // Include entries.
6799 for (unsigned N = Record[Idx++]; N; --N) {
6800 std::string Path = ReadString(Record, Idx);
6802 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
6803 bool IsFramework = Record[Idx++];
6804 bool IgnoreSysRoot = Record[Idx++];
6805 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
6806 IgnoreSysRoot);
6807 }
6808
6809 // System header prefixes.
6810 for (unsigned N = Record[Idx++]; N; --N) {
6811 std::string Prefix = ReadString(Record, Idx);
6812 bool IsSystemHeader = Record[Idx++];
6813 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
6814 }
6815
6816 // VFS overlay files.
6817 for (unsigned N = Record[Idx++]; N; --N) {
6818 std::string VFSOverlayFile = ReadString(Record, Idx);
6819 HSOpts.VFSOverlayFiles.emplace_back(std::move(VFSOverlayFile));
6820 }
6821
6822 return Listener.ReadHeaderSearchPaths(HSOpts, Complain);
6823}
6824
6825bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
6826 StringRef ModuleFilename,
6827 bool Complain,
6828 ASTReaderListener &Listener,
6829 std::string &SuggestedPredefines) {
6830 PreprocessorOptions PPOpts;
6831 unsigned Idx = 0;
6832
6833 // Macro definitions/undefs
6834 bool ReadMacros = Record[Idx++];
6835 if (ReadMacros) {
6836 for (unsigned N = Record[Idx++]; N; --N) {
6837 std::string Macro = ReadString(Record, Idx);
6838 bool IsUndef = Record[Idx++];
6839 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
6840 }
6841 }
6842
6843 // Includes
6844 for (unsigned N = Record[Idx++]; N; --N) {
6845 PPOpts.Includes.push_back(ReadString(Record, Idx));
6846 }
6847
6848 // Macro Includes
6849 for (unsigned N = Record[Idx++]; N; --N) {
6850 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
6851 }
6852
6853 PPOpts.UsePredefines = Record[Idx++];
6854 PPOpts.DetailedRecord = Record[Idx++];
6855 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
6857 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
6858 SuggestedPredefines.clear();
6859 return Listener.ReadPreprocessorOptions(PPOpts, ModuleFilename, ReadMacros,
6860 Complain, SuggestedPredefines);
6861}
6862
6863std::pair<ModuleFile *, unsigned>
6864ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
6865 GlobalPreprocessedEntityMapType::iterator
6866 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
6867 assert(I != GlobalPreprocessedEntityMap.end() &&
6868 "Corrupted global preprocessed entity map");
6869 ModuleFile *M = I->second;
6870 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
6871 return std::make_pair(M, LocalIndex);
6872}
6873
6874llvm::iterator_range<PreprocessingRecord::iterator>
6875ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
6876 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
6877 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
6879
6880 return llvm::make_range(PreprocessingRecord::iterator(),
6881 PreprocessingRecord::iterator());
6882}
6883
6884bool ASTReader::canRecoverFromOutOfDate(StringRef ModuleFileName,
6885 unsigned int ClientLoadCapabilities) {
6886 return ClientLoadCapabilities & ARR_OutOfDate &&
6887 !getModuleManager()
6888 .getModuleCache()
6889 .getInMemoryModuleCache()
6890 .isPCMFinal(ModuleFileName);
6891}
6892
6893llvm::iterator_range<ASTReader::ModuleDeclIterator>
6895 return llvm::make_range(
6896 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
6897 ModuleDeclIterator(this, &Mod,
6899}
6900
6902 auto I = GlobalSkippedRangeMap.find(GlobalIndex);
6903 assert(I != GlobalSkippedRangeMap.end() &&
6904 "Corrupted global skipped range map");
6905 ModuleFile *M = I->second;
6906 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedSkippedRangeID;
6907 assert(LocalIndex < M->NumPreprocessedSkippedRanges);
6908 PPSkippedRange RawRange = M->PreprocessedSkippedRangeOffsets[LocalIndex];
6909 SourceRange Range(ReadSourceLocation(*M, RawRange.getBegin()),
6910 ReadSourceLocation(*M, RawRange.getEnd()));
6911 assert(Range.isValid());
6912 return Range;
6913}
6914
6915unsigned
6916ASTReader::translatePreprocessedEntityIDToIndex(PreprocessedEntityID ID) const {
6917 unsigned ModuleFileIndex = ID >> 32;
6918 assert(ModuleFileIndex && "not translating loaded MacroID?");
6919 assert(getModuleManager().size() > ModuleFileIndex - 1);
6920 ModuleFile &MF = getModuleManager()[ModuleFileIndex - 1];
6921
6922 ID &= llvm::maskTrailingOnes<PreprocessedEntityID>(32);
6923 return MF.BasePreprocessedEntityID + ID;
6924}
6925
6927 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
6928 ModuleFile &M = *PPInfo.first;
6929 unsigned LocalIndex = PPInfo.second;
6931 (static_cast<PreprocessedEntityID>(M.Index + 1) << 32) | LocalIndex;
6932 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
6933
6934 if (!PP.getPreprocessingRecord()) {
6935 Error("no preprocessing record");
6936 return nullptr;
6937 }
6938
6940 if (llvm::Error Err = M.PreprocessorDetailCursor.JumpToBit(
6941 M.MacroOffsetsBase + PPOffs.getOffset())) {
6942 Error(std::move(Err));
6943 return nullptr;
6944 }
6945
6947 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
6948 if (!MaybeEntry) {
6949 Error(MaybeEntry.takeError());
6950 return nullptr;
6951 }
6952 llvm::BitstreamEntry Entry = MaybeEntry.get();
6953
6954 if (Entry.Kind != llvm::BitstreamEntry::Record)
6955 return nullptr;
6956
6957 // Read the record.
6958 SourceRange Range(ReadSourceLocation(M, PPOffs.getBegin()),
6959 ReadSourceLocation(M, PPOffs.getEnd()));
6960 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
6961 StringRef Blob;
6963 Expected<unsigned> MaybeRecType =
6964 M.PreprocessorDetailCursor.readRecord(Entry.ID, Record, &Blob);
6965 if (!MaybeRecType) {
6966 Error(MaybeRecType.takeError());
6967 return nullptr;
6968 }
6969 switch ((PreprocessorDetailRecordTypes)MaybeRecType.get()) {
6970 case PPD_MACRO_EXPANSION: {
6971 bool isBuiltin = Record[0];
6972 IdentifierInfo *Name = nullptr;
6973 MacroDefinitionRecord *Def = nullptr;
6974 if (isBuiltin)
6975 Name = getLocalIdentifier(M, Record[1]);
6976 else {
6977 PreprocessedEntityID GlobalID =
6979 unsigned Index = translatePreprocessedEntityIDToIndex(GlobalID);
6980 Def =
6981 cast<MacroDefinitionRecord>(PPRec.getLoadedPreprocessedEntity(Index));
6982 }
6983
6984 MacroExpansion *ME;
6985 if (isBuiltin)
6986 ME = new (PPRec) MacroExpansion(Name, Range);
6987 else
6988 ME = new (PPRec) MacroExpansion(Def, Range);
6989
6990 return ME;
6991 }
6992
6993 case PPD_MACRO_DEFINITION: {
6994 // Decode the identifier info and then check again; if the macro is
6995 // still defined and associated with the identifier,
6997 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
6998
6999 if (DeserializationListener)
7000 DeserializationListener->MacroDefinitionRead(PPID, MD);
7001
7002 return MD;
7003 }
7004
7006 const char *FullFileNameStart = Blob.data() + Record[0];
7007 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
7009 if (!FullFileName.empty())
7010 File = PP.getFileManager().getOptionalFileRef(FullFileName);
7011
7012 // FIXME: Stable encoding
7014 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
7016 = new (PPRec) InclusionDirective(PPRec, Kind,
7017 StringRef(Blob.data(), Record[0]),
7018 Record[1], Record[3],
7019 File,
7020 Range);
7021 return ID;
7022 }
7023 }
7024
7025 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
7026}
7027
7028/// Find the next module that contains entities and return the ID
7029/// of the first entry.
7030///
7031/// \param SLocMapI points at a chunk of a module that contains no
7032/// preprocessed entities or the entities it contains are not the ones we are
7033/// looking for.
7034unsigned ASTReader::findNextPreprocessedEntity(
7035 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
7036 ++SLocMapI;
7037 for (GlobalSLocOffsetMapType::const_iterator
7038 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
7039 ModuleFile &M = *SLocMapI->second;
7041 return M.BasePreprocessedEntityID;
7042 }
7043
7044 return getTotalNumPreprocessedEntities();
7045}
7046
7047namespace {
7048
7049struct PPEntityComp {
7050 const ASTReader &Reader;
7051 ModuleFile &M;
7052
7053 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) {}
7054
7055 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
7056 SourceLocation LHS = getLoc(L);
7057 SourceLocation RHS = getLoc(R);
7058 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7059 }
7060
7061 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
7062 SourceLocation LHS = getLoc(L);
7063 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7064 }
7065
7066 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
7067 SourceLocation RHS = getLoc(R);
7068 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7069 }
7070
7071 SourceLocation getLoc(const PPEntityOffset &PPE) const {
7072 return Reader.ReadSourceLocation(M, PPE.getBegin());
7073 }
7074};
7075
7076} // namespace
7077
7078unsigned ASTReader::findPreprocessedEntity(SourceLocation Loc,
7079 bool EndsAfter) const {
7080 if (SourceMgr.isLocalSourceLocation(Loc))
7081 return getTotalNumPreprocessedEntities();
7082
7083 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
7084 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
7085 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
7086 "Corrupted global sloc offset map");
7087
7088 if (SLocMapI->second->NumPreprocessedEntities == 0)
7089 return findNextPreprocessedEntity(SLocMapI);
7090
7091 ModuleFile &M = *SLocMapI->second;
7092
7093 using pp_iterator = const PPEntityOffset *;
7094
7095 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
7096 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
7097
7098 size_t Count = M.NumPreprocessedEntities;
7099 size_t Half;
7100 pp_iterator First = pp_begin;
7101 pp_iterator PPI;
7102
7103 if (EndsAfter) {
7104 PPI = std::upper_bound(pp_begin, pp_end, Loc,
7105 PPEntityComp(*this, M));
7106 } else {
7107 // Do a binary search manually instead of using std::lower_bound because
7108 // The end locations of entities may be unordered (when a macro expansion
7109 // is inside another macro argument), but for this case it is not important
7110 // whether we get the first macro expansion or its containing macro.
7111 while (Count > 0) {
7112 Half = Count / 2;
7113 PPI = First;
7114 std::advance(PPI, Half);
7115 if (SourceMgr.isBeforeInTranslationUnit(
7116 ReadSourceLocation(M, PPI->getEnd()), Loc)) {
7117 First = PPI;
7118 ++First;
7119 Count = Count - Half - 1;
7120 } else
7121 Count = Half;
7122 }
7123 }
7124
7125 if (PPI == pp_end)
7126 return findNextPreprocessedEntity(SLocMapI);
7127
7128 return M.BasePreprocessedEntityID + (PPI - pp_begin);
7129}
7130
7131/// Returns a pair of [Begin, End) indices of preallocated
7132/// preprocessed entities that \arg Range encompasses.
7133std::pair<unsigned, unsigned>
7135 if (Range.isInvalid())
7136 return std::make_pair(0,0);
7137 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
7138
7139 unsigned BeginID = findPreprocessedEntity(Range.getBegin(), false);
7140 unsigned EndID = findPreprocessedEntity(Range.getEnd(), true);
7141 return std::make_pair(BeginID, EndID);
7142}
7143
7144/// Optionally returns true or false if the preallocated preprocessed
7145/// entity with index \arg Index came from file \arg FID.
7146std::optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
7147 FileID FID) {
7148 if (FID.isInvalid())
7149 return false;
7150
7151 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
7152 ModuleFile &M = *PPInfo.first;
7153 unsigned LocalIndex = PPInfo.second;
7154 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
7155
7156 SourceLocation Loc = ReadSourceLocation(M, PPOffs.getBegin());
7157 if (Loc.isInvalid())
7158 return false;
7159
7160 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
7161 return true;
7162 else
7163 return false;
7164}
7165
7166namespace {
7167
7168 /// Visitor used to search for information about a header file.
7169 class HeaderFileInfoVisitor {
7170 FileEntryRef FE;
7171 std::optional<HeaderFileInfo> HFI;
7172
7173 public:
7174 explicit HeaderFileInfoVisitor(FileEntryRef FE) : FE(FE) {}
7175
7176 bool operator()(ModuleFile &M) {
7179 if (!Table)
7180 return false;
7181
7182 // Look in the on-disk hash table for an entry for this file name.
7183 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
7184 if (Pos == Table->end())
7185 return false;
7186
7187 HFI = *Pos;
7188 return true;
7189 }
7190
7191 std::optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
7192 };
7193
7194} // namespace
7195
7197 HeaderFileInfoVisitor Visitor(FE);
7198 ModuleMgr.visit(Visitor);
7199 if (std::optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
7200 return *HFI;
7201
7202 return HeaderFileInfo();
7203}
7204
7206 using DiagState = DiagnosticsEngine::DiagState;
7208
7209 for (ModuleFile &F : ModuleMgr) {
7210 unsigned Idx = 0;
7211 auto &Record = F.PragmaDiagMappings;
7212 if (Record.empty())
7213 continue;
7214
7215 DiagStates.clear();
7216
7217 auto ReadDiagState = [&](const DiagState &BasedOn,
7218 bool IncludeNonPragmaStates) {
7219 unsigned BackrefID = Record[Idx++];
7220 if (BackrefID != 0)
7221 return DiagStates[BackrefID - 1];
7222
7223 // A new DiagState was created here.
7224 Diag.DiagStates.push_back(BasedOn);
7225 DiagState *NewState = &Diag.DiagStates.back();
7226 DiagStates.push_back(NewState);
7227 unsigned Size = Record[Idx++];
7228 assert(Idx + Size * 2 <= Record.size() &&
7229 "Invalid data, not enough diag/map pairs");
7230 while (Size--) {
7231 unsigned DiagID = Record[Idx++];
7232 DiagnosticMapping NewMapping =
7234 if (!NewMapping.isPragma() && !IncludeNonPragmaStates)
7235 continue;
7236
7237 DiagnosticMapping &Mapping = NewState->getOrAddMapping(DiagID);
7238
7239 // If this mapping was specified as a warning but the severity was
7240 // upgraded due to diagnostic settings, simulate the current diagnostic
7241 // settings (and use a warning).
7242 if (NewMapping.wasUpgradedFromWarning() && !Mapping.isErrorOrFatal()) {
7244 NewMapping.setUpgradedFromWarning(false);
7245 }
7246
7247 Mapping = NewMapping;
7248 }
7249 return NewState;
7250 };
7251
7252 // Read the first state.
7253 DiagState *FirstState;
7254 if (F.Kind == MK_ImplicitModule) {
7255 // Implicitly-built modules are reused with different diagnostic
7256 // settings. Use the initial diagnostic state from Diag to simulate this
7257 // compilation's diagnostic settings.
7258 FirstState = Diag.DiagStatesByLoc.FirstDiagState;
7259 DiagStates.push_back(FirstState);
7260
7261 // Skip the initial diagnostic state from the serialized module.
7262 assert(Record[1] == 0 &&
7263 "Invalid data, unexpected backref in initial state");
7264 Idx = 3 + Record[2] * 2;
7265 assert(Idx < Record.size() &&
7266 "Invalid data, not enough state change pairs in initial state");
7267 } else if (F.isModule()) {
7268 // For an explicit module, preserve the flags from the module build
7269 // command line (-w, -Weverything, -Werror, ...) along with any explicit
7270 // -Wblah flags.
7271 unsigned Flags = Record[Idx++];
7272 DiagState Initial(*Diag.getDiagnosticIDs());
7273 Initial.SuppressSystemWarnings = Flags & 1; Flags >>= 1;
7274 Initial.ErrorsAsFatal = Flags & 1; Flags >>= 1;
7275 Initial.WarningsAsErrors = Flags & 1; Flags >>= 1;
7276 Initial.EnableAllWarnings = Flags & 1; Flags >>= 1;
7277 Initial.IgnoreAllWarnings = Flags & 1; Flags >>= 1;
7278 Initial.ExtBehavior = (diag::Severity)Flags;
7279 FirstState = ReadDiagState(Initial, true);
7280
7281 assert(F.OriginalSourceFileID.isValid());
7282
7283 // Set up the root buffer of the module to start with the initial
7284 // diagnostic state of the module itself, to cover files that contain no
7285 // explicit transitions (for which we did not serialize anything).
7286 Diag.DiagStatesByLoc.Files[F.OriginalSourceFileID]
7287 .StateTransitions.push_back({FirstState, 0});
7288 } else {
7289 // For prefix ASTs, start with whatever the user configured on the
7290 // command line.
7291 Idx++; // Skip flags.
7292 FirstState = ReadDiagState(*Diag.DiagStatesByLoc.CurDiagState, false);
7293 }
7294
7295 // Read the state transitions.
7296 unsigned NumLocations = Record[Idx++];
7297 while (NumLocations--) {
7298 assert(Idx < Record.size() &&
7299 "Invalid data, missing pragma diagnostic states");
7300 FileID FID = ReadFileID(F, Record, Idx);
7301 assert(FID.isValid() && "invalid FileID for transition");
7302 unsigned Transitions = Record[Idx++];
7303
7304 // Note that we don't need to set up Parent/ParentOffset here, because
7305 // we won't be changing the diagnostic state within imported FileIDs
7306 // (other than perhaps appending to the main source file, which has no
7307 // parent).
7308 auto &F = Diag.DiagStatesByLoc.Files[FID];
7309 F.StateTransitions.reserve(F.StateTransitions.size() + Transitions);
7310 for (unsigned I = 0; I != Transitions; ++I) {
7311 unsigned Offset = Record[Idx++];
7312 auto *State = ReadDiagState(*FirstState, false);
7313 F.StateTransitions.push_back({State, Offset});
7314 }
7315 }
7316
7317 // Read the final state.
7318 assert(Idx < Record.size() &&
7319 "Invalid data, missing final pragma diagnostic state");
7320 SourceLocation CurStateLoc = ReadSourceLocation(F, Record[Idx++]);
7321 auto *CurState = ReadDiagState(*FirstState, false);
7322
7323 if (!F.isModule()) {
7324 Diag.DiagStatesByLoc.CurDiagState = CurState;
7325 Diag.DiagStatesByLoc.CurDiagStateLoc = CurStateLoc;
7326
7327 // Preserve the property that the imaginary root file describes the
7328 // current state.
7329 FileID NullFile;
7330 auto &T = Diag.DiagStatesByLoc.Files[NullFile].StateTransitions;
7331 if (T.empty())
7332 T.push_back({CurState, 0});
7333 else
7334 T[0].State = CurState;
7335 }
7336
7337 // Restore the push stack so that unmatched pushes from a preamble are
7338 // visible when the main file is parsed, allowing the corresponding
7339 // `#pragma diagnostic pop` to succeed.
7340 assert(Idx < Record.size() &&
7341 "Invalid data, missing diagnostic push stack");
7342 unsigned NumPushes = Record[Idx++];
7343 for (unsigned I = 0; I != NumPushes; ++I) {
7344 auto *State = ReadDiagState(*FirstState, false);
7345 if (!F.isModule())
7346 Diag.DiagStateOnPushStack.push_back(State);
7347 }
7348
7349 // Don't try to read these mappings again.
7350 Record.clear();
7351 }
7352}
7353
7354/// Get the correct cursor and offset for loading a type.
7355ASTReader::RecordLocation ASTReader::TypeCursorForIndex(TypeID ID) {
7356 auto [M, Index] = translateTypeIDToIndex(ID);
7357 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex].get() +
7359}
7360
7361static std::optional<Type::TypeClass> getTypeClassForCode(TypeCode code) {
7362 switch (code) {
7363#define TYPE_BIT_CODE(CLASS_ID, CODE_ID, CODE_VALUE) \
7364 case TYPE_##CODE_ID: return Type::CLASS_ID;
7365#include "clang/Serialization/TypeBitCodes.def"
7366 default:
7367 return std::nullopt;
7368 }
7369}
7370
7371/// Read and return the type with the given index..
7372///
7373/// The index is the type ID, shifted and minus the number of predefs. This
7374/// routine actually reads the record corresponding to the type at the given
7375/// location. It is a helper routine for GetType, which deals with reading type
7376/// IDs.
7377QualType ASTReader::readTypeRecord(TypeID ID) {
7378 assert(ContextObj && "reading type with no AST context");
7379 ASTContext &Context = *ContextObj;
7380 RecordLocation Loc = TypeCursorForIndex(ID);
7381 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
7382
7383 // Keep track of where we are in the stream, then jump back there
7384 // after reading this type.
7385 SavedStreamPosition SavedPosition(DeclsCursor);
7386
7387 ReadingKindTracker ReadingKind(Read_Type, *this);
7388
7389 // Note that we are loading a type record.
7390 Deserializing AType(this);
7391
7392 if (llvm::Error Err = DeclsCursor.JumpToBit(Loc.Offset)) {
7393 Error(std::move(Err));
7394 return QualType();
7395 }
7396 Expected<unsigned> RawCode = DeclsCursor.ReadCode();
7397 if (!RawCode) {
7398 Error(RawCode.takeError());
7399 return QualType();
7400 }
7401
7402 ASTRecordReader Record(*this, *Loc.F);
7403 Expected<unsigned> Code = Record.readRecord(DeclsCursor, RawCode.get());
7404 if (!Code) {
7405 Error(Code.takeError());
7406 return QualType();
7407 }
7408 if (Code.get() == TYPE_EXT_QUAL) {
7409 QualType baseType = Record.readQualType();
7410 Qualifiers quals = Record.readQualifiers();
7411 return Context.getQualifiedType(baseType, quals);
7412 }
7413
7414 auto maybeClass = getTypeClassForCode((TypeCode) Code.get());
7415 if (!maybeClass) {
7416 Error("Unexpected code for type");
7417 return QualType();
7418 }
7419
7420 serialization::AbstractTypeReader<ASTRecordReader> TypeReader(Record);
7421 return TypeReader.read(*maybeClass);
7422}
7423
7424namespace clang {
7425
7426class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
7427 ASTRecordReader &Reader;
7428
7429 SourceLocation readSourceLocation() { return Reader.readSourceLocation(); }
7430 SourceRange readSourceRange() { return Reader.readSourceRange(); }
7431
7432 TypeSourceInfo *GetTypeSourceInfo() {
7433 return Reader.readTypeSourceInfo();
7434 }
7435
7436 NestedNameSpecifierLoc ReadNestedNameSpecifierLoc() {
7437 return Reader.readNestedNameSpecifierLoc();
7438 }
7439
7440 Attr *ReadAttr() {
7441 return Reader.readAttr();
7442 }
7443
7444public:
7445 TypeLocReader(ASTRecordReader &Reader) : Reader(Reader) {}
7446
7447 // We want compile-time assurance that we've enumerated all of
7448 // these, so unfortunately we have to declare them first, then
7449 // define them out-of-line.
7450#define ABSTRACT_TYPELOC(CLASS, PARENT)
7451#define TYPELOC(CLASS, PARENT) \
7452 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
7453#include "clang/AST/TypeLocNodes.def"
7454
7457 void VisitTagTypeLoc(TagTypeLoc TL);
7458};
7459
7460} // namespace clang
7461
7462void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
7463 // nothing to do
7464}
7465
7466void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
7467 TL.setBuiltinLoc(readSourceLocation());
7468 if (TL.needsExtraLocalData()) {
7469 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Reader.readInt()));
7470 TL.setWrittenSignSpec(static_cast<TypeSpecifierSign>(Reader.readInt()));
7471 TL.setWrittenWidthSpec(static_cast<TypeSpecifierWidth>(Reader.readInt()));
7472 TL.setModeAttr(Reader.readInt());
7473 }
7474}
7475
7476void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
7477 TL.setNameLoc(readSourceLocation());
7478}
7479
7480void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
7481 TL.setStarLoc(readSourceLocation());
7482}
7483
7484void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
7485 // nothing to do
7486}
7487
7488void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
7489 // nothing to do
7490}
7491
7492void TypeLocReader::VisitArrayParameterTypeLoc(ArrayParameterTypeLoc TL) {
7493 // nothing to do
7494}
7495
7496void TypeLocReader::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
7497 TL.setExpansionLoc(readSourceLocation());
7498}
7499
7500void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
7501 TL.setCaretLoc(readSourceLocation());
7502}
7503
7504void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
7505 TL.setAmpLoc(readSourceLocation());
7506}
7507
7508void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
7509 TL.setAmpAmpLoc(readSourceLocation());
7510}
7511
7512void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
7513 TL.setStarLoc(readSourceLocation());
7514 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
7515}
7516
7518 TL.setLBracketLoc(readSourceLocation());
7519 TL.setRBracketLoc(readSourceLocation());
7520 if (Reader.readBool())
7521 TL.setSizeExpr(Reader.readExpr());
7522 else
7523 TL.setSizeExpr(nullptr);
7524}
7525
7526void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
7527 VisitArrayTypeLoc(TL);
7528}
7529
7530void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
7531 VisitArrayTypeLoc(TL);
7532}
7533
7534void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
7535 VisitArrayTypeLoc(TL);
7536}
7537
7538void TypeLocReader::VisitDependentSizedArrayTypeLoc(
7539 DependentSizedArrayTypeLoc TL) {
7540 VisitArrayTypeLoc(TL);
7541}
7542
7543void TypeLocReader::VisitDependentAddressSpaceTypeLoc(
7544 DependentAddressSpaceTypeLoc TL) {
7545
7546 TL.setAttrNameLoc(readSourceLocation());
7547 TL.setAttrOperandParensRange(readSourceRange());
7548 TL.setAttrExprOperand(Reader.readExpr());
7549}
7550
7551void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
7552 DependentSizedExtVectorTypeLoc TL) {
7553 TL.setNameLoc(readSourceLocation());
7554}
7555
7556void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
7557 TL.setNameLoc(readSourceLocation());
7558}
7559
7560void TypeLocReader::VisitDependentVectorTypeLoc(
7561 DependentVectorTypeLoc TL) {
7562 TL.setNameLoc(readSourceLocation());
7563}
7564
7565void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
7566 TL.setNameLoc(readSourceLocation());
7567}
7568
7569void TypeLocReader::VisitConstantMatrixTypeLoc(ConstantMatrixTypeLoc TL) {
7570 TL.setAttrNameLoc(readSourceLocation());
7571 TL.setAttrOperandParensRange(readSourceRange());
7572 TL.setAttrRowOperand(Reader.readExpr());
7573 TL.setAttrColumnOperand(Reader.readExpr());
7574}
7575
7576void TypeLocReader::VisitDependentSizedMatrixTypeLoc(
7577 DependentSizedMatrixTypeLoc TL) {
7578 TL.setAttrNameLoc(readSourceLocation());
7579 TL.setAttrOperandParensRange(readSourceRange());
7580 TL.setAttrRowOperand(Reader.readExpr());
7581 TL.setAttrColumnOperand(Reader.readExpr());
7582}
7583
7585 TL.setLocalRangeBegin(readSourceLocation());
7586 TL.setLParenLoc(readSourceLocation());
7587 TL.setRParenLoc(readSourceLocation());
7588 TL.setExceptionSpecRange(readSourceRange());
7589 TL.setLocalRangeEnd(readSourceLocation());
7590 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
7591 TL.setParam(i, Reader.readDeclAs<ParmVarDecl>());
7592 }
7593}
7594
7595void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
7596 VisitFunctionTypeLoc(TL);
7597}
7598
7599void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
7600 VisitFunctionTypeLoc(TL);
7601}
7602
7603void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
7604 SourceLocation ElaboratedKeywordLoc = readSourceLocation();
7605 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc();
7606 SourceLocation NameLoc = readSourceLocation();
7607 TL.set(ElaboratedKeywordLoc, QualifierLoc, NameLoc);
7608}
7609
7610void TypeLocReader::VisitUsingTypeLoc(UsingTypeLoc TL) {
7611 SourceLocation ElaboratedKeywordLoc = readSourceLocation();
7612 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc();
7613 SourceLocation NameLoc = readSourceLocation();
7614 TL.set(ElaboratedKeywordLoc, QualifierLoc, NameLoc);
7615}
7616
7617void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
7618 SourceLocation ElaboratedKeywordLoc = readSourceLocation();
7619 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc();
7620 SourceLocation NameLoc = readSourceLocation();
7621 TL.set(ElaboratedKeywordLoc, QualifierLoc, NameLoc);
7622}
7623
7624void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
7625 TL.setTypeofLoc(readSourceLocation());
7626 TL.setLParenLoc(readSourceLocation());
7627 TL.setRParenLoc(readSourceLocation());
7628}
7629
7630void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
7631 TL.setTypeofLoc(readSourceLocation());
7632 TL.setLParenLoc(readSourceLocation());
7633 TL.setRParenLoc(readSourceLocation());
7634 TL.setUnmodifiedTInfo(GetTypeSourceInfo());
7635}
7636
7637void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
7638 TL.setDecltypeLoc(readSourceLocation());
7639 TL.setRParenLoc(readSourceLocation());
7640}
7641
7642void TypeLocReader::VisitPackIndexingTypeLoc(PackIndexingTypeLoc TL) {
7643 TL.setEllipsisLoc(readSourceLocation());
7644}
7645
7646void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
7647 TL.setKWLoc(readSourceLocation());
7648 TL.setLParenLoc(readSourceLocation());
7649 TL.setRParenLoc(readSourceLocation());
7650 TL.setUnderlyingTInfo(GetTypeSourceInfo());
7651}
7652
7654 auto NNS = readNestedNameSpecifierLoc();
7655 auto TemplateKWLoc = readSourceLocation();
7656 auto ConceptNameLoc = readDeclarationNameInfo();
7657 auto FoundDecl = readDeclAs<NamedDecl>();
7658 auto NamedConcept = readDeclAs<ConceptDecl>();
7659 auto *CR = ConceptReference::Create(
7660 getContext(), NNS, TemplateKWLoc, ConceptNameLoc, FoundDecl, NamedConcept,
7661 (readBool() ? readASTTemplateArgumentListInfo() : nullptr));
7662 return CR;
7663}
7664
7665void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
7666 TL.setNameLoc(readSourceLocation());
7667 if (Reader.readBool())
7668 TL.setConceptReference(Reader.readConceptReference());
7669 if (Reader.readBool())
7670 TL.setRParenLoc(readSourceLocation());
7671}
7672
7673void TypeLocReader::VisitDeducedTemplateSpecializationTypeLoc(
7675 TL.setElaboratedKeywordLoc(readSourceLocation());
7676 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
7677 TL.setTemplateNameLoc(readSourceLocation());
7678}
7679
7681 TL.setElaboratedKeywordLoc(readSourceLocation());
7682 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
7683 TL.setNameLoc(readSourceLocation());
7684}
7685
7686void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
7687 VisitTagTypeLoc(TL);
7688}
7689
7690void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
7691 VisitTagTypeLoc(TL);
7692}
7693
7694void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) { VisitTagTypeLoc(TL); }
7695
7696void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
7697 TL.setAttr(ReadAttr());
7698}
7699
7700void TypeLocReader::VisitCountAttributedTypeLoc(CountAttributedTypeLoc TL) {
7701 // Nothing to do
7702}
7703
7704void TypeLocReader::VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) {
7705 // Nothing to do.
7706}
7707
7708void TypeLocReader::VisitOverflowBehaviorTypeLoc(OverflowBehaviorTypeLoc TL) {
7709 TL.setAttrLoc(readSourceLocation());
7710}
7711
7712void TypeLocReader::VisitHLSLAttributedResourceTypeLoc(
7713 HLSLAttributedResourceTypeLoc TL) {
7714 // Nothing to do.
7715}
7716
7717void TypeLocReader::VisitHLSLInlineSpirvTypeLoc(HLSLInlineSpirvTypeLoc TL) {
7718 // Nothing to do.
7719}
7720
7721void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
7722 TL.setNameLoc(readSourceLocation());
7723}
7724
7725void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
7726 SubstTemplateTypeParmTypeLoc TL) {
7727 TL.setNameLoc(readSourceLocation());
7728}
7729
7730void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
7731 SubstTemplateTypeParmPackTypeLoc TL) {
7732 TL.setNameLoc(readSourceLocation());
7733}
7734
7735void TypeLocReader::VisitSubstBuiltinTemplatePackTypeLoc(
7736 SubstBuiltinTemplatePackTypeLoc TL) {
7737 TL.setNameLoc(readSourceLocation());
7738}
7739
7740void TypeLocReader::VisitTemplateSpecializationTypeLoc(
7741 TemplateSpecializationTypeLoc TL) {
7742 SourceLocation ElaboratedKeywordLoc = readSourceLocation();
7743 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc();
7744 SourceLocation TemplateKeywordLoc = readSourceLocation();
7745 SourceLocation NameLoc = readSourceLocation();
7746 SourceLocation LAngleLoc = readSourceLocation();
7747 SourceLocation RAngleLoc = readSourceLocation();
7748 TL.set(ElaboratedKeywordLoc, QualifierLoc, TemplateKeywordLoc, NameLoc,
7749 LAngleLoc, RAngleLoc);
7750 MutableArrayRef<TemplateArgumentLocInfo> Args = TL.getArgLocInfos();
7751 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
7752 Args[I] = Reader.readTemplateArgumentLocInfo(
7753 TL.getTypePtr()->template_arguments()[I].getKind());
7754}
7755
7756void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
7757 TL.setLParenLoc(readSourceLocation());
7758 TL.setRParenLoc(readSourceLocation());
7759}
7760
7761void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
7762 TL.setElaboratedKeywordLoc(readSourceLocation());
7763 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
7764 TL.setNameLoc(readSourceLocation());
7765}
7766
7767void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
7768 TL.setEllipsisLoc(readSourceLocation());
7769}
7770
7771void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
7772 TL.setNameLoc(readSourceLocation());
7773 TL.setNameEndLoc(readSourceLocation());
7774}
7775
7776void TypeLocReader::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
7777 if (TL.getNumProtocols()) {
7778 TL.setProtocolLAngleLoc(readSourceLocation());
7779 TL.setProtocolRAngleLoc(readSourceLocation());
7780 }
7781 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
7782 TL.setProtocolLoc(i, readSourceLocation());
7783}
7784
7785void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
7786 TL.setHasBaseTypeAsWritten(Reader.readBool());
7787 TL.setTypeArgsLAngleLoc(readSourceLocation());
7788 TL.setTypeArgsRAngleLoc(readSourceLocation());
7789 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
7790 TL.setTypeArgTInfo(i, GetTypeSourceInfo());
7791 TL.setProtocolLAngleLoc(readSourceLocation());
7792 TL.setProtocolRAngleLoc(readSourceLocation());
7793 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
7794 TL.setProtocolLoc(i, readSourceLocation());
7795}
7796
7797void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
7798 TL.setStarLoc(readSourceLocation());
7799}
7800
7801void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
7802 TL.setKWLoc(readSourceLocation());
7803 TL.setLParenLoc(readSourceLocation());
7804 TL.setRParenLoc(readSourceLocation());
7805}
7806
7807void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) {
7808 TL.setKWLoc(readSourceLocation());
7809}
7810
7811void TypeLocReader::VisitBitIntTypeLoc(clang::BitIntTypeLoc TL) {
7812 TL.setNameLoc(readSourceLocation());
7813}
7814
7815void TypeLocReader::VisitDependentBitIntTypeLoc(
7816 clang::DependentBitIntTypeLoc TL) {
7817 TL.setNameLoc(readSourceLocation());
7818}
7819
7820void TypeLocReader::VisitPredefinedSugarTypeLoc(PredefinedSugarTypeLoc TL) {
7821 // Nothing to do.
7822}
7823
7825 TypeLocReader TLR(*this);
7826 for (; !TL.isNull(); TL = TL.getNextTypeLoc())
7827 TLR.Visit(TL);
7828}
7829
7831 QualType InfoTy = readType();
7832 if (InfoTy.isNull())
7833 return nullptr;
7834
7835 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
7836 readTypeLoc(TInfo->getTypeLoc());
7837 return TInfo;
7838}
7839
7841 return (ID & llvm::maskTrailingOnes<TypeID>(32)) >> Qualifiers::FastWidth;
7842}
7843
7845 return ID >> 32;
7846}
7847
7849 // We don't need to erase the higher bits since if these bits are not 0,
7850 // it must be larger than NUM_PREDEF_TYPE_IDS.
7852}
7853
7854std::pair<ModuleFile *, unsigned>
7855ASTReader::translateTypeIDToIndex(serialization::TypeID ID) const {
7856 assert(!isPredefinedType(ID) &&
7857 "Predefined type shouldn't be in TypesLoaded");
7858 unsigned ModuleFileIndex = getModuleFileIndexForTypeID(ID);
7859 assert(ModuleFileIndex && "Untranslated Local Decl?");
7860
7861 ModuleFile *OwningModuleFile = &getModuleManager()[ModuleFileIndex - 1];
7862 assert(OwningModuleFile &&
7863 "untranslated type ID or local type ID shouldn't be in TypesLoaded");
7864
7865 return {OwningModuleFile,
7866 OwningModuleFile->BaseTypeIndex + getIndexForTypeID(ID)};
7867}
7868
7870 assert(ContextObj && "reading type with no AST context");
7871 ASTContext &Context = *ContextObj;
7872
7873 unsigned FastQuals = ID & Qualifiers::FastMask;
7874
7875 if (isPredefinedType(ID)) {
7876 QualType T;
7877 unsigned Index = getIndexForTypeID(ID);
7878 switch ((PredefinedTypeIDs)Index) {
7880 // We should never use this one.
7881 llvm_unreachable("Invalid predefined type");
7882 break;
7884 return QualType();
7886 T = Context.VoidTy;
7887 break;
7889 T = Context.BoolTy;
7890 break;
7893 // FIXME: Check that the signedness of CharTy is correct!
7894 T = Context.CharTy;
7895 break;
7897 T = Context.UnsignedCharTy;
7898 break;
7900 T = Context.UnsignedShortTy;
7901 break;
7903 T = Context.UnsignedIntTy;
7904 break;
7906 T = Context.UnsignedLongTy;
7907 break;
7909 T = Context.UnsignedLongLongTy;
7910 break;
7912 T = Context.UnsignedInt128Ty;
7913 break;
7915 T = Context.SignedCharTy;
7916 break;
7918 T = Context.WCharTy;
7919 break;
7921 T = Context.ShortTy;
7922 break;
7923 case PREDEF_TYPE_INT_ID:
7924 T = Context.IntTy;
7925 break;
7927 T = Context.LongTy;
7928 break;
7930 T = Context.LongLongTy;
7931 break;
7933 T = Context.Int128Ty;
7934 break;
7936 T = Context.BFloat16Ty;
7937 break;
7939 T = Context.HalfTy;
7940 break;
7942 T = Context.FloatTy;
7943 break;
7945 T = Context.DoubleTy;
7946 break;
7948 T = Context.LongDoubleTy;
7949 break;
7951 T = Context.ShortAccumTy;
7952 break;
7954 T = Context.AccumTy;
7955 break;
7957 T = Context.LongAccumTy;
7958 break;
7960 T = Context.UnsignedShortAccumTy;
7961 break;
7963 T = Context.UnsignedAccumTy;
7964 break;
7966 T = Context.UnsignedLongAccumTy;
7967 break;
7969 T = Context.ShortFractTy;
7970 break;
7972 T = Context.FractTy;
7973 break;
7975 T = Context.LongFractTy;
7976 break;
7978 T = Context.UnsignedShortFractTy;
7979 break;
7981 T = Context.UnsignedFractTy;
7982 break;
7984 T = Context.UnsignedLongFractTy;
7985 break;
7987 T = Context.SatShortAccumTy;
7988 break;
7990 T = Context.SatAccumTy;
7991 break;
7993 T = Context.SatLongAccumTy;
7994 break;
7996 T = Context.SatUnsignedShortAccumTy;
7997 break;
7999 T = Context.SatUnsignedAccumTy;
8000 break;
8002 T = Context.SatUnsignedLongAccumTy;
8003 break;
8005 T = Context.SatShortFractTy;
8006 break;
8008 T = Context.SatFractTy;
8009 break;
8011 T = Context.SatLongFractTy;
8012 break;
8014 T = Context.SatUnsignedShortFractTy;
8015 break;
8017 T = Context.SatUnsignedFractTy;
8018 break;
8020 T = Context.SatUnsignedLongFractTy;
8021 break;
8023 T = Context.Float16Ty;
8024 break;
8026 T = Context.Float128Ty;
8027 break;
8029 T = Context.Ibm128Ty;
8030 break;
8032 T = Context.OverloadTy;
8033 break;
8035 T = Context.UnresolvedTemplateTy;
8036 break;
8038 T = Context.BoundMemberTy;
8039 break;
8041 T = Context.PseudoObjectTy;
8042 break;
8044 T = Context.DependentTy;
8045 break;
8047 T = Context.UnknownAnyTy;
8048 break;
8050 T = Context.NullPtrTy;
8051 break;
8053 T = Context.Char8Ty;
8054 break;
8056 T = Context.Char16Ty;
8057 break;
8059 T = Context.Char32Ty;
8060 break;
8062 T = Context.ObjCBuiltinIdTy;
8063 break;
8065 T = Context.ObjCBuiltinClassTy;
8066 break;
8068 T = Context.ObjCBuiltinSelTy;
8069 break;
8070#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8071 case PREDEF_TYPE_##Id##_ID: \
8072 T = Context.SingletonId; \
8073 break;
8074#include "clang/Basic/OpenCLImageTypes.def"
8075#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
8076 case PREDEF_TYPE_##Id##_ID: \
8077 T = Context.Id##Ty; \
8078 break;
8079#include "clang/Basic/OpenCLExtensionTypes.def"
8081 T = Context.OCLSamplerTy;
8082 break;
8084 T = Context.OCLEventTy;
8085 break;
8087 T = Context.OCLClkEventTy;
8088 break;
8090 T = Context.OCLQueueTy;
8091 break;
8093 T = Context.OCLReserveIDTy;
8094 break;
8096 T = Context.getAutoDeductType();
8097 break;
8099 T = Context.getAutoRRefDeductType();
8100 break;
8102 T = Context.ARCUnbridgedCastTy;
8103 break;
8105 T = Context.BuiltinFnTy;
8106 break;
8108 T = Context.IncompleteMatrixIdxTy;
8109 break;
8111 T = Context.ArraySectionTy;
8112 break;
8114 T = Context.OMPArrayShapingTy;
8115 break;
8117 T = Context.OMPIteratorTy;
8118 break;
8119#define SVE_TYPE(Name, Id, SingletonId) \
8120 case PREDEF_TYPE_##Id##_ID: \
8121 T = Context.SingletonId; \
8122 break;
8123#include "clang/Basic/AArch64ACLETypes.def"
8124#define PPC_VECTOR_TYPE(Name, Id, Size) \
8125 case PREDEF_TYPE_##Id##_ID: \
8126 T = Context.Id##Ty; \
8127 break;
8128#include "clang/Basic/PPCTypes.def"
8129#define RVV_TYPE(Name, Id, SingletonId) \
8130 case PREDEF_TYPE_##Id##_ID: \
8131 T = Context.SingletonId; \
8132 break;
8133#include "clang/Basic/RISCVVTypes.def"
8134#define WASM_TYPE(Name, Id, SingletonId) \
8135 case PREDEF_TYPE_##Id##_ID: \
8136 T = Context.SingletonId; \
8137 break;
8138#include "clang/Basic/WebAssemblyReferenceTypes.def"
8139#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) \
8140 case PREDEF_TYPE_##Id##_ID: \
8141 T = Context.SingletonId; \
8142 break;
8143#include "clang/Basic/AMDGPUTypes.def"
8144#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
8145 case PREDEF_TYPE_##Id##_ID: \
8146 T = Context.SingletonId; \
8147 break;
8148#include "clang/Basic/HLSLIntangibleTypes.def"
8149 }
8150
8151 assert(!T.isNull() && "Unknown predefined type");
8152 return T.withFastQualifiers(FastQuals);
8153 }
8154
8155 unsigned Index = translateTypeIDToIndex(ID).second;
8156
8157 assert(Index < TypesLoaded.size() && "Type index out-of-range");
8158 if (TypesLoaded[Index].isNull()) {
8159 TypesLoaded[Index] = readTypeRecord(ID);
8160 if (TypesLoaded[Index].isNull())
8161 return QualType();
8162
8163 TypesLoaded[Index]->setFromAST();
8164 if (DeserializationListener)
8165 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
8166 TypesLoaded[Index]);
8167 }
8168
8169 return TypesLoaded[Index].withFastQualifiers(FastQuals);
8170}
8171
8173 return GetType(getGlobalTypeID(F, LocalID));
8174}
8175
8177 LocalTypeID LocalID) const {
8178 if (isPredefinedType(LocalID))
8179 return LocalID;
8180
8181 if (!F.ModuleOffsetMap.empty())
8182 ReadModuleOffsetMap(F);
8183
8184 unsigned ModuleFileIndex = getModuleFileIndexForTypeID(LocalID);
8185 LocalID &= llvm::maskTrailingOnes<TypeID>(32);
8186
8187 if (ModuleFileIndex == 0)
8189
8190 ModuleFile &MF =
8191 ModuleFileIndex ? *F.TransitiveImports[ModuleFileIndex - 1] : F;
8192 ModuleFileIndex = MF.Index + 1;
8193 return ((uint64_t)ModuleFileIndex << 32) | LocalID;
8194}
8195
8198 switch (Kind) {
8200 return readExpr();
8202 return readTypeSourceInfo();
8205 SourceLocation TemplateKWLoc = readSourceLocation();
8207 SourceLocation TemplateNameLoc = readSourceLocation();
8210 : SourceLocation();
8211 return TemplateArgumentLocInfo(getASTContext(), TemplateKWLoc, QualifierLoc,
8212 TemplateNameLoc, EllipsisLoc);
8213 }
8220 // FIXME: Is this right?
8221 return TemplateArgumentLocInfo();
8222 }
8223 llvm_unreachable("unexpected template argument loc");
8224}
8225
8235
8238 Result.setLAngleLoc(readSourceLocation());
8239 Result.setRAngleLoc(readSourceLocation());
8240 unsigned NumArgsAsWritten = readInt();
8241 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
8242 Result.addArgument(readTemplateArgumentLoc());
8243}
8244
8251
8253
8255 if (NumCurrentElementsDeserializing) {
8256 // We arrange to not care about the complete redeclaration chain while we're
8257 // deserializing. Just remember that the AST has marked this one as complete
8258 // but that it's not actually complete yet, so we know we still need to
8259 // complete it later.
8260 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
8261 return;
8262 }
8263
8264 if (!D->getDeclContext()) {
8265 assert(isa<TranslationUnitDecl>(D) && "Not a TU?");
8266 return;
8267 }
8268
8269 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
8270
8271 // If this is a named declaration, complete it by looking it up
8272 // within its context.
8273 //
8274 // FIXME: Merging a function definition should merge
8275 // all mergeable entities within it.
8277 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
8278 if (!getContext().getLangOpts().CPlusPlus &&
8280 // Outside of C++, we don't have a lookup table for the TU, so update
8281 // the identifier instead. (For C++ modules, we don't store decls
8282 // in the serialized identifier table, so we do the lookup in the TU.)
8283 auto *II = Name.getAsIdentifierInfo();
8284 assert(II && "non-identifier name in C?");
8285 if (II->isOutOfDate())
8287 } else
8288 DC->lookup(Name);
8290 // Find all declarations of this kind from the relevant context.
8291 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
8292 auto *DC = cast<DeclContext>(DCDecl);
8295 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
8296 }
8297 }
8298 }
8299
8302 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
8303 Template = CTSD->getSpecializedTemplate();
8304 Args = CTSD->getTemplateArgs().asArray();
8305 } else if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D)) {
8306 Template = VTSD->getSpecializedTemplate();
8307 Args = VTSD->getTemplateArgs().asArray();
8308 } else if (auto *FD = dyn_cast<FunctionDecl>(D)) {
8309 if (auto *Tmplt = FD->getPrimaryTemplate()) {
8310 Template = Tmplt;
8311 Args = FD->getTemplateSpecializationArgs()->asArray();
8312 }
8313 }
8314
8315 if (Template)
8316 Template->loadLazySpecializationsImpl(Args);
8317}
8318
8321 RecordLocation Loc = getLocalBitOffset(Offset);
8322 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
8323 SavedStreamPosition SavedPosition(Cursor);
8324 if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {
8325 Error(std::move(Err));
8326 return nullptr;
8327 }
8328 ReadingKindTracker ReadingKind(Read_Decl, *this);
8329 Deserializing D(this);
8330
8331 Expected<unsigned> MaybeCode = Cursor.ReadCode();
8332 if (!MaybeCode) {
8333 Error(MaybeCode.takeError());
8334 return nullptr;
8335 }
8336 unsigned Code = MaybeCode.get();
8337
8338 ASTRecordReader Record(*this, *Loc.F);
8339 Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code);
8340 if (!MaybeRecCode) {
8341 Error(MaybeRecCode.takeError());
8342 return nullptr;
8343 }
8344 if (MaybeRecCode.get() != DECL_CXX_CTOR_INITIALIZERS) {
8345 Error("malformed AST file: missing C++ ctor initializers");
8346 return nullptr;
8347 }
8348
8349 return Record.readCXXCtorInitializers();
8350}
8351
8353 assert(ContextObj && "reading base specifiers with no AST context");
8354 ASTContext &Context = *ContextObj;
8355
8356 RecordLocation Loc = getLocalBitOffset(Offset);
8357 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
8358 SavedStreamPosition SavedPosition(Cursor);
8359 if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {
8360 Error(std::move(Err));
8361 return nullptr;
8362 }
8363 ReadingKindTracker ReadingKind(Read_Decl, *this);
8364 Deserializing D(this);
8365
8366 Expected<unsigned> MaybeCode = Cursor.ReadCode();
8367 if (!MaybeCode) {
8368 Error(MaybeCode.takeError());
8369 return nullptr;
8370 }
8371 unsigned Code = MaybeCode.get();
8372
8373 ASTRecordReader Record(*this, *Loc.F);
8374 Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code);
8375 if (!MaybeRecCode) {
8376 Error(MaybeCode.takeError());
8377 return nullptr;
8378 }
8379 unsigned RecCode = MaybeRecCode.get();
8380
8381 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
8382 Error("malformed AST file: missing C++ base specifiers");
8383 return nullptr;
8384 }
8385
8386 unsigned NumBases = Record.readInt();
8387 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
8388 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
8389 for (unsigned I = 0; I != NumBases; ++I)
8390 Bases[I] = Record.readCXXBaseSpecifier();
8391 return Bases;
8392}
8393
8395 LocalDeclID LocalID) const {
8396 if (LocalID < NUM_PREDEF_DECL_IDS)
8397 return GlobalDeclID(LocalID.getRawValue());
8398
8399 unsigned OwningModuleFileIndex = LocalID.getModuleFileIndex();
8400 DeclID ID = LocalID.getLocalDeclIndex();
8401
8402 if (!F.ModuleOffsetMap.empty())
8403 ReadModuleOffsetMap(F);
8404
8405 ModuleFile *OwningModuleFile =
8406 OwningModuleFileIndex == 0
8407 ? &F
8408 : F.TransitiveImports[OwningModuleFileIndex - 1];
8409
8410 if (OwningModuleFileIndex == 0)
8411 ID -= NUM_PREDEF_DECL_IDS;
8412
8413 uint64_t NewModuleFileIndex = OwningModuleFile->Index + 1;
8414 return GlobalDeclID(NewModuleFileIndex, ID);
8415}
8416
8418 // Predefined decls aren't from any module.
8419 if (ID < NUM_PREDEF_DECL_IDS)
8420 return false;
8421
8422 unsigned ModuleFileIndex = ID.getModuleFileIndex();
8423 return M.Index == ModuleFileIndex - 1;
8424}
8425
8427 // Predefined decls aren't from any module.
8428 if (ID < NUM_PREDEF_DECL_IDS)
8429 return nullptr;
8430
8431 uint64_t ModuleFileIndex = ID.getModuleFileIndex();
8432 assert(ModuleFileIndex && "Untranslated Local Decl?");
8433
8434 return &getModuleManager()[ModuleFileIndex - 1];
8435}
8436
8438 if (!D->isFromASTFile())
8439 return nullptr;
8440
8441 return getOwningModuleFile(D->getGlobalID());
8442}
8443
8445 if (ID < NUM_PREDEF_DECL_IDS)
8446 return SourceLocation();
8447
8448 if (Decl *D = GetExistingDecl(ID))
8449 return D->getLocation();
8450
8451 SourceLocation Loc;
8452 DeclCursorForID(ID, Loc);
8453 return Loc;
8454}
8455
8456Decl *ASTReader::getPredefinedDecl(PredefinedDeclIDs ID) {
8457 assert(ContextObj && "reading predefined decl without AST context");
8458 ASTContext &Context = *ContextObj;
8459 Decl *NewLoaded = nullptr;
8460 switch (ID) {
8462 return nullptr;
8463
8465 return Context.getTranslationUnitDecl();
8466
8468 if (Context.ObjCIdDecl)
8469 return Context.ObjCIdDecl;
8470 NewLoaded = Context.getObjCIdDecl();
8471 break;
8472
8474 if (Context.ObjCSelDecl)
8475 return Context.ObjCSelDecl;
8476 NewLoaded = Context.getObjCSelDecl();
8477 break;
8478
8480 if (Context.ObjCClassDecl)
8481 return Context.ObjCClassDecl;
8482 NewLoaded = Context.getObjCClassDecl();
8483 break;
8484
8486 if (Context.ObjCProtocolClassDecl)
8487 return Context.ObjCProtocolClassDecl;
8488 NewLoaded = Context.getObjCProtocolDecl();
8489 break;
8490
8492 if (Context.Int128Decl)
8493 return Context.Int128Decl;
8494 NewLoaded = Context.getInt128Decl();
8495 break;
8496
8498 if (Context.UInt128Decl)
8499 return Context.UInt128Decl;
8500 NewLoaded = Context.getUInt128Decl();
8501 break;
8502
8504 if (Context.ObjCInstanceTypeDecl)
8505 return Context.ObjCInstanceTypeDecl;
8506 NewLoaded = Context.getObjCInstanceTypeDecl();
8507 break;
8508
8510 if (Context.BuiltinVaListDecl)
8511 return Context.BuiltinVaListDecl;
8512 NewLoaded = Context.getBuiltinVaListDecl();
8513 break;
8514
8516 if (Context.VaListTagDecl)
8517 return Context.VaListTagDecl;
8518 NewLoaded = Context.getVaListTagDecl();
8519 break;
8520
8522 if (Context.BuiltinMSVaListDecl)
8523 return Context.BuiltinMSVaListDecl;
8524 NewLoaded = Context.getBuiltinMSVaListDecl();
8525 break;
8526
8528 // ASTContext::getMSGuidTagDecl won't create MSGuidTagDecl conditionally.
8529 return Context.getMSGuidTagDecl();
8530
8532 if (Context.ExternCContext)
8533 return Context.ExternCContext;
8534 NewLoaded = Context.getExternCContextDecl();
8535 break;
8536
8538 if (Context.CFConstantStringTypeDecl)
8539 return Context.CFConstantStringTypeDecl;
8540 NewLoaded = Context.getCFConstantStringDecl();
8541 break;
8542
8544 if (Context.CFConstantStringTagDecl)
8545 return Context.CFConstantStringTagDecl;
8546 NewLoaded = Context.getCFConstantStringTagDecl();
8547 break;
8548
8550 return Context.getMSTypeInfoTagDecl();
8551
8552#define BuiltinTemplate(BTName) \
8553 case PREDEF_DECL##BTName##_ID: \
8554 if (Context.Decl##BTName) \
8555 return Context.Decl##BTName; \
8556 NewLoaded = Context.get##BTName##Decl(); \
8557 break;
8558#include "clang/Basic/BuiltinTemplates.inc"
8559
8561 llvm_unreachable("Invalid decl ID");
8562 break;
8563 }
8564
8565 assert(NewLoaded && "Failed to load predefined decl?");
8566
8567 if (DeserializationListener)
8568 DeserializationListener->PredefinedDeclBuilt(ID, NewLoaded);
8569
8570 return NewLoaded;
8571}
8572
8573unsigned ASTReader::translateGlobalDeclIDToIndex(GlobalDeclID GlobalID) const {
8574 ModuleFile *OwningModuleFile = getOwningModuleFile(GlobalID);
8575 if (!OwningModuleFile) {
8576 assert(GlobalID < NUM_PREDEF_DECL_IDS && "Untransalted Global ID?");
8577 return GlobalID.getRawValue();
8578 }
8579
8580 return OwningModuleFile->BaseDeclIndex + GlobalID.getLocalDeclIndex();
8581}
8582
8584 assert(ContextObj && "reading decl with no AST context");
8585
8586 if (ID < NUM_PREDEF_DECL_IDS) {
8587 Decl *D = getPredefinedDecl((PredefinedDeclIDs)ID);
8588 if (D) {
8589 // Track that we have merged the declaration with ID \p ID into the
8590 // pre-existing predefined declaration \p D.
8591 auto &Merged = KeyDecls[D->getCanonicalDecl()];
8592 if (Merged.empty())
8593 Merged.push_back(ID);
8594 }
8595 return D;
8596 }
8597
8598 unsigned Index = translateGlobalDeclIDToIndex(ID);
8599
8600 if (Index >= DeclsLoaded.size()) {
8601 assert(0 && "declaration ID out-of-range for AST file");
8602 Error("declaration ID out-of-range for AST file");
8603 return nullptr;
8604 }
8605
8606 return DeclsLoaded[Index];
8607}
8608
8610 if (ID < NUM_PREDEF_DECL_IDS)
8611 return GetExistingDecl(ID);
8612
8613 unsigned Index = translateGlobalDeclIDToIndex(ID);
8614
8615 if (Index >= DeclsLoaded.size()) {
8616 assert(0 && "declaration ID out-of-range for AST file");
8617 Error("declaration ID out-of-range for AST file");
8618 return nullptr;
8619 }
8620
8621 if (!DeclsLoaded[Index]) {
8622 ReadDeclRecord(ID);
8623 if (DeserializationListener)
8624 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
8625 }
8626
8627 return DeclsLoaded[Index];
8628}
8629
8631 GlobalDeclID GlobalID) {
8632 if (GlobalID < NUM_PREDEF_DECL_IDS)
8633 return LocalDeclID::get(*this, M, GlobalID.getRawValue());
8634
8635 if (!M.ModuleOffsetMap.empty())
8636 ReadModuleOffsetMap(M);
8637
8638 ModuleFile *Owner = getOwningModuleFile(GlobalID);
8639 DeclID ID = GlobalID.getLocalDeclIndex();
8640
8641 if (Owner == &M) {
8642 ID += NUM_PREDEF_DECL_IDS;
8643 return LocalDeclID::get(*this, M, ID);
8644 }
8645
8646 uint64_t OrignalModuleFileIndex = 0;
8647 for (unsigned I = 0; I < M.TransitiveImports.size(); I++)
8648 if (M.TransitiveImports[I] == Owner) {
8649 OrignalModuleFileIndex = I + 1;
8650 break;
8651 }
8652
8653 if (!OrignalModuleFileIndex)
8654 return LocalDeclID();
8655
8656 return LocalDeclID::get(*this, M, OrignalModuleFileIndex, ID);
8657}
8658
8660 unsigned &Idx) {
8661 if (Idx >= Record.size()) {
8662 Error("Corrupted AST file");
8663 return GlobalDeclID(0);
8664 }
8665
8666 return getGlobalDeclID(F, LocalDeclID::get(*this, F, Record[Idx++]));
8667}
8668
8669/// Resolve the offset of a statement into a statement.
8670///
8671/// This operation will read a new statement from the external
8672/// source each time it is called, and is meant to be used via a
8673/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
8675 // Switch case IDs are per Decl.
8677
8678 // Offset here is a global offset across the entire chain.
8679 RecordLocation Loc = getLocalBitOffset(Offset);
8680 if (llvm::Error Err = Loc.F->DeclsCursor.JumpToBit(Loc.Offset)) {
8681 Error(std::move(Err));
8682 return nullptr;
8683 }
8684 assert(NumCurrentElementsDeserializing == 0 &&
8685 "should not be called while already deserializing");
8686 Deserializing D(this);
8687 return ReadStmtFromStream(*Loc.F);
8688}
8689
8690bool ASTReader::LoadExternalSpecializationsImpl(SpecLookupTableTy &SpecLookups,
8691 const Decl *D) {
8692 assert(D);
8693
8694 auto It = SpecLookups.find(D);
8695 if (It == SpecLookups.end())
8696 return false;
8697
8698 // Get Decl may violate the iterator from SpecializationsLookups so we store
8699 // the DeclIDs in ahead.
8701 It->second.Table.findAll();
8702
8703 // Since we've loaded all the specializations, we can erase it from
8704 // the lookup table.
8705 SpecLookups.erase(It);
8706
8707 bool NewSpecsFound = false;
8708 Deserializing LookupResults(this);
8709 for (auto &Info : Infos) {
8710 if (GetExistingDecl(Info))
8711 continue;
8712 NewSpecsFound = true;
8713 GetDecl(Info);
8714 }
8715
8716 return NewSpecsFound;
8717}
8718
8720 assert(D);
8721
8723 bool NewSpecsFound =
8724 LoadExternalSpecializationsImpl(PartialSpecializationsLookups, D);
8725 if (OnlyPartial)
8726 return NewSpecsFound;
8727
8728 NewSpecsFound |= LoadExternalSpecializationsImpl(SpecializationsLookups, D);
8729 return NewSpecsFound;
8730}
8731
8732bool ASTReader::LoadExternalSpecializationsImpl(
8733 SpecLookupTableTy &SpecLookups, const Decl *D,
8734 ArrayRef<TemplateArgument> TemplateArgs) {
8735 assert(D);
8736
8737 reader::LazySpecializationInfoLookupTable *LookupTable = nullptr;
8738 if (auto It = SpecLookups.find(D); It != SpecLookups.end())
8739 LookupTable = &It->getSecond();
8740 if (!LookupTable)
8741 return false;
8742
8743 // NOTE: The getNameForDiagnostic usage in the lambda may mutate the
8744 // `SpecLookups` object.
8745 llvm::TimeTraceScope TimeScope("Load External Specializations for ", [&] {
8746 std::string Name;
8747 llvm::raw_string_ostream OS(Name);
8748 auto *ND = cast<NamedDecl>(D);
8750 /*Qualified=*/true);
8751 return Name;
8752 });
8753
8754 Deserializing LookupResults(this);
8755 auto HashValue = StableHashForTemplateArguments(TemplateArgs);
8756
8757 // Get Decl may violate the iterator from SpecLookups
8759 LookupTable->Table.find(HashValue);
8760
8761 bool NewSpecsFound = false;
8762 for (auto &Info : Infos) {
8763 if (GetExistingDecl(Info))
8764 continue;
8765 NewSpecsFound = true;
8766 GetDecl(Info);
8767 }
8768
8769 return NewSpecsFound;
8770}
8771
8773 const Decl *D, ArrayRef<TemplateArgument> TemplateArgs) {
8774 assert(D);
8775
8776 bool NewDeclsFound = LoadExternalSpecializationsImpl(
8777 PartialSpecializationsLookups, D, TemplateArgs);
8778 NewDeclsFound |=
8779 LoadExternalSpecializationsImpl(SpecializationsLookups, D, TemplateArgs);
8780
8781 return NewDeclsFound;
8782}
8783
8785 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
8786 SmallVectorImpl<Decl *> &Decls) {
8787 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
8788
8789 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
8790 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
8791 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
8792 auto K = (Decl::Kind)+LexicalDecls[I];
8793 if (!IsKindWeWant(K))
8794 continue;
8795
8796 auto ID = (DeclID) + LexicalDecls[I + 1];
8797
8798 // Don't add predefined declarations to the lexical context more
8799 // than once.
8800 if (ID < NUM_PREDEF_DECL_IDS) {
8801 if (PredefsVisited[ID])
8802 continue;
8803
8804 PredefsVisited[ID] = true;
8805 }
8806
8807 if (Decl *D = GetLocalDecl(*M, LocalDeclID::get(*this, *M, ID))) {
8808 assert(D->getKind() == K && "wrong kind for lexical decl");
8809 if (!DC->isDeclInLexicalTraversal(D))
8810 Decls.push_back(D);
8811 }
8812 }
8813 };
8814
8815 if (isa<TranslationUnitDecl>(DC)) {
8816 for (const auto &Lexical : TULexicalDecls)
8817 Visit(Lexical.first, Lexical.second);
8818 } else {
8819 auto I = LexicalDecls.find(DC);
8820 if (I != LexicalDecls.end())
8821 Visit(I->second.first, I->second.second);
8822 }
8823
8824 ++NumLexicalDeclContextsRead;
8825}
8826
8827namespace {
8828
8829class UnalignedDeclIDComp {
8830 ASTReader &Reader;
8831 ModuleFile &Mod;
8832
8833public:
8834 UnalignedDeclIDComp(ASTReader &Reader, ModuleFile &M)
8835 : Reader(Reader), Mod(M) {}
8836
8837 bool operator()(unaligned_decl_id_t L, unaligned_decl_id_t R) const {
8838 SourceLocation LHS = getLocation(L);
8839 SourceLocation RHS = getLocation(R);
8840 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
8841 }
8842
8843 bool operator()(SourceLocation LHS, unaligned_decl_id_t R) const {
8844 SourceLocation RHS = getLocation(R);
8845 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
8846 }
8847
8848 bool operator()(unaligned_decl_id_t L, SourceLocation RHS) const {
8849 SourceLocation LHS = getLocation(L);
8850 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
8851 }
8852
8853 SourceLocation getLocation(unaligned_decl_id_t ID) const {
8854 return Reader.getSourceManager().getFileLoc(
8856 Reader.getGlobalDeclID(Mod, LocalDeclID::get(Reader, Mod, ID))));
8857 }
8858};
8859
8860} // namespace
8861
8863 unsigned Offset, unsigned Length,
8864 SmallVectorImpl<Decl *> &Decls) {
8866
8867 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
8868 if (I == FileDeclIDs.end())
8869 return;
8870
8871 FileDeclsInfo &DInfo = I->second;
8872 if (DInfo.Decls.empty())
8873 return;
8874
8876 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
8877 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
8878
8879 UnalignedDeclIDComp DIDComp(*this, *DInfo.Mod);
8881 llvm::lower_bound(DInfo.Decls, BeginLoc, DIDComp);
8882 if (BeginIt != DInfo.Decls.begin())
8883 --BeginIt;
8884
8885 // If we are pointing at a top-level decl inside an objc container, we need
8886 // to backtrack until we find it otherwise we will fail to report that the
8887 // region overlaps with an objc container.
8888 while (BeginIt != DInfo.Decls.begin() &&
8889 GetDecl(getGlobalDeclID(*DInfo.Mod,
8890 LocalDeclID::get(*this, *DInfo.Mod, *BeginIt)))
8891 ->isTopLevelDeclInObjCContainer())
8892 --BeginIt;
8893
8895 llvm::upper_bound(DInfo.Decls, EndLoc, DIDComp);
8896 if (EndIt != DInfo.Decls.end())
8897 ++EndIt;
8898
8899 for (ArrayRef<unaligned_decl_id_t>::iterator DIt = BeginIt; DIt != EndIt;
8900 ++DIt)
8901 Decls.push_back(GetDecl(getGlobalDeclID(
8902 *DInfo.Mod, LocalDeclID::get(*this, *DInfo.Mod, *DIt))));
8903}
8904
8906 DeclarationName Name,
8907 const DeclContext *OriginalDC) {
8908 assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
8909 "DeclContext has no visible decls in storage");
8910 if (!Name)
8911 return false;
8912
8913 // Load the list of declarations.
8914 DeclsSet DS;
8915
8916 auto Find = [&, this](auto &&Table, auto &&Key) {
8917 for (GlobalDeclID ID : Table.find(Key)) {
8919 if (ND->getDeclName() != Name)
8920 continue;
8921 // Special case for namespaces: There can be a lot of redeclarations of
8922 // some namespaces, and we import a "key declaration" per imported module.
8923 // Since all declarations of a namespace are essentially interchangeable,
8924 // we can optimize namespace look-up by only storing the key declaration
8925 // of the current TU, rather than storing N key declarations where N is
8926 // the # of imported modules that declare that namespace.
8927 // TODO: Try to generalize this optimization to other redeclarable decls.
8928 if (isa<NamespaceDecl>(ND))
8930 DS.insert(ND);
8931 }
8932 };
8933
8934 Deserializing LookupResults(this);
8935
8936 // FIXME: Clear the redundancy with templated lambda in C++20 when that's
8937 // available.
8938 if (auto It = Lookups.find(DC); It != Lookups.end()) {
8939 ++NumVisibleDeclContextsRead;
8940 Find(It->second.Table, Name);
8941 }
8942
8943 auto FindModuleLocalLookup = [&, this](Module *NamedModule) {
8944 if (auto It = ModuleLocalLookups.find(DC); It != ModuleLocalLookups.end()) {
8945 ++NumModuleLocalVisibleDeclContexts;
8946 Find(It->second.Table, std::make_pair(Name, NamedModule));
8947 }
8948 };
8949 if (auto *NamedModule =
8950 OriginalDC ? cast<Decl>(OriginalDC)->getTopLevelOwningNamedModule()
8951 : nullptr)
8952 FindModuleLocalLookup(NamedModule);
8953 // See clang/test/Modules/ModulesLocalNamespace.cppm for the motiviation case.
8954 // We're going to find a decl but the decl context of the lookup is
8955 // unspecified. In this case, the OriginalDC may be the decl context in other
8956 // module.
8957 if (ContextObj && ContextObj->getCurrentNamedModule())
8958 FindModuleLocalLookup(ContextObj->getCurrentNamedModule());
8959
8960 if (auto It = TULocalLookups.find(DC); It != TULocalLookups.end()) {
8961 ++NumTULocalVisibleDeclContexts;
8962 Find(It->second.Table, Name);
8963 }
8964
8965 SetExternalVisibleDeclsForName(DC, Name, DS);
8966 return !DS.empty();
8967}
8968
8970 if (!DC->hasExternalVisibleStorage())
8971 return;
8972
8973 DeclsMap Decls;
8974
8975 auto findAll = [&](auto &LookupTables, unsigned &NumRead) {
8976 auto It = LookupTables.find(DC);
8977 if (It == LookupTables.end())
8978 return;
8979
8980 NumRead++;
8981
8982 for (GlobalDeclID ID : It->second.Table.findAll()) {
8984 // Special case for namespaces: There can be a lot of redeclarations of
8985 // some namespaces, and we import a "key declaration" per imported module.
8986 // Since all declarations of a namespace are essentially interchangeable,
8987 // we can optimize namespace look-up by only storing the key declaration
8988 // of the current TU, rather than storing N key declarations where N is
8989 // the # of imported modules that declare that namespace.
8990 // TODO: Try to generalize this optimization to other redeclarable decls.
8991 if (isa<NamespaceDecl>(ND))
8993 Decls[ND->getDeclName()].insert(ND);
8994 }
8995
8996 // FIXME: Why a PCH test is failing if we remove the iterator after findAll?
8997 };
8998
8999 findAll(Lookups, NumVisibleDeclContextsRead);
9000 findAll(ModuleLocalLookups, NumModuleLocalVisibleDeclContexts);
9001 findAll(TULocalLookups, NumTULocalVisibleDeclContexts);
9002
9003 for (auto &[Name, DS] : Decls)
9004 SetExternalVisibleDeclsForName(DC, Name, DS);
9005
9006 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
9007}
9008
9011 auto I = Lookups.find(Primary);
9012 return I == Lookups.end() ? nullptr : &I->second;
9013}
9014
9017 auto I = ModuleLocalLookups.find(Primary);
9018 return I == ModuleLocalLookups.end() ? nullptr : &I->second;
9019}
9020
9023 auto I = TULocalLookups.find(Primary);
9024 return I == TULocalLookups.end() ? nullptr : &I->second;
9025}
9026
9029 assert(D->isCanonicalDecl());
9030 auto &LookupTable =
9031 IsPartial ? PartialSpecializationsLookups : SpecializationsLookups;
9032 auto I = LookupTable.find(D);
9033 return I == LookupTable.end() ? nullptr : &I->second;
9034}
9035
9037 assert(D->isCanonicalDecl());
9038 return PartialSpecializationsLookups.contains(D) ||
9039 SpecializationsLookups.contains(D);
9040}
9041
9042/// Under non-PCH compilation the consumer receives the objc methods
9043/// before receiving the implementation, and codegen depends on this.
9044/// We simulate this by deserializing and passing to consumer the methods of the
9045/// implementation before passing the deserialized implementation decl.
9047 ASTConsumer *Consumer) {
9048 assert(ImplD && Consumer);
9049
9050 for (auto *I : ImplD->methods())
9051 Consumer->HandleInterestingDecl(DeclGroupRef(I));
9052
9053 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
9054}
9055
9056void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
9057 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
9058 PassObjCImplDeclToConsumer(ImplD, Consumer);
9059 else
9060 Consumer->HandleInterestingDecl(DeclGroupRef(D));
9061}
9062
9063void ASTReader::PassVTableToConsumer(CXXRecordDecl *RD) {
9064 Consumer->HandleVTable(RD);
9065}
9066
9068 this->Consumer = Consumer;
9069
9070 if (Consumer)
9071 PassInterestingDeclsToConsumer();
9072
9073 if (DeserializationListener)
9074 DeserializationListener->ReaderInitialized(this);
9075}
9076
9078 std::fprintf(stderr, "*** AST File Statistics:\n");
9079
9080 unsigned NumTypesLoaded =
9081 TypesLoaded.size() - llvm::count(TypesLoaded.materialized(), QualType());
9082 unsigned NumDeclsLoaded =
9083 DeclsLoaded.size() -
9084 llvm::count(DeclsLoaded.materialized(), (Decl *)nullptr);
9085 unsigned NumIdentifiersLoaded =
9086 IdentifiersLoaded.size() -
9087 llvm::count(IdentifiersLoaded, (IdentifierInfo *)nullptr);
9088 unsigned NumMacrosLoaded =
9089 MacrosLoaded.size() - llvm::count(MacrosLoaded, (MacroInfo *)nullptr);
9090 unsigned NumSelectorsLoaded =
9091 SelectorsLoaded.size() - llvm::count(SelectorsLoaded, Selector());
9092
9093 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
9094 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
9095 NumSLocEntriesRead, TotalNumSLocEntries,
9096 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
9097 if (!TypesLoaded.empty())
9098 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
9099 NumTypesLoaded, (unsigned)TypesLoaded.size(),
9100 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
9101 if (!DeclsLoaded.empty())
9102 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
9103 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
9104 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
9105 if (!IdentifiersLoaded.empty())
9106 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
9107 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
9108 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
9109 if (!MacrosLoaded.empty())
9110 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
9111 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
9112 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
9113 if (!SelectorsLoaded.empty())
9114 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
9115 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
9116 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
9117 if (TotalNumStatements)
9118 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
9119 NumStatementsRead, TotalNumStatements,
9120 ((float)NumStatementsRead/TotalNumStatements * 100));
9121 if (TotalNumMacros)
9122 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
9123 NumMacrosRead, TotalNumMacros,
9124 ((float)NumMacrosRead/TotalNumMacros * 100));
9125 if (TotalLexicalDeclContexts)
9126 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
9127 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
9128 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
9129 * 100));
9130 if (TotalVisibleDeclContexts)
9131 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
9132 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
9133 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
9134 * 100));
9135 if (TotalModuleLocalVisibleDeclContexts)
9136 std::fprintf(
9137 stderr, " %u/%u module local visible declcontexts read (%f%%)\n",
9138 NumModuleLocalVisibleDeclContexts, TotalModuleLocalVisibleDeclContexts,
9139 ((float)NumModuleLocalVisibleDeclContexts /
9140 TotalModuleLocalVisibleDeclContexts * 100));
9141 if (TotalTULocalVisibleDeclContexts)
9142 std::fprintf(stderr, " %u/%u visible declcontexts in GMF read (%f%%)\n",
9143 NumTULocalVisibleDeclContexts, TotalTULocalVisibleDeclContexts,
9144 ((float)NumTULocalVisibleDeclContexts /
9145 TotalTULocalVisibleDeclContexts * 100));
9146 if (TotalNumMethodPoolEntries)
9147 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
9148 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
9149 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
9150 * 100));
9151 if (NumMethodPoolLookups)
9152 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
9153 NumMethodPoolHits, NumMethodPoolLookups,
9154 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
9155 if (NumMethodPoolTableLookups)
9156 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
9157 NumMethodPoolTableHits, NumMethodPoolTableLookups,
9158 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
9159 * 100.0));
9160 if (NumIdentifierLookupHits)
9161 std::fprintf(stderr,
9162 " %u / %u identifier table lookups succeeded (%f%%)\n",
9163 NumIdentifierLookupHits, NumIdentifierLookups,
9164 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
9165
9166 if (GlobalIndex) {
9167 std::fprintf(stderr, "\n");
9168 GlobalIndex->printStats();
9169 }
9170
9171 std::fprintf(stderr, "\n");
9172 dump();
9173 std::fprintf(stderr, "\n");
9174}
9175
9176template<typename Key, typename ModuleFile, unsigned InitialCapacity>
9177LLVM_DUMP_METHOD static void
9178dumpModuleIDMap(StringRef Name,
9179 const ContinuousRangeMap<Key, ModuleFile *,
9180 InitialCapacity> &Map) {
9181 if (Map.begin() == Map.end())
9182 return;
9183
9185
9186 llvm::errs() << Name << ":\n";
9187 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
9188 I != IEnd; ++I)
9189 llvm::errs() << " " << (DeclID)I->first << " -> " << I->second->FileName
9190 << "\n";
9191}
9192
9193LLVM_DUMP_METHOD void ASTReader::dump() {
9194 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
9195 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
9196 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
9197 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
9198 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
9199 dumpModuleIDMap("Global preprocessed entity map",
9200 GlobalPreprocessedEntityMap);
9201
9202 llvm::errs() << "\n*** PCH/Modules Loaded:";
9203 for (ModuleFile &M : ModuleMgr)
9204 M.dump();
9205}
9206
9207/// Return the amount of memory used by memory buffers, breaking down
9208/// by heap-backed versus mmap'ed memory.
9210 for (ModuleFile &I : ModuleMgr) {
9211 if (llvm::MemoryBuffer *buf = I.Buffer) {
9212 size_t bytes = buf->getBufferSize();
9213 switch (buf->getBufferKind()) {
9214 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
9215 sizes.malloc_bytes += bytes;
9216 break;
9217 case llvm::MemoryBuffer::MemoryBuffer_MMap:
9218 sizes.mmap_bytes += bytes;
9219 break;
9220 }
9221 }
9222 }
9223}
9224
9226 SemaObj = &S;
9227 S.addExternalSource(this);
9228
9229 // Makes sure any declarations that were deserialized "too early"
9230 // still get added to the identifier's declaration chains.
9231 for (GlobalDeclID ID : PreloadedDeclIDs) {
9233 pushExternalDeclIntoScope(D, D->getDeclName());
9234 }
9235 PreloadedDeclIDs.clear();
9236
9237 // FIXME: What happens if these are changed by a module import?
9238 if (!FPPragmaOptions.empty()) {
9239 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
9240 FPOptionsOverride NewOverrides =
9241 FPOptionsOverride::getFromOpaqueInt(FPPragmaOptions[0]);
9242 SemaObj->CurFPFeatures =
9243 NewOverrides.applyOverrides(SemaObj->getLangOpts());
9244 }
9245
9246 for (GlobalDeclID ID : DeclsWithEffectsToVerify) {
9247 Decl *D = GetDecl(ID);
9248 if (auto *FD = dyn_cast<FunctionDecl>(D))
9249 SemaObj->addDeclWithEffects(FD, FD->getFunctionEffects());
9250 else if (auto *BD = dyn_cast<BlockDecl>(D))
9251 SemaObj->addDeclWithEffects(BD, BD->getFunctionEffects());
9252 else
9253 llvm_unreachable("unexpected Decl type in DeclsWithEffectsToVerify");
9254 }
9255 DeclsWithEffectsToVerify.clear();
9256
9257 SemaObj->OpenCLFeatures = OpenCLExtensions;
9258
9259 UpdateSema();
9260}
9261
9263 assert(SemaObj && "no Sema to update");
9264
9265 // Load the offsets of the declarations that Sema references.
9266 // They will be lazily deserialized when needed.
9267 if (!SemaDeclRefs.empty()) {
9268 assert(SemaDeclRefs.size() % 3 == 0);
9269 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 3) {
9270 if (!SemaObj->StdNamespace)
9271 SemaObj->StdNamespace = SemaDeclRefs[I].getRawValue();
9272 if (!SemaObj->StdBadAlloc)
9273 SemaObj->StdBadAlloc = SemaDeclRefs[I + 1].getRawValue();
9274 if (!SemaObj->StdAlignValT)
9275 SemaObj->StdAlignValT = SemaDeclRefs[I + 2].getRawValue();
9276 }
9277 SemaDeclRefs.clear();
9278 }
9279
9280 // Update the state of pragmas. Use the same API as if we had encountered the
9281 // pragma in the source.
9282 if(OptimizeOffPragmaLocation.isValid())
9283 SemaObj->ActOnPragmaOptimize(/* On = */ false, OptimizeOffPragmaLocation);
9284 if (PragmaMSStructState != -1)
9285 SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState);
9286 if (PointersToMembersPragmaLocation.isValid()) {
9287 SemaObj->ActOnPragmaMSPointersToMembers(
9289 PragmaMSPointersToMembersState,
9290 PointersToMembersPragmaLocation);
9291 }
9292 SemaObj->CUDA().ForceHostDeviceDepth = ForceHostDeviceDepth;
9293 if (!RISCVVecIntrinsicPragma.empty()) {
9294 assert(RISCVVecIntrinsicPragma.size() == 3 &&
9295 "Wrong number of RISCVVecIntrinsicPragma");
9296 SemaObj->RISCV().DeclareRVVBuiltins = RISCVVecIntrinsicPragma[0];
9297 SemaObj->RISCV().DeclareSiFiveVectorBuiltins = RISCVVecIntrinsicPragma[1];
9298 SemaObj->RISCV().DeclareAndesVectorBuiltins = RISCVVecIntrinsicPragma[2];
9299 }
9300
9301 if (PragmaAlignPackCurrentValue) {
9302 // The bottom of the stack might have a default value. It must be adjusted
9303 // to the current value to ensure that the packing state is preserved after
9304 // popping entries that were included/imported from a PCH/module.
9305 bool DropFirst = false;
9306 if (!PragmaAlignPackStack.empty() &&
9307 PragmaAlignPackStack.front().Location.isInvalid()) {
9308 assert(PragmaAlignPackStack.front().Value ==
9309 SemaObj->AlignPackStack.DefaultValue &&
9310 "Expected a default alignment value");
9311 SemaObj->AlignPackStack.Stack.emplace_back(
9312 PragmaAlignPackStack.front().SlotLabel,
9313 SemaObj->AlignPackStack.CurrentValue,
9314 SemaObj->AlignPackStack.CurrentPragmaLocation,
9315 PragmaAlignPackStack.front().PushLocation);
9316 DropFirst = true;
9317 }
9318 for (const auto &Entry :
9319 llvm::ArrayRef(PragmaAlignPackStack).drop_front(DropFirst ? 1 : 0)) {
9320 SemaObj->AlignPackStack.Stack.emplace_back(
9321 Entry.SlotLabel, Entry.Value, Entry.Location, Entry.PushLocation);
9322 }
9323 if (PragmaAlignPackCurrentLocation.isInvalid()) {
9324 assert(*PragmaAlignPackCurrentValue ==
9325 SemaObj->AlignPackStack.DefaultValue &&
9326 "Expected a default align and pack value");
9327 // Keep the current values.
9328 } else {
9329 SemaObj->AlignPackStack.CurrentValue = *PragmaAlignPackCurrentValue;
9330 SemaObj->AlignPackStack.CurrentPragmaLocation =
9331 PragmaAlignPackCurrentLocation;
9332 }
9333 }
9334 if (FpPragmaCurrentValue) {
9335 // The bottom of the stack might have a default value. It must be adjusted
9336 // to the current value to ensure that fp-pragma state is preserved after
9337 // popping entries that were included/imported from a PCH/module.
9338 bool DropFirst = false;
9339 if (!FpPragmaStack.empty() && FpPragmaStack.front().Location.isInvalid()) {
9340 assert(FpPragmaStack.front().Value ==
9341 SemaObj->FpPragmaStack.DefaultValue &&
9342 "Expected a default pragma float_control value");
9343 SemaObj->FpPragmaStack.Stack.emplace_back(
9344 FpPragmaStack.front().SlotLabel, SemaObj->FpPragmaStack.CurrentValue,
9345 SemaObj->FpPragmaStack.CurrentPragmaLocation,
9346 FpPragmaStack.front().PushLocation);
9347 DropFirst = true;
9348 }
9349 for (const auto &Entry :
9350 llvm::ArrayRef(FpPragmaStack).drop_front(DropFirst ? 1 : 0))
9351 SemaObj->FpPragmaStack.Stack.emplace_back(
9352 Entry.SlotLabel, Entry.Value, Entry.Location, Entry.PushLocation);
9353 if (FpPragmaCurrentLocation.isInvalid()) {
9354 assert(*FpPragmaCurrentValue == SemaObj->FpPragmaStack.DefaultValue &&
9355 "Expected a default pragma float_control value");
9356 // Keep the current values.
9357 } else {
9358 SemaObj->FpPragmaStack.CurrentValue = *FpPragmaCurrentValue;
9359 SemaObj->FpPragmaStack.CurrentPragmaLocation = FpPragmaCurrentLocation;
9360 }
9361 }
9362
9363 // For non-modular AST files, restore visiblity of modules.
9364 for (auto &Import : PendingImportedModulesSema) {
9365 if (Import.ImportLoc.isInvalid())
9366 continue;
9367 if (Module *Imported = getSubmodule(Import.ID)) {
9368 SemaObj->makeModuleVisible(Imported, Import.ImportLoc);
9369 }
9370 }
9371 PendingImportedModulesSema.clear();
9372}
9373
9375 // Note that we are loading an identifier.
9376 Deserializing AnIdentifier(this);
9377
9378 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
9379 NumIdentifierLookups,
9380 NumIdentifierLookupHits);
9381
9382 // We don't need to do identifier table lookups in C++ modules (we preload
9383 // all interesting declarations, and don't need to use the scope for name
9384 // lookups). Perform the lookup in PCH files, though, since we don't build
9385 // a complete initial identifier table if we're carrying on from a PCH.
9386 if (PP.getLangOpts().CPlusPlus) {
9387 for (auto *F : ModuleMgr.pch_modules())
9388 if (Visitor(*F))
9389 break;
9390 } else {
9391 // If there is a global index, look there first to determine which modules
9392 // provably do not have any results for this identifier.
9394 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
9395 if (!loadGlobalIndex()) {
9396 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
9397 HitsPtr = &Hits;
9398 }
9399 }
9400
9401 ModuleMgr.visit(Visitor, HitsPtr);
9402 }
9403
9404 IdentifierInfo *II = Visitor.getIdentifierInfo();
9406 return II;
9407}
9408
9409namespace clang {
9410
9411 /// An identifier-lookup iterator that enumerates all of the
9412 /// identifiers stored within a set of AST files.
9414 /// The AST reader whose identifiers are being enumerated.
9415 const ASTReader &Reader;
9416
9417 /// The current index into the chain of AST files stored in
9418 /// the AST reader.
9419 unsigned Index;
9420
9421 /// The current position within the identifier lookup table
9422 /// of the current AST file.
9423 ASTIdentifierLookupTable::key_iterator Current;
9424
9425 /// The end position within the identifier lookup table of
9426 /// the current AST file.
9427 ASTIdentifierLookupTable::key_iterator End;
9428
9429 /// Whether to skip any modules in the ASTReader.
9430 bool SkipModules;
9431
9432 public:
9433 explicit ASTIdentifierIterator(const ASTReader &Reader,
9434 bool SkipModules = false);
9435
9436 StringRef Next() override;
9437 };
9438
9439} // namespace clang
9440
9442 bool SkipModules)
9443 : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) {
9444}
9445
9447 while (Current == End) {
9448 // If we have exhausted all of our AST files, we're done.
9449 if (Index == 0)
9450 return StringRef();
9451
9452 --Index;
9453 ModuleFile &F = Reader.ModuleMgr[Index];
9454 if (SkipModules && F.isModule())
9455 continue;
9456
9457 ASTIdentifierLookupTable *IdTable =
9459 Current = IdTable->key_begin();
9460 End = IdTable->key_end();
9461 }
9462
9463 // We have any identifiers remaining in the current AST file; return
9464 // the next one.
9465 StringRef Result = *Current;
9466 ++Current;
9467 return Result;
9468}
9469
9470namespace {
9471
9472/// A utility for appending two IdentifierIterators.
9473class ChainedIdentifierIterator : public IdentifierIterator {
9474 std::unique_ptr<IdentifierIterator> Current;
9475 std::unique_ptr<IdentifierIterator> Queued;
9476
9477public:
9478 ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First,
9479 std::unique_ptr<IdentifierIterator> Second)
9480 : Current(std::move(First)), Queued(std::move(Second)) {}
9481
9482 StringRef Next() override {
9483 if (!Current)
9484 return StringRef();
9485
9486 StringRef result = Current->Next();
9487 if (!result.empty())
9488 return result;
9489
9490 // Try the queued iterator, which may itself be empty.
9491 Current.reset();
9492 std::swap(Current, Queued);
9493 return Next();
9494 }
9495};
9496
9497} // namespace
9498
9500 if (!loadGlobalIndex()) {
9501 std::unique_ptr<IdentifierIterator> ReaderIter(
9502 new ASTIdentifierIterator(*this, /*SkipModules=*/true));
9503 std::unique_ptr<IdentifierIterator> ModulesIter(
9504 GlobalIndex->createIdentifierIterator());
9505 return new ChainedIdentifierIterator(std::move(ReaderIter),
9506 std::move(ModulesIter));
9507 }
9508
9509 return new ASTIdentifierIterator(*this);
9510}
9511
9512namespace clang {
9513namespace serialization {
9514
9516 ASTReader &Reader;
9517 Selector Sel;
9518 unsigned PriorGeneration;
9519 unsigned InstanceBits = 0;
9520 unsigned FactoryBits = 0;
9521 bool InstanceHasMoreThanOneDecl = false;
9522 bool FactoryHasMoreThanOneDecl = false;
9523 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
9524 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
9525
9526 public:
9528 unsigned PriorGeneration)
9529 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration) {}
9530
9532 if (!M.SelectorLookupTable)
9533 return false;
9534
9535 // If we've already searched this module file, skip it now.
9536 if (M.Generation <= PriorGeneration)
9537 return true;
9538
9539 ++Reader.NumMethodPoolTableLookups;
9540 ASTSelectorLookupTable *PoolTable
9542 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
9543 if (Pos == PoolTable->end())
9544 return false;
9545
9546 ++Reader.NumMethodPoolTableHits;
9547 ++Reader.NumSelectorsRead;
9548 // FIXME: Not quite happy with the statistics here. We probably should
9549 // disable this tracking when called via LoadSelector.
9550 // Also, should entries without methods count as misses?
9551 ++Reader.NumMethodPoolEntriesRead;
9553 if (Reader.DeserializationListener)
9554 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
9555
9556 // Append methods in the reverse order, so that later we can process them
9557 // in the order they appear in the source code by iterating through
9558 // the vector in the reverse order.
9559 InstanceMethods.append(Data.Instance.rbegin(), Data.Instance.rend());
9560 FactoryMethods.append(Data.Factory.rbegin(), Data.Factory.rend());
9561 InstanceBits = Data.InstanceBits;
9562 FactoryBits = Data.FactoryBits;
9563 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
9564 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
9565 return false;
9566 }
9567
9568 /// Retrieve the instance methods found by this visitor.
9570 return InstanceMethods;
9571 }
9572
9573 /// Retrieve the instance methods found by this visitor.
9575 return FactoryMethods;
9576 }
9577
9578 unsigned getInstanceBits() const { return InstanceBits; }
9579 unsigned getFactoryBits() const { return FactoryBits; }
9580
9582 return InstanceHasMoreThanOneDecl;
9583 }
9584
9585 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
9586 };
9587
9588} // namespace serialization
9589} // namespace clang
9590
9591/// Add the given set of methods to the method list.
9593 ObjCMethodList &List) {
9594 for (ObjCMethodDecl *M : llvm::reverse(Methods))
9595 S.ObjC().addMethodToGlobalList(&List, M);
9596}
9597
9599 // Get the selector generation and update it to the current generation.
9600 unsigned &Generation = SelectorGeneration[Sel];
9601 unsigned PriorGeneration = Generation;
9602 Generation = getGeneration();
9603 SelectorOutOfDate[Sel] = false;
9604
9605 // Search for methods defined with this selector.
9606 ++NumMethodPoolLookups;
9607 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
9608 ModuleMgr.visit(Visitor);
9609
9610 if (Visitor.getInstanceMethods().empty() &&
9611 Visitor.getFactoryMethods().empty())
9612 return;
9613
9614 ++NumMethodPoolHits;
9615
9616 if (!getSema())
9617 return;
9618
9619 Sema &S = *getSema();
9620 auto &Methods = S.ObjC().MethodPool[Sel];
9621
9622 Methods.first.setBits(Visitor.getInstanceBits());
9623 Methods.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
9624 Methods.second.setBits(Visitor.getFactoryBits());
9625 Methods.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
9626
9627 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
9628 // when building a module we keep every method individually and may need to
9629 // update hasMoreThanOneDecl as we add the methods.
9630 addMethodsToPool(S, Visitor.getInstanceMethods(), Methods.first);
9631 addMethodsToPool(S, Visitor.getFactoryMethods(), Methods.second);
9632}
9633
9635 if (SelectorOutOfDate[Sel])
9636 ReadMethodPool(Sel);
9637}
9638
9641 Namespaces.clear();
9642
9643 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
9644 if (NamespaceDecl *Namespace
9645 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
9646 Namespaces.push_back(Namespace);
9647 }
9648}
9649
9651 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {
9652 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
9653 UndefinedButUsedDecl &U = UndefinedButUsed[Idx++];
9656 Undefined.insert(std::make_pair(D, Loc));
9657 }
9658 UndefinedButUsed.clear();
9659}
9660
9662 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
9663 Exprs) {
9664 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
9665 FieldDecl *FD =
9666 cast<FieldDecl>(GetDecl(GlobalDeclID(DelayedDeleteExprs[Idx++])));
9667 uint64_t Count = DelayedDeleteExprs[Idx++];
9668 for (uint64_t C = 0; C < Count; ++C) {
9669 SourceLocation DeleteLoc =
9670 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
9671 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
9672 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
9673 }
9674 }
9675}
9676
9678 SmallVectorImpl<VarDecl *> &TentativeDefs) {
9679 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
9680 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
9681 if (Var)
9682 TentativeDefs.push_back(Var);
9683 }
9684 TentativeDefinitions.clear();
9685}
9686
9689 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
9691 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
9692 if (D)
9693 Decls.push_back(D);
9694 }
9695 UnusedFileScopedDecls.clear();
9696}
9697
9700 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
9702 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
9703 if (D)
9704 Decls.push_back(D);
9705 }
9706 DelegatingCtorDecls.clear();
9707}
9708
9710 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
9712 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
9713 if (D)
9714 Decls.push_back(D);
9715 }
9716 ExtVectorDecls.clear();
9717}
9718
9721 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
9722 ++I) {
9723 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
9724 GetDecl(UnusedLocalTypedefNameCandidates[I]));
9725 if (D)
9726 Decls.insert(D);
9727 }
9728 UnusedLocalTypedefNameCandidates.clear();
9729}
9730
9733 for (auto I : DeclsToCheckForDeferredDiags) {
9734 auto *D = dyn_cast_or_null<Decl>(GetDecl(I));
9735 if (D)
9736 Decls.insert(D);
9737 }
9738 DeclsToCheckForDeferredDiags.clear();
9739}
9740
9742 SmallVectorImpl<std::pair<Selector, SourceLocation>> &Sels) {
9743 if (ReferencedSelectorsData.empty())
9744 return;
9745
9746 // If there are @selector references added them to its pool. This is for
9747 // implementation of -Wselector.
9748 unsigned int DataSize = ReferencedSelectorsData.size()-1;
9749 unsigned I = 0;
9750 while (I < DataSize) {
9751 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
9752 SourceLocation SelLoc
9753 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
9754 Sels.push_back(std::make_pair(Sel, SelLoc));
9755 }
9756 ReferencedSelectorsData.clear();
9757}
9758
9760 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo>> &WeakIDs) {
9761 if (WeakUndeclaredIdentifiers.empty())
9762 return;
9763
9764 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
9765 IdentifierInfo *WeakId
9766 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
9767 IdentifierInfo *AliasId
9768 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
9769 SourceLocation Loc =
9770 SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
9771 WeakInfo WI(AliasId, Loc);
9772 WeakIDs.push_back(std::make_pair(WeakId, WI));
9773 }
9774 WeakUndeclaredIdentifiers.clear();
9775}
9776
9778 SmallVectorImpl<std::pair<IdentifierInfo *, AsmLabelAttr *>> &ExtnameIDs) {
9779 if (ExtnameUndeclaredIdentifiers.empty())
9780 return;
9781
9782 for (unsigned I = 0, N = ExtnameUndeclaredIdentifiers.size(); I < N; I += 3) {
9783 IdentifierInfo *NameId =
9784 DecodeIdentifierInfo(ExtnameUndeclaredIdentifiers[I]);
9785 IdentifierInfo *ExtnameId =
9786 DecodeIdentifierInfo(ExtnameUndeclaredIdentifiers[I + 1]);
9787 SourceLocation Loc =
9788 SourceLocation::getFromRawEncoding(ExtnameUndeclaredIdentifiers[I + 2]);
9789 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
9790 getContext(), ExtnameId->getName(),
9791 AttributeCommonInfo(ExtnameId, SourceRange(Loc),
9793 ExtnameIDs.push_back(std::make_pair(NameId, Attr));
9794 }
9795 ExtnameUndeclaredIdentifiers.clear();
9796}
9797
9799 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
9801 VTableUse &TableInfo = VTableUses[Idx++];
9802 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(TableInfo.ID));
9803 VT.Location = SourceLocation::getFromRawEncoding(TableInfo.RawLoc);
9804 VT.DefinitionRequired = TableInfo.Used;
9805 VTables.push_back(VT);
9806 }
9807
9808 VTableUses.clear();
9809}
9810
9812 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation>> &Pending) {
9813 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
9814 PendingInstantiation &Inst = PendingInstantiations[Idx++];
9815 ValueDecl *D = cast<ValueDecl>(GetDecl(Inst.ID));
9817
9818 Pending.push_back(std::make_pair(D, Loc));
9819 }
9820 PendingInstantiations.clear();
9821}
9822
9824 llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>>
9825 &LPTMap) {
9826 for (auto &LPT : LateParsedTemplates) {
9827 ModuleFile *FMod = LPT.first;
9828 RecordDataImpl &LateParsed = LPT.second;
9829 for (unsigned Idx = 0, N = LateParsed.size(); Idx < N;
9830 /* In loop */) {
9831 FunctionDecl *FD = ReadDeclAs<FunctionDecl>(*FMod, LateParsed, Idx);
9832
9833 auto LT = std::make_unique<LateParsedTemplate>();
9834 LT->D = ReadDecl(*FMod, LateParsed, Idx);
9835 LT->FPO = FPOptions::getFromOpaqueInt(LateParsed[Idx++]);
9836
9837 ModuleFile *F = getOwningModuleFile(LT->D);
9838 assert(F && "No module");
9839
9840 unsigned TokN = LateParsed[Idx++];
9841 LT->Toks.reserve(TokN);
9842 for (unsigned T = 0; T < TokN; ++T)
9843 LT->Toks.push_back(ReadToken(*F, LateParsed, Idx));
9844
9845 LPTMap.insert(std::make_pair(FD, std::move(LT)));
9846 }
9847 }
9848
9849 LateParsedTemplates.clear();
9850}
9851
9853 if (!Lambda->getLambdaContextDecl())
9854 return;
9855
9856 auto LambdaInfo =
9857 std::make_pair(Lambda->getLambdaContextDecl()->getCanonicalDecl(),
9858 Lambda->getLambdaIndexInContext());
9859
9860 // Handle the import and then include case for lambdas.
9861 if (auto Iter = LambdaDeclarationsForMerging.find(LambdaInfo);
9862 Iter != LambdaDeclarationsForMerging.end() &&
9863 Iter->second->isFromASTFile() && Lambda->getFirstDecl() == Lambda) {
9865 cast<CXXRecordDecl>(Iter->second)->getMostRecentDecl();
9866 Lambda->setPreviousDecl(Previous);
9867 return;
9868 }
9869
9870 // Keep track of this lambda so it can be merged with another lambda that
9871 // is loaded later.
9872 LambdaDeclarationsForMerging.insert({LambdaInfo, Lambda});
9873}
9874
9876 // It would be complicated to avoid reading the methods anyway. So don't.
9877 ReadMethodPool(Sel);
9878}
9879
9881 assert(ID && "Non-zero identifier ID required");
9882 unsigned Index = translateIdentifierIDToIndex(ID).second;
9883 assert(Index < IdentifiersLoaded.size() && "identifier ID out of range");
9884 IdentifiersLoaded[Index] = II;
9885 if (DeserializationListener)
9886 DeserializationListener->IdentifierRead(ID, II);
9887}
9888
9889/// Set the globally-visible declarations associated with the given
9890/// identifier.
9891///
9892/// If the AST reader is currently in a state where the given declaration IDs
9893/// cannot safely be resolved, they are queued until it is safe to resolve
9894/// them.
9895///
9896/// \param II an IdentifierInfo that refers to one or more globally-visible
9897/// declarations.
9898///
9899/// \param DeclIDs the set of declaration IDs with the name @p II that are
9900/// visible at global scope.
9901///
9902/// \param Decls if non-null, this vector will be populated with the set of
9903/// deserialized declarations. These declarations will not be pushed into
9904/// scope.
9907 SmallVectorImpl<Decl *> *Decls) {
9908 if (NumCurrentElementsDeserializing && !Decls) {
9909 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
9910 return;
9911 }
9912
9913 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
9914 if (!SemaObj) {
9915 // Queue this declaration so that it will be added to the
9916 // translation unit scope and identifier's declaration chain
9917 // once a Sema object is known.
9918 PreloadedDeclIDs.push_back(DeclIDs[I]);
9919 continue;
9920 }
9921
9922 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
9923
9924 // If we're simply supposed to record the declarations, do so now.
9925 if (Decls) {
9926 Decls->push_back(D);
9927 continue;
9928 }
9929
9930 // Introduce this declaration into the translation-unit scope
9931 // and add it to the declaration chain for this identifier, so
9932 // that (unqualified) name lookup will find it.
9933 pushExternalDeclIntoScope(D, II);
9934 }
9935}
9936
9937std::pair<ModuleFile *, unsigned>
9938ASTReader::translateIdentifierIDToIndex(IdentifierID ID) const {
9939 if (ID == 0)
9940 return {nullptr, 0};
9941
9942 unsigned ModuleFileIndex = ID >> 32;
9943 unsigned LocalID = ID & llvm::maskTrailingOnes<IdentifierID>(32);
9944
9945 assert(ModuleFileIndex && "not translating loaded IdentifierID?");
9946 assert(getModuleManager().size() > ModuleFileIndex - 1);
9947
9948 ModuleFile &MF = getModuleManager()[ModuleFileIndex - 1];
9949 assert(LocalID < MF.LocalNumIdentifiers);
9950 return {&MF, MF.BaseIdentifierID + LocalID};
9951}
9952
9954 if (ID == 0)
9955 return nullptr;
9956
9957 if (IdentifiersLoaded.empty()) {
9958 Error("no identifier table in AST file");
9959 return nullptr;
9960 }
9961
9962 auto [M, Index] = translateIdentifierIDToIndex(ID);
9963 if (!IdentifiersLoaded[Index]) {
9964 assert(M != nullptr && "Untranslated Identifier ID?");
9965 assert(Index >= M->BaseIdentifierID);
9966 unsigned LocalIndex = Index - M->BaseIdentifierID;
9967 const unsigned char *Data =
9968 M->IdentifierTableData + M->IdentifierOffsets[LocalIndex];
9969
9970 ASTIdentifierLookupTrait Trait(*this, *M);
9971 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
9972 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
9973 auto &II = PP.getIdentifierTable().get(Key);
9974 IdentifiersLoaded[Index] = &II;
9975 bool IsModule = getPreprocessor().getCurrentModule() != nullptr;
9976 markIdentifierFromAST(*this, II, IsModule);
9977 if (DeserializationListener)
9978 DeserializationListener->IdentifierRead(ID, &II);
9979 }
9980
9981 return IdentifiersLoaded[Index];
9982}
9983
9987
9989 if (LocalID < NUM_PREDEF_IDENT_IDS)
9990 return LocalID;
9991
9992 if (!M.ModuleOffsetMap.empty())
9993 ReadModuleOffsetMap(M);
9994
9995 unsigned ModuleFileIndex = LocalID >> 32;
9996 LocalID &= llvm::maskTrailingOnes<IdentifierID>(32);
9997 ModuleFile *MF =
9998 ModuleFileIndex ? M.TransitiveImports[ModuleFileIndex - 1] : &M;
9999 assert(MF && "malformed identifier ID encoding?");
10000
10001 if (!ModuleFileIndex)
10002 LocalID -= NUM_PREDEF_IDENT_IDS;
10003
10004 return ((IdentifierID)(MF->Index + 1) << 32) | LocalID;
10005}
10006
10007std::pair<ModuleFile *, unsigned>
10008ASTReader::translateMacroIDToIndex(MacroID ID) const {
10009 if (ID == 0)
10010 return {nullptr, 0};
10011
10012 unsigned ModuleFileIndex = ID >> 32;
10013 assert(ModuleFileIndex && "not translating loaded MacroID?");
10014 assert(getModuleManager().size() > ModuleFileIndex - 1);
10015 ModuleFile &MF = getModuleManager()[ModuleFileIndex - 1];
10016
10017 unsigned LocalID = ID & llvm::maskTrailingOnes<MacroID>(32);
10018 assert(LocalID < MF.LocalNumMacros);
10019 return {&MF, MF.BaseMacroID + LocalID};
10020}
10021
10023 if (ID == 0)
10024 return nullptr;
10025
10026 if (MacrosLoaded.empty()) {
10027 Error("no macro table in AST file");
10028 return nullptr;
10029 }
10030
10031 auto [M, Index] = translateMacroIDToIndex(ID);
10032 if (!MacrosLoaded[Index]) {
10033 assert(M != nullptr && "Untranslated Macro ID?");
10034 assert(Index >= M->BaseMacroID);
10035 unsigned LocalIndex = Index - M->BaseMacroID;
10036 uint64_t DataOffset = M->MacroOffsetsBase + M->MacroOffsets[LocalIndex];
10037 MacrosLoaded[Index] = ReadMacroRecord(*M, DataOffset);
10038
10039 if (DeserializationListener)
10040 DeserializationListener->MacroRead(ID, MacrosLoaded[Index]);
10041 }
10042
10043 return MacrosLoaded[Index];
10044}
10045
10047 if (LocalID < NUM_PREDEF_MACRO_IDS)
10048 return LocalID;
10049
10050 if (!M.ModuleOffsetMap.empty())
10051 ReadModuleOffsetMap(M);
10052
10053 unsigned ModuleFileIndex = LocalID >> 32;
10054 LocalID &= llvm::maskTrailingOnes<MacroID>(32);
10055 ModuleFile *MF =
10056 ModuleFileIndex ? M.TransitiveImports[ModuleFileIndex - 1] : &M;
10057 assert(MF && "malformed identifier ID encoding?");
10058
10059 if (!ModuleFileIndex) {
10060 assert(LocalID >= NUM_PREDEF_MACRO_IDS);
10061 LocalID -= NUM_PREDEF_MACRO_IDS;
10062 }
10063
10064 return (static_cast<MacroID>(MF->Index + 1) << 32) | LocalID;
10065}
10066
10068ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) const {
10069 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
10070 return LocalID;
10071
10072 if (!M.ModuleOffsetMap.empty())
10073 ReadModuleOffsetMap(M);
10074
10077 assert(I != M.SubmoduleRemap.end()
10078 && "Invalid index into submodule index remap");
10079
10080 return LocalID + I->second;
10081}
10082
10084 return getSubmodule(ID);
10085}
10086
10088 if (ID & 1) {
10089 // It's a module, look it up by submodule ID.
10090 auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(M, ID >> 1));
10091 return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
10092 } else {
10093 // It's a prefix (preamble, PCH, ...). Look it up by index.
10094 int IndexFromEnd = static_cast<int>(ID >> 1);
10095 assert(IndexFromEnd && "got reference to unknown module file");
10096 return getModuleManager().pch_modules().end()[-IndexFromEnd];
10097 }
10098}
10099
10101 if (!M)
10102 return 1;
10103
10104 // For a file representing a module, use the submodule ID of the top-level
10105 // module as the file ID. For any other kind of file, the number of such
10106 // files loaded beforehand will be the same on reload.
10107 // FIXME: Is this true even if we have an explicit module file and a PCH?
10108 if (M->isModule())
10109 return ((M->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
10110
10111 auto PCHModules = getModuleManager().pch_modules();
10112 auto I = llvm::find(PCHModules, M);
10113 assert(I != PCHModules.end() && "emitting reference to unknown file");
10114 return std::distance(I, PCHModules.end()) << 1;
10115}
10116
10117std::optional<ASTSourceDescriptor> ASTReader::getSourceDescriptor(unsigned ID) {
10118 if (Module *M = getSubmodule(ID))
10119 return ASTSourceDescriptor(*M);
10120
10121 // If there is only a single PCH, return it instead.
10122 // Chained PCH are not supported.
10123 const auto &PCHChain = ModuleMgr.pch_modules();
10124 if (std::distance(std::begin(PCHChain), std::end(PCHChain))) {
10125 ModuleFile &MF = ModuleMgr.getPrimaryModule();
10126 StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName);
10127 StringRef FileName = llvm::sys::path::filename(MF.FileName);
10128 return ASTSourceDescriptor(ModuleName,
10129 llvm::sys::path::parent_path(MF.FileName),
10130 FileName, MF.Signature);
10131 }
10132 return std::nullopt;
10133}
10134
10136 auto I = DefinitionSource.find(FD);
10137 if (I == DefinitionSource.end())
10138 return EK_ReplyHazy;
10139 return I->second ? EK_Never : EK_Always;
10140}
10141
10143 return ThisDeclarationWasADefinitionSet.contains(FD);
10144}
10145
10147 return DecodeSelector(getGlobalSelectorID(M, LocalID));
10148}
10149
10151 if (ID == 0)
10152 return Selector();
10153
10154 if (ID > SelectorsLoaded.size()) {
10155 Error("selector ID out of range in AST file");
10156 return Selector();
10157 }
10158
10159 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
10160 // Load this selector from the selector table.
10161 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
10162 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
10163 ModuleFile &M = *I->second;
10164 ASTSelectorLookupTrait Trait(*this, M);
10165 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
10166 SelectorsLoaded[ID - 1] =
10167 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
10168 if (DeserializationListener)
10169 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
10170 }
10171
10172 return SelectorsLoaded[ID - 1];
10173}
10174
10178
10180 // ID 0 (the null selector) is considered an external selector.
10181 return getTotalNumSelectors() + 1;
10182}
10183
10185ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
10186 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
10187 return LocalID;
10188
10189 if (!M.ModuleOffsetMap.empty())
10190 ReadModuleOffsetMap(M);
10191
10194 assert(I != M.SelectorRemap.end()
10195 && "Invalid index into selector index remap");
10196
10197 return LocalID + I->second;
10198}
10199
10225
10227 DeclarationNameInfo NameInfo;
10228 NameInfo.setName(readDeclarationName());
10229 NameInfo.setLoc(readSourceLocation());
10230 NameInfo.setInfo(readDeclarationNameLoc(NameInfo.getName()));
10231 return NameInfo;
10232}
10233
10237
10239 auto Kind = readInt();
10240 auto ResultType = readQualType();
10241 auto Value = readAPInt();
10242 SpirvOperand Op(SpirvOperand::SpirvOperandKind(Kind), ResultType, Value);
10243 assert(Op.isValid());
10244 return Op;
10245}
10246
10249 unsigned NumTPLists = readInt();
10250 Info.NumTemplParamLists = NumTPLists;
10251 if (NumTPLists) {
10252 Info.TemplParamLists =
10253 new (getContext()) TemplateParameterList *[NumTPLists];
10254 for (unsigned i = 0; i != NumTPLists; ++i)
10256 }
10257}
10258
10261 SourceLocation TemplateLoc = readSourceLocation();
10262 SourceLocation LAngleLoc = readSourceLocation();
10263 SourceLocation RAngleLoc = readSourceLocation();
10264
10265 unsigned NumParams = readInt();
10267 Params.reserve(NumParams);
10268 while (NumParams--)
10269 Params.push_back(readDeclAs<NamedDecl>());
10270
10271 bool HasRequiresClause = readBool();
10272 Expr *RequiresClause = HasRequiresClause ? readExpr() : nullptr;
10273
10275 getContext(), TemplateLoc, LAngleLoc, Params, RAngleLoc, RequiresClause);
10276 return TemplateParams;
10277}
10278
10281 bool Canonicalize) {
10282 unsigned NumTemplateArgs = readInt();
10283 TemplArgs.reserve(NumTemplateArgs);
10284 while (NumTemplateArgs--)
10285 TemplArgs.push_back(readTemplateArgument(Canonicalize));
10286}
10287
10288/// Read a UnresolvedSet structure.
10290 unsigned NumDecls = readInt();
10291 Set.reserve(getContext(), NumDecls);
10292 while (NumDecls--) {
10293 GlobalDeclID ID = readDeclID();
10295 Set.addLazyDecl(getContext(), ID, AS);
10296 }
10297}
10298
10301 bool isVirtual = readBool();
10302 bool isBaseOfClass = readBool();
10303 AccessSpecifier AS = static_cast<AccessSpecifier>(readInt());
10304 bool inheritConstructors = readBool();
10306 SourceRange Range = readSourceRange();
10307 SourceLocation EllipsisLoc = readSourceLocation();
10308 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
10309 EllipsisLoc);
10310 Result.setInheritConstructors(inheritConstructors);
10311 return Result;
10312}
10313
10316 ASTContext &Context = getContext();
10317 unsigned NumInitializers = readInt();
10318 assert(NumInitializers && "wrote ctor initializers but have no inits");
10319 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
10320 for (unsigned i = 0; i != NumInitializers; ++i) {
10321 TypeSourceInfo *TInfo = nullptr;
10322 bool IsBaseVirtual = false;
10323 FieldDecl *Member = nullptr;
10324 IndirectFieldDecl *IndirectMember = nullptr;
10325
10327 switch (Type) {
10329 TInfo = readTypeSourceInfo();
10330 IsBaseVirtual = readBool();
10331 break;
10332
10334 TInfo = readTypeSourceInfo();
10335 break;
10336
10339 break;
10340
10342 IndirectMember = readDeclAs<IndirectFieldDecl>();
10343 break;
10344 }
10345
10346 SourceLocation MemberOrEllipsisLoc = readSourceLocation();
10347 Expr *Init = readExpr();
10348 SourceLocation LParenLoc = readSourceLocation();
10349 SourceLocation RParenLoc = readSourceLocation();
10350
10351 CXXCtorInitializer *BOMInit;
10353 BOMInit = new (Context)
10354 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
10355 RParenLoc, MemberOrEllipsisLoc);
10357 BOMInit = new (Context)
10358 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
10359 else if (Member)
10360 BOMInit = new (Context)
10361 CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc, LParenLoc,
10362 Init, RParenLoc);
10363 else
10364 BOMInit = new (Context)
10365 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
10366 LParenLoc, Init, RParenLoc);
10367
10368 if (/*IsWritten*/readBool()) {
10369 unsigned SourceOrder = readInt();
10370 BOMInit->setSourceOrder(SourceOrder);
10371 }
10372
10373 CtorInitializers[i] = BOMInit;
10374 }
10375
10376 return CtorInitializers;
10377}
10378
10381 ASTContext &Context = getContext();
10382 unsigned N = readInt();
10384 for (unsigned I = 0; I != N; ++I) {
10385 auto Kind = readNestedNameSpecifierKind();
10386 switch (Kind) {
10388 auto *NS = readDeclAs<NamespaceBaseDecl>();
10389 SourceRange Range = readSourceRange();
10390 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
10391 break;
10392 }
10393
10396 if (!T)
10397 return NestedNameSpecifierLoc();
10398 SourceLocation ColonColonLoc = readSourceLocation();
10399 Builder.Make(Context, T->getTypeLoc(), ColonColonLoc);
10400 break;
10401 }
10402
10404 SourceLocation ColonColonLoc = readSourceLocation();
10405 Builder.MakeGlobal(Context, ColonColonLoc);
10406 break;
10407 }
10408
10411 SourceRange Range = readSourceRange();
10412 Builder.MakeMicrosoftSuper(Context, RD, Range.getBegin(), Range.getEnd());
10413 break;
10414 }
10415
10417 llvm_unreachable("unexpected null nested name specifier");
10418 }
10419 }
10420
10421 return Builder.getWithLocInContext(Context);
10422}
10423
10425 unsigned &Idx) {
10428 return SourceRange(beg, end);
10429}
10430
10432 const StringRef Blob) {
10433 unsigned Count = Record[0];
10434 const char *Byte = Blob.data();
10435 llvm::BitVector Ret = llvm::BitVector(Count, false);
10436 for (unsigned I = 0; I < Count; ++Byte)
10437 for (unsigned Bit = 0; Bit < 8 && I < Count; ++Bit, ++I)
10438 if (*Byte & (1 << Bit))
10439 Ret[I] = true;
10440 return Ret;
10441}
10442
10443/// Read a floating-point value
10444llvm::APFloat ASTRecordReader::readAPFloat(const llvm::fltSemantics &Sem) {
10445 return llvm::APFloat(Sem, readAPInt());
10446}
10447
10448// Read a string
10449std::string ASTReader::ReadString(const RecordDataImpl &Record, unsigned &Idx) {
10450 unsigned Len = Record[Idx++];
10451 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
10452 Idx += Len;
10453 return Result;
10454}
10455
10456StringRef ASTReader::ReadStringBlob(const RecordDataImpl &Record, unsigned &Idx,
10457 StringRef &Blob) {
10458 unsigned Len = Record[Idx++];
10459 StringRef Result = Blob.substr(0, Len);
10460 Blob = Blob.substr(Len);
10461 return Result;
10462}
10463
10465 unsigned &Idx) {
10466 return ReadPath(F.BaseDirectory, Record, Idx);
10467}
10468
10469std::string ASTReader::ReadPath(StringRef BaseDirectory,
10470 const RecordData &Record, unsigned &Idx) {
10471 std::string Filename = ReadString(Record, Idx);
10472 return ResolveImportedPathAndAllocate(PathBuf, Filename, BaseDirectory);
10473}
10474
10475std::string ASTReader::ReadPathBlob(StringRef BaseDirectory,
10476 const RecordData &Record, unsigned &Idx,
10477 StringRef &Blob) {
10478 StringRef Filename = ReadStringBlob(Record, Idx, Blob);
10479 return ResolveImportedPathAndAllocate(PathBuf, Filename, BaseDirectory);
10480}
10481
10483 unsigned &Idx) {
10484 unsigned Major = Record[Idx++];
10485 unsigned Minor = Record[Idx++];
10486 unsigned Subminor = Record[Idx++];
10487 if (Minor == 0)
10488 return VersionTuple(Major);
10489 if (Subminor == 0)
10490 return VersionTuple(Major, Minor - 1);
10491 return VersionTuple(Major, Minor - 1, Subminor - 1);
10492}
10493
10500
10501DiagnosticBuilder ASTReader::Diag(unsigned DiagID) const {
10502 return Diag(CurrentImportLoc, DiagID);
10503}
10504
10506 return Diags.Report(Loc, DiagID);
10507}
10508
10510 llvm::function_ref<void()> Fn) {
10511 // When Sema is available, avoid duplicate errors.
10512 if (SemaObj) {
10513 SemaObj->runWithSufficientStackSpace(Loc, Fn);
10514 return;
10515 }
10516
10517 StackHandler.runWithSufficientStackSpace(Loc, Fn);
10518}
10519
10520/// Retrieve the identifier table associated with the
10521/// preprocessor.
10523 return PP.getIdentifierTable();
10524}
10525
10526/// Record that the given ID maps to the given switch-case
10527/// statement.
10529 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
10530 "Already have a SwitchCase with this ID");
10531 (*CurrSwitchCaseStmts)[ID] = SC;
10532}
10533
10534/// Retrieve the switch-case statement with the given ID.
10536 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
10537 return (*CurrSwitchCaseStmts)[ID];
10538}
10539
10541 CurrSwitchCaseStmts->clear();
10542}
10543
10545 ASTContext &Context = getContext();
10546 std::vector<RawComment *> Comments;
10547 for (SmallVectorImpl<std::pair<BitstreamCursor,
10549 I = CommentsCursors.begin(),
10550 E = CommentsCursors.end();
10551 I != E; ++I) {
10552 Comments.clear();
10553 BitstreamCursor &Cursor = I->first;
10554 serialization::ModuleFile &F = *I->second;
10555 SavedStreamPosition SavedPosition(Cursor);
10556
10558 while (true) {
10560 Cursor.advanceSkippingSubblocks(
10561 BitstreamCursor::AF_DontPopBlockAtEnd);
10562 if (!MaybeEntry) {
10563 Error(MaybeEntry.takeError());
10564 return;
10565 }
10566 llvm::BitstreamEntry Entry = MaybeEntry.get();
10567
10568 switch (Entry.Kind) {
10569 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
10570 case llvm::BitstreamEntry::Error:
10571 Error("malformed block record in AST file");
10572 return;
10573 case llvm::BitstreamEntry::EndBlock:
10574 goto NextCursor;
10575 case llvm::BitstreamEntry::Record:
10576 // The interesting case.
10577 break;
10578 }
10579
10580 // Read a record.
10581 Record.clear();
10582 Expected<unsigned> MaybeComment = Cursor.readRecord(Entry.ID, Record);
10583 if (!MaybeComment) {
10584 Error(MaybeComment.takeError());
10585 return;
10586 }
10587 switch ((CommentRecordTypes)MaybeComment.get()) {
10588 case COMMENTS_RAW_COMMENT: {
10589 unsigned Idx = 0;
10590 SourceRange SR = ReadSourceRange(F, Record, Idx);
10593 bool IsTrailingComment = Record[Idx++];
10594 bool IsAlmostTrailingComment = Record[Idx++];
10595 Comments.push_back(new (Context) RawComment(
10596 SR, Kind, IsTrailingComment, IsAlmostTrailingComment));
10597 break;
10598 }
10599 }
10600 }
10601 NextCursor:
10602 for (RawComment *C : Comments) {
10603 SourceLocation CommentLoc = C->getBeginLoc();
10604 if (CommentLoc.isValid()) {
10605 FileIDAndOffset Loc = SourceMgr.getDecomposedLoc(CommentLoc);
10606 if (Loc.first.isValid())
10607 Context.Comments.OrderedComments[Loc.first].emplace(Loc.second, C);
10608 }
10609 }
10610 }
10611}
10612
10614 serialization::ModuleFile &MF, bool IncludeSystem,
10615 llvm::function_ref<void(const serialization::InputFileInfo &IFI,
10616 bool IsSystem)>
10617 Visitor) {
10618 unsigned NumUserInputs = MF.NumUserInputFiles;
10619 unsigned NumInputs = MF.InputFilesLoaded.size();
10620 assert(NumUserInputs <= NumInputs);
10621 unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
10622 for (unsigned I = 0; I < N; ++I) {
10623 bool IsSystem = I >= NumUserInputs;
10624 InputFileInfo IFI = getInputFileInfo(MF, I+1);
10625 Visitor(IFI, IsSystem);
10626 }
10627}
10628
10630 bool IncludeSystem, bool Complain,
10631 llvm::function_ref<void(const serialization::InputFile &IF,
10632 bool isSystem)> Visitor) {
10633 unsigned NumUserInputs = MF.NumUserInputFiles;
10634 unsigned NumInputs = MF.InputFilesLoaded.size();
10635 assert(NumUserInputs <= NumInputs);
10636 unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
10637 for (unsigned I = 0; I < N; ++I) {
10638 bool IsSystem = I >= NumUserInputs;
10639 InputFile IF = getInputFile(MF, I+1, Complain);
10640 Visitor(IF, IsSystem);
10641 }
10642}
10643
10646 llvm::function_ref<void(FileEntryRef FE)> Visitor) {
10647 unsigned NumInputs = MF.InputFilesLoaded.size();
10648 for (unsigned I = 0; I < NumInputs; ++I) {
10649 InputFileInfo IFI = getInputFileInfo(MF, I + 1);
10650 if (IFI.TopLevel && IFI.ModuleMap)
10651 if (auto FE = getInputFile(MF, I + 1).getFile())
10652 Visitor(*FE);
10653 }
10654}
10655
10656void ASTReader::finishPendingActions() {
10657 while (!PendingIdentifierInfos.empty() ||
10658 !PendingDeducedFunctionTypes.empty() ||
10659 !PendingDeducedVarTypes.empty() || !PendingDeclChains.empty() ||
10660 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
10661 !PendingUpdateRecords.empty() ||
10662 !PendingObjCExtensionIvarRedeclarations.empty()) {
10663 // If any identifiers with corresponding top-level declarations have
10664 // been loaded, load those declarations now.
10665 using TopLevelDeclsMap =
10666 llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2>>;
10667 TopLevelDeclsMap TopLevelDecls;
10668
10669 while (!PendingIdentifierInfos.empty()) {
10670 IdentifierInfo *II = PendingIdentifierInfos.back().first;
10672 std::move(PendingIdentifierInfos.back().second);
10673 PendingIdentifierInfos.pop_back();
10674
10675 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
10676 }
10677
10678 // Load each function type that we deferred loading because it was a
10679 // deduced type that might refer to a local type declared within itself.
10680 for (unsigned I = 0; I != PendingDeducedFunctionTypes.size(); ++I) {
10681 auto *FD = PendingDeducedFunctionTypes[I].first;
10682 FD->setType(GetType(PendingDeducedFunctionTypes[I].second));
10683
10684 if (auto *DT = FD->getReturnType()->getContainedDeducedType()) {
10685 // If we gave a function a deduced return type, remember that we need to
10686 // propagate that along the redeclaration chain.
10687 if (DT->isDeduced()) {
10688 PendingDeducedTypeUpdates.insert(
10689 {FD->getCanonicalDecl(), FD->getReturnType()});
10690 continue;
10691 }
10692
10693 // The function has undeduced DeduceType return type. We hope we can
10694 // find the deduced type by iterating the redecls in other modules
10695 // later.
10696 PendingUndeducedFunctionDecls.push_back(FD);
10697 continue;
10698 }
10699 }
10700 PendingDeducedFunctionTypes.clear();
10701
10702 // Load each variable type that we deferred loading because it was a
10703 // deduced type that might refer to a local type declared within itself.
10704 for (unsigned I = 0; I != PendingDeducedVarTypes.size(); ++I) {
10705 auto *VD = PendingDeducedVarTypes[I].first;
10706 VD->setType(GetType(PendingDeducedVarTypes[I].second));
10707 }
10708 PendingDeducedVarTypes.clear();
10709
10710 // Load pending declaration chains.
10711 for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
10712 loadPendingDeclChain(PendingDeclChains[I].first,
10713 PendingDeclChains[I].second);
10714 PendingDeclChains.clear();
10715
10716 // Make the most recent of the top-level declarations visible.
10717 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
10718 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
10719 IdentifierInfo *II = TLD->first;
10720 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
10721 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
10722 }
10723 }
10724
10725 // Load any pending macro definitions.
10726 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
10727 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
10728 SmallVector<PendingMacroInfo, 2> GlobalIDs;
10729 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
10730 // Initialize the macro history from chained-PCHs ahead of module imports.
10731 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
10732 ++IDIdx) {
10733 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
10734 if (!Info.M->isModule())
10735 resolvePendingMacro(II, Info);
10736 }
10737 // Handle module imports.
10738 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
10739 ++IDIdx) {
10740 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
10741 if (Info.M->isModule())
10742 resolvePendingMacro(II, Info);
10743 }
10744 }
10745 PendingMacroIDs.clear();
10746
10747 // Wire up the DeclContexts for Decls that we delayed setting until
10748 // recursive loading is completed.
10749 while (!PendingDeclContextInfos.empty()) {
10750 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
10751 PendingDeclContextInfos.pop_front();
10752 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
10753 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
10754 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
10755 }
10756
10757 // Perform any pending declaration updates.
10758 while (!PendingUpdateRecords.empty()) {
10759 auto Update = PendingUpdateRecords.pop_back_val();
10760 ReadingKindTracker ReadingKind(Read_Decl, *this);
10761 loadDeclUpdateRecords(Update);
10762 }
10763
10764 while (!PendingObjCExtensionIvarRedeclarations.empty()) {
10765 auto ExtensionsPair = PendingObjCExtensionIvarRedeclarations.back().first;
10766 auto DuplicateIvars =
10767 PendingObjCExtensionIvarRedeclarations.back().second;
10769 StructuralEquivalenceContext Ctx(
10770 ContextObj->getLangOpts(), ExtensionsPair.first->getASTContext(),
10771 ExtensionsPair.second->getASTContext(), NonEquivalentDecls,
10772 StructuralEquivalenceKind::Default, /*StrictTypeSpelling =*/false,
10773 /*Complain =*/false,
10774 /*ErrorOnTagTypeMismatch =*/true);
10775 if (Ctx.IsEquivalent(ExtensionsPair.first, ExtensionsPair.second)) {
10776 // Merge redeclared ivars with their predecessors.
10777 for (auto IvarPair : DuplicateIvars) {
10778 ObjCIvarDecl *Ivar = IvarPair.first, *PrevIvar = IvarPair.second;
10779 // Change semantic DeclContext but keep the lexical one.
10780 Ivar->setDeclContextsImpl(PrevIvar->getDeclContext(),
10781 Ivar->getLexicalDeclContext(),
10782 getContext());
10783 getContext().setPrimaryMergedDecl(Ivar, PrevIvar->getCanonicalDecl());
10784 }
10785 // Invalidate duplicate extension and the cached ivar list.
10786 ExtensionsPair.first->setInvalidDecl();
10787 ExtensionsPair.second->getClassInterface()
10788 ->getDefinition()
10789 ->setIvarList(nullptr);
10790 } else {
10791 for (auto IvarPair : DuplicateIvars) {
10792 Diag(IvarPair.first->getLocation(),
10793 diag::err_duplicate_ivar_declaration)
10794 << IvarPair.first->getIdentifier();
10795 Diag(IvarPair.second->getLocation(), diag::note_previous_definition);
10796 }
10797 }
10798 PendingObjCExtensionIvarRedeclarations.pop_back();
10799 }
10800 }
10801
10802 // At this point, all update records for loaded decls are in place, so any
10803 // fake class definitions should have become real.
10804 assert(PendingFakeDefinitionData.empty() &&
10805 "faked up a class definition but never saw the real one");
10806
10807 // If we deserialized any C++ or Objective-C class definitions, any
10808 // Objective-C protocol definitions, or any redeclarable templates, make sure
10809 // that all redeclarations point to the definitions. Note that this can only
10810 // happen now, after the redeclaration chains have been fully wired.
10811 for (Decl *D : PendingDefinitions) {
10812 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
10813 if (auto *RD = dyn_cast<CXXRecordDecl>(TD)) {
10814 for (auto *R = getMostRecentExistingDecl(RD); R;
10815 R = R->getPreviousDecl()) {
10816 assert((R == D) ==
10817 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
10818 "declaration thinks it's the definition but it isn't");
10819 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
10820 }
10821 }
10822
10823 continue;
10824 }
10825
10826 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
10827 // Make sure that the ObjCInterfaceType points at the definition.
10828 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
10829 ->Decl = ID;
10830
10831 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
10832 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
10833
10834 continue;
10835 }
10836
10837 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
10838 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
10839 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
10840
10841 continue;
10842 }
10843
10844 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
10845 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
10846 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
10847 }
10848 PendingDefinitions.clear();
10849
10850 for (auto [D, Previous] : PendingWarningForDuplicatedDefsInModuleUnits) {
10851 auto hasDefinitionImpl = [this](Decl *D, auto hasDefinitionImpl) {
10852 if (auto *VD = dyn_cast<VarDecl>(D))
10853 return VD->isThisDeclarationADefinition() ||
10854 VD->isThisDeclarationADemotedDefinition();
10855
10856 if (auto *TD = dyn_cast<TagDecl>(D))
10857 return TD->isThisDeclarationADefinition() ||
10858 TD->isThisDeclarationADemotedDefinition();
10859
10860 if (auto *FD = dyn_cast<FunctionDecl>(D))
10861 return FD->isThisDeclarationADefinition() || PendingBodies.count(FD);
10862
10863 if (auto *RTD = dyn_cast<RedeclarableTemplateDecl>(D))
10864 return hasDefinitionImpl(RTD->getTemplatedDecl(), hasDefinitionImpl);
10865
10866 // Conservatively return false here.
10867 return false;
10868 };
10869
10870 auto hasDefinition = [&hasDefinitionImpl](Decl *D) {
10871 return hasDefinitionImpl(D, hasDefinitionImpl);
10872 };
10873
10874 // It is not good to prevent multiple declarations since the forward
10875 // declaration is common. Let's try to avoid duplicated definitions
10876 // only.
10878 continue;
10879
10880 Module *PM = Previous->getOwningModule();
10881 Module *DM = D->getOwningModule();
10882 Diag(D->getLocation(), diag::warn_decls_in_multiple_modules)
10884 << (DM ? DM->getTopLevelModuleName() : "global module");
10885 Diag(Previous->getLocation(), diag::note_also_found);
10886 }
10887 PendingWarningForDuplicatedDefsInModuleUnits.clear();
10888
10889 // Load the bodies of any functions or methods we've encountered. We do
10890 // this now (delayed) so that we can be sure that the declaration chains
10891 // have been fully wired up (hasBody relies on this).
10892 // FIXME: We shouldn't require complete redeclaration chains here.
10893 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
10894 PBEnd = PendingBodies.end();
10895 PB != PBEnd; ++PB) {
10896 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
10897 // FIXME: Check for =delete/=default?
10898 const FunctionDecl *Defn = nullptr;
10899 if (!getContext().getLangOpts().Modules || !FD->hasBody(Defn)) {
10900 FD->setLazyBody(PB->second);
10901 } else {
10902 auto *NonConstDefn = const_cast<FunctionDecl*>(Defn);
10903 mergeDefinitionVisibility(NonConstDefn, FD);
10904
10905 if (!FD->isLateTemplateParsed() &&
10906 !NonConstDefn->isLateTemplateParsed() &&
10907 // We only perform ODR checks for decls not in the explicit
10908 // global module fragment.
10909 !shouldSkipCheckingODR(FD) &&
10910 !shouldSkipCheckingODR(NonConstDefn) &&
10911 FD->getODRHash() != NonConstDefn->getODRHash()) {
10912 if (!isa<CXXMethodDecl>(FD)) {
10913 PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
10914 } else if (FD->getLexicalParent()->isFileContext() &&
10915 NonConstDefn->getLexicalParent()->isFileContext()) {
10916 // Only diagnose out-of-line method definitions. If they are
10917 // in class definitions, then an error will be generated when
10918 // processing the class bodies.
10919 PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
10920 }
10921 }
10922 }
10923 continue;
10924 }
10925
10926 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
10927 if (!getContext().getLangOpts().Modules || !MD->hasBody())
10928 MD->setLazyBody(PB->second);
10929 }
10930 PendingBodies.clear();
10931
10932 // Inform any classes that had members added that they now have more members.
10933 for (auto [RD, MD] : PendingAddedClassMembers) {
10934 RD->addedMember(MD);
10935 }
10936 PendingAddedClassMembers.clear();
10937
10938 // Do some cleanup.
10939 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
10941 PendingMergedDefinitionsToDeduplicate.clear();
10942
10943 // For each decl chain that we wanted to complete while deserializing, mark
10944 // it as "still needs to be completed".
10945 for (Decl *D : PendingIncompleteDeclChains)
10946 markIncompleteDeclChain(D);
10947 PendingIncompleteDeclChains.clear();
10948
10949 assert(PendingIdentifierInfos.empty() &&
10950 "Should be empty at the end of finishPendingActions");
10951 assert(PendingDeducedFunctionTypes.empty() &&
10952 "Should be empty at the end of finishPendingActions");
10953 assert(PendingDeducedVarTypes.empty() &&
10954 "Should be empty at the end of finishPendingActions");
10955 assert(PendingDeclChains.empty() &&
10956 "Should be empty at the end of finishPendingActions");
10957 assert(PendingMacroIDs.empty() &&
10958 "Should be empty at the end of finishPendingActions");
10959 assert(PendingDeclContextInfos.empty() &&
10960 "Should be empty at the end of finishPendingActions");
10961 assert(PendingUpdateRecords.empty() &&
10962 "Should be empty at the end of finishPendingActions");
10963 assert(PendingObjCExtensionIvarRedeclarations.empty() &&
10964 "Should be empty at the end of finishPendingActions");
10965 assert(PendingFakeDefinitionData.empty() &&
10966 "Should be empty at the end of finishPendingActions");
10967 assert(PendingDefinitions.empty() &&
10968 "Should be empty at the end of finishPendingActions");
10969 assert(PendingWarningForDuplicatedDefsInModuleUnits.empty() &&
10970 "Should be empty at the end of finishPendingActions");
10971 assert(PendingBodies.empty() &&
10972 "Should be empty at the end of finishPendingActions");
10973 assert(PendingAddedClassMembers.empty() &&
10974 "Should be empty at the end of finishPendingActions");
10975 assert(PendingMergedDefinitionsToDeduplicate.empty() &&
10976 "Should be empty at the end of finishPendingActions");
10977 assert(PendingIncompleteDeclChains.empty() &&
10978 "Should be empty at the end of finishPendingActions");
10979}
10980
10981void ASTReader::diagnoseOdrViolations() {
10982 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty() &&
10983 PendingRecordOdrMergeFailures.empty() &&
10984 PendingFunctionOdrMergeFailures.empty() &&
10985 PendingEnumOdrMergeFailures.empty() &&
10986 PendingObjCInterfaceOdrMergeFailures.empty() &&
10987 PendingObjCProtocolOdrMergeFailures.empty())
10988 return;
10989
10990 // Trigger the import of the full definition of each class that had any
10991 // odr-merging problems, so we can produce better diagnostics for them.
10992 // These updates may in turn find and diagnose some ODR failures, so take
10993 // ownership of the set first.
10994 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
10995 PendingOdrMergeFailures.clear();
10996 for (auto &Merge : OdrMergeFailures) {
10997 Merge.first->buildLookup();
10998 Merge.first->decls_begin();
10999 Merge.first->bases_begin();
11000 Merge.first->vbases_begin();
11001 for (auto &RecordPair : Merge.second) {
11002 auto *RD = RecordPair.first;
11003 RD->decls_begin();
11004 RD->bases_begin();
11005 RD->vbases_begin();
11006 }
11007 }
11008
11009 // Trigger the import of the full definition of each record in C/ObjC.
11010 auto RecordOdrMergeFailures = std::move(PendingRecordOdrMergeFailures);
11011 PendingRecordOdrMergeFailures.clear();
11012 for (auto &Merge : RecordOdrMergeFailures) {
11013 Merge.first->decls_begin();
11014 for (auto &D : Merge.second)
11015 D->decls_begin();
11016 }
11017
11018 // Trigger the import of the full interface definition.
11019 auto ObjCInterfaceOdrMergeFailures =
11020 std::move(PendingObjCInterfaceOdrMergeFailures);
11021 PendingObjCInterfaceOdrMergeFailures.clear();
11022 for (auto &Merge : ObjCInterfaceOdrMergeFailures) {
11023 Merge.first->decls_begin();
11024 for (auto &InterfacePair : Merge.second)
11025 InterfacePair.first->decls_begin();
11026 }
11027
11028 // Trigger the import of functions.
11029 auto FunctionOdrMergeFailures = std::move(PendingFunctionOdrMergeFailures);
11030 PendingFunctionOdrMergeFailures.clear();
11031 for (auto &Merge : FunctionOdrMergeFailures) {
11032 Merge.first->buildLookup();
11033 Merge.first->decls_begin();
11034 Merge.first->getBody();
11035 for (auto &FD : Merge.second) {
11036 FD->buildLookup();
11037 FD->decls_begin();
11038 FD->getBody();
11039 }
11040 }
11041
11042 // Trigger the import of enums.
11043 auto EnumOdrMergeFailures = std::move(PendingEnumOdrMergeFailures);
11044 PendingEnumOdrMergeFailures.clear();
11045 for (auto &Merge : EnumOdrMergeFailures) {
11046 Merge.first->decls_begin();
11047 for (auto &Enum : Merge.second) {
11048 Enum->decls_begin();
11049 }
11050 }
11051
11052 // Trigger the import of the full protocol definition.
11053 auto ObjCProtocolOdrMergeFailures =
11054 std::move(PendingObjCProtocolOdrMergeFailures);
11055 PendingObjCProtocolOdrMergeFailures.clear();
11056 for (auto &Merge : ObjCProtocolOdrMergeFailures) {
11057 Merge.first->decls_begin();
11058 for (auto &ProtocolPair : Merge.second)
11059 ProtocolPair.first->decls_begin();
11060 }
11061
11062 // For each declaration from a merged context, check that the canonical
11063 // definition of that context also contains a declaration of the same
11064 // entity.
11065 //
11066 // Caution: this loop does things that might invalidate iterators into
11067 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
11068 while (!PendingOdrMergeChecks.empty()) {
11069 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
11070
11071 // FIXME: Skip over implicit declarations for now. This matters for things
11072 // like implicitly-declared special member functions. This isn't entirely
11073 // correct; we can end up with multiple unmerged declarations of the same
11074 // implicit entity.
11075 if (D->isImplicit())
11076 continue;
11077
11078 DeclContext *CanonDef = D->getDeclContext();
11079
11080 bool Found = false;
11081 const Decl *DCanon = D->getCanonicalDecl();
11082
11083 for (auto *RI : D->redecls()) {
11084 if (RI->getLexicalDeclContext() == CanonDef) {
11085 Found = true;
11086 break;
11087 }
11088 }
11089 if (Found)
11090 continue;
11091
11092 // Quick check failed, time to do the slow thing. Note, we can't just
11093 // look up the name of D in CanonDef here, because the member that is
11094 // in CanonDef might not be found by name lookup (it might have been
11095 // replaced by a more recent declaration in the lookup table), and we
11096 // can't necessarily find it in the redeclaration chain because it might
11097 // be merely mergeable, not redeclarable.
11098 llvm::SmallVector<const NamedDecl*, 4> Candidates;
11099 for (auto *CanonMember : CanonDef->decls()) {
11100 if (CanonMember->getCanonicalDecl() == DCanon) {
11101 // This can happen if the declaration is merely mergeable and not
11102 // actually redeclarable (we looked for redeclarations earlier).
11103 //
11104 // FIXME: We should be able to detect this more efficiently, without
11105 // pulling in all of the members of CanonDef.
11106 Found = true;
11107 break;
11108 }
11109 if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
11110 if (ND->getDeclName() == D->getDeclName())
11111 Candidates.push_back(ND);
11112 }
11113
11114 if (!Found) {
11115 // The AST doesn't like TagDecls becoming invalid after they've been
11116 // completed. We only really need to mark FieldDecls as invalid here.
11117 if (!isa<TagDecl>(D))
11118 D->setInvalidDecl();
11119
11120 // Ensure we don't accidentally recursively enter deserialization while
11121 // we're producing our diagnostic.
11122 Deserializing RecursionGuard(this);
11123
11124 std::string CanonDefModule =
11126 cast<Decl>(CanonDef));
11127 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
11129 << CanonDef << CanonDefModule.empty() << CanonDefModule;
11130
11131 if (Candidates.empty())
11132 Diag(cast<Decl>(CanonDef)->getLocation(),
11133 diag::note_module_odr_violation_no_possible_decls) << D;
11134 else {
11135 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
11136 Diag(Candidates[I]->getLocation(),
11137 diag::note_module_odr_violation_possible_decl)
11138 << Candidates[I];
11139 }
11140
11141 DiagnosedOdrMergeFailures.insert(CanonDef);
11142 }
11143 }
11144
11145 if (OdrMergeFailures.empty() && RecordOdrMergeFailures.empty() &&
11146 FunctionOdrMergeFailures.empty() && EnumOdrMergeFailures.empty() &&
11147 ObjCInterfaceOdrMergeFailures.empty() &&
11148 ObjCProtocolOdrMergeFailures.empty())
11149 return;
11150
11151 ODRDiagsEmitter DiagsEmitter(Diags, getContext(),
11152 getPreprocessor().getLangOpts());
11153
11154 // Issue any pending ODR-failure diagnostics.
11155 for (auto &Merge : OdrMergeFailures) {
11156 // If we've already pointed out a specific problem with this class, don't
11157 // bother issuing a general "something's different" diagnostic.
11158 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
11159 continue;
11160
11161 bool Diagnosed = false;
11162 CXXRecordDecl *FirstRecord = Merge.first;
11163 for (auto &RecordPair : Merge.second) {
11164 if (DiagsEmitter.diagnoseMismatch(FirstRecord, RecordPair.first,
11165 RecordPair.second)) {
11166 Diagnosed = true;
11167 break;
11168 }
11169 }
11170
11171 if (!Diagnosed) {
11172 // All definitions are updates to the same declaration. This happens if a
11173 // module instantiates the declaration of a class template specialization
11174 // and two or more other modules instantiate its definition.
11175 //
11176 // FIXME: Indicate which modules had instantiations of this definition.
11177 // FIXME: How can this even happen?
11178 Diag(Merge.first->getLocation(),
11179 diag::err_module_odr_violation_different_instantiations)
11180 << Merge.first;
11181 }
11182 }
11183
11184 // Issue any pending ODR-failure diagnostics for RecordDecl in C/ObjC. Note
11185 // that in C++ this is done as a part of CXXRecordDecl ODR checking.
11186 for (auto &Merge : RecordOdrMergeFailures) {
11187 // If we've already pointed out a specific problem with this class, don't
11188 // bother issuing a general "something's different" diagnostic.
11189 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
11190 continue;
11191
11192 RecordDecl *FirstRecord = Merge.first;
11193 bool Diagnosed = false;
11194 for (auto *SecondRecord : Merge.second) {
11195 if (DiagsEmitter.diagnoseMismatch(FirstRecord, SecondRecord)) {
11196 Diagnosed = true;
11197 break;
11198 }
11199 }
11200 (void)Diagnosed;
11201 assert(Diagnosed && "Unable to emit ODR diagnostic.");
11202 }
11203
11204 // Issue ODR failures diagnostics for functions.
11205 for (auto &Merge : FunctionOdrMergeFailures) {
11206 FunctionDecl *FirstFunction = Merge.first;
11207 bool Diagnosed = false;
11208 for (auto &SecondFunction : Merge.second) {
11209 if (DiagsEmitter.diagnoseMismatch(FirstFunction, SecondFunction)) {
11210 Diagnosed = true;
11211 break;
11212 }
11213 }
11214 (void)Diagnosed;
11215 assert(Diagnosed && "Unable to emit ODR diagnostic.");
11216 }
11217
11218 // Issue ODR failures diagnostics for enums.
11219 for (auto &Merge : EnumOdrMergeFailures) {
11220 // If we've already pointed out a specific problem with this enum, don't
11221 // bother issuing a general "something's different" diagnostic.
11222 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
11223 continue;
11224
11225 EnumDecl *FirstEnum = Merge.first;
11226 bool Diagnosed = false;
11227 for (auto &SecondEnum : Merge.second) {
11228 if (DiagsEmitter.diagnoseMismatch(FirstEnum, SecondEnum)) {
11229 Diagnosed = true;
11230 break;
11231 }
11232 }
11233 (void)Diagnosed;
11234 assert(Diagnosed && "Unable to emit ODR diagnostic.");
11235 }
11236
11237 for (auto &Merge : ObjCInterfaceOdrMergeFailures) {
11238 // If we've already pointed out a specific problem with this interface,
11239 // don't bother issuing a general "something's different" diagnostic.
11240 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
11241 continue;
11242
11243 bool Diagnosed = false;
11244 ObjCInterfaceDecl *FirstID = Merge.first;
11245 for (auto &InterfacePair : Merge.second) {
11246 if (DiagsEmitter.diagnoseMismatch(FirstID, InterfacePair.first,
11247 InterfacePair.second)) {
11248 Diagnosed = true;
11249 break;
11250 }
11251 }
11252 (void)Diagnosed;
11253 assert(Diagnosed && "Unable to emit ODR diagnostic.");
11254 }
11255
11256 for (auto &Merge : ObjCProtocolOdrMergeFailures) {
11257 // If we've already pointed out a specific problem with this protocol,
11258 // don't bother issuing a general "something's different" diagnostic.
11259 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
11260 continue;
11261
11262 ObjCProtocolDecl *FirstProtocol = Merge.first;
11263 bool Diagnosed = false;
11264 for (auto &ProtocolPair : Merge.second) {
11265 if (DiagsEmitter.diagnoseMismatch(FirstProtocol, ProtocolPair.first,
11266 ProtocolPair.second)) {
11267 Diagnosed = true;
11268 break;
11269 }
11270 }
11271 (void)Diagnosed;
11272 assert(Diagnosed && "Unable to emit ODR diagnostic.");
11273 }
11274}
11275
11277 if (llvm::Timer *T = ReadTimer.get();
11278 ++NumCurrentElementsDeserializing == 1 && T)
11279 ReadTimeRegion.emplace(T);
11280}
11281
11283 assert(NumCurrentElementsDeserializing &&
11284 "FinishedDeserializing not paired with StartedDeserializing");
11285 if (NumCurrentElementsDeserializing == 1) {
11286 // We decrease NumCurrentElementsDeserializing only after pending actions
11287 // are finished, to avoid recursively re-calling finishPendingActions().
11288 finishPendingActions();
11289 }
11290 --NumCurrentElementsDeserializing;
11291
11292 if (NumCurrentElementsDeserializing == 0) {
11293 {
11294 // Guard variable to avoid recursively entering the process of passing
11295 // decls to consumer.
11296 SaveAndRestore GuardPassingDeclsToConsumer(CanPassDeclsToConsumer,
11297 /*NewValue=*/false);
11298
11299 // Propagate exception specification and deduced type updates along
11300 // redeclaration chains.
11301 //
11302 // We do this now rather than in finishPendingActions because we want to
11303 // be able to walk the complete redeclaration chains of the updated decls.
11304 while (!PendingExceptionSpecUpdates.empty() ||
11305 !PendingDeducedTypeUpdates.empty() ||
11306 !PendingUndeducedFunctionDecls.empty()) {
11307 auto ESUpdates = std::move(PendingExceptionSpecUpdates);
11308 PendingExceptionSpecUpdates.clear();
11309 for (auto Update : ESUpdates) {
11310 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
11311 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
11312 auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
11313 if (auto *Listener = getContext().getASTMutationListener())
11314 Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
11315 for (auto *Redecl : Update.second->redecls())
11317 }
11318
11319 auto DTUpdates = std::move(PendingDeducedTypeUpdates);
11320 PendingDeducedTypeUpdates.clear();
11321 for (auto Update : DTUpdates) {
11322 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
11323 // FIXME: If the return type is already deduced, check that it
11324 // matches.
11326 Update.second);
11327 }
11328
11329 auto UDTUpdates = std::move(PendingUndeducedFunctionDecls);
11330 PendingUndeducedFunctionDecls.clear();
11331 // We hope we can find the deduced type for the functions by iterating
11332 // redeclarations in other modules.
11333 for (FunctionDecl *UndeducedFD : UDTUpdates)
11334 (void)UndeducedFD->getMostRecentDecl();
11335 }
11336
11337 ReadTimeRegion.reset();
11338
11339 diagnoseOdrViolations();
11340 }
11341
11342 // We are not in recursive loading, so it's safe to pass the "interesting"
11343 // decls to the consumer.
11344 if (Consumer)
11345 PassInterestingDeclsToConsumer();
11346 }
11347}
11348
11349void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
11350 if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) {
11351 // Remove any fake results before adding any real ones.
11352 auto It = PendingFakeLookupResults.find(II);
11353 if (It != PendingFakeLookupResults.end()) {
11354 for (auto *ND : It->second)
11355 SemaObj->IdResolver.RemoveDecl(ND);
11356 // FIXME: this works around module+PCH performance issue.
11357 // Rather than erase the result from the map, which is O(n), just clear
11358 // the vector of NamedDecls.
11359 It->second.clear();
11360 }
11361 }
11362
11363 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
11364 SemaObj->TUScope->AddDecl(D);
11365 } else if (SemaObj->TUScope) {
11366 // Adding the decl to IdResolver may have failed because it was already in
11367 // (even though it was not added in scope). If it is already in, make sure
11368 // it gets in the scope as well.
11369 if (llvm::is_contained(SemaObj->IdResolver.decls(Name), D))
11370 SemaObj->TUScope->AddDecl(D);
11371 }
11372}
11373
11375 ASTContext *Context,
11376 const PCHContainerReader &PCHContainerRdr,
11377 const CodeGenOptions &CodeGenOpts,
11378 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
11379 StringRef isysroot,
11380 DisableValidationForModuleKind DisableValidationKind,
11381 bool AllowASTWithCompilerErrors,
11382 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
11383 bool ForceValidateUserInputs,
11384 bool ValidateASTInputFilesContent, bool UseGlobalIndex,
11385 std::unique_ptr<llvm::Timer> ReadTimer)
11386 : Listener(bool(DisableValidationKind & DisableValidationForModuleKind::PCH)
11388 : cast<ASTReaderListener>(new PCHValidator(PP, *this))),
11389 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
11390 PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()),
11391 StackHandler(Diags), PP(PP), ContextObj(Context),
11392 CodeGenOpts(CodeGenOpts),
11393 ModuleMgr(PP.getFileManager(), ModCache, PCHContainerRdr,
11394 PP.getHeaderSearchInfo()),
11395 DummyIdResolver(PP), ReadTimer(std::move(ReadTimer)), isysroot(isysroot),
11396 DisableValidationKind(DisableValidationKind),
11397 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
11398 AllowConfigurationMismatch(AllowConfigurationMismatch),
11399 ValidateSystemInputs(ValidateSystemInputs),
11400 ForceValidateUserInputs(ForceValidateUserInputs),
11401 ValidateASTInputFilesContent(ValidateASTInputFilesContent),
11402 UseGlobalIndex(UseGlobalIndex), CurrSwitchCaseStmts(&SwitchCaseStmts) {
11403 SourceMgr.setExternalSLocEntrySource(this);
11404
11405 PathBuf.reserve(256);
11406
11407 for (const auto &Ext : Extensions) {
11408 auto BlockName = Ext->getExtensionMetadata().BlockName;
11409 auto Known = ModuleFileExtensions.find(BlockName);
11410 if (Known != ModuleFileExtensions.end()) {
11411 Diags.Report(diag::warn_duplicate_module_file_extension)
11412 << BlockName;
11413 continue;
11414 }
11415
11416 ModuleFileExtensions.insert({BlockName, Ext});
11417 }
11418}
11419
11421 if (OwnsDeserializationListener)
11422 delete DeserializationListener;
11423}
11424
11426 return SemaObj ? SemaObj->IdResolver : DummyIdResolver;
11427}
11428
11430 unsigned AbbrevID) {
11431 Idx = 0;
11432 Record.clear();
11433 return Cursor.readRecord(AbbrevID, Record);
11434}
11435//===----------------------------------------------------------------------===//
11436//// OMPClauseReader implementation
11437////===----------------------------------------------------------------------===//
11438
11439// This has to be in namespace clang because it's friended by all
11440// of the OMP clauses.
11441namespace clang {
11442
11443class OMPClauseReader : public OMPClauseVisitor<OMPClauseReader> {
11444 ASTRecordReader &Record;
11445 ASTContext &Context;
11446
11447public:
11449 : Record(Record), Context(Record.getContext()) {}
11450#define GEN_CLANG_CLAUSE_CLASS
11451#define CLAUSE_CLASS(Enum, Str, Class) void Visit##Class(Class *C);
11452#include "llvm/Frontend/OpenMP/OMP.inc"
11456};
11457
11458} // end namespace clang
11459
11463
11465 OMPClause *C = nullptr;
11466 switch (llvm::omp::Clause(Record.readInt())) {
11467 case llvm::omp::OMPC_if:
11468 C = new (Context) OMPIfClause();
11469 break;
11470 case llvm::omp::OMPC_final:
11471 C = new (Context) OMPFinalClause();
11472 break;
11473 case llvm::omp::OMPC_num_threads:
11474 C = new (Context) OMPNumThreadsClause();
11475 break;
11476 case llvm::omp::OMPC_safelen:
11477 C = new (Context) OMPSafelenClause();
11478 break;
11479 case llvm::omp::OMPC_simdlen:
11480 C = new (Context) OMPSimdlenClause();
11481 break;
11482 case llvm::omp::OMPC_sizes: {
11483 unsigned NumSizes = Record.readInt();
11484 C = OMPSizesClause::CreateEmpty(Context, NumSizes);
11485 break;
11486 }
11487 case llvm::omp::OMPC_counts: {
11488 unsigned NumCounts = Record.readInt();
11489 C = OMPCountsClause::CreateEmpty(Context, NumCounts);
11490 break;
11491 }
11492 case llvm::omp::OMPC_permutation: {
11493 unsigned NumLoops = Record.readInt();
11494 C = OMPPermutationClause::CreateEmpty(Context, NumLoops);
11495 break;
11496 }
11497 case llvm::omp::OMPC_full:
11498 C = OMPFullClause::CreateEmpty(Context);
11499 break;
11500 case llvm::omp::OMPC_partial:
11502 break;
11503 case llvm::omp::OMPC_looprange:
11505 break;
11506 case llvm::omp::OMPC_allocator:
11507 C = new (Context) OMPAllocatorClause();
11508 break;
11509 case llvm::omp::OMPC_collapse:
11510 C = new (Context) OMPCollapseClause();
11511 break;
11512 case llvm::omp::OMPC_default:
11513 C = new (Context) OMPDefaultClause();
11514 break;
11515 case llvm::omp::OMPC_proc_bind:
11516 C = new (Context) OMPProcBindClause();
11517 break;
11518 case llvm::omp::OMPC_schedule:
11519 C = new (Context) OMPScheduleClause();
11520 break;
11521 case llvm::omp::OMPC_ordered:
11522 C = OMPOrderedClause::CreateEmpty(Context, Record.readInt());
11523 break;
11524 case llvm::omp::OMPC_nowait:
11525 C = new (Context) OMPNowaitClause();
11526 break;
11527 case llvm::omp::OMPC_untied:
11528 C = new (Context) OMPUntiedClause();
11529 break;
11530 case llvm::omp::OMPC_mergeable:
11531 C = new (Context) OMPMergeableClause();
11532 break;
11533 case llvm::omp::OMPC_threadset:
11534 C = new (Context) OMPThreadsetClause();
11535 break;
11536 case llvm::omp::OMPC_transparent:
11537 C = new (Context) OMPTransparentClause();
11538 break;
11539 case llvm::omp::OMPC_read:
11540 C = new (Context) OMPReadClause();
11541 break;
11542 case llvm::omp::OMPC_write:
11543 C = new (Context) OMPWriteClause();
11544 break;
11545 case llvm::omp::OMPC_update:
11546 C = OMPUpdateClause::CreateEmpty(Context, Record.readInt());
11547 break;
11548 case llvm::omp::OMPC_capture:
11549 C = new (Context) OMPCaptureClause();
11550 break;
11551 case llvm::omp::OMPC_compare:
11552 C = new (Context) OMPCompareClause();
11553 break;
11554 case llvm::omp::OMPC_fail:
11555 C = new (Context) OMPFailClause();
11556 break;
11557 case llvm::omp::OMPC_seq_cst:
11558 C = new (Context) OMPSeqCstClause();
11559 break;
11560 case llvm::omp::OMPC_acq_rel:
11561 C = new (Context) OMPAcqRelClause();
11562 break;
11563 case llvm::omp::OMPC_absent: {
11564 unsigned NumKinds = Record.readInt();
11565 C = OMPAbsentClause::CreateEmpty(Context, NumKinds);
11566 break;
11567 }
11568 case llvm::omp::OMPC_holds:
11569 C = new (Context) OMPHoldsClause();
11570 break;
11571 case llvm::omp::OMPC_contains: {
11572 unsigned NumKinds = Record.readInt();
11573 C = OMPContainsClause::CreateEmpty(Context, NumKinds);
11574 break;
11575 }
11576 case llvm::omp::OMPC_no_openmp:
11577 C = new (Context) OMPNoOpenMPClause();
11578 break;
11579 case llvm::omp::OMPC_no_openmp_routines:
11580 C = new (Context) OMPNoOpenMPRoutinesClause();
11581 break;
11582 case llvm::omp::OMPC_no_openmp_constructs:
11583 C = new (Context) OMPNoOpenMPConstructsClause();
11584 break;
11585 case llvm::omp::OMPC_no_parallelism:
11586 C = new (Context) OMPNoParallelismClause();
11587 break;
11588 case llvm::omp::OMPC_acquire:
11589 C = new (Context) OMPAcquireClause();
11590 break;
11591 case llvm::omp::OMPC_release:
11592 C = new (Context) OMPReleaseClause();
11593 break;
11594 case llvm::omp::OMPC_relaxed:
11595 C = new (Context) OMPRelaxedClause();
11596 break;
11597 case llvm::omp::OMPC_weak:
11598 C = new (Context) OMPWeakClause();
11599 break;
11600 case llvm::omp::OMPC_threads:
11601 C = new (Context) OMPThreadsClause();
11602 break;
11603 case llvm::omp::OMPC_simd:
11604 C = new (Context) OMPSIMDClause();
11605 break;
11606 case llvm::omp::OMPC_nogroup:
11607 C = new (Context) OMPNogroupClause();
11608 break;
11609 case llvm::omp::OMPC_unified_address:
11610 C = new (Context) OMPUnifiedAddressClause();
11611 break;
11612 case llvm::omp::OMPC_unified_shared_memory:
11613 C = new (Context) OMPUnifiedSharedMemoryClause();
11614 break;
11615 case llvm::omp::OMPC_reverse_offload:
11616 C = new (Context) OMPReverseOffloadClause();
11617 break;
11618 case llvm::omp::OMPC_dynamic_allocators:
11619 C = new (Context) OMPDynamicAllocatorsClause();
11620 break;
11621 case llvm::omp::OMPC_atomic_default_mem_order:
11622 C = new (Context) OMPAtomicDefaultMemOrderClause();
11623 break;
11624 case llvm::omp::OMPC_self_maps:
11625 C = new (Context) OMPSelfMapsClause();
11626 break;
11627 case llvm::omp::OMPC_at:
11628 C = new (Context) OMPAtClause();
11629 break;
11630 case llvm::omp::OMPC_severity:
11631 C = new (Context) OMPSeverityClause();
11632 break;
11633 case llvm::omp::OMPC_message:
11634 C = new (Context) OMPMessageClause();
11635 break;
11636 case llvm::omp::OMPC_private:
11637 C = OMPPrivateClause::CreateEmpty(Context, Record.readInt());
11638 break;
11639 case llvm::omp::OMPC_firstprivate:
11640 C = OMPFirstprivateClause::CreateEmpty(Context, Record.readInt());
11641 break;
11642 case llvm::omp::OMPC_lastprivate:
11643 C = OMPLastprivateClause::CreateEmpty(Context, Record.readInt());
11644 break;
11645 case llvm::omp::OMPC_shared:
11646 C = OMPSharedClause::CreateEmpty(Context, Record.readInt());
11647 break;
11648 case llvm::omp::OMPC_reduction: {
11649 unsigned N = Record.readInt();
11650 auto Modifier = Record.readEnum<OpenMPReductionClauseModifier>();
11651 C = OMPReductionClause::CreateEmpty(Context, N, Modifier);
11652 break;
11653 }
11654 case llvm::omp::OMPC_task_reduction:
11655 C = OMPTaskReductionClause::CreateEmpty(Context, Record.readInt());
11656 break;
11657 case llvm::omp::OMPC_in_reduction:
11658 C = OMPInReductionClause::CreateEmpty(Context, Record.readInt());
11659 break;
11660 case llvm::omp::OMPC_linear:
11661 C = OMPLinearClause::CreateEmpty(Context, Record.readInt());
11662 break;
11663 case llvm::omp::OMPC_aligned:
11664 C = OMPAlignedClause::CreateEmpty(Context, Record.readInt());
11665 break;
11666 case llvm::omp::OMPC_copyin:
11667 C = OMPCopyinClause::CreateEmpty(Context, Record.readInt());
11668 break;
11669 case llvm::omp::OMPC_copyprivate:
11670 C = OMPCopyprivateClause::CreateEmpty(Context, Record.readInt());
11671 break;
11672 case llvm::omp::OMPC_flush:
11673 C = OMPFlushClause::CreateEmpty(Context, Record.readInt());
11674 break;
11675 case llvm::omp::OMPC_depobj:
11677 break;
11678 case llvm::omp::OMPC_depend: {
11679 unsigned NumVars = Record.readInt();
11680 unsigned NumLoops = Record.readInt();
11681 C = OMPDependClause::CreateEmpty(Context, NumVars, NumLoops);
11682 break;
11683 }
11684 case llvm::omp::OMPC_device:
11685 C = new (Context) OMPDeviceClause();
11686 break;
11687 case llvm::omp::OMPC_map: {
11689 Sizes.NumVars = Record.readInt();
11690 Sizes.NumUniqueDeclarations = Record.readInt();
11691 Sizes.NumComponentLists = Record.readInt();
11692 Sizes.NumComponents = Record.readInt();
11693 C = OMPMapClause::CreateEmpty(Context, Sizes);
11694 break;
11695 }
11696 case llvm::omp::OMPC_num_teams:
11697 C = OMPNumTeamsClause::CreateEmpty(Context, Record.readInt());
11698 break;
11699 case llvm::omp::OMPC_thread_limit:
11700 C = OMPThreadLimitClause::CreateEmpty(Context, Record.readInt());
11701 break;
11702 case llvm::omp::OMPC_priority:
11703 C = new (Context) OMPPriorityClause();
11704 break;
11705 case llvm::omp::OMPC_grainsize:
11706 C = new (Context) OMPGrainsizeClause();
11707 break;
11708 case llvm::omp::OMPC_num_tasks:
11709 C = new (Context) OMPNumTasksClause();
11710 break;
11711 case llvm::omp::OMPC_hint:
11712 C = new (Context) OMPHintClause();
11713 break;
11714 case llvm::omp::OMPC_dist_schedule:
11715 C = new (Context) OMPDistScheduleClause();
11716 break;
11717 case llvm::omp::OMPC_defaultmap:
11718 C = new (Context) OMPDefaultmapClause();
11719 break;
11720 case llvm::omp::OMPC_to: {
11722 Sizes.NumVars = Record.readInt();
11723 Sizes.NumUniqueDeclarations = Record.readInt();
11724 Sizes.NumComponentLists = Record.readInt();
11725 Sizes.NumComponents = Record.readInt();
11726 C = OMPToClause::CreateEmpty(Context, Sizes);
11727 break;
11728 }
11729 case llvm::omp::OMPC_from: {
11731 Sizes.NumVars = Record.readInt();
11732 Sizes.NumUniqueDeclarations = Record.readInt();
11733 Sizes.NumComponentLists = Record.readInt();
11734 Sizes.NumComponents = Record.readInt();
11735 C = OMPFromClause::CreateEmpty(Context, Sizes);
11736 break;
11737 }
11738 case llvm::omp::OMPC_use_device_ptr: {
11740 Sizes.NumVars = Record.readInt();
11741 Sizes.NumUniqueDeclarations = Record.readInt();
11742 Sizes.NumComponentLists = Record.readInt();
11743 Sizes.NumComponents = Record.readInt();
11744 C = OMPUseDevicePtrClause::CreateEmpty(Context, Sizes);
11745 break;
11746 }
11747 case llvm::omp::OMPC_use_device_addr: {
11749 Sizes.NumVars = Record.readInt();
11750 Sizes.NumUniqueDeclarations = Record.readInt();
11751 Sizes.NumComponentLists = Record.readInt();
11752 Sizes.NumComponents = Record.readInt();
11753 C = OMPUseDeviceAddrClause::CreateEmpty(Context, Sizes);
11754 break;
11755 }
11756 case llvm::omp::OMPC_is_device_ptr: {
11758 Sizes.NumVars = Record.readInt();
11759 Sizes.NumUniqueDeclarations = Record.readInt();
11760 Sizes.NumComponentLists = Record.readInt();
11761 Sizes.NumComponents = Record.readInt();
11762 C = OMPIsDevicePtrClause::CreateEmpty(Context, Sizes);
11763 break;
11764 }
11765 case llvm::omp::OMPC_has_device_addr: {
11767 Sizes.NumVars = Record.readInt();
11768 Sizes.NumUniqueDeclarations = Record.readInt();
11769 Sizes.NumComponentLists = Record.readInt();
11770 Sizes.NumComponents = Record.readInt();
11771 C = OMPHasDeviceAddrClause::CreateEmpty(Context, Sizes);
11772 break;
11773 }
11774 case llvm::omp::OMPC_allocate:
11775 C = OMPAllocateClause::CreateEmpty(Context, Record.readInt());
11776 break;
11777 case llvm::omp::OMPC_nontemporal:
11778 C = OMPNontemporalClause::CreateEmpty(Context, Record.readInt());
11779 break;
11780 case llvm::omp::OMPC_inclusive:
11781 C = OMPInclusiveClause::CreateEmpty(Context, Record.readInt());
11782 break;
11783 case llvm::omp::OMPC_exclusive:
11784 C = OMPExclusiveClause::CreateEmpty(Context, Record.readInt());
11785 break;
11786 case llvm::omp::OMPC_order:
11787 C = new (Context) OMPOrderClause();
11788 break;
11789 case llvm::omp::OMPC_init:
11790 C = OMPInitClause::CreateEmpty(Context, Record.readInt());
11791 break;
11792 case llvm::omp::OMPC_use:
11793 C = new (Context) OMPUseClause();
11794 break;
11795 case llvm::omp::OMPC_destroy:
11796 C = new (Context) OMPDestroyClause();
11797 break;
11798 case llvm::omp::OMPC_novariants:
11799 C = new (Context) OMPNovariantsClause();
11800 break;
11801 case llvm::omp::OMPC_nocontext:
11802 C = new (Context) OMPNocontextClause();
11803 break;
11804 case llvm::omp::OMPC_detach:
11805 C = new (Context) OMPDetachClause();
11806 break;
11807 case llvm::omp::OMPC_uses_allocators:
11808 C = OMPUsesAllocatorsClause::CreateEmpty(Context, Record.readInt());
11809 break;
11810 case llvm::omp::OMPC_affinity:
11811 C = OMPAffinityClause::CreateEmpty(Context, Record.readInt());
11812 break;
11813 case llvm::omp::OMPC_filter:
11814 C = new (Context) OMPFilterClause();
11815 break;
11816 case llvm::omp::OMPC_bind:
11817 C = OMPBindClause::CreateEmpty(Context);
11818 break;
11819 case llvm::omp::OMPC_align:
11820 C = new (Context) OMPAlignClause();
11821 break;
11822 case llvm::omp::OMPC_ompx_dyn_cgroup_mem:
11823 C = new (Context) OMPXDynCGroupMemClause();
11824 break;
11825 case llvm::omp::OMPC_dyn_groupprivate:
11826 C = new (Context) OMPDynGroupprivateClause();
11827 break;
11828 case llvm::omp::OMPC_doacross: {
11829 unsigned NumVars = Record.readInt();
11830 unsigned NumLoops = Record.readInt();
11831 C = OMPDoacrossClause::CreateEmpty(Context, NumVars, NumLoops);
11832 break;
11833 }
11834 case llvm::omp::OMPC_ompx_attribute:
11835 C = new (Context) OMPXAttributeClause();
11836 break;
11837 case llvm::omp::OMPC_ompx_bare:
11838 C = new (Context) OMPXBareClause();
11839 break;
11840#define OMP_CLAUSE_NO_CLASS(Enum, Str) \
11841 case llvm::omp::Enum: \
11842 break;
11843#include "llvm/Frontend/OpenMP/OMPKinds.def"
11844 default:
11845 break;
11846 }
11847 assert(C && "Unknown OMPClause type");
11848
11849 Visit(C);
11850 C->setLocStart(Record.readSourceLocation());
11851 C->setLocEnd(Record.readSourceLocation());
11852
11853 return C;
11854}
11855
11857 C->setPreInitStmt(Record.readSubStmt(),
11858 static_cast<OpenMPDirectiveKind>(Record.readInt()));
11859}
11860
11863 C->setPostUpdateExpr(Record.readSubExpr());
11864}
11865
11866void OMPClauseReader::VisitOMPIfClause(OMPIfClause *C) {
11868 C->setNameModifier(static_cast<OpenMPDirectiveKind>(Record.readInt()));
11869 C->setNameModifierLoc(Record.readSourceLocation());
11870 C->setColonLoc(Record.readSourceLocation());
11871 C->setCondition(Record.readSubExpr());
11872 C->setLParenLoc(Record.readSourceLocation());
11873}
11874
11875void OMPClauseReader::VisitOMPFinalClause(OMPFinalClause *C) {
11877 C->setCondition(Record.readSubExpr());
11878 C->setLParenLoc(Record.readSourceLocation());
11879}
11880
11881void OMPClauseReader::VisitOMPNumThreadsClause(OMPNumThreadsClause *C) {
11883 C->setModifier(Record.readEnum<OpenMPNumThreadsClauseModifier>());
11884 C->setNumThreads(Record.readSubExpr());
11885 C->setModifierLoc(Record.readSourceLocation());
11886 C->setLParenLoc(Record.readSourceLocation());
11887}
11888
11889void OMPClauseReader::VisitOMPSafelenClause(OMPSafelenClause *C) {
11890 C->setSafelen(Record.readSubExpr());
11891 C->setLParenLoc(Record.readSourceLocation());
11892}
11893
11894void OMPClauseReader::VisitOMPSimdlenClause(OMPSimdlenClause *C) {
11895 C->setSimdlen(Record.readSubExpr());
11896 C->setLParenLoc(Record.readSourceLocation());
11897}
11898
11899void OMPClauseReader::VisitOMPSizesClause(OMPSizesClause *C) {
11900 for (Expr *&E : C->getSizesRefs())
11901 E = Record.readSubExpr();
11902 C->setLParenLoc(Record.readSourceLocation());
11903}
11904
11905void OMPClauseReader::VisitOMPCountsClause(OMPCountsClause *C) {
11906 bool HasFill = Record.readBool();
11907 if (HasFill)
11908 C->setOmpFillIndex(Record.readInt());
11909 C->setOmpFillLoc(Record.readSourceLocation());
11910 for (Expr *&E : C->getCountsRefs())
11911 E = Record.readSubExpr();
11912 C->setLParenLoc(Record.readSourceLocation());
11913}
11914
11915void OMPClauseReader::VisitOMPPermutationClause(OMPPermutationClause *C) {
11916 for (Expr *&E : C->getArgsRefs())
11917 E = Record.readSubExpr();
11918 C->setLParenLoc(Record.readSourceLocation());
11919}
11920
11921void OMPClauseReader::VisitOMPFullClause(OMPFullClause *C) {}
11922
11923void OMPClauseReader::VisitOMPPartialClause(OMPPartialClause *C) {
11924 C->setFactor(Record.readSubExpr());
11925 C->setLParenLoc(Record.readSourceLocation());
11926}
11927
11928void OMPClauseReader::VisitOMPLoopRangeClause(OMPLoopRangeClause *C) {
11929 C->setFirst(Record.readSubExpr());
11930 C->setCount(Record.readSubExpr());
11931 C->setLParenLoc(Record.readSourceLocation());
11932 C->setFirstLoc(Record.readSourceLocation());
11933 C->setCountLoc(Record.readSourceLocation());
11934}
11935
11936void OMPClauseReader::VisitOMPAllocatorClause(OMPAllocatorClause *C) {
11937 C->setAllocator(Record.readExpr());
11938 C->setLParenLoc(Record.readSourceLocation());
11939}
11940
11941void OMPClauseReader::VisitOMPCollapseClause(OMPCollapseClause *C) {
11942 C->setNumForLoops(Record.readSubExpr());
11943 C->setLParenLoc(Record.readSourceLocation());
11944}
11945
11946void OMPClauseReader::VisitOMPDefaultClause(OMPDefaultClause *C) {
11947 C->setDefaultKind(static_cast<llvm::omp::DefaultKind>(Record.readInt()));
11948 C->setLParenLoc(Record.readSourceLocation());
11949 C->setDefaultKindKwLoc(Record.readSourceLocation());
11950 C->setDefaultVariableCategory(
11951 Record.readEnum<OpenMPDefaultClauseVariableCategory>());
11952 C->setDefaultVariableCategoryLocation(Record.readSourceLocation());
11953}
11954
11955// Read the parameter of threadset clause. This will have been saved when
11956// OMPClauseWriter is called.
11957void OMPClauseReader::VisitOMPThreadsetClause(OMPThreadsetClause *C) {
11958 C->setLParenLoc(Record.readSourceLocation());
11959 SourceLocation ThreadsetKindLoc = Record.readSourceLocation();
11960 C->setThreadsetKindLoc(ThreadsetKindLoc);
11961 OpenMPThreadsetKind TKind =
11962 static_cast<OpenMPThreadsetKind>(Record.readInt());
11963 C->setThreadsetKind(TKind);
11964}
11965
11966void OMPClauseReader::VisitOMPTransparentClause(OMPTransparentClause *C) {
11967 C->setLParenLoc(Record.readSourceLocation());
11968 C->setImpexTypeKind(Record.readSubExpr());
11969}
11970
11971void OMPClauseReader::VisitOMPProcBindClause(OMPProcBindClause *C) {
11972 C->setProcBindKind(static_cast<llvm::omp::ProcBindKind>(Record.readInt()));
11973 C->setLParenLoc(Record.readSourceLocation());
11974 C->setProcBindKindKwLoc(Record.readSourceLocation());
11975}
11976
11977void OMPClauseReader::VisitOMPScheduleClause(OMPScheduleClause *C) {
11979 C->setScheduleKind(
11980 static_cast<OpenMPScheduleClauseKind>(Record.readInt()));
11981 C->setFirstScheduleModifier(
11982 static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
11983 C->setSecondScheduleModifier(
11984 static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
11985 C->setChunkSize(Record.readSubExpr());
11986 C->setLParenLoc(Record.readSourceLocation());
11987 C->setFirstScheduleModifierLoc(Record.readSourceLocation());
11988 C->setSecondScheduleModifierLoc(Record.readSourceLocation());
11989 C->setScheduleKindLoc(Record.readSourceLocation());
11990 C->setCommaLoc(Record.readSourceLocation());
11991}
11992
11993void OMPClauseReader::VisitOMPOrderedClause(OMPOrderedClause *C) {
11994 C->setNumForLoops(Record.readSubExpr());
11995 for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
11996 C->setLoopNumIterations(I, Record.readSubExpr());
11997 for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
11998 C->setLoopCounter(I, Record.readSubExpr());
11999 C->setLParenLoc(Record.readSourceLocation());
12000}
12001
12002void OMPClauseReader::VisitOMPDetachClause(OMPDetachClause *C) {
12003 C->setEventHandler(Record.readSubExpr());
12004 C->setLParenLoc(Record.readSourceLocation());
12005}
12006
12007void OMPClauseReader::VisitOMPNowaitClause(OMPNowaitClause *C) {
12008 C->setCondition(Record.readSubExpr());
12009 C->setLParenLoc(Record.readSourceLocation());
12010}
12011
12012void OMPClauseReader::VisitOMPUntiedClause(OMPUntiedClause *) {}
12013
12014void OMPClauseReader::VisitOMPMergeableClause(OMPMergeableClause *) {}
12015
12016void OMPClauseReader::VisitOMPReadClause(OMPReadClause *) {}
12017
12018void OMPClauseReader::VisitOMPWriteClause(OMPWriteClause *) {}
12019
12020void OMPClauseReader::VisitOMPUpdateClause(OMPUpdateClause *C) {
12021 if (C->isExtended()) {
12022 C->setLParenLoc(Record.readSourceLocation());
12023 C->setArgumentLoc(Record.readSourceLocation());
12024 C->setDependencyKind(Record.readEnum<OpenMPDependClauseKind>());
12025 }
12026}
12027
12028void OMPClauseReader::VisitOMPCaptureClause(OMPCaptureClause *) {}
12029
12030void OMPClauseReader::VisitOMPCompareClause(OMPCompareClause *) {}
12031
12032// Read the parameter of fail clause. This will have been saved when
12033// OMPClauseWriter is called.
12034void OMPClauseReader::VisitOMPFailClause(OMPFailClause *C) {
12035 C->setLParenLoc(Record.readSourceLocation());
12036 SourceLocation FailParameterLoc = Record.readSourceLocation();
12037 C->setFailParameterLoc(FailParameterLoc);
12038 OpenMPClauseKind CKind = Record.readEnum<OpenMPClauseKind>();
12039 C->setFailParameter(CKind);
12040}
12041
12042void OMPClauseReader::VisitOMPAbsentClause(OMPAbsentClause *C) {
12043 unsigned Count = C->getDirectiveKinds().size();
12044 C->setLParenLoc(Record.readSourceLocation());
12045 llvm::SmallVector<OpenMPDirectiveKind, 4> DKVec;
12046 DKVec.reserve(Count);
12047 for (unsigned I = 0; I < Count; I++) {
12048 DKVec.push_back(Record.readEnum<OpenMPDirectiveKind>());
12049 }
12050 C->setDirectiveKinds(DKVec);
12051}
12052
12053void OMPClauseReader::VisitOMPHoldsClause(OMPHoldsClause *C) {
12054 C->setExpr(Record.readExpr());
12055 C->setLParenLoc(Record.readSourceLocation());
12056}
12057
12058void OMPClauseReader::VisitOMPContainsClause(OMPContainsClause *C) {
12059 unsigned Count = C->getDirectiveKinds().size();
12060 C->setLParenLoc(Record.readSourceLocation());
12061 llvm::SmallVector<OpenMPDirectiveKind, 4> DKVec;
12062 DKVec.reserve(Count);
12063 for (unsigned I = 0; I < Count; I++) {
12064 DKVec.push_back(Record.readEnum<OpenMPDirectiveKind>());
12065 }
12066 C->setDirectiveKinds(DKVec);
12067}
12068
12069void OMPClauseReader::VisitOMPNoOpenMPClause(OMPNoOpenMPClause *) {}
12070
12071void OMPClauseReader::VisitOMPNoOpenMPRoutinesClause(
12072 OMPNoOpenMPRoutinesClause *) {}
12073
12074void OMPClauseReader::VisitOMPNoOpenMPConstructsClause(
12075 OMPNoOpenMPConstructsClause *) {}
12076
12077void OMPClauseReader::VisitOMPNoParallelismClause(OMPNoParallelismClause *) {}
12078
12079void OMPClauseReader::VisitOMPSeqCstClause(OMPSeqCstClause *) {}
12080
12081void OMPClauseReader::VisitOMPAcqRelClause(OMPAcqRelClause *) {}
12082
12083void OMPClauseReader::VisitOMPAcquireClause(OMPAcquireClause *) {}
12084
12085void OMPClauseReader::VisitOMPReleaseClause(OMPReleaseClause *) {}
12086
12087void OMPClauseReader::VisitOMPRelaxedClause(OMPRelaxedClause *) {}
12088
12089void OMPClauseReader::VisitOMPWeakClause(OMPWeakClause *) {}
12090
12091void OMPClauseReader::VisitOMPThreadsClause(OMPThreadsClause *) {}
12092
12093void OMPClauseReader::VisitOMPSIMDClause(OMPSIMDClause *) {}
12094
12095void OMPClauseReader::VisitOMPNogroupClause(OMPNogroupClause *) {}
12096
12097void OMPClauseReader::VisitOMPInitClause(OMPInitClause *C) {
12098 unsigned NumVars = C->varlist_size();
12099 SmallVector<Expr *, 16> Vars;
12100 Vars.reserve(NumVars);
12101 for (unsigned I = 0; I != NumVars; ++I)
12102 Vars.push_back(Record.readSubExpr());
12103 C->setVarRefs(Vars);
12104 C->setIsTarget(Record.readBool());
12105 C->setIsTargetSync(Record.readBool());
12106 C->setLParenLoc(Record.readSourceLocation());
12107 C->setVarLoc(Record.readSourceLocation());
12108}
12109
12110void OMPClauseReader::VisitOMPUseClause(OMPUseClause *C) {
12111 C->setInteropVar(Record.readSubExpr());
12112 C->setLParenLoc(Record.readSourceLocation());
12113 C->setVarLoc(Record.readSourceLocation());
12114}
12115
12116void OMPClauseReader::VisitOMPDestroyClause(OMPDestroyClause *C) {
12117 C->setInteropVar(Record.readSubExpr());
12118 C->setLParenLoc(Record.readSourceLocation());
12119 C->setVarLoc(Record.readSourceLocation());
12120}
12121
12122void OMPClauseReader::VisitOMPNovariantsClause(OMPNovariantsClause *C) {
12124 C->setCondition(Record.readSubExpr());
12125 C->setLParenLoc(Record.readSourceLocation());
12126}
12127
12128void OMPClauseReader::VisitOMPNocontextClause(OMPNocontextClause *C) {
12130 C->setCondition(Record.readSubExpr());
12131 C->setLParenLoc(Record.readSourceLocation());
12132}
12133
12134void OMPClauseReader::VisitOMPUnifiedAddressClause(OMPUnifiedAddressClause *) {}
12135
12136void OMPClauseReader::VisitOMPUnifiedSharedMemoryClause(
12137 OMPUnifiedSharedMemoryClause *) {}
12138
12139void OMPClauseReader::VisitOMPReverseOffloadClause(OMPReverseOffloadClause *) {}
12140
12141void
12142OMPClauseReader::VisitOMPDynamicAllocatorsClause(OMPDynamicAllocatorsClause *) {
12143}
12144
12145void OMPClauseReader::VisitOMPAtomicDefaultMemOrderClause(
12146 OMPAtomicDefaultMemOrderClause *C) {
12147 C->setAtomicDefaultMemOrderKind(
12148 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Record.readInt()));
12149 C->setLParenLoc(Record.readSourceLocation());
12150 C->setAtomicDefaultMemOrderKindKwLoc(Record.readSourceLocation());
12151}
12152
12153void OMPClauseReader::VisitOMPSelfMapsClause(OMPSelfMapsClause *) {}
12154
12155void OMPClauseReader::VisitOMPAtClause(OMPAtClause *C) {
12156 C->setAtKind(static_cast<OpenMPAtClauseKind>(Record.readInt()));
12157 C->setLParenLoc(Record.readSourceLocation());
12158 C->setAtKindKwLoc(Record.readSourceLocation());
12159}
12160
12161void OMPClauseReader::VisitOMPSeverityClause(OMPSeverityClause *C) {
12162 C->setSeverityKind(static_cast<OpenMPSeverityClauseKind>(Record.readInt()));
12163 C->setLParenLoc(Record.readSourceLocation());
12164 C->setSeverityKindKwLoc(Record.readSourceLocation());
12165}
12166
12167void OMPClauseReader::VisitOMPMessageClause(OMPMessageClause *C) {
12169 C->setMessageString(Record.readSubExpr());
12170 C->setLParenLoc(Record.readSourceLocation());
12171}
12172
12173void OMPClauseReader::VisitOMPPrivateClause(OMPPrivateClause *C) {
12174 C->setLParenLoc(Record.readSourceLocation());
12175 unsigned NumVars = C->varlist_size();
12176 SmallVector<Expr *, 16> Vars;
12177 Vars.reserve(NumVars);
12178 for (unsigned i = 0; i != NumVars; ++i)
12179 Vars.push_back(Record.readSubExpr());
12180 C->setVarRefs(Vars);
12181 Vars.clear();
12182 for (unsigned i = 0; i != NumVars; ++i)
12183 Vars.push_back(Record.readSubExpr());
12184 C->setPrivateCopies(Vars);
12185}
12186
12187void OMPClauseReader::VisitOMPFirstprivateClause(OMPFirstprivateClause *C) {
12189 C->setLParenLoc(Record.readSourceLocation());
12190 unsigned NumVars = C->varlist_size();
12191 SmallVector<Expr *, 16> Vars;
12192 Vars.reserve(NumVars);
12193 for (unsigned i = 0; i != NumVars; ++i)
12194 Vars.push_back(Record.readSubExpr());
12195 C->setVarRefs(Vars);
12196 Vars.clear();
12197 for (unsigned i = 0; i != NumVars; ++i)
12198 Vars.push_back(Record.readSubExpr());
12199 C->setPrivateCopies(Vars);
12200 Vars.clear();
12201 for (unsigned i = 0; i != NumVars; ++i)
12202 Vars.push_back(Record.readSubExpr());
12203 C->setInits(Vars);
12204}
12205
12206void OMPClauseReader::VisitOMPLastprivateClause(OMPLastprivateClause *C) {
12208 C->setLParenLoc(Record.readSourceLocation());
12209 C->setKind(Record.readEnum<OpenMPLastprivateModifier>());
12210 C->setKindLoc(Record.readSourceLocation());
12211 C->setColonLoc(Record.readSourceLocation());
12212 unsigned NumVars = C->varlist_size();
12213 SmallVector<Expr *, 16> Vars;
12214 Vars.reserve(NumVars);
12215 for (unsigned i = 0; i != NumVars; ++i)
12216 Vars.push_back(Record.readSubExpr());
12217 C->setVarRefs(Vars);
12218 Vars.clear();
12219 for (unsigned i = 0; i != NumVars; ++i)
12220 Vars.push_back(Record.readSubExpr());
12221 C->setPrivateCopies(Vars);
12222 Vars.clear();
12223 for (unsigned i = 0; i != NumVars; ++i)
12224 Vars.push_back(Record.readSubExpr());
12225 C->setSourceExprs(Vars);
12226 Vars.clear();
12227 for (unsigned i = 0; i != NumVars; ++i)
12228 Vars.push_back(Record.readSubExpr());
12229 C->setDestinationExprs(Vars);
12230 Vars.clear();
12231 for (unsigned i = 0; i != NumVars; ++i)
12232 Vars.push_back(Record.readSubExpr());
12233 C->setAssignmentOps(Vars);
12234}
12235
12236void OMPClauseReader::VisitOMPSharedClause(OMPSharedClause *C) {
12237 C->setLParenLoc(Record.readSourceLocation());
12238 unsigned NumVars = C->varlist_size();
12239 SmallVector<Expr *, 16> Vars;
12240 Vars.reserve(NumVars);
12241 for (unsigned i = 0; i != NumVars; ++i)
12242 Vars.push_back(Record.readSubExpr());
12243 C->setVarRefs(Vars);
12244}
12245
12246void OMPClauseReader::VisitOMPReductionClause(OMPReductionClause *C) {
12248 C->setLParenLoc(Record.readSourceLocation());
12249 C->setModifierLoc(Record.readSourceLocation());
12250 C->setColonLoc(Record.readSourceLocation());
12251 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
12252 DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
12253 C->setQualifierLoc(NNSL);
12254 C->setNameInfo(DNI);
12255
12256 unsigned NumVars = C->varlist_size();
12257 SmallVector<Expr *, 16> Vars;
12258 Vars.reserve(NumVars);
12259 for (unsigned i = 0; i != NumVars; ++i)
12260 Vars.push_back(Record.readSubExpr());
12261 C->setVarRefs(Vars);
12262 Vars.clear();
12263 for (unsigned i = 0; i != NumVars; ++i)
12264 Vars.push_back(Record.readSubExpr());
12265 C->setPrivates(Vars);
12266 Vars.clear();
12267 for (unsigned i = 0; i != NumVars; ++i)
12268 Vars.push_back(Record.readSubExpr());
12269 C->setLHSExprs(Vars);
12270 Vars.clear();
12271 for (unsigned i = 0; i != NumVars; ++i)
12272 Vars.push_back(Record.readSubExpr());
12273 C->setRHSExprs(Vars);
12274 Vars.clear();
12275 for (unsigned i = 0; i != NumVars; ++i)
12276 Vars.push_back(Record.readSubExpr());
12277 C->setReductionOps(Vars);
12278 if (C->getModifier() == OMPC_REDUCTION_inscan) {
12279 Vars.clear();
12280 for (unsigned i = 0; i != NumVars; ++i)
12281 Vars.push_back(Record.readSubExpr());
12282 C->setInscanCopyOps(Vars);
12283 Vars.clear();
12284 for (unsigned i = 0; i != NumVars; ++i)
12285 Vars.push_back(Record.readSubExpr());
12286 C->setInscanCopyArrayTemps(Vars);
12287 Vars.clear();
12288 for (unsigned i = 0; i != NumVars; ++i)
12289 Vars.push_back(Record.readSubExpr());
12290 C->setInscanCopyArrayElems(Vars);
12291 }
12292 unsigned NumFlags = Record.readInt();
12293 SmallVector<bool, 16> Flags;
12294 Flags.reserve(NumFlags);
12295 for ([[maybe_unused]] unsigned I : llvm::seq<unsigned>(NumFlags))
12296 Flags.push_back(Record.readInt());
12297 C->setPrivateVariableReductionFlags(Flags);
12298}
12299
12300void OMPClauseReader::VisitOMPTaskReductionClause(OMPTaskReductionClause *C) {
12302 C->setLParenLoc(Record.readSourceLocation());
12303 C->setColonLoc(Record.readSourceLocation());
12304 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
12305 DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
12306 C->setQualifierLoc(NNSL);
12307 C->setNameInfo(DNI);
12308
12309 unsigned NumVars = C->varlist_size();
12310 SmallVector<Expr *, 16> Vars;
12311 Vars.reserve(NumVars);
12312 for (unsigned I = 0; I != NumVars; ++I)
12313 Vars.push_back(Record.readSubExpr());
12314 C->setVarRefs(Vars);
12315 Vars.clear();
12316 for (unsigned I = 0; I != NumVars; ++I)
12317 Vars.push_back(Record.readSubExpr());
12318 C->setPrivates(Vars);
12319 Vars.clear();
12320 for (unsigned I = 0; I != NumVars; ++I)
12321 Vars.push_back(Record.readSubExpr());
12322 C->setLHSExprs(Vars);
12323 Vars.clear();
12324 for (unsigned I = 0; I != NumVars; ++I)
12325 Vars.push_back(Record.readSubExpr());
12326 C->setRHSExprs(Vars);
12327 Vars.clear();
12328 for (unsigned I = 0; I != NumVars; ++I)
12329 Vars.push_back(Record.readSubExpr());
12330 C->setReductionOps(Vars);
12331}
12332
12333void OMPClauseReader::VisitOMPInReductionClause(OMPInReductionClause *C) {
12335 C->setLParenLoc(Record.readSourceLocation());
12336 C->setColonLoc(Record.readSourceLocation());
12337 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
12338 DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
12339 C->setQualifierLoc(NNSL);
12340 C->setNameInfo(DNI);
12341
12342 unsigned NumVars = C->varlist_size();
12343 SmallVector<Expr *, 16> Vars;
12344 Vars.reserve(NumVars);
12345 for (unsigned I = 0; I != NumVars; ++I)
12346 Vars.push_back(Record.readSubExpr());
12347 C->setVarRefs(Vars);
12348 Vars.clear();
12349 for (unsigned I = 0; I != NumVars; ++I)
12350 Vars.push_back(Record.readSubExpr());
12351 C->setPrivates(Vars);
12352 Vars.clear();
12353 for (unsigned I = 0; I != NumVars; ++I)
12354 Vars.push_back(Record.readSubExpr());
12355 C->setLHSExprs(Vars);
12356 Vars.clear();
12357 for (unsigned I = 0; I != NumVars; ++I)
12358 Vars.push_back(Record.readSubExpr());
12359 C->setRHSExprs(Vars);
12360 Vars.clear();
12361 for (unsigned I = 0; I != NumVars; ++I)
12362 Vars.push_back(Record.readSubExpr());
12363 C->setReductionOps(Vars);
12364 Vars.clear();
12365 for (unsigned I = 0; I != NumVars; ++I)
12366 Vars.push_back(Record.readSubExpr());
12367 C->setTaskgroupDescriptors(Vars);
12368}
12369
12370void OMPClauseReader::VisitOMPLinearClause(OMPLinearClause *C) {
12372 C->setLParenLoc(Record.readSourceLocation());
12373 C->setColonLoc(Record.readSourceLocation());
12374 C->setModifier(static_cast<OpenMPLinearClauseKind>(Record.readInt()));
12375 C->setModifierLoc(Record.readSourceLocation());
12376 unsigned NumVars = C->varlist_size();
12377 SmallVector<Expr *, 16> Vars;
12378 Vars.reserve(NumVars);
12379 for (unsigned i = 0; i != NumVars; ++i)
12380 Vars.push_back(Record.readSubExpr());
12381 C->setVarRefs(Vars);
12382 Vars.clear();
12383 for (unsigned i = 0; i != NumVars; ++i)
12384 Vars.push_back(Record.readSubExpr());
12385 C->setPrivates(Vars);
12386 Vars.clear();
12387 for (unsigned i = 0; i != NumVars; ++i)
12388 Vars.push_back(Record.readSubExpr());
12389 C->setInits(Vars);
12390 Vars.clear();
12391 for (unsigned i = 0; i != NumVars; ++i)
12392 Vars.push_back(Record.readSubExpr());
12393 C->setUpdates(Vars);
12394 Vars.clear();
12395 for (unsigned i = 0; i != NumVars; ++i)
12396 Vars.push_back(Record.readSubExpr());
12397 C->setFinals(Vars);
12398 C->setStep(Record.readSubExpr());
12399 C->setCalcStep(Record.readSubExpr());
12400 Vars.clear();
12401 for (unsigned I = 0; I != NumVars + 1; ++I)
12402 Vars.push_back(Record.readSubExpr());
12403 C->setUsedExprs(Vars);
12404}
12405
12406void OMPClauseReader::VisitOMPAlignedClause(OMPAlignedClause *C) {
12407 C->setLParenLoc(Record.readSourceLocation());
12408 C->setColonLoc(Record.readSourceLocation());
12409 unsigned NumVars = C->varlist_size();
12410 SmallVector<Expr *, 16> Vars;
12411 Vars.reserve(NumVars);
12412 for (unsigned i = 0; i != NumVars; ++i)
12413 Vars.push_back(Record.readSubExpr());
12414 C->setVarRefs(Vars);
12415 C->setAlignment(Record.readSubExpr());
12416}
12417
12418void OMPClauseReader::VisitOMPCopyinClause(OMPCopyinClause *C) {
12419 C->setLParenLoc(Record.readSourceLocation());
12420 unsigned NumVars = C->varlist_size();
12421 SmallVector<Expr *, 16> Exprs;
12422 Exprs.reserve(NumVars);
12423 for (unsigned i = 0; i != NumVars; ++i)
12424 Exprs.push_back(Record.readSubExpr());
12425 C->setVarRefs(Exprs);
12426 Exprs.clear();
12427 for (unsigned i = 0; i != NumVars; ++i)
12428 Exprs.push_back(Record.readSubExpr());
12429 C->setSourceExprs(Exprs);
12430 Exprs.clear();
12431 for (unsigned i = 0; i != NumVars; ++i)
12432 Exprs.push_back(Record.readSubExpr());
12433 C->setDestinationExprs(Exprs);
12434 Exprs.clear();
12435 for (unsigned i = 0; i != NumVars; ++i)
12436 Exprs.push_back(Record.readSubExpr());
12437 C->setAssignmentOps(Exprs);
12438}
12439
12440void OMPClauseReader::VisitOMPCopyprivateClause(OMPCopyprivateClause *C) {
12441 C->setLParenLoc(Record.readSourceLocation());
12442 unsigned NumVars = C->varlist_size();
12443 SmallVector<Expr *, 16> Exprs;
12444 Exprs.reserve(NumVars);
12445 for (unsigned i = 0; i != NumVars; ++i)
12446 Exprs.push_back(Record.readSubExpr());
12447 C->setVarRefs(Exprs);
12448 Exprs.clear();
12449 for (unsigned i = 0; i != NumVars; ++i)
12450 Exprs.push_back(Record.readSubExpr());
12451 C->setSourceExprs(Exprs);
12452 Exprs.clear();
12453 for (unsigned i = 0; i != NumVars; ++i)
12454 Exprs.push_back(Record.readSubExpr());
12455 C->setDestinationExprs(Exprs);
12456 Exprs.clear();
12457 for (unsigned i = 0; i != NumVars; ++i)
12458 Exprs.push_back(Record.readSubExpr());
12459 C->setAssignmentOps(Exprs);
12460}
12461
12462void OMPClauseReader::VisitOMPFlushClause(OMPFlushClause *C) {
12463 C->setLParenLoc(Record.readSourceLocation());
12464 unsigned NumVars = C->varlist_size();
12465 SmallVector<Expr *, 16> Vars;
12466 Vars.reserve(NumVars);
12467 for (unsigned i = 0; i != NumVars; ++i)
12468 Vars.push_back(Record.readSubExpr());
12469 C->setVarRefs(Vars);
12470}
12471
12472void OMPClauseReader::VisitOMPDepobjClause(OMPDepobjClause *C) {
12473 C->setDepobj(Record.readSubExpr());
12474 C->setLParenLoc(Record.readSourceLocation());
12475}
12476
12477void OMPClauseReader::VisitOMPDependClause(OMPDependClause *C) {
12478 C->setLParenLoc(Record.readSourceLocation());
12479 C->setModifier(Record.readSubExpr());
12480 C->setDependencyKind(
12481 static_cast<OpenMPDependClauseKind>(Record.readInt()));
12482 C->setDependencyLoc(Record.readSourceLocation());
12483 C->setColonLoc(Record.readSourceLocation());
12484 C->setOmpAllMemoryLoc(Record.readSourceLocation());
12485 unsigned NumVars = C->varlist_size();
12486 SmallVector<Expr *, 16> Vars;
12487 Vars.reserve(NumVars);
12488 for (unsigned I = 0; I != NumVars; ++I)
12489 Vars.push_back(Record.readSubExpr());
12490 C->setVarRefs(Vars);
12491 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
12492 C->setLoopData(I, Record.readSubExpr());
12493}
12494
12495void OMPClauseReader::VisitOMPDeviceClause(OMPDeviceClause *C) {
12497 C->setModifier(Record.readEnum<OpenMPDeviceClauseModifier>());
12498 C->setDevice(Record.readSubExpr());
12499 C->setModifierLoc(Record.readSourceLocation());
12500 C->setLParenLoc(Record.readSourceLocation());
12501}
12502
12503void OMPClauseReader::VisitOMPMapClause(OMPMapClause *C) {
12504 C->setLParenLoc(Record.readSourceLocation());
12505 bool HasIteratorModifier = false;
12506 for (unsigned I = 0; I < NumberOfOMPMapClauseModifiers; ++I) {
12507 C->setMapTypeModifier(
12508 I, static_cast<OpenMPMapModifierKind>(Record.readInt()));
12509 C->setMapTypeModifierLoc(I, Record.readSourceLocation());
12510 if (C->getMapTypeModifier(I) == OMPC_MAP_MODIFIER_iterator)
12511 HasIteratorModifier = true;
12512 }
12513 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
12514 C->setMapperIdInfo(Record.readDeclarationNameInfo());
12515 C->setMapType(
12516 static_cast<OpenMPMapClauseKind>(Record.readInt()));
12517 C->setMapLoc(Record.readSourceLocation());
12518 C->setColonLoc(Record.readSourceLocation());
12519 auto NumVars = C->varlist_size();
12520 auto UniqueDecls = C->getUniqueDeclarationsNum();
12521 auto TotalLists = C->getTotalComponentListNum();
12522 auto TotalComponents = C->getTotalComponentsNum();
12523
12524 SmallVector<Expr *, 16> Vars;
12525 Vars.reserve(NumVars);
12526 for (unsigned i = 0; i != NumVars; ++i)
12527 Vars.push_back(Record.readExpr());
12528 C->setVarRefs(Vars);
12529
12530 SmallVector<Expr *, 16> UDMappers;
12531 UDMappers.reserve(NumVars);
12532 for (unsigned I = 0; I < NumVars; ++I)
12533 UDMappers.push_back(Record.readExpr());
12534 C->setUDMapperRefs(UDMappers);
12535
12536 if (HasIteratorModifier)
12537 C->setIteratorModifier(Record.readExpr());
12538
12539 SmallVector<ValueDecl *, 16> Decls;
12540 Decls.reserve(UniqueDecls);
12541 for (unsigned i = 0; i < UniqueDecls; ++i)
12542 Decls.push_back(Record.readDeclAs<ValueDecl>());
12543 C->setUniqueDecls(Decls);
12544
12545 SmallVector<unsigned, 16> ListsPerDecl;
12546 ListsPerDecl.reserve(UniqueDecls);
12547 for (unsigned i = 0; i < UniqueDecls; ++i)
12548 ListsPerDecl.push_back(Record.readInt());
12549 C->setDeclNumLists(ListsPerDecl);
12550
12551 SmallVector<unsigned, 32> ListSizes;
12552 ListSizes.reserve(TotalLists);
12553 for (unsigned i = 0; i < TotalLists; ++i)
12554 ListSizes.push_back(Record.readInt());
12555 C->setComponentListSizes(ListSizes);
12556
12557 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12558 Components.reserve(TotalComponents);
12559 for (unsigned i = 0; i < TotalComponents; ++i) {
12560 Expr *AssociatedExprPr = Record.readExpr();
12561 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12562 Components.emplace_back(AssociatedExprPr, AssociatedDecl,
12563 /*IsNonContiguous=*/false);
12564 }
12565 C->setComponents(Components, ListSizes);
12566}
12567
12568void OMPClauseReader::VisitOMPAllocateClause(OMPAllocateClause *C) {
12569 C->setFirstAllocateModifier(Record.readEnum<OpenMPAllocateClauseModifier>());
12570 C->setSecondAllocateModifier(Record.readEnum<OpenMPAllocateClauseModifier>());
12571 C->setLParenLoc(Record.readSourceLocation());
12572 C->setColonLoc(Record.readSourceLocation());
12573 C->setAllocator(Record.readSubExpr());
12574 C->setAlignment(Record.readSubExpr());
12575 unsigned NumVars = C->varlist_size();
12576 SmallVector<Expr *, 16> Vars;
12577 Vars.reserve(NumVars);
12578 for (unsigned i = 0; i != NumVars; ++i)
12579 Vars.push_back(Record.readSubExpr());
12580 C->setVarRefs(Vars);
12581}
12582
12583void OMPClauseReader::VisitOMPNumTeamsClause(OMPNumTeamsClause *C) {
12585 C->setLParenLoc(Record.readSourceLocation());
12586 unsigned NumVars = C->varlist_size();
12587 SmallVector<Expr *, 16> Vars;
12588 Vars.reserve(NumVars);
12589 for (unsigned I = 0; I != NumVars; ++I)
12590 Vars.push_back(Record.readSubExpr());
12591 C->setVarRefs(Vars);
12592}
12593
12594void OMPClauseReader::VisitOMPThreadLimitClause(OMPThreadLimitClause *C) {
12596 C->setLParenLoc(Record.readSourceLocation());
12597 unsigned NumVars = C->varlist_size();
12598 SmallVector<Expr *, 16> Vars;
12599 Vars.reserve(NumVars);
12600 for (unsigned I = 0; I != NumVars; ++I)
12601 Vars.push_back(Record.readSubExpr());
12602 C->setVarRefs(Vars);
12603}
12604
12605void OMPClauseReader::VisitOMPPriorityClause(OMPPriorityClause *C) {
12607 C->setPriority(Record.readSubExpr());
12608 C->setLParenLoc(Record.readSourceLocation());
12609}
12610
12611void OMPClauseReader::VisitOMPGrainsizeClause(OMPGrainsizeClause *C) {
12613 C->setModifier(Record.readEnum<OpenMPGrainsizeClauseModifier>());
12614 C->setGrainsize(Record.readSubExpr());
12615 C->setModifierLoc(Record.readSourceLocation());
12616 C->setLParenLoc(Record.readSourceLocation());
12617}
12618
12619void OMPClauseReader::VisitOMPNumTasksClause(OMPNumTasksClause *C) {
12621 C->setModifier(Record.readEnum<OpenMPNumTasksClauseModifier>());
12622 C->setNumTasks(Record.readSubExpr());
12623 C->setModifierLoc(Record.readSourceLocation());
12624 C->setLParenLoc(Record.readSourceLocation());
12625}
12626
12627void OMPClauseReader::VisitOMPHintClause(OMPHintClause *C) {
12628 C->setHint(Record.readSubExpr());
12629 C->setLParenLoc(Record.readSourceLocation());
12630}
12631
12632void OMPClauseReader::VisitOMPDistScheduleClause(OMPDistScheduleClause *C) {
12634 C->setDistScheduleKind(
12635 static_cast<OpenMPDistScheduleClauseKind>(Record.readInt()));
12636 C->setChunkSize(Record.readSubExpr());
12637 C->setLParenLoc(Record.readSourceLocation());
12638 C->setDistScheduleKindLoc(Record.readSourceLocation());
12639 C->setCommaLoc(Record.readSourceLocation());
12640}
12641
12642void OMPClauseReader::VisitOMPDefaultmapClause(OMPDefaultmapClause *C) {
12643 C->setDefaultmapKind(
12644 static_cast<OpenMPDefaultmapClauseKind>(Record.readInt()));
12645 C->setDefaultmapModifier(
12646 static_cast<OpenMPDefaultmapClauseModifier>(Record.readInt()));
12647 C->setLParenLoc(Record.readSourceLocation());
12648 C->setDefaultmapModifierLoc(Record.readSourceLocation());
12649 C->setDefaultmapKindLoc(Record.readSourceLocation());
12650}
12651
12652void OMPClauseReader::VisitOMPToClause(OMPToClause *C) {
12653 C->setLParenLoc(Record.readSourceLocation());
12654 for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) {
12655 C->setMotionModifier(
12656 I, static_cast<OpenMPMotionModifierKind>(Record.readInt()));
12657 C->setMotionModifierLoc(I, Record.readSourceLocation());
12658 if (C->getMotionModifier(I) == OMPC_MOTION_MODIFIER_iterator)
12659 C->setIteratorModifier(Record.readExpr());
12660 }
12661 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
12662 C->setMapperIdInfo(Record.readDeclarationNameInfo());
12663 C->setColonLoc(Record.readSourceLocation());
12664 auto NumVars = C->varlist_size();
12665 auto UniqueDecls = C->getUniqueDeclarationsNum();
12666 auto TotalLists = C->getTotalComponentListNum();
12667 auto TotalComponents = C->getTotalComponentsNum();
12668
12669 SmallVector<Expr *, 16> Vars;
12670 Vars.reserve(NumVars);
12671 for (unsigned i = 0; i != NumVars; ++i)
12672 Vars.push_back(Record.readSubExpr());
12673 C->setVarRefs(Vars);
12674
12675 SmallVector<Expr *, 16> UDMappers;
12676 UDMappers.reserve(NumVars);
12677 for (unsigned I = 0; I < NumVars; ++I)
12678 UDMappers.push_back(Record.readSubExpr());
12679 C->setUDMapperRefs(UDMappers);
12680
12681 SmallVector<ValueDecl *, 16> Decls;
12682 Decls.reserve(UniqueDecls);
12683 for (unsigned i = 0; i < UniqueDecls; ++i)
12684 Decls.push_back(Record.readDeclAs<ValueDecl>());
12685 C->setUniqueDecls(Decls);
12686
12687 SmallVector<unsigned, 16> ListsPerDecl;
12688 ListsPerDecl.reserve(UniqueDecls);
12689 for (unsigned i = 0; i < UniqueDecls; ++i)
12690 ListsPerDecl.push_back(Record.readInt());
12691 C->setDeclNumLists(ListsPerDecl);
12692
12693 SmallVector<unsigned, 32> ListSizes;
12694 ListSizes.reserve(TotalLists);
12695 for (unsigned i = 0; i < TotalLists; ++i)
12696 ListSizes.push_back(Record.readInt());
12697 C->setComponentListSizes(ListSizes);
12698
12699 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12700 Components.reserve(TotalComponents);
12701 for (unsigned i = 0; i < TotalComponents; ++i) {
12702 Expr *AssociatedExprPr = Record.readSubExpr();
12703 bool IsNonContiguous = Record.readBool();
12704 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12705 Components.emplace_back(AssociatedExprPr, AssociatedDecl, IsNonContiguous);
12706 }
12707 C->setComponents(Components, ListSizes);
12708}
12709
12710void OMPClauseReader::VisitOMPFromClause(OMPFromClause *C) {
12711 C->setLParenLoc(Record.readSourceLocation());
12712 for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) {
12713 C->setMotionModifier(
12714 I, static_cast<OpenMPMotionModifierKind>(Record.readInt()));
12715 C->setMotionModifierLoc(I, Record.readSourceLocation());
12716 if (C->getMotionModifier(I) == OMPC_MOTION_MODIFIER_iterator)
12717 C->setIteratorModifier(Record.readExpr());
12718 }
12719 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
12720 C->setMapperIdInfo(Record.readDeclarationNameInfo());
12721 C->setColonLoc(Record.readSourceLocation());
12722 auto NumVars = C->varlist_size();
12723 auto UniqueDecls = C->getUniqueDeclarationsNum();
12724 auto TotalLists = C->getTotalComponentListNum();
12725 auto TotalComponents = C->getTotalComponentsNum();
12726
12727 SmallVector<Expr *, 16> Vars;
12728 Vars.reserve(NumVars);
12729 for (unsigned i = 0; i != NumVars; ++i)
12730 Vars.push_back(Record.readSubExpr());
12731 C->setVarRefs(Vars);
12732
12733 SmallVector<Expr *, 16> UDMappers;
12734 UDMappers.reserve(NumVars);
12735 for (unsigned I = 0; I < NumVars; ++I)
12736 UDMappers.push_back(Record.readSubExpr());
12737 C->setUDMapperRefs(UDMappers);
12738
12739 SmallVector<ValueDecl *, 16> Decls;
12740 Decls.reserve(UniqueDecls);
12741 for (unsigned i = 0; i < UniqueDecls; ++i)
12742 Decls.push_back(Record.readDeclAs<ValueDecl>());
12743 C->setUniqueDecls(Decls);
12744
12745 SmallVector<unsigned, 16> ListsPerDecl;
12746 ListsPerDecl.reserve(UniqueDecls);
12747 for (unsigned i = 0; i < UniqueDecls; ++i)
12748 ListsPerDecl.push_back(Record.readInt());
12749 C->setDeclNumLists(ListsPerDecl);
12750
12751 SmallVector<unsigned, 32> ListSizes;
12752 ListSizes.reserve(TotalLists);
12753 for (unsigned i = 0; i < TotalLists; ++i)
12754 ListSizes.push_back(Record.readInt());
12755 C->setComponentListSizes(ListSizes);
12756
12757 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12758 Components.reserve(TotalComponents);
12759 for (unsigned i = 0; i < TotalComponents; ++i) {
12760 Expr *AssociatedExprPr = Record.readSubExpr();
12761 bool IsNonContiguous = Record.readBool();
12762 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12763 Components.emplace_back(AssociatedExprPr, AssociatedDecl, IsNonContiguous);
12764 }
12765 C->setComponents(Components, ListSizes);
12766}
12767
12768void OMPClauseReader::VisitOMPUseDevicePtrClause(OMPUseDevicePtrClause *C) {
12769 C->setLParenLoc(Record.readSourceLocation());
12770 C->setFallbackModifier(Record.readEnum<OpenMPUseDevicePtrFallbackModifier>());
12771 C->setFallbackModifierLoc(Record.readSourceLocation());
12772 auto NumVars = C->varlist_size();
12773 auto UniqueDecls = C->getUniqueDeclarationsNum();
12774 auto TotalLists = C->getTotalComponentListNum();
12775 auto TotalComponents = C->getTotalComponentsNum();
12776
12777 SmallVector<Expr *, 16> Vars;
12778 Vars.reserve(NumVars);
12779 for (unsigned i = 0; i != NumVars; ++i)
12780 Vars.push_back(Record.readSubExpr());
12781 C->setVarRefs(Vars);
12782 Vars.clear();
12783 for (unsigned i = 0; i != NumVars; ++i)
12784 Vars.push_back(Record.readSubExpr());
12785 C->setPrivateCopies(Vars);
12786 Vars.clear();
12787 for (unsigned i = 0; i != NumVars; ++i)
12788 Vars.push_back(Record.readSubExpr());
12789 C->setInits(Vars);
12790
12791 SmallVector<ValueDecl *, 16> Decls;
12792 Decls.reserve(UniqueDecls);
12793 for (unsigned i = 0; i < UniqueDecls; ++i)
12794 Decls.push_back(Record.readDeclAs<ValueDecl>());
12795 C->setUniqueDecls(Decls);
12796
12797 SmallVector<unsigned, 16> ListsPerDecl;
12798 ListsPerDecl.reserve(UniqueDecls);
12799 for (unsigned i = 0; i < UniqueDecls; ++i)
12800 ListsPerDecl.push_back(Record.readInt());
12801 C->setDeclNumLists(ListsPerDecl);
12802
12803 SmallVector<unsigned, 32> ListSizes;
12804 ListSizes.reserve(TotalLists);
12805 for (unsigned i = 0; i < TotalLists; ++i)
12806 ListSizes.push_back(Record.readInt());
12807 C->setComponentListSizes(ListSizes);
12808
12809 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12810 Components.reserve(TotalComponents);
12811 for (unsigned i = 0; i < TotalComponents; ++i) {
12812 auto *AssociatedExprPr = Record.readSubExpr();
12813 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12814 Components.emplace_back(AssociatedExprPr, AssociatedDecl,
12815 /*IsNonContiguous=*/false);
12816 }
12817 C->setComponents(Components, ListSizes);
12818}
12819
12820void OMPClauseReader::VisitOMPUseDeviceAddrClause(OMPUseDeviceAddrClause *C) {
12821 C->setLParenLoc(Record.readSourceLocation());
12822 auto NumVars = C->varlist_size();
12823 auto UniqueDecls = C->getUniqueDeclarationsNum();
12824 auto TotalLists = C->getTotalComponentListNum();
12825 auto TotalComponents = C->getTotalComponentsNum();
12826
12827 SmallVector<Expr *, 16> Vars;
12828 Vars.reserve(NumVars);
12829 for (unsigned i = 0; i != NumVars; ++i)
12830 Vars.push_back(Record.readSubExpr());
12831 C->setVarRefs(Vars);
12832
12833 SmallVector<ValueDecl *, 16> Decls;
12834 Decls.reserve(UniqueDecls);
12835 for (unsigned i = 0; i < UniqueDecls; ++i)
12836 Decls.push_back(Record.readDeclAs<ValueDecl>());
12837 C->setUniqueDecls(Decls);
12838
12839 SmallVector<unsigned, 16> ListsPerDecl;
12840 ListsPerDecl.reserve(UniqueDecls);
12841 for (unsigned i = 0; i < UniqueDecls; ++i)
12842 ListsPerDecl.push_back(Record.readInt());
12843 C->setDeclNumLists(ListsPerDecl);
12844
12845 SmallVector<unsigned, 32> ListSizes;
12846 ListSizes.reserve(TotalLists);
12847 for (unsigned i = 0; i < TotalLists; ++i)
12848 ListSizes.push_back(Record.readInt());
12849 C->setComponentListSizes(ListSizes);
12850
12851 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12852 Components.reserve(TotalComponents);
12853 for (unsigned i = 0; i < TotalComponents; ++i) {
12854 Expr *AssociatedExpr = Record.readSubExpr();
12855 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12856 Components.emplace_back(AssociatedExpr, AssociatedDecl,
12857 /*IsNonContiguous*/ false);
12858 }
12859 C->setComponents(Components, ListSizes);
12860}
12861
12862void OMPClauseReader::VisitOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
12863 C->setLParenLoc(Record.readSourceLocation());
12864 auto NumVars = C->varlist_size();
12865 auto UniqueDecls = C->getUniqueDeclarationsNum();
12866 auto TotalLists = C->getTotalComponentListNum();
12867 auto TotalComponents = C->getTotalComponentsNum();
12868
12869 SmallVector<Expr *, 16> Vars;
12870 Vars.reserve(NumVars);
12871 for (unsigned i = 0; i != NumVars; ++i)
12872 Vars.push_back(Record.readSubExpr());
12873 C->setVarRefs(Vars);
12874 Vars.clear();
12875
12876 SmallVector<ValueDecl *, 16> Decls;
12877 Decls.reserve(UniqueDecls);
12878 for (unsigned i = 0; i < UniqueDecls; ++i)
12879 Decls.push_back(Record.readDeclAs<ValueDecl>());
12880 C->setUniqueDecls(Decls);
12881
12882 SmallVector<unsigned, 16> ListsPerDecl;
12883 ListsPerDecl.reserve(UniqueDecls);
12884 for (unsigned i = 0; i < UniqueDecls; ++i)
12885 ListsPerDecl.push_back(Record.readInt());
12886 C->setDeclNumLists(ListsPerDecl);
12887
12888 SmallVector<unsigned, 32> ListSizes;
12889 ListSizes.reserve(TotalLists);
12890 for (unsigned i = 0; i < TotalLists; ++i)
12891 ListSizes.push_back(Record.readInt());
12892 C->setComponentListSizes(ListSizes);
12893
12894 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12895 Components.reserve(TotalComponents);
12896 for (unsigned i = 0; i < TotalComponents; ++i) {
12897 Expr *AssociatedExpr = Record.readSubExpr();
12898 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12899 Components.emplace_back(AssociatedExpr, AssociatedDecl,
12900 /*IsNonContiguous=*/false);
12901 }
12902 C->setComponents(Components, ListSizes);
12903}
12904
12905void OMPClauseReader::VisitOMPHasDeviceAddrClause(OMPHasDeviceAddrClause *C) {
12906 C->setLParenLoc(Record.readSourceLocation());
12907 auto NumVars = C->varlist_size();
12908 auto UniqueDecls = C->getUniqueDeclarationsNum();
12909 auto TotalLists = C->getTotalComponentListNum();
12910 auto TotalComponents = C->getTotalComponentsNum();
12911
12912 SmallVector<Expr *, 16> Vars;
12913 Vars.reserve(NumVars);
12914 for (unsigned I = 0; I != NumVars; ++I)
12915 Vars.push_back(Record.readSubExpr());
12916 C->setVarRefs(Vars);
12917 Vars.clear();
12918
12919 SmallVector<ValueDecl *, 16> Decls;
12920 Decls.reserve(UniqueDecls);
12921 for (unsigned I = 0; I < UniqueDecls; ++I)
12922 Decls.push_back(Record.readDeclAs<ValueDecl>());
12923 C->setUniqueDecls(Decls);
12924
12925 SmallVector<unsigned, 16> ListsPerDecl;
12926 ListsPerDecl.reserve(UniqueDecls);
12927 for (unsigned I = 0; I < UniqueDecls; ++I)
12928 ListsPerDecl.push_back(Record.readInt());
12929 C->setDeclNumLists(ListsPerDecl);
12930
12931 SmallVector<unsigned, 32> ListSizes;
12932 ListSizes.reserve(TotalLists);
12933 for (unsigned i = 0; i < TotalLists; ++i)
12934 ListSizes.push_back(Record.readInt());
12935 C->setComponentListSizes(ListSizes);
12936
12937 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12938 Components.reserve(TotalComponents);
12939 for (unsigned I = 0; I < TotalComponents; ++I) {
12940 Expr *AssociatedExpr = Record.readSubExpr();
12941 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12942 Components.emplace_back(AssociatedExpr, AssociatedDecl,
12943 /*IsNonContiguous=*/false);
12944 }
12945 C->setComponents(Components, ListSizes);
12946}
12947
12948void OMPClauseReader::VisitOMPNontemporalClause(OMPNontemporalClause *C) {
12949 C->setLParenLoc(Record.readSourceLocation());
12950 unsigned NumVars = C->varlist_size();
12951 SmallVector<Expr *, 16> Vars;
12952 Vars.reserve(NumVars);
12953 for (unsigned i = 0; i != NumVars; ++i)
12954 Vars.push_back(Record.readSubExpr());
12955 C->setVarRefs(Vars);
12956 Vars.clear();
12957 Vars.reserve(NumVars);
12958 for (unsigned i = 0; i != NumVars; ++i)
12959 Vars.push_back(Record.readSubExpr());
12960 C->setPrivateRefs(Vars);
12961}
12962
12963void OMPClauseReader::VisitOMPInclusiveClause(OMPInclusiveClause *C) {
12964 C->setLParenLoc(Record.readSourceLocation());
12965 unsigned NumVars = C->varlist_size();
12966 SmallVector<Expr *, 16> Vars;
12967 Vars.reserve(NumVars);
12968 for (unsigned i = 0; i != NumVars; ++i)
12969 Vars.push_back(Record.readSubExpr());
12970 C->setVarRefs(Vars);
12971}
12972
12973void OMPClauseReader::VisitOMPExclusiveClause(OMPExclusiveClause *C) {
12974 C->setLParenLoc(Record.readSourceLocation());
12975 unsigned NumVars = C->varlist_size();
12976 SmallVector<Expr *, 16> Vars;
12977 Vars.reserve(NumVars);
12978 for (unsigned i = 0; i != NumVars; ++i)
12979 Vars.push_back(Record.readSubExpr());
12980 C->setVarRefs(Vars);
12981}
12982
12983void OMPClauseReader::VisitOMPUsesAllocatorsClause(OMPUsesAllocatorsClause *C) {
12984 C->setLParenLoc(Record.readSourceLocation());
12985 unsigned NumOfAllocators = C->getNumberOfAllocators();
12986 SmallVector<OMPUsesAllocatorsClause::Data, 4> Data;
12987 Data.reserve(NumOfAllocators);
12988 for (unsigned I = 0; I != NumOfAllocators; ++I) {
12989 OMPUsesAllocatorsClause::Data &D = Data.emplace_back();
12990 D.Allocator = Record.readSubExpr();
12991 D.AllocatorTraits = Record.readSubExpr();
12992 D.LParenLoc = Record.readSourceLocation();
12993 D.RParenLoc = Record.readSourceLocation();
12994 }
12995 C->setAllocatorsData(Data);
12996}
12997
12998void OMPClauseReader::VisitOMPAffinityClause(OMPAffinityClause *C) {
12999 C->setLParenLoc(Record.readSourceLocation());
13000 C->setModifier(Record.readSubExpr());
13001 C->setColonLoc(Record.readSourceLocation());
13002 unsigned NumOfLocators = C->varlist_size();
13003 SmallVector<Expr *, 4> Locators;
13004 Locators.reserve(NumOfLocators);
13005 for (unsigned I = 0; I != NumOfLocators; ++I)
13006 Locators.push_back(Record.readSubExpr());
13007 C->setVarRefs(Locators);
13008}
13009
13010void OMPClauseReader::VisitOMPOrderClause(OMPOrderClause *C) {
13011 C->setKind(Record.readEnum<OpenMPOrderClauseKind>());
13012 C->setModifier(Record.readEnum<OpenMPOrderClauseModifier>());
13013 C->setLParenLoc(Record.readSourceLocation());
13014 C->setKindKwLoc(Record.readSourceLocation());
13015 C->setModifierKwLoc(Record.readSourceLocation());
13016}
13017
13018void OMPClauseReader::VisitOMPFilterClause(OMPFilterClause *C) {
13020 C->setThreadID(Record.readSubExpr());
13021 C->setLParenLoc(Record.readSourceLocation());
13022}
13023
13024void OMPClauseReader::VisitOMPBindClause(OMPBindClause *C) {
13025 C->setBindKind(Record.readEnum<OpenMPBindClauseKind>());
13026 C->setLParenLoc(Record.readSourceLocation());
13027 C->setBindKindLoc(Record.readSourceLocation());
13028}
13029
13030void OMPClauseReader::VisitOMPAlignClause(OMPAlignClause *C) {
13031 C->setAlignment(Record.readExpr());
13032 C->setLParenLoc(Record.readSourceLocation());
13033}
13034
13035void OMPClauseReader::VisitOMPXDynCGroupMemClause(OMPXDynCGroupMemClause *C) {
13037 C->setSize(Record.readSubExpr());
13038 C->setLParenLoc(Record.readSourceLocation());
13039}
13040
13041void OMPClauseReader::VisitOMPDynGroupprivateClause(
13042 OMPDynGroupprivateClause *C) {
13044 C->setDynGroupprivateModifier(
13045 Record.readEnum<OpenMPDynGroupprivateClauseModifier>());
13046 C->setDynGroupprivateFallbackModifier(
13048 C->setSize(Record.readSubExpr());
13049 C->setLParenLoc(Record.readSourceLocation());
13050 C->setDynGroupprivateModifierLoc(Record.readSourceLocation());
13051 C->setDynGroupprivateFallbackModifierLoc(Record.readSourceLocation());
13052}
13053
13054void OMPClauseReader::VisitOMPDoacrossClause(OMPDoacrossClause *C) {
13055 C->setLParenLoc(Record.readSourceLocation());
13056 C->setDependenceType(
13057 static_cast<OpenMPDoacrossClauseModifier>(Record.readInt()));
13058 C->setDependenceLoc(Record.readSourceLocation());
13059 C->setColonLoc(Record.readSourceLocation());
13060 unsigned NumVars = C->varlist_size();
13061 SmallVector<Expr *, 16> Vars;
13062 Vars.reserve(NumVars);
13063 for (unsigned I = 0; I != NumVars; ++I)
13064 Vars.push_back(Record.readSubExpr());
13065 C->setVarRefs(Vars);
13066 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
13067 C->setLoopData(I, Record.readSubExpr());
13068}
13069
13070void OMPClauseReader::VisitOMPXAttributeClause(OMPXAttributeClause *C) {
13071 AttrVec Attrs;
13072 Record.readAttributes(Attrs);
13073 C->setAttrs(Attrs);
13074 C->setLocStart(Record.readSourceLocation());
13075 C->setLParenLoc(Record.readSourceLocation());
13076 C->setLocEnd(Record.readSourceLocation());
13077}
13078
13079void OMPClauseReader::VisitOMPXBareClause(OMPXBareClause *C) {}
13080
13083 TI.Sets.resize(readUInt32());
13084 for (auto &Set : TI.Sets) {
13086 Set.Selectors.resize(readUInt32());
13087 for (auto &Selector : Set.Selectors) {
13089 Selector.ScoreOrCondition = nullptr;
13090 if (readBool())
13091 Selector.ScoreOrCondition = readExprRef();
13092 Selector.Properties.resize(readUInt32());
13093 for (auto &Property : Selector.Properties)
13095 }
13096 }
13097 return &TI;
13098}
13099
13101 if (!Data)
13102 return;
13103 if (Reader->ReadingKind == ASTReader::Read_Stmt) {
13104 // Skip NumClauses, NumChildren and HasAssociatedStmt fields.
13105 skipInts(3);
13106 }
13107 SmallVector<OMPClause *, 4> Clauses(Data->getNumClauses());
13108 for (unsigned I = 0, E = Data->getNumClauses(); I < E; ++I)
13109 Clauses[I] = readOMPClause();
13110 Data->setClauses(Clauses);
13111 if (Data->hasAssociatedStmt())
13112 Data->setAssociatedStmt(readStmt());
13113 for (unsigned I = 0, E = Data->getNumChildren(); I < E; ++I)
13114 Data->getChildren()[I] = readStmt();
13115}
13116
13118 unsigned NumVars = readInt();
13120 for (unsigned I = 0; I < NumVars; ++I)
13121 VarList.push_back(readExpr());
13122 return VarList;
13123}
13124
13126 unsigned NumExprs = readInt();
13128 for (unsigned I = 0; I < NumExprs; ++I)
13129 ExprList.push_back(readSubExpr());
13130 return ExprList;
13131}
13132
13137
13138 switch (ClauseKind) {
13140 SourceLocation LParenLoc = readSourceLocation();
13142 return OpenACCDefaultClause::Create(getContext(), DCK, BeginLoc, LParenLoc,
13143 EndLoc);
13144 }
13145 case OpenACCClauseKind::If: {
13146 SourceLocation LParenLoc = readSourceLocation();
13147 Expr *CondExpr = readSubExpr();
13148 return OpenACCIfClause::Create(getContext(), BeginLoc, LParenLoc, CondExpr,
13149 EndLoc);
13150 }
13152 SourceLocation LParenLoc = readSourceLocation();
13153 bool isConditionExprClause = readBool();
13154 if (isConditionExprClause) {
13155 Expr *CondExpr = readBool() ? readSubExpr() : nullptr;
13156 return OpenACCSelfClause::Create(getContext(), BeginLoc, LParenLoc,
13157 CondExpr, EndLoc);
13158 }
13159 unsigned NumVars = readInt();
13161 for (unsigned I = 0; I < NumVars; ++I)
13162 VarList.push_back(readSubExpr());
13163 return OpenACCSelfClause::Create(getContext(), BeginLoc, LParenLoc, VarList,
13164 EndLoc);
13165 }
13167 SourceLocation LParenLoc = readSourceLocation();
13168 unsigned NumClauses = readInt();
13170 for (unsigned I = 0; I < NumClauses; ++I)
13171 IntExprs.push_back(readSubExpr());
13172 return OpenACCNumGangsClause::Create(getContext(), BeginLoc, LParenLoc,
13173 IntExprs, EndLoc);
13174 }
13176 SourceLocation LParenLoc = readSourceLocation();
13177 Expr *IntExpr = readSubExpr();
13178 return OpenACCNumWorkersClause::Create(getContext(), BeginLoc, LParenLoc,
13179 IntExpr, EndLoc);
13180 }
13182 SourceLocation LParenLoc = readSourceLocation();
13183 Expr *IntExpr = readSubExpr();
13184 return OpenACCDeviceNumClause::Create(getContext(), BeginLoc, LParenLoc,
13185 IntExpr, EndLoc);
13186 }
13188 SourceLocation LParenLoc = readSourceLocation();
13189 Expr *IntExpr = readSubExpr();
13190 return OpenACCDefaultAsyncClause::Create(getContext(), BeginLoc, LParenLoc,
13191 IntExpr, EndLoc);
13192 }
13194 SourceLocation LParenLoc = readSourceLocation();
13195 Expr *IntExpr = readSubExpr();
13196 return OpenACCVectorLengthClause::Create(getContext(), BeginLoc, LParenLoc,
13197 IntExpr, EndLoc);
13198 }
13200 SourceLocation LParenLoc = readSourceLocation();
13202
13204 for (unsigned I = 0; I < VarList.size(); ++I) {
13205 static_assert(sizeof(OpenACCPrivateRecipe) == 1 * sizeof(int *));
13206 VarDecl *Alloca = readDeclAs<VarDecl>();
13207 RecipeList.push_back({Alloca});
13208 }
13209
13210 return OpenACCPrivateClause::Create(getContext(), BeginLoc, LParenLoc,
13211 VarList, RecipeList, EndLoc);
13212 }
13214 SourceLocation LParenLoc = readSourceLocation();
13216 return OpenACCHostClause::Create(getContext(), BeginLoc, LParenLoc, VarList,
13217 EndLoc);
13218 }
13220 SourceLocation LParenLoc = readSourceLocation();
13222 return OpenACCDeviceClause::Create(getContext(), BeginLoc, LParenLoc,
13223 VarList, EndLoc);
13224 }
13226 SourceLocation LParenLoc = readSourceLocation();
13229 for (unsigned I = 0; I < VarList.size(); ++I) {
13230 static_assert(sizeof(OpenACCFirstPrivateRecipe) == 2 * sizeof(int *));
13231 VarDecl *Recipe = readDeclAs<VarDecl>();
13232 VarDecl *RecipeTemp = readDeclAs<VarDecl>();
13233 RecipeList.push_back({Recipe, RecipeTemp});
13234 }
13235
13236 return OpenACCFirstPrivateClause::Create(getContext(), BeginLoc, LParenLoc,
13237 VarList, RecipeList, EndLoc);
13238 }
13240 SourceLocation LParenLoc = readSourceLocation();
13242 return OpenACCAttachClause::Create(getContext(), BeginLoc, LParenLoc,
13243 VarList, EndLoc);
13244 }
13246 SourceLocation LParenLoc = readSourceLocation();
13248 return OpenACCDetachClause::Create(getContext(), BeginLoc, LParenLoc,
13249 VarList, EndLoc);
13250 }
13252 SourceLocation LParenLoc = readSourceLocation();
13254 return OpenACCDeleteClause::Create(getContext(), BeginLoc, LParenLoc,
13255 VarList, EndLoc);
13256 }
13258 SourceLocation LParenLoc = readSourceLocation();
13260 return OpenACCUseDeviceClause::Create(getContext(), BeginLoc, LParenLoc,
13261 VarList, EndLoc);
13262 }
13264 SourceLocation LParenLoc = readSourceLocation();
13266 return OpenACCDevicePtrClause::Create(getContext(), BeginLoc, LParenLoc,
13267 VarList, EndLoc);
13268 }
13270 SourceLocation LParenLoc = readSourceLocation();
13272 return OpenACCNoCreateClause::Create(getContext(), BeginLoc, LParenLoc,
13273 VarList, EndLoc);
13274 }
13276 SourceLocation LParenLoc = readSourceLocation();
13278 return OpenACCPresentClause::Create(getContext(), BeginLoc, LParenLoc,
13279 VarList, EndLoc);
13280 }
13284 SourceLocation LParenLoc = readSourceLocation();
13287 return OpenACCCopyClause::Create(getContext(), ClauseKind, BeginLoc,
13288 LParenLoc, ModList, VarList, EndLoc);
13289 }
13293 SourceLocation LParenLoc = readSourceLocation();
13296 return OpenACCCopyInClause::Create(getContext(), ClauseKind, BeginLoc,
13297 LParenLoc, ModList, VarList, EndLoc);
13298 }
13302 SourceLocation LParenLoc = readSourceLocation();
13305 return OpenACCCopyOutClause::Create(getContext(), ClauseKind, BeginLoc,
13306 LParenLoc, ModList, VarList, EndLoc);
13307 }
13311 SourceLocation LParenLoc = readSourceLocation();
13314 return OpenACCCreateClause::Create(getContext(), ClauseKind, BeginLoc,
13315 LParenLoc, ModList, VarList, EndLoc);
13316 }
13318 SourceLocation LParenLoc = readSourceLocation();
13319 Expr *AsyncExpr = readBool() ? readSubExpr() : nullptr;
13320 return OpenACCAsyncClause::Create(getContext(), BeginLoc, LParenLoc,
13321 AsyncExpr, EndLoc);
13322 }
13324 SourceLocation LParenLoc = readSourceLocation();
13325 Expr *DevNumExpr = readBool() ? readSubExpr() : nullptr;
13326 SourceLocation QueuesLoc = readSourceLocation();
13328 return OpenACCWaitClause::Create(getContext(), BeginLoc, LParenLoc,
13329 DevNumExpr, QueuesLoc, QueueIdExprs,
13330 EndLoc);
13331 }
13334 SourceLocation LParenLoc = readSourceLocation();
13336 unsigned NumArchs = readInt();
13337
13338 for (unsigned I = 0; I < NumArchs; ++I) {
13339 IdentifierInfo *Ident = readBool() ? readIdentifier() : nullptr;
13341 Archs.emplace_back(Loc, Ident);
13342 }
13343
13344 return OpenACCDeviceTypeClause::Create(getContext(), ClauseKind, BeginLoc,
13345 LParenLoc, Archs, EndLoc);
13346 }
13348 SourceLocation LParenLoc = readSourceLocation();
13352
13353 for (unsigned I = 0; I < VarList.size(); ++I) {
13354 VarDecl *Recipe = readDeclAs<VarDecl>();
13355
13356 static_assert(sizeof(OpenACCReductionRecipe::CombinerRecipe) ==
13357 3 * sizeof(int *));
13358
13360 unsigned NumCombiners = readInt();
13361 for (unsigned I = 0; I < NumCombiners; ++I) {
13364 Expr *Op = readExpr();
13365
13366 Combiners.push_back({LHS, RHS, Op});
13367 }
13368
13369 RecipeList.push_back({Recipe, Combiners});
13370 }
13371
13372 return OpenACCReductionClause::Create(getContext(), BeginLoc, LParenLoc, Op,
13373 VarList, RecipeList, EndLoc);
13374 }
13376 return OpenACCSeqClause::Create(getContext(), BeginLoc, EndLoc);
13378 return OpenACCNoHostClause::Create(getContext(), BeginLoc, EndLoc);
13380 return OpenACCFinalizeClause::Create(getContext(), BeginLoc, EndLoc);
13382 return OpenACCIfPresentClause::Create(getContext(), BeginLoc, EndLoc);
13384 return OpenACCIndependentClause::Create(getContext(), BeginLoc, EndLoc);
13386 return OpenACCAutoClause::Create(getContext(), BeginLoc, EndLoc);
13388 SourceLocation LParenLoc = readSourceLocation();
13389 bool HasForce = readBool();
13390 Expr *LoopCount = readSubExpr();
13391 return OpenACCCollapseClause::Create(getContext(), BeginLoc, LParenLoc,
13392 HasForce, LoopCount, EndLoc);
13393 }
13395 SourceLocation LParenLoc = readSourceLocation();
13396 unsigned NumClauses = readInt();
13397 llvm::SmallVector<Expr *> SizeExprs;
13398 for (unsigned I = 0; I < NumClauses; ++I)
13399 SizeExprs.push_back(readSubExpr());
13400 return OpenACCTileClause::Create(getContext(), BeginLoc, LParenLoc,
13401 SizeExprs, EndLoc);
13402 }
13404 SourceLocation LParenLoc = readSourceLocation();
13405 unsigned NumExprs = readInt();
13408 for (unsigned I = 0; I < NumExprs; ++I) {
13409 GangKinds.push_back(readEnum<OpenACCGangKind>());
13410 // Can't use `readSubExpr` because this is usable from a 'decl' construct.
13411 Exprs.push_back(readExpr());
13412 }
13413 return OpenACCGangClause::Create(getContext(), BeginLoc, LParenLoc,
13414 GangKinds, Exprs, EndLoc);
13415 }
13417 SourceLocation LParenLoc = readSourceLocation();
13418 Expr *WorkerExpr = readBool() ? readSubExpr() : nullptr;
13419 return OpenACCWorkerClause::Create(getContext(), BeginLoc, LParenLoc,
13420 WorkerExpr, EndLoc);
13421 }
13423 SourceLocation LParenLoc = readSourceLocation();
13424 Expr *VectorExpr = readBool() ? readSubExpr() : nullptr;
13425 return OpenACCVectorClause::Create(getContext(), BeginLoc, LParenLoc,
13426 VectorExpr, EndLoc);
13427 }
13429 SourceLocation LParenLoc = readSourceLocation();
13431 return OpenACCLinkClause::Create(getContext(), BeginLoc, LParenLoc, VarList,
13432 EndLoc);
13433 }
13435 SourceLocation LParenLoc = readSourceLocation();
13438 LParenLoc, VarList, EndLoc);
13439 }
13440
13442 SourceLocation LParenLoc = readSourceLocation();
13443 bool IsString = readBool();
13444 if (IsString)
13445 return OpenACCBindClause::Create(getContext(), BeginLoc, LParenLoc,
13446 cast<StringLiteral>(readExpr()), EndLoc);
13447 return OpenACCBindClause::Create(getContext(), BeginLoc, LParenLoc,
13448 readIdentifier(), EndLoc);
13449 }
13452 llvm_unreachable("Clause serialization not yet implemented");
13453 }
13454 llvm_unreachable("Invalid Clause Kind");
13455}
13456
13459 for (unsigned I = 0; I < Clauses.size(); ++I)
13460 Clauses[I] = readOpenACCClause();
13461}
13462
13463void ASTRecordReader::readOpenACCRoutineDeclAttr(OpenACCRoutineDeclAttr *A) {
13464 unsigned NumVars = readInt();
13465 A->Clauses.resize(NumVars);
13466 readOpenACCClauseList(A->Clauses);
13467}
13468
13469static unsigned getStableHashForModuleName(StringRef PrimaryModuleName) {
13470 // TODO: Maybe it is better to check PrimaryModuleName is a valid
13471 // module name?
13472 llvm::FoldingSetNodeID ID;
13473 ID.AddString(PrimaryModuleName);
13474 return ID.computeStableHash();
13475}
13476
13478 if (!M)
13479 return std::nullopt;
13480
13481 if (M->isHeaderLikeModule())
13482 return std::nullopt;
13483
13484 if (M->isGlobalModule())
13485 return std::nullopt;
13486
13487 StringRef PrimaryModuleName = M->getPrimaryModuleInterfaceName();
13488 return getStableHashForModuleName(PrimaryModuleName);
13489}
Defines the clang::ASTContext interface.
static unsigned moduleKindForDiagnostic(ModuleKind Kind)
static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD, ASTConsumer *Consumer)
Under non-PCH compilation the consumer receives the objc methods before receiving the implementation,...
static bool checkCodegenOptions(const CodeGenOptions &CGOpts, const CodeGenOptions &ExistingCGOpts, StringRef ModuleFilename, DiagnosticsEngine *Diags, bool AllowCompatibleDifferences=true)
static llvm::Error doesntStartWithASTFileMagic(BitstreamCursor &Stream)
Whether Stream doesn't start with the AST file magic number 'CPCH'.
static std::vector< std::string > accumulateFeaturesAsWritten(std::vector< std::string > FeaturesAsWritten)
static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags)
static std::pair< bool, bool > wasValidatedInBuildSession(const ModuleFile &MF, const HeaderSearchOptions &HSOpts)
Returns {build-session validation applies, MF was validated this session}.
static unsigned getModuleFileIndexForTypeID(serialization::TypeID ID)
static void collectMacroDefinitions(const PreprocessorOptions &PPOpts, MacroDefinitionsMap &Macros, SmallVectorImpl< StringRef > *MacroNames=nullptr)
Collect the macro definitions provided by the given preprocessor options.
static void markIdentifierFromAST(ASTReader &Reader, IdentifierInfo &II, bool IsModule)
static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method)
Move the given method to the back of the global list of methods.
static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps)
static bool isInterestingIdentifier(ASTReader &Reader, const IdentifierInfo &II, bool IsModule)
Whether the given identifier is "interesting".
static bool parseModuleFileExtensionMetadata(const SmallVectorImpl< uint64_t > &Record, StringRef Blob, ModuleFileExtensionMetadata &Metadata)
Parse a record and blob containing module file extension metadata.
static Module * getTopImportImplicitModule(ModuleManager &ModuleMgr, Preprocessor &PP)
Return the top import module if it is implicit, nullptr otherwise.
static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts, const PreprocessorOptions &ExistingPPOpts, StringRef ModuleFilename, bool ReadMacros, DiagnosticsEngine *Diags, FileManager &FileMgr, std::string &SuggestedPredefines, const LangOptions &LangOpts, OptionValidation Validation=OptionValidateContradictions)
Check the preprocessor options deserialized from the control block against the preprocessor options i...
static void addMethodsToPool(Sema &S, ArrayRef< ObjCMethodDecl * > Methods, ObjCMethodList &List)
Add the given set of methods to the method list.
static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags, DiagnosticsEngine &Diags, StringRef ModuleFilename, bool IsSystem, bool SystemHeaderWarningsInModule, bool Complain)
static bool isPredefinedType(serialization::TypeID ID)
static bool readBit(unsigned &Bits)
static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags, DiagnosticsEngine &Diags, StringRef ModuleFilename, bool Complain)
static std::optional< Type::TypeClass > getTypeClassForCode(TypeCode code)
static std::pair< unsigned, unsigned > readULEBKeyDataLength(const unsigned char *&P)
Read ULEB-encoded key length and data length.
static unsigned getStableHashForModuleName(StringRef PrimaryModuleName)
static LLVM_DUMP_METHOD void dumpModuleIDMap(StringRef Name, const ContinuousRangeMap< Key, ModuleFile *, InitialCapacity > &Map)
OptionValidation
@ OptionValidateStrictMatches
@ OptionValidateNone
@ OptionValidateContradictions
static bool checkTargetOptions(const TargetOptions &TargetOpts, const TargetOptions &ExistingTargetOpts, StringRef ModuleFilename, DiagnosticsEngine *Diags, bool AllowCompatibleDifferences=true)
Compare the given set of target options against an existing set of target options.
static bool checkLanguageOptions(const LangOptions &LangOpts, const LangOptions &ExistingLangOpts, StringRef ModuleFilename, DiagnosticsEngine *Diags, bool AllowCompatibleDifferences=true)
Compare the given set of language options against an existing set of language options.
static std::pair< StringRef, StringRef > getUnresolvedInputFilenames(const ASTReader::RecordData &Record, const StringRef InputBlob)
#define CHECK_TARGET_OPT(Field, Name)
static ASTFileSignature readASTFileSignature(StringRef PCH)
Reads and return the signature record from PCH's control block, or else returns 0.
static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID)
Given a cursor at the start of an AST file, scan ahead and drop the cursor into the start of the give...
static unsigned getIndexForTypeID(serialization::TypeID ID)
static uint64_t readULEB(const unsigned char *&P)
static bool checkModuleCachePath(FileManager &FileMgr, StringRef ContextHash, StringRef ExistingSpecificModuleCachePath, StringRef ASTFilename, DiagnosticsEngine *Diags, const LangOptions &LangOpts, const PreprocessorOptions &PPOpts, const HeaderSearchOptions &HSOpts, const HeaderSearchOptions &ASTFileHSOpts)
Check that the specified and the existing module cache paths are equivalent.
Defines the clang::ASTSourceDescriptor class, which abstracts clang modules and precompiled header fi...
static StringRef bytes(const std::vector< T, Allocator > &v)
Defines the Diagnostic-related interfaces.
Defines the clang::CommentOptions interface.
static void dump(llvm::raw_ostream &OS, StringRef FunctionName, ArrayRef< CounterExpression > Expressions, ArrayRef< CounterMappingRegion > Regions)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the C++ template declaration subclasses.
Defines the Diagnostic IDs-related interfaces.
static bool hasDefinition(const ObjCObjectPointerType *ObjPtr)
Defines the clang::Expr interface and subclasses for C++ expressions.
Defines the clang::FileManager interface and associated types.
Defines the clang::FileSystemOptions interface.
Token Tok
The Token.
FormatToken * Previous
The previous token in the unwrapped line.
FormatToken * Next
The next token in the unwrapped line.
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
Result
Implement __builtin_bit_cast and related operations.
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the clang::LangOptions interface.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Record Record
Definition MachO.h:31
Defines the clang::MacroInfo and clang::MacroDirective classes.
Defines the clang::Module class, which describes a module in the source code.
Defines types useful for describing an Objective-C runtime.
#define SM(sm)
Defines some OpenACC-specific enums and functions.
This file defines OpenMP AST classes for clauses.
Defines some OpenMP-specific enums and functions.
Defines an enumeration for C++ overloaded operators.
Defines the clang::Preprocessor interface.
Defines the clang::SanitizerKind enum.
This file declares semantic analysis for CUDA constructs.
This file declares semantic analysis for Objective-C.
Defines the clang::SourceLocation class and associated facilities.
Defines implementation details of the clang::SourceManager class.
Defines the SourceManager interface.
Defines various enumerations that describe declaration and type specifiers.
Defines the clang::TargetOptions class.
#define IMPORT(DERIVED, BASE)
Definition Template.h:630
Defines the clang::TokenKind enum and support functions.
Defines the clang::TypeLoc interface and its subclasses.
C Language Family Type Representation.
Defines version macros and version-related utility functions for Clang.
__DEVICE__ void * memcpy(void *__a, const void *__b, size_t __c)
__device__ __2f16 b
static OMPAffinityClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with the place for N locator items.
static OMPAlignedClause * CreateEmpty(const ASTContext &C, unsigned NumVars)
Creates an empty clause with the place for NumVars variables.
static OMPBindClause * CreateEmpty(const ASTContext &C)
Build an empty 'bind' clause.
Contains data for OpenMP directives: clauses, children expressions/statements (helpers for codegen) a...
static OMPCopyinClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with N variables.
static OMPCopyprivateClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with N variables.
This represents 'defaultmap' clause in the 'pragma omp ...' directive.
static OMPDependClause * CreateEmpty(const ASTContext &C, unsigned N, unsigned NumLoops)
Creates an empty clause with N variables.
static OMPDepobjClause * CreateEmpty(const ASTContext &C)
Creates an empty clause.
This represents 'destroy' clause in the 'pragma omp depobj' directive or the 'pragma omp interop' dir...
This represents 'detach' clause in the 'pragma omp task' directive.
This represents 'device' clause in the 'pragma omp ...' directive.
This represents 'dist_schedule' clause in the 'pragma omp ...' directive.
static OMPDoacrossClause * CreateEmpty(const ASTContext &C, unsigned N, unsigned NumLoops)
Creates an empty clause with N expressions.
This represents 'dyn_groupprivate' clause in 'pragma omp target ...' and 'pragma omp teams ....
static OMPExclusiveClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with the place for N variables.
This represents 'filter' clause in the 'pragma omp ...' directive.
static OMPFlushClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with N variables.
static OMPFromClause * CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes)
Creates an empty clause with the place for NumVars variables.
This represents 'grainsize' clause in the 'pragma omp ...' directive.
static OMPHasDeviceAddrClause * CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes)
Creates an empty clause with the place for NumVars variables.
This represents 'hint' clause in the 'pragma omp ...' directive.
static OMPInclusiveClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with the place for N variables.
static OMPInitClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with N expressions.
static OMPIsDevicePtrClause * CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes)
Creates an empty clause with the place for NumVars variables.
static OMPMapClause * CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes)
Creates an empty clause with the place for NumVars original expressions, NumUniqueDeclarations declar...
This represents 'nocontext' clause in the 'pragma omp ...' directive.
This represents 'nogroup' clause in the 'pragma omp ...' directive.
static OMPNontemporalClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with the place for N variables.
This represents 'novariants' clause in the 'pragma omp ...' directive.
This represents 'num_tasks' clause in the 'pragma omp ...' directive.
static OMPNumTeamsClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with N variables.
This represents 'order' clause in the 'pragma omp ...' directive.
This represents 'priority' clause in the 'pragma omp ...' directive.
This represents 'simd' clause in the 'pragma omp ...' directive.
static OMPThreadLimitClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with N variables.
This represents 'threads' clause in the 'pragma omp ...' directive.
static OMPToClause * CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes)
Creates an empty clause with the place for NumVars variables.
llvm::SmallVector< OMPTraitSet, 2 > Sets
The outermost level of selector sets.
This represents the 'use' clause in 'pragma omp ...' directives.
static OMPUseDeviceAddrClause * CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes)
Creates an empty clause with the place for NumVars variables.
static OMPUseDevicePtrClause * CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes)
Creates an empty clause with the place for NumVars variables.
static OMPUsesAllocatorsClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with the place for N allocators.
This represents 'ompx_attribute' clause in a directive that might generate an outlined function.
This represents 'ompx_bare' clause in the 'pragma omp target teams ...' directive.
This represents 'ompx_dyn_cgroup_mem' clause in the 'pragma omp target ...' directive.
ASTConsumer - This is an abstract interface that should be implemented by clients that read ASTs.
Definition ASTConsumer.h:35
virtual void HandleInterestingDecl(DeclGroupRef D)
HandleInterestingDecl - Handle the specified interesting declaration.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:227
OMPTraitInfo & getNewOMPTraitInfo()
Return a new OMPTraitInfo object owned by this context.
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
void adjustExceptionSpec(FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI, bool AsWritten=false)
Change the exception specification on a function once it is delay-parsed, instantiated,...
const clang::PrintingPolicy & getPrintingPolicy() const
Definition ASTContext.h:858
void deduplicateMergedDefinitionsFor(NamedDecl *ND)
Clean up the merged definition list.
void adjustDeducedFunctionResultType(FunctionDecl *FD, QualType ResultType)
Change the result type of a function type once it is deduced.
void setPrimaryMergedDecl(Decl *D, Decl *Primary)
ASTIdentifierIterator(const ASTReader &Reader, bool SkipModules=false)
StringRef Next() override
Retrieve the next string in the identifier table and advances the iterator for the following string.
Abstract interface for callback invocations by the ASTReader.
Definition ASTReader.h:117
virtual bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, StringRef ModuleFilename, StringRef ContextHash, bool Complain)
Receives the header search options.
Definition ASTReader.h:186
virtual void ReadModuleMapFile(StringRef ModuleMapPath)
Definition ASTReader.h:130
virtual bool needsInputFileVisitation()
Returns true if this ASTReaderListener wants to receive the input files of the AST file via visitInpu...
Definition ASTReader.h:232
virtual bool ReadDiagnosticOptions(DiagnosticOptions &DiagOpts, StringRef ModuleFilename, bool Complain)
Receives the diagnostic options.
Definition ASTReader.h:164
virtual bool ReadTargetOptions(const TargetOptions &TargetOpts, StringRef ModuleFilename, bool Complain, bool AllowCompatibleDifferences)
Receives the target options.
Definition ASTReader.h:154
virtual bool visitInputFile(StringRef Filename, bool isSystem, bool isOverridden, bool isExplicitModule)
if needsInputFileVisitation returns true, this is called for each non-system input file of the AST Fi...
Definition ASTReader.h:244
virtual bool ReadHeaderSearchPaths(const HeaderSearchOptions &HSOpts, bool Complain)
Receives the header search paths.
Definition ASTReader.h:201
virtual bool ReadFileSystemOptions(const FileSystemOptions &FSOpts, bool Complain)
Receives the file system options.
Definition ASTReader.h:173
virtual void visitModuleFile(ModuleFileName Filename, serialization::ModuleKind Kind, bool DirectlyImported)
This is called for each AST file loaded.
Definition ASTReader.h:226
virtual bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, StringRef ModuleFilename, bool ReadMacros, bool Complain, std::string &SuggestedPredefines)
Receives the preprocessor options.
Definition ASTReader.h:214
virtual bool ReadLanguageOptions(const LangOptions &LangOpts, StringRef ModuleFilename, bool Complain, bool AllowCompatibleDifferences)
Receives the language options.
Definition ASTReader.h:135
virtual void ReadModuleName(StringRef ModuleName)
Definition ASTReader.h:129
virtual void ReadCounter(const serialization::ModuleFile &M, uint32_t Value)
Receives COUNTER value.
Definition ASTReader.h:222
virtual bool needsSystemInputFileVisitation()
Returns true if this ASTReaderListener wants to receive the system input files of the AST file via vi...
Definition ASTReader.h:236
virtual bool ReadCodeGenOptions(const CodeGenOptions &CGOpts, StringRef ModuleFilename, bool Complain, bool AllowCompatibleDifferences)
Receives the codegen options.
Definition ASTReader.h:144
Reads an AST files chain containing the contents of a translation unit.
Definition ASTReader.h:427
std::optional< bool > isPreprocessedEntityInFileID(unsigned Index, FileID FID) override
Optionally returns true or false if the preallocated preprocessed entity with index Index came from f...
PreprocessedEntity * ReadPreprocessedEntity(unsigned Index) override
Read a preallocated preprocessed entity from the external source.
void markIdentifierUpToDate(const IdentifierInfo *II)
Note that this identifier is up-to-date.
void visitTopLevelModuleMaps(serialization::ModuleFile &MF, llvm::function_ref< void(FileEntryRef)> Visitor)
Visit all the top-level module maps loaded when building the given module file.
void setDeserializationListener(ASTDeserializationListener *Listener, bool TakeOwnership=false)
Set the AST deserialization listener.
SmallVectorImpl< uint64_t > RecordDataImpl
Definition ASTReader.h:443
serialization::SubmoduleID getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) const
Retrieve the global submodule ID given a module and its local ID number.
ExtKind hasExternalDefinitions(const Decl *D) override
IdentifierTable & getIdentifierTable()
Retrieve the identifier table associated with the preprocessor.
ModuleManager & getModuleManager()
Retrieve the module manager.
Definition ASTReader.h:1977
bool isDeclIDFromModule(GlobalDeclID ID, ModuleFile &M) const
Returns true if global DeclID ID originated from module M.
friend class ASTIdentifierIterator
Definition ASTReader.h:432
bool ReadSLocEntry(int ID) override
Read the source location entry with index ID.
void RecordSwitchCaseID(SwitchCase *SC, unsigned ID)
Record that the given ID maps to the given switch-case statement.
DiagnosticBuilder Diag(unsigned DiagID) const
Report a diagnostic.
ASTContext & getContext()
Retrieve the AST context that this AST reader supplements.
Definition ASTReader.h:2599
Decl * ReadDecl(ModuleFile &F, const RecordDataImpl &R, unsigned &I)
Reads a declaration from the given position in a record in the given module.
Definition ASTReader.h:2170
static std::string ReadString(const RecordDataImpl &Record, unsigned &Idx)
void ReadDeclsToCheckForDeferredDiags(llvm::SmallSetVector< Decl *, 4 > &Decls) override
Read the set of decls to be checked for deferred diags.
void InitializeSema(Sema &S) override
Initialize the semantic source with the Sema instance being used to perform semantic analysis on the ...
@ ARR_Missing
The client can handle an AST file that cannot load because it is missing.
Definition ASTReader.h:1825
@ ARR_ConfigurationMismatch
The client can handle an AST file that cannot load because it's compiled configuration doesn't match ...
Definition ASTReader.h:1838
@ ARR_OutOfDate
The client can handle an AST file that cannot load because it is out-of-date relative to its input fi...
Definition ASTReader.h:1829
@ ARR_VersionMismatch
The client can handle an AST file that cannot load because it was built with a different version of C...
Definition ASTReader.h:1833
void ReadMismatchingDeleteExpressions(llvm::MapVector< FieldDecl *, llvm::SmallVector< std::pair< SourceLocation, bool >, 4 > > &Exprs) override
void FindFileRegionDecls(FileID File, unsigned Offset, unsigned Length, SmallVectorImpl< Decl * > &Decls) override
Get the decls that are contained in a file in the Offset/Length range.
std::string ReadPathBlob(StringRef BaseDirectory, const RecordData &Record, unsigned &Idx, StringRef &Blob)
SourceRange ReadSkippedRange(unsigned Index) override
Read a preallocated skipped range from the external source.
serialization::TypeID getGlobalTypeID(ModuleFile &F, serialization::LocalTypeID LocalID) const
Map a local type ID within a given AST file into a global type ID.
void dump()
Dump information about the AST reader to standard error.
MacroInfo * ReadMacroRecord(ModuleFile &F, uint64_t Offset)
Reads the macro record located at the given offset.
SmallVector< std::pair< llvm::BitstreamCursor, serialization::ModuleFile * >, 8 > CommentsCursors
Cursors for comments blocks.
Definition ASTReader.h:2633
Selector getLocalSelector(ModuleFile &M, unsigned LocalID)
Retrieve a selector from the given module with its local ID number.
void FindExternalLexicalDecls(const DeclContext *DC, llvm::function_ref< bool(Decl::Kind)> IsKindWeWant, SmallVectorImpl< Decl * > &Decls) override
Read all of the declarations lexically stored in a declaration context.
ModuleFile * getOwningModuleFile(const Decl *D) const
Retrieve the module file that owns the given declaration, or NULL if the declaration is not from a mo...
std::optional< ASTSourceDescriptor > getSourceDescriptor(unsigned ID) override
Return a descriptor for the corresponding module.
const serialization::reader::DeclContextLookupTable * getLoadedLookupTables(DeclContext *Primary) const
Get the loaded lookup tables for Primary, if any.
T * ReadDeclAs(ModuleFile &F, const RecordDataImpl &R, unsigned &I)
Reads a declaration from the given position in a record in the given module.
Definition ASTReader.h:2180
QualType getLocalType(ModuleFile &F, serialization::LocalTypeID LocalID)
Resolve a local type ID within a given AST file into a type.
void ReadExtnameUndeclaredIdentifiers(SmallVectorImpl< std::pair< IdentifierInfo *, AsmLabelAttr * > > &ExtnameIDs) override
Read the set of pragma redefine_extname'd, undeclared identifiers known to the external Sema source.
friend class LocalDeclID
Definition ASTReader.h:440
void SetGloballyVisibleDecls(IdentifierInfo *II, const SmallVectorImpl< GlobalDeclID > &DeclIDs, SmallVectorImpl< Decl * > *Decls=nullptr)
Set the globally-visible declarations associated with the given identifier.
serialization::ModuleKind ModuleKind
Definition ASTReader.h:474
bool loadGlobalIndex()
Attempts to load the global index.
void ReadComments() override
Loads comments ranges.
SourceManager & getSourceManager() const
Definition ASTReader.h:1809
const serialization::reader::ModuleLocalLookupTable * getModuleLocalLookupTables(DeclContext *Primary) const
SourceLocation getSourceLocationForDeclID(GlobalDeclID ID)
Returns the source location for the decl ID.
void makeModuleVisible(Module *Mod, Module::NameVisibilityKind NameVisibility, SourceLocation ImportLoc)
Make the entities in the given module and any of its (non-explicit) submodules visible to name lookup...
SourceRange ReadSourceRange(ModuleFile &F, const RecordData &Record, unsigned &Idx)
Read a source range.
bool LoadExternalSpecializations(const Decl *D, bool OnlyPartial) override
Load all the external specializations for the Decl.
ASTReadResult ReadASTCore(ModuleFileName FileName, ModuleKind Type, SourceLocation ImportLoc, ModuleFile *ImportedBy, SmallVectorImpl< ImportedModule > &Loaded, off_t ExpectedSize, time_t ExpectedModTime, ASTFileSignature ExpectedSignature, unsigned ClientLoadCapabilities)
void finalizeForWriting()
Finalizes the AST reader's state before writing an AST file to disk.
Sema * getSema()
Retrieve the semantic analysis object used to analyze the translation unit in which the precompiled h...
Definition ASTReader.h:2611
static std::string ResolveImportedPathAndAllocate(SmallString< 0 > &Buf, StringRef Path, ModuleFile &ModF)
Resolve Path in the context of module file M.
static StringRef ReadStringBlob(const RecordDataImpl &Record, unsigned &Idx, StringRef &Blob)
CXXCtorInitializer ** GetExternalCXXCtorInitializers(uint64_t Offset) override
Read the contents of a CXXCtorInitializer array.
void visitInputFileInfos(serialization::ModuleFile &MF, bool IncludeSystem, llvm::function_ref< void(const serialization::InputFileInfo &IFI, bool IsSystem)> Visitor)
Visit all the input file infos of the given module file.
unsigned getTotalNumSLocs() const
Returns the number of source locations found in the chain.
Definition ASTReader.h:2046
void StartTranslationUnit(ASTConsumer *Consumer) override
Function that will be invoked when we begin parsing a new translation unit involving this external AS...
LocalDeclID mapGlobalIDToModuleFileGlobalID(ModuleFile &M, GlobalDeclID GlobalID)
Map a global declaration ID into the declaration ID used to refer to this declaration within the give...
void resolvePendingMacro(IdentifierInfo *II, const PendingMacroInfo &PMInfo)
void ReadTentativeDefinitions(SmallVectorImpl< VarDecl * > &TentativeDefs) override
Read the set of tentative definitions known to the external Sema source.
Decl * GetExternalDecl(GlobalDeclID ID) override
Resolve a declaration ID into a declaration, potentially building a new declaration.
serialization::MacroID ReadMacroID(ModuleFile &F, const RecordDataImpl &Record, unsigned &Idx)
Reads a macro ID from the given position in a record in the given module.
GlobalDeclID ReadDeclID(ModuleFile &F, const RecordDataImpl &Record, unsigned &Idx)
Reads a declaration ID from the given position in a record in the given module.
llvm::Expected< SourceLocation::UIntTy > readSLocOffset(ModuleFile *F, unsigned Index)
Try to read the offset of the SLocEntry at the given index in the given module file.
~ASTReader() override
bool haveUnloadedSpecializations(const Decl *D) const
If we have any unloaded specialization for D.
friend class PCHValidator
Definition ASTReader.h:436
friend class serialization::ReadMethodPoolVisitor
Definition ASTReader.h:438
void CompleteRedeclChain(const Decl *D) override
If any redeclarations of D have been imported since it was last checked, this digs out those redeclar...
SourceLocation TranslateSourceLocation(ModuleFile &ModuleFile, SourceLocation Loc) const
Translate a source location from another module file's source location space into ours.
Definition ASTReader.h:2485
static llvm::Error ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor, unsigned BlockID, uint64_t *StartOfBlockOffset=nullptr)
ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the specified cursor.
void SetIdentifierInfo(serialization::IdentifierID ID, IdentifierInfo *II)
std::pair< unsigned, unsigned > findPreprocessedEntitiesInRange(SourceRange Range) override
Returns a pair of [Begin, End) indices of preallocated preprocessed entities that Range encompasses.
IdentifierInfo * get(StringRef Name) override
Retrieve the IdentifierInfo for the named identifier.
IdentifierInfo * getLocalIdentifier(ModuleFile &M, uint64_t LocalID)
void visitInputFiles(serialization::ModuleFile &MF, bool IncludeSystem, bool Complain, llvm::function_ref< void(const serialization::InputFile &IF, bool isSystem)> Visitor)
Visit all the input files of the given module file.
Module * getModule(unsigned ID) override
Retrieve the module that corresponds to the given module ID.
llvm::iterator_range< ModuleDeclIterator > getModuleFileLevelDecls(ModuleFile &Mod)
Stmt * GetExternalDeclStmt(uint64_t Offset) override
Resolve the offset of a statement into a statement.
Selector GetExternalSelector(serialization::SelectorID ID) override
Resolve a selector ID into a selector.
unsigned getTotalNumSelectors() const
Returns the number of selectors found in the chain.
Definition ASTReader.h:2076
MacroInfo * getMacro(serialization::MacroID ID)
Retrieve the macro with the given ID.
void ReadUndefinedButUsed(llvm::MapVector< NamedDecl *, SourceLocation > &Undefined) override
Load the set of used but not defined functions or variables with internal linkage,...
void ReadDelegatingConstructors(SmallVectorImpl< CXXConstructorDecl * > &Decls) override
Read the set of delegating constructors known to the external Sema source.
QualType GetType(serialization::TypeID ID)
Resolve a type ID into a type, potentially building a new type.
void addPendingMacro(IdentifierInfo *II, ModuleFile *M, uint32_t MacroDirectivesOffset)
Add a macro to deserialize its macro directive history.
GlobalDeclID getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const
Map from a local declaration ID within a given module to a global declaration ID.
void ReadWeakUndeclaredIdentifiers(SmallVectorImpl< std::pair< IdentifierInfo *, WeakInfo > > &WeakIDs) override
Read the set of weak, undeclared identifiers known to the external Sema source.
void completeVisibleDeclsMap(const DeclContext *DC) override
Load all external visible decls in the given DeclContext.
void AssignedLambdaNumbering(CXXRecordDecl *Lambda) override
Notify the external source that a lambda was assigned a mangling number.
void ReadUnusedLocalTypedefNameCandidates(llvm::SmallSetVector< const TypedefNameDecl *, 4 > &Decls) override
Read the set of potentially unused typedefs known to the source.
IdentifierResolver & getIdResolver()
Get the identifier resolver used for name lookup / updates in the translation unit scope.
static bool readASTFileControlBlock(StringRef Filename, FileManager &FileMgr, const ModuleCache &ModCache, const PCHContainerReader &PCHContainerRdr, bool FindModuleFileExtensions, ASTReaderListener &Listener, bool ValidateDiagnosticOptions, unsigned ClientLoadCapabilities=ARR_ConfigurationMismatch|ARR_OutOfDate)
Read the control block for the named AST file.
Module * getSubmodule(uint32_t GlobalID) override
Retrieve the submodule that corresponds to a global submodule ID.
void ReadExtVectorDecls(SmallVectorImpl< TypedefNameDecl * > &Decls) override
Read the set of ext_vector type declarations known to the external Sema source.
SmallVector< GlobalDeclID, 16 > PreloadedDeclIDs
Definition ASTReader.h:2606
std::pair< SourceLocation, StringRef > getModuleImportLoc(int ID) override
Retrieve the module import location and module name for the given source manager entry ID.
void ReadUnusedFileScopedDecls(SmallVectorImpl< const DeclaratorDecl * > &Decls) override
Read the set of unused file-scope declarations known to the external Sema source.
void ReadReferencedSelectors(SmallVectorImpl< std::pair< Selector, SourceLocation > > &Sels) override
Read the set of referenced selectors known to the external Sema source.
Selector DecodeSelector(serialization::SelectorID Idx)
StringRef getOriginalSourceFile()
Retrieve the name of the original source file name for the primary module file.
Definition ASTReader.h:1985
std::string ReadPath(ModuleFile &F, const RecordData &Record, unsigned &Idx)
friend class serialization::reader::ASTIdentifierLookupTrait
Definition ASTReader.h:437
unsigned getModuleFileID(ModuleFile *M)
Get an ID for the given module file.
Decl * getKeyDeclaration(Decl *D)
Returns the first key declaration for the given declaration.
Definition ASTReader.h:1476
bool FindExternalVisibleDeclsByName(const DeclContext *DC, DeclarationName Name, const DeclContext *OriginalDC) override
Finds all the visible declarations with a given name.
IdentifierInfo * DecodeIdentifierInfo(serialization::IdentifierID ID)
ASTReadResult
The result of reading the control block of an AST file, which can fail for various reasons.
Definition ASTReader.h:447
@ Success
The control block was read successfully.
Definition ASTReader.h:450
@ ConfigurationMismatch
The AST file was written with a different language/target configuration.
Definition ASTReader.h:467
@ OutOfDate
The AST file is out-of-date relative to its input files, and needs to be regenerated.
Definition ASTReader.h:460
@ Failure
The AST file itself appears corrupted.
Definition ASTReader.h:453
@ VersionMismatch
The AST file was written by a different version of Clang.
Definition ASTReader.h:463
@ HadErrors
The AST file has errors.
Definition ASTReader.h:470
@ Missing
The AST file was missing.
Definition ASTReader.h:456
static VersionTuple ReadVersionTuple(const RecordData &Record, unsigned &Idx)
Read a version tuple.
Token ReadToken(ModuleFile &M, const RecordDataImpl &Record, unsigned &Idx)
Reads a token out of a record.
SwitchCase * getSwitchCaseWithID(unsigned ID)
Retrieve the switch-case statement with the given ID.
serialization::IdentifierID getGlobalIdentifierID(ModuleFile &M, uint64_t LocalID)
FileID TranslateFileID(ModuleFile &F, FileID FID) const
Translate a FileID from another module file's FileID space into ours.
Definition ASTReader.h:2513
void ReadLateParsedTemplates(llvm::MapVector< const FunctionDecl *, std::unique_ptr< LateParsedTemplate > > &LPTMap) override
Read the set of late parsed template functions for this source.
IdentifierIterator * getIdentifiers() override
Retrieve an iterator into the set of all identifiers in all loaded AST files.
void ReadUsedVTables(SmallVectorImpl< ExternalVTableUse > &VTables) override
Read the set of used vtables known to the external Sema source.
bool isGlobalIndexUnavailable() const
Determine whether we tried to load the global index, but failed, e.g., because it is out-of-date or d...
uint32_t GetNumExternalSelectors() override
Returns the number of selectors known to the external AST source.
static TemporarilyOwnedStringRef ResolveImportedPath(SmallString< 0 > &Buf, StringRef Path, ModuleFile &ModF)
Resolve Path in the context of module file M.
void updateOutOfDateSelector(Selector Sel) override
Load the contents of the global method pool for a given selector if necessary.
Decl * GetExistingDecl(GlobalDeclID ID)
Resolve a declaration ID into a declaration.
static llvm::BitVector ReadBitVector(const RecordData &Record, const StringRef Blob)
ModuleFile * getLocalModuleFile(ModuleFile &M, unsigned ID) const
Retrieve the module file with a given local ID within the specified ModuleFile.
ASTReader(Preprocessor &PP, ModuleCache &ModCache, ASTContext *Context, const PCHContainerReader &PCHContainerRdr, const CodeGenOptions &CodeGenOpts, ArrayRef< std::shared_ptr< ModuleFileExtension > > Extensions, StringRef isysroot="", DisableValidationForModuleKind DisableValidationKind=DisableValidationForModuleKind::None, bool AllowASTWithCompilerErrors=false, bool AllowConfigurationMismatch=false, bool ValidateSystemInputs=false, bool ForceValidateUserInputs=true, bool ValidateASTInputFilesContent=false, bool UseGlobalIndex=true, std::unique_ptr< llvm::Timer > ReadTimer={})
Load the AST file and validate its contents against the given Preprocessor.
void LoadSelector(Selector Sel)
Load a selector from disk, registering its ID if it exists.
void ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag)
void makeNamesVisible(const HiddenNames &Names, Module *Owner)
Make the names within this set of hidden names visible.
void UpdateSema()
Update the state of Sema after loading some additional modules.
Decl * GetDecl(GlobalDeclID ID)
Resolve a declaration ID into a declaration, potentially building a new declaration.
Decl * GetLocalDecl(ModuleFile &F, LocalDeclID LocalID)
Reads a declaration with the given local ID in the given module.
Definition ASTReader.h:2134
int getSLocEntryID(SourceLocation::UIntTy SLocOffset) override
Get the index ID for the loaded SourceLocation offset.
SourceLocation ReadSourceLocation(ModuleFile &MF, RawLocEncoding Raw) const
Read a source location from raw form.
Definition ASTReader.h:2469
void ReadPendingInstantiations(SmallVectorImpl< std::pair< ValueDecl *, SourceLocation > > &Pending) override
Read the set of pending instantiations known to the external Sema source.
Preprocessor & getPreprocessor() const
Retrieve the preprocessor.
Definition ASTReader.h:1981
serialization::reader::LazySpecializationInfoLookupTable * getLoadedSpecializationsLookupTables(const Decl *D, bool IsPartial)
Get the loaded specializations lookup tables for D, if any.
CXXTemporary * ReadCXXTemporary(ModuleFile &F, const RecordData &Record, unsigned &Idx)
void ReadKnownNamespaces(SmallVectorImpl< NamespaceDecl * > &Namespaces) override
Load the set of namespaces that are known to the external source, which will be used during typo corr...
void PrintStats() override
Print some statistics about AST usage.
static bool isAcceptableASTFile(StringRef Filename, FileManager &FileMgr, const ModuleCache &ModCache, const PCHContainerReader &PCHContainerRdr, const LangOptions &LangOpts, const CodeGenOptions &CGOpts, const TargetOptions &TargetOpts, const PreprocessorOptions &PPOpts, const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath, bool RequireStrictOptionMatches=false)
Determine whether the given AST file is acceptable to load into a translation unit with the given lan...
void mergeDefinitionVisibility(NamedDecl *Def, NamedDecl *MergedDef)
Note that MergedDef is a redefinition of the canonical definition Def, so Def should be visible whene...
serialization::SelectorID getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const
Retrieve the global selector ID that corresponds to this the local selector ID in a given module.
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
friend class ASTRecordReader
Definition ASTReader.h:433
SmallVector< uint64_t, 64 > RecordData
Definition ASTReader.h:442
FileID ReadFileID(ModuleFile &F, const RecordDataImpl &Record, unsigned &Idx) const
Read a FileID.
Definition ASTReader.h:2507
void StartedDeserializing() override
Notify ASTReader that we started deserialization of a decl or type so until FinishedDeserializing is ...
serialization::MacroID getGlobalMacroID(ModuleFile &M, serialization::MacroID LocalID)
Retrieve the global macro ID corresponding to the given local ID within the given module file.
void ReadMethodPool(Selector Sel) override
Load the contents of the global method pool for a given selector.
void InitializeContext()
Initializes the ASTContext.
CXXBaseSpecifier * GetExternalCXXBaseSpecifiers(uint64_t Offset) override
Resolve the offset of a set of C++ base specifiers in the decl stream into an array of specifiers.
const serialization::reader::DeclContextLookupTable * getTULocalLookupTables(DeclContext *Primary) const
FileManager & getFileManager() const
Definition ASTReader.h:1810
bool wasThisDeclarationADefinition(const FunctionDecl *FD) override
True if this function declaration was a definition before in its own module.
void FinishedDeserializing() override
Notify ASTReader that we finished the deserialization of a decl or type.
void updateOutOfDateIdentifier(const IdentifierInfo &II) override
Update an out-of-date identifier.
ASTReadResult ReadAST(ModuleFileName FileName, ModuleKind Type, SourceLocation ImportLoc, unsigned ClientLoadCapabilities, ModuleFile **NewLoadedModuleFile=nullptr)
Load the AST file designated by the given file name.
void ReadDefinedMacros() override
Read the set of macros defined by this external macro source.
HeaderFileInfo GetHeaderFileInfo(FileEntryRef FE) override
Read the header file information for the given file entry.
void getMemoryBufferSizes(MemoryBufferSizes &sizes) const override
Return the amount of memory used by memory buffers, breaking down by heap-backed versus mmap'ed memor...
serialization::ModuleFile ModuleFile
Definition ASTReader.h:473
bool hasGlobalIndex() const
Determine whether this AST reader has a global index.
Definition ASTReader.h:1946
serialization::PreprocessedEntityID getGlobalPreprocessedEntityID(ModuleFile &M, serialization::PreprocessedEntityID LocalID) const
Determine the global preprocessed entity ID that corresponds to the given local ID within the given m...
An object for streaming information from a record.
bool readBool()
Read a boolean value, advancing Idx.
uint32_t readUInt32()
Read a 32-bit unsigned value; required to satisfy BasicReader.
llvm::APFloat readAPFloat(const llvm::fltSemantics &Sem)
Read an arbitrary constant value, advancing Idx.
TemplateArgumentLoc readTemplateArgumentLoc()
Reads a TemplateArgumentLoc, advancing Idx.
SourceRange readSourceRange()
Read a source range, advancing Idx.
SourceLocation readSourceLocation()
Read a source location, advancing Idx.
void readUnresolvedSet(LazyASTUnresolvedSet &Set)
Read a UnresolvedSet structure, advancing Idx.
void readTemplateArgumentList(SmallVectorImpl< TemplateArgument > &TemplArgs, bool Canonicalize=false)
Read a template argument array, advancing Idx.
void readQualifierInfo(QualifierInfo &Info)
DeclarationNameLoc readDeclarationNameLoc(DeclarationName Name)
Read a declaration name, advancing Idx.
CXXBaseSpecifier readCXXBaseSpecifier()
Read a C++ base specifier, advancing Idx.
QualType readType()
Read a type from the current position in the record.
T * readDeclAs()
Reads a declaration from the given position in the record, advancing Idx.
Expected< unsigned > readRecord(llvm::BitstreamCursor &Cursor, unsigned AbbrevID)
Reads a record with id AbbrevID from Cursor, resetting the internal state.
DeclarationNameInfo readDeclarationNameInfo()
void readTypeLoc(TypeLoc TL)
Reads the location information for a type.
IdentifierInfo * readIdentifier()
TemplateArgumentLocInfo readTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind)
Reads a TemplateArgumentLocInfo appropriate for the given TemplateArgument kind, advancing Idx.
TemplateArgument readTemplateArgument(bool Canonicalize)
ASTContext & getContext()
Retrieve the AST context that this AST reader supplements.
TypeSourceInfo * readTypeSourceInfo()
Reads a declarator info from the given record, advancing Idx.
void readTemplateArgumentListInfo(TemplateArgumentListInfo &Result)
TypeCoupledDeclRefInfo readTypeCoupledDeclRefInfo()
void skipInts(unsigned N)
Skips the specified number of values.
GlobalDeclID readDeclID()
Reads a declaration ID from the given position in this record.
NestedNameSpecifierLoc readNestedNameSpecifierLoc()
Return a nested name specifier, advancing Idx.
ConceptReference * readConceptReference()
void readOMPChildren(OMPChildren *Data)
Read an OpenMP children, advancing Idx.
OMPClause * readOMPClause()
Read an OpenMP clause, advancing Idx.
void readOpenACCClauseList(MutableArrayRef< const OpenACCClause * > Clauses)
Read a list of OpenACC clauses into the passed SmallVector, during statement reading.
OMPTraitInfo * readOMPTraitInfo()
Read an OMPTraitInfo object, advancing Idx.
TemplateParameterList * readTemplateParameterList()
Read a template parameter list, advancing Idx.
OpenACCClause * readOpenACCClause()
Read an OpenACC clause, advancing Idx.
llvm::SmallVector< Expr * > readOpenACCVarList()
Read a list of Exprs used for a var-list.
CXXCtorInitializer ** readCXXCtorInitializers()
Read a CXXCtorInitializer array, advancing Idx.
SpirvOperand readHLSLSpirvOperand()
Stmt * readStmt()
Reads a statement.
const ASTTemplateArgumentListInfo * readASTTemplateArgumentListInfo()
uint64_t readInt()
Returns the current value in this record, and advances to the next value.
Expr * readExpr()
Reads an expression.
void readOpenACCRoutineDeclAttr(OpenACCRoutineDeclAttr *A)
llvm::SmallVector< Expr * > readOpenACCIntExprList()
Read a list of Exprs used for a int-expr-list.
Expr * readSubExpr()
Reads a sub-expression operand during statement reading.
Abstracts clang modules and precompiled header files and holds everything needed to generate debug in...
Wrapper for source info for arrays.
Definition TypeLoc.h:1777
void setLBracketLoc(SourceLocation Loc)
Definition TypeLoc.h:1783
void setRBracketLoc(SourceLocation Loc)
Definition TypeLoc.h:1791
void setSizeExpr(Expr *Size)
Definition TypeLoc.h:1803
void setRParenLoc(SourceLocation Loc)
Definition TypeLoc.h:2689
void setLParenLoc(SourceLocation Loc)
Definition TypeLoc.h:2681
void setKWLoc(SourceLocation Loc)
Definition TypeLoc.h:2673
Attr - This represents one attribute.
Definition Attr.h:46
void setAttr(const Attr *A)
Definition TypeLoc.h:1034
void setConceptReference(ConceptReference *CR)
Definition TypeLoc.h:2405
void setRParenLoc(SourceLocation Loc)
Definition TypeLoc.h:2399
void setCaretLoc(SourceLocation Loc)
Definition TypeLoc.h:1532
void setWrittenTypeSpec(TypeSpecifierType written)
Definition TypeLoc.h:663
bool needsExtraLocalData() const
Definition TypeLoc.h:606
void setModeAttr(bool written)
Definition TypeLoc.h:675
void setBuiltinLoc(SourceLocation Loc)
Definition TypeLoc.h:583
void setWrittenWidthSpec(TypeSpecifierWidth written)
Definition TypeLoc.h:652
void setWrittenSignSpec(TypeSpecifierSign written)
Definition TypeLoc.h:636
Represents a base class of a C++ class.
Definition DeclCXX.h:146
Represents a C++ constructor within a class.
Definition DeclCXX.h:2620
Represents a C++ base or member initializer.
Definition DeclCXX.h:2385
void setSourceOrder(int Pos)
Set the source order of this initializer.
Definition DeclCXX.h:2572
Represents a C++ destructor within a class.
Definition DeclCXX.h:2882
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
Decl * getLambdaContextDecl() const
Retrieve the declaration that provides additional context for a lambda, when the normal declaration c...
Definition DeclCXX.cpp:1834
unsigned getLambdaIndexInContext() const
Retrieve the index of this lambda within the context declaration returned by getLambdaContextDecl().
Definition DeclCXX.h:1799
base_class_iterator bases_begin()
Definition DeclCXX.h:615
base_class_iterator vbases_begin()
Definition DeclCXX.h:632
Represents a C++ temporary.
Definition ExprCXX.h:1463
static CXXTemporary * Create(const ASTContext &C, const CXXDestructorDecl *Destructor)
Definition ExprCXX.cpp:1120
void ReadCounter(const serialization::ModuleFile &M, uint32_t Value) override
Receives COUNTER value.
bool visitInputFile(StringRef Filename, bool isSystem, bool isOverridden, bool isExplicitModule) override
if needsInputFileVisitation returns true, this is called for each non-system input file of the AST Fi...
bool ReadCodeGenOptions(const CodeGenOptions &CGOpts, StringRef ModuleFilename, bool Complain, bool AllowCompatibleDifferences) override
Receives the codegen options.
bool ReadFullVersionInformation(StringRef FullVersion) override
Receives the full Clang version information.
bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, StringRef ModuleFilename, StringRef ContextHash, bool Complain) override
Receives the header search options.
bool ReadFileSystemOptions(const FileSystemOptions &FSOpts, bool Complain) override
Receives the file system options.
void ReadModuleMapFile(StringRef ModuleMapPath) override
bool ReadLanguageOptions(const LangOptions &LangOpts, StringRef ModuleFilename, bool Complain, bool AllowCompatibleDifferences) override
Receives the language options.
void visitModuleFile(ModuleFileName Filename, serialization::ModuleKind Kind, bool DirectlyImported) override
This is called for each AST file loaded.
bool ReadTargetOptions(const TargetOptions &TargetOpts, StringRef ModuleFilename, bool Complain, bool AllowCompatibleDifferences) override
Receives the target options.
void ReadModuleName(StringRef ModuleName) override
bool needsInputFileVisitation() override
Returns true if this ASTReaderListener wants to receive the input files of the AST file via visitInpu...
bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, StringRef ModuleFilename, bool ReadMacros, bool Complain, std::string &SuggestedPredefines) override
Receives the preprocessor options.
void readModuleFileExtension(const ModuleFileExtensionMetadata &Metadata) override
Indicates that a particular module file extension has been read.
bool needsSystemInputFileVisitation() override
Returns true if this ASTReaderListener wants to receive the system input files of the AST file via vi...
bool ReadDiagnosticOptions(DiagnosticOptions &DiagOpts, StringRef ModuleFilename, bool Complain) override
Receives the diagnostic options.
CompatibilityKind
For ASTs produced with different option value, signifies their level of compatibility.
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
A reference to a concept and its template args, as it appears in the code.
Definition ASTConcept.h:130
static ConceptReference * Create(const ASTContext &C, NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc, DeclarationNameInfo ConceptNameInfo, NamedDecl *FoundDecl, TemplateDecl *NamedConcept, const ASTTemplateArgumentListInfo *ArgsAsWritten)
const TypeClass * getTypePtr() const
Definition TypeLoc.h:433
A map from continuous integer ranges to some value, with a very specialized interface.
void insertOrReplace(const value_type &Val)
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1462
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
bool hasExternalVisibleStorage() const
Whether this DeclContext has external storage containing additional declarations that are visible in ...
Definition DeclBase.h:2713
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
void setMustBuildLookupTable()
Mark that there are external lexical declarations that we need to include in our lookup table (and th...
Definition DeclBase.h:2686
bool hasExternalLexicalStorage() const
Whether this DeclContext has external storage containing additional declarations that are lexically i...
Definition DeclBase.h:2701
DeclContext * getPrimaryContext()
getPrimaryContext - There may be many different declarations of the same entity (including forward de...
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition DeclBase.h:2386
void setHasExternalLexicalStorage(bool ES=true) const
State whether this DeclContext has external storage for declarations lexically in this context.
Definition DeclBase.h:2707
bool isDeclInLexicalTraversal(const Decl *D) const
Determine whether the given declaration is stored in the list of declarations lexically within this c...
Definition DeclBase.h:2727
decl_iterator decls_begin() const
unsigned getModuleFileIndex() const
Definition DeclID.h:125
DeclID getRawValue() const
Definition DeclID.h:115
unsigned getLocalDeclIndex() const
uint64_t DeclID
An ID number that refers to a declaration in an AST file.
Definition DeclID.h:108
TypeSpecifierType TST
Definition DeclSpec.h:250
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:547
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:601
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition DeclBase.cpp:178
bool isUnconditionallyVisible() const
Determine whether this declaration is definitely visible to name lookup, independent of whether the o...
Definition DeclBase.h:867
Kind
Lists the kind of concrete classes of Decl.
Definition DeclBase.h:89
bool isCanonicalDecl() const
Whether this particular Decl is a canonical one.
Definition DeclBase.h:997
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition DeclBase.h:850
Module * getImportedOwningModule() const
Get the imported owning module, if this decl is from an imported (non-local) module.
Definition DeclBase.h:820
bool isFromASTFile() const
Determine whether this declaration came from an AST file (such as a precompiled header or module) rat...
Definition DeclBase.h:801
SourceLocation getLocation() const
Definition DeclBase.h:447
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition DeclBase.h:1062
DeclContext * getDeclContext()
Definition DeclBase.h:456
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:931
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:991
Kind getKind() const
Definition DeclBase.h:450
GlobalDeclID getGlobalID() const
Retrieve the global declaration ID associated with this declaration, which specifies where this Decl ...
Definition DeclBase.cpp:110
void setVisibleDespiteOwningModule()
Set that this declaration is globally visible, even if it came from a module that is not visible.
Definition DeclBase.h:878
DeclarationNameLoc - Additional source/type location info for a declaration name.
static DeclarationNameLoc makeNamedTypeLoc(TypeSourceInfo *TInfo)
Construct location information for a constructor, destructor or conversion operator.
static DeclarationNameLoc makeCXXLiteralOperatorNameLoc(SourceLocation Loc)
Construct location information for a literal C++ operator.
static DeclarationNameLoc makeCXXOperatorNameLoc(SourceLocation BeginLoc, SourceLocation EndLoc)
Construct location information for a non-literal C++ operator.
The name of a declaration.
IdentifierInfo * getAsIdentifierInfo() const
Retrieve the IdentifierInfo * stored in this declaration name, or null if this declaration name isn't...
TemplateDecl * getCXXDeductionGuideTemplate() const
If this name is the name of a C++ deduction guide, return the template associated with that name.
const IdentifierInfo * getCXXLiteralIdentifier() const
If this name is the name of a literal operator, retrieve the identifier associated with it.
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
NameKind
The kind of the name stored in this DeclarationName.
Selector getObjCSelector() const
Get the Objective-C selector stored in this declaration name.
NameKind getNameKind() const
Determine what kind of name this is.
Represents a ValueDecl that came out of a declarator.
Definition Decl.h:780
void setRParenLoc(SourceLocation Loc)
Definition TypeLoc.h:2291
void setDecltypeLoc(SourceLocation Loc)
Definition TypeLoc.h:2288
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition TypeLoc.h:2531
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:2513
void setTemplateNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2519
void setAttrNameLoc(SourceLocation loc)
Definition TypeLoc.h:1977
void setAttrOperandParensRange(SourceRange range)
Definition TypeLoc.h:1998
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2601
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:2581
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition TypeLoc.h:2590
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2096
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2068
A little helper class used to produce diagnostics.
bool wasUpgradedFromWarning() const
Whether this mapping attempted to map the diagnostic to a warning, but was overruled because the diag...
void setSeverity(diag::Severity Value)
static DiagnosticMapping deserialize(unsigned Bits)
Deserialize a mapping.
void setUpgradedFromWarning(bool Value)
Options for controlling the compiler diagnostics engine.
std::vector< std::string > Remarks
The list of -R... options used to alter the diagnostic mappings, with the prefixes removed.
std::vector< std::string > Warnings
The list of -W... options used to alter the diagnostic mappings, with the prefixes removed.
std::vector< std::string > SystemHeaderWarningsModules
The list of -Wsystem-headers-in-module=... options used to override whether -Wsystem-headers is enabl...
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:233
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
DiagnosticOptions & getDiagnosticOptions() const
Retrieve the diagnostic options.
Definition Diagnostic.h:603
bool getEnableAllWarnings() const
Definition Diagnostic.h:703
Level
The level of the diagnostic, after it has been through mapping.
Definition Diagnostic.h:238
Level getDiagnosticLevel(unsigned DiagID, SourceLocation Loc) const
Based on the way the client configured the DiagnosticsEngine object, classify the specified diagnosti...
Definition Diagnostic.h:975
bool getSuppressSystemWarnings() const
Definition Diagnostic.h:729
bool getWarningsAsErrors() const
Definition Diagnostic.h:711
diag::Severity getExtensionHandlingBehavior() const
Definition Diagnostic.h:819
const IntrusiveRefCntPtr< DiagnosticIDs > & getDiagnosticIDs() const
Definition Diagnostic.h:598
StringRef getName() const
void set(SourceLocation ElaboratedKeywordLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation NameLoc)
Definition TypeLoc.h:744
This represents one expression.
Definition Expr.h:112
RAII class for safely pairing a StartedDeserializing call with FinishedDeserializing.
static DeclContextLookupResult SetExternalVisibleDeclsForName(const DeclContext *DC, DeclarationName Name, ArrayRef< NamedDecl * > Decls)
uint32_t incrementGeneration(ASTContext &C)
Increment the current generation.
uint32_t getGeneration() const
Get the current generation of this AST source.
Represents difference between two FPOptions values.
static FPOptionsOverride getFromOpaqueInt(storage_type I)
FPOptions applyOverrides(FPOptions Base)
static FPOptions getFromOpaqueInt(storage_type Value)
Represents a member of a struct/union/class.
Definition Decl.h:3178
A reference to a FileEntry that includes the name of the file as it was accessed by the FileManager's...
Definition FileEntry.h:57
time_t getModificationTime() const
Definition FileEntry.h:354
off_t getSize() const
Definition FileEntry.h:346
StringRef getName() const
The name of this FileEntry.
Definition FileEntry.h:61
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
bool isValid() const
bool isInvalid() const
Implements support for file system lookup, file system caching, and directory search management.
Definition FileManager.h:53
llvm::ErrorOr< std::unique_ptr< llvm::MemoryBuffer > > getBufferForFile(FileEntryRef Entry, bool isVolatile=false, bool RequiresNullTerminator=true, std::optional< int64_t > MaybeLimit=std::nullopt, bool IsText=true)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful,...
FileEntryRef getVirtualFileRef(StringRef Filename, off_t Size, time_t ModificationTime)
Retrieve a file entry for a "virtual" file that acts as if there were a file with the given name on d...
OptionalFileEntryRef getOptionalFileRef(StringRef Filename, bool OpenFile=false, bool CacheFailure=true, bool IsText=true)
Get a FileEntryRef if it exists, without doing anything on error.
Keeps track of options that affect how file operations are performed.
std::string WorkingDir
If set, paths are resolved as if the working directory was set to the value of WorkingDir.
Represents a function declaration or definition.
Definition Decl.h:2018
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5369
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5658
Wrapper for source info for functions.
Definition TypeLoc.h:1644
unsigned getNumParams() const
Definition TypeLoc.h:1716
void setLocalRangeBegin(SourceLocation L)
Definition TypeLoc.h:1664
void setLParenLoc(SourceLocation Loc)
Definition TypeLoc.h:1680
void setParam(unsigned i, ParmVarDecl *VD)
Definition TypeLoc.h:1723
void setRParenLoc(SourceLocation Loc)
Definition TypeLoc.h:1688
void setLocalRangeEnd(SourceLocation L)
Definition TypeLoc.h:1672
void setExceptionSpecRange(SourceRange R)
Definition TypeLoc.h:1702
llvm::SmallPtrSet< ModuleFile *, 4 > HitSet
A set of module files in which we found a result.
static std::pair< GlobalModuleIndex *, llvm::Error > readIndex(llvm::StringRef Path)
Read a global index file for the given directory.
HeaderSearchOptions - Helper class for storing options related to the initialization of the HeaderSea...
uint64_t BuildSessionTimestamp
The time in seconds when the build session started.
unsigned ImplicitModuleMaps
Implicit module maps.
std::vector< SystemHeaderPrefix > SystemHeaderPrefixes
User-specified system header prefixes.
unsigned EnablePrebuiltImplicitModules
Also search for prebuilt implicit modules in the prebuilt module cache path.
unsigned ModuleMapFileHomeIsCwd
Set the 'home directory' of a module map file to the current working directory (or the home directory...
std::string Sysroot
If non-empty, the directory to use as a "virtual system root" for include paths.
std::string ModuleCachePath
The directory used for the module cache.
std::string ModuleUserBuildPath
The directory used for a user build.
std::vector< std::string > VFSOverlayFiles
The set of user-provided virtual filesystem overlay files.
unsigned UseLibcxx
Use libc++ instead of the default libstdc++.
unsigned UseBuiltinIncludes
Include the compiler builtin includes.
unsigned UseStandardCXXIncludes
Include the system standard C++ library include search directories.
std::vector< Entry > UserEntries
User specified include entries.
std::string ResourceDir
The directory which holds the compiler resource files (builtin includes, etc.).
unsigned UseStandardSystemIncludes
Include the system standard include search directories.
unsigned ModulesValidateOncePerBuildSession
If true, skip verifying input files used by modules if the module was already verified during this bu...
unsigned DisableModuleHash
Whether we should disable the use of the hash string within the module cache.
Encapsulates the information needed to find the file referenced by a #include or #include_next,...
Module * lookupModule(StringRef ModuleName, SourceLocation ImportLoc=SourceLocation(), bool AllowSearch=true, bool AllowExtraModuleMapSearch=false)
Lookup a module Search for a module with the given name.
const HeaderSearchOptions & getHeaderSearchOpts() const
Retrieve the header-search options with which this header search was initialized.
StringRef getSpecificModuleCachePath() const
Retrieve the specific module cache path.
One of these records is kept for each identifier that is lexed.
unsigned getBuiltinID() const
Return a value indicating whether this is a builtin function.
bool isCPlusPlusOperatorKeyword() const
tok::TokenKind getTokenID() const
If this is a source-language token (e.g.
bool hadMacroDefinition() const
Returns true if this identifier was #defined to some value at any moment.
void setIsPoisoned(bool Value=true)
setIsPoisoned - Mark this identifier as poisoned.
bool isFromAST() const
Return true if the identifier in its current state was loaded from an AST file.
bool isPoisoned() const
Return true if this token has been poisoned.
bool hasRevertedTokenIDToIdentifier() const
True if revertTokenIDToIdentifier() was called.
tok::NotableIdentifierKind getNotableIdentifierID() const
void setOutOfDate(bool OOD)
Set whether the information for this identifier is out of date with respect to the external source.
tok::ObjCKeywordKind getObjCKeywordID() const
Return the Objective-C keyword ID for the this identifier.
void setObjCOrBuiltinID(unsigned ID)
void revertTokenIDToIdentifier()
Revert TokenID to tok::identifier; used for GNU libstdc++ 4.2 compatibility.
bool isOutOfDate() const
Determine whether the information for this identifier is out of date with respect to the external sou...
void setChangedSinceDeserialization()
Note that this identifier has changed since it was loaded from an AST file.
void * getFETokenInfo() const
Get and set FETokenInfo.
StringRef getName() const
Return the actual identifier string.
bool isExtensionToken() const
get/setExtension - Initialize information about whether or not this language token is an extension.
An iterator that walks over all of the known identifiers in the lookup table.
IdentifierResolver - Keeps track of shadowed decls on enclosing scopes.
void RemoveDecl(NamedDecl *D)
RemoveDecl - Unlink the decl from its shadowed decl chain.
Implements an efficient mapping from strings to IdentifierInfo nodes.
llvm::MemoryBuffer * lookupPCM(llvm::StringRef Filename, off_t &Size, time_t &ModTime) const
Get a pointer to the PCM if it exists and set Size and ModTime to its on-disk size and modification t...
Record the location of an inclusion directive, such as an #include or #import statement.
InclusionKind
The kind of inclusion directives known to the preprocessor.
Represents a field injected from an anonymous union/struct into the parent scope.
Definition Decl.h:3485
Wrapper for source info for injected class names of class templates.
Definition TypeLoc.h:872
void setAmpLoc(SourceLocation Loc)
Definition TypeLoc.h:1614
CompatibilityKind
For ASTs produced with different option value, signifies their level of compatibility.
Definition LangOptions.h:83
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
clang::ObjCRuntime ObjCRuntime
SanitizerSet Sanitize
Set of enabled sanitizers.
CommentOptions CommentOpts
Options for parsing comments.
std::string OMPHostIRFile
Name of the IR file that contains the result of the OpenMP target host code generation.
std::vector< llvm::Triple > OMPTargetTriples
Triples of the OpenMP targets that the host code codegen should take into account in order to generat...
std::string CurrentModule
The name of the current module, of which the main source file is a part.
std::vector< std::string > ModuleFeatures
The names of any features to enable in module 'requires' decls in addition to the hard-coded list in ...
An UnresolvedSet-like class that might not have been loaded from the external AST source yet.
unsigned getLineTableFilenameID(StringRef Str)
void AddEntry(FileID FID, const std::vector< LineEntry > &Entries)
Add a new line entry that has already been encoded into the internal representation of the line table...
static LocalDeclID get(ASTReader &Reader, serialization::ModuleFile &MF, DeclID ID)
Record the location of a macro definition.
Encapsulates changes to the "macros namespace" (the location where the macro name became active,...
Definition MacroInfo.h:313
void setPrevious(MacroDirective *Prev)
Set previous definition of the macro with the same name.
Definition MacroInfo.h:351
Records the location of a macro expansion.
Encapsulates the data about a macro definition (e.g.
Definition MacroInfo.h:39
void setUsedForHeaderGuard(bool Val)
Definition MacroInfo.h:296
void setHasCommaPasting()
Definition MacroInfo.h:220
void setDefinitionEndLoc(SourceLocation EndLoc)
Set the location of the last token in the macro.
Definition MacroInfo.h:128
void setParameterList(ArrayRef< IdentifierInfo * > List, llvm::BumpPtrAllocator &PPAllocator)
Set the specified list of identifiers as the parameter list for this macro.
Definition MacroInfo.h:166
llvm::MutableArrayRef< Token > allocateTokens(unsigned NumTokens, llvm::BumpPtrAllocator &PPAllocator)
Definition MacroInfo.h:254
void setIsFunctionLike()
Function/Object-likeness.
Definition MacroInfo.h:200
void setIsGNUVarargs()
Definition MacroInfo.h:206
void setIsC99Varargs()
Varargs querying methods. This can only be set for function-like macros.
Definition MacroInfo.h:205
void setIsUsed(bool Val)
Set the value of the IsUsed flag.
Definition MacroInfo.h:154
void setExpansionLoc(SourceLocation Loc)
Definition TypeLoc.h:1383
void setAttrRowOperand(Expr *e)
Definition TypeLoc.h:2131
void setAttrColumnOperand(Expr *e)
Definition TypeLoc.h:2137
void setAttrOperandParensRange(SourceRange range)
Definition TypeLoc.h:2146
void setAttrNameLoc(SourceLocation loc)
Definition TypeLoc.h:2125
void setStarLoc(SourceLocation Loc)
Definition TypeLoc.h:1550
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition TypeLoc.h:1559
The module cache used for compiling modules implicitly.
Definition ModuleCache.h:37
virtual InMemoryModuleCache & getInMemoryModuleCache()=0
Returns this process's view of the module cache.
Deduplication key for a loaded module file in ModuleManager.
Definition Module.h:79
Identifies a module file to be loaded.
Definition Module.h:109
bool empty() const
Checks whether the module file name is empty.
Definition Module.h:194
static ModuleFileName makeExplicit(std::string Name)
Creates a file name for an explicit module.
Definition Module.h:142
static ModuleFileName makeInMemory(StringRef Name)
Creates a file name for an in-memory module.
Definition Module.h:134
StringRef str() const
Returns the plain module file name.
Definition Module.h:188
static ModuleFileName makeFromRaw(StringRef Name, unsigned RawKind)
Creates a file name from the raw kind value.
Definition Module.h:126
void addLinkAsDependency(Module *Mod)
Make module to use export_as as the link dependency name if enough information is available or add it...
Definition ModuleMap.cpp:64
OptionalFileEntryRef getContainingModuleMapFile(const Module *Module) const
Module * findModule(StringRef Name) const
Retrieve a module with the given name.
void setUmbrellaHeaderAsWritten(Module *Mod, FileEntryRef UmbrellaHeader, const Twine &NameAsWritten, const Twine &PathRelativeToRootModuleDirectory, SourceLocation Loc=SourceLocation())
Sets the umbrella header of the given module to the given header.
void addHeader(Module *Mod, Module::Header Header, ModuleHeaderRole Role, bool Imported=false, SourceLocation Loc=SourceLocation())
Adds this header to the given module.
OptionalFileEntryRef findUmbrellaHeaderForModule(Module *M, std::string NameAsWritten, SmallVectorImpl< char > &RelativePathName)
Find the FileEntry for an umbrella header in a module as if it was written in the module map as a hea...
void setInferredModuleAllowedBy(Module *M, FileID ModMapFID)
void setUmbrellaDirAsWritten(Module *Mod, DirectoryEntryRef UmbrellaDir, const Twine &NameAsWritten, const Twine &PathRelativeToRootModuleDirectory, SourceLocation Loc=SourceLocation())
Sets the umbrella directory of the given module to the given directory.
llvm::DenseSet< FileEntryRef > AdditionalModMapsSet
Definition ModuleMap.h:196
Module * findOrCreateModuleFirst(StringRef Name, Module *Parent, bool IsFramework, bool IsExplicit)
Call ModuleMap::findOrCreateModule and throw away the information whether the module was found or cre...
Definition ModuleMap.h:572
Module * createModule(StringRef Name, Module *Parent, bool IsFramework, bool IsExplicit)
Create new submodule, assuming it does not exist.
void resolveLinkAsDependencies(Module *Mod)
Use PendingLinkAsModule information to mark top level link names that are going to be replaced by exp...
Definition ModuleMap.cpp:53
ModuleHeaderRole
Flags describing the role of a module header.
Definition ModuleMap.h:126
Reference to a module that consists of either an existing/materialized Module object,...
Definition Module.h:275
Describes a module or submodule.
Definition Module.h:340
StringRef getTopLevelModuleName() const
Retrieve the name of the top-level module.
Definition Module.h:950
void addRequirement(StringRef Feature, bool RequiredState, const LangOptions &LangOpts, const TargetInfo &Target)
Add the given feature requirement to the list of features required by this module.
Definition Module.cpp:313
SmallVector< ExportDecl, 2 > Exports
The set of export declarations.
Definition Module.h:671
unsigned InferSubmodules
Whether we should infer submodules for this module based on the headers.
Definition Module.h:606
std::vector< std::string > ConfigMacros
The set of "configuration macros", which are macros that (intentionally) change how this module is bu...
Definition Module.h:728
unsigned IsUnimportable
Whether this module has declared itself unimportable, either because it's missing a requirement from ...
Definition Module.h:561
NameVisibilityKind NameVisibility
The visibility of names within this particular module.
Definition Module.h:651
NameVisibilityKind
Describes the visibility of the various names within a particular module.
Definition Module.h:643
@ Hidden
All of the names in this module are hidden.
Definition Module.h:645
@ AllVisible
All of the names in this module are visible.
Definition Module.h:647
const ModuleFileKey * getASTFileKey() const
The serialized AST file key for this module, if one was created.
Definition Module.h:961
SourceLocation DefinitionLoc
The location of the module definition.
Definition Module.h:346
SmallVector< UnresolvedHeaderDirective, 1 > MissingHeaders
Headers that are mentioned in the module map file but could not be found on the file system.
Definition Module.h:541
ModuleKind Kind
The kind of this module.
Definition Module.h:385
void addTopHeaderFilename(StringRef Filename)
Add a top-level header filename associated with this module.
Definition Module.h:1001
bool isUnimportable() const
Determine whether this module has been declared unimportable.
Definition Module.h:763
void setASTFileNameAndKey(ModuleFileName NewName, ModuleFileKey NewKey)
Set the serialized module file for the top-level module of this module.
Definition Module.h:967
unsigned IsSystem
Whether this is a "system" module (which assumes that all headers in it are system headers).
Definition Module.h:589
std::string Name
The name of this module.
Definition Module.h:343
const ModuleFileName * getASTFileName() const
The serialized AST file name for this module, if one was created.
Definition Module.h:955
unsigned IsExternC
Whether this is an 'extern "C"' module (which implicitly puts all headers in it within an 'extern "C"...
Definition Module.h:595
unsigned ModuleMapIsPrivate
Whether this module came from a "private" module map, found next to a regular (public) module map.
Definition Module.h:634
llvm::SmallVector< LinkLibrary, 2 > LinkLibraries
The set of libraries or frameworks to link against when an entity from this module is used.
Definition Module.h:720
SmallVector< UnresolvedExportDecl, 2 > UnresolvedExports
The set of export declarations that have yet to be resolved.
Definition Module.h:689
std::optional< Header > getUmbrellaHeaderAsWritten() const
Retrieve the umbrella header as written.
Definition Module.h:985
SmallVector< Requirement, 2 > Requirements
The set of language features required to use this module.
Definition Module.h:552
bool isHeaderLikeModule() const
Is this module have similar semantics as headers.
Definition Module.h:866
OptionalDirectoryEntryRef Directory
The build directory of this module.
Definition Module.h:394
llvm::SmallVector< ModuleRef, 2 > AffectingClangModules
The set of top-level modules that affected the compilation of this module, but were not imported.
Definition Module.h:662
unsigned NamedModuleHasInit
Whether this C++20 named modules doesn't need an initializer.
Definition Module.h:639
StringRef getPrimaryModuleInterfaceName() const
Get the primary module interface name from a partition.
Definition Module.h:905
unsigned ConfigMacrosExhaustive
Whether the set of configuration macros is exhaustive.
Definition Module.h:624
std::string PresumedModuleMapFile
The presumed file name for the module map defining this module.
Definition Module.h:398
ASTFileSignature Signature
The module signature.
Definition Module.h:407
bool isGlobalModule() const
Does this Module scope describe a fragment of the global module within some C++ module.
Definition Module.h:438
unsigned InferExportWildcard
Whether, when inferring submodules, the inferr submodules should export all modules they import (e....
Definition Module.h:616
void getExportedModules(SmallVectorImpl< Module * > &Exported) const
Appends this module's list of exported modules to Exported.
Definition Module.cpp:379
std::vector< UnresolvedConflict > UnresolvedConflicts
The list of conflicts for which the module-id has not yet been resolved.
Definition Module.h:741
unsigned IsFromModuleFile
Whether this module was loaded from a module file.
Definition Module.h:576
std::optional< DirectoryName > getUmbrellaDirAsWritten() const
Retrieve the umbrella directory as written.
Definition Module.h:977
std::string ExportAsModule
The module through which entities defined in this module will eventually be exposed,...
Definition Module.h:417
unsigned IsAvailable
Whether this module is available in the current translation unit.
Definition Module.h:572
unsigned InferExplicitSubmodules
Whether, when inferring submodules, the inferred submodules should be explicit.
Definition Module.h:611
void addSubmodule(StringRef Name, Module *Submodule)
Add a child submodule.
Definition Module.h:849
llvm::SmallVector< ModuleRef, 2 > Imports
The set of modules imported by this module, and on which this module depends.
Definition Module.h:658
std::vector< Conflict > Conflicts
The list of conflicts.
Definition Module.h:753
This represents a decl that may have a name.
Definition Decl.h:274
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
virtual void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const
Appends a human-readable name for this declaration into the given stream.
Definition Decl.cpp:1852
Represent a C++ namespace.
Definition Decl.h:592
Class that aids in the construction of nested-name-specifiers along with source-location information ...
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
A C++ nested-name-specifier augmented with source location information.
@ MicrosoftSuper
Microsoft's '__super' specifier, stored as a CXXRecordDecl* of the class it appeared in.
@ Global
The global specifier '::'. There is no stored value.
@ Namespace
A namespace-like entity, stored as a NamespaceBaseDecl*.
static std::string getOwningModuleNameForDiagnostic(const Decl *D)
Get the best name we know for the module that owns the given declaration, or an empty string if the d...
This represents the 'align' clause in the 'pragma omp allocate' directive.
This represents clause 'allocate' in the 'pragma omp ...' directives.
static OMPAllocateClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with the place for N variables.
This represents 'allocator' clause in the 'pragma omp ...' directive.
void VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C)
OMPClauseReader(ASTRecordReader &Record)
void VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C)
Class that handles post-update expression for some clauses, like 'lastprivate', 'reduction' etc.
Class that handles pre-initialization statement for some clauses, like 'schedule',...
This is a basic class for representing single OpenMP clause.
This represents 'collapse' clause in the 'pragma omp ...' directive.
This represents the 'counts' clause in the 'pragma omp split' directive.
static OMPCountsClause * CreateEmpty(const ASTContext &C, unsigned NumCounts)
Build an empty 'counts' AST node for deserialization.
This represents 'default' clause in the 'pragma omp ...' directive.
This represents 'final' clause in the 'pragma omp ...' directive.
Representation of the 'full' clause of the 'pragma omp unroll' directive.
static OMPFullClause * CreateEmpty(const ASTContext &C)
Build an empty 'full' AST node for deserialization.
This represents 'if' clause in the 'pragma omp ...' directive.
This class represents the 'looprange' clause in the 'pragma omp fuse' directive.
static OMPLoopRangeClause * CreateEmpty(const ASTContext &C)
Build an empty 'looprange' clause node.
This represents 'num_threads' clause in the 'pragma omp ...' directive.
Representation of the 'partial' clause of the 'pragma omp unroll' directive.
static OMPPartialClause * CreateEmpty(const ASTContext &C)
Build an empty 'partial' AST node for deserialization.
This class represents the 'permutation' clause in the 'pragma omp interchange' directive.
static OMPPermutationClause * CreateEmpty(const ASTContext &C, unsigned NumLoops)
Build an empty 'permutation' AST node for deserialization.
This represents 'safelen' clause in the 'pragma omp ...' directive.
This represents 'simdlen' clause in the 'pragma omp ...' directive.
This represents the 'sizes' clause in the 'pragma omp tile' directive.
static OMPSizesClause * CreateEmpty(const ASTContext &C, unsigned NumSizes)
Build an empty 'sizes' AST node for deserialization.
This represents 'threadset' clause in the 'pragma omp task ...' directive.
method_range methods() const
Definition DeclObjC.h:1016
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:1313
void setNameEndLoc(SourceLocation Loc)
Definition TypeLoc.h:1325
ObjCMethodDecl - Represents an instance or class method declaration.
Definition DeclObjC.h:140
bool hasBody() const override
Determine whether this method has a body.
Definition DeclObjC.h:523
void setLazyBody(uint64_t Offset)
Definition DeclObjC.h:528
void setStarLoc(SourceLocation Loc)
Definition TypeLoc.h:1592
void setTypeArgsRAngleLoc(SourceLocation Loc)
Definition TypeLoc.h:1196
unsigned getNumTypeArgs() const
Definition TypeLoc.h:1200
unsigned getNumProtocols() const
Definition TypeLoc.h:1230
void setTypeArgsLAngleLoc(SourceLocation Loc)
Definition TypeLoc.h:1188
void setTypeArgTInfo(unsigned i, TypeSourceInfo *TInfo)
Definition TypeLoc.h:1209
void setProtocolLAngleLoc(SourceLocation Loc)
Definition TypeLoc.h:1218
void setProtocolRAngleLoc(SourceLocation Loc)
Definition TypeLoc.h:1226
void setHasBaseTypeAsWritten(bool HasBaseType)
Definition TypeLoc.h:1258
void setProtocolLoc(unsigned i, SourceLocation Loc)
Definition TypeLoc.h:1239
The basic abstraction for the target Objective-C runtime.
Definition ObjCRuntime.h:28
Kind
The basic Objective-C runtimes that we know about.
Definition ObjCRuntime.h:31
unsigned getNumProtocols() const
Definition TypeLoc.h:932
void setProtocolLoc(unsigned i, SourceLocation Loc)
Definition TypeLoc.h:941
void setProtocolLAngleLoc(SourceLocation Loc)
Definition TypeLoc.h:918
void setProtocolRAngleLoc(SourceLocation Loc)
Definition TypeLoc.h:928
static OpenACCAsyncClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, Expr *IntExpr, SourceLocation EndLoc)
static OpenACCAttachClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCAutoClause * Create(const ASTContext &Ctx, SourceLocation BeginLoc, SourceLocation EndLoc)
static OpenACCBindClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, const IdentifierInfo *ID, SourceLocation EndLoc)
This is the base type for all OpenACC Clauses.
static OpenACCCollapseClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, bool HasForce, Expr *LoopCount, SourceLocation EndLoc)
static OpenACCCopyClause * Create(const ASTContext &C, OpenACCClauseKind Spelling, SourceLocation BeginLoc, SourceLocation LParenLoc, OpenACCModifierKind Mods, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCCopyInClause * Create(const ASTContext &C, OpenACCClauseKind Spelling, SourceLocation BeginLoc, SourceLocation LParenLoc, OpenACCModifierKind Mods, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCCopyOutClause * Create(const ASTContext &C, OpenACCClauseKind Spelling, SourceLocation BeginLoc, SourceLocation LParenLoc, OpenACCModifierKind Mods, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCCreateClause * Create(const ASTContext &C, OpenACCClauseKind Spelling, SourceLocation BeginLoc, SourceLocation LParenLoc, OpenACCModifierKind Mods, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCDefaultAsyncClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, Expr *IntExpr, SourceLocation EndLoc)
static OpenACCDefaultClause * Create(const ASTContext &C, OpenACCDefaultClauseKind K, SourceLocation BeginLoc, SourceLocation LParenLoc, SourceLocation EndLoc)
static OpenACCDeleteClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCDetachClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCDeviceClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCDeviceNumClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, Expr *IntExpr, SourceLocation EndLoc)
static OpenACCDevicePtrClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCDeviceResidentClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCDeviceTypeClause * Create(const ASTContext &C, OpenACCClauseKind K, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< DeviceTypeArgument > Archs, SourceLocation EndLoc)
static OpenACCFinalizeClause * Create(const ASTContext &Ctx, SourceLocation BeginLoc, SourceLocation EndLoc)
static OpenACCFirstPrivateClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, ArrayRef< OpenACCFirstPrivateRecipe > InitRecipes, SourceLocation EndLoc)
static OpenACCGangClause * Create(const ASTContext &Ctx, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< OpenACCGangKind > GangKinds, ArrayRef< Expr * > IntExprs, SourceLocation EndLoc)
static OpenACCHostClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCIfClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, Expr *ConditionExpr, SourceLocation EndLoc)
static OpenACCIfPresentClause * Create(const ASTContext &Ctx, SourceLocation BeginLoc, SourceLocation EndLoc)
static OpenACCIndependentClause * Create(const ASTContext &Ctx, SourceLocation BeginLoc, SourceLocation EndLoc)
static OpenACCLinkClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCNoCreateClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCNoHostClause * Create(const ASTContext &Ctx, SourceLocation BeginLoc, SourceLocation EndLoc)
static OpenACCNumGangsClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > IntExprs, SourceLocation EndLoc)
static OpenACCNumWorkersClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, Expr *IntExpr, SourceLocation EndLoc)
static OpenACCPresentClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCPrivateClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, ArrayRef< OpenACCPrivateRecipe > InitRecipes, SourceLocation EndLoc)
static OpenACCReductionClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, OpenACCReductionOperator Operator, ArrayRef< Expr * > VarList, ArrayRef< OpenACCReductionRecipeWithStorage > Recipes, SourceLocation EndLoc)
static OpenACCSelfClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, Expr *ConditionExpr, SourceLocation EndLoc)
static OpenACCSeqClause * Create(const ASTContext &Ctx, SourceLocation BeginLoc, SourceLocation EndLoc)
static OpenACCTileClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > SizeExprs, SourceLocation EndLoc)
static OpenACCUseDeviceClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCVectorClause * Create(const ASTContext &Ctx, SourceLocation BeginLoc, SourceLocation LParenLoc, Expr *IntExpr, SourceLocation EndLoc)
static OpenACCVectorLengthClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, Expr *IntExpr, SourceLocation EndLoc)
static OpenACCWaitClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, Expr *DevNumExpr, SourceLocation QueuesLoc, ArrayRef< Expr * > QueueIdExprs, SourceLocation EndLoc)
static OpenACCWorkerClause * Create(const ASTContext &Ctx, SourceLocation BeginLoc, SourceLocation LParenLoc, Expr *IntExpr, SourceLocation EndLoc)
void setAttrLoc(SourceLocation loc)
Definition TypeLoc.h:1099
This abstract interface provides operations for unwrapping containers for serialized ASTs (precompile...
bool ReadDiagnosticOptions(DiagnosticOptions &DiagOpts, StringRef ModuleFilename, bool Complain) override
Receives the diagnostic options.
bool ReadLanguageOptions(const LangOptions &LangOpts, StringRef ModuleFilename, bool Complain, bool AllowCompatibleDifferences) override
Receives the language options.
void ReadCounter(const serialization::ModuleFile &M, uint32_t Value) override
Receives COUNTER value.
bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, StringRef ModuleFilename, bool ReadMacros, bool Complain, std::string &SuggestedPredefines) override
Receives the preprocessor options.
bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, StringRef ModuleFilename, StringRef ContextHash, bool Complain) override
Receives the header search options.
bool ReadCodeGenOptions(const CodeGenOptions &CGOpts, StringRef ModuleFilename, bool Complain, bool AllowCompatibleDifferences) override
Receives the codegen options.
bool ReadTargetOptions(const TargetOptions &TargetOpts, StringRef ModuleFilename, bool Complain, bool AllowCompatibleDifferences) override
Receives the target options.
void setEllipsisLoc(SourceLocation Loc)
Definition TypeLoc.h:2633
void setEllipsisLoc(SourceLocation Loc)
Definition TypeLoc.h:2316
void setRParenLoc(SourceLocation Loc)
Definition TypeLoc.h:1415
void setLParenLoc(SourceLocation Loc)
Definition TypeLoc.h:1411
Represents a parameter to a function.
Definition Decl.h:1808
void setKWLoc(SourceLocation Loc)
Definition TypeLoc.h:2725
void setStarLoc(SourceLocation Loc)
Definition TypeLoc.h:1519
Base class that describes a preprocessed entity, which may be a preprocessor directive or macro expan...
A record of the steps taken while preprocessing a source file, including the various preprocessing di...
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
std::vector< std::string > MacroIncludes
std::vector< std::string > Includes
ObjCXXARCStandardLibraryKind ObjCXXARCStandardLibrary
The Objective-C++ ARC standard library that we should support, by providing appropriate definitions t...
std::string PCHThroughHeader
If non-empty, the filename used in an include directive in the primary source file (or command-line p...
bool DetailedRecord
Whether we should maintain a detailed record of all macro definitions and expansions.
std::string ImplicitPCHInclude
The implicit PCH included at the start of the translation unit, or empty.
bool AllowPCHWithDifferentModulesCachePath
When true, a PCH with modules cache path different to the current compilation will not be rejected.
bool UsePredefines
Initialize the preprocessor with the compiler and target specific predefines.
std::vector< std::pair< std::string, bool > > Macros
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Module * getCurrentModule()
Retrieves the module that we're currently building, if any.
HeaderSearch & getHeaderSearchInfo() const
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
@ FastWidth
The width of the "fast" qualifier mask.
Definition TypeBase.h:376
@ FastMask
The fast qualifier mask.
Definition TypeBase.h:379
void setAmpAmpLoc(SourceLocation Loc)
Definition TypeLoc.h:1628
Wrapper for source info for record types.
Definition TypeLoc.h:855
Declaration of a redeclarable template.
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
void setPreviousDecl(decl_type *PrevDecl)
Set the previous declaration.
Definition Decl.h:5348
This table allows us to fully hide how we implement multi-keyword caching.
Selector getNullarySelector(const IdentifierInfo *ID)
Selector getSelector(unsigned NumArgs, const IdentifierInfo **IIV)
Can create any sort of selector.
Selector getUnarySelector(const IdentifierInfo *ID)
Smart pointer class that efficiently represents Objective-C method names.
void * getAsOpaquePtr() const
void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method)
Add the given method to the list of globally-known methods.
GlobalMethodPool MethodPool
Method Pool - allows efficient lookup when typechecking messages to "id".
Definition SemaObjC.h:220
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:868
SemaObjC & ObjC()
Definition Sema.h:1518
void addExternalSource(IntrusiveRefCntPtr< ExternalSemaSource > E)
Registers an external source.
Definition Sema.cpp:661
IdentifierResolver IdResolver
Definition Sema.h:3519
PragmaMsStackAction
Definition Sema.h:1849
ASTReaderListenter implementation to set SuggestedPredefines of ASTReader which is required to use a ...
Definition ASTReader.h:360
bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, StringRef ModuleFilename, bool ReadMacros, bool Complain, std::string &SuggestedPredefines) override
Receives the preprocessor options.
Encodes a location in the source.
static SourceLocation getFromRawEncoding(UIntTy Encoding)
Turn a raw encoding of a SourceLocation object into a real SourceLocation.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
This class handles loading and caching of source files into memory.
SourceLocation getFileLoc(SourceLocation Loc) const
Given Loc, if it is a macro location return the expansion location or the spelling location,...
bool isBeforeInTranslationUnit(SourceLocation LHS, SourceLocation RHS) const
Determines the order of 2 source locations in the translation unit.
A trivial tuple used to represent a source range.
One instance of this struct is kept for every file loaded or used.
OptionalFileEntryRef ContentsEntry
References the file which the contents were actually loaded from.
std::optional< llvm::MemoryBufferRef > getBufferIfLoaded() const
Return the buffer, only if it has been loaded.
unsigned BufferOverridden
Indicates whether the buffer itself was provided to override the actual file contents.
OptionalFileEntryRef OrigEntry
Reference to the file entry representing this ContentCache.
Information about a FileID, basically just the logical file that it represents and include stack info...
void setHasLineDirectives()
Set the flag that indicates that this FileID has line table entries associated with it.
Stmt - This represents one statement.
Definition Stmt.h:86
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition TypeLoc.h:816
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:824
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:805
Options for controlling the target.
std::string Triple
The name of the target triple to compile for.
std::vector< std::string > Features
The list of target specific features to enable or disable – this should be a list of strings starting...
std::string ABI
If given, the name of the target ABI to use.
std::string TuneCPU
If given, the name of the target CPU to tune code for.
std::string CPU
If given, the name of the target CPU to generate code for.
std::vector< std::string > FeaturesAsWritten
The list of target specific features to enable or disable, as written on the command line.
A convenient class for passing around template argument information.
Location wrapper for a TemplateArgument.
Represents a template argument.
Expr * getAsExpr() const
Retrieve the template argument as an expression.
ArgKind
The kind of template argument we're storing.
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
@ Template
The template argument is a template name that was provided for a template template parameter.
@ StructuralValue
The template argument is a non-type template argument that can't be represented by the special-case D...
@ Pack
The template argument is actually a parameter pack.
@ TemplateExpansion
The template argument is a pack expansion of a template name that was provided for a template templat...
@ NullPtr
The template argument is a null pointer or null pointer to member that was provided for a non-type te...
@ Type
The template argument is a type.
@ Null
Represents an empty template argument, e.g., one that has not been deduced.
@ Integral
The template argument is an integral value stored in an llvm::APSInt that was provided for an integra...
@ Expression
The template argument is an expression, and we've not resolved it to one of the other forms yet,...
ArgKind getKind() const
Return the kind of stored template argument.
Stores a list of template parameters for a TemplateDecl and its derived classes.
static TemplateParameterList * Create(const ASTContext &C, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > Params, SourceLocation RAngleLoc, Expr *RequiresClause)
MutableArrayRef< TemplateArgumentLocInfo > getArgLocInfos()
Definition TypeLoc.h:1913
void set(SourceLocation ElaboratedKeywordLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKeywordLoc, SourceLocation NameLoc, SourceLocation LAngleLoc, SourceLocation RAngleLoc)
Definition TypeLoc.cpp:648
Token - This structure provides full information about a lexed token.
Definition Token.h:36
[BoundsSafety] Represents information of declarations referenced by the arguments of the counted_by a...
Definition TypeBase.h:3418
TypeLocReader(ASTRecordReader &Reader)
void VisitArrayTypeLoc(ArrayTypeLoc)
void VisitFunctionTypeLoc(FunctionTypeLoc)
void VisitTagTypeLoc(TagTypeLoc TL)
RetTy Visit(TypeLoc TyLoc)
Base wrapper for a particular "section" of type source info.
Definition TypeLoc.h:59
TypeLoc getNextTypeLoc() const
Get the next TypeLoc pointed by this TypeLoc, e.g for "int*" the TypeLoc is a PointerLoc and next Typ...
Definition TypeLoc.h:171
bool isNull() const
Definition TypeLoc.h:121
void setUnmodifiedTInfo(TypeSourceInfo *TI) const
Definition TypeLoc.h:2265
A container of type source information.
Definition TypeBase.h:8416
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition TypeLoc.h:267
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:551
The base class of the type hierarchy.
Definition TypeBase.h:1875
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9275
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3580
void setLParenLoc(SourceLocation Loc)
Definition TypeLoc.h:2208
void setTypeofLoc(SourceLocation Loc)
Definition TypeLoc.h:2200
void setRParenLoc(SourceLocation Loc)
Definition TypeLoc.h:2216
void setRParenLoc(SourceLocation Loc)
Definition TypeLoc.h:2350
void setKWLoc(SourceLocation Loc)
Definition TypeLoc.h:2344
void setUnderlyingTInfo(TypeSourceInfo *TInfo)
Definition TypeLoc.h:2356
void setLParenLoc(SourceLocation Loc)
Definition TypeLoc.h:2347
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
Represents a variable declaration or definition.
Definition Decl.h:924
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2045
Captures information about a #pragma weak directive.
Definition Weak.h:25
@ Missing
The module file is missing.
@ OutOfDate
The module file is out-of-date.
@ NewlyLoaded
The module file was just loaded in response to this call.
@ AlreadyLoaded
The module file had already been loaded.
Source location and bit offset of a declaration.
A key used when looking up entities by DeclarationName.
unsigned getHash() const
Compute a fingerprint of this key for use in on-disk hash table.
The input file that has been loaded from this AST file, along with bools indicating whether this was ...
Definition ModuleFile.h:85
OptionalFileEntryRef getFile() const
Definition ModuleFile.h:114
static InputFile getNotFound()
Definition ModuleFile.h:108
Information about a module that has been loaded by the ASTReader.
Definition ModuleFile.h:158
const PPEntityOffset * PreprocessedEntityOffsets
Definition ModuleFile.h:417
void * IdentifierLookupTable
A pointer to an on-disk hash table of opaque type IdentifierHashTable.
Definition ModuleFile.h:372
void * SelectorLookupTable
A pointer to an on-disk hash table of opaque type ASTSelectorLookupTable.
Definition ModuleFile.h:496
std::vector< std::unique_ptr< ModuleFileExtensionReader > > ExtensionReaders
The list of extension readers that are attached to this module file.
Definition ModuleFile.h:284
SourceLocation DirectImportLoc
The source location where the module was explicitly or implicitly imported in the local translation u...
Definition ModuleFile.h:274
StringRef Data
The serialized bitstream data for this file.
Definition ModuleFile.h:260
const serialization::ObjCCategoriesInfo * ObjCCategoriesMap
Array of category list location information within this module file, sorted by the definition ID.
Definition ModuleFile.h:524
uint64_t SubmodulesOffsetBase
Absolute offset of the start of the submodules block.
Definition ModuleFile.h:464
int SLocEntryBaseID
The base ID in the source manager's view of this module.
Definition ModuleFile.h:336
ModuleFileKey FileKey
The key ModuleManager used for the module file.
Definition ModuleFile.h:180
serialization::IdentifierID BaseIdentifierID
Base identifier ID for identifiers local to this module.
Definition ModuleFile.h:362
serialization::PreprocessedEntityID BasePreprocessedEntityID
Base preprocessed entity ID for preprocessed entities local to this module.
Definition ModuleFile.h:415
serialization::TypeID BaseTypeIndex
Base type ID for types local to this module as represented in the global type ID space.
Definition ModuleFile.h:544
unsigned LocalNumObjCCategoriesInMap
The number of redeclaration info entries in ObjCCategoriesMap.
Definition ModuleFile.h:527
uint64_t MacroOffsetsBase
Base file offset for the offsets in MacroOffsets.
Definition ModuleFile.h:389
const llvm::support::unaligned_uint64_t * InputFileOffsets
Relative offsets for all of the input file entries in the AST file.
Definition ModuleFile.h:299
std::vector< unsigned > PreloadIdentifierOffsets
Offsets of identifiers that we're going to preload within IdentifierTableData.
Definition ModuleFile.h:376
unsigned LocalNumIdentifiers
The number of identifiers in this AST file.
Definition ModuleFile.h:352
llvm::BitstreamCursor DeclsCursor
DeclsCursor - This is a cursor to the start of the DECLTYPES_BLOCK block.
Definition ModuleFile.h:503
const llvm::support::unaligned_uint64_t * SubmoduleOffsets
Relative offsets for all submodule entries in the AST file.
Definition ModuleFile.h:467
const unsigned char * IdentifierTableData
Actual data for the on-disk hash table of identifiers.
Definition ModuleFile.h:368
llvm::BitstreamCursor SubmodulesCursor
The cursor to the start of the submodules block.
Definition ModuleFile.h:461
uint64_t SLocEntryOffsetsBase
Base file offset for the offsets in SLocEntryOffsets.
Definition ModuleFile.h:343
llvm::BitstreamCursor InputFilesCursor
The cursor to the start of the input-files block.
Definition ModuleFile.h:293
std::vector< InputFile > InputFilesLoaded
The input files that have been loaded from this AST file.
Definition ModuleFile.h:302
serialization::SelectorID BaseSelectorID
Base selector ID for selectors local to this module.
Definition ModuleFile.h:481
llvm::SetVector< ModuleFile * > ImportedBy
List of modules which depend on this module.
Definition ModuleFile.h:552
const char * HeaderFileInfoTableData
Actual data for the on-disk hash table of header file information.
Definition ModuleFile.h:436
SourceLocation ImportLoc
The source location where this module was first imported.
Definition ModuleFile.h:277
const serialization::unaligned_decl_id_t * FileSortedDecls
Array of file-level DeclIDs sorted by file.
Definition ModuleFile.h:519
const uint32_t * SLocEntryOffsets
Offsets for all of the source location entries in the AST file.
Definition ModuleFile.h:347
llvm::BitstreamCursor MacroCursor
The cursor to the start of the preprocessor block, which stores all of the macro definitions.
Definition ModuleFile.h:382
FileID OriginalSourceFileID
The file ID for the original source file that was used to build this AST file.
Definition ModuleFile.h:203
time_t ModTime
Modification of the module file.
Definition ModuleFile.h:223
std::string ActualOriginalSourceFileName
The actual original source file name that was used to build this AST file.
Definition ModuleFile.h:199
uint64_t PreprocessorDetailStartOffset
The offset of the start of the preprocessor detail cursor.
Definition ModuleFile.h:411
std::vector< InputFileInfo > InputFileInfosLoaded
The input file infos that have been loaded from this AST file.
Definition ModuleFile.h:305
unsigned LocalNumSubmodules
The number of submodules in this module.
Definition ModuleFile.h:445
SourceLocation FirstLoc
The first source location in this module.
Definition ModuleFile.h:280
unsigned LocalTopLevelSubmoduleID
Local submodule ID of the top-level module.
Definition ModuleFile.h:455
ASTFileSignature ASTBlockHash
The signature of the AST block of the module file, this can be used to unique module files based on A...
Definition ModuleFile.h:231
uint64_t SourceManagerBlockStartOffset
The bit offset to the start of the SOURCE_MANAGER_BLOCK.
Definition ModuleFile.h:330
bool DidReadTopLevelSubmodule
Whether the top-level module has been read from the AST file.
Definition ModuleFile.h:217
std::string OriginalSourceFileName
The original source file name that was used to build the primary AST file, which may have been modifi...
Definition ModuleFile.h:195
bool isModule() const
Is this a module file for a module (rather than a PCH or similar).
Definition ModuleFile.h:570
bool HasTimestamps
Whether timestamps are included in this module file.
Definition ModuleFile.h:214
uint64_t InputFilesOffsetBase
Absolute offset of the start of the input-files block.
Definition ModuleFile.h:296
llvm::BitstreamCursor SLocEntryCursor
Cursor used to read source location entries.
Definition ModuleFile.h:327
bool RelocatablePCH
Whether this precompiled header is a relocatable PCH file.
Definition ModuleFile.h:208
const uint32_t * SelectorOffsets
Offsets into the selector lookup table's data array where each selector resides.
Definition ModuleFile.h:478
unsigned BaseDeclIndex
Base declaration index in ASTReader for declarations local to this module.
Definition ModuleFile.h:516
unsigned LocalNumSLocEntries
The number of source location entries in this AST file.
Definition ModuleFile.h:333
void * HeaderFileInfoTable
The on-disk hash table that contains information about each of the header files.
Definition ModuleFile.h:440
unsigned Index
The index of this module in the list of modules.
Definition ModuleFile.h:171
llvm::BitstreamCursor Stream
The main bitstream cursor for the main block.
Definition ModuleFile.h:263
serialization::SubmoduleID BaseSubmoduleID
Base submodule ID for submodules local to this module.
Definition ModuleFile.h:448
uint64_t SizeInBits
The size of this file, in bits.
Definition ModuleFile.h:251
const UnalignedUInt64 * TypeOffsets
Offset of each type within the bitstream, indexed by the type ID, or the representation of a Type*.
Definition ModuleFile.h:540
uint64_t GlobalBitOffset
The global bit offset (or base) of this module.
Definition ModuleFile.h:254
bool StandardCXXModule
Whether this module file is a standard C++ module.
Definition ModuleFile.h:211
unsigned LocalNumTypes
The number of types in this AST file.
Definition ModuleFile.h:536
StringRef ModuleOffsetMap
The module offset map data for this file.
Definition ModuleFile.h:288
const PPSkippedRange * PreprocessedSkippedRangeOffsets
Definition ModuleFile.h:423
uint64_t InputFilesValidationTimestamp
If non-zero, specifies the time when we last validated input files.
Definition ModuleFile.h:315
llvm::BitstreamCursor PreprocessorDetailCursor
The cursor to the start of the (optional) detailed preprocessing record block.
Definition ModuleFile.h:408
SourceLocation::UIntTy SLocEntryBaseOffset
The base offset in the source manager's view of this module.
Definition ModuleFile.h:339
bool isDirectlyImported() const
Determine whether this module was directly imported at any point during translation.
Definition ModuleFile.h:567
unsigned LocalBaseSubmoduleID
Base submodule ID for submodules local to this module within its own address space.
Definition ModuleFile.h:452
const DeclOffset * DeclOffsets
Offset of each declaration within the bitstream, indexed by the declaration ID (-1).
Definition ModuleFile.h:513
uint64_t MacroStartOffset
The offset of the start of the set of defined macros.
Definition ModuleFile.h:402
ASTFileSignature Signature
The signature of the module file, which may be used instead of the size and modification time to iden...
Definition ModuleFile.h:227
unsigned LocalNumMacros
The number of macros in this AST file.
Definition ModuleFile.h:385
const unsigned char * SelectorLookupTableData
A pointer to the character data that comprises the selector table.
Definition ModuleFile.h:489
void dump()
Dump debugging output for this module.
unsigned LocalNumDecls
The number of declarations in this AST file.
Definition ModuleFile.h:509
unsigned LocalNumHeaderFileInfos
The number of local HeaderFileInfo structures.
Definition ModuleFile.h:429
llvm::BitVector SearchPathUsage
The bit vector denoting usage of each header search entry (true = used).
Definition ModuleFile.h:234
InputFilesValidation InputFilesValidationStatus
Captures the high-level result of validating input files.
Definition ModuleFile.h:322
unsigned Generation
The generation of which this module file is a part.
Definition ModuleFile.h:244
const uint32_t * IdentifierOffsets
Offsets into the identifier table data.
Definition ModuleFile.h:359
ContinuousRangeMap< uint32_t, int, 2 > SelectorRemap
Remapping table for selector IDs in this module.
Definition ModuleFile.h:484
const uint32_t * MacroOffsets
Offsets of macros in the preprocessor block.
Definition ModuleFile.h:396
uint64_t ASTBlockStartOffset
The bit offset of the AST block of this module.
Definition ModuleFile.h:257
ModuleFileName FileName
The file name of the module file.
Definition ModuleFile.h:177
ContinuousRangeMap< uint32_t, int, 2 > SubmoduleRemap
Remapping table for submodule IDs in this module.
Definition ModuleFile.h:458
llvm::BitVector VFSUsage
The bit vector denoting usage of each VFS entry (true = used).
Definition ModuleFile.h:237
uint64_t DeclsBlockStartOffset
The offset to the start of the DECLTYPES_BLOCK block.
Definition ModuleFile.h:506
SmallVector< uint64_t, 8 > PragmaDiagMappings
Diagnostic IDs and their mappings that the user changed.
Definition ModuleFile.h:549
unsigned BasePreprocessedSkippedRangeID
Base ID for preprocessed skipped ranges local to this module.
Definition ModuleFile.h:421
unsigned LocalNumSelectors
The number of selectors new to this file.
Definition ModuleFile.h:474
ModuleKind Kind
The type of this module.
Definition ModuleFile.h:174
std::string ModuleName
The name of the module.
Definition ModuleFile.h:183
serialization::MacroID BaseMacroID
Base macro ID for macros local to this module.
Definition ModuleFile.h:399
SmallVector< uint64_t, 1 > ObjCCategories
The Objective-C category lists for categories known to this module.
Definition ModuleFile.h:531
std::string BaseDirectory
The base directory of the module.
Definition ModuleFile.h:186
llvm::SmallVector< ModuleFile *, 16 > TransitiveImports
List of modules which this modules dependent on.
Definition ModuleFile.h:563
Manages the set of modules loaded by an AST reader.
llvm::iterator_range< SmallVectorImpl< ModuleFile * >::const_iterator > pch_modules() const
A range covering the PCH and preamble module files loaded.
ModuleReverseIterator rbegin()
Reverse iterator to traverse all loaded modules.
unsigned size() const
Number of modules loaded.
Source range/offset of a preprocessed entity.
RawLocEncoding getBegin() const
Source range of a skipped preprocessor region.
RawLocEncoding getBegin() const
ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel, unsigned PriorGeneration)
ArrayRef< ObjCMethodDecl * > getInstanceMethods() const
Retrieve the instance methods found by this visitor.
ArrayRef< ObjCMethodDecl * > getFactoryMethods() const
Retrieve the instance methods found by this visitor.
static TypeIdx fromTypeID(TypeID ID)
32 aligned uint64_t in the AST file.
static std::pair< unsigned, unsigned > ReadKeyDataLength(const unsigned char *&d)
void ReadDataIntoImpl(const unsigned char *d, unsigned DataLen, data_type_builder &Val)
DeclarationNameKey ReadKeyBase(const unsigned char *&d)
internal_key_type ReadKey(const unsigned char *d, unsigned)
void ReadDataInto(internal_key_type, const unsigned char *d, unsigned DataLen, data_type_builder &Val)
static std::pair< unsigned, unsigned > ReadKeyDataLength(const unsigned char *&d)
static hash_value_type ComputeHash(const internal_key_type &a)
static internal_key_type ReadKey(const unsigned char *d, unsigned n)
Class that performs lookup for an identifier stored in an AST file.
IdentifierID ReadIdentifierID(const unsigned char *d)
data_type ReadData(const internal_key_type &k, const unsigned char *d, unsigned DataLen)
Class that performs lookup for a selector's entries in the global method pool stored in an AST file.
internal_key_type ReadKey(const unsigned char *d, unsigned)
data_type ReadData(Selector, const unsigned char *d, unsigned DataLen)
static std::pair< unsigned, unsigned > ReadKeyDataLength(const unsigned char *&d)
static hash_value_type ComputeHash(Selector Sel)
static std::pair< unsigned, unsigned > ReadKeyDataLength(const unsigned char *&d)
internal_key_type GetInternalKey(external_key_type ekey)
bool EqualKey(internal_key_ref a, internal_key_ref b)
static hash_value_type ComputeHash(internal_key_ref ikey)
data_type ReadData(internal_key_ref, const unsigned char *d, unsigned DataLen)
static internal_key_type ReadKey(const unsigned char *d, unsigned)
Class that performs lookup to specialized decls.
void ReadDataInto(internal_key_type, const unsigned char *d, unsigned DataLen, data_type_builder &Val)
static std::pair< unsigned, unsigned > ReadKeyDataLength(const unsigned char *&d)
internal_key_type ReadKey(const unsigned char *d, unsigned)
std::pair< DeclarationName, const Module * > external_key_type
void ReadDataInto(internal_key_type, const unsigned char *d, unsigned DataLen, data_type_builder &Val)
std::pair< DeclarationNameKey, unsigned > internal_key_type
internal_key_type ReadKey(const unsigned char *d, unsigned)
static hash_value_type ComputeHash(const internal_key_type &Key)
static internal_key_type GetInternalKey(const external_key_type &Key)
PredefinedTypeIDs
Predefined type IDs.
CtorInitializerType
The different kinds of data that can occur in a CtorInitializer.
const unsigned NUM_PREDEF_TYPE_IDS
The number of predefined type IDs that are reserved for the PREDEF_TYPE_* constants.
const unsigned NumSpecialTypeIDs
The number of special type IDs.
TypeCode
Record codes for each kind of type.
@ PREDEF_TYPE_LONG_ACCUM_ID
The 'long _Accum' type.
@ PREDEF_TYPE_SAMPLER_ID
OpenCL sampler type.
@ PREDEF_TYPE_INT128_ID
The '__int128_t' type.
@ PREDEF_TYPE_CHAR32_ID
The C++ 'char32_t' type.
@ PREDEF_TYPE_SAT_SHORT_ACCUM_ID
The '_Sat short _Accum' type.
@ PREDEF_TYPE_IBM128_ID
The '__ibm128' type.
@ PREDEF_TYPE_SHORT_FRACT_ID
The 'short _Fract' type.
@ PREDEF_TYPE_AUTO_RREF_DEDUCT
The "auto &&" deduction type.
@ PREDEF_TYPE_BOUND_MEMBER
The placeholder type for bound member functions.
@ PREDEF_TYPE_LONGLONG_ID
The (signed) 'long long' type.
@ PREDEF_TYPE_FRACT_ID
The '_Fract' type.
@ PREDEF_TYPE_ARC_UNBRIDGED_CAST
ARC's unbridged-cast placeholder type.
@ PREDEF_TYPE_USHORT_FRACT_ID
The 'unsigned short _Fract' type.
@ PREDEF_TYPE_SAT_ULONG_FRACT_ID
The '_Sat unsigned long _Fract' type.
@ PREDEF_TYPE_BOOL_ID
The 'bool' or '_Bool' type.
@ PREDEF_TYPE_SAT_LONG_ACCUM_ID
The '_Sat long _Accum' type.
@ PREDEF_TYPE_SAT_LONG_FRACT_ID
The '_Sat long _Fract' type.
@ PREDEF_TYPE_SAT_SHORT_FRACT_ID
The '_Sat short _Fract' type.
@ PREDEF_TYPE_CHAR_U_ID
The 'char' type, when it is unsigned.
@ PREDEF_TYPE_RESERVE_ID_ID
OpenCL reserve_id type.
@ PREDEF_TYPE_SAT_ACCUM_ID
The '_Sat _Accum' type.
@ PREDEF_TYPE_BUILTIN_FN
The placeholder type for builtin functions.
@ PREDEF_TYPE_SHORT_ACCUM_ID
The 'short _Accum' type.
@ PREDEF_TYPE_FLOAT_ID
The 'float' type.
@ PREDEF_TYPE_QUEUE_ID
OpenCL queue type.
@ PREDEF_TYPE_INT_ID
The (signed) 'int' type.
@ PREDEF_TYPE_OBJC_SEL
The ObjC 'SEL' type.
@ PREDEF_TYPE_BFLOAT16_ID
The '__bf16' type.
@ PREDEF_TYPE_WCHAR_ID
The C++ 'wchar_t' type.
@ PREDEF_TYPE_UCHAR_ID
The 'unsigned char' type.
@ PREDEF_TYPE_UACCUM_ID
The 'unsigned _Accum' type.
@ PREDEF_TYPE_SCHAR_ID
The 'signed char' type.
@ PREDEF_TYPE_CHAR_S_ID
The 'char' type, when it is signed.
@ PREDEF_TYPE_NULLPTR_ID
The type of 'nullptr'.
@ PREDEF_TYPE_ULONG_FRACT_ID
The 'unsigned long _Fract' type.
@ PREDEF_TYPE_FLOAT16_ID
The '_Float16' type.
@ PREDEF_TYPE_UINT_ID
The 'unsigned int' type.
@ PREDEF_TYPE_FLOAT128_ID
The '__float128' type.
@ PREDEF_TYPE_OBJC_ID
The ObjC 'id' type.
@ PREDEF_TYPE_CHAR16_ID
The C++ 'char16_t' type.
@ PREDEF_TYPE_ARRAY_SECTION
The placeholder type for an array section.
@ PREDEF_TYPE_ULONGLONG_ID
The 'unsigned long long' type.
@ PREDEF_TYPE_SAT_UFRACT_ID
The '_Sat unsigned _Fract' type.
@ PREDEF_TYPE_USHORT_ID
The 'unsigned short' type.
@ PREDEF_TYPE_SHORT_ID
The (signed) 'short' type.
@ PREDEF_TYPE_OMP_ARRAY_SHAPING
The placeholder type for OpenMP array shaping operation.
@ PREDEF_TYPE_DEPENDENT_ID
The placeholder type for dependent types.
@ PREDEF_TYPE_LONGDOUBLE_ID
The 'long double' type.
@ PREDEF_TYPE_DOUBLE_ID
The 'double' type.
@ PREDEF_TYPE_UINT128_ID
The '__uint128_t' type.
@ PREDEF_TYPE_HALF_ID
The OpenCL 'half' / ARM NEON __fp16 type.
@ PREDEF_TYPE_VOID_ID
The void type.
@ PREDEF_TYPE_SAT_USHORT_FRACT_ID
The '_Sat unsigned short _Fract' type.
@ PREDEF_TYPE_ACCUM_ID
The '_Accum' type.
@ PREDEF_TYPE_SAT_FRACT_ID
The '_Sat _Fract' type.
@ PREDEF_TYPE_NULL_ID
The NULL type.
@ PREDEF_TYPE_USHORT_ACCUM_ID
The 'unsigned short _Accum' type.
@ PREDEF_TYPE_CHAR8_ID
The C++ 'char8_t' type.
@ PREDEF_TYPE_UFRACT_ID
The 'unsigned _Fract' type.
@ PREDEF_TYPE_OVERLOAD_ID
The placeholder type for overloaded function sets.
@ PREDEF_TYPE_INCOMPLETE_MATRIX_IDX
A placeholder type for incomplete matrix index operations.
@ PREDEF_TYPE_UNRESOLVED_TEMPLATE
The placeholder type for unresolved templates.
@ PREDEF_TYPE_SAT_USHORT_ACCUM_ID
The '_Sat unsigned short _Accum' type.
@ PREDEF_TYPE_LONG_ID
The (signed) 'long' type.
@ PREDEF_TYPE_SAT_ULONG_ACCUM_ID
The '_Sat unsigned long _Accum' type.
@ PREDEF_TYPE_LONG_FRACT_ID
The 'long _Fract' type.
@ PREDEF_TYPE_UNKNOWN_ANY
The 'unknown any' placeholder type.
@ PREDEF_TYPE_OMP_ITERATOR
The placeholder type for OpenMP iterator expression.
@ PREDEF_TYPE_PSEUDO_OBJECT
The pseudo-object placeholder type.
@ PREDEF_TYPE_OBJC_CLASS
The ObjC 'Class' type.
@ PREDEF_TYPE_ULONG_ID
The 'unsigned long' type.
@ PREDEF_TYPE_SAT_UACCUM_ID
The '_Sat unsigned _Accum' type.
@ PREDEF_TYPE_CLK_EVENT_ID
OpenCL clk event type.
@ PREDEF_TYPE_EVENT_ID
OpenCL event type.
@ PREDEF_TYPE_ULONG_ACCUM_ID
The 'unsigned long _Accum' type.
@ PREDEF_TYPE_AUTO_DEDUCT
The "auto" deduction type.
@ DECL_CXX_BASE_SPECIFIERS
A record containing CXXBaseSpecifiers.
@ DECL_CONTEXT_TU_LOCAL_VISIBLE
A record that stores the set of declarations that are only visible to the TU.
@ DECL_CONTEXT_LEXICAL
A record that stores the set of declarations that are lexically stored within a given DeclContext.
@ DECL_CXX_CTOR_INITIALIZERS
A record containing CXXCtorInitializers.
@ DECL_CONTEXT_MODULE_LOCAL_VISIBLE
A record containing the set of declarations that are only visible from DeclContext in the same module...
@ DECL_CONTEXT_VISIBLE
A record that stores the set of declarations that are visible from a given DeclContext.
@ TYPE_EXT_QUAL
An ExtQualType record.
@ SPECIAL_TYPE_OBJC_SEL_REDEFINITION
Objective-C "SEL" redefinition type.
@ SPECIAL_TYPE_UCONTEXT_T
C ucontext_t typedef type.
@ SPECIAL_TYPE_JMP_BUF
C jmp_buf typedef type.
@ SPECIAL_TYPE_FILE
C FILE typedef type.
@ SPECIAL_TYPE_SIGJMP_BUF
C sigjmp_buf typedef type.
@ SPECIAL_TYPE_OBJC_CLASS_REDEFINITION
Objective-C "Class" redefinition type.
@ SPECIAL_TYPE_CF_CONSTANT_STRING
CFConstantString type.
@ SPECIAL_TYPE_OBJC_ID_REDEFINITION
Objective-C "id" redefinition type.
Defines the clang::TargetInfo interface.
CharacteristicKind
Indicates whether a file or directory holds normal user code, system code, or system code which is im...
internal::Matcher< T > findAll(const internal::Matcher< T > &Matcher)
Matches if the node or any descendant matches.
@ ModuleFile
The module file (.pcm). Required.
unsigned kind
All of the diagnostics that can be emitted by the frontend.
Severity
Enum values that allow the client to map NOTEs, WARNINGs, and EXTENSIONs to either Ignore (nothing),...
@ Warning
Present this diagnostic as a warning.
@ Error
Present this diagnostic as an error.
IncludeDirGroup
IncludeDirGroup - Identifies the group an include Entry belongs to, representing its relative positiv...
std::variant< struct RequiresDecl, struct HeaderDecl, struct UmbrellaDirDecl, struct ModuleDecl, struct ExcludeDecl, struct ExportDecl, struct ExportAsDecl, struct ExternModuleDecl, struct UseDecl, struct LinkDecl, struct ConfigMacrosDecl, struct ConflictDecl > Decl
All declarations that can appear in a module declaration.
llvm::OnDiskChainedHashTable< ASTSelectorLookupTrait > ASTSelectorLookupTable
The on-disk hash table used for the global method pool.
llvm::OnDiskChainedHashTable< HeaderFileInfoTrait > HeaderFileInfoLookupTable
The on-disk hash table used for known header files.
llvm::OnDiskIterableChainedHashTable< ASTIdentifierLookupTrait > ASTIdentifierLookupTable
The on-disk hash table used to contain information about all of the identifiers in the program.
@ EXTENSION_METADATA
Metadata describing this particular extension.
SubmoduleRecordTypes
Record types used within a submodule description block.
@ SUBMODULE_EXCLUDED_HEADER
Specifies a header that has been explicitly excluded from this submodule.
@ SUBMODULE_TOPHEADER
Specifies a top-level header that falls into this (sub)module.
@ SUBMODULE_PRIVATE_TEXTUAL_HEADER
Specifies a header that is private to this submodule but must be textually included.
@ SUBMODULE_HEADER
Specifies a header that falls into this (sub)module.
@ SUBMODULE_EXPORT_AS
Specifies the name of the module that will eventually re-export the entities in this module.
@ SUBMODULE_UMBRELLA_DIR
Specifies an umbrella directory.
@ SUBMODULE_UMBRELLA_HEADER
Specifies the umbrella header used to create this module, if any.
@ SUBMODULE_REQUIRES
Specifies a required feature.
@ SUBMODULE_PRIVATE_HEADER
Specifies a header that is private to this submodule.
@ SUBMODULE_IMPORTS
Specifies the submodules that are imported by this submodule.
@ SUBMODULE_CONFLICT
Specifies a conflict with another module.
@ SUBMODULE_CHILD
Specifies a direct submodule by name and ID, enabling on-demand deserialization of children without l...
@ SUBMODULE_INITIALIZERS
Specifies some declarations with initializers that must be emitted to initialize the module.
@ SUBMODULE_END
Defines the end of a single submodule. Sentinel record without any data.
@ SUBMODULE_DEFINITION
Defines the major attributes of a submodule, including its name and parent.
@ SUBMODULE_LINK_LIBRARY
Specifies a library or framework to link against.
@ SUBMODULE_CONFIG_MACRO
Specifies a configuration macro for this module.
@ SUBMODULE_EXPORTS
Specifies the submodules that are re-exported from this submodule.
@ SUBMODULE_TEXTUAL_HEADER
Specifies a header that is part of the module but must be textually included.
@ SUBMODULE_AFFECTING_MODULES
Specifies affecting modules that were not imported.
uint32_t SelectorID
An ID number that refers to an ObjC selector in an AST file.
@ SkippedInBuildSession
When the validation is skipped because it was already done in the current build session.
Definition ModuleFile.h:144
@ AllFiles
When the validation is done both for user files and system files.
Definition ModuleFile.h:148
@ Disabled
When the validation is disabled. For example, for a precompiled header.
Definition ModuleFile.h:141
@ UserFiles
When the validation is done only for user files as an optimization.
Definition ModuleFile.h:146
const unsigned int NUM_PREDEF_IDENT_IDS
The number of predefined identifier IDs.
Definition ASTBitCodes.h:66
OptionsRecordTypes
Record types that occur within the options block inside the control block.
@ FILE_SYSTEM_OPTIONS
Record code for the filesystem options table.
@ TARGET_OPTIONS
Record code for the target options table.
@ PREPROCESSOR_OPTIONS
Record code for the preprocessor options table.
@ HEADER_SEARCH_OPTIONS
Record code for the headers search options table.
@ CODEGEN_OPTIONS
Record code for the codegen options table.
@ LANGUAGE_OPTIONS
Record code for the language options table.
const unsigned int NUM_PREDEF_PP_ENTITY_IDS
The number of predefined preprocessed entity IDs.
const unsigned int NUM_PREDEF_SUBMODULE_IDS
The number of predefined submodule IDs.
@ SUBMODULE_BLOCK_ID
The block containing the submodule structure.
@ PREPROCESSOR_DETAIL_BLOCK_ID
The block containing the detailed preprocessing record.
@ AST_BLOCK_ID
The AST block, which acts as a container around the full AST block.
@ SOURCE_MANAGER_BLOCK_ID
The block containing information about the source manager.
@ CONTROL_BLOCK_ID
The control block, which contains all of the information that needs to be validated prior to committi...
@ DECLTYPES_BLOCK_ID
The block containing the definitions of all of the types and decls used within the AST file.
@ PREPROCESSOR_BLOCK_ID
The block containing information about the preprocessor.
@ COMMENTS_BLOCK_ID
The block containing comments.
@ UNHASHED_CONTROL_BLOCK_ID
A block with unhashed content.
@ EXTENSION_BLOCK_ID
A block containing a module file extension.
@ OPTIONS_BLOCK_ID
The block of configuration options, used to check that a module is being used in a configuration comp...
@ INPUT_FILES_BLOCK_ID
The block of input files, which were used as inputs to create this AST file.
unsigned StableHashForTemplateArguments(llvm::ArrayRef< TemplateArgument > Args)
Calculate a stable hash value for template arguments.
CommentRecordTypes
Record types used within a comments block.
DeclIDBase::DeclID DeclID
An ID number that refers to a declaration in an AST file.
Definition ASTBitCodes.h:70
@ SM_SLOC_FILE_ENTRY
Describes a source location entry (SLocEntry) for a file.
@ SM_SLOC_BUFFER_BLOB_COMPRESSED
Describes a zlib-compressed blob that contains the data for a buffer entry.
@ SM_SLOC_BUFFER_ENTRY
Describes a source location entry (SLocEntry) for a buffer.
@ SM_SLOC_BUFFER_BLOB
Describes a blob that contains the data for a buffer entry.
@ SM_SLOC_EXPANSION_ENTRY
Describes a source location entry (SLocEntry) for a macro expansion.
const unsigned int NUM_PREDEF_SELECTOR_IDS
The number of predefined selector IDs.
bool needsAnonymousDeclarationNumber(const NamedDecl *D)
Determine whether the given declaration needs an anonymous declaration number.
const unsigned VERSION_MAJOR
AST file major version number supported by this version of Clang.
Definition ASTBitCodes.h:47
uint64_t PreprocessedEntityID
An ID number that refers to an entity in the detailed preprocessing record.
llvm::support::detail::packed_endian_specific_integral< serialization::DeclID, llvm::endianness::native, llvm::support::unaligned > unaligned_decl_id_t
PreprocessorRecordTypes
Record types used within a preprocessor block.
@ PP_TOKEN
Describes one token.
@ PP_MACRO_FUNCTION_LIKE
A function-like macro definition.
@ PP_MACRO_OBJECT_LIKE
An object-like macro definition.
@ PP_MACRO_DIRECTIVE_HISTORY
The macro directives history for a particular identifier.
@ PP_MODULE_MACRO
A macro directive exported by a module.
ControlRecordTypes
Record types that occur within the control block.
@ MODULE_MAP_FILE
Record code for the module map file that was used to build this AST file.
@ MODULE_DIRECTORY
Record code for the module build directory.
@ ORIGINAL_FILE_ID
Record code for file ID of the file or buffer that was used to generate the AST file.
@ MODULE_NAME
Record code for the module name.
@ ORIGINAL_FILE
Record code for the original file that was used to generate the AST file, including both its file ID ...
@ IMPORT
Record code for another AST file imported by this AST file.
@ INPUT_FILE_OFFSETS
Offsets into the input-files block where input files reside.
@ METADATA
AST file metadata, including the AST file version number and information about the compiler used to b...
UnhashedControlBlockRecordTypes
Record codes for the unhashed control block.
@ DIAGNOSTIC_OPTIONS
Record code for the diagnostic options table.
@ HEADER_SEARCH_ENTRY_USAGE
Record code for the indices of used header search entries.
@ AST_BLOCK_HASH
Record code for the content hash of the AST block.
@ DIAG_PRAGMA_MAPPINGS
Record code for #pragma diagnostic mappings.
@ SIGNATURE
Record code for the signature that identifiers this AST file.
@ HEADER_SEARCH_PATHS
Record code for the headers search paths.
@ VFS_USAGE
Record code for the indices of used VFSs.
uint64_t MacroID
An ID number that refers to a macro in an AST file.
InputFileRecordTypes
Record types that occur within the input-files block inside the control block.
@ INPUT_FILE_HASH
The input file content hash.
@ INPUT_FILE
An input file.
uint64_t TypeID
An ID number that refers to a type in an AST file.
Definition ASTBitCodes.h:88
PreprocessorDetailRecordTypes
Record types used within a preprocessor detail block.
@ PPD_INCLUSION_DIRECTIVE
Describes an inclusion directive within the preprocessing record.
@ PPD_MACRO_EXPANSION
Describes a macro expansion within the preprocessing record.
@ PPD_MACRO_DEFINITION
Describes a macro definition within the preprocessing record.
ModuleKind
Specifies the kind of module that has been loaded.
Definition ModuleFile.h:44
@ MK_PCH
File is a PCH file treated as such.
Definition ModuleFile.h:52
@ MK_Preamble
File is a PCH file treated as the preamble.
Definition ModuleFile.h:55
@ MK_MainFile
File is a PCH file treated as the actual main file.
Definition ModuleFile.h:58
@ MK_ExplicitModule
File is an explicitly-loaded module.
Definition ModuleFile.h:49
@ MK_ImplicitModule
File is an implicitly-loaded module.
Definition ModuleFile.h:46
@ MK_PrebuiltModule
File is from a prebuilt module path.
Definition ModuleFile.h:61
uint32_t SubmoduleID
An ID number that refers to a submodule in a module file.
const unsigned int NUM_PREDEF_MACRO_IDS
The number of predefined macro IDs.
ASTRecordTypes
Record types that occur within the AST block itself.
@ DECL_UPDATE_OFFSETS
Record for offsets of DECL_UPDATES records for declarations that were modified after being deserializ...
@ STATISTICS
Record code for the extra statistics we gather while generating an AST file.
@ FLOAT_CONTROL_PRAGMA_OPTIONS
Record code for #pragma float_control options.
@ KNOWN_NAMESPACES
Record code for the set of known namespaces, which are used for typo correction.
@ SPECIAL_TYPES
Record code for the set of non-builtin, special types.
@ PENDING_IMPLICIT_INSTANTIATIONS
Record code for pending implicit instantiations.
@ TYPE_OFFSET
Record code for the offsets of each type.
@ DELEGATING_CTORS
The list of delegating constructor declarations.
@ PP_ASSUME_NONNULL_LOC
ID 66 used to be the list of included files.
@ EXT_VECTOR_DECLS
Record code for the set of ext_vector type names.
@ OPENCL_EXTENSIONS
Record code for enabled OpenCL extensions.
@ FP_PRAGMA_OPTIONS
Record code for floating point #pragma options.
@ PP_UNSAFE_BUFFER_USAGE
Record code for #pragma clang unsafe_buffer_usage begin/end.
@ CXX_ADDED_TEMPLATE_PARTIAL_SPECIALIZATION
@ DECLS_WITH_EFFECTS_TO_VERIFY
Record code for Sema's vector of functions/blocks with effects to be verified.
@ VTABLE_USES
Record code for the array of VTable uses.
@ LATE_PARSED_TEMPLATE
Record code for late parsed template functions.
@ DECLS_TO_CHECK_FOR_DEFERRED_DIAGS
Record code for the Decls to be checked for deferred diags.
@ SUBMODULE_METADATA
Record that encodes the number of submodules, their base ID in the AST file, and for each module the ...
@ DECL_OFFSET
Record code for the offsets of each decl.
@ SOURCE_MANAGER_LINE_TABLE
Record code for the source manager line table information, which stores information about #line direc...
@ PP_COUNTER_VALUE
The value of the next COUNTER to dispense.
@ DELETE_EXPRS_TO_ANALYZE
Delete expressions that will be analyzed later.
@ EXTNAME_UNDECLARED_IDENTIFIERS
Record code for extname-redefined undeclared identifiers.
@ RELATED_DECLS_MAP
Record code for related declarations that have to be deserialized together from the same module.
@ UPDATE_VISIBLE
Record code for an update to a decl context's lookup table.
@ CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH
Number of unmatched pragma clang cuda_force_host_device begin directives we've seen.
@ MACRO_OFFSET
Record code for the table of offsets of each macro ID.
@ PPD_ENTITIES_OFFSETS
Record code for the table of offsets to entries in the preprocessing record.
@ RISCV_VECTOR_INTRINSICS_PRAGMA
Record code for pragma clang riscv intrinsic vector.
@ VTABLES_TO_EMIT
Record code for vtables to emit.
@ IDENTIFIER_OFFSET
Record code for the table of offsets of each identifier ID.
@ OBJC_CATEGORIES
Record code for the array of Objective-C categories (including extensions).
@ METHOD_POOL
Record code for the Objective-C method pool,.
@ DELAYED_NAMESPACE_LEXICAL_VISIBLE_RECORD
Record code for lexical and visible block for delayed namespace in reduced BMI.
@ PP_CONDITIONAL_STACK
The stack of open ifs/ifdefs recorded in a preamble.
@ REFERENCED_SELECTOR_POOL
Record code for referenced selector pool.
@ SOURCE_LOCATION_OFFSETS
Record code for the table of offsets into the block of source-location information.
@ WEAK_UNDECLARED_IDENTIFIERS
Record code for weak undeclared identifiers.
@ UNDEFINED_BUT_USED
Record code for undefined but used functions and variables that need a definition in this TU.
@ FILE_SORTED_DECLS
Record code for a file sorted array of DeclIDs in a module.
@ MSSTRUCT_PRAGMA_OPTIONS
Record code for #pragma ms_struct options.
@ TENTATIVE_DEFINITIONS
Record code for the array of tentative definitions.
@ UNUSED_FILESCOPED_DECLS
Record code for the array of unused file scoped decls.
@ ALIGN_PACK_PRAGMA_OPTIONS
Record code for #pragma align/pack options.
@ IMPORTED_MODULES
Record code for an array of all of the (sub)modules that were imported by the AST file.
@ SELECTOR_OFFSETS
Record code for the table of offsets into the Objective-C method pool.
@ UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES
Record code for potentially unused local typedef names.
@ EAGERLY_DESERIALIZED_DECLS
Record code for the array of eagerly deserialized decls.
@ INTERESTING_IDENTIFIERS
A list of "interesting" identifiers.
@ HEADER_SEARCH_TABLE
Record code for header search information.
@ OBJC_CATEGORIES_MAP
Record code for map of Objective-C class definition IDs to the ObjC categories in a module that are a...
@ CUDA_SPECIAL_DECL_REFS
Record code for special CUDA declarations.
@ TU_UPDATE_LEXICAL
Record code for an update to the TU's lexically contained declarations.
@ PPD_SKIPPED_RANGES
A table of skipped ranges within the preprocessing record.
@ IDENTIFIER_TABLE
Record code for the identifier table.
@ SEMA_DECL_REFS
Record code for declarations that Sema keeps references of.
@ OPTIMIZE_PRAGMA_OPTIONS
Record code for #pragma optimize options.
@ MODULE_OFFSET_MAP
Record code for the remapping information used to relate loaded modules to the various offsets and ID...
@ POINTERS_TO_MEMBERS_PRAGMA_OPTIONS
Record code for #pragma ms_struct options.
unsigned ComputeHash(Selector Sel)
TypeID LocalTypeID
Same with TypeID except that the LocalTypeID is only meaningful with the corresponding ModuleFile.
Definition ASTBitCodes.h:94
uint64_t IdentifierID
An ID number that refers to an identifier in an AST file.
Definition ASTBitCodes.h:63
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition TokenKinds.h:25
The JSON file list parser is used to communicate input to InstallAPI.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
OpenACCReductionOperator
bool isa(CodeGen::Address addr)
Definition Address.h:330
CustomizableOptional< FileEntryRef > OptionalFileEntryRef
Definition FileEntry.h:208
SanitizerMask getPPTransparentSanitizers()
Return the sanitizers which do not affect preprocessing.
Definition Sanitizers.h:230
@ CPlusPlus
OpenMPDefaultClauseVariableCategory
OpenMP variable-category for 'default' clause.
OpenACCModifierKind
OpenMPDefaultmapClauseModifier
OpenMP modifiers for 'defaultmap' clause.
OpenMPOrderClauseModifier
OpenMP modifiers for 'order' clause.
std::vector< std::string > Macros
A list of macros of the form <definition>=<expansion> .
Definition Format.h:3951
@ Success
Annotation was successful.
Definition Parser.h:65
std::pair< FileID, unsigned > FileIDAndOffset
OpenMPAtClauseKind
OpenMP attributes for 'at' clause.
OpenMPReductionClauseModifier
OpenMP modifiers for 'reduction' clause.
OpenACCClauseKind
Represents the kind of an OpenACC clause.
@ Auto
'auto' clause, allowed on 'loop' directives.
@ Bind
'bind' clause, allowed on routine constructs.
@ Gang
'gang' clause, allowed on 'loop' and Combined constructs.
@ Wait
'wait' clause, allowed on Compute, Data, 'update', and Combined constructs.
@ DevicePtr
'deviceptr' clause, allowed on Compute and Combined Constructs, plus 'data' and 'declare'.
@ PCopyOut
'copyout' clause alias 'pcopyout'. Preserved for diagnostic purposes.
@ VectorLength
'vector_length' clause, allowed on 'parallel', 'kernels', 'parallel loop', and 'kernels loop' constru...
@ Async
'async' clause, allowed on Compute, Data, 'update', 'wait', and Combined constructs.
@ PresentOrCreate
'create' clause alias 'present_or_create'.
@ Collapse
'collapse' clause, allowed on 'loop' and Combined constructs.
@ NoHost
'nohost' clause, allowed on 'routine' directives.
@ PresentOrCopy
'copy' clause alias 'present_or_copy'. Preserved for diagnostic purposes.
@ DeviceNum
'device_num' clause, allowed on 'init', 'shutdown', and 'set' constructs.
@ Private
'private' clause, allowed on 'parallel', 'serial', 'loop', 'parallel loop', and 'serial loop' constru...
@ Invalid
Represents an invalid clause, for the purposes of parsing.
@ Vector
'vector' clause, allowed on 'loop', Combined, and 'routine' directives.
@ Copy
'copy' clause, allowed on Compute and Combined Constructs, plus 'data' and 'declare'.
@ Worker
'worker' clause, allowed on 'loop', Combined, and 'routine' directives.
@ Create
'create' clause, allowed on Compute and Combined constructs, plus 'data', 'enter data',...
@ DeviceType
'device_type' clause, allowed on Compute, 'data', 'init', 'shutdown', 'set', update',...
@ DefaultAsync
'default_async' clause, allowed on 'set' construct.
@ Attach
'attach' clause, allowed on Compute and Combined constructs, plus 'data' and 'enter data'.
@ Shortloop
'shortloop' is represented in the ACC.td file, but isn't present in the standard.
@ NumGangs
'num_gangs' clause, allowed on 'parallel', 'kernels', parallel loop', and 'kernels loop' constructs.
@ If
'if' clause, allowed on all the Compute Constructs, Data Constructs, Executable Constructs,...
@ Default
'default' clause, allowed on parallel, serial, kernel (and compound) constructs.
@ UseDevice
'use_device' clause, allowed on 'host_data' construct.
@ NoCreate
'no_create' clause, allowed on allowed on Compute and Combined constructs, plus 'data'.
@ PresentOrCopyOut
'copyout' clause alias 'present_or_copyout'.
@ Link
'link' clause, allowed on 'declare' construct.
@ Reduction
'reduction' clause, allowed on Parallel, Serial, Loop, and the combined constructs.
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
@ CopyOut
'copyout' clause, allowed on Compute and Combined constructs, plus 'data', 'exit data',...
@ Seq
'seq' clause, allowed on 'loop' and 'routine' directives.
@ FirstPrivate
'firstprivate' clause, allowed on 'parallel', 'serial', 'parallel loop', and 'serial loop' constructs...
@ Host
'host' clause, allowed on 'update' construct.
@ PCopy
'copy' clause alias 'pcopy'. Preserved for diagnostic purposes.
@ Tile
'tile' clause, allowed on 'loop' and Combined constructs.
@ PCopyIn
'copyin' clause alias 'pcopyin'. Preserved for diagnostic purposes.
@ DeviceResident
'device_resident' clause, allowed on the 'declare' construct.
@ PCreate
'create' clause alias 'pcreate'. Preserved for diagnostic purposes.
@ Present
'present' clause, allowed on Compute and Combined constructs, plus 'data' and 'declare'.
@ DType
'dtype' clause, an alias for 'device_type', stored separately for diagnostic purposes.
@ CopyIn
'copyin' clause, allowed on Compute and Combined constructs, plus 'data', 'enter data',...
@ Device
'device' clause, allowed on the 'update' construct.
@ Independent
'independent' clause, allowed on 'loop' directives.
@ NumWorkers
'num_workers' clause, allowed on 'parallel', 'kernels', parallel loop', and 'kernels loop' constructs...
@ IfPresent
'if_present' clause, allowed on 'host_data' and 'update' directives.
@ Detach
'detach' clause, allowed on the 'exit data' construct.
@ Delete
'delete' clause, allowed on the 'exit data' construct.
@ PresentOrCopyIn
'copyin' clause alias 'present_or_copyin'.
@ Finalize
'finalize' clause, allowed on 'exit data' directive.
OpenMPScheduleClauseModifier
OpenMP modifiers for 'schedule' clause.
Definition OpenMPKinds.h:39
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition Specifiers.h:124
SmallVector< Attr *, 4 > AttrVec
AttrVec - A vector of Attr, which is how they are stored on the AST.
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
OpenMPDistScheduleClauseKind
OpenMP attributes for 'dist_schedule' clause.
OpenMPDoacrossClauseModifier
OpenMP dependence types for 'doacross' clause.
OpenACCDefaultClauseKind
static constexpr unsigned NumberOfOMPMapClauseModifiers
Number of allowed map-type-modifiers.
Definition OpenMPKinds.h:88
OpenMPDynGroupprivateClauseFallbackModifier
@ Module
Module linkage, which indicates that the entity can be referred to from other translation units withi...
Definition Linkage.h:54
ObjCXXARCStandardLibraryKind
Enumerate the kinds of standard library that.
PredefinedDeclIDs
Predefined declaration IDs.
Definition DeclID.h:31
@ PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID
The internal '__NSConstantString' tag type.
Definition DeclID.h:78
@ PREDEF_DECL_TRANSLATION_UNIT_ID
The translation unit.
Definition DeclID.h:36
@ PREDEF_DECL_OBJC_CLASS_ID
The Objective-C 'Class' type.
Definition DeclID.h:45
@ PREDEF_DECL_BUILTIN_MS_GUID_ID
The predeclared '_GUID' struct.
Definition DeclID.h:69
@ PREDEF_DECL_BUILTIN_MS_TYPE_INFO_TAG_ID
The predeclared 'type_info' struct.
Definition DeclID.h:81
@ PREDEF_DECL_OBJC_INSTANCETYPE_ID
The internal 'instancetype' typedef.
Definition DeclID.h:57
@ PREDEF_DECL_OBJC_PROTOCOL_ID
The Objective-C 'Protocol' type.
Definition DeclID.h:48
@ PREDEF_DECL_UNSIGNED_INT_128_ID
The unsigned 128-bit integer type.
Definition DeclID.h:54
@ PREDEF_DECL_OBJC_SEL_ID
The Objective-C 'SEL' type.
Definition DeclID.h:42
@ NUM_PREDEF_DECL_IDS
The number of declaration IDs that are predefined.
Definition DeclID.h:87
@ PREDEF_DECL_INT_128_ID
The signed 128-bit integer type.
Definition DeclID.h:51
@ PREDEF_DECL_VA_LIST_TAG
The internal '__va_list_tag' struct, if any.
Definition DeclID.h:63
@ PREDEF_DECL_BUILTIN_MS_VA_LIST_ID
The internal '__builtin_ms_va_list' typedef.
Definition DeclID.h:66
@ PREDEF_DECL_CF_CONSTANT_STRING_ID
The internal '__NSConstantString' typedef.
Definition DeclID.h:75
@ PREDEF_DECL_NULL_ID
The NULL declaration.
Definition DeclID.h:33
@ PREDEF_DECL_BUILTIN_VA_LIST_ID
The internal '__builtin_va_list' typedef.
Definition DeclID.h:60
@ PREDEF_DECL_EXTERN_C_CONTEXT_ID
The extern "C" context.
Definition DeclID.h:72
@ PREDEF_DECL_OBJC_ID_ID
The Objective-C 'id' type.
Definition DeclID.h:39
@ Property
The type of a property.
Definition TypeBase.h:911
@ Result
The result type of a method or function.
Definition TypeBase.h:905
OpenMPBindClauseKind
OpenMP bindings for the 'bind' clause.
OptionalUnsigned< unsigned > UnsignedOrNone
std::string createSpecificModuleCachePath(FileManager &FileMgr, StringRef ModuleCachePath, bool DisableModuleHash, std::string ContextHash)
OpenMPLastprivateModifier
OpenMP 'lastprivate' clause modifier.
@ Template
We are parsing a template declaration.
Definition Parser.h:81
OpenMPDependClauseKind
OpenMP attributes for 'depend' clause.
Definition OpenMPKinds.h:55
OpenMPGrainsizeClauseModifier
OpenMPNumTasksClauseModifier
OpenMPUseDevicePtrFallbackModifier
OpenMP 6.1 use_device_ptr fallback modifier.
OpenMPSeverityClauseKind
OpenMP attributes for 'severity' clause.
void ProcessWarningOptions(DiagnosticsEngine &Diags, const DiagnosticOptions &Opts, llvm::vfs::FileSystem &VFS, bool ReportDiags=true)
ProcessWarningOptions - Initialize the diagnostic client and process the warning options specified on...
Definition Warnings.cpp:46
static constexpr unsigned NumberOfOMPMotionModifiers
Number of allowed motion-modifiers.
TypeSpecifierWidth
Specifies the width of a type, e.g., short, long, or long long.
Definition Specifiers.h:48
OpenMPMotionModifierKind
OpenMP modifier kind for 'to' or 'from' clause.
Definition OpenMPKinds.h:92
PragmaMSStructKind
Definition PragmaKinds.h:23
OpenMPDefaultmapClauseKind
OpenMP attributes for 'defaultmap' clause.
OpenMPAllocateClauseModifier
OpenMP modifiers for 'allocate' clause.
OpenMPLinearClauseKind
OpenMP attributes for 'linear' clause.
Definition OpenMPKinds.h:63
llvm::omp::Directive OpenMPDirectiveKind
OpenMP directives.
Definition OpenMPKinds.h:25
TypeSpecifierSign
Specifies the signedness of a type, e.g., signed or unsigned.
Definition Specifiers.h:51
OpenMPDynGroupprivateClauseModifier
DisableValidationForModuleKind
Whether to disable the normal validation performed on precompiled headers and module files when they ...
@ None
Perform validation, don't disable it.
@ PCH
Disable validation for a precompiled header and the modules it depends on.
@ Module
Disable validation for module files.
bool shouldSkipCheckingODR(const Decl *D)
Definition ASTReader.h:2703
std::string getClangFullRepositoryVersion()
Retrieves the full repository version that is an amalgamation of the information in getClangRepositor...
Definition Version.cpp:68
OpenMPNumThreadsClauseModifier
OpenMPAtomicDefaultMemOrderClauseKind
OpenMP attributes for 'atomic_default_mem_order' clause.
U cast(CodeGen::Address addr)
Definition Address.h:327
@ None
The alignment was not explicit in code.
Definition ASTContext.h:180
OpenMPDeviceClauseModifier
OpenMP modifiers for 'device' clause.
Definition OpenMPKinds.h:48
OpenMPMapModifierKind
OpenMP modifier kind for 'map' clause.
Definition OpenMPKinds.h:79
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5982
llvm::omp::Clause OpenMPClauseKind
OpenMP clauses.
Definition OpenMPKinds.h:28
OpenMPOrderClauseKind
OpenMP attributes for 'order' clause.
OpenMPScheduleClauseKind
OpenMP attributes for 'schedule' clause.
Definition OpenMPKinds.h:31
OpenMPThreadsetKind
OpenMP modifiers for 'threadset' clause.
UnsignedOrNone getPrimaryModuleHash(const Module *M)
Calculate a hash value for the primary module name of the given module.
OpenMPMapClauseKind
OpenMP mapping kind for 'map' clause.
Definition OpenMPKinds.h:71
unsigned long uint64_t
unsigned int uint32_t
#define true
Definition stdbool.h:25
__LIBC_ATTRS FILE * stderr
This structure contains all sizes needed for by an OMPMappableExprListClause.
unsigned NumComponents
Total number of expression components.
unsigned NumUniqueDeclarations
Number of unique base declarations.
unsigned NumVars
Number of expressions listed.
unsigned NumComponentLists
Number of component lists.
Expr * AllocatorTraits
Allocator traits.
SourceLocation LParenLoc
Locations of '(' and ')' symbols.
The signature of a module, which is a hash of the AST content.
Definition Module.h:198
static constexpr size_t size
Definition Module.h:201
static ASTFileSignature create(std::array< uint8_t, 20 > Bytes)
Definition Module.h:221
static ASTFileSignature createDummy()
Definition Module.h:231
Represents an explicit template argument list in C++, e.g., the "<int>" in "sort<int>".
static const ASTTemplateArgumentListInfo * Create(const ASTContext &C, const TemplateArgumentListInfo &List)
bool ParseAllComments
Treat ordinary comments as documentation comments.
BlockCommandNamesTy BlockCommandNames
Command names to treat as block commands in comments.
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
DeclarationName getName() const
getName - Returns the embedded declaration name.
void setLoc(SourceLocation L)
setLoc - Sets the main location of the declaration name.
void setInfo(const DeclarationNameLoc &Info)
void setName(DeclarationName N)
setName - Sets the embedded declaration name.
A simple structure that captures a vtable use for the purposes of the ExternalSemaSource.
The preprocessor keeps track of this information for each file that is #included.
void mergeModuleMembership(ModuleMap::ModuleHeaderRole Role)
Update the module membership bits based on the header role.
LazyIdentifierInfoPtr LazyControllingMacro
If this file has a #ifndef XXX (or equivalent) guard that protects the entire contents of the file,...
unsigned DirInfo
Keep track of whether this is a system header, and if so, whether it is C++ clean or not.
unsigned isPragmaOnce
True if this is a #pragma once file.
unsigned IsValid
Whether this file has been looked up as a header.
unsigned isImport
True if this is a #import'd file.
unsigned External
Whether this header file info was supplied by an external source, and has not changed since.
static LineEntry get(unsigned Offs, unsigned Line, int Filename, SrcMgr::CharacteristicKind FileKind, unsigned IncludeOffset)
Metadata for a module file extension.
unsigned MajorVersion
The major version of the extension data.
std::string UserInfo
A string containing additional user information that will be stored with the metadata.
std::string BlockName
The name used to identify this particular extension block within the resulting module file.
unsigned MinorVersion
The minor version of the extension data.
A conflict between two modules.
Definition Module.h:744
std::string Message
The message provided to the user when there is a conflict.
Definition Module.h:749
ModuleRef Other
The module that this module conflicts with.
Definition Module.h:746
Information about a header directive as found in the module map file.
Definition Module.h:487
A library or framework to link against when an entity from this module is used.
Definition Module.h:703
a linked list of methods with the same selector name but different signatures.
ObjCMethodList * getNext() const
A struct with extended info about a syntactic name qualifier, to be used for the case of out-of-line ...
Definition Decl.h:753
TemplateParameterList ** TemplParamLists
A new-allocated array of size NumTemplParamLists, containing pointers to the "outer" template paramet...
Definition Decl.h:767
NestedNameSpecifierLoc QualifierLoc
Definition Decl.h:754
unsigned NumTemplParamLists
The number of "outer" template parameter lists.
Definition Decl.h:760
void clear(SanitizerMask K=SanitizerKind::All)
Disable the sanitizers specified in K.
Definition Sanitizers.h:195
SanitizerMask Mask
Bitmask of enabled sanitizers.
Definition Sanitizers.h:201
Helper class that saves the current stream position and then restores it when destroyed.
PragmaMsStackAction Action
Definition Sema.h:1860
llvm::DenseSet< std::tuple< Decl *, Decl *, int > > NonEquivalentDeclSet
Store declaration pairs already found to be non-equivalent.
Location information for a TemplateArgument.
Describes a single change detected in a module file or input file.
Definition ModuleFile.h:125
The input file info that has been loaded from an AST file.
Definition ModuleFile.h:65
Describes the categories of an Objective-C class.
MultiOnDiskHashTable< LazySpecializationInfoLookupTrait > Table
#define log(__x)
Definition tgmath.h:460