clang 22.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/Decl.h"
23#include "clang/AST/DeclBase.h"
24#include "clang/AST/DeclCXX.h"
26#include "clang/AST/DeclGroup.h"
27#include "clang/AST/DeclObjC.h"
30#include "clang/AST/Expr.h"
31#include "clang/AST/ExprCXX.h"
40#include "clang/AST/Type.h"
41#include "clang/AST/TypeLoc.h"
53#include "clang/Basic/LLVM.h"
55#include "clang/Basic/Module.h"
69#include "clang/Basic/Version.h"
72#include "clang/Lex/MacroInfo.h"
73#include "clang/Lex/ModuleMap.h"
77#include "clang/Lex/Token.h"
79#include "clang/Sema/Scope.h"
80#include "clang/Sema/Sema.h"
81#include "clang/Sema/SemaCUDA.h"
82#include "clang/Sema/SemaObjC.h"
83#include "clang/Sema/Weak.h"
96#include "llvm/ADT/APFloat.h"
97#include "llvm/ADT/APInt.h"
98#include "llvm/ADT/ArrayRef.h"
99#include "llvm/ADT/DenseMap.h"
100#include "llvm/ADT/FoldingSet.h"
101#include "llvm/ADT/IntrusiveRefCntPtr.h"
102#include "llvm/ADT/STLExtras.h"
103#include "llvm/ADT/ScopeExit.h"
104#include "llvm/ADT/Sequence.h"
105#include "llvm/ADT/SmallPtrSet.h"
106#include "llvm/ADT/SmallVector.h"
107#include "llvm/ADT/StringExtras.h"
108#include "llvm/ADT/StringMap.h"
109#include "llvm/ADT/StringRef.h"
110#include "llvm/ADT/iterator_range.h"
111#include "llvm/Bitstream/BitstreamReader.h"
112#include "llvm/Support/Compiler.h"
113#include "llvm/Support/Compression.h"
114#include "llvm/Support/DJB.h"
115#include "llvm/Support/Endian.h"
116#include "llvm/Support/Error.h"
117#include "llvm/Support/ErrorHandling.h"
118#include "llvm/Support/LEB128.h"
119#include "llvm/Support/MemoryBuffer.h"
120#include "llvm/Support/Path.h"
121#include "llvm/Support/SaveAndRestore.h"
122#include "llvm/Support/TimeProfiler.h"
123#include "llvm/Support/Timer.h"
124#include "llvm/Support/VersionTuple.h"
125#include "llvm/Support/raw_ostream.h"
126#include "llvm/TargetParser/Triple.h"
127#include <algorithm>
128#include <cassert>
129#include <cstddef>
130#include <cstdint>
131#include <cstdio>
132#include <ctime>
133#include <iterator>
134#include <limits>
135#include <map>
136#include <memory>
137#include <optional>
138#include <string>
139#include <system_error>
140#include <tuple>
141#include <utility>
142#include <vector>
143
144using namespace clang;
145using namespace clang::serialization;
146using namespace clang::serialization::reader;
147using llvm::BitstreamCursor;
148
149//===----------------------------------------------------------------------===//
150// ChainedASTReaderListener implementation
151//===----------------------------------------------------------------------===//
152
153bool
155 return First->ReadFullVersionInformation(FullVersion) ||
156 Second->ReadFullVersionInformation(FullVersion);
157}
158
160 First->ReadModuleName(ModuleName);
161 Second->ReadModuleName(ModuleName);
162}
163
164void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
165 First->ReadModuleMapFile(ModuleMapPath);
166 Second->ReadModuleMapFile(ModuleMapPath);
167}
168
170 const LangOptions &LangOpts, StringRef ModuleFilename, bool Complain,
171 bool AllowCompatibleDifferences) {
172 return First->ReadLanguageOptions(LangOpts, ModuleFilename, Complain,
173 AllowCompatibleDifferences) ||
174 Second->ReadLanguageOptions(LangOpts, ModuleFilename, Complain,
175 AllowCompatibleDifferences);
176}
177
179 const CodeGenOptions &CGOpts, StringRef ModuleFilename, bool Complain,
180 bool AllowCompatibleDifferences) {
181 return First->ReadCodeGenOptions(CGOpts, ModuleFilename, Complain,
182 AllowCompatibleDifferences) ||
183 Second->ReadCodeGenOptions(CGOpts, ModuleFilename, Complain,
184 AllowCompatibleDifferences);
185}
186
188 const TargetOptions &TargetOpts, StringRef ModuleFilename, bool Complain,
189 bool AllowCompatibleDifferences) {
190 return First->ReadTargetOptions(TargetOpts, ModuleFilename, Complain,
191 AllowCompatibleDifferences) ||
192 Second->ReadTargetOptions(TargetOpts, ModuleFilename, Complain,
193 AllowCompatibleDifferences);
194}
195
197 DiagnosticOptions &DiagOpts, StringRef ModuleFilename, bool Complain) {
198 return First->ReadDiagnosticOptions(DiagOpts, ModuleFilename, Complain) ||
199 Second->ReadDiagnosticOptions(DiagOpts, ModuleFilename, Complain);
200}
201
202bool
204 bool Complain) {
205 return First->ReadFileSystemOptions(FSOpts, Complain) ||
206 Second->ReadFileSystemOptions(FSOpts, Complain);
207}
208
210 const HeaderSearchOptions &HSOpts, StringRef ModuleFilename,
211 StringRef SpecificModuleCachePath, bool Complain) {
212 return First->ReadHeaderSearchOptions(HSOpts, ModuleFilename,
213 SpecificModuleCachePath, Complain) ||
214 Second->ReadHeaderSearchOptions(HSOpts, ModuleFilename,
215 SpecificModuleCachePath, Complain);
216}
217
219 const PreprocessorOptions &PPOpts, StringRef ModuleFilename,
220 bool ReadMacros, bool Complain, std::string &SuggestedPredefines) {
221 return First->ReadPreprocessorOptions(PPOpts, ModuleFilename, ReadMacros,
222 Complain, SuggestedPredefines) ||
223 Second->ReadPreprocessorOptions(PPOpts, ModuleFilename, ReadMacros,
224 Complain, SuggestedPredefines);
225}
226
228 uint32_t Value) {
229 First->ReadCounter(M, Value);
230 Second->ReadCounter(M, Value);
231}
232
234 return First->needsInputFileVisitation() ||
235 Second->needsInputFileVisitation();
236}
237
239 return First->needsSystemInputFileVisitation() ||
240 Second->needsSystemInputFileVisitation();
241}
242
244 ModuleKind Kind) {
245 First->visitModuleFile(Filename, Kind);
246 Second->visitModuleFile(Filename, Kind);
247}
248
250 bool isSystem,
251 bool isOverridden,
252 bool isExplicitModule) {
253 bool Continue = false;
254 if (First->needsInputFileVisitation() &&
255 (!isSystem || First->needsSystemInputFileVisitation()))
256 Continue |= First->visitInputFile(Filename, isSystem, isOverridden,
257 isExplicitModule);
258 if (Second->needsInputFileVisitation() &&
259 (!isSystem || Second->needsSystemInputFileVisitation()))
260 Continue |= Second->visitInputFile(Filename, isSystem, isOverridden,
261 isExplicitModule);
262 return Continue;
263}
264
266 const ModuleFileExtensionMetadata &Metadata) {
267 First->readModuleFileExtension(Metadata);
268 Second->readModuleFileExtension(Metadata);
269}
270
271//===----------------------------------------------------------------------===//
272// PCH validator implementation
273//===----------------------------------------------------------------------===//
274
276
277/// Compare the given set of language options against an existing set of
278/// language options.
279///
280/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
281/// \param AllowCompatibleDifferences If true, differences between compatible
282/// language options will be permitted.
283///
284/// \returns true if the languagae options mis-match, false otherwise.
285static bool checkLanguageOptions(const LangOptions &LangOpts,
286 const LangOptions &ExistingLangOpts,
287 StringRef ModuleFilename,
288 DiagnosticsEngine *Diags,
289 bool AllowCompatibleDifferences = true) {
290 // FIXME: Replace with C++20 `using enum LangOptions::CompatibilityKind`.
292
293#define LANGOPT(Name, Bits, Default, Compatibility, Description) \
294 if constexpr (CK::Compatibility != CK::Benign) { \
295 if ((CK::Compatibility == CK::NotCompatible) || \
296 (CK::Compatibility == CK::Compatible && \
297 !AllowCompatibleDifferences)) { \
298 if (ExistingLangOpts.Name != LangOpts.Name) { \
299 if (Diags) { \
300 if (Bits == 1) \
301 Diags->Report(diag::err_ast_file_langopt_mismatch) \
302 << Description << LangOpts.Name << ExistingLangOpts.Name \
303 << ModuleFilename; \
304 else \
305 Diags->Report(diag::err_ast_file_langopt_value_mismatch) \
306 << Description << ModuleFilename; \
307 } \
308 return true; \
309 } \
310 } \
311 }
312
313#define VALUE_LANGOPT(Name, Bits, Default, Compatibility, Description) \
314 if constexpr (CK::Compatibility != CK::Benign) { \
315 if ((CK::Compatibility == CK::NotCompatible) || \
316 (CK::Compatibility == CK::Compatible && \
317 !AllowCompatibleDifferences)) { \
318 if (ExistingLangOpts.Name != LangOpts.Name) { \
319 if (Diags) \
320 Diags->Report(diag::err_ast_file_langopt_value_mismatch) \
321 << Description << ModuleFilename; \
322 return true; \
323 } \
324 } \
325 }
326
327#define ENUM_LANGOPT(Name, Type, Bits, Default, Compatibility, Description) \
328 if constexpr (CK::Compatibility != CK::Benign) { \
329 if ((CK::Compatibility == CK::NotCompatible) || \
330 (CK::Compatibility == CK::Compatible && \
331 !AllowCompatibleDifferences)) { \
332 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
333 if (Diags) \
334 Diags->Report(diag::err_ast_file_langopt_value_mismatch) \
335 << Description << ModuleFilename; \
336 return true; \
337 } \
338 } \
339 }
340
341#include "clang/Basic/LangOptions.def"
342
343 if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) {
344 if (Diags)
345 Diags->Report(diag::err_ast_file_langopt_value_mismatch)
346 << "module features" << ModuleFilename;
347 return true;
348 }
349
350 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
351 if (Diags)
352 Diags->Report(diag::err_ast_file_langopt_value_mismatch)
353 << "target Objective-C runtime" << ModuleFilename;
354 return true;
355 }
356
357 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
359 if (Diags)
360 Diags->Report(diag::err_ast_file_langopt_value_mismatch)
361 << "block command names" << ModuleFilename;
362 return true;
363 }
364
365 // Sanitizer feature mismatches are treated as compatible differences. If
366 // compatible differences aren't allowed, we still only want to check for
367 // mismatches of non-modular sanitizers (the only ones which can affect AST
368 // generation).
369 if (!AllowCompatibleDifferences) {
370 SanitizerMask ModularSanitizers = getPPTransparentSanitizers();
371 SanitizerSet ExistingSanitizers = ExistingLangOpts.Sanitize;
372 SanitizerSet ImportedSanitizers = LangOpts.Sanitize;
373 ExistingSanitizers.clear(ModularSanitizers);
374 ImportedSanitizers.clear(ModularSanitizers);
375 if (ExistingSanitizers.Mask != ImportedSanitizers.Mask) {
376 const std::string Flag = "-fsanitize=";
377 if (Diags) {
378#define SANITIZER(NAME, ID) \
379 { \
380 bool InExistingModule = ExistingSanitizers.has(SanitizerKind::ID); \
381 bool InImportedModule = ImportedSanitizers.has(SanitizerKind::ID); \
382 if (InExistingModule != InImportedModule) \
383 Diags->Report(diag::err_ast_file_targetopt_feature_mismatch) \
384 << InExistingModule << ModuleFilename << (Flag + NAME); \
385 }
386#include "clang/Basic/Sanitizers.def"
387 }
388 return true;
389 }
390 }
391
392 return false;
393}
394
395static bool checkCodegenOptions(const CodeGenOptions &CGOpts,
396 const CodeGenOptions &ExistingCGOpts,
397 StringRef ModuleFilename,
398 DiagnosticsEngine *Diags,
399 bool AllowCompatibleDifferences = true) {
400 // FIXME: Specify and print a description for each option instead of the name.
401 // FIXME: Replace with C++20 `using enum CodeGenOptions::CompatibilityKind`.
403#define CODEGENOPT(Name, Bits, Default, Compatibility) \
404 if constexpr (CK::Compatibility != CK::Benign) { \
405 if ((CK::Compatibility == CK::NotCompatible) || \
406 (CK::Compatibility == CK::Compatible && \
407 !AllowCompatibleDifferences)) { \
408 if (ExistingCGOpts.Name != CGOpts.Name) { \
409 if (Diags) { \
410 if (Bits == 1) \
411 Diags->Report(diag::err_ast_file_codegenopt_mismatch) \
412 << #Name << CGOpts.Name << ExistingCGOpts.Name \
413 << ModuleFilename; \
414 else \
415 Diags->Report(diag::err_ast_file_codegenopt_value_mismatch) \
416 << #Name << ModuleFilename; \
417 } \
418 return true; \
419 } \
420 } \
421 }
422
423#define VALUE_CODEGENOPT(Name, Bits, Default, Compatibility) \
424 if constexpr (CK::Compatibility != CK::Benign) { \
425 if ((CK::Compatibility == CK::NotCompatible) || \
426 (CK::Compatibility == CK::Compatible && \
427 !AllowCompatibleDifferences)) { \
428 if (ExistingCGOpts.Name != CGOpts.Name) { \
429 if (Diags) \
430 Diags->Report(diag::err_ast_file_codegenopt_value_mismatch) \
431 << #Name << ModuleFilename; \
432 return true; \
433 } \
434 } \
435 }
436#define ENUM_CODEGENOPT(Name, Type, Bits, Default, Compatibility) \
437 if constexpr (CK::Compatibility != CK::Benign) { \
438 if ((CK::Compatibility == CK::NotCompatible) || \
439 (CK::Compatibility == CK::Compatible && \
440 !AllowCompatibleDifferences)) { \
441 if (ExistingCGOpts.get##Name() != CGOpts.get##Name()) { \
442 if (Diags) \
443 Diags->Report(diag::err_ast_file_codegenopt_value_mismatch) \
444 << #Name << ModuleFilename; \
445 return true; \
446 } \
447 } \
448 }
449#define DEBUGOPT(Name, Bits, Default, Compatibility)
450#define VALUE_DEBUGOPT(Name, Bits, Default, Compatibility)
451#define ENUM_DEBUGOPT(Name, Type, Bits, Default, Compatibility)
452#include "clang/Basic/CodeGenOptions.def"
453
454 return false;
455}
456
457/// Compare the given set of target options against an existing set of
458/// target options.
459///
460/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
461///
462/// \returns true if the target options mis-match, false otherwise.
463static bool checkTargetOptions(const TargetOptions &TargetOpts,
464 const TargetOptions &ExistingTargetOpts,
465 StringRef ModuleFilename,
466 DiagnosticsEngine *Diags,
467 bool AllowCompatibleDifferences = true) {
468#define CHECK_TARGET_OPT(Field, Name) \
469 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
470 if (Diags) \
471 Diags->Report(diag::err_ast_file_targetopt_mismatch) \
472 << ModuleFilename << Name << TargetOpts.Field \
473 << ExistingTargetOpts.Field; \
474 return true; \
475 }
476
477 // The triple and ABI must match exactly.
478 CHECK_TARGET_OPT(Triple, "target");
479 CHECK_TARGET_OPT(ABI, "target ABI");
480
481 // We can tolerate different CPUs in many cases, notably when one CPU
482 // supports a strict superset of another. When allowing compatible
483 // differences skip this check.
484 if (!AllowCompatibleDifferences) {
485 CHECK_TARGET_OPT(CPU, "target CPU");
486 CHECK_TARGET_OPT(TuneCPU, "tune CPU");
487 }
488
489#undef CHECK_TARGET_OPT
490
491 // Compare feature sets.
492 SmallVector<StringRef, 4> ExistingFeatures(
493 ExistingTargetOpts.FeaturesAsWritten.begin(),
494 ExistingTargetOpts.FeaturesAsWritten.end());
495 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
496 TargetOpts.FeaturesAsWritten.end());
497 llvm::sort(ExistingFeatures);
498 llvm::sort(ReadFeatures);
499
500 // We compute the set difference in both directions explicitly so that we can
501 // diagnose the differences differently.
502 SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
503 std::set_difference(
504 ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
505 ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
506 std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
507 ExistingFeatures.begin(), ExistingFeatures.end(),
508 std::back_inserter(UnmatchedReadFeatures));
509
510 // If we are allowing compatible differences and the read feature set is
511 // a strict subset of the existing feature set, there is nothing to diagnose.
512 if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
513 return false;
514
515 if (Diags) {
516 for (StringRef Feature : UnmatchedReadFeatures)
517 Diags->Report(diag::err_ast_file_targetopt_feature_mismatch)
518 << /* is-existing-feature */ false << ModuleFilename << Feature;
519 for (StringRef Feature : UnmatchedExistingFeatures)
520 Diags->Report(diag::err_ast_file_targetopt_feature_mismatch)
521 << /* is-existing-feature */ true << ModuleFilename << Feature;
522 }
523
524 return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
525}
526
528 StringRef ModuleFilename, bool Complain,
529 bool AllowCompatibleDifferences) {
530 const LangOptions &ExistingLangOpts = PP.getLangOpts();
531 return checkLanguageOptions(LangOpts, ExistingLangOpts, ModuleFilename,
532 Complain ? &Reader.Diags : nullptr,
533 AllowCompatibleDifferences);
534}
535
537 StringRef ModuleFilename, bool Complain,
538 bool AllowCompatibleDifferences) {
539 const CodeGenOptions &ExistingCGOpts = Reader.getCodeGenOpts();
540 return checkCodegenOptions(ExistingCGOpts, CGOpts, ModuleFilename,
541 Complain ? &Reader.Diags : nullptr,
542 AllowCompatibleDifferences);
543}
544
546 StringRef ModuleFilename, bool Complain,
547 bool AllowCompatibleDifferences) {
548 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
549 return checkTargetOptions(TargetOpts, ExistingTargetOpts, ModuleFilename,
550 Complain ? &Reader.Diags : nullptr,
551 AllowCompatibleDifferences);
552}
553
554namespace {
555
556using MacroDefinitionsMap =
557 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>;
558
559class DeclsSet {
562
563public:
564 operator ArrayRef<NamedDecl *>() const { return Decls; }
565
566 bool empty() const { return Decls.empty(); }
567
568 bool insert(NamedDecl *ND) {
569 auto [_, Inserted] = Found.insert(ND);
570 if (Inserted)
571 Decls.push_back(ND);
572 return Inserted;
573 }
574};
575
576using DeclsMap = llvm::DenseMap<DeclarationName, DeclsSet>;
577
578} // namespace
579
581 DiagnosticsEngine &Diags,
582 StringRef ModuleFilename,
583 bool Complain) {
584 using Level = DiagnosticsEngine::Level;
585
586 // Check current mappings for new -Werror mappings, and the stored mappings
587 // for cases that were explicitly mapped to *not* be errors that are now
588 // errors because of options like -Werror.
589 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
590
591 for (DiagnosticsEngine *MappingSource : MappingSources) {
592 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
593 diag::kind DiagID = DiagIDMappingPair.first;
594 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
595 if (CurLevel < DiagnosticsEngine::Error)
596 continue; // not significant
597 Level StoredLevel =
598 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
599 if (StoredLevel < DiagnosticsEngine::Error) {
600 if (Complain)
601 Diags.Report(diag::err_ast_file_diagopt_mismatch)
602 << "-Werror=" + Diags.getDiagnosticIDs()
603 ->getWarningOptionForDiag(DiagID)
604 .str()
605 << ModuleFilename;
606 return true;
607 }
608 }
609 }
610
611 return false;
612}
613
616 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
617 return true;
618 return Ext >= diag::Severity::Error;
619}
620
622 DiagnosticsEngine &Diags,
623 StringRef ModuleFilename, bool IsSystem,
624 bool SystemHeaderWarningsInModule,
625 bool Complain) {
626 // Top-level options
627 if (IsSystem) {
628 if (Diags.getSuppressSystemWarnings())
629 return false;
630 // If -Wsystem-headers was not enabled before, and it was not explicit,
631 // be conservative
632 if (StoredDiags.getSuppressSystemWarnings() &&
633 !SystemHeaderWarningsInModule) {
634 if (Complain)
635 Diags.Report(diag::err_ast_file_diagopt_mismatch)
636 << "-Wsystem-headers" << ModuleFilename;
637 return true;
638 }
639 }
640
641 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
642 if (Complain)
643 Diags.Report(diag::err_ast_file_diagopt_mismatch)
644 << "-Werror" << ModuleFilename;
645 return true;
646 }
647
648 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
649 !StoredDiags.getEnableAllWarnings()) {
650 if (Complain)
651 Diags.Report(diag::err_ast_file_diagopt_mismatch)
652 << "-Weverything -Werror" << ModuleFilename;
653 return true;
654 }
655
656 if (isExtHandlingFromDiagsError(Diags) &&
657 !isExtHandlingFromDiagsError(StoredDiags)) {
658 if (Complain)
659 Diags.Report(diag::err_ast_file_diagopt_mismatch)
660 << "-pedantic-errors" << ModuleFilename;
661 return true;
662 }
663
664 return checkDiagnosticGroupMappings(StoredDiags, Diags, ModuleFilename,
665 Complain);
666}
667
668/// Return the top import module if it is implicit, nullptr otherwise.
670 Preprocessor &PP) {
671 // If the original import came from a file explicitly generated by the user,
672 // don't check the diagnostic mappings.
673 // FIXME: currently this is approximated by checking whether this is not a
674 // module import of an implicitly-loaded module file.
675 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
676 // the transitive closure of its imports, since unrelated modules cannot be
677 // imported until after this module finishes validation.
678 ModuleFile *TopImport = &*ModuleMgr.rbegin();
679 while (!TopImport->ImportedBy.empty())
680 TopImport = TopImport->ImportedBy[0];
681 if (TopImport->Kind != MK_ImplicitModule)
682 return nullptr;
683
684 StringRef ModuleName = TopImport->ModuleName;
685 assert(!ModuleName.empty() && "diagnostic options read before module name");
686
687 Module *M =
688 PP.getHeaderSearchInfo().lookupModule(ModuleName, TopImport->ImportLoc);
689 assert(M && "missing module");
690 return M;
691}
692
694 StringRef ModuleFilename,
695 bool Complain) {
696 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
698 auto Diags = llvm::makeIntrusiveRefCnt<DiagnosticsEngine>(DiagIDs, DiagOpts);
699 // This should never fail, because we would have processed these options
700 // before writing them to an ASTFile.
701 ProcessWarningOptions(*Diags, DiagOpts,
702 PP.getFileManager().getVirtualFileSystem(),
703 /*Report*/ false);
704
705 ModuleManager &ModuleMgr = Reader.getModuleManager();
706 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
707
708 Module *TopM = getTopImportImplicitModule(ModuleMgr, PP);
709 if (!TopM)
710 return false;
711
712 Module *Importer = PP.getCurrentModule();
713
714 DiagnosticOptions &ExistingOpts = ExistingDiags.getDiagnosticOptions();
715 bool SystemHeaderWarningsInModule =
716 Importer && llvm::is_contained(ExistingOpts.SystemHeaderWarningsModules,
717 Importer->Name);
718
719 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
720 // contains the union of their flags.
721 return checkDiagnosticMappings(*Diags, ExistingDiags, ModuleFilename,
722 TopM->IsSystem, SystemHeaderWarningsInModule,
723 Complain);
724}
725
726/// Collect the macro definitions provided by the given preprocessor
727/// options.
728static void
730 MacroDefinitionsMap &Macros,
731 SmallVectorImpl<StringRef> *MacroNames = nullptr) {
732 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
733 StringRef Macro = PPOpts.Macros[I].first;
734 bool IsUndef = PPOpts.Macros[I].second;
735
736 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
737 StringRef MacroName = MacroPair.first;
738 StringRef MacroBody = MacroPair.second;
739
740 // For an #undef'd macro, we only care about the name.
741 if (IsUndef) {
742 auto [It, Inserted] = Macros.try_emplace(MacroName);
743 if (MacroNames && Inserted)
744 MacroNames->push_back(MacroName);
745
746 It->second = std::make_pair("", true);
747 continue;
748 }
749
750 // For a #define'd macro, figure out the actual definition.
751 if (MacroName.size() == Macro.size())
752 MacroBody = "1";
753 else {
754 // Note: GCC drops anything following an end-of-line character.
755 StringRef::size_type End = MacroBody.find_first_of("\n\r");
756 MacroBody = MacroBody.substr(0, End);
757 }
758
759 auto [It, Inserted] = Macros.try_emplace(MacroName);
760 if (MacroNames && Inserted)
761 MacroNames->push_back(MacroName);
762 It->second = std::make_pair(MacroBody, false);
763 }
764}
765
771
772/// Check the preprocessor options deserialized from the control block
773/// against the preprocessor options in an existing preprocessor.
774///
775/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
776/// \param Validation If set to OptionValidateNone, ignore differences in
777/// preprocessor options. If set to OptionValidateContradictions,
778/// require that options passed both in the AST file and on the command
779/// line (-D or -U) match, but tolerate options missing in one or the
780/// other. If set to OptionValidateContradictions, require that there
781/// are no differences in the options between the two.
783 const PreprocessorOptions &PPOpts,
784 const PreprocessorOptions &ExistingPPOpts, StringRef ModuleFilename,
785 bool ReadMacros, DiagnosticsEngine *Diags, FileManager &FileMgr,
786 std::string &SuggestedPredefines, const LangOptions &LangOpts,
788 if (ReadMacros) {
789 // Check macro definitions.
790 MacroDefinitionsMap ASTFileMacros;
791 collectMacroDefinitions(PPOpts, ASTFileMacros);
792 MacroDefinitionsMap ExistingMacros;
793 SmallVector<StringRef, 4> ExistingMacroNames;
794 collectMacroDefinitions(ExistingPPOpts, ExistingMacros,
795 &ExistingMacroNames);
796
797 // Use a line marker to enter the <command line> file, as the defines and
798 // undefines here will have come from the command line.
799 SuggestedPredefines += "# 1 \"<command line>\" 1\n";
800
801 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
802 // Dig out the macro definition in the existing preprocessor options.
803 StringRef MacroName = ExistingMacroNames[I];
804 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
805
806 // Check whether we know anything about this macro name or not.
807 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>::iterator Known =
808 ASTFileMacros.find(MacroName);
809 if (Validation == OptionValidateNone || Known == ASTFileMacros.end()) {
810 if (Validation == OptionValidateStrictMatches) {
811 // If strict matches are requested, don't tolerate any extra defines
812 // on the command line that are missing in the AST file.
813 if (Diags) {
814 Diags->Report(diag::err_ast_file_macro_def_undef)
815 << MacroName << true << ModuleFilename;
816 }
817 return true;
818 }
819 // FIXME: Check whether this identifier was referenced anywhere in the
820 // AST file. If so, we should reject the AST file. Unfortunately, this
821 // information isn't in the control block. What shall we do about it?
822
823 if (Existing.second) {
824 SuggestedPredefines += "#undef ";
825 SuggestedPredefines += MacroName.str();
826 SuggestedPredefines += '\n';
827 } else {
828 SuggestedPredefines += "#define ";
829 SuggestedPredefines += MacroName.str();
830 SuggestedPredefines += ' ';
831 SuggestedPredefines += Existing.first.str();
832 SuggestedPredefines += '\n';
833 }
834 continue;
835 }
836
837 // If the macro was defined in one but undef'd in the other, we have a
838 // conflict.
839 if (Existing.second != Known->second.second) {
840 if (Diags) {
841 Diags->Report(diag::err_ast_file_macro_def_undef)
842 << MacroName << Known->second.second << ModuleFilename;
843 }
844 return true;
845 }
846
847 // If the macro was #undef'd in both, or if the macro bodies are
848 // identical, it's fine.
849 if (Existing.second || Existing.first == Known->second.first) {
850 ASTFileMacros.erase(Known);
851 continue;
852 }
853
854 // The macro bodies differ; complain.
855 if (Diags) {
856 Diags->Report(diag::err_ast_file_macro_def_conflict)
857 << MacroName << Known->second.first << Existing.first
858 << ModuleFilename;
859 }
860 return true;
861 }
862
863 // Leave the <command line> file and return to <built-in>.
864 SuggestedPredefines += "# 1 \"<built-in>\" 2\n";
865
866 if (Validation == OptionValidateStrictMatches) {
867 // If strict matches are requested, don't tolerate any extra defines in
868 // the AST file that are missing on the command line.
869 for (const auto &MacroName : ASTFileMacros.keys()) {
870 if (Diags) {
871 Diags->Report(diag::err_ast_file_macro_def_undef)
872 << MacroName << false << ModuleFilename;
873 }
874 return true;
875 }
876 }
877 }
878
879 // Check whether we're using predefines.
880 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines &&
881 Validation != OptionValidateNone) {
882 if (Diags) {
883 Diags->Report(diag::err_ast_file_undef)
884 << ExistingPPOpts.UsePredefines << ModuleFilename;
885 }
886 return true;
887 }
888
889 // Detailed record is important since it is used for the module cache hash.
890 if (LangOpts.Modules &&
891 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord &&
892 Validation != OptionValidateNone) {
893 if (Diags) {
894 Diags->Report(diag::err_ast_file_pp_detailed_record)
895 << PPOpts.DetailedRecord << ModuleFilename;
896 }
897 return true;
898 }
899
900 // Compute the #include and #include_macros lines we need.
901 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
902 StringRef File = ExistingPPOpts.Includes[I];
903
904 if (!ExistingPPOpts.ImplicitPCHInclude.empty() &&
905 !ExistingPPOpts.PCHThroughHeader.empty()) {
906 // In case the through header is an include, we must add all the includes
907 // to the predefines so the start point can be determined.
908 SuggestedPredefines += "#include \"";
909 SuggestedPredefines += File;
910 SuggestedPredefines += "\"\n";
911 continue;
912 }
913
914 if (File == ExistingPPOpts.ImplicitPCHInclude)
915 continue;
916
917 if (llvm::is_contained(PPOpts.Includes, File))
918 continue;
919
920 SuggestedPredefines += "#include \"";
921 SuggestedPredefines += File;
922 SuggestedPredefines += "\"\n";
923 }
924
925 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
926 StringRef File = ExistingPPOpts.MacroIncludes[I];
927 if (llvm::is_contained(PPOpts.MacroIncludes, File))
928 continue;
929
930 SuggestedPredefines += "#__include_macros \"";
931 SuggestedPredefines += File;
932 SuggestedPredefines += "\"\n##\n";
933 }
934
935 return false;
936}
937
939 StringRef ModuleFilename,
940 bool ReadMacros, bool Complain,
941 std::string &SuggestedPredefines) {
942 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
943
945 PPOpts, ExistingPPOpts, ModuleFilename, ReadMacros,
946 Complain ? &Reader.Diags : nullptr, PP.getFileManager(),
947 SuggestedPredefines, PP.getLangOpts());
948}
949
951 const PreprocessorOptions &PPOpts, StringRef ModuleFilename,
952 bool ReadMacros, bool Complain, std::string &SuggestedPredefines) {
953 return checkPreprocessorOptions(PPOpts, PP.getPreprocessorOpts(),
954 ModuleFilename, ReadMacros, nullptr,
955 PP.getFileManager(), SuggestedPredefines,
956 PP.getLangOpts(), OptionValidateNone);
957}
958
959/// Check that the specified and the existing module cache paths are equivalent.
960///
961/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
962/// \returns true when the module cache paths differ.
963static bool checkModuleCachePath(llvm::vfs::FileSystem &VFS,
964 StringRef SpecificModuleCachePath,
965 StringRef ExistingModuleCachePath,
966 StringRef ModuleFilename,
967 DiagnosticsEngine *Diags,
968 const LangOptions &LangOpts,
969 const PreprocessorOptions &PPOpts) {
970 if (!LangOpts.Modules || PPOpts.AllowPCHWithDifferentModulesCachePath ||
971 SpecificModuleCachePath == ExistingModuleCachePath)
972 return false;
973 auto EqualOrErr =
974 VFS.equivalent(SpecificModuleCachePath, ExistingModuleCachePath);
975 if (EqualOrErr && *EqualOrErr)
976 return false;
977 if (Diags)
978 Diags->Report(diag::err_ast_file_modulecache_mismatch)
979 << SpecificModuleCachePath << ExistingModuleCachePath << ModuleFilename;
980 return true;
981}
982
984 StringRef ModuleFilename,
985 StringRef SpecificModuleCachePath,
986 bool Complain) {
988 Reader.getFileManager().getVirtualFileSystem(), SpecificModuleCachePath,
989 PP.getHeaderSearchInfo().getModuleCachePath(), ModuleFilename,
990 Complain ? &Reader.Diags : nullptr, PP.getLangOpts(),
991 PP.getPreprocessorOpts());
992}
993
995 PP.setCounterValue(Value);
996}
997
998//===----------------------------------------------------------------------===//
999// AST reader implementation
1000//===----------------------------------------------------------------------===//
1001
1002static uint64_t readULEB(const unsigned char *&P) {
1003 unsigned Length = 0;
1004 const char *Error = nullptr;
1005
1006 uint64_t Val = llvm::decodeULEB128(P, &Length, nullptr, &Error);
1007 if (Error)
1008 llvm::report_fatal_error(Error);
1009 P += Length;
1010 return Val;
1011}
1012
1013/// Read ULEB-encoded key length and data length.
1014static std::pair<unsigned, unsigned>
1015readULEBKeyDataLength(const unsigned char *&P) {
1016 unsigned KeyLen = readULEB(P);
1017 if ((unsigned)KeyLen != KeyLen)
1018 llvm::report_fatal_error("key too large");
1019
1020 unsigned DataLen = readULEB(P);
1021 if ((unsigned)DataLen != DataLen)
1022 llvm::report_fatal_error("data too large");
1023
1024 return std::make_pair(KeyLen, DataLen);
1025}
1026
1028 bool TakeOwnership) {
1029 DeserializationListener = Listener;
1030 OwnsDeserializationListener = TakeOwnership;
1031}
1032
1036
1038 LocalDeclID ID(Value);
1039#ifndef NDEBUG
1040 if (!MF.ModuleOffsetMap.empty())
1041 Reader.ReadModuleOffsetMap(MF);
1042
1043 unsigned ModuleFileIndex = ID.getModuleFileIndex();
1044 unsigned LocalDeclID = ID.getLocalDeclIndex();
1045
1046 assert(ModuleFileIndex <= MF.TransitiveImports.size());
1047
1048 ModuleFile *OwningModuleFile =
1049 ModuleFileIndex == 0 ? &MF : MF.TransitiveImports[ModuleFileIndex - 1];
1050 assert(OwningModuleFile);
1051
1052 unsigned LocalNumDecls = OwningModuleFile->LocalNumDecls;
1053
1054 if (!ModuleFileIndex)
1055 LocalNumDecls += NUM_PREDEF_DECL_IDS;
1056
1057 assert(LocalDeclID < LocalNumDecls);
1058#endif
1059 (void)Reader;
1060 (void)MF;
1061 return ID;
1062}
1063
1064LocalDeclID LocalDeclID::get(ASTReader &Reader, ModuleFile &MF,
1065 unsigned ModuleFileIndex, unsigned LocalDeclID) {
1066 DeclID Value = (DeclID)ModuleFileIndex << 32 | (DeclID)LocalDeclID;
1067 return LocalDeclID::get(Reader, MF, Value);
1068}
1069
1070std::pair<unsigned, unsigned>
1072 return readULEBKeyDataLength(d);
1073}
1074
1076ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
1077 using namespace llvm::support;
1078
1079 SelectorTable &SelTable = Reader.getContext().Selectors;
1080 unsigned N = endian::readNext<uint16_t, llvm::endianness::little>(d);
1081 const IdentifierInfo *FirstII = Reader.getLocalIdentifier(
1082 F, endian::readNext<IdentifierID, llvm::endianness::little>(d));
1083 if (N == 0)
1084 return SelTable.getNullarySelector(FirstII);
1085 else if (N == 1)
1086 return SelTable.getUnarySelector(FirstII);
1087
1089 Args.push_back(FirstII);
1090 for (unsigned I = 1; I != N; ++I)
1091 Args.push_back(Reader.getLocalIdentifier(
1092 F, endian::readNext<IdentifierID, llvm::endianness::little>(d)));
1093
1094 return SelTable.getSelector(N, Args.data());
1095}
1096
1099 unsigned DataLen) {
1100 using namespace llvm::support;
1101
1103
1104 Result.ID = Reader.getGlobalSelectorID(
1105 F, endian::readNext<uint32_t, llvm::endianness::little>(d));
1106 unsigned FullInstanceBits =
1107 endian::readNext<uint16_t, llvm::endianness::little>(d);
1108 unsigned FullFactoryBits =
1109 endian::readNext<uint16_t, llvm::endianness::little>(d);
1110 Result.InstanceBits = FullInstanceBits & 0x3;
1111 Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
1112 Result.FactoryBits = FullFactoryBits & 0x3;
1113 Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
1114 unsigned NumInstanceMethods = FullInstanceBits >> 3;
1115 unsigned NumFactoryMethods = FullFactoryBits >> 3;
1116
1117 // Load instance methods
1118 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
1119 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
1121 Reader, F,
1122 endian::readNext<DeclID, llvm::endianness::little>(d))))
1123 Result.Instance.push_back(Method);
1124 }
1125
1126 // Load factory methods
1127 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
1128 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
1130 Reader, F,
1131 endian::readNext<DeclID, llvm::endianness::little>(d))))
1132 Result.Factory.push_back(Method);
1133 }
1134
1135 return Result;
1136}
1137
1139 return llvm::djbHash(a);
1140}
1141
1142std::pair<unsigned, unsigned>
1144 return readULEBKeyDataLength(d);
1145}
1146
1148ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
1149 assert(n >= 2 && d[n-1] == '\0');
1150 return StringRef((const char*) d, n-1);
1151}
1152
1153/// Whether the given identifier is "interesting".
1154static bool isInterestingIdentifier(ASTReader &Reader, const IdentifierInfo &II,
1155 bool IsModule) {
1156 bool IsInteresting =
1157 II.getNotableIdentifierID() != tok::NotableIdentifierKind::not_notable ||
1159 II.getObjCKeywordID() != tok::ObjCKeywordKind::objc_not_keyword;
1160 return II.hadMacroDefinition() || II.isPoisoned() ||
1161 (!IsModule && IsInteresting) || II.hasRevertedTokenIDToIdentifier() ||
1162 (!(IsModule && Reader.getPreprocessor().getLangOpts().CPlusPlus) &&
1163 II.getFETokenInfo());
1164}
1165
1166static bool readBit(unsigned &Bits) {
1167 bool Value = Bits & 0x1;
1168 Bits >>= 1;
1169 return Value;
1170}
1171
1173 using namespace llvm::support;
1174
1175 IdentifierID RawID =
1176 endian::readNext<IdentifierID, llvm::endianness::little>(d);
1177 return Reader.getGlobalIdentifierID(F, RawID >> 1);
1178}
1179
1181 bool IsModule) {
1182 if (!II.isFromAST()) {
1183 II.setIsFromAST();
1184 if (isInterestingIdentifier(Reader, II, IsModule))
1186 }
1187}
1188
1190 const unsigned char* d,
1191 unsigned DataLen) {
1192 using namespace llvm::support;
1193
1194 IdentifierID RawID =
1195 endian::readNext<IdentifierID, llvm::endianness::little>(d);
1196 bool IsInteresting = RawID & 0x01;
1197
1198 DataLen -= sizeof(IdentifierID);
1199
1200 // Wipe out the "is interesting" bit.
1201 RawID = RawID >> 1;
1202
1203 // Build the IdentifierInfo and link the identifier ID with it.
1204 IdentifierInfo *II = KnownII;
1205 if (!II) {
1206 II = &Reader.getIdentifierTable().getOwn(k);
1207 KnownII = II;
1208 }
1209 bool IsModule = Reader.getPreprocessor().getCurrentModule() != nullptr;
1210 markIdentifierFromAST(Reader, *II, IsModule);
1211 Reader.markIdentifierUpToDate(II);
1212
1213 IdentifierID ID = Reader.getGlobalIdentifierID(F, RawID);
1214 if (!IsInteresting) {
1215 // For uninteresting identifiers, there's nothing else to do. Just notify
1216 // the reader that we've finished loading this identifier.
1217 Reader.SetIdentifierInfo(ID, II);
1218 return II;
1219 }
1220
1221 unsigned ObjCOrBuiltinID =
1222 endian::readNext<uint16_t, llvm::endianness::little>(d);
1223 unsigned Bits = endian::readNext<uint16_t, llvm::endianness::little>(d);
1224 bool CPlusPlusOperatorKeyword = readBit(Bits);
1225 bool HasRevertedTokenIDToIdentifier = readBit(Bits);
1226 bool Poisoned = readBit(Bits);
1227 bool ExtensionToken = readBit(Bits);
1228 bool HasMacroDefinition = readBit(Bits);
1229
1230 assert(Bits == 0 && "Extra bits in the identifier?");
1231 DataLen -= sizeof(uint16_t) * 2;
1232
1233 // Set or check the various bits in the IdentifierInfo structure.
1234 // Token IDs are read-only.
1235 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
1237 if (!F.isModule())
1238 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
1239 assert(II->isExtensionToken() == ExtensionToken &&
1240 "Incorrect extension token flag");
1241 (void)ExtensionToken;
1242 if (Poisoned)
1243 II->setIsPoisoned(true);
1244 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
1245 "Incorrect C++ operator keyword flag");
1246 (void)CPlusPlusOperatorKeyword;
1247
1248 // If this identifier has a macro definition, deserialize it or notify the
1249 // visitor the actual definition is in a different module.
1250 if (HasMacroDefinition) {
1251 uint32_t MacroDirectivesOffset =
1252 endian::readNext<uint32_t, llvm::endianness::little>(d);
1253 DataLen -= 4;
1254
1255 if (MacroDirectivesOffset)
1256 Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
1257 else
1258 hasMacroDefinitionInDependencies = true;
1259 }
1260
1261 Reader.SetIdentifierInfo(ID, II);
1262
1263 // Read all of the declarations visible at global scope with this
1264 // name.
1265 if (DataLen > 0) {
1267 for (; DataLen > 0; DataLen -= sizeof(DeclID))
1268 DeclIDs.push_back(Reader.getGlobalDeclID(
1270 Reader, F,
1271 endian::readNext<DeclID, llvm::endianness::little>(d))));
1272 Reader.SetGloballyVisibleDecls(II, DeclIDs);
1273 }
1274
1275 return II;
1276}
1277
1279 : Kind(Name.getNameKind()) {
1280 switch (Kind) {
1282 Data = (uint64_t)Name.getAsIdentifierInfo();
1283 break;
1287 Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
1288 break;
1290 Data = Name.getCXXOverloadedOperator();
1291 break;
1293 Data = (uint64_t)Name.getCXXLiteralIdentifier();
1294 break;
1296 Data = (uint64_t)Name.getCXXDeductionGuideTemplate()
1298 break;
1303 Data = 0;
1304 break;
1305 }
1306}
1307
1309 llvm::FoldingSetNodeID ID;
1310 ID.AddInteger(Kind);
1311
1312 switch (Kind) {
1316 ID.AddString(((IdentifierInfo*)Data)->getName());
1317 break;
1321 ID.AddInteger(serialization::ComputeHash(Selector(Data)));
1322 break;
1324 ID.AddInteger((OverloadedOperatorKind)Data);
1325 break;
1330 break;
1331 }
1332
1333 return ID.computeStableHash();
1334}
1335
1336ModuleFile *
1338 using namespace llvm::support;
1339
1340 uint32_t ModuleFileID =
1341 endian::readNext<uint32_t, llvm::endianness::little>(d);
1342 return Reader.getLocalModuleFile(F, ModuleFileID);
1343}
1344
1345std::pair<unsigned, unsigned>
1349
1352 using namespace llvm::support;
1353
1354 auto Kind = (DeclarationName::NameKind)*d++;
1355 uint64_t Data;
1356 switch (Kind) {
1360 Data = (uint64_t)Reader.getLocalIdentifier(
1361 F, endian::readNext<IdentifierID, llvm::endianness::little>(d));
1362 break;
1366 Data = (uint64_t)Reader
1367 .getLocalSelector(
1368 F, endian::readNext<uint32_t, llvm::endianness::little>(d))
1369 .getAsOpaquePtr();
1370 break;
1372 Data = *d++; // OverloadedOperatorKind
1373 break;
1378 Data = 0;
1379 break;
1380 }
1381
1382 return DeclarationNameKey(Kind, Data);
1383}
1384
1386ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
1387 return ReadKeyBase(d);
1388}
1389
1391 const unsigned char *d, unsigned DataLen, data_type_builder &Val) {
1392 using namespace llvm::support;
1393
1394 for (unsigned NumDecls = DataLen / sizeof(DeclID); NumDecls; --NumDecls) {
1396 Reader, F, endian::readNext<DeclID, llvm::endianness::little>(d));
1397 Val.insert(Reader.getGlobalDeclID(F, ID));
1398 }
1399}
1400
1402 const unsigned char *d,
1403 unsigned DataLen,
1404 data_type_builder &Val) {
1405 ReadDataIntoImpl(d, DataLen, Val);
1406}
1407
1410 llvm::FoldingSetNodeID ID;
1411 ID.AddInteger(Key.first.getHash());
1412 ID.AddInteger(Key.second);
1413 return ID.computeStableHash();
1414}
1415
1418 DeclarationNameKey Name(Key.first);
1419
1420 UnsignedOrNone ModuleHash = getPrimaryModuleHash(Key.second);
1421 if (!ModuleHash)
1422 return {Name, 0};
1423
1424 return {Name, *ModuleHash};
1425}
1426
1428ModuleLocalNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
1430 unsigned PrimaryModuleHash =
1431 llvm::support::endian::readNext<uint32_t, llvm::endianness::little>(d);
1432 return {Name, PrimaryModuleHash};
1433}
1434
1436 const unsigned char *d,
1437 unsigned DataLen,
1438 data_type_builder &Val) {
1439 ReadDataIntoImpl(d, DataLen, Val);
1440}
1441
1442ModuleFile *
1444 using namespace llvm::support;
1445
1446 uint32_t ModuleFileID =
1447 endian::readNext<uint32_t, llvm::endianness::little, unaligned>(d);
1448 return Reader.getLocalModuleFile(F, ModuleFileID);
1449}
1450
1452LazySpecializationInfoLookupTrait::ReadKey(const unsigned char *d, unsigned) {
1453 using namespace llvm::support;
1454 return endian::readNext<uint32_t, llvm::endianness::little, unaligned>(d);
1455}
1456
1457std::pair<unsigned, unsigned>
1461
1463 const unsigned char *d,
1464 unsigned DataLen,
1465 data_type_builder &Val) {
1466 using namespace llvm::support;
1467
1468 for (unsigned NumDecls =
1470 NumDecls; --NumDecls) {
1471 LocalDeclID LocalID = LocalDeclID::get(
1472 Reader, F,
1473 endian::readNext<DeclID, llvm::endianness::little, unaligned>(d));
1474 Val.insert(Reader.getGlobalDeclID(F, LocalID));
1475 }
1476}
1477
1478bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
1479 BitstreamCursor &Cursor,
1480 uint64_t Offset,
1481 DeclContext *DC) {
1482 assert(Offset != 0);
1483
1484 SavedStreamPosition SavedPosition(Cursor);
1485 if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1486 Error(std::move(Err));
1487 return true;
1488 }
1489
1490 RecordData Record;
1491 StringRef Blob;
1492 Expected<unsigned> MaybeCode = Cursor.ReadCode();
1493 if (!MaybeCode) {
1494 Error(MaybeCode.takeError());
1495 return true;
1496 }
1497 unsigned Code = MaybeCode.get();
1498
1499 Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
1500 if (!MaybeRecCode) {
1501 Error(MaybeRecCode.takeError());
1502 return true;
1503 }
1504 unsigned RecCode = MaybeRecCode.get();
1505 if (RecCode != DECL_CONTEXT_LEXICAL) {
1506 Error("Expected lexical block");
1507 return true;
1508 }
1509
1510 assert(!isa<TranslationUnitDecl>(DC) &&
1511 "expected a TU_UPDATE_LEXICAL record for TU");
1512 // If we are handling a C++ class template instantiation, we can see multiple
1513 // lexical updates for the same record. It's important that we select only one
1514 // of them, so that field numbering works properly. Just pick the first one we
1515 // see.
1516 auto &Lex = LexicalDecls[DC];
1517 if (!Lex.first) {
1518 Lex = std::make_pair(
1519 &M, llvm::ArrayRef(
1520 reinterpret_cast<const unaligned_decl_id_t *>(Blob.data()),
1521 Blob.size() / sizeof(DeclID)));
1522 }
1524 return false;
1525}
1526
1527bool ASTReader::ReadVisibleDeclContextStorage(
1528 ModuleFile &M, BitstreamCursor &Cursor, uint64_t Offset, GlobalDeclID ID,
1529 ASTReader::VisibleDeclContextStorageKind VisibleKind) {
1530 assert(Offset != 0);
1531
1532 SavedStreamPosition SavedPosition(Cursor);
1533 if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1534 Error(std::move(Err));
1535 return true;
1536 }
1537
1538 RecordData Record;
1539 StringRef Blob;
1540 Expected<unsigned> MaybeCode = Cursor.ReadCode();
1541 if (!MaybeCode) {
1542 Error(MaybeCode.takeError());
1543 return true;
1544 }
1545 unsigned Code = MaybeCode.get();
1546
1547 Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
1548 if (!MaybeRecCode) {
1549 Error(MaybeRecCode.takeError());
1550 return true;
1551 }
1552 unsigned RecCode = MaybeRecCode.get();
1553 switch (VisibleKind) {
1554 case VisibleDeclContextStorageKind::GenerallyVisible:
1555 if (RecCode != DECL_CONTEXT_VISIBLE) {
1556 Error("Expected visible lookup table block");
1557 return true;
1558 }
1559 break;
1560 case VisibleDeclContextStorageKind::ModuleLocalVisible:
1561 if (RecCode != DECL_CONTEXT_MODULE_LOCAL_VISIBLE) {
1562 Error("Expected module local visible lookup table block");
1563 return true;
1564 }
1565 break;
1566 case VisibleDeclContextStorageKind::TULocalVisible:
1567 if (RecCode != DECL_CONTEXT_TU_LOCAL_VISIBLE) {
1568 Error("Expected TU local lookup table block");
1569 return true;
1570 }
1571 break;
1572 }
1573
1574 // We can't safely determine the primary context yet, so delay attaching the
1575 // lookup table until we're done with recursive deserialization.
1576 auto *Data = (const unsigned char*)Blob.data();
1577 switch (VisibleKind) {
1578 case VisibleDeclContextStorageKind::GenerallyVisible:
1579 PendingVisibleUpdates[ID].push_back(UpdateData{&M, Data});
1580 break;
1581 case VisibleDeclContextStorageKind::ModuleLocalVisible:
1582 PendingModuleLocalVisibleUpdates[ID].push_back(UpdateData{&M, Data});
1583 break;
1584 case VisibleDeclContextStorageKind::TULocalVisible:
1585 if (M.Kind == MK_MainFile)
1586 TULocalUpdates[ID].push_back(UpdateData{&M, Data});
1587 break;
1588 }
1589 return false;
1590}
1591
1592void ASTReader::AddSpecializations(const Decl *D, const unsigned char *Data,
1593 ModuleFile &M, bool IsPartial) {
1594 D = D->getCanonicalDecl();
1595 auto &SpecLookups =
1596 IsPartial ? PartialSpecializationsLookups : SpecializationsLookups;
1597 SpecLookups[D].Table.add(&M, Data,
1599}
1600
1601bool ASTReader::ReadSpecializations(ModuleFile &M, BitstreamCursor &Cursor,
1602 uint64_t Offset, Decl *D, bool IsPartial) {
1603 assert(Offset != 0);
1604
1605 SavedStreamPosition SavedPosition(Cursor);
1606 if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1607 Error(std::move(Err));
1608 return true;
1609 }
1610
1611 RecordData Record;
1612 StringRef Blob;
1613 Expected<unsigned> MaybeCode = Cursor.ReadCode();
1614 if (!MaybeCode) {
1615 Error(MaybeCode.takeError());
1616 return true;
1617 }
1618 unsigned Code = MaybeCode.get();
1619
1620 Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
1621 if (!MaybeRecCode) {
1622 Error(MaybeRecCode.takeError());
1623 return true;
1624 }
1625 unsigned RecCode = MaybeRecCode.get();
1626 if (RecCode != DECL_SPECIALIZATIONS &&
1627 RecCode != DECL_PARTIAL_SPECIALIZATIONS) {
1628 Error("Expected decl specs block");
1629 return true;
1630 }
1631
1632 auto *Data = (const unsigned char *)Blob.data();
1633 AddSpecializations(D, Data, M, IsPartial);
1634 return false;
1635}
1636
1637void ASTReader::Error(StringRef Msg) const {
1638 Error(diag::err_fe_ast_file_malformed, Msg);
1639 if (PP.getLangOpts().Modules &&
1640 !PP.getHeaderSearchInfo().getModuleCachePath().empty()) {
1641 Diag(diag::note_module_cache_path)
1642 << PP.getHeaderSearchInfo().getModuleCachePath();
1643 }
1644}
1645
1646void ASTReader::Error(unsigned DiagID, StringRef Arg1, StringRef Arg2,
1647 StringRef Arg3) const {
1648 Diag(DiagID) << Arg1 << Arg2 << Arg3;
1649}
1650
1651namespace {
1652struct AlreadyReportedDiagnosticError
1653 : llvm::ErrorInfo<AlreadyReportedDiagnosticError> {
1654 static char ID;
1655
1656 void log(raw_ostream &OS) const override {
1657 llvm_unreachable("reporting an already-reported diagnostic error");
1658 }
1659
1660 std::error_code convertToErrorCode() const override {
1661 return llvm::inconvertibleErrorCode();
1662 }
1663};
1664
1665char AlreadyReportedDiagnosticError::ID = 0;
1666} // namespace
1667
1668void ASTReader::Error(llvm::Error &&Err) const {
1669 handleAllErrors(
1670 std::move(Err), [](AlreadyReportedDiagnosticError &) {},
1671 [&](llvm::ErrorInfoBase &E) { return Error(E.message()); });
1672}
1673
1674//===----------------------------------------------------------------------===//
1675// Source Manager Deserialization
1676//===----------------------------------------------------------------------===//
1677
1678/// Read the line table in the source manager block.
1679void ASTReader::ParseLineTable(ModuleFile &F, const RecordData &Record) {
1680 unsigned Idx = 0;
1681 LineTableInfo &LineTable = SourceMgr.getLineTable();
1682
1683 // Parse the file names
1684 std::map<int, int> FileIDs;
1685 FileIDs[-1] = -1; // For unspecified filenames.
1686 for (unsigned I = 0; Record[Idx]; ++I) {
1687 // Extract the file name
1688 auto Filename = ReadPath(F, Record, Idx);
1689 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1690 }
1691 ++Idx;
1692
1693 // Parse the line entries
1694 std::vector<LineEntry> Entries;
1695 while (Idx < Record.size()) {
1696 FileID FID = ReadFileID(F, Record, Idx);
1697
1698 // Extract the line entries
1699 unsigned NumEntries = Record[Idx++];
1700 assert(NumEntries && "no line entries for file ID");
1701 Entries.clear();
1702 Entries.reserve(NumEntries);
1703 for (unsigned I = 0; I != NumEntries; ++I) {
1704 unsigned FileOffset = Record[Idx++];
1705 unsigned LineNo = Record[Idx++];
1706 int FilenameID = FileIDs[Record[Idx++]];
1709 unsigned IncludeOffset = Record[Idx++];
1710 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1711 FileKind, IncludeOffset));
1712 }
1713 LineTable.AddEntry(FID, Entries);
1714 }
1715}
1716
1717/// Read a source manager block
1718llvm::Error ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1719 using namespace SrcMgr;
1720
1721 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
1722
1723 // Set the source-location entry cursor to the current position in
1724 // the stream. This cursor will be used to read the contents of the
1725 // source manager block initially, and then lazily read
1726 // source-location entries as needed.
1727 SLocEntryCursor = F.Stream;
1728
1729 // The stream itself is going to skip over the source manager block.
1730 if (llvm::Error Err = F.Stream.SkipBlock())
1731 return Err;
1732
1733 // Enter the source manager block.
1734 if (llvm::Error Err = SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID))
1735 return Err;
1736 F.SourceManagerBlockStartOffset = SLocEntryCursor.GetCurrentBitNo();
1737
1738 RecordData Record;
1739 while (true) {
1740 Expected<llvm::BitstreamEntry> MaybeE =
1741 SLocEntryCursor.advanceSkippingSubblocks();
1742 if (!MaybeE)
1743 return MaybeE.takeError();
1744 llvm::BitstreamEntry E = MaybeE.get();
1745
1746 switch (E.Kind) {
1747 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1748 case llvm::BitstreamEntry::Error:
1749 return llvm::createStringError(std::errc::illegal_byte_sequence,
1750 "malformed block record in AST file");
1751 case llvm::BitstreamEntry::EndBlock:
1752 return llvm::Error::success();
1753 case llvm::BitstreamEntry::Record:
1754 // The interesting case.
1755 break;
1756 }
1757
1758 // Read a record.
1759 Record.clear();
1760 StringRef Blob;
1761 Expected<unsigned> MaybeRecord =
1762 SLocEntryCursor.readRecord(E.ID, Record, &Blob);
1763 if (!MaybeRecord)
1764 return MaybeRecord.takeError();
1765 switch (MaybeRecord.get()) {
1766 default: // Default behavior: ignore.
1767 break;
1768
1769 case SM_SLOC_FILE_ENTRY:
1772 // Once we hit one of the source location entries, we're done.
1773 return llvm::Error::success();
1774 }
1775 }
1776}
1777
1778llvm::Expected<SourceLocation::UIntTy>
1780 BitstreamCursor &Cursor = F->SLocEntryCursor;
1781 SavedStreamPosition SavedPosition(Cursor);
1782 if (llvm::Error Err = Cursor.JumpToBit(F->SLocEntryOffsetsBase +
1783 F->SLocEntryOffsets[Index]))
1784 return std::move(Err);
1785
1786 Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
1787 if (!MaybeEntry)
1788 return MaybeEntry.takeError();
1789
1790 llvm::BitstreamEntry Entry = MaybeEntry.get();
1791 if (Entry.Kind != llvm::BitstreamEntry::Record)
1792 return llvm::createStringError(
1793 std::errc::illegal_byte_sequence,
1794 "incorrectly-formatted source location entry in AST file");
1795
1797 StringRef Blob;
1798 Expected<unsigned> MaybeSLOC = Cursor.readRecord(Entry.ID, Record, &Blob);
1799 if (!MaybeSLOC)
1800 return MaybeSLOC.takeError();
1801
1802 switch (MaybeSLOC.get()) {
1803 default:
1804 return llvm::createStringError(
1805 std::errc::illegal_byte_sequence,
1806 "incorrectly-formatted source location entry in AST file");
1807 case SM_SLOC_FILE_ENTRY:
1810 return F->SLocEntryBaseOffset + Record[0];
1811 }
1812}
1813
1815 auto SLocMapI =
1816 GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset - SLocOffset - 1);
1817 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
1818 "Corrupted global sloc offset map");
1819 ModuleFile *F = SLocMapI->second;
1820
1821 bool Invalid = false;
1822
1823 auto It = llvm::upper_bound(
1824 llvm::index_range(0, F->LocalNumSLocEntries), SLocOffset,
1825 [&](SourceLocation::UIntTy Offset, std::size_t LocalIndex) {
1826 int ID = F->SLocEntryBaseID + LocalIndex;
1827 std::size_t Index = -ID - 2;
1828 if (!SourceMgr.SLocEntryOffsetLoaded[Index]) {
1829 assert(!SourceMgr.SLocEntryLoaded[Index]);
1830 auto MaybeEntryOffset = readSLocOffset(F, LocalIndex);
1831 if (!MaybeEntryOffset) {
1832 Error(MaybeEntryOffset.takeError());
1833 Invalid = true;
1834 return true;
1835 }
1836 SourceMgr.LoadedSLocEntryTable[Index] =
1837 SrcMgr::SLocEntry::getOffsetOnly(*MaybeEntryOffset);
1838 SourceMgr.SLocEntryOffsetLoaded[Index] = true;
1839 }
1840 return Offset < SourceMgr.LoadedSLocEntryTable[Index].getOffset();
1841 });
1842
1843 if (Invalid)
1844 return 0;
1845
1846 // The iterator points to the first entry with start offset greater than the
1847 // offset of interest. The previous entry must contain the offset of interest.
1848 return F->SLocEntryBaseID + *std::prev(It);
1849}
1850
1852 if (ID == 0)
1853 return false;
1854
1855 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1856 Error("source location entry ID out-of-range for AST file");
1857 return true;
1858 }
1859
1860 // Local helper to read the (possibly-compressed) buffer data following the
1861 // entry record.
1862 auto ReadBuffer = [this](
1863 BitstreamCursor &SLocEntryCursor,
1864 StringRef Name) -> std::unique_ptr<llvm::MemoryBuffer> {
1866 StringRef Blob;
1867 Expected<unsigned> MaybeCode = SLocEntryCursor.ReadCode();
1868 if (!MaybeCode) {
1869 Error(MaybeCode.takeError());
1870 return nullptr;
1871 }
1872 unsigned Code = MaybeCode.get();
1873
1874 Expected<unsigned> MaybeRecCode =
1875 SLocEntryCursor.readRecord(Code, Record, &Blob);
1876 if (!MaybeRecCode) {
1877 Error(MaybeRecCode.takeError());
1878 return nullptr;
1879 }
1880 unsigned RecCode = MaybeRecCode.get();
1881
1882 if (RecCode == SM_SLOC_BUFFER_BLOB_COMPRESSED) {
1883 // Inspect the first byte to differentiate zlib (\x78) and zstd
1884 // (little-endian 0xFD2FB528).
1885 const llvm::compression::Format F =
1886 Blob.size() > 0 && Blob.data()[0] == 0x78
1887 ? llvm::compression::Format::Zlib
1888 : llvm::compression::Format::Zstd;
1889 if (const char *Reason = llvm::compression::getReasonIfUnsupported(F)) {
1890 Error(Reason);
1891 return nullptr;
1892 }
1893 SmallVector<uint8_t, 0> Decompressed;
1894 if (llvm::Error E = llvm::compression::decompress(
1895 F, llvm::arrayRefFromStringRef(Blob), Decompressed, Record[0])) {
1896 Error("could not decompress embedded file contents: " +
1897 llvm::toString(std::move(E)));
1898 return nullptr;
1899 }
1900 return llvm::MemoryBuffer::getMemBufferCopy(
1901 llvm::toStringRef(Decompressed), Name);
1902 } else if (RecCode == SM_SLOC_BUFFER_BLOB) {
1903 return llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name, true);
1904 } else {
1905 Error("AST record has invalid code");
1906 return nullptr;
1907 }
1908 };
1909
1910 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1911 if (llvm::Error Err = F->SLocEntryCursor.JumpToBit(
1913 F->SLocEntryOffsets[ID - F->SLocEntryBaseID])) {
1914 Error(std::move(Err));
1915 return true;
1916 }
1917
1918 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
1920
1921 ++NumSLocEntriesRead;
1922 Expected<llvm::BitstreamEntry> MaybeEntry = SLocEntryCursor.advance();
1923 if (!MaybeEntry) {
1924 Error(MaybeEntry.takeError());
1925 return true;
1926 }
1927 llvm::BitstreamEntry Entry = MaybeEntry.get();
1928
1929 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1930 Error("incorrectly-formatted source location entry in AST file");
1931 return true;
1932 }
1933
1935 StringRef Blob;
1936 Expected<unsigned> MaybeSLOC =
1937 SLocEntryCursor.readRecord(Entry.ID, Record, &Blob);
1938 if (!MaybeSLOC) {
1939 Error(MaybeSLOC.takeError());
1940 return true;
1941 }
1942 switch (MaybeSLOC.get()) {
1943 default:
1944 Error("incorrectly-formatted source location entry in AST file");
1945 return true;
1946
1947 case SM_SLOC_FILE_ENTRY: {
1948 // We will detect whether a file changed and return 'Failure' for it, but
1949 // we will also try to fail gracefully by setting up the SLocEntry.
1950 unsigned InputID = Record[4];
1951 InputFile IF = getInputFile(*F, InputID);
1953 bool OverriddenBuffer = IF.isOverridden();
1954
1955 // Note that we only check if a File was returned. If it was out-of-date
1956 // we have complained but we will continue creating a FileID to recover
1957 // gracefully.
1958 if (!File)
1959 return true;
1960
1961 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1962 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1963 // This is the module's main file.
1964 IncludeLoc = getImportLocation(F);
1965 }
1967 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1968 FileID FID = SourceMgr.createFileID(*File, IncludeLoc, FileCharacter, ID,
1969 BaseOffset + Record[0]);
1970 SrcMgr::FileInfo &FileInfo = SourceMgr.getSLocEntry(FID).getFile();
1971 FileInfo.NumCreatedFIDs = Record[5];
1972 if (Record[3])
1973 FileInfo.setHasLineDirectives();
1974
1975 unsigned NumFileDecls = Record[7];
1976 if (NumFileDecls && ContextObj) {
1977 const unaligned_decl_id_t *FirstDecl = F->FileSortedDecls + Record[6];
1978 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1979 FileDeclIDs[FID] =
1980 FileDeclsInfo(F, llvm::ArrayRef(FirstDecl, NumFileDecls));
1981 }
1982
1983 const SrcMgr::ContentCache &ContentCache =
1984 SourceMgr.getOrCreateContentCache(*File, isSystem(FileCharacter));
1985 if (OverriddenBuffer && !ContentCache.BufferOverridden &&
1986 ContentCache.ContentsEntry == ContentCache.OrigEntry &&
1987 !ContentCache.getBufferIfLoaded()) {
1988 auto Buffer = ReadBuffer(SLocEntryCursor, File->getName());
1989 if (!Buffer)
1990 return true;
1991 SourceMgr.overrideFileContents(*File, std::move(Buffer));
1992 }
1993
1994 break;
1995 }
1996
1997 case SM_SLOC_BUFFER_ENTRY: {
1998 const char *Name = Blob.data();
1999 unsigned Offset = Record[0];
2001 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
2002 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
2003 if (IncludeLoc.isInvalid() && F->isModule()) {
2004 IncludeLoc = getImportLocation(F);
2005 }
2006
2007 auto Buffer = ReadBuffer(SLocEntryCursor, Name);
2008 if (!Buffer)
2009 return true;
2010 FileID FID = SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
2011 BaseOffset + Offset, IncludeLoc);
2012 if (Record[3]) {
2013 auto &FileInfo = SourceMgr.getSLocEntry(FID).getFile();
2014 FileInfo.setHasLineDirectives();
2015 }
2016 break;
2017 }
2018
2020 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
2021 SourceLocation ExpansionBegin = ReadSourceLocation(*F, Record[2]);
2022 SourceLocation ExpansionEnd = ReadSourceLocation(*F, Record[3]);
2023 SourceMgr.createExpansionLoc(SpellingLoc, ExpansionBegin, ExpansionEnd,
2024 Record[5], Record[4], ID,
2025 BaseOffset + Record[0]);
2026 break;
2027 }
2028 }
2029
2030 return false;
2031}
2032
2033std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
2034 if (ID == 0)
2035 return std::make_pair(SourceLocation(), "");
2036
2037 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
2038 Error("source location entry ID out-of-range for AST file");
2039 return std::make_pair(SourceLocation(), "");
2040 }
2041
2042 // Find which module file this entry lands in.
2043 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
2044 if (!M->isModule())
2045 return std::make_pair(SourceLocation(), "");
2046
2047 // FIXME: Can we map this down to a particular submodule? That would be
2048 // ideal.
2049 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
2050}
2051
2052/// Find the location where the module F is imported.
2053SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
2054 if (F->ImportLoc.isValid())
2055 return F->ImportLoc;
2056
2057 // Otherwise we have a PCH. It's considered to be "imported" at the first
2058 // location of its includer.
2059 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
2060 // Main file is the importer.
2061 assert(SourceMgr.getMainFileID().isValid() && "missing main file");
2062 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
2063 }
2064 return F->ImportedBy[0]->FirstLoc;
2065}
2066
2067/// Enter a subblock of the specified BlockID with the specified cursor. Read
2068/// the abbreviations that are at the top of the block and then leave the cursor
2069/// pointing into the block.
2070llvm::Error ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor,
2071 unsigned BlockID,
2072 uint64_t *StartOfBlockOffset) {
2073 if (llvm::Error Err = Cursor.EnterSubBlock(BlockID))
2074 return Err;
2075
2076 if (StartOfBlockOffset)
2077 *StartOfBlockOffset = Cursor.GetCurrentBitNo();
2078
2079 while (true) {
2080 uint64_t Offset = Cursor.GetCurrentBitNo();
2081 Expected<unsigned> MaybeCode = Cursor.ReadCode();
2082 if (!MaybeCode)
2083 return MaybeCode.takeError();
2084 unsigned Code = MaybeCode.get();
2085
2086 // We expect all abbrevs to be at the start of the block.
2087 if (Code != llvm::bitc::DEFINE_ABBREV) {
2088 if (llvm::Error Err = Cursor.JumpToBit(Offset))
2089 return Err;
2090 return llvm::Error::success();
2091 }
2092 if (llvm::Error Err = Cursor.ReadAbbrevRecord())
2093 return Err;
2094 }
2095}
2096
2098 unsigned &Idx) {
2099 Token Tok;
2100 Tok.startToken();
2101 Tok.setLocation(ReadSourceLocation(M, Record, Idx));
2102 Tok.setKind((tok::TokenKind)Record[Idx++]);
2103 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
2104
2105 if (Tok.isAnnotation()) {
2106 Tok.setAnnotationEndLoc(ReadSourceLocation(M, Record, Idx));
2107 switch (Tok.getKind()) {
2108 case tok::annot_pragma_loop_hint: {
2109 auto *Info = new (PP.getPreprocessorAllocator()) PragmaLoopHintInfo;
2110 Info->PragmaName = ReadToken(M, Record, Idx);
2111 Info->Option = ReadToken(M, Record, Idx);
2112 unsigned NumTokens = Record[Idx++];
2114 Toks.reserve(NumTokens);
2115 for (unsigned I = 0; I < NumTokens; ++I)
2116 Toks.push_back(ReadToken(M, Record, Idx));
2117 Info->Toks = llvm::ArrayRef(Toks).copy(PP.getPreprocessorAllocator());
2118 Tok.setAnnotationValue(static_cast<void *>(Info));
2119 break;
2120 }
2121 case tok::annot_pragma_pack: {
2122 auto *Info = new (PP.getPreprocessorAllocator()) Sema::PragmaPackInfo;
2123 Info->Action = static_cast<Sema::PragmaMsStackAction>(Record[Idx++]);
2124 auto SlotLabel = ReadString(Record, Idx);
2125 Info->SlotLabel =
2126 llvm::StringRef(SlotLabel).copy(PP.getPreprocessorAllocator());
2127 Info->Alignment = ReadToken(M, Record, Idx);
2128 Tok.setAnnotationValue(static_cast<void *>(Info));
2129 break;
2130 }
2131 // Some annotation tokens do not use the PtrData field.
2132 case tok::annot_pragma_openmp:
2133 case tok::annot_pragma_openmp_end:
2134 case tok::annot_pragma_unused:
2135 case tok::annot_pragma_openacc:
2136 case tok::annot_pragma_openacc_end:
2137 case tok::annot_repl_input_end:
2138 break;
2139 default:
2140 llvm_unreachable("missing deserialization code for annotation token");
2141 }
2142 } else {
2143 Tok.setLength(Record[Idx++]);
2144 if (IdentifierInfo *II = getLocalIdentifier(M, Record[Idx++]))
2145 Tok.setIdentifierInfo(II);
2146 }
2147 return Tok;
2148}
2149
2151 BitstreamCursor &Stream = F.MacroCursor;
2152
2153 // Keep track of where we are in the stream, then jump back there
2154 // after reading this macro.
2155 SavedStreamPosition SavedPosition(Stream);
2156
2157 if (llvm::Error Err = Stream.JumpToBit(Offset)) {
2158 // FIXME this drops errors on the floor.
2159 consumeError(std::move(Err));
2160 return nullptr;
2161 }
2164 MacroInfo *Macro = nullptr;
2165 llvm::MutableArrayRef<Token> MacroTokens;
2166
2167 while (true) {
2168 // Advance to the next record, but if we get to the end of the block, don't
2169 // pop it (removing all the abbreviations from the cursor) since we want to
2170 // be able to reseek within the block and read entries.
2171 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
2173 Stream.advanceSkippingSubblocks(Flags);
2174 if (!MaybeEntry) {
2175 Error(MaybeEntry.takeError());
2176 return Macro;
2177 }
2178 llvm::BitstreamEntry Entry = MaybeEntry.get();
2179
2180 switch (Entry.Kind) {
2181 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
2182 case llvm::BitstreamEntry::Error:
2183 Error("malformed block record in AST file");
2184 return Macro;
2185 case llvm::BitstreamEntry::EndBlock:
2186 return Macro;
2187 case llvm::BitstreamEntry::Record:
2188 // The interesting case.
2189 break;
2190 }
2191
2192 // Read a record.
2193 Record.clear();
2195 if (Expected<unsigned> MaybeRecType = Stream.readRecord(Entry.ID, Record))
2196 RecType = (PreprocessorRecordTypes)MaybeRecType.get();
2197 else {
2198 Error(MaybeRecType.takeError());
2199 return Macro;
2200 }
2201 switch (RecType) {
2202 case PP_MODULE_MACRO:
2204 return Macro;
2205
2208 // If we already have a macro, that means that we've hit the end
2209 // of the definition of the macro we were looking for. We're
2210 // done.
2211 if (Macro)
2212 return Macro;
2213
2214 unsigned NextIndex = 1; // Skip identifier ID.
2215 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
2216 MacroInfo *MI = PP.AllocateMacroInfo(Loc);
2217 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
2218 MI->setIsUsed(Record[NextIndex++]);
2219 MI->setUsedForHeaderGuard(Record[NextIndex++]);
2220 MacroTokens = MI->allocateTokens(Record[NextIndex++],
2221 PP.getPreprocessorAllocator());
2222 if (RecType == PP_MACRO_FUNCTION_LIKE) {
2223 // Decode function-like macro info.
2224 bool isC99VarArgs = Record[NextIndex++];
2225 bool isGNUVarArgs = Record[NextIndex++];
2226 bool hasCommaPasting = Record[NextIndex++];
2227 MacroParams.clear();
2228 unsigned NumArgs = Record[NextIndex++];
2229 for (unsigned i = 0; i != NumArgs; ++i)
2230 MacroParams.push_back(getLocalIdentifier(F, Record[NextIndex++]));
2231
2232 // Install function-like macro info.
2233 MI->setIsFunctionLike();
2234 if (isC99VarArgs) MI->setIsC99Varargs();
2235 if (isGNUVarArgs) MI->setIsGNUVarargs();
2236 if (hasCommaPasting) MI->setHasCommaPasting();
2237 MI->setParameterList(MacroParams, PP.getPreprocessorAllocator());
2238 }
2239
2240 // Remember that we saw this macro last so that we add the tokens that
2241 // form its body to it.
2242 Macro = MI;
2243
2244 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
2245 Record[NextIndex]) {
2246 // We have a macro definition. Register the association
2248 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
2249 unsigned Index = translatePreprocessedEntityIDToIndex(GlobalID);
2250 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
2251 PreprocessingRecord::PPEntityID PPID =
2252 PPRec.getPPEntityID(Index, /*isLoaded=*/true);
2253 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
2254 PPRec.getPreprocessedEntity(PPID));
2255 if (PPDef)
2256 PPRec.RegisterMacroDefinition(Macro, PPDef);
2257 }
2258
2259 ++NumMacrosRead;
2260 break;
2261 }
2262
2263 case PP_TOKEN: {
2264 // If we see a TOKEN before a PP_MACRO_*, then the file is
2265 // erroneous, just pretend we didn't see this.
2266 if (!Macro) break;
2267 if (MacroTokens.empty()) {
2268 Error("unexpected number of macro tokens for a macro in AST file");
2269 return Macro;
2270 }
2271
2272 unsigned Idx = 0;
2273 MacroTokens[0] = ReadToken(F, Record, Idx);
2274 MacroTokens = MacroTokens.drop_front();
2275 break;
2276 }
2277 }
2278 }
2279}
2280
2283 PreprocessedEntityID LocalID) const {
2284 if (!M.ModuleOffsetMap.empty())
2285 ReadModuleOffsetMap(M);
2286
2287 unsigned ModuleFileIndex = LocalID >> 32;
2288 LocalID &= llvm::maskTrailingOnes<PreprocessedEntityID>(32);
2289 ModuleFile *MF =
2290 ModuleFileIndex ? M.TransitiveImports[ModuleFileIndex - 1] : &M;
2291 assert(MF && "malformed identifier ID encoding?");
2292
2293 if (!ModuleFileIndex) {
2294 assert(LocalID >= NUM_PREDEF_PP_ENTITY_IDS);
2295 LocalID -= NUM_PREDEF_PP_ENTITY_IDS;
2296 }
2297
2298 return (static_cast<PreprocessedEntityID>(MF->Index + 1) << 32) | LocalID;
2299}
2300
2302HeaderFileInfoTrait::getFile(const internal_key_type &Key) {
2303 FileManager &FileMgr = Reader.getFileManager();
2304 if (!Key.Imported)
2305 return FileMgr.getOptionalFileRef(Key.Filename);
2306
2307 auto Resolved =
2308 ASTReader::ResolveImportedPath(Reader.getPathBuf(), Key.Filename, M);
2309 return FileMgr.getOptionalFileRef(*Resolved);
2310}
2311
2313 uint8_t buf[sizeof(ikey.Size) + sizeof(ikey.ModTime)];
2314 memcpy(buf, &ikey.Size, sizeof(ikey.Size));
2315 memcpy(buf + sizeof(ikey.Size), &ikey.ModTime, sizeof(ikey.ModTime));
2316 return llvm::xxh3_64bits(buf);
2317}
2318
2321 internal_key_type ikey = {ekey.getSize(),
2322 M.HasTimestamps ? ekey.getModificationTime() : 0,
2323 ekey.getName(), /*Imported*/ false};
2324 return ikey;
2325}
2326
2328 if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime))
2329 return false;
2330
2331 if (llvm::sys::path::is_absolute(a.Filename) && a.Filename == b.Filename)
2332 return true;
2333
2334 // Determine whether the actual files are equivalent.
2335 OptionalFileEntryRef FEA = getFile(a);
2336 OptionalFileEntryRef FEB = getFile(b);
2337 return FEA && FEA == FEB;
2338}
2339
2340std::pair<unsigned, unsigned>
2342 return readULEBKeyDataLength(d);
2343}
2344
2346HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
2347 using namespace llvm::support;
2348
2349 internal_key_type ikey;
2350 ikey.Size = off_t(endian::readNext<uint64_t, llvm::endianness::little>(d));
2351 ikey.ModTime =
2352 time_t(endian::readNext<uint64_t, llvm::endianness::little>(d));
2353 ikey.Filename = (const char *)d;
2354 ikey.Imported = true;
2355 return ikey;
2356}
2357
2360 unsigned DataLen) {
2361 using namespace llvm::support;
2362
2363 const unsigned char *End = d + DataLen;
2364 HeaderFileInfo HFI;
2365 unsigned Flags = *d++;
2366
2368 bool Included = (Flags >> 6) & 0x01;
2369 if (Included)
2370 if ((FE = getFile(key)))
2371 // Not using \c Preprocessor::markIncluded(), since that would attempt to
2372 // deserialize this header file info again.
2373 Reader.getPreprocessor().getIncludedFiles().insert(*FE);
2374
2375 // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
2376 HFI.isImport |= (Flags >> 5) & 0x01;
2377 HFI.isPragmaOnce |= (Flags >> 4) & 0x01;
2378 HFI.DirInfo = (Flags >> 1) & 0x07;
2379 HFI.LazyControllingMacro = Reader.getGlobalIdentifierID(
2380 M, endian::readNext<IdentifierID, llvm::endianness::little>(d));
2381
2382 assert((End - d) % 4 == 0 &&
2383 "Wrong data length in HeaderFileInfo deserialization");
2384 while (d != End) {
2385 uint32_t LocalSMID =
2386 endian::readNext<uint32_t, llvm::endianness::little>(d);
2387 auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 7);
2388 LocalSMID >>= 3;
2389
2390 // This header is part of a module. Associate it with the module to enable
2391 // implicit module import.
2392 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
2393 Module *Mod = Reader.getSubmodule(GlobalSMID);
2394 ModuleMap &ModMap =
2395 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
2396
2397 if (FE || (FE = getFile(key))) {
2398 // FIXME: NameAsWritten
2399 Module::Header H = {std::string(key.Filename), "", *FE};
2400 ModMap.addHeader(Mod, H, HeaderRole, /*Imported=*/true);
2401 }
2402 HFI.mergeModuleMembership(HeaderRole);
2403 }
2404
2405 // This HeaderFileInfo was externally loaded.
2406 HFI.External = true;
2407 HFI.IsValid = true;
2408 return HFI;
2409}
2410
2412 uint32_t MacroDirectivesOffset) {
2413 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
2414 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
2415}
2416
2418 // Note that we are loading defined macros.
2419 Deserializing Macros(this);
2420
2421 for (ModuleFile &I : llvm::reverse(ModuleMgr)) {
2422 BitstreamCursor &MacroCursor = I.MacroCursor;
2423
2424 // If there was no preprocessor block, skip this file.
2425 if (MacroCursor.getBitcodeBytes().empty())
2426 continue;
2427
2428 BitstreamCursor Cursor = MacroCursor;
2429 if (llvm::Error Err = Cursor.JumpToBit(I.MacroStartOffset)) {
2430 Error(std::move(Err));
2431 return;
2432 }
2433
2435 while (true) {
2436 Expected<llvm::BitstreamEntry> MaybeE = Cursor.advanceSkippingSubblocks();
2437 if (!MaybeE) {
2438 Error(MaybeE.takeError());
2439 return;
2440 }
2441 llvm::BitstreamEntry E = MaybeE.get();
2442
2443 switch (E.Kind) {
2444 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
2445 case llvm::BitstreamEntry::Error:
2446 Error("malformed block record in AST file");
2447 return;
2448 case llvm::BitstreamEntry::EndBlock:
2449 goto NextCursor;
2450
2451 case llvm::BitstreamEntry::Record: {
2452 Record.clear();
2453 Expected<unsigned> MaybeRecord = Cursor.readRecord(E.ID, Record);
2454 if (!MaybeRecord) {
2455 Error(MaybeRecord.takeError());
2456 return;
2457 }
2458 switch (MaybeRecord.get()) {
2459 default: // Default behavior: ignore.
2460 break;
2461
2465 if (II->isOutOfDate())
2467 break;
2468 }
2469
2470 case PP_TOKEN:
2471 // Ignore tokens.
2472 break;
2473 }
2474 break;
2475 }
2476 }
2477 }
2478 NextCursor: ;
2479 }
2480}
2481
2482namespace {
2483
2484 /// Visitor class used to look up identifirs in an AST file.
2485 class IdentifierLookupVisitor {
2486 StringRef Name;
2487 unsigned NameHash;
2488 unsigned PriorGeneration;
2489 unsigned &NumIdentifierLookups;
2490 unsigned &NumIdentifierLookupHits;
2491 IdentifierInfo *Found = nullptr;
2492
2493 public:
2494 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
2495 unsigned &NumIdentifierLookups,
2496 unsigned &NumIdentifierLookupHits)
2497 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
2498 PriorGeneration(PriorGeneration),
2499 NumIdentifierLookups(NumIdentifierLookups),
2500 NumIdentifierLookupHits(NumIdentifierLookupHits) {}
2501
2502 bool operator()(ModuleFile &M) {
2503 // If we've already searched this module file, skip it now.
2504 if (M.Generation <= PriorGeneration)
2505 return true;
2506
2509 if (!IdTable)
2510 return false;
2511
2512 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
2513 Found);
2514 ++NumIdentifierLookups;
2515 ASTIdentifierLookupTable::iterator Pos =
2516 IdTable->find_hashed(Name, NameHash, &Trait);
2517 if (Pos == IdTable->end())
2518 return false;
2519
2520 // Dereferencing the iterator has the effect of building the
2521 // IdentifierInfo node and populating it with the various
2522 // declarations it needs.
2523 ++NumIdentifierLookupHits;
2524 Found = *Pos;
2525 if (Trait.hasMoreInformationInDependencies()) {
2526 // Look for the identifier in extra modules as they contain more info.
2527 return false;
2528 }
2529 return true;
2530 }
2531
2532 // Retrieve the identifier info found within the module
2533 // files.
2534 IdentifierInfo *getIdentifierInfo() const { return Found; }
2535 };
2536
2537} // namespace
2538
2540 // Note that we are loading an identifier.
2541 Deserializing AnIdentifier(this);
2542
2543 unsigned PriorGeneration = 0;
2544 if (getContext().getLangOpts().Modules)
2545 PriorGeneration = IdentifierGeneration[&II];
2546
2547 // If there is a global index, look there first to determine which modules
2548 // provably do not have any results for this identifier.
2550 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
2551 if (!loadGlobalIndex()) {
2552 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
2553 HitsPtr = &Hits;
2554 }
2555 }
2556
2557 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
2558 NumIdentifierLookups,
2559 NumIdentifierLookupHits);
2560 ModuleMgr.visit(Visitor, HitsPtr);
2562}
2563
2565 if (!II)
2566 return;
2567
2568 const_cast<IdentifierInfo *>(II)->setOutOfDate(false);
2569
2570 // Update the generation for this identifier.
2571 if (getContext().getLangOpts().Modules)
2572 IdentifierGeneration[II] = getGeneration();
2573}
2574
2576 unsigned &Idx) {
2577 uint64_t ModuleFileIndex = Record[Idx++] << 32;
2578 uint64_t LocalIndex = Record[Idx++];
2579 return getGlobalMacroID(F, (ModuleFileIndex | LocalIndex));
2580}
2581
2583 const PendingMacroInfo &PMInfo) {
2584 ModuleFile &M = *PMInfo.M;
2585
2586 BitstreamCursor &Cursor = M.MacroCursor;
2587 SavedStreamPosition SavedPosition(Cursor);
2588 if (llvm::Error Err =
2589 Cursor.JumpToBit(M.MacroOffsetsBase + PMInfo.MacroDirectivesOffset)) {
2590 Error(std::move(Err));
2591 return;
2592 }
2593
2594 struct ModuleMacroRecord {
2595 SubmoduleID SubModID;
2596 MacroInfo *MI;
2598 };
2600
2601 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
2602 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
2603 // macro histroy.
2605 while (true) {
2607 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
2608 if (!MaybeEntry) {
2609 Error(MaybeEntry.takeError());
2610 return;
2611 }
2612 llvm::BitstreamEntry Entry = MaybeEntry.get();
2613
2614 if (Entry.Kind != llvm::BitstreamEntry::Record) {
2615 Error("malformed block record in AST file");
2616 return;
2617 }
2618
2619 Record.clear();
2620 Expected<unsigned> MaybePP = Cursor.readRecord(Entry.ID, Record);
2621 if (!MaybePP) {
2622 Error(MaybePP.takeError());
2623 return;
2624 }
2625 switch ((PreprocessorRecordTypes)MaybePP.get()) {
2627 break;
2628
2629 case PP_MODULE_MACRO: {
2630 ModuleMacros.push_back(ModuleMacroRecord());
2631 auto &Info = ModuleMacros.back();
2632 unsigned Idx = 0;
2633 Info.SubModID = getGlobalSubmoduleID(M, Record[Idx++]);
2634 Info.MI = getMacro(ReadMacroID(M, Record, Idx));
2635 for (int I = Idx, N = Record.size(); I != N; ++I)
2636 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
2637 continue;
2638 }
2639
2640 default:
2641 Error("malformed block record in AST file");
2642 return;
2643 }
2644
2645 // We found the macro directive history; that's the last record
2646 // for this macro.
2647 break;
2648 }
2649
2650 // Module macros are listed in reverse dependency order.
2651 {
2652 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
2654 for (auto &MMR : ModuleMacros) {
2655 Overrides.clear();
2656 for (unsigned ModID : MMR.Overrides) {
2657 Module *Mod = getSubmodule(ModID);
2658 auto *Macro = PP.getModuleMacro(Mod, II);
2659 assert(Macro && "missing definition for overridden macro");
2660 Overrides.push_back(Macro);
2661 }
2662
2663 bool Inserted = false;
2664 Module *Owner = getSubmodule(MMR.SubModID);
2665 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
2666 }
2667 }
2668
2669 // Don't read the directive history for a module; we don't have anywhere
2670 // to put it.
2671 if (M.isModule())
2672 return;
2673
2674 // Deserialize the macro directives history in reverse source-order.
2675 MacroDirective *Latest = nullptr, *Earliest = nullptr;
2676 unsigned Idx = 0, N = Record.size();
2677 while (Idx < N) {
2678 MacroDirective *MD = nullptr;
2681 switch (K) {
2683 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
2684 MD = PP.AllocateDefMacroDirective(MI, Loc);
2685 break;
2686 }
2688 MD = PP.AllocateUndefMacroDirective(Loc);
2689 break;
2691 bool isPublic = Record[Idx++];
2692 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
2693 break;
2694 }
2695
2696 if (!Latest)
2697 Latest = MD;
2698 if (Earliest)
2699 Earliest->setPrevious(MD);
2700 Earliest = MD;
2701 }
2702
2703 if (Latest)
2704 PP.setLoadedMacroDirective(II, Earliest, Latest);
2705}
2706
2707bool ASTReader::shouldDisableValidationForFile(
2708 const serialization::ModuleFile &M) const {
2709 if (DisableValidationKind == DisableValidationForModuleKind::None)
2710 return false;
2711
2712 // If a PCH is loaded and validation is disabled for PCH then disable
2713 // validation for the PCH and the modules it loads.
2714 ModuleKind K = CurrentDeserializingModuleKind.value_or(M.Kind);
2715
2716 switch (K) {
2717 case MK_MainFile:
2718 case MK_Preamble:
2719 case MK_PCH:
2720 return bool(DisableValidationKind & DisableValidationForModuleKind::PCH);
2721 case MK_ImplicitModule:
2722 case MK_ExplicitModule:
2723 case MK_PrebuiltModule:
2724 return bool(DisableValidationKind & DisableValidationForModuleKind::Module);
2725 }
2726
2727 return false;
2728}
2729
2730static std::pair<StringRef, StringRef>
2732 const StringRef InputBlob) {
2733 uint16_t AsRequestedLength = Record[7];
2734 return {InputBlob.substr(0, AsRequestedLength),
2735 InputBlob.substr(AsRequestedLength)};
2736}
2737
2738InputFileInfo ASTReader::getInputFileInfo(ModuleFile &F, unsigned ID) {
2739 // If this ID is bogus, just return an empty input file.
2740 if (ID == 0 || ID > F.InputFileInfosLoaded.size())
2741 return InputFileInfo();
2742
2743 // If we've already loaded this input file, return it.
2744 if (F.InputFileInfosLoaded[ID - 1].isValid())
2745 return F.InputFileInfosLoaded[ID - 1];
2746
2747 // Go find this input file.
2748 BitstreamCursor &Cursor = F.InputFilesCursor;
2749 SavedStreamPosition SavedPosition(Cursor);
2750 if (llvm::Error Err = Cursor.JumpToBit(F.InputFilesOffsetBase +
2751 F.InputFileOffsets[ID - 1])) {
2752 // FIXME this drops errors on the floor.
2753 consumeError(std::move(Err));
2754 }
2755
2756 Expected<unsigned> MaybeCode = Cursor.ReadCode();
2757 if (!MaybeCode) {
2758 // FIXME this drops errors on the floor.
2759 consumeError(MaybeCode.takeError());
2760 }
2761 unsigned Code = MaybeCode.get();
2762 RecordData Record;
2763 StringRef Blob;
2764
2765 if (Expected<unsigned> Maybe = Cursor.readRecord(Code, Record, &Blob))
2766 assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE &&
2767 "invalid record type for input file");
2768 else {
2769 // FIXME this drops errors on the floor.
2770 consumeError(Maybe.takeError());
2771 }
2772
2773 assert(Record[0] == ID && "Bogus stored ID or offset");
2774 InputFileInfo R;
2775 R.StoredSize = static_cast<off_t>(Record[1]);
2776 R.StoredTime = static_cast<time_t>(Record[2]);
2777 R.Overridden = static_cast<bool>(Record[3]);
2778 R.Transient = static_cast<bool>(Record[4]);
2779 R.TopLevel = static_cast<bool>(Record[5]);
2780 R.ModuleMap = static_cast<bool>(Record[6]);
2781 auto [UnresolvedFilenameAsRequested, UnresolvedFilename] =
2783 R.UnresolvedImportedFilenameAsRequested = UnresolvedFilenameAsRequested;
2784 R.UnresolvedImportedFilename = UnresolvedFilename.empty()
2785 ? UnresolvedFilenameAsRequested
2786 : UnresolvedFilename;
2787
2788 Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
2789 if (!MaybeEntry) // FIXME this drops errors on the floor.
2790 consumeError(MaybeEntry.takeError());
2791 llvm::BitstreamEntry Entry = MaybeEntry.get();
2792 assert(Entry.Kind == llvm::BitstreamEntry::Record &&
2793 "expected record type for input file hash");
2794
2795 Record.clear();
2796 if (Expected<unsigned> Maybe = Cursor.readRecord(Entry.ID, Record))
2797 assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE_HASH &&
2798 "invalid record type for input file hash");
2799 else {
2800 // FIXME this drops errors on the floor.
2801 consumeError(Maybe.takeError());
2802 }
2803 R.ContentHash = (static_cast<uint64_t>(Record[1]) << 32) |
2804 static_cast<uint64_t>(Record[0]);
2805
2806 // Note that we've loaded this input file info.
2807 F.InputFileInfosLoaded[ID - 1] = R;
2808 return R;
2809}
2810
2811static unsigned moduleKindForDiagnostic(ModuleKind Kind);
2812InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
2813 // If this ID is bogus, just return an empty input file.
2814 if (ID == 0 || ID > F.InputFilesLoaded.size())
2815 return InputFile();
2816
2817 // If we've already loaded this input file, return it.
2818 if (F.InputFilesLoaded[ID-1].getFile())
2819 return F.InputFilesLoaded[ID-1];
2820
2821 if (F.InputFilesLoaded[ID-1].isNotFound())
2822 return InputFile();
2823
2824 // Go find this input file.
2825 BitstreamCursor &Cursor = F.InputFilesCursor;
2826 SavedStreamPosition SavedPosition(Cursor);
2827 if (llvm::Error Err = Cursor.JumpToBit(F.InputFilesOffsetBase +
2828 F.InputFileOffsets[ID - 1])) {
2829 // FIXME this drops errors on the floor.
2830 consumeError(std::move(Err));
2831 }
2832
2833 InputFileInfo FI = getInputFileInfo(F, ID);
2834 off_t StoredSize = FI.StoredSize;
2835 time_t StoredTime = FI.StoredTime;
2836 bool Overridden = FI.Overridden;
2837 bool Transient = FI.Transient;
2838 auto Filename =
2839 ResolveImportedPath(PathBuf, FI.UnresolvedImportedFilenameAsRequested, F);
2840 uint64_t StoredContentHash = FI.ContentHash;
2841
2842 // For standard C++ modules, we don't need to check the inputs.
2843 bool SkipChecks = F.StandardCXXModule;
2844
2845 const HeaderSearchOptions &HSOpts =
2846 PP.getHeaderSearchInfo().getHeaderSearchOpts();
2847
2848 // The option ForceCheckCXX20ModulesInputFiles is only meaningful for C++20
2849 // modules.
2851 SkipChecks = false;
2852 Overridden = false;
2853 }
2854
2855 auto File = FileMgr.getOptionalFileRef(*Filename, /*OpenFile=*/false);
2856
2857 // For an overridden file, create a virtual file with the stored
2858 // size/timestamp.
2859 if ((Overridden || Transient || SkipChecks) && !File)
2860 File = FileMgr.getVirtualFileRef(*Filename, StoredSize, StoredTime);
2861
2862 if (!File) {
2863 if (Complain) {
2864 std::string ErrorStr = "could not find file '";
2865 ErrorStr += *Filename;
2866 ErrorStr += "' referenced by AST file '";
2867 ErrorStr += F.FileName;
2868 ErrorStr += "'";
2869 Error(ErrorStr);
2870 }
2871 // Record that we didn't find the file.
2873 return InputFile();
2874 }
2875
2876 // Check if there was a request to override the contents of the file
2877 // that was part of the precompiled header. Overriding such a file
2878 // can lead to problems when lexing using the source locations from the
2879 // PCH.
2880 SourceManager &SM = getSourceManager();
2881 // FIXME: Reject if the overrides are different.
2882 if ((!Overridden && !Transient) && !SkipChecks &&
2883 SM.isFileOverridden(*File)) {
2884 if (Complain)
2885 Error(diag::err_fe_pch_file_overridden, *Filename);
2886
2887 // After emitting the diagnostic, bypass the overriding file to recover
2888 // (this creates a separate FileEntry).
2889 File = SM.bypassFileContentsOverride(*File);
2890 if (!File) {
2892 return InputFile();
2893 }
2894 }
2895
2896 struct Change {
2897 enum ModificationKind {
2898 Size,
2899 ModTime,
2900 Content,
2901 None,
2902 } Kind;
2903 std::optional<int64_t> Old = std::nullopt;
2904 std::optional<int64_t> New = std::nullopt;
2905 };
2906 auto HasInputContentChanged = [&](Change OriginalChange) {
2907 assert(ValidateASTInputFilesContent &&
2908 "We should only check the content of the inputs with "
2909 "ValidateASTInputFilesContent enabled.");
2910
2911 if (StoredContentHash == 0)
2912 return OriginalChange;
2913
2914 auto MemBuffOrError = FileMgr.getBufferForFile(*File);
2915 if (!MemBuffOrError) {
2916 if (!Complain)
2917 return OriginalChange;
2918 std::string ErrorStr = "could not get buffer for file '";
2919 ErrorStr += File->getName();
2920 ErrorStr += "'";
2921 Error(ErrorStr);
2922 return OriginalChange;
2923 }
2924
2925 auto ContentHash = xxh3_64bits(MemBuffOrError.get()->getBuffer());
2926 if (StoredContentHash == static_cast<uint64_t>(ContentHash))
2927 return Change{Change::None};
2928
2929 return Change{Change::Content};
2930 };
2931 auto HasInputFileChanged = [&]() {
2932 if (StoredSize != File->getSize())
2933 return Change{Change::Size, StoredSize, File->getSize()};
2934 if (!shouldDisableValidationForFile(F) && StoredTime &&
2935 StoredTime != File->getModificationTime()) {
2936 Change MTimeChange = {Change::ModTime, StoredTime,
2937 File->getModificationTime()};
2938
2939 // In case the modification time changes but not the content,
2940 // accept the cached file as legit.
2941 if (ValidateASTInputFilesContent)
2942 return HasInputContentChanged(MTimeChange);
2943
2944 return MTimeChange;
2945 }
2946 return Change{Change::None};
2947 };
2948
2949 bool IsOutOfDate = false;
2950 auto FileChange = SkipChecks ? Change{Change::None} : HasInputFileChanged();
2951 // When ForceCheckCXX20ModulesInputFiles and ValidateASTInputFilesContent
2952 // enabled, it is better to check the contents of the inputs. Since we can't
2953 // get correct modified time information for inputs from overriden inputs.
2954 if (HSOpts.ForceCheckCXX20ModulesInputFiles && ValidateASTInputFilesContent &&
2955 F.StandardCXXModule && FileChange.Kind == Change::None)
2956 FileChange = HasInputContentChanged(FileChange);
2957
2958 // When we have StoredTime equal to zero and ValidateASTInputFilesContent,
2959 // it is better to check the content of the input files because we cannot rely
2960 // on the file modification time, which will be the same (zero) for these
2961 // files.
2962 if (!StoredTime && ValidateASTInputFilesContent &&
2963 FileChange.Kind == Change::None)
2964 FileChange = HasInputContentChanged(FileChange);
2965
2966 // For an overridden file, there is nothing to validate.
2967 if (!Overridden && FileChange.Kind != Change::None) {
2968 if (Complain) {
2969 // Build a list of the PCH imports that got us here (in reverse).
2970 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2971 while (!ImportStack.back()->ImportedBy.empty())
2972 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
2973
2974 // The top-level AST file is stale.
2975 StringRef TopLevelASTFileName(ImportStack.back()->FileName);
2976 Diag(diag::err_fe_ast_file_modified)
2977 << *Filename << moduleKindForDiagnostic(ImportStack.back()->Kind)
2978 << TopLevelASTFileName << FileChange.Kind
2979 << (FileChange.Old && FileChange.New)
2980 << llvm::itostr(FileChange.Old.value_or(0))
2981 << llvm::itostr(FileChange.New.value_or(0));
2982
2983 // Print the import stack.
2984 if (ImportStack.size() > 1) {
2985 Diag(diag::note_ast_file_required_by)
2986 << *Filename << ImportStack[0]->FileName;
2987 for (unsigned I = 1; I < ImportStack.size(); ++I)
2988 Diag(diag::note_ast_file_required_by)
2989 << ImportStack[I - 1]->FileName << ImportStack[I]->FileName;
2990 }
2991
2992 Diag(diag::note_ast_file_rebuild_required) << TopLevelASTFileName;
2993 }
2994
2995 IsOutOfDate = true;
2996 }
2997 // FIXME: If the file is overridden and we've already opened it,
2998 // issue an error (or split it into a separate FileEntry).
2999
3000 InputFile IF = InputFile(*File, Overridden || Transient, IsOutOfDate);
3001
3002 // Note that we've loaded this input file.
3003 F.InputFilesLoaded[ID-1] = IF;
3004 return IF;
3005}
3006
3007ASTReader::TemporarilyOwnedStringRef
3009 ModuleFile &ModF) {
3010 return ResolveImportedPath(Buf, Path, ModF.BaseDirectory);
3011}
3012
3013ASTReader::TemporarilyOwnedStringRef
3015 StringRef Prefix) {
3016 assert(Buf.capacity() != 0 && "Overlapping ResolveImportedPath calls");
3017
3018 if (Prefix.empty() || Path.empty() || llvm::sys::path::is_absolute(Path) ||
3019 Path == "<built-in>" || Path == "<command line>")
3020 return {Path, Buf};
3021
3022 Buf.clear();
3023 llvm::sys::path::append(Buf, Prefix, Path);
3024 StringRef ResolvedPath{Buf.data(), Buf.size()};
3025 return {ResolvedPath, Buf};
3026}
3027
3029 StringRef P,
3030 ModuleFile &ModF) {
3031 return ResolveImportedPathAndAllocate(Buf, P, ModF.BaseDirectory);
3032}
3033
3035 StringRef P,
3036 StringRef Prefix) {
3037 auto ResolvedPath = ResolveImportedPath(Buf, P, Prefix);
3038 return ResolvedPath->str();
3039}
3040
3041static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
3042 switch (ARR) {
3043 case ASTReader::Failure: return true;
3044 case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
3045 case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
3048 return !(Caps & ASTReader::ARR_ConfigurationMismatch);
3049 case ASTReader::HadErrors: return true;
3050 case ASTReader::Success: return false;
3051 }
3052
3053 llvm_unreachable("unknown ASTReadResult");
3054}
3055
3056ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(
3057 BitstreamCursor &Stream, StringRef Filename,
3058 unsigned ClientLoadCapabilities, bool AllowCompatibleConfigurationMismatch,
3059 ASTReaderListener &Listener, std::string &SuggestedPredefines) {
3060 if (llvm::Error Err = Stream.EnterSubBlock(OPTIONS_BLOCK_ID)) {
3061 // FIXME this drops errors on the floor.
3062 consumeError(std::move(Err));
3063 return Failure;
3064 }
3065
3066 // Read all of the records in the options block.
3067 RecordData Record;
3068 ASTReadResult Result = Success;
3069 while (true) {
3070 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
3071 if (!MaybeEntry) {
3072 // FIXME this drops errors on the floor.
3073 consumeError(MaybeEntry.takeError());
3074 return Failure;
3075 }
3076 llvm::BitstreamEntry Entry = MaybeEntry.get();
3077
3078 switch (Entry.Kind) {
3079 case llvm::BitstreamEntry::Error:
3080 case llvm::BitstreamEntry::SubBlock:
3081 return Failure;
3082
3083 case llvm::BitstreamEntry::EndBlock:
3084 return Result;
3085
3086 case llvm::BitstreamEntry::Record:
3087 // The interesting case.
3088 break;
3089 }
3090
3091 // Read and process a record.
3092 Record.clear();
3093 Expected<unsigned> MaybeRecordType = Stream.readRecord(Entry.ID, Record);
3094 if (!MaybeRecordType) {
3095 // FIXME this drops errors on the floor.
3096 consumeError(MaybeRecordType.takeError());
3097 return Failure;
3098 }
3099 switch ((OptionsRecordTypes)MaybeRecordType.get()) {
3100 case LANGUAGE_OPTIONS: {
3101 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
3102 if (ParseLanguageOptions(Record, Filename, Complain, Listener,
3103 AllowCompatibleConfigurationMismatch))
3104 Result = ConfigurationMismatch;
3105 break;
3106 }
3107
3108 case CODEGEN_OPTIONS: {
3109 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
3110 if (ParseCodeGenOptions(Record, Filename, Complain, Listener,
3111 AllowCompatibleConfigurationMismatch))
3112 Result = ConfigurationMismatch;
3113 break;
3114 }
3115
3116 case TARGET_OPTIONS: {
3117 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
3118 if (ParseTargetOptions(Record, Filename, Complain, Listener,
3119 AllowCompatibleConfigurationMismatch))
3120 Result = ConfigurationMismatch;
3121 break;
3122 }
3123
3124 case FILE_SYSTEM_OPTIONS: {
3125 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
3126 if (!AllowCompatibleConfigurationMismatch &&
3127 ParseFileSystemOptions(Record, Complain, Listener))
3128 Result = ConfigurationMismatch;
3129 break;
3130 }
3131
3132 case HEADER_SEARCH_OPTIONS: {
3133 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
3134 if (!AllowCompatibleConfigurationMismatch &&
3135 ParseHeaderSearchOptions(Record, Filename, Complain, Listener))
3136 Result = ConfigurationMismatch;
3137 break;
3138 }
3139
3141 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
3142 if (!AllowCompatibleConfigurationMismatch &&
3143 ParsePreprocessorOptions(Record, Filename, Complain, Listener,
3144 SuggestedPredefines))
3145 Result = ConfigurationMismatch;
3146 break;
3147 }
3148 }
3149}
3150
3152ASTReader::ReadControlBlock(ModuleFile &F,
3153 SmallVectorImpl<ImportedModule> &Loaded,
3154 const ModuleFile *ImportedBy,
3155 unsigned ClientLoadCapabilities) {
3156 BitstreamCursor &Stream = F.Stream;
3157
3158 if (llvm::Error Err = Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
3159 Error(std::move(Err));
3160 return Failure;
3161 }
3162
3163 // Lambda to read the unhashed control block the first time it's called.
3164 //
3165 // For PCM files, the unhashed control block cannot be read until after the
3166 // MODULE_NAME record. However, PCH files have no MODULE_NAME, and yet still
3167 // need to look ahead before reading the IMPORTS record. For consistency,
3168 // this block is always read somehow (see BitstreamEntry::EndBlock).
3169 bool HasReadUnhashedControlBlock = false;
3170 auto readUnhashedControlBlockOnce = [&]() {
3171 if (!HasReadUnhashedControlBlock) {
3172 HasReadUnhashedControlBlock = true;
3173 if (ASTReadResult Result =
3174 readUnhashedControlBlock(F, ImportedBy, ClientLoadCapabilities))
3175 return Result;
3176 }
3177 return Success;
3178 };
3179
3180 bool DisableValidation = shouldDisableValidationForFile(F);
3181
3182 // Read all of the records and blocks in the control block.
3183 RecordData Record;
3184 unsigned NumInputs = 0;
3185 unsigned NumUserInputs = 0;
3186 StringRef BaseDirectoryAsWritten;
3187 while (true) {
3188 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
3189 if (!MaybeEntry) {
3190 Error(MaybeEntry.takeError());
3191 return Failure;
3192 }
3193 llvm::BitstreamEntry Entry = MaybeEntry.get();
3194
3195 switch (Entry.Kind) {
3196 case llvm::BitstreamEntry::Error:
3197 Error("malformed block record in AST file");
3198 return Failure;
3199 case llvm::BitstreamEntry::EndBlock: {
3200 // Validate the module before returning. This call catches an AST with
3201 // no module name and no imports.
3202 if (ASTReadResult Result = readUnhashedControlBlockOnce())
3203 return Result;
3204
3205 // Validate input files.
3206 const HeaderSearchOptions &HSOpts =
3207 PP.getHeaderSearchInfo().getHeaderSearchOpts();
3208
3209 // All user input files reside at the index range [0, NumUserInputs), and
3210 // system input files reside at [NumUserInputs, NumInputs). For explicitly
3211 // loaded module files, ignore missing inputs.
3212 if (!DisableValidation && F.Kind != MK_ExplicitModule &&
3213 F.Kind != MK_PrebuiltModule) {
3214 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
3215
3216 // If we are reading a module, we will create a verification timestamp,
3217 // so we verify all input files. Otherwise, verify only user input
3218 // files.
3219
3220 unsigned N = ValidateSystemInputs ? NumInputs : NumUserInputs;
3224 N = ForceValidateUserInputs ? NumUserInputs : 0;
3225
3226 if (N != 0)
3227 Diag(diag::remark_module_validation)
3228 << N << F.ModuleName << F.FileName;
3229
3230 for (unsigned I = 0; I < N; ++I) {
3231 InputFile IF = getInputFile(F, I+1, Complain);
3232 if (!IF.getFile() || IF.isOutOfDate())
3233 return OutOfDate;
3234 }
3235 }
3236
3237 if (Listener)
3238 Listener->visitModuleFile(F.FileName, F.Kind);
3239
3240 if (Listener && Listener->needsInputFileVisitation()) {
3241 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
3242 : NumUserInputs;
3243 for (unsigned I = 0; I < N; ++I) {
3244 bool IsSystem = I >= NumUserInputs;
3245 InputFileInfo FI = getInputFileInfo(F, I + 1);
3246 auto FilenameAsRequested = ResolveImportedPath(
3248 Listener->visitInputFile(
3249 *FilenameAsRequested, IsSystem, FI.Overridden,
3251 }
3252 }
3253
3254 return Success;
3255 }
3256
3257 case llvm::BitstreamEntry::SubBlock:
3258 switch (Entry.ID) {
3260 F.InputFilesCursor = Stream;
3261 if (llvm::Error Err = Stream.SkipBlock()) {
3262 Error(std::move(Err));
3263 return Failure;
3264 }
3265 if (ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
3266 Error("malformed block record in AST file");
3267 return Failure;
3268 }
3269 F.InputFilesOffsetBase = F.InputFilesCursor.GetCurrentBitNo();
3270 continue;
3271
3272 case OPTIONS_BLOCK_ID:
3273 // If we're reading the first module for this group, check its options
3274 // are compatible with ours. For modules it imports, no further checking
3275 // is required, because we checked them when we built it.
3276 if (Listener && !ImportedBy) {
3277 // Should we allow the configuration of the module file to differ from
3278 // the configuration of the current translation unit in a compatible
3279 // way?
3280 //
3281 // FIXME: Allow this for files explicitly specified with -include-pch.
3282 bool AllowCompatibleConfigurationMismatch =
3284
3285 ASTReadResult Result =
3286 ReadOptionsBlock(Stream, F.FileName, ClientLoadCapabilities,
3287 AllowCompatibleConfigurationMismatch, *Listener,
3288 SuggestedPredefines);
3289 if (Result == Failure) {
3290 Error("malformed block record in AST file");
3291 return Result;
3292 }
3293
3294 if (DisableValidation ||
3295 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
3296 Result = Success;
3297
3298 // If we can't load the module, exit early since we likely
3299 // will rebuild the module anyway. The stream may be in the
3300 // middle of a block.
3301 if (Result != Success)
3302 return Result;
3303 } else if (llvm::Error Err = Stream.SkipBlock()) {
3304 Error(std::move(Err));
3305 return Failure;
3306 }
3307 continue;
3308
3309 default:
3310 if (llvm::Error Err = Stream.SkipBlock()) {
3311 Error(std::move(Err));
3312 return Failure;
3313 }
3314 continue;
3315 }
3316
3317 case llvm::BitstreamEntry::Record:
3318 // The interesting case.
3319 break;
3320 }
3321
3322 // Read and process a record.
3323 Record.clear();
3324 StringRef Blob;
3325 Expected<unsigned> MaybeRecordType =
3326 Stream.readRecord(Entry.ID, Record, &Blob);
3327 if (!MaybeRecordType) {
3328 Error(MaybeRecordType.takeError());
3329 return Failure;
3330 }
3331 switch ((ControlRecordTypes)MaybeRecordType.get()) {
3332 case METADATA: {
3333 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
3334 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
3335 Diag(Record[0] < VERSION_MAJOR ? diag::err_ast_file_version_too_old
3336 : diag::err_ast_file_version_too_new)
3338 return VersionMismatch;
3339 }
3340
3341 bool hasErrors = Record[7];
3342 if (hasErrors && !DisableValidation) {
3343 // If requested by the caller and the module hasn't already been read
3344 // or compiled, mark modules on error as out-of-date.
3345 if ((ClientLoadCapabilities & ARR_TreatModuleWithErrorsAsOutOfDate) &&
3346 canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
3347 return OutOfDate;
3348
3349 if (!AllowASTWithCompilerErrors) {
3350 Diag(diag::err_ast_file_with_compiler_errors)
3352 return HadErrors;
3353 }
3354 }
3355 if (hasErrors) {
3356 Diags.ErrorOccurred = true;
3357 Diags.UncompilableErrorOccurred = true;
3358 Diags.UnrecoverableErrorOccurred = true;
3359 }
3360
3361 F.RelocatablePCH = Record[4];
3362 // Relative paths in a relocatable PCH are relative to our sysroot.
3363 if (F.RelocatablePCH)
3364 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
3365
3367
3368 F.HasTimestamps = Record[6];
3369
3370 const std::string &CurBranch = getClangFullRepositoryVersion();
3371 StringRef ASTBranch = Blob;
3372 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
3373 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
3374 Diag(diag::err_ast_file_different_branch)
3375 << moduleKindForDiagnostic(F.Kind) << F.FileName << ASTBranch
3376 << CurBranch;
3377 return VersionMismatch;
3378 }
3379 break;
3380 }
3381
3382 case IMPORT: {
3383 // Validate the AST before processing any imports (otherwise, untangling
3384 // them can be error-prone and expensive). A module will have a name and
3385 // will already have been validated, but this catches the PCH case.
3386 if (ASTReadResult Result = readUnhashedControlBlockOnce())
3387 return Result;
3388
3389 unsigned Idx = 0;
3390 // Read information about the AST file.
3391 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
3392
3393 // The import location will be the local one for now; we will adjust
3394 // all import locations of module imports after the global source
3395 // location info are setup, in ReadAST.
3396 auto [ImportLoc, ImportModuleFileIndex] =
3397 ReadUntranslatedSourceLocation(Record[Idx++]);
3398 // The import location must belong to the current module file itself.
3399 assert(ImportModuleFileIndex == 0);
3400
3401 StringRef ImportedName = ReadStringBlob(Record, Idx, Blob);
3402
3403 bool IsImportingStdCXXModule = Record[Idx++];
3404
3405 off_t StoredSize = 0;
3406 time_t StoredModTime = 0;
3407 ASTFileSignature StoredSignature;
3408 std::string ImportedFile;
3409 std::string StoredFile;
3410 bool IgnoreImportedByNote = false;
3411
3412 // For prebuilt and explicit modules first consult the file map for
3413 // an override. Note that here we don't search prebuilt module
3414 // directories if we're not importing standard c++ module, only the
3415 // explicit name to file mappings. Also, we will still verify the
3416 // size/signature making sure it is essentially the same file but
3417 // perhaps in a different location.
3418 if (ImportedKind == MK_PrebuiltModule || ImportedKind == MK_ExplicitModule)
3419 ImportedFile = PP.getHeaderSearchInfo().getPrebuiltModuleFileName(
3420 ImportedName, /*FileMapOnly*/ !IsImportingStdCXXModule);
3421
3422 if (IsImportingStdCXXModule && ImportedFile.empty()) {
3423 Diag(diag::err_failed_to_find_module_file) << ImportedName;
3424 return Missing;
3425 }
3426
3427 if (!IsImportingStdCXXModule) {
3428 StoredSize = (off_t)Record[Idx++];
3429 StoredModTime = (time_t)Record[Idx++];
3430
3431 StringRef SignatureBytes = Blob.substr(0, ASTFileSignature::size);
3432 StoredSignature = ASTFileSignature::create(SignatureBytes.begin(),
3433 SignatureBytes.end());
3434 Blob = Blob.substr(ASTFileSignature::size);
3435
3436 // Use BaseDirectoryAsWritten to ensure we use the same path in the
3437 // ModuleCache as when writing.
3438 StoredFile = ReadPathBlob(BaseDirectoryAsWritten, Record, Idx, Blob);
3439 if (ImportedFile.empty()) {
3440 ImportedFile = StoredFile;
3441 } else if (!getDiags().isIgnored(
3442 diag::warn_module_file_mapping_mismatch,
3443 CurrentImportLoc)) {
3444 auto ImportedFileRef =
3445 PP.getFileManager().getOptionalFileRef(ImportedFile);
3446 auto StoredFileRef =
3447 PP.getFileManager().getOptionalFileRef(StoredFile);
3448 if ((ImportedFileRef && StoredFileRef) &&
3449 (*ImportedFileRef != *StoredFileRef)) {
3450 Diag(diag::warn_module_file_mapping_mismatch)
3451 << ImportedFile << StoredFile;
3452 Diag(diag::note_module_file_imported_by)
3453 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
3454 IgnoreImportedByNote = true;
3455 }
3456 }
3457 }
3458
3459 // If our client can't cope with us being out of date, we can't cope with
3460 // our dependency being missing.
3461 unsigned Capabilities = ClientLoadCapabilities;
3462 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3463 Capabilities &= ~ARR_Missing;
3464
3465 // Load the AST file.
3466 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
3467 Loaded, StoredSize, StoredModTime,
3468 StoredSignature, Capabilities);
3469
3470 // Check the AST we just read from ImportedFile contains a different
3471 // module than we expected (ImportedName). This can occur for C++20
3472 // Modules when given a mismatch via -fmodule-file=<name>=<file>
3473 if (IsImportingStdCXXModule) {
3474 if (const auto *Imported =
3475 getModuleManager().lookupByFileName(ImportedFile);
3476 Imported != nullptr && Imported->ModuleName != ImportedName) {
3477 Diag(diag::err_failed_to_find_module_file) << ImportedName;
3478 Result = Missing;
3479 }
3480 }
3481
3482 // If we diagnosed a problem, produce a backtrace.
3483 bool recompilingFinalized = Result == OutOfDate &&
3484 (Capabilities & ARR_OutOfDate) &&
3485 getModuleManager()
3486 .getModuleCache()
3487 .getInMemoryModuleCache()
3488 .isPCMFinal(F.FileName);
3489 if (!IgnoreImportedByNote &&
3490 (isDiagnosedResult(Result, Capabilities) || recompilingFinalized))
3491 Diag(diag::note_module_file_imported_by)
3492 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
3493
3494 switch (Result) {
3495 case Failure: return Failure;
3496 // If we have to ignore the dependency, we'll have to ignore this too.
3497 case Missing:
3498 case OutOfDate: return OutOfDate;
3499 case VersionMismatch: return VersionMismatch;
3500 case ConfigurationMismatch: return ConfigurationMismatch;
3501 case HadErrors: return HadErrors;
3502 case Success: break;
3503 }
3504 break;
3505 }
3506
3507 case ORIGINAL_FILE:
3508 F.OriginalSourceFileID = FileID::get(Record[0]);
3509 F.ActualOriginalSourceFileName = std::string(Blob);
3510 F.OriginalSourceFileName = ResolveImportedPathAndAllocate(
3511 PathBuf, F.ActualOriginalSourceFileName, F);
3512 break;
3513
3514 case ORIGINAL_FILE_ID:
3515 F.OriginalSourceFileID = FileID::get(Record[0]);
3516 break;
3517
3518 case MODULE_NAME:
3519 F.ModuleName = std::string(Blob);
3520 Diag(diag::remark_module_import)
3521 << F.ModuleName << F.FileName << (ImportedBy ? true : false)
3522 << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());
3523 if (Listener)
3524 Listener->ReadModuleName(F.ModuleName);
3525
3526 // Validate the AST as soon as we have a name so we can exit early on
3527 // failure.
3528 if (ASTReadResult Result = readUnhashedControlBlockOnce())
3529 return Result;
3530
3531 break;
3532
3533 case MODULE_DIRECTORY: {
3534 // Save the BaseDirectory as written in the PCM for computing the module
3535 // filename for the ModuleCache.
3536 BaseDirectoryAsWritten = Blob;
3537 assert(!F.ModuleName.empty() &&
3538 "MODULE_DIRECTORY found before MODULE_NAME");
3539 F.BaseDirectory = std::string(Blob);
3540 if (!PP.getPreprocessorOpts().ModulesCheckRelocated)
3541 break;
3542 // If we've already loaded a module map file covering this module, we may
3543 // have a better path for it (relative to the current build).
3544 Module *M = PP.getHeaderSearchInfo().lookupModule(
3545 F.ModuleName, SourceLocation(), /*AllowSearch*/ true,
3546 /*AllowExtraModuleMapSearch*/ true);
3547 if (M && M->Directory) {
3548 // If we're implicitly loading a module, the base directory can't
3549 // change between the build and use.
3550 // Don't emit module relocation error if we have -fno-validate-pch
3551 if (!bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation &
3554 auto BuildDir = PP.getFileManager().getOptionalDirectoryRef(Blob);
3555 if (!BuildDir || *BuildDir != M->Directory) {
3556 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
3557 Diag(diag::err_imported_module_relocated)
3558 << F.ModuleName << Blob << M->Directory->getName();
3559 return OutOfDate;
3560 }
3561 }
3562 F.BaseDirectory = std::string(M->Directory->getName());
3563 }
3564 break;
3565 }
3566
3567 case MODULE_MAP_FILE:
3568 if (ASTReadResult Result =
3569 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
3570 return Result;
3571 break;
3572
3573 case INPUT_FILE_OFFSETS:
3574 NumInputs = Record[0];
3575 NumUserInputs = Record[1];
3577 (const llvm::support::unaligned_uint64_t *)Blob.data();
3578 F.InputFilesLoaded.resize(NumInputs);
3579 F.InputFileInfosLoaded.resize(NumInputs);
3580 F.NumUserInputFiles = NumUserInputs;
3581 break;
3582 }
3583 }
3584}
3585
3586llvm::Error ASTReader::ReadASTBlock(ModuleFile &F,
3587 unsigned ClientLoadCapabilities) {
3588 BitstreamCursor &Stream = F.Stream;
3589
3590 if (llvm::Error Err = Stream.EnterSubBlock(AST_BLOCK_ID))
3591 return Err;
3592 F.ASTBlockStartOffset = Stream.GetCurrentBitNo();
3593
3594 // Read all of the records and blocks for the AST file.
3595 RecordData Record;
3596 while (true) {
3597 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
3598 if (!MaybeEntry)
3599 return MaybeEntry.takeError();
3600 llvm::BitstreamEntry Entry = MaybeEntry.get();
3601
3602 switch (Entry.Kind) {
3603 case llvm::BitstreamEntry::Error:
3604 return llvm::createStringError(
3605 std::errc::illegal_byte_sequence,
3606 "error at end of module block in AST file");
3607 case llvm::BitstreamEntry::EndBlock:
3608 // Outside of C++, we do not store a lookup map for the translation unit.
3609 // Instead, mark it as needing a lookup map to be built if this module
3610 // contains any declarations lexically within it (which it always does!).
3611 // This usually has no cost, since we very rarely need the lookup map for
3612 // the translation unit outside C++.
3613 if (ASTContext *Ctx = ContextObj) {
3614 DeclContext *DC = Ctx->getTranslationUnitDecl();
3615 if (DC->hasExternalLexicalStorage() && !Ctx->getLangOpts().CPlusPlus)
3617 }
3618
3619 return llvm::Error::success();
3620 case llvm::BitstreamEntry::SubBlock:
3621 switch (Entry.ID) {
3622 case DECLTYPES_BLOCK_ID:
3623 // We lazily load the decls block, but we want to set up the
3624 // DeclsCursor cursor to point into it. Clone our current bitcode
3625 // cursor to it, enter the block and read the abbrevs in that block.
3626 // With the main cursor, we just skip over it.
3627 F.DeclsCursor = Stream;
3628 if (llvm::Error Err = Stream.SkipBlock())
3629 return Err;
3630 if (llvm::Error Err = ReadBlockAbbrevs(
3632 return Err;
3633 break;
3634
3636 F.MacroCursor = Stream;
3637 if (!PP.getExternalSource())
3638 PP.setExternalSource(this);
3639
3640 if (llvm::Error Err = Stream.SkipBlock())
3641 return Err;
3642 if (llvm::Error Err =
3643 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID))
3644 return Err;
3645 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
3646 break;
3647
3649 F.PreprocessorDetailCursor = Stream;
3650
3651 if (llvm::Error Err = Stream.SkipBlock()) {
3652 return Err;
3653 }
3654 if (llvm::Error Err = ReadBlockAbbrevs(F.PreprocessorDetailCursor,
3656 return Err;
3658 = F.PreprocessorDetailCursor.GetCurrentBitNo();
3659
3660 if (!PP.getPreprocessingRecord())
3661 PP.createPreprocessingRecord();
3662 if (!PP.getPreprocessingRecord()->getExternalSource())
3663 PP.getPreprocessingRecord()->SetExternalSource(*this);
3664 break;
3665
3667 if (llvm::Error Err = ReadSourceManagerBlock(F))
3668 return Err;
3669 break;
3670
3671 case SUBMODULE_BLOCK_ID:
3672 if (llvm::Error Err = ReadSubmoduleBlock(F, ClientLoadCapabilities))
3673 return Err;
3674 break;
3675
3676 case COMMENTS_BLOCK_ID: {
3677 BitstreamCursor C = Stream;
3678
3679 if (llvm::Error Err = Stream.SkipBlock())
3680 return Err;
3681 if (llvm::Error Err = ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID))
3682 return Err;
3683 CommentsCursors.push_back(std::make_pair(C, &F));
3684 break;
3685 }
3686
3687 default:
3688 if (llvm::Error Err = Stream.SkipBlock())
3689 return Err;
3690 break;
3691 }
3692 continue;
3693
3694 case llvm::BitstreamEntry::Record:
3695 // The interesting case.
3696 break;
3697 }
3698
3699 // Read and process a record.
3700 Record.clear();
3701 StringRef Blob;
3702 Expected<unsigned> MaybeRecordType =
3703 Stream.readRecord(Entry.ID, Record, &Blob);
3704 if (!MaybeRecordType)
3705 return MaybeRecordType.takeError();
3706 ASTRecordTypes RecordType = (ASTRecordTypes)MaybeRecordType.get();
3707
3708 // If we're not loading an AST context, we don't care about most records.
3709 if (!ContextObj) {
3710 switch (RecordType) {
3711 case IDENTIFIER_TABLE:
3712 case IDENTIFIER_OFFSET:
3714 case STATISTICS:
3717 case PP_COUNTER_VALUE:
3719 case MODULE_OFFSET_MAP:
3723 case IMPORTED_MODULES:
3724 case MACRO_OFFSET:
3725 break;
3726 default:
3727 continue;
3728 }
3729 }
3730
3731 switch (RecordType) {
3732 default: // Default behavior: ignore.
3733 break;
3734
3735 case TYPE_OFFSET: {
3736 if (F.LocalNumTypes != 0)
3737 return llvm::createStringError(
3738 std::errc::illegal_byte_sequence,
3739 "duplicate TYPE_OFFSET record in AST file");
3740 F.TypeOffsets = reinterpret_cast<const UnalignedUInt64 *>(Blob.data());
3741 F.LocalNumTypes = Record[0];
3742 F.BaseTypeIndex = getTotalNumTypes();
3743
3744 if (F.LocalNumTypes > 0)
3745 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
3746
3747 break;
3748 }
3749
3750 case DECL_OFFSET: {
3751 if (F.LocalNumDecls != 0)
3752 return llvm::createStringError(
3753 std::errc::illegal_byte_sequence,
3754 "duplicate DECL_OFFSET record in AST file");
3755 F.DeclOffsets = (const DeclOffset *)Blob.data();
3756 F.LocalNumDecls = Record[0];
3757 F.BaseDeclIndex = getTotalNumDecls();
3758
3759 if (F.LocalNumDecls > 0)
3760 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
3761
3762 break;
3763 }
3764
3765 case TU_UPDATE_LEXICAL: {
3766 DeclContext *TU = ContextObj->getTranslationUnitDecl();
3767 LexicalContents Contents(
3768 reinterpret_cast<const unaligned_decl_id_t *>(Blob.data()),
3769 static_cast<unsigned int>(Blob.size() / sizeof(DeclID)));
3770 TULexicalDecls.push_back(std::make_pair(&F, Contents));
3772 break;
3773 }
3774
3775 case UPDATE_VISIBLE: {
3776 unsigned Idx = 0;
3777 GlobalDeclID ID = ReadDeclID(F, Record, Idx);
3778 auto *Data = (const unsigned char*)Blob.data();
3779 PendingVisibleUpdates[ID].push_back(UpdateData{&F, Data});
3780 // If we've already loaded the decl, perform the updates when we finish
3781 // loading this block.
3782 if (Decl *D = GetExistingDecl(ID))
3783 PendingUpdateRecords.push_back(
3784 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3785 break;
3786 }
3787
3789 unsigned Idx = 0;
3790 GlobalDeclID ID = ReadDeclID(F, Record, Idx);
3791 auto *Data = (const unsigned char *)Blob.data();
3792 PendingModuleLocalVisibleUpdates[ID].push_back(UpdateData{&F, Data});
3793 // If we've already loaded the decl, perform the updates when we finish
3794 // loading this block.
3795 if (Decl *D = GetExistingDecl(ID))
3796 PendingUpdateRecords.push_back(
3797 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3798 break;
3799 }
3800
3802 if (F.Kind != MK_MainFile)
3803 break;
3804 unsigned Idx = 0;
3805 GlobalDeclID ID = ReadDeclID(F, Record, Idx);
3806 auto *Data = (const unsigned char *)Blob.data();
3807 TULocalUpdates[ID].push_back(UpdateData{&F, Data});
3808 // If we've already loaded the decl, perform the updates when we finish
3809 // loading this block.
3810 if (Decl *D = GetExistingDecl(ID))
3811 PendingUpdateRecords.push_back(
3812 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3813 break;
3814 }
3815
3817 unsigned Idx = 0;
3818 GlobalDeclID ID = ReadDeclID(F, Record, Idx);
3819 auto *Data = (const unsigned char *)Blob.data();
3820 PendingSpecializationsUpdates[ID].push_back(UpdateData{&F, Data});
3821 // If we've already loaded the decl, perform the updates when we finish
3822 // loading this block.
3823 if (Decl *D = GetExistingDecl(ID))
3824 PendingUpdateRecords.push_back(
3825 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3826 break;
3827 }
3828
3830 unsigned Idx = 0;
3831 GlobalDeclID ID = ReadDeclID(F, Record, Idx);
3832 auto *Data = (const unsigned char *)Blob.data();
3833 PendingPartialSpecializationsUpdates[ID].push_back(UpdateData{&F, Data});
3834 // If we've already loaded the decl, perform the updates when we finish
3835 // loading this block.
3836 if (Decl *D = GetExistingDecl(ID))
3837 PendingUpdateRecords.push_back(
3838 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3839 break;
3840 }
3841
3842 case IDENTIFIER_TABLE:
3844 reinterpret_cast<const unsigned char *>(Blob.data());
3845 if (Record[0]) {
3846 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
3848 F.IdentifierTableData + sizeof(uint32_t),
3850 ASTIdentifierLookupTrait(*this, F));
3851
3852 PP.getIdentifierTable().setExternalIdentifierLookup(this);
3853 }
3854 break;
3855
3856 case IDENTIFIER_OFFSET: {
3857 if (F.LocalNumIdentifiers != 0)
3858 return llvm::createStringError(
3859 std::errc::illegal_byte_sequence,
3860 "duplicate IDENTIFIER_OFFSET record in AST file");
3861 F.IdentifierOffsets = (const uint32_t *)Blob.data();
3863 F.BaseIdentifierID = getTotalNumIdentifiers();
3864
3865 if (F.LocalNumIdentifiers > 0)
3866 IdentifiersLoaded.resize(IdentifiersLoaded.size()
3868 break;
3869 }
3870
3872 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
3873 break;
3874
3876 // FIXME: Skip reading this record if our ASTConsumer doesn't care
3877 // about "interesting" decls (for instance, if we're building a module).
3878 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
3879 EagerlyDeserializedDecls.push_back(ReadDeclID(F, Record, I));
3880 break;
3881
3883 // FIXME: Skip reading this record if our ASTConsumer doesn't care about
3884 // them (ie: if we're not codegenerating this module).
3885 if (F.Kind == MK_MainFile ||
3886 getContext().getLangOpts().BuildingPCHWithObjectFile)
3887 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
3888 EagerlyDeserializedDecls.push_back(ReadDeclID(F, Record, I));
3889 break;
3890
3891 case SPECIAL_TYPES:
3892 if (SpecialTypes.empty()) {
3893 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3894 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
3895 break;
3896 }
3897
3898 if (Record.empty())
3899 break;
3900
3901 if (SpecialTypes.size() != Record.size())
3902 return llvm::createStringError(std::errc::illegal_byte_sequence,
3903 "invalid special-types record");
3904
3905 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
3906 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
3907 if (!SpecialTypes[I])
3908 SpecialTypes[I] = ID;
3909 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
3910 // merge step?
3911 }
3912 break;
3913
3914 case STATISTICS:
3915 TotalNumStatements += Record[0];
3916 TotalNumMacros += Record[1];
3917 TotalLexicalDeclContexts += Record[2];
3918 TotalVisibleDeclContexts += Record[3];
3919 TotalModuleLocalVisibleDeclContexts += Record[4];
3920 TotalTULocalVisibleDeclContexts += Record[5];
3921 break;
3922
3924 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
3925 UnusedFileScopedDecls.push_back(ReadDeclID(F, Record, I));
3926 break;
3927
3928 case DELEGATING_CTORS:
3929 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
3930 DelegatingCtorDecls.push_back(ReadDeclID(F, Record, I));
3931 break;
3932
3934 if (Record.size() % 3 != 0)
3935 return llvm::createStringError(std::errc::illegal_byte_sequence,
3936 "invalid weak identifiers record");
3937
3938 // FIXME: Ignore weak undeclared identifiers from non-original PCH
3939 // files. This isn't the way to do it :)
3940 WeakUndeclaredIdentifiers.clear();
3941
3942 // Translate the weak, undeclared identifiers into global IDs.
3943 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
3944 WeakUndeclaredIdentifiers.push_back(
3945 getGlobalIdentifierID(F, Record[I++]));
3946 WeakUndeclaredIdentifiers.push_back(
3947 getGlobalIdentifierID(F, Record[I++]));
3948 WeakUndeclaredIdentifiers.push_back(
3949 ReadSourceLocation(F, Record, I).getRawEncoding());
3950 }
3951 break;
3952
3953 case SELECTOR_OFFSETS: {
3954 F.SelectorOffsets = (const uint32_t *)Blob.data();
3956 unsigned LocalBaseSelectorID = Record[1];
3957 F.BaseSelectorID = getTotalNumSelectors();
3958
3959 if (F.LocalNumSelectors > 0) {
3960 // Introduce the global -> local mapping for selectors within this
3961 // module.
3962 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
3963
3964 // Introduce the local -> global mapping for selectors within this
3965 // module.
3967 std::make_pair(LocalBaseSelectorID,
3968 F.BaseSelectorID - LocalBaseSelectorID));
3969
3970 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
3971 }
3972 break;
3973 }
3974
3975 case METHOD_POOL:
3976 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
3977 if (Record[0])
3979 = ASTSelectorLookupTable::Create(
3982 ASTSelectorLookupTrait(*this, F));
3983 TotalNumMethodPoolEntries += Record[1];
3984 break;
3985
3987 if (!Record.empty()) {
3988 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
3989 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
3990 Record[Idx++]));
3991 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
3992 getRawEncoding());
3993 }
3994 }
3995 break;
3996
3997 case PP_ASSUME_NONNULL_LOC: {
3998 unsigned Idx = 0;
3999 if (!Record.empty())
4000 PP.setPreambleRecordedPragmaAssumeNonNullLoc(
4001 ReadSourceLocation(F, Record, Idx));
4002 break;
4003 }
4004
4006 if (!Record.empty()) {
4007 SmallVector<SourceLocation, 64> SrcLocs;
4008 unsigned Idx = 0;
4009 while (Idx < Record.size())
4010 SrcLocs.push_back(ReadSourceLocation(F, Record, Idx));
4011 PP.setDeserializedSafeBufferOptOutMap(SrcLocs);
4012 }
4013 break;
4014 }
4015
4017 if (!Record.empty()) {
4018 unsigned Idx = 0, End = Record.size() - 1;
4019 bool ReachedEOFWhileSkipping = Record[Idx++];
4020 std::optional<Preprocessor::PreambleSkipInfo> SkipInfo;
4021 if (ReachedEOFWhileSkipping) {
4022 SourceLocation HashToken = ReadSourceLocation(F, Record, Idx);
4023 SourceLocation IfTokenLoc = ReadSourceLocation(F, Record, Idx);
4024 bool FoundNonSkipPortion = Record[Idx++];
4025 bool FoundElse = Record[Idx++];
4026 SourceLocation ElseLoc = ReadSourceLocation(F, Record, Idx);
4027 SkipInfo.emplace(HashToken, IfTokenLoc, FoundNonSkipPortion,
4028 FoundElse, ElseLoc);
4029 }
4030 SmallVector<PPConditionalInfo, 4> ConditionalStack;
4031 while (Idx < End) {
4032 auto Loc = ReadSourceLocation(F, Record, Idx);
4033 bool WasSkipping = Record[Idx++];
4034 bool FoundNonSkip = Record[Idx++];
4035 bool FoundElse = Record[Idx++];
4036 ConditionalStack.push_back(
4037 {Loc, WasSkipping, FoundNonSkip, FoundElse});
4038 }
4039 PP.setReplayablePreambleConditionalStack(ConditionalStack, SkipInfo);
4040 }
4041 break;
4042
4043 case PP_COUNTER_VALUE:
4044 if (!Record.empty() && Listener)
4045 Listener->ReadCounter(F, Record[0]);
4046 break;
4047
4048 case FILE_SORTED_DECLS:
4049 F.FileSortedDecls = (const unaligned_decl_id_t *)Blob.data();
4051 break;
4052
4054 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
4056 SourceLocation::UIntTy SLocSpaceSize = Record[1];
4058 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
4059 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
4060 SLocSpaceSize);
4061 if (!F.SLocEntryBaseID) {
4062 Diags.Report(SourceLocation(), diag::remark_sloc_usage);
4063 SourceMgr.noteSLocAddressSpaceUsage(Diags);
4064 return llvm::createStringError(std::errc::invalid_argument,
4065 "ran out of source locations");
4066 }
4067 // Make our entry in the range map. BaseID is negative and growing, so
4068 // we invert it. Because we invert it, though, we need the other end of
4069 // the range.
4070 unsigned RangeStart =
4071 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
4072 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
4074
4075 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
4076 assert((F.SLocEntryBaseOffset & SourceLocation::MacroIDBit) == 0);
4077 GlobalSLocOffsetMap.insert(
4078 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
4079 - SLocSpaceSize,&F));
4080
4081 TotalNumSLocEntries += F.LocalNumSLocEntries;
4082 break;
4083 }
4084
4085 case MODULE_OFFSET_MAP:
4086 F.ModuleOffsetMap = Blob;
4087 break;
4088
4090 ParseLineTable(F, Record);
4091 break;
4092
4093 case EXT_VECTOR_DECLS:
4094 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4095 ExtVectorDecls.push_back(ReadDeclID(F, Record, I));
4096 break;
4097
4098 case VTABLE_USES:
4099 if (Record.size() % 3 != 0)
4100 return llvm::createStringError(std::errc::illegal_byte_sequence,
4101 "Invalid VTABLE_USES record");
4102
4103 // Later tables overwrite earlier ones.
4104 // FIXME: Modules will have some trouble with this. This is clearly not
4105 // the right way to do this.
4106 VTableUses.clear();
4107
4108 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
4109 VTableUses.push_back(
4110 {ReadDeclID(F, Record, Idx),
4111 ReadSourceLocation(F, Record, Idx).getRawEncoding(),
4112 (bool)Record[Idx++]});
4113 }
4114 break;
4115
4117
4118 if (Record.size() % 2 != 0)
4119 return llvm::createStringError(
4120 std::errc::illegal_byte_sequence,
4121 "Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
4122
4123 // For standard C++20 module, we will only reads the instantiations
4124 // if it is the main file.
4125 if (!F.StandardCXXModule || F.Kind == MK_MainFile) {
4126 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
4127 PendingInstantiations.push_back(
4128 {ReadDeclID(F, Record, I),
4129 ReadSourceLocation(F, Record, I).getRawEncoding()});
4130 }
4131 }
4132 break;
4133
4134 case SEMA_DECL_REFS:
4135 if (Record.size() != 3)
4136 return llvm::createStringError(std::errc::illegal_byte_sequence,
4137 "Invalid SEMA_DECL_REFS block");
4138 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4139 SemaDeclRefs.push_back(ReadDeclID(F, Record, I));
4140 break;
4141
4142 case PPD_ENTITIES_OFFSETS: {
4143 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
4144 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
4145 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
4146
4147 unsigned StartingID;
4148 if (!PP.getPreprocessingRecord())
4149 PP.createPreprocessingRecord();
4150 if (!PP.getPreprocessingRecord()->getExternalSource())
4151 PP.getPreprocessingRecord()->SetExternalSource(*this);
4152 StartingID
4153 = PP.getPreprocessingRecord()
4154 ->allocateLoadedEntities(F.NumPreprocessedEntities);
4155 F.BasePreprocessedEntityID = StartingID;
4156
4157 if (F.NumPreprocessedEntities > 0) {
4158 // Introduce the global -> local mapping for preprocessed entities in
4159 // this module.
4160 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
4161 }
4162
4163 break;
4164 }
4165
4166 case PPD_SKIPPED_RANGES: {
4167 F.PreprocessedSkippedRangeOffsets = (const PPSkippedRange*)Blob.data();
4168 assert(Blob.size() % sizeof(PPSkippedRange) == 0);
4169 F.NumPreprocessedSkippedRanges = Blob.size() / sizeof(PPSkippedRange);
4170
4171 if (!PP.getPreprocessingRecord())
4172 PP.createPreprocessingRecord();
4173 if (!PP.getPreprocessingRecord()->getExternalSource())
4174 PP.getPreprocessingRecord()->SetExternalSource(*this);
4175 F.BasePreprocessedSkippedRangeID = PP.getPreprocessingRecord()
4176 ->allocateSkippedRanges(F.NumPreprocessedSkippedRanges);
4177
4179 GlobalSkippedRangeMap.insert(
4180 std::make_pair(F.BasePreprocessedSkippedRangeID, &F));
4181 break;
4182 }
4183
4185 if (Record.size() % 2 != 0)
4186 return llvm::createStringError(
4187 std::errc::illegal_byte_sequence,
4188 "invalid DECL_UPDATE_OFFSETS block in AST file");
4189 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/) {
4190 GlobalDeclID ID = ReadDeclID(F, Record, I);
4191 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I++]));
4192
4193 // If we've already loaded the decl, perform the updates when we finish
4194 // loading this block.
4195 if (Decl *D = GetExistingDecl(ID))
4196 PendingUpdateRecords.push_back(
4197 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
4198 }
4199 break;
4200
4202 if (Record.size() % 5 != 0)
4203 return llvm::createStringError(
4204 std::errc::illegal_byte_sequence,
4205 "invalid DELAYED_NAMESPACE_LEXICAL_VISIBLE_RECORD block in AST "
4206 "file");
4207 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/) {
4208 GlobalDeclID ID = ReadDeclID(F, Record, I);
4209
4210 uint64_t BaseOffset = F.DeclsBlockStartOffset;
4211 assert(BaseOffset && "Invalid DeclsBlockStartOffset for module file!");
4212 uint64_t LocalLexicalOffset = Record[I++];
4213 uint64_t LexicalOffset =
4214 LocalLexicalOffset ? BaseOffset + LocalLexicalOffset : 0;
4215 uint64_t LocalVisibleOffset = Record[I++];
4216 uint64_t VisibleOffset =
4217 LocalVisibleOffset ? BaseOffset + LocalVisibleOffset : 0;
4218 uint64_t LocalModuleLocalOffset = Record[I++];
4219 uint64_t ModuleLocalOffset =
4220 LocalModuleLocalOffset ? BaseOffset + LocalModuleLocalOffset : 0;
4221 uint64_t TULocalLocalOffset = Record[I++];
4222 uint64_t TULocalOffset =
4223 TULocalLocalOffset ? BaseOffset + TULocalLocalOffset : 0;
4224
4225 DelayedNamespaceOffsetMap[ID] = {
4226 {VisibleOffset, TULocalOffset, ModuleLocalOffset}, LexicalOffset};
4227
4228 assert(!GetExistingDecl(ID) &&
4229 "We shouldn't load the namespace in the front of delayed "
4230 "namespace lexical and visible block");
4231 }
4232 break;
4233 }
4234
4235 case RELATED_DECLS_MAP:
4236 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/) {
4237 GlobalDeclID ID = ReadDeclID(F, Record, I);
4238 auto &RelatedDecls = RelatedDeclsMap[ID];
4239 unsigned NN = Record[I++];
4240 RelatedDecls.reserve(NN);
4241 for (unsigned II = 0; II < NN; II++)
4242 RelatedDecls.push_back(ReadDeclID(F, Record, I));
4243 }
4244 break;
4245
4247 if (F.LocalNumObjCCategoriesInMap != 0)
4248 return llvm::createStringError(
4249 std::errc::illegal_byte_sequence,
4250 "duplicate OBJC_CATEGORIES_MAP record in AST file");
4251
4253 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
4254 break;
4255
4256 case OBJC_CATEGORIES:
4257 F.ObjCCategories.swap(Record);
4258 break;
4259
4261 // Later tables overwrite earlier ones.
4262 // FIXME: Modules will have trouble with this.
4263 CUDASpecialDeclRefs.clear();
4264 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4265 CUDASpecialDeclRefs.push_back(ReadDeclID(F, Record, I));
4266 break;
4267
4269 F.HeaderFileInfoTableData = Blob.data();
4271 if (Record[0]) {
4272 F.HeaderFileInfoTable = HeaderFileInfoLookupTable::Create(
4273 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
4274 (const unsigned char *)F.HeaderFileInfoTableData,
4275 HeaderFileInfoTrait(*this, F));
4276
4277 PP.getHeaderSearchInfo().SetExternalSource(this);
4278 if (!PP.getHeaderSearchInfo().getExternalLookup())
4279 PP.getHeaderSearchInfo().SetExternalLookup(this);
4280 }
4281 break;
4282
4283 case FP_PRAGMA_OPTIONS:
4284 // Later tables overwrite earlier ones.
4285 FPPragmaOptions.swap(Record);
4286 break;
4287
4289 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4290 DeclsWithEffectsToVerify.push_back(ReadDeclID(F, Record, I));
4291 break;
4292
4293 case OPENCL_EXTENSIONS:
4294 for (unsigned I = 0, E = Record.size(); I != E; ) {
4295 auto Name = ReadString(Record, I);
4296 auto &OptInfo = OpenCLExtensions.OptMap[Name];
4297 OptInfo.Supported = Record[I++] != 0;
4298 OptInfo.Enabled = Record[I++] != 0;
4299 OptInfo.WithPragma = Record[I++] != 0;
4300 OptInfo.Avail = Record[I++];
4301 OptInfo.Core = Record[I++];
4302 OptInfo.Opt = Record[I++];
4303 }
4304 break;
4305
4307 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4308 TentativeDefinitions.push_back(ReadDeclID(F, Record, I));
4309 break;
4310
4311 case KNOWN_NAMESPACES:
4312 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4313 KnownNamespaces.push_back(ReadDeclID(F, Record, I));
4314 break;
4315
4316 case UNDEFINED_BUT_USED:
4317 if (Record.size() % 2 != 0)
4318 return llvm::createStringError(std::errc::illegal_byte_sequence,
4319 "invalid undefined-but-used record");
4320 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
4321 UndefinedButUsed.push_back(
4322 {ReadDeclID(F, Record, I),
4323 ReadSourceLocation(F, Record, I).getRawEncoding()});
4324 }
4325 break;
4326
4328 for (unsigned I = 0, N = Record.size(); I != N;) {
4329 DelayedDeleteExprs.push_back(ReadDeclID(F, Record, I).getRawValue());
4330 const uint64_t Count = Record[I++];
4331 DelayedDeleteExprs.push_back(Count);
4332 for (uint64_t C = 0; C < Count; ++C) {
4333 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
4334 bool IsArrayForm = Record[I++] == 1;
4335 DelayedDeleteExprs.push_back(IsArrayForm);
4336 }
4337 }
4338 break;
4339
4340 case VTABLES_TO_EMIT:
4341 if (F.Kind == MK_MainFile ||
4342 getContext().getLangOpts().BuildingPCHWithObjectFile)
4343 for (unsigned I = 0, N = Record.size(); I != N;)
4344 VTablesToEmit.push_back(ReadDeclID(F, Record, I));
4345 break;
4346
4347 case IMPORTED_MODULES:
4348 if (!F.isModule()) {
4349 // If we aren't loading a module (which has its own exports), make
4350 // all of the imported modules visible.
4351 // FIXME: Deal with macros-only imports.
4352 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
4353 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
4354 SourceLocation Loc = ReadSourceLocation(F, Record, I);
4355 if (GlobalID) {
4356 PendingImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
4357 if (DeserializationListener)
4358 DeserializationListener->ModuleImportRead(GlobalID, Loc);
4359 }
4360 }
4361 }
4362 break;
4363
4364 case MACRO_OFFSET: {
4365 if (F.LocalNumMacros != 0)
4366 return llvm::createStringError(
4367 std::errc::illegal_byte_sequence,
4368 "duplicate MACRO_OFFSET record in AST file");
4369 F.MacroOffsets = (const uint32_t *)Blob.data();
4370 F.LocalNumMacros = Record[0];
4372 F.BaseMacroID = getTotalNumMacros();
4373
4374 if (F.LocalNumMacros > 0)
4375 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
4376 break;
4377 }
4378
4380 LateParsedTemplates.emplace_back(
4381 std::piecewise_construct, std::forward_as_tuple(&F),
4382 std::forward_as_tuple(Record.begin(), Record.end()));
4383 break;
4384
4386 if (Record.size() != 1)
4387 return llvm::createStringError(std::errc::illegal_byte_sequence,
4388 "invalid pragma optimize record");
4389 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
4390 break;
4391
4393 if (Record.size() != 1)
4394 return llvm::createStringError(std::errc::illegal_byte_sequence,
4395 "invalid pragma ms_struct record");
4396 PragmaMSStructState = Record[0];
4397 break;
4398
4400 if (Record.size() != 2)
4401 return llvm::createStringError(
4402 std::errc::illegal_byte_sequence,
4403 "invalid pragma pointers to members record");
4404 PragmaMSPointersToMembersState = Record[0];
4405 PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]);
4406 break;
4407
4409 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4410 UnusedLocalTypedefNameCandidates.push_back(ReadDeclID(F, Record, I));
4411 break;
4412
4414 if (Record.size() != 1)
4415 return llvm::createStringError(std::errc::illegal_byte_sequence,
4416 "invalid cuda pragma options record");
4417 ForceHostDeviceDepth = Record[0];
4418 break;
4419
4421 if (Record.size() < 3)
4422 return llvm::createStringError(std::errc::illegal_byte_sequence,
4423 "invalid pragma pack record");
4424 PragmaAlignPackCurrentValue = ReadAlignPackInfo(Record[0]);
4425 PragmaAlignPackCurrentLocation = ReadSourceLocation(F, Record[1]);
4426 unsigned NumStackEntries = Record[2];
4427 unsigned Idx = 3;
4428 // Reset the stack when importing a new module.
4429 PragmaAlignPackStack.clear();
4430 for (unsigned I = 0; I < NumStackEntries; ++I) {
4431 PragmaAlignPackStackEntry Entry;
4432 Entry.Value = ReadAlignPackInfo(Record[Idx++]);
4433 Entry.Location = ReadSourceLocation(F, Record[Idx++]);
4434 Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]);
4435 PragmaAlignPackStrings.push_back(ReadString(Record, Idx));
4436 Entry.SlotLabel = PragmaAlignPackStrings.back();
4437 PragmaAlignPackStack.push_back(Entry);
4438 }
4439 break;
4440 }
4441
4443 if (Record.size() < 3)
4444 return llvm::createStringError(std::errc::illegal_byte_sequence,
4445 "invalid pragma float control record");
4446 FpPragmaCurrentValue = FPOptionsOverride::getFromOpaqueInt(Record[0]);
4447 FpPragmaCurrentLocation = ReadSourceLocation(F, Record[1]);
4448 unsigned NumStackEntries = Record[2];
4449 unsigned Idx = 3;
4450 // Reset the stack when importing a new module.
4451 FpPragmaStack.clear();
4452 for (unsigned I = 0; I < NumStackEntries; ++I) {
4453 FpPragmaStackEntry Entry;
4454 Entry.Value = FPOptionsOverride::getFromOpaqueInt(Record[Idx++]);
4455 Entry.Location = ReadSourceLocation(F, Record[Idx++]);
4456 Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]);
4457 FpPragmaStrings.push_back(ReadString(Record, Idx));
4458 Entry.SlotLabel = FpPragmaStrings.back();
4459 FpPragmaStack.push_back(Entry);
4460 }
4461 break;
4462 }
4463
4465 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4466 DeclsToCheckForDeferredDiags.insert(ReadDeclID(F, Record, I));
4467 break;
4468
4470 unsigned NumRecords = Record.front();
4471 // Last record which is used to keep number of valid records.
4472 if (Record.size() - 1 != NumRecords)
4473 return llvm::createStringError(std::errc::illegal_byte_sequence,
4474 "invalid rvv intrinsic pragma record");
4475
4476 if (RISCVVecIntrinsicPragma.empty())
4477 RISCVVecIntrinsicPragma.append(NumRecords, 0);
4478 // There might be multiple precompiled modules imported, we need to union
4479 // them all.
4480 for (unsigned i = 0; i < NumRecords; ++i)
4481 RISCVVecIntrinsicPragma[i] |= Record[i + 1];
4482 break;
4483 }
4484 }
4485 }
4486}
4487
4488void ASTReader::ReadModuleOffsetMap(ModuleFile &F) const {
4489 assert(!F.ModuleOffsetMap.empty() && "no module offset map to read");
4490
4491 // Additional remapping information.
4492 const unsigned char *Data = (const unsigned char*)F.ModuleOffsetMap.data();
4493 const unsigned char *DataEnd = Data + F.ModuleOffsetMap.size();
4494 F.ModuleOffsetMap = StringRef();
4495
4497 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
4498 RemapBuilder SelectorRemap(F.SelectorRemap);
4499
4500 auto &ImportedModuleVector = F.TransitiveImports;
4501 assert(ImportedModuleVector.empty());
4502
4503 while (Data < DataEnd) {
4504 // FIXME: Looking up dependency modules by filename is horrible. Let's
4505 // start fixing this with prebuilt, explicit and implicit modules and see
4506 // how it goes...
4507 using namespace llvm::support;
4508 ModuleKind Kind = static_cast<ModuleKind>(
4509 endian::readNext<uint8_t, llvm::endianness::little>(Data));
4510 uint16_t Len = endian::readNext<uint16_t, llvm::endianness::little>(Data);
4511 StringRef Name = StringRef((const char*)Data, Len);
4512 Data += Len;
4515 ? ModuleMgr.lookupByModuleName(Name)
4516 : ModuleMgr.lookupByFileName(Name));
4517 if (!OM) {
4518 std::string Msg = "refers to unknown module, cannot find ";
4519 Msg.append(std::string(Name));
4520 Error(Msg);
4521 return;
4522 }
4523
4524 ImportedModuleVector.push_back(OM);
4525
4526 uint32_t SubmoduleIDOffset =
4527 endian::readNext<uint32_t, llvm::endianness::little>(Data);
4528 uint32_t SelectorIDOffset =
4529 endian::readNext<uint32_t, llvm::endianness::little>(Data);
4530
4531 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
4532 RemapBuilder &Remap) {
4533 constexpr uint32_t None = std::numeric_limits<uint32_t>::max();
4534 if (Offset != None)
4535 Remap.insert(std::make_pair(Offset,
4536 static_cast<int>(BaseOffset - Offset)));
4537 };
4538
4539 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
4540 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
4541 }
4542}
4543
4545ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
4546 const ModuleFile *ImportedBy,
4547 unsigned ClientLoadCapabilities) {
4548 unsigned Idx = 0;
4549 F.ModuleMapPath = ReadPath(F, Record, Idx);
4550
4551 // Try to resolve ModuleName in the current header search context and
4552 // verify that it is found in the same module map file as we saved. If the
4553 // top-level AST file is a main file, skip this check because there is no
4554 // usable header search context.
4555 assert(!F.ModuleName.empty() &&
4556 "MODULE_NAME should come before MODULE_MAP_FILE");
4557 if (PP.getPreprocessorOpts().ModulesCheckRelocated &&
4558 F.Kind == MK_ImplicitModule && ModuleMgr.begin()->Kind != MK_MainFile) {
4559 // An implicitly-loaded module file should have its module listed in some
4560 // module map file that we've already loaded.
4561 Module *M =
4562 PP.getHeaderSearchInfo().lookupModule(F.ModuleName, F.ImportLoc);
4563 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
4564 OptionalFileEntryRef ModMap =
4565 M ? Map.getModuleMapFileForUniquing(M) : std::nullopt;
4566 // Don't emit module relocation error if we have -fno-validate-pch
4567 if (!bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation &
4569 !ModMap) {
4570 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities)) {
4571 if (auto ASTFE = M ? M->getASTFile() : std::nullopt) {
4572 // This module was defined by an imported (explicit) module.
4573 Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
4574 << ASTFE->getName();
4575 // TODO: Add a note with the module map paths if they differ.
4576 } else {
4577 // This module was built with a different module map.
4578 Diag(diag::err_imported_module_not_found)
4579 << F.ModuleName << F.FileName
4580 << (ImportedBy ? ImportedBy->FileName : "") << F.ModuleMapPath
4581 << !ImportedBy;
4582 // In case it was imported by a PCH, there's a chance the user is
4583 // just missing to include the search path to the directory containing
4584 // the modulemap.
4585 if (ImportedBy && ImportedBy->Kind == MK_PCH)
4586 Diag(diag::note_imported_by_pch_module_not_found)
4587 << llvm::sys::path::parent_path(F.ModuleMapPath);
4588 }
4589 }
4590 return OutOfDate;
4591 }
4592
4593 assert(M && M->Name == F.ModuleName && "found module with different name");
4594
4595 // Check the primary module map file.
4596 auto StoredModMap = FileMgr.getOptionalFileRef(F.ModuleMapPath);
4597 if (!StoredModMap || *StoredModMap != ModMap) {
4598 assert(ModMap && "found module is missing module map file");
4599 assert((ImportedBy || F.Kind == MK_ImplicitModule) &&
4600 "top-level import should be verified");
4601 bool NotImported = F.Kind == MK_ImplicitModule && !ImportedBy;
4602 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4603 Diag(diag::err_imported_module_modmap_changed)
4604 << F.ModuleName << (NotImported ? F.FileName : ImportedBy->FileName)
4605 << ModMap->getName() << F.ModuleMapPath << NotImported;
4606 return OutOfDate;
4607 }
4608
4609 ModuleMap::AdditionalModMapsSet AdditionalStoredMaps;
4610 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
4611 // FIXME: we should use input files rather than storing names.
4612 std::string Filename = ReadPath(F, Record, Idx);
4613 auto SF = FileMgr.getOptionalFileRef(Filename, false, false);
4614 if (!SF) {
4615 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4616 Error("could not find file '" + Filename +"' referenced by AST file");
4617 return OutOfDate;
4618 }
4619 AdditionalStoredMaps.insert(*SF);
4620 }
4621
4622 // Check any additional module map files (e.g. module.private.modulemap)
4623 // that are not in the pcm.
4624 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
4625 for (FileEntryRef ModMap : *AdditionalModuleMaps) {
4626 // Remove files that match
4627 // Note: SmallPtrSet::erase is really remove
4628 if (!AdditionalStoredMaps.erase(ModMap)) {
4629 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4630 Diag(diag::err_module_different_modmap)
4631 << F.ModuleName << /*new*/0 << ModMap.getName();
4632 return OutOfDate;
4633 }
4634 }
4635 }
4636
4637 // Check any additional module map files that are in the pcm, but not
4638 // found in header search. Cases that match are already removed.
4639 for (FileEntryRef ModMap : AdditionalStoredMaps) {
4640 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4641 Diag(diag::err_module_different_modmap)
4642 << F.ModuleName << /*not new*/1 << ModMap.getName();
4643 return OutOfDate;
4644 }
4645 }
4646
4647 if (Listener)
4648 Listener->ReadModuleMapFile(F.ModuleMapPath);
4649 return Success;
4650}
4651
4652/// Move the given method to the back of the global list of methods.
4654 // Find the entry for this selector in the method pool.
4655 SemaObjC::GlobalMethodPool::iterator Known =
4656 S.ObjC().MethodPool.find(Method->getSelector());
4657 if (Known == S.ObjC().MethodPool.end())
4658 return;
4659
4660 // Retrieve the appropriate method list.
4661 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
4662 : Known->second.second;
4663 bool Found = false;
4664 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
4665 if (!Found) {
4666 if (List->getMethod() == Method) {
4667 Found = true;
4668 } else {
4669 // Keep searching.
4670 continue;
4671 }
4672 }
4673
4674 if (List->getNext())
4675 List->setMethod(List->getNext()->getMethod());
4676 else
4677 List->setMethod(Method);
4678 }
4679}
4680
4681void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
4682 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
4683 for (Decl *D : Names) {
4684 bool wasHidden = !D->isUnconditionallyVisible();
4686
4687 if (wasHidden && SemaObj) {
4688 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
4690 }
4691 }
4692 }
4693}
4694
4696 Module::NameVisibilityKind NameVisibility,
4697 SourceLocation ImportLoc) {
4700 Stack.push_back(Mod);
4701 while (!Stack.empty()) {
4702 Mod = Stack.pop_back_val();
4703
4704 if (NameVisibility <= Mod->NameVisibility) {
4705 // This module already has this level of visibility (or greater), so
4706 // there is nothing more to do.
4707 continue;
4708 }
4709
4710 if (Mod->isUnimportable()) {
4711 // Modules that aren't importable cannot be made visible.
4712 continue;
4713 }
4714
4715 // Update the module's name visibility.
4716 Mod->NameVisibility = NameVisibility;
4717
4718 // If we've already deserialized any names from this module,
4719 // mark them as visible.
4720 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
4721 if (Hidden != HiddenNamesMap.end()) {
4722 auto HiddenNames = std::move(*Hidden);
4723 HiddenNamesMap.erase(Hidden);
4724 makeNamesVisible(HiddenNames.second, HiddenNames.first);
4725 assert(!HiddenNamesMap.contains(Mod) &&
4726 "making names visible added hidden names");
4727 }
4728
4729 // Push any exported modules onto the stack to be marked as visible.
4731 Mod->getExportedModules(Exports);
4733 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
4734 Module *Exported = *I;
4735 if (Visited.insert(Exported).second)
4736 Stack.push_back(Exported);
4737 }
4738 }
4739}
4740
4741/// We've merged the definition \p MergedDef into the existing definition
4742/// \p Def. Ensure that \p Def is made visible whenever \p MergedDef is made
4743/// visible.
4745 NamedDecl *MergedDef) {
4746 if (!Def->isUnconditionallyVisible()) {
4747 // If MergedDef is visible or becomes visible, make the definition visible.
4748 if (MergedDef->isUnconditionallyVisible())
4750 else {
4751 getContext().mergeDefinitionIntoModule(
4752 Def, MergedDef->getImportedOwningModule(),
4753 /*NotifyListeners*/ false);
4754 PendingMergedDefinitionsToDeduplicate.insert(Def);
4755 }
4756 }
4757}
4758
4760 if (GlobalIndex)
4761 return false;
4762
4763 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
4764 !PP.getLangOpts().Modules)
4765 return true;
4766
4767 // Try to load the global index.
4768 TriedLoadingGlobalIndex = true;
4769 StringRef ModuleCachePath
4770 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
4771 std::pair<GlobalModuleIndex *, llvm::Error> Result =
4772 GlobalModuleIndex::readIndex(ModuleCachePath);
4773 if (llvm::Error Err = std::move(Result.second)) {
4774 assert(!Result.first);
4775 consumeError(std::move(Err)); // FIXME this drops errors on the floor.
4776 return true;
4777 }
4778
4779 GlobalIndex.reset(Result.first);
4780 ModuleMgr.setGlobalIndex(GlobalIndex.get());
4781 return false;
4782}
4783
4785 return PP.getLangOpts().Modules && UseGlobalIndex &&
4786 !hasGlobalIndex() && TriedLoadingGlobalIndex;
4787}
4788
4789/// Given a cursor at the start of an AST file, scan ahead and drop the
4790/// cursor into the start of the given block ID, returning false on success and
4791/// true on failure.
4792static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
4793 while (true) {
4794 Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
4795 if (!MaybeEntry) {
4796 // FIXME this drops errors on the floor.
4797 consumeError(MaybeEntry.takeError());
4798 return true;
4799 }
4800 llvm::BitstreamEntry Entry = MaybeEntry.get();
4801
4802 switch (Entry.Kind) {
4803 case llvm::BitstreamEntry::Error:
4804 case llvm::BitstreamEntry::EndBlock:
4805 return true;
4806
4807 case llvm::BitstreamEntry::Record:
4808 // Ignore top-level records.
4809 if (Expected<unsigned> Skipped = Cursor.skipRecord(Entry.ID))
4810 break;
4811 else {
4812 // FIXME this drops errors on the floor.
4813 consumeError(Skipped.takeError());
4814 return true;
4815 }
4816
4817 case llvm::BitstreamEntry::SubBlock:
4818 if (Entry.ID == BlockID) {
4819 if (llvm::Error Err = Cursor.EnterSubBlock(BlockID)) {
4820 // FIXME this drops the error on the floor.
4821 consumeError(std::move(Err));
4822 return true;
4823 }
4824 // Found it!
4825 return false;
4826 }
4827
4828 if (llvm::Error Err = Cursor.SkipBlock()) {
4829 // FIXME this drops the error on the floor.
4830 consumeError(std::move(Err));
4831 return true;
4832 }
4833 }
4834 }
4835}
4836
4838 SourceLocation ImportLoc,
4839 unsigned ClientLoadCapabilities,
4840 ModuleFile **NewLoadedModuleFile) {
4841 llvm::TimeTraceScope scope("ReadAST", FileName);
4842
4843 llvm::SaveAndRestore SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
4845 CurrentDeserializingModuleKind, Type);
4846
4847 // Defer any pending actions until we get to the end of reading the AST file.
4848 Deserializing AnASTFile(this);
4849
4850 // Bump the generation number.
4851 unsigned PreviousGeneration = 0;
4852 if (ContextObj)
4853 PreviousGeneration = incrementGeneration(*ContextObj);
4854
4855 unsigned NumModules = ModuleMgr.size();
4857 if (ASTReadResult ReadResult =
4858 ReadASTCore(FileName, Type, ImportLoc,
4859 /*ImportedBy=*/nullptr, Loaded, 0, 0, ASTFileSignature(),
4860 ClientLoadCapabilities)) {
4861 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules);
4862
4863 // If we find that any modules are unusable, the global index is going
4864 // to be out-of-date. Just remove it.
4865 GlobalIndex.reset();
4866 ModuleMgr.setGlobalIndex(nullptr);
4867 return ReadResult;
4868 }
4869
4870 if (NewLoadedModuleFile && !Loaded.empty())
4871 *NewLoadedModuleFile = Loaded.back().Mod;
4872
4873 // Here comes stuff that we only do once the entire chain is loaded. Do *not*
4874 // remove modules from this point. Various fields are updated during reading
4875 // the AST block and removing the modules would result in dangling pointers.
4876 // They are generally only incidentally dereferenced, ie. a binary search
4877 // runs over `GlobalSLocEntryMap`, which could cause an invalid module to
4878 // be dereferenced but it wouldn't actually be used.
4879
4880 // Load the AST blocks of all of the modules that we loaded. We can still
4881 // hit errors parsing the ASTs at this point.
4882 for (ImportedModule &M : Loaded) {
4883 ModuleFile &F = *M.Mod;
4884 llvm::TimeTraceScope Scope2("Read Loaded AST", F.ModuleName);
4885
4886 // Read the AST block.
4887 if (llvm::Error Err = ReadASTBlock(F, ClientLoadCapabilities)) {
4888 Error(std::move(Err));
4889 return Failure;
4890 }
4891
4892 // The AST block should always have a definition for the main module.
4893 if (F.isModule() && !F.DidReadTopLevelSubmodule) {
4894 Error(diag::err_module_file_missing_top_level_submodule, F.FileName);
4895 return Failure;
4896 }
4897
4898 // Read the extension blocks.
4900 if (llvm::Error Err = ReadExtensionBlock(F)) {
4901 Error(std::move(Err));
4902 return Failure;
4903 }
4904 }
4905
4906 // Once read, set the ModuleFile bit base offset and update the size in
4907 // bits of all files we've seen.
4908 F.GlobalBitOffset = TotalModulesSizeInBits;
4909 TotalModulesSizeInBits += F.SizeInBits;
4910 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
4911 }
4912
4913 // Preload source locations and interesting indentifiers.
4914 for (ImportedModule &M : Loaded) {
4915 ModuleFile &F = *M.Mod;
4916
4917 // Map the original source file ID into the ID space of the current
4918 // compilation.
4921
4922 for (auto Offset : F.PreloadIdentifierOffsets) {
4923 const unsigned char *Data = F.IdentifierTableData + Offset;
4924
4925 ASTIdentifierLookupTrait Trait(*this, F);
4926 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
4927 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
4928
4929 IdentifierInfo *II;
4930 if (!PP.getLangOpts().CPlusPlus) {
4931 // Identifiers present in both the module file and the importing
4932 // instance are marked out-of-date so that they can be deserialized
4933 // on next use via ASTReader::updateOutOfDateIdentifier().
4934 // Identifiers present in the module file but not in the importing
4935 // instance are ignored for now, preventing growth of the identifier
4936 // table. They will be deserialized on first use via ASTReader::get().
4937 auto It = PP.getIdentifierTable().find(Key);
4938 if (It == PP.getIdentifierTable().end())
4939 continue;
4940 II = It->second;
4941 } else {
4942 // With C++ modules, not many identifiers are considered interesting.
4943 // All identifiers in the module file can be placed into the identifier
4944 // table of the importing instance and marked as out-of-date. This makes
4945 // ASTReader::get() a no-op, and deserialization will take place on
4946 // first/next use via ASTReader::updateOutOfDateIdentifier().
4947 II = &PP.getIdentifierTable().getOwn(Key);
4948 }
4949
4950 II->setOutOfDate(true);
4951
4952 // Mark this identifier as being from an AST file so that we can track
4953 // whether we need to serialize it.
4954 markIdentifierFromAST(*this, *II, /*IsModule=*/true);
4955
4956 // Associate the ID with the identifier so that the writer can reuse it.
4957 auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
4958 SetIdentifierInfo(ID, II);
4959 }
4960 }
4961
4962 // Builtins and library builtins have already been initialized. Mark all
4963 // identifiers as out-of-date, so that they are deserialized on first use.
4964 if (Type == MK_PCH || Type == MK_Preamble || Type == MK_MainFile)
4965 for (auto &Id : PP.getIdentifierTable())
4966 Id.second->setOutOfDate(true);
4967
4968 // Mark selectors as out of date.
4969 for (const auto &Sel : SelectorGeneration)
4970 SelectorOutOfDate[Sel.first] = true;
4971
4972 // Setup the import locations and notify the module manager that we've
4973 // committed to these module files.
4974 for (ImportedModule &M : Loaded) {
4975 ModuleFile &F = *M.Mod;
4976
4977 ModuleMgr.moduleFileAccepted(&F);
4978
4979 // Set the import location.
4980 F.DirectImportLoc = ImportLoc;
4981 // FIXME: We assume that locations from PCH / preamble do not need
4982 // any translation.
4983 if (!M.ImportedBy)
4984 F.ImportLoc = M.ImportLoc;
4985 else
4986 F.ImportLoc = TranslateSourceLocation(*M.ImportedBy, M.ImportLoc);
4987 }
4988
4989 // Resolve any unresolved module exports.
4990 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
4991 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
4993 Module *ResolvedMod = getSubmodule(GlobalID);
4994
4995 switch (Unresolved.Kind) {
4996 case UnresolvedModuleRef::Conflict:
4997 if (ResolvedMod) {
4998 Module::Conflict Conflict;
4999 Conflict.Other = ResolvedMod;
5000 Conflict.Message = Unresolved.String.str();
5001 Unresolved.Mod->Conflicts.push_back(Conflict);
5002 }
5003 continue;
5004
5005 case UnresolvedModuleRef::Import:
5006 if (ResolvedMod)
5007 Unresolved.Mod->Imports.insert(ResolvedMod);
5008 continue;
5009
5010 case UnresolvedModuleRef::Affecting:
5011 if (ResolvedMod)
5012 Unresolved.Mod->AffectingClangModules.insert(ResolvedMod);
5013 continue;
5014
5015 case UnresolvedModuleRef::Export:
5016 if (ResolvedMod || Unresolved.IsWildcard)
5017 Unresolved.Mod->Exports.push_back(
5018 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
5019 continue;
5020 }
5021 }
5022 UnresolvedModuleRefs.clear();
5023
5024 // FIXME: How do we load the 'use'd modules? They may not be submodules.
5025 // Might be unnecessary as use declarations are only used to build the
5026 // module itself.
5027
5028 if (ContextObj)
5030
5031 if (SemaObj)
5032 UpdateSema();
5033
5034 if (DeserializationListener)
5035 DeserializationListener->ReaderInitialized(this);
5036
5037 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
5038 if (PrimaryModule.OriginalSourceFileID.isValid()) {
5039 // If this AST file is a precompiled preamble, then set the
5040 // preamble file ID of the source manager to the file source file
5041 // from which the preamble was built.
5042 if (Type == MK_Preamble) {
5043 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
5044 } else if (Type == MK_MainFile) {
5045 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
5046 }
5047 }
5048
5049 // For any Objective-C class definitions we have already loaded, make sure
5050 // that we load any additional categories.
5051 if (ContextObj) {
5052 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
5053 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
5054 ObjCClassesLoaded[I], PreviousGeneration);
5055 }
5056 }
5057
5058 const HeaderSearchOptions &HSOpts =
5059 PP.getHeaderSearchInfo().getHeaderSearchOpts();
5061 // Now we are certain that the module and all modules it depends on are
5062 // up-to-date. For implicitly-built module files, ensure the corresponding
5063 // timestamp files are up-to-date in this build session.
5064 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
5065 ImportedModule &M = Loaded[I];
5066 if (M.Mod->Kind == MK_ImplicitModule &&
5068 getModuleManager().getModuleCache().updateModuleTimestamp(
5069 M.Mod->FileName);
5070 }
5071 }
5072
5073 return Success;
5074}
5075
5076static ASTFileSignature readASTFileSignature(StringRef PCH);
5077
5078/// Whether \p Stream doesn't start with the AST file magic number 'CPCH'.
5079static llvm::Error doesntStartWithASTFileMagic(BitstreamCursor &Stream) {
5080 // FIXME checking magic headers is done in other places such as
5081 // SerializedDiagnosticReader and GlobalModuleIndex, but error handling isn't
5082 // always done the same. Unify it all with a helper.
5083 if (!Stream.canSkipToPos(4))
5084 return llvm::createStringError(
5085 std::errc::illegal_byte_sequence,
5086 "file too small to contain precompiled file magic");
5087 for (unsigned C : {'C', 'P', 'C', 'H'})
5088 if (Expected<llvm::SimpleBitstreamCursor::word_t> Res = Stream.Read(8)) {
5089 if (Res.get() != C)
5090 return llvm::createStringError(
5091 std::errc::illegal_byte_sequence,
5092 "file doesn't start with precompiled file magic");
5093 } else
5094 return Res.takeError();
5095 return llvm::Error::success();
5096}
5097
5099 switch (Kind) {
5100 case MK_PCH:
5101 return 0; // PCH
5102 case MK_ImplicitModule:
5103 case MK_ExplicitModule:
5104 case MK_PrebuiltModule:
5105 return 1; // module
5106 case MK_MainFile:
5107 case MK_Preamble:
5108 return 2; // main source file
5109 }
5110 llvm_unreachable("unknown module kind");
5111}
5112
5114ASTReader::ReadASTCore(StringRef FileName,
5116 SourceLocation ImportLoc,
5117 ModuleFile *ImportedBy,
5118 SmallVectorImpl<ImportedModule> &Loaded,
5119 off_t ExpectedSize, time_t ExpectedModTime,
5120 ASTFileSignature ExpectedSignature,
5121 unsigned ClientLoadCapabilities) {
5122 ModuleFile *M;
5123 std::string ErrorStr;
5125 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
5126 getGeneration(), ExpectedSize, ExpectedModTime,
5127 ExpectedSignature, readASTFileSignature,
5128 M, ErrorStr);
5129
5130 switch (AddResult) {
5132 Diag(diag::remark_module_import)
5133 << M->ModuleName << M->FileName << (ImportedBy ? true : false)
5134 << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());
5135 return Success;
5136
5138 // Load module file below.
5139 break;
5140
5142 // The module file was missing; if the client can handle that, return
5143 // it.
5144 if (ClientLoadCapabilities & ARR_Missing)
5145 return Missing;
5146
5147 // Otherwise, return an error.
5148 Diag(diag::err_ast_file_not_found)
5149 << moduleKindForDiagnostic(Type) << FileName << !ErrorStr.empty()
5150 << ErrorStr;
5151 return Failure;
5152
5154 // We couldn't load the module file because it is out-of-date. If the
5155 // client can handle out-of-date, return it.
5156 if (ClientLoadCapabilities & ARR_OutOfDate)
5157 return OutOfDate;
5158
5159 // Otherwise, return an error.
5160 Diag(diag::err_ast_file_out_of_date)
5161 << moduleKindForDiagnostic(Type) << FileName << !ErrorStr.empty()
5162 << ErrorStr;
5163 return Failure;
5164 }
5165
5166 assert(M && "Missing module file");
5167
5168 bool ShouldFinalizePCM = false;
5169 auto FinalizeOrDropPCM = llvm::make_scope_exit([&]() {
5170 auto &MC = getModuleManager().getModuleCache().getInMemoryModuleCache();
5171 if (ShouldFinalizePCM)
5172 MC.finalizePCM(FileName);
5173 else
5174 MC.tryToDropPCM(FileName);
5175 });
5176 ModuleFile &F = *M;
5177 BitstreamCursor &Stream = F.Stream;
5178 Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(*F.Buffer));
5179 F.SizeInBits = F.Buffer->getBufferSize() * 8;
5180
5181 // Sniff for the signature.
5182 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5183 Diag(diag::err_ast_file_invalid)
5184 << moduleKindForDiagnostic(Type) << FileName << std::move(Err);
5185 return Failure;
5186 }
5187
5188 // This is used for compatibility with older PCH formats.
5189 bool HaveReadControlBlock = false;
5190 while (true) {
5191 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5192 if (!MaybeEntry) {
5193 Error(MaybeEntry.takeError());
5194 return Failure;
5195 }
5196 llvm::BitstreamEntry Entry = MaybeEntry.get();
5197
5198 switch (Entry.Kind) {
5199 case llvm::BitstreamEntry::Error:
5200 case llvm::BitstreamEntry::Record:
5201 case llvm::BitstreamEntry::EndBlock:
5202 Error("invalid record at top-level of AST file");
5203 return Failure;
5204
5205 case llvm::BitstreamEntry::SubBlock:
5206 break;
5207 }
5208
5209 switch (Entry.ID) {
5210 case CONTROL_BLOCK_ID:
5211 HaveReadControlBlock = true;
5212 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
5213 case Success:
5214 // Check that we didn't try to load a non-module AST file as a module.
5215 //
5216 // FIXME: Should we also perform the converse check? Loading a module as
5217 // a PCH file sort of works, but it's a bit wonky.
5219 Type == MK_PrebuiltModule) &&
5220 F.ModuleName.empty()) {
5221 auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
5222 if (Result != OutOfDate ||
5223 (ClientLoadCapabilities & ARR_OutOfDate) == 0)
5224 Diag(diag::err_module_file_not_module) << FileName;
5225 return Result;
5226 }
5227 break;
5228
5229 case Failure: return Failure;
5230 case Missing: return Missing;
5231 case OutOfDate: return OutOfDate;
5232 case VersionMismatch: return VersionMismatch;
5233 case ConfigurationMismatch: return ConfigurationMismatch;
5234 case HadErrors: return HadErrors;
5235 }
5236 break;
5237
5238 case AST_BLOCK_ID:
5239 if (!HaveReadControlBlock) {
5240 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
5241 Diag(diag::err_ast_file_version_too_old)
5243 return VersionMismatch;
5244 }
5245
5246 // Record that we've loaded this module.
5247 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
5248 ShouldFinalizePCM = true;
5249 return Success;
5250
5251 default:
5252 if (llvm::Error Err = Stream.SkipBlock()) {
5253 Error(std::move(Err));
5254 return Failure;
5255 }
5256 break;
5257 }
5258 }
5259
5260 llvm_unreachable("unexpected break; expected return");
5261}
5262
5264ASTReader::readUnhashedControlBlock(ModuleFile &F, bool WasImportedBy,
5265 unsigned ClientLoadCapabilities) {
5266 const HeaderSearchOptions &HSOpts =
5267 PP.getHeaderSearchInfo().getHeaderSearchOpts();
5268 bool AllowCompatibleConfigurationMismatch =
5270 bool DisableValidation = shouldDisableValidationForFile(F);
5271
5272 ASTReadResult Result = readUnhashedControlBlockImpl(
5273 &F, F.Data, F.FileName, ClientLoadCapabilities,
5274 AllowCompatibleConfigurationMismatch, Listener.get(),
5275 WasImportedBy ? false : HSOpts.ModulesValidateDiagnosticOptions);
5276
5277 // If F was directly imported by another module, it's implicitly validated by
5278 // the importing module.
5279 if (DisableValidation || WasImportedBy ||
5280 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
5281 return Success;
5282
5283 if (Result == Failure) {
5284 Error("malformed block record in AST file");
5285 return Failure;
5286 }
5287
5288 if (Result == OutOfDate && F.Kind == MK_ImplicitModule) {
5289 // If this module has already been finalized in the ModuleCache, we're stuck
5290 // with it; we can only load a single version of each module.
5291 //
5292 // This can happen when a module is imported in two contexts: in one, as a
5293 // user module; in another, as a system module (due to an import from
5294 // another module marked with the [system] flag). It usually indicates a
5295 // bug in the module map: this module should also be marked with [system].
5296 //
5297 // If -Wno-system-headers (the default), and the first import is as a
5298 // system module, then validation will fail during the as-user import,
5299 // since -Werror flags won't have been validated. However, it's reasonable
5300 // to treat this consistently as a system module.
5301 //
5302 // If -Wsystem-headers, the PCM on disk was built with
5303 // -Wno-system-headers, and the first import is as a user module, then
5304 // validation will fail during the as-system import since the PCM on disk
5305 // doesn't guarantee that -Werror was respected. However, the -Werror
5306 // flags were checked during the initial as-user import.
5307 if (getModuleManager().getModuleCache().getInMemoryModuleCache().isPCMFinal(
5308 F.FileName)) {
5309 Diag(diag::warn_module_system_bit_conflict) << F.FileName;
5310 return Success;
5311 }
5312 }
5313
5314 return Result;
5315}
5316
5317ASTReader::ASTReadResult ASTReader::readUnhashedControlBlockImpl(
5318 ModuleFile *F, llvm::StringRef StreamData, StringRef Filename,
5319 unsigned ClientLoadCapabilities, bool AllowCompatibleConfigurationMismatch,
5320 ASTReaderListener *Listener, bool ValidateDiagnosticOptions) {
5321 // Initialize a stream.
5322 BitstreamCursor Stream(StreamData);
5323
5324 // Sniff for the signature.
5325 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5326 // FIXME this drops the error on the floor.
5327 consumeError(std::move(Err));
5328 return Failure;
5329 }
5330
5331 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
5333 return Failure;
5334
5335 // Read all of the records in the options block.
5336 RecordData Record;
5337 ASTReadResult Result = Success;
5338 while (true) {
5339 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5340 if (!MaybeEntry) {
5341 // FIXME this drops the error on the floor.
5342 consumeError(MaybeEntry.takeError());
5343 return Failure;
5344 }
5345 llvm::BitstreamEntry Entry = MaybeEntry.get();
5346
5347 switch (Entry.Kind) {
5348 case llvm::BitstreamEntry::Error:
5349 case llvm::BitstreamEntry::SubBlock:
5350 return Failure;
5351
5352 case llvm::BitstreamEntry::EndBlock:
5353 return Result;
5354
5355 case llvm::BitstreamEntry::Record:
5356 // The interesting case.
5357 break;
5358 }
5359
5360 // Read and process a record.
5361 Record.clear();
5362 StringRef Blob;
5363 Expected<unsigned> MaybeRecordType =
5364 Stream.readRecord(Entry.ID, Record, &Blob);
5365 if (!MaybeRecordType) {
5366 // FIXME this drops the error.
5367 return Failure;
5368 }
5369 switch ((UnhashedControlBlockRecordTypes)MaybeRecordType.get()) {
5370 case SIGNATURE:
5371 if (F) {
5372 F->Signature = ASTFileSignature::create(Blob.begin(), Blob.end());
5374 "Dummy AST file signature not backpatched in ASTWriter.");
5375 }
5376 break;
5377 case AST_BLOCK_HASH:
5378 if (F) {
5379 F->ASTBlockHash = ASTFileSignature::create(Blob.begin(), Blob.end());
5381 "Dummy AST block hash not backpatched in ASTWriter.");
5382 }
5383 break;
5384 case DIAGNOSTIC_OPTIONS: {
5385 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
5386 if (Listener && ValidateDiagnosticOptions &&
5387 !AllowCompatibleConfigurationMismatch &&
5388 ParseDiagnosticOptions(Record, Filename, Complain, *Listener))
5389 Result = OutOfDate; // Don't return early. Read the signature.
5390 break;
5391 }
5392 case HEADER_SEARCH_PATHS: {
5393 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
5394 if (Listener && !AllowCompatibleConfigurationMismatch &&
5395 ParseHeaderSearchPaths(Record, Complain, *Listener))
5396 Result = ConfigurationMismatch;
5397 break;
5398 }
5400 if (!F)
5401 break;
5402 if (F->PragmaDiagMappings.empty())
5403 F->PragmaDiagMappings.swap(Record);
5404 else
5405 F->PragmaDiagMappings.insert(F->PragmaDiagMappings.end(),
5406 Record.begin(), Record.end());
5407 break;
5409 if (F)
5410 F->SearchPathUsage = ReadBitVector(Record, Blob);
5411 break;
5412 case VFS_USAGE:
5413 if (F)
5414 F->VFSUsage = ReadBitVector(Record, Blob);
5415 break;
5416 }
5417 }
5418}
5419
5420/// Parse a record and blob containing module file extension metadata.
5423 StringRef Blob,
5424 ModuleFileExtensionMetadata &Metadata) {
5425 if (Record.size() < 4) return true;
5426
5427 Metadata.MajorVersion = Record[0];
5428 Metadata.MinorVersion = Record[1];
5429
5430 unsigned BlockNameLen = Record[2];
5431 unsigned UserInfoLen = Record[3];
5432
5433 if (BlockNameLen + UserInfoLen > Blob.size()) return true;
5434
5435 Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
5436 Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,
5437 Blob.data() + BlockNameLen + UserInfoLen);
5438 return false;
5439}
5440
5441llvm::Error ASTReader::ReadExtensionBlock(ModuleFile &F) {
5442 BitstreamCursor &Stream = F.Stream;
5443
5444 RecordData Record;
5445 while (true) {
5446 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5447 if (!MaybeEntry)
5448 return MaybeEntry.takeError();
5449 llvm::BitstreamEntry Entry = MaybeEntry.get();
5450
5451 switch (Entry.Kind) {
5452 case llvm::BitstreamEntry::SubBlock:
5453 if (llvm::Error Err = Stream.SkipBlock())
5454 return Err;
5455 continue;
5456 case llvm::BitstreamEntry::EndBlock:
5457 return llvm::Error::success();
5458 case llvm::BitstreamEntry::Error:
5459 return llvm::createStringError(std::errc::illegal_byte_sequence,
5460 "malformed block record in AST file");
5461 case llvm::BitstreamEntry::Record:
5462 break;
5463 }
5464
5465 Record.clear();
5466 StringRef Blob;
5467 Expected<unsigned> MaybeRecCode =
5468 Stream.readRecord(Entry.ID, Record, &Blob);
5469 if (!MaybeRecCode)
5470 return MaybeRecCode.takeError();
5471 switch (MaybeRecCode.get()) {
5472 case EXTENSION_METADATA: {
5473 ModuleFileExtensionMetadata Metadata;
5474 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
5475 return llvm::createStringError(
5476 std::errc::illegal_byte_sequence,
5477 "malformed EXTENSION_METADATA in AST file");
5478
5479 // Find a module file extension with this block name.
5480 auto Known = ModuleFileExtensions.find(Metadata.BlockName);
5481 if (Known == ModuleFileExtensions.end()) break;
5482
5483 // Form a reader.
5484 if (auto Reader = Known->second->createExtensionReader(Metadata, *this,
5485 F, Stream)) {
5486 F.ExtensionReaders.push_back(std::move(Reader));
5487 }
5488
5489 break;
5490 }
5491 }
5492 }
5493
5494 llvm_unreachable("ReadExtensionBlock should return from while loop");
5495}
5496
5498 assert(ContextObj && "no context to initialize");
5499 ASTContext &Context = *ContextObj;
5500
5501 // If there's a listener, notify them that we "read" the translation unit.
5502 if (DeserializationListener)
5503 DeserializationListener->DeclRead(
5505 Context.getTranslationUnitDecl());
5506
5507 // FIXME: Find a better way to deal with collisions between these
5508 // built-in types. Right now, we just ignore the problem.
5509
5510 // Load the special types.
5511 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
5512 if (TypeID String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
5513 if (!Context.CFConstantStringTypeDecl)
5514 Context.setCFConstantStringType(GetType(String));
5515 }
5516
5517 if (TypeID File = SpecialTypes[SPECIAL_TYPE_FILE]) {
5518 QualType FileType = GetType(File);
5519 if (FileType.isNull()) {
5520 Error("FILE type is NULL");
5521 return;
5522 }
5523
5524 if (!Context.FILEDecl) {
5525 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
5526 Context.setFILEDecl(Typedef->getDecl());
5527 else {
5528 const TagType *Tag = FileType->getAs<TagType>();
5529 if (!Tag) {
5530 Error("Invalid FILE type in AST file");
5531 return;
5532 }
5533 Context.setFILEDecl(Tag->getDecl());
5534 }
5535 }
5536 }
5537
5538 if (TypeID Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
5539 QualType Jmp_bufType = GetType(Jmp_buf);
5540 if (Jmp_bufType.isNull()) {
5541 Error("jmp_buf type is NULL");
5542 return;
5543 }
5544
5545 if (!Context.jmp_bufDecl) {
5546 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
5547 Context.setjmp_bufDecl(Typedef->getDecl());
5548 else {
5549 const TagType *Tag = Jmp_bufType->getAs<TagType>();
5550 if (!Tag) {
5551 Error("Invalid jmp_buf type in AST file");
5552 return;
5553 }
5554 Context.setjmp_bufDecl(Tag->getDecl());
5555 }
5556 }
5557 }
5558
5559 if (TypeID Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
5560 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
5561 if (Sigjmp_bufType.isNull()) {
5562 Error("sigjmp_buf type is NULL");
5563 return;
5564 }
5565
5566 if (!Context.sigjmp_bufDecl) {
5567 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
5568 Context.setsigjmp_bufDecl(Typedef->getDecl());
5569 else {
5570 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
5571 assert(Tag && "Invalid sigjmp_buf type in AST file");
5572 Context.setsigjmp_bufDecl(Tag->getDecl());
5573 }
5574 }
5575 }
5576
5577 if (TypeID ObjCIdRedef = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
5578 if (Context.ObjCIdRedefinitionType.isNull())
5579 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
5580 }
5581
5582 if (TypeID ObjCClassRedef =
5584 if (Context.ObjCClassRedefinitionType.isNull())
5585 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
5586 }
5587
5588 if (TypeID ObjCSelRedef =
5589 SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
5590 if (Context.ObjCSelRedefinitionType.isNull())
5591 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
5592 }
5593
5594 if (TypeID Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
5595 QualType Ucontext_tType = GetType(Ucontext_t);
5596 if (Ucontext_tType.isNull()) {
5597 Error("ucontext_t type is NULL");
5598 return;
5599 }
5600
5601 if (!Context.ucontext_tDecl) {
5602 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
5603 Context.setucontext_tDecl(Typedef->getDecl());
5604 else {
5605 const TagType *Tag = Ucontext_tType->getAs<TagType>();
5606 assert(Tag && "Invalid ucontext_t type in AST file");
5607 Context.setucontext_tDecl(Tag->getDecl());
5608 }
5609 }
5610 }
5611 }
5612
5613 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
5614
5615 // If there were any CUDA special declarations, deserialize them.
5616 if (!CUDASpecialDeclRefs.empty()) {
5617 assert(CUDASpecialDeclRefs.size() == 3 && "More decl refs than expected!");
5618 Context.setcudaConfigureCallDecl(
5619 cast_or_null<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
5620 Context.setcudaGetParameterBufferDecl(
5621 cast_or_null<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[1])));
5622 Context.setcudaLaunchDeviceDecl(
5623 cast_or_null<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[2])));
5624 }
5625
5626 // Re-export any modules that were imported by a non-module AST file.
5627 // FIXME: This does not make macro-only imports visible again.
5628 for (auto &Import : PendingImportedModules) {
5629 if (Module *Imported = getSubmodule(Import.ID)) {
5631 /*ImportLoc=*/Import.ImportLoc);
5632 if (Import.ImportLoc.isValid())
5633 PP.makeModuleVisible(Imported, Import.ImportLoc);
5634 // This updates visibility for Preprocessor only. For Sema, which can be
5635 // nullptr here, we do the same later, in UpdateSema().
5636 }
5637 }
5638
5639 // Hand off these modules to Sema.
5640 PendingImportedModulesSema.append(PendingImportedModules);
5641 PendingImportedModules.clear();
5642}
5643
5645 // Nothing to do for now.
5646}
5647
5648/// Reads and return the signature record from \p PCH's control block, or
5649/// else returns 0.
5651 BitstreamCursor Stream(PCH);
5652 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5653 // FIXME this drops the error on the floor.
5654 consumeError(std::move(Err));
5655 return ASTFileSignature();
5656 }
5657
5658 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
5660 return ASTFileSignature();
5661
5662 // Scan for SIGNATURE inside the diagnostic options block.
5664 while (true) {
5666 Stream.advanceSkippingSubblocks();
5667 if (!MaybeEntry) {
5668 // FIXME this drops the error on the floor.
5669 consumeError(MaybeEntry.takeError());
5670 return ASTFileSignature();
5671 }
5672 llvm::BitstreamEntry Entry = MaybeEntry.get();
5673
5674 if (Entry.Kind != llvm::BitstreamEntry::Record)
5675 return ASTFileSignature();
5676
5677 Record.clear();
5678 StringRef Blob;
5679 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);
5680 if (!MaybeRecord) {
5681 // FIXME this drops the error on the floor.
5682 consumeError(MaybeRecord.takeError());
5683 return ASTFileSignature();
5684 }
5685 if (SIGNATURE == MaybeRecord.get()) {
5686 auto Signature = ASTFileSignature::create(Blob.begin(), Blob.end());
5687 assert(Signature != ASTFileSignature::createDummy() &&
5688 "Dummy AST file signature not backpatched in ASTWriter.");
5689 return Signature;
5690 }
5691 }
5692}
5693
5694/// Retrieve the name of the original source file name
5695/// directly from the AST file, without actually loading the AST
5696/// file.
5698 const std::string &ASTFileName, FileManager &FileMgr,
5699 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
5700 // Open the AST file.
5701 auto Buffer = FileMgr.getBufferForFile(ASTFileName, /*IsVolatile=*/false,
5702 /*RequiresNullTerminator=*/false,
5703 /*MaybeLimit=*/std::nullopt,
5704 /*IsText=*/false);
5705 if (!Buffer) {
5706 Diags.Report(diag::err_fe_unable_to_read_pch_file)
5707 << ASTFileName << Buffer.getError().message();
5708 return std::string();
5709 }
5710
5711 // Initialize the stream
5712 BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer));
5713
5714 // Sniff for the signature.
5715 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5716 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName << std::move(Err);
5717 return std::string();
5718 }
5719
5720 // Scan for the CONTROL_BLOCK_ID block.
5721 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
5722 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
5723 return std::string();
5724 }
5725
5726 // Scan for ORIGINAL_FILE inside the control block.
5728 while (true) {
5730 Stream.advanceSkippingSubblocks();
5731 if (!MaybeEntry) {
5732 // FIXME this drops errors on the floor.
5733 consumeError(MaybeEntry.takeError());
5734 return std::string();
5735 }
5736 llvm::BitstreamEntry Entry = MaybeEntry.get();
5737
5738 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
5739 return std::string();
5740
5741 if (Entry.Kind != llvm::BitstreamEntry::Record) {
5742 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
5743 return std::string();
5744 }
5745
5746 Record.clear();
5747 StringRef Blob;
5748 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);
5749 if (!MaybeRecord) {
5750 // FIXME this drops the errors on the floor.
5751 consumeError(MaybeRecord.takeError());
5752 return std::string();
5753 }
5754 if (ORIGINAL_FILE == MaybeRecord.get())
5755 return Blob.str();
5756 }
5757}
5758
5759namespace {
5760
5761 class SimplePCHValidator : public ASTReaderListener {
5762 const LangOptions &ExistingLangOpts;
5763 const CodeGenOptions &ExistingCGOpts;
5764 const TargetOptions &ExistingTargetOpts;
5765 const PreprocessorOptions &ExistingPPOpts;
5766 std::string ExistingModuleCachePath;
5768 bool StrictOptionMatches;
5769
5770 public:
5771 SimplePCHValidator(const LangOptions &ExistingLangOpts,
5772 const CodeGenOptions &ExistingCGOpts,
5773 const TargetOptions &ExistingTargetOpts,
5774 const PreprocessorOptions &ExistingPPOpts,
5775 StringRef ExistingModuleCachePath, FileManager &FileMgr,
5776 bool StrictOptionMatches)
5777 : ExistingLangOpts(ExistingLangOpts), ExistingCGOpts(ExistingCGOpts),
5778 ExistingTargetOpts(ExistingTargetOpts),
5779 ExistingPPOpts(ExistingPPOpts),
5780 ExistingModuleCachePath(ExistingModuleCachePath), FileMgr(FileMgr),
5781 StrictOptionMatches(StrictOptionMatches) {}
5782
5783 bool ReadLanguageOptions(const LangOptions &LangOpts,
5784 StringRef ModuleFilename, bool Complain,
5785 bool AllowCompatibleDifferences) override {
5786 return checkLanguageOptions(ExistingLangOpts, LangOpts, ModuleFilename,
5787 nullptr, AllowCompatibleDifferences);
5788 }
5789
5790 bool ReadCodeGenOptions(const CodeGenOptions &CGOpts,
5791 StringRef ModuleFilename, bool Complain,
5792 bool AllowCompatibleDifferences) override {
5793 return checkCodegenOptions(ExistingCGOpts, CGOpts, ModuleFilename,
5794 nullptr, AllowCompatibleDifferences);
5795 }
5796
5797 bool ReadTargetOptions(const TargetOptions &TargetOpts,
5798 StringRef ModuleFilename, bool Complain,
5799 bool AllowCompatibleDifferences) override {
5800 return checkTargetOptions(ExistingTargetOpts, TargetOpts, ModuleFilename,
5801 nullptr, AllowCompatibleDifferences);
5802 }
5803
5804 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
5805 StringRef ModuleFilename,
5806 StringRef SpecificModuleCachePath,
5807 bool Complain) override {
5809 SpecificModuleCachePath,
5810 ExistingModuleCachePath, ModuleFilename,
5811 nullptr, ExistingLangOpts, ExistingPPOpts);
5812 }
5813
5814 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
5815 StringRef ModuleFilename, bool ReadMacros,
5816 bool Complain,
5817 std::string &SuggestedPredefines) override {
5819 PPOpts, ExistingPPOpts, ModuleFilename, ReadMacros, /*Diags=*/nullptr,
5820 FileMgr, SuggestedPredefines, ExistingLangOpts,
5821 StrictOptionMatches ? OptionValidateStrictMatches
5823 }
5824 };
5825
5826} // namespace
5827
5829 StringRef Filename, FileManager &FileMgr, const ModuleCache &ModCache,
5830 const PCHContainerReader &PCHContainerRdr, bool FindModuleFileExtensions,
5831 ASTReaderListener &Listener, bool ValidateDiagnosticOptions,
5832 unsigned ClientLoadCapabilities) {
5833 // Open the AST file.
5834 std::unique_ptr<llvm::MemoryBuffer> OwnedBuffer;
5835 llvm::MemoryBuffer *Buffer =
5836 ModCache.getInMemoryModuleCache().lookupPCM(Filename);
5837 if (!Buffer) {
5838 // FIXME: We should add the pcm to the InMemoryModuleCache if it could be
5839 // read again later, but we do not have the context here to determine if it
5840 // is safe to change the result of InMemoryModuleCache::getPCMState().
5841
5842 // FIXME: This allows use of the VFS; we do not allow use of the
5843 // VFS when actually loading a module.
5844 auto Entry =
5845 Filename == "-" ? FileMgr.getSTDIN() : FileMgr.getFileRef(Filename);
5846 if (!Entry) {
5847 llvm::consumeError(Entry.takeError());
5848 return true;
5849 }
5850 auto BufferOrErr = FileMgr.getBufferForFile(*Entry);
5851 if (!BufferOrErr)
5852 return true;
5853 OwnedBuffer = std::move(*BufferOrErr);
5854 Buffer = OwnedBuffer.get();
5855 }
5856
5857 // Initialize the stream
5858 StringRef Bytes = PCHContainerRdr.ExtractPCH(*Buffer);
5859 BitstreamCursor Stream(Bytes);
5860
5861 // Sniff for the signature.
5862 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5863 consumeError(std::move(Err)); // FIXME this drops errors on the floor.
5864 return true;
5865 }
5866
5867 // Scan for the CONTROL_BLOCK_ID block.
5869 return true;
5870
5871 bool NeedsInputFiles = Listener.needsInputFileVisitation();
5872 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
5873 bool NeedsImports = Listener.needsImportVisitation();
5874 BitstreamCursor InputFilesCursor;
5875 uint64_t InputFilesOffsetBase = 0;
5876
5878 std::string ModuleDir;
5879 bool DoneWithControlBlock = false;
5880 SmallString<0> PathBuf;
5881 PathBuf.reserve(256);
5882 // Additional path buffer to use when multiple paths need to be resolved.
5883 // For example, when deserializing input files that contains a path that was
5884 // resolved from a vfs overlay and an external location.
5885 SmallString<0> AdditionalPathBuf;
5886 AdditionalPathBuf.reserve(256);
5887 while (!DoneWithControlBlock) {
5888 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5889 if (!MaybeEntry) {
5890 // FIXME this drops the error on the floor.
5891 consumeError(MaybeEntry.takeError());
5892 return true;
5893 }
5894 llvm::BitstreamEntry Entry = MaybeEntry.get();
5895
5896 switch (Entry.Kind) {
5897 case llvm::BitstreamEntry::SubBlock: {
5898 switch (Entry.ID) {
5899 case OPTIONS_BLOCK_ID: {
5900 std::string IgnoredSuggestedPredefines;
5901 if (ReadOptionsBlock(Stream, Filename, ClientLoadCapabilities,
5902 /*AllowCompatibleConfigurationMismatch*/ false,
5903 Listener, IgnoredSuggestedPredefines) != Success)
5904 return true;
5905 break;
5906 }
5907
5909 InputFilesCursor = Stream;
5910 if (llvm::Error Err = Stream.SkipBlock()) {
5911 // FIXME this drops the error on the floor.
5912 consumeError(std::move(Err));
5913 return true;
5914 }
5915 if (NeedsInputFiles &&
5916 ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID))
5917 return true;
5918 InputFilesOffsetBase = InputFilesCursor.GetCurrentBitNo();
5919 break;
5920
5921 default:
5922 if (llvm::Error Err = Stream.SkipBlock()) {
5923 // FIXME this drops the error on the floor.
5924 consumeError(std::move(Err));
5925 return true;
5926 }
5927 break;
5928 }
5929
5930 continue;
5931 }
5932
5933 case llvm::BitstreamEntry::EndBlock:
5934 DoneWithControlBlock = true;
5935 break;
5936
5937 case llvm::BitstreamEntry::Error:
5938 return true;
5939
5940 case llvm::BitstreamEntry::Record:
5941 break;
5942 }
5943
5944 if (DoneWithControlBlock) break;
5945
5946 Record.clear();
5947 StringRef Blob;
5948 Expected<unsigned> MaybeRecCode =
5949 Stream.readRecord(Entry.ID, Record, &Blob);
5950 if (!MaybeRecCode) {
5951 // FIXME this drops the error.
5952 return Failure;
5953 }
5954 switch ((ControlRecordTypes)MaybeRecCode.get()) {
5955 case METADATA:
5956 if (Record[0] != VERSION_MAJOR)
5957 return true;
5958 if (Listener.ReadFullVersionInformation(Blob))
5959 return true;
5960 break;
5961 case MODULE_NAME:
5962 Listener.ReadModuleName(Blob);
5963 break;
5964 case MODULE_DIRECTORY:
5965 ModuleDir = std::string(Blob);
5966 break;
5967 case MODULE_MAP_FILE: {
5968 unsigned Idx = 0;
5969 std::string PathStr = ReadString(Record, Idx);
5970 auto Path = ResolveImportedPath(PathBuf, PathStr, ModuleDir);
5971 Listener.ReadModuleMapFile(*Path);
5972 break;
5973 }
5974 case INPUT_FILE_OFFSETS: {
5975 if (!NeedsInputFiles)
5976 break;
5977
5978 unsigned NumInputFiles = Record[0];
5979 unsigned NumUserFiles = Record[1];
5980 const llvm::support::unaligned_uint64_t *InputFileOffs =
5981 (const llvm::support::unaligned_uint64_t *)Blob.data();
5982 for (unsigned I = 0; I != NumInputFiles; ++I) {
5983 // Go find this input file.
5984 bool isSystemFile = I >= NumUserFiles;
5985
5986 if (isSystemFile && !NeedsSystemInputFiles)
5987 break; // the rest are system input files
5988
5989 BitstreamCursor &Cursor = InputFilesCursor;
5990 SavedStreamPosition SavedPosition(Cursor);
5991 if (llvm::Error Err =
5992 Cursor.JumpToBit(InputFilesOffsetBase + InputFileOffs[I])) {
5993 // FIXME this drops errors on the floor.
5994 consumeError(std::move(Err));
5995 }
5996
5997 Expected<unsigned> MaybeCode = Cursor.ReadCode();
5998 if (!MaybeCode) {
5999 // FIXME this drops errors on the floor.
6000 consumeError(MaybeCode.takeError());
6001 }
6002 unsigned Code = MaybeCode.get();
6003
6005 StringRef Blob;
6006 bool shouldContinue = false;
6007 Expected<unsigned> MaybeRecordType =
6008 Cursor.readRecord(Code, Record, &Blob);
6009 if (!MaybeRecordType) {
6010 // FIXME this drops errors on the floor.
6011 consumeError(MaybeRecordType.takeError());
6012 }
6013 switch ((InputFileRecordTypes)MaybeRecordType.get()) {
6014 case INPUT_FILE_HASH:
6015 break;
6016 case INPUT_FILE:
6017 bool Overridden = static_cast<bool>(Record[3]);
6018 auto [UnresolvedFilenameAsRequested, UnresolvedFilename] =
6020 auto FilenameAsRequestedBuf = ResolveImportedPath(
6021 PathBuf, UnresolvedFilenameAsRequested, ModuleDir);
6022 StringRef Filename;
6023 if (UnresolvedFilename.empty())
6024 Filename = *FilenameAsRequestedBuf;
6025 else {
6026 auto FilenameBuf = ResolveImportedPath(
6027 AdditionalPathBuf, UnresolvedFilename, ModuleDir);
6028 Filename = *FilenameBuf;
6029 }
6030 shouldContinue = Listener.visitInputFileAsRequested(
6031 *FilenameAsRequestedBuf, Filename, isSystemFile, Overridden,
6032 /*IsExplicitModule=*/false);
6033 break;
6034 }
6035 if (!shouldContinue)
6036 break;
6037 }
6038 break;
6039 }
6040
6041 case IMPORT: {
6042 if (!NeedsImports)
6043 break;
6044
6045 unsigned Idx = 0;
6046 // Read information about the AST file.
6047
6048 // Skip Kind
6049 Idx++;
6050
6051 // Skip ImportLoc
6052 Idx++;
6053
6054 StringRef ModuleName = ReadStringBlob(Record, Idx, Blob);
6055
6056 bool IsStandardCXXModule = Record[Idx++];
6057
6058 // In C++20 Modules, we don't record the path to imported
6059 // modules in the BMI files.
6060 if (IsStandardCXXModule) {
6061 Listener.visitImport(ModuleName, /*Filename=*/"");
6062 continue;
6063 }
6064
6065 // Skip Size and ModTime.
6066 Idx += 1 + 1;
6067 // Skip signature.
6068 Blob = Blob.substr(ASTFileSignature::size);
6069
6070 StringRef FilenameStr = ReadStringBlob(Record, Idx, Blob);
6071 auto Filename = ResolveImportedPath(PathBuf, FilenameStr, ModuleDir);
6072 Listener.visitImport(ModuleName, *Filename);
6073 break;
6074 }
6075
6076 default:
6077 // No other validation to perform.
6078 break;
6079 }
6080 }
6081
6082 // Look for module file extension blocks, if requested.
6083 if (FindModuleFileExtensions) {
6084 BitstreamCursor SavedStream = Stream;
6085 while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {
6086 bool DoneWithExtensionBlock = false;
6087 while (!DoneWithExtensionBlock) {
6088 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
6089 if (!MaybeEntry) {
6090 // FIXME this drops the error.
6091 return true;
6092 }
6093 llvm::BitstreamEntry Entry = MaybeEntry.get();
6094
6095 switch (Entry.Kind) {
6096 case llvm::BitstreamEntry::SubBlock:
6097 if (llvm::Error Err = Stream.SkipBlock()) {
6098 // FIXME this drops the error on the floor.
6099 consumeError(std::move(Err));
6100 return true;
6101 }
6102 continue;
6103
6104 case llvm::BitstreamEntry::EndBlock:
6105 DoneWithExtensionBlock = true;
6106 continue;
6107
6108 case llvm::BitstreamEntry::Error:
6109 return true;
6110
6111 case llvm::BitstreamEntry::Record:
6112 break;
6113 }
6114
6115 Record.clear();
6116 StringRef Blob;
6117 Expected<unsigned> MaybeRecCode =
6118 Stream.readRecord(Entry.ID, Record, &Blob);
6119 if (!MaybeRecCode) {
6120 // FIXME this drops the error.
6121 return true;
6122 }
6123 switch (MaybeRecCode.get()) {
6124 case EXTENSION_METADATA: {
6126 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
6127 return true;
6128
6129 Listener.readModuleFileExtension(Metadata);
6130 break;
6131 }
6132 }
6133 }
6134 }
6135 Stream = std::move(SavedStream);
6136 }
6137
6138 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
6139 if (readUnhashedControlBlockImpl(
6140 nullptr, Bytes, Filename, ClientLoadCapabilities,
6141 /*AllowCompatibleConfigurationMismatch*/ false, &Listener,
6142 ValidateDiagnosticOptions) != Success)
6143 return true;
6144
6145 return false;
6146}
6147
6149 StringRef Filename, FileManager &FileMgr, const ModuleCache &ModCache,
6150 const PCHContainerReader &PCHContainerRdr, const LangOptions &LangOpts,
6151 const CodeGenOptions &CGOpts, const TargetOptions &TargetOpts,
6152 const PreprocessorOptions &PPOpts, StringRef ExistingModuleCachePath,
6153 bool RequireStrictOptionMatches) {
6154 SimplePCHValidator validator(LangOpts, CGOpts, TargetOpts, PPOpts,
6155 ExistingModuleCachePath, FileMgr,
6156 RequireStrictOptionMatches);
6157 return !readASTFileControlBlock(Filename, FileMgr, ModCache, PCHContainerRdr,
6158 /*FindModuleFileExtensions=*/false, validator,
6159 /*ValidateDiagnosticOptions=*/true);
6160}
6161
6162llvm::Error ASTReader::ReadSubmoduleBlock(ModuleFile &F,
6163 unsigned ClientLoadCapabilities) {
6164 // Enter the submodule block.
6165 if (llvm::Error Err = F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID))
6166 return Err;
6167
6168 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
6169 bool KnowsTopLevelModule = ModMap.findModule(F.ModuleName) != nullptr;
6170 // If we don't know the top-level module, there's no point in doing qualified
6171 // lookup of its submodules; it won't find anything anywhere within this tree.
6172 // Let's skip that and avoid some string lookups.
6173 auto CreateModule = !KnowsTopLevelModule
6176
6177 bool First = true;
6178 Module *CurrentModule = nullptr;
6179 RecordData Record;
6180 while (true) {
6182 F.Stream.advanceSkippingSubblocks();
6183 if (!MaybeEntry)
6184 return MaybeEntry.takeError();
6185 llvm::BitstreamEntry Entry = MaybeEntry.get();
6186
6187 switch (Entry.Kind) {
6188 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
6189 case llvm::BitstreamEntry::Error:
6190 return llvm::createStringError(std::errc::illegal_byte_sequence,
6191 "malformed block record in AST file");
6192 case llvm::BitstreamEntry::EndBlock:
6193 return llvm::Error::success();
6194 case llvm::BitstreamEntry::Record:
6195 // The interesting case.
6196 break;
6197 }
6198
6199 // Read a record.
6200 StringRef Blob;
6201 Record.clear();
6202 Expected<unsigned> MaybeKind = F.Stream.readRecord(Entry.ID, Record, &Blob);
6203 if (!MaybeKind)
6204 return MaybeKind.takeError();
6205 unsigned Kind = MaybeKind.get();
6206
6207 if ((Kind == SUBMODULE_METADATA) != First)
6208 return llvm::createStringError(
6209 std::errc::illegal_byte_sequence,
6210 "submodule metadata record should be at beginning of block");
6211 First = false;
6212
6213 // Submodule information is only valid if we have a current module.
6214 // FIXME: Should we error on these cases?
6215 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
6216 Kind != SUBMODULE_DEFINITION)
6217 continue;
6218
6219 switch (Kind) {
6220 default: // Default behavior: ignore.
6221 break;
6222
6223 case SUBMODULE_DEFINITION: {
6224 if (Record.size() < 13)
6225 return llvm::createStringError(std::errc::illegal_byte_sequence,
6226 "malformed module definition");
6227
6228 StringRef Name = Blob;
6229 unsigned Idx = 0;
6230 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
6231 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
6233 SourceLocation DefinitionLoc = ReadSourceLocation(F, Record[Idx++]);
6234 FileID InferredAllowedBy = ReadFileID(F, Record, Idx);
6235 bool IsFramework = Record[Idx++];
6236 bool IsExplicit = Record[Idx++];
6237 bool IsSystem = Record[Idx++];
6238 bool IsExternC = Record[Idx++];
6239 bool InferSubmodules = Record[Idx++];
6240 bool InferExplicitSubmodules = Record[Idx++];
6241 bool InferExportWildcard = Record[Idx++];
6242 bool ConfigMacrosExhaustive = Record[Idx++];
6243 bool ModuleMapIsPrivate = Record[Idx++];
6244 bool NamedModuleHasInit = Record[Idx++];
6245
6246 Module *ParentModule = nullptr;
6247 if (Parent)
6248 ParentModule = getSubmodule(Parent);
6249
6250 CurrentModule = std::invoke(CreateModule, &ModMap, Name, ParentModule,
6251 IsFramework, IsExplicit);
6252
6253 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
6254 if (GlobalIndex >= SubmodulesLoaded.size() ||
6255 SubmodulesLoaded[GlobalIndex])
6256 return llvm::createStringError(std::errc::invalid_argument,
6257 "too many submodules");
6258
6259 if (!ParentModule) {
6260 if (OptionalFileEntryRef CurFile = CurrentModule->getASTFile()) {
6261 // Don't emit module relocation error if we have -fno-validate-pch
6262 if (!bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation &
6264 assert(CurFile != F.File && "ModuleManager did not de-duplicate");
6265
6266 Diag(diag::err_module_file_conflict)
6267 << CurrentModule->getTopLevelModuleName() << CurFile->getName()
6268 << F.File.getName();
6269
6270 auto CurModMapFile =
6271 ModMap.getContainingModuleMapFile(CurrentModule);
6272 auto ModMapFile = FileMgr.getOptionalFileRef(F.ModuleMapPath);
6273 if (CurModMapFile && ModMapFile && CurModMapFile != ModMapFile)
6274 Diag(diag::note_module_file_conflict)
6275 << CurModMapFile->getName() << ModMapFile->getName();
6276
6277 return llvm::make_error<AlreadyReportedDiagnosticError>();
6278 }
6279 }
6280
6281 F.DidReadTopLevelSubmodule = true;
6282 CurrentModule->setASTFile(F.File);
6283 CurrentModule->PresumedModuleMapFile = F.ModuleMapPath;
6284 }
6285
6286 CurrentModule->Kind = Kind;
6287 // Note that we may be rewriting an existing location and it is important
6288 // to keep doing that. In particular, we would like to prefer a
6289 // `DefinitionLoc` loaded from the module file instead of the location
6290 // created in the current source manager, because it allows the new
6291 // location to be marked as "unaffecting" when writing and avoid creating
6292 // duplicate locations for the same module map file.
6293 CurrentModule->DefinitionLoc = DefinitionLoc;
6294 CurrentModule->Signature = F.Signature;
6295 CurrentModule->IsFromModuleFile = true;
6296 if (InferredAllowedBy.isValid())
6297 ModMap.setInferredModuleAllowedBy(CurrentModule, InferredAllowedBy);
6298 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
6299 CurrentModule->IsExternC = IsExternC;
6300 CurrentModule->InferSubmodules = InferSubmodules;
6301 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
6302 CurrentModule->InferExportWildcard = InferExportWildcard;
6303 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
6304 CurrentModule->ModuleMapIsPrivate = ModuleMapIsPrivate;
6305 CurrentModule->NamedModuleHasInit = NamedModuleHasInit;
6306 if (DeserializationListener)
6307 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
6308
6309 SubmodulesLoaded[GlobalIndex] = CurrentModule;
6310
6311 // Clear out data that will be replaced by what is in the module file.
6312 CurrentModule->LinkLibraries.clear();
6313 CurrentModule->ConfigMacros.clear();
6314 CurrentModule->UnresolvedConflicts.clear();
6315 CurrentModule->Conflicts.clear();
6316
6317 // The module is available unless it's missing a requirement; relevant
6318 // requirements will be (re-)added by SUBMODULE_REQUIRES records.
6319 // Missing headers that were present when the module was built do not
6320 // make it unavailable -- if we got this far, this must be an explicitly
6321 // imported module file.
6322 CurrentModule->Requirements.clear();
6323 CurrentModule->MissingHeaders.clear();
6324 CurrentModule->IsUnimportable =
6325 ParentModule && ParentModule->IsUnimportable;
6326 CurrentModule->IsAvailable = !CurrentModule->IsUnimportable;
6327 break;
6328 }
6329
6331 // FIXME: This doesn't work for framework modules as `Filename` is the
6332 // name as written in the module file and does not include
6333 // `Headers/`, so this path will never exist.
6334 auto Filename = ResolveImportedPath(PathBuf, Blob, F);
6335 if (auto Umbrella = PP.getFileManager().getOptionalFileRef(*Filename)) {
6336 if (!CurrentModule->getUmbrellaHeaderAsWritten()) {
6337 // FIXME: NameAsWritten
6338 ModMap.setUmbrellaHeaderAsWritten(CurrentModule, *Umbrella, Blob, "");
6339 }
6340 // Note that it's too late at this point to return out of date if the
6341 // name from the PCM doesn't match up with the one in the module map,
6342 // but also quite unlikely since we will have already checked the
6343 // modification time and size of the module map file itself.
6344 }
6345 break;
6346 }
6347
6348 case SUBMODULE_HEADER:
6351 // We lazily associate headers with their modules via the HeaderInfo table.
6352 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
6353 // of complete filenames or remove it entirely.
6354 break;
6355
6358 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
6359 // them here.
6360 break;
6361
6362 case SUBMODULE_TOPHEADER: {
6363 auto HeaderName = ResolveImportedPath(PathBuf, Blob, F);
6364 CurrentModule->addTopHeaderFilename(*HeaderName);
6365 break;
6366 }
6367
6369 // See comments in SUBMODULE_UMBRELLA_HEADER
6370 auto Dirname = ResolveImportedPath(PathBuf, Blob, F);
6371 if (auto Umbrella =
6372 PP.getFileManager().getOptionalDirectoryRef(*Dirname)) {
6373 if (!CurrentModule->getUmbrellaDirAsWritten()) {
6374 // FIXME: NameAsWritten
6375 ModMap.setUmbrellaDirAsWritten(CurrentModule, *Umbrella, Blob, "");
6376 }
6377 }
6378 break;
6379 }
6380
6381 case SUBMODULE_METADATA: {
6382 F.BaseSubmoduleID = getTotalNumSubmodules();
6384 unsigned LocalBaseSubmoduleID = Record[1];
6385 if (F.LocalNumSubmodules > 0) {
6386 // Introduce the global -> local mapping for submodules within this
6387 // module.
6388 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
6389
6390 // Introduce the local -> global mapping for submodules within this
6391 // module.
6393 std::make_pair(LocalBaseSubmoduleID,
6394 F.BaseSubmoduleID - LocalBaseSubmoduleID));
6395
6396 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
6397 }
6398 break;
6399 }
6400
6401 case SUBMODULE_IMPORTS:
6402 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
6403 UnresolvedModuleRef Unresolved;
6404 Unresolved.File = &F;
6405 Unresolved.Mod = CurrentModule;
6406 Unresolved.ID = Record[Idx];
6407 Unresolved.Kind = UnresolvedModuleRef::Import;
6408 Unresolved.IsWildcard = false;
6409 UnresolvedModuleRefs.push_back(Unresolved);
6410 }
6411 break;
6412
6414 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
6415 UnresolvedModuleRef Unresolved;
6416 Unresolved.File = &F;
6417 Unresolved.Mod = CurrentModule;
6418 Unresolved.ID = Record[Idx];
6419 Unresolved.Kind = UnresolvedModuleRef::Affecting;
6420 Unresolved.IsWildcard = false;
6421 UnresolvedModuleRefs.push_back(Unresolved);
6422 }
6423 break;
6424
6425 case SUBMODULE_EXPORTS:
6426 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
6427 UnresolvedModuleRef Unresolved;
6428 Unresolved.File = &F;
6429 Unresolved.Mod = CurrentModule;
6430 Unresolved.ID = Record[Idx];
6431 Unresolved.Kind = UnresolvedModuleRef::Export;
6432 Unresolved.IsWildcard = Record[Idx + 1];
6433 UnresolvedModuleRefs.push_back(Unresolved);
6434 }
6435
6436 // Once we've loaded the set of exports, there's no reason to keep
6437 // the parsed, unresolved exports around.
6438 CurrentModule->UnresolvedExports.clear();
6439 break;
6440
6441 case SUBMODULE_REQUIRES:
6442 CurrentModule->addRequirement(Blob, Record[0], PP.getLangOpts(),
6443 PP.getTargetInfo());
6444 break;
6445
6447 ModMap.resolveLinkAsDependencies(CurrentModule);
6448 CurrentModule->LinkLibraries.push_back(
6449 Module::LinkLibrary(std::string(Blob), Record[0]));
6450 break;
6451
6453 CurrentModule->ConfigMacros.push_back(Blob.str());
6454 break;
6455
6456 case SUBMODULE_CONFLICT: {
6457 UnresolvedModuleRef Unresolved;
6458 Unresolved.File = &F;
6459 Unresolved.Mod = CurrentModule;
6460 Unresolved.ID = Record[0];
6461 Unresolved.Kind = UnresolvedModuleRef::Conflict;
6462 Unresolved.IsWildcard = false;
6463 Unresolved.String = Blob;
6464 UnresolvedModuleRefs.push_back(Unresolved);
6465 break;
6466 }
6467
6469 if (!ContextObj)
6470 break;
6471 // Standard C++ module has its own way to initialize variables.
6472 if (!F.StandardCXXModule || F.Kind == MK_MainFile) {
6473 SmallVector<GlobalDeclID, 16> Inits;
6474 for (unsigned I = 0; I < Record.size(); /*in loop*/)
6475 Inits.push_back(ReadDeclID(F, Record, I));
6476 ContextObj->addLazyModuleInitializers(CurrentModule, Inits);
6477 }
6478 break;
6479 }
6480
6482 CurrentModule->ExportAsModule = Blob.str();
6483 ModMap.addLinkAsDependency(CurrentModule);
6484 break;
6485 }
6486 }
6487}
6488
6489/// Parse the record that corresponds to a LangOptions data
6490/// structure.
6491///
6492/// This routine parses the language options from the AST file and then gives
6493/// them to the AST listener if one is set.
6494///
6495/// \returns true if the listener deems the file unacceptable, false otherwise.
6496bool ASTReader::ParseLanguageOptions(const RecordData &Record,
6497 StringRef ModuleFilename, bool Complain,
6498 ASTReaderListener &Listener,
6499 bool AllowCompatibleDifferences) {
6500 LangOptions LangOpts;
6501 unsigned Idx = 0;
6502#define LANGOPT(Name, Bits, Default, Compatibility, Description) \
6503 LangOpts.Name = Record[Idx++];
6504#define ENUM_LANGOPT(Name, Type, Bits, Default, Compatibility, Description) \
6505 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
6506#include "clang/Basic/LangOptions.def"
6507#define SANITIZER(NAME, ID) \
6508 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
6509#include "clang/Basic/Sanitizers.def"
6510
6511 for (unsigned N = Record[Idx++]; N; --N)
6512 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
6513
6514 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
6515 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
6516 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
6517
6518 LangOpts.CurrentModule = ReadString(Record, Idx);
6519
6520 // Comment options.
6521 for (unsigned N = Record[Idx++]; N; --N) {
6522 LangOpts.CommentOpts.BlockCommandNames.push_back(
6523 ReadString(Record, Idx));
6524 }
6525 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
6526
6527 // OpenMP offloading options.
6528 for (unsigned N = Record[Idx++]; N; --N) {
6529 LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx)));
6530 }
6531
6532 LangOpts.OMPHostIRFile = ReadString(Record, Idx);
6533
6534 return Listener.ReadLanguageOptions(LangOpts, ModuleFilename, Complain,
6535 AllowCompatibleDifferences);
6536}
6537
6538bool ASTReader::ParseCodeGenOptions(const RecordData &Record,
6539 StringRef ModuleFilename, bool Complain,
6540 ASTReaderListener &Listener,
6541 bool AllowCompatibleDifferences) {
6542 unsigned Idx = 0;
6543 CodeGenOptions CGOpts;
6545#define CODEGENOPT(Name, Bits, Default, Compatibility) \
6546 if constexpr (CK::Compatibility != CK::Benign) \
6547 CGOpts.Name = static_cast<unsigned>(Record[Idx++]);
6548#define ENUM_CODEGENOPT(Name, Type, Bits, Default, Compatibility) \
6549 if constexpr (CK::Compatibility != CK::Benign) \
6550 CGOpts.set##Name(static_cast<clang::CodeGenOptions::Type>(Record[Idx++]));
6551#define DEBUGOPT(Name, Bits, Default, Compatibility)
6552#define VALUE_DEBUGOPT(Name, Bits, Default, Compatibility)
6553#define ENUM_DEBUGOPT(Name, Type, Bits, Default, Compatibility)
6554#include "clang/Basic/CodeGenOptions.def"
6555
6556 return Listener.ReadCodeGenOptions(CGOpts, ModuleFilename, Complain,
6557 AllowCompatibleDifferences);
6558}
6559
6560bool ASTReader::ParseTargetOptions(const RecordData &Record,
6561 StringRef ModuleFilename, bool Complain,
6562 ASTReaderListener &Listener,
6563 bool AllowCompatibleDifferences) {
6564 unsigned Idx = 0;
6565 TargetOptions TargetOpts;
6566 TargetOpts.Triple = ReadString(Record, Idx);
6567 TargetOpts.CPU = ReadString(Record, Idx);
6568 TargetOpts.TuneCPU = ReadString(Record, Idx);
6569 TargetOpts.ABI = ReadString(Record, Idx);
6570 for (unsigned N = Record[Idx++]; N; --N) {
6571 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
6572 }
6573 for (unsigned N = Record[Idx++]; N; --N) {
6574 TargetOpts.Features.push_back(ReadString(Record, Idx));
6575 }
6576
6577 return Listener.ReadTargetOptions(TargetOpts, ModuleFilename, Complain,
6578 AllowCompatibleDifferences);
6579}
6580
6581bool ASTReader::ParseDiagnosticOptions(const RecordData &Record,
6582 StringRef ModuleFilename, bool Complain,
6583 ASTReaderListener &Listener) {
6584 DiagnosticOptions DiagOpts;
6585 unsigned Idx = 0;
6586#define DIAGOPT(Name, Bits, Default) DiagOpts.Name = Record[Idx++];
6587#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
6588 DiagOpts.set##Name(static_cast<Type>(Record[Idx++]));
6589#include "clang/Basic/DiagnosticOptions.def"
6590
6591 for (unsigned N = Record[Idx++]; N; --N)
6592 DiagOpts.Warnings.push_back(ReadString(Record, Idx));
6593 for (unsigned N = Record[Idx++]; N; --N)
6594 DiagOpts.Remarks.push_back(ReadString(Record, Idx));
6595
6596 return Listener.ReadDiagnosticOptions(DiagOpts, ModuleFilename, Complain);
6597}
6598
6599bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
6600 ASTReaderListener &Listener) {
6601 FileSystemOptions FSOpts;
6602 unsigned Idx = 0;
6603 FSOpts.WorkingDir = ReadString(Record, Idx);
6604 return Listener.ReadFileSystemOptions(FSOpts, Complain);
6605}
6606
6607bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
6608 StringRef ModuleFilename,
6609 bool Complain,
6610 ASTReaderListener &Listener) {
6611 HeaderSearchOptions HSOpts;
6612 unsigned Idx = 0;
6613 HSOpts.Sysroot = ReadString(Record, Idx);
6614
6615 HSOpts.ResourceDir = ReadString(Record, Idx);
6616 HSOpts.ModuleCachePath = ReadString(Record, Idx);
6617 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
6618 HSOpts.DisableModuleHash = Record[Idx++];
6619 HSOpts.ImplicitModuleMaps = Record[Idx++];
6620 HSOpts.ModuleMapFileHomeIsCwd = Record[Idx++];
6621 HSOpts.EnablePrebuiltImplicitModules = Record[Idx++];
6622 HSOpts.UseBuiltinIncludes = Record[Idx++];
6623 HSOpts.UseStandardSystemIncludes = Record[Idx++];
6624 HSOpts.UseStandardCXXIncludes = Record[Idx++];
6625 HSOpts.UseLibcxx = Record[Idx++];
6626 std::string SpecificModuleCachePath = ReadString(Record, Idx);
6627
6628 return Listener.ReadHeaderSearchOptions(HSOpts, ModuleFilename,
6629 SpecificModuleCachePath, Complain);
6630}
6631
6632bool ASTReader::ParseHeaderSearchPaths(const RecordData &Record, bool Complain,
6633 ASTReaderListener &Listener) {
6634 HeaderSearchOptions HSOpts;
6635 unsigned Idx = 0;
6636
6637 // Include entries.
6638 for (unsigned N = Record[Idx++]; N; --N) {
6639 std::string Path = ReadString(Record, Idx);
6641 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
6642 bool IsFramework = Record[Idx++];
6643 bool IgnoreSysRoot = Record[Idx++];
6644 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
6645 IgnoreSysRoot);
6646 }
6647
6648 // System header prefixes.
6649 for (unsigned N = Record[Idx++]; N; --N) {
6650 std::string Prefix = ReadString(Record, Idx);
6651 bool IsSystemHeader = Record[Idx++];
6652 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
6653 }
6654
6655 // VFS overlay files.
6656 for (unsigned N = Record[Idx++]; N; --N) {
6657 std::string VFSOverlayFile = ReadString(Record, Idx);
6658 HSOpts.VFSOverlayFiles.emplace_back(std::move(VFSOverlayFile));
6659 }
6660
6661 return Listener.ReadHeaderSearchPaths(HSOpts, Complain);
6662}
6663
6664bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
6665 StringRef ModuleFilename,
6666 bool Complain,
6667 ASTReaderListener &Listener,
6668 std::string &SuggestedPredefines) {
6669 PreprocessorOptions PPOpts;
6670 unsigned Idx = 0;
6671
6672 // Macro definitions/undefs
6673 bool ReadMacros = Record[Idx++];
6674 if (ReadMacros) {
6675 for (unsigned N = Record[Idx++]; N; --N) {
6676 std::string Macro = ReadString(Record, Idx);
6677 bool IsUndef = Record[Idx++];
6678 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
6679 }
6680 }
6681
6682 // Includes
6683 for (unsigned N = Record[Idx++]; N; --N) {
6684 PPOpts.Includes.push_back(ReadString(Record, Idx));
6685 }
6686
6687 // Macro Includes
6688 for (unsigned N = Record[Idx++]; N; --N) {
6689 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
6690 }
6691
6692 PPOpts.UsePredefines = Record[Idx++];
6693 PPOpts.DetailedRecord = Record[Idx++];
6694 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
6696 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
6697 SuggestedPredefines.clear();
6698 return Listener.ReadPreprocessorOptions(PPOpts, ModuleFilename, ReadMacros,
6699 Complain, SuggestedPredefines);
6700}
6701
6702std::pair<ModuleFile *, unsigned>
6703ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
6704 GlobalPreprocessedEntityMapType::iterator
6705 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
6706 assert(I != GlobalPreprocessedEntityMap.end() &&
6707 "Corrupted global preprocessed entity map");
6708 ModuleFile *M = I->second;
6709 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
6710 return std::make_pair(M, LocalIndex);
6711}
6712
6713llvm::iterator_range<PreprocessingRecord::iterator>
6714ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
6715 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
6716 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
6718
6719 return llvm::make_range(PreprocessingRecord::iterator(),
6720 PreprocessingRecord::iterator());
6721}
6722
6723bool ASTReader::canRecoverFromOutOfDate(StringRef ModuleFileName,
6724 unsigned int ClientLoadCapabilities) {
6725 return ClientLoadCapabilities & ARR_OutOfDate &&
6726 !getModuleManager()
6727 .getModuleCache()
6728 .getInMemoryModuleCache()
6729 .isPCMFinal(ModuleFileName);
6730}
6731
6732llvm::iterator_range<ASTReader::ModuleDeclIterator>
6734 return llvm::make_range(
6735 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
6736 ModuleDeclIterator(this, &Mod,
6738}
6739
6741 auto I = GlobalSkippedRangeMap.find(GlobalIndex);
6742 assert(I != GlobalSkippedRangeMap.end() &&
6743 "Corrupted global skipped range map");
6744 ModuleFile *M = I->second;
6745 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedSkippedRangeID;
6746 assert(LocalIndex < M->NumPreprocessedSkippedRanges);
6747 PPSkippedRange RawRange = M->PreprocessedSkippedRangeOffsets[LocalIndex];
6748 SourceRange Range(ReadSourceLocation(*M, RawRange.getBegin()),
6749 ReadSourceLocation(*M, RawRange.getEnd()));
6750 assert(Range.isValid());
6751 return Range;
6752}
6753
6754unsigned
6755ASTReader::translatePreprocessedEntityIDToIndex(PreprocessedEntityID ID) const {
6756 unsigned ModuleFileIndex = ID >> 32;
6757 assert(ModuleFileIndex && "not translating loaded MacroID?");
6758 assert(getModuleManager().size() > ModuleFileIndex - 1);
6759 ModuleFile &MF = getModuleManager()[ModuleFileIndex - 1];
6760
6761 ID &= llvm::maskTrailingOnes<PreprocessedEntityID>(32);
6762 return MF.BasePreprocessedEntityID + ID;
6763}
6764
6766 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
6767 ModuleFile &M = *PPInfo.first;
6768 unsigned LocalIndex = PPInfo.second;
6770 (static_cast<PreprocessedEntityID>(M.Index + 1) << 32) | LocalIndex;
6771 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
6772
6773 if (!PP.getPreprocessingRecord()) {
6774 Error("no preprocessing record");
6775 return nullptr;
6776 }
6777
6779 if (llvm::Error Err = M.PreprocessorDetailCursor.JumpToBit(
6780 M.MacroOffsetsBase + PPOffs.getOffset())) {
6781 Error(std::move(Err));
6782 return nullptr;
6783 }
6784
6786 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
6787 if (!MaybeEntry) {
6788 Error(MaybeEntry.takeError());
6789 return nullptr;
6790 }
6791 llvm::BitstreamEntry Entry = MaybeEntry.get();
6792
6793 if (Entry.Kind != llvm::BitstreamEntry::Record)
6794 return nullptr;
6795
6796 // Read the record.
6797 SourceRange Range(ReadSourceLocation(M, PPOffs.getBegin()),
6798 ReadSourceLocation(M, PPOffs.getEnd()));
6799 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
6800 StringRef Blob;
6802 Expected<unsigned> MaybeRecType =
6803 M.PreprocessorDetailCursor.readRecord(Entry.ID, Record, &Blob);
6804 if (!MaybeRecType) {
6805 Error(MaybeRecType.takeError());
6806 return nullptr;
6807 }
6808 switch ((PreprocessorDetailRecordTypes)MaybeRecType.get()) {
6809 case PPD_MACRO_EXPANSION: {
6810 bool isBuiltin = Record[0];
6811 IdentifierInfo *Name = nullptr;
6812 MacroDefinitionRecord *Def = nullptr;
6813 if (isBuiltin)
6814 Name = getLocalIdentifier(M, Record[1]);
6815 else {
6816 PreprocessedEntityID GlobalID =
6818 unsigned Index = translatePreprocessedEntityIDToIndex(GlobalID);
6819 Def =
6820 cast<MacroDefinitionRecord>(PPRec.getLoadedPreprocessedEntity(Index));
6821 }
6822
6823 MacroExpansion *ME;
6824 if (isBuiltin)
6825 ME = new (PPRec) MacroExpansion(Name, Range);
6826 else
6827 ME = new (PPRec) MacroExpansion(Def, Range);
6828
6829 return ME;
6830 }
6831
6832 case PPD_MACRO_DEFINITION: {
6833 // Decode the identifier info and then check again; if the macro is
6834 // still defined and associated with the identifier,
6836 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
6837
6838 if (DeserializationListener)
6839 DeserializationListener->MacroDefinitionRead(PPID, MD);
6840
6841 return MD;
6842 }
6843
6845 const char *FullFileNameStart = Blob.data() + Record[0];
6846 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
6848 if (!FullFileName.empty())
6849 File = PP.getFileManager().getOptionalFileRef(FullFileName);
6850
6851 // FIXME: Stable encoding
6853 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
6855 = new (PPRec) InclusionDirective(PPRec, Kind,
6856 StringRef(Blob.data(), Record[0]),
6857 Record[1], Record[3],
6858 File,
6859 Range);
6860 return ID;
6861 }
6862 }
6863
6864 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
6865}
6866
6867/// Find the next module that contains entities and return the ID
6868/// of the first entry.
6869///
6870/// \param SLocMapI points at a chunk of a module that contains no
6871/// preprocessed entities or the entities it contains are not the ones we are
6872/// looking for.
6873unsigned ASTReader::findNextPreprocessedEntity(
6874 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
6875 ++SLocMapI;
6876 for (GlobalSLocOffsetMapType::const_iterator
6877 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
6878 ModuleFile &M = *SLocMapI->second;
6880 return M.BasePreprocessedEntityID;
6881 }
6882
6883 return getTotalNumPreprocessedEntities();
6884}
6885
6886namespace {
6887
6888struct PPEntityComp {
6889 const ASTReader &Reader;
6890 ModuleFile &M;
6891
6892 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) {}
6893
6894 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
6895 SourceLocation LHS = getLoc(L);
6896 SourceLocation RHS = getLoc(R);
6897 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6898 }
6899
6900 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
6901 SourceLocation LHS = getLoc(L);
6902 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6903 }
6904
6905 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
6906 SourceLocation RHS = getLoc(R);
6907 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6908 }
6909
6910 SourceLocation getLoc(const PPEntityOffset &PPE) const {
6911 return Reader.ReadSourceLocation(M, PPE.getBegin());
6912 }
6913};
6914
6915} // namespace
6916
6917unsigned ASTReader::findPreprocessedEntity(SourceLocation Loc,
6918 bool EndsAfter) const {
6919 if (SourceMgr.isLocalSourceLocation(Loc))
6920 return getTotalNumPreprocessedEntities();
6921
6922 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
6923 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
6924 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
6925 "Corrupted global sloc offset map");
6926
6927 if (SLocMapI->second->NumPreprocessedEntities == 0)
6928 return findNextPreprocessedEntity(SLocMapI);
6929
6930 ModuleFile &M = *SLocMapI->second;
6931
6932 using pp_iterator = const PPEntityOffset *;
6933
6934 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
6935 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
6936
6937 size_t Count = M.NumPreprocessedEntities;
6938 size_t Half;
6939 pp_iterator First = pp_begin;
6940 pp_iterator PPI;
6941
6942 if (EndsAfter) {
6943 PPI = std::upper_bound(pp_begin, pp_end, Loc,
6944 PPEntityComp(*this, M));
6945 } else {
6946 // Do a binary search manually instead of using std::lower_bound because
6947 // The end locations of entities may be unordered (when a macro expansion
6948 // is inside another macro argument), but for this case it is not important
6949 // whether we get the first macro expansion or its containing macro.
6950 while (Count > 0) {
6951 Half = Count / 2;
6952 PPI = First;
6953 std::advance(PPI, Half);
6954 if (SourceMgr.isBeforeInTranslationUnit(
6955 ReadSourceLocation(M, PPI->getEnd()), Loc)) {
6956 First = PPI;
6957 ++First;
6958 Count = Count - Half - 1;
6959 } else
6960 Count = Half;
6961 }
6962 }
6963
6964 if (PPI == pp_end)
6965 return findNextPreprocessedEntity(SLocMapI);
6966
6967 return M.BasePreprocessedEntityID + (PPI - pp_begin);
6968}
6969
6970/// Returns a pair of [Begin, End) indices of preallocated
6971/// preprocessed entities that \arg Range encompasses.
6972std::pair<unsigned, unsigned>
6974 if (Range.isInvalid())
6975 return std::make_pair(0,0);
6976 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
6977
6978 unsigned BeginID = findPreprocessedEntity(Range.getBegin(), false);
6979 unsigned EndID = findPreprocessedEntity(Range.getEnd(), true);
6980 return std::make_pair(BeginID, EndID);
6981}
6982
6983/// Optionally returns true or false if the preallocated preprocessed
6984/// entity with index \arg Index came from file \arg FID.
6985std::optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
6986 FileID FID) {
6987 if (FID.isInvalid())
6988 return false;
6989
6990 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
6991 ModuleFile &M = *PPInfo.first;
6992 unsigned LocalIndex = PPInfo.second;
6993 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
6994
6995 SourceLocation Loc = ReadSourceLocation(M, PPOffs.getBegin());
6996 if (Loc.isInvalid())
6997 return false;
6998
6999 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
7000 return true;
7001 else
7002 return false;
7003}
7004
7005namespace {
7006
7007 /// Visitor used to search for information about a header file.
7008 class HeaderFileInfoVisitor {
7009 FileEntryRef FE;
7010 std::optional<HeaderFileInfo> HFI;
7011
7012 public:
7013 explicit HeaderFileInfoVisitor(FileEntryRef FE) : FE(FE) {}
7014
7015 bool operator()(ModuleFile &M) {
7018 if (!Table)
7019 return false;
7020
7021 // Look in the on-disk hash table for an entry for this file name.
7022 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
7023 if (Pos == Table->end())
7024 return false;
7025
7026 HFI = *Pos;
7027 return true;
7028 }
7029
7030 std::optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
7031 };
7032
7033} // namespace
7034
7036 HeaderFileInfoVisitor Visitor(FE);
7037 ModuleMgr.visit(Visitor);
7038 if (std::optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
7039 return *HFI;
7040
7041 return HeaderFileInfo();
7042}
7043
7045 using DiagState = DiagnosticsEngine::DiagState;
7047
7048 for (ModuleFile &F : ModuleMgr) {
7049 unsigned Idx = 0;
7050 auto &Record = F.PragmaDiagMappings;
7051 if (Record.empty())
7052 continue;
7053
7054 DiagStates.clear();
7055
7056 auto ReadDiagState = [&](const DiagState &BasedOn,
7057 bool IncludeNonPragmaStates) {
7058 unsigned BackrefID = Record[Idx++];
7059 if (BackrefID != 0)
7060 return DiagStates[BackrefID - 1];
7061
7062 // A new DiagState was created here.
7063 Diag.DiagStates.push_back(BasedOn);
7064 DiagState *NewState = &Diag.DiagStates.back();
7065 DiagStates.push_back(NewState);
7066 unsigned Size = Record[Idx++];
7067 assert(Idx + Size * 2 <= Record.size() &&
7068 "Invalid data, not enough diag/map pairs");
7069 while (Size--) {
7070 unsigned DiagID = Record[Idx++];
7071 DiagnosticMapping NewMapping =
7073 if (!NewMapping.isPragma() && !IncludeNonPragmaStates)
7074 continue;
7075
7076 DiagnosticMapping &Mapping = NewState->getOrAddMapping(DiagID);
7077
7078 // If this mapping was specified as a warning but the severity was
7079 // upgraded due to diagnostic settings, simulate the current diagnostic
7080 // settings (and use a warning).
7081 if (NewMapping.wasUpgradedFromWarning() && !Mapping.isErrorOrFatal()) {
7083 NewMapping.setUpgradedFromWarning(false);
7084 }
7085
7086 Mapping = NewMapping;
7087 }
7088 return NewState;
7089 };
7090
7091 // Read the first state.
7092 DiagState *FirstState;
7093 if (F.Kind == MK_ImplicitModule) {
7094 // Implicitly-built modules are reused with different diagnostic
7095 // settings. Use the initial diagnostic state from Diag to simulate this
7096 // compilation's diagnostic settings.
7097 FirstState = Diag.DiagStatesByLoc.FirstDiagState;
7098 DiagStates.push_back(FirstState);
7099
7100 // Skip the initial diagnostic state from the serialized module.
7101 assert(Record[1] == 0 &&
7102 "Invalid data, unexpected backref in initial state");
7103 Idx = 3 + Record[2] * 2;
7104 assert(Idx < Record.size() &&
7105 "Invalid data, not enough state change pairs in initial state");
7106 } else if (F.isModule()) {
7107 // For an explicit module, preserve the flags from the module build
7108 // command line (-w, -Weverything, -Werror, ...) along with any explicit
7109 // -Wblah flags.
7110 unsigned Flags = Record[Idx++];
7111 DiagState Initial(*Diag.getDiagnosticIDs());
7112 Initial.SuppressSystemWarnings = Flags & 1; Flags >>= 1;
7113 Initial.ErrorsAsFatal = Flags & 1; Flags >>= 1;
7114 Initial.WarningsAsErrors = Flags & 1; Flags >>= 1;
7115 Initial.EnableAllWarnings = Flags & 1; Flags >>= 1;
7116 Initial.IgnoreAllWarnings = Flags & 1; Flags >>= 1;
7117 Initial.ExtBehavior = (diag::Severity)Flags;
7118 FirstState = ReadDiagState(Initial, true);
7119
7120 assert(F.OriginalSourceFileID.isValid());
7121
7122 // Set up the root buffer of the module to start with the initial
7123 // diagnostic state of the module itself, to cover files that contain no
7124 // explicit transitions (for which we did not serialize anything).
7125 Diag.DiagStatesByLoc.Files[F.OriginalSourceFileID]
7126 .StateTransitions.push_back({FirstState, 0});
7127 } else {
7128 // For prefix ASTs, start with whatever the user configured on the
7129 // command line.
7130 Idx++; // Skip flags.
7131 FirstState = ReadDiagState(*Diag.DiagStatesByLoc.CurDiagState, false);
7132 }
7133
7134 // Read the state transitions.
7135 unsigned NumLocations = Record[Idx++];
7136 while (NumLocations--) {
7137 assert(Idx < Record.size() &&
7138 "Invalid data, missing pragma diagnostic states");
7139 FileID FID = ReadFileID(F, Record, Idx);
7140 assert(FID.isValid() && "invalid FileID for transition");
7141 unsigned Transitions = Record[Idx++];
7142
7143 // Note that we don't need to set up Parent/ParentOffset here, because
7144 // we won't be changing the diagnostic state within imported FileIDs
7145 // (other than perhaps appending to the main source file, which has no
7146 // parent).
7147 auto &F = Diag.DiagStatesByLoc.Files[FID];
7148 F.StateTransitions.reserve(F.StateTransitions.size() + Transitions);
7149 for (unsigned I = 0; I != Transitions; ++I) {
7150 unsigned Offset = Record[Idx++];
7151 auto *State = ReadDiagState(*FirstState, false);
7152 F.StateTransitions.push_back({State, Offset});
7153 }
7154 }
7155
7156 // Read the final state.
7157 assert(Idx < Record.size() &&
7158 "Invalid data, missing final pragma diagnostic state");
7159 SourceLocation CurStateLoc = ReadSourceLocation(F, Record[Idx++]);
7160 auto *CurState = ReadDiagState(*FirstState, false);
7161
7162 if (!F.isModule()) {
7163 Diag.DiagStatesByLoc.CurDiagState = CurState;
7164 Diag.DiagStatesByLoc.CurDiagStateLoc = CurStateLoc;
7165
7166 // Preserve the property that the imaginary root file describes the
7167 // current state.
7168 FileID NullFile;
7169 auto &T = Diag.DiagStatesByLoc.Files[NullFile].StateTransitions;
7170 if (T.empty())
7171 T.push_back({CurState, 0});
7172 else
7173 T[0].State = CurState;
7174 }
7175
7176 // Don't try to read these mappings again.
7177 Record.clear();
7178 }
7179}
7180
7181/// Get the correct cursor and offset for loading a type.
7182ASTReader::RecordLocation ASTReader::TypeCursorForIndex(TypeID ID) {
7183 auto [M, Index] = translateTypeIDToIndex(ID);
7184 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex].get() +
7186}
7187
7188static std::optional<Type::TypeClass> getTypeClassForCode(TypeCode code) {
7189 switch (code) {
7190#define TYPE_BIT_CODE(CLASS_ID, CODE_ID, CODE_VALUE) \
7191 case TYPE_##CODE_ID: return Type::CLASS_ID;
7192#include "clang/Serialization/TypeBitCodes.def"
7193 default:
7194 return std::nullopt;
7195 }
7196}
7197
7198/// Read and return the type with the given index..
7199///
7200/// The index is the type ID, shifted and minus the number of predefs. This
7201/// routine actually reads the record corresponding to the type at the given
7202/// location. It is a helper routine for GetType, which deals with reading type
7203/// IDs.
7204QualType ASTReader::readTypeRecord(TypeID ID) {
7205 assert(ContextObj && "reading type with no AST context");
7206 ASTContext &Context = *ContextObj;
7207 RecordLocation Loc = TypeCursorForIndex(ID);
7208 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
7209
7210 // Keep track of where we are in the stream, then jump back there
7211 // after reading this type.
7212 SavedStreamPosition SavedPosition(DeclsCursor);
7213
7214 ReadingKindTracker ReadingKind(Read_Type, *this);
7215
7216 // Note that we are loading a type record.
7217 Deserializing AType(this);
7218
7219 if (llvm::Error Err = DeclsCursor.JumpToBit(Loc.Offset)) {
7220 Error(std::move(Err));
7221 return QualType();
7222 }
7223 Expected<unsigned> RawCode = DeclsCursor.ReadCode();
7224 if (!RawCode) {
7225 Error(RawCode.takeError());
7226 return QualType();
7227 }
7228
7229 ASTRecordReader Record(*this, *Loc.F);
7230 Expected<unsigned> Code = Record.readRecord(DeclsCursor, RawCode.get());
7231 if (!Code) {
7232 Error(Code.takeError());
7233 return QualType();
7234 }
7235 if (Code.get() == TYPE_EXT_QUAL) {
7236 QualType baseType = Record.readQualType();
7237 Qualifiers quals = Record.readQualifiers();
7238 return Context.getQualifiedType(baseType, quals);
7239 }
7240
7241 auto maybeClass = getTypeClassForCode((TypeCode) Code.get());
7242 if (!maybeClass) {
7243 Error("Unexpected code for type");
7244 return QualType();
7245 }
7246
7247 serialization::AbstractTypeReader<ASTRecordReader> TypeReader(Record);
7248 return TypeReader.read(*maybeClass);
7249}
7250
7251namespace clang {
7252
7253class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
7254 ASTRecordReader &Reader;
7255
7256 SourceLocation readSourceLocation() { return Reader.readSourceLocation(); }
7257 SourceRange readSourceRange() { return Reader.readSourceRange(); }
7258
7259 TypeSourceInfo *GetTypeSourceInfo() {
7260 return Reader.readTypeSourceInfo();
7261 }
7262
7263 NestedNameSpecifierLoc ReadNestedNameSpecifierLoc() {
7264 return Reader.readNestedNameSpecifierLoc();
7265 }
7266
7267 Attr *ReadAttr() {
7268 return Reader.readAttr();
7269 }
7270
7271public:
7272 TypeLocReader(ASTRecordReader &Reader) : Reader(Reader) {}
7273
7274 // We want compile-time assurance that we've enumerated all of
7275 // these, so unfortunately we have to declare them first, then
7276 // define them out-of-line.
7277#define ABSTRACT_TYPELOC(CLASS, PARENT)
7278#define TYPELOC(CLASS, PARENT) \
7279 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
7280#include "clang/AST/TypeLocNodes.def"
7281
7284 void VisitTagTypeLoc(TagTypeLoc TL);
7285};
7286
7287} // namespace clang
7288
7289void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
7290 // nothing to do
7291}
7292
7293void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
7294 TL.setBuiltinLoc(readSourceLocation());
7295 if (TL.needsExtraLocalData()) {
7296 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Reader.readInt()));
7297 TL.setWrittenSignSpec(static_cast<TypeSpecifierSign>(Reader.readInt()));
7298 TL.setWrittenWidthSpec(static_cast<TypeSpecifierWidth>(Reader.readInt()));
7299 TL.setModeAttr(Reader.readInt());
7300 }
7301}
7302
7303void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
7304 TL.setNameLoc(readSourceLocation());
7305}
7306
7307void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
7308 TL.setStarLoc(readSourceLocation());
7309}
7310
7311void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
7312 // nothing to do
7313}
7314
7315void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
7316 // nothing to do
7317}
7318
7319void TypeLocReader::VisitArrayParameterTypeLoc(ArrayParameterTypeLoc TL) {
7320 // nothing to do
7321}
7322
7323void TypeLocReader::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
7324 TL.setExpansionLoc(readSourceLocation());
7325}
7326
7327void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
7328 TL.setCaretLoc(readSourceLocation());
7329}
7330
7331void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
7332 TL.setAmpLoc(readSourceLocation());
7333}
7334
7335void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
7336 TL.setAmpAmpLoc(readSourceLocation());
7337}
7338
7339void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
7340 TL.setStarLoc(readSourceLocation());
7341 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
7342}
7343
7345 TL.setLBracketLoc(readSourceLocation());
7346 TL.setRBracketLoc(readSourceLocation());
7347 if (Reader.readBool())
7348 TL.setSizeExpr(Reader.readExpr());
7349 else
7350 TL.setSizeExpr(nullptr);
7351}
7352
7353void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
7354 VisitArrayTypeLoc(TL);
7355}
7356
7357void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
7358 VisitArrayTypeLoc(TL);
7359}
7360
7361void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
7362 VisitArrayTypeLoc(TL);
7363}
7364
7365void TypeLocReader::VisitDependentSizedArrayTypeLoc(
7366 DependentSizedArrayTypeLoc TL) {
7367 VisitArrayTypeLoc(TL);
7368}
7369
7370void TypeLocReader::VisitDependentAddressSpaceTypeLoc(
7371 DependentAddressSpaceTypeLoc TL) {
7372
7373 TL.setAttrNameLoc(readSourceLocation());
7374 TL.setAttrOperandParensRange(readSourceRange());
7375 TL.setAttrExprOperand(Reader.readExpr());
7376}
7377
7378void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
7379 DependentSizedExtVectorTypeLoc TL) {
7380 TL.setNameLoc(readSourceLocation());
7381}
7382
7383void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
7384 TL.setNameLoc(readSourceLocation());
7385}
7386
7387void TypeLocReader::VisitDependentVectorTypeLoc(
7388 DependentVectorTypeLoc TL) {
7389 TL.setNameLoc(readSourceLocation());
7390}
7391
7392void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
7393 TL.setNameLoc(readSourceLocation());
7394}
7395
7396void TypeLocReader::VisitConstantMatrixTypeLoc(ConstantMatrixTypeLoc TL) {
7397 TL.setAttrNameLoc(readSourceLocation());
7398 TL.setAttrOperandParensRange(readSourceRange());
7399 TL.setAttrRowOperand(Reader.readExpr());
7400 TL.setAttrColumnOperand(Reader.readExpr());
7401}
7402
7403void TypeLocReader::VisitDependentSizedMatrixTypeLoc(
7404 DependentSizedMatrixTypeLoc TL) {
7405 TL.setAttrNameLoc(readSourceLocation());
7406 TL.setAttrOperandParensRange(readSourceRange());
7407 TL.setAttrRowOperand(Reader.readExpr());
7408 TL.setAttrColumnOperand(Reader.readExpr());
7409}
7410
7412 TL.setLocalRangeBegin(readSourceLocation());
7413 TL.setLParenLoc(readSourceLocation());
7414 TL.setRParenLoc(readSourceLocation());
7415 TL.setExceptionSpecRange(readSourceRange());
7416 TL.setLocalRangeEnd(readSourceLocation());
7417 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
7418 TL.setParam(i, Reader.readDeclAs<ParmVarDecl>());
7419 }
7420}
7421
7422void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
7423 VisitFunctionTypeLoc(TL);
7424}
7425
7426void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
7427 VisitFunctionTypeLoc(TL);
7428}
7429
7430void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
7431 SourceLocation ElaboratedKeywordLoc = readSourceLocation();
7432 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc();
7433 SourceLocation NameLoc = readSourceLocation();
7434 TL.set(ElaboratedKeywordLoc, QualifierLoc, NameLoc);
7435}
7436
7437void TypeLocReader::VisitUsingTypeLoc(UsingTypeLoc TL) {
7438 SourceLocation ElaboratedKeywordLoc = readSourceLocation();
7439 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc();
7440 SourceLocation NameLoc = readSourceLocation();
7441 TL.set(ElaboratedKeywordLoc, QualifierLoc, NameLoc);
7442}
7443
7444void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
7445 SourceLocation ElaboratedKeywordLoc = readSourceLocation();
7446 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc();
7447 SourceLocation NameLoc = readSourceLocation();
7448 TL.set(ElaboratedKeywordLoc, QualifierLoc, NameLoc);
7449}
7450
7451void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
7452 TL.setTypeofLoc(readSourceLocation());
7453 TL.setLParenLoc(readSourceLocation());
7454 TL.setRParenLoc(readSourceLocation());
7455}
7456
7457void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
7458 TL.setTypeofLoc(readSourceLocation());
7459 TL.setLParenLoc(readSourceLocation());
7460 TL.setRParenLoc(readSourceLocation());
7461 TL.setUnmodifiedTInfo(GetTypeSourceInfo());
7462}
7463
7464void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
7465 TL.setDecltypeLoc(readSourceLocation());
7466 TL.setRParenLoc(readSourceLocation());
7467}
7468
7469void TypeLocReader::VisitPackIndexingTypeLoc(PackIndexingTypeLoc TL) {
7470 TL.setEllipsisLoc(readSourceLocation());
7471}
7472
7473void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
7474 TL.setKWLoc(readSourceLocation());
7475 TL.setLParenLoc(readSourceLocation());
7476 TL.setRParenLoc(readSourceLocation());
7477 TL.setUnderlyingTInfo(GetTypeSourceInfo());
7478}
7479
7481 auto NNS = readNestedNameSpecifierLoc();
7482 auto TemplateKWLoc = readSourceLocation();
7483 auto ConceptNameLoc = readDeclarationNameInfo();
7484 auto FoundDecl = readDeclAs<NamedDecl>();
7485 auto NamedConcept = readDeclAs<ConceptDecl>();
7486 auto *CR = ConceptReference::Create(
7487 getContext(), NNS, TemplateKWLoc, ConceptNameLoc, FoundDecl, NamedConcept,
7488 (readBool() ? readASTTemplateArgumentListInfo() : nullptr));
7489 return CR;
7490}
7491
7492void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
7493 TL.setNameLoc(readSourceLocation());
7494 if (Reader.readBool())
7495 TL.setConceptReference(Reader.readConceptReference());
7496 if (Reader.readBool())
7497 TL.setRParenLoc(readSourceLocation());
7498}
7499
7500void TypeLocReader::VisitDeducedTemplateSpecializationTypeLoc(
7502 TL.setElaboratedKeywordLoc(readSourceLocation());
7503 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
7504 TL.setTemplateNameLoc(readSourceLocation());
7505}
7506
7508 TL.setElaboratedKeywordLoc(readSourceLocation());
7509 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
7510 TL.setNameLoc(readSourceLocation());
7511}
7512
7513void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
7514 VisitTagTypeLoc(TL);
7515}
7516
7517void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
7518 VisitTagTypeLoc(TL);
7519}
7520
7521void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) { VisitTagTypeLoc(TL); }
7522
7523void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
7524 TL.setAttr(ReadAttr());
7525}
7526
7527void TypeLocReader::VisitCountAttributedTypeLoc(CountAttributedTypeLoc TL) {
7528 // Nothing to do
7529}
7530
7531void TypeLocReader::VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) {
7532 // Nothing to do.
7533}
7534
7535void TypeLocReader::VisitHLSLAttributedResourceTypeLoc(
7536 HLSLAttributedResourceTypeLoc TL) {
7537 // Nothing to do.
7538}
7539
7540void TypeLocReader::VisitHLSLInlineSpirvTypeLoc(HLSLInlineSpirvTypeLoc TL) {
7541 // Nothing to do.
7542}
7543
7544void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
7545 TL.setNameLoc(readSourceLocation());
7546}
7547
7548void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
7549 SubstTemplateTypeParmTypeLoc TL) {
7550 TL.setNameLoc(readSourceLocation());
7551}
7552
7553void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
7554 SubstTemplateTypeParmPackTypeLoc TL) {
7555 TL.setNameLoc(readSourceLocation());
7556}
7557
7558void TypeLocReader::VisitSubstBuiltinTemplatePackTypeLoc(
7559 SubstBuiltinTemplatePackTypeLoc TL) {
7560 TL.setNameLoc(readSourceLocation());
7561}
7562
7563void TypeLocReader::VisitTemplateSpecializationTypeLoc(
7564 TemplateSpecializationTypeLoc TL) {
7565 SourceLocation ElaboratedKeywordLoc = readSourceLocation();
7566 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc();
7567 SourceLocation TemplateKeywordLoc = readSourceLocation();
7568 SourceLocation NameLoc = readSourceLocation();
7569 SourceLocation LAngleLoc = readSourceLocation();
7570 SourceLocation RAngleLoc = readSourceLocation();
7571 TL.set(ElaboratedKeywordLoc, QualifierLoc, TemplateKeywordLoc, NameLoc,
7572 LAngleLoc, RAngleLoc);
7573 MutableArrayRef<TemplateArgumentLocInfo> Args = TL.getArgLocInfos();
7574 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
7575 Args[I] = Reader.readTemplateArgumentLocInfo(
7576 TL.getTypePtr()->template_arguments()[I].getKind());
7577}
7578
7579void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
7580 TL.setLParenLoc(readSourceLocation());
7581 TL.setRParenLoc(readSourceLocation());
7582}
7583
7584void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
7585 TL.setElaboratedKeywordLoc(readSourceLocation());
7586 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
7587 TL.setNameLoc(readSourceLocation());
7588}
7589
7590void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
7591 TL.setEllipsisLoc(readSourceLocation());
7592}
7593
7594void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
7595 TL.setNameLoc(readSourceLocation());
7596 TL.setNameEndLoc(readSourceLocation());
7597}
7598
7599void TypeLocReader::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
7600 if (TL.getNumProtocols()) {
7601 TL.setProtocolLAngleLoc(readSourceLocation());
7602 TL.setProtocolRAngleLoc(readSourceLocation());
7603 }
7604 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
7605 TL.setProtocolLoc(i, readSourceLocation());
7606}
7607
7608void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
7609 TL.setHasBaseTypeAsWritten(Reader.readBool());
7610 TL.setTypeArgsLAngleLoc(readSourceLocation());
7611 TL.setTypeArgsRAngleLoc(readSourceLocation());
7612 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
7613 TL.setTypeArgTInfo(i, GetTypeSourceInfo());
7614 TL.setProtocolLAngleLoc(readSourceLocation());
7615 TL.setProtocolRAngleLoc(readSourceLocation());
7616 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
7617 TL.setProtocolLoc(i, readSourceLocation());
7618}
7619
7620void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
7621 TL.setStarLoc(readSourceLocation());
7622}
7623
7624void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
7625 TL.setKWLoc(readSourceLocation());
7626 TL.setLParenLoc(readSourceLocation());
7627 TL.setRParenLoc(readSourceLocation());
7628}
7629
7630void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) {
7631 TL.setKWLoc(readSourceLocation());
7632}
7633
7634void TypeLocReader::VisitBitIntTypeLoc(clang::BitIntTypeLoc TL) {
7635 TL.setNameLoc(readSourceLocation());
7636}
7637
7638void TypeLocReader::VisitDependentBitIntTypeLoc(
7639 clang::DependentBitIntTypeLoc TL) {
7640 TL.setNameLoc(readSourceLocation());
7641}
7642
7643void TypeLocReader::VisitPredefinedSugarTypeLoc(PredefinedSugarTypeLoc TL) {
7644 // Nothing to do.
7645}
7646
7648 TypeLocReader TLR(*this);
7649 for (; !TL.isNull(); TL = TL.getNextTypeLoc())
7650 TLR.Visit(TL);
7651}
7652
7654 QualType InfoTy = readType();
7655 if (InfoTy.isNull())
7656 return nullptr;
7657
7658 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
7659 readTypeLoc(TInfo->getTypeLoc());
7660 return TInfo;
7661}
7662
7664 return (ID & llvm::maskTrailingOnes<TypeID>(32)) >> Qualifiers::FastWidth;
7665}
7666
7668 return ID >> 32;
7669}
7670
7672 // We don't need to erase the higher bits since if these bits are not 0,
7673 // it must be larger than NUM_PREDEF_TYPE_IDS.
7675}
7676
7677std::pair<ModuleFile *, unsigned>
7678ASTReader::translateTypeIDToIndex(serialization::TypeID ID) const {
7679 assert(!isPredefinedType(ID) &&
7680 "Predefined type shouldn't be in TypesLoaded");
7681 unsigned ModuleFileIndex = getModuleFileIndexForTypeID(ID);
7682 assert(ModuleFileIndex && "Untranslated Local Decl?");
7683
7684 ModuleFile *OwningModuleFile = &getModuleManager()[ModuleFileIndex - 1];
7685 assert(OwningModuleFile &&
7686 "untranslated type ID or local type ID shouldn't be in TypesLoaded");
7687
7688 return {OwningModuleFile,
7689 OwningModuleFile->BaseTypeIndex + getIndexForTypeID(ID)};
7690}
7691
7693 assert(ContextObj && "reading type with no AST context");
7694 ASTContext &Context = *ContextObj;
7695
7696 unsigned FastQuals = ID & Qualifiers::FastMask;
7697
7698 if (isPredefinedType(ID)) {
7699 QualType T;
7700 unsigned Index = getIndexForTypeID(ID);
7701 switch ((PredefinedTypeIDs)Index) {
7703 // We should never use this one.
7704 llvm_unreachable("Invalid predefined type");
7705 break;
7707 return QualType();
7709 T = Context.VoidTy;
7710 break;
7712 T = Context.BoolTy;
7713 break;
7716 // FIXME: Check that the signedness of CharTy is correct!
7717 T = Context.CharTy;
7718 break;
7720 T = Context.UnsignedCharTy;
7721 break;
7723 T = Context.UnsignedShortTy;
7724 break;
7726 T = Context.UnsignedIntTy;
7727 break;
7729 T = Context.UnsignedLongTy;
7730 break;
7732 T = Context.UnsignedLongLongTy;
7733 break;
7735 T = Context.UnsignedInt128Ty;
7736 break;
7738 T = Context.SignedCharTy;
7739 break;
7741 T = Context.WCharTy;
7742 break;
7744 T = Context.ShortTy;
7745 break;
7746 case PREDEF_TYPE_INT_ID:
7747 T = Context.IntTy;
7748 break;
7750 T = Context.LongTy;
7751 break;
7753 T = Context.LongLongTy;
7754 break;
7756 T = Context.Int128Ty;
7757 break;
7759 T = Context.BFloat16Ty;
7760 break;
7762 T = Context.HalfTy;
7763 break;
7765 T = Context.FloatTy;
7766 break;
7768 T = Context.DoubleTy;
7769 break;
7771 T = Context.LongDoubleTy;
7772 break;
7774 T = Context.ShortAccumTy;
7775 break;
7777 T = Context.AccumTy;
7778 break;
7780 T = Context.LongAccumTy;
7781 break;
7783 T = Context.UnsignedShortAccumTy;
7784 break;
7786 T = Context.UnsignedAccumTy;
7787 break;
7789 T = Context.UnsignedLongAccumTy;
7790 break;
7792 T = Context.ShortFractTy;
7793 break;
7795 T = Context.FractTy;
7796 break;
7798 T = Context.LongFractTy;
7799 break;
7801 T = Context.UnsignedShortFractTy;
7802 break;
7804 T = Context.UnsignedFractTy;
7805 break;
7807 T = Context.UnsignedLongFractTy;
7808 break;
7810 T = Context.SatShortAccumTy;
7811 break;
7813 T = Context.SatAccumTy;
7814 break;
7816 T = Context.SatLongAccumTy;
7817 break;
7819 T = Context.SatUnsignedShortAccumTy;
7820 break;
7822 T = Context.SatUnsignedAccumTy;
7823 break;
7825 T = Context.SatUnsignedLongAccumTy;
7826 break;
7828 T = Context.SatShortFractTy;
7829 break;
7831 T = Context.SatFractTy;
7832 break;
7834 T = Context.SatLongFractTy;
7835 break;
7837 T = Context.SatUnsignedShortFractTy;
7838 break;
7840 T = Context.SatUnsignedFractTy;
7841 break;
7843 T = Context.SatUnsignedLongFractTy;
7844 break;
7846 T = Context.Float16Ty;
7847 break;
7849 T = Context.Float128Ty;
7850 break;
7852 T = Context.Ibm128Ty;
7853 break;
7855 T = Context.OverloadTy;
7856 break;
7858 T = Context.UnresolvedTemplateTy;
7859 break;
7861 T = Context.BoundMemberTy;
7862 break;
7864 T = Context.PseudoObjectTy;
7865 break;
7867 T = Context.DependentTy;
7868 break;
7870 T = Context.UnknownAnyTy;
7871 break;
7873 T = Context.NullPtrTy;
7874 break;
7876 T = Context.Char8Ty;
7877 break;
7879 T = Context.Char16Ty;
7880 break;
7882 T = Context.Char32Ty;
7883 break;
7885 T = Context.ObjCBuiltinIdTy;
7886 break;
7888 T = Context.ObjCBuiltinClassTy;
7889 break;
7891 T = Context.ObjCBuiltinSelTy;
7892 break;
7893#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7894 case PREDEF_TYPE_##Id##_ID: \
7895 T = Context.SingletonId; \
7896 break;
7897#include "clang/Basic/OpenCLImageTypes.def"
7898#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
7899 case PREDEF_TYPE_##Id##_ID: \
7900 T = Context.Id##Ty; \
7901 break;
7902#include "clang/Basic/OpenCLExtensionTypes.def"
7904 T = Context.OCLSamplerTy;
7905 break;
7907 T = Context.OCLEventTy;
7908 break;
7910 T = Context.OCLClkEventTy;
7911 break;
7913 T = Context.OCLQueueTy;
7914 break;
7916 T = Context.OCLReserveIDTy;
7917 break;
7919 T = Context.getAutoDeductType();
7920 break;
7922 T = Context.getAutoRRefDeductType();
7923 break;
7925 T = Context.ARCUnbridgedCastTy;
7926 break;
7928 T = Context.BuiltinFnTy;
7929 break;
7931 T = Context.IncompleteMatrixIdxTy;
7932 break;
7934 T = Context.ArraySectionTy;
7935 break;
7937 T = Context.OMPArrayShapingTy;
7938 break;
7940 T = Context.OMPIteratorTy;
7941 break;
7942#define SVE_TYPE(Name, Id, SingletonId) \
7943 case PREDEF_TYPE_##Id##_ID: \
7944 T = Context.SingletonId; \
7945 break;
7946#include "clang/Basic/AArch64ACLETypes.def"
7947#define PPC_VECTOR_TYPE(Name, Id, Size) \
7948 case PREDEF_TYPE_##Id##_ID: \
7949 T = Context.Id##Ty; \
7950 break;
7951#include "clang/Basic/PPCTypes.def"
7952#define RVV_TYPE(Name, Id, SingletonId) \
7953 case PREDEF_TYPE_##Id##_ID: \
7954 T = Context.SingletonId; \
7955 break;
7956#include "clang/Basic/RISCVVTypes.def"
7957#define WASM_TYPE(Name, Id, SingletonId) \
7958 case PREDEF_TYPE_##Id##_ID: \
7959 T = Context.SingletonId; \
7960 break;
7961#include "clang/Basic/WebAssemblyReferenceTypes.def"
7962#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) \
7963 case PREDEF_TYPE_##Id##_ID: \
7964 T = Context.SingletonId; \
7965 break;
7966#include "clang/Basic/AMDGPUTypes.def"
7967#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
7968 case PREDEF_TYPE_##Id##_ID: \
7969 T = Context.SingletonId; \
7970 break;
7971#include "clang/Basic/HLSLIntangibleTypes.def"
7972 }
7973
7974 assert(!T.isNull() && "Unknown predefined type");
7975 return T.withFastQualifiers(FastQuals);
7976 }
7977
7978 unsigned Index = translateTypeIDToIndex(ID).second;
7979
7980 assert(Index < TypesLoaded.size() && "Type index out-of-range");
7981 if (TypesLoaded[Index].isNull()) {
7982 TypesLoaded[Index] = readTypeRecord(ID);
7983 if (TypesLoaded[Index].isNull())
7984 return QualType();
7985
7986 TypesLoaded[Index]->setFromAST();
7987 if (DeserializationListener)
7988 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
7989 TypesLoaded[Index]);
7990 }
7991
7992 return TypesLoaded[Index].withFastQualifiers(FastQuals);
7993}
7994
7996 return GetType(getGlobalTypeID(F, LocalID));
7997}
7998
8000 LocalTypeID LocalID) const {
8001 if (isPredefinedType(LocalID))
8002 return LocalID;
8003
8004 if (!F.ModuleOffsetMap.empty())
8005 ReadModuleOffsetMap(F);
8006
8007 unsigned ModuleFileIndex = getModuleFileIndexForTypeID(LocalID);
8008 LocalID &= llvm::maskTrailingOnes<TypeID>(32);
8009
8010 if (ModuleFileIndex == 0)
8012
8013 ModuleFile &MF =
8014 ModuleFileIndex ? *F.TransitiveImports[ModuleFileIndex - 1] : F;
8015 ModuleFileIndex = MF.Index + 1;
8016 return ((uint64_t)ModuleFileIndex << 32) | LocalID;
8017}
8018
8021 switch (Kind) {
8023 return readExpr();
8025 return readTypeSourceInfo();
8028 SourceLocation TemplateKWLoc = readSourceLocation();
8030 SourceLocation TemplateNameLoc = readSourceLocation();
8033 : SourceLocation();
8034 return TemplateArgumentLocInfo(getASTContext(), TemplateKWLoc, QualifierLoc,
8035 TemplateNameLoc, EllipsisLoc);
8036 }
8043 // FIXME: Is this right?
8044 return TemplateArgumentLocInfo();
8045 }
8046 llvm_unreachable("unexpected template argument loc");
8047}
8048
8058
8061 Result.setLAngleLoc(readSourceLocation());
8062 Result.setRAngleLoc(readSourceLocation());
8063 unsigned NumArgsAsWritten = readInt();
8064 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
8065 Result.addArgument(readTemplateArgumentLoc());
8066}
8067
8074
8076
8078 if (NumCurrentElementsDeserializing) {
8079 // We arrange to not care about the complete redeclaration chain while we're
8080 // deserializing. Just remember that the AST has marked this one as complete
8081 // but that it's not actually complete yet, so we know we still need to
8082 // complete it later.
8083 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
8084 return;
8085 }
8086
8087 if (!D->getDeclContext()) {
8088 assert(isa<TranslationUnitDecl>(D) && "Not a TU?");
8089 return;
8090 }
8091
8092 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
8093
8094 // If this is a named declaration, complete it by looking it up
8095 // within its context.
8096 //
8097 // FIXME: Merging a function definition should merge
8098 // all mergeable entities within it.
8100 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
8101 if (!getContext().getLangOpts().CPlusPlus &&
8103 // Outside of C++, we don't have a lookup table for the TU, so update
8104 // the identifier instead. (For C++ modules, we don't store decls
8105 // in the serialized identifier table, so we do the lookup in the TU.)
8106 auto *II = Name.getAsIdentifierInfo();
8107 assert(II && "non-identifier name in C?");
8108 if (II->isOutOfDate())
8110 } else
8111 DC->lookup(Name);
8113 // Find all declarations of this kind from the relevant context.
8114 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
8115 auto *DC = cast<DeclContext>(DCDecl);
8118 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
8119 }
8120 }
8121 }
8122
8125 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
8126 Template = CTSD->getSpecializedTemplate();
8127 Args = CTSD->getTemplateArgs().asArray();
8128 } else if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D)) {
8129 Template = VTSD->getSpecializedTemplate();
8130 Args = VTSD->getTemplateArgs().asArray();
8131 } else if (auto *FD = dyn_cast<FunctionDecl>(D)) {
8132 if (auto *Tmplt = FD->getPrimaryTemplate()) {
8133 Template = Tmplt;
8134 Args = FD->getTemplateSpecializationArgs()->asArray();
8135 }
8136 }
8137
8138 if (Template) {
8139 // For partitial specialization, load all the specializations for safety.
8142 Template->loadLazySpecializationsImpl();
8143 else
8144 Template->loadLazySpecializationsImpl(Args);
8145 }
8146}
8147
8150 RecordLocation Loc = getLocalBitOffset(Offset);
8151 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
8152 SavedStreamPosition SavedPosition(Cursor);
8153 if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {
8154 Error(std::move(Err));
8155 return nullptr;
8156 }
8157 ReadingKindTracker ReadingKind(Read_Decl, *this);
8158 Deserializing D(this);
8159
8160 Expected<unsigned> MaybeCode = Cursor.ReadCode();
8161 if (!MaybeCode) {
8162 Error(MaybeCode.takeError());
8163 return nullptr;
8164 }
8165 unsigned Code = MaybeCode.get();
8166
8167 ASTRecordReader Record(*this, *Loc.F);
8168 Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code);
8169 if (!MaybeRecCode) {
8170 Error(MaybeRecCode.takeError());
8171 return nullptr;
8172 }
8173 if (MaybeRecCode.get() != DECL_CXX_CTOR_INITIALIZERS) {
8174 Error("malformed AST file: missing C++ ctor initializers");
8175 return nullptr;
8176 }
8177
8178 return Record.readCXXCtorInitializers();
8179}
8180
8182 assert(ContextObj && "reading base specifiers with no AST context");
8183 ASTContext &Context = *ContextObj;
8184
8185 RecordLocation Loc = getLocalBitOffset(Offset);
8186 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
8187 SavedStreamPosition SavedPosition(Cursor);
8188 if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {
8189 Error(std::move(Err));
8190 return nullptr;
8191 }
8192 ReadingKindTracker ReadingKind(Read_Decl, *this);
8193 Deserializing D(this);
8194
8195 Expected<unsigned> MaybeCode = Cursor.ReadCode();
8196 if (!MaybeCode) {
8197 Error(MaybeCode.takeError());
8198 return nullptr;
8199 }
8200 unsigned Code = MaybeCode.get();
8201
8202 ASTRecordReader Record(*this, *Loc.F);
8203 Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code);
8204 if (!MaybeRecCode) {
8205 Error(MaybeCode.takeError());
8206 return nullptr;
8207 }
8208 unsigned RecCode = MaybeRecCode.get();
8209
8210 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
8211 Error("malformed AST file: missing C++ base specifiers");
8212 return nullptr;
8213 }
8214
8215 unsigned NumBases = Record.readInt();
8216 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
8217 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
8218 for (unsigned I = 0; I != NumBases; ++I)
8219 Bases[I] = Record.readCXXBaseSpecifier();
8220 return Bases;
8221}
8222
8224 LocalDeclID LocalID) const {
8225 if (LocalID < NUM_PREDEF_DECL_IDS)
8226 return GlobalDeclID(LocalID.getRawValue());
8227
8228 unsigned OwningModuleFileIndex = LocalID.getModuleFileIndex();
8229 DeclID ID = LocalID.getLocalDeclIndex();
8230
8231 if (!F.ModuleOffsetMap.empty())
8232 ReadModuleOffsetMap(F);
8233
8234 ModuleFile *OwningModuleFile =
8235 OwningModuleFileIndex == 0
8236 ? &F
8237 : F.TransitiveImports[OwningModuleFileIndex - 1];
8238
8239 if (OwningModuleFileIndex == 0)
8240 ID -= NUM_PREDEF_DECL_IDS;
8241
8242 uint64_t NewModuleFileIndex = OwningModuleFile->Index + 1;
8243 return GlobalDeclID(NewModuleFileIndex, ID);
8244}
8245
8247 // Predefined decls aren't from any module.
8248 if (ID < NUM_PREDEF_DECL_IDS)
8249 return false;
8250
8251 unsigned ModuleFileIndex = ID.getModuleFileIndex();
8252 return M.Index == ModuleFileIndex - 1;
8253}
8254
8256 // Predefined decls aren't from any module.
8257 if (ID < NUM_PREDEF_DECL_IDS)
8258 return nullptr;
8259
8260 uint64_t ModuleFileIndex = ID.getModuleFileIndex();
8261 assert(ModuleFileIndex && "Untranslated Local Decl?");
8262
8263 return &getModuleManager()[ModuleFileIndex - 1];
8264}
8265
8267 if (!D->isFromASTFile())
8268 return nullptr;
8269
8270 return getOwningModuleFile(D->getGlobalID());
8271}
8272
8274 if (ID < NUM_PREDEF_DECL_IDS)
8275 return SourceLocation();
8276
8277 if (Decl *D = GetExistingDecl(ID))
8278 return D->getLocation();
8279
8280 SourceLocation Loc;
8281 DeclCursorForID(ID, Loc);
8282 return Loc;
8283}
8284
8285Decl *ASTReader::getPredefinedDecl(PredefinedDeclIDs ID) {
8286 assert(ContextObj && "reading predefined decl without AST context");
8287 ASTContext &Context = *ContextObj;
8288 Decl *NewLoaded = nullptr;
8289 switch (ID) {
8291 return nullptr;
8292
8294 return Context.getTranslationUnitDecl();
8295
8297 if (Context.ObjCIdDecl)
8298 return Context.ObjCIdDecl;
8299 NewLoaded = Context.getObjCIdDecl();
8300 break;
8301
8303 if (Context.ObjCSelDecl)
8304 return Context.ObjCSelDecl;
8305 NewLoaded = Context.getObjCSelDecl();
8306 break;
8307
8309 if (Context.ObjCClassDecl)
8310 return Context.ObjCClassDecl;
8311 NewLoaded = Context.getObjCClassDecl();
8312 break;
8313
8315 if (Context.ObjCProtocolClassDecl)
8316 return Context.ObjCProtocolClassDecl;
8317 NewLoaded = Context.getObjCProtocolDecl();
8318 break;
8319
8321 if (Context.Int128Decl)
8322 return Context.Int128Decl;
8323 NewLoaded = Context.getInt128Decl();
8324 break;
8325
8327 if (Context.UInt128Decl)
8328 return Context.UInt128Decl;
8329 NewLoaded = Context.getUInt128Decl();
8330 break;
8331
8333 if (Context.ObjCInstanceTypeDecl)
8334 return Context.ObjCInstanceTypeDecl;
8335 NewLoaded = Context.getObjCInstanceTypeDecl();
8336 break;
8337
8339 if (Context.BuiltinVaListDecl)
8340 return Context.BuiltinVaListDecl;
8341 NewLoaded = Context.getBuiltinVaListDecl();
8342 break;
8343
8345 if (Context.VaListTagDecl)
8346 return Context.VaListTagDecl;
8347 NewLoaded = Context.getVaListTagDecl();
8348 break;
8349
8351 if (Context.BuiltinMSVaListDecl)
8352 return Context.BuiltinMSVaListDecl;
8353 NewLoaded = Context.getBuiltinMSVaListDecl();
8354 break;
8355
8357 // ASTContext::getMSGuidTagDecl won't create MSGuidTagDecl conditionally.
8358 return Context.getMSGuidTagDecl();
8359
8361 if (Context.ExternCContext)
8362 return Context.ExternCContext;
8363 NewLoaded = Context.getExternCContextDecl();
8364 break;
8365
8367 if (Context.CFConstantStringTypeDecl)
8368 return Context.CFConstantStringTypeDecl;
8369 NewLoaded = Context.getCFConstantStringDecl();
8370 break;
8371
8373 if (Context.CFConstantStringTagDecl)
8374 return Context.CFConstantStringTagDecl;
8375 NewLoaded = Context.getCFConstantStringTagDecl();
8376 break;
8377
8379 return Context.getMSTypeInfoTagDecl();
8380
8381#define BuiltinTemplate(BTName) \
8382 case PREDEF_DECL##BTName##_ID: \
8383 if (Context.Decl##BTName) \
8384 return Context.Decl##BTName; \
8385 NewLoaded = Context.get##BTName##Decl(); \
8386 break;
8387#include "clang/Basic/BuiltinTemplates.inc"
8388
8390 llvm_unreachable("Invalid decl ID");
8391 break;
8392 }
8393
8394 assert(NewLoaded && "Failed to load predefined decl?");
8395
8396 if (DeserializationListener)
8397 DeserializationListener->PredefinedDeclBuilt(ID, NewLoaded);
8398
8399 return NewLoaded;
8400}
8401
8402unsigned ASTReader::translateGlobalDeclIDToIndex(GlobalDeclID GlobalID) const {
8403 ModuleFile *OwningModuleFile = getOwningModuleFile(GlobalID);
8404 if (!OwningModuleFile) {
8405 assert(GlobalID < NUM_PREDEF_DECL_IDS && "Untransalted Global ID?");
8406 return GlobalID.getRawValue();
8407 }
8408
8409 return OwningModuleFile->BaseDeclIndex + GlobalID.getLocalDeclIndex();
8410}
8411
8413 assert(ContextObj && "reading decl with no AST context");
8414
8415 if (ID < NUM_PREDEF_DECL_IDS) {
8416 Decl *D = getPredefinedDecl((PredefinedDeclIDs)ID);
8417 if (D) {
8418 // Track that we have merged the declaration with ID \p ID into the
8419 // pre-existing predefined declaration \p D.
8420 auto &Merged = KeyDecls[D->getCanonicalDecl()];
8421 if (Merged.empty())
8422 Merged.push_back(ID);
8423 }
8424 return D;
8425 }
8426
8427 unsigned Index = translateGlobalDeclIDToIndex(ID);
8428
8429 if (Index >= DeclsLoaded.size()) {
8430 assert(0 && "declaration ID out-of-range for AST file");
8431 Error("declaration ID out-of-range for AST file");
8432 return nullptr;
8433 }
8434
8435 return DeclsLoaded[Index];
8436}
8437
8439 if (ID < NUM_PREDEF_DECL_IDS)
8440 return GetExistingDecl(ID);
8441
8442 unsigned Index = translateGlobalDeclIDToIndex(ID);
8443
8444 if (Index >= DeclsLoaded.size()) {
8445 assert(0 && "declaration ID out-of-range for AST file");
8446 Error("declaration ID out-of-range for AST file");
8447 return nullptr;
8448 }
8449
8450 if (!DeclsLoaded[Index]) {
8451 ReadDeclRecord(ID);
8452 if (DeserializationListener)
8453 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
8454 }
8455
8456 return DeclsLoaded[Index];
8457}
8458
8460 GlobalDeclID GlobalID) {
8461 if (GlobalID < NUM_PREDEF_DECL_IDS)
8462 return LocalDeclID::get(*this, M, GlobalID.getRawValue());
8463
8464 if (!M.ModuleOffsetMap.empty())
8465 ReadModuleOffsetMap(M);
8466
8467 ModuleFile *Owner = getOwningModuleFile(GlobalID);
8468 DeclID ID = GlobalID.getLocalDeclIndex();
8469
8470 if (Owner == &M) {
8471 ID += NUM_PREDEF_DECL_IDS;
8472 return LocalDeclID::get(*this, M, ID);
8473 }
8474
8475 uint64_t OrignalModuleFileIndex = 0;
8476 for (unsigned I = 0; I < M.TransitiveImports.size(); I++)
8477 if (M.TransitiveImports[I] == Owner) {
8478 OrignalModuleFileIndex = I + 1;
8479 break;
8480 }
8481
8482 if (!OrignalModuleFileIndex)
8483 return LocalDeclID();
8484
8485 return LocalDeclID::get(*this, M, OrignalModuleFileIndex, ID);
8486}
8487
8489 unsigned &Idx) {
8490 if (Idx >= Record.size()) {
8491 Error("Corrupted AST file");
8492 return GlobalDeclID(0);
8493 }
8494
8495 return getGlobalDeclID(F, LocalDeclID::get(*this, F, Record[Idx++]));
8496}
8497
8498/// Resolve the offset of a statement into a statement.
8499///
8500/// This operation will read a new statement from the external
8501/// source each time it is called, and is meant to be used via a
8502/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
8504 // Switch case IDs are per Decl.
8506
8507 // Offset here is a global offset across the entire chain.
8508 RecordLocation Loc = getLocalBitOffset(Offset);
8509 if (llvm::Error Err = Loc.F->DeclsCursor.JumpToBit(Loc.Offset)) {
8510 Error(std::move(Err));
8511 return nullptr;
8512 }
8513 assert(NumCurrentElementsDeserializing == 0 &&
8514 "should not be called while already deserializing");
8515 Deserializing D(this);
8516 return ReadStmtFromStream(*Loc.F);
8517}
8518
8519bool ASTReader::LoadExternalSpecializationsImpl(SpecLookupTableTy &SpecLookups,
8520 const Decl *D) {
8521 assert(D);
8522
8523 auto It = SpecLookups.find(D);
8524 if (It == SpecLookups.end())
8525 return false;
8526
8527 // Get Decl may violate the iterator from SpecializationsLookups so we store
8528 // the DeclIDs in ahead.
8530 It->second.Table.findAll();
8531
8532 // Since we've loaded all the specializations, we can erase it from
8533 // the lookup table.
8534 SpecLookups.erase(It);
8535
8536 bool NewSpecsFound = false;
8537 Deserializing LookupResults(this);
8538 for (auto &Info : Infos) {
8539 if (GetExistingDecl(Info))
8540 continue;
8541 NewSpecsFound = true;
8542 GetDecl(Info);
8543 }
8544
8545 return NewSpecsFound;
8546}
8547
8548bool ASTReader::LoadExternalSpecializations(const Decl *D, bool OnlyPartial) {
8549 assert(D);
8550
8552 bool NewSpecsFound =
8553 LoadExternalSpecializationsImpl(PartialSpecializationsLookups, D);
8554 if (OnlyPartial)
8555 return NewSpecsFound;
8556
8557 NewSpecsFound |= LoadExternalSpecializationsImpl(SpecializationsLookups, D);
8558 return NewSpecsFound;
8559}
8560
8561bool ASTReader::LoadExternalSpecializationsImpl(
8562 SpecLookupTableTy &SpecLookups, const Decl *D,
8563 ArrayRef<TemplateArgument> TemplateArgs) {
8564 assert(D);
8565
8566 auto It = SpecLookups.find(D);
8567 if (It == SpecLookups.end())
8568 return false;
8569
8570 llvm::TimeTraceScope TimeScope("Load External Specializations for ", [&] {
8571 std::string Name;
8572 llvm::raw_string_ostream OS(Name);
8573 auto *ND = cast<NamedDecl>(D);
8575 /*Qualified=*/true);
8576 return Name;
8577 });
8578
8579 Deserializing LookupResults(this);
8580 auto HashValue = StableHashForTemplateArguments(TemplateArgs);
8581
8582 // Get Decl may violate the iterator from SpecLookups
8584 It->second.Table.find(HashValue);
8585
8586 bool NewSpecsFound = false;
8587 for (auto &Info : Infos) {
8588 if (GetExistingDecl(Info))
8589 continue;
8590 NewSpecsFound = true;
8591 GetDecl(Info);
8592 }
8593
8594 return NewSpecsFound;
8595}
8596
8598 const Decl *D, ArrayRef<TemplateArgument> TemplateArgs) {
8599 assert(D);
8600
8601 bool NewDeclsFound = LoadExternalSpecializationsImpl(
8602 PartialSpecializationsLookups, D, TemplateArgs);
8603 NewDeclsFound |=
8604 LoadExternalSpecializationsImpl(SpecializationsLookups, D, TemplateArgs);
8605
8606 return NewDeclsFound;
8607}
8608
8610 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
8611 SmallVectorImpl<Decl *> &Decls) {
8612 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
8613
8614 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
8615 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
8616 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
8617 auto K = (Decl::Kind)+LexicalDecls[I];
8618 if (!IsKindWeWant(K))
8619 continue;
8620
8621 auto ID = (DeclID) + LexicalDecls[I + 1];
8622
8623 // Don't add predefined declarations to the lexical context more
8624 // than once.
8625 if (ID < NUM_PREDEF_DECL_IDS) {
8626 if (PredefsVisited[ID])
8627 continue;
8628
8629 PredefsVisited[ID] = true;
8630 }
8631
8632 if (Decl *D = GetLocalDecl(*M, LocalDeclID::get(*this, *M, ID))) {
8633 assert(D->getKind() == K && "wrong kind for lexical decl");
8634 if (!DC->isDeclInLexicalTraversal(D))
8635 Decls.push_back(D);
8636 }
8637 }
8638 };
8639
8640 if (isa<TranslationUnitDecl>(DC)) {
8641 for (const auto &Lexical : TULexicalDecls)
8642 Visit(Lexical.first, Lexical.second);
8643 } else {
8644 auto I = LexicalDecls.find(DC);
8645 if (I != LexicalDecls.end())
8646 Visit(I->second.first, I->second.second);
8647 }
8648
8649 ++NumLexicalDeclContextsRead;
8650}
8651
8652namespace {
8653
8654class UnalignedDeclIDComp {
8655 ASTReader &Reader;
8656 ModuleFile &Mod;
8657
8658public:
8659 UnalignedDeclIDComp(ASTReader &Reader, ModuleFile &M)
8660 : Reader(Reader), Mod(M) {}
8661
8662 bool operator()(unaligned_decl_id_t L, unaligned_decl_id_t R) const {
8663 SourceLocation LHS = getLocation(L);
8664 SourceLocation RHS = getLocation(R);
8665 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
8666 }
8667
8668 bool operator()(SourceLocation LHS, unaligned_decl_id_t R) const {
8669 SourceLocation RHS = getLocation(R);
8670 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
8671 }
8672
8673 bool operator()(unaligned_decl_id_t L, SourceLocation RHS) const {
8674 SourceLocation LHS = getLocation(L);
8675 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
8676 }
8677
8678 SourceLocation getLocation(unaligned_decl_id_t ID) const {
8679 return Reader.getSourceManager().getFileLoc(
8681 Reader.getGlobalDeclID(Mod, LocalDeclID::get(Reader, Mod, ID))));
8682 }
8683};
8684
8685} // namespace
8686
8688 unsigned Offset, unsigned Length,
8689 SmallVectorImpl<Decl *> &Decls) {
8691
8692 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
8693 if (I == FileDeclIDs.end())
8694 return;
8695
8696 FileDeclsInfo &DInfo = I->second;
8697 if (DInfo.Decls.empty())
8698 return;
8699
8701 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
8702 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
8703
8704 UnalignedDeclIDComp DIDComp(*this, *DInfo.Mod);
8706 llvm::lower_bound(DInfo.Decls, BeginLoc, DIDComp);
8707 if (BeginIt != DInfo.Decls.begin())
8708 --BeginIt;
8709
8710 // If we are pointing at a top-level decl inside an objc container, we need
8711 // to backtrack until we find it otherwise we will fail to report that the
8712 // region overlaps with an objc container.
8713 while (BeginIt != DInfo.Decls.begin() &&
8714 GetDecl(getGlobalDeclID(*DInfo.Mod,
8715 LocalDeclID::get(*this, *DInfo.Mod, *BeginIt)))
8716 ->isTopLevelDeclInObjCContainer())
8717 --BeginIt;
8718
8720 llvm::upper_bound(DInfo.Decls, EndLoc, DIDComp);
8721 if (EndIt != DInfo.Decls.end())
8722 ++EndIt;
8723
8724 for (ArrayRef<unaligned_decl_id_t>::iterator DIt = BeginIt; DIt != EndIt;
8725 ++DIt)
8726 Decls.push_back(GetDecl(getGlobalDeclID(
8727 *DInfo.Mod, LocalDeclID::get(*this, *DInfo.Mod, *DIt))));
8728}
8729
8731 DeclarationName Name,
8732 const DeclContext *OriginalDC) {
8733 assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
8734 "DeclContext has no visible decls in storage");
8735 if (!Name)
8736 return false;
8737
8738 // Load the list of declarations.
8739 DeclsSet DS;
8740
8741 auto Find = [&, this](auto &&Table, auto &&Key) {
8742 for (GlobalDeclID ID : Table.find(Key)) {
8744 if (ND->getDeclName() != Name)
8745 continue;
8746 // Special case for namespaces: There can be a lot of redeclarations of
8747 // some namespaces, and we import a "key declaration" per imported module.
8748 // Since all declarations of a namespace are essentially interchangeable,
8749 // we can optimize namespace look-up by only storing the key declaration
8750 // of the current TU, rather than storing N key declarations where N is
8751 // the # of imported modules that declare that namespace.
8752 // TODO: Try to generalize this optimization to other redeclarable decls.
8753 if (isa<NamespaceDecl>(ND))
8755 DS.insert(ND);
8756 }
8757 };
8758
8759 Deserializing LookupResults(this);
8760
8761 // FIXME: Clear the redundancy with templated lambda in C++20 when that's
8762 // available.
8763 if (auto It = Lookups.find(DC); It != Lookups.end()) {
8764 ++NumVisibleDeclContextsRead;
8765 Find(It->second.Table, Name);
8766 }
8767
8768 auto FindModuleLocalLookup = [&, this](Module *NamedModule) {
8769 if (auto It = ModuleLocalLookups.find(DC); It != ModuleLocalLookups.end()) {
8770 ++NumModuleLocalVisibleDeclContexts;
8771 Find(It->second.Table, std::make_pair(Name, NamedModule));
8772 }
8773 };
8774 if (auto *NamedModule =
8775 OriginalDC ? cast<Decl>(OriginalDC)->getTopLevelOwningNamedModule()
8776 : nullptr)
8777 FindModuleLocalLookup(NamedModule);
8778 // See clang/test/Modules/ModulesLocalNamespace.cppm for the motiviation case.
8779 // We're going to find a decl but the decl context of the lookup is
8780 // unspecified. In this case, the OriginalDC may be the decl context in other
8781 // module.
8782 if (ContextObj && ContextObj->getCurrentNamedModule())
8783 FindModuleLocalLookup(ContextObj->getCurrentNamedModule());
8784
8785 if (auto It = TULocalLookups.find(DC); It != TULocalLookups.end()) {
8786 ++NumTULocalVisibleDeclContexts;
8787 Find(It->second.Table, Name);
8788 }
8789
8790 SetExternalVisibleDeclsForName(DC, Name, DS);
8791 return !DS.empty();
8792}
8793
8795 if (!DC->hasExternalVisibleStorage())
8796 return;
8797
8798 DeclsMap Decls;
8799
8800 auto findAll = [&](auto &LookupTables, unsigned &NumRead) {
8801 auto It = LookupTables.find(DC);
8802 if (It == LookupTables.end())
8803 return;
8804
8805 NumRead++;
8806
8807 for (GlobalDeclID ID : It->second.Table.findAll()) {
8809 // Special case for namespaces: There can be a lot of redeclarations of
8810 // some namespaces, and we import a "key declaration" per imported module.
8811 // Since all declarations of a namespace are essentially interchangeable,
8812 // we can optimize namespace look-up by only storing the key declaration
8813 // of the current TU, rather than storing N key declarations where N is
8814 // the # of imported modules that declare that namespace.
8815 // TODO: Try to generalize this optimization to other redeclarable decls.
8816 if (isa<NamespaceDecl>(ND))
8818 Decls[ND->getDeclName()].insert(ND);
8819 }
8820
8821 // FIXME: Why a PCH test is failing if we remove the iterator after findAll?
8822 };
8823
8824 findAll(Lookups, NumVisibleDeclContextsRead);
8825 findAll(ModuleLocalLookups, NumModuleLocalVisibleDeclContexts);
8826 findAll(TULocalLookups, NumTULocalVisibleDeclContexts);
8827
8828 for (auto &[Name, DS] : Decls)
8829 SetExternalVisibleDeclsForName(DC, Name, DS);
8830
8831 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
8832}
8833
8836 auto I = Lookups.find(Primary);
8837 return I == Lookups.end() ? nullptr : &I->second;
8838}
8839
8842 auto I = ModuleLocalLookups.find(Primary);
8843 return I == ModuleLocalLookups.end() ? nullptr : &I->second;
8844}
8845
8848 auto I = TULocalLookups.find(Primary);
8849 return I == TULocalLookups.end() ? nullptr : &I->second;
8850}
8851
8854 assert(D->isCanonicalDecl());
8855 auto &LookupTable =
8856 IsPartial ? PartialSpecializationsLookups : SpecializationsLookups;
8857 auto I = LookupTable.find(D);
8858 return I == LookupTable.end() ? nullptr : &I->second;
8859}
8860
8862 assert(D->isCanonicalDecl());
8863 return PartialSpecializationsLookups.contains(D) ||
8864 SpecializationsLookups.contains(D);
8865}
8866
8867/// Under non-PCH compilation the consumer receives the objc methods
8868/// before receiving the implementation, and codegen depends on this.
8869/// We simulate this by deserializing and passing to consumer the methods of the
8870/// implementation before passing the deserialized implementation decl.
8872 ASTConsumer *Consumer) {
8873 assert(ImplD && Consumer);
8874
8875 for (auto *I : ImplD->methods())
8876 Consumer->HandleInterestingDecl(DeclGroupRef(I));
8877
8878 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
8879}
8880
8881void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
8882 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
8883 PassObjCImplDeclToConsumer(ImplD, Consumer);
8884 else
8885 Consumer->HandleInterestingDecl(DeclGroupRef(D));
8886}
8887
8888void ASTReader::PassVTableToConsumer(CXXRecordDecl *RD) {
8889 Consumer->HandleVTable(RD);
8890}
8891
8893 this->Consumer = Consumer;
8894
8895 if (Consumer)
8896 PassInterestingDeclsToConsumer();
8897
8898 if (DeserializationListener)
8899 DeserializationListener->ReaderInitialized(this);
8900}
8901
8903 std::fprintf(stderr, "*** AST File Statistics:\n");
8904
8905 unsigned NumTypesLoaded =
8906 TypesLoaded.size() - llvm::count(TypesLoaded.materialized(), QualType());
8907 unsigned NumDeclsLoaded =
8908 DeclsLoaded.size() -
8909 llvm::count(DeclsLoaded.materialized(), (Decl *)nullptr);
8910 unsigned NumIdentifiersLoaded =
8911 IdentifiersLoaded.size() -
8912 llvm::count(IdentifiersLoaded, (IdentifierInfo *)nullptr);
8913 unsigned NumMacrosLoaded =
8914 MacrosLoaded.size() - llvm::count(MacrosLoaded, (MacroInfo *)nullptr);
8915 unsigned NumSelectorsLoaded =
8916 SelectorsLoaded.size() - llvm::count(SelectorsLoaded, Selector());
8917
8918 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
8919 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
8920 NumSLocEntriesRead, TotalNumSLocEntries,
8921 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
8922 if (!TypesLoaded.empty())
8923 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
8924 NumTypesLoaded, (unsigned)TypesLoaded.size(),
8925 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
8926 if (!DeclsLoaded.empty())
8927 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
8928 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
8929 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
8930 if (!IdentifiersLoaded.empty())
8931 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
8932 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
8933 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
8934 if (!MacrosLoaded.empty())
8935 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
8936 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
8937 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
8938 if (!SelectorsLoaded.empty())
8939 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
8940 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
8941 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
8942 if (TotalNumStatements)
8943 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
8944 NumStatementsRead, TotalNumStatements,
8945 ((float)NumStatementsRead/TotalNumStatements * 100));
8946 if (TotalNumMacros)
8947 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
8948 NumMacrosRead, TotalNumMacros,
8949 ((float)NumMacrosRead/TotalNumMacros * 100));
8950 if (TotalLexicalDeclContexts)
8951 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
8952 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
8953 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
8954 * 100));
8955 if (TotalVisibleDeclContexts)
8956 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
8957 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
8958 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
8959 * 100));
8960 if (TotalModuleLocalVisibleDeclContexts)
8961 std::fprintf(
8962 stderr, " %u/%u module local visible declcontexts read (%f%%)\n",
8963 NumModuleLocalVisibleDeclContexts, TotalModuleLocalVisibleDeclContexts,
8964 ((float)NumModuleLocalVisibleDeclContexts /
8965 TotalModuleLocalVisibleDeclContexts * 100));
8966 if (TotalTULocalVisibleDeclContexts)
8967 std::fprintf(stderr, " %u/%u visible declcontexts in GMF read (%f%%)\n",
8968 NumTULocalVisibleDeclContexts, TotalTULocalVisibleDeclContexts,
8969 ((float)NumTULocalVisibleDeclContexts /
8970 TotalTULocalVisibleDeclContexts * 100));
8971 if (TotalNumMethodPoolEntries)
8972 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
8973 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
8974 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
8975 * 100));
8976 if (NumMethodPoolLookups)
8977 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
8978 NumMethodPoolHits, NumMethodPoolLookups,
8979 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
8980 if (NumMethodPoolTableLookups)
8981 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
8982 NumMethodPoolTableHits, NumMethodPoolTableLookups,
8983 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
8984 * 100.0));
8985 if (NumIdentifierLookupHits)
8986 std::fprintf(stderr,
8987 " %u / %u identifier table lookups succeeded (%f%%)\n",
8988 NumIdentifierLookupHits, NumIdentifierLookups,
8989 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
8990
8991 if (GlobalIndex) {
8992 std::fprintf(stderr, "\n");
8993 GlobalIndex->printStats();
8994 }
8995
8996 std::fprintf(stderr, "\n");
8997 dump();
8998 std::fprintf(stderr, "\n");
8999}
9000
9001template<typename Key, typename ModuleFile, unsigned InitialCapacity>
9002LLVM_DUMP_METHOD static void
9003dumpModuleIDMap(StringRef Name,
9004 const ContinuousRangeMap<Key, ModuleFile *,
9005 InitialCapacity> &Map) {
9006 if (Map.begin() == Map.end())
9007 return;
9008
9010
9011 llvm::errs() << Name << ":\n";
9012 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
9013 I != IEnd; ++I)
9014 llvm::errs() << " " << (DeclID)I->first << " -> " << I->second->FileName
9015 << "\n";
9016}
9017
9018LLVM_DUMP_METHOD void ASTReader::dump() {
9019 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
9020 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
9021 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
9022 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
9023 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
9024 dumpModuleIDMap("Global preprocessed entity map",
9025 GlobalPreprocessedEntityMap);
9026
9027 llvm::errs() << "\n*** PCH/Modules Loaded:";
9028 for (ModuleFile &M : ModuleMgr)
9029 M.dump();
9030}
9031
9032/// Return the amount of memory used by memory buffers, breaking down
9033/// by heap-backed versus mmap'ed memory.
9035 for (ModuleFile &I : ModuleMgr) {
9036 if (llvm::MemoryBuffer *buf = I.Buffer) {
9037 size_t bytes = buf->getBufferSize();
9038 switch (buf->getBufferKind()) {
9039 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
9040 sizes.malloc_bytes += bytes;
9041 break;
9042 case llvm::MemoryBuffer::MemoryBuffer_MMap:
9043 sizes.mmap_bytes += bytes;
9044 break;
9045 }
9046 }
9047 }
9048}
9049
9051 SemaObj = &S;
9052 S.addExternalSource(this);
9053
9054 // Makes sure any declarations that were deserialized "too early"
9055 // still get added to the identifier's declaration chains.
9056 for (GlobalDeclID ID : PreloadedDeclIDs) {
9058 pushExternalDeclIntoScope(D, D->getDeclName());
9059 }
9060 PreloadedDeclIDs.clear();
9061
9062 // FIXME: What happens if these are changed by a module import?
9063 if (!FPPragmaOptions.empty()) {
9064 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
9065 FPOptionsOverride NewOverrides =
9066 FPOptionsOverride::getFromOpaqueInt(FPPragmaOptions[0]);
9067 SemaObj->CurFPFeatures =
9068 NewOverrides.applyOverrides(SemaObj->getLangOpts());
9069 }
9070
9071 for (GlobalDeclID ID : DeclsWithEffectsToVerify) {
9072 Decl *D = GetDecl(ID);
9073 if (auto *FD = dyn_cast<FunctionDecl>(D))
9074 SemaObj->addDeclWithEffects(FD, FD->getFunctionEffects());
9075 else if (auto *BD = dyn_cast<BlockDecl>(D))
9076 SemaObj->addDeclWithEffects(BD, BD->getFunctionEffects());
9077 else
9078 llvm_unreachable("unexpected Decl type in DeclsWithEffectsToVerify");
9079 }
9080 DeclsWithEffectsToVerify.clear();
9081
9082 SemaObj->OpenCLFeatures = OpenCLExtensions;
9083
9084 UpdateSema();
9085}
9086
9088 assert(SemaObj && "no Sema to update");
9089
9090 // Load the offsets of the declarations that Sema references.
9091 // They will be lazily deserialized when needed.
9092 if (!SemaDeclRefs.empty()) {
9093 assert(SemaDeclRefs.size() % 3 == 0);
9094 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 3) {
9095 if (!SemaObj->StdNamespace)
9096 SemaObj->StdNamespace = SemaDeclRefs[I].getRawValue();
9097 if (!SemaObj->StdBadAlloc)
9098 SemaObj->StdBadAlloc = SemaDeclRefs[I + 1].getRawValue();
9099 if (!SemaObj->StdAlignValT)
9100 SemaObj->StdAlignValT = SemaDeclRefs[I + 2].getRawValue();
9101 }
9102 SemaDeclRefs.clear();
9103 }
9104
9105 // Update the state of pragmas. Use the same API as if we had encountered the
9106 // pragma in the source.
9107 if(OptimizeOffPragmaLocation.isValid())
9108 SemaObj->ActOnPragmaOptimize(/* On = */ false, OptimizeOffPragmaLocation);
9109 if (PragmaMSStructState != -1)
9110 SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState);
9111 if (PointersToMembersPragmaLocation.isValid()) {
9112 SemaObj->ActOnPragmaMSPointersToMembers(
9114 PragmaMSPointersToMembersState,
9115 PointersToMembersPragmaLocation);
9116 }
9117 SemaObj->CUDA().ForceHostDeviceDepth = ForceHostDeviceDepth;
9118 if (!RISCVVecIntrinsicPragma.empty()) {
9119 assert(RISCVVecIntrinsicPragma.size() == 3 &&
9120 "Wrong number of RISCVVecIntrinsicPragma");
9121 SemaObj->RISCV().DeclareRVVBuiltins = RISCVVecIntrinsicPragma[0];
9122 SemaObj->RISCV().DeclareSiFiveVectorBuiltins = RISCVVecIntrinsicPragma[1];
9123 SemaObj->RISCV().DeclareAndesVectorBuiltins = RISCVVecIntrinsicPragma[2];
9124 }
9125
9126 if (PragmaAlignPackCurrentValue) {
9127 // The bottom of the stack might have a default value. It must be adjusted
9128 // to the current value to ensure that the packing state is preserved after
9129 // popping entries that were included/imported from a PCH/module.
9130 bool DropFirst = false;
9131 if (!PragmaAlignPackStack.empty() &&
9132 PragmaAlignPackStack.front().Location.isInvalid()) {
9133 assert(PragmaAlignPackStack.front().Value ==
9134 SemaObj->AlignPackStack.DefaultValue &&
9135 "Expected a default alignment value");
9136 SemaObj->AlignPackStack.Stack.emplace_back(
9137 PragmaAlignPackStack.front().SlotLabel,
9138 SemaObj->AlignPackStack.CurrentValue,
9139 SemaObj->AlignPackStack.CurrentPragmaLocation,
9140 PragmaAlignPackStack.front().PushLocation);
9141 DropFirst = true;
9142 }
9143 for (const auto &Entry :
9144 llvm::ArrayRef(PragmaAlignPackStack).drop_front(DropFirst ? 1 : 0)) {
9145 SemaObj->AlignPackStack.Stack.emplace_back(
9146 Entry.SlotLabel, Entry.Value, Entry.Location, Entry.PushLocation);
9147 }
9148 if (PragmaAlignPackCurrentLocation.isInvalid()) {
9149 assert(*PragmaAlignPackCurrentValue ==
9150 SemaObj->AlignPackStack.DefaultValue &&
9151 "Expected a default align and pack value");
9152 // Keep the current values.
9153 } else {
9154 SemaObj->AlignPackStack.CurrentValue = *PragmaAlignPackCurrentValue;
9155 SemaObj->AlignPackStack.CurrentPragmaLocation =
9156 PragmaAlignPackCurrentLocation;
9157 }
9158 }
9159 if (FpPragmaCurrentValue) {
9160 // The bottom of the stack might have a default value. It must be adjusted
9161 // to the current value to ensure that fp-pragma state is preserved after
9162 // popping entries that were included/imported from a PCH/module.
9163 bool DropFirst = false;
9164 if (!FpPragmaStack.empty() && FpPragmaStack.front().Location.isInvalid()) {
9165 assert(FpPragmaStack.front().Value ==
9166 SemaObj->FpPragmaStack.DefaultValue &&
9167 "Expected a default pragma float_control value");
9168 SemaObj->FpPragmaStack.Stack.emplace_back(
9169 FpPragmaStack.front().SlotLabel, SemaObj->FpPragmaStack.CurrentValue,
9170 SemaObj->FpPragmaStack.CurrentPragmaLocation,
9171 FpPragmaStack.front().PushLocation);
9172 DropFirst = true;
9173 }
9174 for (const auto &Entry :
9175 llvm::ArrayRef(FpPragmaStack).drop_front(DropFirst ? 1 : 0))
9176 SemaObj->FpPragmaStack.Stack.emplace_back(
9177 Entry.SlotLabel, Entry.Value, Entry.Location, Entry.PushLocation);
9178 if (FpPragmaCurrentLocation.isInvalid()) {
9179 assert(*FpPragmaCurrentValue == SemaObj->FpPragmaStack.DefaultValue &&
9180 "Expected a default pragma float_control value");
9181 // Keep the current values.
9182 } else {
9183 SemaObj->FpPragmaStack.CurrentValue = *FpPragmaCurrentValue;
9184 SemaObj->FpPragmaStack.CurrentPragmaLocation = FpPragmaCurrentLocation;
9185 }
9186 }
9187
9188 // For non-modular AST files, restore visiblity of modules.
9189 for (auto &Import : PendingImportedModulesSema) {
9190 if (Import.ImportLoc.isInvalid())
9191 continue;
9192 if (Module *Imported = getSubmodule(Import.ID)) {
9193 SemaObj->makeModuleVisible(Imported, Import.ImportLoc);
9194 }
9195 }
9196 PendingImportedModulesSema.clear();
9197}
9198
9200 // Note that we are loading an identifier.
9201 Deserializing AnIdentifier(this);
9202
9203 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
9204 NumIdentifierLookups,
9205 NumIdentifierLookupHits);
9206
9207 // We don't need to do identifier table lookups in C++ modules (we preload
9208 // all interesting declarations, and don't need to use the scope for name
9209 // lookups). Perform the lookup in PCH files, though, since we don't build
9210 // a complete initial identifier table if we're carrying on from a PCH.
9211 if (PP.getLangOpts().CPlusPlus) {
9212 for (auto *F : ModuleMgr.pch_modules())
9213 if (Visitor(*F))
9214 break;
9215 } else {
9216 // If there is a global index, look there first to determine which modules
9217 // provably do not have any results for this identifier.
9219 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
9220 if (!loadGlobalIndex()) {
9221 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
9222 HitsPtr = &Hits;
9223 }
9224 }
9225
9226 ModuleMgr.visit(Visitor, HitsPtr);
9227 }
9228
9229 IdentifierInfo *II = Visitor.getIdentifierInfo();
9231 return II;
9232}
9233
9234namespace clang {
9235
9236 /// An identifier-lookup iterator that enumerates all of the
9237 /// identifiers stored within a set of AST files.
9239 /// The AST reader whose identifiers are being enumerated.
9240 const ASTReader &Reader;
9241
9242 /// The current index into the chain of AST files stored in
9243 /// the AST reader.
9244 unsigned Index;
9245
9246 /// The current position within the identifier lookup table
9247 /// of the current AST file.
9248 ASTIdentifierLookupTable::key_iterator Current;
9249
9250 /// The end position within the identifier lookup table of
9251 /// the current AST file.
9252 ASTIdentifierLookupTable::key_iterator End;
9253
9254 /// Whether to skip any modules in the ASTReader.
9255 bool SkipModules;
9256
9257 public:
9258 explicit ASTIdentifierIterator(const ASTReader &Reader,
9259 bool SkipModules = false);
9260
9261 StringRef Next() override;
9262 };
9263
9264} // namespace clang
9265
9267 bool SkipModules)
9268 : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) {
9269}
9270
9272 while (Current == End) {
9273 // If we have exhausted all of our AST files, we're done.
9274 if (Index == 0)
9275 return StringRef();
9276
9277 --Index;
9278 ModuleFile &F = Reader.ModuleMgr[Index];
9279 if (SkipModules && F.isModule())
9280 continue;
9281
9282 ASTIdentifierLookupTable *IdTable =
9284 Current = IdTable->key_begin();
9285 End = IdTable->key_end();
9286 }
9287
9288 // We have any identifiers remaining in the current AST file; return
9289 // the next one.
9290 StringRef Result = *Current;
9291 ++Current;
9292 return Result;
9293}
9294
9295namespace {
9296
9297/// A utility for appending two IdentifierIterators.
9298class ChainedIdentifierIterator : public IdentifierIterator {
9299 std::unique_ptr<IdentifierIterator> Current;
9300 std::unique_ptr<IdentifierIterator> Queued;
9301
9302public:
9303 ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First,
9304 std::unique_ptr<IdentifierIterator> Second)
9305 : Current(std::move(First)), Queued(std::move(Second)) {}
9306
9307 StringRef Next() override {
9308 if (!Current)
9309 return StringRef();
9310
9311 StringRef result = Current->Next();
9312 if (!result.empty())
9313 return result;
9314
9315 // Try the queued iterator, which may itself be empty.
9316 Current.reset();
9317 std::swap(Current, Queued);
9318 return Next();
9319 }
9320};
9321
9322} // namespace
9323
9325 if (!loadGlobalIndex()) {
9326 std::unique_ptr<IdentifierIterator> ReaderIter(
9327 new ASTIdentifierIterator(*this, /*SkipModules=*/true));
9328 std::unique_ptr<IdentifierIterator> ModulesIter(
9329 GlobalIndex->createIdentifierIterator());
9330 return new ChainedIdentifierIterator(std::move(ReaderIter),
9331 std::move(ModulesIter));
9332 }
9333
9334 return new ASTIdentifierIterator(*this);
9335}
9336
9337namespace clang {
9338namespace serialization {
9339
9341 ASTReader &Reader;
9342 Selector Sel;
9343 unsigned PriorGeneration;
9344 unsigned InstanceBits = 0;
9345 unsigned FactoryBits = 0;
9346 bool InstanceHasMoreThanOneDecl = false;
9347 bool FactoryHasMoreThanOneDecl = false;
9348 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
9349 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
9350
9351 public:
9353 unsigned PriorGeneration)
9354 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration) {}
9355
9357 if (!M.SelectorLookupTable)
9358 return false;
9359
9360 // If we've already searched this module file, skip it now.
9361 if (M.Generation <= PriorGeneration)
9362 return true;
9363
9364 ++Reader.NumMethodPoolTableLookups;
9365 ASTSelectorLookupTable *PoolTable
9367 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
9368 if (Pos == PoolTable->end())
9369 return false;
9370
9371 ++Reader.NumMethodPoolTableHits;
9372 ++Reader.NumSelectorsRead;
9373 // FIXME: Not quite happy with the statistics here. We probably should
9374 // disable this tracking when called via LoadSelector.
9375 // Also, should entries without methods count as misses?
9376 ++Reader.NumMethodPoolEntriesRead;
9378 if (Reader.DeserializationListener)
9379 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
9380
9381 // Append methods in the reverse order, so that later we can process them
9382 // in the order they appear in the source code by iterating through
9383 // the vector in the reverse order.
9384 InstanceMethods.append(Data.Instance.rbegin(), Data.Instance.rend());
9385 FactoryMethods.append(Data.Factory.rbegin(), Data.Factory.rend());
9386 InstanceBits = Data.InstanceBits;
9387 FactoryBits = Data.FactoryBits;
9388 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
9389 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
9390 return false;
9391 }
9392
9393 /// Retrieve the instance methods found by this visitor.
9395 return InstanceMethods;
9396 }
9397
9398 /// Retrieve the instance methods found by this visitor.
9400 return FactoryMethods;
9401 }
9402
9403 unsigned getInstanceBits() const { return InstanceBits; }
9404 unsigned getFactoryBits() const { return FactoryBits; }
9405
9407 return InstanceHasMoreThanOneDecl;
9408 }
9409
9410 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
9411 };
9412
9413} // namespace serialization
9414} // namespace clang
9415
9416/// Add the given set of methods to the method list.
9418 ObjCMethodList &List) {
9419 for (ObjCMethodDecl *M : llvm::reverse(Methods))
9420 S.ObjC().addMethodToGlobalList(&List, M);
9421}
9422
9424 // Get the selector generation and update it to the current generation.
9425 unsigned &Generation = SelectorGeneration[Sel];
9426 unsigned PriorGeneration = Generation;
9427 Generation = getGeneration();
9428 SelectorOutOfDate[Sel] = false;
9429
9430 // Search for methods defined with this selector.
9431 ++NumMethodPoolLookups;
9432 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
9433 ModuleMgr.visit(Visitor);
9434
9435 if (Visitor.getInstanceMethods().empty() &&
9436 Visitor.getFactoryMethods().empty())
9437 return;
9438
9439 ++NumMethodPoolHits;
9440
9441 if (!getSema())
9442 return;
9443
9444 Sema &S = *getSema();
9445 auto &Methods = S.ObjC().MethodPool[Sel];
9446
9447 Methods.first.setBits(Visitor.getInstanceBits());
9448 Methods.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
9449 Methods.second.setBits(Visitor.getFactoryBits());
9450 Methods.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
9451
9452 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
9453 // when building a module we keep every method individually and may need to
9454 // update hasMoreThanOneDecl as we add the methods.
9455 addMethodsToPool(S, Visitor.getInstanceMethods(), Methods.first);
9456 addMethodsToPool(S, Visitor.getFactoryMethods(), Methods.second);
9457}
9458
9460 if (SelectorOutOfDate[Sel])
9461 ReadMethodPool(Sel);
9462}
9463
9466 Namespaces.clear();
9467
9468 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
9469 if (NamespaceDecl *Namespace
9470 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
9471 Namespaces.push_back(Namespace);
9472 }
9473}
9474
9476 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {
9477 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
9478 UndefinedButUsedDecl &U = UndefinedButUsed[Idx++];
9481 Undefined.insert(std::make_pair(D, Loc));
9482 }
9483 UndefinedButUsed.clear();
9484}
9485
9487 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
9488 Exprs) {
9489 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
9490 FieldDecl *FD =
9491 cast<FieldDecl>(GetDecl(GlobalDeclID(DelayedDeleteExprs[Idx++])));
9492 uint64_t Count = DelayedDeleteExprs[Idx++];
9493 for (uint64_t C = 0; C < Count; ++C) {
9494 SourceLocation DeleteLoc =
9495 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
9496 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
9497 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
9498 }
9499 }
9500}
9501
9503 SmallVectorImpl<VarDecl *> &TentativeDefs) {
9504 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
9505 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
9506 if (Var)
9507 TentativeDefs.push_back(Var);
9508 }
9509 TentativeDefinitions.clear();
9510}
9511
9514 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
9516 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
9517 if (D)
9518 Decls.push_back(D);
9519 }
9520 UnusedFileScopedDecls.clear();
9521}
9522
9525 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
9527 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
9528 if (D)
9529 Decls.push_back(D);
9530 }
9531 DelegatingCtorDecls.clear();
9532}
9533
9535 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
9537 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
9538 if (D)
9539 Decls.push_back(D);
9540 }
9541 ExtVectorDecls.clear();
9542}
9543
9546 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
9547 ++I) {
9548 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
9549 GetDecl(UnusedLocalTypedefNameCandidates[I]));
9550 if (D)
9551 Decls.insert(D);
9552 }
9553 UnusedLocalTypedefNameCandidates.clear();
9554}
9555
9558 for (auto I : DeclsToCheckForDeferredDiags) {
9559 auto *D = dyn_cast_or_null<Decl>(GetDecl(I));
9560 if (D)
9561 Decls.insert(D);
9562 }
9563 DeclsToCheckForDeferredDiags.clear();
9564}
9565
9567 SmallVectorImpl<std::pair<Selector, SourceLocation>> &Sels) {
9568 if (ReferencedSelectorsData.empty())
9569 return;
9570
9571 // If there are @selector references added them to its pool. This is for
9572 // implementation of -Wselector.
9573 unsigned int DataSize = ReferencedSelectorsData.size()-1;
9574 unsigned I = 0;
9575 while (I < DataSize) {
9576 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
9577 SourceLocation SelLoc
9578 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
9579 Sels.push_back(std::make_pair(Sel, SelLoc));
9580 }
9581 ReferencedSelectorsData.clear();
9582}
9583
9585 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo>> &WeakIDs) {
9586 if (WeakUndeclaredIdentifiers.empty())
9587 return;
9588
9589 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
9590 IdentifierInfo *WeakId
9591 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
9592 IdentifierInfo *AliasId
9593 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
9594 SourceLocation Loc =
9595 SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
9596 WeakInfo WI(AliasId, Loc);
9597 WeakIDs.push_back(std::make_pair(WeakId, WI));
9598 }
9599 WeakUndeclaredIdentifiers.clear();
9600}
9601
9603 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
9605 VTableUse &TableInfo = VTableUses[Idx++];
9606 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(TableInfo.ID));
9607 VT.Location = SourceLocation::getFromRawEncoding(TableInfo.RawLoc);
9608 VT.DefinitionRequired = TableInfo.Used;
9609 VTables.push_back(VT);
9610 }
9611
9612 VTableUses.clear();
9613}
9614
9616 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation>> &Pending) {
9617 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
9618 PendingInstantiation &Inst = PendingInstantiations[Idx++];
9619 ValueDecl *D = cast<ValueDecl>(GetDecl(Inst.ID));
9621
9622 Pending.push_back(std::make_pair(D, Loc));
9623 }
9624 PendingInstantiations.clear();
9625}
9626
9628 llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>>
9629 &LPTMap) {
9630 for (auto &LPT : LateParsedTemplates) {
9631 ModuleFile *FMod = LPT.first;
9632 RecordDataImpl &LateParsed = LPT.second;
9633 for (unsigned Idx = 0, N = LateParsed.size(); Idx < N;
9634 /* In loop */) {
9635 FunctionDecl *FD = ReadDeclAs<FunctionDecl>(*FMod, LateParsed, Idx);
9636
9637 auto LT = std::make_unique<LateParsedTemplate>();
9638 LT->D = ReadDecl(*FMod, LateParsed, Idx);
9639 LT->FPO = FPOptions::getFromOpaqueInt(LateParsed[Idx++]);
9640
9641 ModuleFile *F = getOwningModuleFile(LT->D);
9642 assert(F && "No module");
9643
9644 unsigned TokN = LateParsed[Idx++];
9645 LT->Toks.reserve(TokN);
9646 for (unsigned T = 0; T < TokN; ++T)
9647 LT->Toks.push_back(ReadToken(*F, LateParsed, Idx));
9648
9649 LPTMap.insert(std::make_pair(FD, std::move(LT)));
9650 }
9651 }
9652
9653 LateParsedTemplates.clear();
9654}
9655
9657 if (!Lambda->getLambdaContextDecl())
9658 return;
9659
9660 auto LambdaInfo =
9661 std::make_pair(Lambda->getLambdaContextDecl()->getCanonicalDecl(),
9662 Lambda->getLambdaIndexInContext());
9663
9664 // Handle the import and then include case for lambdas.
9665 if (auto Iter = LambdaDeclarationsForMerging.find(LambdaInfo);
9666 Iter != LambdaDeclarationsForMerging.end() &&
9667 Iter->second->isFromASTFile() && Lambda->getFirstDecl() == Lambda) {
9669 cast<CXXRecordDecl>(Iter->second)->getMostRecentDecl();
9670 Lambda->setPreviousDecl(Previous);
9671 return;
9672 }
9673
9674 // Keep track of this lambda so it can be merged with another lambda that
9675 // is loaded later.
9676 LambdaDeclarationsForMerging.insert({LambdaInfo, Lambda});
9677}
9678
9680 // It would be complicated to avoid reading the methods anyway. So don't.
9681 ReadMethodPool(Sel);
9682}
9683
9685 assert(ID && "Non-zero identifier ID required");
9686 unsigned Index = translateIdentifierIDToIndex(ID).second;
9687 assert(Index < IdentifiersLoaded.size() && "identifier ID out of range");
9688 IdentifiersLoaded[Index] = II;
9689 if (DeserializationListener)
9690 DeserializationListener->IdentifierRead(ID, II);
9691}
9692
9693/// Set the globally-visible declarations associated with the given
9694/// identifier.
9695///
9696/// If the AST reader is currently in a state where the given declaration IDs
9697/// cannot safely be resolved, they are queued until it is safe to resolve
9698/// them.
9699///
9700/// \param II an IdentifierInfo that refers to one or more globally-visible
9701/// declarations.
9702///
9703/// \param DeclIDs the set of declaration IDs with the name @p II that are
9704/// visible at global scope.
9705///
9706/// \param Decls if non-null, this vector will be populated with the set of
9707/// deserialized declarations. These declarations will not be pushed into
9708/// scope.
9711 SmallVectorImpl<Decl *> *Decls) {
9712 if (NumCurrentElementsDeserializing && !Decls) {
9713 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
9714 return;
9715 }
9716
9717 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
9718 if (!SemaObj) {
9719 // Queue this declaration so that it will be added to the
9720 // translation unit scope and identifier's declaration chain
9721 // once a Sema object is known.
9722 PreloadedDeclIDs.push_back(DeclIDs[I]);
9723 continue;
9724 }
9725
9726 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
9727
9728 // If we're simply supposed to record the declarations, do so now.
9729 if (Decls) {
9730 Decls->push_back(D);
9731 continue;
9732 }
9733
9734 // Introduce this declaration into the translation-unit scope
9735 // and add it to the declaration chain for this identifier, so
9736 // that (unqualified) name lookup will find it.
9737 pushExternalDeclIntoScope(D, II);
9738 }
9739}
9740
9741std::pair<ModuleFile *, unsigned>
9742ASTReader::translateIdentifierIDToIndex(IdentifierID ID) const {
9743 if (ID == 0)
9744 return {nullptr, 0};
9745
9746 unsigned ModuleFileIndex = ID >> 32;
9747 unsigned LocalID = ID & llvm::maskTrailingOnes<IdentifierID>(32);
9748
9749 assert(ModuleFileIndex && "not translating loaded IdentifierID?");
9750 assert(getModuleManager().size() > ModuleFileIndex - 1);
9751
9752 ModuleFile &MF = getModuleManager()[ModuleFileIndex - 1];
9753 assert(LocalID < MF.LocalNumIdentifiers);
9754 return {&MF, MF.BaseIdentifierID + LocalID};
9755}
9756
9758 if (ID == 0)
9759 return nullptr;
9760
9761 if (IdentifiersLoaded.empty()) {
9762 Error("no identifier table in AST file");
9763 return nullptr;
9764 }
9765
9766 auto [M, Index] = translateIdentifierIDToIndex(ID);
9767 if (!IdentifiersLoaded[Index]) {
9768 assert(M != nullptr && "Untranslated Identifier ID?");
9769 assert(Index >= M->BaseIdentifierID);
9770 unsigned LocalIndex = Index - M->BaseIdentifierID;
9771 const unsigned char *Data =
9772 M->IdentifierTableData + M->IdentifierOffsets[LocalIndex];
9773
9774 ASTIdentifierLookupTrait Trait(*this, *M);
9775 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
9776 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
9777 auto &II = PP.getIdentifierTable().get(Key);
9778 IdentifiersLoaded[Index] = &II;
9779 bool IsModule = getPreprocessor().getCurrentModule() != nullptr;
9780 markIdentifierFromAST(*this, II, IsModule);
9781 if (DeserializationListener)
9782 DeserializationListener->IdentifierRead(ID, &II);
9783 }
9784
9785 return IdentifiersLoaded[Index];
9786}
9787
9791
9793 if (LocalID < NUM_PREDEF_IDENT_IDS)
9794 return LocalID;
9795
9796 if (!M.ModuleOffsetMap.empty())
9797 ReadModuleOffsetMap(M);
9798
9799 unsigned ModuleFileIndex = LocalID >> 32;
9800 LocalID &= llvm::maskTrailingOnes<IdentifierID>(32);
9801 ModuleFile *MF =
9802 ModuleFileIndex ? M.TransitiveImports[ModuleFileIndex - 1] : &M;
9803 assert(MF && "malformed identifier ID encoding?");
9804
9805 if (!ModuleFileIndex)
9806 LocalID -= NUM_PREDEF_IDENT_IDS;
9807
9808 return ((IdentifierID)(MF->Index + 1) << 32) | LocalID;
9809}
9810
9811std::pair<ModuleFile *, unsigned>
9812ASTReader::translateMacroIDToIndex(MacroID ID) const {
9813 if (ID == 0)
9814 return {nullptr, 0};
9815
9816 unsigned ModuleFileIndex = ID >> 32;
9817 assert(ModuleFileIndex && "not translating loaded MacroID?");
9818 assert(getModuleManager().size() > ModuleFileIndex - 1);
9819 ModuleFile &MF = getModuleManager()[ModuleFileIndex - 1];
9820
9821 unsigned LocalID = ID & llvm::maskTrailingOnes<MacroID>(32);
9822 assert(LocalID < MF.LocalNumMacros);
9823 return {&MF, MF.BaseMacroID + LocalID};
9824}
9825
9827 if (ID == 0)
9828 return nullptr;
9829
9830 if (MacrosLoaded.empty()) {
9831 Error("no macro table in AST file");
9832 return nullptr;
9833 }
9834
9835 auto [M, Index] = translateMacroIDToIndex(ID);
9836 if (!MacrosLoaded[Index]) {
9837 assert(M != nullptr && "Untranslated Macro ID?");
9838 assert(Index >= M->BaseMacroID);
9839 unsigned LocalIndex = Index - M->BaseMacroID;
9840 uint64_t DataOffset = M->MacroOffsetsBase + M->MacroOffsets[LocalIndex];
9841 MacrosLoaded[Index] = ReadMacroRecord(*M, DataOffset);
9842
9843 if (DeserializationListener)
9844 DeserializationListener->MacroRead(ID, MacrosLoaded[Index]);
9845 }
9846
9847 return MacrosLoaded[Index];
9848}
9849
9851 if (LocalID < NUM_PREDEF_MACRO_IDS)
9852 return LocalID;
9853
9854 if (!M.ModuleOffsetMap.empty())
9855 ReadModuleOffsetMap(M);
9856
9857 unsigned ModuleFileIndex = LocalID >> 32;
9858 LocalID &= llvm::maskTrailingOnes<MacroID>(32);
9859 ModuleFile *MF =
9860 ModuleFileIndex ? M.TransitiveImports[ModuleFileIndex - 1] : &M;
9861 assert(MF && "malformed identifier ID encoding?");
9862
9863 if (!ModuleFileIndex) {
9864 assert(LocalID >= NUM_PREDEF_MACRO_IDS);
9865 LocalID -= NUM_PREDEF_MACRO_IDS;
9866 }
9867
9868 return (static_cast<MacroID>(MF->Index + 1) << 32) | LocalID;
9869}
9870
9872ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) const {
9873 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
9874 return LocalID;
9875
9876 if (!M.ModuleOffsetMap.empty())
9877 ReadModuleOffsetMap(M);
9878
9881 assert(I != M.SubmoduleRemap.end()
9882 && "Invalid index into submodule index remap");
9883
9884 return LocalID + I->second;
9885}
9886
9888 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
9889 assert(GlobalID == 0 && "Unhandled global submodule ID");
9890 return nullptr;
9891 }
9892
9893 if (GlobalID > SubmodulesLoaded.size()) {
9894 Error("submodule ID out of range in AST file");
9895 return nullptr;
9896 }
9897
9898 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
9899}
9900
9902 return getSubmodule(ID);
9903}
9904
9906 if (ID & 1) {
9907 // It's a module, look it up by submodule ID.
9908 auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(M, ID >> 1));
9909 return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
9910 } else {
9911 // It's a prefix (preamble, PCH, ...). Look it up by index.
9912 int IndexFromEnd = static_cast<int>(ID >> 1);
9913 assert(IndexFromEnd && "got reference to unknown module file");
9914 return getModuleManager().pch_modules().end()[-IndexFromEnd];
9915 }
9916}
9917
9919 if (!M)
9920 return 1;
9921
9922 // For a file representing a module, use the submodule ID of the top-level
9923 // module as the file ID. For any other kind of file, the number of such
9924 // files loaded beforehand will be the same on reload.
9925 // FIXME: Is this true even if we have an explicit module file and a PCH?
9926 if (M->isModule())
9927 return ((M->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
9928
9929 auto PCHModules = getModuleManager().pch_modules();
9930 auto I = llvm::find(PCHModules, M);
9931 assert(I != PCHModules.end() && "emitting reference to unknown file");
9932 return std::distance(I, PCHModules.end()) << 1;
9933}
9934
9935std::optional<ASTSourceDescriptor> ASTReader::getSourceDescriptor(unsigned ID) {
9936 if (Module *M = getSubmodule(ID))
9937 return ASTSourceDescriptor(*M);
9938
9939 // If there is only a single PCH, return it instead.
9940 // Chained PCH are not supported.
9941 const auto &PCHChain = ModuleMgr.pch_modules();
9942 if (std::distance(std::begin(PCHChain), std::end(PCHChain))) {
9943 ModuleFile &MF = ModuleMgr.getPrimaryModule();
9944 StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName);
9945 StringRef FileName = llvm::sys::path::filename(MF.FileName);
9946 return ASTSourceDescriptor(ModuleName,
9947 llvm::sys::path::parent_path(MF.FileName),
9948 FileName, MF.Signature);
9949 }
9950 return std::nullopt;
9951}
9952
9954 auto I = DefinitionSource.find(FD);
9955 if (I == DefinitionSource.end())
9956 return EK_ReplyHazy;
9957 return I->second ? EK_Never : EK_Always;
9958}
9959
9961 return ThisDeclarationWasADefinitionSet.contains(FD);
9962}
9963
9965 return DecodeSelector(getGlobalSelectorID(M, LocalID));
9966}
9967
9969 if (ID == 0)
9970 return Selector();
9971
9972 if (ID > SelectorsLoaded.size()) {
9973 Error("selector ID out of range in AST file");
9974 return Selector();
9975 }
9976
9977 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
9978 // Load this selector from the selector table.
9979 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
9980 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
9981 ModuleFile &M = *I->second;
9982 ASTSelectorLookupTrait Trait(*this, M);
9983 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
9984 SelectorsLoaded[ID - 1] =
9985 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
9986 if (DeserializationListener)
9987 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
9988 }
9989
9990 return SelectorsLoaded[ID - 1];
9991}
9992
9996
9998 // ID 0 (the null selector) is considered an external selector.
9999 return getTotalNumSelectors() + 1;
10000}
10001
10003ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
10004 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
10005 return LocalID;
10006
10007 if (!M.ModuleOffsetMap.empty())
10008 ReadModuleOffsetMap(M);
10009
10012 assert(I != M.SelectorRemap.end()
10013 && "Invalid index into selector index remap");
10014
10015 return LocalID + I->second;
10016}
10017
10043
10045 DeclarationNameInfo NameInfo;
10046 NameInfo.setName(readDeclarationName());
10047 NameInfo.setLoc(readSourceLocation());
10048 NameInfo.setInfo(readDeclarationNameLoc(NameInfo.getName()));
10049 return NameInfo;
10050}
10051
10055
10057 auto Kind = readInt();
10058 auto ResultType = readQualType();
10059 auto Value = readAPInt();
10060 SpirvOperand Op(SpirvOperand::SpirvOperandKind(Kind), ResultType, Value);
10061 assert(Op.isValid());
10062 return Op;
10063}
10064
10067 unsigned NumTPLists = readInt();
10068 Info.NumTemplParamLists = NumTPLists;
10069 if (NumTPLists) {
10070 Info.TemplParamLists =
10071 new (getContext()) TemplateParameterList *[NumTPLists];
10072 for (unsigned i = 0; i != NumTPLists; ++i)
10074 }
10075}
10076
10079 SourceLocation TemplateLoc = readSourceLocation();
10080 SourceLocation LAngleLoc = readSourceLocation();
10081 SourceLocation RAngleLoc = readSourceLocation();
10082
10083 unsigned NumParams = readInt();
10085 Params.reserve(NumParams);
10086 while (NumParams--)
10087 Params.push_back(readDeclAs<NamedDecl>());
10088
10089 bool HasRequiresClause = readBool();
10090 Expr *RequiresClause = HasRequiresClause ? readExpr() : nullptr;
10091
10093 getContext(), TemplateLoc, LAngleLoc, Params, RAngleLoc, RequiresClause);
10094 return TemplateParams;
10095}
10096
10099 bool Canonicalize) {
10100 unsigned NumTemplateArgs = readInt();
10101 TemplArgs.reserve(NumTemplateArgs);
10102 while (NumTemplateArgs--)
10103 TemplArgs.push_back(readTemplateArgument(Canonicalize));
10104}
10105
10106/// Read a UnresolvedSet structure.
10108 unsigned NumDecls = readInt();
10109 Set.reserve(getContext(), NumDecls);
10110 while (NumDecls--) {
10111 GlobalDeclID ID = readDeclID();
10113 Set.addLazyDecl(getContext(), ID, AS);
10114 }
10115}
10116
10119 bool isVirtual = readBool();
10120 bool isBaseOfClass = readBool();
10121 AccessSpecifier AS = static_cast<AccessSpecifier>(readInt());
10122 bool inheritConstructors = readBool();
10124 SourceRange Range = readSourceRange();
10125 SourceLocation EllipsisLoc = readSourceLocation();
10126 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
10127 EllipsisLoc);
10128 Result.setInheritConstructors(inheritConstructors);
10129 return Result;
10130}
10131
10134 ASTContext &Context = getContext();
10135 unsigned NumInitializers = readInt();
10136 assert(NumInitializers && "wrote ctor initializers but have no inits");
10137 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
10138 for (unsigned i = 0; i != NumInitializers; ++i) {
10139 TypeSourceInfo *TInfo = nullptr;
10140 bool IsBaseVirtual = false;
10141 FieldDecl *Member = nullptr;
10142 IndirectFieldDecl *IndirectMember = nullptr;
10143
10145 switch (Type) {
10147 TInfo = readTypeSourceInfo();
10148 IsBaseVirtual = readBool();
10149 break;
10150
10152 TInfo = readTypeSourceInfo();
10153 break;
10154
10157 break;
10158
10160 IndirectMember = readDeclAs<IndirectFieldDecl>();
10161 break;
10162 }
10163
10164 SourceLocation MemberOrEllipsisLoc = readSourceLocation();
10165 Expr *Init = readExpr();
10166 SourceLocation LParenLoc = readSourceLocation();
10167 SourceLocation RParenLoc = readSourceLocation();
10168
10169 CXXCtorInitializer *BOMInit;
10171 BOMInit = new (Context)
10172 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
10173 RParenLoc, MemberOrEllipsisLoc);
10175 BOMInit = new (Context)
10176 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
10177 else if (Member)
10178 BOMInit = new (Context)
10179 CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc, LParenLoc,
10180 Init, RParenLoc);
10181 else
10182 BOMInit = new (Context)
10183 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
10184 LParenLoc, Init, RParenLoc);
10185
10186 if (/*IsWritten*/readBool()) {
10187 unsigned SourceOrder = readInt();
10188 BOMInit->setSourceOrder(SourceOrder);
10189 }
10190
10191 CtorInitializers[i] = BOMInit;
10192 }
10193
10194 return CtorInitializers;
10195}
10196
10199 ASTContext &Context = getContext();
10200 unsigned N = readInt();
10202 for (unsigned I = 0; I != N; ++I) {
10203 auto Kind = readNestedNameSpecifierKind();
10204 switch (Kind) {
10206 auto *NS = readDeclAs<NamespaceBaseDecl>();
10207 SourceRange Range = readSourceRange();
10208 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
10209 break;
10210 }
10211
10214 if (!T)
10215 return NestedNameSpecifierLoc();
10216 SourceLocation ColonColonLoc = readSourceLocation();
10217 Builder.Make(Context, T->getTypeLoc(), ColonColonLoc);
10218 break;
10219 }
10220
10222 SourceLocation ColonColonLoc = readSourceLocation();
10223 Builder.MakeGlobal(Context, ColonColonLoc);
10224 break;
10225 }
10226
10229 SourceRange Range = readSourceRange();
10230 Builder.MakeMicrosoftSuper(Context, RD, Range.getBegin(), Range.getEnd());
10231 break;
10232 }
10233
10235 llvm_unreachable("unexpected null nested name specifier");
10236 }
10237 }
10238
10239 return Builder.getWithLocInContext(Context);
10240}
10241
10243 unsigned &Idx) {
10246 return SourceRange(beg, end);
10247}
10248
10250 const StringRef Blob) {
10251 unsigned Count = Record[0];
10252 const char *Byte = Blob.data();
10253 llvm::BitVector Ret = llvm::BitVector(Count, false);
10254 for (unsigned I = 0; I < Count; ++Byte)
10255 for (unsigned Bit = 0; Bit < 8 && I < Count; ++Bit, ++I)
10256 if (*Byte & (1 << Bit))
10257 Ret[I] = true;
10258 return Ret;
10259}
10260
10261/// Read a floating-point value
10262llvm::APFloat ASTRecordReader::readAPFloat(const llvm::fltSemantics &Sem) {
10263 return llvm::APFloat(Sem, readAPInt());
10264}
10265
10266// Read a string
10267std::string ASTReader::ReadString(const RecordDataImpl &Record, unsigned &Idx) {
10268 unsigned Len = Record[Idx++];
10269 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
10270 Idx += Len;
10271 return Result;
10272}
10273
10274StringRef ASTReader::ReadStringBlob(const RecordDataImpl &Record, unsigned &Idx,
10275 StringRef &Blob) {
10276 unsigned Len = Record[Idx++];
10277 StringRef Result = Blob.substr(0, Len);
10278 Blob = Blob.substr(Len);
10279 return Result;
10280}
10281
10283 unsigned &Idx) {
10284 return ReadPath(F.BaseDirectory, Record, Idx);
10285}
10286
10287std::string ASTReader::ReadPath(StringRef BaseDirectory,
10288 const RecordData &Record, unsigned &Idx) {
10289 std::string Filename = ReadString(Record, Idx);
10290 return ResolveImportedPathAndAllocate(PathBuf, Filename, BaseDirectory);
10291}
10292
10293std::string ASTReader::ReadPathBlob(StringRef BaseDirectory,
10294 const RecordData &Record, unsigned &Idx,
10295 StringRef &Blob) {
10296 StringRef Filename = ReadStringBlob(Record, Idx, Blob);
10297 return ResolveImportedPathAndAllocate(PathBuf, Filename, BaseDirectory);
10298}
10299
10301 unsigned &Idx) {
10302 unsigned Major = Record[Idx++];
10303 unsigned Minor = Record[Idx++];
10304 unsigned Subminor = Record[Idx++];
10305 if (Minor == 0)
10306 return VersionTuple(Major);
10307 if (Subminor == 0)
10308 return VersionTuple(Major, Minor - 1);
10309 return VersionTuple(Major, Minor - 1, Subminor - 1);
10310}
10311
10318
10319DiagnosticBuilder ASTReader::Diag(unsigned DiagID) const {
10320 return Diag(CurrentImportLoc, DiagID);
10321}
10322
10324 return Diags.Report(Loc, DiagID);
10325}
10326
10328 llvm::function_ref<void()> Fn) {
10329 // When Sema is available, avoid duplicate errors.
10330 if (SemaObj) {
10331 SemaObj->runWithSufficientStackSpace(Loc, Fn);
10332 return;
10333 }
10334
10335 StackHandler.runWithSufficientStackSpace(Loc, Fn);
10336}
10337
10338/// Retrieve the identifier table associated with the
10339/// preprocessor.
10341 return PP.getIdentifierTable();
10342}
10343
10344/// Record that the given ID maps to the given switch-case
10345/// statement.
10347 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
10348 "Already have a SwitchCase with this ID");
10349 (*CurrSwitchCaseStmts)[ID] = SC;
10350}
10351
10352/// Retrieve the switch-case statement with the given ID.
10354 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
10355 return (*CurrSwitchCaseStmts)[ID];
10356}
10357
10359 CurrSwitchCaseStmts->clear();
10360}
10361
10363 ASTContext &Context = getContext();
10364 std::vector<RawComment *> Comments;
10365 for (SmallVectorImpl<std::pair<BitstreamCursor,
10367 I = CommentsCursors.begin(),
10368 E = CommentsCursors.end();
10369 I != E; ++I) {
10370 Comments.clear();
10371 BitstreamCursor &Cursor = I->first;
10372 serialization::ModuleFile &F = *I->second;
10373 SavedStreamPosition SavedPosition(Cursor);
10374
10376 while (true) {
10378 Cursor.advanceSkippingSubblocks(
10379 BitstreamCursor::AF_DontPopBlockAtEnd);
10380 if (!MaybeEntry) {
10381 Error(MaybeEntry.takeError());
10382 return;
10383 }
10384 llvm::BitstreamEntry Entry = MaybeEntry.get();
10385
10386 switch (Entry.Kind) {
10387 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
10388 case llvm::BitstreamEntry::Error:
10389 Error("malformed block record in AST file");
10390 return;
10391 case llvm::BitstreamEntry::EndBlock:
10392 goto NextCursor;
10393 case llvm::BitstreamEntry::Record:
10394 // The interesting case.
10395 break;
10396 }
10397
10398 // Read a record.
10399 Record.clear();
10400 Expected<unsigned> MaybeComment = Cursor.readRecord(Entry.ID, Record);
10401 if (!MaybeComment) {
10402 Error(MaybeComment.takeError());
10403 return;
10404 }
10405 switch ((CommentRecordTypes)MaybeComment.get()) {
10406 case COMMENTS_RAW_COMMENT: {
10407 unsigned Idx = 0;
10408 SourceRange SR = ReadSourceRange(F, Record, Idx);
10411 bool IsTrailingComment = Record[Idx++];
10412 bool IsAlmostTrailingComment = Record[Idx++];
10413 Comments.push_back(new (Context) RawComment(
10414 SR, Kind, IsTrailingComment, IsAlmostTrailingComment));
10415 break;
10416 }
10417 }
10418 }
10419 NextCursor:
10420 for (RawComment *C : Comments) {
10421 SourceLocation CommentLoc = C->getBeginLoc();
10422 if (CommentLoc.isValid()) {
10423 FileIDAndOffset Loc = SourceMgr.getDecomposedLoc(CommentLoc);
10424 if (Loc.first.isValid())
10425 Context.Comments.OrderedComments[Loc.first].emplace(Loc.second, C);
10426 }
10427 }
10428 }
10429}
10430
10432 serialization::ModuleFile &MF, bool IncludeSystem,
10433 llvm::function_ref<void(const serialization::InputFileInfo &IFI,
10434 bool IsSystem)>
10435 Visitor) {
10436 unsigned NumUserInputs = MF.NumUserInputFiles;
10437 unsigned NumInputs = MF.InputFilesLoaded.size();
10438 assert(NumUserInputs <= NumInputs);
10439 unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
10440 for (unsigned I = 0; I < N; ++I) {
10441 bool IsSystem = I >= NumUserInputs;
10442 InputFileInfo IFI = getInputFileInfo(MF, I+1);
10443 Visitor(IFI, IsSystem);
10444 }
10445}
10446
10448 bool IncludeSystem, bool Complain,
10449 llvm::function_ref<void(const serialization::InputFile &IF,
10450 bool isSystem)> Visitor) {
10451 unsigned NumUserInputs = MF.NumUserInputFiles;
10452 unsigned NumInputs = MF.InputFilesLoaded.size();
10453 assert(NumUserInputs <= NumInputs);
10454 unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
10455 for (unsigned I = 0; I < N; ++I) {
10456 bool IsSystem = I >= NumUserInputs;
10457 InputFile IF = getInputFile(MF, I+1, Complain);
10458 Visitor(IF, IsSystem);
10459 }
10460}
10461
10464 llvm::function_ref<void(FileEntryRef FE)> Visitor) {
10465 unsigned NumInputs = MF.InputFilesLoaded.size();
10466 for (unsigned I = 0; I < NumInputs; ++I) {
10467 InputFileInfo IFI = getInputFileInfo(MF, I + 1);
10468 if (IFI.TopLevel && IFI.ModuleMap)
10469 if (auto FE = getInputFile(MF, I + 1).getFile())
10470 Visitor(*FE);
10471 }
10472}
10473
10474void ASTReader::finishPendingActions() {
10475 while (!PendingIdentifierInfos.empty() ||
10476 !PendingDeducedFunctionTypes.empty() ||
10477 !PendingDeducedVarTypes.empty() || !PendingDeclChains.empty() ||
10478 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
10479 !PendingUpdateRecords.empty() ||
10480 !PendingObjCExtensionIvarRedeclarations.empty()) {
10481 // If any identifiers with corresponding top-level declarations have
10482 // been loaded, load those declarations now.
10483 using TopLevelDeclsMap =
10484 llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2>>;
10485 TopLevelDeclsMap TopLevelDecls;
10486
10487 while (!PendingIdentifierInfos.empty()) {
10488 IdentifierInfo *II = PendingIdentifierInfos.back().first;
10490 std::move(PendingIdentifierInfos.back().second);
10491 PendingIdentifierInfos.pop_back();
10492
10493 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
10494 }
10495
10496 // Load each function type that we deferred loading because it was a
10497 // deduced type that might refer to a local type declared within itself.
10498 for (unsigned I = 0; I != PendingDeducedFunctionTypes.size(); ++I) {
10499 auto *FD = PendingDeducedFunctionTypes[I].first;
10500 FD->setType(GetType(PendingDeducedFunctionTypes[I].second));
10501
10502 if (auto *DT = FD->getReturnType()->getContainedDeducedType()) {
10503 // If we gave a function a deduced return type, remember that we need to
10504 // propagate that along the redeclaration chain.
10505 if (DT->isDeduced()) {
10506 PendingDeducedTypeUpdates.insert(
10507 {FD->getCanonicalDecl(), FD->getReturnType()});
10508 continue;
10509 }
10510
10511 // The function has undeduced DeduceType return type. We hope we can
10512 // find the deduced type by iterating the redecls in other modules
10513 // later.
10514 PendingUndeducedFunctionDecls.push_back(FD);
10515 continue;
10516 }
10517 }
10518 PendingDeducedFunctionTypes.clear();
10519
10520 // Load each variable type that we deferred loading because it was a
10521 // deduced type that might refer to a local type declared within itself.
10522 for (unsigned I = 0; I != PendingDeducedVarTypes.size(); ++I) {
10523 auto *VD = PendingDeducedVarTypes[I].first;
10524 VD->setType(GetType(PendingDeducedVarTypes[I].second));
10525 }
10526 PendingDeducedVarTypes.clear();
10527
10528 // Load pending declaration chains.
10529 for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
10530 loadPendingDeclChain(PendingDeclChains[I].first,
10531 PendingDeclChains[I].second);
10532 PendingDeclChains.clear();
10533
10534 // Make the most recent of the top-level declarations visible.
10535 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
10536 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
10537 IdentifierInfo *II = TLD->first;
10538 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
10539 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
10540 }
10541 }
10542
10543 // Load any pending macro definitions.
10544 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
10545 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
10546 SmallVector<PendingMacroInfo, 2> GlobalIDs;
10547 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
10548 // Initialize the macro history from chained-PCHs ahead of module imports.
10549 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
10550 ++IDIdx) {
10551 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
10552 if (!Info.M->isModule())
10553 resolvePendingMacro(II, Info);
10554 }
10555 // Handle module imports.
10556 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
10557 ++IDIdx) {
10558 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
10559 if (Info.M->isModule())
10560 resolvePendingMacro(II, Info);
10561 }
10562 }
10563 PendingMacroIDs.clear();
10564
10565 // Wire up the DeclContexts for Decls that we delayed setting until
10566 // recursive loading is completed.
10567 while (!PendingDeclContextInfos.empty()) {
10568 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
10569 PendingDeclContextInfos.pop_front();
10570 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
10571 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
10572 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
10573 }
10574
10575 // Perform any pending declaration updates.
10576 while (!PendingUpdateRecords.empty()) {
10577 auto Update = PendingUpdateRecords.pop_back_val();
10578 ReadingKindTracker ReadingKind(Read_Decl, *this);
10579 loadDeclUpdateRecords(Update);
10580 }
10581
10582 while (!PendingObjCExtensionIvarRedeclarations.empty()) {
10583 auto ExtensionsPair = PendingObjCExtensionIvarRedeclarations.back().first;
10584 auto DuplicateIvars =
10585 PendingObjCExtensionIvarRedeclarations.back().second;
10587 StructuralEquivalenceContext Ctx(
10588 ContextObj->getLangOpts(), ExtensionsPair.first->getASTContext(),
10589 ExtensionsPair.second->getASTContext(), NonEquivalentDecls,
10590 StructuralEquivalenceKind::Default, /*StrictTypeSpelling =*/false,
10591 /*Complain =*/false,
10592 /*ErrorOnTagTypeMismatch =*/true);
10593 if (Ctx.IsEquivalent(ExtensionsPair.first, ExtensionsPair.second)) {
10594 // Merge redeclared ivars with their predecessors.
10595 for (auto IvarPair : DuplicateIvars) {
10596 ObjCIvarDecl *Ivar = IvarPair.first, *PrevIvar = IvarPair.second;
10597 // Change semantic DeclContext but keep the lexical one.
10598 Ivar->setDeclContextsImpl(PrevIvar->getDeclContext(),
10599 Ivar->getLexicalDeclContext(),
10600 getContext());
10601 getContext().setPrimaryMergedDecl(Ivar, PrevIvar->getCanonicalDecl());
10602 }
10603 // Invalidate duplicate extension and the cached ivar list.
10604 ExtensionsPair.first->setInvalidDecl();
10605 ExtensionsPair.second->getClassInterface()
10606 ->getDefinition()
10607 ->setIvarList(nullptr);
10608 } else {
10609 for (auto IvarPair : DuplicateIvars) {
10610 Diag(IvarPair.first->getLocation(),
10611 diag::err_duplicate_ivar_declaration)
10612 << IvarPair.first->getIdentifier();
10613 Diag(IvarPair.second->getLocation(), diag::note_previous_definition);
10614 }
10615 }
10616 PendingObjCExtensionIvarRedeclarations.pop_back();
10617 }
10618 }
10619
10620 // At this point, all update records for loaded decls are in place, so any
10621 // fake class definitions should have become real.
10622 assert(PendingFakeDefinitionData.empty() &&
10623 "faked up a class definition but never saw the real one");
10624
10625 // If we deserialized any C++ or Objective-C class definitions, any
10626 // Objective-C protocol definitions, or any redeclarable templates, make sure
10627 // that all redeclarations point to the definitions. Note that this can only
10628 // happen now, after the redeclaration chains have been fully wired.
10629 for (Decl *D : PendingDefinitions) {
10630 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
10631 if (auto *RD = dyn_cast<CXXRecordDecl>(TD)) {
10632 for (auto *R = getMostRecentExistingDecl(RD); R;
10633 R = R->getPreviousDecl()) {
10634 assert((R == D) ==
10635 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
10636 "declaration thinks it's the definition but it isn't");
10637 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
10638 }
10639 }
10640
10641 continue;
10642 }
10643
10644 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
10645 // Make sure that the ObjCInterfaceType points at the definition.
10646 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
10647 ->Decl = ID;
10648
10649 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
10650 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
10651
10652 continue;
10653 }
10654
10655 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
10656 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
10657 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
10658
10659 continue;
10660 }
10661
10662 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
10663 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
10664 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
10665 }
10666 PendingDefinitions.clear();
10667
10668 for (auto [D, Previous] : PendingWarningForDuplicatedDefsInModuleUnits) {
10669 auto hasDefinitionImpl = [this](Decl *D, auto hasDefinitionImpl) {
10670 if (auto *VD = dyn_cast<VarDecl>(D))
10671 return VD->isThisDeclarationADefinition() ||
10672 VD->isThisDeclarationADemotedDefinition();
10673
10674 if (auto *TD = dyn_cast<TagDecl>(D))
10675 return TD->isThisDeclarationADefinition() ||
10676 TD->isThisDeclarationADemotedDefinition();
10677
10678 if (auto *FD = dyn_cast<FunctionDecl>(D))
10679 return FD->isThisDeclarationADefinition() || PendingBodies.count(FD);
10680
10681 if (auto *RTD = dyn_cast<RedeclarableTemplateDecl>(D))
10682 return hasDefinitionImpl(RTD->getTemplatedDecl(), hasDefinitionImpl);
10683
10684 // Conservatively return false here.
10685 return false;
10686 };
10687
10688 auto hasDefinition = [&hasDefinitionImpl](Decl *D) {
10689 return hasDefinitionImpl(D, hasDefinitionImpl);
10690 };
10691
10692 // It is not good to prevent multiple declarations since the forward
10693 // declaration is common. Let's try to avoid duplicated definitions
10694 // only.
10696 continue;
10697
10698 Module *PM = Previous->getOwningModule();
10699 Module *DM = D->getOwningModule();
10700 Diag(D->getLocation(), diag::warn_decls_in_multiple_modules)
10702 << (DM ? DM->getTopLevelModuleName() : "global module");
10703 Diag(Previous->getLocation(), diag::note_also_found);
10704 }
10705 PendingWarningForDuplicatedDefsInModuleUnits.clear();
10706
10707 // Load the bodies of any functions or methods we've encountered. We do
10708 // this now (delayed) so that we can be sure that the declaration chains
10709 // have been fully wired up (hasBody relies on this).
10710 // FIXME: We shouldn't require complete redeclaration chains here.
10711 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
10712 PBEnd = PendingBodies.end();
10713 PB != PBEnd; ++PB) {
10714 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
10715 // FIXME: Check for =delete/=default?
10716 const FunctionDecl *Defn = nullptr;
10717 if (!getContext().getLangOpts().Modules || !FD->hasBody(Defn)) {
10718 FD->setLazyBody(PB->second);
10719 } else {
10720 auto *NonConstDefn = const_cast<FunctionDecl*>(Defn);
10721 mergeDefinitionVisibility(NonConstDefn, FD);
10722
10723 if (!FD->isLateTemplateParsed() &&
10724 !NonConstDefn->isLateTemplateParsed() &&
10725 // We only perform ODR checks for decls not in the explicit
10726 // global module fragment.
10727 !shouldSkipCheckingODR(FD) &&
10728 !shouldSkipCheckingODR(NonConstDefn) &&
10729 FD->getODRHash() != NonConstDefn->getODRHash()) {
10730 if (!isa<CXXMethodDecl>(FD)) {
10731 PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
10732 } else if (FD->getLexicalParent()->isFileContext() &&
10733 NonConstDefn->getLexicalParent()->isFileContext()) {
10734 // Only diagnose out-of-line method definitions. If they are
10735 // in class definitions, then an error will be generated when
10736 // processing the class bodies.
10737 PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
10738 }
10739 }
10740 }
10741 continue;
10742 }
10743
10744 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
10745 if (!getContext().getLangOpts().Modules || !MD->hasBody())
10746 MD->setLazyBody(PB->second);
10747 }
10748 PendingBodies.clear();
10749
10750 // Inform any classes that had members added that they now have more members.
10751 for (auto [RD, MD] : PendingAddedClassMembers) {
10752 RD->addedMember(MD);
10753 }
10754 PendingAddedClassMembers.clear();
10755
10756 // Do some cleanup.
10757 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
10759 PendingMergedDefinitionsToDeduplicate.clear();
10760
10761 // For each decl chain that we wanted to complete while deserializing, mark
10762 // it as "still needs to be completed".
10763 for (Decl *D : PendingIncompleteDeclChains)
10764 markIncompleteDeclChain(D);
10765 PendingIncompleteDeclChains.clear();
10766
10767 assert(PendingIdentifierInfos.empty() &&
10768 "Should be empty at the end of finishPendingActions");
10769 assert(PendingDeducedFunctionTypes.empty() &&
10770 "Should be empty at the end of finishPendingActions");
10771 assert(PendingDeducedVarTypes.empty() &&
10772 "Should be empty at the end of finishPendingActions");
10773 assert(PendingDeclChains.empty() &&
10774 "Should be empty at the end of finishPendingActions");
10775 assert(PendingMacroIDs.empty() &&
10776 "Should be empty at the end of finishPendingActions");
10777 assert(PendingDeclContextInfos.empty() &&
10778 "Should be empty at the end of finishPendingActions");
10779 assert(PendingUpdateRecords.empty() &&
10780 "Should be empty at the end of finishPendingActions");
10781 assert(PendingObjCExtensionIvarRedeclarations.empty() &&
10782 "Should be empty at the end of finishPendingActions");
10783 assert(PendingFakeDefinitionData.empty() &&
10784 "Should be empty at the end of finishPendingActions");
10785 assert(PendingDefinitions.empty() &&
10786 "Should be empty at the end of finishPendingActions");
10787 assert(PendingWarningForDuplicatedDefsInModuleUnits.empty() &&
10788 "Should be empty at the end of finishPendingActions");
10789 assert(PendingBodies.empty() &&
10790 "Should be empty at the end of finishPendingActions");
10791 assert(PendingAddedClassMembers.empty() &&
10792 "Should be empty at the end of finishPendingActions");
10793 assert(PendingMergedDefinitionsToDeduplicate.empty() &&
10794 "Should be empty at the end of finishPendingActions");
10795 assert(PendingIncompleteDeclChains.empty() &&
10796 "Should be empty at the end of finishPendingActions");
10797}
10798
10799void ASTReader::diagnoseOdrViolations() {
10800 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty() &&
10801 PendingRecordOdrMergeFailures.empty() &&
10802 PendingFunctionOdrMergeFailures.empty() &&
10803 PendingEnumOdrMergeFailures.empty() &&
10804 PendingObjCInterfaceOdrMergeFailures.empty() &&
10805 PendingObjCProtocolOdrMergeFailures.empty())
10806 return;
10807
10808 // Trigger the import of the full definition of each class that had any
10809 // odr-merging problems, so we can produce better diagnostics for them.
10810 // These updates may in turn find and diagnose some ODR failures, so take
10811 // ownership of the set first.
10812 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
10813 PendingOdrMergeFailures.clear();
10814 for (auto &Merge : OdrMergeFailures) {
10815 Merge.first->buildLookup();
10816 Merge.first->decls_begin();
10817 Merge.first->bases_begin();
10818 Merge.first->vbases_begin();
10819 for (auto &RecordPair : Merge.second) {
10820 auto *RD = RecordPair.first;
10821 RD->decls_begin();
10822 RD->bases_begin();
10823 RD->vbases_begin();
10824 }
10825 }
10826
10827 // Trigger the import of the full definition of each record in C/ObjC.
10828 auto RecordOdrMergeFailures = std::move(PendingRecordOdrMergeFailures);
10829 PendingRecordOdrMergeFailures.clear();
10830 for (auto &Merge : RecordOdrMergeFailures) {
10831 Merge.first->decls_begin();
10832 for (auto &D : Merge.second)
10833 D->decls_begin();
10834 }
10835
10836 // Trigger the import of the full interface definition.
10837 auto ObjCInterfaceOdrMergeFailures =
10838 std::move(PendingObjCInterfaceOdrMergeFailures);
10839 PendingObjCInterfaceOdrMergeFailures.clear();
10840 for (auto &Merge : ObjCInterfaceOdrMergeFailures) {
10841 Merge.first->decls_begin();
10842 for (auto &InterfacePair : Merge.second)
10843 InterfacePair.first->decls_begin();
10844 }
10845
10846 // Trigger the import of functions.
10847 auto FunctionOdrMergeFailures = std::move(PendingFunctionOdrMergeFailures);
10848 PendingFunctionOdrMergeFailures.clear();
10849 for (auto &Merge : FunctionOdrMergeFailures) {
10850 Merge.first->buildLookup();
10851 Merge.first->decls_begin();
10852 Merge.first->getBody();
10853 for (auto &FD : Merge.second) {
10854 FD->buildLookup();
10855 FD->decls_begin();
10856 FD->getBody();
10857 }
10858 }
10859
10860 // Trigger the import of enums.
10861 auto EnumOdrMergeFailures = std::move(PendingEnumOdrMergeFailures);
10862 PendingEnumOdrMergeFailures.clear();
10863 for (auto &Merge : EnumOdrMergeFailures) {
10864 Merge.first->decls_begin();
10865 for (auto &Enum : Merge.second) {
10866 Enum->decls_begin();
10867 }
10868 }
10869
10870 // Trigger the import of the full protocol definition.
10871 auto ObjCProtocolOdrMergeFailures =
10872 std::move(PendingObjCProtocolOdrMergeFailures);
10873 PendingObjCProtocolOdrMergeFailures.clear();
10874 for (auto &Merge : ObjCProtocolOdrMergeFailures) {
10875 Merge.first->decls_begin();
10876 for (auto &ProtocolPair : Merge.second)
10877 ProtocolPair.first->decls_begin();
10878 }
10879
10880 // For each declaration from a merged context, check that the canonical
10881 // definition of that context also contains a declaration of the same
10882 // entity.
10883 //
10884 // Caution: this loop does things that might invalidate iterators into
10885 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
10886 while (!PendingOdrMergeChecks.empty()) {
10887 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
10888
10889 // FIXME: Skip over implicit declarations for now. This matters for things
10890 // like implicitly-declared special member functions. This isn't entirely
10891 // correct; we can end up with multiple unmerged declarations of the same
10892 // implicit entity.
10893 if (D->isImplicit())
10894 continue;
10895
10896 DeclContext *CanonDef = D->getDeclContext();
10897
10898 bool Found = false;
10899 const Decl *DCanon = D->getCanonicalDecl();
10900
10901 for (auto *RI : D->redecls()) {
10902 if (RI->getLexicalDeclContext() == CanonDef) {
10903 Found = true;
10904 break;
10905 }
10906 }
10907 if (Found)
10908 continue;
10909
10910 // Quick check failed, time to do the slow thing. Note, we can't just
10911 // look up the name of D in CanonDef here, because the member that is
10912 // in CanonDef might not be found by name lookup (it might have been
10913 // replaced by a more recent declaration in the lookup table), and we
10914 // can't necessarily find it in the redeclaration chain because it might
10915 // be merely mergeable, not redeclarable.
10916 llvm::SmallVector<const NamedDecl*, 4> Candidates;
10917 for (auto *CanonMember : CanonDef->decls()) {
10918 if (CanonMember->getCanonicalDecl() == DCanon) {
10919 // This can happen if the declaration is merely mergeable and not
10920 // actually redeclarable (we looked for redeclarations earlier).
10921 //
10922 // FIXME: We should be able to detect this more efficiently, without
10923 // pulling in all of the members of CanonDef.
10924 Found = true;
10925 break;
10926 }
10927 if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
10928 if (ND->getDeclName() == D->getDeclName())
10929 Candidates.push_back(ND);
10930 }
10931
10932 if (!Found) {
10933 // The AST doesn't like TagDecls becoming invalid after they've been
10934 // completed. We only really need to mark FieldDecls as invalid here.
10935 if (!isa<TagDecl>(D))
10936 D->setInvalidDecl();
10937
10938 // Ensure we don't accidentally recursively enter deserialization while
10939 // we're producing our diagnostic.
10940 Deserializing RecursionGuard(this);
10941
10942 std::string CanonDefModule =
10944 cast<Decl>(CanonDef));
10945 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
10947 << CanonDef << CanonDefModule.empty() << CanonDefModule;
10948
10949 if (Candidates.empty())
10950 Diag(cast<Decl>(CanonDef)->getLocation(),
10951 diag::note_module_odr_violation_no_possible_decls) << D;
10952 else {
10953 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
10954 Diag(Candidates[I]->getLocation(),
10955 diag::note_module_odr_violation_possible_decl)
10956 << Candidates[I];
10957 }
10958
10959 DiagnosedOdrMergeFailures.insert(CanonDef);
10960 }
10961 }
10962
10963 if (OdrMergeFailures.empty() && RecordOdrMergeFailures.empty() &&
10964 FunctionOdrMergeFailures.empty() && EnumOdrMergeFailures.empty() &&
10965 ObjCInterfaceOdrMergeFailures.empty() &&
10966 ObjCProtocolOdrMergeFailures.empty())
10967 return;
10968
10969 ODRDiagsEmitter DiagsEmitter(Diags, getContext(),
10970 getPreprocessor().getLangOpts());
10971
10972 // Issue any pending ODR-failure diagnostics.
10973 for (auto &Merge : OdrMergeFailures) {
10974 // If we've already pointed out a specific problem with this class, don't
10975 // bother issuing a general "something's different" diagnostic.
10976 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
10977 continue;
10978
10979 bool Diagnosed = false;
10980 CXXRecordDecl *FirstRecord = Merge.first;
10981 for (auto &RecordPair : Merge.second) {
10982 if (DiagsEmitter.diagnoseMismatch(FirstRecord, RecordPair.first,
10983 RecordPair.second)) {
10984 Diagnosed = true;
10985 break;
10986 }
10987 }
10988
10989 if (!Diagnosed) {
10990 // All definitions are updates to the same declaration. This happens if a
10991 // module instantiates the declaration of a class template specialization
10992 // and two or more other modules instantiate its definition.
10993 //
10994 // FIXME: Indicate which modules had instantiations of this definition.
10995 // FIXME: How can this even happen?
10996 Diag(Merge.first->getLocation(),
10997 diag::err_module_odr_violation_different_instantiations)
10998 << Merge.first;
10999 }
11000 }
11001
11002 // Issue any pending ODR-failure diagnostics for RecordDecl in C/ObjC. Note
11003 // that in C++ this is done as a part of CXXRecordDecl ODR checking.
11004 for (auto &Merge : RecordOdrMergeFailures) {
11005 // If we've already pointed out a specific problem with this class, don't
11006 // bother issuing a general "something's different" diagnostic.
11007 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
11008 continue;
11009
11010 RecordDecl *FirstRecord = Merge.first;
11011 bool Diagnosed = false;
11012 for (auto *SecondRecord : Merge.second) {
11013 if (DiagsEmitter.diagnoseMismatch(FirstRecord, SecondRecord)) {
11014 Diagnosed = true;
11015 break;
11016 }
11017 }
11018 (void)Diagnosed;
11019 assert(Diagnosed && "Unable to emit ODR diagnostic.");
11020 }
11021
11022 // Issue ODR failures diagnostics for functions.
11023 for (auto &Merge : FunctionOdrMergeFailures) {
11024 FunctionDecl *FirstFunction = Merge.first;
11025 bool Diagnosed = false;
11026 for (auto &SecondFunction : Merge.second) {
11027 if (DiagsEmitter.diagnoseMismatch(FirstFunction, SecondFunction)) {
11028 Diagnosed = true;
11029 break;
11030 }
11031 }
11032 (void)Diagnosed;
11033 assert(Diagnosed && "Unable to emit ODR diagnostic.");
11034 }
11035
11036 // Issue ODR failures diagnostics for enums.
11037 for (auto &Merge : EnumOdrMergeFailures) {
11038 // If we've already pointed out a specific problem with this enum, don't
11039 // bother issuing a general "something's different" diagnostic.
11040 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
11041 continue;
11042
11043 EnumDecl *FirstEnum = Merge.first;
11044 bool Diagnosed = false;
11045 for (auto &SecondEnum : Merge.second) {
11046 if (DiagsEmitter.diagnoseMismatch(FirstEnum, SecondEnum)) {
11047 Diagnosed = true;
11048 break;
11049 }
11050 }
11051 (void)Diagnosed;
11052 assert(Diagnosed && "Unable to emit ODR diagnostic.");
11053 }
11054
11055 for (auto &Merge : ObjCInterfaceOdrMergeFailures) {
11056 // If we've already pointed out a specific problem with this interface,
11057 // don't bother issuing a general "something's different" diagnostic.
11058 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
11059 continue;
11060
11061 bool Diagnosed = false;
11062 ObjCInterfaceDecl *FirstID = Merge.first;
11063 for (auto &InterfacePair : Merge.second) {
11064 if (DiagsEmitter.diagnoseMismatch(FirstID, InterfacePair.first,
11065 InterfacePair.second)) {
11066 Diagnosed = true;
11067 break;
11068 }
11069 }
11070 (void)Diagnosed;
11071 assert(Diagnosed && "Unable to emit ODR diagnostic.");
11072 }
11073
11074 for (auto &Merge : ObjCProtocolOdrMergeFailures) {
11075 // If we've already pointed out a specific problem with this protocol,
11076 // don't bother issuing a general "something's different" diagnostic.
11077 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
11078 continue;
11079
11080 ObjCProtocolDecl *FirstProtocol = Merge.first;
11081 bool Diagnosed = false;
11082 for (auto &ProtocolPair : Merge.second) {
11083 if (DiagsEmitter.diagnoseMismatch(FirstProtocol, ProtocolPair.first,
11084 ProtocolPair.second)) {
11085 Diagnosed = true;
11086 break;
11087 }
11088 }
11089 (void)Diagnosed;
11090 assert(Diagnosed && "Unable to emit ODR diagnostic.");
11091 }
11092}
11093
11095 if (llvm::Timer *T = ReadTimer.get();
11096 ++NumCurrentElementsDeserializing == 1 && T)
11097 ReadTimeRegion.emplace(T);
11098}
11099
11101 assert(NumCurrentElementsDeserializing &&
11102 "FinishedDeserializing not paired with StartedDeserializing");
11103 if (NumCurrentElementsDeserializing == 1) {
11104 // We decrease NumCurrentElementsDeserializing only after pending actions
11105 // are finished, to avoid recursively re-calling finishPendingActions().
11106 finishPendingActions();
11107 }
11108 --NumCurrentElementsDeserializing;
11109
11110 if (NumCurrentElementsDeserializing == 0) {
11111 {
11112 // Guard variable to avoid recursively entering the process of passing
11113 // decls to consumer.
11114 SaveAndRestore GuardPassingDeclsToConsumer(CanPassDeclsToConsumer,
11115 /*NewValue=*/false);
11116
11117 // Propagate exception specification and deduced type updates along
11118 // redeclaration chains.
11119 //
11120 // We do this now rather than in finishPendingActions because we want to
11121 // be able to walk the complete redeclaration chains of the updated decls.
11122 while (!PendingExceptionSpecUpdates.empty() ||
11123 !PendingDeducedTypeUpdates.empty() ||
11124 !PendingUndeducedFunctionDecls.empty()) {
11125 auto ESUpdates = std::move(PendingExceptionSpecUpdates);
11126 PendingExceptionSpecUpdates.clear();
11127 for (auto Update : ESUpdates) {
11128 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
11129 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
11130 auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
11131 if (auto *Listener = getContext().getASTMutationListener())
11132 Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
11133 for (auto *Redecl : Update.second->redecls())
11135 }
11136
11137 auto DTUpdates = std::move(PendingDeducedTypeUpdates);
11138 PendingDeducedTypeUpdates.clear();
11139 for (auto Update : DTUpdates) {
11140 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
11141 // FIXME: If the return type is already deduced, check that it
11142 // matches.
11144 Update.second);
11145 }
11146
11147 auto UDTUpdates = std::move(PendingUndeducedFunctionDecls);
11148 PendingUndeducedFunctionDecls.clear();
11149 // We hope we can find the deduced type for the functions by iterating
11150 // redeclarations in other modules.
11151 for (FunctionDecl *UndeducedFD : UDTUpdates)
11152 (void)UndeducedFD->getMostRecentDecl();
11153 }
11154
11155 ReadTimeRegion.reset();
11156
11157 diagnoseOdrViolations();
11158 }
11159
11160 // We are not in recursive loading, so it's safe to pass the "interesting"
11161 // decls to the consumer.
11162 if (Consumer)
11163 PassInterestingDeclsToConsumer();
11164 }
11165}
11166
11167void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
11168 if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) {
11169 // Remove any fake results before adding any real ones.
11170 auto It = PendingFakeLookupResults.find(II);
11171 if (It != PendingFakeLookupResults.end()) {
11172 for (auto *ND : It->second)
11173 SemaObj->IdResolver.RemoveDecl(ND);
11174 // FIXME: this works around module+PCH performance issue.
11175 // Rather than erase the result from the map, which is O(n), just clear
11176 // the vector of NamedDecls.
11177 It->second.clear();
11178 }
11179 }
11180
11181 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
11182 SemaObj->TUScope->AddDecl(D);
11183 } else if (SemaObj->TUScope) {
11184 // Adding the decl to IdResolver may have failed because it was already in
11185 // (even though it was not added in scope). If it is already in, make sure
11186 // it gets in the scope as well.
11187 if (llvm::is_contained(SemaObj->IdResolver.decls(Name), D))
11188 SemaObj->TUScope->AddDecl(D);
11189 }
11190}
11191
11193 ASTContext *Context,
11194 const PCHContainerReader &PCHContainerRdr,
11195 const CodeGenOptions &CodeGenOpts,
11196 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
11197 StringRef isysroot,
11198 DisableValidationForModuleKind DisableValidationKind,
11199 bool AllowASTWithCompilerErrors,
11200 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
11201 bool ForceValidateUserInputs,
11202 bool ValidateASTInputFilesContent, bool UseGlobalIndex,
11203 std::unique_ptr<llvm::Timer> ReadTimer)
11204 : Listener(bool(DisableValidationKind & DisableValidationForModuleKind::PCH)
11206 : cast<ASTReaderListener>(new PCHValidator(PP, *this))),
11207 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
11208 PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()),
11209 StackHandler(Diags), PP(PP), ContextObj(Context),
11210 CodeGenOpts(CodeGenOpts),
11211 ModuleMgr(PP.getFileManager(), ModCache, PCHContainerRdr,
11212 PP.getHeaderSearchInfo()),
11213 DummyIdResolver(PP), ReadTimer(std::move(ReadTimer)), isysroot(isysroot),
11214 DisableValidationKind(DisableValidationKind),
11215 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
11216 AllowConfigurationMismatch(AllowConfigurationMismatch),
11217 ValidateSystemInputs(ValidateSystemInputs),
11218 ForceValidateUserInputs(ForceValidateUserInputs),
11219 ValidateASTInputFilesContent(ValidateASTInputFilesContent),
11220 UseGlobalIndex(UseGlobalIndex), CurrSwitchCaseStmts(&SwitchCaseStmts) {
11221 SourceMgr.setExternalSLocEntrySource(this);
11222
11223 PathBuf.reserve(256);
11224
11225 for (const auto &Ext : Extensions) {
11226 auto BlockName = Ext->getExtensionMetadata().BlockName;
11227 auto Known = ModuleFileExtensions.find(BlockName);
11228 if (Known != ModuleFileExtensions.end()) {
11229 Diags.Report(diag::warn_duplicate_module_file_extension)
11230 << BlockName;
11231 continue;
11232 }
11233
11234 ModuleFileExtensions.insert({BlockName, Ext});
11235 }
11236}
11237
11239 if (OwnsDeserializationListener)
11240 delete DeserializationListener;
11241}
11242
11244 return SemaObj ? SemaObj->IdResolver : DummyIdResolver;
11245}
11246
11248 unsigned AbbrevID) {
11249 Idx = 0;
11250 Record.clear();
11251 return Cursor.readRecord(AbbrevID, Record);
11252}
11253//===----------------------------------------------------------------------===//
11254//// OMPClauseReader implementation
11255////===----------------------------------------------------------------------===//
11256
11257// This has to be in namespace clang because it's friended by all
11258// of the OMP clauses.
11259namespace clang {
11260
11261class OMPClauseReader : public OMPClauseVisitor<OMPClauseReader> {
11262 ASTRecordReader &Record;
11263 ASTContext &Context;
11264
11265public:
11267 : Record(Record), Context(Record.getContext()) {}
11268#define GEN_CLANG_CLAUSE_CLASS
11269#define CLAUSE_CLASS(Enum, Str, Class) void Visit##Class(Class *C);
11270#include "llvm/Frontend/OpenMP/OMP.inc"
11274};
11275
11276} // end namespace clang
11277
11281
11283 OMPClause *C = nullptr;
11284 switch (llvm::omp::Clause(Record.readInt())) {
11285 case llvm::omp::OMPC_if:
11286 C = new (Context) OMPIfClause();
11287 break;
11288 case llvm::omp::OMPC_final:
11289 C = new (Context) OMPFinalClause();
11290 break;
11291 case llvm::omp::OMPC_num_threads:
11292 C = new (Context) OMPNumThreadsClause();
11293 break;
11294 case llvm::omp::OMPC_safelen:
11295 C = new (Context) OMPSafelenClause();
11296 break;
11297 case llvm::omp::OMPC_simdlen:
11298 C = new (Context) OMPSimdlenClause();
11299 break;
11300 case llvm::omp::OMPC_sizes: {
11301 unsigned NumSizes = Record.readInt();
11302 C = OMPSizesClause::CreateEmpty(Context, NumSizes);
11303 break;
11304 }
11305 case llvm::omp::OMPC_permutation: {
11306 unsigned NumLoops = Record.readInt();
11307 C = OMPPermutationClause::CreateEmpty(Context, NumLoops);
11308 break;
11309 }
11310 case llvm::omp::OMPC_full:
11311 C = OMPFullClause::CreateEmpty(Context);
11312 break;
11313 case llvm::omp::OMPC_partial:
11315 break;
11316 case llvm::omp::OMPC_looprange:
11318 break;
11319 case llvm::omp::OMPC_allocator:
11320 C = new (Context) OMPAllocatorClause();
11321 break;
11322 case llvm::omp::OMPC_collapse:
11323 C = new (Context) OMPCollapseClause();
11324 break;
11325 case llvm::omp::OMPC_default:
11326 C = new (Context) OMPDefaultClause();
11327 break;
11328 case llvm::omp::OMPC_proc_bind:
11329 C = new (Context) OMPProcBindClause();
11330 break;
11331 case llvm::omp::OMPC_schedule:
11332 C = new (Context) OMPScheduleClause();
11333 break;
11334 case llvm::omp::OMPC_ordered:
11335 C = OMPOrderedClause::CreateEmpty(Context, Record.readInt());
11336 break;
11337 case llvm::omp::OMPC_nowait:
11338 C = new (Context) OMPNowaitClause();
11339 break;
11340 case llvm::omp::OMPC_untied:
11341 C = new (Context) OMPUntiedClause();
11342 break;
11343 case llvm::omp::OMPC_mergeable:
11344 C = new (Context) OMPMergeableClause();
11345 break;
11346 case llvm::omp::OMPC_threadset:
11347 C = new (Context) OMPThreadsetClause();
11348 break;
11349 case llvm::omp::OMPC_read:
11350 C = new (Context) OMPReadClause();
11351 break;
11352 case llvm::omp::OMPC_write:
11353 C = new (Context) OMPWriteClause();
11354 break;
11355 case llvm::omp::OMPC_update:
11356 C = OMPUpdateClause::CreateEmpty(Context, Record.readInt());
11357 break;
11358 case llvm::omp::OMPC_capture:
11359 C = new (Context) OMPCaptureClause();
11360 break;
11361 case llvm::omp::OMPC_compare:
11362 C = new (Context) OMPCompareClause();
11363 break;
11364 case llvm::omp::OMPC_fail:
11365 C = new (Context) OMPFailClause();
11366 break;
11367 case llvm::omp::OMPC_seq_cst:
11368 C = new (Context) OMPSeqCstClause();
11369 break;
11370 case llvm::omp::OMPC_acq_rel:
11371 C = new (Context) OMPAcqRelClause();
11372 break;
11373 case llvm::omp::OMPC_absent: {
11374 unsigned NumKinds = Record.readInt();
11375 C = OMPAbsentClause::CreateEmpty(Context, NumKinds);
11376 break;
11377 }
11378 case llvm::omp::OMPC_holds:
11379 C = new (Context) OMPHoldsClause();
11380 break;
11381 case llvm::omp::OMPC_contains: {
11382 unsigned NumKinds = Record.readInt();
11383 C = OMPContainsClause::CreateEmpty(Context, NumKinds);
11384 break;
11385 }
11386 case llvm::omp::OMPC_no_openmp:
11387 C = new (Context) OMPNoOpenMPClause();
11388 break;
11389 case llvm::omp::OMPC_no_openmp_routines:
11390 C = new (Context) OMPNoOpenMPRoutinesClause();
11391 break;
11392 case llvm::omp::OMPC_no_openmp_constructs:
11393 C = new (Context) OMPNoOpenMPConstructsClause();
11394 break;
11395 case llvm::omp::OMPC_no_parallelism:
11396 C = new (Context) OMPNoParallelismClause();
11397 break;
11398 case llvm::omp::OMPC_acquire:
11399 C = new (Context) OMPAcquireClause();
11400 break;
11401 case llvm::omp::OMPC_release:
11402 C = new (Context) OMPReleaseClause();
11403 break;
11404 case llvm::omp::OMPC_relaxed:
11405 C = new (Context) OMPRelaxedClause();
11406 break;
11407 case llvm::omp::OMPC_weak:
11408 C = new (Context) OMPWeakClause();
11409 break;
11410 case llvm::omp::OMPC_threads:
11411 C = new (Context) OMPThreadsClause();
11412 break;
11413 case llvm::omp::OMPC_simd:
11414 C = new (Context) OMPSIMDClause();
11415 break;
11416 case llvm::omp::OMPC_nogroup:
11417 C = new (Context) OMPNogroupClause();
11418 break;
11419 case llvm::omp::OMPC_unified_address:
11420 C = new (Context) OMPUnifiedAddressClause();
11421 break;
11422 case llvm::omp::OMPC_unified_shared_memory:
11423 C = new (Context) OMPUnifiedSharedMemoryClause();
11424 break;
11425 case llvm::omp::OMPC_reverse_offload:
11426 C = new (Context) OMPReverseOffloadClause();
11427 break;
11428 case llvm::omp::OMPC_dynamic_allocators:
11429 C = new (Context) OMPDynamicAllocatorsClause();
11430 break;
11431 case llvm::omp::OMPC_atomic_default_mem_order:
11432 C = new (Context) OMPAtomicDefaultMemOrderClause();
11433 break;
11434 case llvm::omp::OMPC_self_maps:
11435 C = new (Context) OMPSelfMapsClause();
11436 break;
11437 case llvm::omp::OMPC_at:
11438 C = new (Context) OMPAtClause();
11439 break;
11440 case llvm::omp::OMPC_severity:
11441 C = new (Context) OMPSeverityClause();
11442 break;
11443 case llvm::omp::OMPC_message:
11444 C = new (Context) OMPMessageClause();
11445 break;
11446 case llvm::omp::OMPC_private:
11447 C = OMPPrivateClause::CreateEmpty(Context, Record.readInt());
11448 break;
11449 case llvm::omp::OMPC_firstprivate:
11450 C = OMPFirstprivateClause::CreateEmpty(Context, Record.readInt());
11451 break;
11452 case llvm::omp::OMPC_lastprivate:
11453 C = OMPLastprivateClause::CreateEmpty(Context, Record.readInt());
11454 break;
11455 case llvm::omp::OMPC_shared:
11456 C = OMPSharedClause::CreateEmpty(Context, Record.readInt());
11457 break;
11458 case llvm::omp::OMPC_reduction: {
11459 unsigned N = Record.readInt();
11460 auto Modifier = Record.readEnum<OpenMPReductionClauseModifier>();
11461 C = OMPReductionClause::CreateEmpty(Context, N, Modifier);
11462 break;
11463 }
11464 case llvm::omp::OMPC_task_reduction:
11465 C = OMPTaskReductionClause::CreateEmpty(Context, Record.readInt());
11466 break;
11467 case llvm::omp::OMPC_in_reduction:
11468 C = OMPInReductionClause::CreateEmpty(Context, Record.readInt());
11469 break;
11470 case llvm::omp::OMPC_linear:
11471 C = OMPLinearClause::CreateEmpty(Context, Record.readInt());
11472 break;
11473 case llvm::omp::OMPC_aligned:
11474 C = OMPAlignedClause::CreateEmpty(Context, Record.readInt());
11475 break;
11476 case llvm::omp::OMPC_copyin:
11477 C = OMPCopyinClause::CreateEmpty(Context, Record.readInt());
11478 break;
11479 case llvm::omp::OMPC_copyprivate:
11480 C = OMPCopyprivateClause::CreateEmpty(Context, Record.readInt());
11481 break;
11482 case llvm::omp::OMPC_flush:
11483 C = OMPFlushClause::CreateEmpty(Context, Record.readInt());
11484 break;
11485 case llvm::omp::OMPC_depobj:
11487 break;
11488 case llvm::omp::OMPC_depend: {
11489 unsigned NumVars = Record.readInt();
11490 unsigned NumLoops = Record.readInt();
11491 C = OMPDependClause::CreateEmpty(Context, NumVars, NumLoops);
11492 break;
11493 }
11494 case llvm::omp::OMPC_device:
11495 C = new (Context) OMPDeviceClause();
11496 break;
11497 case llvm::omp::OMPC_map: {
11499 Sizes.NumVars = Record.readInt();
11500 Sizes.NumUniqueDeclarations = Record.readInt();
11501 Sizes.NumComponentLists = Record.readInt();
11502 Sizes.NumComponents = Record.readInt();
11503 C = OMPMapClause::CreateEmpty(Context, Sizes);
11504 break;
11505 }
11506 case llvm::omp::OMPC_num_teams:
11507 C = OMPNumTeamsClause::CreateEmpty(Context, Record.readInt());
11508 break;
11509 case llvm::omp::OMPC_thread_limit:
11510 C = OMPThreadLimitClause::CreateEmpty(Context, Record.readInt());
11511 break;
11512 case llvm::omp::OMPC_priority:
11513 C = new (Context) OMPPriorityClause();
11514 break;
11515 case llvm::omp::OMPC_grainsize:
11516 C = new (Context) OMPGrainsizeClause();
11517 break;
11518 case llvm::omp::OMPC_num_tasks:
11519 C = new (Context) OMPNumTasksClause();
11520 break;
11521 case llvm::omp::OMPC_hint:
11522 C = new (Context) OMPHintClause();
11523 break;
11524 case llvm::omp::OMPC_dist_schedule:
11525 C = new (Context) OMPDistScheduleClause();
11526 break;
11527 case llvm::omp::OMPC_defaultmap:
11528 C = new (Context) OMPDefaultmapClause();
11529 break;
11530 case llvm::omp::OMPC_to: {
11532 Sizes.NumVars = Record.readInt();
11533 Sizes.NumUniqueDeclarations = Record.readInt();
11534 Sizes.NumComponentLists = Record.readInt();
11535 Sizes.NumComponents = Record.readInt();
11536 C = OMPToClause::CreateEmpty(Context, Sizes);
11537 break;
11538 }
11539 case llvm::omp::OMPC_from: {
11541 Sizes.NumVars = Record.readInt();
11542 Sizes.NumUniqueDeclarations = Record.readInt();
11543 Sizes.NumComponentLists = Record.readInt();
11544 Sizes.NumComponents = Record.readInt();
11545 C = OMPFromClause::CreateEmpty(Context, Sizes);
11546 break;
11547 }
11548 case llvm::omp::OMPC_use_device_ptr: {
11550 Sizes.NumVars = Record.readInt();
11551 Sizes.NumUniqueDeclarations = Record.readInt();
11552 Sizes.NumComponentLists = Record.readInt();
11553 Sizes.NumComponents = Record.readInt();
11554 C = OMPUseDevicePtrClause::CreateEmpty(Context, Sizes);
11555 break;
11556 }
11557 case llvm::omp::OMPC_use_device_addr: {
11559 Sizes.NumVars = Record.readInt();
11560 Sizes.NumUniqueDeclarations = Record.readInt();
11561 Sizes.NumComponentLists = Record.readInt();
11562 Sizes.NumComponents = Record.readInt();
11563 C = OMPUseDeviceAddrClause::CreateEmpty(Context, Sizes);
11564 break;
11565 }
11566 case llvm::omp::OMPC_is_device_ptr: {
11568 Sizes.NumVars = Record.readInt();
11569 Sizes.NumUniqueDeclarations = Record.readInt();
11570 Sizes.NumComponentLists = Record.readInt();
11571 Sizes.NumComponents = Record.readInt();
11572 C = OMPIsDevicePtrClause::CreateEmpty(Context, Sizes);
11573 break;
11574 }
11575 case llvm::omp::OMPC_has_device_addr: {
11577 Sizes.NumVars = Record.readInt();
11578 Sizes.NumUniqueDeclarations = Record.readInt();
11579 Sizes.NumComponentLists = Record.readInt();
11580 Sizes.NumComponents = Record.readInt();
11581 C = OMPHasDeviceAddrClause::CreateEmpty(Context, Sizes);
11582 break;
11583 }
11584 case llvm::omp::OMPC_allocate:
11585 C = OMPAllocateClause::CreateEmpty(Context, Record.readInt());
11586 break;
11587 case llvm::omp::OMPC_nontemporal:
11588 C = OMPNontemporalClause::CreateEmpty(Context, Record.readInt());
11589 break;
11590 case llvm::omp::OMPC_inclusive:
11591 C = OMPInclusiveClause::CreateEmpty(Context, Record.readInt());
11592 break;
11593 case llvm::omp::OMPC_exclusive:
11594 C = OMPExclusiveClause::CreateEmpty(Context, Record.readInt());
11595 break;
11596 case llvm::omp::OMPC_order:
11597 C = new (Context) OMPOrderClause();
11598 break;
11599 case llvm::omp::OMPC_init:
11600 C = OMPInitClause::CreateEmpty(Context, Record.readInt());
11601 break;
11602 case llvm::omp::OMPC_use:
11603 C = new (Context) OMPUseClause();
11604 break;
11605 case llvm::omp::OMPC_destroy:
11606 C = new (Context) OMPDestroyClause();
11607 break;
11608 case llvm::omp::OMPC_novariants:
11609 C = new (Context) OMPNovariantsClause();
11610 break;
11611 case llvm::omp::OMPC_nocontext:
11612 C = new (Context) OMPNocontextClause();
11613 break;
11614 case llvm::omp::OMPC_detach:
11615 C = new (Context) OMPDetachClause();
11616 break;
11617 case llvm::omp::OMPC_uses_allocators:
11618 C = OMPUsesAllocatorsClause::CreateEmpty(Context, Record.readInt());
11619 break;
11620 case llvm::omp::OMPC_affinity:
11621 C = OMPAffinityClause::CreateEmpty(Context, Record.readInt());
11622 break;
11623 case llvm::omp::OMPC_filter:
11624 C = new (Context) OMPFilterClause();
11625 break;
11626 case llvm::omp::OMPC_bind:
11627 C = OMPBindClause::CreateEmpty(Context);
11628 break;
11629 case llvm::omp::OMPC_align:
11630 C = new (Context) OMPAlignClause();
11631 break;
11632 case llvm::omp::OMPC_ompx_dyn_cgroup_mem:
11633 C = new (Context) OMPXDynCGroupMemClause();
11634 break;
11635 case llvm::omp::OMPC_dyn_groupprivate:
11636 C = new (Context) OMPDynGroupprivateClause();
11637 break;
11638 case llvm::omp::OMPC_doacross: {
11639 unsigned NumVars = Record.readInt();
11640 unsigned NumLoops = Record.readInt();
11641 C = OMPDoacrossClause::CreateEmpty(Context, NumVars, NumLoops);
11642 break;
11643 }
11644 case llvm::omp::OMPC_ompx_attribute:
11645 C = new (Context) OMPXAttributeClause();
11646 break;
11647 case llvm::omp::OMPC_ompx_bare:
11648 C = new (Context) OMPXBareClause();
11649 break;
11650#define OMP_CLAUSE_NO_CLASS(Enum, Str) \
11651 case llvm::omp::Enum: \
11652 break;
11653#include "llvm/Frontend/OpenMP/OMPKinds.def"
11654 default:
11655 break;
11656 }
11657 assert(C && "Unknown OMPClause type");
11658
11659 Visit(C);
11660 C->setLocStart(Record.readSourceLocation());
11661 C->setLocEnd(Record.readSourceLocation());
11662
11663 return C;
11664}
11665
11667 C->setPreInitStmt(Record.readSubStmt(),
11668 static_cast<OpenMPDirectiveKind>(Record.readInt()));
11669}
11670
11673 C->setPostUpdateExpr(Record.readSubExpr());
11674}
11675
11676void OMPClauseReader::VisitOMPIfClause(OMPIfClause *C) {
11678 C->setNameModifier(static_cast<OpenMPDirectiveKind>(Record.readInt()));
11679 C->setNameModifierLoc(Record.readSourceLocation());
11680 C->setColonLoc(Record.readSourceLocation());
11681 C->setCondition(Record.readSubExpr());
11682 C->setLParenLoc(Record.readSourceLocation());
11683}
11684
11685void OMPClauseReader::VisitOMPFinalClause(OMPFinalClause *C) {
11687 C->setCondition(Record.readSubExpr());
11688 C->setLParenLoc(Record.readSourceLocation());
11689}
11690
11691void OMPClauseReader::VisitOMPNumThreadsClause(OMPNumThreadsClause *C) {
11693 C->setModifier(Record.readEnum<OpenMPNumThreadsClauseModifier>());
11694 C->setNumThreads(Record.readSubExpr());
11695 C->setModifierLoc(Record.readSourceLocation());
11696 C->setLParenLoc(Record.readSourceLocation());
11697}
11698
11699void OMPClauseReader::VisitOMPSafelenClause(OMPSafelenClause *C) {
11700 C->setSafelen(Record.readSubExpr());
11701 C->setLParenLoc(Record.readSourceLocation());
11702}
11703
11704void OMPClauseReader::VisitOMPSimdlenClause(OMPSimdlenClause *C) {
11705 C->setSimdlen(Record.readSubExpr());
11706 C->setLParenLoc(Record.readSourceLocation());
11707}
11708
11709void OMPClauseReader::VisitOMPSizesClause(OMPSizesClause *C) {
11710 for (Expr *&E : C->getSizesRefs())
11711 E = Record.readSubExpr();
11712 C->setLParenLoc(Record.readSourceLocation());
11713}
11714
11715void OMPClauseReader::VisitOMPPermutationClause(OMPPermutationClause *C) {
11716 for (Expr *&E : C->getArgsRefs())
11717 E = Record.readSubExpr();
11718 C->setLParenLoc(Record.readSourceLocation());
11719}
11720
11721void OMPClauseReader::VisitOMPFullClause(OMPFullClause *C) {}
11722
11723void OMPClauseReader::VisitOMPPartialClause(OMPPartialClause *C) {
11724 C->setFactor(Record.readSubExpr());
11725 C->setLParenLoc(Record.readSourceLocation());
11726}
11727
11728void OMPClauseReader::VisitOMPLoopRangeClause(OMPLoopRangeClause *C) {
11729 C->setFirst(Record.readSubExpr());
11730 C->setCount(Record.readSubExpr());
11731 C->setLParenLoc(Record.readSourceLocation());
11732 C->setFirstLoc(Record.readSourceLocation());
11733 C->setCountLoc(Record.readSourceLocation());
11734}
11735
11736void OMPClauseReader::VisitOMPAllocatorClause(OMPAllocatorClause *C) {
11737 C->setAllocator(Record.readExpr());
11738 C->setLParenLoc(Record.readSourceLocation());
11739}
11740
11741void OMPClauseReader::VisitOMPCollapseClause(OMPCollapseClause *C) {
11742 C->setNumForLoops(Record.readSubExpr());
11743 C->setLParenLoc(Record.readSourceLocation());
11744}
11745
11746void OMPClauseReader::VisitOMPDefaultClause(OMPDefaultClause *C) {
11747 C->setDefaultKind(static_cast<llvm::omp::DefaultKind>(Record.readInt()));
11748 C->setLParenLoc(Record.readSourceLocation());
11749 C->setDefaultKindKwLoc(Record.readSourceLocation());
11750 C->setDefaultVariableCategory(
11751 Record.readEnum<OpenMPDefaultClauseVariableCategory>());
11752 C->setDefaultVariableCategoryLocation(Record.readSourceLocation());
11753}
11754
11755// Read the parameter of threadset clause. This will have been saved when
11756// OMPClauseWriter is called.
11757void OMPClauseReader::VisitOMPThreadsetClause(OMPThreadsetClause *C) {
11758 C->setLParenLoc(Record.readSourceLocation());
11759 SourceLocation ThreadsetKindLoc = Record.readSourceLocation();
11760 C->setThreadsetKindLoc(ThreadsetKindLoc);
11761 OpenMPThreadsetKind TKind =
11762 static_cast<OpenMPThreadsetKind>(Record.readInt());
11763 C->setThreadsetKind(TKind);
11764}
11765
11766void OMPClauseReader::VisitOMPProcBindClause(OMPProcBindClause *C) {
11767 C->setProcBindKind(static_cast<llvm::omp::ProcBindKind>(Record.readInt()));
11768 C->setLParenLoc(Record.readSourceLocation());
11769 C->setProcBindKindKwLoc(Record.readSourceLocation());
11770}
11771
11772void OMPClauseReader::VisitOMPScheduleClause(OMPScheduleClause *C) {
11774 C->setScheduleKind(
11775 static_cast<OpenMPScheduleClauseKind>(Record.readInt()));
11776 C->setFirstScheduleModifier(
11777 static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
11778 C->setSecondScheduleModifier(
11779 static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
11780 C->setChunkSize(Record.readSubExpr());
11781 C->setLParenLoc(Record.readSourceLocation());
11782 C->setFirstScheduleModifierLoc(Record.readSourceLocation());
11783 C->setSecondScheduleModifierLoc(Record.readSourceLocation());
11784 C->setScheduleKindLoc(Record.readSourceLocation());
11785 C->setCommaLoc(Record.readSourceLocation());
11786}
11787
11788void OMPClauseReader::VisitOMPOrderedClause(OMPOrderedClause *C) {
11789 C->setNumForLoops(Record.readSubExpr());
11790 for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
11791 C->setLoopNumIterations(I, Record.readSubExpr());
11792 for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
11793 C->setLoopCounter(I, Record.readSubExpr());
11794 C->setLParenLoc(Record.readSourceLocation());
11795}
11796
11797void OMPClauseReader::VisitOMPDetachClause(OMPDetachClause *C) {
11798 C->setEventHandler(Record.readSubExpr());
11799 C->setLParenLoc(Record.readSourceLocation());
11800}
11801
11802void OMPClauseReader::VisitOMPNowaitClause(OMPNowaitClause *C) {
11803 C->setCondition(Record.readSubExpr());
11804 C->setLParenLoc(Record.readSourceLocation());
11805}
11806
11807void OMPClauseReader::VisitOMPUntiedClause(OMPUntiedClause *) {}
11808
11809void OMPClauseReader::VisitOMPMergeableClause(OMPMergeableClause *) {}
11810
11811void OMPClauseReader::VisitOMPReadClause(OMPReadClause *) {}
11812
11813void OMPClauseReader::VisitOMPWriteClause(OMPWriteClause *) {}
11814
11815void OMPClauseReader::VisitOMPUpdateClause(OMPUpdateClause *C) {
11816 if (C->isExtended()) {
11817 C->setLParenLoc(Record.readSourceLocation());
11818 C->setArgumentLoc(Record.readSourceLocation());
11819 C->setDependencyKind(Record.readEnum<OpenMPDependClauseKind>());
11820 }
11821}
11822
11823void OMPClauseReader::VisitOMPCaptureClause(OMPCaptureClause *) {}
11824
11825void OMPClauseReader::VisitOMPCompareClause(OMPCompareClause *) {}
11826
11827// Read the parameter of fail clause. This will have been saved when
11828// OMPClauseWriter is called.
11829void OMPClauseReader::VisitOMPFailClause(OMPFailClause *C) {
11830 C->setLParenLoc(Record.readSourceLocation());
11831 SourceLocation FailParameterLoc = Record.readSourceLocation();
11832 C->setFailParameterLoc(FailParameterLoc);
11833 OpenMPClauseKind CKind = Record.readEnum<OpenMPClauseKind>();
11834 C->setFailParameter(CKind);
11835}
11836
11837void OMPClauseReader::VisitOMPAbsentClause(OMPAbsentClause *C) {
11838 unsigned Count = C->getDirectiveKinds().size();
11839 C->setLParenLoc(Record.readSourceLocation());
11840 llvm::SmallVector<OpenMPDirectiveKind, 4> DKVec;
11841 DKVec.reserve(Count);
11842 for (unsigned I = 0; I < Count; I++) {
11843 DKVec.push_back(Record.readEnum<OpenMPDirectiveKind>());
11844 }
11845 C->setDirectiveKinds(DKVec);
11846}
11847
11848void OMPClauseReader::VisitOMPHoldsClause(OMPHoldsClause *C) {
11849 C->setExpr(Record.readExpr());
11850 C->setLParenLoc(Record.readSourceLocation());
11851}
11852
11853void OMPClauseReader::VisitOMPContainsClause(OMPContainsClause *C) {
11854 unsigned Count = C->getDirectiveKinds().size();
11855 C->setLParenLoc(Record.readSourceLocation());
11856 llvm::SmallVector<OpenMPDirectiveKind, 4> DKVec;
11857 DKVec.reserve(Count);
11858 for (unsigned I = 0; I < Count; I++) {
11859 DKVec.push_back(Record.readEnum<OpenMPDirectiveKind>());
11860 }
11861 C->setDirectiveKinds(DKVec);
11862}
11863
11864void OMPClauseReader::VisitOMPNoOpenMPClause(OMPNoOpenMPClause *) {}
11865
11866void OMPClauseReader::VisitOMPNoOpenMPRoutinesClause(
11868
11869void OMPClauseReader::VisitOMPNoOpenMPConstructsClause(
11871
11872void OMPClauseReader::VisitOMPNoParallelismClause(OMPNoParallelismClause *) {}
11873
11874void OMPClauseReader::VisitOMPSeqCstClause(OMPSeqCstClause *) {}
11875
11876void OMPClauseReader::VisitOMPAcqRelClause(OMPAcqRelClause *) {}
11877
11878void OMPClauseReader::VisitOMPAcquireClause(OMPAcquireClause *) {}
11879
11880void OMPClauseReader::VisitOMPReleaseClause(OMPReleaseClause *) {}
11881
11882void OMPClauseReader::VisitOMPRelaxedClause(OMPRelaxedClause *) {}
11883
11884void OMPClauseReader::VisitOMPWeakClause(OMPWeakClause *) {}
11885
11886void OMPClauseReader::VisitOMPThreadsClause(OMPThreadsClause *) {}
11887
11888void OMPClauseReader::VisitOMPSIMDClause(OMPSIMDClause *) {}
11889
11890void OMPClauseReader::VisitOMPNogroupClause(OMPNogroupClause *) {}
11891
11892void OMPClauseReader::VisitOMPInitClause(OMPInitClause *C) {
11893 unsigned NumVars = C->varlist_size();
11894 SmallVector<Expr *, 16> Vars;
11895 Vars.reserve(NumVars);
11896 for (unsigned I = 0; I != NumVars; ++I)
11897 Vars.push_back(Record.readSubExpr());
11898 C->setVarRefs(Vars);
11899 C->setIsTarget(Record.readBool());
11900 C->setIsTargetSync(Record.readBool());
11901 C->setLParenLoc(Record.readSourceLocation());
11902 C->setVarLoc(Record.readSourceLocation());
11903}
11904
11905void OMPClauseReader::VisitOMPUseClause(OMPUseClause *C) {
11906 C->setInteropVar(Record.readSubExpr());
11907 C->setLParenLoc(Record.readSourceLocation());
11908 C->setVarLoc(Record.readSourceLocation());
11909}
11910
11911void OMPClauseReader::VisitOMPDestroyClause(OMPDestroyClause *C) {
11912 C->setInteropVar(Record.readSubExpr());
11913 C->setLParenLoc(Record.readSourceLocation());
11914 C->setVarLoc(Record.readSourceLocation());
11915}
11916
11917void OMPClauseReader::VisitOMPNovariantsClause(OMPNovariantsClause *C) {
11919 C->setCondition(Record.readSubExpr());
11920 C->setLParenLoc(Record.readSourceLocation());
11921}
11922
11923void OMPClauseReader::VisitOMPNocontextClause(OMPNocontextClause *C) {
11925 C->setCondition(Record.readSubExpr());
11926 C->setLParenLoc(Record.readSourceLocation());
11927}
11928
11929void OMPClauseReader::VisitOMPUnifiedAddressClause(OMPUnifiedAddressClause *) {}
11930
11931void OMPClauseReader::VisitOMPUnifiedSharedMemoryClause(
11933
11934void OMPClauseReader::VisitOMPReverseOffloadClause(OMPReverseOffloadClause *) {}
11935
11936void
11937OMPClauseReader::VisitOMPDynamicAllocatorsClause(OMPDynamicAllocatorsClause *) {
11938}
11939
11940void OMPClauseReader::VisitOMPAtomicDefaultMemOrderClause(
11942 C->setAtomicDefaultMemOrderKind(
11943 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Record.readInt()));
11944 C->setLParenLoc(Record.readSourceLocation());
11945 C->setAtomicDefaultMemOrderKindKwLoc(Record.readSourceLocation());
11946}
11947
11948void OMPClauseReader::VisitOMPSelfMapsClause(OMPSelfMapsClause *) {}
11949
11950void OMPClauseReader::VisitOMPAtClause(OMPAtClause *C) {
11951 C->setAtKind(static_cast<OpenMPAtClauseKind>(Record.readInt()));
11952 C->setLParenLoc(Record.readSourceLocation());
11953 C->setAtKindKwLoc(Record.readSourceLocation());
11954}
11955
11956void OMPClauseReader::VisitOMPSeverityClause(OMPSeverityClause *C) {
11957 C->setSeverityKind(static_cast<OpenMPSeverityClauseKind>(Record.readInt()));
11958 C->setLParenLoc(Record.readSourceLocation());
11959 C->setSeverityKindKwLoc(Record.readSourceLocation());
11960}
11961
11962void OMPClauseReader::VisitOMPMessageClause(OMPMessageClause *C) {
11964 C->setMessageString(Record.readSubExpr());
11965 C->setLParenLoc(Record.readSourceLocation());
11966}
11967
11968void OMPClauseReader::VisitOMPPrivateClause(OMPPrivateClause *C) {
11969 C->setLParenLoc(Record.readSourceLocation());
11970 unsigned NumVars = C->varlist_size();
11971 SmallVector<Expr *, 16> Vars;
11972 Vars.reserve(NumVars);
11973 for (unsigned i = 0; i != NumVars; ++i)
11974 Vars.push_back(Record.readSubExpr());
11975 C->setVarRefs(Vars);
11976 Vars.clear();
11977 for (unsigned i = 0; i != NumVars; ++i)
11978 Vars.push_back(Record.readSubExpr());
11979 C->setPrivateCopies(Vars);
11980}
11981
11982void OMPClauseReader::VisitOMPFirstprivateClause(OMPFirstprivateClause *C) {
11984 C->setLParenLoc(Record.readSourceLocation());
11985 unsigned NumVars = C->varlist_size();
11986 SmallVector<Expr *, 16> Vars;
11987 Vars.reserve(NumVars);
11988 for (unsigned i = 0; i != NumVars; ++i)
11989 Vars.push_back(Record.readSubExpr());
11990 C->setVarRefs(Vars);
11991 Vars.clear();
11992 for (unsigned i = 0; i != NumVars; ++i)
11993 Vars.push_back(Record.readSubExpr());
11994 C->setPrivateCopies(Vars);
11995 Vars.clear();
11996 for (unsigned i = 0; i != NumVars; ++i)
11997 Vars.push_back(Record.readSubExpr());
11998 C->setInits(Vars);
11999}
12000
12001void OMPClauseReader::VisitOMPLastprivateClause(OMPLastprivateClause *C) {
12003 C->setLParenLoc(Record.readSourceLocation());
12004 C->setKind(Record.readEnum<OpenMPLastprivateModifier>());
12005 C->setKindLoc(Record.readSourceLocation());
12006 C->setColonLoc(Record.readSourceLocation());
12007 unsigned NumVars = C->varlist_size();
12008 SmallVector<Expr *, 16> Vars;
12009 Vars.reserve(NumVars);
12010 for (unsigned i = 0; i != NumVars; ++i)
12011 Vars.push_back(Record.readSubExpr());
12012 C->setVarRefs(Vars);
12013 Vars.clear();
12014 for (unsigned i = 0; i != NumVars; ++i)
12015 Vars.push_back(Record.readSubExpr());
12016 C->setPrivateCopies(Vars);
12017 Vars.clear();
12018 for (unsigned i = 0; i != NumVars; ++i)
12019 Vars.push_back(Record.readSubExpr());
12020 C->setSourceExprs(Vars);
12021 Vars.clear();
12022 for (unsigned i = 0; i != NumVars; ++i)
12023 Vars.push_back(Record.readSubExpr());
12024 C->setDestinationExprs(Vars);
12025 Vars.clear();
12026 for (unsigned i = 0; i != NumVars; ++i)
12027 Vars.push_back(Record.readSubExpr());
12028 C->setAssignmentOps(Vars);
12029}
12030
12031void OMPClauseReader::VisitOMPSharedClause(OMPSharedClause *C) {
12032 C->setLParenLoc(Record.readSourceLocation());
12033 unsigned NumVars = C->varlist_size();
12034 SmallVector<Expr *, 16> Vars;
12035 Vars.reserve(NumVars);
12036 for (unsigned i = 0; i != NumVars; ++i)
12037 Vars.push_back(Record.readSubExpr());
12038 C->setVarRefs(Vars);
12039}
12040
12041void OMPClauseReader::VisitOMPReductionClause(OMPReductionClause *C) {
12043 C->setLParenLoc(Record.readSourceLocation());
12044 C->setModifierLoc(Record.readSourceLocation());
12045 C->setColonLoc(Record.readSourceLocation());
12046 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
12047 DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
12048 C->setQualifierLoc(NNSL);
12049 C->setNameInfo(DNI);
12050
12051 unsigned NumVars = C->varlist_size();
12052 SmallVector<Expr *, 16> Vars;
12053 Vars.reserve(NumVars);
12054 for (unsigned i = 0; i != NumVars; ++i)
12055 Vars.push_back(Record.readSubExpr());
12056 C->setVarRefs(Vars);
12057 Vars.clear();
12058 for (unsigned i = 0; i != NumVars; ++i)
12059 Vars.push_back(Record.readSubExpr());
12060 C->setPrivates(Vars);
12061 Vars.clear();
12062 for (unsigned i = 0; i != NumVars; ++i)
12063 Vars.push_back(Record.readSubExpr());
12064 C->setLHSExprs(Vars);
12065 Vars.clear();
12066 for (unsigned i = 0; i != NumVars; ++i)
12067 Vars.push_back(Record.readSubExpr());
12068 C->setRHSExprs(Vars);
12069 Vars.clear();
12070 for (unsigned i = 0; i != NumVars; ++i)
12071 Vars.push_back(Record.readSubExpr());
12072 C->setReductionOps(Vars);
12073 if (C->getModifier() == OMPC_REDUCTION_inscan) {
12074 Vars.clear();
12075 for (unsigned i = 0; i != NumVars; ++i)
12076 Vars.push_back(Record.readSubExpr());
12077 C->setInscanCopyOps(Vars);
12078 Vars.clear();
12079 for (unsigned i = 0; i != NumVars; ++i)
12080 Vars.push_back(Record.readSubExpr());
12081 C->setInscanCopyArrayTemps(Vars);
12082 Vars.clear();
12083 for (unsigned i = 0; i != NumVars; ++i)
12084 Vars.push_back(Record.readSubExpr());
12085 C->setInscanCopyArrayElems(Vars);
12086 }
12087 unsigned NumFlags = Record.readInt();
12088 SmallVector<bool, 16> Flags;
12089 Flags.reserve(NumFlags);
12090 for ([[maybe_unused]] unsigned I : llvm::seq<unsigned>(NumFlags))
12091 Flags.push_back(Record.readInt());
12092 C->setPrivateVariableReductionFlags(Flags);
12093}
12094
12095void OMPClauseReader::VisitOMPTaskReductionClause(OMPTaskReductionClause *C) {
12097 C->setLParenLoc(Record.readSourceLocation());
12098 C->setColonLoc(Record.readSourceLocation());
12099 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
12100 DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
12101 C->setQualifierLoc(NNSL);
12102 C->setNameInfo(DNI);
12103
12104 unsigned NumVars = C->varlist_size();
12105 SmallVector<Expr *, 16> Vars;
12106 Vars.reserve(NumVars);
12107 for (unsigned I = 0; I != NumVars; ++I)
12108 Vars.push_back(Record.readSubExpr());
12109 C->setVarRefs(Vars);
12110 Vars.clear();
12111 for (unsigned I = 0; I != NumVars; ++I)
12112 Vars.push_back(Record.readSubExpr());
12113 C->setPrivates(Vars);
12114 Vars.clear();
12115 for (unsigned I = 0; I != NumVars; ++I)
12116 Vars.push_back(Record.readSubExpr());
12117 C->setLHSExprs(Vars);
12118 Vars.clear();
12119 for (unsigned I = 0; I != NumVars; ++I)
12120 Vars.push_back(Record.readSubExpr());
12121 C->setRHSExprs(Vars);
12122 Vars.clear();
12123 for (unsigned I = 0; I != NumVars; ++I)
12124 Vars.push_back(Record.readSubExpr());
12125 C->setReductionOps(Vars);
12126}
12127
12128void OMPClauseReader::VisitOMPInReductionClause(OMPInReductionClause *C) {
12130 C->setLParenLoc(Record.readSourceLocation());
12131 C->setColonLoc(Record.readSourceLocation());
12132 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
12133 DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
12134 C->setQualifierLoc(NNSL);
12135 C->setNameInfo(DNI);
12136
12137 unsigned NumVars = C->varlist_size();
12138 SmallVector<Expr *, 16> Vars;
12139 Vars.reserve(NumVars);
12140 for (unsigned I = 0; I != NumVars; ++I)
12141 Vars.push_back(Record.readSubExpr());
12142 C->setVarRefs(Vars);
12143 Vars.clear();
12144 for (unsigned I = 0; I != NumVars; ++I)
12145 Vars.push_back(Record.readSubExpr());
12146 C->setPrivates(Vars);
12147 Vars.clear();
12148 for (unsigned I = 0; I != NumVars; ++I)
12149 Vars.push_back(Record.readSubExpr());
12150 C->setLHSExprs(Vars);
12151 Vars.clear();
12152 for (unsigned I = 0; I != NumVars; ++I)
12153 Vars.push_back(Record.readSubExpr());
12154 C->setRHSExprs(Vars);
12155 Vars.clear();
12156 for (unsigned I = 0; I != NumVars; ++I)
12157 Vars.push_back(Record.readSubExpr());
12158 C->setReductionOps(Vars);
12159 Vars.clear();
12160 for (unsigned I = 0; I != NumVars; ++I)
12161 Vars.push_back(Record.readSubExpr());
12162 C->setTaskgroupDescriptors(Vars);
12163}
12164
12165void OMPClauseReader::VisitOMPLinearClause(OMPLinearClause *C) {
12167 C->setLParenLoc(Record.readSourceLocation());
12168 C->setColonLoc(Record.readSourceLocation());
12169 C->setModifier(static_cast<OpenMPLinearClauseKind>(Record.readInt()));
12170 C->setModifierLoc(Record.readSourceLocation());
12171 unsigned NumVars = C->varlist_size();
12172 SmallVector<Expr *, 16> Vars;
12173 Vars.reserve(NumVars);
12174 for (unsigned i = 0; i != NumVars; ++i)
12175 Vars.push_back(Record.readSubExpr());
12176 C->setVarRefs(Vars);
12177 Vars.clear();
12178 for (unsigned i = 0; i != NumVars; ++i)
12179 Vars.push_back(Record.readSubExpr());
12180 C->setPrivates(Vars);
12181 Vars.clear();
12182 for (unsigned i = 0; i != NumVars; ++i)
12183 Vars.push_back(Record.readSubExpr());
12184 C->setInits(Vars);
12185 Vars.clear();
12186 for (unsigned i = 0; i != NumVars; ++i)
12187 Vars.push_back(Record.readSubExpr());
12188 C->setUpdates(Vars);
12189 Vars.clear();
12190 for (unsigned i = 0; i != NumVars; ++i)
12191 Vars.push_back(Record.readSubExpr());
12192 C->setFinals(Vars);
12193 C->setStep(Record.readSubExpr());
12194 C->setCalcStep(Record.readSubExpr());
12195 Vars.clear();
12196 for (unsigned I = 0; I != NumVars + 1; ++I)
12197 Vars.push_back(Record.readSubExpr());
12198 C->setUsedExprs(Vars);
12199}
12200
12201void OMPClauseReader::VisitOMPAlignedClause(OMPAlignedClause *C) {
12202 C->setLParenLoc(Record.readSourceLocation());
12203 C->setColonLoc(Record.readSourceLocation());
12204 unsigned NumVars = C->varlist_size();
12205 SmallVector<Expr *, 16> Vars;
12206 Vars.reserve(NumVars);
12207 for (unsigned i = 0; i != NumVars; ++i)
12208 Vars.push_back(Record.readSubExpr());
12209 C->setVarRefs(Vars);
12210 C->setAlignment(Record.readSubExpr());
12211}
12212
12213void OMPClauseReader::VisitOMPCopyinClause(OMPCopyinClause *C) {
12214 C->setLParenLoc(Record.readSourceLocation());
12215 unsigned NumVars = C->varlist_size();
12216 SmallVector<Expr *, 16> Exprs;
12217 Exprs.reserve(NumVars);
12218 for (unsigned i = 0; i != NumVars; ++i)
12219 Exprs.push_back(Record.readSubExpr());
12220 C->setVarRefs(Exprs);
12221 Exprs.clear();
12222 for (unsigned i = 0; i != NumVars; ++i)
12223 Exprs.push_back(Record.readSubExpr());
12224 C->setSourceExprs(Exprs);
12225 Exprs.clear();
12226 for (unsigned i = 0; i != NumVars; ++i)
12227 Exprs.push_back(Record.readSubExpr());
12228 C->setDestinationExprs(Exprs);
12229 Exprs.clear();
12230 for (unsigned i = 0; i != NumVars; ++i)
12231 Exprs.push_back(Record.readSubExpr());
12232 C->setAssignmentOps(Exprs);
12233}
12234
12235void OMPClauseReader::VisitOMPCopyprivateClause(OMPCopyprivateClause *C) {
12236 C->setLParenLoc(Record.readSourceLocation());
12237 unsigned NumVars = C->varlist_size();
12238 SmallVector<Expr *, 16> Exprs;
12239 Exprs.reserve(NumVars);
12240 for (unsigned i = 0; i != NumVars; ++i)
12241 Exprs.push_back(Record.readSubExpr());
12242 C->setVarRefs(Exprs);
12243 Exprs.clear();
12244 for (unsigned i = 0; i != NumVars; ++i)
12245 Exprs.push_back(Record.readSubExpr());
12246 C->setSourceExprs(Exprs);
12247 Exprs.clear();
12248 for (unsigned i = 0; i != NumVars; ++i)
12249 Exprs.push_back(Record.readSubExpr());
12250 C->setDestinationExprs(Exprs);
12251 Exprs.clear();
12252 for (unsigned i = 0; i != NumVars; ++i)
12253 Exprs.push_back(Record.readSubExpr());
12254 C->setAssignmentOps(Exprs);
12255}
12256
12257void OMPClauseReader::VisitOMPFlushClause(OMPFlushClause *C) {
12258 C->setLParenLoc(Record.readSourceLocation());
12259 unsigned NumVars = C->varlist_size();
12260 SmallVector<Expr *, 16> Vars;
12261 Vars.reserve(NumVars);
12262 for (unsigned i = 0; i != NumVars; ++i)
12263 Vars.push_back(Record.readSubExpr());
12264 C->setVarRefs(Vars);
12265}
12266
12267void OMPClauseReader::VisitOMPDepobjClause(OMPDepobjClause *C) {
12268 C->setDepobj(Record.readSubExpr());
12269 C->setLParenLoc(Record.readSourceLocation());
12270}
12271
12272void OMPClauseReader::VisitOMPDependClause(OMPDependClause *C) {
12273 C->setLParenLoc(Record.readSourceLocation());
12274 C->setModifier(Record.readSubExpr());
12275 C->setDependencyKind(
12276 static_cast<OpenMPDependClauseKind>(Record.readInt()));
12277 C->setDependencyLoc(Record.readSourceLocation());
12278 C->setColonLoc(Record.readSourceLocation());
12279 C->setOmpAllMemoryLoc(Record.readSourceLocation());
12280 unsigned NumVars = C->varlist_size();
12281 SmallVector<Expr *, 16> Vars;
12282 Vars.reserve(NumVars);
12283 for (unsigned I = 0; I != NumVars; ++I)
12284 Vars.push_back(Record.readSubExpr());
12285 C->setVarRefs(Vars);
12286 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
12287 C->setLoopData(I, Record.readSubExpr());
12288}
12289
12290void OMPClauseReader::VisitOMPDeviceClause(OMPDeviceClause *C) {
12292 C->setModifier(Record.readEnum<OpenMPDeviceClauseModifier>());
12293 C->setDevice(Record.readSubExpr());
12294 C->setModifierLoc(Record.readSourceLocation());
12295 C->setLParenLoc(Record.readSourceLocation());
12296}
12297
12298void OMPClauseReader::VisitOMPMapClause(OMPMapClause *C) {
12299 C->setLParenLoc(Record.readSourceLocation());
12300 bool HasIteratorModifier = false;
12301 for (unsigned I = 0; I < NumberOfOMPMapClauseModifiers; ++I) {
12302 C->setMapTypeModifier(
12303 I, static_cast<OpenMPMapModifierKind>(Record.readInt()));
12304 C->setMapTypeModifierLoc(I, Record.readSourceLocation());
12305 if (C->getMapTypeModifier(I) == OMPC_MAP_MODIFIER_iterator)
12306 HasIteratorModifier = true;
12307 }
12308 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
12309 C->setMapperIdInfo(Record.readDeclarationNameInfo());
12310 C->setMapType(
12311 static_cast<OpenMPMapClauseKind>(Record.readInt()));
12312 C->setMapLoc(Record.readSourceLocation());
12313 C->setColonLoc(Record.readSourceLocation());
12314 auto NumVars = C->varlist_size();
12315 auto UniqueDecls = C->getUniqueDeclarationsNum();
12316 auto TotalLists = C->getTotalComponentListNum();
12317 auto TotalComponents = C->getTotalComponentsNum();
12318
12319 SmallVector<Expr *, 16> Vars;
12320 Vars.reserve(NumVars);
12321 for (unsigned i = 0; i != NumVars; ++i)
12322 Vars.push_back(Record.readExpr());
12323 C->setVarRefs(Vars);
12324
12325 SmallVector<Expr *, 16> UDMappers;
12326 UDMappers.reserve(NumVars);
12327 for (unsigned I = 0; I < NumVars; ++I)
12328 UDMappers.push_back(Record.readExpr());
12329 C->setUDMapperRefs(UDMappers);
12330
12331 if (HasIteratorModifier)
12332 C->setIteratorModifier(Record.readExpr());
12333
12334 SmallVector<ValueDecl *, 16> Decls;
12335 Decls.reserve(UniqueDecls);
12336 for (unsigned i = 0; i < UniqueDecls; ++i)
12337 Decls.push_back(Record.readDeclAs<ValueDecl>());
12338 C->setUniqueDecls(Decls);
12339
12340 SmallVector<unsigned, 16> ListsPerDecl;
12341 ListsPerDecl.reserve(UniqueDecls);
12342 for (unsigned i = 0; i < UniqueDecls; ++i)
12343 ListsPerDecl.push_back(Record.readInt());
12344 C->setDeclNumLists(ListsPerDecl);
12345
12346 SmallVector<unsigned, 32> ListSizes;
12347 ListSizes.reserve(TotalLists);
12348 for (unsigned i = 0; i < TotalLists; ++i)
12349 ListSizes.push_back(Record.readInt());
12350 C->setComponentListSizes(ListSizes);
12351
12352 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12353 Components.reserve(TotalComponents);
12354 for (unsigned i = 0; i < TotalComponents; ++i) {
12355 Expr *AssociatedExprPr = Record.readExpr();
12356 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12357 Components.emplace_back(AssociatedExprPr, AssociatedDecl,
12358 /*IsNonContiguous=*/false);
12359 }
12360 C->setComponents(Components, ListSizes);
12361}
12362
12363void OMPClauseReader::VisitOMPAllocateClause(OMPAllocateClause *C) {
12364 C->setFirstAllocateModifier(Record.readEnum<OpenMPAllocateClauseModifier>());
12365 C->setSecondAllocateModifier(Record.readEnum<OpenMPAllocateClauseModifier>());
12366 C->setLParenLoc(Record.readSourceLocation());
12367 C->setColonLoc(Record.readSourceLocation());
12368 C->setAllocator(Record.readSubExpr());
12369 C->setAlignment(Record.readSubExpr());
12370 unsigned NumVars = C->varlist_size();
12371 SmallVector<Expr *, 16> Vars;
12372 Vars.reserve(NumVars);
12373 for (unsigned i = 0; i != NumVars; ++i)
12374 Vars.push_back(Record.readSubExpr());
12375 C->setVarRefs(Vars);
12376}
12377
12378void OMPClauseReader::VisitOMPNumTeamsClause(OMPNumTeamsClause *C) {
12380 C->setLParenLoc(Record.readSourceLocation());
12381 unsigned NumVars = C->varlist_size();
12382 SmallVector<Expr *, 16> Vars;
12383 Vars.reserve(NumVars);
12384 for (unsigned I = 0; I != NumVars; ++I)
12385 Vars.push_back(Record.readSubExpr());
12386 C->setVarRefs(Vars);
12387}
12388
12389void OMPClauseReader::VisitOMPThreadLimitClause(OMPThreadLimitClause *C) {
12391 C->setLParenLoc(Record.readSourceLocation());
12392 unsigned NumVars = C->varlist_size();
12393 SmallVector<Expr *, 16> Vars;
12394 Vars.reserve(NumVars);
12395 for (unsigned I = 0; I != NumVars; ++I)
12396 Vars.push_back(Record.readSubExpr());
12397 C->setVarRefs(Vars);
12398}
12399
12400void OMPClauseReader::VisitOMPPriorityClause(OMPPriorityClause *C) {
12402 C->setPriority(Record.readSubExpr());
12403 C->setLParenLoc(Record.readSourceLocation());
12404}
12405
12406void OMPClauseReader::VisitOMPGrainsizeClause(OMPGrainsizeClause *C) {
12408 C->setModifier(Record.readEnum<OpenMPGrainsizeClauseModifier>());
12409 C->setGrainsize(Record.readSubExpr());
12410 C->setModifierLoc(Record.readSourceLocation());
12411 C->setLParenLoc(Record.readSourceLocation());
12412}
12413
12414void OMPClauseReader::VisitOMPNumTasksClause(OMPNumTasksClause *C) {
12416 C->setModifier(Record.readEnum<OpenMPNumTasksClauseModifier>());
12417 C->setNumTasks(Record.readSubExpr());
12418 C->setModifierLoc(Record.readSourceLocation());
12419 C->setLParenLoc(Record.readSourceLocation());
12420}
12421
12422void OMPClauseReader::VisitOMPHintClause(OMPHintClause *C) {
12423 C->setHint(Record.readSubExpr());
12424 C->setLParenLoc(Record.readSourceLocation());
12425}
12426
12427void OMPClauseReader::VisitOMPDistScheduleClause(OMPDistScheduleClause *C) {
12429 C->setDistScheduleKind(
12430 static_cast<OpenMPDistScheduleClauseKind>(Record.readInt()));
12431 C->setChunkSize(Record.readSubExpr());
12432 C->setLParenLoc(Record.readSourceLocation());
12433 C->setDistScheduleKindLoc(Record.readSourceLocation());
12434 C->setCommaLoc(Record.readSourceLocation());
12435}
12436
12437void OMPClauseReader::VisitOMPDefaultmapClause(OMPDefaultmapClause *C) {
12438 C->setDefaultmapKind(
12439 static_cast<OpenMPDefaultmapClauseKind>(Record.readInt()));
12440 C->setDefaultmapModifier(
12441 static_cast<OpenMPDefaultmapClauseModifier>(Record.readInt()));
12442 C->setLParenLoc(Record.readSourceLocation());
12443 C->setDefaultmapModifierLoc(Record.readSourceLocation());
12444 C->setDefaultmapKindLoc(Record.readSourceLocation());
12445}
12446
12447void OMPClauseReader::VisitOMPToClause(OMPToClause *C) {
12448 C->setLParenLoc(Record.readSourceLocation());
12449 for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) {
12450 C->setMotionModifier(
12451 I, static_cast<OpenMPMotionModifierKind>(Record.readInt()));
12452 C->setMotionModifierLoc(I, Record.readSourceLocation());
12453 if (C->getMotionModifier(I) == OMPC_MOTION_MODIFIER_iterator)
12454 C->setIteratorModifier(Record.readExpr());
12455 }
12456 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
12457 C->setMapperIdInfo(Record.readDeclarationNameInfo());
12458 C->setColonLoc(Record.readSourceLocation());
12459 auto NumVars = C->varlist_size();
12460 auto UniqueDecls = C->getUniqueDeclarationsNum();
12461 auto TotalLists = C->getTotalComponentListNum();
12462 auto TotalComponents = C->getTotalComponentsNum();
12463
12464 SmallVector<Expr *, 16> Vars;
12465 Vars.reserve(NumVars);
12466 for (unsigned i = 0; i != NumVars; ++i)
12467 Vars.push_back(Record.readSubExpr());
12468 C->setVarRefs(Vars);
12469
12470 SmallVector<Expr *, 16> UDMappers;
12471 UDMappers.reserve(NumVars);
12472 for (unsigned I = 0; I < NumVars; ++I)
12473 UDMappers.push_back(Record.readSubExpr());
12474 C->setUDMapperRefs(UDMappers);
12475
12476 SmallVector<ValueDecl *, 16> Decls;
12477 Decls.reserve(UniqueDecls);
12478 for (unsigned i = 0; i < UniqueDecls; ++i)
12479 Decls.push_back(Record.readDeclAs<ValueDecl>());
12480 C->setUniqueDecls(Decls);
12481
12482 SmallVector<unsigned, 16> ListsPerDecl;
12483 ListsPerDecl.reserve(UniqueDecls);
12484 for (unsigned i = 0; i < UniqueDecls; ++i)
12485 ListsPerDecl.push_back(Record.readInt());
12486 C->setDeclNumLists(ListsPerDecl);
12487
12488 SmallVector<unsigned, 32> ListSizes;
12489 ListSizes.reserve(TotalLists);
12490 for (unsigned i = 0; i < TotalLists; ++i)
12491 ListSizes.push_back(Record.readInt());
12492 C->setComponentListSizes(ListSizes);
12493
12494 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12495 Components.reserve(TotalComponents);
12496 for (unsigned i = 0; i < TotalComponents; ++i) {
12497 Expr *AssociatedExprPr = Record.readSubExpr();
12498 bool IsNonContiguous = Record.readBool();
12499 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12500 Components.emplace_back(AssociatedExprPr, AssociatedDecl, IsNonContiguous);
12501 }
12502 C->setComponents(Components, ListSizes);
12503}
12504
12505void OMPClauseReader::VisitOMPFromClause(OMPFromClause *C) {
12506 C->setLParenLoc(Record.readSourceLocation());
12507 for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) {
12508 C->setMotionModifier(
12509 I, static_cast<OpenMPMotionModifierKind>(Record.readInt()));
12510 C->setMotionModifierLoc(I, Record.readSourceLocation());
12511 if (C->getMotionModifier(I) == OMPC_MOTION_MODIFIER_iterator)
12512 C->setIteratorModifier(Record.readExpr());
12513 }
12514 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
12515 C->setMapperIdInfo(Record.readDeclarationNameInfo());
12516 C->setColonLoc(Record.readSourceLocation());
12517 auto NumVars = C->varlist_size();
12518 auto UniqueDecls = C->getUniqueDeclarationsNum();
12519 auto TotalLists = C->getTotalComponentListNum();
12520 auto TotalComponents = C->getTotalComponentsNum();
12521
12522 SmallVector<Expr *, 16> Vars;
12523 Vars.reserve(NumVars);
12524 for (unsigned i = 0; i != NumVars; ++i)
12525 Vars.push_back(Record.readSubExpr());
12526 C->setVarRefs(Vars);
12527
12528 SmallVector<Expr *, 16> UDMappers;
12529 UDMappers.reserve(NumVars);
12530 for (unsigned I = 0; I < NumVars; ++I)
12531 UDMappers.push_back(Record.readSubExpr());
12532 C->setUDMapperRefs(UDMappers);
12533
12534 SmallVector<ValueDecl *, 16> Decls;
12535 Decls.reserve(UniqueDecls);
12536 for (unsigned i = 0; i < UniqueDecls; ++i)
12537 Decls.push_back(Record.readDeclAs<ValueDecl>());
12538 C->setUniqueDecls(Decls);
12539
12540 SmallVector<unsigned, 16> ListsPerDecl;
12541 ListsPerDecl.reserve(UniqueDecls);
12542 for (unsigned i = 0; i < UniqueDecls; ++i)
12543 ListsPerDecl.push_back(Record.readInt());
12544 C->setDeclNumLists(ListsPerDecl);
12545
12546 SmallVector<unsigned, 32> ListSizes;
12547 ListSizes.reserve(TotalLists);
12548 for (unsigned i = 0; i < TotalLists; ++i)
12549 ListSizes.push_back(Record.readInt());
12550 C->setComponentListSizes(ListSizes);
12551
12552 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12553 Components.reserve(TotalComponents);
12554 for (unsigned i = 0; i < TotalComponents; ++i) {
12555 Expr *AssociatedExprPr = Record.readSubExpr();
12556 bool IsNonContiguous = Record.readBool();
12557 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12558 Components.emplace_back(AssociatedExprPr, AssociatedDecl, IsNonContiguous);
12559 }
12560 C->setComponents(Components, ListSizes);
12561}
12562
12563void OMPClauseReader::VisitOMPUseDevicePtrClause(OMPUseDevicePtrClause *C) {
12564 C->setLParenLoc(Record.readSourceLocation());
12565 auto NumVars = C->varlist_size();
12566 auto UniqueDecls = C->getUniqueDeclarationsNum();
12567 auto TotalLists = C->getTotalComponentListNum();
12568 auto TotalComponents = C->getTotalComponentsNum();
12569
12570 SmallVector<Expr *, 16> Vars;
12571 Vars.reserve(NumVars);
12572 for (unsigned i = 0; i != NumVars; ++i)
12573 Vars.push_back(Record.readSubExpr());
12574 C->setVarRefs(Vars);
12575 Vars.clear();
12576 for (unsigned i = 0; i != NumVars; ++i)
12577 Vars.push_back(Record.readSubExpr());
12578 C->setPrivateCopies(Vars);
12579 Vars.clear();
12580 for (unsigned i = 0; i != NumVars; ++i)
12581 Vars.push_back(Record.readSubExpr());
12582 C->setInits(Vars);
12583
12584 SmallVector<ValueDecl *, 16> Decls;
12585 Decls.reserve(UniqueDecls);
12586 for (unsigned i = 0; i < UniqueDecls; ++i)
12587 Decls.push_back(Record.readDeclAs<ValueDecl>());
12588 C->setUniqueDecls(Decls);
12589
12590 SmallVector<unsigned, 16> ListsPerDecl;
12591 ListsPerDecl.reserve(UniqueDecls);
12592 for (unsigned i = 0; i < UniqueDecls; ++i)
12593 ListsPerDecl.push_back(Record.readInt());
12594 C->setDeclNumLists(ListsPerDecl);
12595
12596 SmallVector<unsigned, 32> ListSizes;
12597 ListSizes.reserve(TotalLists);
12598 for (unsigned i = 0; i < TotalLists; ++i)
12599 ListSizes.push_back(Record.readInt());
12600 C->setComponentListSizes(ListSizes);
12601
12602 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12603 Components.reserve(TotalComponents);
12604 for (unsigned i = 0; i < TotalComponents; ++i) {
12605 auto *AssociatedExprPr = Record.readSubExpr();
12606 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12607 Components.emplace_back(AssociatedExprPr, AssociatedDecl,
12608 /*IsNonContiguous=*/false);
12609 }
12610 C->setComponents(Components, ListSizes);
12611}
12612
12613void OMPClauseReader::VisitOMPUseDeviceAddrClause(OMPUseDeviceAddrClause *C) {
12614 C->setLParenLoc(Record.readSourceLocation());
12615 auto NumVars = C->varlist_size();
12616 auto UniqueDecls = C->getUniqueDeclarationsNum();
12617 auto TotalLists = C->getTotalComponentListNum();
12618 auto TotalComponents = C->getTotalComponentsNum();
12619
12620 SmallVector<Expr *, 16> Vars;
12621 Vars.reserve(NumVars);
12622 for (unsigned i = 0; i != NumVars; ++i)
12623 Vars.push_back(Record.readSubExpr());
12624 C->setVarRefs(Vars);
12625
12626 SmallVector<ValueDecl *, 16> Decls;
12627 Decls.reserve(UniqueDecls);
12628 for (unsigned i = 0; i < UniqueDecls; ++i)
12629 Decls.push_back(Record.readDeclAs<ValueDecl>());
12630 C->setUniqueDecls(Decls);
12631
12632 SmallVector<unsigned, 16> ListsPerDecl;
12633 ListsPerDecl.reserve(UniqueDecls);
12634 for (unsigned i = 0; i < UniqueDecls; ++i)
12635 ListsPerDecl.push_back(Record.readInt());
12636 C->setDeclNumLists(ListsPerDecl);
12637
12638 SmallVector<unsigned, 32> ListSizes;
12639 ListSizes.reserve(TotalLists);
12640 for (unsigned i = 0; i < TotalLists; ++i)
12641 ListSizes.push_back(Record.readInt());
12642 C->setComponentListSizes(ListSizes);
12643
12644 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12645 Components.reserve(TotalComponents);
12646 for (unsigned i = 0; i < TotalComponents; ++i) {
12647 Expr *AssociatedExpr = Record.readSubExpr();
12648 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12649 Components.emplace_back(AssociatedExpr, AssociatedDecl,
12650 /*IsNonContiguous*/ false);
12651 }
12652 C->setComponents(Components, ListSizes);
12653}
12654
12655void OMPClauseReader::VisitOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
12656 C->setLParenLoc(Record.readSourceLocation());
12657 auto NumVars = C->varlist_size();
12658 auto UniqueDecls = C->getUniqueDeclarationsNum();
12659 auto TotalLists = C->getTotalComponentListNum();
12660 auto TotalComponents = C->getTotalComponentsNum();
12661
12662 SmallVector<Expr *, 16> Vars;
12663 Vars.reserve(NumVars);
12664 for (unsigned i = 0; i != NumVars; ++i)
12665 Vars.push_back(Record.readSubExpr());
12666 C->setVarRefs(Vars);
12667 Vars.clear();
12668
12669 SmallVector<ValueDecl *, 16> Decls;
12670 Decls.reserve(UniqueDecls);
12671 for (unsigned i = 0; i < UniqueDecls; ++i)
12672 Decls.push_back(Record.readDeclAs<ValueDecl>());
12673 C->setUniqueDecls(Decls);
12674
12675 SmallVector<unsigned, 16> ListsPerDecl;
12676 ListsPerDecl.reserve(UniqueDecls);
12677 for (unsigned i = 0; i < UniqueDecls; ++i)
12678 ListsPerDecl.push_back(Record.readInt());
12679 C->setDeclNumLists(ListsPerDecl);
12680
12681 SmallVector<unsigned, 32> ListSizes;
12682 ListSizes.reserve(TotalLists);
12683 for (unsigned i = 0; i < TotalLists; ++i)
12684 ListSizes.push_back(Record.readInt());
12685 C->setComponentListSizes(ListSizes);
12686
12687 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12688 Components.reserve(TotalComponents);
12689 for (unsigned i = 0; i < TotalComponents; ++i) {
12690 Expr *AssociatedExpr = Record.readSubExpr();
12691 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12692 Components.emplace_back(AssociatedExpr, AssociatedDecl,
12693 /*IsNonContiguous=*/false);
12694 }
12695 C->setComponents(Components, ListSizes);
12696}
12697
12698void OMPClauseReader::VisitOMPHasDeviceAddrClause(OMPHasDeviceAddrClause *C) {
12699 C->setLParenLoc(Record.readSourceLocation());
12700 auto NumVars = C->varlist_size();
12701 auto UniqueDecls = C->getUniqueDeclarationsNum();
12702 auto TotalLists = C->getTotalComponentListNum();
12703 auto TotalComponents = C->getTotalComponentsNum();
12704
12705 SmallVector<Expr *, 16> Vars;
12706 Vars.reserve(NumVars);
12707 for (unsigned I = 0; I != NumVars; ++I)
12708 Vars.push_back(Record.readSubExpr());
12709 C->setVarRefs(Vars);
12710 Vars.clear();
12711
12712 SmallVector<ValueDecl *, 16> Decls;
12713 Decls.reserve(UniqueDecls);
12714 for (unsigned I = 0; I < UniqueDecls; ++I)
12715 Decls.push_back(Record.readDeclAs<ValueDecl>());
12716 C->setUniqueDecls(Decls);
12717
12718 SmallVector<unsigned, 16> ListsPerDecl;
12719 ListsPerDecl.reserve(UniqueDecls);
12720 for (unsigned I = 0; I < UniqueDecls; ++I)
12721 ListsPerDecl.push_back(Record.readInt());
12722 C->setDeclNumLists(ListsPerDecl);
12723
12724 SmallVector<unsigned, 32> ListSizes;
12725 ListSizes.reserve(TotalLists);
12726 for (unsigned i = 0; i < TotalLists; ++i)
12727 ListSizes.push_back(Record.readInt());
12728 C->setComponentListSizes(ListSizes);
12729
12730 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12731 Components.reserve(TotalComponents);
12732 for (unsigned I = 0; I < TotalComponents; ++I) {
12733 Expr *AssociatedExpr = Record.readSubExpr();
12734 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12735 Components.emplace_back(AssociatedExpr, AssociatedDecl,
12736 /*IsNonContiguous=*/false);
12737 }
12738 C->setComponents(Components, ListSizes);
12739}
12740
12741void OMPClauseReader::VisitOMPNontemporalClause(OMPNontemporalClause *C) {
12742 C->setLParenLoc(Record.readSourceLocation());
12743 unsigned NumVars = C->varlist_size();
12744 SmallVector<Expr *, 16> Vars;
12745 Vars.reserve(NumVars);
12746 for (unsigned i = 0; i != NumVars; ++i)
12747 Vars.push_back(Record.readSubExpr());
12748 C->setVarRefs(Vars);
12749 Vars.clear();
12750 Vars.reserve(NumVars);
12751 for (unsigned i = 0; i != NumVars; ++i)
12752 Vars.push_back(Record.readSubExpr());
12753 C->setPrivateRefs(Vars);
12754}
12755
12756void OMPClauseReader::VisitOMPInclusiveClause(OMPInclusiveClause *C) {
12757 C->setLParenLoc(Record.readSourceLocation());
12758 unsigned NumVars = C->varlist_size();
12759 SmallVector<Expr *, 16> Vars;
12760 Vars.reserve(NumVars);
12761 for (unsigned i = 0; i != NumVars; ++i)
12762 Vars.push_back(Record.readSubExpr());
12763 C->setVarRefs(Vars);
12764}
12765
12766void OMPClauseReader::VisitOMPExclusiveClause(OMPExclusiveClause *C) {
12767 C->setLParenLoc(Record.readSourceLocation());
12768 unsigned NumVars = C->varlist_size();
12769 SmallVector<Expr *, 16> Vars;
12770 Vars.reserve(NumVars);
12771 for (unsigned i = 0; i != NumVars; ++i)
12772 Vars.push_back(Record.readSubExpr());
12773 C->setVarRefs(Vars);
12774}
12775
12776void OMPClauseReader::VisitOMPUsesAllocatorsClause(OMPUsesAllocatorsClause *C) {
12777 C->setLParenLoc(Record.readSourceLocation());
12778 unsigned NumOfAllocators = C->getNumberOfAllocators();
12779 SmallVector<OMPUsesAllocatorsClause::Data, 4> Data;
12780 Data.reserve(NumOfAllocators);
12781 for (unsigned I = 0; I != NumOfAllocators; ++I) {
12782 OMPUsesAllocatorsClause::Data &D = Data.emplace_back();
12783 D.Allocator = Record.readSubExpr();
12784 D.AllocatorTraits = Record.readSubExpr();
12785 D.LParenLoc = Record.readSourceLocation();
12786 D.RParenLoc = Record.readSourceLocation();
12787 }
12788 C->setAllocatorsData(Data);
12789}
12790
12791void OMPClauseReader::VisitOMPAffinityClause(OMPAffinityClause *C) {
12792 C->setLParenLoc(Record.readSourceLocation());
12793 C->setModifier(Record.readSubExpr());
12794 C->setColonLoc(Record.readSourceLocation());
12795 unsigned NumOfLocators = C->varlist_size();
12796 SmallVector<Expr *, 4> Locators;
12797 Locators.reserve(NumOfLocators);
12798 for (unsigned I = 0; I != NumOfLocators; ++I)
12799 Locators.push_back(Record.readSubExpr());
12800 C->setVarRefs(Locators);
12801}
12802
12803void OMPClauseReader::VisitOMPOrderClause(OMPOrderClause *C) {
12804 C->setKind(Record.readEnum<OpenMPOrderClauseKind>());
12805 C->setModifier(Record.readEnum<OpenMPOrderClauseModifier>());
12806 C->setLParenLoc(Record.readSourceLocation());
12807 C->setKindKwLoc(Record.readSourceLocation());
12808 C->setModifierKwLoc(Record.readSourceLocation());
12809}
12810
12811void OMPClauseReader::VisitOMPFilterClause(OMPFilterClause *C) {
12813 C->setThreadID(Record.readSubExpr());
12814 C->setLParenLoc(Record.readSourceLocation());
12815}
12816
12817void OMPClauseReader::VisitOMPBindClause(OMPBindClause *C) {
12818 C->setBindKind(Record.readEnum<OpenMPBindClauseKind>());
12819 C->setLParenLoc(Record.readSourceLocation());
12820 C->setBindKindLoc(Record.readSourceLocation());
12821}
12822
12823void OMPClauseReader::VisitOMPAlignClause(OMPAlignClause *C) {
12824 C->setAlignment(Record.readExpr());
12825 C->setLParenLoc(Record.readSourceLocation());
12826}
12827
12828void OMPClauseReader::VisitOMPXDynCGroupMemClause(OMPXDynCGroupMemClause *C) {
12830 C->setSize(Record.readSubExpr());
12831 C->setLParenLoc(Record.readSourceLocation());
12832}
12833
12834void OMPClauseReader::VisitOMPDynGroupprivateClause(
12837 C->setDynGroupprivateModifier(
12838 Record.readEnum<OpenMPDynGroupprivateClauseModifier>());
12839 C->setDynGroupprivateFallbackModifier(
12841 C->setSize(Record.readSubExpr());
12842 C->setLParenLoc(Record.readSourceLocation());
12843 C->setDynGroupprivateModifierLoc(Record.readSourceLocation());
12844 C->setDynGroupprivateFallbackModifierLoc(Record.readSourceLocation());
12845}
12846
12847void OMPClauseReader::VisitOMPDoacrossClause(OMPDoacrossClause *C) {
12848 C->setLParenLoc(Record.readSourceLocation());
12849 C->setDependenceType(
12850 static_cast<OpenMPDoacrossClauseModifier>(Record.readInt()));
12851 C->setDependenceLoc(Record.readSourceLocation());
12852 C->setColonLoc(Record.readSourceLocation());
12853 unsigned NumVars = C->varlist_size();
12854 SmallVector<Expr *, 16> Vars;
12855 Vars.reserve(NumVars);
12856 for (unsigned I = 0; I != NumVars; ++I)
12857 Vars.push_back(Record.readSubExpr());
12858 C->setVarRefs(Vars);
12859 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
12860 C->setLoopData(I, Record.readSubExpr());
12861}
12862
12863void OMPClauseReader::VisitOMPXAttributeClause(OMPXAttributeClause *C) {
12864 AttrVec Attrs;
12865 Record.readAttributes(Attrs);
12866 C->setAttrs(Attrs);
12867 C->setLocStart(Record.readSourceLocation());
12868 C->setLParenLoc(Record.readSourceLocation());
12869 C->setLocEnd(Record.readSourceLocation());
12870}
12871
12872void OMPClauseReader::VisitOMPXBareClause(OMPXBareClause *C) {}
12873
12876 TI.Sets.resize(readUInt32());
12877 for (auto &Set : TI.Sets) {
12879 Set.Selectors.resize(readUInt32());
12880 for (auto &Selector : Set.Selectors) {
12882 Selector.ScoreOrCondition = nullptr;
12883 if (readBool())
12884 Selector.ScoreOrCondition = readExprRef();
12885 Selector.Properties.resize(readUInt32());
12886 for (auto &Property : Selector.Properties)
12888 }
12889 }
12890 return &TI;
12891}
12892
12894 if (!Data)
12895 return;
12896 if (Reader->ReadingKind == ASTReader::Read_Stmt) {
12897 // Skip NumClauses, NumChildren and HasAssociatedStmt fields.
12898 skipInts(3);
12899 }
12900 SmallVector<OMPClause *, 4> Clauses(Data->getNumClauses());
12901 for (unsigned I = 0, E = Data->getNumClauses(); I < E; ++I)
12902 Clauses[I] = readOMPClause();
12903 Data->setClauses(Clauses);
12904 if (Data->hasAssociatedStmt())
12905 Data->setAssociatedStmt(readStmt());
12906 for (unsigned I = 0, E = Data->getNumChildren(); I < E; ++I)
12907 Data->getChildren()[I] = readStmt();
12908}
12909
12911 unsigned NumVars = readInt();
12913 for (unsigned I = 0; I < NumVars; ++I)
12914 VarList.push_back(readExpr());
12915 return VarList;
12916}
12917
12919 unsigned NumExprs = readInt();
12921 for (unsigned I = 0; I < NumExprs; ++I)
12922 ExprList.push_back(readSubExpr());
12923 return ExprList;
12924}
12925
12930
12931 switch (ClauseKind) {
12933 SourceLocation LParenLoc = readSourceLocation();
12935 return OpenACCDefaultClause::Create(getContext(), DCK, BeginLoc, LParenLoc,
12936 EndLoc);
12937 }
12938 case OpenACCClauseKind::If: {
12939 SourceLocation LParenLoc = readSourceLocation();
12940 Expr *CondExpr = readSubExpr();
12941 return OpenACCIfClause::Create(getContext(), BeginLoc, LParenLoc, CondExpr,
12942 EndLoc);
12943 }
12945 SourceLocation LParenLoc = readSourceLocation();
12946 bool isConditionExprClause = readBool();
12947 if (isConditionExprClause) {
12948 Expr *CondExpr = readBool() ? readSubExpr() : nullptr;
12949 return OpenACCSelfClause::Create(getContext(), BeginLoc, LParenLoc,
12950 CondExpr, EndLoc);
12951 }
12952 unsigned NumVars = readInt();
12954 for (unsigned I = 0; I < NumVars; ++I)
12955 VarList.push_back(readSubExpr());
12956 return OpenACCSelfClause::Create(getContext(), BeginLoc, LParenLoc, VarList,
12957 EndLoc);
12958 }
12960 SourceLocation LParenLoc = readSourceLocation();
12961 unsigned NumClauses = readInt();
12963 for (unsigned I = 0; I < NumClauses; ++I)
12964 IntExprs.push_back(readSubExpr());
12965 return OpenACCNumGangsClause::Create(getContext(), BeginLoc, LParenLoc,
12966 IntExprs, EndLoc);
12967 }
12969 SourceLocation LParenLoc = readSourceLocation();
12970 Expr *IntExpr = readSubExpr();
12971 return OpenACCNumWorkersClause::Create(getContext(), BeginLoc, LParenLoc,
12972 IntExpr, EndLoc);
12973 }
12975 SourceLocation LParenLoc = readSourceLocation();
12976 Expr *IntExpr = readSubExpr();
12977 return OpenACCDeviceNumClause::Create(getContext(), BeginLoc, LParenLoc,
12978 IntExpr, EndLoc);
12979 }
12981 SourceLocation LParenLoc = readSourceLocation();
12982 Expr *IntExpr = readSubExpr();
12983 return OpenACCDefaultAsyncClause::Create(getContext(), BeginLoc, LParenLoc,
12984 IntExpr, EndLoc);
12985 }
12987 SourceLocation LParenLoc = readSourceLocation();
12988 Expr *IntExpr = readSubExpr();
12989 return OpenACCVectorLengthClause::Create(getContext(), BeginLoc, LParenLoc,
12990 IntExpr, EndLoc);
12991 }
12993 SourceLocation LParenLoc = readSourceLocation();
12995
12997 for (unsigned I = 0; I < VarList.size(); ++I) {
12998 static_assert(sizeof(OpenACCPrivateRecipe) == 1 * sizeof(int *));
12999 VarDecl *Alloca = readDeclAs<VarDecl>();
13000 RecipeList.push_back({Alloca});
13001 }
13002
13003 return OpenACCPrivateClause::Create(getContext(), BeginLoc, LParenLoc,
13004 VarList, RecipeList, EndLoc);
13005 }
13007 SourceLocation LParenLoc = readSourceLocation();
13009 return OpenACCHostClause::Create(getContext(), BeginLoc, LParenLoc, VarList,
13010 EndLoc);
13011 }
13013 SourceLocation LParenLoc = readSourceLocation();
13015 return OpenACCDeviceClause::Create(getContext(), BeginLoc, LParenLoc,
13016 VarList, EndLoc);
13017 }
13019 SourceLocation LParenLoc = readSourceLocation();
13022 for (unsigned I = 0; I < VarList.size(); ++I) {
13023 static_assert(sizeof(OpenACCFirstPrivateRecipe) == 2 * sizeof(int *));
13024 VarDecl *Recipe = readDeclAs<VarDecl>();
13025 VarDecl *RecipeTemp = readDeclAs<VarDecl>();
13026 RecipeList.push_back({Recipe, RecipeTemp});
13027 }
13028
13029 return OpenACCFirstPrivateClause::Create(getContext(), BeginLoc, LParenLoc,
13030 VarList, RecipeList, EndLoc);
13031 }
13033 SourceLocation LParenLoc = readSourceLocation();
13035 return OpenACCAttachClause::Create(getContext(), BeginLoc, LParenLoc,
13036 VarList, EndLoc);
13037 }
13039 SourceLocation LParenLoc = readSourceLocation();
13041 return OpenACCDetachClause::Create(getContext(), BeginLoc, LParenLoc,
13042 VarList, EndLoc);
13043 }
13045 SourceLocation LParenLoc = readSourceLocation();
13047 return OpenACCDeleteClause::Create(getContext(), BeginLoc, LParenLoc,
13048 VarList, EndLoc);
13049 }
13051 SourceLocation LParenLoc = readSourceLocation();
13053 return OpenACCUseDeviceClause::Create(getContext(), BeginLoc, LParenLoc,
13054 VarList, EndLoc);
13055 }
13057 SourceLocation LParenLoc = readSourceLocation();
13059 return OpenACCDevicePtrClause::Create(getContext(), BeginLoc, LParenLoc,
13060 VarList, EndLoc);
13061 }
13063 SourceLocation LParenLoc = readSourceLocation();
13065 return OpenACCNoCreateClause::Create(getContext(), BeginLoc, LParenLoc,
13066 VarList, EndLoc);
13067 }
13069 SourceLocation LParenLoc = readSourceLocation();
13071 return OpenACCPresentClause::Create(getContext(), BeginLoc, LParenLoc,
13072 VarList, EndLoc);
13073 }
13077 SourceLocation LParenLoc = readSourceLocation();
13080 return OpenACCCopyClause::Create(getContext(), ClauseKind, BeginLoc,
13081 LParenLoc, ModList, VarList, EndLoc);
13082 }
13086 SourceLocation LParenLoc = readSourceLocation();
13089 return OpenACCCopyInClause::Create(getContext(), ClauseKind, BeginLoc,
13090 LParenLoc, ModList, VarList, EndLoc);
13091 }
13095 SourceLocation LParenLoc = readSourceLocation();
13098 return OpenACCCopyOutClause::Create(getContext(), ClauseKind, BeginLoc,
13099 LParenLoc, ModList, VarList, EndLoc);
13100 }
13104 SourceLocation LParenLoc = readSourceLocation();
13107 return OpenACCCreateClause::Create(getContext(), ClauseKind, BeginLoc,
13108 LParenLoc, ModList, VarList, EndLoc);
13109 }
13111 SourceLocation LParenLoc = readSourceLocation();
13112 Expr *AsyncExpr = readBool() ? readSubExpr() : nullptr;
13113 return OpenACCAsyncClause::Create(getContext(), BeginLoc, LParenLoc,
13114 AsyncExpr, EndLoc);
13115 }
13117 SourceLocation LParenLoc = readSourceLocation();
13118 Expr *DevNumExpr = readBool() ? readSubExpr() : nullptr;
13119 SourceLocation QueuesLoc = readSourceLocation();
13121 return OpenACCWaitClause::Create(getContext(), BeginLoc, LParenLoc,
13122 DevNumExpr, QueuesLoc, QueueIdExprs,
13123 EndLoc);
13124 }
13127 SourceLocation LParenLoc = readSourceLocation();
13129 unsigned NumArchs = readInt();
13130
13131 for (unsigned I = 0; I < NumArchs; ++I) {
13132 IdentifierInfo *Ident = readBool() ? readIdentifier() : nullptr;
13134 Archs.emplace_back(Loc, Ident);
13135 }
13136
13137 return OpenACCDeviceTypeClause::Create(getContext(), ClauseKind, BeginLoc,
13138 LParenLoc, Archs, EndLoc);
13139 }
13141 SourceLocation LParenLoc = readSourceLocation();
13145
13146 for (unsigned I = 0; I < VarList.size(); ++I) {
13147 VarDecl *Recipe = readDeclAs<VarDecl>();
13148
13149 static_assert(sizeof(OpenACCReductionRecipe::CombinerRecipe) ==
13150 3 * sizeof(int *));
13151
13153 unsigned NumCombiners = readInt();
13154 for (unsigned I = 0; I < NumCombiners; ++I) {
13157 Expr *Op = readExpr();
13158
13159 Combiners.push_back({LHS, RHS, Op});
13160 }
13161
13162 RecipeList.push_back({Recipe, Combiners});
13163 }
13164
13165 return OpenACCReductionClause::Create(getContext(), BeginLoc, LParenLoc, Op,
13166 VarList, RecipeList, EndLoc);
13167 }
13169 return OpenACCSeqClause::Create(getContext(), BeginLoc, EndLoc);
13171 return OpenACCNoHostClause::Create(getContext(), BeginLoc, EndLoc);
13173 return OpenACCFinalizeClause::Create(getContext(), BeginLoc, EndLoc);
13175 return OpenACCIfPresentClause::Create(getContext(), BeginLoc, EndLoc);
13177 return OpenACCIndependentClause::Create(getContext(), BeginLoc, EndLoc);
13179 return OpenACCAutoClause::Create(getContext(), BeginLoc, EndLoc);
13181 SourceLocation LParenLoc = readSourceLocation();
13182 bool HasForce = readBool();
13183 Expr *LoopCount = readSubExpr();
13184 return OpenACCCollapseClause::Create(getContext(), BeginLoc, LParenLoc,
13185 HasForce, LoopCount, EndLoc);
13186 }
13188 SourceLocation LParenLoc = readSourceLocation();
13189 unsigned NumClauses = readInt();
13190 llvm::SmallVector<Expr *> SizeExprs;
13191 for (unsigned I = 0; I < NumClauses; ++I)
13192 SizeExprs.push_back(readSubExpr());
13193 return OpenACCTileClause::Create(getContext(), BeginLoc, LParenLoc,
13194 SizeExprs, EndLoc);
13195 }
13197 SourceLocation LParenLoc = readSourceLocation();
13198 unsigned NumExprs = readInt();
13201 for (unsigned I = 0; I < NumExprs; ++I) {
13202 GangKinds.push_back(readEnum<OpenACCGangKind>());
13203 // Can't use `readSubExpr` because this is usable from a 'decl' construct.
13204 Exprs.push_back(readExpr());
13205 }
13206 return OpenACCGangClause::Create(getContext(), BeginLoc, LParenLoc,
13207 GangKinds, Exprs, EndLoc);
13208 }
13210 SourceLocation LParenLoc = readSourceLocation();
13211 Expr *WorkerExpr = readBool() ? readSubExpr() : nullptr;
13212 return OpenACCWorkerClause::Create(getContext(), BeginLoc, LParenLoc,
13213 WorkerExpr, EndLoc);
13214 }
13216 SourceLocation LParenLoc = readSourceLocation();
13217 Expr *VectorExpr = readBool() ? readSubExpr() : nullptr;
13218 return OpenACCVectorClause::Create(getContext(), BeginLoc, LParenLoc,
13219 VectorExpr, EndLoc);
13220 }
13222 SourceLocation LParenLoc = readSourceLocation();
13224 return OpenACCLinkClause::Create(getContext(), BeginLoc, LParenLoc, VarList,
13225 EndLoc);
13226 }
13228 SourceLocation LParenLoc = readSourceLocation();
13231 LParenLoc, VarList, EndLoc);
13232 }
13233
13235 SourceLocation LParenLoc = readSourceLocation();
13236 bool IsString = readBool();
13237 if (IsString)
13238 return OpenACCBindClause::Create(getContext(), BeginLoc, LParenLoc,
13239 cast<StringLiteral>(readExpr()), EndLoc);
13240 return OpenACCBindClause::Create(getContext(), BeginLoc, LParenLoc,
13241 readIdentifier(), EndLoc);
13242 }
13245 llvm_unreachable("Clause serialization not yet implemented");
13246 }
13247 llvm_unreachable("Invalid Clause Kind");
13248}
13249
13252 for (unsigned I = 0; I < Clauses.size(); ++I)
13253 Clauses[I] = readOpenACCClause();
13254}
13255
13256void ASTRecordReader::readOpenACCRoutineDeclAttr(OpenACCRoutineDeclAttr *A) {
13257 unsigned NumVars = readInt();
13258 A->Clauses.resize(NumVars);
13259 readOpenACCClauseList(A->Clauses);
13260}
13261
13262static unsigned getStableHashForModuleName(StringRef PrimaryModuleName) {
13263 // TODO: Maybe it is better to check PrimaryModuleName is a valid
13264 // module name?
13265 llvm::FoldingSetNodeID ID;
13266 ID.AddString(PrimaryModuleName);
13267 return ID.computeStableHash();
13268}
13269
13271 if (!M)
13272 return std::nullopt;
13273
13274 if (M->isHeaderLikeModule())
13275 return std::nullopt;
13276
13277 if (M->isGlobalModule())
13278 return std::nullopt;
13279
13280 StringRef PrimaryModuleName = M->getPrimaryModuleInterfaceName();
13281 return getStableHashForModuleName(PrimaryModuleName);
13282}
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 bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags)
static bool checkModuleCachePath(llvm::vfs::FileSystem &VFS, StringRef SpecificModuleCachePath, StringRef ExistingModuleCachePath, StringRef ModuleFilename, DiagnosticsEngine *Diags, const LangOptions &LangOpts, const PreprocessorOptions &PPOpts)
Check that the specified and the existing module cache paths are equivalent.
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)
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.
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:628
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
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:220
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:843
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 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:202
virtual bool ReadFileSystemOptions(const FileSystemOptions &FSOpts, bool Complain)
Receives the file system options.
Definition ASTReader.h:173
virtual bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, StringRef ModuleFilename, bool ReadMacros, bool Complain, std::string &SuggestedPredefines)
Receives the preprocessor options.
Definition ASTReader.h:215
virtual bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, StringRef ModuleFilename, StringRef SpecificModuleCachePath, bool Complain)
Receives the header search options.
Definition ASTReader.h:186
virtual bool ReadLanguageOptions(const LangOptions &LangOpts, StringRef ModuleFilename, bool Complain, bool AllowCompatibleDifferences)
Receives the language options.
Definition ASTReader.h:135
virtual void visitModuleFile(StringRef Filename, serialization::ModuleKind Kind)
This is called for each AST file loaded.
Definition ASTReader.h:227
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:223
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:430
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:446
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:1992
bool isDeclIDFromModule(GlobalDeclID ID, ModuleFile &M) const
Returns true if global DeclID ID originated from module M.
friend class ASTIdentifierIterator
Definition ASTReader.h:435
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:2610
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:2184
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:1834
@ ARR_ConfigurationMismatch
The client can handle an AST file that cannot load because it's compiled configuration doesn't match ...
Definition ASTReader.h:1847
@ 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:1838
@ 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:1842
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:2644
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:2194
QualType getLocalType(ModuleFile &F, serialization::LocalTypeID LocalID)
Resolve a local type ID within a given AST file into a type.
friend class LocalDeclID
Definition ASTReader.h:443
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:477
bool loadGlobalIndex()
Attempts to load the global index.
void ReadComments() override
Loads comments ranges.
SourceManager & getSourceManager() const
Definition ASTReader.h:1818
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.
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:2622
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:2060
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:439
friend class serialization::ReadMethodPoolVisitor
Definition ASTReader.h:441
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:2496
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.
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, StringRef ExistingModuleCachePath, bool RequireStrictOptionMatches=false)
Determine whether the given AST file is acceptable to load into a translation unit with the given lan...
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:2090
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.
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:2617
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)
ASTReadResult ReadAST(StringRef FileName, ModuleKind Type, SourceLocation ImportLoc, unsigned ClientLoadCapabilities, ModuleFile **NewLoadedModuleFile=nullptr)
Load the AST file designated by the given file name.
StringRef getOriginalSourceFile()
Retrieve the name of the original source file name for the primary module file.
Definition ASTReader.h:2000
std::string ReadPath(ModuleFile &F, const RecordData &Record, unsigned &Idx)
friend class serialization::reader::ASTIdentifierLookupTrait
Definition ASTReader.h:440
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:1499
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:450
@ Success
The control block was read successfully.
Definition ASTReader.h:453
@ ConfigurationMismatch
The AST file was written with a different language/target configuration.
Definition ASTReader.h:470
@ OutOfDate
The AST file is out-of-date relative to its input files, and needs to be regenerated.
Definition ASTReader.h:463
@ Failure
The AST file itself appears corrupted.
Definition ASTReader.h:456
@ VersionMismatch
The AST file was written by a different version of Clang.
Definition ASTReader.h:466
@ HadErrors
The AST file has errors.
Definition ASTReader.h:473
@ Missing
The AST file was missing.
Definition ASTReader.h:459
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:2524
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:2148
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:2480
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:1996
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...
Module * getSubmodule(serialization::SubmoduleID GlobalID)
Retrieve the submodule that corresponds to a global submodule ID.
void PrintStats() override
Print some statistics about AST usage.
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:436
SmallVector< uint64_t, 64 > RecordData
Definition ASTReader.h:445
FileID ReadFileID(ModuleFile &F, const RecordDataImpl &Record, unsigned &Idx) const
Read a FileID.
Definition ASTReader.h:2518
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:1819
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.
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:476
bool hasGlobalIndex() const
Determine whether this AST reader has a global index.
Definition ASTReader.h:1955
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:1748
void setLBracketLoc(SourceLocation Loc)
Definition TypeLoc.h:1754
void setRBracketLoc(SourceLocation Loc)
Definition TypeLoc.h:1762
void setSizeExpr(Expr *Size)
Definition TypeLoc.h:1774
void setRParenLoc(SourceLocation Loc)
Definition TypeLoc.h:2660
void setLParenLoc(SourceLocation Loc)
Definition TypeLoc.h:2652
void setKWLoc(SourceLocation Loc)
Definition TypeLoc.h:2644
Attr - This represents one attribute.
Definition Attr.h:45
void setAttr(const Attr *A)
Definition TypeLoc.h:1034
void setConceptReference(ConceptReference *CR)
Definition TypeLoc.h:2376
void setRParenLoc(SourceLocation Loc)
Definition TypeLoc.h:2370
void setCaretLoc(SourceLocation Loc)
Definition TypeLoc.h:1503
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:2604
Represents a C++ base or member initializer.
Definition DeclCXX.h:2369
void setSourceOrder(int Pos)
Set the source order of this initializer.
Definition DeclCXX.h:2556
Represents a C++ destructor within a class.
Definition DeclCXX.h:2869
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:1828
unsigned getLambdaIndexInContext() const
Retrieve the index of this lambda within the context declaration returned by getLambdaContextDecl().
Definition DeclCXX.h:1790
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:1459
static CXXTemporary * Create(const ASTContext &C, const CXXDestructorDecl *Destructor)
Definition ExprCXX.cpp:1113
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 SpecificModuleCachePath, 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.
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.
void visitModuleFile(StringRef Filename, serialization::ModuleKind Kind) override
This is called for each AST file loaded.
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)
typename Representation::iterator iterator
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1449
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:2700
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:2673
bool hasExternalLexicalStorage() const
Whether this DeclContext has external storage containing additional declarations that are lexically i...
Definition DeclBase.h:2688
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:2373
void setHasExternalLexicalStorage(bool ES=true) const
State whether this DeclContext has external storage for declarations lexically in this context.
Definition DeclBase.h:2694
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:2714
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:247
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:546
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:593
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:859
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:984
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition DeclBase.h:842
Module * getImportedOwningModule() const
Get the imported owning module, if this decl is from an imported (non-local) module.
Definition DeclBase.h:812
bool isFromASTFile() const
Determine whether this declaration came from an AST file (such as a precompiled header or module) rat...
Definition DeclBase.h:793
SourceLocation getLocation() const
Definition DeclBase.h:439
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition DeclBase.h:1049
DeclContext * getDeclContext()
Definition DeclBase.h:448
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:918
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:978
Kind getKind() const
Definition DeclBase.h:442
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:870
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:2262
void setDecltypeLoc(SourceLocation Loc)
Definition TypeLoc.h:2259
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition TypeLoc.h:2502
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:2484
void setTemplateNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2490
void setAttrNameLoc(SourceLocation loc)
Definition TypeLoc.h:1948
void setAttrOperandParensRange(SourceRange range)
Definition TypeLoc.h:1969
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2572
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:2552
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition TypeLoc.h:2561
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2067
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2039
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:232
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
DiagnosticOptions & getDiagnosticOptions() const
Retrieve the diagnostic options.
Definition Diagnostic.h:597
bool getEnableAllWarnings() const
Definition Diagnostic.h:697
Level
The level of the diagnostic, after it has been through mapping.
Definition Diagnostic.h:237
Level getDiagnosticLevel(unsigned DiagID, SourceLocation Loc) const
Based on the way the client configured the DiagnosticsEngine object, classify the specified diagnosti...
Definition Diagnostic.h:966
bool getSuppressSystemWarnings() const
Definition Diagnostic.h:723
bool getWarningsAsErrors() const
Definition Diagnostic.h:705
diag::Severity getExtensionHandlingBehavior() const
Definition Diagnostic.h:810
const IntrusiveRefCntPtr< DiagnosticIDs > & getDiagnosticIDs() const
Definition Diagnostic.h:592
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:3160
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::vfs::FileSystem & getVirtualFileSystem() const
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,...
OptionalFileEntryRef getOptionalFileRef(StringRef Filename, bool OpenFile=false, bool CacheFailure=true)
Get a FileEntryRef if it exists, without doing anything on error.
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...
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:2000
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5269
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5558
Wrapper for source info for functions.
Definition TypeLoc.h:1615
unsigned getNumParams() const
Definition TypeLoc.h:1687
void setLocalRangeBegin(SourceLocation L)
Definition TypeLoc.h:1635
void setLParenLoc(SourceLocation Loc)
Definition TypeLoc.h:1651
void setParam(unsigned i, ParmVarDecl *VD)
Definition TypeLoc.h:1694
void setRParenLoc(SourceLocation Loc)
Definition TypeLoc.h:1659
void setLocalRangeEnd(SourceLocation L)
Definition TypeLoc.h:1643
void setExceptionSpecRange(SourceRange R)
Definition TypeLoc.h:1673
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.
Module * lookupModule(StringRef ModuleName, SourceLocation ImportLoc=SourceLocation(), bool AllowSearch=true, bool AllowExtraModuleMapSearch=false)
Lookup a module Search for a module with the given name.
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) const
Get a pointer to the pCM if it exists; else nullptr.
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:3467
Wrapper for source info for injected class names of class templates.
Definition TypeLoc.h:872
void setAmpLoc(SourceLocation Loc)
Definition TypeLoc.h:1585
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:1354
void setAttrRowOperand(Expr *e)
Definition TypeLoc.h:2102
void setAttrColumnOperand(Expr *e)
Definition TypeLoc.h:2108
void setAttrOperandParensRange(SourceRange range)
Definition TypeLoc.h:2117
void setAttrNameLoc(SourceLocation loc)
Definition TypeLoc.h:2096
void setStarLoc(SourceLocation Loc)
Definition TypeLoc.h:1521
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition TypeLoc.h:1530
The module cache used for compiling modules implicitly.
Definition ModuleCache.h:26
virtual InMemoryModuleCache & getInMemoryModuleCache()=0
Returns this process's view of the module cache.
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:62
void setUmbrellaDirAsWritten(Module *Mod, DirectoryEntryRef UmbrellaDir, const Twine &NameAsWritten, const Twine &PathRelativeToRootModuleDirectory)
Sets the umbrella directory of the given module to the given directory.
OptionalFileEntryRef getContainingModuleMapFile(const Module *Module) const
Module * findModule(StringRef Name) const
Retrieve a module with the given name.
void setInferredModuleAllowedBy(Module *M, FileID ModMapFID)
void setUmbrellaHeaderAsWritten(Module *Mod, FileEntryRef UmbrellaHeader, const Twine &NameAsWritten, const Twine &PathRelativeToRootModuleDirectory)
Sets the umbrella header of the given module to the given header.
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:539
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:51
ModuleHeaderRole
Flags describing the role of a module header.
Definition ModuleMap.h:126
void addHeader(Module *Mod, Module::Header Header, ModuleHeaderRole Role, bool Imported=false)
Adds this header to the given module.
Describes a module or submodule.
Definition Module.h:144
StringRef getTopLevelModuleName() const
Retrieve the name of the top-level module.
Definition Module.h:732
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
unsigned InferSubmodules
Whether we should infer submodules for this module based on the headers.
Definition Module.h:406
std::vector< std::string > ConfigMacros
The set of "configuration macros", which are macros that (intentionally) change how this module is bu...
Definition Module.h:528
unsigned IsUnimportable
Whether this module has declared itself unimportable, either because it's missing a requirement from ...
Definition Module.h:361
NameVisibilityKind NameVisibility
The visibility of names within this particular module.
Definition Module.h:451
NameVisibilityKind
Describes the visibility of the various names within a particular module.
Definition Module.h:443
@ Hidden
All of the names in this module are hidden.
Definition Module.h:445
@ AllVisible
All of the names in this module are visible.
Definition Module.h:447
SourceLocation DefinitionLoc
The location of the module definition.
Definition Module.h:150
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:341
ModuleKind Kind
The kind of this module.
Definition Module.h:189
void addTopHeaderFilename(StringRef Filename)
Add a top-level header filename associated with this module.
Definition Module.h:772
bool isUnimportable() const
Determine whether this module has been declared unimportable.
Definition Module.h:563
void setASTFile(OptionalFileEntryRef File)
Set the serialized AST file for the top-level module of this module.
Definition Module.h:742
unsigned IsSystem
Whether this is a "system" module (which assumes that all headers in it are system headers).
Definition Module.h:389
std::string Name
The name of this module.
Definition Module.h:147
unsigned IsExternC
Whether this is an 'extern "C"' module (which implicitly puts all headers in it within an 'extern "C"...
Definition Module.h:395
unsigned ModuleMapIsPrivate
Whether this module came from a "private" module map, found next to a regular (public) module map.
Definition Module.h:434
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:520
SmallVector< UnresolvedExportDecl, 2 > UnresolvedExports
The set of export declarations that have yet to be resolved.
Definition Module.h:489
std::optional< Header > getUmbrellaHeaderAsWritten() const
Retrieve the umbrella header as written.
Definition Module.h:756
SmallVector< Requirement, 2 > Requirements
The set of language features required to use this module.
Definition Module.h:352
bool isHeaderLikeModule() const
Is this module have similar semantics as headers.
Definition Module.h:648
OptionalDirectoryEntryRef Directory
The build directory of this module.
Definition Module.h:198
unsigned NamedModuleHasInit
Whether this C++20 named modules doesn't need an initializer.
Definition Module.h:439
StringRef getPrimaryModuleInterfaceName() const
Get the primary module interface name from a partition.
Definition Module.h:687
unsigned ConfigMacrosExhaustive
Whether the set of configuration macros is exhaustive.
Definition Module.h:424
std::string PresumedModuleMapFile
The presumed file name for the module map defining this module.
Definition Module.h:202
ASTFileSignature Signature
The module signature.
Definition Module.h:208
bool isGlobalModule() const
Does this Module scope describe a fragment of the global module within some C++ module.
Definition Module.h:239
unsigned InferExportWildcard
Whether, when inferring submodules, the inferr submodules should export all modules they import (e....
Definition Module.h:416
void getExportedModules(SmallVectorImpl< Module * > &Exported) const
Appends this module's list of exported modules to Exported.
Definition Module.cpp:383
std::vector< UnresolvedConflict > UnresolvedConflicts
The list of conflicts for which the module-id has not yet been resolved.
Definition Module.h:541
unsigned IsFromModuleFile
Whether this module was loaded from a module file.
Definition Module.h:376
llvm::PointerIntPair< Module *, 1, bool > ExportDecl
Describes an exported module.
Definition Module.h:468
std::optional< DirectoryName > getUmbrellaDirAsWritten() const
Retrieve the umbrella directory as written.
Definition Module.h:748
std::string ExportAsModule
The module through which entities defined in this module will eventually be exposed,...
Definition Module.h:218
unsigned IsAvailable
Whether this module is available in the current translation unit.
Definition Module.h:372
unsigned InferExplicitSubmodules
Whether, when inferring submodules, the inferred submodules should be explicit.
Definition Module.h:411
OptionalFileEntryRef getASTFile() const
The serialized AST file for this module, if one was created.
Definition Module.h:737
std::vector< Conflict > Conflicts
The list of conflicts.
Definition Module.h:553
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:1841
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 'absent' clause in the 'pragma omp assume' directive.
static OMPAbsentClause * CreateEmpty(const ASTContext &C, unsigned NumKinds)
This represents 'acq_rel' clause in the 'pragma omp atomic|flush' directives.
This represents 'acquire' clause in the 'pragma omp atomic|flush' directives.
This represents clause 'affinity' in the 'pragma omp task'-based directives.
static OMPAffinityClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with the place for N locator items.
This represents the 'align' clause in the 'pragma omp allocate' directive.
This represents clause 'aligned' in the 'pragma omp ...' directives.
static OMPAlignedClause * CreateEmpty(const ASTContext &C, unsigned NumVars)
Creates an empty clause with the place for NumVars variables.
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.
This represents 'at' clause in the 'pragma omp error' directive.
This represents 'atomic_default_mem_order' clause in the 'pragma omp requires' directive.
This represents 'bind' clause in the 'pragma omp ...' directives.
static OMPBindClause * CreateEmpty(const ASTContext &C)
Build an empty 'bind' clause.
This represents 'capture' clause in the 'pragma omp atomic' directive.
Contains data for OpenMP directives: clauses, children expressions/statements (helpers for codegen) a...
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 'compare' clause in the 'pragma omp atomic' directive.
This represents the 'contains' clause in the 'pragma omp assume' directive.
static OMPContainsClause * CreateEmpty(const ASTContext &C, unsigned NumKinds)
This represents clause 'copyin' in the 'pragma omp ...' directives.
static OMPCopyinClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with N variables.
This represents clause 'copyprivate' in the 'pragma omp ...' directives.
static OMPCopyprivateClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with N variables.
This represents 'default' clause in the 'pragma omp ...' directive.
This represents 'defaultmap' clause in the 'pragma omp ...' directive.
This represents implicit clause 'depend' for the 'pragma omp task' directive.
static OMPDependClause * CreateEmpty(const ASTContext &C, unsigned N, unsigned NumLoops)
Creates an empty clause with N variables.
This represents implicit clause 'depobj' for the 'pragma omp depobj' directive.
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.
This represents the 'doacross' clause for the 'pragma omp ordered' 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 ....
This represents 'dynamic_allocators' clause in the 'pragma omp requires' directive.
This represents clause 'exclusive' in the 'pragma omp scan' directive.
static OMPExclusiveClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with the place for N variables.
This represents 'fail' clause in the 'pragma omp atomic' directive.
This represents 'filter' clause in the 'pragma omp ...' directive.
This represents 'final' clause in the 'pragma omp ...' directive.
This represents clause 'firstprivate' in the 'pragma omp ...' directives.
static OMPFirstprivateClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with the place for N variables.
This represents implicit clause 'flush' for the 'pragma omp flush' directive.
static OMPFlushClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with N variables.
This represents clause 'from' in the 'pragma omp ...' directives.
static OMPFromClause * CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes)
Creates an empty clause with the place for NumVars variables.
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 'grainsize' clause in the 'pragma omp ...' directive.
This represents clause 'has_device_ptr' in the 'pragma omp ...' directives.
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.
This represents the 'holds' clause in the 'pragma omp assume' directive.
This represents 'if' clause in the 'pragma omp ...' directive.
This represents clause 'in_reduction' in the 'pragma omp task' directives.
static OMPInReductionClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with the place for N variables.
This represents clause 'inclusive' in the 'pragma omp scan' directive.
static OMPInclusiveClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with the place for N variables.
This represents the 'init' clause in 'pragma omp ...' directives.
static OMPInitClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with N expressions.
This represents clause 'is_device_ptr' in the 'pragma omp ...' directives.
static OMPIsDevicePtrClause * CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes)
Creates an empty clause with the place for NumVars variables.
This represents clause 'lastprivate' in the 'pragma omp ...' directives.
static OMPLastprivateClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with the place for N variables.
This represents clause 'linear' in the 'pragma omp ...' directives.
static OMPLinearClause * CreateEmpty(const ASTContext &C, unsigned NumVars)
Creates an empty clause with the place for NumVars variables.
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 clause 'map' in the 'pragma omp ...' directives.
static OMPMapClause * CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes)
Creates an empty clause with the place for NumVars original expressions, NumUniqueDeclarations declar...
This represents 'mergeable' clause in the 'pragma omp ...' directive.
This represents the 'message' clause in the 'pragma omp error' and the 'pragma omp parallel' directiv...
This represents the 'no_openmp' clause in the 'pragma omp assume' directive.
This represents the 'no_openmp_constructs' clause in the.
This represents the 'no_openmp_routines' clause in the 'pragma omp assume' directive.
This represents the 'no_parallelism' clause in the 'pragma omp assume' directive.
This represents 'nocontext' clause in the 'pragma omp ...' directive.
This represents 'nogroup' clause in the 'pragma omp ...' directive.
This represents clause 'nontemporal' in the 'pragma omp ...' directives.
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 'nowait' clause in the 'pragma omp ...' directive.
This represents 'num_tasks' clause in the 'pragma omp ...' directive.
This represents 'num_teams' clause in the 'pragma omp ...' directive.
static OMPNumTeamsClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with N variables.
This represents 'num_threads' clause in the 'pragma omp ...' directive.
This represents 'order' clause in the 'pragma omp ...' directive.
This represents 'ordered' clause in the 'pragma omp ...' directive.
static OMPOrderedClause * CreateEmpty(const ASTContext &C, unsigned NumLoops)
Build an empty clause.
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 'priority' clause in the 'pragma omp ...' directive.
This represents clause 'private' in the 'pragma omp ...' directives.
static OMPPrivateClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with the place for N variables.
This represents 'proc_bind' clause in the 'pragma omp ...' directive.
This represents 'read' clause in the 'pragma omp atomic' directive.
This represents clause 'reduction' in the 'pragma omp ...' directives.
static OMPReductionClause * CreateEmpty(const ASTContext &C, unsigned N, OpenMPReductionClauseModifier Modifier)
Creates an empty clause with the place for N variables.
This represents 'relaxed' clause in the 'pragma omp atomic' directives.
This represents 'release' clause in the 'pragma omp atomic|flush' directives.
This represents 'reverse_offload' clause in the 'pragma omp requires' directive.
This represents 'simd' clause in the 'pragma omp ...' directive.
This represents 'safelen' clause in the 'pragma omp ...' directive.
This represents 'schedule' clause in the 'pragma omp ...' directive.
This represents 'self_maps' clause in the 'pragma omp requires' directive.
This represents 'seq_cst' clause in the 'pragma omp atomic|flush' directives.
This represents the 'severity' clause in the 'pragma omp error' and the 'pragma omp parallel' directi...
This represents clause 'shared' in the 'pragma omp ...' directives.
static OMPSharedClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with N variables.
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 clause 'task_reduction' in the 'pragma omp taskgroup' directives.
static OMPTaskReductionClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with the place for N variables.
This represents 'thread_limit' 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.
This represents 'threadset' clause in the 'pragma omp task ...' directive.
This represents clause 'to' in the 'pragma omp ...' directives.
static OMPToClause * CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes)
Creates an empty clause with the place for NumVars variables.
Helper data structure representing the traits in a match clause of an declare variant or metadirectiv...
llvm::SmallVector< OMPTraitSet, 2 > Sets
The outermost level of selector sets.
This represents 'unified_address' clause in the 'pragma omp requires' directive.
This represents 'unified_shared_memory' clause in the 'pragma omp requires' directive.
This represents 'untied' clause in the 'pragma omp ...' directive.
This represents 'update' clause in the 'pragma omp atomic' directive.
static OMPUpdateClause * CreateEmpty(const ASTContext &C, bool IsExtended)
Creates an empty clause with the place for N variables.
This represents the 'use' clause in 'pragma omp ...' directives.
This represents clause 'use_device_addr' in the 'pragma omp ...' directives.
static OMPUseDeviceAddrClause * CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes)
Creates an empty clause with the place for NumVars variables.
This represents clause 'use_device_ptr' in the 'pragma omp ...' directives.
static OMPUseDevicePtrClause * CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes)
Creates an empty clause with the place for NumVars variables.
This represents clause 'uses_allocators' in the 'pragma omp target'-based directives.
static OMPUsesAllocatorsClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with the place for N allocators.
This represents 'weak' clause in the 'pragma omp atomic' directives.
This represents 'write' clause in the 'pragma omp atomic' directive.
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.
method_range methods() const
Definition DeclObjC.h:1016
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:1284
void setNameEndLoc(SourceLocation Loc)
Definition TypeLoc.h:1296
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:1563
void setTypeArgsRAngleLoc(SourceLocation Loc)
Definition TypeLoc.h:1167
unsigned getNumTypeArgs() const
Definition TypeLoc.h:1171
unsigned getNumProtocols() const
Definition TypeLoc.h:1201
void setTypeArgsLAngleLoc(SourceLocation Loc)
Definition TypeLoc.h:1159
void setTypeArgTInfo(unsigned i, TypeSourceInfo *TInfo)
Definition TypeLoc.h:1180
void setProtocolLAngleLoc(SourceLocation Loc)
Definition TypeLoc.h:1189
void setProtocolRAngleLoc(SourceLocation Loc)
Definition TypeLoc.h:1197
void setHasBaseTypeAsWritten(bool HasBaseType)
Definition TypeLoc.h:1229
void setProtocolLoc(unsigned i, SourceLocation Loc)
Definition TypeLoc.h:1210
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)
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.
bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, StringRef ModuleFilename, StringRef SpecificModuleCachePath, bool Complain) override
Receives the header search 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 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:2604
void setEllipsisLoc(SourceLocation Loc)
Definition TypeLoc.h:2287
void setRParenLoc(SourceLocation Loc)
Definition TypeLoc.h:1386
void setLParenLoc(SourceLocation Loc)
Definition TypeLoc.h:1382
Represents a parameter to a function.
Definition Decl.h:1790
void setKWLoc(SourceLocation Loc)
Definition TypeLoc.h:2696
void setStarLoc(SourceLocation Loc)
Definition TypeLoc.h:1490
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:1599
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:5326
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:855
SemaObjC & ObjC()
Definition Sema.h:1487
void addExternalSource(IntrusiveRefCntPtr< ExternalSemaSource > E)
Registers an external source.
Definition Sema.cpp:655
IdentifierResolver IdResolver
Definition Sema.h:3461
PragmaMsStackAction
Definition Sema.h:1818
ASTReaderListenter implementation to set SuggestedPredefines of ASTReader which is required to use a ...
Definition ASTReader.h:362
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:85
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:1884
void set(SourceLocation ElaboratedKeywordLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKeywordLoc, SourceLocation NameLoc, SourceLocation LAngleLoc, SourceLocation RAngleLoc)
Definition TypeLoc.cpp:644
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:3357
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:2236
A container of type source information.
Definition TypeBase.h:8264
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:1833
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9112
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3562
void setLParenLoc(SourceLocation Loc)
Definition TypeLoc.h:2179
void setTypeofLoc(SourceLocation Loc)
Definition TypeLoc.h:2171
void setRParenLoc(SourceLocation Loc)
Definition TypeLoc.h:2187
void setRParenLoc(SourceLocation Loc)
Definition TypeLoc.h:2321
void setKWLoc(SourceLocation Loc)
Definition TypeLoc.h:2315
void setUnderlyingTInfo(TypeSourceInfo *TInfo)
Definition TypeLoc.h:2327
void setLParenLoc(SourceLocation Loc)
Definition TypeLoc.h:2318
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:926
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2016
Captures information about a #pragma weak directive.
Definition Weak.h:25
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:84
OptionalFileEntryRef getFile() const
Definition ModuleFile.h:113
static InputFile getNotFound()
Definition ModuleFile.h:107
Information about a module that has been loaded by the ASTReader.
Definition ModuleFile.h:130
const PPEntityOffset * PreprocessedEntityOffsets
Definition ModuleFile.h:372
void * IdentifierLookupTable
A pointer to an on-disk hash table of opaque type IdentifierHashTable.
Definition ModuleFile.h:327
void * SelectorLookupTable
A pointer to an on-disk hash table of opaque type ASTSelectorLookupTable.
Definition ModuleFile.h:435
std::vector< std::unique_ptr< ModuleFileExtensionReader > > ExtensionReaders
The list of extension readers that are attached to this module file.
Definition ModuleFile.h:246
SourceLocation DirectImportLoc
The source location where the module was explicitly or implicitly imported in the local translation u...
Definition ModuleFile.h:236
StringRef Data
The serialized bitstream data for this file.
Definition ModuleFile.h:222
const serialization::ObjCCategoriesInfo * ObjCCategoriesMap
Array of category list location information within this module file, sorted by the definition ID.
Definition ModuleFile.h:463
int SLocEntryBaseID
The base ID in the source manager's view of this module.
Definition ModuleFile.h:291
serialization::IdentifierID BaseIdentifierID
Base identifier ID for identifiers local to this module.
Definition ModuleFile.h:317
serialization::PreprocessedEntityID BasePreprocessedEntityID
Base preprocessed entity ID for preprocessed entities local to this module.
Definition ModuleFile.h:370
serialization::TypeID BaseTypeIndex
Base type ID for types local to this module as represented in the global type ID space.
Definition ModuleFile.h:483
unsigned LocalNumObjCCategoriesInMap
The number of redeclaration info entries in ObjCCategoriesMap.
Definition ModuleFile.h:466
uint64_t MacroOffsetsBase
Base file offset for the offsets in MacroOffsets.
Definition ModuleFile.h:344
const llvm::support::unaligned_uint64_t * InputFileOffsets
Relative offsets for all of the input file entries in the AST file.
Definition ModuleFile.h:261
std::vector< unsigned > PreloadIdentifierOffsets
Offsets of identifiers that we're going to preload within IdentifierTableData.
Definition ModuleFile.h:331
unsigned LocalNumIdentifiers
The number of identifiers in this AST file.
Definition ModuleFile.h:307
llvm::BitstreamCursor DeclsCursor
DeclsCursor - This is a cursor to the start of the DECLTYPES_BLOCK block.
Definition ModuleFile.h:442
const unsigned char * IdentifierTableData
Actual data for the on-disk hash table of identifiers.
Definition ModuleFile.h:323
uint64_t SLocEntryOffsetsBase
Base file offset for the offsets in SLocEntryOffsets.
Definition ModuleFile.h:298
llvm::BitstreamCursor InputFilesCursor
The cursor to the start of the input-files block.
Definition ModuleFile.h:255
std::vector< InputFile > InputFilesLoaded
The input files that have been loaded from this AST file.
Definition ModuleFile.h:264
serialization::SelectorID BaseSelectorID
Base selector ID for selectors local to this module.
Definition ModuleFile.h:420
llvm::SetVector< ModuleFile * > ImportedBy
List of modules which depend on this module.
Definition ModuleFile.h:491
const char * HeaderFileInfoTableData
Actual data for the on-disk hash table of header file information.
Definition ModuleFile.h:391
SourceLocation ImportLoc
The source location where this module was first imported.
Definition ModuleFile.h:239
const serialization::unaligned_decl_id_t * FileSortedDecls
Array of file-level DeclIDs sorted by file.
Definition ModuleFile.h:458
const uint32_t * SLocEntryOffsets
Offsets for all of the source location entries in the AST file.
Definition ModuleFile.h:302
llvm::BitstreamCursor MacroCursor
The cursor to the start of the preprocessor block, which stores all of the macro definitions.
Definition ModuleFile.h:337
FileID OriginalSourceFileID
The file ID for the original source file that was used to build this AST file.
Definition ModuleFile.h:168
FileEntryRef File
The file entry for the module file.
Definition ModuleFile.h:185
std::string ActualOriginalSourceFileName
The actual original source file name that was used to build this AST file.
Definition ModuleFile.h:164
uint64_t PreprocessorDetailStartOffset
The offset of the start of the preprocessor detail cursor.
Definition ModuleFile.h:366
std::vector< InputFileInfo > InputFileInfosLoaded
The input file infos that have been loaded from this AST file.
Definition ModuleFile.h:267
unsigned LocalNumSubmodules
The number of submodules in this module.
Definition ModuleFile.h:400
SourceLocation FirstLoc
The first source location in this module.
Definition ModuleFile.h:242
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:193
uint64_t SourceManagerBlockStartOffset
The bit offset to the start of the SOURCE_MANAGER_BLOCK.
Definition ModuleFile.h:285
bool DidReadTopLevelSubmodule
Whether the top-level module has been read from the AST file.
Definition ModuleFile.h:182
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:160
bool isModule() const
Is this a module file for a module (rather than a PCH or similar).
Definition ModuleFile.h:509
bool HasTimestamps
Whether timestamps are included in this module file.
Definition ModuleFile.h:179
uint64_t InputFilesOffsetBase
Absolute offset of the start of the input-files block.
Definition ModuleFile.h:258
llvm::BitstreamCursor SLocEntryCursor
Cursor used to read source location entries.
Definition ModuleFile.h:282
bool RelocatablePCH
Whether this precompiled header is a relocatable PCH file.
Definition ModuleFile.h:173
const uint32_t * SelectorOffsets
Offsets into the selector lookup table's data array where each selector resides.
Definition ModuleFile.h:417
unsigned BaseDeclIndex
Base declaration index in ASTReader for declarations local to this module.
Definition ModuleFile.h:455
unsigned LocalNumSLocEntries
The number of source location entries in this AST file.
Definition ModuleFile.h:288
void * HeaderFileInfoTable
The on-disk hash table that contains information about each of the header files.
Definition ModuleFile.h:395
unsigned Index
The index of this module in the list of modules.
Definition ModuleFile.h:139
llvm::BitstreamCursor Stream
The main bitstream cursor for the main block.
Definition ModuleFile.h:225
serialization::SubmoduleID BaseSubmoduleID
Base submodule ID for submodules local to this module.
Definition ModuleFile.h:403
uint64_t SizeInBits
The size of this file, in bits.
Definition ModuleFile.h:213
const UnalignedUInt64 * TypeOffsets
Offset of each type within the bitstream, indexed by the type ID, or the representation of a Type*.
Definition ModuleFile.h:479
uint64_t GlobalBitOffset
The global bit offset (or base) of this module.
Definition ModuleFile.h:216
bool StandardCXXModule
Whether this module file is a standard C++ module.
Definition ModuleFile.h:176
unsigned LocalNumTypes
The number of types in this AST file.
Definition ModuleFile.h:475
StringRef ModuleOffsetMap
The module offset map data for this file.
Definition ModuleFile.h:250
const PPSkippedRange * PreprocessedSkippedRangeOffsets
Definition ModuleFile.h:378
std::string FileName
The file name of the module file.
Definition ModuleFile.h:145
uint64_t InputFilesValidationTimestamp
If non-zero, specifies the time when we last validated input files.
Definition ModuleFile.h:277
llvm::BitstreamCursor PreprocessorDetailCursor
The cursor to the start of the (optional) detailed preprocessing record block.
Definition ModuleFile.h:363
SourceLocation::UIntTy SLocEntryBaseOffset
The base offset in the source manager's view of this module.
Definition ModuleFile.h:294
const DeclOffset * DeclOffsets
Offset of each declaration within the bitstream, indexed by the declaration ID (-1).
Definition ModuleFile.h:452
uint64_t MacroStartOffset
The offset of the start of the set of defined macros.
Definition ModuleFile.h:357
ASTFileSignature Signature
The signature of the module file, which may be used instead of the size and modification time to iden...
Definition ModuleFile.h:189
unsigned LocalNumMacros
The number of macros in this AST file.
Definition ModuleFile.h:340
const unsigned char * SelectorLookupTableData
A pointer to the character data that comprises the selector table.
Definition ModuleFile.h:428
void dump()
Dump debugging output for this module.
unsigned LocalNumDecls
The number of declarations in this AST file.
Definition ModuleFile.h:448
unsigned LocalNumHeaderFileInfos
The number of local HeaderFileInfo structures.
Definition ModuleFile.h:384
llvm::BitVector SearchPathUsage
The bit vector denoting usage of each header search entry (true = used).
Definition ModuleFile.h:196
unsigned Generation
The generation of which this module file is a part.
Definition ModuleFile.h:206
const uint32_t * IdentifierOffsets
Offsets into the identifier table data.
Definition ModuleFile.h:314
ContinuousRangeMap< uint32_t, int, 2 > SelectorRemap
Remapping table for selector IDs in this module.
Definition ModuleFile.h:423
const uint32_t * MacroOffsets
Offsets of macros in the preprocessor block.
Definition ModuleFile.h:351
uint64_t ASTBlockStartOffset
The bit offset of the AST block of this module.
Definition ModuleFile.h:219
ContinuousRangeMap< uint32_t, int, 2 > SubmoduleRemap
Remapping table for submodule IDs in this module.
Definition ModuleFile.h:406
llvm::BitVector VFSUsage
The bit vector denoting usage of each VFS entry (true = used).
Definition ModuleFile.h:199
uint64_t DeclsBlockStartOffset
The offset to the start of the DECLTYPES_BLOCK block.
Definition ModuleFile.h:445
SmallVector< uint64_t, 8 > PragmaDiagMappings
Diagnostic IDs and their mappings that the user changed.
Definition ModuleFile.h:488
unsigned BasePreprocessedSkippedRangeID
Base ID for preprocessed skipped ranges local to this module.
Definition ModuleFile.h:376
unsigned LocalNumSelectors
The number of selectors new to this file.
Definition ModuleFile.h:413
ModuleKind Kind
The type of this module.
Definition ModuleFile.h:142
std::string ModuleName
The name of the module.
Definition ModuleFile.h:148
serialization::MacroID BaseMacroID
Base macro ID for macros local to this module.
Definition ModuleFile.h:354
SmallVector< uint64_t, 1 > ObjCCategories
The Objective-C category lists for categories known to this module.
Definition ModuleFile.h:470
std::string BaseDirectory
The base directory of the module.
Definition ModuleFile.h:151
llvm::SmallVector< ModuleFile *, 16 > TransitiveImports
List of modules which this modules dependent on.
Definition ModuleFile.h:502
Manages the set of modules loaded by an AST reader.
AddModuleResult
The result of attempting to add a new module.
@ 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.
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)
#define bool
Definition gpuintrin.h:32
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.
@ 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_METADATA
Metadata for submodules as a whole.
@ 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_INITIALIZERS
Specifies some declarations with initializers that must be emitted to initialize the module.
@ 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.
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:43
@ MK_PCH
File is a PCH file treated as such.
Definition ModuleFile.h:51
@ MK_Preamble
File is a PCH file treated as the preamble.
Definition ModuleFile.h:54
@ MK_MainFile
File is a PCH file treated as the actual main file.
Definition ModuleFile.h:57
@ MK_ExplicitModule
File is an explicitly-loaded module.
Definition ModuleFile.h:48
@ MK_ImplicitModule
File is an implicitly-loaded module.
Definition ModuleFile.h:45
@ MK_PrebuiltModule
File is from a prebuilt module path.
Definition ModuleFile.h:60
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.
@ 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.
@ 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:3704
@ 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:123
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.
const FunctionProtoType * T
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
@ Type
The name was classified as a type.
Definition Sema.h:563
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:47
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:50
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:2714
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:178
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:5882
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
The signature of a module, which is a hash of the AST content.
Definition Module.h:58
static constexpr size_t size
Definition Module.h:61
static ASTFileSignature create(std::array< uint8_t, 20 > Bytes)
Definition Module.h:81
static ASTFileSignature createDummy()
Definition Module.h:91
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:544
Module * Other
The module that this module conflicts with.
Definition Module.h:546
std::string Message
The message provided to the user when there is a conflict.
Definition Module.h:549
Information about a header directive as found in the module map file.
Definition Module.h:287
This structure contains all sizes needed for by an OMPMappableExprListClause.
unsigned NumComponentLists
Number of component lists.
unsigned NumVars
Number of expressions listed.
unsigned NumUniqueDeclarations
Number of unique base declarations.
unsigned NumComponents
Total number of expression components.
SourceLocation LParenLoc
Locations of '(' and ')' symbols.
Expr * AllocatorTraits
Allocator traits.
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:1829
llvm::DenseSet< std::tuple< Decl *, Decl *, int > > NonEquivalentDeclSet
Store declaration pairs already found to be non-equivalent.
Location information for a TemplateArgument.
The input file info that has been loaded from an AST file.
Definition ModuleFile.h:64
Describes the categories of an Objective-C class.
#define log(__x)
Definition tgmath.h:460