clang 23.0.0git
ASTReader.cpp
Go to the documentation of this file.
1//===- ASTReader.cpp - AST File Reader ------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the ASTReader class, which reads AST files.
10//
11//===----------------------------------------------------------------------===//
12
13#include "ASTCommon.h"
14#include "ASTReaderInternals.h"
22#include "clang/AST/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 ContextHash, bool Complain) {
212 return First->ReadHeaderSearchOptions(HSOpts, ModuleFilename, ContextHash,
213 Complain) ||
214 Second->ReadHeaderSearchOptions(HSOpts, ModuleFilename, ContextHash,
215 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(FileManager &FileMgr, StringRef ContextHash,
964 StringRef ExistingSpecificModuleCachePath,
965 StringRef ASTFilename,
966 DiagnosticsEngine *Diags,
967 const LangOptions &LangOpts,
968 const PreprocessorOptions &PPOpts,
969 const HeaderSearchOptions &HSOpts,
970 const HeaderSearchOptions &ASTFileHSOpts) {
971 std::string SpecificModuleCachePath = createSpecificModuleCachePath(
972 FileMgr, ASTFileHSOpts.ModuleCachePath, ASTFileHSOpts.DisableModuleHash,
973 std::string(ContextHash));
974
975 if (!LangOpts.Modules || PPOpts.AllowPCHWithDifferentModulesCachePath ||
976 SpecificModuleCachePath == ExistingSpecificModuleCachePath)
977 return false;
978 auto EqualOrErr = FileMgr.getVirtualFileSystem().equivalent(
979 SpecificModuleCachePath, ExistingSpecificModuleCachePath);
980 if (EqualOrErr && *EqualOrErr)
981 return false;
982 if (Diags) {
983 // If the module cache arguments provided from the command line are the
984 // same, the mismatch must come from other arguments of the configuration
985 // and not directly the cache path.
986 EqualOrErr = FileMgr.getVirtualFileSystem().equivalent(
987 ASTFileHSOpts.ModuleCachePath, HSOpts.ModuleCachePath);
988 if (EqualOrErr && *EqualOrErr)
989 Diags->Report(clang::diag::warn_ast_file_config_mismatch) << ASTFilename;
990 else
991 Diags->Report(diag::err_ast_file_modulecache_mismatch)
992 << SpecificModuleCachePath << ExistingSpecificModuleCachePath
993 << ASTFilename;
994 }
995 return true;
996}
997
999 StringRef ASTFilename,
1000 StringRef ContextHash,
1001 bool Complain) {
1002 const HeaderSearch &HeaderSearchInfo = PP.getHeaderSearchInfo();
1003 return checkModuleCachePath(Reader.getFileManager(), ContextHash,
1004 HeaderSearchInfo.getSpecificModuleCachePath(),
1005 ASTFilename, Complain ? &Reader.Diags : nullptr,
1006 PP.getLangOpts(), PP.getPreprocessorOpts(),
1007 HeaderSearchInfo.getHeaderSearchOpts(), HSOpts);
1008}
1009
1011 PP.setCounterValue(Value);
1012}
1013
1014//===----------------------------------------------------------------------===//
1015// AST reader implementation
1016//===----------------------------------------------------------------------===//
1017
1018static uint64_t readULEB(const unsigned char *&P) {
1019 unsigned Length = 0;
1020 const char *Error = nullptr;
1021
1022 uint64_t Val = llvm::decodeULEB128(P, &Length, nullptr, &Error);
1023 if (Error)
1024 llvm::report_fatal_error(Error);
1025 P += Length;
1026 return Val;
1027}
1028
1029/// Read ULEB-encoded key length and data length.
1030static std::pair<unsigned, unsigned>
1031readULEBKeyDataLength(const unsigned char *&P) {
1032 unsigned KeyLen = readULEB(P);
1033 if ((unsigned)KeyLen != KeyLen)
1034 llvm::report_fatal_error("key too large");
1035
1036 unsigned DataLen = readULEB(P);
1037 if ((unsigned)DataLen != DataLen)
1038 llvm::report_fatal_error("data too large");
1039
1040 return std::make_pair(KeyLen, DataLen);
1041}
1042
1044 bool TakeOwnership) {
1045 DeserializationListener = Listener;
1046 OwnsDeserializationListener = TakeOwnership;
1047}
1048
1052
1054 LocalDeclID ID(Value);
1055#ifndef NDEBUG
1056 if (!MF.ModuleOffsetMap.empty())
1057 Reader.ReadModuleOffsetMap(MF);
1058
1059 unsigned ModuleFileIndex = ID.getModuleFileIndex();
1060 unsigned LocalDeclID = ID.getLocalDeclIndex();
1061
1062 assert(ModuleFileIndex <= MF.TransitiveImports.size());
1063
1064 ModuleFile *OwningModuleFile =
1065 ModuleFileIndex == 0 ? &MF : MF.TransitiveImports[ModuleFileIndex - 1];
1066 assert(OwningModuleFile);
1067
1068 unsigned LocalNumDecls = OwningModuleFile->LocalNumDecls;
1069
1070 if (!ModuleFileIndex)
1071 LocalNumDecls += NUM_PREDEF_DECL_IDS;
1072
1073 assert(LocalDeclID < LocalNumDecls);
1074#endif
1075 (void)Reader;
1076 (void)MF;
1077 return ID;
1078}
1079
1080LocalDeclID LocalDeclID::get(ASTReader &Reader, ModuleFile &MF,
1081 unsigned ModuleFileIndex, unsigned LocalDeclID) {
1082 DeclID Value = (DeclID)ModuleFileIndex << 32 | (DeclID)LocalDeclID;
1083 return LocalDeclID::get(Reader, MF, Value);
1084}
1085
1086std::pair<unsigned, unsigned>
1088 return readULEBKeyDataLength(d);
1089}
1090
1092ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
1093 using namespace llvm::support;
1094
1095 SelectorTable &SelTable = Reader.getContext().Selectors;
1096 unsigned N = endian::readNext<uint16_t, llvm::endianness::little>(d);
1097 const IdentifierInfo *FirstII = Reader.getLocalIdentifier(
1098 F, endian::readNext<IdentifierID, llvm::endianness::little>(d));
1099 if (N == 0)
1100 return SelTable.getNullarySelector(FirstII);
1101 else if (N == 1)
1102 return SelTable.getUnarySelector(FirstII);
1103
1105 Args.push_back(FirstII);
1106 for (unsigned I = 1; I != N; ++I)
1107 Args.push_back(Reader.getLocalIdentifier(
1108 F, endian::readNext<IdentifierID, llvm::endianness::little>(d)));
1109
1110 return SelTable.getSelector(N, Args.data());
1111}
1112
1115 unsigned DataLen) {
1116 using namespace llvm::support;
1117
1119
1120 Result.ID = Reader.getGlobalSelectorID(
1121 F, endian::readNext<uint32_t, llvm::endianness::little>(d));
1122 unsigned FullInstanceBits =
1123 endian::readNext<uint16_t, llvm::endianness::little>(d);
1124 unsigned FullFactoryBits =
1125 endian::readNext<uint16_t, llvm::endianness::little>(d);
1126 Result.InstanceBits = FullInstanceBits & 0x3;
1127 Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
1128 Result.FactoryBits = FullFactoryBits & 0x3;
1129 Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
1130 unsigned NumInstanceMethods = FullInstanceBits >> 3;
1131 unsigned NumFactoryMethods = FullFactoryBits >> 3;
1132
1133 // Load instance methods
1134 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
1135 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
1137 Reader, F,
1138 endian::readNext<DeclID, llvm::endianness::little>(d))))
1139 Result.Instance.push_back(Method);
1140 }
1141
1142 // Load factory methods
1143 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
1144 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
1146 Reader, F,
1147 endian::readNext<DeclID, llvm::endianness::little>(d))))
1148 Result.Factory.push_back(Method);
1149 }
1150
1151 return Result;
1152}
1153
1155 return llvm::djbHash(a);
1156}
1157
1158std::pair<unsigned, unsigned>
1160 return readULEBKeyDataLength(d);
1161}
1162
1164ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
1165 assert(n >= 2 && d[n-1] == '\0');
1166 return StringRef((const char*) d, n-1);
1167}
1168
1169/// Whether the given identifier is "interesting".
1170static bool isInterestingIdentifier(ASTReader &Reader, const IdentifierInfo &II,
1171 bool IsModule) {
1172 bool IsInteresting =
1173 II.getNotableIdentifierID() != tok::NotableIdentifierKind::not_notable ||
1175 II.getObjCKeywordID() != tok::ObjCKeywordKind::objc_not_keyword;
1176 return II.hadMacroDefinition() || II.isPoisoned() ||
1177 (!IsModule && IsInteresting) || II.hasRevertedTokenIDToIdentifier() ||
1178 (!(IsModule && Reader.getPreprocessor().getLangOpts().CPlusPlus) &&
1179 II.getFETokenInfo());
1180}
1181
1182static bool readBit(unsigned &Bits) {
1183 bool Value = Bits & 0x1;
1184 Bits >>= 1;
1185 return Value;
1186}
1187
1189 using namespace llvm::support;
1190
1191 IdentifierID RawID =
1192 endian::readNext<IdentifierID, llvm::endianness::little>(d);
1193 return Reader.getGlobalIdentifierID(F, RawID >> 1);
1194}
1195
1197 bool IsModule) {
1198 if (!II.isFromAST()) {
1199 II.setIsFromAST();
1200 if (isInterestingIdentifier(Reader, II, IsModule))
1202 }
1203}
1204
1206 const unsigned char* d,
1207 unsigned DataLen) {
1208 using namespace llvm::support;
1209
1210 IdentifierID RawID =
1211 endian::readNext<IdentifierID, llvm::endianness::little>(d);
1212 bool IsInteresting = RawID & 0x01;
1213
1214 DataLen -= sizeof(IdentifierID);
1215
1216 // Wipe out the "is interesting" bit.
1217 RawID = RawID >> 1;
1218
1219 // Build the IdentifierInfo and link the identifier ID with it.
1220 IdentifierInfo *II = KnownII;
1221 if (!II) {
1222 II = &Reader.getIdentifierTable().getOwn(k);
1223 KnownII = II;
1224 }
1225 bool IsModule = Reader.getPreprocessor().getCurrentModule() != nullptr;
1226 markIdentifierFromAST(Reader, *II, IsModule);
1227 Reader.markIdentifierUpToDate(II);
1228
1229 IdentifierID ID = Reader.getGlobalIdentifierID(F, RawID);
1230 if (!IsInteresting) {
1231 // For uninteresting identifiers, there's nothing else to do. Just notify
1232 // the reader that we've finished loading this identifier.
1233 Reader.SetIdentifierInfo(ID, II);
1234 return II;
1235 }
1236
1237 unsigned ObjCOrBuiltinID =
1238 endian::readNext<uint16_t, llvm::endianness::little>(d);
1239 unsigned Bits = endian::readNext<uint16_t, llvm::endianness::little>(d);
1240 bool CPlusPlusOperatorKeyword = readBit(Bits);
1241 bool HasRevertedTokenIDToIdentifier = readBit(Bits);
1242 bool Poisoned = readBit(Bits);
1243 bool ExtensionToken = readBit(Bits);
1244 bool HasMacroDefinition = readBit(Bits);
1245
1246 assert(Bits == 0 && "Extra bits in the identifier?");
1247 DataLen -= sizeof(uint16_t) * 2;
1248
1249 // Set or check the various bits in the IdentifierInfo structure.
1250 // Token IDs are read-only.
1251 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
1253 if (!F.isModule())
1254 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
1255 assert(II->isExtensionToken() == ExtensionToken &&
1256 "Incorrect extension token flag");
1257 (void)ExtensionToken;
1258 if (Poisoned)
1259 II->setIsPoisoned(true);
1260 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
1261 "Incorrect C++ operator keyword flag");
1262 (void)CPlusPlusOperatorKeyword;
1263
1264 // If this identifier has a macro definition, deserialize it or notify the
1265 // visitor the actual definition is in a different module.
1266 if (HasMacroDefinition) {
1267 uint32_t MacroDirectivesOffset =
1268 endian::readNext<uint32_t, llvm::endianness::little>(d);
1269 DataLen -= 4;
1270
1271 if (MacroDirectivesOffset)
1272 Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
1273 else
1274 hasMacroDefinitionInDependencies = true;
1275 }
1276
1277 Reader.SetIdentifierInfo(ID, II);
1278
1279 // Read all of the declarations visible at global scope with this
1280 // name.
1281 if (DataLen > 0) {
1283 for (; DataLen > 0; DataLen -= sizeof(DeclID))
1284 DeclIDs.push_back(Reader.getGlobalDeclID(
1286 Reader, F,
1287 endian::readNext<DeclID, llvm::endianness::little>(d))));
1288 Reader.SetGloballyVisibleDecls(II, DeclIDs);
1289 }
1290
1291 return II;
1292}
1293
1295 : Kind(Name.getNameKind()) {
1296 switch (Kind) {
1298 Data = (uint64_t)Name.getAsIdentifierInfo();
1299 break;
1303 Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
1304 break;
1306 Data = Name.getCXXOverloadedOperator();
1307 break;
1309 Data = (uint64_t)Name.getCXXLiteralIdentifier();
1310 break;
1312 Data = (uint64_t)Name.getCXXDeductionGuideTemplate()
1314 break;
1319 Data = 0;
1320 break;
1321 }
1322}
1323
1325 llvm::FoldingSetNodeID ID;
1326 ID.AddInteger(Kind);
1327
1328 switch (Kind) {
1332 ID.AddString(((IdentifierInfo*)Data)->getName());
1333 break;
1337 ID.AddInteger(serialization::ComputeHash(Selector(Data)));
1338 break;
1340 ID.AddInteger((OverloadedOperatorKind)Data);
1341 break;
1346 break;
1347 }
1348
1349 return ID.computeStableHash();
1350}
1351
1352ModuleFile *
1354 using namespace llvm::support;
1355
1356 uint32_t ModuleFileID =
1357 endian::readNext<uint32_t, llvm::endianness::little>(d);
1358 return Reader.getLocalModuleFile(F, ModuleFileID);
1359}
1360
1361std::pair<unsigned, unsigned>
1365
1368 using namespace llvm::support;
1369
1370 auto Kind = (DeclarationName::NameKind)*d++;
1371 uint64_t Data;
1372 switch (Kind) {
1376 Data = (uint64_t)Reader.getLocalIdentifier(
1377 F, endian::readNext<IdentifierID, llvm::endianness::little>(d));
1378 break;
1382 Data = (uint64_t)Reader
1383 .getLocalSelector(
1384 F, endian::readNext<uint32_t, llvm::endianness::little>(d))
1385 .getAsOpaquePtr();
1386 break;
1388 Data = *d++; // OverloadedOperatorKind
1389 break;
1394 Data = 0;
1395 break;
1396 }
1397
1398 return DeclarationNameKey(Kind, Data);
1399}
1400
1402ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
1403 return ReadKeyBase(d);
1404}
1405
1407 const unsigned char *d, unsigned DataLen, data_type_builder &Val) {
1408 using namespace llvm::support;
1409
1410 for (unsigned NumDecls = DataLen / sizeof(DeclID); NumDecls; --NumDecls) {
1412 Reader, F, endian::readNext<DeclID, llvm::endianness::little>(d));
1413 Val.insert(Reader.getGlobalDeclID(F, ID));
1414 }
1415}
1416
1418 const unsigned char *d,
1419 unsigned DataLen,
1420 data_type_builder &Val) {
1421 ReadDataIntoImpl(d, DataLen, Val);
1422}
1423
1426 llvm::FoldingSetNodeID ID;
1427 ID.AddInteger(Key.first.getHash());
1428 ID.AddInteger(Key.second);
1429 return ID.computeStableHash();
1430}
1431
1434 DeclarationNameKey Name(Key.first);
1435
1436 UnsignedOrNone ModuleHash = getPrimaryModuleHash(Key.second);
1437 if (!ModuleHash)
1438 return {Name, 0};
1439
1440 return {Name, *ModuleHash};
1441}
1442
1444ModuleLocalNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
1446 unsigned PrimaryModuleHash =
1447 llvm::support::endian::readNext<uint32_t, llvm::endianness::little>(d);
1448 return {Name, PrimaryModuleHash};
1449}
1450
1452 const unsigned char *d,
1453 unsigned DataLen,
1454 data_type_builder &Val) {
1455 ReadDataIntoImpl(d, DataLen, Val);
1456}
1457
1458ModuleFile *
1460 using namespace llvm::support;
1461
1462 uint32_t ModuleFileID =
1463 endian::readNext<uint32_t, llvm::endianness::little, unaligned>(d);
1464 return Reader.getLocalModuleFile(F, ModuleFileID);
1465}
1466
1468LazySpecializationInfoLookupTrait::ReadKey(const unsigned char *d, unsigned) {
1469 using namespace llvm::support;
1470 return endian::readNext<uint32_t, llvm::endianness::little, unaligned>(d);
1471}
1472
1473std::pair<unsigned, unsigned>
1477
1479 const unsigned char *d,
1480 unsigned DataLen,
1481 data_type_builder &Val) {
1482 using namespace llvm::support;
1483
1484 for (unsigned NumDecls =
1486 NumDecls; --NumDecls) {
1487 LocalDeclID LocalID = LocalDeclID::get(
1488 Reader, F,
1489 endian::readNext<DeclID, llvm::endianness::little, unaligned>(d));
1490 Val.insert(Reader.getGlobalDeclID(F, LocalID));
1491 }
1492}
1493
1494bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
1495 BitstreamCursor &Cursor,
1496 uint64_t Offset,
1497 DeclContext *DC) {
1498 assert(Offset != 0);
1499
1500 SavedStreamPosition SavedPosition(Cursor);
1501 if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1502 Error(std::move(Err));
1503 return true;
1504 }
1505
1506 RecordData Record;
1507 StringRef Blob;
1508 Expected<unsigned> MaybeCode = Cursor.ReadCode();
1509 if (!MaybeCode) {
1510 Error(MaybeCode.takeError());
1511 return true;
1512 }
1513 unsigned Code = MaybeCode.get();
1514
1515 Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
1516 if (!MaybeRecCode) {
1517 Error(MaybeRecCode.takeError());
1518 return true;
1519 }
1520 unsigned RecCode = MaybeRecCode.get();
1521 if (RecCode != DECL_CONTEXT_LEXICAL) {
1522 Error("Expected lexical block");
1523 return true;
1524 }
1525
1526 assert(!isa<TranslationUnitDecl>(DC) &&
1527 "expected a TU_UPDATE_LEXICAL record for TU");
1528 // If we are handling a C++ class template instantiation, we can see multiple
1529 // lexical updates for the same record. It's important that we select only one
1530 // of them, so that field numbering works properly. Just pick the first one we
1531 // see.
1532 auto &Lex = LexicalDecls[DC];
1533 if (!Lex.first) {
1534 Lex = std::make_pair(
1535 &M, llvm::ArrayRef(
1536 reinterpret_cast<const unaligned_decl_id_t *>(Blob.data()),
1537 Blob.size() / sizeof(DeclID)));
1538 }
1540 return false;
1541}
1542
1543bool ASTReader::ReadVisibleDeclContextStorage(
1544 ModuleFile &M, BitstreamCursor &Cursor, uint64_t Offset, GlobalDeclID ID,
1545 ASTReader::VisibleDeclContextStorageKind VisibleKind) {
1546 assert(Offset != 0);
1547
1548 SavedStreamPosition SavedPosition(Cursor);
1549 if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1550 Error(std::move(Err));
1551 return true;
1552 }
1553
1554 RecordData Record;
1555 StringRef Blob;
1556 Expected<unsigned> MaybeCode = Cursor.ReadCode();
1557 if (!MaybeCode) {
1558 Error(MaybeCode.takeError());
1559 return true;
1560 }
1561 unsigned Code = MaybeCode.get();
1562
1563 Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
1564 if (!MaybeRecCode) {
1565 Error(MaybeRecCode.takeError());
1566 return true;
1567 }
1568 unsigned RecCode = MaybeRecCode.get();
1569 switch (VisibleKind) {
1570 case VisibleDeclContextStorageKind::GenerallyVisible:
1571 if (RecCode != DECL_CONTEXT_VISIBLE) {
1572 Error("Expected visible lookup table block");
1573 return true;
1574 }
1575 break;
1576 case VisibleDeclContextStorageKind::ModuleLocalVisible:
1577 if (RecCode != DECL_CONTEXT_MODULE_LOCAL_VISIBLE) {
1578 Error("Expected module local visible lookup table block");
1579 return true;
1580 }
1581 break;
1582 case VisibleDeclContextStorageKind::TULocalVisible:
1583 if (RecCode != DECL_CONTEXT_TU_LOCAL_VISIBLE) {
1584 Error("Expected TU local lookup table block");
1585 return true;
1586 }
1587 break;
1588 }
1589
1590 // We can't safely determine the primary context yet, so delay attaching the
1591 // lookup table until we're done with recursive deserialization.
1592 auto *Data = (const unsigned char*)Blob.data();
1593 switch (VisibleKind) {
1594 case VisibleDeclContextStorageKind::GenerallyVisible:
1595 PendingVisibleUpdates[ID].push_back(UpdateData{&M, Data});
1596 break;
1597 case VisibleDeclContextStorageKind::ModuleLocalVisible:
1598 PendingModuleLocalVisibleUpdates[ID].push_back(UpdateData{&M, Data});
1599 break;
1600 case VisibleDeclContextStorageKind::TULocalVisible:
1601 if (M.Kind == MK_MainFile)
1602 TULocalUpdates[ID].push_back(UpdateData{&M, Data});
1603 break;
1604 }
1605 return false;
1606}
1607
1608void ASTReader::AddSpecializations(const Decl *D, const unsigned char *Data,
1609 ModuleFile &M, bool IsPartial) {
1610 D = D->getCanonicalDecl();
1611 auto &SpecLookups =
1612 IsPartial ? PartialSpecializationsLookups : SpecializationsLookups;
1613 SpecLookups[D].Table.add(&M, Data,
1615}
1616
1617bool ASTReader::ReadSpecializations(ModuleFile &M, BitstreamCursor &Cursor,
1618 uint64_t Offset, Decl *D, bool IsPartial) {
1619 assert(Offset != 0);
1620
1621 SavedStreamPosition SavedPosition(Cursor);
1622 if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1623 Error(std::move(Err));
1624 return true;
1625 }
1626
1627 RecordData Record;
1628 StringRef Blob;
1629 Expected<unsigned> MaybeCode = Cursor.ReadCode();
1630 if (!MaybeCode) {
1631 Error(MaybeCode.takeError());
1632 return true;
1633 }
1634 unsigned Code = MaybeCode.get();
1635
1636 Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
1637 if (!MaybeRecCode) {
1638 Error(MaybeRecCode.takeError());
1639 return true;
1640 }
1641 unsigned RecCode = MaybeRecCode.get();
1642 if (RecCode != DECL_SPECIALIZATIONS &&
1643 RecCode != DECL_PARTIAL_SPECIALIZATIONS) {
1644 Error("Expected decl specs block");
1645 return true;
1646 }
1647
1648 auto *Data = (const unsigned char *)Blob.data();
1649 AddSpecializations(D, Data, M, IsPartial);
1650 return false;
1651}
1652
1653void ASTReader::Error(StringRef Msg) const {
1654 Error(diag::err_fe_ast_file_malformed, Msg);
1655 if (PP.getLangOpts().Modules &&
1656 !PP.getHeaderSearchInfo().getSpecificModuleCachePath().empty()) {
1657 Diag(diag::note_module_cache_path)
1658 << PP.getHeaderSearchInfo().getSpecificModuleCachePath();
1659 }
1660}
1661
1662void ASTReader::Error(unsigned DiagID, StringRef Arg1, StringRef Arg2,
1663 StringRef Arg3) const {
1664 Diag(DiagID) << Arg1 << Arg2 << Arg3;
1665}
1666
1667namespace {
1668struct AlreadyReportedDiagnosticError
1669 : llvm::ErrorInfo<AlreadyReportedDiagnosticError> {
1670 static char ID;
1671
1672 void log(raw_ostream &OS) const override {
1673 llvm_unreachable("reporting an already-reported diagnostic error");
1674 }
1675
1676 std::error_code convertToErrorCode() const override {
1677 return llvm::inconvertibleErrorCode();
1678 }
1679};
1680
1681char AlreadyReportedDiagnosticError::ID = 0;
1682} // namespace
1683
1684void ASTReader::Error(llvm::Error &&Err) const {
1685 handleAllErrors(
1686 std::move(Err), [](AlreadyReportedDiagnosticError &) {},
1687 [&](llvm::ErrorInfoBase &E) { return Error(E.message()); });
1688}
1689
1690//===----------------------------------------------------------------------===//
1691// Source Manager Deserialization
1692//===----------------------------------------------------------------------===//
1693
1694/// Read the line table in the source manager block.
1695void ASTReader::ParseLineTable(ModuleFile &F, const RecordData &Record) {
1696 unsigned Idx = 0;
1697 LineTableInfo &LineTable = SourceMgr.getLineTable();
1698
1699 // Parse the file names
1700 std::map<int, int> FileIDs;
1701 FileIDs[-1] = -1; // For unspecified filenames.
1702 for (unsigned I = 0; Record[Idx]; ++I) {
1703 // Extract the file name
1704 auto Filename = ReadPath(F, Record, Idx);
1705 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1706 }
1707 ++Idx;
1708
1709 // Parse the line entries
1710 std::vector<LineEntry> Entries;
1711 while (Idx < Record.size()) {
1712 FileID FID = ReadFileID(F, Record, Idx);
1713
1714 // Extract the line entries
1715 unsigned NumEntries = Record[Idx++];
1716 assert(NumEntries && "no line entries for file ID");
1717 Entries.clear();
1718 Entries.reserve(NumEntries);
1719 for (unsigned I = 0; I != NumEntries; ++I) {
1720 unsigned FileOffset = Record[Idx++];
1721 unsigned LineNo = Record[Idx++];
1722 int FilenameID = FileIDs[Record[Idx++]];
1725 unsigned IncludeOffset = Record[Idx++];
1726 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1727 FileKind, IncludeOffset));
1728 }
1729 LineTable.AddEntry(FID, Entries);
1730 }
1731}
1732
1733/// Read a source manager block
1734llvm::Error ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1735 using namespace SrcMgr;
1736
1737 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
1738
1739 // Set the source-location entry cursor to the current position in
1740 // the stream. This cursor will be used to read the contents of the
1741 // source manager block initially, and then lazily read
1742 // source-location entries as needed.
1743 SLocEntryCursor = F.Stream;
1744
1745 // The stream itself is going to skip over the source manager block.
1746 if (llvm::Error Err = F.Stream.SkipBlock())
1747 return Err;
1748
1749 // Enter the source manager block.
1750 if (llvm::Error Err = SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID))
1751 return Err;
1752 F.SourceManagerBlockStartOffset = SLocEntryCursor.GetCurrentBitNo();
1753
1754 RecordData Record;
1755 while (true) {
1756 Expected<llvm::BitstreamEntry> MaybeE =
1757 SLocEntryCursor.advanceSkippingSubblocks();
1758 if (!MaybeE)
1759 return MaybeE.takeError();
1760 llvm::BitstreamEntry E = MaybeE.get();
1761
1762 switch (E.Kind) {
1763 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1764 case llvm::BitstreamEntry::Error:
1765 return llvm::createStringError(std::errc::illegal_byte_sequence,
1766 "malformed block record in AST file");
1767 case llvm::BitstreamEntry::EndBlock:
1768 return llvm::Error::success();
1769 case llvm::BitstreamEntry::Record:
1770 // The interesting case.
1771 break;
1772 }
1773
1774 // Read a record.
1775 Record.clear();
1776 StringRef Blob;
1777 Expected<unsigned> MaybeRecord =
1778 SLocEntryCursor.readRecord(E.ID, Record, &Blob);
1779 if (!MaybeRecord)
1780 return MaybeRecord.takeError();
1781 switch (MaybeRecord.get()) {
1782 default: // Default behavior: ignore.
1783 break;
1784
1785 case SM_SLOC_FILE_ENTRY:
1788 // Once we hit one of the source location entries, we're done.
1789 return llvm::Error::success();
1790 }
1791 }
1792}
1793
1794llvm::Expected<SourceLocation::UIntTy>
1796 BitstreamCursor &Cursor = F->SLocEntryCursor;
1797 SavedStreamPosition SavedPosition(Cursor);
1798 if (llvm::Error Err = Cursor.JumpToBit(F->SLocEntryOffsetsBase +
1799 F->SLocEntryOffsets[Index]))
1800 return std::move(Err);
1801
1802 Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
1803 if (!MaybeEntry)
1804 return MaybeEntry.takeError();
1805
1806 llvm::BitstreamEntry Entry = MaybeEntry.get();
1807 if (Entry.Kind != llvm::BitstreamEntry::Record)
1808 return llvm::createStringError(
1809 std::errc::illegal_byte_sequence,
1810 "incorrectly-formatted source location entry in AST file");
1811
1813 StringRef Blob;
1814 Expected<unsigned> MaybeSLOC = Cursor.readRecord(Entry.ID, Record, &Blob);
1815 if (!MaybeSLOC)
1816 return MaybeSLOC.takeError();
1817
1818 switch (MaybeSLOC.get()) {
1819 default:
1820 return llvm::createStringError(
1821 std::errc::illegal_byte_sequence,
1822 "incorrectly-formatted source location entry in AST file");
1823 case SM_SLOC_FILE_ENTRY:
1826 return F->SLocEntryBaseOffset + Record[0];
1827 }
1828}
1829
1831 auto SLocMapI =
1832 GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset - SLocOffset - 1);
1833 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
1834 "Corrupted global sloc offset map");
1835 ModuleFile *F = SLocMapI->second;
1836
1837 bool Invalid = false;
1838
1839 auto It = llvm::upper_bound(
1840 llvm::index_range(0, F->LocalNumSLocEntries), SLocOffset,
1841 [&](SourceLocation::UIntTy Offset, std::size_t LocalIndex) {
1842 int ID = F->SLocEntryBaseID + LocalIndex;
1843 std::size_t Index = -ID - 2;
1844 if (!SourceMgr.SLocEntryOffsetLoaded[Index]) {
1845 assert(!SourceMgr.SLocEntryLoaded[Index]);
1846 auto MaybeEntryOffset = readSLocOffset(F, LocalIndex);
1847 if (!MaybeEntryOffset) {
1848 Error(MaybeEntryOffset.takeError());
1849 Invalid = true;
1850 return true;
1851 }
1852 SourceMgr.LoadedSLocEntryTable[Index] =
1853 SrcMgr::SLocEntry::getOffsetOnly(*MaybeEntryOffset);
1854 SourceMgr.SLocEntryOffsetLoaded[Index] = true;
1855 }
1856 return Offset < SourceMgr.LoadedSLocEntryTable[Index].getOffset();
1857 });
1858
1859 if (Invalid)
1860 return 0;
1861
1862 // The iterator points to the first entry with start offset greater than the
1863 // offset of interest. The previous entry must contain the offset of interest.
1864 return F->SLocEntryBaseID + *std::prev(It);
1865}
1866
1868 if (ID == 0)
1869 return false;
1870
1871 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1872 Error("source location entry ID out-of-range for AST file");
1873 return true;
1874 }
1875
1876 // Local helper to read the (possibly-compressed) buffer data following the
1877 // entry record.
1878 auto ReadBuffer = [this](
1879 BitstreamCursor &SLocEntryCursor,
1880 StringRef Name) -> std::unique_ptr<llvm::MemoryBuffer> {
1882 StringRef Blob;
1883 Expected<unsigned> MaybeCode = SLocEntryCursor.ReadCode();
1884 if (!MaybeCode) {
1885 Error(MaybeCode.takeError());
1886 return nullptr;
1887 }
1888 unsigned Code = MaybeCode.get();
1889
1890 Expected<unsigned> MaybeRecCode =
1891 SLocEntryCursor.readRecord(Code, Record, &Blob);
1892 if (!MaybeRecCode) {
1893 Error(MaybeRecCode.takeError());
1894 return nullptr;
1895 }
1896 unsigned RecCode = MaybeRecCode.get();
1897
1898 if (RecCode == SM_SLOC_BUFFER_BLOB_COMPRESSED) {
1899 // Inspect the first byte to differentiate zlib (\x78) and zstd
1900 // (little-endian 0xFD2FB528).
1901 const llvm::compression::Format F =
1902 Blob.size() > 0 && Blob.data()[0] == 0x78
1903 ? llvm::compression::Format::Zlib
1904 : llvm::compression::Format::Zstd;
1905 if (const char *Reason = llvm::compression::getReasonIfUnsupported(F)) {
1906 Error(Reason);
1907 return nullptr;
1908 }
1909 SmallVector<uint8_t, 0> Decompressed;
1910 if (llvm::Error E = llvm::compression::decompress(
1911 F, llvm::arrayRefFromStringRef(Blob), Decompressed, Record[0])) {
1912 Error("could not decompress embedded file contents: " +
1913 llvm::toString(std::move(E)));
1914 return nullptr;
1915 }
1916 return llvm::MemoryBuffer::getMemBufferCopy(
1917 llvm::toStringRef(Decompressed), Name);
1918 } else if (RecCode == SM_SLOC_BUFFER_BLOB) {
1919 return llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name, true);
1920 } else {
1921 Error("AST record has invalid code");
1922 return nullptr;
1923 }
1924 };
1925
1926 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1927 if (llvm::Error Err = F->SLocEntryCursor.JumpToBit(
1929 F->SLocEntryOffsets[ID - F->SLocEntryBaseID])) {
1930 Error(std::move(Err));
1931 return true;
1932 }
1933
1934 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
1936
1937 ++NumSLocEntriesRead;
1938 Expected<llvm::BitstreamEntry> MaybeEntry = SLocEntryCursor.advance();
1939 if (!MaybeEntry) {
1940 Error(MaybeEntry.takeError());
1941 return true;
1942 }
1943 llvm::BitstreamEntry Entry = MaybeEntry.get();
1944
1945 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1946 Error("incorrectly-formatted source location entry in AST file");
1947 return true;
1948 }
1949
1951 StringRef Blob;
1952 Expected<unsigned> MaybeSLOC =
1953 SLocEntryCursor.readRecord(Entry.ID, Record, &Blob);
1954 if (!MaybeSLOC) {
1955 Error(MaybeSLOC.takeError());
1956 return true;
1957 }
1958 switch (MaybeSLOC.get()) {
1959 default:
1960 Error("incorrectly-formatted source location entry in AST file");
1961 return true;
1962
1963 case SM_SLOC_FILE_ENTRY: {
1964 // We will detect whether a file changed and return 'Failure' for it, but
1965 // we will also try to fail gracefully by setting up the SLocEntry.
1966 unsigned InputID = Record[4];
1967 InputFile IF = getInputFile(*F, InputID);
1969 bool OverriddenBuffer = IF.isOverridden();
1970
1971 // Note that we only check if a File was returned. If it was out-of-date
1972 // we have complained but we will continue creating a FileID to recover
1973 // gracefully.
1974 if (!File)
1975 return true;
1976
1977 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1978 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1979 // This is the module's main file.
1980 IncludeLoc = getImportLocation(F);
1981 }
1983 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1984 FileID FID = SourceMgr.createFileID(*File, IncludeLoc, FileCharacter, ID,
1985 BaseOffset + Record[0]);
1986 SrcMgr::FileInfo &FileInfo = SourceMgr.getSLocEntry(FID).getFile();
1987 FileInfo.NumCreatedFIDs = Record[5];
1988 if (Record[3])
1989 FileInfo.setHasLineDirectives();
1990
1991 unsigned NumFileDecls = Record[7];
1992 if (NumFileDecls && ContextObj) {
1993 const unaligned_decl_id_t *FirstDecl = F->FileSortedDecls + Record[6];
1994 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1995 FileDeclIDs[FID] =
1996 FileDeclsInfo(F, llvm::ArrayRef(FirstDecl, NumFileDecls));
1997 }
1998
1999 const SrcMgr::ContentCache &ContentCache =
2000 SourceMgr.getOrCreateContentCache(*File, isSystem(FileCharacter));
2001 if (OverriddenBuffer && !ContentCache.BufferOverridden &&
2002 ContentCache.ContentsEntry == ContentCache.OrigEntry &&
2003 !ContentCache.getBufferIfLoaded()) {
2004 auto Buffer = ReadBuffer(SLocEntryCursor, File->getName());
2005 if (!Buffer)
2006 return true;
2007 SourceMgr.overrideFileContents(*File, std::move(Buffer));
2008 }
2009
2010 break;
2011 }
2012
2013 case SM_SLOC_BUFFER_ENTRY: {
2014 const char *Name = Blob.data();
2015 unsigned Offset = Record[0];
2017 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
2018 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
2019 if (IncludeLoc.isInvalid() && F->isModule()) {
2020 IncludeLoc = getImportLocation(F);
2021 }
2022
2023 auto Buffer = ReadBuffer(SLocEntryCursor, Name);
2024 if (!Buffer)
2025 return true;
2026 FileID FID = SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
2027 BaseOffset + Offset, IncludeLoc);
2028 if (Record[3]) {
2029 auto &FileInfo = SourceMgr.getSLocEntry(FID).getFile();
2030 FileInfo.setHasLineDirectives();
2031 }
2032 break;
2033 }
2034
2036 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
2037 SourceLocation ExpansionBegin = ReadSourceLocation(*F, Record[2]);
2038 SourceLocation ExpansionEnd = ReadSourceLocation(*F, Record[3]);
2039 SourceMgr.createExpansionLoc(SpellingLoc, ExpansionBegin, ExpansionEnd,
2040 Record[5], Record[4], ID,
2041 BaseOffset + Record[0]);
2042 break;
2043 }
2044 }
2045
2046 return false;
2047}
2048
2049std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
2050 if (ID == 0)
2051 return std::make_pair(SourceLocation(), "");
2052
2053 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
2054 Error("source location entry ID out-of-range for AST file");
2055 return std::make_pair(SourceLocation(), "");
2056 }
2057
2058 // Find which module file this entry lands in.
2059 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
2060 if (!M->isModule())
2061 return std::make_pair(SourceLocation(), "");
2062
2063 // FIXME: Can we map this down to a particular submodule? That would be
2064 // ideal.
2065 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
2066}
2067
2068/// Find the location where the module F is imported.
2069SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
2070 if (F->ImportLoc.isValid())
2071 return F->ImportLoc;
2072
2073 // Otherwise we have a PCH. It's considered to be "imported" at the first
2074 // location of its includer.
2075 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
2076 // Main file is the importer.
2077 assert(SourceMgr.getMainFileID().isValid() && "missing main file");
2078 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
2079 }
2080 return F->ImportedBy[0]->FirstLoc;
2081}
2082
2083/// Enter a subblock of the specified BlockID with the specified cursor. Read
2084/// the abbreviations that are at the top of the block and then leave the cursor
2085/// pointing into the block.
2086llvm::Error ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor,
2087 unsigned BlockID,
2088 uint64_t *StartOfBlockOffset) {
2089 if (llvm::Error Err = Cursor.EnterSubBlock(BlockID))
2090 return Err;
2091
2092 if (StartOfBlockOffset)
2093 *StartOfBlockOffset = Cursor.GetCurrentBitNo();
2094
2095 while (true) {
2096 uint64_t Offset = Cursor.GetCurrentBitNo();
2097 Expected<unsigned> MaybeCode = Cursor.ReadCode();
2098 if (!MaybeCode)
2099 return MaybeCode.takeError();
2100 unsigned Code = MaybeCode.get();
2101
2102 // We expect all abbrevs to be at the start of the block.
2103 if (Code != llvm::bitc::DEFINE_ABBREV) {
2104 if (llvm::Error Err = Cursor.JumpToBit(Offset))
2105 return Err;
2106 return llvm::Error::success();
2107 }
2108 if (llvm::Error Err = Cursor.ReadAbbrevRecord())
2109 return Err;
2110 }
2111}
2112
2114 unsigned &Idx) {
2115 Token Tok;
2116 Tok.startToken();
2117 Tok.setLocation(ReadSourceLocation(M, Record, Idx));
2118 Tok.setKind((tok::TokenKind)Record[Idx++]);
2119 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
2120
2121 if (Tok.isAnnotation()) {
2122 Tok.setAnnotationEndLoc(ReadSourceLocation(M, Record, Idx));
2123 switch (Tok.getKind()) {
2124 case tok::annot_pragma_loop_hint: {
2125 auto *Info = new (PP.getPreprocessorAllocator()) PragmaLoopHintInfo;
2126 Info->PragmaName = ReadToken(M, Record, Idx);
2127 Info->Option = ReadToken(M, Record, Idx);
2128 unsigned NumTokens = Record[Idx++];
2130 Toks.reserve(NumTokens);
2131 for (unsigned I = 0; I < NumTokens; ++I)
2132 Toks.push_back(ReadToken(M, Record, Idx));
2133 Info->Toks = llvm::ArrayRef(Toks).copy(PP.getPreprocessorAllocator());
2134 Tok.setAnnotationValue(static_cast<void *>(Info));
2135 break;
2136 }
2137 case tok::annot_pragma_pack: {
2138 auto *Info = new (PP.getPreprocessorAllocator()) Sema::PragmaPackInfo;
2139 Info->Action = static_cast<Sema::PragmaMsStackAction>(Record[Idx++]);
2140 auto SlotLabel = ReadString(Record, Idx);
2141 Info->SlotLabel =
2142 llvm::StringRef(SlotLabel).copy(PP.getPreprocessorAllocator());
2143 Info->Alignment = ReadToken(M, Record, Idx);
2144 Tok.setAnnotationValue(static_cast<void *>(Info));
2145 break;
2146 }
2147 // Some annotation tokens do not use the PtrData field.
2148 case tok::annot_pragma_openmp:
2149 case tok::annot_pragma_openmp_end:
2150 case tok::annot_pragma_unused:
2151 case tok::annot_pragma_openacc:
2152 case tok::annot_pragma_openacc_end:
2153 case tok::annot_repl_input_end:
2154 break;
2155 default:
2156 llvm_unreachable("missing deserialization code for annotation token");
2157 }
2158 } else {
2159 Tok.setLength(Record[Idx++]);
2160 if (IdentifierInfo *II = getLocalIdentifier(M, Record[Idx++]))
2161 Tok.setIdentifierInfo(II);
2162 }
2163 return Tok;
2164}
2165
2167 BitstreamCursor &Stream = F.MacroCursor;
2168
2169 // Keep track of where we are in the stream, then jump back there
2170 // after reading this macro.
2171 SavedStreamPosition SavedPosition(Stream);
2172
2173 if (llvm::Error Err = Stream.JumpToBit(Offset)) {
2174 // FIXME this drops errors on the floor.
2175 consumeError(std::move(Err));
2176 return nullptr;
2177 }
2180 MacroInfo *Macro = nullptr;
2181 llvm::MutableArrayRef<Token> MacroTokens;
2182
2183 while (true) {
2184 // Advance to the next record, but if we get to the end of the block, don't
2185 // pop it (removing all the abbreviations from the cursor) since we want to
2186 // be able to reseek within the block and read entries.
2187 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
2189 Stream.advanceSkippingSubblocks(Flags);
2190 if (!MaybeEntry) {
2191 Error(MaybeEntry.takeError());
2192 return Macro;
2193 }
2194 llvm::BitstreamEntry Entry = MaybeEntry.get();
2195
2196 switch (Entry.Kind) {
2197 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
2198 case llvm::BitstreamEntry::Error:
2199 Error("malformed block record in AST file");
2200 return Macro;
2201 case llvm::BitstreamEntry::EndBlock:
2202 return Macro;
2203 case llvm::BitstreamEntry::Record:
2204 // The interesting case.
2205 break;
2206 }
2207
2208 // Read a record.
2209 Record.clear();
2211 if (Expected<unsigned> MaybeRecType = Stream.readRecord(Entry.ID, Record))
2212 RecType = (PreprocessorRecordTypes)MaybeRecType.get();
2213 else {
2214 Error(MaybeRecType.takeError());
2215 return Macro;
2216 }
2217 switch (RecType) {
2218 case PP_MODULE_MACRO:
2220 return Macro;
2221
2224 // If we already have a macro, that means that we've hit the end
2225 // of the definition of the macro we were looking for. We're
2226 // done.
2227 if (Macro)
2228 return Macro;
2229
2230 unsigned NextIndex = 1; // Skip identifier ID.
2231 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
2232 MacroInfo *MI = PP.AllocateMacroInfo(Loc);
2233 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
2234 MI->setIsUsed(Record[NextIndex++]);
2235 MI->setUsedForHeaderGuard(Record[NextIndex++]);
2236 MacroTokens = MI->allocateTokens(Record[NextIndex++],
2237 PP.getPreprocessorAllocator());
2238 if (RecType == PP_MACRO_FUNCTION_LIKE) {
2239 // Decode function-like macro info.
2240 bool isC99VarArgs = Record[NextIndex++];
2241 bool isGNUVarArgs = Record[NextIndex++];
2242 bool hasCommaPasting = Record[NextIndex++];
2243 MacroParams.clear();
2244 unsigned NumArgs = Record[NextIndex++];
2245 for (unsigned i = 0; i != NumArgs; ++i)
2246 MacroParams.push_back(getLocalIdentifier(F, Record[NextIndex++]));
2247
2248 // Install function-like macro info.
2249 MI->setIsFunctionLike();
2250 if (isC99VarArgs) MI->setIsC99Varargs();
2251 if (isGNUVarArgs) MI->setIsGNUVarargs();
2252 if (hasCommaPasting) MI->setHasCommaPasting();
2253 MI->setParameterList(MacroParams, PP.getPreprocessorAllocator());
2254 }
2255
2256 // Remember that we saw this macro last so that we add the tokens that
2257 // form its body to it.
2258 Macro = MI;
2259
2260 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
2261 Record[NextIndex]) {
2262 // We have a macro definition. Register the association
2264 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
2265 unsigned Index = translatePreprocessedEntityIDToIndex(GlobalID);
2266 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
2267 PreprocessingRecord::PPEntityID PPID =
2268 PPRec.getPPEntityID(Index, /*isLoaded=*/true);
2269 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
2270 PPRec.getPreprocessedEntity(PPID));
2271 if (PPDef)
2272 PPRec.RegisterMacroDefinition(Macro, PPDef);
2273 }
2274
2275 ++NumMacrosRead;
2276 break;
2277 }
2278
2279 case PP_TOKEN: {
2280 // If we see a TOKEN before a PP_MACRO_*, then the file is
2281 // erroneous, just pretend we didn't see this.
2282 if (!Macro) break;
2283 if (MacroTokens.empty()) {
2284 Error("unexpected number of macro tokens for a macro in AST file");
2285 return Macro;
2286 }
2287
2288 unsigned Idx = 0;
2289 MacroTokens[0] = ReadToken(F, Record, Idx);
2290 MacroTokens = MacroTokens.drop_front();
2291 break;
2292 }
2293 }
2294 }
2295}
2296
2299 PreprocessedEntityID LocalID) const {
2300 if (!M.ModuleOffsetMap.empty())
2301 ReadModuleOffsetMap(M);
2302
2303 unsigned ModuleFileIndex = LocalID >> 32;
2304 LocalID &= llvm::maskTrailingOnes<PreprocessedEntityID>(32);
2305 ModuleFile *MF =
2306 ModuleFileIndex ? M.TransitiveImports[ModuleFileIndex - 1] : &M;
2307 assert(MF && "malformed identifier ID encoding?");
2308
2309 if (!ModuleFileIndex) {
2310 assert(LocalID >= NUM_PREDEF_PP_ENTITY_IDS);
2311 LocalID -= NUM_PREDEF_PP_ENTITY_IDS;
2312 }
2313
2314 return (static_cast<PreprocessedEntityID>(MF->Index + 1) << 32) | LocalID;
2315}
2316
2318HeaderFileInfoTrait::getFile(const internal_key_type &Key) {
2319 FileManager &FileMgr = Reader.getFileManager();
2320 if (!Key.Imported)
2321 return FileMgr.getOptionalFileRef(Key.Filename);
2322
2323 auto Resolved =
2324 ASTReader::ResolveImportedPath(Reader.getPathBuf(), Key.Filename, M);
2325 return FileMgr.getOptionalFileRef(*Resolved);
2326}
2327
2329 uint8_t buf[sizeof(ikey.Size) + sizeof(ikey.ModTime)];
2330 memcpy(buf, &ikey.Size, sizeof(ikey.Size));
2331 memcpy(buf + sizeof(ikey.Size), &ikey.ModTime, sizeof(ikey.ModTime));
2332 return llvm::xxh3_64bits(buf);
2333}
2334
2337 internal_key_type ikey = {ekey.getSize(),
2338 M.HasTimestamps ? ekey.getModificationTime() : 0,
2339 ekey.getName(), /*Imported*/ false};
2340 return ikey;
2341}
2342
2344 if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime))
2345 return false;
2346
2347 if (llvm::sys::path::is_absolute(a.Filename) && a.Filename == b.Filename)
2348 return true;
2349
2350 // Determine whether the actual files are equivalent.
2351 OptionalFileEntryRef FEA = getFile(a);
2352 OptionalFileEntryRef FEB = getFile(b);
2353 return FEA && FEA == FEB;
2354}
2355
2356std::pair<unsigned, unsigned>
2358 return readULEBKeyDataLength(d);
2359}
2360
2362HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
2363 using namespace llvm::support;
2364
2365 internal_key_type ikey;
2366 ikey.Size = off_t(endian::readNext<uint64_t, llvm::endianness::little>(d));
2367 ikey.ModTime =
2368 time_t(endian::readNext<uint64_t, llvm::endianness::little>(d));
2369 ikey.Filename = (const char *)d;
2370 ikey.Imported = true;
2371 return ikey;
2372}
2373
2376 unsigned DataLen) {
2377 using namespace llvm::support;
2378
2379 const unsigned char *End = d + DataLen;
2380 HeaderFileInfo HFI;
2381 unsigned Flags = *d++;
2382
2384 bool Included = (Flags >> 6) & 0x01;
2385 if (Included)
2386 if ((FE = getFile(key)))
2387 // Not using \c Preprocessor::markIncluded(), since that would attempt to
2388 // deserialize this header file info again.
2389 Reader.getPreprocessor().getIncludedFiles().insert(*FE);
2390
2391 // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
2392 HFI.isImport |= (Flags >> 5) & 0x01;
2393 HFI.isPragmaOnce |= (Flags >> 4) & 0x01;
2394 HFI.DirInfo = (Flags >> 1) & 0x07;
2395 HFI.LazyControllingMacro = Reader.getGlobalIdentifierID(
2396 M, endian::readNext<IdentifierID, llvm::endianness::little>(d));
2397
2398 assert((End - d) % 4 == 0 &&
2399 "Wrong data length in HeaderFileInfo deserialization");
2400 while (d != End) {
2401 uint32_t LocalSMID =
2402 endian::readNext<uint32_t, llvm::endianness::little>(d);
2403 auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 7);
2404 LocalSMID >>= 3;
2405
2406 // This header is part of a module. Associate it with the module to enable
2407 // implicit module import.
2408 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
2409 Module *Mod = Reader.getSubmodule(GlobalSMID);
2410 ModuleMap &ModMap =
2411 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
2412
2413 if (FE || (FE = getFile(key))) {
2414 // FIXME: NameAsWritten
2415 Module::Header H = {std::string(key.Filename), "", *FE};
2416 ModMap.addHeader(Mod, H, HeaderRole, /*Imported=*/true);
2417 }
2418 HFI.mergeModuleMembership(HeaderRole);
2419 }
2420
2421 // This HeaderFileInfo was externally loaded.
2422 HFI.External = true;
2423 HFI.IsValid = true;
2424 return HFI;
2425}
2426
2428 uint32_t MacroDirectivesOffset) {
2429 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
2430 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
2431}
2432
2434 // Note that we are loading defined macros.
2435 Deserializing Macros(this);
2436
2437 for (ModuleFile &I : llvm::reverse(ModuleMgr)) {
2438 BitstreamCursor &MacroCursor = I.MacroCursor;
2439
2440 // If there was no preprocessor block, skip this file.
2441 if (MacroCursor.getBitcodeBytes().empty())
2442 continue;
2443
2444 BitstreamCursor Cursor = MacroCursor;
2445 if (llvm::Error Err = Cursor.JumpToBit(I.MacroStartOffset)) {
2446 Error(std::move(Err));
2447 return;
2448 }
2449
2451 while (true) {
2452 Expected<llvm::BitstreamEntry> MaybeE = Cursor.advanceSkippingSubblocks();
2453 if (!MaybeE) {
2454 Error(MaybeE.takeError());
2455 return;
2456 }
2457 llvm::BitstreamEntry E = MaybeE.get();
2458
2459 switch (E.Kind) {
2460 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
2461 case llvm::BitstreamEntry::Error:
2462 Error("malformed block record in AST file");
2463 return;
2464 case llvm::BitstreamEntry::EndBlock:
2465 goto NextCursor;
2466
2467 case llvm::BitstreamEntry::Record: {
2468 Record.clear();
2469 Expected<unsigned> MaybeRecord = Cursor.readRecord(E.ID, Record);
2470 if (!MaybeRecord) {
2471 Error(MaybeRecord.takeError());
2472 return;
2473 }
2474 switch (MaybeRecord.get()) {
2475 default: // Default behavior: ignore.
2476 break;
2477
2481 if (II->isOutOfDate())
2483 break;
2484 }
2485
2486 case PP_TOKEN:
2487 // Ignore tokens.
2488 break;
2489 }
2490 break;
2491 }
2492 }
2493 }
2494 NextCursor: ;
2495 }
2496}
2497
2498namespace {
2499
2500 /// Visitor class used to look up identifirs in an AST file.
2501 class IdentifierLookupVisitor {
2502 StringRef Name;
2503 unsigned NameHash;
2504 unsigned PriorGeneration;
2505 unsigned &NumIdentifierLookups;
2506 unsigned &NumIdentifierLookupHits;
2507 IdentifierInfo *Found = nullptr;
2508
2509 public:
2510 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
2511 unsigned &NumIdentifierLookups,
2512 unsigned &NumIdentifierLookupHits)
2513 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
2514 PriorGeneration(PriorGeneration),
2515 NumIdentifierLookups(NumIdentifierLookups),
2516 NumIdentifierLookupHits(NumIdentifierLookupHits) {}
2517
2518 bool operator()(ModuleFile &M) {
2519 // If we've already searched this module file, skip it now.
2520 if (M.Generation <= PriorGeneration)
2521 return true;
2522
2525 if (!IdTable)
2526 return false;
2527
2528 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
2529 Found);
2530 ++NumIdentifierLookups;
2531 ASTIdentifierLookupTable::iterator Pos =
2532 IdTable->find_hashed(Name, NameHash, &Trait);
2533 if (Pos == IdTable->end())
2534 return false;
2535
2536 // Dereferencing the iterator has the effect of building the
2537 // IdentifierInfo node and populating it with the various
2538 // declarations it needs.
2539 ++NumIdentifierLookupHits;
2540 Found = *Pos;
2541 if (Trait.hasMoreInformationInDependencies()) {
2542 // Look for the identifier in extra modules as they contain more info.
2543 return false;
2544 }
2545 return true;
2546 }
2547
2548 // Retrieve the identifier info found within the module
2549 // files.
2550 IdentifierInfo *getIdentifierInfo() const { return Found; }
2551 };
2552
2553} // namespace
2554
2556 // Note that we are loading an identifier.
2557 Deserializing AnIdentifier(this);
2558
2559 unsigned PriorGeneration = 0;
2560 if (getContext().getLangOpts().Modules)
2561 PriorGeneration = IdentifierGeneration[&II];
2562
2563 // If there is a global index, look there first to determine which modules
2564 // provably do not have any results for this identifier.
2566 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
2567 if (!loadGlobalIndex()) {
2568 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
2569 HitsPtr = &Hits;
2570 }
2571 }
2572
2573 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
2574 NumIdentifierLookups,
2575 NumIdentifierLookupHits);
2576 ModuleMgr.visit(Visitor, HitsPtr);
2578}
2579
2581 if (!II)
2582 return;
2583
2584 const_cast<IdentifierInfo *>(II)->setOutOfDate(false);
2585
2586 // Update the generation for this identifier.
2587 if (getContext().getLangOpts().Modules)
2588 IdentifierGeneration[II] = getGeneration();
2589}
2590
2592 unsigned &Idx) {
2593 uint64_t ModuleFileIndex = Record[Idx++] << 32;
2594 uint64_t LocalIndex = Record[Idx++];
2595 return getGlobalMacroID(F, (ModuleFileIndex | LocalIndex));
2596}
2597
2599 const PendingMacroInfo &PMInfo) {
2600 ModuleFile &M = *PMInfo.M;
2601
2602 BitstreamCursor &Cursor = M.MacroCursor;
2603 SavedStreamPosition SavedPosition(Cursor);
2604 if (llvm::Error Err =
2605 Cursor.JumpToBit(M.MacroOffsetsBase + PMInfo.MacroDirectivesOffset)) {
2606 Error(std::move(Err));
2607 return;
2608 }
2609
2610 struct ModuleMacroRecord {
2611 SubmoduleID SubModID;
2612 MacroInfo *MI;
2614 };
2616
2617 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
2618 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
2619 // macro histroy.
2621 while (true) {
2623 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
2624 if (!MaybeEntry) {
2625 Error(MaybeEntry.takeError());
2626 return;
2627 }
2628 llvm::BitstreamEntry Entry = MaybeEntry.get();
2629
2630 if (Entry.Kind != llvm::BitstreamEntry::Record) {
2631 Error("malformed block record in AST file");
2632 return;
2633 }
2634
2635 Record.clear();
2636 Expected<unsigned> MaybePP = Cursor.readRecord(Entry.ID, Record);
2637 if (!MaybePP) {
2638 Error(MaybePP.takeError());
2639 return;
2640 }
2641 switch ((PreprocessorRecordTypes)MaybePP.get()) {
2643 break;
2644
2645 case PP_MODULE_MACRO: {
2646 ModuleMacros.push_back(ModuleMacroRecord());
2647 auto &Info = ModuleMacros.back();
2648 unsigned Idx = 0;
2649 Info.SubModID = getGlobalSubmoduleID(M, Record[Idx++]);
2650 Info.MI = getMacro(ReadMacroID(M, Record, Idx));
2651 for (int I = Idx, N = Record.size(); I != N; ++I)
2652 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
2653 continue;
2654 }
2655
2656 default:
2657 Error("malformed block record in AST file");
2658 return;
2659 }
2660
2661 // We found the macro directive history; that's the last record
2662 // for this macro.
2663 break;
2664 }
2665
2666 // Module macros are listed in reverse dependency order.
2667 {
2668 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
2670 for (auto &MMR : ModuleMacros) {
2671 Overrides.clear();
2672 for (unsigned ModID : MMR.Overrides) {
2673 Module *Mod = getSubmodule(ModID);
2674 auto *Macro = PP.getModuleMacro(Mod, II);
2675 assert(Macro && "missing definition for overridden macro");
2676 Overrides.push_back(Macro);
2677 }
2678
2679 bool Inserted = false;
2680 Module *Owner = getSubmodule(MMR.SubModID);
2681 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
2682 }
2683 }
2684
2685 // Don't read the directive history for a module; we don't have anywhere
2686 // to put it.
2687 if (M.isModule())
2688 return;
2689
2690 // Deserialize the macro directives history in reverse source-order.
2691 MacroDirective *Latest = nullptr, *Earliest = nullptr;
2692 unsigned Idx = 0, N = Record.size();
2693 while (Idx < N) {
2694 MacroDirective *MD = nullptr;
2697 switch (K) {
2699 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
2700 MD = PP.AllocateDefMacroDirective(MI, Loc);
2701 break;
2702 }
2704 MD = PP.AllocateUndefMacroDirective(Loc);
2705 break;
2707 bool isPublic = Record[Idx++];
2708 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
2709 break;
2710 }
2711
2712 if (!Latest)
2713 Latest = MD;
2714 if (Earliest)
2715 Earliest->setPrevious(MD);
2716 Earliest = MD;
2717 }
2718
2719 if (Latest)
2720 PP.setLoadedMacroDirective(II, Earliest, Latest);
2721}
2722
2723bool ASTReader::shouldDisableValidationForFile(
2724 const serialization::ModuleFile &M) const {
2725 if (DisableValidationKind == DisableValidationForModuleKind::None)
2726 return false;
2727
2728 // If a PCH is loaded and validation is disabled for PCH then disable
2729 // validation for the PCH and the modules it loads.
2730 ModuleKind K = CurrentDeserializingModuleKind.value_or(M.Kind);
2731
2732 switch (K) {
2733 case MK_MainFile:
2734 case MK_Preamble:
2735 case MK_PCH:
2736 return bool(DisableValidationKind & DisableValidationForModuleKind::PCH);
2737 case MK_ImplicitModule:
2738 case MK_ExplicitModule:
2739 case MK_PrebuiltModule:
2740 return bool(DisableValidationKind & DisableValidationForModuleKind::Module);
2741 }
2742
2743 return false;
2744}
2745
2746static std::pair<StringRef, StringRef>
2748 const StringRef InputBlob) {
2749 uint16_t AsRequestedLength = Record[7];
2750 return {InputBlob.substr(0, AsRequestedLength),
2751 InputBlob.substr(AsRequestedLength)};
2752}
2753
2754InputFileInfo ASTReader::getInputFileInfo(ModuleFile &F, unsigned ID) {
2755 // If this ID is bogus, just return an empty input file.
2756 if (ID == 0 || ID > F.InputFileInfosLoaded.size())
2757 return InputFileInfo();
2758
2759 // If we've already loaded this input file, return it.
2760 if (F.InputFileInfosLoaded[ID - 1].isValid())
2761 return F.InputFileInfosLoaded[ID - 1];
2762
2763 // Go find this input file.
2764 BitstreamCursor &Cursor = F.InputFilesCursor;
2765 SavedStreamPosition SavedPosition(Cursor);
2766 if (llvm::Error Err = Cursor.JumpToBit(F.InputFilesOffsetBase +
2767 F.InputFileOffsets[ID - 1])) {
2768 // FIXME this drops errors on the floor.
2769 consumeError(std::move(Err));
2770 }
2771
2772 Expected<unsigned> MaybeCode = Cursor.ReadCode();
2773 if (!MaybeCode) {
2774 // FIXME this drops errors on the floor.
2775 consumeError(MaybeCode.takeError());
2776 }
2777 unsigned Code = MaybeCode.get();
2778 RecordData Record;
2779 StringRef Blob;
2780
2781 if (Expected<unsigned> Maybe = Cursor.readRecord(Code, Record, &Blob))
2782 assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE &&
2783 "invalid record type for input file");
2784 else {
2785 // FIXME this drops errors on the floor.
2786 consumeError(Maybe.takeError());
2787 }
2788
2789 assert(Record[0] == ID && "Bogus stored ID or offset");
2791 R.StoredSize = static_cast<off_t>(Record[1]);
2792 R.StoredTime = static_cast<time_t>(Record[2]);
2793 R.Overridden = static_cast<bool>(Record[3]);
2794 R.Transient = static_cast<bool>(Record[4]);
2795 R.TopLevel = static_cast<bool>(Record[5]);
2796 R.ModuleMap = static_cast<bool>(Record[6]);
2797 auto [UnresolvedFilenameAsRequested, UnresolvedFilename] =
2799 R.UnresolvedImportedFilenameAsRequested = UnresolvedFilenameAsRequested;
2800 R.UnresolvedImportedFilename = UnresolvedFilename.empty()
2801 ? UnresolvedFilenameAsRequested
2802 : UnresolvedFilename;
2803
2804 Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
2805 if (!MaybeEntry) // FIXME this drops errors on the floor.
2806 consumeError(MaybeEntry.takeError());
2807 llvm::BitstreamEntry Entry = MaybeEntry.get();
2808 assert(Entry.Kind == llvm::BitstreamEntry::Record &&
2809 "expected record type for input file hash");
2810
2811 Record.clear();
2812 if (Expected<unsigned> Maybe = Cursor.readRecord(Entry.ID, Record))
2813 assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE_HASH &&
2814 "invalid record type for input file hash");
2815 else {
2816 // FIXME this drops errors on the floor.
2817 consumeError(Maybe.takeError());
2818 }
2819 R.ContentHash = (static_cast<uint64_t>(Record[1]) << 32) |
2820 static_cast<uint64_t>(Record[0]);
2821
2822 // Note that we've loaded this input file info.
2823 F.InputFileInfosLoaded[ID - 1] = R;
2824 return R;
2825}
2826
2827static unsigned moduleKindForDiagnostic(ModuleKind Kind);
2828InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
2829 // If this ID is bogus, just return an empty input file.
2830 if (ID == 0 || ID > F.InputFilesLoaded.size())
2831 return InputFile();
2832
2833 // If we've already loaded this input file, return it.
2834 if (F.InputFilesLoaded[ID-1].getFile())
2835 return F.InputFilesLoaded[ID-1];
2836
2837 if (F.InputFilesLoaded[ID-1].isNotFound())
2838 return InputFile();
2839
2840 // Go find this input file.
2841 BitstreamCursor &Cursor = F.InputFilesCursor;
2842 SavedStreamPosition SavedPosition(Cursor);
2843 if (llvm::Error Err = Cursor.JumpToBit(F.InputFilesOffsetBase +
2844 F.InputFileOffsets[ID - 1])) {
2845 // FIXME this drops errors on the floor.
2846 consumeError(std::move(Err));
2847 }
2848
2849 InputFileInfo FI = getInputFileInfo(F, ID);
2850 off_t StoredSize = FI.StoredSize;
2851 time_t StoredTime = FI.StoredTime;
2852 bool Overridden = FI.Overridden;
2853 bool Transient = FI.Transient;
2854 auto Filename =
2855 ResolveImportedPath(PathBuf, FI.UnresolvedImportedFilenameAsRequested, F);
2856 uint64_t StoredContentHash = FI.ContentHash;
2857
2858 // For standard C++ modules, we don't need to check the inputs.
2859 bool SkipChecks = F.StandardCXXModule;
2860
2861 const HeaderSearchOptions &HSOpts =
2862 PP.getHeaderSearchInfo().getHeaderSearchOpts();
2863
2864 // The option ForceCheckCXX20ModulesInputFiles is only meaningful for C++20
2865 // modules.
2867 SkipChecks = false;
2868 Overridden = false;
2869 }
2870
2871 auto File = FileMgr.getOptionalFileRef(*Filename, /*OpenFile=*/false);
2872
2873 // For an overridden file, create a virtual file with the stored
2874 // size/timestamp.
2875 if ((Overridden || Transient || SkipChecks) && !File)
2876 File = FileMgr.getVirtualFileRef(*Filename, StoredSize, StoredTime);
2877
2878 if (!File) {
2879 if (Complain) {
2880 std::string ErrorStr = "could not find file '";
2881 ErrorStr += *Filename;
2882 ErrorStr += "' referenced by AST file '";
2883 ErrorStr += F.FileName.str();
2884 ErrorStr += "'";
2885 Error(ErrorStr);
2886 }
2887 // Record that we didn't find the file.
2889 return InputFile();
2890 }
2891
2892 // Check if there was a request to override the contents of the file
2893 // that was part of the precompiled header. Overriding such a file
2894 // can lead to problems when lexing using the source locations from the
2895 // PCH.
2896 SourceManager &SM = getSourceManager();
2897 // FIXME: Reject if the overrides are different.
2898 if ((!Overridden && !Transient) && !SkipChecks &&
2899 SM.isFileOverridden(*File)) {
2900 if (Complain)
2901 Error(diag::err_fe_pch_file_overridden, *Filename);
2902
2903 // After emitting the diagnostic, bypass the overriding file to recover
2904 // (this creates a separate FileEntry).
2905 File = SM.bypassFileContentsOverride(*File);
2906 if (!File) {
2908 return InputFile();
2909 }
2910 }
2911
2912 struct Change {
2913 enum ModificationKind {
2914 Size,
2915 ModTime,
2916 Content,
2917 None,
2918 } Kind;
2919 std::optional<int64_t> Old = std::nullopt;
2920 std::optional<int64_t> New = std::nullopt;
2921 };
2922 auto HasInputContentChanged = [&](Change OriginalChange) {
2923 assert(ValidateASTInputFilesContent &&
2924 "We should only check the content of the inputs with "
2925 "ValidateASTInputFilesContent enabled.");
2926
2927 if (StoredContentHash == 0)
2928 return OriginalChange;
2929
2930 auto MemBuffOrError = FileMgr.getBufferForFile(*File);
2931 if (!MemBuffOrError) {
2932 if (!Complain)
2933 return OriginalChange;
2934 std::string ErrorStr = "could not get buffer for file '";
2935 ErrorStr += File->getName();
2936 ErrorStr += "'";
2937 Error(ErrorStr);
2938 return OriginalChange;
2939 }
2940
2941 auto ContentHash = xxh3_64bits(MemBuffOrError.get()->getBuffer());
2942 if (StoredContentHash == static_cast<uint64_t>(ContentHash))
2943 return Change{Change::None};
2944
2945 return Change{Change::Content};
2946 };
2947 auto HasInputFileChanged = [&]() {
2948 if (StoredSize != File->getSize())
2949 return Change{Change::Size, StoredSize, File->getSize()};
2950 if (!shouldDisableValidationForFile(F) && StoredTime &&
2951 StoredTime != File->getModificationTime()) {
2952 Change MTimeChange = {Change::ModTime, StoredTime,
2953 File->getModificationTime()};
2954
2955 // In case the modification time changes but not the content,
2956 // accept the cached file as legit.
2957 if (ValidateASTInputFilesContent)
2958 return HasInputContentChanged(MTimeChange);
2959
2960 return MTimeChange;
2961 }
2962 return Change{Change::None};
2963 };
2964
2965 bool IsOutOfDate = false;
2966 auto FileChange = SkipChecks ? Change{Change::None} : HasInputFileChanged();
2967 // When ForceCheckCXX20ModulesInputFiles and ValidateASTInputFilesContent
2968 // enabled, it is better to check the contents of the inputs. Since we can't
2969 // get correct modified time information for inputs from overriden inputs.
2970 if (HSOpts.ForceCheckCXX20ModulesInputFiles && ValidateASTInputFilesContent &&
2971 F.StandardCXXModule && FileChange.Kind == Change::None)
2972 FileChange = HasInputContentChanged(FileChange);
2973
2974 // When we have StoredTime equal to zero and ValidateASTInputFilesContent,
2975 // it is better to check the content of the input files because we cannot rely
2976 // on the file modification time, which will be the same (zero) for these
2977 // files.
2978 if (!StoredTime && ValidateASTInputFilesContent &&
2979 FileChange.Kind == Change::None)
2980 FileChange = HasInputContentChanged(FileChange);
2981
2982 // For an overridden file, there is nothing to validate.
2983 if (!Overridden && FileChange.Kind != Change::None) {
2984 if (Complain) {
2985 // Build a list of the PCH imports that got us here (in reverse).
2986 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2987 while (!ImportStack.back()->ImportedBy.empty())
2988 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
2989
2990 // The top-level AST file is stale.
2991 StringRef TopLevelASTFileName(ImportStack.back()->FileName);
2992 Diag(diag::err_fe_ast_file_modified)
2993 << *Filename << moduleKindForDiagnostic(ImportStack.back()->Kind)
2994 << TopLevelASTFileName;
2995 Diag(diag::note_fe_ast_file_modified)
2996 << FileChange.Kind << (FileChange.Old && FileChange.New)
2997 << llvm::itostr(FileChange.Old.value_or(0))
2998 << llvm::itostr(FileChange.New.value_or(0));
2999
3000 // Print the import stack.
3001 if (ImportStack.size() > 1) {
3002 Diag(diag::note_ast_file_required_by)
3003 << *Filename << ImportStack[0]->FileName;
3004 for (unsigned I = 1; I < ImportStack.size(); ++I)
3005 Diag(diag::note_ast_file_required_by)
3006 << ImportStack[I - 1]->FileName << ImportStack[I]->FileName;
3007 }
3008
3010 Diag(diag::note_ast_file_rebuild_required) << TopLevelASTFileName;
3011 Diag(diag::note_ast_file_input_files_validation_status)
3013 }
3014
3015 IsOutOfDate = true;
3016 }
3017 // FIXME: If the file is overridden and we've already opened it,
3018 // issue an error (or split it into a separate FileEntry).
3019
3020 InputFile IF = InputFile(*File, Overridden || Transient, IsOutOfDate);
3021
3022 // Note that we've loaded this input file.
3023 F.InputFilesLoaded[ID-1] = IF;
3024 return IF;
3025}
3026
3027ASTReader::TemporarilyOwnedStringRef
3029 ModuleFile &ModF) {
3030 return ResolveImportedPath(Buf, Path, ModF.BaseDirectory);
3031}
3032
3033ASTReader::TemporarilyOwnedStringRef
3035 StringRef Prefix) {
3036 assert(Buf.capacity() != 0 && "Overlapping ResolveImportedPath calls");
3037
3038 if (Prefix.empty() || Path.empty() || llvm::sys::path::is_absolute(Path) ||
3039 Path == "<built-in>" || Path == "<command line>")
3040 return {Path, Buf};
3041
3042 Buf.clear();
3043 llvm::sys::path::append(Buf, Prefix, Path);
3044 StringRef ResolvedPath{Buf.data(), Buf.size()};
3045 return {ResolvedPath, Buf};
3046}
3047
3049 StringRef P,
3050 ModuleFile &ModF) {
3051 return ResolveImportedPathAndAllocate(Buf, P, ModF.BaseDirectory);
3052}
3053
3055 StringRef P,
3056 StringRef Prefix) {
3057 auto ResolvedPath = ResolveImportedPath(Buf, P, Prefix);
3058 return ResolvedPath->str();
3059}
3060
3061static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
3062 switch (ARR) {
3063 case ASTReader::Failure: return true;
3064 case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
3065 case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
3068 return !(Caps & ASTReader::ARR_ConfigurationMismatch);
3069 case ASTReader::HadErrors: return true;
3070 case ASTReader::Success: return false;
3071 }
3072
3073 llvm_unreachable("unknown ASTReadResult");
3074}
3075
3076ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(
3077 BitstreamCursor &Stream, StringRef Filename,
3078 unsigned ClientLoadCapabilities, bool AllowCompatibleConfigurationMismatch,
3079 ASTReaderListener &Listener, std::string &SuggestedPredefines) {
3080 if (llvm::Error Err = Stream.EnterSubBlock(OPTIONS_BLOCK_ID)) {
3081 // FIXME this drops errors on the floor.
3082 consumeError(std::move(Err));
3083 return Failure;
3084 }
3085
3086 // Read all of the records in the options block.
3087 RecordData Record;
3088 ASTReadResult Result = Success;
3089 while (true) {
3090 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
3091 if (!MaybeEntry) {
3092 // FIXME this drops errors on the floor.
3093 consumeError(MaybeEntry.takeError());
3094 return Failure;
3095 }
3096 llvm::BitstreamEntry Entry = MaybeEntry.get();
3097
3098 switch (Entry.Kind) {
3099 case llvm::BitstreamEntry::Error:
3100 case llvm::BitstreamEntry::SubBlock:
3101 return Failure;
3102
3103 case llvm::BitstreamEntry::EndBlock:
3104 return Result;
3105
3106 case llvm::BitstreamEntry::Record:
3107 // The interesting case.
3108 break;
3109 }
3110
3111 // Read and process a record.
3112 Record.clear();
3113 Expected<unsigned> MaybeRecordType = Stream.readRecord(Entry.ID, Record);
3114 if (!MaybeRecordType) {
3115 // FIXME this drops errors on the floor.
3116 consumeError(MaybeRecordType.takeError());
3117 return Failure;
3118 }
3119 switch ((OptionsRecordTypes)MaybeRecordType.get()) {
3120 case LANGUAGE_OPTIONS: {
3121 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
3122 if (ParseLanguageOptions(Record, Filename, Complain, Listener,
3123 AllowCompatibleConfigurationMismatch))
3124 Result = ConfigurationMismatch;
3125 break;
3126 }
3127
3128 case CODEGEN_OPTIONS: {
3129 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
3130 if (ParseCodeGenOptions(Record, Filename, Complain, Listener,
3131 AllowCompatibleConfigurationMismatch))
3132 Result = ConfigurationMismatch;
3133 break;
3134 }
3135
3136 case TARGET_OPTIONS: {
3137 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
3138 if (ParseTargetOptions(Record, Filename, Complain, Listener,
3139 AllowCompatibleConfigurationMismatch))
3140 Result = ConfigurationMismatch;
3141 break;
3142 }
3143
3144 case FILE_SYSTEM_OPTIONS: {
3145 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
3146 if (!AllowCompatibleConfigurationMismatch &&
3147 ParseFileSystemOptions(Record, Complain, Listener))
3148 Result = ConfigurationMismatch;
3149 break;
3150 }
3151
3152 case HEADER_SEARCH_OPTIONS: {
3153 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
3154 if (!AllowCompatibleConfigurationMismatch &&
3155 ParseHeaderSearchOptions(Record, Filename, Complain, Listener))
3156 Result = ConfigurationMismatch;
3157 break;
3158 }
3159
3161 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
3162 if (!AllowCompatibleConfigurationMismatch &&
3163 ParsePreprocessorOptions(Record, Filename, Complain, Listener,
3164 SuggestedPredefines))
3165 Result = ConfigurationMismatch;
3166 break;
3167 }
3168 }
3169}
3170
3171ASTReader::RelocationResult
3172ASTReader::getModuleForRelocationChecks(ModuleFile &F, bool DirectoryCheck) {
3173 // Don't emit module relocation errors if we have -fno-validate-pch.
3174 const bool IgnoreError =
3175 bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation &
3177
3178 if (!PP.getPreprocessorOpts().ModulesCheckRelocated)
3179 return {std::nullopt, IgnoreError};
3180
3181 const bool IsImplicitModule = F.Kind == MK_ImplicitModule;
3182
3183 if (!DirectoryCheck &&
3184 (!IsImplicitModule || ModuleMgr.begin()->Kind == MK_MainFile))
3185 return {std::nullopt, IgnoreError};
3186
3187 const HeaderSearchOptions &HSOpts =
3188 PP.getHeaderSearchInfo().getHeaderSearchOpts();
3189
3190 // When only validating modules once per build session,
3191 // Skip check if the timestamp is up to date or module was built in same build
3192 // session.
3193 if (HSOpts.ModulesValidateOncePerBuildSession && IsImplicitModule) {
3195 return {std::nullopt, IgnoreError};
3196 if (static_cast<uint64_t>(F.ModTime) >= HSOpts.BuildSessionTimestamp)
3197 return {std::nullopt, IgnoreError};
3198 }
3199
3200 Diag(diag::remark_module_check_relocation) << F.ModuleName << F.FileName;
3201
3202 // If we've already loaded a module map file covering this module, we may
3203 // have a better path for it (relative to the current build if doing directory
3204 // check).
3205 Module *M = PP.getHeaderSearchInfo().lookupModule(
3206 F.ModuleName, DirectoryCheck ? SourceLocation() : F.ImportLoc,
3207 /*AllowSearch=*/DirectoryCheck,
3208 /*AllowExtraModuleMapSearch=*/DirectoryCheck);
3209
3210 return {M, IgnoreError};
3211}
3212
3214ASTReader::ReadControlBlock(ModuleFile &F,
3215 SmallVectorImpl<ImportedModule> &Loaded,
3216 const ModuleFile *ImportedBy,
3217 unsigned ClientLoadCapabilities) {
3218 BitstreamCursor &Stream = F.Stream;
3219
3220 if (llvm::Error Err = Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
3221 Error(std::move(Err));
3222 return Failure;
3223 }
3224
3225 // Lambda to read the unhashed control block the first time it's called.
3226 //
3227 // For PCM files, the unhashed control block cannot be read until after the
3228 // MODULE_NAME record. However, PCH files have no MODULE_NAME, and yet still
3229 // need to look ahead before reading the IMPORTS record. For consistency,
3230 // this block is always read somehow (see BitstreamEntry::EndBlock).
3231 bool HasReadUnhashedControlBlock = false;
3232 auto readUnhashedControlBlockOnce = [&]() {
3233 if (!HasReadUnhashedControlBlock) {
3234 HasReadUnhashedControlBlock = true;
3235 if (ASTReadResult Result =
3236 readUnhashedControlBlock(F, ImportedBy, ClientLoadCapabilities))
3237 return Result;
3238 }
3239 return Success;
3240 };
3241
3242 bool DisableValidation = shouldDisableValidationForFile(F);
3243
3244 // Read all of the records and blocks in the control block.
3245 RecordData Record;
3246 unsigned NumInputs = 0;
3247 unsigned NumUserInputs = 0;
3248 StringRef BaseDirectoryAsWritten;
3249 while (true) {
3250 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
3251 if (!MaybeEntry) {
3252 Error(MaybeEntry.takeError());
3253 return Failure;
3254 }
3255 llvm::BitstreamEntry Entry = MaybeEntry.get();
3256
3257 switch (Entry.Kind) {
3258 case llvm::BitstreamEntry::Error:
3259 Error("malformed block record in AST file");
3260 return Failure;
3261 case llvm::BitstreamEntry::EndBlock: {
3262 // Validate the module before returning. This call catches an AST with
3263 // no module name and no imports.
3264 if (ASTReadResult Result = readUnhashedControlBlockOnce())
3265 return Result;
3266
3267 // Validate input files.
3268 const HeaderSearchOptions &HSOpts =
3269 PP.getHeaderSearchInfo().getHeaderSearchOpts();
3270
3271 // All user input files reside at the index range [0, NumUserInputs), and
3272 // system input files reside at [NumUserInputs, NumInputs). For explicitly
3273 // loaded module files, ignore missing inputs.
3274 if (!DisableValidation && F.Kind != MK_ExplicitModule &&
3275 F.Kind != MK_PrebuiltModule) {
3276 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
3277
3278 // If we are reading a module, we will create a verification timestamp,
3279 // so we verify all input files. Otherwise, verify only user input
3280 // files.
3281
3282 unsigned N = ValidateSystemInputs ? NumInputs : NumUserInputs;
3283 F.InputFilesValidationStatus = ValidateSystemInputs
3288 F.Kind == MK_ImplicitModule) {
3289 N = ForceValidateUserInputs ? NumUserInputs : 0;
3291 ForceValidateUserInputs
3294 }
3295
3296 if (N != 0)
3297 Diag(diag::remark_module_validation)
3298 << N << F.ModuleName << F.FileName;
3299
3300 for (unsigned I = 0; I < N; ++I) {
3301 InputFile IF = getInputFile(F, I+1, Complain);
3302 if (!IF.getFile() || IF.isOutOfDate())
3303 return OutOfDate;
3304 }
3305 } else {
3307 }
3308
3309 if (Listener)
3310 Listener->visitModuleFile(F.FileName, F.Kind);
3311
3312 if (Listener && Listener->needsInputFileVisitation()) {
3313 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
3314 : NumUserInputs;
3315 for (unsigned I = 0; I < N; ++I) {
3316 bool IsSystem = I >= NumUserInputs;
3317 InputFileInfo FI = getInputFileInfo(F, I + 1);
3318 auto FilenameAsRequested = ResolveImportedPath(
3320 Listener->visitInputFile(
3321 *FilenameAsRequested, IsSystem, FI.Overridden,
3323 }
3324 }
3325
3326 return Success;
3327 }
3328
3329 case llvm::BitstreamEntry::SubBlock:
3330 switch (Entry.ID) {
3332 F.InputFilesCursor = Stream;
3333 if (llvm::Error Err = Stream.SkipBlock()) {
3334 Error(std::move(Err));
3335 return Failure;
3336 }
3337 if (ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
3338 Error("malformed block record in AST file");
3339 return Failure;
3340 }
3341 F.InputFilesOffsetBase = F.InputFilesCursor.GetCurrentBitNo();
3342 continue;
3343
3344 case OPTIONS_BLOCK_ID:
3345 // If we're reading the first module for this group, check its options
3346 // are compatible with ours. For modules it imports, no further checking
3347 // is required, because we checked them when we built it.
3348 if (Listener && !ImportedBy) {
3349 // Should we allow the configuration of the module file to differ from
3350 // the configuration of the current translation unit in a compatible
3351 // way?
3352 //
3353 // FIXME: Allow this for files explicitly specified with -include-pch.
3354 bool AllowCompatibleConfigurationMismatch =
3356
3357 ASTReadResult Result =
3358 ReadOptionsBlock(Stream, F.FileName, ClientLoadCapabilities,
3359 AllowCompatibleConfigurationMismatch, *Listener,
3360 SuggestedPredefines);
3361 if (Result == Failure) {
3362 Error("malformed block record in AST file");
3363 return Result;
3364 }
3365
3366 if (DisableValidation ||
3367 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
3368 Result = Success;
3369
3370 // If we can't load the module, exit early since we likely
3371 // will rebuild the module anyway. The stream may be in the
3372 // middle of a block.
3373 if (Result != Success)
3374 return Result;
3375 } else if (llvm::Error Err = Stream.SkipBlock()) {
3376 Error(std::move(Err));
3377 return Failure;
3378 }
3379 continue;
3380
3381 default:
3382 if (llvm::Error Err = Stream.SkipBlock()) {
3383 Error(std::move(Err));
3384 return Failure;
3385 }
3386 continue;
3387 }
3388
3389 case llvm::BitstreamEntry::Record:
3390 // The interesting case.
3391 break;
3392 }
3393
3394 // Read and process a record.
3395 Record.clear();
3396 StringRef Blob;
3397 Expected<unsigned> MaybeRecordType =
3398 Stream.readRecord(Entry.ID, Record, &Blob);
3399 if (!MaybeRecordType) {
3400 Error(MaybeRecordType.takeError());
3401 return Failure;
3402 }
3403 switch ((ControlRecordTypes)MaybeRecordType.get()) {
3404 case METADATA: {
3405 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
3406 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
3407 Diag(Record[0] < VERSION_MAJOR ? diag::err_ast_file_version_too_old
3408 : diag::err_ast_file_version_too_new)
3410 return VersionMismatch;
3411 }
3412
3413 bool hasErrors = Record[7];
3414 if (hasErrors && !DisableValidation) {
3415 // If requested by the caller and the module hasn't already been read
3416 // or compiled, mark modules on error as out-of-date.
3417 if ((ClientLoadCapabilities & ARR_TreatModuleWithErrorsAsOutOfDate) &&
3418 canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
3419 return OutOfDate;
3420
3421 if (!AllowASTWithCompilerErrors) {
3422 Diag(diag::err_ast_file_with_compiler_errors)
3424 return HadErrors;
3425 }
3426 }
3427 if (hasErrors) {
3428 Diags.ErrorOccurred = true;
3429 Diags.UncompilableErrorOccurred = true;
3430 Diags.UnrecoverableErrorOccurred = true;
3431 }
3432
3433 F.RelocatablePCH = Record[4];
3434 // Relative paths in a relocatable PCH are relative to our sysroot.
3435 if (F.RelocatablePCH)
3436 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
3437
3439
3440 F.HasTimestamps = Record[6];
3441
3442 const std::string &CurBranch = getClangFullRepositoryVersion();
3443 StringRef ASTBranch = Blob;
3444 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
3445 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
3446 Diag(diag::err_ast_file_different_branch)
3447 << moduleKindForDiagnostic(F.Kind) << F.FileName << ASTBranch
3448 << CurBranch;
3449 return VersionMismatch;
3450 }
3451 break;
3452 }
3453
3454 case IMPORT: {
3455 // Validate the AST before processing any imports (otherwise, untangling
3456 // them can be error-prone and expensive). A module will have a name and
3457 // will already have been validated, but this catches the PCH case.
3458 if (ASTReadResult Result = readUnhashedControlBlockOnce())
3459 return Result;
3460
3461 unsigned Idx = 0;
3462 // Read information about the AST file.
3463 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
3464
3465 // The import location will be the local one for now; we will adjust
3466 // all import locations of module imports after the global source
3467 // location info are setup, in ReadAST.
3468 auto [ImportLoc, ImportModuleFileIndex] =
3469 ReadUntranslatedSourceLocation(Record[Idx++]);
3470 // The import location must belong to the current module file itself.
3471 assert(ImportModuleFileIndex == 0);
3472
3473 StringRef ImportedName = ReadStringBlob(Record, Idx, Blob);
3474
3475 bool IsImportingStdCXXModule = Record[Idx++];
3476
3477 off_t StoredSize = 0;
3478 time_t StoredModTime = 0;
3479 unsigned ImplicitModuleSuffixLength = 0;
3480 ASTFileSignature StoredSignature;
3481 ModuleFileName ImportedFile;
3482 std::string StoredFile;
3483 bool IgnoreImportedByNote = false;
3484
3485 // For prebuilt and explicit modules first consult the file map for
3486 // an override. Note that here we don't search prebuilt module
3487 // directories if we're not importing standard c++ module, only the
3488 // explicit name to file mappings. Also, we will still verify the
3489 // size/signature making sure it is essentially the same file but
3490 // perhaps in a different location.
3491 if (ImportedKind == MK_PrebuiltModule || ImportedKind == MK_ExplicitModule)
3492 ImportedFile = PP.getHeaderSearchInfo().getPrebuiltModuleFileName(
3493 ImportedName, /*FileMapOnly*/ !IsImportingStdCXXModule);
3494
3495 if (IsImportingStdCXXModule && ImportedFile.empty()) {
3496 Diag(diag::err_failed_to_find_module_file) << ImportedName;
3497 return Missing;
3498 }
3499
3500 if (!IsImportingStdCXXModule) {
3501 StoredSize = (off_t)Record[Idx++];
3502 StoredModTime = (time_t)Record[Idx++];
3503 ImplicitModuleSuffixLength = (unsigned)Record[Idx++];
3504
3505 StringRef SignatureBytes = Blob.substr(0, ASTFileSignature::size);
3506 StoredSignature = ASTFileSignature::create(SignatureBytes.begin(),
3507 SignatureBytes.end());
3508 Blob = Blob.substr(ASTFileSignature::size);
3509
3510 StoredFile = ReadPathBlob(BaseDirectoryAsWritten, Record, Idx, Blob);
3511 if (ImportedFile.empty()) {
3512 ImportedFile = ImplicitModuleSuffixLength
3514 StoredFile, ImplicitModuleSuffixLength)
3515 : ModuleFileName::makeExplicit(StoredFile);
3516 assert((ImportedKind == MK_ImplicitModule) ==
3517 (ImplicitModuleSuffixLength != 0));
3518 } else if (!getDiags().isIgnored(
3519 diag::warn_module_file_mapping_mismatch,
3520 CurrentImportLoc)) {
3521 auto ImportedFileRef =
3522 PP.getFileManager().getOptionalFileRef(ImportedFile);
3523 auto StoredFileRef =
3524 PP.getFileManager().getOptionalFileRef(StoredFile);
3525 if ((ImportedFileRef && StoredFileRef) &&
3526 (*ImportedFileRef != *StoredFileRef)) {
3527 Diag(diag::warn_module_file_mapping_mismatch)
3528 << ImportedFile << StoredFile;
3529 Diag(diag::note_module_file_imported_by)
3530 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
3531 IgnoreImportedByNote = true;
3532 }
3533 }
3534 }
3535
3536 // If our client can't cope with us being out of date, we can't cope with
3537 // our dependency being missing.
3538 unsigned Capabilities = ClientLoadCapabilities;
3539 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3540 Capabilities &= ~ARR_Missing;
3541
3542 // Load the AST file.
3543 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
3544 Loaded, StoredSize, StoredModTime,
3545 StoredSignature, Capabilities);
3546
3547 // Check the AST we just read from ImportedFile contains a different
3548 // module than we expected (ImportedName). This can occur for C++20
3549 // Modules when given a mismatch via -fmodule-file=<name>=<file>
3550 if (IsImportingStdCXXModule) {
3551 if (const auto *Imported =
3552 getModuleManager().lookupByFileName(ImportedFile);
3553 Imported != nullptr && Imported->ModuleName != ImportedName) {
3554 Diag(diag::err_failed_to_find_module_file) << ImportedName;
3555 Result = Missing;
3556 }
3557 }
3558
3559 // If we diagnosed a problem, produce a backtrace.
3560 bool recompilingFinalized = Result == OutOfDate &&
3561 (Capabilities & ARR_OutOfDate) &&
3562 getModuleManager()
3563 .getModuleCache()
3564 .getInMemoryModuleCache()
3565 .isPCMFinal(F.FileName);
3566 if (!IgnoreImportedByNote &&
3567 (isDiagnosedResult(Result, Capabilities) || recompilingFinalized))
3568 Diag(diag::note_module_file_imported_by)
3569 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
3570
3571 switch (Result) {
3572 case Failure: return Failure;
3573 // If we have to ignore the dependency, we'll have to ignore this too.
3574 case Missing:
3575 case OutOfDate: return OutOfDate;
3576 case VersionMismatch: return VersionMismatch;
3577 case ConfigurationMismatch: return ConfigurationMismatch;
3578 case HadErrors: return HadErrors;
3579 case Success: break;
3580 }
3581 break;
3582 }
3583
3584 case ORIGINAL_FILE:
3585 F.OriginalSourceFileID = FileID::get(Record[0]);
3586 F.ActualOriginalSourceFileName = std::string(Blob);
3587 F.OriginalSourceFileName = ResolveImportedPathAndAllocate(
3588 PathBuf, F.ActualOriginalSourceFileName, F);
3589 break;
3590
3591 case ORIGINAL_FILE_ID:
3592 F.OriginalSourceFileID = FileID::get(Record[0]);
3593 break;
3594
3595 case MODULE_NAME:
3596 F.ModuleName = std::string(Blob);
3597 Diag(diag::remark_module_import)
3598 << F.ModuleName << F.FileName << (ImportedBy ? true : false)
3599 << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());
3600 if (Listener)
3601 Listener->ReadModuleName(F.ModuleName);
3602
3603 // Validate the AST as soon as we have a name so we can exit early on
3604 // failure.
3605 if (ASTReadResult Result = readUnhashedControlBlockOnce())
3606 return Result;
3607
3608 break;
3609
3610 case MODULE_DIRECTORY: {
3611 // Save the BaseDirectory as written in the PCM for computing the module
3612 // filename for the ModuleCache.
3613 BaseDirectoryAsWritten = Blob;
3614 assert(!F.ModuleName.empty() &&
3615 "MODULE_DIRECTORY found before MODULE_NAME");
3616 F.BaseDirectory = std::string(Blob);
3617
3618 auto [MaybeM, IgnoreError] =
3619 getModuleForRelocationChecks(F, /*DirectoryCheck=*/true);
3620 if (!MaybeM.has_value())
3621 break;
3622
3623 Module *M = MaybeM.value();
3624 if (!M || !M->Directory)
3625 break;
3626 if (IgnoreError) {
3627 F.BaseDirectory = std::string(M->Directory->getName());
3628 break;
3629 }
3630 if ((F.Kind == MK_ExplicitModule) || (F.Kind == MK_PrebuiltModule))
3631 break;
3632
3633 // If we're implicitly loading a module, the base directory can't
3634 // change between the build and use.
3635 auto BuildDir = PP.getFileManager().getOptionalDirectoryRef(Blob);
3636 if (BuildDir && (*BuildDir == M->Directory)) {
3637 F.BaseDirectory = std::string(M->Directory->getName());
3638 break;
3639 }
3640 Diag(diag::remark_module_relocated)
3641 << F.ModuleName << Blob << M->Directory->getName();
3642
3643 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
3644 Diag(diag::err_imported_module_relocated)
3645 << F.ModuleName << Blob << M->Directory->getName();
3646 return OutOfDate;
3647 }
3648
3649 case MODULE_MAP_FILE:
3650 if (ASTReadResult Result =
3651 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
3652 return Result;
3653 break;
3654
3655 case INPUT_FILE_OFFSETS:
3656 NumInputs = Record[0];
3657 NumUserInputs = Record[1];
3659 (const llvm::support::unaligned_uint64_t *)Blob.data();
3660 F.InputFilesLoaded.resize(NumInputs);
3661 F.InputFileInfosLoaded.resize(NumInputs);
3662 F.NumUserInputFiles = NumUserInputs;
3663 break;
3664 }
3665 }
3666}
3667
3668llvm::Error ASTReader::ReadASTBlock(ModuleFile &F,
3669 unsigned ClientLoadCapabilities) {
3670 BitstreamCursor &Stream = F.Stream;
3671
3672 if (llvm::Error Err = Stream.EnterSubBlock(AST_BLOCK_ID))
3673 return Err;
3674 F.ASTBlockStartOffset = Stream.GetCurrentBitNo();
3675
3676 // Read all of the records and blocks for the AST file.
3677 RecordData Record;
3678 while (true) {
3679 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
3680 if (!MaybeEntry)
3681 return MaybeEntry.takeError();
3682 llvm::BitstreamEntry Entry = MaybeEntry.get();
3683
3684 switch (Entry.Kind) {
3685 case llvm::BitstreamEntry::Error:
3686 return llvm::createStringError(
3687 std::errc::illegal_byte_sequence,
3688 "error at end of module block in AST file");
3689 case llvm::BitstreamEntry::EndBlock:
3690 // Outside of C++, we do not store a lookup map for the translation unit.
3691 // Instead, mark it as needing a lookup map to be built if this module
3692 // contains any declarations lexically within it (which it always does!).
3693 // This usually has no cost, since we very rarely need the lookup map for
3694 // the translation unit outside C++.
3695 if (ASTContext *Ctx = ContextObj) {
3696 DeclContext *DC = Ctx->getTranslationUnitDecl();
3697 if (DC->hasExternalLexicalStorage() && !Ctx->getLangOpts().CPlusPlus)
3699 }
3700
3701 return llvm::Error::success();
3702 case llvm::BitstreamEntry::SubBlock:
3703 switch (Entry.ID) {
3704 case DECLTYPES_BLOCK_ID:
3705 // We lazily load the decls block, but we want to set up the
3706 // DeclsCursor cursor to point into it. Clone our current bitcode
3707 // cursor to it, enter the block and read the abbrevs in that block.
3708 // With the main cursor, we just skip over it.
3709 F.DeclsCursor = Stream;
3710 if (llvm::Error Err = Stream.SkipBlock())
3711 return Err;
3712 if (llvm::Error Err = ReadBlockAbbrevs(
3714 return Err;
3715 break;
3716
3718 F.MacroCursor = Stream;
3719 if (!PP.getExternalSource())
3720 PP.setExternalSource(this);
3721
3722 if (llvm::Error Err = Stream.SkipBlock())
3723 return Err;
3724 if (llvm::Error Err =
3725 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID))
3726 return Err;
3727 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
3728 break;
3729
3731 F.PreprocessorDetailCursor = Stream;
3732
3733 if (llvm::Error Err = Stream.SkipBlock()) {
3734 return Err;
3735 }
3736 if (llvm::Error Err = ReadBlockAbbrevs(F.PreprocessorDetailCursor,
3738 return Err;
3740 = F.PreprocessorDetailCursor.GetCurrentBitNo();
3741
3742 if (!PP.getPreprocessingRecord())
3743 PP.createPreprocessingRecord();
3744 if (!PP.getPreprocessingRecord()->getExternalSource())
3745 PP.getPreprocessingRecord()->SetExternalSource(*this);
3746 break;
3747
3749 if (llvm::Error Err = ReadSourceManagerBlock(F))
3750 return Err;
3751 break;
3752
3753 case SUBMODULE_BLOCK_ID:
3754 if (llvm::Error Err = ReadSubmoduleBlock(F, ClientLoadCapabilities))
3755 return Err;
3756 break;
3757
3758 case COMMENTS_BLOCK_ID: {
3759 BitstreamCursor C = Stream;
3760
3761 if (llvm::Error Err = Stream.SkipBlock())
3762 return Err;
3763 if (llvm::Error Err = ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID))
3764 return Err;
3765 CommentsCursors.push_back(std::make_pair(C, &F));
3766 break;
3767 }
3768
3769 default:
3770 if (llvm::Error Err = Stream.SkipBlock())
3771 return Err;
3772 break;
3773 }
3774 continue;
3775
3776 case llvm::BitstreamEntry::Record:
3777 // The interesting case.
3778 break;
3779 }
3780
3781 // Read and process a record.
3782 Record.clear();
3783 StringRef Blob;
3784 Expected<unsigned> MaybeRecordType =
3785 Stream.readRecord(Entry.ID, Record, &Blob);
3786 if (!MaybeRecordType)
3787 return MaybeRecordType.takeError();
3788 ASTRecordTypes RecordType = (ASTRecordTypes)MaybeRecordType.get();
3789
3790 // If we're not loading an AST context, we don't care about most records.
3791 if (!ContextObj) {
3792 switch (RecordType) {
3793 case IDENTIFIER_TABLE:
3794 case IDENTIFIER_OFFSET:
3796 case STATISTICS:
3799 case PP_COUNTER_VALUE:
3801 case MODULE_OFFSET_MAP:
3805 case IMPORTED_MODULES:
3806 case MACRO_OFFSET:
3807 break;
3808 default:
3809 continue;
3810 }
3811 }
3812
3813 switch (RecordType) {
3814 default: // Default behavior: ignore.
3815 break;
3816
3817 case TYPE_OFFSET: {
3818 if (F.LocalNumTypes != 0)
3819 return llvm::createStringError(
3820 std::errc::illegal_byte_sequence,
3821 "duplicate TYPE_OFFSET record in AST file");
3822 F.TypeOffsets = reinterpret_cast<const UnalignedUInt64 *>(Blob.data());
3823 F.LocalNumTypes = Record[0];
3824 F.BaseTypeIndex = getTotalNumTypes();
3825
3826 if (F.LocalNumTypes > 0)
3827 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
3828
3829 break;
3830 }
3831
3832 case DECL_OFFSET: {
3833 if (F.LocalNumDecls != 0)
3834 return llvm::createStringError(
3835 std::errc::illegal_byte_sequence,
3836 "duplicate DECL_OFFSET record in AST file");
3837 F.DeclOffsets = (const DeclOffset *)Blob.data();
3838 F.LocalNumDecls = Record[0];
3839 F.BaseDeclIndex = getTotalNumDecls();
3840
3841 if (F.LocalNumDecls > 0)
3842 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
3843
3844 break;
3845 }
3846
3847 case TU_UPDATE_LEXICAL: {
3848 DeclContext *TU = ContextObj->getTranslationUnitDecl();
3849 LexicalContents Contents(
3850 reinterpret_cast<const unaligned_decl_id_t *>(Blob.data()),
3851 static_cast<unsigned int>(Blob.size() / sizeof(DeclID)));
3852 TULexicalDecls.push_back(std::make_pair(&F, Contents));
3854 break;
3855 }
3856
3857 case UPDATE_VISIBLE: {
3858 unsigned Idx = 0;
3859 GlobalDeclID ID = ReadDeclID(F, Record, Idx);
3860 auto *Data = (const unsigned char*)Blob.data();
3861 PendingVisibleUpdates[ID].push_back(UpdateData{&F, Data});
3862 // If we've already loaded the decl, perform the updates when we finish
3863 // loading this block.
3864 if (Decl *D = GetExistingDecl(ID))
3865 PendingUpdateRecords.push_back(
3866 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3867 break;
3868 }
3869
3871 unsigned Idx = 0;
3872 GlobalDeclID ID = ReadDeclID(F, Record, Idx);
3873 auto *Data = (const unsigned char *)Blob.data();
3874 PendingModuleLocalVisibleUpdates[ID].push_back(UpdateData{&F, Data});
3875 // If we've already loaded the decl, perform the updates when we finish
3876 // loading this block.
3877 if (Decl *D = GetExistingDecl(ID))
3878 PendingUpdateRecords.push_back(
3879 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3880 break;
3881 }
3882
3884 if (F.Kind != MK_MainFile)
3885 break;
3886 unsigned Idx = 0;
3887 GlobalDeclID ID = ReadDeclID(F, Record, Idx);
3888 auto *Data = (const unsigned char *)Blob.data();
3889 TULocalUpdates[ID].push_back(UpdateData{&F, Data});
3890 // If we've already loaded the decl, perform the updates when we finish
3891 // loading this block.
3892 if (Decl *D = GetExistingDecl(ID))
3893 PendingUpdateRecords.push_back(
3894 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3895 break;
3896 }
3897
3899 unsigned Idx = 0;
3900 GlobalDeclID ID = ReadDeclID(F, Record, Idx);
3901 auto *Data = (const unsigned char *)Blob.data();
3902 PendingSpecializationsUpdates[ID].push_back(UpdateData{&F, Data});
3903 // If we've already loaded the decl, perform the updates when we finish
3904 // loading this block.
3905 if (Decl *D = GetExistingDecl(ID))
3906 PendingUpdateRecords.push_back(
3907 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3908 break;
3909 }
3910
3912 unsigned Idx = 0;
3913 GlobalDeclID ID = ReadDeclID(F, Record, Idx);
3914 auto *Data = (const unsigned char *)Blob.data();
3915 PendingPartialSpecializationsUpdates[ID].push_back(UpdateData{&F, Data});
3916 // If we've already loaded the decl, perform the updates when we finish
3917 // loading this block.
3918 if (Decl *D = GetExistingDecl(ID))
3919 PendingUpdateRecords.push_back(
3920 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3921 break;
3922 }
3923
3924 case IDENTIFIER_TABLE:
3926 reinterpret_cast<const unsigned char *>(Blob.data());
3927 if (Record[0]) {
3928 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
3930 F.IdentifierTableData + sizeof(uint32_t),
3932 ASTIdentifierLookupTrait(*this, F));
3933
3934 PP.getIdentifierTable().setExternalIdentifierLookup(this);
3935 }
3936 break;
3937
3938 case IDENTIFIER_OFFSET: {
3939 if (F.LocalNumIdentifiers != 0)
3940 return llvm::createStringError(
3941 std::errc::illegal_byte_sequence,
3942 "duplicate IDENTIFIER_OFFSET record in AST file");
3943 F.IdentifierOffsets = (const uint32_t *)Blob.data();
3945 F.BaseIdentifierID = getTotalNumIdentifiers();
3946
3947 if (F.LocalNumIdentifiers > 0)
3948 IdentifiersLoaded.resize(IdentifiersLoaded.size()
3950 break;
3951 }
3952
3954 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
3955 break;
3956
3958 // FIXME: Skip reading this record if our ASTConsumer doesn't care
3959 // about "interesting" decls (for instance, if we're building a module).
3960 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
3961 EagerlyDeserializedDecls.push_back(ReadDeclID(F, Record, I));
3962 break;
3963
3965 // FIXME: Skip reading this record if our ASTConsumer doesn't care about
3966 // them (ie: if we're not codegenerating this module).
3967 if (F.Kind == MK_MainFile ||
3968 getContext().getLangOpts().BuildingPCHWithObjectFile)
3969 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
3970 EagerlyDeserializedDecls.push_back(ReadDeclID(F, Record, I));
3971 break;
3972
3973 case SPECIAL_TYPES:
3974 if (SpecialTypes.empty()) {
3975 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3976 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
3977 break;
3978 }
3979
3980 if (Record.empty())
3981 break;
3982
3983 if (SpecialTypes.size() != Record.size())
3984 return llvm::createStringError(std::errc::illegal_byte_sequence,
3985 "invalid special-types record");
3986
3987 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
3988 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
3989 if (!SpecialTypes[I])
3990 SpecialTypes[I] = ID;
3991 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
3992 // merge step?
3993 }
3994 break;
3995
3996 case STATISTICS:
3997 TotalNumStatements += Record[0];
3998 TotalNumMacros += Record[1];
3999 TotalLexicalDeclContexts += Record[2];
4000 TotalVisibleDeclContexts += Record[3];
4001 TotalModuleLocalVisibleDeclContexts += Record[4];
4002 TotalTULocalVisibleDeclContexts += Record[5];
4003 break;
4004
4006 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4007 UnusedFileScopedDecls.push_back(ReadDeclID(F, Record, I));
4008 break;
4009
4010 case DELEGATING_CTORS:
4011 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4012 DelegatingCtorDecls.push_back(ReadDeclID(F, Record, I));
4013 break;
4014
4016 if (Record.size() % 3 != 0)
4017 return llvm::createStringError(std::errc::illegal_byte_sequence,
4018 "invalid weak identifiers record");
4019
4020 // FIXME: Ignore weak undeclared identifiers from non-original PCH
4021 // files. This isn't the way to do it :)
4022 WeakUndeclaredIdentifiers.clear();
4023
4024 // Translate the weak, undeclared identifiers into global IDs.
4025 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
4026 WeakUndeclaredIdentifiers.push_back(
4027 getGlobalIdentifierID(F, Record[I++]));
4028 WeakUndeclaredIdentifiers.push_back(
4029 getGlobalIdentifierID(F, Record[I++]));
4030 WeakUndeclaredIdentifiers.push_back(
4031 ReadSourceLocation(F, Record, I).getRawEncoding());
4032 }
4033 break;
4034
4035 case SELECTOR_OFFSETS: {
4036 F.SelectorOffsets = (const uint32_t *)Blob.data();
4038 unsigned LocalBaseSelectorID = Record[1];
4039 F.BaseSelectorID = getTotalNumSelectors();
4040
4041 if (F.LocalNumSelectors > 0) {
4042 // Introduce the global -> local mapping for selectors within this
4043 // module.
4044 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
4045
4046 // Introduce the local -> global mapping for selectors within this
4047 // module.
4049 std::make_pair(LocalBaseSelectorID,
4050 F.BaseSelectorID - LocalBaseSelectorID));
4051
4052 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
4053 }
4054 break;
4055 }
4056
4057 case METHOD_POOL:
4058 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
4059 if (Record[0])
4061 = ASTSelectorLookupTable::Create(
4064 ASTSelectorLookupTrait(*this, F));
4065 TotalNumMethodPoolEntries += Record[1];
4066 break;
4067
4069 if (!Record.empty()) {
4070 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
4071 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
4072 Record[Idx++]));
4073 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
4074 getRawEncoding());
4075 }
4076 }
4077 break;
4078
4079 case PP_ASSUME_NONNULL_LOC: {
4080 unsigned Idx = 0;
4081 if (!Record.empty())
4082 PP.setPreambleRecordedPragmaAssumeNonNullLoc(
4083 ReadSourceLocation(F, Record, Idx));
4084 break;
4085 }
4086
4088 if (!Record.empty()) {
4089 SmallVector<SourceLocation, 64> SrcLocs;
4090 unsigned Idx = 0;
4091 while (Idx < Record.size())
4092 SrcLocs.push_back(ReadSourceLocation(F, Record, Idx));
4093 PP.setDeserializedSafeBufferOptOutMap(SrcLocs);
4094 }
4095 break;
4096 }
4097
4099 if (!Record.empty()) {
4100 unsigned Idx = 0, End = Record.size() - 1;
4101 bool ReachedEOFWhileSkipping = Record[Idx++];
4102 std::optional<Preprocessor::PreambleSkipInfo> SkipInfo;
4103 if (ReachedEOFWhileSkipping) {
4104 SourceLocation HashToken = ReadSourceLocation(F, Record, Idx);
4105 SourceLocation IfTokenLoc = ReadSourceLocation(F, Record, Idx);
4106 bool FoundNonSkipPortion = Record[Idx++];
4107 bool FoundElse = Record[Idx++];
4108 SourceLocation ElseLoc = ReadSourceLocation(F, Record, Idx);
4109 SkipInfo.emplace(HashToken, IfTokenLoc, FoundNonSkipPortion,
4110 FoundElse, ElseLoc);
4111 }
4112 SmallVector<PPConditionalInfo, 4> ConditionalStack;
4113 while (Idx < End) {
4114 auto Loc = ReadSourceLocation(F, Record, Idx);
4115 bool WasSkipping = Record[Idx++];
4116 bool FoundNonSkip = Record[Idx++];
4117 bool FoundElse = Record[Idx++];
4118 ConditionalStack.push_back(
4119 {Loc, WasSkipping, FoundNonSkip, FoundElse});
4120 }
4121 PP.setReplayablePreambleConditionalStack(ConditionalStack, SkipInfo);
4122 }
4123 break;
4124
4125 case PP_COUNTER_VALUE:
4126 if (!Record.empty() && Listener)
4127 Listener->ReadCounter(F, Record[0]);
4128 break;
4129
4130 case FILE_SORTED_DECLS:
4131 F.FileSortedDecls = (const unaligned_decl_id_t *)Blob.data();
4133 break;
4134
4136 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
4138 SourceLocation::UIntTy SLocSpaceSize = Record[1];
4140 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
4141 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
4142 SLocSpaceSize);
4143 if (!F.SLocEntryBaseID) {
4144 Diags.Report(SourceLocation(), diag::remark_sloc_usage);
4145 SourceMgr.noteSLocAddressSpaceUsage(Diags);
4146 return llvm::createStringError(std::errc::invalid_argument,
4147 "ran out of source locations");
4148 }
4149 // Make our entry in the range map. BaseID is negative and growing, so
4150 // we invert it. Because we invert it, though, we need the other end of
4151 // the range.
4152 unsigned RangeStart =
4153 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
4154 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
4156
4157 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
4158 assert((F.SLocEntryBaseOffset & SourceLocation::MacroIDBit) == 0);
4159 GlobalSLocOffsetMap.insert(
4160 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
4161 - SLocSpaceSize,&F));
4162
4163 TotalNumSLocEntries += F.LocalNumSLocEntries;
4164 break;
4165 }
4166
4167 case MODULE_OFFSET_MAP:
4168 F.ModuleOffsetMap = Blob;
4169 break;
4170
4172 ParseLineTable(F, Record);
4173 break;
4174
4175 case EXT_VECTOR_DECLS:
4176 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4177 ExtVectorDecls.push_back(ReadDeclID(F, Record, I));
4178 break;
4179
4180 case VTABLE_USES:
4181 if (Record.size() % 3 != 0)
4182 return llvm::createStringError(std::errc::illegal_byte_sequence,
4183 "Invalid VTABLE_USES record");
4184
4185 // Later tables overwrite earlier ones.
4186 // FIXME: Modules will have some trouble with this. This is clearly not
4187 // the right way to do this.
4188 VTableUses.clear();
4189
4190 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
4191 VTableUses.push_back(
4192 {ReadDeclID(F, Record, Idx),
4193 ReadSourceLocation(F, Record, Idx).getRawEncoding(),
4194 (bool)Record[Idx++]});
4195 }
4196 break;
4197
4199
4200 if (Record.size() % 2 != 0)
4201 return llvm::createStringError(
4202 std::errc::illegal_byte_sequence,
4203 "Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
4204
4205 // For standard C++20 module, we will only reads the instantiations
4206 // if it is the main file.
4207 if (!F.StandardCXXModule || F.Kind == MK_MainFile) {
4208 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
4209 PendingInstantiations.push_back(
4210 {ReadDeclID(F, Record, I),
4211 ReadSourceLocation(F, Record, I).getRawEncoding()});
4212 }
4213 }
4214 break;
4215
4216 case SEMA_DECL_REFS:
4217 if (Record.size() != 3)
4218 return llvm::createStringError(std::errc::illegal_byte_sequence,
4219 "Invalid SEMA_DECL_REFS block");
4220 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4221 SemaDeclRefs.push_back(ReadDeclID(F, Record, I));
4222 break;
4223
4224 case PPD_ENTITIES_OFFSETS: {
4225 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
4226 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
4227 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
4228
4229 unsigned StartingID;
4230 if (!PP.getPreprocessingRecord())
4231 PP.createPreprocessingRecord();
4232 if (!PP.getPreprocessingRecord()->getExternalSource())
4233 PP.getPreprocessingRecord()->SetExternalSource(*this);
4234 StartingID
4235 = PP.getPreprocessingRecord()
4236 ->allocateLoadedEntities(F.NumPreprocessedEntities);
4237 F.BasePreprocessedEntityID = StartingID;
4238
4239 if (F.NumPreprocessedEntities > 0) {
4240 // Introduce the global -> local mapping for preprocessed entities in
4241 // this module.
4242 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
4243 }
4244
4245 break;
4246 }
4247
4248 case PPD_SKIPPED_RANGES: {
4249 F.PreprocessedSkippedRangeOffsets = (const PPSkippedRange*)Blob.data();
4250 assert(Blob.size() % sizeof(PPSkippedRange) == 0);
4251 F.NumPreprocessedSkippedRanges = Blob.size() / sizeof(PPSkippedRange);
4252
4253 if (!PP.getPreprocessingRecord())
4254 PP.createPreprocessingRecord();
4255 if (!PP.getPreprocessingRecord()->getExternalSource())
4256 PP.getPreprocessingRecord()->SetExternalSource(*this);
4257 F.BasePreprocessedSkippedRangeID = PP.getPreprocessingRecord()
4258 ->allocateSkippedRanges(F.NumPreprocessedSkippedRanges);
4259
4261 GlobalSkippedRangeMap.insert(
4262 std::make_pair(F.BasePreprocessedSkippedRangeID, &F));
4263 break;
4264 }
4265
4267 if (Record.size() % 2 != 0)
4268 return llvm::createStringError(
4269 std::errc::illegal_byte_sequence,
4270 "invalid DECL_UPDATE_OFFSETS block in AST file");
4271 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/) {
4272 GlobalDeclID ID = ReadDeclID(F, Record, I);
4273 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I++]));
4274
4275 // If we've already loaded the decl, perform the updates when we finish
4276 // loading this block.
4277 if (Decl *D = GetExistingDecl(ID))
4278 PendingUpdateRecords.push_back(
4279 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
4280 }
4281 break;
4282
4284 if (Record.size() % 5 != 0)
4285 return llvm::createStringError(
4286 std::errc::illegal_byte_sequence,
4287 "invalid DELAYED_NAMESPACE_LEXICAL_VISIBLE_RECORD block in AST "
4288 "file");
4289 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/) {
4290 GlobalDeclID ID = ReadDeclID(F, Record, I);
4291
4292 uint64_t BaseOffset = F.DeclsBlockStartOffset;
4293 assert(BaseOffset && "Invalid DeclsBlockStartOffset for module file!");
4294 uint64_t LocalLexicalOffset = Record[I++];
4295 uint64_t LexicalOffset =
4296 LocalLexicalOffset ? BaseOffset + LocalLexicalOffset : 0;
4297 uint64_t LocalVisibleOffset = Record[I++];
4298 uint64_t VisibleOffset =
4299 LocalVisibleOffset ? BaseOffset + LocalVisibleOffset : 0;
4300 uint64_t LocalModuleLocalOffset = Record[I++];
4301 uint64_t ModuleLocalOffset =
4302 LocalModuleLocalOffset ? BaseOffset + LocalModuleLocalOffset : 0;
4303 uint64_t TULocalLocalOffset = Record[I++];
4304 uint64_t TULocalOffset =
4305 TULocalLocalOffset ? BaseOffset + TULocalLocalOffset : 0;
4306
4307 DelayedNamespaceOffsetMap[ID] = {
4308 {VisibleOffset, ModuleLocalOffset, TULocalOffset}, LexicalOffset};
4309
4310 assert(!GetExistingDecl(ID) &&
4311 "We shouldn't load the namespace in the front of delayed "
4312 "namespace lexical and visible block");
4313 }
4314 break;
4315 }
4316
4317 case RELATED_DECLS_MAP:
4318 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/) {
4319 GlobalDeclID ID = ReadDeclID(F, Record, I);
4320 auto &RelatedDecls = RelatedDeclsMap[ID];
4321 unsigned NN = Record[I++];
4322 RelatedDecls.reserve(NN);
4323 for (unsigned II = 0; II < NN; II++)
4324 RelatedDecls.push_back(ReadDeclID(F, Record, I));
4325 }
4326 break;
4327
4329 if (F.LocalNumObjCCategoriesInMap != 0)
4330 return llvm::createStringError(
4331 std::errc::illegal_byte_sequence,
4332 "duplicate OBJC_CATEGORIES_MAP record in AST file");
4333
4335 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
4336 break;
4337
4338 case OBJC_CATEGORIES:
4339 F.ObjCCategories.swap(Record);
4340 break;
4341
4343 // Later tables overwrite earlier ones.
4344 // FIXME: Modules will have trouble with this.
4345 CUDASpecialDeclRefs.clear();
4346 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4347 CUDASpecialDeclRefs.push_back(ReadDeclID(F, Record, I));
4348 break;
4349
4351 F.HeaderFileInfoTableData = Blob.data();
4353 if (Record[0]) {
4354 F.HeaderFileInfoTable = HeaderFileInfoLookupTable::Create(
4355 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
4356 (const unsigned char *)F.HeaderFileInfoTableData,
4357 HeaderFileInfoTrait(*this, F));
4358
4359 PP.getHeaderSearchInfo().SetExternalSource(this);
4360 if (!PP.getHeaderSearchInfo().getExternalLookup())
4361 PP.getHeaderSearchInfo().SetExternalLookup(this);
4362 }
4363 break;
4364
4365 case FP_PRAGMA_OPTIONS:
4366 // Later tables overwrite earlier ones.
4367 FPPragmaOptions.swap(Record);
4368 break;
4369
4371 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4372 DeclsWithEffectsToVerify.push_back(ReadDeclID(F, Record, I));
4373 break;
4374
4375 case OPENCL_EXTENSIONS:
4376 for (unsigned I = 0, E = Record.size(); I != E; ) {
4377 auto Name = ReadString(Record, I);
4378 auto &OptInfo = OpenCLExtensions.OptMap[Name];
4379 OptInfo.Supported = Record[I++] != 0;
4380 OptInfo.Enabled = Record[I++] != 0;
4381 OptInfo.WithPragma = Record[I++] != 0;
4382 OptInfo.Avail = Record[I++];
4383 OptInfo.Core = Record[I++];
4384 OptInfo.Opt = Record[I++];
4385 }
4386 break;
4387
4389 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4390 TentativeDefinitions.push_back(ReadDeclID(F, Record, I));
4391 break;
4392
4393 case KNOWN_NAMESPACES:
4394 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4395 KnownNamespaces.push_back(ReadDeclID(F, Record, I));
4396 break;
4397
4398 case UNDEFINED_BUT_USED:
4399 if (Record.size() % 2 != 0)
4400 return llvm::createStringError(std::errc::illegal_byte_sequence,
4401 "invalid undefined-but-used record");
4402 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
4403 UndefinedButUsed.push_back(
4404 {ReadDeclID(F, Record, I),
4405 ReadSourceLocation(F, Record, I).getRawEncoding()});
4406 }
4407 break;
4408
4410 for (unsigned I = 0, N = Record.size(); I != N;) {
4411 DelayedDeleteExprs.push_back(ReadDeclID(F, Record, I).getRawValue());
4412 const uint64_t Count = Record[I++];
4413 DelayedDeleteExprs.push_back(Count);
4414 for (uint64_t C = 0; C < Count; ++C) {
4415 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
4416 bool IsArrayForm = Record[I++] == 1;
4417 DelayedDeleteExprs.push_back(IsArrayForm);
4418 }
4419 }
4420 break;
4421
4422 case VTABLES_TO_EMIT:
4423 if (F.Kind == MK_MainFile ||
4424 getContext().getLangOpts().BuildingPCHWithObjectFile)
4425 for (unsigned I = 0, N = Record.size(); I != N;)
4426 VTablesToEmit.push_back(ReadDeclID(F, Record, I));
4427 break;
4428
4429 case IMPORTED_MODULES:
4430 if (!F.isModule()) {
4431 // If we aren't loading a module (which has its own exports), make
4432 // all of the imported modules visible.
4433 // FIXME: Deal with macros-only imports.
4434 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
4435 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
4436 SourceLocation Loc = ReadSourceLocation(F, Record, I);
4437 if (GlobalID) {
4438 PendingImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
4439 if (DeserializationListener)
4440 DeserializationListener->ModuleImportRead(GlobalID, Loc);
4441 }
4442 }
4443 }
4444 break;
4445
4446 case MACRO_OFFSET: {
4447 if (F.LocalNumMacros != 0)
4448 return llvm::createStringError(
4449 std::errc::illegal_byte_sequence,
4450 "duplicate MACRO_OFFSET record in AST file");
4451 F.MacroOffsets = (const uint32_t *)Blob.data();
4452 F.LocalNumMacros = Record[0];
4454 F.BaseMacroID = getTotalNumMacros();
4455
4456 if (F.LocalNumMacros > 0)
4457 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
4458 break;
4459 }
4460
4462 LateParsedTemplates.emplace_back(
4463 std::piecewise_construct, std::forward_as_tuple(&F),
4464 std::forward_as_tuple(Record.begin(), Record.end()));
4465 break;
4466
4468 if (Record.size() != 1)
4469 return llvm::createStringError(std::errc::illegal_byte_sequence,
4470 "invalid pragma optimize record");
4471 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
4472 break;
4473
4475 if (Record.size() != 1)
4476 return llvm::createStringError(std::errc::illegal_byte_sequence,
4477 "invalid pragma ms_struct record");
4478 PragmaMSStructState = Record[0];
4479 break;
4480
4482 if (Record.size() != 2)
4483 return llvm::createStringError(
4484 std::errc::illegal_byte_sequence,
4485 "invalid pragma pointers to members record");
4486 PragmaMSPointersToMembersState = Record[0];
4487 PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]);
4488 break;
4489
4491 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4492 UnusedLocalTypedefNameCandidates.push_back(ReadDeclID(F, Record, I));
4493 break;
4494
4496 if (Record.size() != 1)
4497 return llvm::createStringError(std::errc::illegal_byte_sequence,
4498 "invalid cuda pragma options record");
4499 ForceHostDeviceDepth = Record[0];
4500 break;
4501
4503 if (Record.size() < 3)
4504 return llvm::createStringError(std::errc::illegal_byte_sequence,
4505 "invalid pragma pack record");
4506 PragmaAlignPackCurrentValue = ReadAlignPackInfo(Record[0]);
4507 PragmaAlignPackCurrentLocation = ReadSourceLocation(F, Record[1]);
4508 unsigned NumStackEntries = Record[2];
4509 unsigned Idx = 3;
4510 // Reset the stack when importing a new module.
4511 PragmaAlignPackStack.clear();
4512 for (unsigned I = 0; I < NumStackEntries; ++I) {
4513 PragmaAlignPackStackEntry Entry;
4514 Entry.Value = ReadAlignPackInfo(Record[Idx++]);
4515 Entry.Location = ReadSourceLocation(F, Record[Idx++]);
4516 Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]);
4517 PragmaAlignPackStrings.push_back(ReadString(Record, Idx));
4518 Entry.SlotLabel = PragmaAlignPackStrings.back();
4519 PragmaAlignPackStack.push_back(Entry);
4520 }
4521 break;
4522 }
4523
4525 if (Record.size() < 3)
4526 return llvm::createStringError(std::errc::illegal_byte_sequence,
4527 "invalid pragma float control record");
4528 FpPragmaCurrentValue = FPOptionsOverride::getFromOpaqueInt(Record[0]);
4529 FpPragmaCurrentLocation = ReadSourceLocation(F, Record[1]);
4530 unsigned NumStackEntries = Record[2];
4531 unsigned Idx = 3;
4532 // Reset the stack when importing a new module.
4533 FpPragmaStack.clear();
4534 for (unsigned I = 0; I < NumStackEntries; ++I) {
4535 FpPragmaStackEntry Entry;
4536 Entry.Value = FPOptionsOverride::getFromOpaqueInt(Record[Idx++]);
4537 Entry.Location = ReadSourceLocation(F, Record[Idx++]);
4538 Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]);
4539 FpPragmaStrings.push_back(ReadString(Record, Idx));
4540 Entry.SlotLabel = FpPragmaStrings.back();
4541 FpPragmaStack.push_back(Entry);
4542 }
4543 break;
4544 }
4545
4547 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4548 DeclsToCheckForDeferredDiags.insert(ReadDeclID(F, Record, I));
4549 break;
4550
4552 unsigned NumRecords = Record.front();
4553 // Last record which is used to keep number of valid records.
4554 if (Record.size() - 1 != NumRecords)
4555 return llvm::createStringError(std::errc::illegal_byte_sequence,
4556 "invalid rvv intrinsic pragma record");
4557
4558 if (RISCVVecIntrinsicPragma.empty())
4559 RISCVVecIntrinsicPragma.append(NumRecords, 0);
4560 // There might be multiple precompiled modules imported, we need to union
4561 // them all.
4562 for (unsigned i = 0; i < NumRecords; ++i)
4563 RISCVVecIntrinsicPragma[i] |= Record[i + 1];
4564 break;
4565 }
4566 }
4567 }
4568}
4569
4570void ASTReader::ReadModuleOffsetMap(ModuleFile &F) const {
4571 assert(!F.ModuleOffsetMap.empty() && "no module offset map to read");
4572
4573 // Additional remapping information.
4574 const unsigned char *Data = (const unsigned char*)F.ModuleOffsetMap.data();
4575 const unsigned char *DataEnd = Data + F.ModuleOffsetMap.size();
4576 F.ModuleOffsetMap = StringRef();
4577
4579 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
4580 RemapBuilder SelectorRemap(F.SelectorRemap);
4581
4582 auto &ImportedModuleVector = F.TransitiveImports;
4583 assert(ImportedModuleVector.empty());
4584
4585 while (Data < DataEnd) {
4586 // FIXME: Looking up dependency modules by filename is horrible. Let's
4587 // start fixing this with prebuilt, explicit and implicit modules and see
4588 // how it goes...
4589 using namespace llvm::support;
4590 ModuleKind Kind = static_cast<ModuleKind>(
4591 endian::readNext<uint8_t, llvm::endianness::little>(Data));
4592 uint16_t Len = endian::readNext<uint16_t, llvm::endianness::little>(Data);
4593 StringRef Name = StringRef((const char*)Data, Len);
4594 Data += Len;
4595 ModuleFile *OM =
4598 ? ModuleMgr.lookupByModuleName(Name)
4599 : ModuleMgr.lookupByFileName(ModuleFileName::makeExplicit(Name)));
4600 if (!OM) {
4601 std::string Msg = "refers to unknown module, cannot find ";
4602 Msg.append(std::string(Name));
4603 Error(Msg);
4604 return;
4605 }
4606
4607 ImportedModuleVector.push_back(OM);
4608
4609 uint32_t SubmoduleIDOffset =
4610 endian::readNext<uint32_t, llvm::endianness::little>(Data);
4611 uint32_t SelectorIDOffset =
4612 endian::readNext<uint32_t, llvm::endianness::little>(Data);
4613
4614 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
4615 RemapBuilder &Remap) {
4616 constexpr uint32_t None = std::numeric_limits<uint32_t>::max();
4617 if (Offset != None)
4618 Remap.insert(std::make_pair(Offset,
4619 static_cast<int>(BaseOffset - Offset)));
4620 };
4621
4622 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
4623 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
4624 }
4625}
4626
4628ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
4629 const ModuleFile *ImportedBy,
4630 unsigned ClientLoadCapabilities) {
4631 unsigned Idx = 0;
4632 F.ModuleMapPath = ReadPath(F, Record, Idx);
4633
4634 // Try to resolve ModuleName in the current header search context and
4635 // verify that it is found in the same module map file as we saved. If the
4636 // top-level AST file is a main file, skip this check because there is no
4637 // usable header search context.
4638 assert(!F.ModuleName.empty() &&
4639 "MODULE_NAME should come before MODULE_MAP_FILE");
4640 auto [MaybeM, IgnoreError] =
4641 getModuleForRelocationChecks(F, /*DirectoryCheck=*/false);
4642 if (MaybeM.has_value()) {
4643 // An implicitly-loaded module file should have its module listed in some
4644 // module map file that we've already loaded.
4645 Module *M = MaybeM.value();
4646 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
4647 OptionalFileEntryRef ModMap =
4648 M ? Map.getModuleMapFileForUniquing(M) : std::nullopt;
4649 if (!IgnoreError && !ModMap) {
4650 if (M && M->Directory)
4651 Diag(diag::remark_module_relocated)
4652 << F.ModuleName << F.BaseDirectory << M->Directory->getName();
4653
4654 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities)) {
4655 if (auto ASTFileName = M ? M->getASTFileName() : nullptr) {
4656 // This module was defined by an imported (explicit) module.
4657 Diag(diag::err_module_file_conflict)
4658 << F.ModuleName << F.FileName << *ASTFileName;
4659 // TODO: Add a note with the module map paths if they differ.
4660 } else {
4661 // This module was built with a different module map.
4662 Diag(diag::err_imported_module_not_found)
4663 << F.ModuleName << F.FileName
4664 << (ImportedBy ? ImportedBy->FileName.str() : "")
4665 << F.ModuleMapPath << !ImportedBy;
4666 // In case it was imported by a PCH, there's a chance the user is
4667 // just missing to include the search path to the directory containing
4668 // the modulemap.
4669 if (ImportedBy && ImportedBy->Kind == MK_PCH)
4670 Diag(diag::note_imported_by_pch_module_not_found)
4671 << llvm::sys::path::parent_path(F.ModuleMapPath);
4672 }
4673 }
4674 return OutOfDate;
4675 }
4676
4677 assert(M && M->Name == F.ModuleName && "found module with different name");
4678
4679 // Check the primary module map file.
4680 auto StoredModMap = FileMgr.getOptionalFileRef(F.ModuleMapPath);
4681 if (!StoredModMap || *StoredModMap != ModMap) {
4682 assert(ModMap && "found module is missing module map file");
4683 assert((ImportedBy || F.Kind == MK_ImplicitModule) &&
4684 "top-level import should be verified");
4685 bool NotImported = F.Kind == MK_ImplicitModule && !ImportedBy;
4686 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4687 Diag(diag::err_imported_module_modmap_changed)
4688 << F.ModuleName << (NotImported ? F.FileName : ImportedBy->FileName)
4689 << ModMap->getName() << F.ModuleMapPath << NotImported;
4690 return OutOfDate;
4691 }
4692
4693 ModuleMap::AdditionalModMapsSet AdditionalStoredMaps;
4694 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
4695 // FIXME: we should use input files rather than storing names.
4696 std::string Filename = ReadPath(F, Record, Idx);
4697 auto SF = FileMgr.getOptionalFileRef(Filename, false, false);
4698 if (!SF) {
4699 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4700 Error("could not find file '" + Filename +"' referenced by AST file");
4701 return OutOfDate;
4702 }
4703 AdditionalStoredMaps.insert(*SF);
4704 }
4705
4706 // Check any additional module map files (e.g. module.private.modulemap)
4707 // that are not in the pcm.
4708 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
4709 for (FileEntryRef ModMap : *AdditionalModuleMaps) {
4710 // Remove files that match
4711 // Note: SmallPtrSet::erase is really remove
4712 if (!AdditionalStoredMaps.erase(ModMap)) {
4713 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4714 Diag(diag::err_module_different_modmap)
4715 << F.ModuleName << /*new*/0 << ModMap.getName();
4716 return OutOfDate;
4717 }
4718 }
4719 }
4720
4721 // Check any additional module map files that are in the pcm, but not
4722 // found in header search. Cases that match are already removed.
4723 for (FileEntryRef ModMap : AdditionalStoredMaps) {
4724 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4725 Diag(diag::err_module_different_modmap)
4726 << F.ModuleName << /*not new*/1 << ModMap.getName();
4727 return OutOfDate;
4728 }
4729 }
4730
4731 if (Listener)
4732 Listener->ReadModuleMapFile(F.ModuleMapPath);
4733 return Success;
4734}
4735
4736/// Move the given method to the back of the global list of methods.
4738 // Find the entry for this selector in the method pool.
4739 SemaObjC::GlobalMethodPool::iterator Known =
4740 S.ObjC().MethodPool.find(Method->getSelector());
4741 if (Known == S.ObjC().MethodPool.end())
4742 return;
4743
4744 // Retrieve the appropriate method list.
4745 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
4746 : Known->second.second;
4747 bool Found = false;
4748 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
4749 if (!Found) {
4750 if (List->getMethod() == Method) {
4751 Found = true;
4752 } else {
4753 // Keep searching.
4754 continue;
4755 }
4756 }
4757
4758 if (List->getNext())
4759 List->setMethod(List->getNext()->getMethod());
4760 else
4761 List->setMethod(Method);
4762 }
4763}
4764
4765void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
4766 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
4767 for (Decl *D : Names) {
4768 bool wasHidden = !D->isUnconditionallyVisible();
4770
4771 if (wasHidden && SemaObj) {
4772 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
4774 }
4775 }
4776 }
4777}
4778
4780 Module::NameVisibilityKind NameVisibility,
4781 SourceLocation ImportLoc) {
4784 Stack.push_back(Mod);
4785 while (!Stack.empty()) {
4786 Mod = Stack.pop_back_val();
4787
4788 if (NameVisibility <= Mod->NameVisibility) {
4789 // This module already has this level of visibility (or greater), so
4790 // there is nothing more to do.
4791 continue;
4792 }
4793
4794 if (Mod->isUnimportable()) {
4795 // Modules that aren't importable cannot be made visible.
4796 continue;
4797 }
4798
4799 // Update the module's name visibility.
4800 Mod->NameVisibility = NameVisibility;
4801
4802 // If we've already deserialized any names from this module,
4803 // mark them as visible.
4804 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
4805 if (Hidden != HiddenNamesMap.end()) {
4806 auto HiddenNames = std::move(*Hidden);
4807 HiddenNamesMap.erase(Hidden);
4808 makeNamesVisible(HiddenNames.second, HiddenNames.first);
4809 assert(!HiddenNamesMap.contains(Mod) &&
4810 "making names visible added hidden names");
4811 }
4812
4813 // Push any exported modules onto the stack to be marked as visible.
4815 Mod->getExportedModules(Exports);
4817 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
4818 Module *Exported = *I;
4819 if (Visited.insert(Exported).second)
4820 Stack.push_back(Exported);
4821 }
4822 }
4823}
4824
4825/// We've merged the definition \p MergedDef into the existing definition
4826/// \p Def. Ensure that \p Def is made visible whenever \p MergedDef is made
4827/// visible.
4829 NamedDecl *MergedDef) {
4830 if (!Def->isUnconditionallyVisible()) {
4831 // If MergedDef is visible or becomes visible, make the definition visible.
4832 if (MergedDef->isUnconditionallyVisible())
4834 else {
4835 getContext().mergeDefinitionIntoModule(
4836 Def, MergedDef->getImportedOwningModule(),
4837 /*NotifyListeners*/ false);
4838 PendingMergedDefinitionsToDeduplicate.insert(Def);
4839 }
4840 }
4841}
4842
4844 if (GlobalIndex)
4845 return false;
4846
4847 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
4848 !PP.getLangOpts().Modules)
4849 return true;
4850
4851 // Try to load the global index.
4852 TriedLoadingGlobalIndex = true;
4853 StringRef SpecificModuleCachePath =
4854 getPreprocessor().getHeaderSearchInfo().getSpecificModuleCachePath();
4855 std::pair<GlobalModuleIndex *, llvm::Error> Result =
4856 GlobalModuleIndex::readIndex(SpecificModuleCachePath);
4857 if (llvm::Error Err = std::move(Result.second)) {
4858 assert(!Result.first);
4859 consumeError(std::move(Err)); // FIXME this drops errors on the floor.
4860 return true;
4861 }
4862
4863 GlobalIndex.reset(Result.first);
4864 ModuleMgr.setGlobalIndex(GlobalIndex.get());
4865 return false;
4866}
4867
4869 return PP.getLangOpts().Modules && UseGlobalIndex &&
4870 !hasGlobalIndex() && TriedLoadingGlobalIndex;
4871}
4872
4873/// Given a cursor at the start of an AST file, scan ahead and drop the
4874/// cursor into the start of the given block ID, returning false on success and
4875/// true on failure.
4876static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
4877 while (true) {
4878 Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
4879 if (!MaybeEntry) {
4880 // FIXME this drops errors on the floor.
4881 consumeError(MaybeEntry.takeError());
4882 return true;
4883 }
4884 llvm::BitstreamEntry Entry = MaybeEntry.get();
4885
4886 switch (Entry.Kind) {
4887 case llvm::BitstreamEntry::Error:
4888 case llvm::BitstreamEntry::EndBlock:
4889 return true;
4890
4891 case llvm::BitstreamEntry::Record:
4892 // Ignore top-level records.
4893 if (Expected<unsigned> Skipped = Cursor.skipRecord(Entry.ID))
4894 break;
4895 else {
4896 // FIXME this drops errors on the floor.
4897 consumeError(Skipped.takeError());
4898 return true;
4899 }
4900
4901 case llvm::BitstreamEntry::SubBlock:
4902 if (Entry.ID == BlockID) {
4903 if (llvm::Error Err = Cursor.EnterSubBlock(BlockID)) {
4904 // FIXME this drops the error on the floor.
4905 consumeError(std::move(Err));
4906 return true;
4907 }
4908 // Found it!
4909 return false;
4910 }
4911
4912 if (llvm::Error Err = Cursor.SkipBlock()) {
4913 // FIXME this drops the error on the floor.
4914 consumeError(std::move(Err));
4915 return true;
4916 }
4917 }
4918 }
4919}
4920
4923 SourceLocation ImportLoc,
4924 unsigned ClientLoadCapabilities,
4925 ModuleFile **NewLoadedModuleFile) {
4926 llvm::TimeTraceScope scope("ReadAST", FileName);
4927
4928 llvm::SaveAndRestore SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
4930 CurrentDeserializingModuleKind, Type);
4931
4932 // Defer any pending actions until we get to the end of reading the AST file.
4933 Deserializing AnASTFile(this);
4934
4935 // Bump the generation number.
4936 unsigned PreviousGeneration = 0;
4937 if (ContextObj)
4938 PreviousGeneration = incrementGeneration(*ContextObj);
4939
4940 unsigned NumModules = ModuleMgr.size();
4942 if (ASTReadResult ReadResult =
4943 ReadASTCore(FileName, Type, ImportLoc,
4944 /*ImportedBy=*/nullptr, Loaded, 0, 0, ASTFileSignature(),
4945 ClientLoadCapabilities)) {
4946 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules);
4947
4948 // If we find that any modules are unusable, the global index is going
4949 // to be out-of-date. Just remove it.
4950 GlobalIndex.reset();
4951 ModuleMgr.setGlobalIndex(nullptr);
4952 return ReadResult;
4953 }
4954
4955 if (NewLoadedModuleFile && !Loaded.empty())
4956 *NewLoadedModuleFile = Loaded.back().Mod;
4957
4958 // Here comes stuff that we only do once the entire chain is loaded. Do *not*
4959 // remove modules from this point. Various fields are updated during reading
4960 // the AST block and removing the modules would result in dangling pointers.
4961 // They are generally only incidentally dereferenced, ie. a binary search
4962 // runs over `GlobalSLocEntryMap`, which could cause an invalid module to
4963 // be dereferenced but it wouldn't actually be used.
4964
4965 // Load the AST blocks of all of the modules that we loaded. We can still
4966 // hit errors parsing the ASTs at this point.
4967 for (ImportedModule &M : Loaded) {
4968 ModuleFile &F = *M.Mod;
4969 llvm::TimeTraceScope Scope2("Read Loaded AST", F.ModuleName);
4970
4971 // Read the AST block.
4972 if (llvm::Error Err = ReadASTBlock(F, ClientLoadCapabilities)) {
4973 Error(std::move(Err));
4974 return Failure;
4975 }
4976
4977 // The AST block should always have a definition for the main module.
4978 if (F.isModule() && !F.DidReadTopLevelSubmodule) {
4979 Error(diag::err_module_file_missing_top_level_submodule, F.FileName);
4980 return Failure;
4981 }
4982
4983 // Read the extension blocks.
4985 if (llvm::Error Err = ReadExtensionBlock(F)) {
4986 Error(std::move(Err));
4987 return Failure;
4988 }
4989 }
4990
4991 // Once read, set the ModuleFile bit base offset and update the size in
4992 // bits of all files we've seen.
4993 F.GlobalBitOffset = TotalModulesSizeInBits;
4994 TotalModulesSizeInBits += F.SizeInBits;
4995 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
4996 }
4997
4998 // Preload source locations and interesting indentifiers.
4999 for (ImportedModule &M : Loaded) {
5000 ModuleFile &F = *M.Mod;
5001
5002 // Map the original source file ID into the ID space of the current
5003 // compilation.
5006
5007 for (auto Offset : F.PreloadIdentifierOffsets) {
5008 const unsigned char *Data = F.IdentifierTableData + Offset;
5009
5010 ASTIdentifierLookupTrait Trait(*this, F);
5011 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
5012 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
5013
5014 IdentifierInfo *II;
5015 if (!PP.getLangOpts().CPlusPlus) {
5016 // Identifiers present in both the module file and the importing
5017 // instance are marked out-of-date so that they can be deserialized
5018 // on next use via ASTReader::updateOutOfDateIdentifier().
5019 // Identifiers present in the module file but not in the importing
5020 // instance are ignored for now, preventing growth of the identifier
5021 // table. They will be deserialized on first use via ASTReader::get().
5022 auto It = PP.getIdentifierTable().find(Key);
5023 if (It == PP.getIdentifierTable().end())
5024 continue;
5025 II = It->second;
5026 } else {
5027 // With C++ modules, not many identifiers are considered interesting.
5028 // All identifiers in the module file can be placed into the identifier
5029 // table of the importing instance and marked as out-of-date. This makes
5030 // ASTReader::get() a no-op, and deserialization will take place on
5031 // first/next use via ASTReader::updateOutOfDateIdentifier().
5032 II = &PP.getIdentifierTable().getOwn(Key);
5033 }
5034
5035 II->setOutOfDate(true);
5036
5037 // Mark this identifier as being from an AST file so that we can track
5038 // whether we need to serialize it.
5039 markIdentifierFromAST(*this, *II, /*IsModule=*/true);
5040
5041 // Associate the ID with the identifier so that the writer can reuse it.
5042 auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
5043 SetIdentifierInfo(ID, II);
5044 }
5045 }
5046
5047 // Builtins and library builtins have already been initialized. Mark all
5048 // identifiers as out-of-date, so that they are deserialized on first use.
5049 if (Type == MK_PCH || Type == MK_Preamble || Type == MK_MainFile)
5050 for (auto &Id : PP.getIdentifierTable())
5051 Id.second->setOutOfDate(true);
5052
5053 // Mark selectors as out of date.
5054 for (const auto &Sel : SelectorGeneration)
5055 SelectorOutOfDate[Sel.first] = true;
5056
5057 // Setup the import locations and notify the module manager that we've
5058 // committed to these module files.
5059 for (ImportedModule &M : Loaded) {
5060 ModuleFile &F = *M.Mod;
5061
5062 ModuleMgr.moduleFileAccepted(&F);
5063
5064 // Set the import location.
5065 F.DirectImportLoc = ImportLoc;
5066 // FIXME: We assume that locations from PCH / preamble do not need
5067 // any translation.
5068 if (!M.ImportedBy)
5069 F.ImportLoc = M.ImportLoc;
5070 else
5071 F.ImportLoc = TranslateSourceLocation(*M.ImportedBy, M.ImportLoc);
5072 }
5073
5074 // Resolve any unresolved module exports.
5075 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
5076 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
5078 Module *ResolvedMod = getSubmodule(GlobalID);
5079
5080 switch (Unresolved.Kind) {
5081 case UnresolvedModuleRef::Conflict:
5082 if (ResolvedMod) {
5083 Module::Conflict Conflict;
5084 Conflict.Other = ResolvedMod;
5085 Conflict.Message = Unresolved.String.str();
5086 Unresolved.Mod->Conflicts.push_back(Conflict);
5087 }
5088 continue;
5089
5090 case UnresolvedModuleRef::Import:
5091 if (ResolvedMod)
5092 Unresolved.Mod->Imports.insert(ResolvedMod);
5093 continue;
5094
5095 case UnresolvedModuleRef::Affecting:
5096 if (ResolvedMod)
5097 Unresolved.Mod->AffectingClangModules.insert(ResolvedMod);
5098 continue;
5099
5100 case UnresolvedModuleRef::Export:
5101 if (ResolvedMod || Unresolved.IsWildcard)
5102 Unresolved.Mod->Exports.push_back(
5103 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
5104 continue;
5105 }
5106 }
5107 UnresolvedModuleRefs.clear();
5108
5109 // FIXME: How do we load the 'use'd modules? They may not be submodules.
5110 // Might be unnecessary as use declarations are only used to build the
5111 // module itself.
5112
5113 if (ContextObj)
5115
5116 if (SemaObj)
5117 UpdateSema();
5118
5119 if (DeserializationListener)
5120 DeserializationListener->ReaderInitialized(this);
5121
5122 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
5123 if (PrimaryModule.OriginalSourceFileID.isValid()) {
5124 // If this AST file is a precompiled preamble, then set the
5125 // preamble file ID of the source manager to the file source file
5126 // from which the preamble was built.
5127 if (Type == MK_Preamble) {
5128 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
5129 } else if (Type == MK_MainFile) {
5130 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
5131 }
5132 }
5133
5134 // For any Objective-C class definitions we have already loaded, make sure
5135 // that we load any additional categories.
5136 if (ContextObj) {
5137 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
5138 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
5139 ObjCClassesLoaded[I], PreviousGeneration);
5140 }
5141 }
5142
5143 const HeaderSearchOptions &HSOpts =
5144 PP.getHeaderSearchInfo().getHeaderSearchOpts();
5146 // Now we are certain that the module and all modules it depends on are
5147 // up-to-date. For implicitly-built module files, ensure the corresponding
5148 // timestamp files are up-to-date in this build session.
5149 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
5150 ImportedModule &M = Loaded[I];
5151 if (M.Mod->Kind == MK_ImplicitModule &&
5153 getModuleManager().getModuleCache().updateModuleTimestamp(
5154 M.Mod->FileName);
5155 }
5156 }
5157
5158 return Success;
5159}
5160
5161static ASTFileSignature readASTFileSignature(StringRef PCH);
5162
5163/// Whether \p Stream doesn't start with the AST file magic number 'CPCH'.
5164static llvm::Error doesntStartWithASTFileMagic(BitstreamCursor &Stream) {
5165 // FIXME checking magic headers is done in other places such as
5166 // SerializedDiagnosticReader and GlobalModuleIndex, but error handling isn't
5167 // always done the same. Unify it all with a helper.
5168 if (!Stream.canSkipToPos(4))
5169 return llvm::createStringError(
5170 std::errc::illegal_byte_sequence,
5171 "file too small to contain precompiled file magic");
5172 for (unsigned C : {'C', 'P', 'C', 'H'})
5173 if (Expected<llvm::SimpleBitstreamCursor::word_t> Res = Stream.Read(8)) {
5174 if (Res.get() != C)
5175 return llvm::createStringError(
5176 std::errc::illegal_byte_sequence,
5177 "file doesn't start with precompiled file magic");
5178 } else
5179 return Res.takeError();
5180 return llvm::Error::success();
5181}
5182
5184 switch (Kind) {
5185 case MK_PCH:
5186 return 0; // PCH
5187 case MK_ImplicitModule:
5188 case MK_ExplicitModule:
5189 case MK_PrebuiltModule:
5190 return 1; // module
5191 case MK_MainFile:
5192 case MK_Preamble:
5193 return 2; // main source file
5194 }
5195 llvm_unreachable("unknown module kind");
5196}
5197
5200 ModuleFile *ImportedBy, SmallVectorImpl<ImportedModule> &Loaded,
5201 off_t ExpectedSize, time_t ExpectedModTime,
5202 ASTFileSignature ExpectedSignature, unsigned ClientLoadCapabilities) {
5203 ModuleFile *M;
5204 std::string ErrorStr;
5206 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
5207 getGeneration(), ExpectedSize, ExpectedModTime,
5208 ExpectedSignature, readASTFileSignature,
5209 M, ErrorStr);
5210
5211 switch (AddResult) {
5213 Diag(diag::remark_module_import)
5214 << M->ModuleName << M->FileName << (ImportedBy ? true : false)
5215 << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());
5216 return Success;
5217
5219 // Load module file below.
5220 break;
5221
5223 // The module file was missing; if the client can handle that, return
5224 // it.
5225 if (ClientLoadCapabilities & ARR_Missing)
5226 return Missing;
5227
5228 // Otherwise, return an error.
5229 Diag(diag::err_ast_file_not_found)
5230 << moduleKindForDiagnostic(Type) << FileName << !ErrorStr.empty()
5231 << ErrorStr;
5232 return Failure;
5233
5235 // We couldn't load the module file because it is out-of-date. If the
5236 // client can handle out-of-date, return it.
5237 if (ClientLoadCapabilities & ARR_OutOfDate)
5238 return OutOfDate;
5239
5240 // Otherwise, return an error.
5241 Diag(diag::err_ast_file_out_of_date)
5242 << moduleKindForDiagnostic(Type) << FileName << !ErrorStr.empty()
5243 << ErrorStr;
5244 return Failure;
5245 }
5246
5247 assert(M && "Missing module file");
5248
5249 bool ShouldFinalizePCM = false;
5250 llvm::scope_exit FinalizeOrDropPCM([&]() {
5251 auto &MC = getModuleManager().getModuleCache().getInMemoryModuleCache();
5252 if (ShouldFinalizePCM)
5253 MC.finalizePCM(FileName);
5254 else
5255 MC.tryToDropPCM(FileName);
5256 });
5257 ModuleFile &F = *M;
5258 BitstreamCursor &Stream = F.Stream;
5259 Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(*F.Buffer));
5260 F.SizeInBits = F.Buffer->getBufferSize() * 8;
5261
5262 // Sniff for the signature.
5263 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5264 Diag(diag::err_ast_file_invalid)
5265 << moduleKindForDiagnostic(Type) << FileName << std::move(Err);
5266 return Failure;
5267 }
5268
5269 // This is used for compatibility with older PCH formats.
5270 bool HaveReadControlBlock = false;
5271 while (true) {
5272 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5273 if (!MaybeEntry) {
5274 Error(MaybeEntry.takeError());
5275 return Failure;
5276 }
5277 llvm::BitstreamEntry Entry = MaybeEntry.get();
5278
5279 switch (Entry.Kind) {
5280 case llvm::BitstreamEntry::Error:
5281 case llvm::BitstreamEntry::Record:
5282 case llvm::BitstreamEntry::EndBlock:
5283 Error("invalid record at top-level of AST file");
5284 return Failure;
5285
5286 case llvm::BitstreamEntry::SubBlock:
5287 break;
5288 }
5289
5290 switch (Entry.ID) {
5291 case CONTROL_BLOCK_ID:
5292 HaveReadControlBlock = true;
5293 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
5294 case Success:
5295 // Check that we didn't try to load a non-module AST file as a module.
5296 //
5297 // FIXME: Should we also perform the converse check? Loading a module as
5298 // a PCH file sort of works, but it's a bit wonky.
5300 Type == MK_PrebuiltModule) &&
5301 F.ModuleName.empty()) {
5303 if (Result != OutOfDate ||
5304 (ClientLoadCapabilities & ARR_OutOfDate) == 0)
5305 Diag(diag::err_module_file_not_module) << FileName;
5306 return Result;
5307 }
5308 break;
5309
5310 case Failure: return Failure;
5311 case Missing: return Missing;
5312 case OutOfDate: return OutOfDate;
5313 case VersionMismatch: return VersionMismatch;
5315 case HadErrors: return HadErrors;
5316 }
5317 break;
5318
5319 case AST_BLOCK_ID:
5320 if (!HaveReadControlBlock) {
5321 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
5322 Diag(diag::err_ast_file_version_too_old)
5324 return VersionMismatch;
5325 }
5326
5327 // Record that we've loaded this module.
5328 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
5329 ShouldFinalizePCM = true;
5330 return Success;
5331
5332 default:
5333 if (llvm::Error Err = Stream.SkipBlock()) {
5334 Error(std::move(Err));
5335 return Failure;
5336 }
5337 break;
5338 }
5339 }
5340
5341 llvm_unreachable("unexpected break; expected return");
5342}
5343
5345ASTReader::readUnhashedControlBlock(ModuleFile &F, bool WasImportedBy,
5346 unsigned ClientLoadCapabilities) {
5347 const HeaderSearchOptions &HSOpts =
5348 PP.getHeaderSearchInfo().getHeaderSearchOpts();
5349 bool AllowCompatibleConfigurationMismatch =
5351 bool DisableValidation = shouldDisableValidationForFile(F);
5352
5353 ASTReadResult Result = readUnhashedControlBlockImpl(
5354 &F, F.Data, F.FileName, ClientLoadCapabilities,
5355 AllowCompatibleConfigurationMismatch, Listener.get(),
5356 WasImportedBy ? false : HSOpts.ModulesValidateDiagnosticOptions);
5357
5358 // If F was directly imported by another module, it's implicitly validated by
5359 // the importing module.
5360 if (DisableValidation || WasImportedBy ||
5361 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
5362 return Success;
5363
5364 if (Result == Failure) {
5365 Error("malformed block record in AST file");
5366 return Failure;
5367 }
5368
5369 if (Result == OutOfDate && F.Kind == MK_ImplicitModule) {
5370 // If this module has already been finalized in the ModuleCache, we're stuck
5371 // with it; we can only load a single version of each module.
5372 //
5373 // This can happen when a module is imported in two contexts: in one, as a
5374 // user module; in another, as a system module (due to an import from
5375 // another module marked with the [system] flag). It usually indicates a
5376 // bug in the module map: this module should also be marked with [system].
5377 //
5378 // If -Wno-system-headers (the default), and the first import is as a
5379 // system module, then validation will fail during the as-user import,
5380 // since -Werror flags won't have been validated. However, it's reasonable
5381 // to treat this consistently as a system module.
5382 //
5383 // If -Wsystem-headers, the PCM on disk was built with
5384 // -Wno-system-headers, and the first import is as a user module, then
5385 // validation will fail during the as-system import since the PCM on disk
5386 // doesn't guarantee that -Werror was respected. However, the -Werror
5387 // flags were checked during the initial as-user import.
5388 if (getModuleManager().getModuleCache().getInMemoryModuleCache().isPCMFinal(
5389 F.FileName)) {
5390 Diag(diag::warn_module_system_bit_conflict) << F.FileName;
5391 return Success;
5392 }
5393 }
5394
5395 return Result;
5396}
5397
5398ASTReader::ASTReadResult ASTReader::readUnhashedControlBlockImpl(
5399 ModuleFile *F, llvm::StringRef StreamData, StringRef Filename,
5400 unsigned ClientLoadCapabilities, bool AllowCompatibleConfigurationMismatch,
5401 ASTReaderListener *Listener, bool ValidateDiagnosticOptions) {
5402 // Initialize a stream.
5403 BitstreamCursor Stream(StreamData);
5404
5405 // Sniff for the signature.
5406 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5407 // FIXME this drops the error on the floor.
5408 consumeError(std::move(Err));
5409 return Failure;
5410 }
5411
5412 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
5414 return Failure;
5415
5416 // Read all of the records in the options block.
5417 RecordData Record;
5418 ASTReadResult Result = Success;
5419 while (true) {
5420 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5421 if (!MaybeEntry) {
5422 // FIXME this drops the error on the floor.
5423 consumeError(MaybeEntry.takeError());
5424 return Failure;
5425 }
5426 llvm::BitstreamEntry Entry = MaybeEntry.get();
5427
5428 switch (Entry.Kind) {
5429 case llvm::BitstreamEntry::Error:
5430 case llvm::BitstreamEntry::SubBlock:
5431 return Failure;
5432
5433 case llvm::BitstreamEntry::EndBlock:
5434 return Result;
5435
5436 case llvm::BitstreamEntry::Record:
5437 // The interesting case.
5438 break;
5439 }
5440
5441 // Read and process a record.
5442 Record.clear();
5443 StringRef Blob;
5444 Expected<unsigned> MaybeRecordType =
5445 Stream.readRecord(Entry.ID, Record, &Blob);
5446 if (!MaybeRecordType) {
5447 // FIXME this drops the error.
5448 return Failure;
5449 }
5450 switch ((UnhashedControlBlockRecordTypes)MaybeRecordType.get()) {
5451 case SIGNATURE:
5452 if (F) {
5453 F->Signature = ASTFileSignature::create(Blob.begin(), Blob.end());
5455 "Dummy AST file signature not backpatched in ASTWriter.");
5456 }
5457 break;
5458 case AST_BLOCK_HASH:
5459 if (F) {
5460 F->ASTBlockHash = ASTFileSignature::create(Blob.begin(), Blob.end());
5462 "Dummy AST block hash not backpatched in ASTWriter.");
5463 }
5464 break;
5465 case DIAGNOSTIC_OPTIONS: {
5466 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
5467 if (Listener && ValidateDiagnosticOptions &&
5468 !AllowCompatibleConfigurationMismatch &&
5469 ParseDiagnosticOptions(Record, Filename, Complain, *Listener))
5470 Result = OutOfDate; // Don't return early. Read the signature.
5471 break;
5472 }
5473 case HEADER_SEARCH_PATHS: {
5474 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
5475 if (Listener && !AllowCompatibleConfigurationMismatch &&
5476 ParseHeaderSearchPaths(Record, Complain, *Listener))
5477 Result = ConfigurationMismatch;
5478 break;
5479 }
5481 if (!F)
5482 break;
5483 if (F->PragmaDiagMappings.empty())
5484 F->PragmaDiagMappings.swap(Record);
5485 else
5486 F->PragmaDiagMappings.insert(F->PragmaDiagMappings.end(),
5487 Record.begin(), Record.end());
5488 break;
5490 if (F)
5491 F->SearchPathUsage = ReadBitVector(Record, Blob);
5492 break;
5493 case VFS_USAGE:
5494 if (F)
5495 F->VFSUsage = ReadBitVector(Record, Blob);
5496 break;
5497 }
5498 }
5499}
5500
5501/// Parse a record and blob containing module file extension metadata.
5504 StringRef Blob,
5505 ModuleFileExtensionMetadata &Metadata) {
5506 if (Record.size() < 4) return true;
5507
5508 Metadata.MajorVersion = Record[0];
5509 Metadata.MinorVersion = Record[1];
5510
5511 unsigned BlockNameLen = Record[2];
5512 unsigned UserInfoLen = Record[3];
5513
5514 if (BlockNameLen + UserInfoLen > Blob.size()) return true;
5515
5516 Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
5517 Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,
5518 Blob.data() + BlockNameLen + UserInfoLen);
5519 return false;
5520}
5521
5522llvm::Error ASTReader::ReadExtensionBlock(ModuleFile &F) {
5523 BitstreamCursor &Stream = F.Stream;
5524
5525 RecordData Record;
5526 while (true) {
5527 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5528 if (!MaybeEntry)
5529 return MaybeEntry.takeError();
5530 llvm::BitstreamEntry Entry = MaybeEntry.get();
5531
5532 switch (Entry.Kind) {
5533 case llvm::BitstreamEntry::SubBlock:
5534 if (llvm::Error Err = Stream.SkipBlock())
5535 return Err;
5536 continue;
5537 case llvm::BitstreamEntry::EndBlock:
5538 return llvm::Error::success();
5539 case llvm::BitstreamEntry::Error:
5540 return llvm::createStringError(std::errc::illegal_byte_sequence,
5541 "malformed block record in AST file");
5542 case llvm::BitstreamEntry::Record:
5543 break;
5544 }
5545
5546 Record.clear();
5547 StringRef Blob;
5548 Expected<unsigned> MaybeRecCode =
5549 Stream.readRecord(Entry.ID, Record, &Blob);
5550 if (!MaybeRecCode)
5551 return MaybeRecCode.takeError();
5552 switch (MaybeRecCode.get()) {
5553 case EXTENSION_METADATA: {
5554 ModuleFileExtensionMetadata Metadata;
5555 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
5556 return llvm::createStringError(
5557 std::errc::illegal_byte_sequence,
5558 "malformed EXTENSION_METADATA in AST file");
5559
5560 // Find a module file extension with this block name.
5561 auto Known = ModuleFileExtensions.find(Metadata.BlockName);
5562 if (Known == ModuleFileExtensions.end()) break;
5563
5564 // Form a reader.
5565 if (auto Reader = Known->second->createExtensionReader(Metadata, *this,
5566 F, Stream)) {
5567 F.ExtensionReaders.push_back(std::move(Reader));
5568 }
5569
5570 break;
5571 }
5572 }
5573 }
5574
5575 llvm_unreachable("ReadExtensionBlock should return from while loop");
5576}
5577
5579 assert(ContextObj && "no context to initialize");
5580 ASTContext &Context = *ContextObj;
5581
5582 // If there's a listener, notify them that we "read" the translation unit.
5583 if (DeserializationListener)
5584 DeserializationListener->DeclRead(
5586 Context.getTranslationUnitDecl());
5587
5588 // FIXME: Find a better way to deal with collisions between these
5589 // built-in types. Right now, we just ignore the problem.
5590
5591 // Load the special types.
5592 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
5593 if (TypeID String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
5594 if (!Context.CFConstantStringTypeDecl)
5595 Context.setCFConstantStringType(GetType(String));
5596 }
5597
5598 if (TypeID File = SpecialTypes[SPECIAL_TYPE_FILE]) {
5599 QualType FileType = GetType(File);
5600 if (FileType.isNull()) {
5601 Error("FILE type is NULL");
5602 return;
5603 }
5604
5605 if (!Context.FILEDecl) {
5606 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
5607 Context.setFILEDecl(Typedef->getDecl());
5608 else {
5609 const TagType *Tag = FileType->getAs<TagType>();
5610 if (!Tag) {
5611 Error("Invalid FILE type in AST file");
5612 return;
5613 }
5614 Context.setFILEDecl(Tag->getDecl());
5615 }
5616 }
5617 }
5618
5619 if (TypeID Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
5620 QualType Jmp_bufType = GetType(Jmp_buf);
5621 if (Jmp_bufType.isNull()) {
5622 Error("jmp_buf type is NULL");
5623 return;
5624 }
5625
5626 if (!Context.jmp_bufDecl) {
5627 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
5628 Context.setjmp_bufDecl(Typedef->getDecl());
5629 else {
5630 const TagType *Tag = Jmp_bufType->getAs<TagType>();
5631 if (!Tag) {
5632 Error("Invalid jmp_buf type in AST file");
5633 return;
5634 }
5635 Context.setjmp_bufDecl(Tag->getDecl());
5636 }
5637 }
5638 }
5639
5640 if (TypeID Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
5641 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
5642 if (Sigjmp_bufType.isNull()) {
5643 Error("sigjmp_buf type is NULL");
5644 return;
5645 }
5646
5647 if (!Context.sigjmp_bufDecl) {
5648 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
5649 Context.setsigjmp_bufDecl(Typedef->getDecl());
5650 else {
5651 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
5652 assert(Tag && "Invalid sigjmp_buf type in AST file");
5653 Context.setsigjmp_bufDecl(Tag->getDecl());
5654 }
5655 }
5656 }
5657
5658 if (TypeID ObjCIdRedef = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
5659 if (Context.ObjCIdRedefinitionType.isNull())
5660 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
5661 }
5662
5663 if (TypeID ObjCClassRedef =
5665 if (Context.ObjCClassRedefinitionType.isNull())
5666 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
5667 }
5668
5669 if (TypeID ObjCSelRedef =
5670 SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
5671 if (Context.ObjCSelRedefinitionType.isNull())
5672 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
5673 }
5674
5675 if (TypeID Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
5676 QualType Ucontext_tType = GetType(Ucontext_t);
5677 if (Ucontext_tType.isNull()) {
5678 Error("ucontext_t type is NULL");
5679 return;
5680 }
5681
5682 if (!Context.ucontext_tDecl) {
5683 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
5684 Context.setucontext_tDecl(Typedef->getDecl());
5685 else {
5686 const TagType *Tag = Ucontext_tType->getAs<TagType>();
5687 assert(Tag && "Invalid ucontext_t type in AST file");
5688 Context.setucontext_tDecl(Tag->getDecl());
5689 }
5690 }
5691 }
5692 }
5693
5694 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
5695
5696 // If there were any CUDA special declarations, deserialize them.
5697 if (!CUDASpecialDeclRefs.empty()) {
5698 assert(CUDASpecialDeclRefs.size() == 3 && "More decl refs than expected!");
5699 Context.setcudaConfigureCallDecl(
5700 cast_or_null<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
5701 Context.setcudaGetParameterBufferDecl(
5702 cast_or_null<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[1])));
5703 Context.setcudaLaunchDeviceDecl(
5704 cast_or_null<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[2])));
5705 }
5706
5707 // Re-export any modules that were imported by a non-module AST file.
5708 // FIXME: This does not make macro-only imports visible again.
5709 for (auto &Import : PendingImportedModules) {
5710 if (Module *Imported = getSubmodule(Import.ID)) {
5712 /*ImportLoc=*/Import.ImportLoc);
5713 if (Import.ImportLoc.isValid())
5714 PP.makeModuleVisible(Imported, Import.ImportLoc);
5715 // This updates visibility for Preprocessor only. For Sema, which can be
5716 // nullptr here, we do the same later, in UpdateSema().
5717 }
5718 }
5719
5720 // Hand off these modules to Sema.
5721 PendingImportedModulesSema.append(PendingImportedModules);
5722 PendingImportedModules.clear();
5723}
5724
5726 // Nothing to do for now.
5727}
5728
5729/// Reads and return the signature record from \p PCH's control block, or
5730/// else returns 0.
5732 BitstreamCursor Stream(PCH);
5733 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5734 // FIXME this drops the error on the floor.
5735 consumeError(std::move(Err));
5736 return ASTFileSignature();
5737 }
5738
5739 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
5741 return ASTFileSignature();
5742
5743 // Scan for SIGNATURE inside the diagnostic options block.
5745 while (true) {
5747 Stream.advanceSkippingSubblocks();
5748 if (!MaybeEntry) {
5749 // FIXME this drops the error on the floor.
5750 consumeError(MaybeEntry.takeError());
5751 return ASTFileSignature();
5752 }
5753 llvm::BitstreamEntry Entry = MaybeEntry.get();
5754
5755 if (Entry.Kind != llvm::BitstreamEntry::Record)
5756 return ASTFileSignature();
5757
5758 Record.clear();
5759 StringRef Blob;
5760 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);
5761 if (!MaybeRecord) {
5762 // FIXME this drops the error on the floor.
5763 consumeError(MaybeRecord.takeError());
5764 return ASTFileSignature();
5765 }
5766 if (SIGNATURE == MaybeRecord.get()) {
5767 auto Signature = ASTFileSignature::create(Blob.begin(), Blob.end());
5768 assert(Signature != ASTFileSignature::createDummy() &&
5769 "Dummy AST file signature not backpatched in ASTWriter.");
5770 return Signature;
5771 }
5772 }
5773}
5774
5775/// Retrieve the name of the original source file name
5776/// directly from the AST file, without actually loading the AST
5777/// file.
5779 const std::string &ASTFileName, FileManager &FileMgr,
5780 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
5781 // Open the AST file.
5782 auto Buffer = FileMgr.getBufferForFile(ASTFileName, /*IsVolatile=*/false,
5783 /*RequiresNullTerminator=*/false,
5784 /*MaybeLimit=*/std::nullopt,
5785 /*IsText=*/false);
5786 if (!Buffer) {
5787 Diags.Report(diag::err_fe_unable_to_read_pch_file)
5788 << ASTFileName << Buffer.getError().message();
5789 return std::string();
5790 }
5791
5792 // Initialize the stream
5793 BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer));
5794
5795 // Sniff for the signature.
5796 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5797 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName << std::move(Err);
5798 return std::string();
5799 }
5800
5801 // Scan for the CONTROL_BLOCK_ID block.
5802 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
5803 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
5804 return std::string();
5805 }
5806
5807 // Scan for ORIGINAL_FILE inside the control block.
5809 while (true) {
5811 Stream.advanceSkippingSubblocks();
5812 if (!MaybeEntry) {
5813 // FIXME this drops errors on the floor.
5814 consumeError(MaybeEntry.takeError());
5815 return std::string();
5816 }
5817 llvm::BitstreamEntry Entry = MaybeEntry.get();
5818
5819 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
5820 return std::string();
5821
5822 if (Entry.Kind != llvm::BitstreamEntry::Record) {
5823 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
5824 return std::string();
5825 }
5826
5827 Record.clear();
5828 StringRef Blob;
5829 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);
5830 if (!MaybeRecord) {
5831 // FIXME this drops the errors on the floor.
5832 consumeError(MaybeRecord.takeError());
5833 return std::string();
5834 }
5835 if (ORIGINAL_FILE == MaybeRecord.get())
5836 return Blob.str();
5837 }
5838}
5839
5840namespace {
5841
5842 class SimplePCHValidator : public ASTReaderListener {
5843 const LangOptions &ExistingLangOpts;
5844 const CodeGenOptions &ExistingCGOpts;
5845 const TargetOptions &ExistingTargetOpts;
5846 const PreprocessorOptions &ExistingPPOpts;
5847 const HeaderSearchOptions &ExistingHSOpts;
5848 std::string ExistingSpecificModuleCachePath;
5850 bool StrictOptionMatches;
5851
5852 public:
5853 SimplePCHValidator(const LangOptions &ExistingLangOpts,
5854 const CodeGenOptions &ExistingCGOpts,
5855 const TargetOptions &ExistingTargetOpts,
5856 const PreprocessorOptions &ExistingPPOpts,
5857 const HeaderSearchOptions &ExistingHSOpts,
5858 StringRef ExistingSpecificModuleCachePath,
5859 FileManager &FileMgr, bool StrictOptionMatches)
5860 : ExistingLangOpts(ExistingLangOpts), ExistingCGOpts(ExistingCGOpts),
5861 ExistingTargetOpts(ExistingTargetOpts),
5862 ExistingPPOpts(ExistingPPOpts), ExistingHSOpts(ExistingHSOpts),
5863 ExistingSpecificModuleCachePath(ExistingSpecificModuleCachePath),
5864 FileMgr(FileMgr), StrictOptionMatches(StrictOptionMatches) {}
5865
5866 bool ReadLanguageOptions(const LangOptions &LangOpts,
5867 StringRef ModuleFilename, bool Complain,
5868 bool AllowCompatibleDifferences) override {
5869 return checkLanguageOptions(ExistingLangOpts, LangOpts, ModuleFilename,
5870 nullptr, AllowCompatibleDifferences);
5871 }
5872
5873 bool ReadCodeGenOptions(const CodeGenOptions &CGOpts,
5874 StringRef ModuleFilename, bool Complain,
5875 bool AllowCompatibleDifferences) override {
5876 return checkCodegenOptions(ExistingCGOpts, CGOpts, ModuleFilename,
5877 nullptr, AllowCompatibleDifferences);
5878 }
5879
5880 bool ReadTargetOptions(const TargetOptions &TargetOpts,
5881 StringRef ModuleFilename, bool Complain,
5882 bool AllowCompatibleDifferences) override {
5883 return checkTargetOptions(ExistingTargetOpts, TargetOpts, ModuleFilename,
5884 nullptr, AllowCompatibleDifferences);
5885 }
5886
5887 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
5888 StringRef ASTFilename, StringRef ContextHash,
5889 bool Complain) override {
5890 return checkModuleCachePath(
5891 FileMgr, ContextHash, ExistingSpecificModuleCachePath, ASTFilename,
5892 nullptr, ExistingLangOpts, ExistingPPOpts, ExistingHSOpts, HSOpts);
5893 }
5894
5895 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
5896 StringRef ModuleFilename, bool ReadMacros,
5897 bool Complain,
5898 std::string &SuggestedPredefines) override {
5900 PPOpts, ExistingPPOpts, ModuleFilename, ReadMacros, /*Diags=*/nullptr,
5901 FileMgr, SuggestedPredefines, ExistingLangOpts,
5902 StrictOptionMatches ? OptionValidateStrictMatches
5904 }
5905 };
5906
5907} // namespace
5908
5910 StringRef Filename, FileManager &FileMgr, const ModuleCache &ModCache,
5911 const PCHContainerReader &PCHContainerRdr, bool FindModuleFileExtensions,
5912 ASTReaderListener &Listener, bool ValidateDiagnosticOptions,
5913 unsigned ClientLoadCapabilities) {
5914 // Open the AST file.
5915 std::unique_ptr<llvm::MemoryBuffer> OwnedBuffer;
5916 llvm::MemoryBuffer *Buffer =
5917 ModCache.getInMemoryModuleCache().lookupPCM(Filename);
5918 if (!Buffer) {
5919 // FIXME: We should add the pcm to the InMemoryModuleCache if it could be
5920 // read again later, but we do not have the context here to determine if it
5921 // is safe to change the result of InMemoryModuleCache::getPCMState().
5922
5923 // FIXME: This allows use of the VFS; we do not allow use of the
5924 // VFS when actually loading a module.
5925 auto Entry =
5926 Filename == "-" ? FileMgr.getSTDIN() : FileMgr.getFileRef(Filename);
5927 if (!Entry) {
5928 llvm::consumeError(Entry.takeError());
5929 return true;
5930 }
5931 auto BufferOrErr = FileMgr.getBufferForFile(*Entry);
5932 if (!BufferOrErr)
5933 return true;
5934 OwnedBuffer = std::move(*BufferOrErr);
5935 Buffer = OwnedBuffer.get();
5936 }
5937
5938 // Initialize the stream
5939 StringRef Bytes = PCHContainerRdr.ExtractPCH(*Buffer);
5940 BitstreamCursor Stream(Bytes);
5941
5942 // Sniff for the signature.
5943 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5944 consumeError(std::move(Err)); // FIXME this drops errors on the floor.
5945 return true;
5946 }
5947
5948 // Scan for the CONTROL_BLOCK_ID block.
5950 return true;
5951
5952 bool NeedsInputFiles = Listener.needsInputFileVisitation();
5953 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
5954 bool NeedsImports = Listener.needsImportVisitation();
5955 BitstreamCursor InputFilesCursor;
5956 uint64_t InputFilesOffsetBase = 0;
5957
5959 std::string ModuleDir;
5960 bool DoneWithControlBlock = false;
5961 SmallString<0> PathBuf;
5962 PathBuf.reserve(256);
5963 // Additional path buffer to use when multiple paths need to be resolved.
5964 // For example, when deserializing input files that contains a path that was
5965 // resolved from a vfs overlay and an external location.
5966 SmallString<0> AdditionalPathBuf;
5967 AdditionalPathBuf.reserve(256);
5968 while (!DoneWithControlBlock) {
5969 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5970 if (!MaybeEntry) {
5971 // FIXME this drops the error on the floor.
5972 consumeError(MaybeEntry.takeError());
5973 return true;
5974 }
5975 llvm::BitstreamEntry Entry = MaybeEntry.get();
5976
5977 switch (Entry.Kind) {
5978 case llvm::BitstreamEntry::SubBlock: {
5979 switch (Entry.ID) {
5980 case OPTIONS_BLOCK_ID: {
5981 std::string IgnoredSuggestedPredefines;
5982 if (ReadOptionsBlock(Stream, Filename, ClientLoadCapabilities,
5983 /*AllowCompatibleConfigurationMismatch*/ false,
5984 Listener, IgnoredSuggestedPredefines) != Success)
5985 return true;
5986 break;
5987 }
5988
5990 InputFilesCursor = Stream;
5991 if (llvm::Error Err = Stream.SkipBlock()) {
5992 // FIXME this drops the error on the floor.
5993 consumeError(std::move(Err));
5994 return true;
5995 }
5996 if (NeedsInputFiles &&
5997 ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID))
5998 return true;
5999 InputFilesOffsetBase = InputFilesCursor.GetCurrentBitNo();
6000 break;
6001
6002 default:
6003 if (llvm::Error Err = Stream.SkipBlock()) {
6004 // FIXME this drops the error on the floor.
6005 consumeError(std::move(Err));
6006 return true;
6007 }
6008 break;
6009 }
6010
6011 continue;
6012 }
6013
6014 case llvm::BitstreamEntry::EndBlock:
6015 DoneWithControlBlock = true;
6016 break;
6017
6018 case llvm::BitstreamEntry::Error:
6019 return true;
6020
6021 case llvm::BitstreamEntry::Record:
6022 break;
6023 }
6024
6025 if (DoneWithControlBlock) break;
6026
6027 Record.clear();
6028 StringRef Blob;
6029 Expected<unsigned> MaybeRecCode =
6030 Stream.readRecord(Entry.ID, Record, &Blob);
6031 if (!MaybeRecCode) {
6032 // FIXME this drops the error.
6033 return Failure;
6034 }
6035 switch ((ControlRecordTypes)MaybeRecCode.get()) {
6036 case METADATA:
6037 if (Record[0] != VERSION_MAJOR)
6038 return true;
6039 if (Listener.ReadFullVersionInformation(Blob))
6040 return true;
6041 break;
6042 case MODULE_NAME:
6043 Listener.ReadModuleName(Blob);
6044 break;
6045 case MODULE_DIRECTORY:
6046 ModuleDir = std::string(Blob);
6047 break;
6048 case MODULE_MAP_FILE: {
6049 unsigned Idx = 0;
6050 std::string PathStr = ReadString(Record, Idx);
6051 auto Path = ResolveImportedPath(PathBuf, PathStr, ModuleDir);
6052 Listener.ReadModuleMapFile(*Path);
6053 break;
6054 }
6055 case INPUT_FILE_OFFSETS: {
6056 if (!NeedsInputFiles)
6057 break;
6058
6059 unsigned NumInputFiles = Record[0];
6060 unsigned NumUserFiles = Record[1];
6061 const llvm::support::unaligned_uint64_t *InputFileOffs =
6062 (const llvm::support::unaligned_uint64_t *)Blob.data();
6063 for (unsigned I = 0; I != NumInputFiles; ++I) {
6064 // Go find this input file.
6065 bool isSystemFile = I >= NumUserFiles;
6066
6067 if (isSystemFile && !NeedsSystemInputFiles)
6068 break; // the rest are system input files
6069
6070 BitstreamCursor &Cursor = InputFilesCursor;
6071 SavedStreamPosition SavedPosition(Cursor);
6072 if (llvm::Error Err =
6073 Cursor.JumpToBit(InputFilesOffsetBase + InputFileOffs[I])) {
6074 // FIXME this drops errors on the floor.
6075 consumeError(std::move(Err));
6076 }
6077
6078 Expected<unsigned> MaybeCode = Cursor.ReadCode();
6079 if (!MaybeCode) {
6080 // FIXME this drops errors on the floor.
6081 consumeError(MaybeCode.takeError());
6082 }
6083 unsigned Code = MaybeCode.get();
6084
6086 StringRef Blob;
6087 bool shouldContinue = false;
6088 Expected<unsigned> MaybeRecordType =
6089 Cursor.readRecord(Code, Record, &Blob);
6090 if (!MaybeRecordType) {
6091 // FIXME this drops errors on the floor.
6092 consumeError(MaybeRecordType.takeError());
6093 }
6094 switch ((InputFileRecordTypes)MaybeRecordType.get()) {
6095 case INPUT_FILE_HASH:
6096 break;
6097 case INPUT_FILE:
6098 time_t StoredTime = static_cast<time_t>(Record[2]);
6099 bool Overridden = static_cast<bool>(Record[3]);
6100 auto [UnresolvedFilenameAsRequested, UnresolvedFilename] =
6102 auto FilenameAsRequestedBuf = ResolveImportedPath(
6103 PathBuf, UnresolvedFilenameAsRequested, ModuleDir);
6104 StringRef Filename;
6105 if (UnresolvedFilename.empty())
6106 Filename = *FilenameAsRequestedBuf;
6107 else {
6108 auto FilenameBuf = ResolveImportedPath(
6109 AdditionalPathBuf, UnresolvedFilename, ModuleDir);
6110 Filename = *FilenameBuf;
6111 }
6112 shouldContinue = Listener.visitInputFileAsRequested(
6113 *FilenameAsRequestedBuf, Filename, isSystemFile, Overridden,
6114 StoredTime, /*IsExplicitModule=*/false);
6115 break;
6116 }
6117 if (!shouldContinue)
6118 break;
6119 }
6120 break;
6121 }
6122
6123 case IMPORT: {
6124 if (!NeedsImports)
6125 break;
6126
6127 unsigned Idx = 0;
6128 // Read information about the AST file.
6129
6130 // Skip Kind
6131 Idx++;
6132
6133 // Skip ImportLoc
6134 Idx++;
6135
6136 StringRef ModuleName = ReadStringBlob(Record, Idx, Blob);
6137
6138 bool IsStandardCXXModule = Record[Idx++];
6139
6140 // In C++20 Modules, we don't record the path to imported
6141 // modules in the BMI files.
6142 if (IsStandardCXXModule) {
6143 Listener.visitImport(ModuleName, /*Filename=*/"");
6144 continue;
6145 }
6146
6147 // Skip Size, ModTime and ImplicitModuleSuffix.
6148 Idx += 1 + 1 + 1;
6149 // Skip signature.
6150 Blob = Blob.substr(ASTFileSignature::size);
6151
6152 StringRef FilenameStr = ReadStringBlob(Record, Idx, Blob);
6153 auto Filename = ResolveImportedPath(PathBuf, FilenameStr, ModuleDir);
6154 Listener.visitImport(ModuleName, *Filename);
6155 break;
6156 }
6157
6158 default:
6159 // No other validation to perform.
6160 break;
6161 }
6162 }
6163
6164 // Look for module file extension blocks, if requested.
6165 if (FindModuleFileExtensions) {
6166 BitstreamCursor SavedStream = Stream;
6167 while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {
6168 bool DoneWithExtensionBlock = false;
6169 while (!DoneWithExtensionBlock) {
6170 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
6171 if (!MaybeEntry) {
6172 // FIXME this drops the error.
6173 return true;
6174 }
6175 llvm::BitstreamEntry Entry = MaybeEntry.get();
6176
6177 switch (Entry.Kind) {
6178 case llvm::BitstreamEntry::SubBlock:
6179 if (llvm::Error Err = Stream.SkipBlock()) {
6180 // FIXME this drops the error on the floor.
6181 consumeError(std::move(Err));
6182 return true;
6183 }
6184 continue;
6185
6186 case llvm::BitstreamEntry::EndBlock:
6187 DoneWithExtensionBlock = true;
6188 continue;
6189
6190 case llvm::BitstreamEntry::Error:
6191 return true;
6192
6193 case llvm::BitstreamEntry::Record:
6194 break;
6195 }
6196
6197 Record.clear();
6198 StringRef Blob;
6199 Expected<unsigned> MaybeRecCode =
6200 Stream.readRecord(Entry.ID, Record, &Blob);
6201 if (!MaybeRecCode) {
6202 // FIXME this drops the error.
6203 return true;
6204 }
6205 switch (MaybeRecCode.get()) {
6206 case EXTENSION_METADATA: {
6208 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
6209 return true;
6210
6211 Listener.readModuleFileExtension(Metadata);
6212 break;
6213 }
6214 }
6215 }
6216 }
6217 Stream = std::move(SavedStream);
6218 }
6219
6220 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
6221 if (readUnhashedControlBlockImpl(
6222 nullptr, Bytes, Filename, ClientLoadCapabilities,
6223 /*AllowCompatibleConfigurationMismatch*/ false, &Listener,
6224 ValidateDiagnosticOptions) != Success)
6225 return true;
6226
6227 return false;
6228}
6229
6231 StringRef Filename, FileManager &FileMgr, const ModuleCache &ModCache,
6232 const PCHContainerReader &PCHContainerRdr, const LangOptions &LangOpts,
6233 const CodeGenOptions &CGOpts, const TargetOptions &TargetOpts,
6234 const PreprocessorOptions &PPOpts, const HeaderSearchOptions &HSOpts,
6235 StringRef SpecificModuleCachePath, bool RequireStrictOptionMatches) {
6236 SimplePCHValidator validator(LangOpts, CGOpts, TargetOpts, PPOpts, HSOpts,
6237 SpecificModuleCachePath, FileMgr,
6238 RequireStrictOptionMatches);
6239 return !readASTFileControlBlock(Filename, FileMgr, ModCache, PCHContainerRdr,
6240 /*FindModuleFileExtensions=*/false, validator,
6241 /*ValidateDiagnosticOptions=*/true);
6242}
6243
6244llvm::Error ASTReader::ReadSubmoduleBlock(ModuleFile &F,
6245 unsigned ClientLoadCapabilities) {
6246 // Enter the submodule block.
6247 if (llvm::Error Err = F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID))
6248 return Err;
6249
6250 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
6251 bool KnowsTopLevelModule = ModMap.findModule(F.ModuleName) != nullptr;
6252 // If we don't know the top-level module, there's no point in doing qualified
6253 // lookup of its submodules; it won't find anything anywhere within this tree.
6254 // Let's skip that and avoid some string lookups.
6255 auto CreateModule = !KnowsTopLevelModule
6258
6259 bool First = true;
6260 Module *CurrentModule = nullptr;
6261 RecordData Record;
6262 while (true) {
6264 F.Stream.advanceSkippingSubblocks();
6265 if (!MaybeEntry)
6266 return MaybeEntry.takeError();
6267 llvm::BitstreamEntry Entry = MaybeEntry.get();
6268
6269 switch (Entry.Kind) {
6270 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
6271 case llvm::BitstreamEntry::Error:
6272 return llvm::createStringError(std::errc::illegal_byte_sequence,
6273 "malformed block record in AST file");
6274 case llvm::BitstreamEntry::EndBlock:
6275 return llvm::Error::success();
6276 case llvm::BitstreamEntry::Record:
6277 // The interesting case.
6278 break;
6279 }
6280
6281 // Read a record.
6282 StringRef Blob;
6283 Record.clear();
6284 Expected<unsigned> MaybeKind = F.Stream.readRecord(Entry.ID, Record, &Blob);
6285 if (!MaybeKind)
6286 return MaybeKind.takeError();
6287 unsigned Kind = MaybeKind.get();
6288
6289 if ((Kind == SUBMODULE_METADATA) != First)
6290 return llvm::createStringError(
6291 std::errc::illegal_byte_sequence,
6292 "submodule metadata record should be at beginning of block");
6293 First = false;
6294
6295 // Submodule information is only valid if we have a current module.
6296 // FIXME: Should we error on these cases?
6297 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
6298 Kind != SUBMODULE_DEFINITION)
6299 continue;
6300
6301 switch (Kind) {
6302 default: // Default behavior: ignore.
6303 break;
6304
6305 case SUBMODULE_DEFINITION: {
6306 if (Record.size() < 13)
6307 return llvm::createStringError(std::errc::illegal_byte_sequence,
6308 "malformed module definition");
6309
6310 StringRef Name = Blob;
6311 unsigned Idx = 0;
6312 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
6313 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
6315 SourceLocation DefinitionLoc = ReadSourceLocation(F, Record[Idx++]);
6316 FileID InferredAllowedBy = ReadFileID(F, Record, Idx);
6317 bool IsFramework = Record[Idx++];
6318 bool IsExplicit = Record[Idx++];
6319 bool IsSystem = Record[Idx++];
6320 bool IsExternC = Record[Idx++];
6321 bool InferSubmodules = Record[Idx++];
6322 bool InferExplicitSubmodules = Record[Idx++];
6323 bool InferExportWildcard = Record[Idx++];
6324 bool ConfigMacrosExhaustive = Record[Idx++];
6325 bool ModuleMapIsPrivate = Record[Idx++];
6326 bool NamedModuleHasInit = Record[Idx++];
6327
6328 Module *ParentModule = nullptr;
6329 if (Parent)
6330 ParentModule = getSubmodule(Parent);
6331
6332 CurrentModule = std::invoke(CreateModule, &ModMap, Name, ParentModule,
6333 IsFramework, IsExplicit);
6334
6335 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
6336 if (GlobalIndex >= SubmodulesLoaded.size() ||
6337 SubmodulesLoaded[GlobalIndex])
6338 return llvm::createStringError(std::errc::invalid_argument,
6339 "too many submodules");
6340
6341 if (!ParentModule) {
6342 if ([[maybe_unused]] const ModuleFileKey *CurFileKey =
6343 CurrentModule->getASTFileKey()) {
6344 // Don't emit module relocation error if we have -fno-validate-pch
6345 if (!bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation &
6347 assert(*CurFileKey != F.FileKey &&
6348 "ModuleManager did not de-duplicate");
6349
6350 Diag(diag::err_module_file_conflict)
6351 << CurrentModule->getTopLevelModuleName()
6352 << *CurrentModule->getASTFileName() << F.FileName;
6353
6354 auto CurModMapFile =
6355 ModMap.getContainingModuleMapFile(CurrentModule);
6356 auto ModMapFile = FileMgr.getOptionalFileRef(F.ModuleMapPath);
6357 if (CurModMapFile && ModMapFile && CurModMapFile != ModMapFile)
6358 Diag(diag::note_module_file_conflict)
6359 << CurModMapFile->getName() << ModMapFile->getName();
6360
6361 return llvm::make_error<AlreadyReportedDiagnosticError>();
6362 }
6363 }
6364
6365 F.DidReadTopLevelSubmodule = true;
6366 CurrentModule->setASTFileNameAndKey(F.FileName, F.FileKey);
6367 CurrentModule->PresumedModuleMapFile = F.ModuleMapPath;
6368 }
6369
6370 CurrentModule->Kind = Kind;
6371 // Note that we may be rewriting an existing location and it is important
6372 // to keep doing that. In particular, we would like to prefer a
6373 // `DefinitionLoc` loaded from the module file instead of the location
6374 // created in the current source manager, because it allows the new
6375 // location to be marked as "unaffecting" when writing and avoid creating
6376 // duplicate locations for the same module map file.
6377 CurrentModule->DefinitionLoc = DefinitionLoc;
6378 CurrentModule->Signature = F.Signature;
6379 CurrentModule->IsFromModuleFile = true;
6380 if (InferredAllowedBy.isValid())
6381 ModMap.setInferredModuleAllowedBy(CurrentModule, InferredAllowedBy);
6382 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
6383 CurrentModule->IsExternC = IsExternC;
6384 CurrentModule->InferSubmodules = InferSubmodules;
6385 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
6386 CurrentModule->InferExportWildcard = InferExportWildcard;
6387 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
6388 CurrentModule->ModuleMapIsPrivate = ModuleMapIsPrivate;
6389 CurrentModule->NamedModuleHasInit = NamedModuleHasInit;
6390
6391 if (!ParentModule && !F.BaseDirectory.empty()) {
6392 if (auto Dir = FileMgr.getOptionalDirectoryRef(F.BaseDirectory))
6393 CurrentModule->Directory = *Dir;
6394 } else if (ParentModule && ParentModule->Directory) {
6395 // Submodules inherit the directory from their parent.
6396 CurrentModule->Directory = ParentModule->Directory;
6397 }
6398
6399 if (DeserializationListener)
6400 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
6401
6402 SubmodulesLoaded[GlobalIndex] = CurrentModule;
6403
6404 // Clear out data that will be replaced by what is in the module file.
6405 CurrentModule->LinkLibraries.clear();
6406 CurrentModule->ConfigMacros.clear();
6407 CurrentModule->UnresolvedConflicts.clear();
6408 CurrentModule->Conflicts.clear();
6409
6410 // The module is available unless it's missing a requirement; relevant
6411 // requirements will be (re-)added by SUBMODULE_REQUIRES records.
6412 // Missing headers that were present when the module was built do not
6413 // make it unavailable -- if we got this far, this must be an explicitly
6414 // imported module file.
6415 CurrentModule->Requirements.clear();
6416 CurrentModule->MissingHeaders.clear();
6417 CurrentModule->IsUnimportable =
6418 ParentModule && ParentModule->IsUnimportable;
6419 CurrentModule->IsAvailable = !CurrentModule->IsUnimportable;
6420 break;
6421 }
6422
6424 SmallString<128> RelativePathName;
6425 if (auto Umbrella = ModMap.findUmbrellaHeaderForModule(
6426 CurrentModule, Blob.str(), RelativePathName)) {
6427 if (!CurrentModule->getUmbrellaHeaderAsWritten()) {
6428 ModMap.setUmbrellaHeaderAsWritten(CurrentModule, *Umbrella, Blob,
6429 RelativePathName);
6430 }
6431 // Note that it's too late at this point to return out of date if the
6432 // name from the PCM doesn't match up with the one in the module map,
6433 // but also quite unlikely since we will have already checked the
6434 // modification time and size of the module map file itself.
6435 }
6436 break;
6437 }
6438
6439 case SUBMODULE_HEADER:
6442 // We lazily associate headers with their modules via the HeaderInfo table.
6443 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
6444 // of complete filenames or remove it entirely.
6445 break;
6446
6449 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
6450 // them here.
6451 break;
6452
6453 case SUBMODULE_TOPHEADER: {
6454 auto HeaderName = ResolveImportedPath(PathBuf, Blob, F);
6455 CurrentModule->addTopHeaderFilename(*HeaderName);
6456 break;
6457 }
6458
6460 auto Dirname = ResolveImportedPath(PathBuf, Blob, F);
6461 if (auto Umbrella =
6462 PP.getFileManager().getOptionalDirectoryRef(*Dirname)) {
6463 if (!CurrentModule->getUmbrellaDirAsWritten()) {
6464 // FIXME: NameAsWritten
6465 ModMap.setUmbrellaDirAsWritten(CurrentModule, *Umbrella, Blob, "");
6466 }
6467 }
6468 break;
6469 }
6470
6471 case SUBMODULE_METADATA: {
6472 F.BaseSubmoduleID = getTotalNumSubmodules();
6474 unsigned LocalBaseSubmoduleID = Record[1];
6475 if (F.LocalNumSubmodules > 0) {
6476 // Introduce the global -> local mapping for submodules within this
6477 // module.
6478 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
6479
6480 // Introduce the local -> global mapping for submodules within this
6481 // module.
6483 std::make_pair(LocalBaseSubmoduleID,
6484 F.BaseSubmoduleID - LocalBaseSubmoduleID));
6485
6486 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
6487 }
6488 break;
6489 }
6490
6491 case SUBMODULE_IMPORTS:
6492 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
6493 UnresolvedModuleRef Unresolved;
6494 Unresolved.File = &F;
6495 Unresolved.Mod = CurrentModule;
6496 Unresolved.ID = Record[Idx];
6497 Unresolved.Kind = UnresolvedModuleRef::Import;
6498 Unresolved.IsWildcard = false;
6499 UnresolvedModuleRefs.push_back(Unresolved);
6500 }
6501 break;
6502
6504 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
6505 UnresolvedModuleRef Unresolved;
6506 Unresolved.File = &F;
6507 Unresolved.Mod = CurrentModule;
6508 Unresolved.ID = Record[Idx];
6509 Unresolved.Kind = UnresolvedModuleRef::Affecting;
6510 Unresolved.IsWildcard = false;
6511 UnresolvedModuleRefs.push_back(Unresolved);
6512 }
6513 break;
6514
6515 case SUBMODULE_EXPORTS:
6516 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
6517 UnresolvedModuleRef Unresolved;
6518 Unresolved.File = &F;
6519 Unresolved.Mod = CurrentModule;
6520 Unresolved.ID = Record[Idx];
6521 Unresolved.Kind = UnresolvedModuleRef::Export;
6522 Unresolved.IsWildcard = Record[Idx + 1];
6523 UnresolvedModuleRefs.push_back(Unresolved);
6524 }
6525
6526 // Once we've loaded the set of exports, there's no reason to keep
6527 // the parsed, unresolved exports around.
6528 CurrentModule->UnresolvedExports.clear();
6529 break;
6530
6531 case SUBMODULE_REQUIRES:
6532 CurrentModule->addRequirement(Blob, Record[0], PP.getLangOpts(),
6533 PP.getTargetInfo());
6534 break;
6535
6537 ModMap.resolveLinkAsDependencies(CurrentModule);
6538 CurrentModule->LinkLibraries.push_back(
6539 Module::LinkLibrary(std::string(Blob), Record[0]));
6540 break;
6541
6543 CurrentModule->ConfigMacros.push_back(Blob.str());
6544 break;
6545
6546 case SUBMODULE_CONFLICT: {
6547 UnresolvedModuleRef Unresolved;
6548 Unresolved.File = &F;
6549 Unresolved.Mod = CurrentModule;
6550 Unresolved.ID = Record[0];
6551 Unresolved.Kind = UnresolvedModuleRef::Conflict;
6552 Unresolved.IsWildcard = false;
6553 Unresolved.String = Blob;
6554 UnresolvedModuleRefs.push_back(Unresolved);
6555 break;
6556 }
6557
6559 if (!ContextObj)
6560 break;
6561 // Standard C++ module has its own way to initialize variables.
6562 if (!F.StandardCXXModule || F.Kind == MK_MainFile) {
6563 SmallVector<GlobalDeclID, 16> Inits;
6564 for (unsigned I = 0; I < Record.size(); /*in loop*/)
6565 Inits.push_back(ReadDeclID(F, Record, I));
6566 ContextObj->addLazyModuleInitializers(CurrentModule, Inits);
6567 }
6568 break;
6569 }
6570
6572 CurrentModule->ExportAsModule = Blob.str();
6573 ModMap.addLinkAsDependency(CurrentModule);
6574 break;
6575 }
6576 }
6577}
6578
6579/// Parse the record that corresponds to a LangOptions data
6580/// structure.
6581///
6582/// This routine parses the language options from the AST file and then gives
6583/// them to the AST listener if one is set.
6584///
6585/// \returns true if the listener deems the file unacceptable, false otherwise.
6586bool ASTReader::ParseLanguageOptions(const RecordData &Record,
6587 StringRef ModuleFilename, bool Complain,
6588 ASTReaderListener &Listener,
6589 bool AllowCompatibleDifferences) {
6590 LangOptions LangOpts;
6591 unsigned Idx = 0;
6592#define LANGOPT(Name, Bits, Default, Compatibility, Description) \
6593 LangOpts.Name = Record[Idx++];
6594#define ENUM_LANGOPT(Name, Type, Bits, Default, Compatibility, Description) \
6595 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
6596#include "clang/Basic/LangOptions.def"
6597#define SANITIZER(NAME, ID) \
6598 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
6599#include "clang/Basic/Sanitizers.def"
6600
6601 for (unsigned N = Record[Idx++]; N; --N)
6602 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
6603
6604 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
6605 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
6606 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
6607
6608 LangOpts.CurrentModule = ReadString(Record, Idx);
6609
6610 // Comment options.
6611 for (unsigned N = Record[Idx++]; N; --N) {
6612 LangOpts.CommentOpts.BlockCommandNames.push_back(
6613 ReadString(Record, Idx));
6614 }
6615 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
6616
6617 // OpenMP offloading options.
6618 for (unsigned N = Record[Idx++]; N; --N) {
6619 LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx)));
6620 }
6621
6622 LangOpts.OMPHostIRFile = ReadString(Record, Idx);
6623
6624 return Listener.ReadLanguageOptions(LangOpts, ModuleFilename, Complain,
6625 AllowCompatibleDifferences);
6626}
6627
6628bool ASTReader::ParseCodeGenOptions(const RecordData &Record,
6629 StringRef ModuleFilename, bool Complain,
6630 ASTReaderListener &Listener,
6631 bool AllowCompatibleDifferences) {
6632 unsigned Idx = 0;
6633 CodeGenOptions CGOpts;
6635#define CODEGENOPT(Name, Bits, Default, Compatibility) \
6636 if constexpr (CK::Compatibility != CK::Benign) \
6637 CGOpts.Name = static_cast<unsigned>(Record[Idx++]);
6638#define ENUM_CODEGENOPT(Name, Type, Bits, Default, Compatibility) \
6639 if constexpr (CK::Compatibility != CK::Benign) \
6640 CGOpts.set##Name(static_cast<clang::CodeGenOptions::Type>(Record[Idx++]));
6641#define DEBUGOPT(Name, Bits, Default, Compatibility)
6642#define VALUE_DEBUGOPT(Name, Bits, Default, Compatibility)
6643#define ENUM_DEBUGOPT(Name, Type, Bits, Default, Compatibility)
6644#include "clang/Basic/CodeGenOptions.def"
6645
6646 return Listener.ReadCodeGenOptions(CGOpts, ModuleFilename, Complain,
6647 AllowCompatibleDifferences);
6648}
6649
6650bool ASTReader::ParseTargetOptions(const RecordData &Record,
6651 StringRef ModuleFilename, bool Complain,
6652 ASTReaderListener &Listener,
6653 bool AllowCompatibleDifferences) {
6654 unsigned Idx = 0;
6655 TargetOptions TargetOpts;
6656 TargetOpts.Triple = ReadString(Record, Idx);
6657 TargetOpts.CPU = ReadString(Record, Idx);
6658 TargetOpts.TuneCPU = ReadString(Record, Idx);
6659 TargetOpts.ABI = ReadString(Record, Idx);
6660 for (unsigned N = Record[Idx++]; N; --N) {
6661 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
6662 }
6663 for (unsigned N = Record[Idx++]; N; --N) {
6664 TargetOpts.Features.push_back(ReadString(Record, Idx));
6665 }
6666
6667 return Listener.ReadTargetOptions(TargetOpts, ModuleFilename, Complain,
6668 AllowCompatibleDifferences);
6669}
6670
6671bool ASTReader::ParseDiagnosticOptions(const RecordData &Record,
6672 StringRef ModuleFilename, bool Complain,
6673 ASTReaderListener &Listener) {
6674 DiagnosticOptions DiagOpts;
6675 unsigned Idx = 0;
6676#define DIAGOPT(Name, Bits, Default) DiagOpts.Name = Record[Idx++];
6677#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
6678 DiagOpts.set##Name(static_cast<Type>(Record[Idx++]));
6679#include "clang/Basic/DiagnosticOptions.def"
6680
6681 for (unsigned N = Record[Idx++]; N; --N)
6682 DiagOpts.Warnings.push_back(ReadString(Record, Idx));
6683 for (unsigned N = Record[Idx++]; N; --N)
6684 DiagOpts.Remarks.push_back(ReadString(Record, Idx));
6685
6686 return Listener.ReadDiagnosticOptions(DiagOpts, ModuleFilename, Complain);
6687}
6688
6689bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
6690 ASTReaderListener &Listener) {
6691 FileSystemOptions FSOpts;
6692 unsigned Idx = 0;
6693 FSOpts.WorkingDir = ReadString(Record, Idx);
6694 return Listener.ReadFileSystemOptions(FSOpts, Complain);
6695}
6696
6697bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
6698 StringRef ModuleFilename,
6699 bool Complain,
6700 ASTReaderListener &Listener) {
6701 HeaderSearchOptions HSOpts;
6702 unsigned Idx = 0;
6703 HSOpts.Sysroot = ReadString(Record, Idx);
6704
6705 HSOpts.ResourceDir = ReadString(Record, Idx);
6706 HSOpts.ModuleCachePath = ReadString(Record, Idx);
6707 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
6708 HSOpts.DisableModuleHash = Record[Idx++];
6709 HSOpts.ImplicitModuleMaps = Record[Idx++];
6710 HSOpts.ModuleMapFileHomeIsCwd = Record[Idx++];
6711 HSOpts.EnablePrebuiltImplicitModules = Record[Idx++];
6712 HSOpts.UseBuiltinIncludes = Record[Idx++];
6713 HSOpts.UseStandardSystemIncludes = Record[Idx++];
6714 HSOpts.UseStandardCXXIncludes = Record[Idx++];
6715 HSOpts.UseLibcxx = Record[Idx++];
6716 std::string ContextHash = ReadString(Record, Idx);
6717
6718 return Listener.ReadHeaderSearchOptions(HSOpts, ModuleFilename, ContextHash,
6719 Complain);
6720}
6721
6722bool ASTReader::ParseHeaderSearchPaths(const RecordData &Record, bool Complain,
6723 ASTReaderListener &Listener) {
6724 HeaderSearchOptions HSOpts;
6725 unsigned Idx = 0;
6726
6727 // Include entries.
6728 for (unsigned N = Record[Idx++]; N; --N) {
6729 std::string Path = ReadString(Record, Idx);
6731 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
6732 bool IsFramework = Record[Idx++];
6733 bool IgnoreSysRoot = Record[Idx++];
6734 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
6735 IgnoreSysRoot);
6736 }
6737
6738 // System header prefixes.
6739 for (unsigned N = Record[Idx++]; N; --N) {
6740 std::string Prefix = ReadString(Record, Idx);
6741 bool IsSystemHeader = Record[Idx++];
6742 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
6743 }
6744
6745 // VFS overlay files.
6746 for (unsigned N = Record[Idx++]; N; --N) {
6747 std::string VFSOverlayFile = ReadString(Record, Idx);
6748 HSOpts.VFSOverlayFiles.emplace_back(std::move(VFSOverlayFile));
6749 }
6750
6751 return Listener.ReadHeaderSearchPaths(HSOpts, Complain);
6752}
6753
6754bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
6755 StringRef ModuleFilename,
6756 bool Complain,
6757 ASTReaderListener &Listener,
6758 std::string &SuggestedPredefines) {
6759 PreprocessorOptions PPOpts;
6760 unsigned Idx = 0;
6761
6762 // Macro definitions/undefs
6763 bool ReadMacros = Record[Idx++];
6764 if (ReadMacros) {
6765 for (unsigned N = Record[Idx++]; N; --N) {
6766 std::string Macro = ReadString(Record, Idx);
6767 bool IsUndef = Record[Idx++];
6768 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
6769 }
6770 }
6771
6772 // Includes
6773 for (unsigned N = Record[Idx++]; N; --N) {
6774 PPOpts.Includes.push_back(ReadString(Record, Idx));
6775 }
6776
6777 // Macro Includes
6778 for (unsigned N = Record[Idx++]; N; --N) {
6779 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
6780 }
6781
6782 PPOpts.UsePredefines = Record[Idx++];
6783 PPOpts.DetailedRecord = Record[Idx++];
6784 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
6786 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
6787 SuggestedPredefines.clear();
6788 return Listener.ReadPreprocessorOptions(PPOpts, ModuleFilename, ReadMacros,
6789 Complain, SuggestedPredefines);
6790}
6791
6792std::pair<ModuleFile *, unsigned>
6793ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
6794 GlobalPreprocessedEntityMapType::iterator
6795 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
6796 assert(I != GlobalPreprocessedEntityMap.end() &&
6797 "Corrupted global preprocessed entity map");
6798 ModuleFile *M = I->second;
6799 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
6800 return std::make_pair(M, LocalIndex);
6801}
6802
6803llvm::iterator_range<PreprocessingRecord::iterator>
6804ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
6805 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
6806 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
6808
6809 return llvm::make_range(PreprocessingRecord::iterator(),
6810 PreprocessingRecord::iterator());
6811}
6812
6813bool ASTReader::canRecoverFromOutOfDate(StringRef ModuleFileName,
6814 unsigned int ClientLoadCapabilities) {
6815 return ClientLoadCapabilities & ARR_OutOfDate &&
6816 !getModuleManager()
6817 .getModuleCache()
6818 .getInMemoryModuleCache()
6819 .isPCMFinal(ModuleFileName);
6820}
6821
6822llvm::iterator_range<ASTReader::ModuleDeclIterator>
6824 return llvm::make_range(
6825 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
6826 ModuleDeclIterator(this, &Mod,
6828}
6829
6831 auto I = GlobalSkippedRangeMap.find(GlobalIndex);
6832 assert(I != GlobalSkippedRangeMap.end() &&
6833 "Corrupted global skipped range map");
6834 ModuleFile *M = I->second;
6835 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedSkippedRangeID;
6836 assert(LocalIndex < M->NumPreprocessedSkippedRanges);
6837 PPSkippedRange RawRange = M->PreprocessedSkippedRangeOffsets[LocalIndex];
6838 SourceRange Range(ReadSourceLocation(*M, RawRange.getBegin()),
6839 ReadSourceLocation(*M, RawRange.getEnd()));
6840 assert(Range.isValid());
6841 return Range;
6842}
6843
6844unsigned
6845ASTReader::translatePreprocessedEntityIDToIndex(PreprocessedEntityID ID) const {
6846 unsigned ModuleFileIndex = ID >> 32;
6847 assert(ModuleFileIndex && "not translating loaded MacroID?");
6848 assert(getModuleManager().size() > ModuleFileIndex - 1);
6849 ModuleFile &MF = getModuleManager()[ModuleFileIndex - 1];
6850
6851 ID &= llvm::maskTrailingOnes<PreprocessedEntityID>(32);
6852 return MF.BasePreprocessedEntityID + ID;
6853}
6854
6856 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
6857 ModuleFile &M = *PPInfo.first;
6858 unsigned LocalIndex = PPInfo.second;
6860 (static_cast<PreprocessedEntityID>(M.Index + 1) << 32) | LocalIndex;
6861 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
6862
6863 if (!PP.getPreprocessingRecord()) {
6864 Error("no preprocessing record");
6865 return nullptr;
6866 }
6867
6869 if (llvm::Error Err = M.PreprocessorDetailCursor.JumpToBit(
6870 M.MacroOffsetsBase + PPOffs.getOffset())) {
6871 Error(std::move(Err));
6872 return nullptr;
6873 }
6874
6876 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
6877 if (!MaybeEntry) {
6878 Error(MaybeEntry.takeError());
6879 return nullptr;
6880 }
6881 llvm::BitstreamEntry Entry = MaybeEntry.get();
6882
6883 if (Entry.Kind != llvm::BitstreamEntry::Record)
6884 return nullptr;
6885
6886 // Read the record.
6887 SourceRange Range(ReadSourceLocation(M, PPOffs.getBegin()),
6888 ReadSourceLocation(M, PPOffs.getEnd()));
6889 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
6890 StringRef Blob;
6892 Expected<unsigned> MaybeRecType =
6893 M.PreprocessorDetailCursor.readRecord(Entry.ID, Record, &Blob);
6894 if (!MaybeRecType) {
6895 Error(MaybeRecType.takeError());
6896 return nullptr;
6897 }
6898 switch ((PreprocessorDetailRecordTypes)MaybeRecType.get()) {
6899 case PPD_MACRO_EXPANSION: {
6900 bool isBuiltin = Record[0];
6901 IdentifierInfo *Name = nullptr;
6902 MacroDefinitionRecord *Def = nullptr;
6903 if (isBuiltin)
6904 Name = getLocalIdentifier(M, Record[1]);
6905 else {
6906 PreprocessedEntityID GlobalID =
6908 unsigned Index = translatePreprocessedEntityIDToIndex(GlobalID);
6909 Def =
6910 cast<MacroDefinitionRecord>(PPRec.getLoadedPreprocessedEntity(Index));
6911 }
6912
6913 MacroExpansion *ME;
6914 if (isBuiltin)
6915 ME = new (PPRec) MacroExpansion(Name, Range);
6916 else
6917 ME = new (PPRec) MacroExpansion(Def, Range);
6918
6919 return ME;
6920 }
6921
6922 case PPD_MACRO_DEFINITION: {
6923 // Decode the identifier info and then check again; if the macro is
6924 // still defined and associated with the identifier,
6926 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
6927
6928 if (DeserializationListener)
6929 DeserializationListener->MacroDefinitionRead(PPID, MD);
6930
6931 return MD;
6932 }
6933
6935 const char *FullFileNameStart = Blob.data() + Record[0];
6936 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
6938 if (!FullFileName.empty())
6939 File = PP.getFileManager().getOptionalFileRef(FullFileName);
6940
6941 // FIXME: Stable encoding
6943 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
6945 = new (PPRec) InclusionDirective(PPRec, Kind,
6946 StringRef(Blob.data(), Record[0]),
6947 Record[1], Record[3],
6948 File,
6949 Range);
6950 return ID;
6951 }
6952 }
6953
6954 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
6955}
6956
6957/// Find the next module that contains entities and return the ID
6958/// of the first entry.
6959///
6960/// \param SLocMapI points at a chunk of a module that contains no
6961/// preprocessed entities or the entities it contains are not the ones we are
6962/// looking for.
6963unsigned ASTReader::findNextPreprocessedEntity(
6964 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
6965 ++SLocMapI;
6966 for (GlobalSLocOffsetMapType::const_iterator
6967 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
6968 ModuleFile &M = *SLocMapI->second;
6970 return M.BasePreprocessedEntityID;
6971 }
6972
6973 return getTotalNumPreprocessedEntities();
6974}
6975
6976namespace {
6977
6978struct PPEntityComp {
6979 const ASTReader &Reader;
6980 ModuleFile &M;
6981
6982 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) {}
6983
6984 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
6985 SourceLocation LHS = getLoc(L);
6986 SourceLocation RHS = getLoc(R);
6987 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6988 }
6989
6990 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
6991 SourceLocation LHS = getLoc(L);
6992 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6993 }
6994
6995 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
6996 SourceLocation RHS = getLoc(R);
6997 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6998 }
6999
7000 SourceLocation getLoc(const PPEntityOffset &PPE) const {
7001 return Reader.ReadSourceLocation(M, PPE.getBegin());
7002 }
7003};
7004
7005} // namespace
7006
7007unsigned ASTReader::findPreprocessedEntity(SourceLocation Loc,
7008 bool EndsAfter) const {
7009 if (SourceMgr.isLocalSourceLocation(Loc))
7010 return getTotalNumPreprocessedEntities();
7011
7012 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
7013 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
7014 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
7015 "Corrupted global sloc offset map");
7016
7017 if (SLocMapI->second->NumPreprocessedEntities == 0)
7018 return findNextPreprocessedEntity(SLocMapI);
7019
7020 ModuleFile &M = *SLocMapI->second;
7021
7022 using pp_iterator = const PPEntityOffset *;
7023
7024 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
7025 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
7026
7027 size_t Count = M.NumPreprocessedEntities;
7028 size_t Half;
7029 pp_iterator First = pp_begin;
7030 pp_iterator PPI;
7031
7032 if (EndsAfter) {
7033 PPI = std::upper_bound(pp_begin, pp_end, Loc,
7034 PPEntityComp(*this, M));
7035 } else {
7036 // Do a binary search manually instead of using std::lower_bound because
7037 // The end locations of entities may be unordered (when a macro expansion
7038 // is inside another macro argument), but for this case it is not important
7039 // whether we get the first macro expansion or its containing macro.
7040 while (Count > 0) {
7041 Half = Count / 2;
7042 PPI = First;
7043 std::advance(PPI, Half);
7044 if (SourceMgr.isBeforeInTranslationUnit(
7045 ReadSourceLocation(M, PPI->getEnd()), Loc)) {
7046 First = PPI;
7047 ++First;
7048 Count = Count - Half - 1;
7049 } else
7050 Count = Half;
7051 }
7052 }
7053
7054 if (PPI == pp_end)
7055 return findNextPreprocessedEntity(SLocMapI);
7056
7057 return M.BasePreprocessedEntityID + (PPI - pp_begin);
7058}
7059
7060/// Returns a pair of [Begin, End) indices of preallocated
7061/// preprocessed entities that \arg Range encompasses.
7062std::pair<unsigned, unsigned>
7064 if (Range.isInvalid())
7065 return std::make_pair(0,0);
7066 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
7067
7068 unsigned BeginID = findPreprocessedEntity(Range.getBegin(), false);
7069 unsigned EndID = findPreprocessedEntity(Range.getEnd(), true);
7070 return std::make_pair(BeginID, EndID);
7071}
7072
7073/// Optionally returns true or false if the preallocated preprocessed
7074/// entity with index \arg Index came from file \arg FID.
7075std::optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
7076 FileID FID) {
7077 if (FID.isInvalid())
7078 return false;
7079
7080 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
7081 ModuleFile &M = *PPInfo.first;
7082 unsigned LocalIndex = PPInfo.second;
7083 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
7084
7085 SourceLocation Loc = ReadSourceLocation(M, PPOffs.getBegin());
7086 if (Loc.isInvalid())
7087 return false;
7088
7089 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
7090 return true;
7091 else
7092 return false;
7093}
7094
7095namespace {
7096
7097 /// Visitor used to search for information about a header file.
7098 class HeaderFileInfoVisitor {
7099 FileEntryRef FE;
7100 std::optional<HeaderFileInfo> HFI;
7101
7102 public:
7103 explicit HeaderFileInfoVisitor(FileEntryRef FE) : FE(FE) {}
7104
7105 bool operator()(ModuleFile &M) {
7108 if (!Table)
7109 return false;
7110
7111 // Look in the on-disk hash table for an entry for this file name.
7112 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
7113 if (Pos == Table->end())
7114 return false;
7115
7116 HFI = *Pos;
7117 return true;
7118 }
7119
7120 std::optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
7121 };
7122
7123} // namespace
7124
7126 HeaderFileInfoVisitor Visitor(FE);
7127 ModuleMgr.visit(Visitor);
7128 if (std::optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
7129 return *HFI;
7130
7131 return HeaderFileInfo();
7132}
7133
7135 using DiagState = DiagnosticsEngine::DiagState;
7137
7138 for (ModuleFile &F : ModuleMgr) {
7139 unsigned Idx = 0;
7140 auto &Record = F.PragmaDiagMappings;
7141 if (Record.empty())
7142 continue;
7143
7144 DiagStates.clear();
7145
7146 auto ReadDiagState = [&](const DiagState &BasedOn,
7147 bool IncludeNonPragmaStates) {
7148 unsigned BackrefID = Record[Idx++];
7149 if (BackrefID != 0)
7150 return DiagStates[BackrefID - 1];
7151
7152 // A new DiagState was created here.
7153 Diag.DiagStates.push_back(BasedOn);
7154 DiagState *NewState = &Diag.DiagStates.back();
7155 DiagStates.push_back(NewState);
7156 unsigned Size = Record[Idx++];
7157 assert(Idx + Size * 2 <= Record.size() &&
7158 "Invalid data, not enough diag/map pairs");
7159 while (Size--) {
7160 unsigned DiagID = Record[Idx++];
7161 DiagnosticMapping NewMapping =
7163 if (!NewMapping.isPragma() && !IncludeNonPragmaStates)
7164 continue;
7165
7166 DiagnosticMapping &Mapping = NewState->getOrAddMapping(DiagID);
7167
7168 // If this mapping was specified as a warning but the severity was
7169 // upgraded due to diagnostic settings, simulate the current diagnostic
7170 // settings (and use a warning).
7171 if (NewMapping.wasUpgradedFromWarning() && !Mapping.isErrorOrFatal()) {
7173 NewMapping.setUpgradedFromWarning(false);
7174 }
7175
7176 Mapping = NewMapping;
7177 }
7178 return NewState;
7179 };
7180
7181 // Read the first state.
7182 DiagState *FirstState;
7183 if (F.Kind == MK_ImplicitModule) {
7184 // Implicitly-built modules are reused with different diagnostic
7185 // settings. Use the initial diagnostic state from Diag to simulate this
7186 // compilation's diagnostic settings.
7187 FirstState = Diag.DiagStatesByLoc.FirstDiagState;
7188 DiagStates.push_back(FirstState);
7189
7190 // Skip the initial diagnostic state from the serialized module.
7191 assert(Record[1] == 0 &&
7192 "Invalid data, unexpected backref in initial state");
7193 Idx = 3 + Record[2] * 2;
7194 assert(Idx < Record.size() &&
7195 "Invalid data, not enough state change pairs in initial state");
7196 } else if (F.isModule()) {
7197 // For an explicit module, preserve the flags from the module build
7198 // command line (-w, -Weverything, -Werror, ...) along with any explicit
7199 // -Wblah flags.
7200 unsigned Flags = Record[Idx++];
7201 DiagState Initial(*Diag.getDiagnosticIDs());
7202 Initial.SuppressSystemWarnings = Flags & 1; Flags >>= 1;
7203 Initial.ErrorsAsFatal = Flags & 1; Flags >>= 1;
7204 Initial.WarningsAsErrors = Flags & 1; Flags >>= 1;
7205 Initial.EnableAllWarnings = Flags & 1; Flags >>= 1;
7206 Initial.IgnoreAllWarnings = Flags & 1; Flags >>= 1;
7207 Initial.ExtBehavior = (diag::Severity)Flags;
7208 FirstState = ReadDiagState(Initial, true);
7209
7210 assert(F.OriginalSourceFileID.isValid());
7211
7212 // Set up the root buffer of the module to start with the initial
7213 // diagnostic state of the module itself, to cover files that contain no
7214 // explicit transitions (for which we did not serialize anything).
7215 Diag.DiagStatesByLoc.Files[F.OriginalSourceFileID]
7216 .StateTransitions.push_back({FirstState, 0});
7217 } else {
7218 // For prefix ASTs, start with whatever the user configured on the
7219 // command line.
7220 Idx++; // Skip flags.
7221 FirstState = ReadDiagState(*Diag.DiagStatesByLoc.CurDiagState, false);
7222 }
7223
7224 // Read the state transitions.
7225 unsigned NumLocations = Record[Idx++];
7226 while (NumLocations--) {
7227 assert(Idx < Record.size() &&
7228 "Invalid data, missing pragma diagnostic states");
7229 FileID FID = ReadFileID(F, Record, Idx);
7230 assert(FID.isValid() && "invalid FileID for transition");
7231 unsigned Transitions = Record[Idx++];
7232
7233 // Note that we don't need to set up Parent/ParentOffset here, because
7234 // we won't be changing the diagnostic state within imported FileIDs
7235 // (other than perhaps appending to the main source file, which has no
7236 // parent).
7237 auto &F = Diag.DiagStatesByLoc.Files[FID];
7238 F.StateTransitions.reserve(F.StateTransitions.size() + Transitions);
7239 for (unsigned I = 0; I != Transitions; ++I) {
7240 unsigned Offset = Record[Idx++];
7241 auto *State = ReadDiagState(*FirstState, false);
7242 F.StateTransitions.push_back({State, Offset});
7243 }
7244 }
7245
7246 // Read the final state.
7247 assert(Idx < Record.size() &&
7248 "Invalid data, missing final pragma diagnostic state");
7249 SourceLocation CurStateLoc = ReadSourceLocation(F, Record[Idx++]);
7250 auto *CurState = ReadDiagState(*FirstState, false);
7251
7252 if (!F.isModule()) {
7253 Diag.DiagStatesByLoc.CurDiagState = CurState;
7254 Diag.DiagStatesByLoc.CurDiagStateLoc = CurStateLoc;
7255
7256 // Preserve the property that the imaginary root file describes the
7257 // current state.
7258 FileID NullFile;
7259 auto &T = Diag.DiagStatesByLoc.Files[NullFile].StateTransitions;
7260 if (T.empty())
7261 T.push_back({CurState, 0});
7262 else
7263 T[0].State = CurState;
7264 }
7265
7266 // Don't try to read these mappings again.
7267 Record.clear();
7268 }
7269}
7270
7271/// Get the correct cursor and offset for loading a type.
7272ASTReader::RecordLocation ASTReader::TypeCursorForIndex(TypeID ID) {
7273 auto [M, Index] = translateTypeIDToIndex(ID);
7274 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex].get() +
7276}
7277
7278static std::optional<Type::TypeClass> getTypeClassForCode(TypeCode code) {
7279 switch (code) {
7280#define TYPE_BIT_CODE(CLASS_ID, CODE_ID, CODE_VALUE) \
7281 case TYPE_##CODE_ID: return Type::CLASS_ID;
7282#include "clang/Serialization/TypeBitCodes.def"
7283 default:
7284 return std::nullopt;
7285 }
7286}
7287
7288/// Read and return the type with the given index..
7289///
7290/// The index is the type ID, shifted and minus the number of predefs. This
7291/// routine actually reads the record corresponding to the type at the given
7292/// location. It is a helper routine for GetType, which deals with reading type
7293/// IDs.
7294QualType ASTReader::readTypeRecord(TypeID ID) {
7295 assert(ContextObj && "reading type with no AST context");
7296 ASTContext &Context = *ContextObj;
7297 RecordLocation Loc = TypeCursorForIndex(ID);
7298 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
7299
7300 // Keep track of where we are in the stream, then jump back there
7301 // after reading this type.
7302 SavedStreamPosition SavedPosition(DeclsCursor);
7303
7304 ReadingKindTracker ReadingKind(Read_Type, *this);
7305
7306 // Note that we are loading a type record.
7307 Deserializing AType(this);
7308
7309 if (llvm::Error Err = DeclsCursor.JumpToBit(Loc.Offset)) {
7310 Error(std::move(Err));
7311 return QualType();
7312 }
7313 Expected<unsigned> RawCode = DeclsCursor.ReadCode();
7314 if (!RawCode) {
7315 Error(RawCode.takeError());
7316 return QualType();
7317 }
7318
7319 ASTRecordReader Record(*this, *Loc.F);
7320 Expected<unsigned> Code = Record.readRecord(DeclsCursor, RawCode.get());
7321 if (!Code) {
7322 Error(Code.takeError());
7323 return QualType();
7324 }
7325 if (Code.get() == TYPE_EXT_QUAL) {
7326 QualType baseType = Record.readQualType();
7327 Qualifiers quals = Record.readQualifiers();
7328 return Context.getQualifiedType(baseType, quals);
7329 }
7330
7331 auto maybeClass = getTypeClassForCode((TypeCode) Code.get());
7332 if (!maybeClass) {
7333 Error("Unexpected code for type");
7334 return QualType();
7335 }
7336
7337 serialization::AbstractTypeReader<ASTRecordReader> TypeReader(Record);
7338 return TypeReader.read(*maybeClass);
7339}
7340
7341namespace clang {
7342
7343class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
7344 ASTRecordReader &Reader;
7345
7346 SourceLocation readSourceLocation() { return Reader.readSourceLocation(); }
7347 SourceRange readSourceRange() { return Reader.readSourceRange(); }
7348
7349 TypeSourceInfo *GetTypeSourceInfo() {
7350 return Reader.readTypeSourceInfo();
7351 }
7352
7353 NestedNameSpecifierLoc ReadNestedNameSpecifierLoc() {
7354 return Reader.readNestedNameSpecifierLoc();
7355 }
7356
7357 Attr *ReadAttr() {
7358 return Reader.readAttr();
7359 }
7360
7361public:
7362 TypeLocReader(ASTRecordReader &Reader) : Reader(Reader) {}
7363
7364 // We want compile-time assurance that we've enumerated all of
7365 // these, so unfortunately we have to declare them first, then
7366 // define them out-of-line.
7367#define ABSTRACT_TYPELOC(CLASS, PARENT)
7368#define TYPELOC(CLASS, PARENT) \
7369 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
7370#include "clang/AST/TypeLocNodes.def"
7371
7374 void VisitTagTypeLoc(TagTypeLoc TL);
7375};
7376
7377} // namespace clang
7378
7379void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
7380 // nothing to do
7381}
7382
7383void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
7384 TL.setBuiltinLoc(readSourceLocation());
7385 if (TL.needsExtraLocalData()) {
7386 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Reader.readInt()));
7387 TL.setWrittenSignSpec(static_cast<TypeSpecifierSign>(Reader.readInt()));
7388 TL.setWrittenWidthSpec(static_cast<TypeSpecifierWidth>(Reader.readInt()));
7389 TL.setModeAttr(Reader.readInt());
7390 }
7391}
7392
7393void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
7394 TL.setNameLoc(readSourceLocation());
7395}
7396
7397void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
7398 TL.setStarLoc(readSourceLocation());
7399}
7400
7401void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
7402 // nothing to do
7403}
7404
7405void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
7406 // nothing to do
7407}
7408
7409void TypeLocReader::VisitArrayParameterTypeLoc(ArrayParameterTypeLoc TL) {
7410 // nothing to do
7411}
7412
7413void TypeLocReader::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
7414 TL.setExpansionLoc(readSourceLocation());
7415}
7416
7417void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
7418 TL.setCaretLoc(readSourceLocation());
7419}
7420
7421void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
7422 TL.setAmpLoc(readSourceLocation());
7423}
7424
7425void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
7426 TL.setAmpAmpLoc(readSourceLocation());
7427}
7428
7429void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
7430 TL.setStarLoc(readSourceLocation());
7431 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
7432}
7433
7435 TL.setLBracketLoc(readSourceLocation());
7436 TL.setRBracketLoc(readSourceLocation());
7437 if (Reader.readBool())
7438 TL.setSizeExpr(Reader.readExpr());
7439 else
7440 TL.setSizeExpr(nullptr);
7441}
7442
7443void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
7444 VisitArrayTypeLoc(TL);
7445}
7446
7447void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
7448 VisitArrayTypeLoc(TL);
7449}
7450
7451void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
7452 VisitArrayTypeLoc(TL);
7453}
7454
7455void TypeLocReader::VisitDependentSizedArrayTypeLoc(
7456 DependentSizedArrayTypeLoc TL) {
7457 VisitArrayTypeLoc(TL);
7458}
7459
7460void TypeLocReader::VisitDependentAddressSpaceTypeLoc(
7461 DependentAddressSpaceTypeLoc TL) {
7462
7463 TL.setAttrNameLoc(readSourceLocation());
7464 TL.setAttrOperandParensRange(readSourceRange());
7465 TL.setAttrExprOperand(Reader.readExpr());
7466}
7467
7468void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
7469 DependentSizedExtVectorTypeLoc TL) {
7470 TL.setNameLoc(readSourceLocation());
7471}
7472
7473void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
7474 TL.setNameLoc(readSourceLocation());
7475}
7476
7477void TypeLocReader::VisitDependentVectorTypeLoc(
7478 DependentVectorTypeLoc TL) {
7479 TL.setNameLoc(readSourceLocation());
7480}
7481
7482void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
7483 TL.setNameLoc(readSourceLocation());
7484}
7485
7486void TypeLocReader::VisitConstantMatrixTypeLoc(ConstantMatrixTypeLoc TL) {
7487 TL.setAttrNameLoc(readSourceLocation());
7488 TL.setAttrOperandParensRange(readSourceRange());
7489 TL.setAttrRowOperand(Reader.readExpr());
7490 TL.setAttrColumnOperand(Reader.readExpr());
7491}
7492
7493void TypeLocReader::VisitDependentSizedMatrixTypeLoc(
7494 DependentSizedMatrixTypeLoc TL) {
7495 TL.setAttrNameLoc(readSourceLocation());
7496 TL.setAttrOperandParensRange(readSourceRange());
7497 TL.setAttrRowOperand(Reader.readExpr());
7498 TL.setAttrColumnOperand(Reader.readExpr());
7499}
7500
7502 TL.setLocalRangeBegin(readSourceLocation());
7503 TL.setLParenLoc(readSourceLocation());
7504 TL.setRParenLoc(readSourceLocation());
7505 TL.setExceptionSpecRange(readSourceRange());
7506 TL.setLocalRangeEnd(readSourceLocation());
7507 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
7508 TL.setParam(i, Reader.readDeclAs<ParmVarDecl>());
7509 }
7510}
7511
7512void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
7513 VisitFunctionTypeLoc(TL);
7514}
7515
7516void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
7517 VisitFunctionTypeLoc(TL);
7518}
7519
7520void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
7521 SourceLocation ElaboratedKeywordLoc = readSourceLocation();
7522 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc();
7523 SourceLocation NameLoc = readSourceLocation();
7524 TL.set(ElaboratedKeywordLoc, QualifierLoc, NameLoc);
7525}
7526
7527void TypeLocReader::VisitUsingTypeLoc(UsingTypeLoc TL) {
7528 SourceLocation ElaboratedKeywordLoc = readSourceLocation();
7529 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc();
7530 SourceLocation NameLoc = readSourceLocation();
7531 TL.set(ElaboratedKeywordLoc, QualifierLoc, NameLoc);
7532}
7533
7534void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
7535 SourceLocation ElaboratedKeywordLoc = readSourceLocation();
7536 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc();
7537 SourceLocation NameLoc = readSourceLocation();
7538 TL.set(ElaboratedKeywordLoc, QualifierLoc, NameLoc);
7539}
7540
7541void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
7542 TL.setTypeofLoc(readSourceLocation());
7543 TL.setLParenLoc(readSourceLocation());
7544 TL.setRParenLoc(readSourceLocation());
7545}
7546
7547void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
7548 TL.setTypeofLoc(readSourceLocation());
7549 TL.setLParenLoc(readSourceLocation());
7550 TL.setRParenLoc(readSourceLocation());
7551 TL.setUnmodifiedTInfo(GetTypeSourceInfo());
7552}
7553
7554void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
7555 TL.setDecltypeLoc(readSourceLocation());
7556 TL.setRParenLoc(readSourceLocation());
7557}
7558
7559void TypeLocReader::VisitPackIndexingTypeLoc(PackIndexingTypeLoc TL) {
7560 TL.setEllipsisLoc(readSourceLocation());
7561}
7562
7563void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
7564 TL.setKWLoc(readSourceLocation());
7565 TL.setLParenLoc(readSourceLocation());
7566 TL.setRParenLoc(readSourceLocation());
7567 TL.setUnderlyingTInfo(GetTypeSourceInfo());
7568}
7569
7571 auto NNS = readNestedNameSpecifierLoc();
7572 auto TemplateKWLoc = readSourceLocation();
7573 auto ConceptNameLoc = readDeclarationNameInfo();
7574 auto FoundDecl = readDeclAs<NamedDecl>();
7575 auto NamedConcept = readDeclAs<ConceptDecl>();
7576 auto *CR = ConceptReference::Create(
7577 getContext(), NNS, TemplateKWLoc, ConceptNameLoc, FoundDecl, NamedConcept,
7578 (readBool() ? readASTTemplateArgumentListInfo() : nullptr));
7579 return CR;
7580}
7581
7582void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
7583 TL.setNameLoc(readSourceLocation());
7584 if (Reader.readBool())
7585 TL.setConceptReference(Reader.readConceptReference());
7586 if (Reader.readBool())
7587 TL.setRParenLoc(readSourceLocation());
7588}
7589
7590void TypeLocReader::VisitDeducedTemplateSpecializationTypeLoc(
7592 TL.setElaboratedKeywordLoc(readSourceLocation());
7593 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
7594 TL.setTemplateNameLoc(readSourceLocation());
7595}
7596
7598 TL.setElaboratedKeywordLoc(readSourceLocation());
7599 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
7600 TL.setNameLoc(readSourceLocation());
7601}
7602
7603void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
7604 VisitTagTypeLoc(TL);
7605}
7606
7607void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
7608 VisitTagTypeLoc(TL);
7609}
7610
7611void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) { VisitTagTypeLoc(TL); }
7612
7613void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
7614 TL.setAttr(ReadAttr());
7615}
7616
7617void TypeLocReader::VisitCountAttributedTypeLoc(CountAttributedTypeLoc TL) {
7618 // Nothing to do
7619}
7620
7621void TypeLocReader::VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) {
7622 // Nothing to do.
7623}
7624
7625void TypeLocReader::VisitOverflowBehaviorTypeLoc(OverflowBehaviorTypeLoc TL) {
7626 TL.setAttrLoc(readSourceLocation());
7627}
7628
7629void TypeLocReader::VisitHLSLAttributedResourceTypeLoc(
7630 HLSLAttributedResourceTypeLoc TL) {
7631 // Nothing to do.
7632}
7633
7634void TypeLocReader::VisitHLSLInlineSpirvTypeLoc(HLSLInlineSpirvTypeLoc TL) {
7635 // Nothing to do.
7636}
7637
7638void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
7639 TL.setNameLoc(readSourceLocation());
7640}
7641
7642void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
7643 SubstTemplateTypeParmTypeLoc TL) {
7644 TL.setNameLoc(readSourceLocation());
7645}
7646
7647void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
7648 SubstTemplateTypeParmPackTypeLoc TL) {
7649 TL.setNameLoc(readSourceLocation());
7650}
7651
7652void TypeLocReader::VisitSubstBuiltinTemplatePackTypeLoc(
7653 SubstBuiltinTemplatePackTypeLoc TL) {
7654 TL.setNameLoc(readSourceLocation());
7655}
7656
7657void TypeLocReader::VisitTemplateSpecializationTypeLoc(
7658 TemplateSpecializationTypeLoc TL) {
7659 SourceLocation ElaboratedKeywordLoc = readSourceLocation();
7660 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc();
7661 SourceLocation TemplateKeywordLoc = readSourceLocation();
7662 SourceLocation NameLoc = readSourceLocation();
7663 SourceLocation LAngleLoc = readSourceLocation();
7664 SourceLocation RAngleLoc = readSourceLocation();
7665 TL.set(ElaboratedKeywordLoc, QualifierLoc, TemplateKeywordLoc, NameLoc,
7666 LAngleLoc, RAngleLoc);
7667 MutableArrayRef<TemplateArgumentLocInfo> Args = TL.getArgLocInfos();
7668 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
7669 Args[I] = Reader.readTemplateArgumentLocInfo(
7670 TL.getTypePtr()->template_arguments()[I].getKind());
7671}
7672
7673void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
7674 TL.setLParenLoc(readSourceLocation());
7675 TL.setRParenLoc(readSourceLocation());
7676}
7677
7678void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
7679 TL.setElaboratedKeywordLoc(readSourceLocation());
7680 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
7681 TL.setNameLoc(readSourceLocation());
7682}
7683
7684void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
7685 TL.setEllipsisLoc(readSourceLocation());
7686}
7687
7688void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
7689 TL.setNameLoc(readSourceLocation());
7690 TL.setNameEndLoc(readSourceLocation());
7691}
7692
7693void TypeLocReader::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
7694 if (TL.getNumProtocols()) {
7695 TL.setProtocolLAngleLoc(readSourceLocation());
7696 TL.setProtocolRAngleLoc(readSourceLocation());
7697 }
7698 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
7699 TL.setProtocolLoc(i, readSourceLocation());
7700}
7701
7702void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
7703 TL.setHasBaseTypeAsWritten(Reader.readBool());
7704 TL.setTypeArgsLAngleLoc(readSourceLocation());
7705 TL.setTypeArgsRAngleLoc(readSourceLocation());
7706 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
7707 TL.setTypeArgTInfo(i, GetTypeSourceInfo());
7708 TL.setProtocolLAngleLoc(readSourceLocation());
7709 TL.setProtocolRAngleLoc(readSourceLocation());
7710 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
7711 TL.setProtocolLoc(i, readSourceLocation());
7712}
7713
7714void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
7715 TL.setStarLoc(readSourceLocation());
7716}
7717
7718void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
7719 TL.setKWLoc(readSourceLocation());
7720 TL.setLParenLoc(readSourceLocation());
7721 TL.setRParenLoc(readSourceLocation());
7722}
7723
7724void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) {
7725 TL.setKWLoc(readSourceLocation());
7726}
7727
7728void TypeLocReader::VisitBitIntTypeLoc(clang::BitIntTypeLoc TL) {
7729 TL.setNameLoc(readSourceLocation());
7730}
7731
7732void TypeLocReader::VisitDependentBitIntTypeLoc(
7733 clang::DependentBitIntTypeLoc TL) {
7734 TL.setNameLoc(readSourceLocation());
7735}
7736
7737void TypeLocReader::VisitPredefinedSugarTypeLoc(PredefinedSugarTypeLoc TL) {
7738 // Nothing to do.
7739}
7740
7742 TypeLocReader TLR(*this);
7743 for (; !TL.isNull(); TL = TL.getNextTypeLoc())
7744 TLR.Visit(TL);
7745}
7746
7748 QualType InfoTy = readType();
7749 if (InfoTy.isNull())
7750 return nullptr;
7751
7752 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
7753 readTypeLoc(TInfo->getTypeLoc());
7754 return TInfo;
7755}
7756
7758 return (ID & llvm::maskTrailingOnes<TypeID>(32)) >> Qualifiers::FastWidth;
7759}
7760
7762 return ID >> 32;
7763}
7764
7766 // We don't need to erase the higher bits since if these bits are not 0,
7767 // it must be larger than NUM_PREDEF_TYPE_IDS.
7769}
7770
7771std::pair<ModuleFile *, unsigned>
7772ASTReader::translateTypeIDToIndex(serialization::TypeID ID) const {
7773 assert(!isPredefinedType(ID) &&
7774 "Predefined type shouldn't be in TypesLoaded");
7775 unsigned ModuleFileIndex = getModuleFileIndexForTypeID(ID);
7776 assert(ModuleFileIndex && "Untranslated Local Decl?");
7777
7778 ModuleFile *OwningModuleFile = &getModuleManager()[ModuleFileIndex - 1];
7779 assert(OwningModuleFile &&
7780 "untranslated type ID or local type ID shouldn't be in TypesLoaded");
7781
7782 return {OwningModuleFile,
7783 OwningModuleFile->BaseTypeIndex + getIndexForTypeID(ID)};
7784}
7785
7787 assert(ContextObj && "reading type with no AST context");
7788 ASTContext &Context = *ContextObj;
7789
7790 unsigned FastQuals = ID & Qualifiers::FastMask;
7791
7792 if (isPredefinedType(ID)) {
7793 QualType T;
7794 unsigned Index = getIndexForTypeID(ID);
7795 switch ((PredefinedTypeIDs)Index) {
7797 // We should never use this one.
7798 llvm_unreachable("Invalid predefined type");
7799 break;
7801 return QualType();
7803 T = Context.VoidTy;
7804 break;
7806 T = Context.BoolTy;
7807 break;
7810 // FIXME: Check that the signedness of CharTy is correct!
7811 T = Context.CharTy;
7812 break;
7814 T = Context.UnsignedCharTy;
7815 break;
7817 T = Context.UnsignedShortTy;
7818 break;
7820 T = Context.UnsignedIntTy;
7821 break;
7823 T = Context.UnsignedLongTy;
7824 break;
7826 T = Context.UnsignedLongLongTy;
7827 break;
7829 T = Context.UnsignedInt128Ty;
7830 break;
7832 T = Context.SignedCharTy;
7833 break;
7835 T = Context.WCharTy;
7836 break;
7838 T = Context.ShortTy;
7839 break;
7840 case PREDEF_TYPE_INT_ID:
7841 T = Context.IntTy;
7842 break;
7844 T = Context.LongTy;
7845 break;
7847 T = Context.LongLongTy;
7848 break;
7850 T = Context.Int128Ty;
7851 break;
7853 T = Context.BFloat16Ty;
7854 break;
7856 T = Context.HalfTy;
7857 break;
7859 T = Context.FloatTy;
7860 break;
7862 T = Context.DoubleTy;
7863 break;
7865 T = Context.LongDoubleTy;
7866 break;
7868 T = Context.ShortAccumTy;
7869 break;
7871 T = Context.AccumTy;
7872 break;
7874 T = Context.LongAccumTy;
7875 break;
7877 T = Context.UnsignedShortAccumTy;
7878 break;
7880 T = Context.UnsignedAccumTy;
7881 break;
7883 T = Context.UnsignedLongAccumTy;
7884 break;
7886 T = Context.ShortFractTy;
7887 break;
7889 T = Context.FractTy;
7890 break;
7892 T = Context.LongFractTy;
7893 break;
7895 T = Context.UnsignedShortFractTy;
7896 break;
7898 T = Context.UnsignedFractTy;
7899 break;
7901 T = Context.UnsignedLongFractTy;
7902 break;
7904 T = Context.SatShortAccumTy;
7905 break;
7907 T = Context.SatAccumTy;
7908 break;
7910 T = Context.SatLongAccumTy;
7911 break;
7913 T = Context.SatUnsignedShortAccumTy;
7914 break;
7916 T = Context.SatUnsignedAccumTy;
7917 break;
7919 T = Context.SatUnsignedLongAccumTy;
7920 break;
7922 T = Context.SatShortFractTy;
7923 break;
7925 T = Context.SatFractTy;
7926 break;
7928 T = Context.SatLongFractTy;
7929 break;
7931 T = Context.SatUnsignedShortFractTy;
7932 break;
7934 T = Context.SatUnsignedFractTy;
7935 break;
7937 T = Context.SatUnsignedLongFractTy;
7938 break;
7940 T = Context.Float16Ty;
7941 break;
7943 T = Context.Float128Ty;
7944 break;
7946 T = Context.Ibm128Ty;
7947 break;
7949 T = Context.OverloadTy;
7950 break;
7952 T = Context.UnresolvedTemplateTy;
7953 break;
7955 T = Context.BoundMemberTy;
7956 break;
7958 T = Context.PseudoObjectTy;
7959 break;
7961 T = Context.DependentTy;
7962 break;
7964 T = Context.UnknownAnyTy;
7965 break;
7967 T = Context.NullPtrTy;
7968 break;
7970 T = Context.Char8Ty;
7971 break;
7973 T = Context.Char16Ty;
7974 break;
7976 T = Context.Char32Ty;
7977 break;
7979 T = Context.ObjCBuiltinIdTy;
7980 break;
7982 T = Context.ObjCBuiltinClassTy;
7983 break;
7985 T = Context.ObjCBuiltinSelTy;
7986 break;
7987#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7988 case PREDEF_TYPE_##Id##_ID: \
7989 T = Context.SingletonId; \
7990 break;
7991#include "clang/Basic/OpenCLImageTypes.def"
7992#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
7993 case PREDEF_TYPE_##Id##_ID: \
7994 T = Context.Id##Ty; \
7995 break;
7996#include "clang/Basic/OpenCLExtensionTypes.def"
7998 T = Context.OCLSamplerTy;
7999 break;
8001 T = Context.OCLEventTy;
8002 break;
8004 T = Context.OCLClkEventTy;
8005 break;
8007 T = Context.OCLQueueTy;
8008 break;
8010 T = Context.OCLReserveIDTy;
8011 break;
8013 T = Context.getAutoDeductType();
8014 break;
8016 T = Context.getAutoRRefDeductType();
8017 break;
8019 T = Context.ARCUnbridgedCastTy;
8020 break;
8022 T = Context.BuiltinFnTy;
8023 break;
8025 T = Context.IncompleteMatrixIdxTy;
8026 break;
8028 T = Context.ArraySectionTy;
8029 break;
8031 T = Context.OMPArrayShapingTy;
8032 break;
8034 T = Context.OMPIteratorTy;
8035 break;
8036#define SVE_TYPE(Name, Id, SingletonId) \
8037 case PREDEF_TYPE_##Id##_ID: \
8038 T = Context.SingletonId; \
8039 break;
8040#include "clang/Basic/AArch64ACLETypes.def"
8041#define PPC_VECTOR_TYPE(Name, Id, Size) \
8042 case PREDEF_TYPE_##Id##_ID: \
8043 T = Context.Id##Ty; \
8044 break;
8045#include "clang/Basic/PPCTypes.def"
8046#define RVV_TYPE(Name, Id, SingletonId) \
8047 case PREDEF_TYPE_##Id##_ID: \
8048 T = Context.SingletonId; \
8049 break;
8050#include "clang/Basic/RISCVVTypes.def"
8051#define WASM_TYPE(Name, Id, SingletonId) \
8052 case PREDEF_TYPE_##Id##_ID: \
8053 T = Context.SingletonId; \
8054 break;
8055#include "clang/Basic/WebAssemblyReferenceTypes.def"
8056#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) \
8057 case PREDEF_TYPE_##Id##_ID: \
8058 T = Context.SingletonId; \
8059 break;
8060#include "clang/Basic/AMDGPUTypes.def"
8061#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
8062 case PREDEF_TYPE_##Id##_ID: \
8063 T = Context.SingletonId; \
8064 break;
8065#include "clang/Basic/HLSLIntangibleTypes.def"
8066 }
8067
8068 assert(!T.isNull() && "Unknown predefined type");
8069 return T.withFastQualifiers(FastQuals);
8070 }
8071
8072 unsigned Index = translateTypeIDToIndex(ID).second;
8073
8074 assert(Index < TypesLoaded.size() && "Type index out-of-range");
8075 if (TypesLoaded[Index].isNull()) {
8076 TypesLoaded[Index] = readTypeRecord(ID);
8077 if (TypesLoaded[Index].isNull())
8078 return QualType();
8079
8080 TypesLoaded[Index]->setFromAST();
8081 if (DeserializationListener)
8082 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
8083 TypesLoaded[Index]);
8084 }
8085
8086 return TypesLoaded[Index].withFastQualifiers(FastQuals);
8087}
8088
8090 return GetType(getGlobalTypeID(F, LocalID));
8091}
8092
8094 LocalTypeID LocalID) const {
8095 if (isPredefinedType(LocalID))
8096 return LocalID;
8097
8098 if (!F.ModuleOffsetMap.empty())
8099 ReadModuleOffsetMap(F);
8100
8101 unsigned ModuleFileIndex = getModuleFileIndexForTypeID(LocalID);
8102 LocalID &= llvm::maskTrailingOnes<TypeID>(32);
8103
8104 if (ModuleFileIndex == 0)
8106
8107 ModuleFile &MF =
8108 ModuleFileIndex ? *F.TransitiveImports[ModuleFileIndex - 1] : F;
8109 ModuleFileIndex = MF.Index + 1;
8110 return ((uint64_t)ModuleFileIndex << 32) | LocalID;
8111}
8112
8115 switch (Kind) {
8117 return readExpr();
8119 return readTypeSourceInfo();
8122 SourceLocation TemplateKWLoc = readSourceLocation();
8124 SourceLocation TemplateNameLoc = readSourceLocation();
8127 : SourceLocation();
8128 return TemplateArgumentLocInfo(getASTContext(), TemplateKWLoc, QualifierLoc,
8129 TemplateNameLoc, EllipsisLoc);
8130 }
8137 // FIXME: Is this right?
8138 return TemplateArgumentLocInfo();
8139 }
8140 llvm_unreachable("unexpected template argument loc");
8141}
8142
8152
8155 Result.setLAngleLoc(readSourceLocation());
8156 Result.setRAngleLoc(readSourceLocation());
8157 unsigned NumArgsAsWritten = readInt();
8158 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
8159 Result.addArgument(readTemplateArgumentLoc());
8160}
8161
8168
8170
8172 if (NumCurrentElementsDeserializing) {
8173 // We arrange to not care about the complete redeclaration chain while we're
8174 // deserializing. Just remember that the AST has marked this one as complete
8175 // but that it's not actually complete yet, so we know we still need to
8176 // complete it later.
8177 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
8178 return;
8179 }
8180
8181 if (!D->getDeclContext()) {
8182 assert(isa<TranslationUnitDecl>(D) && "Not a TU?");
8183 return;
8184 }
8185
8186 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
8187
8188 // If this is a named declaration, complete it by looking it up
8189 // within its context.
8190 //
8191 // FIXME: Merging a function definition should merge
8192 // all mergeable entities within it.
8194 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
8195 if (!getContext().getLangOpts().CPlusPlus &&
8197 // Outside of C++, we don't have a lookup table for the TU, so update
8198 // the identifier instead. (For C++ modules, we don't store decls
8199 // in the serialized identifier table, so we do the lookup in the TU.)
8200 auto *II = Name.getAsIdentifierInfo();
8201 assert(II && "non-identifier name in C?");
8202 if (II->isOutOfDate())
8204 } else
8205 DC->lookup(Name);
8207 // Find all declarations of this kind from the relevant context.
8208 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
8209 auto *DC = cast<DeclContext>(DCDecl);
8212 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
8213 }
8214 }
8215 }
8216
8219 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
8220 Template = CTSD->getSpecializedTemplate();
8221 Args = CTSD->getTemplateArgs().asArray();
8222 } else if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D)) {
8223 Template = VTSD->getSpecializedTemplate();
8224 Args = VTSD->getTemplateArgs().asArray();
8225 } else if (auto *FD = dyn_cast<FunctionDecl>(D)) {
8226 if (auto *Tmplt = FD->getPrimaryTemplate()) {
8227 Template = Tmplt;
8228 Args = FD->getTemplateSpecializationArgs()->asArray();
8229 }
8230 }
8231
8232 if (Template)
8233 Template->loadLazySpecializationsImpl(Args);
8234}
8235
8238 RecordLocation Loc = getLocalBitOffset(Offset);
8239 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
8240 SavedStreamPosition SavedPosition(Cursor);
8241 if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {
8242 Error(std::move(Err));
8243 return nullptr;
8244 }
8245 ReadingKindTracker ReadingKind(Read_Decl, *this);
8246 Deserializing D(this);
8247
8248 Expected<unsigned> MaybeCode = Cursor.ReadCode();
8249 if (!MaybeCode) {
8250 Error(MaybeCode.takeError());
8251 return nullptr;
8252 }
8253 unsigned Code = MaybeCode.get();
8254
8255 ASTRecordReader Record(*this, *Loc.F);
8256 Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code);
8257 if (!MaybeRecCode) {
8258 Error(MaybeRecCode.takeError());
8259 return nullptr;
8260 }
8261 if (MaybeRecCode.get() != DECL_CXX_CTOR_INITIALIZERS) {
8262 Error("malformed AST file: missing C++ ctor initializers");
8263 return nullptr;
8264 }
8265
8266 return Record.readCXXCtorInitializers();
8267}
8268
8270 assert(ContextObj && "reading base specifiers with no AST context");
8271 ASTContext &Context = *ContextObj;
8272
8273 RecordLocation Loc = getLocalBitOffset(Offset);
8274 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
8275 SavedStreamPosition SavedPosition(Cursor);
8276 if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {
8277 Error(std::move(Err));
8278 return nullptr;
8279 }
8280 ReadingKindTracker ReadingKind(Read_Decl, *this);
8281 Deserializing D(this);
8282
8283 Expected<unsigned> MaybeCode = Cursor.ReadCode();
8284 if (!MaybeCode) {
8285 Error(MaybeCode.takeError());
8286 return nullptr;
8287 }
8288 unsigned Code = MaybeCode.get();
8289
8290 ASTRecordReader Record(*this, *Loc.F);
8291 Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code);
8292 if (!MaybeRecCode) {
8293 Error(MaybeCode.takeError());
8294 return nullptr;
8295 }
8296 unsigned RecCode = MaybeRecCode.get();
8297
8298 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
8299 Error("malformed AST file: missing C++ base specifiers");
8300 return nullptr;
8301 }
8302
8303 unsigned NumBases = Record.readInt();
8304 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
8305 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
8306 for (unsigned I = 0; I != NumBases; ++I)
8307 Bases[I] = Record.readCXXBaseSpecifier();
8308 return Bases;
8309}
8310
8312 LocalDeclID LocalID) const {
8313 if (LocalID < NUM_PREDEF_DECL_IDS)
8314 return GlobalDeclID(LocalID.getRawValue());
8315
8316 unsigned OwningModuleFileIndex = LocalID.getModuleFileIndex();
8317 DeclID ID = LocalID.getLocalDeclIndex();
8318
8319 if (!F.ModuleOffsetMap.empty())
8320 ReadModuleOffsetMap(F);
8321
8322 ModuleFile *OwningModuleFile =
8323 OwningModuleFileIndex == 0
8324 ? &F
8325 : F.TransitiveImports[OwningModuleFileIndex - 1];
8326
8327 if (OwningModuleFileIndex == 0)
8328 ID -= NUM_PREDEF_DECL_IDS;
8329
8330 uint64_t NewModuleFileIndex = OwningModuleFile->Index + 1;
8331 return GlobalDeclID(NewModuleFileIndex, ID);
8332}
8333
8335 // Predefined decls aren't from any module.
8336 if (ID < NUM_PREDEF_DECL_IDS)
8337 return false;
8338
8339 unsigned ModuleFileIndex = ID.getModuleFileIndex();
8340 return M.Index == ModuleFileIndex - 1;
8341}
8342
8344 // Predefined decls aren't from any module.
8345 if (ID < NUM_PREDEF_DECL_IDS)
8346 return nullptr;
8347
8348 uint64_t ModuleFileIndex = ID.getModuleFileIndex();
8349 assert(ModuleFileIndex && "Untranslated Local Decl?");
8350
8351 return &getModuleManager()[ModuleFileIndex - 1];
8352}
8353
8355 if (!D->isFromASTFile())
8356 return nullptr;
8357
8358 return getOwningModuleFile(D->getGlobalID());
8359}
8360
8362 if (ID < NUM_PREDEF_DECL_IDS)
8363 return SourceLocation();
8364
8365 if (Decl *D = GetExistingDecl(ID))
8366 return D->getLocation();
8367
8368 SourceLocation Loc;
8369 DeclCursorForID(ID, Loc);
8370 return Loc;
8371}
8372
8373Decl *ASTReader::getPredefinedDecl(PredefinedDeclIDs ID) {
8374 assert(ContextObj && "reading predefined decl without AST context");
8375 ASTContext &Context = *ContextObj;
8376 Decl *NewLoaded = nullptr;
8377 switch (ID) {
8379 return nullptr;
8380
8382 return Context.getTranslationUnitDecl();
8383
8385 if (Context.ObjCIdDecl)
8386 return Context.ObjCIdDecl;
8387 NewLoaded = Context.getObjCIdDecl();
8388 break;
8389
8391 if (Context.ObjCSelDecl)
8392 return Context.ObjCSelDecl;
8393 NewLoaded = Context.getObjCSelDecl();
8394 break;
8395
8397 if (Context.ObjCClassDecl)
8398 return Context.ObjCClassDecl;
8399 NewLoaded = Context.getObjCClassDecl();
8400 break;
8401
8403 if (Context.ObjCProtocolClassDecl)
8404 return Context.ObjCProtocolClassDecl;
8405 NewLoaded = Context.getObjCProtocolDecl();
8406 break;
8407
8409 if (Context.Int128Decl)
8410 return Context.Int128Decl;
8411 NewLoaded = Context.getInt128Decl();
8412 break;
8413
8415 if (Context.UInt128Decl)
8416 return Context.UInt128Decl;
8417 NewLoaded = Context.getUInt128Decl();
8418 break;
8419
8421 if (Context.ObjCInstanceTypeDecl)
8422 return Context.ObjCInstanceTypeDecl;
8423 NewLoaded = Context.getObjCInstanceTypeDecl();
8424 break;
8425
8427 if (Context.BuiltinVaListDecl)
8428 return Context.BuiltinVaListDecl;
8429 NewLoaded = Context.getBuiltinVaListDecl();
8430 break;
8431
8433 if (Context.VaListTagDecl)
8434 return Context.VaListTagDecl;
8435 NewLoaded = Context.getVaListTagDecl();
8436 break;
8437
8439 if (Context.BuiltinMSVaListDecl)
8440 return Context.BuiltinMSVaListDecl;
8441 NewLoaded = Context.getBuiltinMSVaListDecl();
8442 break;
8443
8445 // ASTContext::getMSGuidTagDecl won't create MSGuidTagDecl conditionally.
8446 return Context.getMSGuidTagDecl();
8447
8449 if (Context.ExternCContext)
8450 return Context.ExternCContext;
8451 NewLoaded = Context.getExternCContextDecl();
8452 break;
8453
8455 if (Context.CFConstantStringTypeDecl)
8456 return Context.CFConstantStringTypeDecl;
8457 NewLoaded = Context.getCFConstantStringDecl();
8458 break;
8459
8461 if (Context.CFConstantStringTagDecl)
8462 return Context.CFConstantStringTagDecl;
8463 NewLoaded = Context.getCFConstantStringTagDecl();
8464 break;
8465
8467 return Context.getMSTypeInfoTagDecl();
8468
8469#define BuiltinTemplate(BTName) \
8470 case PREDEF_DECL##BTName##_ID: \
8471 if (Context.Decl##BTName) \
8472 return Context.Decl##BTName; \
8473 NewLoaded = Context.get##BTName##Decl(); \
8474 break;
8475#include "clang/Basic/BuiltinTemplates.inc"
8476
8478 llvm_unreachable("Invalid decl ID");
8479 break;
8480 }
8481
8482 assert(NewLoaded && "Failed to load predefined decl?");
8483
8484 if (DeserializationListener)
8485 DeserializationListener->PredefinedDeclBuilt(ID, NewLoaded);
8486
8487 return NewLoaded;
8488}
8489
8490unsigned ASTReader::translateGlobalDeclIDToIndex(GlobalDeclID GlobalID) const {
8491 ModuleFile *OwningModuleFile = getOwningModuleFile(GlobalID);
8492 if (!OwningModuleFile) {
8493 assert(GlobalID < NUM_PREDEF_DECL_IDS && "Untransalted Global ID?");
8494 return GlobalID.getRawValue();
8495 }
8496
8497 return OwningModuleFile->BaseDeclIndex + GlobalID.getLocalDeclIndex();
8498}
8499
8501 assert(ContextObj && "reading decl with no AST context");
8502
8503 if (ID < NUM_PREDEF_DECL_IDS) {
8504 Decl *D = getPredefinedDecl((PredefinedDeclIDs)ID);
8505 if (D) {
8506 // Track that we have merged the declaration with ID \p ID into the
8507 // pre-existing predefined declaration \p D.
8508 auto &Merged = KeyDecls[D->getCanonicalDecl()];
8509 if (Merged.empty())
8510 Merged.push_back(ID);
8511 }
8512 return D;
8513 }
8514
8515 unsigned Index = translateGlobalDeclIDToIndex(ID);
8516
8517 if (Index >= DeclsLoaded.size()) {
8518 assert(0 && "declaration ID out-of-range for AST file");
8519 Error("declaration ID out-of-range for AST file");
8520 return nullptr;
8521 }
8522
8523 return DeclsLoaded[Index];
8524}
8525
8527 if (ID < NUM_PREDEF_DECL_IDS)
8528 return GetExistingDecl(ID);
8529
8530 unsigned Index = translateGlobalDeclIDToIndex(ID);
8531
8532 if (Index >= DeclsLoaded.size()) {
8533 assert(0 && "declaration ID out-of-range for AST file");
8534 Error("declaration ID out-of-range for AST file");
8535 return nullptr;
8536 }
8537
8538 if (!DeclsLoaded[Index]) {
8539 ReadDeclRecord(ID);
8540 if (DeserializationListener)
8541 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
8542 }
8543
8544 return DeclsLoaded[Index];
8545}
8546
8548 GlobalDeclID GlobalID) {
8549 if (GlobalID < NUM_PREDEF_DECL_IDS)
8550 return LocalDeclID::get(*this, M, GlobalID.getRawValue());
8551
8552 if (!M.ModuleOffsetMap.empty())
8553 ReadModuleOffsetMap(M);
8554
8555 ModuleFile *Owner = getOwningModuleFile(GlobalID);
8556 DeclID ID = GlobalID.getLocalDeclIndex();
8557
8558 if (Owner == &M) {
8559 ID += NUM_PREDEF_DECL_IDS;
8560 return LocalDeclID::get(*this, M, ID);
8561 }
8562
8563 uint64_t OrignalModuleFileIndex = 0;
8564 for (unsigned I = 0; I < M.TransitiveImports.size(); I++)
8565 if (M.TransitiveImports[I] == Owner) {
8566 OrignalModuleFileIndex = I + 1;
8567 break;
8568 }
8569
8570 if (!OrignalModuleFileIndex)
8571 return LocalDeclID();
8572
8573 return LocalDeclID::get(*this, M, OrignalModuleFileIndex, ID);
8574}
8575
8577 unsigned &Idx) {
8578 if (Idx >= Record.size()) {
8579 Error("Corrupted AST file");
8580 return GlobalDeclID(0);
8581 }
8582
8583 return getGlobalDeclID(F, LocalDeclID::get(*this, F, Record[Idx++]));
8584}
8585
8586/// Resolve the offset of a statement into a statement.
8587///
8588/// This operation will read a new statement from the external
8589/// source each time it is called, and is meant to be used via a
8590/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
8592 // Switch case IDs are per Decl.
8594
8595 // Offset here is a global offset across the entire chain.
8596 RecordLocation Loc = getLocalBitOffset(Offset);
8597 if (llvm::Error Err = Loc.F->DeclsCursor.JumpToBit(Loc.Offset)) {
8598 Error(std::move(Err));
8599 return nullptr;
8600 }
8601 assert(NumCurrentElementsDeserializing == 0 &&
8602 "should not be called while already deserializing");
8603 Deserializing D(this);
8604 return ReadStmtFromStream(*Loc.F);
8605}
8606
8607bool ASTReader::LoadExternalSpecializationsImpl(SpecLookupTableTy &SpecLookups,
8608 const Decl *D) {
8609 assert(D);
8610
8611 auto It = SpecLookups.find(D);
8612 if (It == SpecLookups.end())
8613 return false;
8614
8615 // Get Decl may violate the iterator from SpecializationsLookups so we store
8616 // the DeclIDs in ahead.
8618 It->second.Table.findAll();
8619
8620 // Since we've loaded all the specializations, we can erase it from
8621 // the lookup table.
8622 SpecLookups.erase(It);
8623
8624 bool NewSpecsFound = false;
8625 Deserializing LookupResults(this);
8626 for (auto &Info : Infos) {
8627 if (GetExistingDecl(Info))
8628 continue;
8629 NewSpecsFound = true;
8630 GetDecl(Info);
8631 }
8632
8633 return NewSpecsFound;
8634}
8635
8637 assert(D);
8638
8640 bool NewSpecsFound =
8641 LoadExternalSpecializationsImpl(PartialSpecializationsLookups, D);
8642 if (OnlyPartial)
8643 return NewSpecsFound;
8644
8645 NewSpecsFound |= LoadExternalSpecializationsImpl(SpecializationsLookups, D);
8646 return NewSpecsFound;
8647}
8648
8649bool ASTReader::LoadExternalSpecializationsImpl(
8650 SpecLookupTableTy &SpecLookups, const Decl *D,
8651 ArrayRef<TemplateArgument> TemplateArgs) {
8652 assert(D);
8653
8654 reader::LazySpecializationInfoLookupTable *LookupTable = nullptr;
8655 if (auto It = SpecLookups.find(D); It != SpecLookups.end())
8656 LookupTable = &It->getSecond();
8657 if (!LookupTable)
8658 return false;
8659
8660 // NOTE: The getNameForDiagnostic usage in the lambda may mutate the
8661 // `SpecLookups` object.
8662 llvm::TimeTraceScope TimeScope("Load External Specializations for ", [&] {
8663 std::string Name;
8664 llvm::raw_string_ostream OS(Name);
8665 auto *ND = cast<NamedDecl>(D);
8667 /*Qualified=*/true);
8668 return Name;
8669 });
8670
8671 Deserializing LookupResults(this);
8672 auto HashValue = StableHashForTemplateArguments(TemplateArgs);
8673
8674 // Get Decl may violate the iterator from SpecLookups
8676 LookupTable->Table.find(HashValue);
8677
8678 bool NewSpecsFound = false;
8679 for (auto &Info : Infos) {
8680 if (GetExistingDecl(Info))
8681 continue;
8682 NewSpecsFound = true;
8683 GetDecl(Info);
8684 }
8685
8686 return NewSpecsFound;
8687}
8688
8690 const Decl *D, ArrayRef<TemplateArgument> TemplateArgs) {
8691 assert(D);
8692
8693 bool NewDeclsFound = LoadExternalSpecializationsImpl(
8694 PartialSpecializationsLookups, D, TemplateArgs);
8695 NewDeclsFound |=
8696 LoadExternalSpecializationsImpl(SpecializationsLookups, D, TemplateArgs);
8697
8698 return NewDeclsFound;
8699}
8700
8702 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
8703 SmallVectorImpl<Decl *> &Decls) {
8704 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
8705
8706 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
8707 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
8708 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
8709 auto K = (Decl::Kind)+LexicalDecls[I];
8710 if (!IsKindWeWant(K))
8711 continue;
8712
8713 auto ID = (DeclID) + LexicalDecls[I + 1];
8714
8715 // Don't add predefined declarations to the lexical context more
8716 // than once.
8717 if (ID < NUM_PREDEF_DECL_IDS) {
8718 if (PredefsVisited[ID])
8719 continue;
8720
8721 PredefsVisited[ID] = true;
8722 }
8723
8724 if (Decl *D = GetLocalDecl(*M, LocalDeclID::get(*this, *M, ID))) {
8725 assert(D->getKind() == K && "wrong kind for lexical decl");
8726 if (!DC->isDeclInLexicalTraversal(D))
8727 Decls.push_back(D);
8728 }
8729 }
8730 };
8731
8732 if (isa<TranslationUnitDecl>(DC)) {
8733 for (const auto &Lexical : TULexicalDecls)
8734 Visit(Lexical.first, Lexical.second);
8735 } else {
8736 auto I = LexicalDecls.find(DC);
8737 if (I != LexicalDecls.end())
8738 Visit(I->second.first, I->second.second);
8739 }
8740
8741 ++NumLexicalDeclContextsRead;
8742}
8743
8744namespace {
8745
8746class UnalignedDeclIDComp {
8747 ASTReader &Reader;
8748 ModuleFile &Mod;
8749
8750public:
8751 UnalignedDeclIDComp(ASTReader &Reader, ModuleFile &M)
8752 : Reader(Reader), Mod(M) {}
8753
8754 bool operator()(unaligned_decl_id_t L, unaligned_decl_id_t R) const {
8755 SourceLocation LHS = getLocation(L);
8756 SourceLocation RHS = getLocation(R);
8757 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
8758 }
8759
8760 bool operator()(SourceLocation LHS, unaligned_decl_id_t R) const {
8761 SourceLocation RHS = getLocation(R);
8762 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
8763 }
8764
8765 bool operator()(unaligned_decl_id_t L, SourceLocation RHS) const {
8766 SourceLocation LHS = getLocation(L);
8767 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
8768 }
8769
8770 SourceLocation getLocation(unaligned_decl_id_t ID) const {
8771 return Reader.getSourceManager().getFileLoc(
8773 Reader.getGlobalDeclID(Mod, LocalDeclID::get(Reader, Mod, ID))));
8774 }
8775};
8776
8777} // namespace
8778
8780 unsigned Offset, unsigned Length,
8781 SmallVectorImpl<Decl *> &Decls) {
8783
8784 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
8785 if (I == FileDeclIDs.end())
8786 return;
8787
8788 FileDeclsInfo &DInfo = I->second;
8789 if (DInfo.Decls.empty())
8790 return;
8791
8793 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
8794 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
8795
8796 UnalignedDeclIDComp DIDComp(*this, *DInfo.Mod);
8798 llvm::lower_bound(DInfo.Decls, BeginLoc, DIDComp);
8799 if (BeginIt != DInfo.Decls.begin())
8800 --BeginIt;
8801
8802 // If we are pointing at a top-level decl inside an objc container, we need
8803 // to backtrack until we find it otherwise we will fail to report that the
8804 // region overlaps with an objc container.
8805 while (BeginIt != DInfo.Decls.begin() &&
8806 GetDecl(getGlobalDeclID(*DInfo.Mod,
8807 LocalDeclID::get(*this, *DInfo.Mod, *BeginIt)))
8808 ->isTopLevelDeclInObjCContainer())
8809 --BeginIt;
8810
8812 llvm::upper_bound(DInfo.Decls, EndLoc, DIDComp);
8813 if (EndIt != DInfo.Decls.end())
8814 ++EndIt;
8815
8816 for (ArrayRef<unaligned_decl_id_t>::iterator DIt = BeginIt; DIt != EndIt;
8817 ++DIt)
8818 Decls.push_back(GetDecl(getGlobalDeclID(
8819 *DInfo.Mod, LocalDeclID::get(*this, *DInfo.Mod, *DIt))));
8820}
8821
8823 DeclarationName Name,
8824 const DeclContext *OriginalDC) {
8825 assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
8826 "DeclContext has no visible decls in storage");
8827 if (!Name)
8828 return false;
8829
8830 // Load the list of declarations.
8831 DeclsSet DS;
8832
8833 auto Find = [&, this](auto &&Table, auto &&Key) {
8834 for (GlobalDeclID ID : Table.find(Key)) {
8836 if (ND->getDeclName() != Name)
8837 continue;
8838 // Special case for namespaces: There can be a lot of redeclarations of
8839 // some namespaces, and we import a "key declaration" per imported module.
8840 // Since all declarations of a namespace are essentially interchangeable,
8841 // we can optimize namespace look-up by only storing the key declaration
8842 // of the current TU, rather than storing N key declarations where N is
8843 // the # of imported modules that declare that namespace.
8844 // TODO: Try to generalize this optimization to other redeclarable decls.
8845 if (isa<NamespaceDecl>(ND))
8847 DS.insert(ND);
8848 }
8849 };
8850
8851 Deserializing LookupResults(this);
8852
8853 // FIXME: Clear the redundancy with templated lambda in C++20 when that's
8854 // available.
8855 if (auto It = Lookups.find(DC); It != Lookups.end()) {
8856 ++NumVisibleDeclContextsRead;
8857 Find(It->second.Table, Name);
8858 }
8859
8860 auto FindModuleLocalLookup = [&, this](Module *NamedModule) {
8861 if (auto It = ModuleLocalLookups.find(DC); It != ModuleLocalLookups.end()) {
8862 ++NumModuleLocalVisibleDeclContexts;
8863 Find(It->second.Table, std::make_pair(Name, NamedModule));
8864 }
8865 };
8866 if (auto *NamedModule =
8867 OriginalDC ? cast<Decl>(OriginalDC)->getTopLevelOwningNamedModule()
8868 : nullptr)
8869 FindModuleLocalLookup(NamedModule);
8870 // See clang/test/Modules/ModulesLocalNamespace.cppm for the motiviation case.
8871 // We're going to find a decl but the decl context of the lookup is
8872 // unspecified. In this case, the OriginalDC may be the decl context in other
8873 // module.
8874 if (ContextObj && ContextObj->getCurrentNamedModule())
8875 FindModuleLocalLookup(ContextObj->getCurrentNamedModule());
8876
8877 if (auto It = TULocalLookups.find(DC); It != TULocalLookups.end()) {
8878 ++NumTULocalVisibleDeclContexts;
8879 Find(It->second.Table, Name);
8880 }
8881
8882 SetExternalVisibleDeclsForName(DC, Name, DS);
8883 return !DS.empty();
8884}
8885
8887 if (!DC->hasExternalVisibleStorage())
8888 return;
8889
8890 DeclsMap Decls;
8891
8892 auto findAll = [&](auto &LookupTables, unsigned &NumRead) {
8893 auto It = LookupTables.find(DC);
8894 if (It == LookupTables.end())
8895 return;
8896
8897 NumRead++;
8898
8899 for (GlobalDeclID ID : It->second.Table.findAll()) {
8901 // Special case for namespaces: There can be a lot of redeclarations of
8902 // some namespaces, and we import a "key declaration" per imported module.
8903 // Since all declarations of a namespace are essentially interchangeable,
8904 // we can optimize namespace look-up by only storing the key declaration
8905 // of the current TU, rather than storing N key declarations where N is
8906 // the # of imported modules that declare that namespace.
8907 // TODO: Try to generalize this optimization to other redeclarable decls.
8908 if (isa<NamespaceDecl>(ND))
8910 Decls[ND->getDeclName()].insert(ND);
8911 }
8912
8913 // FIXME: Why a PCH test is failing if we remove the iterator after findAll?
8914 };
8915
8916 findAll(Lookups, NumVisibleDeclContextsRead);
8917 findAll(ModuleLocalLookups, NumModuleLocalVisibleDeclContexts);
8918 findAll(TULocalLookups, NumTULocalVisibleDeclContexts);
8919
8920 for (auto &[Name, DS] : Decls)
8921 SetExternalVisibleDeclsForName(DC, Name, DS);
8922
8923 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
8924}
8925
8928 auto I = Lookups.find(Primary);
8929 return I == Lookups.end() ? nullptr : &I->second;
8930}
8931
8934 auto I = ModuleLocalLookups.find(Primary);
8935 return I == ModuleLocalLookups.end() ? nullptr : &I->second;
8936}
8937
8940 auto I = TULocalLookups.find(Primary);
8941 return I == TULocalLookups.end() ? nullptr : &I->second;
8942}
8943
8946 assert(D->isCanonicalDecl());
8947 auto &LookupTable =
8948 IsPartial ? PartialSpecializationsLookups : SpecializationsLookups;
8949 auto I = LookupTable.find(D);
8950 return I == LookupTable.end() ? nullptr : &I->second;
8951}
8952
8954 assert(D->isCanonicalDecl());
8955 return PartialSpecializationsLookups.contains(D) ||
8956 SpecializationsLookups.contains(D);
8957}
8958
8959/// Under non-PCH compilation the consumer receives the objc methods
8960/// before receiving the implementation, and codegen depends on this.
8961/// We simulate this by deserializing and passing to consumer the methods of the
8962/// implementation before passing the deserialized implementation decl.
8964 ASTConsumer *Consumer) {
8965 assert(ImplD && Consumer);
8966
8967 for (auto *I : ImplD->methods())
8968 Consumer->HandleInterestingDecl(DeclGroupRef(I));
8969
8970 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
8971}
8972
8973void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
8974 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
8975 PassObjCImplDeclToConsumer(ImplD, Consumer);
8976 else
8977 Consumer->HandleInterestingDecl(DeclGroupRef(D));
8978}
8979
8980void ASTReader::PassVTableToConsumer(CXXRecordDecl *RD) {
8981 Consumer->HandleVTable(RD);
8982}
8983
8985 this->Consumer = Consumer;
8986
8987 if (Consumer)
8988 PassInterestingDeclsToConsumer();
8989
8990 if (DeserializationListener)
8991 DeserializationListener->ReaderInitialized(this);
8992}
8993
8995 std::fprintf(stderr, "*** AST File Statistics:\n");
8996
8997 unsigned NumTypesLoaded =
8998 TypesLoaded.size() - llvm::count(TypesLoaded.materialized(), QualType());
8999 unsigned NumDeclsLoaded =
9000 DeclsLoaded.size() -
9001 llvm::count(DeclsLoaded.materialized(), (Decl *)nullptr);
9002 unsigned NumIdentifiersLoaded =
9003 IdentifiersLoaded.size() -
9004 llvm::count(IdentifiersLoaded, (IdentifierInfo *)nullptr);
9005 unsigned NumMacrosLoaded =
9006 MacrosLoaded.size() - llvm::count(MacrosLoaded, (MacroInfo *)nullptr);
9007 unsigned NumSelectorsLoaded =
9008 SelectorsLoaded.size() - llvm::count(SelectorsLoaded, Selector());
9009
9010 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
9011 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
9012 NumSLocEntriesRead, TotalNumSLocEntries,
9013 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
9014 if (!TypesLoaded.empty())
9015 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
9016 NumTypesLoaded, (unsigned)TypesLoaded.size(),
9017 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
9018 if (!DeclsLoaded.empty())
9019 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
9020 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
9021 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
9022 if (!IdentifiersLoaded.empty())
9023 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
9024 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
9025 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
9026 if (!MacrosLoaded.empty())
9027 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
9028 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
9029 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
9030 if (!SelectorsLoaded.empty())
9031 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
9032 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
9033 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
9034 if (TotalNumStatements)
9035 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
9036 NumStatementsRead, TotalNumStatements,
9037 ((float)NumStatementsRead/TotalNumStatements * 100));
9038 if (TotalNumMacros)
9039 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
9040 NumMacrosRead, TotalNumMacros,
9041 ((float)NumMacrosRead/TotalNumMacros * 100));
9042 if (TotalLexicalDeclContexts)
9043 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
9044 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
9045 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
9046 * 100));
9047 if (TotalVisibleDeclContexts)
9048 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
9049 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
9050 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
9051 * 100));
9052 if (TotalModuleLocalVisibleDeclContexts)
9053 std::fprintf(
9054 stderr, " %u/%u module local visible declcontexts read (%f%%)\n",
9055 NumModuleLocalVisibleDeclContexts, TotalModuleLocalVisibleDeclContexts,
9056 ((float)NumModuleLocalVisibleDeclContexts /
9057 TotalModuleLocalVisibleDeclContexts * 100));
9058 if (TotalTULocalVisibleDeclContexts)
9059 std::fprintf(stderr, " %u/%u visible declcontexts in GMF read (%f%%)\n",
9060 NumTULocalVisibleDeclContexts, TotalTULocalVisibleDeclContexts,
9061 ((float)NumTULocalVisibleDeclContexts /
9062 TotalTULocalVisibleDeclContexts * 100));
9063 if (TotalNumMethodPoolEntries)
9064 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
9065 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
9066 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
9067 * 100));
9068 if (NumMethodPoolLookups)
9069 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
9070 NumMethodPoolHits, NumMethodPoolLookups,
9071 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
9072 if (NumMethodPoolTableLookups)
9073 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
9074 NumMethodPoolTableHits, NumMethodPoolTableLookups,
9075 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
9076 * 100.0));
9077 if (NumIdentifierLookupHits)
9078 std::fprintf(stderr,
9079 " %u / %u identifier table lookups succeeded (%f%%)\n",
9080 NumIdentifierLookupHits, NumIdentifierLookups,
9081 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
9082
9083 if (GlobalIndex) {
9084 std::fprintf(stderr, "\n");
9085 GlobalIndex->printStats();
9086 }
9087
9088 std::fprintf(stderr, "\n");
9089 dump();
9090 std::fprintf(stderr, "\n");
9091}
9092
9093template<typename Key, typename ModuleFile, unsigned InitialCapacity>
9094LLVM_DUMP_METHOD static void
9095dumpModuleIDMap(StringRef Name,
9096 const ContinuousRangeMap<Key, ModuleFile *,
9097 InitialCapacity> &Map) {
9098 if (Map.begin() == Map.end())
9099 return;
9100
9102
9103 llvm::errs() << Name << ":\n";
9104 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
9105 I != IEnd; ++I)
9106 llvm::errs() << " " << (DeclID)I->first << " -> " << I->second->FileName
9107 << "\n";
9108}
9109
9110LLVM_DUMP_METHOD void ASTReader::dump() {
9111 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
9112 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
9113 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
9114 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
9115 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
9116 dumpModuleIDMap("Global preprocessed entity map",
9117 GlobalPreprocessedEntityMap);
9118
9119 llvm::errs() << "\n*** PCH/Modules Loaded:";
9120 for (ModuleFile &M : ModuleMgr)
9121 M.dump();
9122}
9123
9124/// Return the amount of memory used by memory buffers, breaking down
9125/// by heap-backed versus mmap'ed memory.
9127 for (ModuleFile &I : ModuleMgr) {
9128 if (llvm::MemoryBuffer *buf = I.Buffer) {
9129 size_t bytes = buf->getBufferSize();
9130 switch (buf->getBufferKind()) {
9131 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
9132 sizes.malloc_bytes += bytes;
9133 break;
9134 case llvm::MemoryBuffer::MemoryBuffer_MMap:
9135 sizes.mmap_bytes += bytes;
9136 break;
9137 }
9138 }
9139 }
9140}
9141
9143 SemaObj = &S;
9144 S.addExternalSource(this);
9145
9146 // Makes sure any declarations that were deserialized "too early"
9147 // still get added to the identifier's declaration chains.
9148 for (GlobalDeclID ID : PreloadedDeclIDs) {
9150 pushExternalDeclIntoScope(D, D->getDeclName());
9151 }
9152 PreloadedDeclIDs.clear();
9153
9154 // FIXME: What happens if these are changed by a module import?
9155 if (!FPPragmaOptions.empty()) {
9156 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
9157 FPOptionsOverride NewOverrides =
9158 FPOptionsOverride::getFromOpaqueInt(FPPragmaOptions[0]);
9159 SemaObj->CurFPFeatures =
9160 NewOverrides.applyOverrides(SemaObj->getLangOpts());
9161 }
9162
9163 for (GlobalDeclID ID : DeclsWithEffectsToVerify) {
9164 Decl *D = GetDecl(ID);
9165 if (auto *FD = dyn_cast<FunctionDecl>(D))
9166 SemaObj->addDeclWithEffects(FD, FD->getFunctionEffects());
9167 else if (auto *BD = dyn_cast<BlockDecl>(D))
9168 SemaObj->addDeclWithEffects(BD, BD->getFunctionEffects());
9169 else
9170 llvm_unreachable("unexpected Decl type in DeclsWithEffectsToVerify");
9171 }
9172 DeclsWithEffectsToVerify.clear();
9173
9174 SemaObj->OpenCLFeatures = OpenCLExtensions;
9175
9176 UpdateSema();
9177}
9178
9180 assert(SemaObj && "no Sema to update");
9181
9182 // Load the offsets of the declarations that Sema references.
9183 // They will be lazily deserialized when needed.
9184 if (!SemaDeclRefs.empty()) {
9185 assert(SemaDeclRefs.size() % 3 == 0);
9186 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 3) {
9187 if (!SemaObj->StdNamespace)
9188 SemaObj->StdNamespace = SemaDeclRefs[I].getRawValue();
9189 if (!SemaObj->StdBadAlloc)
9190 SemaObj->StdBadAlloc = SemaDeclRefs[I + 1].getRawValue();
9191 if (!SemaObj->StdAlignValT)
9192 SemaObj->StdAlignValT = SemaDeclRefs[I + 2].getRawValue();
9193 }
9194 SemaDeclRefs.clear();
9195 }
9196
9197 // Update the state of pragmas. Use the same API as if we had encountered the
9198 // pragma in the source.
9199 if(OptimizeOffPragmaLocation.isValid())
9200 SemaObj->ActOnPragmaOptimize(/* On = */ false, OptimizeOffPragmaLocation);
9201 if (PragmaMSStructState != -1)
9202 SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState);
9203 if (PointersToMembersPragmaLocation.isValid()) {
9204 SemaObj->ActOnPragmaMSPointersToMembers(
9206 PragmaMSPointersToMembersState,
9207 PointersToMembersPragmaLocation);
9208 }
9209 SemaObj->CUDA().ForceHostDeviceDepth = ForceHostDeviceDepth;
9210 if (!RISCVVecIntrinsicPragma.empty()) {
9211 assert(RISCVVecIntrinsicPragma.size() == 3 &&
9212 "Wrong number of RISCVVecIntrinsicPragma");
9213 SemaObj->RISCV().DeclareRVVBuiltins = RISCVVecIntrinsicPragma[0];
9214 SemaObj->RISCV().DeclareSiFiveVectorBuiltins = RISCVVecIntrinsicPragma[1];
9215 SemaObj->RISCV().DeclareAndesVectorBuiltins = RISCVVecIntrinsicPragma[2];
9216 }
9217
9218 if (PragmaAlignPackCurrentValue) {
9219 // The bottom of the stack might have a default value. It must be adjusted
9220 // to the current value to ensure that the packing state is preserved after
9221 // popping entries that were included/imported from a PCH/module.
9222 bool DropFirst = false;
9223 if (!PragmaAlignPackStack.empty() &&
9224 PragmaAlignPackStack.front().Location.isInvalid()) {
9225 assert(PragmaAlignPackStack.front().Value ==
9226 SemaObj->AlignPackStack.DefaultValue &&
9227 "Expected a default alignment value");
9228 SemaObj->AlignPackStack.Stack.emplace_back(
9229 PragmaAlignPackStack.front().SlotLabel,
9230 SemaObj->AlignPackStack.CurrentValue,
9231 SemaObj->AlignPackStack.CurrentPragmaLocation,
9232 PragmaAlignPackStack.front().PushLocation);
9233 DropFirst = true;
9234 }
9235 for (const auto &Entry :
9236 llvm::ArrayRef(PragmaAlignPackStack).drop_front(DropFirst ? 1 : 0)) {
9237 SemaObj->AlignPackStack.Stack.emplace_back(
9238 Entry.SlotLabel, Entry.Value, Entry.Location, Entry.PushLocation);
9239 }
9240 if (PragmaAlignPackCurrentLocation.isInvalid()) {
9241 assert(*PragmaAlignPackCurrentValue ==
9242 SemaObj->AlignPackStack.DefaultValue &&
9243 "Expected a default align and pack value");
9244 // Keep the current values.
9245 } else {
9246 SemaObj->AlignPackStack.CurrentValue = *PragmaAlignPackCurrentValue;
9247 SemaObj->AlignPackStack.CurrentPragmaLocation =
9248 PragmaAlignPackCurrentLocation;
9249 }
9250 }
9251 if (FpPragmaCurrentValue) {
9252 // The bottom of the stack might have a default value. It must be adjusted
9253 // to the current value to ensure that fp-pragma state is preserved after
9254 // popping entries that were included/imported from a PCH/module.
9255 bool DropFirst = false;
9256 if (!FpPragmaStack.empty() && FpPragmaStack.front().Location.isInvalid()) {
9257 assert(FpPragmaStack.front().Value ==
9258 SemaObj->FpPragmaStack.DefaultValue &&
9259 "Expected a default pragma float_control value");
9260 SemaObj->FpPragmaStack.Stack.emplace_back(
9261 FpPragmaStack.front().SlotLabel, SemaObj->FpPragmaStack.CurrentValue,
9262 SemaObj->FpPragmaStack.CurrentPragmaLocation,
9263 FpPragmaStack.front().PushLocation);
9264 DropFirst = true;
9265 }
9266 for (const auto &Entry :
9267 llvm::ArrayRef(FpPragmaStack).drop_front(DropFirst ? 1 : 0))
9268 SemaObj->FpPragmaStack.Stack.emplace_back(
9269 Entry.SlotLabel, Entry.Value, Entry.Location, Entry.PushLocation);
9270 if (FpPragmaCurrentLocation.isInvalid()) {
9271 assert(*FpPragmaCurrentValue == SemaObj->FpPragmaStack.DefaultValue &&
9272 "Expected a default pragma float_control value");
9273 // Keep the current values.
9274 } else {
9275 SemaObj->FpPragmaStack.CurrentValue = *FpPragmaCurrentValue;
9276 SemaObj->FpPragmaStack.CurrentPragmaLocation = FpPragmaCurrentLocation;
9277 }
9278 }
9279
9280 // For non-modular AST files, restore visiblity of modules.
9281 for (auto &Import : PendingImportedModulesSema) {
9282 if (Import.ImportLoc.isInvalid())
9283 continue;
9284 if (Module *Imported = getSubmodule(Import.ID)) {
9285 SemaObj->makeModuleVisible(Imported, Import.ImportLoc);
9286 }
9287 }
9288 PendingImportedModulesSema.clear();
9289}
9290
9292 // Note that we are loading an identifier.
9293 Deserializing AnIdentifier(this);
9294
9295 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
9296 NumIdentifierLookups,
9297 NumIdentifierLookupHits);
9298
9299 // We don't need to do identifier table lookups in C++ modules (we preload
9300 // all interesting declarations, and don't need to use the scope for name
9301 // lookups). Perform the lookup in PCH files, though, since we don't build
9302 // a complete initial identifier table if we're carrying on from a PCH.
9303 if (PP.getLangOpts().CPlusPlus) {
9304 for (auto *F : ModuleMgr.pch_modules())
9305 if (Visitor(*F))
9306 break;
9307 } else {
9308 // If there is a global index, look there first to determine which modules
9309 // provably do not have any results for this identifier.
9311 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
9312 if (!loadGlobalIndex()) {
9313 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
9314 HitsPtr = &Hits;
9315 }
9316 }
9317
9318 ModuleMgr.visit(Visitor, HitsPtr);
9319 }
9320
9321 IdentifierInfo *II = Visitor.getIdentifierInfo();
9323 return II;
9324}
9325
9326namespace clang {
9327
9328 /// An identifier-lookup iterator that enumerates all of the
9329 /// identifiers stored within a set of AST files.
9331 /// The AST reader whose identifiers are being enumerated.
9332 const ASTReader &Reader;
9333
9334 /// The current index into the chain of AST files stored in
9335 /// the AST reader.
9336 unsigned Index;
9337
9338 /// The current position within the identifier lookup table
9339 /// of the current AST file.
9340 ASTIdentifierLookupTable::key_iterator Current;
9341
9342 /// The end position within the identifier lookup table of
9343 /// the current AST file.
9344 ASTIdentifierLookupTable::key_iterator End;
9345
9346 /// Whether to skip any modules in the ASTReader.
9347 bool SkipModules;
9348
9349 public:
9350 explicit ASTIdentifierIterator(const ASTReader &Reader,
9351 bool SkipModules = false);
9352
9353 StringRef Next() override;
9354 };
9355
9356} // namespace clang
9357
9359 bool SkipModules)
9360 : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) {
9361}
9362
9364 while (Current == End) {
9365 // If we have exhausted all of our AST files, we're done.
9366 if (Index == 0)
9367 return StringRef();
9368
9369 --Index;
9370 ModuleFile &F = Reader.ModuleMgr[Index];
9371 if (SkipModules && F.isModule())
9372 continue;
9373
9374 ASTIdentifierLookupTable *IdTable =
9376 Current = IdTable->key_begin();
9377 End = IdTable->key_end();
9378 }
9379
9380 // We have any identifiers remaining in the current AST file; return
9381 // the next one.
9382 StringRef Result = *Current;
9383 ++Current;
9384 return Result;
9385}
9386
9387namespace {
9388
9389/// A utility for appending two IdentifierIterators.
9390class ChainedIdentifierIterator : public IdentifierIterator {
9391 std::unique_ptr<IdentifierIterator> Current;
9392 std::unique_ptr<IdentifierIterator> Queued;
9393
9394public:
9395 ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First,
9396 std::unique_ptr<IdentifierIterator> Second)
9397 : Current(std::move(First)), Queued(std::move(Second)) {}
9398
9399 StringRef Next() override {
9400 if (!Current)
9401 return StringRef();
9402
9403 StringRef result = Current->Next();
9404 if (!result.empty())
9405 return result;
9406
9407 // Try the queued iterator, which may itself be empty.
9408 Current.reset();
9409 std::swap(Current, Queued);
9410 return Next();
9411 }
9412};
9413
9414} // namespace
9415
9417 if (!loadGlobalIndex()) {
9418 std::unique_ptr<IdentifierIterator> ReaderIter(
9419 new ASTIdentifierIterator(*this, /*SkipModules=*/true));
9420 std::unique_ptr<IdentifierIterator> ModulesIter(
9421 GlobalIndex->createIdentifierIterator());
9422 return new ChainedIdentifierIterator(std::move(ReaderIter),
9423 std::move(ModulesIter));
9424 }
9425
9426 return new ASTIdentifierIterator(*this);
9427}
9428
9429namespace clang {
9430namespace serialization {
9431
9433 ASTReader &Reader;
9434 Selector Sel;
9435 unsigned PriorGeneration;
9436 unsigned InstanceBits = 0;
9437 unsigned FactoryBits = 0;
9438 bool InstanceHasMoreThanOneDecl = false;
9439 bool FactoryHasMoreThanOneDecl = false;
9440 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
9441 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
9442
9443 public:
9445 unsigned PriorGeneration)
9446 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration) {}
9447
9449 if (!M.SelectorLookupTable)
9450 return false;
9451
9452 // If we've already searched this module file, skip it now.
9453 if (M.Generation <= PriorGeneration)
9454 return true;
9455
9456 ++Reader.NumMethodPoolTableLookups;
9457 ASTSelectorLookupTable *PoolTable
9459 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
9460 if (Pos == PoolTable->end())
9461 return false;
9462
9463 ++Reader.NumMethodPoolTableHits;
9464 ++Reader.NumSelectorsRead;
9465 // FIXME: Not quite happy with the statistics here. We probably should
9466 // disable this tracking when called via LoadSelector.
9467 // Also, should entries without methods count as misses?
9468 ++Reader.NumMethodPoolEntriesRead;
9470 if (Reader.DeserializationListener)
9471 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
9472
9473 // Append methods in the reverse order, so that later we can process them
9474 // in the order they appear in the source code by iterating through
9475 // the vector in the reverse order.
9476 InstanceMethods.append(Data.Instance.rbegin(), Data.Instance.rend());
9477 FactoryMethods.append(Data.Factory.rbegin(), Data.Factory.rend());
9478 InstanceBits = Data.InstanceBits;
9479 FactoryBits = Data.FactoryBits;
9480 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
9481 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
9482 return false;
9483 }
9484
9485 /// Retrieve the instance methods found by this visitor.
9487 return InstanceMethods;
9488 }
9489
9490 /// Retrieve the instance methods found by this visitor.
9492 return FactoryMethods;
9493 }
9494
9495 unsigned getInstanceBits() const { return InstanceBits; }
9496 unsigned getFactoryBits() const { return FactoryBits; }
9497
9499 return InstanceHasMoreThanOneDecl;
9500 }
9501
9502 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
9503 };
9504
9505} // namespace serialization
9506} // namespace clang
9507
9508/// Add the given set of methods to the method list.
9510 ObjCMethodList &List) {
9511 for (ObjCMethodDecl *M : llvm::reverse(Methods))
9512 S.ObjC().addMethodToGlobalList(&List, M);
9513}
9514
9516 // Get the selector generation and update it to the current generation.
9517 unsigned &Generation = SelectorGeneration[Sel];
9518 unsigned PriorGeneration = Generation;
9519 Generation = getGeneration();
9520 SelectorOutOfDate[Sel] = false;
9521
9522 // Search for methods defined with this selector.
9523 ++NumMethodPoolLookups;
9524 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
9525 ModuleMgr.visit(Visitor);
9526
9527 if (Visitor.getInstanceMethods().empty() &&
9528 Visitor.getFactoryMethods().empty())
9529 return;
9530
9531 ++NumMethodPoolHits;
9532
9533 if (!getSema())
9534 return;
9535
9536 Sema &S = *getSema();
9537 auto &Methods = S.ObjC().MethodPool[Sel];
9538
9539 Methods.first.setBits(Visitor.getInstanceBits());
9540 Methods.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
9541 Methods.second.setBits(Visitor.getFactoryBits());
9542 Methods.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
9543
9544 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
9545 // when building a module we keep every method individually and may need to
9546 // update hasMoreThanOneDecl as we add the methods.
9547 addMethodsToPool(S, Visitor.getInstanceMethods(), Methods.first);
9548 addMethodsToPool(S, Visitor.getFactoryMethods(), Methods.second);
9549}
9550
9552 if (SelectorOutOfDate[Sel])
9553 ReadMethodPool(Sel);
9554}
9555
9558 Namespaces.clear();
9559
9560 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
9561 if (NamespaceDecl *Namespace
9562 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
9563 Namespaces.push_back(Namespace);
9564 }
9565}
9566
9568 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {
9569 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
9570 UndefinedButUsedDecl &U = UndefinedButUsed[Idx++];
9573 Undefined.insert(std::make_pair(D, Loc));
9574 }
9575 UndefinedButUsed.clear();
9576}
9577
9579 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
9580 Exprs) {
9581 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
9582 FieldDecl *FD =
9583 cast<FieldDecl>(GetDecl(GlobalDeclID(DelayedDeleteExprs[Idx++])));
9584 uint64_t Count = DelayedDeleteExprs[Idx++];
9585 for (uint64_t C = 0; C < Count; ++C) {
9586 SourceLocation DeleteLoc =
9587 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
9588 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
9589 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
9590 }
9591 }
9592}
9593
9595 SmallVectorImpl<VarDecl *> &TentativeDefs) {
9596 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
9597 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
9598 if (Var)
9599 TentativeDefs.push_back(Var);
9600 }
9601 TentativeDefinitions.clear();
9602}
9603
9606 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
9608 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
9609 if (D)
9610 Decls.push_back(D);
9611 }
9612 UnusedFileScopedDecls.clear();
9613}
9614
9617 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
9619 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
9620 if (D)
9621 Decls.push_back(D);
9622 }
9623 DelegatingCtorDecls.clear();
9624}
9625
9627 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
9629 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
9630 if (D)
9631 Decls.push_back(D);
9632 }
9633 ExtVectorDecls.clear();
9634}
9635
9638 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
9639 ++I) {
9640 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
9641 GetDecl(UnusedLocalTypedefNameCandidates[I]));
9642 if (D)
9643 Decls.insert(D);
9644 }
9645 UnusedLocalTypedefNameCandidates.clear();
9646}
9647
9650 for (auto I : DeclsToCheckForDeferredDiags) {
9651 auto *D = dyn_cast_or_null<Decl>(GetDecl(I));
9652 if (D)
9653 Decls.insert(D);
9654 }
9655 DeclsToCheckForDeferredDiags.clear();
9656}
9657
9659 SmallVectorImpl<std::pair<Selector, SourceLocation>> &Sels) {
9660 if (ReferencedSelectorsData.empty())
9661 return;
9662
9663 // If there are @selector references added them to its pool. This is for
9664 // implementation of -Wselector.
9665 unsigned int DataSize = ReferencedSelectorsData.size()-1;
9666 unsigned I = 0;
9667 while (I < DataSize) {
9668 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
9669 SourceLocation SelLoc
9670 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
9671 Sels.push_back(std::make_pair(Sel, SelLoc));
9672 }
9673 ReferencedSelectorsData.clear();
9674}
9675
9677 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo>> &WeakIDs) {
9678 if (WeakUndeclaredIdentifiers.empty())
9679 return;
9680
9681 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
9682 IdentifierInfo *WeakId
9683 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
9684 IdentifierInfo *AliasId
9685 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
9686 SourceLocation Loc =
9687 SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
9688 WeakInfo WI(AliasId, Loc);
9689 WeakIDs.push_back(std::make_pair(WeakId, WI));
9690 }
9691 WeakUndeclaredIdentifiers.clear();
9692}
9693
9695 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
9697 VTableUse &TableInfo = VTableUses[Idx++];
9698 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(TableInfo.ID));
9699 VT.Location = SourceLocation::getFromRawEncoding(TableInfo.RawLoc);
9700 VT.DefinitionRequired = TableInfo.Used;
9701 VTables.push_back(VT);
9702 }
9703
9704 VTableUses.clear();
9705}
9706
9708 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation>> &Pending) {
9709 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
9710 PendingInstantiation &Inst = PendingInstantiations[Idx++];
9711 ValueDecl *D = cast<ValueDecl>(GetDecl(Inst.ID));
9713
9714 Pending.push_back(std::make_pair(D, Loc));
9715 }
9716 PendingInstantiations.clear();
9717}
9718
9720 llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>>
9721 &LPTMap) {
9722 for (auto &LPT : LateParsedTemplates) {
9723 ModuleFile *FMod = LPT.first;
9724 RecordDataImpl &LateParsed = LPT.second;
9725 for (unsigned Idx = 0, N = LateParsed.size(); Idx < N;
9726 /* In loop */) {
9727 FunctionDecl *FD = ReadDeclAs<FunctionDecl>(*FMod, LateParsed, Idx);
9728
9729 auto LT = std::make_unique<LateParsedTemplate>();
9730 LT->D = ReadDecl(*FMod, LateParsed, Idx);
9731 LT->FPO = FPOptions::getFromOpaqueInt(LateParsed[Idx++]);
9732
9733 ModuleFile *F = getOwningModuleFile(LT->D);
9734 assert(F && "No module");
9735
9736 unsigned TokN = LateParsed[Idx++];
9737 LT->Toks.reserve(TokN);
9738 for (unsigned T = 0; T < TokN; ++T)
9739 LT->Toks.push_back(ReadToken(*F, LateParsed, Idx));
9740
9741 LPTMap.insert(std::make_pair(FD, std::move(LT)));
9742 }
9743 }
9744
9745 LateParsedTemplates.clear();
9746}
9747
9749 if (!Lambda->getLambdaContextDecl())
9750 return;
9751
9752 auto LambdaInfo =
9753 std::make_pair(Lambda->getLambdaContextDecl()->getCanonicalDecl(),
9754 Lambda->getLambdaIndexInContext());
9755
9756 // Handle the import and then include case for lambdas.
9757 if (auto Iter = LambdaDeclarationsForMerging.find(LambdaInfo);
9758 Iter != LambdaDeclarationsForMerging.end() &&
9759 Iter->second->isFromASTFile() && Lambda->getFirstDecl() == Lambda) {
9761 cast<CXXRecordDecl>(Iter->second)->getMostRecentDecl();
9762 Lambda->setPreviousDecl(Previous);
9763 return;
9764 }
9765
9766 // Keep track of this lambda so it can be merged with another lambda that
9767 // is loaded later.
9768 LambdaDeclarationsForMerging.insert({LambdaInfo, Lambda});
9769}
9770
9772 // It would be complicated to avoid reading the methods anyway. So don't.
9773 ReadMethodPool(Sel);
9774}
9775
9777 assert(ID && "Non-zero identifier ID required");
9778 unsigned Index = translateIdentifierIDToIndex(ID).second;
9779 assert(Index < IdentifiersLoaded.size() && "identifier ID out of range");
9780 IdentifiersLoaded[Index] = II;
9781 if (DeserializationListener)
9782 DeserializationListener->IdentifierRead(ID, II);
9783}
9784
9785/// Set the globally-visible declarations associated with the given
9786/// identifier.
9787///
9788/// If the AST reader is currently in a state where the given declaration IDs
9789/// cannot safely be resolved, they are queued until it is safe to resolve
9790/// them.
9791///
9792/// \param II an IdentifierInfo that refers to one or more globally-visible
9793/// declarations.
9794///
9795/// \param DeclIDs the set of declaration IDs with the name @p II that are
9796/// visible at global scope.
9797///
9798/// \param Decls if non-null, this vector will be populated with the set of
9799/// deserialized declarations. These declarations will not be pushed into
9800/// scope.
9803 SmallVectorImpl<Decl *> *Decls) {
9804 if (NumCurrentElementsDeserializing && !Decls) {
9805 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
9806 return;
9807 }
9808
9809 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
9810 if (!SemaObj) {
9811 // Queue this declaration so that it will be added to the
9812 // translation unit scope and identifier's declaration chain
9813 // once a Sema object is known.
9814 PreloadedDeclIDs.push_back(DeclIDs[I]);
9815 continue;
9816 }
9817
9818 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
9819
9820 // If we're simply supposed to record the declarations, do so now.
9821 if (Decls) {
9822 Decls->push_back(D);
9823 continue;
9824 }
9825
9826 // Introduce this declaration into the translation-unit scope
9827 // and add it to the declaration chain for this identifier, so
9828 // that (unqualified) name lookup will find it.
9829 pushExternalDeclIntoScope(D, II);
9830 }
9831}
9832
9833std::pair<ModuleFile *, unsigned>
9834ASTReader::translateIdentifierIDToIndex(IdentifierID ID) const {
9835 if (ID == 0)
9836 return {nullptr, 0};
9837
9838 unsigned ModuleFileIndex = ID >> 32;
9839 unsigned LocalID = ID & llvm::maskTrailingOnes<IdentifierID>(32);
9840
9841 assert(ModuleFileIndex && "not translating loaded IdentifierID?");
9842 assert(getModuleManager().size() > ModuleFileIndex - 1);
9843
9844 ModuleFile &MF = getModuleManager()[ModuleFileIndex - 1];
9845 assert(LocalID < MF.LocalNumIdentifiers);
9846 return {&MF, MF.BaseIdentifierID + LocalID};
9847}
9848
9850 if (ID == 0)
9851 return nullptr;
9852
9853 if (IdentifiersLoaded.empty()) {
9854 Error("no identifier table in AST file");
9855 return nullptr;
9856 }
9857
9858 auto [M, Index] = translateIdentifierIDToIndex(ID);
9859 if (!IdentifiersLoaded[Index]) {
9860 assert(M != nullptr && "Untranslated Identifier ID?");
9861 assert(Index >= M->BaseIdentifierID);
9862 unsigned LocalIndex = Index - M->BaseIdentifierID;
9863 const unsigned char *Data =
9864 M->IdentifierTableData + M->IdentifierOffsets[LocalIndex];
9865
9866 ASTIdentifierLookupTrait Trait(*this, *M);
9867 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
9868 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
9869 auto &II = PP.getIdentifierTable().get(Key);
9870 IdentifiersLoaded[Index] = &II;
9871 bool IsModule = getPreprocessor().getCurrentModule() != nullptr;
9872 markIdentifierFromAST(*this, II, IsModule);
9873 if (DeserializationListener)
9874 DeserializationListener->IdentifierRead(ID, &II);
9875 }
9876
9877 return IdentifiersLoaded[Index];
9878}
9879
9883
9885 if (LocalID < NUM_PREDEF_IDENT_IDS)
9886 return LocalID;
9887
9888 if (!M.ModuleOffsetMap.empty())
9889 ReadModuleOffsetMap(M);
9890
9891 unsigned ModuleFileIndex = LocalID >> 32;
9892 LocalID &= llvm::maskTrailingOnes<IdentifierID>(32);
9893 ModuleFile *MF =
9894 ModuleFileIndex ? M.TransitiveImports[ModuleFileIndex - 1] : &M;
9895 assert(MF && "malformed identifier ID encoding?");
9896
9897 if (!ModuleFileIndex)
9898 LocalID -= NUM_PREDEF_IDENT_IDS;
9899
9900 return ((IdentifierID)(MF->Index + 1) << 32) | LocalID;
9901}
9902
9903std::pair<ModuleFile *, unsigned>
9904ASTReader::translateMacroIDToIndex(MacroID ID) const {
9905 if (ID == 0)
9906 return {nullptr, 0};
9907
9908 unsigned ModuleFileIndex = ID >> 32;
9909 assert(ModuleFileIndex && "not translating loaded MacroID?");
9910 assert(getModuleManager().size() > ModuleFileIndex - 1);
9911 ModuleFile &MF = getModuleManager()[ModuleFileIndex - 1];
9912
9913 unsigned LocalID = ID & llvm::maskTrailingOnes<MacroID>(32);
9914 assert(LocalID < MF.LocalNumMacros);
9915 return {&MF, MF.BaseMacroID + LocalID};
9916}
9917
9919 if (ID == 0)
9920 return nullptr;
9921
9922 if (MacrosLoaded.empty()) {
9923 Error("no macro table in AST file");
9924 return nullptr;
9925 }
9926
9927 auto [M, Index] = translateMacroIDToIndex(ID);
9928 if (!MacrosLoaded[Index]) {
9929 assert(M != nullptr && "Untranslated Macro ID?");
9930 assert(Index >= M->BaseMacroID);
9931 unsigned LocalIndex = Index - M->BaseMacroID;
9932 uint64_t DataOffset = M->MacroOffsetsBase + M->MacroOffsets[LocalIndex];
9933 MacrosLoaded[Index] = ReadMacroRecord(*M, DataOffset);
9934
9935 if (DeserializationListener)
9936 DeserializationListener->MacroRead(ID, MacrosLoaded[Index]);
9937 }
9938
9939 return MacrosLoaded[Index];
9940}
9941
9943 if (LocalID < NUM_PREDEF_MACRO_IDS)
9944 return LocalID;
9945
9946 if (!M.ModuleOffsetMap.empty())
9947 ReadModuleOffsetMap(M);
9948
9949 unsigned ModuleFileIndex = LocalID >> 32;
9950 LocalID &= llvm::maskTrailingOnes<MacroID>(32);
9951 ModuleFile *MF =
9952 ModuleFileIndex ? M.TransitiveImports[ModuleFileIndex - 1] : &M;
9953 assert(MF && "malformed identifier ID encoding?");
9954
9955 if (!ModuleFileIndex) {
9956 assert(LocalID >= NUM_PREDEF_MACRO_IDS);
9957 LocalID -= NUM_PREDEF_MACRO_IDS;
9958 }
9959
9960 return (static_cast<MacroID>(MF->Index + 1) << 32) | LocalID;
9961}
9962
9964ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) const {
9965 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
9966 return LocalID;
9967
9968 if (!M.ModuleOffsetMap.empty())
9969 ReadModuleOffsetMap(M);
9970
9973 assert(I != M.SubmoduleRemap.end()
9974 && "Invalid index into submodule index remap");
9975
9976 return LocalID + I->second;
9977}
9978
9980 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
9981 assert(GlobalID == 0 && "Unhandled global submodule ID");
9982 return nullptr;
9983 }
9984
9985 if (GlobalID > SubmodulesLoaded.size()) {
9986 Error("submodule ID out of range in AST file");
9987 return nullptr;
9988 }
9989
9990 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
9991}
9992
9994 return getSubmodule(ID);
9995}
9996
9998 if (ID & 1) {
9999 // It's a module, look it up by submodule ID.
10000 auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(M, ID >> 1));
10001 return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
10002 } else {
10003 // It's a prefix (preamble, PCH, ...). Look it up by index.
10004 int IndexFromEnd = static_cast<int>(ID >> 1);
10005 assert(IndexFromEnd && "got reference to unknown module file");
10006 return getModuleManager().pch_modules().end()[-IndexFromEnd];
10007 }
10008}
10009
10011 if (!M)
10012 return 1;
10013
10014 // For a file representing a module, use the submodule ID of the top-level
10015 // module as the file ID. For any other kind of file, the number of such
10016 // files loaded beforehand will be the same on reload.
10017 // FIXME: Is this true even if we have an explicit module file and a PCH?
10018 if (M->isModule())
10019 return ((M->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
10020
10021 auto PCHModules = getModuleManager().pch_modules();
10022 auto I = llvm::find(PCHModules, M);
10023 assert(I != PCHModules.end() && "emitting reference to unknown file");
10024 return std::distance(I, PCHModules.end()) << 1;
10025}
10026
10027std::optional<ASTSourceDescriptor> ASTReader::getSourceDescriptor(unsigned ID) {
10028 if (Module *M = getSubmodule(ID))
10029 return ASTSourceDescriptor(*M);
10030
10031 // If there is only a single PCH, return it instead.
10032 // Chained PCH are not supported.
10033 const auto &PCHChain = ModuleMgr.pch_modules();
10034 if (std::distance(std::begin(PCHChain), std::end(PCHChain))) {
10035 ModuleFile &MF = ModuleMgr.getPrimaryModule();
10036 StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName);
10037 StringRef FileName = llvm::sys::path::filename(MF.FileName);
10038 return ASTSourceDescriptor(ModuleName,
10039 llvm::sys::path::parent_path(MF.FileName),
10040 FileName, MF.Signature);
10041 }
10042 return std::nullopt;
10043}
10044
10046 auto I = DefinitionSource.find(FD);
10047 if (I == DefinitionSource.end())
10048 return EK_ReplyHazy;
10049 return I->second ? EK_Never : EK_Always;
10050}
10051
10053 return ThisDeclarationWasADefinitionSet.contains(FD);
10054}
10055
10057 return DecodeSelector(getGlobalSelectorID(M, LocalID));
10058}
10059
10061 if (ID == 0)
10062 return Selector();
10063
10064 if (ID > SelectorsLoaded.size()) {
10065 Error("selector ID out of range in AST file");
10066 return Selector();
10067 }
10068
10069 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
10070 // Load this selector from the selector table.
10071 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
10072 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
10073 ModuleFile &M = *I->second;
10074 ASTSelectorLookupTrait Trait(*this, M);
10075 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
10076 SelectorsLoaded[ID - 1] =
10077 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
10078 if (DeserializationListener)
10079 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
10080 }
10081
10082 return SelectorsLoaded[ID - 1];
10083}
10084
10088
10090 // ID 0 (the null selector) is considered an external selector.
10091 return getTotalNumSelectors() + 1;
10092}
10093
10095ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
10096 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
10097 return LocalID;
10098
10099 if (!M.ModuleOffsetMap.empty())
10100 ReadModuleOffsetMap(M);
10101
10104 assert(I != M.SelectorRemap.end()
10105 && "Invalid index into selector index remap");
10106
10107 return LocalID + I->second;
10108}
10109
10135
10137 DeclarationNameInfo NameInfo;
10138 NameInfo.setName(readDeclarationName());
10139 NameInfo.setLoc(readSourceLocation());
10140 NameInfo.setInfo(readDeclarationNameLoc(NameInfo.getName()));
10141 return NameInfo;
10142}
10143
10147
10149 auto Kind = readInt();
10150 auto ResultType = readQualType();
10151 auto Value = readAPInt();
10152 SpirvOperand Op(SpirvOperand::SpirvOperandKind(Kind), ResultType, Value);
10153 assert(Op.isValid());
10154 return Op;
10155}
10156
10159 unsigned NumTPLists = readInt();
10160 Info.NumTemplParamLists = NumTPLists;
10161 if (NumTPLists) {
10162 Info.TemplParamLists =
10163 new (getContext()) TemplateParameterList *[NumTPLists];
10164 for (unsigned i = 0; i != NumTPLists; ++i)
10166 }
10167}
10168
10171 SourceLocation TemplateLoc = readSourceLocation();
10172 SourceLocation LAngleLoc = readSourceLocation();
10173 SourceLocation RAngleLoc = readSourceLocation();
10174
10175 unsigned NumParams = readInt();
10177 Params.reserve(NumParams);
10178 while (NumParams--)
10179 Params.push_back(readDeclAs<NamedDecl>());
10180
10181 bool HasRequiresClause = readBool();
10182 Expr *RequiresClause = HasRequiresClause ? readExpr() : nullptr;
10183
10185 getContext(), TemplateLoc, LAngleLoc, Params, RAngleLoc, RequiresClause);
10186 return TemplateParams;
10187}
10188
10191 bool Canonicalize) {
10192 unsigned NumTemplateArgs = readInt();
10193 TemplArgs.reserve(NumTemplateArgs);
10194 while (NumTemplateArgs--)
10195 TemplArgs.push_back(readTemplateArgument(Canonicalize));
10196}
10197
10198/// Read a UnresolvedSet structure.
10200 unsigned NumDecls = readInt();
10201 Set.reserve(getContext(), NumDecls);
10202 while (NumDecls--) {
10203 GlobalDeclID ID = readDeclID();
10205 Set.addLazyDecl(getContext(), ID, AS);
10206 }
10207}
10208
10211 bool isVirtual = readBool();
10212 bool isBaseOfClass = readBool();
10213 AccessSpecifier AS = static_cast<AccessSpecifier>(readInt());
10214 bool inheritConstructors = readBool();
10216 SourceRange Range = readSourceRange();
10217 SourceLocation EllipsisLoc = readSourceLocation();
10218 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
10219 EllipsisLoc);
10220 Result.setInheritConstructors(inheritConstructors);
10221 return Result;
10222}
10223
10226 ASTContext &Context = getContext();
10227 unsigned NumInitializers = readInt();
10228 assert(NumInitializers && "wrote ctor initializers but have no inits");
10229 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
10230 for (unsigned i = 0; i != NumInitializers; ++i) {
10231 TypeSourceInfo *TInfo = nullptr;
10232 bool IsBaseVirtual = false;
10233 FieldDecl *Member = nullptr;
10234 IndirectFieldDecl *IndirectMember = nullptr;
10235
10237 switch (Type) {
10239 TInfo = readTypeSourceInfo();
10240 IsBaseVirtual = readBool();
10241 break;
10242
10244 TInfo = readTypeSourceInfo();
10245 break;
10246
10249 break;
10250
10252 IndirectMember = readDeclAs<IndirectFieldDecl>();
10253 break;
10254 }
10255
10256 SourceLocation MemberOrEllipsisLoc = readSourceLocation();
10257 Expr *Init = readExpr();
10258 SourceLocation LParenLoc = readSourceLocation();
10259 SourceLocation RParenLoc = readSourceLocation();
10260
10261 CXXCtorInitializer *BOMInit;
10263 BOMInit = new (Context)
10264 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
10265 RParenLoc, MemberOrEllipsisLoc);
10267 BOMInit = new (Context)
10268 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
10269 else if (Member)
10270 BOMInit = new (Context)
10271 CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc, LParenLoc,
10272 Init, RParenLoc);
10273 else
10274 BOMInit = new (Context)
10275 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
10276 LParenLoc, Init, RParenLoc);
10277
10278 if (/*IsWritten*/readBool()) {
10279 unsigned SourceOrder = readInt();
10280 BOMInit->setSourceOrder(SourceOrder);
10281 }
10282
10283 CtorInitializers[i] = BOMInit;
10284 }
10285
10286 return CtorInitializers;
10287}
10288
10291 ASTContext &Context = getContext();
10292 unsigned N = readInt();
10294 for (unsigned I = 0; I != N; ++I) {
10295 auto Kind = readNestedNameSpecifierKind();
10296 switch (Kind) {
10298 auto *NS = readDeclAs<NamespaceBaseDecl>();
10299 SourceRange Range = readSourceRange();
10300 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
10301 break;
10302 }
10303
10306 if (!T)
10307 return NestedNameSpecifierLoc();
10308 SourceLocation ColonColonLoc = readSourceLocation();
10309 Builder.Make(Context, T->getTypeLoc(), ColonColonLoc);
10310 break;
10311 }
10312
10314 SourceLocation ColonColonLoc = readSourceLocation();
10315 Builder.MakeGlobal(Context, ColonColonLoc);
10316 break;
10317 }
10318
10321 SourceRange Range = readSourceRange();
10322 Builder.MakeMicrosoftSuper(Context, RD, Range.getBegin(), Range.getEnd());
10323 break;
10324 }
10325
10327 llvm_unreachable("unexpected null nested name specifier");
10328 }
10329 }
10330
10331 return Builder.getWithLocInContext(Context);
10332}
10333
10335 unsigned &Idx) {
10338 return SourceRange(beg, end);
10339}
10340
10342 const StringRef Blob) {
10343 unsigned Count = Record[0];
10344 const char *Byte = Blob.data();
10345 llvm::BitVector Ret = llvm::BitVector(Count, false);
10346 for (unsigned I = 0; I < Count; ++Byte)
10347 for (unsigned Bit = 0; Bit < 8 && I < Count; ++Bit, ++I)
10348 if (*Byte & (1 << Bit))
10349 Ret[I] = true;
10350 return Ret;
10351}
10352
10353/// Read a floating-point value
10354llvm::APFloat ASTRecordReader::readAPFloat(const llvm::fltSemantics &Sem) {
10355 return llvm::APFloat(Sem, readAPInt());
10356}
10357
10358// Read a string
10359std::string ASTReader::ReadString(const RecordDataImpl &Record, unsigned &Idx) {
10360 unsigned Len = Record[Idx++];
10361 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
10362 Idx += Len;
10363 return Result;
10364}
10365
10366StringRef ASTReader::ReadStringBlob(const RecordDataImpl &Record, unsigned &Idx,
10367 StringRef &Blob) {
10368 unsigned Len = Record[Idx++];
10369 StringRef Result = Blob.substr(0, Len);
10370 Blob = Blob.substr(Len);
10371 return Result;
10372}
10373
10375 unsigned &Idx) {
10376 return ReadPath(F.BaseDirectory, Record, Idx);
10377}
10378
10379std::string ASTReader::ReadPath(StringRef BaseDirectory,
10380 const RecordData &Record, unsigned &Idx) {
10381 std::string Filename = ReadString(Record, Idx);
10382 return ResolveImportedPathAndAllocate(PathBuf, Filename, BaseDirectory);
10383}
10384
10385std::string ASTReader::ReadPathBlob(StringRef BaseDirectory,
10386 const RecordData &Record, unsigned &Idx,
10387 StringRef &Blob) {
10388 StringRef Filename = ReadStringBlob(Record, Idx, Blob);
10389 return ResolveImportedPathAndAllocate(PathBuf, Filename, BaseDirectory);
10390}
10391
10393 unsigned &Idx) {
10394 unsigned Major = Record[Idx++];
10395 unsigned Minor = Record[Idx++];
10396 unsigned Subminor = Record[Idx++];
10397 if (Minor == 0)
10398 return VersionTuple(Major);
10399 if (Subminor == 0)
10400 return VersionTuple(Major, Minor - 1);
10401 return VersionTuple(Major, Minor - 1, Subminor - 1);
10402}
10403
10410
10411DiagnosticBuilder ASTReader::Diag(unsigned DiagID) const {
10412 return Diag(CurrentImportLoc, DiagID);
10413}
10414
10416 return Diags.Report(Loc, DiagID);
10417}
10418
10420 llvm::function_ref<void()> Fn) {
10421 // When Sema is available, avoid duplicate errors.
10422 if (SemaObj) {
10423 SemaObj->runWithSufficientStackSpace(Loc, Fn);
10424 return;
10425 }
10426
10427 StackHandler.runWithSufficientStackSpace(Loc, Fn);
10428}
10429
10430/// Retrieve the identifier table associated with the
10431/// preprocessor.
10433 return PP.getIdentifierTable();
10434}
10435
10436/// Record that the given ID maps to the given switch-case
10437/// statement.
10439 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
10440 "Already have a SwitchCase with this ID");
10441 (*CurrSwitchCaseStmts)[ID] = SC;
10442}
10443
10444/// Retrieve the switch-case statement with the given ID.
10446 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
10447 return (*CurrSwitchCaseStmts)[ID];
10448}
10449
10451 CurrSwitchCaseStmts->clear();
10452}
10453
10455 ASTContext &Context = getContext();
10456 std::vector<RawComment *> Comments;
10457 for (SmallVectorImpl<std::pair<BitstreamCursor,
10459 I = CommentsCursors.begin(),
10460 E = CommentsCursors.end();
10461 I != E; ++I) {
10462 Comments.clear();
10463 BitstreamCursor &Cursor = I->first;
10464 serialization::ModuleFile &F = *I->second;
10465 SavedStreamPosition SavedPosition(Cursor);
10466
10468 while (true) {
10470 Cursor.advanceSkippingSubblocks(
10471 BitstreamCursor::AF_DontPopBlockAtEnd);
10472 if (!MaybeEntry) {
10473 Error(MaybeEntry.takeError());
10474 return;
10475 }
10476 llvm::BitstreamEntry Entry = MaybeEntry.get();
10477
10478 switch (Entry.Kind) {
10479 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
10480 case llvm::BitstreamEntry::Error:
10481 Error("malformed block record in AST file");
10482 return;
10483 case llvm::BitstreamEntry::EndBlock:
10484 goto NextCursor;
10485 case llvm::BitstreamEntry::Record:
10486 // The interesting case.
10487 break;
10488 }
10489
10490 // Read a record.
10491 Record.clear();
10492 Expected<unsigned> MaybeComment = Cursor.readRecord(Entry.ID, Record);
10493 if (!MaybeComment) {
10494 Error(MaybeComment.takeError());
10495 return;
10496 }
10497 switch ((CommentRecordTypes)MaybeComment.get()) {
10498 case COMMENTS_RAW_COMMENT: {
10499 unsigned Idx = 0;
10500 SourceRange SR = ReadSourceRange(F, Record, Idx);
10503 bool IsTrailingComment = Record[Idx++];
10504 bool IsAlmostTrailingComment = Record[Idx++];
10505 Comments.push_back(new (Context) RawComment(
10506 SR, Kind, IsTrailingComment, IsAlmostTrailingComment));
10507 break;
10508 }
10509 }
10510 }
10511 NextCursor:
10512 for (RawComment *C : Comments) {
10513 SourceLocation CommentLoc = C->getBeginLoc();
10514 if (CommentLoc.isValid()) {
10515 FileIDAndOffset Loc = SourceMgr.getDecomposedLoc(CommentLoc);
10516 if (Loc.first.isValid())
10517 Context.Comments.OrderedComments[Loc.first].emplace(Loc.second, C);
10518 }
10519 }
10520 }
10521}
10522
10524 serialization::ModuleFile &MF, bool IncludeSystem,
10525 llvm::function_ref<void(const serialization::InputFileInfo &IFI,
10526 bool IsSystem)>
10527 Visitor) {
10528 unsigned NumUserInputs = MF.NumUserInputFiles;
10529 unsigned NumInputs = MF.InputFilesLoaded.size();
10530 assert(NumUserInputs <= NumInputs);
10531 unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
10532 for (unsigned I = 0; I < N; ++I) {
10533 bool IsSystem = I >= NumUserInputs;
10534 InputFileInfo IFI = getInputFileInfo(MF, I+1);
10535 Visitor(IFI, IsSystem);
10536 }
10537}
10538
10540 bool IncludeSystem, bool Complain,
10541 llvm::function_ref<void(const serialization::InputFile &IF,
10542 bool isSystem)> Visitor) {
10543 unsigned NumUserInputs = MF.NumUserInputFiles;
10544 unsigned NumInputs = MF.InputFilesLoaded.size();
10545 assert(NumUserInputs <= NumInputs);
10546 unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
10547 for (unsigned I = 0; I < N; ++I) {
10548 bool IsSystem = I >= NumUserInputs;
10549 InputFile IF = getInputFile(MF, I+1, Complain);
10550 Visitor(IF, IsSystem);
10551 }
10552}
10553
10556 llvm::function_ref<void(FileEntryRef FE)> Visitor) {
10557 unsigned NumInputs = MF.InputFilesLoaded.size();
10558 for (unsigned I = 0; I < NumInputs; ++I) {
10559 InputFileInfo IFI = getInputFileInfo(MF, I + 1);
10560 if (IFI.TopLevel && IFI.ModuleMap)
10561 if (auto FE = getInputFile(MF, I + 1).getFile())
10562 Visitor(*FE);
10563 }
10564}
10565
10566void ASTReader::finishPendingActions() {
10567 while (!PendingIdentifierInfos.empty() ||
10568 !PendingDeducedFunctionTypes.empty() ||
10569 !PendingDeducedVarTypes.empty() || !PendingDeclChains.empty() ||
10570 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
10571 !PendingUpdateRecords.empty() ||
10572 !PendingObjCExtensionIvarRedeclarations.empty()) {
10573 // If any identifiers with corresponding top-level declarations have
10574 // been loaded, load those declarations now.
10575 using TopLevelDeclsMap =
10576 llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2>>;
10577 TopLevelDeclsMap TopLevelDecls;
10578
10579 while (!PendingIdentifierInfos.empty()) {
10580 IdentifierInfo *II = PendingIdentifierInfos.back().first;
10582 std::move(PendingIdentifierInfos.back().second);
10583 PendingIdentifierInfos.pop_back();
10584
10585 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
10586 }
10587
10588 // Load each function type that we deferred loading because it was a
10589 // deduced type that might refer to a local type declared within itself.
10590 for (unsigned I = 0; I != PendingDeducedFunctionTypes.size(); ++I) {
10591 auto *FD = PendingDeducedFunctionTypes[I].first;
10592 FD->setType(GetType(PendingDeducedFunctionTypes[I].second));
10593
10594 if (auto *DT = FD->getReturnType()->getContainedDeducedType()) {
10595 // If we gave a function a deduced return type, remember that we need to
10596 // propagate that along the redeclaration chain.
10597 if (DT->isDeduced()) {
10598 PendingDeducedTypeUpdates.insert(
10599 {FD->getCanonicalDecl(), FD->getReturnType()});
10600 continue;
10601 }
10602
10603 // The function has undeduced DeduceType return type. We hope we can
10604 // find the deduced type by iterating the redecls in other modules
10605 // later.
10606 PendingUndeducedFunctionDecls.push_back(FD);
10607 continue;
10608 }
10609 }
10610 PendingDeducedFunctionTypes.clear();
10611
10612 // Load each variable type that we deferred loading because it was a
10613 // deduced type that might refer to a local type declared within itself.
10614 for (unsigned I = 0; I != PendingDeducedVarTypes.size(); ++I) {
10615 auto *VD = PendingDeducedVarTypes[I].first;
10616 VD->setType(GetType(PendingDeducedVarTypes[I].second));
10617 }
10618 PendingDeducedVarTypes.clear();
10619
10620 // Load pending declaration chains.
10621 for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
10622 loadPendingDeclChain(PendingDeclChains[I].first,
10623 PendingDeclChains[I].second);
10624 PendingDeclChains.clear();
10625
10626 // Make the most recent of the top-level declarations visible.
10627 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
10628 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
10629 IdentifierInfo *II = TLD->first;
10630 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
10631 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
10632 }
10633 }
10634
10635 // Load any pending macro definitions.
10636 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
10637 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
10638 SmallVector<PendingMacroInfo, 2> GlobalIDs;
10639 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
10640 // Initialize the macro history from chained-PCHs ahead of module imports.
10641 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
10642 ++IDIdx) {
10643 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
10644 if (!Info.M->isModule())
10645 resolvePendingMacro(II, Info);
10646 }
10647 // Handle module imports.
10648 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
10649 ++IDIdx) {
10650 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
10651 if (Info.M->isModule())
10652 resolvePendingMacro(II, Info);
10653 }
10654 }
10655 PendingMacroIDs.clear();
10656
10657 // Wire up the DeclContexts for Decls that we delayed setting until
10658 // recursive loading is completed.
10659 while (!PendingDeclContextInfos.empty()) {
10660 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
10661 PendingDeclContextInfos.pop_front();
10662 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
10663 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
10664 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
10665 }
10666
10667 // Perform any pending declaration updates.
10668 while (!PendingUpdateRecords.empty()) {
10669 auto Update = PendingUpdateRecords.pop_back_val();
10670 ReadingKindTracker ReadingKind(Read_Decl, *this);
10671 loadDeclUpdateRecords(Update);
10672 }
10673
10674 while (!PendingObjCExtensionIvarRedeclarations.empty()) {
10675 auto ExtensionsPair = PendingObjCExtensionIvarRedeclarations.back().first;
10676 auto DuplicateIvars =
10677 PendingObjCExtensionIvarRedeclarations.back().second;
10679 StructuralEquivalenceContext Ctx(
10680 ContextObj->getLangOpts(), ExtensionsPair.first->getASTContext(),
10681 ExtensionsPair.second->getASTContext(), NonEquivalentDecls,
10682 StructuralEquivalenceKind::Default, /*StrictTypeSpelling =*/false,
10683 /*Complain =*/false,
10684 /*ErrorOnTagTypeMismatch =*/true);
10685 if (Ctx.IsEquivalent(ExtensionsPair.first, ExtensionsPair.second)) {
10686 // Merge redeclared ivars with their predecessors.
10687 for (auto IvarPair : DuplicateIvars) {
10688 ObjCIvarDecl *Ivar = IvarPair.first, *PrevIvar = IvarPair.second;
10689 // Change semantic DeclContext but keep the lexical one.
10690 Ivar->setDeclContextsImpl(PrevIvar->getDeclContext(),
10691 Ivar->getLexicalDeclContext(),
10692 getContext());
10693 getContext().setPrimaryMergedDecl(Ivar, PrevIvar->getCanonicalDecl());
10694 }
10695 // Invalidate duplicate extension and the cached ivar list.
10696 ExtensionsPair.first->setInvalidDecl();
10697 ExtensionsPair.second->getClassInterface()
10698 ->getDefinition()
10699 ->setIvarList(nullptr);
10700 } else {
10701 for (auto IvarPair : DuplicateIvars) {
10702 Diag(IvarPair.first->getLocation(),
10703 diag::err_duplicate_ivar_declaration)
10704 << IvarPair.first->getIdentifier();
10705 Diag(IvarPair.second->getLocation(), diag::note_previous_definition);
10706 }
10707 }
10708 PendingObjCExtensionIvarRedeclarations.pop_back();
10709 }
10710 }
10711
10712 // At this point, all update records for loaded decls are in place, so any
10713 // fake class definitions should have become real.
10714 assert(PendingFakeDefinitionData.empty() &&
10715 "faked up a class definition but never saw the real one");
10716
10717 // If we deserialized any C++ or Objective-C class definitions, any
10718 // Objective-C protocol definitions, or any redeclarable templates, make sure
10719 // that all redeclarations point to the definitions. Note that this can only
10720 // happen now, after the redeclaration chains have been fully wired.
10721 for (Decl *D : PendingDefinitions) {
10722 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
10723 if (auto *RD = dyn_cast<CXXRecordDecl>(TD)) {
10724 for (auto *R = getMostRecentExistingDecl(RD); R;
10725 R = R->getPreviousDecl()) {
10726 assert((R == D) ==
10727 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
10728 "declaration thinks it's the definition but it isn't");
10729 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
10730 }
10731 }
10732
10733 continue;
10734 }
10735
10736 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
10737 // Make sure that the ObjCInterfaceType points at the definition.
10738 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
10739 ->Decl = ID;
10740
10741 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
10742 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
10743
10744 continue;
10745 }
10746
10747 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
10748 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
10749 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
10750
10751 continue;
10752 }
10753
10754 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
10755 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
10756 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
10757 }
10758 PendingDefinitions.clear();
10759
10760 for (auto [D, Previous] : PendingWarningForDuplicatedDefsInModuleUnits) {
10761 auto hasDefinitionImpl = [this](Decl *D, auto hasDefinitionImpl) {
10762 if (auto *VD = dyn_cast<VarDecl>(D))
10763 return VD->isThisDeclarationADefinition() ||
10764 VD->isThisDeclarationADemotedDefinition();
10765
10766 if (auto *TD = dyn_cast<TagDecl>(D))
10767 return TD->isThisDeclarationADefinition() ||
10768 TD->isThisDeclarationADemotedDefinition();
10769
10770 if (auto *FD = dyn_cast<FunctionDecl>(D))
10771 return FD->isThisDeclarationADefinition() || PendingBodies.count(FD);
10772
10773 if (auto *RTD = dyn_cast<RedeclarableTemplateDecl>(D))
10774 return hasDefinitionImpl(RTD->getTemplatedDecl(), hasDefinitionImpl);
10775
10776 // Conservatively return false here.
10777 return false;
10778 };
10779
10780 auto hasDefinition = [&hasDefinitionImpl](Decl *D) {
10781 return hasDefinitionImpl(D, hasDefinitionImpl);
10782 };
10783
10784 // It is not good to prevent multiple declarations since the forward
10785 // declaration is common. Let's try to avoid duplicated definitions
10786 // only.
10788 continue;
10789
10790 Module *PM = Previous->getOwningModule();
10791 Module *DM = D->getOwningModule();
10792 Diag(D->getLocation(), diag::warn_decls_in_multiple_modules)
10794 << (DM ? DM->getTopLevelModuleName() : "global module");
10795 Diag(Previous->getLocation(), diag::note_also_found);
10796 }
10797 PendingWarningForDuplicatedDefsInModuleUnits.clear();
10798
10799 // Load the bodies of any functions or methods we've encountered. We do
10800 // this now (delayed) so that we can be sure that the declaration chains
10801 // have been fully wired up (hasBody relies on this).
10802 // FIXME: We shouldn't require complete redeclaration chains here.
10803 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
10804 PBEnd = PendingBodies.end();
10805 PB != PBEnd; ++PB) {
10806 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
10807 // FIXME: Check for =delete/=default?
10808 const FunctionDecl *Defn = nullptr;
10809 if (!getContext().getLangOpts().Modules || !FD->hasBody(Defn)) {
10810 FD->setLazyBody(PB->second);
10811 } else {
10812 auto *NonConstDefn = const_cast<FunctionDecl*>(Defn);
10813 mergeDefinitionVisibility(NonConstDefn, FD);
10814
10815 if (!FD->isLateTemplateParsed() &&
10816 !NonConstDefn->isLateTemplateParsed() &&
10817 // We only perform ODR checks for decls not in the explicit
10818 // global module fragment.
10819 !shouldSkipCheckingODR(FD) &&
10820 !shouldSkipCheckingODR(NonConstDefn) &&
10821 FD->getODRHash() != NonConstDefn->getODRHash()) {
10822 if (!isa<CXXMethodDecl>(FD)) {
10823 PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
10824 } else if (FD->getLexicalParent()->isFileContext() &&
10825 NonConstDefn->getLexicalParent()->isFileContext()) {
10826 // Only diagnose out-of-line method definitions. If they are
10827 // in class definitions, then an error will be generated when
10828 // processing the class bodies.
10829 PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
10830 }
10831 }
10832 }
10833 continue;
10834 }
10835
10836 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
10837 if (!getContext().getLangOpts().Modules || !MD->hasBody())
10838 MD->setLazyBody(PB->second);
10839 }
10840 PendingBodies.clear();
10841
10842 // Inform any classes that had members added that they now have more members.
10843 for (auto [RD, MD] : PendingAddedClassMembers) {
10844 RD->addedMember(MD);
10845 }
10846 PendingAddedClassMembers.clear();
10847
10848 // Do some cleanup.
10849 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
10851 PendingMergedDefinitionsToDeduplicate.clear();
10852
10853 // For each decl chain that we wanted to complete while deserializing, mark
10854 // it as "still needs to be completed".
10855 for (Decl *D : PendingIncompleteDeclChains)
10856 markIncompleteDeclChain(D);
10857 PendingIncompleteDeclChains.clear();
10858
10859 assert(PendingIdentifierInfos.empty() &&
10860 "Should be empty at the end of finishPendingActions");
10861 assert(PendingDeducedFunctionTypes.empty() &&
10862 "Should be empty at the end of finishPendingActions");
10863 assert(PendingDeducedVarTypes.empty() &&
10864 "Should be empty at the end of finishPendingActions");
10865 assert(PendingDeclChains.empty() &&
10866 "Should be empty at the end of finishPendingActions");
10867 assert(PendingMacroIDs.empty() &&
10868 "Should be empty at the end of finishPendingActions");
10869 assert(PendingDeclContextInfos.empty() &&
10870 "Should be empty at the end of finishPendingActions");
10871 assert(PendingUpdateRecords.empty() &&
10872 "Should be empty at the end of finishPendingActions");
10873 assert(PendingObjCExtensionIvarRedeclarations.empty() &&
10874 "Should be empty at the end of finishPendingActions");
10875 assert(PendingFakeDefinitionData.empty() &&
10876 "Should be empty at the end of finishPendingActions");
10877 assert(PendingDefinitions.empty() &&
10878 "Should be empty at the end of finishPendingActions");
10879 assert(PendingWarningForDuplicatedDefsInModuleUnits.empty() &&
10880 "Should be empty at the end of finishPendingActions");
10881 assert(PendingBodies.empty() &&
10882 "Should be empty at the end of finishPendingActions");
10883 assert(PendingAddedClassMembers.empty() &&
10884 "Should be empty at the end of finishPendingActions");
10885 assert(PendingMergedDefinitionsToDeduplicate.empty() &&
10886 "Should be empty at the end of finishPendingActions");
10887 assert(PendingIncompleteDeclChains.empty() &&
10888 "Should be empty at the end of finishPendingActions");
10889}
10890
10891void ASTReader::diagnoseOdrViolations() {
10892 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty() &&
10893 PendingRecordOdrMergeFailures.empty() &&
10894 PendingFunctionOdrMergeFailures.empty() &&
10895 PendingEnumOdrMergeFailures.empty() &&
10896 PendingObjCInterfaceOdrMergeFailures.empty() &&
10897 PendingObjCProtocolOdrMergeFailures.empty())
10898 return;
10899
10900 // Trigger the import of the full definition of each class that had any
10901 // odr-merging problems, so we can produce better diagnostics for them.
10902 // These updates may in turn find and diagnose some ODR failures, so take
10903 // ownership of the set first.
10904 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
10905 PendingOdrMergeFailures.clear();
10906 for (auto &Merge : OdrMergeFailures) {
10907 Merge.first->buildLookup();
10908 Merge.first->decls_begin();
10909 Merge.first->bases_begin();
10910 Merge.first->vbases_begin();
10911 for (auto &RecordPair : Merge.second) {
10912 auto *RD = RecordPair.first;
10913 RD->decls_begin();
10914 RD->bases_begin();
10915 RD->vbases_begin();
10916 }
10917 }
10918
10919 // Trigger the import of the full definition of each record in C/ObjC.
10920 auto RecordOdrMergeFailures = std::move(PendingRecordOdrMergeFailures);
10921 PendingRecordOdrMergeFailures.clear();
10922 for (auto &Merge : RecordOdrMergeFailures) {
10923 Merge.first->decls_begin();
10924 for (auto &D : Merge.second)
10925 D->decls_begin();
10926 }
10927
10928 // Trigger the import of the full interface definition.
10929 auto ObjCInterfaceOdrMergeFailures =
10930 std::move(PendingObjCInterfaceOdrMergeFailures);
10931 PendingObjCInterfaceOdrMergeFailures.clear();
10932 for (auto &Merge : ObjCInterfaceOdrMergeFailures) {
10933 Merge.first->decls_begin();
10934 for (auto &InterfacePair : Merge.second)
10935 InterfacePair.first->decls_begin();
10936 }
10937
10938 // Trigger the import of functions.
10939 auto FunctionOdrMergeFailures = std::move(PendingFunctionOdrMergeFailures);
10940 PendingFunctionOdrMergeFailures.clear();
10941 for (auto &Merge : FunctionOdrMergeFailures) {
10942 Merge.first->buildLookup();
10943 Merge.first->decls_begin();
10944 Merge.first->getBody();
10945 for (auto &FD : Merge.second) {
10946 FD->buildLookup();
10947 FD->decls_begin();
10948 FD->getBody();
10949 }
10950 }
10951
10952 // Trigger the import of enums.
10953 auto EnumOdrMergeFailures = std::move(PendingEnumOdrMergeFailures);
10954 PendingEnumOdrMergeFailures.clear();
10955 for (auto &Merge : EnumOdrMergeFailures) {
10956 Merge.first->decls_begin();
10957 for (auto &Enum : Merge.second) {
10958 Enum->decls_begin();
10959 }
10960 }
10961
10962 // Trigger the import of the full protocol definition.
10963 auto ObjCProtocolOdrMergeFailures =
10964 std::move(PendingObjCProtocolOdrMergeFailures);
10965 PendingObjCProtocolOdrMergeFailures.clear();
10966 for (auto &Merge : ObjCProtocolOdrMergeFailures) {
10967 Merge.first->decls_begin();
10968 for (auto &ProtocolPair : Merge.second)
10969 ProtocolPair.first->decls_begin();
10970 }
10971
10972 // For each declaration from a merged context, check that the canonical
10973 // definition of that context also contains a declaration of the same
10974 // entity.
10975 //
10976 // Caution: this loop does things that might invalidate iterators into
10977 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
10978 while (!PendingOdrMergeChecks.empty()) {
10979 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
10980
10981 // FIXME: Skip over implicit declarations for now. This matters for things
10982 // like implicitly-declared special member functions. This isn't entirely
10983 // correct; we can end up with multiple unmerged declarations of the same
10984 // implicit entity.
10985 if (D->isImplicit())
10986 continue;
10987
10988 DeclContext *CanonDef = D->getDeclContext();
10989
10990 bool Found = false;
10991 const Decl *DCanon = D->getCanonicalDecl();
10992
10993 for (auto *RI : D->redecls()) {
10994 if (RI->getLexicalDeclContext() == CanonDef) {
10995 Found = true;
10996 break;
10997 }
10998 }
10999 if (Found)
11000 continue;
11001
11002 // Quick check failed, time to do the slow thing. Note, we can't just
11003 // look up the name of D in CanonDef here, because the member that is
11004 // in CanonDef might not be found by name lookup (it might have been
11005 // replaced by a more recent declaration in the lookup table), and we
11006 // can't necessarily find it in the redeclaration chain because it might
11007 // be merely mergeable, not redeclarable.
11008 llvm::SmallVector<const NamedDecl*, 4> Candidates;
11009 for (auto *CanonMember : CanonDef->decls()) {
11010 if (CanonMember->getCanonicalDecl() == DCanon) {
11011 // This can happen if the declaration is merely mergeable and not
11012 // actually redeclarable (we looked for redeclarations earlier).
11013 //
11014 // FIXME: We should be able to detect this more efficiently, without
11015 // pulling in all of the members of CanonDef.
11016 Found = true;
11017 break;
11018 }
11019 if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
11020 if (ND->getDeclName() == D->getDeclName())
11021 Candidates.push_back(ND);
11022 }
11023
11024 if (!Found) {
11025 // The AST doesn't like TagDecls becoming invalid after they've been
11026 // completed. We only really need to mark FieldDecls as invalid here.
11027 if (!isa<TagDecl>(D))
11028 D->setInvalidDecl();
11029
11030 // Ensure we don't accidentally recursively enter deserialization while
11031 // we're producing our diagnostic.
11032 Deserializing RecursionGuard(this);
11033
11034 std::string CanonDefModule =
11036 cast<Decl>(CanonDef));
11037 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
11039 << CanonDef << CanonDefModule.empty() << CanonDefModule;
11040
11041 if (Candidates.empty())
11042 Diag(cast<Decl>(CanonDef)->getLocation(),
11043 diag::note_module_odr_violation_no_possible_decls) << D;
11044 else {
11045 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
11046 Diag(Candidates[I]->getLocation(),
11047 diag::note_module_odr_violation_possible_decl)
11048 << Candidates[I];
11049 }
11050
11051 DiagnosedOdrMergeFailures.insert(CanonDef);
11052 }
11053 }
11054
11055 if (OdrMergeFailures.empty() && RecordOdrMergeFailures.empty() &&
11056 FunctionOdrMergeFailures.empty() && EnumOdrMergeFailures.empty() &&
11057 ObjCInterfaceOdrMergeFailures.empty() &&
11058 ObjCProtocolOdrMergeFailures.empty())
11059 return;
11060
11061 ODRDiagsEmitter DiagsEmitter(Diags, getContext(),
11062 getPreprocessor().getLangOpts());
11063
11064 // Issue any pending ODR-failure diagnostics.
11065 for (auto &Merge : OdrMergeFailures) {
11066 // If we've already pointed out a specific problem with this class, don't
11067 // bother issuing a general "something's different" diagnostic.
11068 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
11069 continue;
11070
11071 bool Diagnosed = false;
11072 CXXRecordDecl *FirstRecord = Merge.first;
11073 for (auto &RecordPair : Merge.second) {
11074 if (DiagsEmitter.diagnoseMismatch(FirstRecord, RecordPair.first,
11075 RecordPair.second)) {
11076 Diagnosed = true;
11077 break;
11078 }
11079 }
11080
11081 if (!Diagnosed) {
11082 // All definitions are updates to the same declaration. This happens if a
11083 // module instantiates the declaration of a class template specialization
11084 // and two or more other modules instantiate its definition.
11085 //
11086 // FIXME: Indicate which modules had instantiations of this definition.
11087 // FIXME: How can this even happen?
11088 Diag(Merge.first->getLocation(),
11089 diag::err_module_odr_violation_different_instantiations)
11090 << Merge.first;
11091 }
11092 }
11093
11094 // Issue any pending ODR-failure diagnostics for RecordDecl in C/ObjC. Note
11095 // that in C++ this is done as a part of CXXRecordDecl ODR checking.
11096 for (auto &Merge : RecordOdrMergeFailures) {
11097 // If we've already pointed out a specific problem with this class, don't
11098 // bother issuing a general "something's different" diagnostic.
11099 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
11100 continue;
11101
11102 RecordDecl *FirstRecord = Merge.first;
11103 bool Diagnosed = false;
11104 for (auto *SecondRecord : Merge.second) {
11105 if (DiagsEmitter.diagnoseMismatch(FirstRecord, SecondRecord)) {
11106 Diagnosed = true;
11107 break;
11108 }
11109 }
11110 (void)Diagnosed;
11111 assert(Diagnosed && "Unable to emit ODR diagnostic.");
11112 }
11113
11114 // Issue ODR failures diagnostics for functions.
11115 for (auto &Merge : FunctionOdrMergeFailures) {
11116 FunctionDecl *FirstFunction = Merge.first;
11117 bool Diagnosed = false;
11118 for (auto &SecondFunction : Merge.second) {
11119 if (DiagsEmitter.diagnoseMismatch(FirstFunction, SecondFunction)) {
11120 Diagnosed = true;
11121 break;
11122 }
11123 }
11124 (void)Diagnosed;
11125 assert(Diagnosed && "Unable to emit ODR diagnostic.");
11126 }
11127
11128 // Issue ODR failures diagnostics for enums.
11129 for (auto &Merge : EnumOdrMergeFailures) {
11130 // If we've already pointed out a specific problem with this enum, don't
11131 // bother issuing a general "something's different" diagnostic.
11132 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
11133 continue;
11134
11135 EnumDecl *FirstEnum = Merge.first;
11136 bool Diagnosed = false;
11137 for (auto &SecondEnum : Merge.second) {
11138 if (DiagsEmitter.diagnoseMismatch(FirstEnum, SecondEnum)) {
11139 Diagnosed = true;
11140 break;
11141 }
11142 }
11143 (void)Diagnosed;
11144 assert(Diagnosed && "Unable to emit ODR diagnostic.");
11145 }
11146
11147 for (auto &Merge : ObjCInterfaceOdrMergeFailures) {
11148 // If we've already pointed out a specific problem with this interface,
11149 // don't bother issuing a general "something's different" diagnostic.
11150 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
11151 continue;
11152
11153 bool Diagnosed = false;
11154 ObjCInterfaceDecl *FirstID = Merge.first;
11155 for (auto &InterfacePair : Merge.second) {
11156 if (DiagsEmitter.diagnoseMismatch(FirstID, InterfacePair.first,
11157 InterfacePair.second)) {
11158 Diagnosed = true;
11159 break;
11160 }
11161 }
11162 (void)Diagnosed;
11163 assert(Diagnosed && "Unable to emit ODR diagnostic.");
11164 }
11165
11166 for (auto &Merge : ObjCProtocolOdrMergeFailures) {
11167 // If we've already pointed out a specific problem with this protocol,
11168 // don't bother issuing a general "something's different" diagnostic.
11169 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
11170 continue;
11171
11172 ObjCProtocolDecl *FirstProtocol = Merge.first;
11173 bool Diagnosed = false;
11174 for (auto &ProtocolPair : Merge.second) {
11175 if (DiagsEmitter.diagnoseMismatch(FirstProtocol, ProtocolPair.first,
11176 ProtocolPair.second)) {
11177 Diagnosed = true;
11178 break;
11179 }
11180 }
11181 (void)Diagnosed;
11182 assert(Diagnosed && "Unable to emit ODR diagnostic.");
11183 }
11184}
11185
11187 if (llvm::Timer *T = ReadTimer.get();
11188 ++NumCurrentElementsDeserializing == 1 && T)
11189 ReadTimeRegion.emplace(T);
11190}
11191
11193 assert(NumCurrentElementsDeserializing &&
11194 "FinishedDeserializing not paired with StartedDeserializing");
11195 if (NumCurrentElementsDeserializing == 1) {
11196 // We decrease NumCurrentElementsDeserializing only after pending actions
11197 // are finished, to avoid recursively re-calling finishPendingActions().
11198 finishPendingActions();
11199 }
11200 --NumCurrentElementsDeserializing;
11201
11202 if (NumCurrentElementsDeserializing == 0) {
11203 {
11204 // Guard variable to avoid recursively entering the process of passing
11205 // decls to consumer.
11206 SaveAndRestore GuardPassingDeclsToConsumer(CanPassDeclsToConsumer,
11207 /*NewValue=*/false);
11208
11209 // Propagate exception specification and deduced type updates along
11210 // redeclaration chains.
11211 //
11212 // We do this now rather than in finishPendingActions because we want to
11213 // be able to walk the complete redeclaration chains of the updated decls.
11214 while (!PendingExceptionSpecUpdates.empty() ||
11215 !PendingDeducedTypeUpdates.empty() ||
11216 !PendingUndeducedFunctionDecls.empty()) {
11217 auto ESUpdates = std::move(PendingExceptionSpecUpdates);
11218 PendingExceptionSpecUpdates.clear();
11219 for (auto Update : ESUpdates) {
11220 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
11221 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
11222 auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
11223 if (auto *Listener = getContext().getASTMutationListener())
11224 Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
11225 for (auto *Redecl : Update.second->redecls())
11227 }
11228
11229 auto DTUpdates = std::move(PendingDeducedTypeUpdates);
11230 PendingDeducedTypeUpdates.clear();
11231 for (auto Update : DTUpdates) {
11232 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
11233 // FIXME: If the return type is already deduced, check that it
11234 // matches.
11236 Update.second);
11237 }
11238
11239 auto UDTUpdates = std::move(PendingUndeducedFunctionDecls);
11240 PendingUndeducedFunctionDecls.clear();
11241 // We hope we can find the deduced type for the functions by iterating
11242 // redeclarations in other modules.
11243 for (FunctionDecl *UndeducedFD : UDTUpdates)
11244 (void)UndeducedFD->getMostRecentDecl();
11245 }
11246
11247 ReadTimeRegion.reset();
11248
11249 diagnoseOdrViolations();
11250 }
11251
11252 // We are not in recursive loading, so it's safe to pass the "interesting"
11253 // decls to the consumer.
11254 if (Consumer)
11255 PassInterestingDeclsToConsumer();
11256 }
11257}
11258
11259void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
11260 if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) {
11261 // Remove any fake results before adding any real ones.
11262 auto It = PendingFakeLookupResults.find(II);
11263 if (It != PendingFakeLookupResults.end()) {
11264 for (auto *ND : It->second)
11265 SemaObj->IdResolver.RemoveDecl(ND);
11266 // FIXME: this works around module+PCH performance issue.
11267 // Rather than erase the result from the map, which is O(n), just clear
11268 // the vector of NamedDecls.
11269 It->second.clear();
11270 }
11271 }
11272
11273 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
11274 SemaObj->TUScope->AddDecl(D);
11275 } else if (SemaObj->TUScope) {
11276 // Adding the decl to IdResolver may have failed because it was already in
11277 // (even though it was not added in scope). If it is already in, make sure
11278 // it gets in the scope as well.
11279 if (llvm::is_contained(SemaObj->IdResolver.decls(Name), D))
11280 SemaObj->TUScope->AddDecl(D);
11281 }
11282}
11283
11285 ASTContext *Context,
11286 const PCHContainerReader &PCHContainerRdr,
11287 const CodeGenOptions &CodeGenOpts,
11288 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
11289 StringRef isysroot,
11290 DisableValidationForModuleKind DisableValidationKind,
11291 bool AllowASTWithCompilerErrors,
11292 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
11293 bool ForceValidateUserInputs,
11294 bool ValidateASTInputFilesContent, bool UseGlobalIndex,
11295 std::unique_ptr<llvm::Timer> ReadTimer)
11296 : Listener(bool(DisableValidationKind & DisableValidationForModuleKind::PCH)
11298 : cast<ASTReaderListener>(new PCHValidator(PP, *this))),
11299 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
11300 PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()),
11301 StackHandler(Diags), PP(PP), ContextObj(Context),
11302 CodeGenOpts(CodeGenOpts),
11303 ModuleMgr(PP.getFileManager(), ModCache, PCHContainerRdr,
11304 PP.getHeaderSearchInfo()),
11305 DummyIdResolver(PP), ReadTimer(std::move(ReadTimer)), isysroot(isysroot),
11306 DisableValidationKind(DisableValidationKind),
11307 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
11308 AllowConfigurationMismatch(AllowConfigurationMismatch),
11309 ValidateSystemInputs(ValidateSystemInputs),
11310 ForceValidateUserInputs(ForceValidateUserInputs),
11311 ValidateASTInputFilesContent(ValidateASTInputFilesContent),
11312 UseGlobalIndex(UseGlobalIndex), CurrSwitchCaseStmts(&SwitchCaseStmts) {
11313 SourceMgr.setExternalSLocEntrySource(this);
11314
11315 PathBuf.reserve(256);
11316
11317 for (const auto &Ext : Extensions) {
11318 auto BlockName = Ext->getExtensionMetadata().BlockName;
11319 auto Known = ModuleFileExtensions.find(BlockName);
11320 if (Known != ModuleFileExtensions.end()) {
11321 Diags.Report(diag::warn_duplicate_module_file_extension)
11322 << BlockName;
11323 continue;
11324 }
11325
11326 ModuleFileExtensions.insert({BlockName, Ext});
11327 }
11328}
11329
11331 if (OwnsDeserializationListener)
11332 delete DeserializationListener;
11333}
11334
11336 return SemaObj ? SemaObj->IdResolver : DummyIdResolver;
11337}
11338
11340 unsigned AbbrevID) {
11341 Idx = 0;
11342 Record.clear();
11343 return Cursor.readRecord(AbbrevID, Record);
11344}
11345//===----------------------------------------------------------------------===//
11346//// OMPClauseReader implementation
11347////===----------------------------------------------------------------------===//
11348
11349// This has to be in namespace clang because it's friended by all
11350// of the OMP clauses.
11351namespace clang {
11352
11353class OMPClauseReader : public OMPClauseVisitor<OMPClauseReader> {
11354 ASTRecordReader &Record;
11355 ASTContext &Context;
11356
11357public:
11359 : Record(Record), Context(Record.getContext()) {}
11360#define GEN_CLANG_CLAUSE_CLASS
11361#define CLAUSE_CLASS(Enum, Str, Class) void Visit##Class(Class *C);
11362#include "llvm/Frontend/OpenMP/OMP.inc"
11366};
11367
11368} // end namespace clang
11369
11373
11375 OMPClause *C = nullptr;
11376 switch (llvm::omp::Clause(Record.readInt())) {
11377 case llvm::omp::OMPC_if:
11378 C = new (Context) OMPIfClause();
11379 break;
11380 case llvm::omp::OMPC_final:
11381 C = new (Context) OMPFinalClause();
11382 break;
11383 case llvm::omp::OMPC_num_threads:
11384 C = new (Context) OMPNumThreadsClause();
11385 break;
11386 case llvm::omp::OMPC_safelen:
11387 C = new (Context) OMPSafelenClause();
11388 break;
11389 case llvm::omp::OMPC_simdlen:
11390 C = new (Context) OMPSimdlenClause();
11391 break;
11392 case llvm::omp::OMPC_sizes: {
11393 unsigned NumSizes = Record.readInt();
11394 C = OMPSizesClause::CreateEmpty(Context, NumSizes);
11395 break;
11396 }
11397 case llvm::omp::OMPC_permutation: {
11398 unsigned NumLoops = Record.readInt();
11399 C = OMPPermutationClause::CreateEmpty(Context, NumLoops);
11400 break;
11401 }
11402 case llvm::omp::OMPC_full:
11403 C = OMPFullClause::CreateEmpty(Context);
11404 break;
11405 case llvm::omp::OMPC_partial:
11407 break;
11408 case llvm::omp::OMPC_looprange:
11410 break;
11411 case llvm::omp::OMPC_allocator:
11412 C = new (Context) OMPAllocatorClause();
11413 break;
11414 case llvm::omp::OMPC_collapse:
11415 C = new (Context) OMPCollapseClause();
11416 break;
11417 case llvm::omp::OMPC_default:
11418 C = new (Context) OMPDefaultClause();
11419 break;
11420 case llvm::omp::OMPC_proc_bind:
11421 C = new (Context) OMPProcBindClause();
11422 break;
11423 case llvm::omp::OMPC_schedule:
11424 C = new (Context) OMPScheduleClause();
11425 break;
11426 case llvm::omp::OMPC_ordered:
11427 C = OMPOrderedClause::CreateEmpty(Context, Record.readInt());
11428 break;
11429 case llvm::omp::OMPC_nowait:
11430 C = new (Context) OMPNowaitClause();
11431 break;
11432 case llvm::omp::OMPC_untied:
11433 C = new (Context) OMPUntiedClause();
11434 break;
11435 case llvm::omp::OMPC_mergeable:
11436 C = new (Context) OMPMergeableClause();
11437 break;
11438 case llvm::omp::OMPC_threadset:
11439 C = new (Context) OMPThreadsetClause();
11440 break;
11441 case llvm::omp::OMPC_transparent:
11442 C = new (Context) OMPTransparentClause();
11443 break;
11444 case llvm::omp::OMPC_read:
11445 C = new (Context) OMPReadClause();
11446 break;
11447 case llvm::omp::OMPC_write:
11448 C = new (Context) OMPWriteClause();
11449 break;
11450 case llvm::omp::OMPC_update:
11451 C = OMPUpdateClause::CreateEmpty(Context, Record.readInt());
11452 break;
11453 case llvm::omp::OMPC_capture:
11454 C = new (Context) OMPCaptureClause();
11455 break;
11456 case llvm::omp::OMPC_compare:
11457 C = new (Context) OMPCompareClause();
11458 break;
11459 case llvm::omp::OMPC_fail:
11460 C = new (Context) OMPFailClause();
11461 break;
11462 case llvm::omp::OMPC_seq_cst:
11463 C = new (Context) OMPSeqCstClause();
11464 break;
11465 case llvm::omp::OMPC_acq_rel:
11466 C = new (Context) OMPAcqRelClause();
11467 break;
11468 case llvm::omp::OMPC_absent: {
11469 unsigned NumKinds = Record.readInt();
11470 C = OMPAbsentClause::CreateEmpty(Context, NumKinds);
11471 break;
11472 }
11473 case llvm::omp::OMPC_holds:
11474 C = new (Context) OMPHoldsClause();
11475 break;
11476 case llvm::omp::OMPC_contains: {
11477 unsigned NumKinds = Record.readInt();
11478 C = OMPContainsClause::CreateEmpty(Context, NumKinds);
11479 break;
11480 }
11481 case llvm::omp::OMPC_no_openmp:
11482 C = new (Context) OMPNoOpenMPClause();
11483 break;
11484 case llvm::omp::OMPC_no_openmp_routines:
11485 C = new (Context) OMPNoOpenMPRoutinesClause();
11486 break;
11487 case llvm::omp::OMPC_no_openmp_constructs:
11488 C = new (Context) OMPNoOpenMPConstructsClause();
11489 break;
11490 case llvm::omp::OMPC_no_parallelism:
11491 C = new (Context) OMPNoParallelismClause();
11492 break;
11493 case llvm::omp::OMPC_acquire:
11494 C = new (Context) OMPAcquireClause();
11495 break;
11496 case llvm::omp::OMPC_release:
11497 C = new (Context) OMPReleaseClause();
11498 break;
11499 case llvm::omp::OMPC_relaxed:
11500 C = new (Context) OMPRelaxedClause();
11501 break;
11502 case llvm::omp::OMPC_weak:
11503 C = new (Context) OMPWeakClause();
11504 break;
11505 case llvm::omp::OMPC_threads:
11506 C = new (Context) OMPThreadsClause();
11507 break;
11508 case llvm::omp::OMPC_simd:
11509 C = new (Context) OMPSIMDClause();
11510 break;
11511 case llvm::omp::OMPC_nogroup:
11512 C = new (Context) OMPNogroupClause();
11513 break;
11514 case llvm::omp::OMPC_unified_address:
11515 C = new (Context) OMPUnifiedAddressClause();
11516 break;
11517 case llvm::omp::OMPC_unified_shared_memory:
11518 C = new (Context) OMPUnifiedSharedMemoryClause();
11519 break;
11520 case llvm::omp::OMPC_reverse_offload:
11521 C = new (Context) OMPReverseOffloadClause();
11522 break;
11523 case llvm::omp::OMPC_dynamic_allocators:
11524 C = new (Context) OMPDynamicAllocatorsClause();
11525 break;
11526 case llvm::omp::OMPC_atomic_default_mem_order:
11527 C = new (Context) OMPAtomicDefaultMemOrderClause();
11528 break;
11529 case llvm::omp::OMPC_self_maps:
11530 C = new (Context) OMPSelfMapsClause();
11531 break;
11532 case llvm::omp::OMPC_at:
11533 C = new (Context) OMPAtClause();
11534 break;
11535 case llvm::omp::OMPC_severity:
11536 C = new (Context) OMPSeverityClause();
11537 break;
11538 case llvm::omp::OMPC_message:
11539 C = new (Context) OMPMessageClause();
11540 break;
11541 case llvm::omp::OMPC_private:
11542 C = OMPPrivateClause::CreateEmpty(Context, Record.readInt());
11543 break;
11544 case llvm::omp::OMPC_firstprivate:
11545 C = OMPFirstprivateClause::CreateEmpty(Context, Record.readInt());
11546 break;
11547 case llvm::omp::OMPC_lastprivate:
11548 C = OMPLastprivateClause::CreateEmpty(Context, Record.readInt());
11549 break;
11550 case llvm::omp::OMPC_shared:
11551 C = OMPSharedClause::CreateEmpty(Context, Record.readInt());
11552 break;
11553 case llvm::omp::OMPC_reduction: {
11554 unsigned N = Record.readInt();
11555 auto Modifier = Record.readEnum<OpenMPReductionClauseModifier>();
11556 C = OMPReductionClause::CreateEmpty(Context, N, Modifier);
11557 break;
11558 }
11559 case llvm::omp::OMPC_task_reduction:
11560 C = OMPTaskReductionClause::CreateEmpty(Context, Record.readInt());
11561 break;
11562 case llvm::omp::OMPC_in_reduction:
11563 C = OMPInReductionClause::CreateEmpty(Context, Record.readInt());
11564 break;
11565 case llvm::omp::OMPC_linear:
11566 C = OMPLinearClause::CreateEmpty(Context, Record.readInt());
11567 break;
11568 case llvm::omp::OMPC_aligned:
11569 C = OMPAlignedClause::CreateEmpty(Context, Record.readInt());
11570 break;
11571 case llvm::omp::OMPC_copyin:
11572 C = OMPCopyinClause::CreateEmpty(Context, Record.readInt());
11573 break;
11574 case llvm::omp::OMPC_copyprivate:
11575 C = OMPCopyprivateClause::CreateEmpty(Context, Record.readInt());
11576 break;
11577 case llvm::omp::OMPC_flush:
11578 C = OMPFlushClause::CreateEmpty(Context, Record.readInt());
11579 break;
11580 case llvm::omp::OMPC_depobj:
11582 break;
11583 case llvm::omp::OMPC_depend: {
11584 unsigned NumVars = Record.readInt();
11585 unsigned NumLoops = Record.readInt();
11586 C = OMPDependClause::CreateEmpty(Context, NumVars, NumLoops);
11587 break;
11588 }
11589 case llvm::omp::OMPC_device:
11590 C = new (Context) OMPDeviceClause();
11591 break;
11592 case llvm::omp::OMPC_map: {
11594 Sizes.NumVars = Record.readInt();
11595 Sizes.NumUniqueDeclarations = Record.readInt();
11596 Sizes.NumComponentLists = Record.readInt();
11597 Sizes.NumComponents = Record.readInt();
11598 C = OMPMapClause::CreateEmpty(Context, Sizes);
11599 break;
11600 }
11601 case llvm::omp::OMPC_num_teams:
11602 C = OMPNumTeamsClause::CreateEmpty(Context, Record.readInt());
11603 break;
11604 case llvm::omp::OMPC_thread_limit:
11605 C = OMPThreadLimitClause::CreateEmpty(Context, Record.readInt());
11606 break;
11607 case llvm::omp::OMPC_priority:
11608 C = new (Context) OMPPriorityClause();
11609 break;
11610 case llvm::omp::OMPC_grainsize:
11611 C = new (Context) OMPGrainsizeClause();
11612 break;
11613 case llvm::omp::OMPC_num_tasks:
11614 C = new (Context) OMPNumTasksClause();
11615 break;
11616 case llvm::omp::OMPC_hint:
11617 C = new (Context) OMPHintClause();
11618 break;
11619 case llvm::omp::OMPC_dist_schedule:
11620 C = new (Context) OMPDistScheduleClause();
11621 break;
11622 case llvm::omp::OMPC_defaultmap:
11623 C = new (Context) OMPDefaultmapClause();
11624 break;
11625 case llvm::omp::OMPC_to: {
11627 Sizes.NumVars = Record.readInt();
11628 Sizes.NumUniqueDeclarations = Record.readInt();
11629 Sizes.NumComponentLists = Record.readInt();
11630 Sizes.NumComponents = Record.readInt();
11631 C = OMPToClause::CreateEmpty(Context, Sizes);
11632 break;
11633 }
11634 case llvm::omp::OMPC_from: {
11636 Sizes.NumVars = Record.readInt();
11637 Sizes.NumUniqueDeclarations = Record.readInt();
11638 Sizes.NumComponentLists = Record.readInt();
11639 Sizes.NumComponents = Record.readInt();
11640 C = OMPFromClause::CreateEmpty(Context, Sizes);
11641 break;
11642 }
11643 case llvm::omp::OMPC_use_device_ptr: {
11645 Sizes.NumVars = Record.readInt();
11646 Sizes.NumUniqueDeclarations = Record.readInt();
11647 Sizes.NumComponentLists = Record.readInt();
11648 Sizes.NumComponents = Record.readInt();
11649 C = OMPUseDevicePtrClause::CreateEmpty(Context, Sizes);
11650 break;
11651 }
11652 case llvm::omp::OMPC_use_device_addr: {
11654 Sizes.NumVars = Record.readInt();
11655 Sizes.NumUniqueDeclarations = Record.readInt();
11656 Sizes.NumComponentLists = Record.readInt();
11657 Sizes.NumComponents = Record.readInt();
11658 C = OMPUseDeviceAddrClause::CreateEmpty(Context, Sizes);
11659 break;
11660 }
11661 case llvm::omp::OMPC_is_device_ptr: {
11663 Sizes.NumVars = Record.readInt();
11664 Sizes.NumUniqueDeclarations = Record.readInt();
11665 Sizes.NumComponentLists = Record.readInt();
11666 Sizes.NumComponents = Record.readInt();
11667 C = OMPIsDevicePtrClause::CreateEmpty(Context, Sizes);
11668 break;
11669 }
11670 case llvm::omp::OMPC_has_device_addr: {
11672 Sizes.NumVars = Record.readInt();
11673 Sizes.NumUniqueDeclarations = Record.readInt();
11674 Sizes.NumComponentLists = Record.readInt();
11675 Sizes.NumComponents = Record.readInt();
11676 C = OMPHasDeviceAddrClause::CreateEmpty(Context, Sizes);
11677 break;
11678 }
11679 case llvm::omp::OMPC_allocate:
11680 C = OMPAllocateClause::CreateEmpty(Context, Record.readInt());
11681 break;
11682 case llvm::omp::OMPC_nontemporal:
11683 C = OMPNontemporalClause::CreateEmpty(Context, Record.readInt());
11684 break;
11685 case llvm::omp::OMPC_inclusive:
11686 C = OMPInclusiveClause::CreateEmpty(Context, Record.readInt());
11687 break;
11688 case llvm::omp::OMPC_exclusive:
11689 C = OMPExclusiveClause::CreateEmpty(Context, Record.readInt());
11690 break;
11691 case llvm::omp::OMPC_order:
11692 C = new (Context) OMPOrderClause();
11693 break;
11694 case llvm::omp::OMPC_init:
11695 C = OMPInitClause::CreateEmpty(Context, Record.readInt());
11696 break;
11697 case llvm::omp::OMPC_use:
11698 C = new (Context) OMPUseClause();
11699 break;
11700 case llvm::omp::OMPC_destroy:
11701 C = new (Context) OMPDestroyClause();
11702 break;
11703 case llvm::omp::OMPC_novariants:
11704 C = new (Context) OMPNovariantsClause();
11705 break;
11706 case llvm::omp::OMPC_nocontext:
11707 C = new (Context) OMPNocontextClause();
11708 break;
11709 case llvm::omp::OMPC_detach:
11710 C = new (Context) OMPDetachClause();
11711 break;
11712 case llvm::omp::OMPC_uses_allocators:
11713 C = OMPUsesAllocatorsClause::CreateEmpty(Context, Record.readInt());
11714 break;
11715 case llvm::omp::OMPC_affinity:
11716 C = OMPAffinityClause::CreateEmpty(Context, Record.readInt());
11717 break;
11718 case llvm::omp::OMPC_filter:
11719 C = new (Context) OMPFilterClause();
11720 break;
11721 case llvm::omp::OMPC_bind:
11722 C = OMPBindClause::CreateEmpty(Context);
11723 break;
11724 case llvm::omp::OMPC_align:
11725 C = new (Context) OMPAlignClause();
11726 break;
11727 case llvm::omp::OMPC_ompx_dyn_cgroup_mem:
11728 C = new (Context) OMPXDynCGroupMemClause();
11729 break;
11730 case llvm::omp::OMPC_dyn_groupprivate:
11731 C = new (Context) OMPDynGroupprivateClause();
11732 break;
11733 case llvm::omp::OMPC_doacross: {
11734 unsigned NumVars = Record.readInt();
11735 unsigned NumLoops = Record.readInt();
11736 C = OMPDoacrossClause::CreateEmpty(Context, NumVars, NumLoops);
11737 break;
11738 }
11739 case llvm::omp::OMPC_ompx_attribute:
11740 C = new (Context) OMPXAttributeClause();
11741 break;
11742 case llvm::omp::OMPC_ompx_bare:
11743 C = new (Context) OMPXBareClause();
11744 break;
11745#define OMP_CLAUSE_NO_CLASS(Enum, Str) \
11746 case llvm::omp::Enum: \
11747 break;
11748#include "llvm/Frontend/OpenMP/OMPKinds.def"
11749 default:
11750 break;
11751 }
11752 assert(C && "Unknown OMPClause type");
11753
11754 Visit(C);
11755 C->setLocStart(Record.readSourceLocation());
11756 C->setLocEnd(Record.readSourceLocation());
11757
11758 return C;
11759}
11760
11762 C->setPreInitStmt(Record.readSubStmt(),
11763 static_cast<OpenMPDirectiveKind>(Record.readInt()));
11764}
11765
11768 C->setPostUpdateExpr(Record.readSubExpr());
11769}
11770
11771void OMPClauseReader::VisitOMPIfClause(OMPIfClause *C) {
11773 C->setNameModifier(static_cast<OpenMPDirectiveKind>(Record.readInt()));
11774 C->setNameModifierLoc(Record.readSourceLocation());
11775 C->setColonLoc(Record.readSourceLocation());
11776 C->setCondition(Record.readSubExpr());
11777 C->setLParenLoc(Record.readSourceLocation());
11778}
11779
11780void OMPClauseReader::VisitOMPFinalClause(OMPFinalClause *C) {
11782 C->setCondition(Record.readSubExpr());
11783 C->setLParenLoc(Record.readSourceLocation());
11784}
11785
11786void OMPClauseReader::VisitOMPNumThreadsClause(OMPNumThreadsClause *C) {
11788 C->setModifier(Record.readEnum<OpenMPNumThreadsClauseModifier>());
11789 C->setNumThreads(Record.readSubExpr());
11790 C->setModifierLoc(Record.readSourceLocation());
11791 C->setLParenLoc(Record.readSourceLocation());
11792}
11793
11794void OMPClauseReader::VisitOMPSafelenClause(OMPSafelenClause *C) {
11795 C->setSafelen(Record.readSubExpr());
11796 C->setLParenLoc(Record.readSourceLocation());
11797}
11798
11799void OMPClauseReader::VisitOMPSimdlenClause(OMPSimdlenClause *C) {
11800 C->setSimdlen(Record.readSubExpr());
11801 C->setLParenLoc(Record.readSourceLocation());
11802}
11803
11804void OMPClauseReader::VisitOMPSizesClause(OMPSizesClause *C) {
11805 for (Expr *&E : C->getSizesRefs())
11806 E = Record.readSubExpr();
11807 C->setLParenLoc(Record.readSourceLocation());
11808}
11809
11810void OMPClauseReader::VisitOMPPermutationClause(OMPPermutationClause *C) {
11811 for (Expr *&E : C->getArgsRefs())
11812 E = Record.readSubExpr();
11813 C->setLParenLoc(Record.readSourceLocation());
11814}
11815
11816void OMPClauseReader::VisitOMPFullClause(OMPFullClause *C) {}
11817
11818void OMPClauseReader::VisitOMPPartialClause(OMPPartialClause *C) {
11819 C->setFactor(Record.readSubExpr());
11820 C->setLParenLoc(Record.readSourceLocation());
11821}
11822
11823void OMPClauseReader::VisitOMPLoopRangeClause(OMPLoopRangeClause *C) {
11824 C->setFirst(Record.readSubExpr());
11825 C->setCount(Record.readSubExpr());
11826 C->setLParenLoc(Record.readSourceLocation());
11827 C->setFirstLoc(Record.readSourceLocation());
11828 C->setCountLoc(Record.readSourceLocation());
11829}
11830
11831void OMPClauseReader::VisitOMPAllocatorClause(OMPAllocatorClause *C) {
11832 C->setAllocator(Record.readExpr());
11833 C->setLParenLoc(Record.readSourceLocation());
11834}
11835
11836void OMPClauseReader::VisitOMPCollapseClause(OMPCollapseClause *C) {
11837 C->setNumForLoops(Record.readSubExpr());
11838 C->setLParenLoc(Record.readSourceLocation());
11839}
11840
11841void OMPClauseReader::VisitOMPDefaultClause(OMPDefaultClause *C) {
11842 C->setDefaultKind(static_cast<llvm::omp::DefaultKind>(Record.readInt()));
11843 C->setLParenLoc(Record.readSourceLocation());
11844 C->setDefaultKindKwLoc(Record.readSourceLocation());
11845 C->setDefaultVariableCategory(
11846 Record.readEnum<OpenMPDefaultClauseVariableCategory>());
11847 C->setDefaultVariableCategoryLocation(Record.readSourceLocation());
11848}
11849
11850// Read the parameter of threadset clause. This will have been saved when
11851// OMPClauseWriter is called.
11852void OMPClauseReader::VisitOMPThreadsetClause(OMPThreadsetClause *C) {
11853 C->setLParenLoc(Record.readSourceLocation());
11854 SourceLocation ThreadsetKindLoc = Record.readSourceLocation();
11855 C->setThreadsetKindLoc(ThreadsetKindLoc);
11856 OpenMPThreadsetKind TKind =
11857 static_cast<OpenMPThreadsetKind>(Record.readInt());
11858 C->setThreadsetKind(TKind);
11859}
11860
11861void OMPClauseReader::VisitOMPTransparentClause(OMPTransparentClause *C) {
11862 C->setLParenLoc(Record.readSourceLocation());
11863 C->setImpexTypeKind(Record.readSubExpr());
11864}
11865
11866void OMPClauseReader::VisitOMPProcBindClause(OMPProcBindClause *C) {
11867 C->setProcBindKind(static_cast<llvm::omp::ProcBindKind>(Record.readInt()));
11868 C->setLParenLoc(Record.readSourceLocation());
11869 C->setProcBindKindKwLoc(Record.readSourceLocation());
11870}
11871
11872void OMPClauseReader::VisitOMPScheduleClause(OMPScheduleClause *C) {
11874 C->setScheduleKind(
11875 static_cast<OpenMPScheduleClauseKind>(Record.readInt()));
11876 C->setFirstScheduleModifier(
11877 static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
11878 C->setSecondScheduleModifier(
11879 static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
11880 C->setChunkSize(Record.readSubExpr());
11881 C->setLParenLoc(Record.readSourceLocation());
11882 C->setFirstScheduleModifierLoc(Record.readSourceLocation());
11883 C->setSecondScheduleModifierLoc(Record.readSourceLocation());
11884 C->setScheduleKindLoc(Record.readSourceLocation());
11885 C->setCommaLoc(Record.readSourceLocation());
11886}
11887
11888void OMPClauseReader::VisitOMPOrderedClause(OMPOrderedClause *C) {
11889 C->setNumForLoops(Record.readSubExpr());
11890 for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
11891 C->setLoopNumIterations(I, Record.readSubExpr());
11892 for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
11893 C->setLoopCounter(I, Record.readSubExpr());
11894 C->setLParenLoc(Record.readSourceLocation());
11895}
11896
11897void OMPClauseReader::VisitOMPDetachClause(OMPDetachClause *C) {
11898 C->setEventHandler(Record.readSubExpr());
11899 C->setLParenLoc(Record.readSourceLocation());
11900}
11901
11902void OMPClauseReader::VisitOMPNowaitClause(OMPNowaitClause *C) {
11903 C->setCondition(Record.readSubExpr());
11904 C->setLParenLoc(Record.readSourceLocation());
11905}
11906
11907void OMPClauseReader::VisitOMPUntiedClause(OMPUntiedClause *) {}
11908
11909void OMPClauseReader::VisitOMPMergeableClause(OMPMergeableClause *) {}
11910
11911void OMPClauseReader::VisitOMPReadClause(OMPReadClause *) {}
11912
11913void OMPClauseReader::VisitOMPWriteClause(OMPWriteClause *) {}
11914
11915void OMPClauseReader::VisitOMPUpdateClause(OMPUpdateClause *C) {
11916 if (C->isExtended()) {
11917 C->setLParenLoc(Record.readSourceLocation());
11918 C->setArgumentLoc(Record.readSourceLocation());
11919 C->setDependencyKind(Record.readEnum<OpenMPDependClauseKind>());
11920 }
11921}
11922
11923void OMPClauseReader::VisitOMPCaptureClause(OMPCaptureClause *) {}
11924
11925void OMPClauseReader::VisitOMPCompareClause(OMPCompareClause *) {}
11926
11927// Read the parameter of fail clause. This will have been saved when
11928// OMPClauseWriter is called.
11929void OMPClauseReader::VisitOMPFailClause(OMPFailClause *C) {
11930 C->setLParenLoc(Record.readSourceLocation());
11931 SourceLocation FailParameterLoc = Record.readSourceLocation();
11932 C->setFailParameterLoc(FailParameterLoc);
11933 OpenMPClauseKind CKind = Record.readEnum<OpenMPClauseKind>();
11934 C->setFailParameter(CKind);
11935}
11936
11937void OMPClauseReader::VisitOMPAbsentClause(OMPAbsentClause *C) {
11938 unsigned Count = C->getDirectiveKinds().size();
11939 C->setLParenLoc(Record.readSourceLocation());
11940 llvm::SmallVector<OpenMPDirectiveKind, 4> DKVec;
11941 DKVec.reserve(Count);
11942 for (unsigned I = 0; I < Count; I++) {
11943 DKVec.push_back(Record.readEnum<OpenMPDirectiveKind>());
11944 }
11945 C->setDirectiveKinds(DKVec);
11946}
11947
11948void OMPClauseReader::VisitOMPHoldsClause(OMPHoldsClause *C) {
11949 C->setExpr(Record.readExpr());
11950 C->setLParenLoc(Record.readSourceLocation());
11951}
11952
11953void OMPClauseReader::VisitOMPContainsClause(OMPContainsClause *C) {
11954 unsigned Count = C->getDirectiveKinds().size();
11955 C->setLParenLoc(Record.readSourceLocation());
11956 llvm::SmallVector<OpenMPDirectiveKind, 4> DKVec;
11957 DKVec.reserve(Count);
11958 for (unsigned I = 0; I < Count; I++) {
11959 DKVec.push_back(Record.readEnum<OpenMPDirectiveKind>());
11960 }
11961 C->setDirectiveKinds(DKVec);
11962}
11963
11964void OMPClauseReader::VisitOMPNoOpenMPClause(OMPNoOpenMPClause *) {}
11965
11966void OMPClauseReader::VisitOMPNoOpenMPRoutinesClause(
11967 OMPNoOpenMPRoutinesClause *) {}
11968
11969void OMPClauseReader::VisitOMPNoOpenMPConstructsClause(
11970 OMPNoOpenMPConstructsClause *) {}
11971
11972void OMPClauseReader::VisitOMPNoParallelismClause(OMPNoParallelismClause *) {}
11973
11974void OMPClauseReader::VisitOMPSeqCstClause(OMPSeqCstClause *) {}
11975
11976void OMPClauseReader::VisitOMPAcqRelClause(OMPAcqRelClause *) {}
11977
11978void OMPClauseReader::VisitOMPAcquireClause(OMPAcquireClause *) {}
11979
11980void OMPClauseReader::VisitOMPReleaseClause(OMPReleaseClause *) {}
11981
11982void OMPClauseReader::VisitOMPRelaxedClause(OMPRelaxedClause *) {}
11983
11984void OMPClauseReader::VisitOMPWeakClause(OMPWeakClause *) {}
11985
11986void OMPClauseReader::VisitOMPThreadsClause(OMPThreadsClause *) {}
11987
11988void OMPClauseReader::VisitOMPSIMDClause(OMPSIMDClause *) {}
11989
11990void OMPClauseReader::VisitOMPNogroupClause(OMPNogroupClause *) {}
11991
11992void OMPClauseReader::VisitOMPInitClause(OMPInitClause *C) {
11993 unsigned NumVars = C->varlist_size();
11994 SmallVector<Expr *, 16> Vars;
11995 Vars.reserve(NumVars);
11996 for (unsigned I = 0; I != NumVars; ++I)
11997 Vars.push_back(Record.readSubExpr());
11998 C->setVarRefs(Vars);
11999 C->setIsTarget(Record.readBool());
12000 C->setIsTargetSync(Record.readBool());
12001 C->setLParenLoc(Record.readSourceLocation());
12002 C->setVarLoc(Record.readSourceLocation());
12003}
12004
12005void OMPClauseReader::VisitOMPUseClause(OMPUseClause *C) {
12006 C->setInteropVar(Record.readSubExpr());
12007 C->setLParenLoc(Record.readSourceLocation());
12008 C->setVarLoc(Record.readSourceLocation());
12009}
12010
12011void OMPClauseReader::VisitOMPDestroyClause(OMPDestroyClause *C) {
12012 C->setInteropVar(Record.readSubExpr());
12013 C->setLParenLoc(Record.readSourceLocation());
12014 C->setVarLoc(Record.readSourceLocation());
12015}
12016
12017void OMPClauseReader::VisitOMPNovariantsClause(OMPNovariantsClause *C) {
12019 C->setCondition(Record.readSubExpr());
12020 C->setLParenLoc(Record.readSourceLocation());
12021}
12022
12023void OMPClauseReader::VisitOMPNocontextClause(OMPNocontextClause *C) {
12025 C->setCondition(Record.readSubExpr());
12026 C->setLParenLoc(Record.readSourceLocation());
12027}
12028
12029void OMPClauseReader::VisitOMPUnifiedAddressClause(OMPUnifiedAddressClause *) {}
12030
12031void OMPClauseReader::VisitOMPUnifiedSharedMemoryClause(
12032 OMPUnifiedSharedMemoryClause *) {}
12033
12034void OMPClauseReader::VisitOMPReverseOffloadClause(OMPReverseOffloadClause *) {}
12035
12036void
12037OMPClauseReader::VisitOMPDynamicAllocatorsClause(OMPDynamicAllocatorsClause *) {
12038}
12039
12040void OMPClauseReader::VisitOMPAtomicDefaultMemOrderClause(
12041 OMPAtomicDefaultMemOrderClause *C) {
12042 C->setAtomicDefaultMemOrderKind(
12043 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Record.readInt()));
12044 C->setLParenLoc(Record.readSourceLocation());
12045 C->setAtomicDefaultMemOrderKindKwLoc(Record.readSourceLocation());
12046}
12047
12048void OMPClauseReader::VisitOMPSelfMapsClause(OMPSelfMapsClause *) {}
12049
12050void OMPClauseReader::VisitOMPAtClause(OMPAtClause *C) {
12051 C->setAtKind(static_cast<OpenMPAtClauseKind>(Record.readInt()));
12052 C->setLParenLoc(Record.readSourceLocation());
12053 C->setAtKindKwLoc(Record.readSourceLocation());
12054}
12055
12056void OMPClauseReader::VisitOMPSeverityClause(OMPSeverityClause *C) {
12057 C->setSeverityKind(static_cast<OpenMPSeverityClauseKind>(Record.readInt()));
12058 C->setLParenLoc(Record.readSourceLocation());
12059 C->setSeverityKindKwLoc(Record.readSourceLocation());
12060}
12061
12062void OMPClauseReader::VisitOMPMessageClause(OMPMessageClause *C) {
12064 C->setMessageString(Record.readSubExpr());
12065 C->setLParenLoc(Record.readSourceLocation());
12066}
12067
12068void OMPClauseReader::VisitOMPPrivateClause(OMPPrivateClause *C) {
12069 C->setLParenLoc(Record.readSourceLocation());
12070 unsigned NumVars = C->varlist_size();
12071 SmallVector<Expr *, 16> Vars;
12072 Vars.reserve(NumVars);
12073 for (unsigned i = 0; i != NumVars; ++i)
12074 Vars.push_back(Record.readSubExpr());
12075 C->setVarRefs(Vars);
12076 Vars.clear();
12077 for (unsigned i = 0; i != NumVars; ++i)
12078 Vars.push_back(Record.readSubExpr());
12079 C->setPrivateCopies(Vars);
12080}
12081
12082void OMPClauseReader::VisitOMPFirstprivateClause(OMPFirstprivateClause *C) {
12084 C->setLParenLoc(Record.readSourceLocation());
12085 unsigned NumVars = C->varlist_size();
12086 SmallVector<Expr *, 16> Vars;
12087 Vars.reserve(NumVars);
12088 for (unsigned i = 0; i != NumVars; ++i)
12089 Vars.push_back(Record.readSubExpr());
12090 C->setVarRefs(Vars);
12091 Vars.clear();
12092 for (unsigned i = 0; i != NumVars; ++i)
12093 Vars.push_back(Record.readSubExpr());
12094 C->setPrivateCopies(Vars);
12095 Vars.clear();
12096 for (unsigned i = 0; i != NumVars; ++i)
12097 Vars.push_back(Record.readSubExpr());
12098 C->setInits(Vars);
12099}
12100
12101void OMPClauseReader::VisitOMPLastprivateClause(OMPLastprivateClause *C) {
12103 C->setLParenLoc(Record.readSourceLocation());
12104 C->setKind(Record.readEnum<OpenMPLastprivateModifier>());
12105 C->setKindLoc(Record.readSourceLocation());
12106 C->setColonLoc(Record.readSourceLocation());
12107 unsigned NumVars = C->varlist_size();
12108 SmallVector<Expr *, 16> Vars;
12109 Vars.reserve(NumVars);
12110 for (unsigned i = 0; i != NumVars; ++i)
12111 Vars.push_back(Record.readSubExpr());
12112 C->setVarRefs(Vars);
12113 Vars.clear();
12114 for (unsigned i = 0; i != NumVars; ++i)
12115 Vars.push_back(Record.readSubExpr());
12116 C->setPrivateCopies(Vars);
12117 Vars.clear();
12118 for (unsigned i = 0; i != NumVars; ++i)
12119 Vars.push_back(Record.readSubExpr());
12120 C->setSourceExprs(Vars);
12121 Vars.clear();
12122 for (unsigned i = 0; i != NumVars; ++i)
12123 Vars.push_back(Record.readSubExpr());
12124 C->setDestinationExprs(Vars);
12125 Vars.clear();
12126 for (unsigned i = 0; i != NumVars; ++i)
12127 Vars.push_back(Record.readSubExpr());
12128 C->setAssignmentOps(Vars);
12129}
12130
12131void OMPClauseReader::VisitOMPSharedClause(OMPSharedClause *C) {
12132 C->setLParenLoc(Record.readSourceLocation());
12133 unsigned NumVars = C->varlist_size();
12134 SmallVector<Expr *, 16> Vars;
12135 Vars.reserve(NumVars);
12136 for (unsigned i = 0; i != NumVars; ++i)
12137 Vars.push_back(Record.readSubExpr());
12138 C->setVarRefs(Vars);
12139}
12140
12141void OMPClauseReader::VisitOMPReductionClause(OMPReductionClause *C) {
12143 C->setLParenLoc(Record.readSourceLocation());
12144 C->setModifierLoc(Record.readSourceLocation());
12145 C->setColonLoc(Record.readSourceLocation());
12146 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
12147 DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
12148 C->setQualifierLoc(NNSL);
12149 C->setNameInfo(DNI);
12150
12151 unsigned NumVars = C->varlist_size();
12152 SmallVector<Expr *, 16> Vars;
12153 Vars.reserve(NumVars);
12154 for (unsigned i = 0; i != NumVars; ++i)
12155 Vars.push_back(Record.readSubExpr());
12156 C->setVarRefs(Vars);
12157 Vars.clear();
12158 for (unsigned i = 0; i != NumVars; ++i)
12159 Vars.push_back(Record.readSubExpr());
12160 C->setPrivates(Vars);
12161 Vars.clear();
12162 for (unsigned i = 0; i != NumVars; ++i)
12163 Vars.push_back(Record.readSubExpr());
12164 C->setLHSExprs(Vars);
12165 Vars.clear();
12166 for (unsigned i = 0; i != NumVars; ++i)
12167 Vars.push_back(Record.readSubExpr());
12168 C->setRHSExprs(Vars);
12169 Vars.clear();
12170 for (unsigned i = 0; i != NumVars; ++i)
12171 Vars.push_back(Record.readSubExpr());
12172 C->setReductionOps(Vars);
12173 if (C->getModifier() == OMPC_REDUCTION_inscan) {
12174 Vars.clear();
12175 for (unsigned i = 0; i != NumVars; ++i)
12176 Vars.push_back(Record.readSubExpr());
12177 C->setInscanCopyOps(Vars);
12178 Vars.clear();
12179 for (unsigned i = 0; i != NumVars; ++i)
12180 Vars.push_back(Record.readSubExpr());
12181 C->setInscanCopyArrayTemps(Vars);
12182 Vars.clear();
12183 for (unsigned i = 0; i != NumVars; ++i)
12184 Vars.push_back(Record.readSubExpr());
12185 C->setInscanCopyArrayElems(Vars);
12186 }
12187 unsigned NumFlags = Record.readInt();
12188 SmallVector<bool, 16> Flags;
12189 Flags.reserve(NumFlags);
12190 for ([[maybe_unused]] unsigned I : llvm::seq<unsigned>(NumFlags))
12191 Flags.push_back(Record.readInt());
12192 C->setPrivateVariableReductionFlags(Flags);
12193}
12194
12195void OMPClauseReader::VisitOMPTaskReductionClause(OMPTaskReductionClause *C) {
12197 C->setLParenLoc(Record.readSourceLocation());
12198 C->setColonLoc(Record.readSourceLocation());
12199 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
12200 DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
12201 C->setQualifierLoc(NNSL);
12202 C->setNameInfo(DNI);
12203
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 Vars.clear();
12211 for (unsigned I = 0; I != NumVars; ++I)
12212 Vars.push_back(Record.readSubExpr());
12213 C->setPrivates(Vars);
12214 Vars.clear();
12215 for (unsigned I = 0; I != NumVars; ++I)
12216 Vars.push_back(Record.readSubExpr());
12217 C->setLHSExprs(Vars);
12218 Vars.clear();
12219 for (unsigned I = 0; I != NumVars; ++I)
12220 Vars.push_back(Record.readSubExpr());
12221 C->setRHSExprs(Vars);
12222 Vars.clear();
12223 for (unsigned I = 0; I != NumVars; ++I)
12224 Vars.push_back(Record.readSubExpr());
12225 C->setReductionOps(Vars);
12226}
12227
12228void OMPClauseReader::VisitOMPInReductionClause(OMPInReductionClause *C) {
12230 C->setLParenLoc(Record.readSourceLocation());
12231 C->setColonLoc(Record.readSourceLocation());
12232 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
12233 DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
12234 C->setQualifierLoc(NNSL);
12235 C->setNameInfo(DNI);
12236
12237 unsigned NumVars = C->varlist_size();
12238 SmallVector<Expr *, 16> Vars;
12239 Vars.reserve(NumVars);
12240 for (unsigned I = 0; I != NumVars; ++I)
12241 Vars.push_back(Record.readSubExpr());
12242 C->setVarRefs(Vars);
12243 Vars.clear();
12244 for (unsigned I = 0; I != NumVars; ++I)
12245 Vars.push_back(Record.readSubExpr());
12246 C->setPrivates(Vars);
12247 Vars.clear();
12248 for (unsigned I = 0; I != NumVars; ++I)
12249 Vars.push_back(Record.readSubExpr());
12250 C->setLHSExprs(Vars);
12251 Vars.clear();
12252 for (unsigned I = 0; I != NumVars; ++I)
12253 Vars.push_back(Record.readSubExpr());
12254 C->setRHSExprs(Vars);
12255 Vars.clear();
12256 for (unsigned I = 0; I != NumVars; ++I)
12257 Vars.push_back(Record.readSubExpr());
12258 C->setReductionOps(Vars);
12259 Vars.clear();
12260 for (unsigned I = 0; I != NumVars; ++I)
12261 Vars.push_back(Record.readSubExpr());
12262 C->setTaskgroupDescriptors(Vars);
12263}
12264
12265void OMPClauseReader::VisitOMPLinearClause(OMPLinearClause *C) {
12267 C->setLParenLoc(Record.readSourceLocation());
12268 C->setColonLoc(Record.readSourceLocation());
12269 C->setModifier(static_cast<OpenMPLinearClauseKind>(Record.readInt()));
12270 C->setModifierLoc(Record.readSourceLocation());
12271 unsigned NumVars = C->varlist_size();
12272 SmallVector<Expr *, 16> Vars;
12273 Vars.reserve(NumVars);
12274 for (unsigned i = 0; i != NumVars; ++i)
12275 Vars.push_back(Record.readSubExpr());
12276 C->setVarRefs(Vars);
12277 Vars.clear();
12278 for (unsigned i = 0; i != NumVars; ++i)
12279 Vars.push_back(Record.readSubExpr());
12280 C->setPrivates(Vars);
12281 Vars.clear();
12282 for (unsigned i = 0; i != NumVars; ++i)
12283 Vars.push_back(Record.readSubExpr());
12284 C->setInits(Vars);
12285 Vars.clear();
12286 for (unsigned i = 0; i != NumVars; ++i)
12287 Vars.push_back(Record.readSubExpr());
12288 C->setUpdates(Vars);
12289 Vars.clear();
12290 for (unsigned i = 0; i != NumVars; ++i)
12291 Vars.push_back(Record.readSubExpr());
12292 C->setFinals(Vars);
12293 C->setStep(Record.readSubExpr());
12294 C->setCalcStep(Record.readSubExpr());
12295 Vars.clear();
12296 for (unsigned I = 0; I != NumVars + 1; ++I)
12297 Vars.push_back(Record.readSubExpr());
12298 C->setUsedExprs(Vars);
12299}
12300
12301void OMPClauseReader::VisitOMPAlignedClause(OMPAlignedClause *C) {
12302 C->setLParenLoc(Record.readSourceLocation());
12303 C->setColonLoc(Record.readSourceLocation());
12304 unsigned NumVars = C->varlist_size();
12305 SmallVector<Expr *, 16> Vars;
12306 Vars.reserve(NumVars);
12307 for (unsigned i = 0; i != NumVars; ++i)
12308 Vars.push_back(Record.readSubExpr());
12309 C->setVarRefs(Vars);
12310 C->setAlignment(Record.readSubExpr());
12311}
12312
12313void OMPClauseReader::VisitOMPCopyinClause(OMPCopyinClause *C) {
12314 C->setLParenLoc(Record.readSourceLocation());
12315 unsigned NumVars = C->varlist_size();
12316 SmallVector<Expr *, 16> Exprs;
12317 Exprs.reserve(NumVars);
12318 for (unsigned i = 0; i != NumVars; ++i)
12319 Exprs.push_back(Record.readSubExpr());
12320 C->setVarRefs(Exprs);
12321 Exprs.clear();
12322 for (unsigned i = 0; i != NumVars; ++i)
12323 Exprs.push_back(Record.readSubExpr());
12324 C->setSourceExprs(Exprs);
12325 Exprs.clear();
12326 for (unsigned i = 0; i != NumVars; ++i)
12327 Exprs.push_back(Record.readSubExpr());
12328 C->setDestinationExprs(Exprs);
12329 Exprs.clear();
12330 for (unsigned i = 0; i != NumVars; ++i)
12331 Exprs.push_back(Record.readSubExpr());
12332 C->setAssignmentOps(Exprs);
12333}
12334
12335void OMPClauseReader::VisitOMPCopyprivateClause(OMPCopyprivateClause *C) {
12336 C->setLParenLoc(Record.readSourceLocation());
12337 unsigned NumVars = C->varlist_size();
12338 SmallVector<Expr *, 16> Exprs;
12339 Exprs.reserve(NumVars);
12340 for (unsigned i = 0; i != NumVars; ++i)
12341 Exprs.push_back(Record.readSubExpr());
12342 C->setVarRefs(Exprs);
12343 Exprs.clear();
12344 for (unsigned i = 0; i != NumVars; ++i)
12345 Exprs.push_back(Record.readSubExpr());
12346 C->setSourceExprs(Exprs);
12347 Exprs.clear();
12348 for (unsigned i = 0; i != NumVars; ++i)
12349 Exprs.push_back(Record.readSubExpr());
12350 C->setDestinationExprs(Exprs);
12351 Exprs.clear();
12352 for (unsigned i = 0; i != NumVars; ++i)
12353 Exprs.push_back(Record.readSubExpr());
12354 C->setAssignmentOps(Exprs);
12355}
12356
12357void OMPClauseReader::VisitOMPFlushClause(OMPFlushClause *C) {
12358 C->setLParenLoc(Record.readSourceLocation());
12359 unsigned NumVars = C->varlist_size();
12360 SmallVector<Expr *, 16> Vars;
12361 Vars.reserve(NumVars);
12362 for (unsigned i = 0; i != NumVars; ++i)
12363 Vars.push_back(Record.readSubExpr());
12364 C->setVarRefs(Vars);
12365}
12366
12367void OMPClauseReader::VisitOMPDepobjClause(OMPDepobjClause *C) {
12368 C->setDepobj(Record.readSubExpr());
12369 C->setLParenLoc(Record.readSourceLocation());
12370}
12371
12372void OMPClauseReader::VisitOMPDependClause(OMPDependClause *C) {
12373 C->setLParenLoc(Record.readSourceLocation());
12374 C->setModifier(Record.readSubExpr());
12375 C->setDependencyKind(
12376 static_cast<OpenMPDependClauseKind>(Record.readInt()));
12377 C->setDependencyLoc(Record.readSourceLocation());
12378 C->setColonLoc(Record.readSourceLocation());
12379 C->setOmpAllMemoryLoc(Record.readSourceLocation());
12380 unsigned NumVars = C->varlist_size();
12381 SmallVector<Expr *, 16> Vars;
12382 Vars.reserve(NumVars);
12383 for (unsigned I = 0; I != NumVars; ++I)
12384 Vars.push_back(Record.readSubExpr());
12385 C->setVarRefs(Vars);
12386 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
12387 C->setLoopData(I, Record.readSubExpr());
12388}
12389
12390void OMPClauseReader::VisitOMPDeviceClause(OMPDeviceClause *C) {
12392 C->setModifier(Record.readEnum<OpenMPDeviceClauseModifier>());
12393 C->setDevice(Record.readSubExpr());
12394 C->setModifierLoc(Record.readSourceLocation());
12395 C->setLParenLoc(Record.readSourceLocation());
12396}
12397
12398void OMPClauseReader::VisitOMPMapClause(OMPMapClause *C) {
12399 C->setLParenLoc(Record.readSourceLocation());
12400 bool HasIteratorModifier = false;
12401 for (unsigned I = 0; I < NumberOfOMPMapClauseModifiers; ++I) {
12402 C->setMapTypeModifier(
12403 I, static_cast<OpenMPMapModifierKind>(Record.readInt()));
12404 C->setMapTypeModifierLoc(I, Record.readSourceLocation());
12405 if (C->getMapTypeModifier(I) == OMPC_MAP_MODIFIER_iterator)
12406 HasIteratorModifier = true;
12407 }
12408 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
12409 C->setMapperIdInfo(Record.readDeclarationNameInfo());
12410 C->setMapType(
12411 static_cast<OpenMPMapClauseKind>(Record.readInt()));
12412 C->setMapLoc(Record.readSourceLocation());
12413 C->setColonLoc(Record.readSourceLocation());
12414 auto NumVars = C->varlist_size();
12415 auto UniqueDecls = C->getUniqueDeclarationsNum();
12416 auto TotalLists = C->getTotalComponentListNum();
12417 auto TotalComponents = C->getTotalComponentsNum();
12418
12419 SmallVector<Expr *, 16> Vars;
12420 Vars.reserve(NumVars);
12421 for (unsigned i = 0; i != NumVars; ++i)
12422 Vars.push_back(Record.readExpr());
12423 C->setVarRefs(Vars);
12424
12425 SmallVector<Expr *, 16> UDMappers;
12426 UDMappers.reserve(NumVars);
12427 for (unsigned I = 0; I < NumVars; ++I)
12428 UDMappers.push_back(Record.readExpr());
12429 C->setUDMapperRefs(UDMappers);
12430
12431 if (HasIteratorModifier)
12432 C->setIteratorModifier(Record.readExpr());
12433
12434 SmallVector<ValueDecl *, 16> Decls;
12435 Decls.reserve(UniqueDecls);
12436 for (unsigned i = 0; i < UniqueDecls; ++i)
12437 Decls.push_back(Record.readDeclAs<ValueDecl>());
12438 C->setUniqueDecls(Decls);
12439
12440 SmallVector<unsigned, 16> ListsPerDecl;
12441 ListsPerDecl.reserve(UniqueDecls);
12442 for (unsigned i = 0; i < UniqueDecls; ++i)
12443 ListsPerDecl.push_back(Record.readInt());
12444 C->setDeclNumLists(ListsPerDecl);
12445
12446 SmallVector<unsigned, 32> ListSizes;
12447 ListSizes.reserve(TotalLists);
12448 for (unsigned i = 0; i < TotalLists; ++i)
12449 ListSizes.push_back(Record.readInt());
12450 C->setComponentListSizes(ListSizes);
12451
12452 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12453 Components.reserve(TotalComponents);
12454 for (unsigned i = 0; i < TotalComponents; ++i) {
12455 Expr *AssociatedExprPr = Record.readExpr();
12456 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12457 Components.emplace_back(AssociatedExprPr, AssociatedDecl,
12458 /*IsNonContiguous=*/false);
12459 }
12460 C->setComponents(Components, ListSizes);
12461}
12462
12463void OMPClauseReader::VisitOMPAllocateClause(OMPAllocateClause *C) {
12464 C->setFirstAllocateModifier(Record.readEnum<OpenMPAllocateClauseModifier>());
12465 C->setSecondAllocateModifier(Record.readEnum<OpenMPAllocateClauseModifier>());
12466 C->setLParenLoc(Record.readSourceLocation());
12467 C->setColonLoc(Record.readSourceLocation());
12468 C->setAllocator(Record.readSubExpr());
12469 C->setAlignment(Record.readSubExpr());
12470 unsigned NumVars = C->varlist_size();
12471 SmallVector<Expr *, 16> Vars;
12472 Vars.reserve(NumVars);
12473 for (unsigned i = 0; i != NumVars; ++i)
12474 Vars.push_back(Record.readSubExpr());
12475 C->setVarRefs(Vars);
12476}
12477
12478void OMPClauseReader::VisitOMPNumTeamsClause(OMPNumTeamsClause *C) {
12480 C->setLParenLoc(Record.readSourceLocation());
12481 unsigned NumVars = C->varlist_size();
12482 SmallVector<Expr *, 16> Vars;
12483 Vars.reserve(NumVars);
12484 for (unsigned I = 0; I != NumVars; ++I)
12485 Vars.push_back(Record.readSubExpr());
12486 C->setVarRefs(Vars);
12487}
12488
12489void OMPClauseReader::VisitOMPThreadLimitClause(OMPThreadLimitClause *C) {
12491 C->setLParenLoc(Record.readSourceLocation());
12492 unsigned NumVars = C->varlist_size();
12493 SmallVector<Expr *, 16> Vars;
12494 Vars.reserve(NumVars);
12495 for (unsigned I = 0; I != NumVars; ++I)
12496 Vars.push_back(Record.readSubExpr());
12497 C->setVarRefs(Vars);
12498}
12499
12500void OMPClauseReader::VisitOMPPriorityClause(OMPPriorityClause *C) {
12502 C->setPriority(Record.readSubExpr());
12503 C->setLParenLoc(Record.readSourceLocation());
12504}
12505
12506void OMPClauseReader::VisitOMPGrainsizeClause(OMPGrainsizeClause *C) {
12508 C->setModifier(Record.readEnum<OpenMPGrainsizeClauseModifier>());
12509 C->setGrainsize(Record.readSubExpr());
12510 C->setModifierLoc(Record.readSourceLocation());
12511 C->setLParenLoc(Record.readSourceLocation());
12512}
12513
12514void OMPClauseReader::VisitOMPNumTasksClause(OMPNumTasksClause *C) {
12516 C->setModifier(Record.readEnum<OpenMPNumTasksClauseModifier>());
12517 C->setNumTasks(Record.readSubExpr());
12518 C->setModifierLoc(Record.readSourceLocation());
12519 C->setLParenLoc(Record.readSourceLocation());
12520}
12521
12522void OMPClauseReader::VisitOMPHintClause(OMPHintClause *C) {
12523 C->setHint(Record.readSubExpr());
12524 C->setLParenLoc(Record.readSourceLocation());
12525}
12526
12527void OMPClauseReader::VisitOMPDistScheduleClause(OMPDistScheduleClause *C) {
12529 C->setDistScheduleKind(
12530 static_cast<OpenMPDistScheduleClauseKind>(Record.readInt()));
12531 C->setChunkSize(Record.readSubExpr());
12532 C->setLParenLoc(Record.readSourceLocation());
12533 C->setDistScheduleKindLoc(Record.readSourceLocation());
12534 C->setCommaLoc(Record.readSourceLocation());
12535}
12536
12537void OMPClauseReader::VisitOMPDefaultmapClause(OMPDefaultmapClause *C) {
12538 C->setDefaultmapKind(
12539 static_cast<OpenMPDefaultmapClauseKind>(Record.readInt()));
12540 C->setDefaultmapModifier(
12541 static_cast<OpenMPDefaultmapClauseModifier>(Record.readInt()));
12542 C->setLParenLoc(Record.readSourceLocation());
12543 C->setDefaultmapModifierLoc(Record.readSourceLocation());
12544 C->setDefaultmapKindLoc(Record.readSourceLocation());
12545}
12546
12547void OMPClauseReader::VisitOMPToClause(OMPToClause *C) {
12548 C->setLParenLoc(Record.readSourceLocation());
12549 for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) {
12550 C->setMotionModifier(
12551 I, static_cast<OpenMPMotionModifierKind>(Record.readInt()));
12552 C->setMotionModifierLoc(I, Record.readSourceLocation());
12553 if (C->getMotionModifier(I) == OMPC_MOTION_MODIFIER_iterator)
12554 C->setIteratorModifier(Record.readExpr());
12555 }
12556 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
12557 C->setMapperIdInfo(Record.readDeclarationNameInfo());
12558 C->setColonLoc(Record.readSourceLocation());
12559 auto NumVars = C->varlist_size();
12560 auto UniqueDecls = C->getUniqueDeclarationsNum();
12561 auto TotalLists = C->getTotalComponentListNum();
12562 auto TotalComponents = C->getTotalComponentsNum();
12563
12564 SmallVector<Expr *, 16> Vars;
12565 Vars.reserve(NumVars);
12566 for (unsigned i = 0; i != NumVars; ++i)
12567 Vars.push_back(Record.readSubExpr());
12568 C->setVarRefs(Vars);
12569
12570 SmallVector<Expr *, 16> UDMappers;
12571 UDMappers.reserve(NumVars);
12572 for (unsigned I = 0; I < NumVars; ++I)
12573 UDMappers.push_back(Record.readSubExpr());
12574 C->setUDMapperRefs(UDMappers);
12575
12576 SmallVector<ValueDecl *, 16> Decls;
12577 Decls.reserve(UniqueDecls);
12578 for (unsigned i = 0; i < UniqueDecls; ++i)
12579 Decls.push_back(Record.readDeclAs<ValueDecl>());
12580 C->setUniqueDecls(Decls);
12581
12582 SmallVector<unsigned, 16> ListsPerDecl;
12583 ListsPerDecl.reserve(UniqueDecls);
12584 for (unsigned i = 0; i < UniqueDecls; ++i)
12585 ListsPerDecl.push_back(Record.readInt());
12586 C->setDeclNumLists(ListsPerDecl);
12587
12588 SmallVector<unsigned, 32> ListSizes;
12589 ListSizes.reserve(TotalLists);
12590 for (unsigned i = 0; i < TotalLists; ++i)
12591 ListSizes.push_back(Record.readInt());
12592 C->setComponentListSizes(ListSizes);
12593
12594 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12595 Components.reserve(TotalComponents);
12596 for (unsigned i = 0; i < TotalComponents; ++i) {
12597 Expr *AssociatedExprPr = Record.readSubExpr();
12598 bool IsNonContiguous = Record.readBool();
12599 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12600 Components.emplace_back(AssociatedExprPr, AssociatedDecl, IsNonContiguous);
12601 }
12602 C->setComponents(Components, ListSizes);
12603}
12604
12605void OMPClauseReader::VisitOMPFromClause(OMPFromClause *C) {
12606 C->setLParenLoc(Record.readSourceLocation());
12607 for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) {
12608 C->setMotionModifier(
12609 I, static_cast<OpenMPMotionModifierKind>(Record.readInt()));
12610 C->setMotionModifierLoc(I, Record.readSourceLocation());
12611 if (C->getMotionModifier(I) == OMPC_MOTION_MODIFIER_iterator)
12612 C->setIteratorModifier(Record.readExpr());
12613 }
12614 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
12615 C->setMapperIdInfo(Record.readDeclarationNameInfo());
12616 C->setColonLoc(Record.readSourceLocation());
12617 auto NumVars = C->varlist_size();
12618 auto UniqueDecls = C->getUniqueDeclarationsNum();
12619 auto TotalLists = C->getTotalComponentListNum();
12620 auto TotalComponents = C->getTotalComponentsNum();
12621
12622 SmallVector<Expr *, 16> Vars;
12623 Vars.reserve(NumVars);
12624 for (unsigned i = 0; i != NumVars; ++i)
12625 Vars.push_back(Record.readSubExpr());
12626 C->setVarRefs(Vars);
12627
12628 SmallVector<Expr *, 16> UDMappers;
12629 UDMappers.reserve(NumVars);
12630 for (unsigned I = 0; I < NumVars; ++I)
12631 UDMappers.push_back(Record.readSubExpr());
12632 C->setUDMapperRefs(UDMappers);
12633
12634 SmallVector<ValueDecl *, 16> Decls;
12635 Decls.reserve(UniqueDecls);
12636 for (unsigned i = 0; i < UniqueDecls; ++i)
12637 Decls.push_back(Record.readDeclAs<ValueDecl>());
12638 C->setUniqueDecls(Decls);
12639
12640 SmallVector<unsigned, 16> ListsPerDecl;
12641 ListsPerDecl.reserve(UniqueDecls);
12642 for (unsigned i = 0; i < UniqueDecls; ++i)
12643 ListsPerDecl.push_back(Record.readInt());
12644 C->setDeclNumLists(ListsPerDecl);
12645
12646 SmallVector<unsigned, 32> ListSizes;
12647 ListSizes.reserve(TotalLists);
12648 for (unsigned i = 0; i < TotalLists; ++i)
12649 ListSizes.push_back(Record.readInt());
12650 C->setComponentListSizes(ListSizes);
12651
12652 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12653 Components.reserve(TotalComponents);
12654 for (unsigned i = 0; i < TotalComponents; ++i) {
12655 Expr *AssociatedExprPr = Record.readSubExpr();
12656 bool IsNonContiguous = Record.readBool();
12657 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12658 Components.emplace_back(AssociatedExprPr, AssociatedDecl, IsNonContiguous);
12659 }
12660 C->setComponents(Components, ListSizes);
12661}
12662
12663void OMPClauseReader::VisitOMPUseDevicePtrClause(OMPUseDevicePtrClause *C) {
12664 C->setLParenLoc(Record.readSourceLocation());
12665 C->setFallbackModifier(Record.readEnum<OpenMPUseDevicePtrFallbackModifier>());
12666 C->setFallbackModifierLoc(Record.readSourceLocation());
12667 auto NumVars = C->varlist_size();
12668 auto UniqueDecls = C->getUniqueDeclarationsNum();
12669 auto TotalLists = C->getTotalComponentListNum();
12670 auto TotalComponents = C->getTotalComponentsNum();
12671
12672 SmallVector<Expr *, 16> Vars;
12673 Vars.reserve(NumVars);
12674 for (unsigned i = 0; i != NumVars; ++i)
12675 Vars.push_back(Record.readSubExpr());
12676 C->setVarRefs(Vars);
12677 Vars.clear();
12678 for (unsigned i = 0; i != NumVars; ++i)
12679 Vars.push_back(Record.readSubExpr());
12680 C->setPrivateCopies(Vars);
12681 Vars.clear();
12682 for (unsigned i = 0; i != NumVars; ++i)
12683 Vars.push_back(Record.readSubExpr());
12684 C->setInits(Vars);
12685
12686 SmallVector<ValueDecl *, 16> Decls;
12687 Decls.reserve(UniqueDecls);
12688 for (unsigned i = 0; i < UniqueDecls; ++i)
12689 Decls.push_back(Record.readDeclAs<ValueDecl>());
12690 C->setUniqueDecls(Decls);
12691
12692 SmallVector<unsigned, 16> ListsPerDecl;
12693 ListsPerDecl.reserve(UniqueDecls);
12694 for (unsigned i = 0; i < UniqueDecls; ++i)
12695 ListsPerDecl.push_back(Record.readInt());
12696 C->setDeclNumLists(ListsPerDecl);
12697
12698 SmallVector<unsigned, 32> ListSizes;
12699 ListSizes.reserve(TotalLists);
12700 for (unsigned i = 0; i < TotalLists; ++i)
12701 ListSizes.push_back(Record.readInt());
12702 C->setComponentListSizes(ListSizes);
12703
12704 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12705 Components.reserve(TotalComponents);
12706 for (unsigned i = 0; i < TotalComponents; ++i) {
12707 auto *AssociatedExprPr = Record.readSubExpr();
12708 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12709 Components.emplace_back(AssociatedExprPr, AssociatedDecl,
12710 /*IsNonContiguous=*/false);
12711 }
12712 C->setComponents(Components, ListSizes);
12713}
12714
12715void OMPClauseReader::VisitOMPUseDeviceAddrClause(OMPUseDeviceAddrClause *C) {
12716 C->setLParenLoc(Record.readSourceLocation());
12717 auto NumVars = C->varlist_size();
12718 auto UniqueDecls = C->getUniqueDeclarationsNum();
12719 auto TotalLists = C->getTotalComponentListNum();
12720 auto TotalComponents = C->getTotalComponentsNum();
12721
12722 SmallVector<Expr *, 16> Vars;
12723 Vars.reserve(NumVars);
12724 for (unsigned i = 0; i != NumVars; ++i)
12725 Vars.push_back(Record.readSubExpr());
12726 C->setVarRefs(Vars);
12727
12728 SmallVector<ValueDecl *, 16> Decls;
12729 Decls.reserve(UniqueDecls);
12730 for (unsigned i = 0; i < UniqueDecls; ++i)
12731 Decls.push_back(Record.readDeclAs<ValueDecl>());
12732 C->setUniqueDecls(Decls);
12733
12734 SmallVector<unsigned, 16> ListsPerDecl;
12735 ListsPerDecl.reserve(UniqueDecls);
12736 for (unsigned i = 0; i < UniqueDecls; ++i)
12737 ListsPerDecl.push_back(Record.readInt());
12738 C->setDeclNumLists(ListsPerDecl);
12739
12740 SmallVector<unsigned, 32> ListSizes;
12741 ListSizes.reserve(TotalLists);
12742 for (unsigned i = 0; i < TotalLists; ++i)
12743 ListSizes.push_back(Record.readInt());
12744 C->setComponentListSizes(ListSizes);
12745
12746 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12747 Components.reserve(TotalComponents);
12748 for (unsigned i = 0; i < TotalComponents; ++i) {
12749 Expr *AssociatedExpr = Record.readSubExpr();
12750 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12751 Components.emplace_back(AssociatedExpr, AssociatedDecl,
12752 /*IsNonContiguous*/ false);
12753 }
12754 C->setComponents(Components, ListSizes);
12755}
12756
12757void OMPClauseReader::VisitOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
12758 C->setLParenLoc(Record.readSourceLocation());
12759 auto NumVars = C->varlist_size();
12760 auto UniqueDecls = C->getUniqueDeclarationsNum();
12761 auto TotalLists = C->getTotalComponentListNum();
12762 auto TotalComponents = C->getTotalComponentsNum();
12763
12764 SmallVector<Expr *, 16> Vars;
12765 Vars.reserve(NumVars);
12766 for (unsigned i = 0; i != NumVars; ++i)
12767 Vars.push_back(Record.readSubExpr());
12768 C->setVarRefs(Vars);
12769 Vars.clear();
12770
12771 SmallVector<ValueDecl *, 16> Decls;
12772 Decls.reserve(UniqueDecls);
12773 for (unsigned i = 0; i < UniqueDecls; ++i)
12774 Decls.push_back(Record.readDeclAs<ValueDecl>());
12775 C->setUniqueDecls(Decls);
12776
12777 SmallVector<unsigned, 16> ListsPerDecl;
12778 ListsPerDecl.reserve(UniqueDecls);
12779 for (unsigned i = 0; i < UniqueDecls; ++i)
12780 ListsPerDecl.push_back(Record.readInt());
12781 C->setDeclNumLists(ListsPerDecl);
12782
12783 SmallVector<unsigned, 32> ListSizes;
12784 ListSizes.reserve(TotalLists);
12785 for (unsigned i = 0; i < TotalLists; ++i)
12786 ListSizes.push_back(Record.readInt());
12787 C->setComponentListSizes(ListSizes);
12788
12789 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12790 Components.reserve(TotalComponents);
12791 for (unsigned i = 0; i < TotalComponents; ++i) {
12792 Expr *AssociatedExpr = Record.readSubExpr();
12793 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12794 Components.emplace_back(AssociatedExpr, AssociatedDecl,
12795 /*IsNonContiguous=*/false);
12796 }
12797 C->setComponents(Components, ListSizes);
12798}
12799
12800void OMPClauseReader::VisitOMPHasDeviceAddrClause(OMPHasDeviceAddrClause *C) {
12801 C->setLParenLoc(Record.readSourceLocation());
12802 auto NumVars = C->varlist_size();
12803 auto UniqueDecls = C->getUniqueDeclarationsNum();
12804 auto TotalLists = C->getTotalComponentListNum();
12805 auto TotalComponents = C->getTotalComponentsNum();
12806
12807 SmallVector<Expr *, 16> Vars;
12808 Vars.reserve(NumVars);
12809 for (unsigned I = 0; I != NumVars; ++I)
12810 Vars.push_back(Record.readSubExpr());
12811 C->setVarRefs(Vars);
12812 Vars.clear();
12813
12814 SmallVector<ValueDecl *, 16> Decls;
12815 Decls.reserve(UniqueDecls);
12816 for (unsigned I = 0; I < UniqueDecls; ++I)
12817 Decls.push_back(Record.readDeclAs<ValueDecl>());
12818 C->setUniqueDecls(Decls);
12819
12820 SmallVector<unsigned, 16> ListsPerDecl;
12821 ListsPerDecl.reserve(UniqueDecls);
12822 for (unsigned I = 0; I < UniqueDecls; ++I)
12823 ListsPerDecl.push_back(Record.readInt());
12824 C->setDeclNumLists(ListsPerDecl);
12825
12826 SmallVector<unsigned, 32> ListSizes;
12827 ListSizes.reserve(TotalLists);
12828 for (unsigned i = 0; i < TotalLists; ++i)
12829 ListSizes.push_back(Record.readInt());
12830 C->setComponentListSizes(ListSizes);
12831
12832 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12833 Components.reserve(TotalComponents);
12834 for (unsigned I = 0; I < TotalComponents; ++I) {
12835 Expr *AssociatedExpr = Record.readSubExpr();
12836 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12837 Components.emplace_back(AssociatedExpr, AssociatedDecl,
12838 /*IsNonContiguous=*/false);
12839 }
12840 C->setComponents(Components, ListSizes);
12841}
12842
12843void OMPClauseReader::VisitOMPNontemporalClause(OMPNontemporalClause *C) {
12844 C->setLParenLoc(Record.readSourceLocation());
12845 unsigned NumVars = C->varlist_size();
12846 SmallVector<Expr *, 16> Vars;
12847 Vars.reserve(NumVars);
12848 for (unsigned i = 0; i != NumVars; ++i)
12849 Vars.push_back(Record.readSubExpr());
12850 C->setVarRefs(Vars);
12851 Vars.clear();
12852 Vars.reserve(NumVars);
12853 for (unsigned i = 0; i != NumVars; ++i)
12854 Vars.push_back(Record.readSubExpr());
12855 C->setPrivateRefs(Vars);
12856}
12857
12858void OMPClauseReader::VisitOMPInclusiveClause(OMPInclusiveClause *C) {
12859 C->setLParenLoc(Record.readSourceLocation());
12860 unsigned NumVars = C->varlist_size();
12861 SmallVector<Expr *, 16> Vars;
12862 Vars.reserve(NumVars);
12863 for (unsigned i = 0; i != NumVars; ++i)
12864 Vars.push_back(Record.readSubExpr());
12865 C->setVarRefs(Vars);
12866}
12867
12868void OMPClauseReader::VisitOMPExclusiveClause(OMPExclusiveClause *C) {
12869 C->setLParenLoc(Record.readSourceLocation());
12870 unsigned NumVars = C->varlist_size();
12871 SmallVector<Expr *, 16> Vars;
12872 Vars.reserve(NumVars);
12873 for (unsigned i = 0; i != NumVars; ++i)
12874 Vars.push_back(Record.readSubExpr());
12875 C->setVarRefs(Vars);
12876}
12877
12878void OMPClauseReader::VisitOMPUsesAllocatorsClause(OMPUsesAllocatorsClause *C) {
12879 C->setLParenLoc(Record.readSourceLocation());
12880 unsigned NumOfAllocators = C->getNumberOfAllocators();
12881 SmallVector<OMPUsesAllocatorsClause::Data, 4> Data;
12882 Data.reserve(NumOfAllocators);
12883 for (unsigned I = 0; I != NumOfAllocators; ++I) {
12884 OMPUsesAllocatorsClause::Data &D = Data.emplace_back();
12885 D.Allocator = Record.readSubExpr();
12886 D.AllocatorTraits = Record.readSubExpr();
12887 D.LParenLoc = Record.readSourceLocation();
12888 D.RParenLoc = Record.readSourceLocation();
12889 }
12890 C->setAllocatorsData(Data);
12891}
12892
12893void OMPClauseReader::VisitOMPAffinityClause(OMPAffinityClause *C) {
12894 C->setLParenLoc(Record.readSourceLocation());
12895 C->setModifier(Record.readSubExpr());
12896 C->setColonLoc(Record.readSourceLocation());
12897 unsigned NumOfLocators = C->varlist_size();
12898 SmallVector<Expr *, 4> Locators;
12899 Locators.reserve(NumOfLocators);
12900 for (unsigned I = 0; I != NumOfLocators; ++I)
12901 Locators.push_back(Record.readSubExpr());
12902 C->setVarRefs(Locators);
12903}
12904
12905void OMPClauseReader::VisitOMPOrderClause(OMPOrderClause *C) {
12906 C->setKind(Record.readEnum<OpenMPOrderClauseKind>());
12907 C->setModifier(Record.readEnum<OpenMPOrderClauseModifier>());
12908 C->setLParenLoc(Record.readSourceLocation());
12909 C->setKindKwLoc(Record.readSourceLocation());
12910 C->setModifierKwLoc(Record.readSourceLocation());
12911}
12912
12913void OMPClauseReader::VisitOMPFilterClause(OMPFilterClause *C) {
12915 C->setThreadID(Record.readSubExpr());
12916 C->setLParenLoc(Record.readSourceLocation());
12917}
12918
12919void OMPClauseReader::VisitOMPBindClause(OMPBindClause *C) {
12920 C->setBindKind(Record.readEnum<OpenMPBindClauseKind>());
12921 C->setLParenLoc(Record.readSourceLocation());
12922 C->setBindKindLoc(Record.readSourceLocation());
12923}
12924
12925void OMPClauseReader::VisitOMPAlignClause(OMPAlignClause *C) {
12926 C->setAlignment(Record.readExpr());
12927 C->setLParenLoc(Record.readSourceLocation());
12928}
12929
12930void OMPClauseReader::VisitOMPXDynCGroupMemClause(OMPXDynCGroupMemClause *C) {
12932 C->setSize(Record.readSubExpr());
12933 C->setLParenLoc(Record.readSourceLocation());
12934}
12935
12936void OMPClauseReader::VisitOMPDynGroupprivateClause(
12937 OMPDynGroupprivateClause *C) {
12939 C->setDynGroupprivateModifier(
12940 Record.readEnum<OpenMPDynGroupprivateClauseModifier>());
12941 C->setDynGroupprivateFallbackModifier(
12943 C->setSize(Record.readSubExpr());
12944 C->setLParenLoc(Record.readSourceLocation());
12945 C->setDynGroupprivateModifierLoc(Record.readSourceLocation());
12946 C->setDynGroupprivateFallbackModifierLoc(Record.readSourceLocation());
12947}
12948
12949void OMPClauseReader::VisitOMPDoacrossClause(OMPDoacrossClause *C) {
12950 C->setLParenLoc(Record.readSourceLocation());
12951 C->setDependenceType(
12952 static_cast<OpenMPDoacrossClauseModifier>(Record.readInt()));
12953 C->setDependenceLoc(Record.readSourceLocation());
12954 C->setColonLoc(Record.readSourceLocation());
12955 unsigned NumVars = C->varlist_size();
12956 SmallVector<Expr *, 16> Vars;
12957 Vars.reserve(NumVars);
12958 for (unsigned I = 0; I != NumVars; ++I)
12959 Vars.push_back(Record.readSubExpr());
12960 C->setVarRefs(Vars);
12961 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
12962 C->setLoopData(I, Record.readSubExpr());
12963}
12964
12965void OMPClauseReader::VisitOMPXAttributeClause(OMPXAttributeClause *C) {
12966 AttrVec Attrs;
12967 Record.readAttributes(Attrs);
12968 C->setAttrs(Attrs);
12969 C->setLocStart(Record.readSourceLocation());
12970 C->setLParenLoc(Record.readSourceLocation());
12971 C->setLocEnd(Record.readSourceLocation());
12972}
12973
12974void OMPClauseReader::VisitOMPXBareClause(OMPXBareClause *C) {}
12975
12978 TI.Sets.resize(readUInt32());
12979 for (auto &Set : TI.Sets) {
12981 Set.Selectors.resize(readUInt32());
12982 for (auto &Selector : Set.Selectors) {
12984 Selector.ScoreOrCondition = nullptr;
12985 if (readBool())
12986 Selector.ScoreOrCondition = readExprRef();
12987 Selector.Properties.resize(readUInt32());
12988 for (auto &Property : Selector.Properties)
12990 }
12991 }
12992 return &TI;
12993}
12994
12996 if (!Data)
12997 return;
12998 if (Reader->ReadingKind == ASTReader::Read_Stmt) {
12999 // Skip NumClauses, NumChildren and HasAssociatedStmt fields.
13000 skipInts(3);
13001 }
13002 SmallVector<OMPClause *, 4> Clauses(Data->getNumClauses());
13003 for (unsigned I = 0, E = Data->getNumClauses(); I < E; ++I)
13004 Clauses[I] = readOMPClause();
13005 Data->setClauses(Clauses);
13006 if (Data->hasAssociatedStmt())
13007 Data->setAssociatedStmt(readStmt());
13008 for (unsigned I = 0, E = Data->getNumChildren(); I < E; ++I)
13009 Data->getChildren()[I] = readStmt();
13010}
13011
13013 unsigned NumVars = readInt();
13015 for (unsigned I = 0; I < NumVars; ++I)
13016 VarList.push_back(readExpr());
13017 return VarList;
13018}
13019
13021 unsigned NumExprs = readInt();
13023 for (unsigned I = 0; I < NumExprs; ++I)
13024 ExprList.push_back(readSubExpr());
13025 return ExprList;
13026}
13027
13032
13033 switch (ClauseKind) {
13035 SourceLocation LParenLoc = readSourceLocation();
13037 return OpenACCDefaultClause::Create(getContext(), DCK, BeginLoc, LParenLoc,
13038 EndLoc);
13039 }
13040 case OpenACCClauseKind::If: {
13041 SourceLocation LParenLoc = readSourceLocation();
13042 Expr *CondExpr = readSubExpr();
13043 return OpenACCIfClause::Create(getContext(), BeginLoc, LParenLoc, CondExpr,
13044 EndLoc);
13045 }
13047 SourceLocation LParenLoc = readSourceLocation();
13048 bool isConditionExprClause = readBool();
13049 if (isConditionExprClause) {
13050 Expr *CondExpr = readBool() ? readSubExpr() : nullptr;
13051 return OpenACCSelfClause::Create(getContext(), BeginLoc, LParenLoc,
13052 CondExpr, EndLoc);
13053 }
13054 unsigned NumVars = readInt();
13056 for (unsigned I = 0; I < NumVars; ++I)
13057 VarList.push_back(readSubExpr());
13058 return OpenACCSelfClause::Create(getContext(), BeginLoc, LParenLoc, VarList,
13059 EndLoc);
13060 }
13062 SourceLocation LParenLoc = readSourceLocation();
13063 unsigned NumClauses = readInt();
13065 for (unsigned I = 0; I < NumClauses; ++I)
13066 IntExprs.push_back(readSubExpr());
13067 return OpenACCNumGangsClause::Create(getContext(), BeginLoc, LParenLoc,
13068 IntExprs, EndLoc);
13069 }
13071 SourceLocation LParenLoc = readSourceLocation();
13072 Expr *IntExpr = readSubExpr();
13073 return OpenACCNumWorkersClause::Create(getContext(), BeginLoc, LParenLoc,
13074 IntExpr, EndLoc);
13075 }
13077 SourceLocation LParenLoc = readSourceLocation();
13078 Expr *IntExpr = readSubExpr();
13079 return OpenACCDeviceNumClause::Create(getContext(), BeginLoc, LParenLoc,
13080 IntExpr, EndLoc);
13081 }
13083 SourceLocation LParenLoc = readSourceLocation();
13084 Expr *IntExpr = readSubExpr();
13085 return OpenACCDefaultAsyncClause::Create(getContext(), BeginLoc, LParenLoc,
13086 IntExpr, EndLoc);
13087 }
13089 SourceLocation LParenLoc = readSourceLocation();
13090 Expr *IntExpr = readSubExpr();
13091 return OpenACCVectorLengthClause::Create(getContext(), BeginLoc, LParenLoc,
13092 IntExpr, EndLoc);
13093 }
13095 SourceLocation LParenLoc = readSourceLocation();
13097
13099 for (unsigned I = 0; I < VarList.size(); ++I) {
13100 static_assert(sizeof(OpenACCPrivateRecipe) == 1 * sizeof(int *));
13101 VarDecl *Alloca = readDeclAs<VarDecl>();
13102 RecipeList.push_back({Alloca});
13103 }
13104
13105 return OpenACCPrivateClause::Create(getContext(), BeginLoc, LParenLoc,
13106 VarList, RecipeList, EndLoc);
13107 }
13109 SourceLocation LParenLoc = readSourceLocation();
13111 return OpenACCHostClause::Create(getContext(), BeginLoc, LParenLoc, VarList,
13112 EndLoc);
13113 }
13115 SourceLocation LParenLoc = readSourceLocation();
13117 return OpenACCDeviceClause::Create(getContext(), BeginLoc, LParenLoc,
13118 VarList, EndLoc);
13119 }
13121 SourceLocation LParenLoc = readSourceLocation();
13124 for (unsigned I = 0; I < VarList.size(); ++I) {
13125 static_assert(sizeof(OpenACCFirstPrivateRecipe) == 2 * sizeof(int *));
13126 VarDecl *Recipe = readDeclAs<VarDecl>();
13127 VarDecl *RecipeTemp = readDeclAs<VarDecl>();
13128 RecipeList.push_back({Recipe, RecipeTemp});
13129 }
13130
13131 return OpenACCFirstPrivateClause::Create(getContext(), BeginLoc, LParenLoc,
13132 VarList, RecipeList, EndLoc);
13133 }
13135 SourceLocation LParenLoc = readSourceLocation();
13137 return OpenACCAttachClause::Create(getContext(), BeginLoc, LParenLoc,
13138 VarList, EndLoc);
13139 }
13141 SourceLocation LParenLoc = readSourceLocation();
13143 return OpenACCDetachClause::Create(getContext(), BeginLoc, LParenLoc,
13144 VarList, EndLoc);
13145 }
13147 SourceLocation LParenLoc = readSourceLocation();
13149 return OpenACCDeleteClause::Create(getContext(), BeginLoc, LParenLoc,
13150 VarList, EndLoc);
13151 }
13153 SourceLocation LParenLoc = readSourceLocation();
13155 return OpenACCUseDeviceClause::Create(getContext(), BeginLoc, LParenLoc,
13156 VarList, EndLoc);
13157 }
13159 SourceLocation LParenLoc = readSourceLocation();
13161 return OpenACCDevicePtrClause::Create(getContext(), BeginLoc, LParenLoc,
13162 VarList, EndLoc);
13163 }
13165 SourceLocation LParenLoc = readSourceLocation();
13167 return OpenACCNoCreateClause::Create(getContext(), BeginLoc, LParenLoc,
13168 VarList, EndLoc);
13169 }
13171 SourceLocation LParenLoc = readSourceLocation();
13173 return OpenACCPresentClause::Create(getContext(), BeginLoc, LParenLoc,
13174 VarList, EndLoc);
13175 }
13179 SourceLocation LParenLoc = readSourceLocation();
13182 return OpenACCCopyClause::Create(getContext(), ClauseKind, BeginLoc,
13183 LParenLoc, ModList, VarList, EndLoc);
13184 }
13188 SourceLocation LParenLoc = readSourceLocation();
13191 return OpenACCCopyInClause::Create(getContext(), ClauseKind, BeginLoc,
13192 LParenLoc, ModList, VarList, EndLoc);
13193 }
13197 SourceLocation LParenLoc = readSourceLocation();
13200 return OpenACCCopyOutClause::Create(getContext(), ClauseKind, BeginLoc,
13201 LParenLoc, ModList, VarList, EndLoc);
13202 }
13206 SourceLocation LParenLoc = readSourceLocation();
13209 return OpenACCCreateClause::Create(getContext(), ClauseKind, BeginLoc,
13210 LParenLoc, ModList, VarList, EndLoc);
13211 }
13213 SourceLocation LParenLoc = readSourceLocation();
13214 Expr *AsyncExpr = readBool() ? readSubExpr() : nullptr;
13215 return OpenACCAsyncClause::Create(getContext(), BeginLoc, LParenLoc,
13216 AsyncExpr, EndLoc);
13217 }
13219 SourceLocation LParenLoc = readSourceLocation();
13220 Expr *DevNumExpr = readBool() ? readSubExpr() : nullptr;
13221 SourceLocation QueuesLoc = readSourceLocation();
13223 return OpenACCWaitClause::Create(getContext(), BeginLoc, LParenLoc,
13224 DevNumExpr, QueuesLoc, QueueIdExprs,
13225 EndLoc);
13226 }
13229 SourceLocation LParenLoc = readSourceLocation();
13231 unsigned NumArchs = readInt();
13232
13233 for (unsigned I = 0; I < NumArchs; ++I) {
13234 IdentifierInfo *Ident = readBool() ? readIdentifier() : nullptr;
13236 Archs.emplace_back(Loc, Ident);
13237 }
13238
13239 return OpenACCDeviceTypeClause::Create(getContext(), ClauseKind, BeginLoc,
13240 LParenLoc, Archs, EndLoc);
13241 }
13243 SourceLocation LParenLoc = readSourceLocation();
13247
13248 for (unsigned I = 0; I < VarList.size(); ++I) {
13249 VarDecl *Recipe = readDeclAs<VarDecl>();
13250
13251 static_assert(sizeof(OpenACCReductionRecipe::CombinerRecipe) ==
13252 3 * sizeof(int *));
13253
13255 unsigned NumCombiners = readInt();
13256 for (unsigned I = 0; I < NumCombiners; ++I) {
13259 Expr *Op = readExpr();
13260
13261 Combiners.push_back({LHS, RHS, Op});
13262 }
13263
13264 RecipeList.push_back({Recipe, Combiners});
13265 }
13266
13267 return OpenACCReductionClause::Create(getContext(), BeginLoc, LParenLoc, Op,
13268 VarList, RecipeList, EndLoc);
13269 }
13271 return OpenACCSeqClause::Create(getContext(), BeginLoc, EndLoc);
13273 return OpenACCNoHostClause::Create(getContext(), BeginLoc, EndLoc);
13275 return OpenACCFinalizeClause::Create(getContext(), BeginLoc, EndLoc);
13277 return OpenACCIfPresentClause::Create(getContext(), BeginLoc, EndLoc);
13279 return OpenACCIndependentClause::Create(getContext(), BeginLoc, EndLoc);
13281 return OpenACCAutoClause::Create(getContext(), BeginLoc, EndLoc);
13283 SourceLocation LParenLoc = readSourceLocation();
13284 bool HasForce = readBool();
13285 Expr *LoopCount = readSubExpr();
13286 return OpenACCCollapseClause::Create(getContext(), BeginLoc, LParenLoc,
13287 HasForce, LoopCount, EndLoc);
13288 }
13290 SourceLocation LParenLoc = readSourceLocation();
13291 unsigned NumClauses = readInt();
13292 llvm::SmallVector<Expr *> SizeExprs;
13293 for (unsigned I = 0; I < NumClauses; ++I)
13294 SizeExprs.push_back(readSubExpr());
13295 return OpenACCTileClause::Create(getContext(), BeginLoc, LParenLoc,
13296 SizeExprs, EndLoc);
13297 }
13299 SourceLocation LParenLoc = readSourceLocation();
13300 unsigned NumExprs = readInt();
13303 for (unsigned I = 0; I < NumExprs; ++I) {
13304 GangKinds.push_back(readEnum<OpenACCGangKind>());
13305 // Can't use `readSubExpr` because this is usable from a 'decl' construct.
13306 Exprs.push_back(readExpr());
13307 }
13308 return OpenACCGangClause::Create(getContext(), BeginLoc, LParenLoc,
13309 GangKinds, Exprs, EndLoc);
13310 }
13312 SourceLocation LParenLoc = readSourceLocation();
13313 Expr *WorkerExpr = readBool() ? readSubExpr() : nullptr;
13314 return OpenACCWorkerClause::Create(getContext(), BeginLoc, LParenLoc,
13315 WorkerExpr, EndLoc);
13316 }
13318 SourceLocation LParenLoc = readSourceLocation();
13319 Expr *VectorExpr = readBool() ? readSubExpr() : nullptr;
13320 return OpenACCVectorClause::Create(getContext(), BeginLoc, LParenLoc,
13321 VectorExpr, EndLoc);
13322 }
13324 SourceLocation LParenLoc = readSourceLocation();
13326 return OpenACCLinkClause::Create(getContext(), BeginLoc, LParenLoc, VarList,
13327 EndLoc);
13328 }
13330 SourceLocation LParenLoc = readSourceLocation();
13333 LParenLoc, VarList, EndLoc);
13334 }
13335
13337 SourceLocation LParenLoc = readSourceLocation();
13338 bool IsString = readBool();
13339 if (IsString)
13340 return OpenACCBindClause::Create(getContext(), BeginLoc, LParenLoc,
13341 cast<StringLiteral>(readExpr()), EndLoc);
13342 return OpenACCBindClause::Create(getContext(), BeginLoc, LParenLoc,
13343 readIdentifier(), EndLoc);
13344 }
13347 llvm_unreachable("Clause serialization not yet implemented");
13348 }
13349 llvm_unreachable("Invalid Clause Kind");
13350}
13351
13354 for (unsigned I = 0; I < Clauses.size(); ++I)
13355 Clauses[I] = readOpenACCClause();
13356}
13357
13358void ASTRecordReader::readOpenACCRoutineDeclAttr(OpenACCRoutineDeclAttr *A) {
13359 unsigned NumVars = readInt();
13360 A->Clauses.resize(NumVars);
13361 readOpenACCClauseList(A->Clauses);
13362}
13363
13364static unsigned getStableHashForModuleName(StringRef PrimaryModuleName) {
13365 // TODO: Maybe it is better to check PrimaryModuleName is a valid
13366 // module name?
13367 llvm::FoldingSetNodeID ID;
13368 ID.AddString(PrimaryModuleName);
13369 return ID.computeStableHash();
13370}
13371
13373 if (!M)
13374 return std::nullopt;
13375
13376 if (M->isHeaderLikeModule())
13377 return std::nullopt;
13378
13379 if (M->isGlobalModule())
13380 return std::nullopt;
13381
13382 StringRef PrimaryModuleName = M->getPrimaryModuleInterfaceName();
13383 return getStableHashForModuleName(PrimaryModuleName);
13384}
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 unsigned getModuleFileIndexForTypeID(serialization::TypeID ID)
static void collectMacroDefinitions(const PreprocessorOptions &PPOpts, MacroDefinitionsMap &Macros, SmallVectorImpl< StringRef > *MacroNames=nullptr)
Collect the macro definitions provided by the given preprocessor options.
static void markIdentifierFromAST(ASTReader &Reader, IdentifierInfo &II, bool IsModule)
static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method)
Move the given method to the back of the global list of methods.
static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps)
static bool isInterestingIdentifier(ASTReader &Reader, const IdentifierInfo &II, bool IsModule)
Whether the given identifier is "interesting".
static bool parseModuleFileExtensionMetadata(const SmallVectorImpl< uint64_t > &Record, StringRef Blob, ModuleFileExtensionMetadata &Metadata)
Parse a record and blob containing module file extension metadata.
static Module * getTopImportImplicitModule(ModuleManager &ModuleMgr, Preprocessor &PP)
Return the top import module if it is implicit, nullptr otherwise.
static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts, const PreprocessorOptions &ExistingPPOpts, StringRef ModuleFilename, bool ReadMacros, DiagnosticsEngine *Diags, FileManager &FileMgr, std::string &SuggestedPredefines, const LangOptions &LangOpts, OptionValidation Validation=OptionValidateContradictions)
Check the preprocessor options deserialized from the control block against the preprocessor options i...
static void addMethodsToPool(Sema &S, ArrayRef< ObjCMethodDecl * > Methods, ObjCMethodList &List)
Add the given set of methods to the method list.
static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags, DiagnosticsEngine &Diags, StringRef ModuleFilename, bool IsSystem, bool SystemHeaderWarningsInModule, bool Complain)
static bool isPredefinedType(serialization::TypeID ID)
static bool readBit(unsigned &Bits)
static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags, DiagnosticsEngine &Diags, StringRef ModuleFilename, bool Complain)
static std::optional< Type::TypeClass > getTypeClassForCode(TypeCode code)
static std::pair< unsigned, unsigned > readULEBKeyDataLength(const unsigned char *&P)
Read ULEB-encoded key length and data length.
static unsigned getStableHashForModuleName(StringRef PrimaryModuleName)
static LLVM_DUMP_METHOD void dumpModuleIDMap(StringRef Name, const ContinuousRangeMap< Key, ModuleFile *, InitialCapacity > &Map)
OptionValidation
@ OptionValidateStrictMatches
@ OptionValidateNone
@ OptionValidateContradictions
static bool checkTargetOptions(const TargetOptions &TargetOpts, const TargetOptions &ExistingTargetOpts, StringRef ModuleFilename, DiagnosticsEngine *Diags, bool AllowCompatibleDifferences=true)
Compare the given set of target options against an existing set of target options.
static bool checkLanguageOptions(const LangOptions &LangOpts, const LangOptions &ExistingLangOpts, StringRef ModuleFilename, DiagnosticsEngine *Diags, bool AllowCompatibleDifferences=true)
Compare the given set of language options against an existing set of language options.
static std::pair< StringRef, StringRef > getUnresolvedInputFilenames(const ASTReader::RecordData &Record, const StringRef InputBlob)
#define CHECK_TARGET_OPT(Field, Name)
static ASTFileSignature readASTFileSignature(StringRef PCH)
Reads and return the signature record from PCH's control block, or else returns 0.
static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID)
Given a cursor at the start of an AST file, scan ahead and drop the cursor into the start of the give...
static unsigned getIndexForTypeID(serialization::TypeID ID)
static uint64_t readULEB(const unsigned char *&P)
static bool checkModuleCachePath(FileManager &FileMgr, StringRef ContextHash, StringRef ExistingSpecificModuleCachePath, StringRef ASTFilename, DiagnosticsEngine *Diags, const LangOptions &LangOpts, const PreprocessorOptions &PPOpts, const HeaderSearchOptions &HSOpts, const HeaderSearchOptions &ASTFileHSOpts)
Check that the specified and the existing module cache paths are equivalent.
Defines the clang::ASTSourceDescriptor class, which abstracts clang modules and precompiled header fi...
static StringRef bytes(const std::vector< T, Allocator > &v)
Defines the Diagnostic-related interfaces.
Defines the clang::CommentOptions interface.
static void dump(llvm::raw_ostream &OS, StringRef FunctionName, ArrayRef< CounterExpression > Expressions, ArrayRef< CounterMappingRegion > Regions)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the C++ template declaration subclasses.
Defines the Diagnostic IDs-related interfaces.
static bool hasDefinition(const ObjCObjectPointerType *ObjPtr)
Defines the clang::Expr interface and subclasses for C++ expressions.
Defines the clang::FileManager interface and associated types.
Defines the clang::FileSystemOptions interface.
Token Tok
The Token.
FormatToken * Previous
The previous token in the unwrapped line.
FormatToken * Next
The next token in the unwrapped line.
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the clang::LangOptions interface.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Record Record
Definition MachO.h:31
Defines the clang::MacroInfo and clang::MacroDirective classes.
Defines the clang::Module class, which describes a module in the source code.
Defines types useful for describing an Objective-C runtime.
#define SM(sm)
Defines some OpenACC-specific enums and functions.
This file defines OpenMP AST classes for clauses.
Defines some OpenMP-specific enums and functions.
Defines an enumeration for C++ overloaded operators.
Defines the clang::Preprocessor interface.
Defines the clang::SanitizerKind enum.
This file declares semantic analysis for CUDA constructs.
This file declares semantic analysis for Objective-C.
Defines the clang::SourceLocation class and associated facilities.
Defines implementation details of the clang::SourceManager class.
Defines the SourceManager interface.
Defines various enumerations that describe declaration and type specifiers.
Defines the clang::TargetOptions class.
#define IMPORT(DERIVED, BASE)
Definition Template.h:630
Defines the clang::TokenKind enum and support functions.
Defines the clang::TypeLoc interface and its subclasses.
C Language Family Type Representation.
Defines version macros and version-related utility functions for Clang.
__DEVICE__ void * memcpy(void *__a, const void *__b, size_t __c)
__device__ __2f16 b
static OMPAffinityClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with the place for N locator items.
static OMPAlignedClause * CreateEmpty(const ASTContext &C, unsigned NumVars)
Creates an empty clause with the place for NumVars variables.
static OMPBindClause * CreateEmpty(const ASTContext &C)
Build an empty 'bind' clause.
Contains data for OpenMP directives: clauses, children expressions/statements (helpers for codegen) a...
static OMPCopyinClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with N variables.
static OMPCopyprivateClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with N variables.
This represents 'defaultmap' clause in the 'pragma omp ...' directive.
static OMPDependClause * CreateEmpty(const ASTContext &C, unsigned N, unsigned NumLoops)
Creates an empty clause with N variables.
static OMPDepobjClause * CreateEmpty(const ASTContext &C)
Creates an empty clause.
This represents 'destroy' clause in the 'pragma omp depobj' directive or the 'pragma omp interop' dir...
This represents 'detach' clause in the 'pragma omp task' directive.
This represents 'device' clause in the 'pragma omp ...' directive.
This represents 'dist_schedule' clause in the 'pragma omp ...' directive.
static OMPDoacrossClause * CreateEmpty(const ASTContext &C, unsigned N, unsigned NumLoops)
Creates an empty clause with N expressions.
This represents 'dyn_groupprivate' clause in 'pragma omp target ...' and 'pragma omp teams ....
static OMPExclusiveClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with the place for N variables.
This represents 'filter' clause in the 'pragma omp ...' directive.
static OMPFlushClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with N variables.
static OMPFromClause * CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes)
Creates an empty clause with the place for NumVars variables.
This represents 'grainsize' clause in the 'pragma omp ...' directive.
static OMPHasDeviceAddrClause * CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes)
Creates an empty clause with the place for NumVars variables.
This represents 'hint' clause in the 'pragma omp ...' directive.
static OMPInclusiveClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with the place for N variables.
static OMPInitClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with N expressions.
static OMPIsDevicePtrClause * CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes)
Creates an empty clause with the place for NumVars variables.
static OMPMapClause * CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes)
Creates an empty clause with the place for NumVars original expressions, NumUniqueDeclarations declar...
This represents 'nocontext' clause in the 'pragma omp ...' directive.
This represents 'nogroup' clause in the 'pragma omp ...' directive.
static OMPNontemporalClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with the place for N variables.
This represents 'novariants' clause in the 'pragma omp ...' directive.
This represents 'num_tasks' clause in the 'pragma omp ...' directive.
static OMPNumTeamsClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with N variables.
This represents 'order' clause in the 'pragma omp ...' directive.
This represents 'priority' clause in the 'pragma omp ...' directive.
This represents 'simd' clause in the 'pragma omp ...' directive.
static OMPThreadLimitClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with N variables.
This represents 'threads' clause in the 'pragma omp ...' directive.
static OMPToClause * CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes)
Creates an empty clause with the place for NumVars variables.
llvm::SmallVector< OMPTraitSet, 2 > Sets
The outermost level of selector sets.
This represents the 'use' clause in 'pragma omp ...' directives.
static OMPUseDeviceAddrClause * CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes)
Creates an empty clause with the place for NumVars variables.
static OMPUseDevicePtrClause * CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes)
Creates an empty clause with the place for NumVars variables.
static OMPUsesAllocatorsClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with the place for N allocators.
This represents 'ompx_attribute' clause in a directive that might generate an outlined function.
This represents 'ompx_bare' clause in the 'pragma omp target teams ...' directive.
This represents 'ompx_dyn_cgroup_mem' clause in the 'pragma omp target ...' directive.
ASTConsumer - This is an abstract interface that should be implemented by clients that read ASTs.
Definition ASTConsumer.h:35
virtual void HandleInterestingDecl(DeclGroupRef D)
HandleInterestingDecl - Handle the specified interesting declaration.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:226
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:851
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 visitModuleFile(ModuleFileName Filename, serialization::ModuleKind Kind)
This is called for each AST file loaded.
Definition ASTReader.h:226
virtual bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, StringRef ModuleFilename, StringRef ContextHash, bool Complain)
Receives the header search options.
Definition ASTReader.h:186
virtual void ReadModuleMapFile(StringRef ModuleMapPath)
Definition ASTReader.h:130
virtual bool needsInputFileVisitation()
Returns true if this ASTReaderListener wants to receive the input files of the AST file via visitInpu...
Definition ASTReader.h:231
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:243
virtual bool ReadHeaderSearchPaths(const HeaderSearchOptions &HSOpts, bool Complain)
Receives the header search paths.
Definition ASTReader.h:201
virtual bool ReadFileSystemOptions(const FileSystemOptions &FSOpts, bool Complain)
Receives the file system options.
Definition ASTReader.h:173
virtual bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, StringRef ModuleFilename, bool ReadMacros, bool Complain, std::string &SuggestedPredefines)
Receives the preprocessor options.
Definition ASTReader.h:214
virtual bool ReadLanguageOptions(const LangOptions &LangOpts, StringRef ModuleFilename, bool Complain, bool AllowCompatibleDifferences)
Receives the language options.
Definition ASTReader.h:135
virtual void ReadModuleName(StringRef ModuleName)
Definition ASTReader.h:129
virtual void ReadCounter(const serialization::ModuleFile &M, uint32_t Value)
Receives COUNTER value.
Definition ASTReader.h:222
virtual bool needsSystemInputFileVisitation()
Returns true if this ASTReaderListener wants to receive the system input files of the AST file via vi...
Definition ASTReader.h:235
virtual bool ReadCodeGenOptions(const CodeGenOptions &CGOpts, StringRef ModuleFilename, bool Complain, bool AllowCompatibleDifferences)
Receives the codegen options.
Definition ASTReader.h:144
Reads an AST files chain containing the contents of a translation unit.
Definition ASTReader.h:427
std::optional< bool > isPreprocessedEntityInFileID(unsigned Index, FileID FID) override
Optionally returns true or false if the preallocated preprocessed entity with index Index came from f...
PreprocessedEntity * ReadPreprocessedEntity(unsigned Index) override
Read a preallocated preprocessed entity from the external source.
void markIdentifierUpToDate(const IdentifierInfo *II)
Note that this identifier is up-to-date.
void visitTopLevelModuleMaps(serialization::ModuleFile &MF, llvm::function_ref< void(FileEntryRef)> Visitor)
Visit all the top-level module maps loaded when building the given module file.
void setDeserializationListener(ASTDeserializationListener *Listener, bool TakeOwnership=false)
Set the AST deserialization listener.
SmallVectorImpl< uint64_t > RecordDataImpl
Definition ASTReader.h:443
serialization::SubmoduleID getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) const
Retrieve the global submodule ID given a module and its local ID number.
ExtKind hasExternalDefinitions(const Decl *D) override
IdentifierTable & getIdentifierTable()
Retrieve the identifier table associated with the preprocessor.
ModuleManager & getModuleManager()
Retrieve the module manager.
Definition ASTReader.h:2005
bool isDeclIDFromModule(GlobalDeclID ID, ModuleFile &M) const
Returns true if global DeclID ID originated from module M.
friend class ASTIdentifierIterator
Definition ASTReader.h:432
bool ReadSLocEntry(int ID) override
Read the source location entry with index ID.
void RecordSwitchCaseID(SwitchCase *SC, unsigned ID)
Record that the given ID maps to the given switch-case statement.
DiagnosticBuilder Diag(unsigned DiagID) const
Report a diagnostic.
ASTContext & getContext()
Retrieve the AST context that this AST reader supplements.
Definition ASTReader.h:2624
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:2198
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:1847
@ ARR_ConfigurationMismatch
The client can handle an AST file that cannot load because it's compiled configuration doesn't match ...
Definition ASTReader.h:1860
@ 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:1851
@ 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:1855
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:2658
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:2208
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:440
void SetGloballyVisibleDecls(IdentifierInfo *II, const SmallVectorImpl< GlobalDeclID > &DeclIDs, SmallVectorImpl< Decl * > *Decls=nullptr)
Set the globally-visible declarations associated with the given identifier.
serialization::ModuleKind ModuleKind
Definition ASTReader.h:474
bool loadGlobalIndex()
Attempts to load the global index.
void ReadComments() override
Loads comments ranges.
SourceManager & getSourceManager() const
Definition ASTReader.h:1831
const serialization::reader::ModuleLocalLookupTable * getModuleLocalLookupTables(DeclContext *Primary) const
SourceLocation getSourceLocationForDeclID(GlobalDeclID ID)
Returns the source location for the decl ID.
void makeModuleVisible(Module *Mod, Module::NameVisibilityKind NameVisibility, SourceLocation ImportLoc)
Make the entities in the given module and any of its (non-explicit) submodules visible to name lookup...
SourceRange ReadSourceRange(ModuleFile &F, const RecordData &Record, unsigned &Idx)
Read a source range.
bool LoadExternalSpecializations(const Decl *D, bool OnlyPartial) override
Load all the external specializations for the Decl.
ASTReadResult ReadASTCore(ModuleFileName FileName, ModuleKind Type, SourceLocation ImportLoc, ModuleFile *ImportedBy, SmallVectorImpl< ImportedModule > &Loaded, off_t ExpectedSize, time_t ExpectedModTime, ASTFileSignature ExpectedSignature, unsigned ClientLoadCapabilities)
void finalizeForWriting()
Finalizes the AST reader's state before writing an AST file to disk.
Sema * getSema()
Retrieve the semantic analysis object used to analyze the translation unit in which the precompiled h...
Definition ASTReader.h:2636
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:2074
void StartTranslationUnit(ASTConsumer *Consumer) override
Function that will be invoked when we begin parsing a new translation unit involving this external AS...
LocalDeclID mapGlobalIDToModuleFileGlobalID(ModuleFile &M, GlobalDeclID GlobalID)
Map a global declaration ID into the declaration ID used to refer to this declaration within the give...
void resolvePendingMacro(IdentifierInfo *II, const PendingMacroInfo &PMInfo)
void ReadTentativeDefinitions(SmallVectorImpl< VarDecl * > &TentativeDefs) override
Read the set of tentative definitions known to the external Sema source.
Decl * GetExternalDecl(GlobalDeclID ID) override
Resolve a declaration ID into a declaration, potentially building a new declaration.
serialization::MacroID ReadMacroID(ModuleFile &F, const RecordDataImpl &Record, unsigned &Idx)
Reads a macro ID from the given position in a record in the given module.
GlobalDeclID ReadDeclID(ModuleFile &F, const RecordDataImpl &Record, unsigned &Idx)
Reads a declaration ID from the given position in a record in the given module.
llvm::Expected< SourceLocation::UIntTy > readSLocOffset(ModuleFile *F, unsigned Index)
Try to read the offset of the SLocEntry at the given index in the given module file.
~ASTReader() override
bool haveUnloadedSpecializations(const Decl *D) const
If we have any unloaded specialization for D.
friend class PCHValidator
Definition ASTReader.h:436
friend class serialization::ReadMethodPoolVisitor
Definition ASTReader.h:438
void CompleteRedeclChain(const Decl *D) override
If any redeclarations of D have been imported since it was last checked, this digs out those redeclar...
SourceLocation TranslateSourceLocation(ModuleFile &ModuleFile, SourceLocation Loc) const
Translate a source location from another module file's source location space into ours.
Definition ASTReader.h:2510
static llvm::Error ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor, unsigned BlockID, uint64_t *StartOfBlockOffset=nullptr)
ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the specified cursor.
void SetIdentifierInfo(serialization::IdentifierID ID, IdentifierInfo *II)
std::pair< unsigned, unsigned > findPreprocessedEntitiesInRange(SourceRange Range) override
Returns a pair of [Begin, End) indices of preallocated preprocessed entities that Range encompasses.
IdentifierInfo * get(StringRef Name) override
Retrieve the IdentifierInfo for the named identifier.
IdentifierInfo * getLocalIdentifier(ModuleFile &M, uint64_t LocalID)
void visitInputFiles(serialization::ModuleFile &MF, bool IncludeSystem, bool Complain, llvm::function_ref< void(const serialization::InputFile &IF, bool isSystem)> Visitor)
Visit all the input files of the given module file.
Module * getModule(unsigned ID) override
Retrieve the module that corresponds to the given module ID.
llvm::iterator_range< ModuleDeclIterator > getModuleFileLevelDecls(ModuleFile &Mod)
Stmt * GetExternalDeclStmt(uint64_t Offset) override
Resolve the offset of a statement into a statement.
Selector GetExternalSelector(serialization::SelectorID ID) override
Resolve a selector ID into a selector.
unsigned getTotalNumSelectors() const
Returns the number of selectors found in the chain.
Definition ASTReader.h:2104
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:2631
std::pair< SourceLocation, StringRef > getModuleImportLoc(int ID) override
Retrieve the module import location and module name for the given source manager entry ID.
void ReadUnusedFileScopedDecls(SmallVectorImpl< const DeclaratorDecl * > &Decls) override
Read the set of unused file-scope declarations known to the external Sema source.
void ReadReferencedSelectors(SmallVectorImpl< std::pair< Selector, SourceLocation > > &Sels) override
Read the set of referenced selectors known to the external Sema source.
Selector DecodeSelector(serialization::SelectorID Idx)
StringRef getOriginalSourceFile()
Retrieve the name of the original source file name for the primary module file.
Definition ASTReader.h:2013
std::string ReadPath(ModuleFile &F, const RecordData &Record, unsigned &Idx)
friend class serialization::reader::ASTIdentifierLookupTrait
Definition ASTReader.h:437
unsigned getModuleFileID(ModuleFile *M)
Get an ID for the given module file.
Decl * getKeyDeclaration(Decl *D)
Returns the first key declaration for the given declaration.
Definition ASTReader.h:1496
bool FindExternalVisibleDeclsByName(const DeclContext *DC, DeclarationName Name, const DeclContext *OriginalDC) override
Finds all the visible declarations with a given name.
IdentifierInfo * DecodeIdentifierInfo(serialization::IdentifierID ID)
ASTReadResult
The result of reading the control block of an AST file, which can fail for various reasons.
Definition ASTReader.h:447
@ Success
The control block was read successfully.
Definition ASTReader.h:450
@ ConfigurationMismatch
The AST file was written with a different language/target configuration.
Definition ASTReader.h:467
@ OutOfDate
The AST file is out-of-date relative to its input files, and needs to be regenerated.
Definition ASTReader.h:460
@ Failure
The AST file itself appears corrupted.
Definition ASTReader.h:453
@ VersionMismatch
The AST file was written by a different version of Clang.
Definition ASTReader.h:463
@ HadErrors
The AST file has errors.
Definition ASTReader.h:470
@ Missing
The AST file was missing.
Definition ASTReader.h:456
static VersionTuple ReadVersionTuple(const RecordData &Record, unsigned &Idx)
Read a version tuple.
Token ReadToken(ModuleFile &M, const RecordDataImpl &Record, unsigned &Idx)
Reads a token out of a record.
SwitchCase * getSwitchCaseWithID(unsigned ID)
Retrieve the switch-case statement with the given ID.
serialization::IdentifierID getGlobalIdentifierID(ModuleFile &M, uint64_t LocalID)
FileID TranslateFileID(ModuleFile &F, FileID FID) const
Translate a FileID from another module file's FileID space into ours.
Definition ASTReader.h:2538
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:2162
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:2494
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:2009
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.
static bool isAcceptableASTFile(StringRef Filename, FileManager &FileMgr, const ModuleCache &ModCache, const PCHContainerReader &PCHContainerRdr, const LangOptions &LangOpts, const CodeGenOptions &CGOpts, const TargetOptions &TargetOpts, const PreprocessorOptions &PPOpts, const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath, bool RequireStrictOptionMatches=false)
Determine whether the given AST file is acceptable to load into a translation unit with the given lan...
void mergeDefinitionVisibility(NamedDecl *Def, NamedDecl *MergedDef)
Note that MergedDef is a redefinition of the canonical definition Def, so Def should be visible whene...
serialization::SelectorID getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const
Retrieve the global selector ID that corresponds to this the local selector ID in a given module.
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
friend class ASTRecordReader
Definition ASTReader.h:433
SmallVector< uint64_t, 64 > RecordData
Definition ASTReader.h:442
FileID ReadFileID(ModuleFile &F, const RecordDataImpl &Record, unsigned &Idx) const
Read a FileID.
Definition ASTReader.h:2532
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:1832
bool wasThisDeclarationADefinition(const FunctionDecl *FD) override
True if this function declaration was a definition before in its own module.
void FinishedDeserializing() override
Notify ASTReader that we finished the deserialization of a decl or type.
void updateOutOfDateIdentifier(const IdentifierInfo &II) override
Update an out-of-date identifier.
ASTReadResult ReadAST(ModuleFileName FileName, ModuleKind Type, SourceLocation ImportLoc, unsigned ClientLoadCapabilities, ModuleFile **NewLoadedModuleFile=nullptr)
Load the AST file designated by the given file name.
void ReadDefinedMacros() override
Read the set of macros defined by this external macro source.
HeaderFileInfo GetHeaderFileInfo(FileEntryRef FE) override
Read the header file information for the given file entry.
void getMemoryBufferSizes(MemoryBufferSizes &sizes) const override
Return the amount of memory used by memory buffers, breaking down by heap-backed versus mmap'ed memor...
serialization::ModuleFile ModuleFile
Definition ASTReader.h:473
bool hasGlobalIndex() const
Determine whether this AST reader has a global index.
Definition ASTReader.h:1968
serialization::PreprocessedEntityID getGlobalPreprocessedEntityID(ModuleFile &M, serialization::PreprocessedEntityID LocalID) const
Determine the global preprocessed entity ID that corresponds to the given local ID within the given m...
An object for streaming information from a record.
bool readBool()
Read a boolean value, advancing Idx.
uint32_t readUInt32()
Read a 32-bit unsigned value; required to satisfy BasicReader.
llvm::APFloat readAPFloat(const llvm::fltSemantics &Sem)
Read an arbitrary constant value, advancing Idx.
TemplateArgumentLoc readTemplateArgumentLoc()
Reads a TemplateArgumentLoc, advancing Idx.
SourceRange readSourceRange()
Read a source range, advancing Idx.
SourceLocation readSourceLocation()
Read a source location, advancing Idx.
void readUnresolvedSet(LazyASTUnresolvedSet &Set)
Read a UnresolvedSet structure, advancing Idx.
void readTemplateArgumentList(SmallVectorImpl< TemplateArgument > &TemplArgs, bool Canonicalize=false)
Read a template argument array, advancing Idx.
void readQualifierInfo(QualifierInfo &Info)
DeclarationNameLoc readDeclarationNameLoc(DeclarationName Name)
Read a declaration name, advancing Idx.
CXXBaseSpecifier readCXXBaseSpecifier()
Read a C++ base specifier, advancing Idx.
QualType readType()
Read a type from the current position in the record.
T * readDeclAs()
Reads a declaration from the given position in the record, advancing Idx.
Expected< unsigned > readRecord(llvm::BitstreamCursor &Cursor, unsigned AbbrevID)
Reads a record with id AbbrevID from Cursor, resetting the internal state.
DeclarationNameInfo readDeclarationNameInfo()
void readTypeLoc(TypeLoc TL)
Reads the location information for a type.
IdentifierInfo * readIdentifier()
TemplateArgumentLocInfo readTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind)
Reads a TemplateArgumentLocInfo appropriate for the given TemplateArgument kind, advancing Idx.
TemplateArgument readTemplateArgument(bool Canonicalize)
ASTContext & getContext()
Retrieve the AST context that this AST reader supplements.
TypeSourceInfo * readTypeSourceInfo()
Reads a declarator info from the given record, advancing Idx.
void readTemplateArgumentListInfo(TemplateArgumentListInfo &Result)
TypeCoupledDeclRefInfo readTypeCoupledDeclRefInfo()
void skipInts(unsigned N)
Skips the specified number of values.
GlobalDeclID readDeclID()
Reads a declaration ID from the given position in this record.
NestedNameSpecifierLoc readNestedNameSpecifierLoc()
Return a nested name specifier, advancing Idx.
ConceptReference * readConceptReference()
void readOMPChildren(OMPChildren *Data)
Read an OpenMP children, advancing Idx.
OMPClause * readOMPClause()
Read an OpenMP clause, advancing Idx.
void readOpenACCClauseList(MutableArrayRef< const OpenACCClause * > Clauses)
Read a list of OpenACC clauses into the passed SmallVector, during statement reading.
OMPTraitInfo * readOMPTraitInfo()
Read an OMPTraitInfo object, advancing Idx.
TemplateParameterList * readTemplateParameterList()
Read a template parameter list, advancing Idx.
OpenACCClause * readOpenACCClause()
Read an OpenACC clause, advancing Idx.
llvm::SmallVector< Expr * > readOpenACCVarList()
Read a list of Exprs used for a var-list.
CXXCtorInitializer ** readCXXCtorInitializers()
Read a CXXCtorInitializer array, advancing Idx.
SpirvOperand readHLSLSpirvOperand()
Stmt * readStmt()
Reads a statement.
const ASTTemplateArgumentListInfo * readASTTemplateArgumentListInfo()
uint64_t readInt()
Returns the current value in this record, and advances to the next value.
Expr * readExpr()
Reads an expression.
void readOpenACCRoutineDeclAttr(OpenACCRoutineDeclAttr *A)
llvm::SmallVector< Expr * > readOpenACCIntExprList()
Read a list of Exprs used for a int-expr-list.
Expr * readSubExpr()
Reads a sub-expression operand during statement reading.
Abstracts clang modules and precompiled header files and holds everything needed to generate debug in...
Wrapper for source info for arrays.
Definition TypeLoc.h:1777
void setLBracketLoc(SourceLocation Loc)
Definition TypeLoc.h:1783
void setRBracketLoc(SourceLocation Loc)
Definition TypeLoc.h:1791
void setSizeExpr(Expr *Size)
Definition TypeLoc.h:1803
void setRParenLoc(SourceLocation Loc)
Definition TypeLoc.h:2689
void setLParenLoc(SourceLocation Loc)
Definition TypeLoc.h:2681
void setKWLoc(SourceLocation Loc)
Definition TypeLoc.h:2673
Attr - This represents one attribute.
Definition Attr.h:46
void setAttr(const Attr *A)
Definition TypeLoc.h:1034
void setConceptReference(ConceptReference *CR)
Definition TypeLoc.h:2405
void setRParenLoc(SourceLocation Loc)
Definition TypeLoc.h:2399
void setCaretLoc(SourceLocation Loc)
Definition TypeLoc.h:1532
void setWrittenTypeSpec(TypeSpecifierType written)
Definition TypeLoc.h:663
bool needsExtraLocalData() const
Definition TypeLoc.h:606
void setModeAttr(bool written)
Definition TypeLoc.h:675
void setBuiltinLoc(SourceLocation Loc)
Definition TypeLoc.h:583
void setWrittenWidthSpec(TypeSpecifierWidth written)
Definition TypeLoc.h:652
void setWrittenSignSpec(TypeSpecifierSign written)
Definition TypeLoc.h:636
Represents a base class of a C++ class.
Definition DeclCXX.h:146
Represents a C++ constructor within a class.
Definition DeclCXX.h:2611
Represents a C++ base or member initializer.
Definition DeclCXX.h:2376
void setSourceOrder(int Pos)
Set the source order of this initializer.
Definition DeclCXX.h:2563
Represents a C++ destructor within a class.
Definition DeclCXX.h:2876
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
Decl * getLambdaContextDecl() const
Retrieve the declaration that provides additional context for a lambda, when the normal declaration c...
Definition DeclCXX.cpp:1834
unsigned getLambdaIndexInContext() const
Retrieve the index of this lambda within the context declaration returned by getLambdaContextDecl().
Definition DeclCXX.h:1799
base_class_iterator bases_begin()
Definition DeclCXX.h:615
base_class_iterator vbases_begin()
Definition DeclCXX.h:632
Represents a C++ temporary.
Definition ExprCXX.h:1460
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.
void visitModuleFile(ModuleFileName Filename, serialization::ModuleKind Kind) override
This is called for each AST file loaded.
bool ReadFullVersionInformation(StringRef FullVersion) override
Receives the full Clang version information.
bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, StringRef ModuleFilename, StringRef ContextHash, bool Complain) override
Receives the header search options.
bool ReadFileSystemOptions(const FileSystemOptions &FSOpts, bool Complain) override
Receives the file system options.
void ReadModuleMapFile(StringRef ModuleMapPath) override
bool ReadLanguageOptions(const LangOptions &LangOpts, StringRef ModuleFilename, bool Complain, bool AllowCompatibleDifferences) override
Receives the language options.
bool ReadTargetOptions(const TargetOptions &TargetOpts, StringRef ModuleFilename, bool Complain, bool AllowCompatibleDifferences) override
Receives the target options.
void ReadModuleName(StringRef ModuleName) override
bool needsInputFileVisitation() override
Returns true if this ASTReaderListener wants to receive the input files of the AST file via visitInpu...
bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, StringRef ModuleFilename, bool ReadMacros, bool Complain, std::string &SuggestedPredefines) override
Receives the preprocessor options.
void readModuleFileExtension(const ModuleFileExtensionMetadata &Metadata) override
Indicates that a particular module file extension has been read.
bool needsSystemInputFileVisitation() override
Returns true if this ASTReaderListener wants to receive the system input files of the AST file via vi...
bool ReadDiagnosticOptions(DiagnosticOptions &DiagOpts, StringRef ModuleFilename, bool Complain) override
Receives the diagnostic options.
CompatibilityKind
For ASTs produced with different option value, signifies their level of compatibility.
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
A reference to a concept and its template args, as it appears in the code.
Definition ASTConcept.h:130
static ConceptReference * Create(const ASTContext &C, NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc, DeclarationNameInfo ConceptNameInfo, NamedDecl *FoundDecl, TemplateDecl *NamedConcept, const ASTTemplateArgumentListInfo *ArgsAsWritten)
const TypeClass * getTypePtr() const
Definition TypeLoc.h:433
A map from continuous integer ranges to some value, with a very specialized interface.
void insertOrReplace(const value_type &Val)
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:248
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:2291
void setDecltypeLoc(SourceLocation Loc)
Definition TypeLoc.h:2288
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition TypeLoc.h:2531
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:2513
void setTemplateNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2519
void setAttrNameLoc(SourceLocation loc)
Definition TypeLoc.h:1977
void setAttrOperandParensRange(SourceRange range)
Definition TypeLoc.h:1998
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2601
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:2581
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition TypeLoc.h:2590
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2096
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2068
A little helper class used to produce diagnostics.
bool wasUpgradedFromWarning() const
Whether this mapping attempted to map the diagnostic to a warning, but was overruled because the diag...
void setSeverity(diag::Severity Value)
static DiagnosticMapping deserialize(unsigned Bits)
Deserialize a mapping.
void setUpgradedFromWarning(bool Value)
Options for controlling the compiler diagnostics engine.
std::vector< std::string > Remarks
The list of -R... options used to alter the diagnostic mappings, with the prefixes removed.
std::vector< std::string > Warnings
The list of -W... options used to alter the diagnostic mappings, with the prefixes removed.
std::vector< std::string > SystemHeaderWarningsModules
The list of -Wsystem-headers-in-module=... options used to override whether -Wsystem-headers is enabl...
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:232
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
DiagnosticOptions & getDiagnosticOptions() const
Retrieve the diagnostic options.
Definition Diagnostic.h:602
bool getEnableAllWarnings() const
Definition Diagnostic.h:702
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:974
bool getSuppressSystemWarnings() const
Definition Diagnostic.h:728
bool getWarningsAsErrors() const
Definition Diagnostic.h:710
diag::Severity getExtensionHandlingBehavior() const
Definition Diagnostic.h:818
const IntrusiveRefCntPtr< DiagnosticIDs > & getDiagnosticIDs() const
Definition Diagnostic.h:597
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:3175
A reference to a FileEntry that includes the name of the file as it was accessed by the FileManager's...
Definition FileEntry.h:57
time_t getModificationTime() const
Definition FileEntry.h:354
off_t getSize() const
Definition FileEntry.h:346
StringRef getName() const
The name of this FileEntry.
Definition FileEntry.h:61
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
bool isValid() const
bool isInvalid() const
Implements support for file system lookup, file system caching, and directory search management.
Definition FileManager.h:53
llvm::ErrorOr< std::unique_ptr< llvm::MemoryBuffer > > getBufferForFile(FileEntryRef Entry, bool isVolatile=false, bool RequiresNullTerminator=true, std::optional< int64_t > MaybeLimit=std::nullopt, bool IsText=true)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful,...
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...
OptionalDirectoryEntryRef getOptionalDirectoryRef(StringRef DirName, bool CacheFailure=true)
Get a DirectoryEntryRef if it exists, without doing anything on error.
Keeps track of options that affect how file operations are performed.
std::string WorkingDir
If set, paths are resolved as if the working directory was set to the value of WorkingDir.
Represents a function declaration or definition.
Definition Decl.h:2015
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5357
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5646
Wrapper for source info for functions.
Definition TypeLoc.h:1644
unsigned getNumParams() const
Definition TypeLoc.h:1716
void setLocalRangeBegin(SourceLocation L)
Definition TypeLoc.h:1664
void setLParenLoc(SourceLocation Loc)
Definition TypeLoc.h:1680
void setParam(unsigned i, ParmVarDecl *VD)
Definition TypeLoc.h:1723
void setRParenLoc(SourceLocation Loc)
Definition TypeLoc.h:1688
void setLocalRangeEnd(SourceLocation L)
Definition TypeLoc.h:1672
void setExceptionSpecRange(SourceRange R)
Definition TypeLoc.h:1702
llvm::SmallPtrSet< ModuleFile *, 4 > HitSet
A set of module files in which we found a result.
static std::pair< GlobalModuleIndex *, llvm::Error > readIndex(llvm::StringRef Path)
Read a global index file for the given directory.
HeaderSearchOptions - Helper class for storing options related to the initialization of the HeaderSea...
uint64_t BuildSessionTimestamp
The time in seconds when the build session started.
unsigned ImplicitModuleMaps
Implicit module maps.
std::vector< SystemHeaderPrefix > SystemHeaderPrefixes
User-specified system header prefixes.
unsigned EnablePrebuiltImplicitModules
Also search for prebuilt implicit modules in the prebuilt module cache path.
unsigned ModuleMapFileHomeIsCwd
Set the 'home directory' of a module map file to the current working directory (or the home directory...
std::string Sysroot
If non-empty, the directory to use as a "virtual system root" for include paths.
std::string ModuleCachePath
The directory used for the module cache.
std::string ModuleUserBuildPath
The directory used for a user build.
std::vector< std::string > VFSOverlayFiles
The set of user-provided virtual filesystem overlay files.
unsigned UseLibcxx
Use libc++ instead of the default libstdc++.
unsigned UseBuiltinIncludes
Include the compiler builtin includes.
unsigned UseStandardCXXIncludes
Include the system standard C++ library include search directories.
std::vector< Entry > UserEntries
User specified include entries.
std::string ResourceDir
The directory which holds the compiler resource files (builtin includes, etc.).
unsigned UseStandardSystemIncludes
Include the system standard include search directories.
unsigned ModulesValidateOncePerBuildSession
If true, skip verifying input files used by modules if the module was already verified during this bu...
unsigned DisableModuleHash
Whether we should disable the use of the hash string within the module cache.
Encapsulates the information needed to find the file referenced by a #include or #include_next,...
Module * lookupModule(StringRef ModuleName, SourceLocation ImportLoc=SourceLocation(), bool AllowSearch=true, bool AllowExtraModuleMapSearch=false)
Lookup a module Search for a module with the given name.
const HeaderSearchOptions & getHeaderSearchOpts() const
Retrieve the header-search options with which this header search was initialized.
StringRef getSpecificModuleCachePath() const
Retrieve the specific module cache path.
One of these records is kept for each identifier that is lexed.
unsigned getBuiltinID() const
Return a value indicating whether this is a builtin function.
bool isCPlusPlusOperatorKeyword() const
tok::TokenKind getTokenID() const
If this is a source-language token (e.g.
bool hadMacroDefinition() const
Returns true if this identifier was #defined to some value at any moment.
void setIsPoisoned(bool Value=true)
setIsPoisoned - Mark this identifier as poisoned.
bool isFromAST() const
Return true if the identifier in its current state was loaded from an AST file.
bool isPoisoned() const
Return true if this token has been poisoned.
bool hasRevertedTokenIDToIdentifier() const
True if revertTokenIDToIdentifier() was called.
tok::NotableIdentifierKind getNotableIdentifierID() const
void setOutOfDate(bool OOD)
Set whether the information for this identifier is out of date with respect to the external source.
tok::ObjCKeywordKind getObjCKeywordID() const
Return the Objective-C keyword ID for the this identifier.
void setObjCOrBuiltinID(unsigned ID)
void revertTokenIDToIdentifier()
Revert TokenID to tok::identifier; used for GNU libstdc++ 4.2 compatibility.
bool isOutOfDate() const
Determine whether the information for this identifier is out of date with respect to the external sou...
void setChangedSinceDeserialization()
Note that this identifier has changed since it was loaded from an AST file.
void * getFETokenInfo() const
Get and set FETokenInfo.
StringRef getName() const
Return the actual identifier string.
bool isExtensionToken() const
get/setExtension - Initialize information about whether or not this language token is an extension.
An iterator that walks over all of the known identifiers in the lookup table.
IdentifierResolver - Keeps track of shadowed decls on enclosing scopes.
void RemoveDecl(NamedDecl *D)
RemoveDecl - Unlink the decl from its shadowed decl chain.
Implements an efficient mapping from strings to IdentifierInfo nodes.
llvm::MemoryBuffer * lookupPCM(llvm::StringRef Filename) 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:3482
Wrapper for source info for injected class names of class templates.
Definition TypeLoc.h:872
void setAmpLoc(SourceLocation Loc)
Definition TypeLoc.h:1614
CompatibilityKind
For ASTs produced with different option value, signifies their level of compatibility.
Definition LangOptions.h:83
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
clang::ObjCRuntime ObjCRuntime
SanitizerSet Sanitize
Set of enabled sanitizers.
CommentOptions CommentOpts
Options for parsing comments.
std::string OMPHostIRFile
Name of the IR file that contains the result of the OpenMP target host code generation.
std::vector< llvm::Triple > OMPTargetTriples
Triples of the OpenMP targets that the host code codegen should take into account in order to generat...
std::string CurrentModule
The name of the current module, of which the main source file is a part.
std::vector< std::string > ModuleFeatures
The names of any features to enable in module 'requires' decls in addition to the hard-coded list in ...
An UnresolvedSet-like class that might not have been loaded from the external AST source yet.
unsigned getLineTableFilenameID(StringRef Str)
void AddEntry(FileID FID, const std::vector< LineEntry > &Entries)
Add a new line entry that has already been encoded into the internal representation of the line table...
static LocalDeclID get(ASTReader &Reader, serialization::ModuleFile &MF, DeclID ID)
Record the location of a macro definition.
Encapsulates changes to the "macros namespace" (the location where the macro name became active,...
Definition MacroInfo.h:313
void setPrevious(MacroDirective *Prev)
Set previous definition of the macro with the same name.
Definition MacroInfo.h:351
Records the location of a macro expansion.
Encapsulates the data about a macro definition (e.g.
Definition MacroInfo.h:39
void setUsedForHeaderGuard(bool Val)
Definition MacroInfo.h:296
void setHasCommaPasting()
Definition MacroInfo.h:220
void setDefinitionEndLoc(SourceLocation EndLoc)
Set the location of the last token in the macro.
Definition MacroInfo.h:128
void setParameterList(ArrayRef< IdentifierInfo * > List, llvm::BumpPtrAllocator &PPAllocator)
Set the specified list of identifiers as the parameter list for this macro.
Definition MacroInfo.h:166
llvm::MutableArrayRef< Token > allocateTokens(unsigned NumTokens, llvm::BumpPtrAllocator &PPAllocator)
Definition MacroInfo.h:254
void setIsFunctionLike()
Function/Object-likeness.
Definition MacroInfo.h:200
void setIsGNUVarargs()
Definition MacroInfo.h:206
void setIsC99Varargs()
Varargs querying methods. This can only be set for function-like macros.
Definition MacroInfo.h:205
void setIsUsed(bool Val)
Set the value of the IsUsed flag.
Definition MacroInfo.h:154
void setExpansionLoc(SourceLocation Loc)
Definition TypeLoc.h:1383
void setAttrRowOperand(Expr *e)
Definition TypeLoc.h:2131
void setAttrColumnOperand(Expr *e)
Definition TypeLoc.h:2137
void setAttrOperandParensRange(SourceRange range)
Definition TypeLoc.h:2146
void setAttrNameLoc(SourceLocation loc)
Definition TypeLoc.h:2125
void setStarLoc(SourceLocation Loc)
Definition TypeLoc.h:1550
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition TypeLoc.h:1559
The module cache used for compiling modules implicitly.
Definition ModuleCache.h:25
virtual InMemoryModuleCache & getInMemoryModuleCache()=0
Returns this process's view of the module cache.
Deduplication key for a loaded module file in ModuleManager.
Definition Module.h:69
Identifies a module file to be loaded.
Definition Module.h:102
bool empty() const
Checks whether the module file name is empty.
Definition Module.h:150
static ModuleFileName makeImplicit(std::string Name, unsigned SuffixLength)
Creates a file name for an implicit module.
Definition Module.h:123
static ModuleFileName makeExplicit(std::string Name)
Creates a file name for an explicit module.
Definition Module.h:111
StringRef str() const
Returns the plain module file name.
Definition Module.h:144
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.
OptionalFileEntryRef findUmbrellaHeaderForModule(Module *M, std::string NameAsWritten, SmallVectorImpl< char > &RelativePathName)
Find the FileEntry for an umbrella header in a module as if it was written in the module map as a hea...
void setInferredModuleAllowedBy(Module *M, FileID ModMapFID)
void 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:555
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:246
StringRef getTopLevelModuleName() const
Retrieve the name of the top-level module.
Definition Module.h:835
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:332
unsigned InferSubmodules
Whether we should infer submodules for this module based on the headers.
Definition Module.h:509
std::vector< std::string > ConfigMacros
The set of "configuration macros", which are macros that (intentionally) change how this module is bu...
Definition Module.h:631
unsigned IsUnimportable
Whether this module has declared itself unimportable, either because it's missing a requirement from ...
Definition Module.h:464
NameVisibilityKind NameVisibility
The visibility of names within this particular module.
Definition Module.h:554
NameVisibilityKind
Describes the visibility of the various names within a particular module.
Definition Module.h:546
@ Hidden
All of the names in this module are hidden.
Definition Module.h:548
@ AllVisible
All of the names in this module are visible.
Definition Module.h:550
const ModuleFileKey * getASTFileKey() const
The serialized AST file key for this module, if one was created.
Definition Module.h:846
SourceLocation DefinitionLoc
The location of the module definition.
Definition Module.h:252
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:444
ModuleKind Kind
The kind of this module.
Definition Module.h:291
void addTopHeaderFilename(StringRef Filename)
Add a top-level header filename associated with this module.
Definition Module.h:886
bool isUnimportable() const
Determine whether this module has been declared unimportable.
Definition Module.h:666
void setASTFileNameAndKey(ModuleFileName NewName, ModuleFileKey NewKey)
Set the serialized module file for the top-level module of this module.
Definition Module.h:852
unsigned IsSystem
Whether this is a "system" module (which assumes that all headers in it are system headers).
Definition Module.h:492
std::string Name
The name of this module.
Definition Module.h:249
const ModuleFileName * getASTFileName() const
The serialized AST file name for this module, if one was created.
Definition Module.h:840
unsigned IsExternC
Whether this is an 'extern "C"' module (which implicitly puts all headers in it within an 'extern "C"...
Definition Module.h:498
unsigned ModuleMapIsPrivate
Whether this module came from a "private" module map, found next to a regular (public) module map.
Definition Module.h:537
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:623
SmallVector< UnresolvedExportDecl, 2 > UnresolvedExports
The set of export declarations that have yet to be resolved.
Definition Module.h:592
std::optional< Header > getUmbrellaHeaderAsWritten() const
Retrieve the umbrella header as written.
Definition Module.h:870
SmallVector< Requirement, 2 > Requirements
The set of language features required to use this module.
Definition Module.h:455
bool isHeaderLikeModule() const
Is this module have similar semantics as headers.
Definition Module.h:751
OptionalDirectoryEntryRef Directory
The build directory of this module.
Definition Module.h:300
unsigned NamedModuleHasInit
Whether this C++20 named modules doesn't need an initializer.
Definition Module.h:542
StringRef getPrimaryModuleInterfaceName() const
Get the primary module interface name from a partition.
Definition Module.h:790
unsigned ConfigMacrosExhaustive
Whether the set of configuration macros is exhaustive.
Definition Module.h:527
std::string PresumedModuleMapFile
The presumed file name for the module map defining this module.
Definition Module.h:304
ASTFileSignature Signature
The module signature.
Definition Module.h:310
bool isGlobalModule() const
Does this Module scope describe a fragment of the global module within some C++ module.
Definition Module.h:341
unsigned InferExportWildcard
Whether, when inferring submodules, the inferr submodules should export all modules they import (e....
Definition Module.h:519
void getExportedModules(SmallVectorImpl< Module * > &Exported) const
Appends this module's list of exported modules to Exported.
Definition Module.cpp:402
std::vector< UnresolvedConflict > UnresolvedConflicts
The list of conflicts for which the module-id has not yet been resolved.
Definition Module.h:644
unsigned IsFromModuleFile
Whether this module was loaded from a module file.
Definition Module.h:479
llvm::PointerIntPair< Module *, 1, bool > ExportDecl
Describes an exported module.
Definition Module.h:571
std::optional< DirectoryName > getUmbrellaDirAsWritten() const
Retrieve the umbrella directory as written.
Definition Module.h:862
std::string ExportAsModule
The module through which entities defined in this module will eventually be exposed,...
Definition Module.h:320
unsigned IsAvailable
Whether this module is available in the current translation unit.
Definition Module.h:475
unsigned InferExplicitSubmodules
Whether, when inferring submodules, the inferred submodules should be explicit.
Definition Module.h:514
std::vector< Conflict > Conflicts
The list of conflicts.
Definition Module.h:656
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:1846
Represent a C++ namespace.
Definition Decl.h:592
Class that aids in the construction of nested-name-specifiers along with source-location information ...
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
A C++ nested-name-specifier augmented with source location information.
@ MicrosoftSuper
Microsoft's '__super' specifier, stored as a CXXRecordDecl* of the class it appeared in.
@ Global
The global specifier '::'. There is no stored value.
@ Namespace
A namespace-like entity, stored as a NamespaceBaseDecl*.
static std::string getOwningModuleNameForDiagnostic(const Decl *D)
Get the best name we know for the module that owns the given declaration, or an empty string if the d...
This represents the 'align' clause in the 'pragma omp allocate' directive.
This represents clause 'allocate' in the 'pragma omp ...' directives.
static OMPAllocateClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with the place for N variables.
This represents 'allocator' clause in the 'pragma omp ...' directive.
void VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C)
OMPClauseReader(ASTRecordReader &Record)
void VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C)
Class that handles post-update expression for some clauses, like 'lastprivate', 'reduction' etc.
Class that handles pre-initialization statement for some clauses, like 'schedule',...
This is a basic class for representing single OpenMP clause.
This represents 'collapse' clause in the 'pragma omp ...' directive.
This represents 'default' clause in the 'pragma omp ...' directive.
This represents 'final' clause in the 'pragma omp ...' directive.
Representation of the 'full' clause of the 'pragma omp unroll' directive.
static OMPFullClause * CreateEmpty(const ASTContext &C)
Build an empty 'full' AST node for deserialization.
This represents 'if' clause in the 'pragma omp ...' directive.
This class represents the 'looprange' clause in the 'pragma omp fuse' directive.
static OMPLoopRangeClause * CreateEmpty(const ASTContext &C)
Build an empty 'looprange' clause node.
This represents 'num_threads' clause in the 'pragma omp ...' directive.
Representation of the 'partial' clause of the 'pragma omp unroll' directive.
static OMPPartialClause * CreateEmpty(const ASTContext &C)
Build an empty 'partial' AST node for deserialization.
This class represents the 'permutation' clause in the 'pragma omp interchange' directive.
static OMPPermutationClause * CreateEmpty(const ASTContext &C, unsigned NumLoops)
Build an empty 'permutation' AST node for deserialization.
This represents 'safelen' clause in the 'pragma omp ...' directive.
This represents 'simdlen' clause in the 'pragma omp ...' directive.
This represents the 'sizes' clause in the 'pragma omp tile' directive.
static OMPSizesClause * CreateEmpty(const ASTContext &C, unsigned NumSizes)
Build an empty 'sizes' AST node for deserialization.
This represents 'threadset' clause in the 'pragma omp task ...' directive.
method_range methods() const
Definition DeclObjC.h:1016
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:1313
void setNameEndLoc(SourceLocation Loc)
Definition TypeLoc.h:1325
ObjCMethodDecl - Represents an instance or class method declaration.
Definition DeclObjC.h:140
bool hasBody() const override
Determine whether this method has a body.
Definition DeclObjC.h:523
void setLazyBody(uint64_t Offset)
Definition DeclObjC.h:528
void setStarLoc(SourceLocation Loc)
Definition TypeLoc.h:1592
void setTypeArgsRAngleLoc(SourceLocation Loc)
Definition TypeLoc.h:1196
unsigned getNumTypeArgs() const
Definition TypeLoc.h:1200
unsigned getNumProtocols() const
Definition TypeLoc.h:1230
void setTypeArgsLAngleLoc(SourceLocation Loc)
Definition TypeLoc.h:1188
void setTypeArgTInfo(unsigned i, TypeSourceInfo *TInfo)
Definition TypeLoc.h:1209
void setProtocolLAngleLoc(SourceLocation Loc)
Definition TypeLoc.h:1218
void setProtocolRAngleLoc(SourceLocation Loc)
Definition TypeLoc.h:1226
void setHasBaseTypeAsWritten(bool HasBaseType)
Definition TypeLoc.h:1258
void setProtocolLoc(unsigned i, SourceLocation Loc)
Definition TypeLoc.h:1239
Kind
The basic Objective-C runtimes that we know about.
Definition ObjCRuntime.h:31
unsigned getNumProtocols() const
Definition TypeLoc.h:932
void setProtocolLoc(unsigned i, SourceLocation Loc)
Definition TypeLoc.h:941
void setProtocolLAngleLoc(SourceLocation Loc)
Definition TypeLoc.h:918
void setProtocolRAngleLoc(SourceLocation Loc)
Definition TypeLoc.h:928
static OpenACCAsyncClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, Expr *IntExpr, SourceLocation EndLoc)
static OpenACCAttachClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCAutoClause * Create(const ASTContext &Ctx, SourceLocation BeginLoc, SourceLocation EndLoc)
static OpenACCBindClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, const IdentifierInfo *ID, SourceLocation EndLoc)
This is the base type for all OpenACC Clauses.
static OpenACCCollapseClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, bool HasForce, Expr *LoopCount, SourceLocation EndLoc)
static OpenACCCopyClause * Create(const ASTContext &C, OpenACCClauseKind Spelling, SourceLocation BeginLoc, SourceLocation LParenLoc, OpenACCModifierKind Mods, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCCopyInClause * Create(const ASTContext &C, OpenACCClauseKind Spelling, SourceLocation BeginLoc, SourceLocation LParenLoc, OpenACCModifierKind Mods, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCCopyOutClause * Create(const ASTContext &C, OpenACCClauseKind Spelling, SourceLocation BeginLoc, SourceLocation LParenLoc, OpenACCModifierKind Mods, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCCreateClause * Create(const ASTContext &C, OpenACCClauseKind Spelling, SourceLocation BeginLoc, SourceLocation LParenLoc, OpenACCModifierKind Mods, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCDefaultAsyncClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, Expr *IntExpr, SourceLocation EndLoc)
static OpenACCDefaultClause * Create(const ASTContext &C, OpenACCDefaultClauseKind K, SourceLocation BeginLoc, SourceLocation LParenLoc, SourceLocation EndLoc)
static OpenACCDeleteClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCDetachClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCDeviceClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCDeviceNumClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, Expr *IntExpr, SourceLocation EndLoc)
static OpenACCDevicePtrClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCDeviceResidentClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCDeviceTypeClause * Create(const ASTContext &C, OpenACCClauseKind K, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< DeviceTypeArgument > Archs, SourceLocation EndLoc)
static OpenACCFinalizeClause * Create(const ASTContext &Ctx, SourceLocation BeginLoc, SourceLocation EndLoc)
static OpenACCFirstPrivateClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, ArrayRef< OpenACCFirstPrivateRecipe > InitRecipes, SourceLocation EndLoc)
static OpenACCGangClause * Create(const ASTContext &Ctx, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< OpenACCGangKind > GangKinds, ArrayRef< Expr * > IntExprs, SourceLocation EndLoc)
static OpenACCHostClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCIfClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, Expr *ConditionExpr, SourceLocation EndLoc)
static OpenACCIfPresentClause * Create(const ASTContext &Ctx, SourceLocation BeginLoc, SourceLocation EndLoc)
static OpenACCIndependentClause * Create(const ASTContext &Ctx, SourceLocation BeginLoc, SourceLocation EndLoc)
static OpenACCLinkClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCNoCreateClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCNoHostClause * Create(const ASTContext &Ctx, SourceLocation BeginLoc, SourceLocation EndLoc)
static OpenACCNumGangsClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > IntExprs, SourceLocation EndLoc)
static OpenACCNumWorkersClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, Expr *IntExpr, SourceLocation EndLoc)
static OpenACCPresentClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCPrivateClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, ArrayRef< OpenACCPrivateRecipe > InitRecipes, SourceLocation EndLoc)
static OpenACCReductionClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, OpenACCReductionOperator Operator, ArrayRef< Expr * > VarList, ArrayRef< OpenACCReductionRecipeWithStorage > Recipes, SourceLocation EndLoc)
static OpenACCSelfClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, Expr *ConditionExpr, SourceLocation EndLoc)
static OpenACCSeqClause * Create(const ASTContext &Ctx, SourceLocation BeginLoc, SourceLocation EndLoc)
static OpenACCTileClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > SizeExprs, SourceLocation EndLoc)
static OpenACCUseDeviceClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCVectorClause * Create(const ASTContext &Ctx, SourceLocation BeginLoc, SourceLocation LParenLoc, Expr *IntExpr, SourceLocation EndLoc)
static OpenACCVectorLengthClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, Expr *IntExpr, SourceLocation EndLoc)
static OpenACCWaitClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, Expr *DevNumExpr, SourceLocation QueuesLoc, ArrayRef< Expr * > QueueIdExprs, SourceLocation EndLoc)
static OpenACCWorkerClause * Create(const ASTContext &Ctx, SourceLocation BeginLoc, SourceLocation LParenLoc, Expr *IntExpr, SourceLocation EndLoc)
void setAttrLoc(SourceLocation loc)
Definition TypeLoc.h:1099
This abstract interface provides operations for unwrapping containers for serialized ASTs (precompile...
bool ReadDiagnosticOptions(DiagnosticOptions &DiagOpts, StringRef ModuleFilename, bool Complain) override
Receives the diagnostic options.
bool ReadLanguageOptions(const LangOptions &LangOpts, StringRef ModuleFilename, bool Complain, bool AllowCompatibleDifferences) override
Receives the language options.
void ReadCounter(const serialization::ModuleFile &M, uint32_t Value) override
Receives COUNTER value.
bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, StringRef ModuleFilename, bool ReadMacros, bool Complain, std::string &SuggestedPredefines) override
Receives the preprocessor options.
bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, StringRef ModuleFilename, StringRef ContextHash, bool Complain) override
Receives the header search options.
bool ReadCodeGenOptions(const CodeGenOptions &CGOpts, StringRef ModuleFilename, bool Complain, bool AllowCompatibleDifferences) override
Receives the codegen options.
bool ReadTargetOptions(const TargetOptions &TargetOpts, StringRef ModuleFilename, bool Complain, bool AllowCompatibleDifferences) override
Receives the target options.
void setEllipsisLoc(SourceLocation Loc)
Definition TypeLoc.h:2633
void setEllipsisLoc(SourceLocation Loc)
Definition TypeLoc.h:2316
void setRParenLoc(SourceLocation Loc)
Definition TypeLoc.h:1415
void setLParenLoc(SourceLocation Loc)
Definition TypeLoc.h:1411
Represents a parameter to a function.
Definition Decl.h:1805
void setKWLoc(SourceLocation Loc)
Definition TypeLoc.h:2725
void setStarLoc(SourceLocation Loc)
Definition TypeLoc.h:1519
Base class that describes a preprocessed entity, which may be a preprocessor directive or macro expan...
A record of the steps taken while preprocessing a source file, including the various preprocessing di...
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
std::vector< std::string > MacroIncludes
std::vector< std::string > Includes
ObjCXXARCStandardLibraryKind ObjCXXARCStandardLibrary
The Objective-C++ ARC standard library that we should support, by providing appropriate definitions t...
std::string PCHThroughHeader
If non-empty, the filename used in an include directive in the primary source file (or command-line p...
bool DetailedRecord
Whether we should maintain a detailed record of all macro definitions and expansions.
std::string ImplicitPCHInclude
The implicit PCH included at the start of the translation unit, or empty.
bool AllowPCHWithDifferentModulesCachePath
When true, a PCH with modules cache path different to the current compilation will not be rejected.
bool UsePredefines
Initialize the preprocessor with the compiler and target specific predefines.
std::vector< std::pair< std::string, bool > > Macros
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Module * getCurrentModule()
Retrieves the module that we're currently building, if any.
HeaderSearch & getHeaderSearchInfo() const
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
@ FastWidth
The width of the "fast" qualifier mask.
Definition TypeBase.h:376
@ FastMask
The fast qualifier mask.
Definition TypeBase.h:379
void setAmpAmpLoc(SourceLocation Loc)
Definition TypeLoc.h:1628
Wrapper for source info for record types.
Definition TypeLoc.h:855
Declaration of a redeclarable template.
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
void setPreviousDecl(decl_type *PrevDecl)
Set the previous declaration.
Definition Decl.h:5347
This table allows us to fully hide how we implement multi-keyword caching.
Selector getNullarySelector(const IdentifierInfo *ID)
Selector getSelector(unsigned NumArgs, const IdentifierInfo **IIV)
Can create any sort of selector.
Selector getUnarySelector(const IdentifierInfo *ID)
Smart pointer class that efficiently represents Objective-C method names.
void * getAsOpaquePtr() const
void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method)
Add the given method to the list of globally-known methods.
GlobalMethodPool MethodPool
Method Pool - allows efficient lookup when typechecking messages to "id".
Definition SemaObjC.h:220
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:868
SemaObjC & ObjC()
Definition Sema.h:1514
void addExternalSource(IntrusiveRefCntPtr< ExternalSemaSource > E)
Registers an external source.
Definition Sema.cpp:656
IdentifierResolver IdResolver
Definition Sema.h:3515
PragmaMsStackAction
Definition Sema.h:1845
ASTReaderListenter implementation to set SuggestedPredefines of ASTReader which is required to use a ...
Definition ASTReader.h:359
bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, StringRef ModuleFilename, bool ReadMacros, bool Complain, std::string &SuggestedPredefines) override
Receives the preprocessor options.
Encodes a location in the source.
static SourceLocation getFromRawEncoding(UIntTy Encoding)
Turn a raw encoding of a SourceLocation object into a real SourceLocation.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
This class handles loading and caching of source files into memory.
SourceLocation getFileLoc(SourceLocation Loc) const
Given Loc, if it is a macro location return the expansion location or the spelling location,...
bool isBeforeInTranslationUnit(SourceLocation LHS, SourceLocation RHS) const
Determines the order of 2 source locations in the translation unit.
A trivial tuple used to represent a source range.
One instance of this struct is kept for every file loaded or used.
OptionalFileEntryRef ContentsEntry
References the file which the contents were actually loaded from.
std::optional< llvm::MemoryBufferRef > getBufferIfLoaded() const
Return the buffer, only if it has been loaded.
unsigned BufferOverridden
Indicates whether the buffer itself was provided to override the actual file contents.
OptionalFileEntryRef OrigEntry
Reference to the file entry representing this ContentCache.
Information about a FileID, basically just the logical file that it represents and include stack info...
void setHasLineDirectives()
Set the flag that indicates that this FileID has line table entries associated with it.
Stmt - This represents one statement.
Definition Stmt.h:86
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition TypeLoc.h:816
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:824
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:805
Options for controlling the target.
std::string Triple
The name of the target triple to compile for.
std::vector< std::string > Features
The list of target specific features to enable or disable – this should be a list of strings starting...
std::string ABI
If given, the name of the target ABI to use.
std::string TuneCPU
If given, the name of the target CPU to tune code for.
std::string CPU
If given, the name of the target CPU to generate code for.
std::vector< std::string > FeaturesAsWritten
The list of target specific features to enable or disable, as written on the command line.
A convenient class for passing around template argument information.
Location wrapper for a TemplateArgument.
Represents a template argument.
Expr * getAsExpr() const
Retrieve the template argument as an expression.
ArgKind
The kind of template argument we're storing.
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
@ Template
The template argument is a template name that was provided for a template template parameter.
@ StructuralValue
The template argument is a non-type template argument that can't be represented by the special-case D...
@ Pack
The template argument is actually a parameter pack.
@ TemplateExpansion
The template argument is a pack expansion of a template name that was provided for a template templat...
@ NullPtr
The template argument is a null pointer or null pointer to member that was provided for a non-type te...
@ Type
The template argument is a type.
@ Null
Represents an empty template argument, e.g., one that has not been deduced.
@ Integral
The template argument is an integral value stored in an llvm::APSInt that was provided for an integra...
@ Expression
The template argument is an expression, and we've not resolved it to one of the other forms yet,...
ArgKind getKind() const
Return the kind of stored template argument.
Stores a list of template parameters for a TemplateDecl and its derived classes.
static TemplateParameterList * Create(const ASTContext &C, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > Params, SourceLocation RAngleLoc, Expr *RequiresClause)
MutableArrayRef< TemplateArgumentLocInfo > getArgLocInfos()
Definition TypeLoc.h:1913
void set(SourceLocation ElaboratedKeywordLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKeywordLoc, SourceLocation NameLoc, SourceLocation LAngleLoc, SourceLocation RAngleLoc)
Definition TypeLoc.cpp:648
Token - This structure provides full information about a lexed token.
Definition Token.h:36
[BoundsSafety] Represents information of declarations referenced by the arguments of the counted_by a...
Definition TypeBase.h:3406
TypeLocReader(ASTRecordReader &Reader)
void VisitArrayTypeLoc(ArrayTypeLoc)
void VisitFunctionTypeLoc(FunctionTypeLoc)
void VisitTagTypeLoc(TagTypeLoc TL)
RetTy Visit(TypeLoc TyLoc)
Base wrapper for a particular "section" of type source info.
Definition TypeLoc.h:59
TypeLoc getNextTypeLoc() const
Get the next TypeLoc pointed by this TypeLoc, e.g for "int*" the TypeLoc is a PointerLoc and next Typ...
Definition TypeLoc.h:171
bool isNull() const
Definition TypeLoc.h:121
void setUnmodifiedTInfo(TypeSourceInfo *TI) const
Definition TypeLoc.h:2265
A container of type source information.
Definition TypeBase.h:8402
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:1866
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9261
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3577
void setLParenLoc(SourceLocation Loc)
Definition TypeLoc.h:2208
void setTypeofLoc(SourceLocation Loc)
Definition TypeLoc.h:2200
void setRParenLoc(SourceLocation Loc)
Definition TypeLoc.h:2216
void setRParenLoc(SourceLocation Loc)
Definition TypeLoc.h:2350
void setKWLoc(SourceLocation Loc)
Definition TypeLoc.h:2344
void setUnderlyingTInfo(TypeSourceInfo *TInfo)
Definition TypeLoc.h:2356
void setLParenLoc(SourceLocation Loc)
Definition TypeLoc.h:2347
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
Represents a variable declaration or definition.
Definition Decl.h:926
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2045
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:145
const PPEntityOffset * PreprocessedEntityOffsets
Definition ModuleFile.h:401
void * IdentifierLookupTable
A pointer to an on-disk hash table of opaque type IdentifierHashTable.
Definition ModuleFile.h:356
void * SelectorLookupTable
A pointer to an on-disk hash table of opaque type ASTSelectorLookupTable.
Definition ModuleFile.h:464
std::vector< std::unique_ptr< ModuleFileExtensionReader > > ExtensionReaders
The list of extension readers that are attached to this module file.
Definition ModuleFile.h:267
SourceLocation DirectImportLoc
The source location where the module was explicitly or implicitly imported in the local translation u...
Definition ModuleFile.h:257
StringRef Data
The serialized bitstream data for this file.
Definition ModuleFile.h:243
const serialization::ObjCCategoriesInfo * ObjCCategoriesMap
Array of category list location information within this module file, sorted by the definition ID.
Definition ModuleFile.h:492
int SLocEntryBaseID
The base ID in the source manager's view of this module.
Definition ModuleFile.h:320
ModuleFileKey FileKey
The key ModuleManager used for the module file.
Definition ModuleFile.h:163
serialization::IdentifierID BaseIdentifierID
Base identifier ID for identifiers local to this module.
Definition ModuleFile.h:346
serialization::PreprocessedEntityID BasePreprocessedEntityID
Base preprocessed entity ID for preprocessed entities local to this module.
Definition ModuleFile.h:399
serialization::TypeID BaseTypeIndex
Base type ID for types local to this module as represented in the global type ID space.
Definition ModuleFile.h:512
unsigned LocalNumObjCCategoriesInMap
The number of redeclaration info entries in ObjCCategoriesMap.
Definition ModuleFile.h:495
uint64_t MacroOffsetsBase
Base file offset for the offsets in MacroOffsets.
Definition ModuleFile.h:373
const llvm::support::unaligned_uint64_t * InputFileOffsets
Relative offsets for all of the input file entries in the AST file.
Definition ModuleFile.h:282
std::vector< unsigned > PreloadIdentifierOffsets
Offsets of identifiers that we're going to preload within IdentifierTableData.
Definition ModuleFile.h:360
unsigned LocalNumIdentifiers
The number of identifiers in this AST file.
Definition ModuleFile.h:336
llvm::BitstreamCursor DeclsCursor
DeclsCursor - This is a cursor to the start of the DECLTYPES_BLOCK block.
Definition ModuleFile.h:471
const unsigned char * IdentifierTableData
Actual data for the on-disk hash table of identifiers.
Definition ModuleFile.h:352
uint64_t SLocEntryOffsetsBase
Base file offset for the offsets in SLocEntryOffsets.
Definition ModuleFile.h:327
llvm::BitstreamCursor InputFilesCursor
The cursor to the start of the input-files block.
Definition ModuleFile.h:276
std::vector< InputFile > InputFilesLoaded
The input files that have been loaded from this AST file.
Definition ModuleFile.h:285
serialization::SelectorID BaseSelectorID
Base selector ID for selectors local to this module.
Definition ModuleFile.h:449
llvm::SetVector< ModuleFile * > ImportedBy
List of modules which depend on this module.
Definition ModuleFile.h:520
const char * HeaderFileInfoTableData
Actual data for the on-disk hash table of header file information.
Definition ModuleFile.h:420
SourceLocation ImportLoc
The source location where this module was first imported.
Definition ModuleFile.h:260
const serialization::unaligned_decl_id_t * FileSortedDecls
Array of file-level DeclIDs sorted by file.
Definition ModuleFile.h:487
const uint32_t * SLocEntryOffsets
Offsets for all of the source location entries in the AST file.
Definition ModuleFile.h:331
llvm::BitstreamCursor MacroCursor
The cursor to the start of the preprocessor block, which stores all of the macro definitions.
Definition ModuleFile.h:366
FileID OriginalSourceFileID
The file ID for the original source file that was used to build this AST file.
Definition ModuleFile.h:186
time_t ModTime
Modification of the module file.
Definition ModuleFile.h:206
std::string ActualOriginalSourceFileName
The actual original source file name that was used to build this AST file.
Definition ModuleFile.h:182
uint64_t PreprocessorDetailStartOffset
The offset of the start of the preprocessor detail cursor.
Definition ModuleFile.h:395
std::vector< InputFileInfo > InputFileInfosLoaded
The input file infos that have been loaded from this AST file.
Definition ModuleFile.h:288
unsigned LocalNumSubmodules
The number of submodules in this module.
Definition ModuleFile.h:429
SourceLocation FirstLoc
The first source location in this module.
Definition ModuleFile.h:263
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:214
uint64_t SourceManagerBlockStartOffset
The bit offset to the start of the SOURCE_MANAGER_BLOCK.
Definition ModuleFile.h:314
bool DidReadTopLevelSubmodule
Whether the top-level module has been read from the AST file.
Definition ModuleFile.h:200
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:178
bool isModule() const
Is this a module file for a module (rather than a PCH or similar).
Definition ModuleFile.h:538
bool HasTimestamps
Whether timestamps are included in this module file.
Definition ModuleFile.h:197
uint64_t InputFilesOffsetBase
Absolute offset of the start of the input-files block.
Definition ModuleFile.h:279
llvm::BitstreamCursor SLocEntryCursor
Cursor used to read source location entries.
Definition ModuleFile.h:311
bool RelocatablePCH
Whether this precompiled header is a relocatable PCH file.
Definition ModuleFile.h:191
const uint32_t * SelectorOffsets
Offsets into the selector lookup table's data array where each selector resides.
Definition ModuleFile.h:446
unsigned BaseDeclIndex
Base declaration index in ASTReader for declarations local to this module.
Definition ModuleFile.h:484
unsigned LocalNumSLocEntries
The number of source location entries in this AST file.
Definition ModuleFile.h:317
void * HeaderFileInfoTable
The on-disk hash table that contains information about each of the header files.
Definition ModuleFile.h:424
unsigned Index
The index of this module in the list of modules.
Definition ModuleFile.h:154
llvm::BitstreamCursor Stream
The main bitstream cursor for the main block.
Definition ModuleFile.h:246
serialization::SubmoduleID BaseSubmoduleID
Base submodule ID for submodules local to this module.
Definition ModuleFile.h:432
uint64_t SizeInBits
The size of this file, in bits.
Definition ModuleFile.h:234
const UnalignedUInt64 * TypeOffsets
Offset of each type within the bitstream, indexed by the type ID, or the representation of a Type*.
Definition ModuleFile.h:508
uint64_t GlobalBitOffset
The global bit offset (or base) of this module.
Definition ModuleFile.h:237
bool StandardCXXModule
Whether this module file is a standard C++ module.
Definition ModuleFile.h:194
unsigned LocalNumTypes
The number of types in this AST file.
Definition ModuleFile.h:504
StringRef ModuleOffsetMap
The module offset map data for this file.
Definition ModuleFile.h:271
const PPSkippedRange * PreprocessedSkippedRangeOffsets
Definition ModuleFile.h:407
uint64_t InputFilesValidationTimestamp
If non-zero, specifies the time when we last validated input files.
Definition ModuleFile.h:298
llvm::BitstreamCursor PreprocessorDetailCursor
The cursor to the start of the (optional) detailed preprocessing record block.
Definition ModuleFile.h:392
SourceLocation::UIntTy SLocEntryBaseOffset
The base offset in the source manager's view of this module.
Definition ModuleFile.h:323
const DeclOffset * DeclOffsets
Offset of each declaration within the bitstream, indexed by the declaration ID (-1).
Definition ModuleFile.h:481
uint64_t MacroStartOffset
The offset of the start of the set of defined macros.
Definition ModuleFile.h:386
ASTFileSignature Signature
The signature of the module file, which may be used instead of the size and modification time to iden...
Definition ModuleFile.h:210
unsigned LocalNumMacros
The number of macros in this AST file.
Definition ModuleFile.h:369
const unsigned char * SelectorLookupTableData
A pointer to the character data that comprises the selector table.
Definition ModuleFile.h:457
void dump()
Dump debugging output for this module.
unsigned LocalNumDecls
The number of declarations in this AST file.
Definition ModuleFile.h:477
unsigned LocalNumHeaderFileInfos
The number of local HeaderFileInfo structures.
Definition ModuleFile.h:413
llvm::BitVector SearchPathUsage
The bit vector denoting usage of each header search entry (true = used).
Definition ModuleFile.h:217
InputFilesValidation InputFilesValidationStatus
Captures the high-level result of validating input files.
Definition ModuleFile.h:305
unsigned Generation
The generation of which this module file is a part.
Definition ModuleFile.h:227
const uint32_t * IdentifierOffsets
Offsets into the identifier table data.
Definition ModuleFile.h:343
ContinuousRangeMap< uint32_t, int, 2 > SelectorRemap
Remapping table for selector IDs in this module.
Definition ModuleFile.h:452
const uint32_t * MacroOffsets
Offsets of macros in the preprocessor block.
Definition ModuleFile.h:380
uint64_t ASTBlockStartOffset
The bit offset of the AST block of this module.
Definition ModuleFile.h:240
ModuleFileName FileName
The file name of the module file.
Definition ModuleFile.h:160
ContinuousRangeMap< uint32_t, int, 2 > SubmoduleRemap
Remapping table for submodule IDs in this module.
Definition ModuleFile.h:435
llvm::BitVector VFSUsage
The bit vector denoting usage of each VFS entry (true = used).
Definition ModuleFile.h:220
uint64_t DeclsBlockStartOffset
The offset to the start of the DECLTYPES_BLOCK block.
Definition ModuleFile.h:474
SmallVector< uint64_t, 8 > PragmaDiagMappings
Diagnostic IDs and their mappings that the user changed.
Definition ModuleFile.h:517
unsigned BasePreprocessedSkippedRangeID
Base ID for preprocessed skipped ranges local to this module.
Definition ModuleFile.h:405
unsigned LocalNumSelectors
The number of selectors new to this file.
Definition ModuleFile.h:442
ModuleKind Kind
The type of this module.
Definition ModuleFile.h:157
std::string ModuleName
The name of the module.
Definition ModuleFile.h:166
serialization::MacroID BaseMacroID
Base macro ID for macros local to this module.
Definition ModuleFile.h:383
SmallVector< uint64_t, 1 > ObjCCategories
The Objective-C category lists for categories known to this module.
Definition ModuleFile.h:499
std::string BaseDirectory
The base directory of the module.
Definition ModuleFile.h:169
llvm::SmallVector< ModuleFile *, 16 > TransitiveImports
List of modules which this modules dependent on.
Definition ModuleFile.h:531
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)
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.
@ SkippedInBuildSession
When the validation is skipped because it was already done in the current build session.
Definition ModuleFile.h:131
@ AllFiles
When the validation is done both for user files and system files.
Definition ModuleFile.h:135
@ Disabled
When the validation is disabled. For example, for a precompiled header.
Definition ModuleFile.h:128
@ UserFiles
When the validation is done only for user files as an optimization.
Definition ModuleFile.h:133
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:3949
@ 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.
std::string createSpecificModuleCachePath(FileManager &FileMgr, StringRef ModuleCachePath, bool DisableModuleHash, std::string ContextHash)
OpenMPLastprivateModifier
OpenMP 'lastprivate' clause modifier.
@ Template
We are parsing a template declaration.
Definition Parser.h:81
OpenMPDependClauseKind
OpenMP attributes for 'depend' clause.
Definition OpenMPKinds.h:55
OpenMPGrainsizeClauseModifier
OpenMPNumTasksClauseModifier
OpenMPUseDevicePtrFallbackModifier
OpenMP 6.1 use_device_ptr fallback modifier.
OpenMPSeverityClauseKind
OpenMP attributes for 'severity' clause.
void ProcessWarningOptions(DiagnosticsEngine &Diags, const DiagnosticOptions &Opts, llvm::vfs::FileSystem &VFS, bool ReportDiags=true)
ProcessWarningOptions - Initialize the diagnostic client and process the warning options specified on...
Definition Warnings.cpp:46
static constexpr unsigned NumberOfOMPMotionModifiers
Number of allowed motion-modifiers.
TypeSpecifierWidth
Specifies the width of a type, e.g., short, long, or long long.
Definition Specifiers.h: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:2728
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:179
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:5970
llvm::omp::Clause OpenMPClauseKind
OpenMP clauses.
Definition OpenMPKinds.h:28
OpenMPOrderClauseKind
OpenMP attributes for 'order' clause.
OpenMPScheduleClauseKind
OpenMP attributes for 'schedule' clause.
Definition OpenMPKinds.h:31
OpenMPThreadsetKind
OpenMP modifiers for 'threadset' clause.
UnsignedOrNone getPrimaryModuleHash(const Module *M)
Calculate a hash value for the primary module name of the given module.
OpenMPMapClauseKind
OpenMP mapping kind for 'map' clause.
Definition OpenMPKinds.h:71
unsigned long uint64_t
unsigned int uint32_t
#define true
Definition stdbool.h:25
__LIBC_ATTRS FILE * stderr
This structure contains all sizes needed for by an OMPMappableExprListClause.
unsigned NumComponents
Total number of expression components.
unsigned NumUniqueDeclarations
Number of unique base declarations.
unsigned NumVars
Number of expressions listed.
unsigned NumComponentLists
Number of component lists.
Expr * AllocatorTraits
Allocator traits.
SourceLocation LParenLoc
Locations of '(' and ')' symbols.
The signature of a module, which is a hash of the AST content.
Definition Module.h:160
static constexpr size_t size
Definition Module.h:163
static ASTFileSignature create(std::array< uint8_t, 20 > Bytes)
Definition Module.h:183
static ASTFileSignature createDummy()
Definition Module.h:193
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:647
Module * Other
The module that this module conflicts with.
Definition Module.h:649
std::string Message
The message provided to the user when there is a conflict.
Definition Module.h:652
Information about a header directive as found in the module map file.
Definition Module.h:390
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:1856
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.
MultiOnDiskHashTable< LazySpecializationInfoLookupTrait > Table
#define log(__x)
Definition tgmath.h:460