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 SpecificModuleCachePath, bool Complain) {
212 return First->ReadHeaderSearchOptions(HSOpts, ModuleFilename,
213 SpecificModuleCachePath, Complain) ||
214 Second->ReadHeaderSearchOptions(HSOpts, ModuleFilename,
215 SpecificModuleCachePath, Complain);
216}
217
219 const PreprocessorOptions &PPOpts, StringRef ModuleFilename,
220 bool ReadMacros, bool Complain, std::string &SuggestedPredefines) {
221 return First->ReadPreprocessorOptions(PPOpts, ModuleFilename, ReadMacros,
222 Complain, SuggestedPredefines) ||
223 Second->ReadPreprocessorOptions(PPOpts, ModuleFilename, ReadMacros,
224 Complain, SuggestedPredefines);
225}
226
228 uint32_t Value) {
229 First->ReadCounter(M, Value);
230 Second->ReadCounter(M, Value);
231}
232
234 return First->needsInputFileVisitation() ||
235 Second->needsInputFileVisitation();
236}
237
239 return First->needsSystemInputFileVisitation() ||
240 Second->needsSystemInputFileVisitation();
241}
242
244 ModuleKind Kind) {
245 First->visitModuleFile(Filename, Kind);
246 Second->visitModuleFile(Filename, Kind);
247}
248
250 bool isSystem,
251 bool isOverridden,
252 bool isExplicitModule) {
253 bool Continue = false;
254 if (First->needsInputFileVisitation() &&
255 (!isSystem || First->needsSystemInputFileVisitation()))
256 Continue |= First->visitInputFile(Filename, isSystem, isOverridden,
257 isExplicitModule);
258 if (Second->needsInputFileVisitation() &&
259 (!isSystem || Second->needsSystemInputFileVisitation()))
260 Continue |= Second->visitInputFile(Filename, isSystem, isOverridden,
261 isExplicitModule);
262 return Continue;
263}
264
266 const ModuleFileExtensionMetadata &Metadata) {
267 First->readModuleFileExtension(Metadata);
268 Second->readModuleFileExtension(Metadata);
269}
270
271//===----------------------------------------------------------------------===//
272// PCH validator implementation
273//===----------------------------------------------------------------------===//
274
276
277/// Compare the given set of language options against an existing set of
278/// language options.
279///
280/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
281/// \param AllowCompatibleDifferences If true, differences between compatible
282/// language options will be permitted.
283///
284/// \returns true if the languagae options mis-match, false otherwise.
285static bool checkLanguageOptions(const LangOptions &LangOpts,
286 const LangOptions &ExistingLangOpts,
287 StringRef ModuleFilename,
288 DiagnosticsEngine *Diags,
289 bool AllowCompatibleDifferences = true) {
290 // FIXME: Replace with C++20 `using enum LangOptions::CompatibilityKind`.
292
293#define LANGOPT(Name, Bits, Default, Compatibility, Description) \
294 if constexpr (CK::Compatibility != CK::Benign) { \
295 if ((CK::Compatibility == CK::NotCompatible) || \
296 (CK::Compatibility == CK::Compatible && \
297 !AllowCompatibleDifferences)) { \
298 if (ExistingLangOpts.Name != LangOpts.Name) { \
299 if (Diags) { \
300 if (Bits == 1) \
301 Diags->Report(diag::err_ast_file_langopt_mismatch) \
302 << Description << LangOpts.Name << ExistingLangOpts.Name \
303 << ModuleFilename; \
304 else \
305 Diags->Report(diag::err_ast_file_langopt_value_mismatch) \
306 << Description << ModuleFilename; \
307 } \
308 return true; \
309 } \
310 } \
311 }
312
313#define VALUE_LANGOPT(Name, Bits, Default, Compatibility, Description) \
314 if constexpr (CK::Compatibility != CK::Benign) { \
315 if ((CK::Compatibility == CK::NotCompatible) || \
316 (CK::Compatibility == CK::Compatible && \
317 !AllowCompatibleDifferences)) { \
318 if (ExistingLangOpts.Name != LangOpts.Name) { \
319 if (Diags) \
320 Diags->Report(diag::err_ast_file_langopt_value_mismatch) \
321 << Description << ModuleFilename; \
322 return true; \
323 } \
324 } \
325 }
326
327#define ENUM_LANGOPT(Name, Type, Bits, Default, Compatibility, Description) \
328 if constexpr (CK::Compatibility != CK::Benign) { \
329 if ((CK::Compatibility == CK::NotCompatible) || \
330 (CK::Compatibility == CK::Compatible && \
331 !AllowCompatibleDifferences)) { \
332 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
333 if (Diags) \
334 Diags->Report(diag::err_ast_file_langopt_value_mismatch) \
335 << Description << ModuleFilename; \
336 return true; \
337 } \
338 } \
339 }
340
341#include "clang/Basic/LangOptions.def"
342
343 if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) {
344 if (Diags)
345 Diags->Report(diag::err_ast_file_langopt_value_mismatch)
346 << "module features" << ModuleFilename;
347 return true;
348 }
349
350 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
351 if (Diags)
352 Diags->Report(diag::err_ast_file_langopt_value_mismatch)
353 << "target Objective-C runtime" << ModuleFilename;
354 return true;
355 }
356
357 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
359 if (Diags)
360 Diags->Report(diag::err_ast_file_langopt_value_mismatch)
361 << "block command names" << ModuleFilename;
362 return true;
363 }
364
365 // Sanitizer feature mismatches are treated as compatible differences. If
366 // compatible differences aren't allowed, we still only want to check for
367 // mismatches of non-modular sanitizers (the only ones which can affect AST
368 // generation).
369 if (!AllowCompatibleDifferences) {
370 SanitizerMask ModularSanitizers = getPPTransparentSanitizers();
371 SanitizerSet ExistingSanitizers = ExistingLangOpts.Sanitize;
372 SanitizerSet ImportedSanitizers = LangOpts.Sanitize;
373 ExistingSanitizers.clear(ModularSanitizers);
374 ImportedSanitizers.clear(ModularSanitizers);
375 if (ExistingSanitizers.Mask != ImportedSanitizers.Mask) {
376 const std::string Flag = "-fsanitize=";
377 if (Diags) {
378#define SANITIZER(NAME, ID) \
379 { \
380 bool InExistingModule = ExistingSanitizers.has(SanitizerKind::ID); \
381 bool InImportedModule = ImportedSanitizers.has(SanitizerKind::ID); \
382 if (InExistingModule != InImportedModule) \
383 Diags->Report(diag::err_ast_file_targetopt_feature_mismatch) \
384 << InExistingModule << ModuleFilename << (Flag + NAME); \
385 }
386#include "clang/Basic/Sanitizers.def"
387 }
388 return true;
389 }
390 }
391
392 return false;
393}
394
395static bool checkCodegenOptions(const CodeGenOptions &CGOpts,
396 const CodeGenOptions &ExistingCGOpts,
397 StringRef ModuleFilename,
398 DiagnosticsEngine *Diags,
399 bool AllowCompatibleDifferences = true) {
400 // FIXME: Specify and print a description for each option instead of the name.
401 // FIXME: Replace with C++20 `using enum CodeGenOptions::CompatibilityKind`.
403#define CODEGENOPT(Name, Bits, Default, Compatibility) \
404 if constexpr (CK::Compatibility != CK::Benign) { \
405 if ((CK::Compatibility == CK::NotCompatible) || \
406 (CK::Compatibility == CK::Compatible && \
407 !AllowCompatibleDifferences)) { \
408 if (ExistingCGOpts.Name != CGOpts.Name) { \
409 if (Diags) { \
410 if (Bits == 1) \
411 Diags->Report(diag::err_ast_file_codegenopt_mismatch) \
412 << #Name << CGOpts.Name << ExistingCGOpts.Name \
413 << ModuleFilename; \
414 else \
415 Diags->Report(diag::err_ast_file_codegenopt_value_mismatch) \
416 << #Name << ModuleFilename; \
417 } \
418 return true; \
419 } \
420 } \
421 }
422
423#define VALUE_CODEGENOPT(Name, Bits, Default, Compatibility) \
424 if constexpr (CK::Compatibility != CK::Benign) { \
425 if ((CK::Compatibility == CK::NotCompatible) || \
426 (CK::Compatibility == CK::Compatible && \
427 !AllowCompatibleDifferences)) { \
428 if (ExistingCGOpts.Name != CGOpts.Name) { \
429 if (Diags) \
430 Diags->Report(diag::err_ast_file_codegenopt_value_mismatch) \
431 << #Name << ModuleFilename; \
432 return true; \
433 } \
434 } \
435 }
436#define ENUM_CODEGENOPT(Name, Type, Bits, Default, Compatibility) \
437 if constexpr (CK::Compatibility != CK::Benign) { \
438 if ((CK::Compatibility == CK::NotCompatible) || \
439 (CK::Compatibility == CK::Compatible && \
440 !AllowCompatibleDifferences)) { \
441 if (ExistingCGOpts.get##Name() != CGOpts.get##Name()) { \
442 if (Diags) \
443 Diags->Report(diag::err_ast_file_codegenopt_value_mismatch) \
444 << #Name << ModuleFilename; \
445 return true; \
446 } \
447 } \
448 }
449#define DEBUGOPT(Name, Bits, Default, Compatibility)
450#define VALUE_DEBUGOPT(Name, Bits, Default, Compatibility)
451#define ENUM_DEBUGOPT(Name, Type, Bits, Default, Compatibility)
452#include "clang/Basic/CodeGenOptions.def"
453
454 return false;
455}
456
457/// Compare the given set of target options against an existing set of
458/// target options.
459///
460/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
461///
462/// \returns true if the target options mis-match, false otherwise.
463static bool checkTargetOptions(const TargetOptions &TargetOpts,
464 const TargetOptions &ExistingTargetOpts,
465 StringRef ModuleFilename,
466 DiagnosticsEngine *Diags,
467 bool AllowCompatibleDifferences = true) {
468#define CHECK_TARGET_OPT(Field, Name) \
469 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
470 if (Diags) \
471 Diags->Report(diag::err_ast_file_targetopt_mismatch) \
472 << ModuleFilename << Name << TargetOpts.Field \
473 << ExistingTargetOpts.Field; \
474 return true; \
475 }
476
477 // The triple and ABI must match exactly.
478 CHECK_TARGET_OPT(Triple, "target");
479 CHECK_TARGET_OPT(ABI, "target ABI");
480
481 // We can tolerate different CPUs in many cases, notably when one CPU
482 // supports a strict superset of another. When allowing compatible
483 // differences skip this check.
484 if (!AllowCompatibleDifferences) {
485 CHECK_TARGET_OPT(CPU, "target CPU");
486 CHECK_TARGET_OPT(TuneCPU, "tune CPU");
487 }
488
489#undef CHECK_TARGET_OPT
490
491 // Compare feature sets.
492 SmallVector<StringRef, 4> ExistingFeatures(
493 ExistingTargetOpts.FeaturesAsWritten.begin(),
494 ExistingTargetOpts.FeaturesAsWritten.end());
495 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
496 TargetOpts.FeaturesAsWritten.end());
497 llvm::sort(ExistingFeatures);
498 llvm::sort(ReadFeatures);
499
500 // We compute the set difference in both directions explicitly so that we can
501 // diagnose the differences differently.
502 SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
503 std::set_difference(
504 ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
505 ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
506 std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
507 ExistingFeatures.begin(), ExistingFeatures.end(),
508 std::back_inserter(UnmatchedReadFeatures));
509
510 // If we are allowing compatible differences and the read feature set is
511 // a strict subset of the existing feature set, there is nothing to diagnose.
512 if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
513 return false;
514
515 if (Diags) {
516 for (StringRef Feature : UnmatchedReadFeatures)
517 Diags->Report(diag::err_ast_file_targetopt_feature_mismatch)
518 << /* is-existing-feature */ false << ModuleFilename << Feature;
519 for (StringRef Feature : UnmatchedExistingFeatures)
520 Diags->Report(diag::err_ast_file_targetopt_feature_mismatch)
521 << /* is-existing-feature */ true << ModuleFilename << Feature;
522 }
523
524 return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
525}
526
528 StringRef ModuleFilename, bool Complain,
529 bool AllowCompatibleDifferences) {
530 const LangOptions &ExistingLangOpts = PP.getLangOpts();
531 return checkLanguageOptions(LangOpts, ExistingLangOpts, ModuleFilename,
532 Complain ? &Reader.Diags : nullptr,
533 AllowCompatibleDifferences);
534}
535
537 StringRef ModuleFilename, bool Complain,
538 bool AllowCompatibleDifferences) {
539 const CodeGenOptions &ExistingCGOpts = Reader.getCodeGenOpts();
540 return checkCodegenOptions(ExistingCGOpts, CGOpts, ModuleFilename,
541 Complain ? &Reader.Diags : nullptr,
542 AllowCompatibleDifferences);
543}
544
546 StringRef ModuleFilename, bool Complain,
547 bool AllowCompatibleDifferences) {
548 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
549 return checkTargetOptions(TargetOpts, ExistingTargetOpts, ModuleFilename,
550 Complain ? &Reader.Diags : nullptr,
551 AllowCompatibleDifferences);
552}
553
554namespace {
555
556using MacroDefinitionsMap =
557 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>;
558
559class DeclsSet {
562
563public:
564 operator ArrayRef<NamedDecl *>() const { return Decls; }
565
566 bool empty() const { return Decls.empty(); }
567
568 bool insert(NamedDecl *ND) {
569 auto [_, Inserted] = Found.insert(ND);
570 if (Inserted)
571 Decls.push_back(ND);
572 return Inserted;
573 }
574};
575
576using DeclsMap = llvm::DenseMap<DeclarationName, DeclsSet>;
577
578} // namespace
579
581 DiagnosticsEngine &Diags,
582 StringRef ModuleFilename,
583 bool Complain) {
584 using Level = DiagnosticsEngine::Level;
585
586 // Check current mappings for new -Werror mappings, and the stored mappings
587 // for cases that were explicitly mapped to *not* be errors that are now
588 // errors because of options like -Werror.
589 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
590
591 for (DiagnosticsEngine *MappingSource : MappingSources) {
592 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
593 diag::kind DiagID = DiagIDMappingPair.first;
594 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
595 if (CurLevel < DiagnosticsEngine::Error)
596 continue; // not significant
597 Level StoredLevel =
598 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
599 if (StoredLevel < DiagnosticsEngine::Error) {
600 if (Complain)
601 Diags.Report(diag::err_ast_file_diagopt_mismatch)
602 << "-Werror=" + Diags.getDiagnosticIDs()
603 ->getWarningOptionForDiag(DiagID)
604 .str()
605 << ModuleFilename;
606 return true;
607 }
608 }
609 }
610
611 return false;
612}
613
616 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
617 return true;
618 return Ext >= diag::Severity::Error;
619}
620
622 DiagnosticsEngine &Diags,
623 StringRef ModuleFilename, bool IsSystem,
624 bool SystemHeaderWarningsInModule,
625 bool Complain) {
626 // Top-level options
627 if (IsSystem) {
628 if (Diags.getSuppressSystemWarnings())
629 return false;
630 // If -Wsystem-headers was not enabled before, and it was not explicit,
631 // be conservative
632 if (StoredDiags.getSuppressSystemWarnings() &&
633 !SystemHeaderWarningsInModule) {
634 if (Complain)
635 Diags.Report(diag::err_ast_file_diagopt_mismatch)
636 << "-Wsystem-headers" << ModuleFilename;
637 return true;
638 }
639 }
640
641 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
642 if (Complain)
643 Diags.Report(diag::err_ast_file_diagopt_mismatch)
644 << "-Werror" << ModuleFilename;
645 return true;
646 }
647
648 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
649 !StoredDiags.getEnableAllWarnings()) {
650 if (Complain)
651 Diags.Report(diag::err_ast_file_diagopt_mismatch)
652 << "-Weverything -Werror" << ModuleFilename;
653 return true;
654 }
655
656 if (isExtHandlingFromDiagsError(Diags) &&
657 !isExtHandlingFromDiagsError(StoredDiags)) {
658 if (Complain)
659 Diags.Report(diag::err_ast_file_diagopt_mismatch)
660 << "-pedantic-errors" << ModuleFilename;
661 return true;
662 }
663
664 return checkDiagnosticGroupMappings(StoredDiags, Diags, ModuleFilename,
665 Complain);
666}
667
668/// Return the top import module if it is implicit, nullptr otherwise.
670 Preprocessor &PP) {
671 // If the original import came from a file explicitly generated by the user,
672 // don't check the diagnostic mappings.
673 // FIXME: currently this is approximated by checking whether this is not a
674 // module import of an implicitly-loaded module file.
675 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
676 // the transitive closure of its imports, since unrelated modules cannot be
677 // imported until after this module finishes validation.
678 ModuleFile *TopImport = &*ModuleMgr.rbegin();
679 while (!TopImport->ImportedBy.empty())
680 TopImport = TopImport->ImportedBy[0];
681 if (TopImport->Kind != MK_ImplicitModule)
682 return nullptr;
683
684 StringRef ModuleName = TopImport->ModuleName;
685 assert(!ModuleName.empty() && "diagnostic options read before module name");
686
687 Module *M =
688 PP.getHeaderSearchInfo().lookupModule(ModuleName, TopImport->ImportLoc);
689 assert(M && "missing module");
690 return M;
691}
692
694 StringRef ModuleFilename,
695 bool Complain) {
696 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
698 auto Diags = llvm::makeIntrusiveRefCnt<DiagnosticsEngine>(DiagIDs, DiagOpts);
699 // This should never fail, because we would have processed these options
700 // before writing them to an ASTFile.
701 ProcessWarningOptions(*Diags, DiagOpts,
702 PP.getFileManager().getVirtualFileSystem(),
703 /*Report*/ false);
704
705 ModuleManager &ModuleMgr = Reader.getModuleManager();
706 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
707
708 Module *TopM = getTopImportImplicitModule(ModuleMgr, PP);
709 if (!TopM)
710 return false;
711
712 Module *Importer = PP.getCurrentModule();
713
714 DiagnosticOptions &ExistingOpts = ExistingDiags.getDiagnosticOptions();
715 bool SystemHeaderWarningsInModule =
716 Importer && llvm::is_contained(ExistingOpts.SystemHeaderWarningsModules,
717 Importer->Name);
718
719 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
720 // contains the union of their flags.
721 return checkDiagnosticMappings(*Diags, ExistingDiags, ModuleFilename,
722 TopM->IsSystem, SystemHeaderWarningsInModule,
723 Complain);
724}
725
726/// Collect the macro definitions provided by the given preprocessor
727/// options.
728static void
730 MacroDefinitionsMap &Macros,
731 SmallVectorImpl<StringRef> *MacroNames = nullptr) {
732 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
733 StringRef Macro = PPOpts.Macros[I].first;
734 bool IsUndef = PPOpts.Macros[I].second;
735
736 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
737 StringRef MacroName = MacroPair.first;
738 StringRef MacroBody = MacroPair.second;
739
740 // For an #undef'd macro, we only care about the name.
741 if (IsUndef) {
742 auto [It, Inserted] = Macros.try_emplace(MacroName);
743 if (MacroNames && Inserted)
744 MacroNames->push_back(MacroName);
745
746 It->second = std::make_pair("", true);
747 continue;
748 }
749
750 // For a #define'd macro, figure out the actual definition.
751 if (MacroName.size() == Macro.size())
752 MacroBody = "1";
753 else {
754 // Note: GCC drops anything following an end-of-line character.
755 StringRef::size_type End = MacroBody.find_first_of("\n\r");
756 MacroBody = MacroBody.substr(0, End);
757 }
758
759 auto [It, Inserted] = Macros.try_emplace(MacroName);
760 if (MacroNames && Inserted)
761 MacroNames->push_back(MacroName);
762 It->second = std::make_pair(MacroBody, false);
763 }
764}
765
771
772/// Check the preprocessor options deserialized from the control block
773/// against the preprocessor options in an existing preprocessor.
774///
775/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
776/// \param Validation If set to OptionValidateNone, ignore differences in
777/// preprocessor options. If set to OptionValidateContradictions,
778/// require that options passed both in the AST file and on the command
779/// line (-D or -U) match, but tolerate options missing in one or the
780/// other. If set to OptionValidateContradictions, require that there
781/// are no differences in the options between the two.
783 const PreprocessorOptions &PPOpts,
784 const PreprocessorOptions &ExistingPPOpts, StringRef ModuleFilename,
785 bool ReadMacros, DiagnosticsEngine *Diags, FileManager &FileMgr,
786 std::string &SuggestedPredefines, const LangOptions &LangOpts,
788 if (ReadMacros) {
789 // Check macro definitions.
790 MacroDefinitionsMap ASTFileMacros;
791 collectMacroDefinitions(PPOpts, ASTFileMacros);
792 MacroDefinitionsMap ExistingMacros;
793 SmallVector<StringRef, 4> ExistingMacroNames;
794 collectMacroDefinitions(ExistingPPOpts, ExistingMacros,
795 &ExistingMacroNames);
796
797 // Use a line marker to enter the <command line> file, as the defines and
798 // undefines here will have come from the command line.
799 SuggestedPredefines += "# 1 \"<command line>\" 1\n";
800
801 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
802 // Dig out the macro definition in the existing preprocessor options.
803 StringRef MacroName = ExistingMacroNames[I];
804 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
805
806 // Check whether we know anything about this macro name or not.
807 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>::iterator Known =
808 ASTFileMacros.find(MacroName);
809 if (Validation == OptionValidateNone || Known == ASTFileMacros.end()) {
810 if (Validation == OptionValidateStrictMatches) {
811 // If strict matches are requested, don't tolerate any extra defines
812 // on the command line that are missing in the AST file.
813 if (Diags) {
814 Diags->Report(diag::err_ast_file_macro_def_undef)
815 << MacroName << true << ModuleFilename;
816 }
817 return true;
818 }
819 // FIXME: Check whether this identifier was referenced anywhere in the
820 // AST file. If so, we should reject the AST file. Unfortunately, this
821 // information isn't in the control block. What shall we do about it?
822
823 if (Existing.second) {
824 SuggestedPredefines += "#undef ";
825 SuggestedPredefines += MacroName.str();
826 SuggestedPredefines += '\n';
827 } else {
828 SuggestedPredefines += "#define ";
829 SuggestedPredefines += MacroName.str();
830 SuggestedPredefines += ' ';
831 SuggestedPredefines += Existing.first.str();
832 SuggestedPredefines += '\n';
833 }
834 continue;
835 }
836
837 // If the macro was defined in one but undef'd in the other, we have a
838 // conflict.
839 if (Existing.second != Known->second.second) {
840 if (Diags) {
841 Diags->Report(diag::err_ast_file_macro_def_undef)
842 << MacroName << Known->second.second << ModuleFilename;
843 }
844 return true;
845 }
846
847 // If the macro was #undef'd in both, or if the macro bodies are
848 // identical, it's fine.
849 if (Existing.second || Existing.first == Known->second.first) {
850 ASTFileMacros.erase(Known);
851 continue;
852 }
853
854 // The macro bodies differ; complain.
855 if (Diags) {
856 Diags->Report(diag::err_ast_file_macro_def_conflict)
857 << MacroName << Known->second.first << Existing.first
858 << ModuleFilename;
859 }
860 return true;
861 }
862
863 // Leave the <command line> file and return to <built-in>.
864 SuggestedPredefines += "# 1 \"<built-in>\" 2\n";
865
866 if (Validation == OptionValidateStrictMatches) {
867 // If strict matches are requested, don't tolerate any extra defines in
868 // the AST file that are missing on the command line.
869 for (const auto &MacroName : ASTFileMacros.keys()) {
870 if (Diags) {
871 Diags->Report(diag::err_ast_file_macro_def_undef)
872 << MacroName << false << ModuleFilename;
873 }
874 return true;
875 }
876 }
877 }
878
879 // Check whether we're using predefines.
880 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines &&
881 Validation != OptionValidateNone) {
882 if (Diags) {
883 Diags->Report(diag::err_ast_file_undef)
884 << ExistingPPOpts.UsePredefines << ModuleFilename;
885 }
886 return true;
887 }
888
889 // Detailed record is important since it is used for the module cache hash.
890 if (LangOpts.Modules &&
891 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord &&
892 Validation != OptionValidateNone) {
893 if (Diags) {
894 Diags->Report(diag::err_ast_file_pp_detailed_record)
895 << PPOpts.DetailedRecord << ModuleFilename;
896 }
897 return true;
898 }
899
900 // Compute the #include and #include_macros lines we need.
901 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
902 StringRef File = ExistingPPOpts.Includes[I];
903
904 if (!ExistingPPOpts.ImplicitPCHInclude.empty() &&
905 !ExistingPPOpts.PCHThroughHeader.empty()) {
906 // In case the through header is an include, we must add all the includes
907 // to the predefines so the start point can be determined.
908 SuggestedPredefines += "#include \"";
909 SuggestedPredefines += File;
910 SuggestedPredefines += "\"\n";
911 continue;
912 }
913
914 if (File == ExistingPPOpts.ImplicitPCHInclude)
915 continue;
916
917 if (llvm::is_contained(PPOpts.Includes, File))
918 continue;
919
920 SuggestedPredefines += "#include \"";
921 SuggestedPredefines += File;
922 SuggestedPredefines += "\"\n";
923 }
924
925 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
926 StringRef File = ExistingPPOpts.MacroIncludes[I];
927 if (llvm::is_contained(PPOpts.MacroIncludes, File))
928 continue;
929
930 SuggestedPredefines += "#__include_macros \"";
931 SuggestedPredefines += File;
932 SuggestedPredefines += "\"\n##\n";
933 }
934
935 return false;
936}
937
939 StringRef ModuleFilename,
940 bool ReadMacros, bool Complain,
941 std::string &SuggestedPredefines) {
942 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
943
945 PPOpts, ExistingPPOpts, ModuleFilename, ReadMacros,
946 Complain ? &Reader.Diags : nullptr, PP.getFileManager(),
947 SuggestedPredefines, PP.getLangOpts());
948}
949
951 const PreprocessorOptions &PPOpts, StringRef ModuleFilename,
952 bool ReadMacros, bool Complain, std::string &SuggestedPredefines) {
953 return checkPreprocessorOptions(PPOpts, PP.getPreprocessorOpts(),
954 ModuleFilename, ReadMacros, nullptr,
955 PP.getFileManager(), SuggestedPredefines,
956 PP.getLangOpts(), OptionValidateNone);
957}
958
959/// Check that the specified and the existing module cache paths are equivalent.
960///
961/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
962/// \returns true when the module cache paths differ.
964 llvm::vfs::FileSystem &VFS, StringRef SpecificModuleCachePath,
965 StringRef ExistingSpecificModuleCachePath, StringRef ASTFilename,
966 DiagnosticsEngine *Diags, const LangOptions &LangOpts,
967 const PreprocessorOptions &PPOpts, const HeaderSearchOptions &HSOpts,
968 const HeaderSearchOptions &ASTFileHSOpts) {
969 if (!LangOpts.Modules || PPOpts.AllowPCHWithDifferentModulesCachePath ||
970 SpecificModuleCachePath == ExistingSpecificModuleCachePath)
971 return false;
972 auto EqualOrErr =
973 VFS.equivalent(SpecificModuleCachePath, ExistingSpecificModuleCachePath);
974 if (EqualOrErr && *EqualOrErr)
975 return false;
976 if (Diags) {
977 // If the module cache arguments provided from the command line are the
978 // same, the mismatch must come from other arguments of the configuration
979 // and not directly the cache path.
980 EqualOrErr =
981 VFS.equivalent(ASTFileHSOpts.ModuleCachePath, HSOpts.ModuleCachePath);
982 if (EqualOrErr && *EqualOrErr)
983 Diags->Report(clang::diag::warn_ast_file_config_mismatch) << ASTFilename;
984 else
985 Diags->Report(diag::err_ast_file_modulecache_mismatch)
986 << SpecificModuleCachePath << ExistingSpecificModuleCachePath
987 << ASTFilename;
988 }
989 return true;
990}
991
993 StringRef ASTFilename,
994 StringRef SpecificModuleCachePath,
995 bool Complain) {
996 const HeaderSearch &HeaderSearchInfo = PP.getHeaderSearchInfo();
998 Reader.getFileManager().getVirtualFileSystem(), SpecificModuleCachePath,
999 HeaderSearchInfo.getSpecificModuleCachePath(), ASTFilename,
1000 Complain ? &Reader.Diags : nullptr, PP.getLangOpts(),
1001 PP.getPreprocessorOpts(), HeaderSearchInfo.getHeaderSearchOpts(), HSOpts);
1002}
1003
1005 PP.setCounterValue(Value);
1006}
1007
1008//===----------------------------------------------------------------------===//
1009// AST reader implementation
1010//===----------------------------------------------------------------------===//
1011
1012static uint64_t readULEB(const unsigned char *&P) {
1013 unsigned Length = 0;
1014 const char *Error = nullptr;
1015
1016 uint64_t Val = llvm::decodeULEB128(P, &Length, nullptr, &Error);
1017 if (Error)
1018 llvm::report_fatal_error(Error);
1019 P += Length;
1020 return Val;
1021}
1022
1023/// Read ULEB-encoded key length and data length.
1024static std::pair<unsigned, unsigned>
1025readULEBKeyDataLength(const unsigned char *&P) {
1026 unsigned KeyLen = readULEB(P);
1027 if ((unsigned)KeyLen != KeyLen)
1028 llvm::report_fatal_error("key too large");
1029
1030 unsigned DataLen = readULEB(P);
1031 if ((unsigned)DataLen != DataLen)
1032 llvm::report_fatal_error("data too large");
1033
1034 return std::make_pair(KeyLen, DataLen);
1035}
1036
1038 bool TakeOwnership) {
1039 DeserializationListener = Listener;
1040 OwnsDeserializationListener = TakeOwnership;
1041}
1042
1046
1048 LocalDeclID ID(Value);
1049#ifndef NDEBUG
1050 if (!MF.ModuleOffsetMap.empty())
1051 Reader.ReadModuleOffsetMap(MF);
1052
1053 unsigned ModuleFileIndex = ID.getModuleFileIndex();
1054 unsigned LocalDeclID = ID.getLocalDeclIndex();
1055
1056 assert(ModuleFileIndex <= MF.TransitiveImports.size());
1057
1058 ModuleFile *OwningModuleFile =
1059 ModuleFileIndex == 0 ? &MF : MF.TransitiveImports[ModuleFileIndex - 1];
1060 assert(OwningModuleFile);
1061
1062 unsigned LocalNumDecls = OwningModuleFile->LocalNumDecls;
1063
1064 if (!ModuleFileIndex)
1065 LocalNumDecls += NUM_PREDEF_DECL_IDS;
1066
1067 assert(LocalDeclID < LocalNumDecls);
1068#endif
1069 (void)Reader;
1070 (void)MF;
1071 return ID;
1072}
1073
1074LocalDeclID LocalDeclID::get(ASTReader &Reader, ModuleFile &MF,
1075 unsigned ModuleFileIndex, unsigned LocalDeclID) {
1076 DeclID Value = (DeclID)ModuleFileIndex << 32 | (DeclID)LocalDeclID;
1077 return LocalDeclID::get(Reader, MF, Value);
1078}
1079
1080std::pair<unsigned, unsigned>
1082 return readULEBKeyDataLength(d);
1083}
1084
1086ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
1087 using namespace llvm::support;
1088
1089 SelectorTable &SelTable = Reader.getContext().Selectors;
1090 unsigned N = endian::readNext<uint16_t, llvm::endianness::little>(d);
1091 const IdentifierInfo *FirstII = Reader.getLocalIdentifier(
1092 F, endian::readNext<IdentifierID, llvm::endianness::little>(d));
1093 if (N == 0)
1094 return SelTable.getNullarySelector(FirstII);
1095 else if (N == 1)
1096 return SelTable.getUnarySelector(FirstII);
1097
1099 Args.push_back(FirstII);
1100 for (unsigned I = 1; I != N; ++I)
1101 Args.push_back(Reader.getLocalIdentifier(
1102 F, endian::readNext<IdentifierID, llvm::endianness::little>(d)));
1103
1104 return SelTable.getSelector(N, Args.data());
1105}
1106
1109 unsigned DataLen) {
1110 using namespace llvm::support;
1111
1113
1114 Result.ID = Reader.getGlobalSelectorID(
1115 F, endian::readNext<uint32_t, llvm::endianness::little>(d));
1116 unsigned FullInstanceBits =
1117 endian::readNext<uint16_t, llvm::endianness::little>(d);
1118 unsigned FullFactoryBits =
1119 endian::readNext<uint16_t, llvm::endianness::little>(d);
1120 Result.InstanceBits = FullInstanceBits & 0x3;
1121 Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
1122 Result.FactoryBits = FullFactoryBits & 0x3;
1123 Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
1124 unsigned NumInstanceMethods = FullInstanceBits >> 3;
1125 unsigned NumFactoryMethods = FullFactoryBits >> 3;
1126
1127 // Load instance methods
1128 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
1129 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
1131 Reader, F,
1132 endian::readNext<DeclID, llvm::endianness::little>(d))))
1133 Result.Instance.push_back(Method);
1134 }
1135
1136 // Load factory methods
1137 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
1138 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
1140 Reader, F,
1141 endian::readNext<DeclID, llvm::endianness::little>(d))))
1142 Result.Factory.push_back(Method);
1143 }
1144
1145 return Result;
1146}
1147
1149 return llvm::djbHash(a);
1150}
1151
1152std::pair<unsigned, unsigned>
1154 return readULEBKeyDataLength(d);
1155}
1156
1158ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
1159 assert(n >= 2 && d[n-1] == '\0');
1160 return StringRef((const char*) d, n-1);
1161}
1162
1163/// Whether the given identifier is "interesting".
1164static bool isInterestingIdentifier(ASTReader &Reader, const IdentifierInfo &II,
1165 bool IsModule) {
1166 bool IsInteresting =
1167 II.getNotableIdentifierID() != tok::NotableIdentifierKind::not_notable ||
1169 II.getObjCKeywordID() != tok::ObjCKeywordKind::objc_not_keyword;
1170 return II.hadMacroDefinition() || II.isPoisoned() ||
1171 (!IsModule && IsInteresting) || II.hasRevertedTokenIDToIdentifier() ||
1172 (!(IsModule && Reader.getPreprocessor().getLangOpts().CPlusPlus) &&
1173 II.getFETokenInfo());
1174}
1175
1176static bool readBit(unsigned &Bits) {
1177 bool Value = Bits & 0x1;
1178 Bits >>= 1;
1179 return Value;
1180}
1181
1183 using namespace llvm::support;
1184
1185 IdentifierID RawID =
1186 endian::readNext<IdentifierID, llvm::endianness::little>(d);
1187 return Reader.getGlobalIdentifierID(F, RawID >> 1);
1188}
1189
1191 bool IsModule) {
1192 if (!II.isFromAST()) {
1193 II.setIsFromAST();
1194 if (isInterestingIdentifier(Reader, II, IsModule))
1196 }
1197}
1198
1200 const unsigned char* d,
1201 unsigned DataLen) {
1202 using namespace llvm::support;
1203
1204 IdentifierID RawID =
1205 endian::readNext<IdentifierID, llvm::endianness::little>(d);
1206 bool IsInteresting = RawID & 0x01;
1207
1208 DataLen -= sizeof(IdentifierID);
1209
1210 // Wipe out the "is interesting" bit.
1211 RawID = RawID >> 1;
1212
1213 // Build the IdentifierInfo and link the identifier ID with it.
1214 IdentifierInfo *II = KnownII;
1215 if (!II) {
1216 II = &Reader.getIdentifierTable().getOwn(k);
1217 KnownII = II;
1218 }
1219 bool IsModule = Reader.getPreprocessor().getCurrentModule() != nullptr;
1220 markIdentifierFromAST(Reader, *II, IsModule);
1221 Reader.markIdentifierUpToDate(II);
1222
1223 IdentifierID ID = Reader.getGlobalIdentifierID(F, RawID);
1224 if (!IsInteresting) {
1225 // For uninteresting identifiers, there's nothing else to do. Just notify
1226 // the reader that we've finished loading this identifier.
1227 Reader.SetIdentifierInfo(ID, II);
1228 return II;
1229 }
1230
1231 unsigned ObjCOrBuiltinID =
1232 endian::readNext<uint16_t, llvm::endianness::little>(d);
1233 unsigned Bits = endian::readNext<uint16_t, llvm::endianness::little>(d);
1234 bool CPlusPlusOperatorKeyword = readBit(Bits);
1235 bool HasRevertedTokenIDToIdentifier = readBit(Bits);
1236 bool Poisoned = readBit(Bits);
1237 bool ExtensionToken = readBit(Bits);
1238 bool HasMacroDefinition = readBit(Bits);
1239
1240 assert(Bits == 0 && "Extra bits in the identifier?");
1241 DataLen -= sizeof(uint16_t) * 2;
1242
1243 // Set or check the various bits in the IdentifierInfo structure.
1244 // Token IDs are read-only.
1245 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
1247 if (!F.isModule())
1248 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
1249 assert(II->isExtensionToken() == ExtensionToken &&
1250 "Incorrect extension token flag");
1251 (void)ExtensionToken;
1252 if (Poisoned)
1253 II->setIsPoisoned(true);
1254 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
1255 "Incorrect C++ operator keyword flag");
1256 (void)CPlusPlusOperatorKeyword;
1257
1258 // If this identifier has a macro definition, deserialize it or notify the
1259 // visitor the actual definition is in a different module.
1260 if (HasMacroDefinition) {
1261 uint32_t MacroDirectivesOffset =
1262 endian::readNext<uint32_t, llvm::endianness::little>(d);
1263 DataLen -= 4;
1264
1265 if (MacroDirectivesOffset)
1266 Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
1267 else
1268 hasMacroDefinitionInDependencies = true;
1269 }
1270
1271 Reader.SetIdentifierInfo(ID, II);
1272
1273 // Read all of the declarations visible at global scope with this
1274 // name.
1275 if (DataLen > 0) {
1277 for (; DataLen > 0; DataLen -= sizeof(DeclID))
1278 DeclIDs.push_back(Reader.getGlobalDeclID(
1280 Reader, F,
1281 endian::readNext<DeclID, llvm::endianness::little>(d))));
1282 Reader.SetGloballyVisibleDecls(II, DeclIDs);
1283 }
1284
1285 return II;
1286}
1287
1289 : Kind(Name.getNameKind()) {
1290 switch (Kind) {
1292 Data = (uint64_t)Name.getAsIdentifierInfo();
1293 break;
1297 Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
1298 break;
1300 Data = Name.getCXXOverloadedOperator();
1301 break;
1303 Data = (uint64_t)Name.getCXXLiteralIdentifier();
1304 break;
1306 Data = (uint64_t)Name.getCXXDeductionGuideTemplate()
1308 break;
1313 Data = 0;
1314 break;
1315 }
1316}
1317
1319 llvm::FoldingSetNodeID ID;
1320 ID.AddInteger(Kind);
1321
1322 switch (Kind) {
1326 ID.AddString(((IdentifierInfo*)Data)->getName());
1327 break;
1331 ID.AddInteger(serialization::ComputeHash(Selector(Data)));
1332 break;
1334 ID.AddInteger((OverloadedOperatorKind)Data);
1335 break;
1340 break;
1341 }
1342
1343 return ID.computeStableHash();
1344}
1345
1346ModuleFile *
1348 using namespace llvm::support;
1349
1350 uint32_t ModuleFileID =
1351 endian::readNext<uint32_t, llvm::endianness::little>(d);
1352 return Reader.getLocalModuleFile(F, ModuleFileID);
1353}
1354
1355std::pair<unsigned, unsigned>
1359
1362 using namespace llvm::support;
1363
1364 auto Kind = (DeclarationName::NameKind)*d++;
1365 uint64_t Data;
1366 switch (Kind) {
1370 Data = (uint64_t)Reader.getLocalIdentifier(
1371 F, endian::readNext<IdentifierID, llvm::endianness::little>(d));
1372 break;
1376 Data = (uint64_t)Reader
1377 .getLocalSelector(
1378 F, endian::readNext<uint32_t, llvm::endianness::little>(d))
1379 .getAsOpaquePtr();
1380 break;
1382 Data = *d++; // OverloadedOperatorKind
1383 break;
1388 Data = 0;
1389 break;
1390 }
1391
1392 return DeclarationNameKey(Kind, Data);
1393}
1394
1396ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
1397 return ReadKeyBase(d);
1398}
1399
1401 const unsigned char *d, unsigned DataLen, data_type_builder &Val) {
1402 using namespace llvm::support;
1403
1404 for (unsigned NumDecls = DataLen / sizeof(DeclID); NumDecls; --NumDecls) {
1406 Reader, F, endian::readNext<DeclID, llvm::endianness::little>(d));
1407 Val.insert(Reader.getGlobalDeclID(F, ID));
1408 }
1409}
1410
1412 const unsigned char *d,
1413 unsigned DataLen,
1414 data_type_builder &Val) {
1415 ReadDataIntoImpl(d, DataLen, Val);
1416}
1417
1420 llvm::FoldingSetNodeID ID;
1421 ID.AddInteger(Key.first.getHash());
1422 ID.AddInteger(Key.second);
1423 return ID.computeStableHash();
1424}
1425
1428 DeclarationNameKey Name(Key.first);
1429
1430 UnsignedOrNone ModuleHash = getPrimaryModuleHash(Key.second);
1431 if (!ModuleHash)
1432 return {Name, 0};
1433
1434 return {Name, *ModuleHash};
1435}
1436
1438ModuleLocalNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
1440 unsigned PrimaryModuleHash =
1441 llvm::support::endian::readNext<uint32_t, llvm::endianness::little>(d);
1442 return {Name, PrimaryModuleHash};
1443}
1444
1446 const unsigned char *d,
1447 unsigned DataLen,
1448 data_type_builder &Val) {
1449 ReadDataIntoImpl(d, DataLen, Val);
1450}
1451
1452ModuleFile *
1454 using namespace llvm::support;
1455
1456 uint32_t ModuleFileID =
1457 endian::readNext<uint32_t, llvm::endianness::little, unaligned>(d);
1458 return Reader.getLocalModuleFile(F, ModuleFileID);
1459}
1460
1462LazySpecializationInfoLookupTrait::ReadKey(const unsigned char *d, unsigned) {
1463 using namespace llvm::support;
1464 return endian::readNext<uint32_t, llvm::endianness::little, unaligned>(d);
1465}
1466
1467std::pair<unsigned, unsigned>
1471
1473 const unsigned char *d,
1474 unsigned DataLen,
1475 data_type_builder &Val) {
1476 using namespace llvm::support;
1477
1478 for (unsigned NumDecls =
1480 NumDecls; --NumDecls) {
1481 LocalDeclID LocalID = LocalDeclID::get(
1482 Reader, F,
1483 endian::readNext<DeclID, llvm::endianness::little, unaligned>(d));
1484 Val.insert(Reader.getGlobalDeclID(F, LocalID));
1485 }
1486}
1487
1488bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
1489 BitstreamCursor &Cursor,
1490 uint64_t Offset,
1491 DeclContext *DC) {
1492 assert(Offset != 0);
1493
1494 SavedStreamPosition SavedPosition(Cursor);
1495 if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1496 Error(std::move(Err));
1497 return true;
1498 }
1499
1500 RecordData Record;
1501 StringRef Blob;
1502 Expected<unsigned> MaybeCode = Cursor.ReadCode();
1503 if (!MaybeCode) {
1504 Error(MaybeCode.takeError());
1505 return true;
1506 }
1507 unsigned Code = MaybeCode.get();
1508
1509 Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
1510 if (!MaybeRecCode) {
1511 Error(MaybeRecCode.takeError());
1512 return true;
1513 }
1514 unsigned RecCode = MaybeRecCode.get();
1515 if (RecCode != DECL_CONTEXT_LEXICAL) {
1516 Error("Expected lexical block");
1517 return true;
1518 }
1519
1520 assert(!isa<TranslationUnitDecl>(DC) &&
1521 "expected a TU_UPDATE_LEXICAL record for TU");
1522 // If we are handling a C++ class template instantiation, we can see multiple
1523 // lexical updates for the same record. It's important that we select only one
1524 // of them, so that field numbering works properly. Just pick the first one we
1525 // see.
1526 auto &Lex = LexicalDecls[DC];
1527 if (!Lex.first) {
1528 Lex = std::make_pair(
1529 &M, llvm::ArrayRef(
1530 reinterpret_cast<const unaligned_decl_id_t *>(Blob.data()),
1531 Blob.size() / sizeof(DeclID)));
1532 }
1534 return false;
1535}
1536
1537bool ASTReader::ReadVisibleDeclContextStorage(
1538 ModuleFile &M, BitstreamCursor &Cursor, uint64_t Offset, GlobalDeclID ID,
1539 ASTReader::VisibleDeclContextStorageKind VisibleKind) {
1540 assert(Offset != 0);
1541
1542 SavedStreamPosition SavedPosition(Cursor);
1543 if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1544 Error(std::move(Err));
1545 return true;
1546 }
1547
1548 RecordData Record;
1549 StringRef Blob;
1550 Expected<unsigned> MaybeCode = Cursor.ReadCode();
1551 if (!MaybeCode) {
1552 Error(MaybeCode.takeError());
1553 return true;
1554 }
1555 unsigned Code = MaybeCode.get();
1556
1557 Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
1558 if (!MaybeRecCode) {
1559 Error(MaybeRecCode.takeError());
1560 return true;
1561 }
1562 unsigned RecCode = MaybeRecCode.get();
1563 switch (VisibleKind) {
1564 case VisibleDeclContextStorageKind::GenerallyVisible:
1565 if (RecCode != DECL_CONTEXT_VISIBLE) {
1566 Error("Expected visible lookup table block");
1567 return true;
1568 }
1569 break;
1570 case VisibleDeclContextStorageKind::ModuleLocalVisible:
1571 if (RecCode != DECL_CONTEXT_MODULE_LOCAL_VISIBLE) {
1572 Error("Expected module local visible lookup table block");
1573 return true;
1574 }
1575 break;
1576 case VisibleDeclContextStorageKind::TULocalVisible:
1577 if (RecCode != DECL_CONTEXT_TU_LOCAL_VISIBLE) {
1578 Error("Expected TU local lookup table block");
1579 return true;
1580 }
1581 break;
1582 }
1583
1584 // We can't safely determine the primary context yet, so delay attaching the
1585 // lookup table until we're done with recursive deserialization.
1586 auto *Data = (const unsigned char*)Blob.data();
1587 switch (VisibleKind) {
1588 case VisibleDeclContextStorageKind::GenerallyVisible:
1589 PendingVisibleUpdates[ID].push_back(UpdateData{&M, Data});
1590 break;
1591 case VisibleDeclContextStorageKind::ModuleLocalVisible:
1592 PendingModuleLocalVisibleUpdates[ID].push_back(UpdateData{&M, Data});
1593 break;
1594 case VisibleDeclContextStorageKind::TULocalVisible:
1595 if (M.Kind == MK_MainFile)
1596 TULocalUpdates[ID].push_back(UpdateData{&M, Data});
1597 break;
1598 }
1599 return false;
1600}
1601
1602void ASTReader::AddSpecializations(const Decl *D, const unsigned char *Data,
1603 ModuleFile &M, bool IsPartial) {
1604 D = D->getCanonicalDecl();
1605 auto &SpecLookups =
1606 IsPartial ? PartialSpecializationsLookups : SpecializationsLookups;
1607 SpecLookups[D].Table.add(&M, Data,
1609}
1610
1611bool ASTReader::ReadSpecializations(ModuleFile &M, BitstreamCursor &Cursor,
1612 uint64_t Offset, Decl *D, bool IsPartial) {
1613 assert(Offset != 0);
1614
1615 SavedStreamPosition SavedPosition(Cursor);
1616 if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1617 Error(std::move(Err));
1618 return true;
1619 }
1620
1621 RecordData Record;
1622 StringRef Blob;
1623 Expected<unsigned> MaybeCode = Cursor.ReadCode();
1624 if (!MaybeCode) {
1625 Error(MaybeCode.takeError());
1626 return true;
1627 }
1628 unsigned Code = MaybeCode.get();
1629
1630 Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
1631 if (!MaybeRecCode) {
1632 Error(MaybeRecCode.takeError());
1633 return true;
1634 }
1635 unsigned RecCode = MaybeRecCode.get();
1636 if (RecCode != DECL_SPECIALIZATIONS &&
1637 RecCode != DECL_PARTIAL_SPECIALIZATIONS) {
1638 Error("Expected decl specs block");
1639 return true;
1640 }
1641
1642 auto *Data = (const unsigned char *)Blob.data();
1643 AddSpecializations(D, Data, M, IsPartial);
1644 return false;
1645}
1646
1647void ASTReader::Error(StringRef Msg) const {
1648 Error(diag::err_fe_ast_file_malformed, Msg);
1649 if (PP.getLangOpts().Modules &&
1650 !PP.getHeaderSearchInfo().getSpecificModuleCachePath().empty()) {
1651 Diag(diag::note_module_cache_path)
1652 << PP.getHeaderSearchInfo().getSpecificModuleCachePath();
1653 }
1654}
1655
1656void ASTReader::Error(unsigned DiagID, StringRef Arg1, StringRef Arg2,
1657 StringRef Arg3) const {
1658 Diag(DiagID) << Arg1 << Arg2 << Arg3;
1659}
1660
1661namespace {
1662struct AlreadyReportedDiagnosticError
1663 : llvm::ErrorInfo<AlreadyReportedDiagnosticError> {
1664 static char ID;
1665
1666 void log(raw_ostream &OS) const override {
1667 llvm_unreachable("reporting an already-reported diagnostic error");
1668 }
1669
1670 std::error_code convertToErrorCode() const override {
1671 return llvm::inconvertibleErrorCode();
1672 }
1673};
1674
1675char AlreadyReportedDiagnosticError::ID = 0;
1676} // namespace
1677
1678void ASTReader::Error(llvm::Error &&Err) const {
1679 handleAllErrors(
1680 std::move(Err), [](AlreadyReportedDiagnosticError &) {},
1681 [&](llvm::ErrorInfoBase &E) { return Error(E.message()); });
1682}
1683
1684//===----------------------------------------------------------------------===//
1685// Source Manager Deserialization
1686//===----------------------------------------------------------------------===//
1687
1688/// Read the line table in the source manager block.
1689void ASTReader::ParseLineTable(ModuleFile &F, const RecordData &Record) {
1690 unsigned Idx = 0;
1691 LineTableInfo &LineTable = SourceMgr.getLineTable();
1692
1693 // Parse the file names
1694 std::map<int, int> FileIDs;
1695 FileIDs[-1] = -1; // For unspecified filenames.
1696 for (unsigned I = 0; Record[Idx]; ++I) {
1697 // Extract the file name
1698 auto Filename = ReadPath(F, Record, Idx);
1699 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1700 }
1701 ++Idx;
1702
1703 // Parse the line entries
1704 std::vector<LineEntry> Entries;
1705 while (Idx < Record.size()) {
1706 FileID FID = ReadFileID(F, Record, Idx);
1707
1708 // Extract the line entries
1709 unsigned NumEntries = Record[Idx++];
1710 assert(NumEntries && "no line entries for file ID");
1711 Entries.clear();
1712 Entries.reserve(NumEntries);
1713 for (unsigned I = 0; I != NumEntries; ++I) {
1714 unsigned FileOffset = Record[Idx++];
1715 unsigned LineNo = Record[Idx++];
1716 int FilenameID = FileIDs[Record[Idx++]];
1719 unsigned IncludeOffset = Record[Idx++];
1720 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1721 FileKind, IncludeOffset));
1722 }
1723 LineTable.AddEntry(FID, Entries);
1724 }
1725}
1726
1727/// Read a source manager block
1728llvm::Error ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1729 using namespace SrcMgr;
1730
1731 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
1732
1733 // Set the source-location entry cursor to the current position in
1734 // the stream. This cursor will be used to read the contents of the
1735 // source manager block initially, and then lazily read
1736 // source-location entries as needed.
1737 SLocEntryCursor = F.Stream;
1738
1739 // The stream itself is going to skip over the source manager block.
1740 if (llvm::Error Err = F.Stream.SkipBlock())
1741 return Err;
1742
1743 // Enter the source manager block.
1744 if (llvm::Error Err = SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID))
1745 return Err;
1746 F.SourceManagerBlockStartOffset = SLocEntryCursor.GetCurrentBitNo();
1747
1748 RecordData Record;
1749 while (true) {
1750 Expected<llvm::BitstreamEntry> MaybeE =
1751 SLocEntryCursor.advanceSkippingSubblocks();
1752 if (!MaybeE)
1753 return MaybeE.takeError();
1754 llvm::BitstreamEntry E = MaybeE.get();
1755
1756 switch (E.Kind) {
1757 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1758 case llvm::BitstreamEntry::Error:
1759 return llvm::createStringError(std::errc::illegal_byte_sequence,
1760 "malformed block record in AST file");
1761 case llvm::BitstreamEntry::EndBlock:
1762 return llvm::Error::success();
1763 case llvm::BitstreamEntry::Record:
1764 // The interesting case.
1765 break;
1766 }
1767
1768 // Read a record.
1769 Record.clear();
1770 StringRef Blob;
1771 Expected<unsigned> MaybeRecord =
1772 SLocEntryCursor.readRecord(E.ID, Record, &Blob);
1773 if (!MaybeRecord)
1774 return MaybeRecord.takeError();
1775 switch (MaybeRecord.get()) {
1776 default: // Default behavior: ignore.
1777 break;
1778
1779 case SM_SLOC_FILE_ENTRY:
1782 // Once we hit one of the source location entries, we're done.
1783 return llvm::Error::success();
1784 }
1785 }
1786}
1787
1788llvm::Expected<SourceLocation::UIntTy>
1790 BitstreamCursor &Cursor = F->SLocEntryCursor;
1791 SavedStreamPosition SavedPosition(Cursor);
1792 if (llvm::Error Err = Cursor.JumpToBit(F->SLocEntryOffsetsBase +
1793 F->SLocEntryOffsets[Index]))
1794 return std::move(Err);
1795
1796 Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
1797 if (!MaybeEntry)
1798 return MaybeEntry.takeError();
1799
1800 llvm::BitstreamEntry Entry = MaybeEntry.get();
1801 if (Entry.Kind != llvm::BitstreamEntry::Record)
1802 return llvm::createStringError(
1803 std::errc::illegal_byte_sequence,
1804 "incorrectly-formatted source location entry in AST file");
1805
1807 StringRef Blob;
1808 Expected<unsigned> MaybeSLOC = Cursor.readRecord(Entry.ID, Record, &Blob);
1809 if (!MaybeSLOC)
1810 return MaybeSLOC.takeError();
1811
1812 switch (MaybeSLOC.get()) {
1813 default:
1814 return llvm::createStringError(
1815 std::errc::illegal_byte_sequence,
1816 "incorrectly-formatted source location entry in AST file");
1817 case SM_SLOC_FILE_ENTRY:
1820 return F->SLocEntryBaseOffset + Record[0];
1821 }
1822}
1823
1825 auto SLocMapI =
1826 GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset - SLocOffset - 1);
1827 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
1828 "Corrupted global sloc offset map");
1829 ModuleFile *F = SLocMapI->second;
1830
1831 bool Invalid = false;
1832
1833 auto It = llvm::upper_bound(
1834 llvm::index_range(0, F->LocalNumSLocEntries), SLocOffset,
1835 [&](SourceLocation::UIntTy Offset, std::size_t LocalIndex) {
1836 int ID = F->SLocEntryBaseID + LocalIndex;
1837 std::size_t Index = -ID - 2;
1838 if (!SourceMgr.SLocEntryOffsetLoaded[Index]) {
1839 assert(!SourceMgr.SLocEntryLoaded[Index]);
1840 auto MaybeEntryOffset = readSLocOffset(F, LocalIndex);
1841 if (!MaybeEntryOffset) {
1842 Error(MaybeEntryOffset.takeError());
1843 Invalid = true;
1844 return true;
1845 }
1846 SourceMgr.LoadedSLocEntryTable[Index] =
1847 SrcMgr::SLocEntry::getOffsetOnly(*MaybeEntryOffset);
1848 SourceMgr.SLocEntryOffsetLoaded[Index] = true;
1849 }
1850 return Offset < SourceMgr.LoadedSLocEntryTable[Index].getOffset();
1851 });
1852
1853 if (Invalid)
1854 return 0;
1855
1856 // The iterator points to the first entry with start offset greater than the
1857 // offset of interest. The previous entry must contain the offset of interest.
1858 return F->SLocEntryBaseID + *std::prev(It);
1859}
1860
1862 if (ID == 0)
1863 return false;
1864
1865 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1866 Error("source location entry ID out-of-range for AST file");
1867 return true;
1868 }
1869
1870 // Local helper to read the (possibly-compressed) buffer data following the
1871 // entry record.
1872 auto ReadBuffer = [this](
1873 BitstreamCursor &SLocEntryCursor,
1874 StringRef Name) -> std::unique_ptr<llvm::MemoryBuffer> {
1876 StringRef Blob;
1877 Expected<unsigned> MaybeCode = SLocEntryCursor.ReadCode();
1878 if (!MaybeCode) {
1879 Error(MaybeCode.takeError());
1880 return nullptr;
1881 }
1882 unsigned Code = MaybeCode.get();
1883
1884 Expected<unsigned> MaybeRecCode =
1885 SLocEntryCursor.readRecord(Code, Record, &Blob);
1886 if (!MaybeRecCode) {
1887 Error(MaybeRecCode.takeError());
1888 return nullptr;
1889 }
1890 unsigned RecCode = MaybeRecCode.get();
1891
1892 if (RecCode == SM_SLOC_BUFFER_BLOB_COMPRESSED) {
1893 // Inspect the first byte to differentiate zlib (\x78) and zstd
1894 // (little-endian 0xFD2FB528).
1895 const llvm::compression::Format F =
1896 Blob.size() > 0 && Blob.data()[0] == 0x78
1897 ? llvm::compression::Format::Zlib
1898 : llvm::compression::Format::Zstd;
1899 if (const char *Reason = llvm::compression::getReasonIfUnsupported(F)) {
1900 Error(Reason);
1901 return nullptr;
1902 }
1903 SmallVector<uint8_t, 0> Decompressed;
1904 if (llvm::Error E = llvm::compression::decompress(
1905 F, llvm::arrayRefFromStringRef(Blob), Decompressed, Record[0])) {
1906 Error("could not decompress embedded file contents: " +
1907 llvm::toString(std::move(E)));
1908 return nullptr;
1909 }
1910 return llvm::MemoryBuffer::getMemBufferCopy(
1911 llvm::toStringRef(Decompressed), Name);
1912 } else if (RecCode == SM_SLOC_BUFFER_BLOB) {
1913 return llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name, true);
1914 } else {
1915 Error("AST record has invalid code");
1916 return nullptr;
1917 }
1918 };
1919
1920 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1921 if (llvm::Error Err = F->SLocEntryCursor.JumpToBit(
1923 F->SLocEntryOffsets[ID - F->SLocEntryBaseID])) {
1924 Error(std::move(Err));
1925 return true;
1926 }
1927
1928 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
1930
1931 ++NumSLocEntriesRead;
1932 Expected<llvm::BitstreamEntry> MaybeEntry = SLocEntryCursor.advance();
1933 if (!MaybeEntry) {
1934 Error(MaybeEntry.takeError());
1935 return true;
1936 }
1937 llvm::BitstreamEntry Entry = MaybeEntry.get();
1938
1939 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1940 Error("incorrectly-formatted source location entry in AST file");
1941 return true;
1942 }
1943
1945 StringRef Blob;
1946 Expected<unsigned> MaybeSLOC =
1947 SLocEntryCursor.readRecord(Entry.ID, Record, &Blob);
1948 if (!MaybeSLOC) {
1949 Error(MaybeSLOC.takeError());
1950 return true;
1951 }
1952 switch (MaybeSLOC.get()) {
1953 default:
1954 Error("incorrectly-formatted source location entry in AST file");
1955 return true;
1956
1957 case SM_SLOC_FILE_ENTRY: {
1958 // We will detect whether a file changed and return 'Failure' for it, but
1959 // we will also try to fail gracefully by setting up the SLocEntry.
1960 unsigned InputID = Record[4];
1961 InputFile IF = getInputFile(*F, InputID);
1963 bool OverriddenBuffer = IF.isOverridden();
1964
1965 // Note that we only check if a File was returned. If it was out-of-date
1966 // we have complained but we will continue creating a FileID to recover
1967 // gracefully.
1968 if (!File)
1969 return true;
1970
1971 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1972 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1973 // This is the module's main file.
1974 IncludeLoc = getImportLocation(F);
1975 }
1977 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1978 FileID FID = SourceMgr.createFileID(*File, IncludeLoc, FileCharacter, ID,
1979 BaseOffset + Record[0]);
1980 SrcMgr::FileInfo &FileInfo = SourceMgr.getSLocEntry(FID).getFile();
1981 FileInfo.NumCreatedFIDs = Record[5];
1982 if (Record[3])
1983 FileInfo.setHasLineDirectives();
1984
1985 unsigned NumFileDecls = Record[7];
1986 if (NumFileDecls && ContextObj) {
1987 const unaligned_decl_id_t *FirstDecl = F->FileSortedDecls + Record[6];
1988 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1989 FileDeclIDs[FID] =
1990 FileDeclsInfo(F, llvm::ArrayRef(FirstDecl, NumFileDecls));
1991 }
1992
1993 const SrcMgr::ContentCache &ContentCache =
1994 SourceMgr.getOrCreateContentCache(*File, isSystem(FileCharacter));
1995 if (OverriddenBuffer && !ContentCache.BufferOverridden &&
1996 ContentCache.ContentsEntry == ContentCache.OrigEntry &&
1997 !ContentCache.getBufferIfLoaded()) {
1998 auto Buffer = ReadBuffer(SLocEntryCursor, File->getName());
1999 if (!Buffer)
2000 return true;
2001 SourceMgr.overrideFileContents(*File, std::move(Buffer));
2002 }
2003
2004 break;
2005 }
2006
2007 case SM_SLOC_BUFFER_ENTRY: {
2008 const char *Name = Blob.data();
2009 unsigned Offset = Record[0];
2011 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
2012 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
2013 if (IncludeLoc.isInvalid() && F->isModule()) {
2014 IncludeLoc = getImportLocation(F);
2015 }
2016
2017 auto Buffer = ReadBuffer(SLocEntryCursor, Name);
2018 if (!Buffer)
2019 return true;
2020 FileID FID = SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
2021 BaseOffset + Offset, IncludeLoc);
2022 if (Record[3]) {
2023 auto &FileInfo = SourceMgr.getSLocEntry(FID).getFile();
2024 FileInfo.setHasLineDirectives();
2025 }
2026 break;
2027 }
2028
2030 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
2031 SourceLocation ExpansionBegin = ReadSourceLocation(*F, Record[2]);
2032 SourceLocation ExpansionEnd = ReadSourceLocation(*F, Record[3]);
2033 SourceMgr.createExpansionLoc(SpellingLoc, ExpansionBegin, ExpansionEnd,
2034 Record[5], Record[4], ID,
2035 BaseOffset + Record[0]);
2036 break;
2037 }
2038 }
2039
2040 return false;
2041}
2042
2043std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
2044 if (ID == 0)
2045 return std::make_pair(SourceLocation(), "");
2046
2047 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
2048 Error("source location entry ID out-of-range for AST file");
2049 return std::make_pair(SourceLocation(), "");
2050 }
2051
2052 // Find which module file this entry lands in.
2053 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
2054 if (!M->isModule())
2055 return std::make_pair(SourceLocation(), "");
2056
2057 // FIXME: Can we map this down to a particular submodule? That would be
2058 // ideal.
2059 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
2060}
2061
2062/// Find the location where the module F is imported.
2063SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
2064 if (F->ImportLoc.isValid())
2065 return F->ImportLoc;
2066
2067 // Otherwise we have a PCH. It's considered to be "imported" at the first
2068 // location of its includer.
2069 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
2070 // Main file is the importer.
2071 assert(SourceMgr.getMainFileID().isValid() && "missing main file");
2072 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
2073 }
2074 return F->ImportedBy[0]->FirstLoc;
2075}
2076
2077/// Enter a subblock of the specified BlockID with the specified cursor. Read
2078/// the abbreviations that are at the top of the block and then leave the cursor
2079/// pointing into the block.
2080llvm::Error ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor,
2081 unsigned BlockID,
2082 uint64_t *StartOfBlockOffset) {
2083 if (llvm::Error Err = Cursor.EnterSubBlock(BlockID))
2084 return Err;
2085
2086 if (StartOfBlockOffset)
2087 *StartOfBlockOffset = Cursor.GetCurrentBitNo();
2088
2089 while (true) {
2090 uint64_t Offset = Cursor.GetCurrentBitNo();
2091 Expected<unsigned> MaybeCode = Cursor.ReadCode();
2092 if (!MaybeCode)
2093 return MaybeCode.takeError();
2094 unsigned Code = MaybeCode.get();
2095
2096 // We expect all abbrevs to be at the start of the block.
2097 if (Code != llvm::bitc::DEFINE_ABBREV) {
2098 if (llvm::Error Err = Cursor.JumpToBit(Offset))
2099 return Err;
2100 return llvm::Error::success();
2101 }
2102 if (llvm::Error Err = Cursor.ReadAbbrevRecord())
2103 return Err;
2104 }
2105}
2106
2108 unsigned &Idx) {
2109 Token Tok;
2110 Tok.startToken();
2111 Tok.setLocation(ReadSourceLocation(M, Record, Idx));
2112 Tok.setKind((tok::TokenKind)Record[Idx++]);
2113 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
2114
2115 if (Tok.isAnnotation()) {
2116 Tok.setAnnotationEndLoc(ReadSourceLocation(M, Record, Idx));
2117 switch (Tok.getKind()) {
2118 case tok::annot_pragma_loop_hint: {
2119 auto *Info = new (PP.getPreprocessorAllocator()) PragmaLoopHintInfo;
2120 Info->PragmaName = ReadToken(M, Record, Idx);
2121 Info->Option = ReadToken(M, Record, Idx);
2122 unsigned NumTokens = Record[Idx++];
2124 Toks.reserve(NumTokens);
2125 for (unsigned I = 0; I < NumTokens; ++I)
2126 Toks.push_back(ReadToken(M, Record, Idx));
2127 Info->Toks = llvm::ArrayRef(Toks).copy(PP.getPreprocessorAllocator());
2128 Tok.setAnnotationValue(static_cast<void *>(Info));
2129 break;
2130 }
2131 case tok::annot_pragma_pack: {
2132 auto *Info = new (PP.getPreprocessorAllocator()) Sema::PragmaPackInfo;
2133 Info->Action = static_cast<Sema::PragmaMsStackAction>(Record[Idx++]);
2134 auto SlotLabel = ReadString(Record, Idx);
2135 Info->SlotLabel =
2136 llvm::StringRef(SlotLabel).copy(PP.getPreprocessorAllocator());
2137 Info->Alignment = ReadToken(M, Record, Idx);
2138 Tok.setAnnotationValue(static_cast<void *>(Info));
2139 break;
2140 }
2141 // Some annotation tokens do not use the PtrData field.
2142 case tok::annot_pragma_openmp:
2143 case tok::annot_pragma_openmp_end:
2144 case tok::annot_pragma_unused:
2145 case tok::annot_pragma_openacc:
2146 case tok::annot_pragma_openacc_end:
2147 case tok::annot_repl_input_end:
2148 break;
2149 default:
2150 llvm_unreachable("missing deserialization code for annotation token");
2151 }
2152 } else {
2153 Tok.setLength(Record[Idx++]);
2154 if (IdentifierInfo *II = getLocalIdentifier(M, Record[Idx++]))
2155 Tok.setIdentifierInfo(II);
2156 }
2157 return Tok;
2158}
2159
2161 BitstreamCursor &Stream = F.MacroCursor;
2162
2163 // Keep track of where we are in the stream, then jump back there
2164 // after reading this macro.
2165 SavedStreamPosition SavedPosition(Stream);
2166
2167 if (llvm::Error Err = Stream.JumpToBit(Offset)) {
2168 // FIXME this drops errors on the floor.
2169 consumeError(std::move(Err));
2170 return nullptr;
2171 }
2174 MacroInfo *Macro = nullptr;
2175 llvm::MutableArrayRef<Token> MacroTokens;
2176
2177 while (true) {
2178 // Advance to the next record, but if we get to the end of the block, don't
2179 // pop it (removing all the abbreviations from the cursor) since we want to
2180 // be able to reseek within the block and read entries.
2181 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
2183 Stream.advanceSkippingSubblocks(Flags);
2184 if (!MaybeEntry) {
2185 Error(MaybeEntry.takeError());
2186 return Macro;
2187 }
2188 llvm::BitstreamEntry Entry = MaybeEntry.get();
2189
2190 switch (Entry.Kind) {
2191 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
2192 case llvm::BitstreamEntry::Error:
2193 Error("malformed block record in AST file");
2194 return Macro;
2195 case llvm::BitstreamEntry::EndBlock:
2196 return Macro;
2197 case llvm::BitstreamEntry::Record:
2198 // The interesting case.
2199 break;
2200 }
2201
2202 // Read a record.
2203 Record.clear();
2205 if (Expected<unsigned> MaybeRecType = Stream.readRecord(Entry.ID, Record))
2206 RecType = (PreprocessorRecordTypes)MaybeRecType.get();
2207 else {
2208 Error(MaybeRecType.takeError());
2209 return Macro;
2210 }
2211 switch (RecType) {
2212 case PP_MODULE_MACRO:
2214 return Macro;
2215
2218 // If we already have a macro, that means that we've hit the end
2219 // of the definition of the macro we were looking for. We're
2220 // done.
2221 if (Macro)
2222 return Macro;
2223
2224 unsigned NextIndex = 1; // Skip identifier ID.
2225 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
2226 MacroInfo *MI = PP.AllocateMacroInfo(Loc);
2227 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
2228 MI->setIsUsed(Record[NextIndex++]);
2229 MI->setUsedForHeaderGuard(Record[NextIndex++]);
2230 MacroTokens = MI->allocateTokens(Record[NextIndex++],
2231 PP.getPreprocessorAllocator());
2232 if (RecType == PP_MACRO_FUNCTION_LIKE) {
2233 // Decode function-like macro info.
2234 bool isC99VarArgs = Record[NextIndex++];
2235 bool isGNUVarArgs = Record[NextIndex++];
2236 bool hasCommaPasting = Record[NextIndex++];
2237 MacroParams.clear();
2238 unsigned NumArgs = Record[NextIndex++];
2239 for (unsigned i = 0; i != NumArgs; ++i)
2240 MacroParams.push_back(getLocalIdentifier(F, Record[NextIndex++]));
2241
2242 // Install function-like macro info.
2243 MI->setIsFunctionLike();
2244 if (isC99VarArgs) MI->setIsC99Varargs();
2245 if (isGNUVarArgs) MI->setIsGNUVarargs();
2246 if (hasCommaPasting) MI->setHasCommaPasting();
2247 MI->setParameterList(MacroParams, PP.getPreprocessorAllocator());
2248 }
2249
2250 // Remember that we saw this macro last so that we add the tokens that
2251 // form its body to it.
2252 Macro = MI;
2253
2254 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
2255 Record[NextIndex]) {
2256 // We have a macro definition. Register the association
2258 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
2259 unsigned Index = translatePreprocessedEntityIDToIndex(GlobalID);
2260 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
2261 PreprocessingRecord::PPEntityID PPID =
2262 PPRec.getPPEntityID(Index, /*isLoaded=*/true);
2263 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
2264 PPRec.getPreprocessedEntity(PPID));
2265 if (PPDef)
2266 PPRec.RegisterMacroDefinition(Macro, PPDef);
2267 }
2268
2269 ++NumMacrosRead;
2270 break;
2271 }
2272
2273 case PP_TOKEN: {
2274 // If we see a TOKEN before a PP_MACRO_*, then the file is
2275 // erroneous, just pretend we didn't see this.
2276 if (!Macro) break;
2277 if (MacroTokens.empty()) {
2278 Error("unexpected number of macro tokens for a macro in AST file");
2279 return Macro;
2280 }
2281
2282 unsigned Idx = 0;
2283 MacroTokens[0] = ReadToken(F, Record, Idx);
2284 MacroTokens = MacroTokens.drop_front();
2285 break;
2286 }
2287 }
2288 }
2289}
2290
2293 PreprocessedEntityID LocalID) const {
2294 if (!M.ModuleOffsetMap.empty())
2295 ReadModuleOffsetMap(M);
2296
2297 unsigned ModuleFileIndex = LocalID >> 32;
2298 LocalID &= llvm::maskTrailingOnes<PreprocessedEntityID>(32);
2299 ModuleFile *MF =
2300 ModuleFileIndex ? M.TransitiveImports[ModuleFileIndex - 1] : &M;
2301 assert(MF && "malformed identifier ID encoding?");
2302
2303 if (!ModuleFileIndex) {
2304 assert(LocalID >= NUM_PREDEF_PP_ENTITY_IDS);
2305 LocalID -= NUM_PREDEF_PP_ENTITY_IDS;
2306 }
2307
2308 return (static_cast<PreprocessedEntityID>(MF->Index + 1) << 32) | LocalID;
2309}
2310
2312HeaderFileInfoTrait::getFile(const internal_key_type &Key) {
2313 FileManager &FileMgr = Reader.getFileManager();
2314 if (!Key.Imported)
2315 return FileMgr.getOptionalFileRef(Key.Filename);
2316
2317 auto Resolved =
2318 ASTReader::ResolveImportedPath(Reader.getPathBuf(), Key.Filename, M);
2319 return FileMgr.getOptionalFileRef(*Resolved);
2320}
2321
2323 uint8_t buf[sizeof(ikey.Size) + sizeof(ikey.ModTime)];
2324 memcpy(buf, &ikey.Size, sizeof(ikey.Size));
2325 memcpy(buf + sizeof(ikey.Size), &ikey.ModTime, sizeof(ikey.ModTime));
2326 return llvm::xxh3_64bits(buf);
2327}
2328
2331 internal_key_type ikey = {ekey.getSize(),
2332 M.HasTimestamps ? ekey.getModificationTime() : 0,
2333 ekey.getName(), /*Imported*/ false};
2334 return ikey;
2335}
2336
2338 if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime))
2339 return false;
2340
2341 if (llvm::sys::path::is_absolute(a.Filename) && a.Filename == b.Filename)
2342 return true;
2343
2344 // Determine whether the actual files are equivalent.
2345 OptionalFileEntryRef FEA = getFile(a);
2346 OptionalFileEntryRef FEB = getFile(b);
2347 return FEA && FEA == FEB;
2348}
2349
2350std::pair<unsigned, unsigned>
2352 return readULEBKeyDataLength(d);
2353}
2354
2356HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
2357 using namespace llvm::support;
2358
2359 internal_key_type ikey;
2360 ikey.Size = off_t(endian::readNext<uint64_t, llvm::endianness::little>(d));
2361 ikey.ModTime =
2362 time_t(endian::readNext<uint64_t, llvm::endianness::little>(d));
2363 ikey.Filename = (const char *)d;
2364 ikey.Imported = true;
2365 return ikey;
2366}
2367
2370 unsigned DataLen) {
2371 using namespace llvm::support;
2372
2373 const unsigned char *End = d + DataLen;
2374 HeaderFileInfo HFI;
2375 unsigned Flags = *d++;
2376
2378 bool Included = (Flags >> 6) & 0x01;
2379 if (Included)
2380 if ((FE = getFile(key)))
2381 // Not using \c Preprocessor::markIncluded(), since that would attempt to
2382 // deserialize this header file info again.
2383 Reader.getPreprocessor().getIncludedFiles().insert(*FE);
2384
2385 // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
2386 HFI.isImport |= (Flags >> 5) & 0x01;
2387 HFI.isPragmaOnce |= (Flags >> 4) & 0x01;
2388 HFI.DirInfo = (Flags >> 1) & 0x07;
2389 HFI.LazyControllingMacro = Reader.getGlobalIdentifierID(
2390 M, endian::readNext<IdentifierID, llvm::endianness::little>(d));
2391
2392 assert((End - d) % 4 == 0 &&
2393 "Wrong data length in HeaderFileInfo deserialization");
2394 while (d != End) {
2395 uint32_t LocalSMID =
2396 endian::readNext<uint32_t, llvm::endianness::little>(d);
2397 auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 7);
2398 LocalSMID >>= 3;
2399
2400 // This header is part of a module. Associate it with the module to enable
2401 // implicit module import.
2402 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
2403 Module *Mod = Reader.getSubmodule(GlobalSMID);
2404 ModuleMap &ModMap =
2405 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
2406
2407 if (FE || (FE = getFile(key))) {
2408 // FIXME: NameAsWritten
2409 Module::Header H = {std::string(key.Filename), "", *FE};
2410 ModMap.addHeader(Mod, H, HeaderRole, /*Imported=*/true);
2411 }
2412 HFI.mergeModuleMembership(HeaderRole);
2413 }
2414
2415 // This HeaderFileInfo was externally loaded.
2416 HFI.External = true;
2417 HFI.IsValid = true;
2418 return HFI;
2419}
2420
2422 uint32_t MacroDirectivesOffset) {
2423 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
2424 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
2425}
2426
2428 // Note that we are loading defined macros.
2429 Deserializing Macros(this);
2430
2431 for (ModuleFile &I : llvm::reverse(ModuleMgr)) {
2432 BitstreamCursor &MacroCursor = I.MacroCursor;
2433
2434 // If there was no preprocessor block, skip this file.
2435 if (MacroCursor.getBitcodeBytes().empty())
2436 continue;
2437
2438 BitstreamCursor Cursor = MacroCursor;
2439 if (llvm::Error Err = Cursor.JumpToBit(I.MacroStartOffset)) {
2440 Error(std::move(Err));
2441 return;
2442 }
2443
2445 while (true) {
2446 Expected<llvm::BitstreamEntry> MaybeE = Cursor.advanceSkippingSubblocks();
2447 if (!MaybeE) {
2448 Error(MaybeE.takeError());
2449 return;
2450 }
2451 llvm::BitstreamEntry E = MaybeE.get();
2452
2453 switch (E.Kind) {
2454 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
2455 case llvm::BitstreamEntry::Error:
2456 Error("malformed block record in AST file");
2457 return;
2458 case llvm::BitstreamEntry::EndBlock:
2459 goto NextCursor;
2460
2461 case llvm::BitstreamEntry::Record: {
2462 Record.clear();
2463 Expected<unsigned> MaybeRecord = Cursor.readRecord(E.ID, Record);
2464 if (!MaybeRecord) {
2465 Error(MaybeRecord.takeError());
2466 return;
2467 }
2468 switch (MaybeRecord.get()) {
2469 default: // Default behavior: ignore.
2470 break;
2471
2475 if (II->isOutOfDate())
2477 break;
2478 }
2479
2480 case PP_TOKEN:
2481 // Ignore tokens.
2482 break;
2483 }
2484 break;
2485 }
2486 }
2487 }
2488 NextCursor: ;
2489 }
2490}
2491
2492namespace {
2493
2494 /// Visitor class used to look up identifirs in an AST file.
2495 class IdentifierLookupVisitor {
2496 StringRef Name;
2497 unsigned NameHash;
2498 unsigned PriorGeneration;
2499 unsigned &NumIdentifierLookups;
2500 unsigned &NumIdentifierLookupHits;
2501 IdentifierInfo *Found = nullptr;
2502
2503 public:
2504 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
2505 unsigned &NumIdentifierLookups,
2506 unsigned &NumIdentifierLookupHits)
2507 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
2508 PriorGeneration(PriorGeneration),
2509 NumIdentifierLookups(NumIdentifierLookups),
2510 NumIdentifierLookupHits(NumIdentifierLookupHits) {}
2511
2512 bool operator()(ModuleFile &M) {
2513 // If we've already searched this module file, skip it now.
2514 if (M.Generation <= PriorGeneration)
2515 return true;
2516
2519 if (!IdTable)
2520 return false;
2521
2522 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
2523 Found);
2524 ++NumIdentifierLookups;
2525 ASTIdentifierLookupTable::iterator Pos =
2526 IdTable->find_hashed(Name, NameHash, &Trait);
2527 if (Pos == IdTable->end())
2528 return false;
2529
2530 // Dereferencing the iterator has the effect of building the
2531 // IdentifierInfo node and populating it with the various
2532 // declarations it needs.
2533 ++NumIdentifierLookupHits;
2534 Found = *Pos;
2535 if (Trait.hasMoreInformationInDependencies()) {
2536 // Look for the identifier in extra modules as they contain more info.
2537 return false;
2538 }
2539 return true;
2540 }
2541
2542 // Retrieve the identifier info found within the module
2543 // files.
2544 IdentifierInfo *getIdentifierInfo() const { return Found; }
2545 };
2546
2547} // namespace
2548
2550 // Note that we are loading an identifier.
2551 Deserializing AnIdentifier(this);
2552
2553 unsigned PriorGeneration = 0;
2554 if (getContext().getLangOpts().Modules)
2555 PriorGeneration = IdentifierGeneration[&II];
2556
2557 // If there is a global index, look there first to determine which modules
2558 // provably do not have any results for this identifier.
2560 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
2561 if (!loadGlobalIndex()) {
2562 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
2563 HitsPtr = &Hits;
2564 }
2565 }
2566
2567 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
2568 NumIdentifierLookups,
2569 NumIdentifierLookupHits);
2570 ModuleMgr.visit(Visitor, HitsPtr);
2572}
2573
2575 if (!II)
2576 return;
2577
2578 const_cast<IdentifierInfo *>(II)->setOutOfDate(false);
2579
2580 // Update the generation for this identifier.
2581 if (getContext().getLangOpts().Modules)
2582 IdentifierGeneration[II] = getGeneration();
2583}
2584
2586 unsigned &Idx) {
2587 uint64_t ModuleFileIndex = Record[Idx++] << 32;
2588 uint64_t LocalIndex = Record[Idx++];
2589 return getGlobalMacroID(F, (ModuleFileIndex | LocalIndex));
2590}
2591
2593 const PendingMacroInfo &PMInfo) {
2594 ModuleFile &M = *PMInfo.M;
2595
2596 BitstreamCursor &Cursor = M.MacroCursor;
2597 SavedStreamPosition SavedPosition(Cursor);
2598 if (llvm::Error Err =
2599 Cursor.JumpToBit(M.MacroOffsetsBase + PMInfo.MacroDirectivesOffset)) {
2600 Error(std::move(Err));
2601 return;
2602 }
2603
2604 struct ModuleMacroRecord {
2605 SubmoduleID SubModID;
2606 MacroInfo *MI;
2608 };
2610
2611 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
2612 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
2613 // macro histroy.
2615 while (true) {
2617 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
2618 if (!MaybeEntry) {
2619 Error(MaybeEntry.takeError());
2620 return;
2621 }
2622 llvm::BitstreamEntry Entry = MaybeEntry.get();
2623
2624 if (Entry.Kind != llvm::BitstreamEntry::Record) {
2625 Error("malformed block record in AST file");
2626 return;
2627 }
2628
2629 Record.clear();
2630 Expected<unsigned> MaybePP = Cursor.readRecord(Entry.ID, Record);
2631 if (!MaybePP) {
2632 Error(MaybePP.takeError());
2633 return;
2634 }
2635 switch ((PreprocessorRecordTypes)MaybePP.get()) {
2637 break;
2638
2639 case PP_MODULE_MACRO: {
2640 ModuleMacros.push_back(ModuleMacroRecord());
2641 auto &Info = ModuleMacros.back();
2642 unsigned Idx = 0;
2643 Info.SubModID = getGlobalSubmoduleID(M, Record[Idx++]);
2644 Info.MI = getMacro(ReadMacroID(M, Record, Idx));
2645 for (int I = Idx, N = Record.size(); I != N; ++I)
2646 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
2647 continue;
2648 }
2649
2650 default:
2651 Error("malformed block record in AST file");
2652 return;
2653 }
2654
2655 // We found the macro directive history; that's the last record
2656 // for this macro.
2657 break;
2658 }
2659
2660 // Module macros are listed in reverse dependency order.
2661 {
2662 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
2664 for (auto &MMR : ModuleMacros) {
2665 Overrides.clear();
2666 for (unsigned ModID : MMR.Overrides) {
2667 Module *Mod = getSubmodule(ModID);
2668 auto *Macro = PP.getModuleMacro(Mod, II);
2669 assert(Macro && "missing definition for overridden macro");
2670 Overrides.push_back(Macro);
2671 }
2672
2673 bool Inserted = false;
2674 Module *Owner = getSubmodule(MMR.SubModID);
2675 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
2676 }
2677 }
2678
2679 // Don't read the directive history for a module; we don't have anywhere
2680 // to put it.
2681 if (M.isModule())
2682 return;
2683
2684 // Deserialize the macro directives history in reverse source-order.
2685 MacroDirective *Latest = nullptr, *Earliest = nullptr;
2686 unsigned Idx = 0, N = Record.size();
2687 while (Idx < N) {
2688 MacroDirective *MD = nullptr;
2691 switch (K) {
2693 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
2694 MD = PP.AllocateDefMacroDirective(MI, Loc);
2695 break;
2696 }
2698 MD = PP.AllocateUndefMacroDirective(Loc);
2699 break;
2701 bool isPublic = Record[Idx++];
2702 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
2703 break;
2704 }
2705
2706 if (!Latest)
2707 Latest = MD;
2708 if (Earliest)
2709 Earliest->setPrevious(MD);
2710 Earliest = MD;
2711 }
2712
2713 if (Latest)
2714 PP.setLoadedMacroDirective(II, Earliest, Latest);
2715}
2716
2717bool ASTReader::shouldDisableValidationForFile(
2718 const serialization::ModuleFile &M) const {
2719 if (DisableValidationKind == DisableValidationForModuleKind::None)
2720 return false;
2721
2722 // If a PCH is loaded and validation is disabled for PCH then disable
2723 // validation for the PCH and the modules it loads.
2724 ModuleKind K = CurrentDeserializingModuleKind.value_or(M.Kind);
2725
2726 switch (K) {
2727 case MK_MainFile:
2728 case MK_Preamble:
2729 case MK_PCH:
2730 return bool(DisableValidationKind & DisableValidationForModuleKind::PCH);
2731 case MK_ImplicitModule:
2732 case MK_ExplicitModule:
2733 case MK_PrebuiltModule:
2734 return bool(DisableValidationKind & DisableValidationForModuleKind::Module);
2735 }
2736
2737 return false;
2738}
2739
2740static std::pair<StringRef, StringRef>
2742 const StringRef InputBlob) {
2743 uint16_t AsRequestedLength = Record[7];
2744 return {InputBlob.substr(0, AsRequestedLength),
2745 InputBlob.substr(AsRequestedLength)};
2746}
2747
2748InputFileInfo ASTReader::getInputFileInfo(ModuleFile &F, unsigned ID) {
2749 // If this ID is bogus, just return an empty input file.
2750 if (ID == 0 || ID > F.InputFileInfosLoaded.size())
2751 return InputFileInfo();
2752
2753 // If we've already loaded this input file, return it.
2754 if (F.InputFileInfosLoaded[ID - 1].isValid())
2755 return F.InputFileInfosLoaded[ID - 1];
2756
2757 // Go find this input file.
2758 BitstreamCursor &Cursor = F.InputFilesCursor;
2759 SavedStreamPosition SavedPosition(Cursor);
2760 if (llvm::Error Err = Cursor.JumpToBit(F.InputFilesOffsetBase +
2761 F.InputFileOffsets[ID - 1])) {
2762 // FIXME this drops errors on the floor.
2763 consumeError(std::move(Err));
2764 }
2765
2766 Expected<unsigned> MaybeCode = Cursor.ReadCode();
2767 if (!MaybeCode) {
2768 // FIXME this drops errors on the floor.
2769 consumeError(MaybeCode.takeError());
2770 }
2771 unsigned Code = MaybeCode.get();
2772 RecordData Record;
2773 StringRef Blob;
2774
2775 if (Expected<unsigned> Maybe = Cursor.readRecord(Code, Record, &Blob))
2776 assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE &&
2777 "invalid record type for input file");
2778 else {
2779 // FIXME this drops errors on the floor.
2780 consumeError(Maybe.takeError());
2781 }
2782
2783 assert(Record[0] == ID && "Bogus stored ID or offset");
2784 InputFileInfo R;
2785 R.StoredSize = static_cast<off_t>(Record[1]);
2786 R.StoredTime = static_cast<time_t>(Record[2]);
2787 R.Overridden = static_cast<bool>(Record[3]);
2788 R.Transient = static_cast<bool>(Record[4]);
2789 R.TopLevel = static_cast<bool>(Record[5]);
2790 R.ModuleMap = static_cast<bool>(Record[6]);
2791 auto [UnresolvedFilenameAsRequested, UnresolvedFilename] =
2793 R.UnresolvedImportedFilenameAsRequested = UnresolvedFilenameAsRequested;
2794 R.UnresolvedImportedFilename = UnresolvedFilename.empty()
2795 ? UnresolvedFilenameAsRequested
2796 : UnresolvedFilename;
2797
2798 Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
2799 if (!MaybeEntry) // FIXME this drops errors on the floor.
2800 consumeError(MaybeEntry.takeError());
2801 llvm::BitstreamEntry Entry = MaybeEntry.get();
2802 assert(Entry.Kind == llvm::BitstreamEntry::Record &&
2803 "expected record type for input file hash");
2804
2805 Record.clear();
2806 if (Expected<unsigned> Maybe = Cursor.readRecord(Entry.ID, Record))
2807 assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE_HASH &&
2808 "invalid record type for input file hash");
2809 else {
2810 // FIXME this drops errors on the floor.
2811 consumeError(Maybe.takeError());
2812 }
2813 R.ContentHash = (static_cast<uint64_t>(Record[1]) << 32) |
2814 static_cast<uint64_t>(Record[0]);
2815
2816 // Note that we've loaded this input file info.
2817 F.InputFileInfosLoaded[ID - 1] = R;
2818 return R;
2819}
2820
2821static unsigned moduleKindForDiagnostic(ModuleKind Kind);
2822InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
2823 // If this ID is bogus, just return an empty input file.
2824 if (ID == 0 || ID > F.InputFilesLoaded.size())
2825 return InputFile();
2826
2827 // If we've already loaded this input file, return it.
2828 if (F.InputFilesLoaded[ID-1].getFile())
2829 return F.InputFilesLoaded[ID-1];
2830
2831 if (F.InputFilesLoaded[ID-1].isNotFound())
2832 return InputFile();
2833
2834 // Go find this input file.
2835 BitstreamCursor &Cursor = F.InputFilesCursor;
2836 SavedStreamPosition SavedPosition(Cursor);
2837 if (llvm::Error Err = Cursor.JumpToBit(F.InputFilesOffsetBase +
2838 F.InputFileOffsets[ID - 1])) {
2839 // FIXME this drops errors on the floor.
2840 consumeError(std::move(Err));
2841 }
2842
2843 InputFileInfo FI = getInputFileInfo(F, ID);
2844 off_t StoredSize = FI.StoredSize;
2845 time_t StoredTime = FI.StoredTime;
2846 bool Overridden = FI.Overridden;
2847 bool Transient = FI.Transient;
2848 auto Filename =
2849 ResolveImportedPath(PathBuf, FI.UnresolvedImportedFilenameAsRequested, F);
2850 uint64_t StoredContentHash = FI.ContentHash;
2851
2852 // For standard C++ modules, we don't need to check the inputs.
2853 bool SkipChecks = F.StandardCXXModule;
2854
2855 const HeaderSearchOptions &HSOpts =
2856 PP.getHeaderSearchInfo().getHeaderSearchOpts();
2857
2858 // The option ForceCheckCXX20ModulesInputFiles is only meaningful for C++20
2859 // modules.
2861 SkipChecks = false;
2862 Overridden = false;
2863 }
2864
2865 auto File = FileMgr.getOptionalFileRef(*Filename, /*OpenFile=*/false);
2866
2867 // For an overridden file, create a virtual file with the stored
2868 // size/timestamp.
2869 if ((Overridden || Transient || SkipChecks) && !File)
2870 File = FileMgr.getVirtualFileRef(*Filename, StoredSize, StoredTime);
2871
2872 if (!File) {
2873 if (Complain) {
2874 std::string ErrorStr = "could not find file '";
2875 ErrorStr += *Filename;
2876 ErrorStr += "' referenced by AST file '";
2877 ErrorStr += F.FileName;
2878 ErrorStr += "'";
2879 Error(ErrorStr);
2880 }
2881 // Record that we didn't find the file.
2883 return InputFile();
2884 }
2885
2886 // Check if there was a request to override the contents of the file
2887 // that was part of the precompiled header. Overriding such a file
2888 // can lead to problems when lexing using the source locations from the
2889 // PCH.
2890 SourceManager &SM = getSourceManager();
2891 // FIXME: Reject if the overrides are different.
2892 if ((!Overridden && !Transient) && !SkipChecks &&
2893 SM.isFileOverridden(*File)) {
2894 if (Complain)
2895 Error(diag::err_fe_pch_file_overridden, *Filename);
2896
2897 // After emitting the diagnostic, bypass the overriding file to recover
2898 // (this creates a separate FileEntry).
2899 File = SM.bypassFileContentsOverride(*File);
2900 if (!File) {
2902 return InputFile();
2903 }
2904 }
2905
2906 struct Change {
2907 enum ModificationKind {
2908 Size,
2909 ModTime,
2910 Content,
2911 None,
2912 } Kind;
2913 std::optional<int64_t> Old = std::nullopt;
2914 std::optional<int64_t> New = std::nullopt;
2915 };
2916 auto HasInputContentChanged = [&](Change OriginalChange) {
2917 assert(ValidateASTInputFilesContent &&
2918 "We should only check the content of the inputs with "
2919 "ValidateASTInputFilesContent enabled.");
2920
2921 if (StoredContentHash == 0)
2922 return OriginalChange;
2923
2924 auto MemBuffOrError = FileMgr.getBufferForFile(*File);
2925 if (!MemBuffOrError) {
2926 if (!Complain)
2927 return OriginalChange;
2928 std::string ErrorStr = "could not get buffer for file '";
2929 ErrorStr += File->getName();
2930 ErrorStr += "'";
2931 Error(ErrorStr);
2932 return OriginalChange;
2933 }
2934
2935 auto ContentHash = xxh3_64bits(MemBuffOrError.get()->getBuffer());
2936 if (StoredContentHash == static_cast<uint64_t>(ContentHash))
2937 return Change{Change::None};
2938
2939 return Change{Change::Content};
2940 };
2941 auto HasInputFileChanged = [&]() {
2942 if (StoredSize != File->getSize())
2943 return Change{Change::Size, StoredSize, File->getSize()};
2944 if (!shouldDisableValidationForFile(F) && StoredTime &&
2945 StoredTime != File->getModificationTime()) {
2946 Change MTimeChange = {Change::ModTime, StoredTime,
2947 File->getModificationTime()};
2948
2949 // In case the modification time changes but not the content,
2950 // accept the cached file as legit.
2951 if (ValidateASTInputFilesContent)
2952 return HasInputContentChanged(MTimeChange);
2953
2954 return MTimeChange;
2955 }
2956 return Change{Change::None};
2957 };
2958
2959 bool IsOutOfDate = false;
2960 auto FileChange = SkipChecks ? Change{Change::None} : HasInputFileChanged();
2961 // When ForceCheckCXX20ModulesInputFiles and ValidateASTInputFilesContent
2962 // enabled, it is better to check the contents of the inputs. Since we can't
2963 // get correct modified time information for inputs from overriden inputs.
2964 if (HSOpts.ForceCheckCXX20ModulesInputFiles && ValidateASTInputFilesContent &&
2965 F.StandardCXXModule && FileChange.Kind == Change::None)
2966 FileChange = HasInputContentChanged(FileChange);
2967
2968 // When we have StoredTime equal to zero and ValidateASTInputFilesContent,
2969 // it is better to check the content of the input files because we cannot rely
2970 // on the file modification time, which will be the same (zero) for these
2971 // files.
2972 if (!StoredTime && ValidateASTInputFilesContent &&
2973 FileChange.Kind == Change::None)
2974 FileChange = HasInputContentChanged(FileChange);
2975
2976 // For an overridden file, there is nothing to validate.
2977 if (!Overridden && FileChange.Kind != Change::None) {
2978 if (Complain) {
2979 // Build a list of the PCH imports that got us here (in reverse).
2980 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2981 while (!ImportStack.back()->ImportedBy.empty())
2982 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
2983
2984 // The top-level AST file is stale.
2985 StringRef TopLevelASTFileName(ImportStack.back()->FileName);
2986 Diag(diag::err_fe_ast_file_modified)
2987 << *Filename << moduleKindForDiagnostic(ImportStack.back()->Kind)
2988 << TopLevelASTFileName;
2989 Diag(diag::note_fe_ast_file_modified)
2990 << FileChange.Kind << (FileChange.Old && FileChange.New)
2991 << llvm::itostr(FileChange.Old.value_or(0))
2992 << llvm::itostr(FileChange.New.value_or(0));
2993
2994 // Print the import stack.
2995 if (ImportStack.size() > 1) {
2996 Diag(diag::note_ast_file_required_by)
2997 << *Filename << ImportStack[0]->FileName;
2998 for (unsigned I = 1; I < ImportStack.size(); ++I)
2999 Diag(diag::note_ast_file_required_by)
3000 << ImportStack[I - 1]->FileName << ImportStack[I]->FileName;
3001 }
3002
3004 Diag(diag::note_ast_file_rebuild_required) << TopLevelASTFileName;
3005 Diag(diag::note_ast_file_input_files_validation_status)
3007 }
3008
3009 IsOutOfDate = true;
3010 }
3011 // FIXME: If the file is overridden and we've already opened it,
3012 // issue an error (or split it into a separate FileEntry).
3013
3014 InputFile IF = InputFile(*File, Overridden || Transient, IsOutOfDate);
3015
3016 // Note that we've loaded this input file.
3017 F.InputFilesLoaded[ID-1] = IF;
3018 return IF;
3019}
3020
3021ASTReader::TemporarilyOwnedStringRef
3023 ModuleFile &ModF) {
3024 return ResolveImportedPath(Buf, Path, ModF.BaseDirectory);
3025}
3026
3027ASTReader::TemporarilyOwnedStringRef
3029 StringRef Prefix) {
3030 assert(Buf.capacity() != 0 && "Overlapping ResolveImportedPath calls");
3031
3032 if (Prefix.empty() || Path.empty() || llvm::sys::path::is_absolute(Path) ||
3033 Path == "<built-in>" || Path == "<command line>")
3034 return {Path, Buf};
3035
3036 Buf.clear();
3037 llvm::sys::path::append(Buf, Prefix, Path);
3038 StringRef ResolvedPath{Buf.data(), Buf.size()};
3039 return {ResolvedPath, Buf};
3040}
3041
3043 StringRef P,
3044 ModuleFile &ModF) {
3045 return ResolveImportedPathAndAllocate(Buf, P, ModF.BaseDirectory);
3046}
3047
3049 StringRef P,
3050 StringRef Prefix) {
3051 auto ResolvedPath = ResolveImportedPath(Buf, P, Prefix);
3052 return ResolvedPath->str();
3053}
3054
3055static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
3056 switch (ARR) {
3057 case ASTReader::Failure: return true;
3058 case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
3059 case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
3062 return !(Caps & ASTReader::ARR_ConfigurationMismatch);
3063 case ASTReader::HadErrors: return true;
3064 case ASTReader::Success: return false;
3065 }
3066
3067 llvm_unreachable("unknown ASTReadResult");
3068}
3069
3070ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(
3071 BitstreamCursor &Stream, StringRef Filename,
3072 unsigned ClientLoadCapabilities, bool AllowCompatibleConfigurationMismatch,
3073 ASTReaderListener &Listener, std::string &SuggestedPredefines) {
3074 if (llvm::Error Err = Stream.EnterSubBlock(OPTIONS_BLOCK_ID)) {
3075 // FIXME this drops errors on the floor.
3076 consumeError(std::move(Err));
3077 return Failure;
3078 }
3079
3080 // Read all of the records in the options block.
3081 RecordData Record;
3082 ASTReadResult Result = Success;
3083 while (true) {
3084 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
3085 if (!MaybeEntry) {
3086 // FIXME this drops errors on the floor.
3087 consumeError(MaybeEntry.takeError());
3088 return Failure;
3089 }
3090 llvm::BitstreamEntry Entry = MaybeEntry.get();
3091
3092 switch (Entry.Kind) {
3093 case llvm::BitstreamEntry::Error:
3094 case llvm::BitstreamEntry::SubBlock:
3095 return Failure;
3096
3097 case llvm::BitstreamEntry::EndBlock:
3098 return Result;
3099
3100 case llvm::BitstreamEntry::Record:
3101 // The interesting case.
3102 break;
3103 }
3104
3105 // Read and process a record.
3106 Record.clear();
3107 Expected<unsigned> MaybeRecordType = Stream.readRecord(Entry.ID, Record);
3108 if (!MaybeRecordType) {
3109 // FIXME this drops errors on the floor.
3110 consumeError(MaybeRecordType.takeError());
3111 return Failure;
3112 }
3113 switch ((OptionsRecordTypes)MaybeRecordType.get()) {
3114 case LANGUAGE_OPTIONS: {
3115 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
3116 if (ParseLanguageOptions(Record, Filename, Complain, Listener,
3117 AllowCompatibleConfigurationMismatch))
3118 Result = ConfigurationMismatch;
3119 break;
3120 }
3121
3122 case CODEGEN_OPTIONS: {
3123 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
3124 if (ParseCodeGenOptions(Record, Filename, Complain, Listener,
3125 AllowCompatibleConfigurationMismatch))
3126 Result = ConfigurationMismatch;
3127 break;
3128 }
3129
3130 case TARGET_OPTIONS: {
3131 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
3132 if (ParseTargetOptions(Record, Filename, Complain, Listener,
3133 AllowCompatibleConfigurationMismatch))
3134 Result = ConfigurationMismatch;
3135 break;
3136 }
3137
3138 case FILE_SYSTEM_OPTIONS: {
3139 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
3140 if (!AllowCompatibleConfigurationMismatch &&
3141 ParseFileSystemOptions(Record, Complain, Listener))
3142 Result = ConfigurationMismatch;
3143 break;
3144 }
3145
3146 case HEADER_SEARCH_OPTIONS: {
3147 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
3148 if (!AllowCompatibleConfigurationMismatch &&
3149 ParseHeaderSearchOptions(Record, Filename, Complain, Listener))
3150 Result = ConfigurationMismatch;
3151 break;
3152 }
3153
3155 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
3156 if (!AllowCompatibleConfigurationMismatch &&
3157 ParsePreprocessorOptions(Record, Filename, Complain, Listener,
3158 SuggestedPredefines))
3159 Result = ConfigurationMismatch;
3160 break;
3161 }
3162 }
3163}
3164
3165ASTReader::RelocationResult
3166ASTReader::getModuleForRelocationChecks(ModuleFile &F, bool DirectoryCheck) {
3167 // Don't emit module relocation errors if we have -fno-validate-pch.
3168 const bool IgnoreError =
3169 bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation &
3171
3172 if (!PP.getPreprocessorOpts().ModulesCheckRelocated)
3173 return {std::nullopt, IgnoreError};
3174
3175 const bool IsImplicitModule = F.Kind == MK_ImplicitModule;
3176
3177 if (!DirectoryCheck &&
3178 (!IsImplicitModule || ModuleMgr.begin()->Kind == MK_MainFile))
3179 return {std::nullopt, IgnoreError};
3180
3181 const HeaderSearchOptions &HSOpts =
3182 PP.getHeaderSearchInfo().getHeaderSearchOpts();
3183
3184 // When only validating modules once per build session,
3185 // Skip check if the timestamp is up to date or module was built in same build
3186 // session.
3187 if (HSOpts.ModulesValidateOncePerBuildSession && IsImplicitModule) {
3189 return {std::nullopt, IgnoreError};
3190 if (static_cast<uint64_t>(F.File.getModificationTime()) >=
3191 HSOpts.BuildSessionTimestamp)
3192 return {std::nullopt, IgnoreError};
3193 }
3194
3195 Diag(diag::remark_module_check_relocation) << F.ModuleName << F.FileName;
3196
3197 // If we've already loaded a module map file covering this module, we may
3198 // have a better path for it (relative to the current build if doing directory
3199 // check).
3200 Module *M = PP.getHeaderSearchInfo().lookupModule(
3201 F.ModuleName, DirectoryCheck ? SourceLocation() : F.ImportLoc,
3202 /*AllowSearch=*/DirectoryCheck,
3203 /*AllowExtraModuleMapSearch=*/DirectoryCheck);
3204
3205 return {M, IgnoreError};
3206}
3207
3209ASTReader::ReadControlBlock(ModuleFile &F,
3210 SmallVectorImpl<ImportedModule> &Loaded,
3211 const ModuleFile *ImportedBy,
3212 unsigned ClientLoadCapabilities) {
3213 BitstreamCursor &Stream = F.Stream;
3214
3215 if (llvm::Error Err = Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
3216 Error(std::move(Err));
3217 return Failure;
3218 }
3219
3220 // Lambda to read the unhashed control block the first time it's called.
3221 //
3222 // For PCM files, the unhashed control block cannot be read until after the
3223 // MODULE_NAME record. However, PCH files have no MODULE_NAME, and yet still
3224 // need to look ahead before reading the IMPORTS record. For consistency,
3225 // this block is always read somehow (see BitstreamEntry::EndBlock).
3226 bool HasReadUnhashedControlBlock = false;
3227 auto readUnhashedControlBlockOnce = [&]() {
3228 if (!HasReadUnhashedControlBlock) {
3229 HasReadUnhashedControlBlock = true;
3230 if (ASTReadResult Result =
3231 readUnhashedControlBlock(F, ImportedBy, ClientLoadCapabilities))
3232 return Result;
3233 }
3234 return Success;
3235 };
3236
3237 bool DisableValidation = shouldDisableValidationForFile(F);
3238
3239 // Read all of the records and blocks in the control block.
3240 RecordData Record;
3241 unsigned NumInputs = 0;
3242 unsigned NumUserInputs = 0;
3243 StringRef BaseDirectoryAsWritten;
3244 while (true) {
3245 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
3246 if (!MaybeEntry) {
3247 Error(MaybeEntry.takeError());
3248 return Failure;
3249 }
3250 llvm::BitstreamEntry Entry = MaybeEntry.get();
3251
3252 switch (Entry.Kind) {
3253 case llvm::BitstreamEntry::Error:
3254 Error("malformed block record in AST file");
3255 return Failure;
3256 case llvm::BitstreamEntry::EndBlock: {
3257 // Validate the module before returning. This call catches an AST with
3258 // no module name and no imports.
3259 if (ASTReadResult Result = readUnhashedControlBlockOnce())
3260 return Result;
3261
3262 // Validate input files.
3263 const HeaderSearchOptions &HSOpts =
3264 PP.getHeaderSearchInfo().getHeaderSearchOpts();
3265
3266 // All user input files reside at the index range [0, NumUserInputs), and
3267 // system input files reside at [NumUserInputs, NumInputs). For explicitly
3268 // loaded module files, ignore missing inputs.
3269 if (!DisableValidation && F.Kind != MK_ExplicitModule &&
3270 F.Kind != MK_PrebuiltModule) {
3271 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
3272
3273 // If we are reading a module, we will create a verification timestamp,
3274 // so we verify all input files. Otherwise, verify only user input
3275 // files.
3276
3277 unsigned N = ValidateSystemInputs ? NumInputs : NumUserInputs;
3278 F.InputFilesValidationStatus = ValidateSystemInputs
3283 F.Kind == MK_ImplicitModule) {
3284 N = ForceValidateUserInputs ? NumUserInputs : 0;
3286 ForceValidateUserInputs
3289 }
3290
3291 if (N != 0)
3292 Diag(diag::remark_module_validation)
3293 << N << F.ModuleName << F.FileName;
3294
3295 for (unsigned I = 0; I < N; ++I) {
3296 InputFile IF = getInputFile(F, I+1, Complain);
3297 if (!IF.getFile() || IF.isOutOfDate())
3298 return OutOfDate;
3299 }
3300 } else {
3302 }
3303
3304 if (Listener)
3305 Listener->visitModuleFile(F.FileName, F.Kind);
3306
3307 if (Listener && Listener->needsInputFileVisitation()) {
3308 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
3309 : NumUserInputs;
3310 for (unsigned I = 0; I < N; ++I) {
3311 bool IsSystem = I >= NumUserInputs;
3312 InputFileInfo FI = getInputFileInfo(F, I + 1);
3313 auto FilenameAsRequested = ResolveImportedPath(
3315 Listener->visitInputFile(
3316 *FilenameAsRequested, IsSystem, FI.Overridden,
3318 }
3319 }
3320
3321 return Success;
3322 }
3323
3324 case llvm::BitstreamEntry::SubBlock:
3325 switch (Entry.ID) {
3327 F.InputFilesCursor = Stream;
3328 if (llvm::Error Err = Stream.SkipBlock()) {
3329 Error(std::move(Err));
3330 return Failure;
3331 }
3332 if (ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
3333 Error("malformed block record in AST file");
3334 return Failure;
3335 }
3336 F.InputFilesOffsetBase = F.InputFilesCursor.GetCurrentBitNo();
3337 continue;
3338
3339 case OPTIONS_BLOCK_ID:
3340 // If we're reading the first module for this group, check its options
3341 // are compatible with ours. For modules it imports, no further checking
3342 // is required, because we checked them when we built it.
3343 if (Listener && !ImportedBy) {
3344 // Should we allow the configuration of the module file to differ from
3345 // the configuration of the current translation unit in a compatible
3346 // way?
3347 //
3348 // FIXME: Allow this for files explicitly specified with -include-pch.
3349 bool AllowCompatibleConfigurationMismatch =
3351
3352 ASTReadResult Result =
3353 ReadOptionsBlock(Stream, F.FileName, ClientLoadCapabilities,
3354 AllowCompatibleConfigurationMismatch, *Listener,
3355 SuggestedPredefines);
3356 if (Result == Failure) {
3357 Error("malformed block record in AST file");
3358 return Result;
3359 }
3360
3361 if (DisableValidation ||
3362 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
3363 Result = Success;
3364
3365 // If we can't load the module, exit early since we likely
3366 // will rebuild the module anyway. The stream may be in the
3367 // middle of a block.
3368 if (Result != Success)
3369 return Result;
3370 } else if (llvm::Error Err = Stream.SkipBlock()) {
3371 Error(std::move(Err));
3372 return Failure;
3373 }
3374 continue;
3375
3376 default:
3377 if (llvm::Error Err = Stream.SkipBlock()) {
3378 Error(std::move(Err));
3379 return Failure;
3380 }
3381 continue;
3382 }
3383
3384 case llvm::BitstreamEntry::Record:
3385 // The interesting case.
3386 break;
3387 }
3388
3389 // Read and process a record.
3390 Record.clear();
3391 StringRef Blob;
3392 Expected<unsigned> MaybeRecordType =
3393 Stream.readRecord(Entry.ID, Record, &Blob);
3394 if (!MaybeRecordType) {
3395 Error(MaybeRecordType.takeError());
3396 return Failure;
3397 }
3398 switch ((ControlRecordTypes)MaybeRecordType.get()) {
3399 case METADATA: {
3400 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
3401 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
3402 Diag(Record[0] < VERSION_MAJOR ? diag::err_ast_file_version_too_old
3403 : diag::err_ast_file_version_too_new)
3405 return VersionMismatch;
3406 }
3407
3408 bool hasErrors = Record[7];
3409 if (hasErrors && !DisableValidation) {
3410 // If requested by the caller and the module hasn't already been read
3411 // or compiled, mark modules on error as out-of-date.
3412 if ((ClientLoadCapabilities & ARR_TreatModuleWithErrorsAsOutOfDate) &&
3413 canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
3414 return OutOfDate;
3415
3416 if (!AllowASTWithCompilerErrors) {
3417 Diag(diag::err_ast_file_with_compiler_errors)
3419 return HadErrors;
3420 }
3421 }
3422 if (hasErrors) {
3423 Diags.ErrorOccurred = true;
3424 Diags.UncompilableErrorOccurred = true;
3425 Diags.UnrecoverableErrorOccurred = true;
3426 }
3427
3428 F.RelocatablePCH = Record[4];
3429 // Relative paths in a relocatable PCH are relative to our sysroot.
3430 if (F.RelocatablePCH)
3431 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
3432
3434
3435 F.HasTimestamps = Record[6];
3436
3437 const std::string &CurBranch = getClangFullRepositoryVersion();
3438 StringRef ASTBranch = Blob;
3439 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
3440 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
3441 Diag(diag::err_ast_file_different_branch)
3442 << moduleKindForDiagnostic(F.Kind) << F.FileName << ASTBranch
3443 << CurBranch;
3444 return VersionMismatch;
3445 }
3446 break;
3447 }
3448
3449 case IMPORT: {
3450 // Validate the AST before processing any imports (otherwise, untangling
3451 // them can be error-prone and expensive). A module will have a name and
3452 // will already have been validated, but this catches the PCH case.
3453 if (ASTReadResult Result = readUnhashedControlBlockOnce())
3454 return Result;
3455
3456 unsigned Idx = 0;
3457 // Read information about the AST file.
3458 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
3459
3460 // The import location will be the local one for now; we will adjust
3461 // all import locations of module imports after the global source
3462 // location info are setup, in ReadAST.
3463 auto [ImportLoc, ImportModuleFileIndex] =
3464 ReadUntranslatedSourceLocation(Record[Idx++]);
3465 // The import location must belong to the current module file itself.
3466 assert(ImportModuleFileIndex == 0);
3467
3468 StringRef ImportedName = ReadStringBlob(Record, Idx, Blob);
3469
3470 bool IsImportingStdCXXModule = Record[Idx++];
3471
3472 off_t StoredSize = 0;
3473 time_t StoredModTime = 0;
3474 ASTFileSignature StoredSignature;
3475 std::string ImportedFile;
3476 std::string StoredFile;
3477 bool IgnoreImportedByNote = false;
3478
3479 // For prebuilt and explicit modules first consult the file map for
3480 // an override. Note that here we don't search prebuilt module
3481 // directories if we're not importing standard c++ module, only the
3482 // explicit name to file mappings. Also, we will still verify the
3483 // size/signature making sure it is essentially the same file but
3484 // perhaps in a different location.
3485 if (ImportedKind == MK_PrebuiltModule || ImportedKind == MK_ExplicitModule)
3486 ImportedFile = PP.getHeaderSearchInfo().getPrebuiltModuleFileName(
3487 ImportedName, /*FileMapOnly*/ !IsImportingStdCXXModule);
3488
3489 if (IsImportingStdCXXModule && ImportedFile.empty()) {
3490 Diag(diag::err_failed_to_find_module_file) << ImportedName;
3491 return Missing;
3492 }
3493
3494 if (!IsImportingStdCXXModule) {
3495 StoredSize = (off_t)Record[Idx++];
3496 StoredModTime = (time_t)Record[Idx++];
3497
3498 StringRef SignatureBytes = Blob.substr(0, ASTFileSignature::size);
3499 StoredSignature = ASTFileSignature::create(SignatureBytes.begin(),
3500 SignatureBytes.end());
3501 Blob = Blob.substr(ASTFileSignature::size);
3502
3503 // Use BaseDirectoryAsWritten to ensure we use the same path in the
3504 // ModuleCache as when writing.
3505 StoredFile = ReadPathBlob(BaseDirectoryAsWritten, Record, Idx, Blob);
3506 if (ImportedFile.empty()) {
3507 ImportedFile = StoredFile;
3508 } else if (!getDiags().isIgnored(
3509 diag::warn_module_file_mapping_mismatch,
3510 CurrentImportLoc)) {
3511 auto ImportedFileRef =
3512 PP.getFileManager().getOptionalFileRef(ImportedFile);
3513 auto StoredFileRef =
3514 PP.getFileManager().getOptionalFileRef(StoredFile);
3515 if ((ImportedFileRef && StoredFileRef) &&
3516 (*ImportedFileRef != *StoredFileRef)) {
3517 Diag(diag::warn_module_file_mapping_mismatch)
3518 << ImportedFile << StoredFile;
3519 Diag(diag::note_module_file_imported_by)
3520 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
3521 IgnoreImportedByNote = true;
3522 }
3523 }
3524 }
3525
3526 // If our client can't cope with us being out of date, we can't cope with
3527 // our dependency being missing.
3528 unsigned Capabilities = ClientLoadCapabilities;
3529 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3530 Capabilities &= ~ARR_Missing;
3531
3532 // Load the AST file.
3533 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
3534 Loaded, StoredSize, StoredModTime,
3535 StoredSignature, Capabilities);
3536
3537 // Check the AST we just read from ImportedFile contains a different
3538 // module than we expected (ImportedName). This can occur for C++20
3539 // Modules when given a mismatch via -fmodule-file=<name>=<file>
3540 if (IsImportingStdCXXModule) {
3541 if (const auto *Imported =
3542 getModuleManager().lookupByFileName(ImportedFile);
3543 Imported != nullptr && Imported->ModuleName != ImportedName) {
3544 Diag(diag::err_failed_to_find_module_file) << ImportedName;
3545 Result = Missing;
3546 }
3547 }
3548
3549 // If we diagnosed a problem, produce a backtrace.
3550 bool recompilingFinalized = Result == OutOfDate &&
3551 (Capabilities & ARR_OutOfDate) &&
3552 getModuleManager()
3553 .getModuleCache()
3554 .getInMemoryModuleCache()
3555 .isPCMFinal(F.FileName);
3556 if (!IgnoreImportedByNote &&
3557 (isDiagnosedResult(Result, Capabilities) || recompilingFinalized))
3558 Diag(diag::note_module_file_imported_by)
3559 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
3560
3561 switch (Result) {
3562 case Failure: return Failure;
3563 // If we have to ignore the dependency, we'll have to ignore this too.
3564 case Missing:
3565 case OutOfDate: return OutOfDate;
3566 case VersionMismatch: return VersionMismatch;
3567 case ConfigurationMismatch: return ConfigurationMismatch;
3568 case HadErrors: return HadErrors;
3569 case Success: break;
3570 }
3571 break;
3572 }
3573
3574 case ORIGINAL_FILE:
3575 F.OriginalSourceFileID = FileID::get(Record[0]);
3576 F.ActualOriginalSourceFileName = std::string(Blob);
3577 F.OriginalSourceFileName = ResolveImportedPathAndAllocate(
3578 PathBuf, F.ActualOriginalSourceFileName, F);
3579 break;
3580
3581 case ORIGINAL_FILE_ID:
3582 F.OriginalSourceFileID = FileID::get(Record[0]);
3583 break;
3584
3585 case MODULE_NAME:
3586 F.ModuleName = std::string(Blob);
3587 Diag(diag::remark_module_import)
3588 << F.ModuleName << F.FileName << (ImportedBy ? true : false)
3589 << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());
3590 if (Listener)
3591 Listener->ReadModuleName(F.ModuleName);
3592
3593 // Validate the AST as soon as we have a name so we can exit early on
3594 // failure.
3595 if (ASTReadResult Result = readUnhashedControlBlockOnce())
3596 return Result;
3597
3598 break;
3599
3600 case MODULE_DIRECTORY: {
3601 // Save the BaseDirectory as written in the PCM for computing the module
3602 // filename for the ModuleCache.
3603 BaseDirectoryAsWritten = Blob;
3604 assert(!F.ModuleName.empty() &&
3605 "MODULE_DIRECTORY found before MODULE_NAME");
3606 F.BaseDirectory = std::string(Blob);
3607
3608 auto [MaybeM, IgnoreError] =
3609 getModuleForRelocationChecks(F, /*DirectoryCheck=*/true);
3610 if (!MaybeM.has_value())
3611 break;
3612
3613 Module *M = MaybeM.value();
3614 if (!M || !M->Directory)
3615 break;
3616 if (IgnoreError) {
3617 F.BaseDirectory = std::string(M->Directory->getName());
3618 break;
3619 }
3620 if ((F.Kind == MK_ExplicitModule) || (F.Kind == MK_PrebuiltModule))
3621 break;
3622
3623 // If we're implicitly loading a module, the base directory can't
3624 // change between the build and use.
3625 auto BuildDir = PP.getFileManager().getOptionalDirectoryRef(Blob);
3626 if (BuildDir && (*BuildDir == M->Directory)) {
3627 F.BaseDirectory = std::string(M->Directory->getName());
3628 break;
3629 }
3630 Diag(diag::remark_module_relocated)
3631 << F.ModuleName << Blob << M->Directory->getName();
3632
3633 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
3634 Diag(diag::err_imported_module_relocated)
3635 << F.ModuleName << Blob << M->Directory->getName();
3636 return OutOfDate;
3637 }
3638
3639 case MODULE_MAP_FILE:
3640 if (ASTReadResult Result =
3641 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
3642 return Result;
3643 break;
3644
3645 case INPUT_FILE_OFFSETS:
3646 NumInputs = Record[0];
3647 NumUserInputs = Record[1];
3649 (const llvm::support::unaligned_uint64_t *)Blob.data();
3650 F.InputFilesLoaded.resize(NumInputs);
3651 F.InputFileInfosLoaded.resize(NumInputs);
3652 F.NumUserInputFiles = NumUserInputs;
3653 break;
3654 }
3655 }
3656}
3657
3658llvm::Error ASTReader::ReadASTBlock(ModuleFile &F,
3659 unsigned ClientLoadCapabilities) {
3660 BitstreamCursor &Stream = F.Stream;
3661
3662 if (llvm::Error Err = Stream.EnterSubBlock(AST_BLOCK_ID))
3663 return Err;
3664 F.ASTBlockStartOffset = Stream.GetCurrentBitNo();
3665
3666 // Read all of the records and blocks for the AST file.
3667 RecordData Record;
3668 while (true) {
3669 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
3670 if (!MaybeEntry)
3671 return MaybeEntry.takeError();
3672 llvm::BitstreamEntry Entry = MaybeEntry.get();
3673
3674 switch (Entry.Kind) {
3675 case llvm::BitstreamEntry::Error:
3676 return llvm::createStringError(
3677 std::errc::illegal_byte_sequence,
3678 "error at end of module block in AST file");
3679 case llvm::BitstreamEntry::EndBlock:
3680 // Outside of C++, we do not store a lookup map for the translation unit.
3681 // Instead, mark it as needing a lookup map to be built if this module
3682 // contains any declarations lexically within it (which it always does!).
3683 // This usually has no cost, since we very rarely need the lookup map for
3684 // the translation unit outside C++.
3685 if (ASTContext *Ctx = ContextObj) {
3686 DeclContext *DC = Ctx->getTranslationUnitDecl();
3687 if (DC->hasExternalLexicalStorage() && !Ctx->getLangOpts().CPlusPlus)
3689 }
3690
3691 return llvm::Error::success();
3692 case llvm::BitstreamEntry::SubBlock:
3693 switch (Entry.ID) {
3694 case DECLTYPES_BLOCK_ID:
3695 // We lazily load the decls block, but we want to set up the
3696 // DeclsCursor cursor to point into it. Clone our current bitcode
3697 // cursor to it, enter the block and read the abbrevs in that block.
3698 // With the main cursor, we just skip over it.
3699 F.DeclsCursor = Stream;
3700 if (llvm::Error Err = Stream.SkipBlock())
3701 return Err;
3702 if (llvm::Error Err = ReadBlockAbbrevs(
3704 return Err;
3705 break;
3706
3708 F.MacroCursor = Stream;
3709 if (!PP.getExternalSource())
3710 PP.setExternalSource(this);
3711
3712 if (llvm::Error Err = Stream.SkipBlock())
3713 return Err;
3714 if (llvm::Error Err =
3715 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID))
3716 return Err;
3717 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
3718 break;
3719
3721 F.PreprocessorDetailCursor = Stream;
3722
3723 if (llvm::Error Err = Stream.SkipBlock()) {
3724 return Err;
3725 }
3726 if (llvm::Error Err = ReadBlockAbbrevs(F.PreprocessorDetailCursor,
3728 return Err;
3730 = F.PreprocessorDetailCursor.GetCurrentBitNo();
3731
3732 if (!PP.getPreprocessingRecord())
3733 PP.createPreprocessingRecord();
3734 if (!PP.getPreprocessingRecord()->getExternalSource())
3735 PP.getPreprocessingRecord()->SetExternalSource(*this);
3736 break;
3737
3739 if (llvm::Error Err = ReadSourceManagerBlock(F))
3740 return Err;
3741 break;
3742
3743 case SUBMODULE_BLOCK_ID:
3744 if (llvm::Error Err = ReadSubmoduleBlock(F, ClientLoadCapabilities))
3745 return Err;
3746 break;
3747
3748 case COMMENTS_BLOCK_ID: {
3749 BitstreamCursor C = Stream;
3750
3751 if (llvm::Error Err = Stream.SkipBlock())
3752 return Err;
3753 if (llvm::Error Err = ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID))
3754 return Err;
3755 CommentsCursors.push_back(std::make_pair(C, &F));
3756 break;
3757 }
3758
3759 default:
3760 if (llvm::Error Err = Stream.SkipBlock())
3761 return Err;
3762 break;
3763 }
3764 continue;
3765
3766 case llvm::BitstreamEntry::Record:
3767 // The interesting case.
3768 break;
3769 }
3770
3771 // Read and process a record.
3772 Record.clear();
3773 StringRef Blob;
3774 Expected<unsigned> MaybeRecordType =
3775 Stream.readRecord(Entry.ID, Record, &Blob);
3776 if (!MaybeRecordType)
3777 return MaybeRecordType.takeError();
3778 ASTRecordTypes RecordType = (ASTRecordTypes)MaybeRecordType.get();
3779
3780 // If we're not loading an AST context, we don't care about most records.
3781 if (!ContextObj) {
3782 switch (RecordType) {
3783 case IDENTIFIER_TABLE:
3784 case IDENTIFIER_OFFSET:
3786 case STATISTICS:
3789 case PP_COUNTER_VALUE:
3791 case MODULE_OFFSET_MAP:
3795 case IMPORTED_MODULES:
3796 case MACRO_OFFSET:
3797 break;
3798 default:
3799 continue;
3800 }
3801 }
3802
3803 switch (RecordType) {
3804 default: // Default behavior: ignore.
3805 break;
3806
3807 case TYPE_OFFSET: {
3808 if (F.LocalNumTypes != 0)
3809 return llvm::createStringError(
3810 std::errc::illegal_byte_sequence,
3811 "duplicate TYPE_OFFSET record in AST file");
3812 F.TypeOffsets = reinterpret_cast<const UnalignedUInt64 *>(Blob.data());
3813 F.LocalNumTypes = Record[0];
3814 F.BaseTypeIndex = getTotalNumTypes();
3815
3816 if (F.LocalNumTypes > 0)
3817 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
3818
3819 break;
3820 }
3821
3822 case DECL_OFFSET: {
3823 if (F.LocalNumDecls != 0)
3824 return llvm::createStringError(
3825 std::errc::illegal_byte_sequence,
3826 "duplicate DECL_OFFSET record in AST file");
3827 F.DeclOffsets = (const DeclOffset *)Blob.data();
3828 F.LocalNumDecls = Record[0];
3829 F.BaseDeclIndex = getTotalNumDecls();
3830
3831 if (F.LocalNumDecls > 0)
3832 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
3833
3834 break;
3835 }
3836
3837 case TU_UPDATE_LEXICAL: {
3838 DeclContext *TU = ContextObj->getTranslationUnitDecl();
3839 LexicalContents Contents(
3840 reinterpret_cast<const unaligned_decl_id_t *>(Blob.data()),
3841 static_cast<unsigned int>(Blob.size() / sizeof(DeclID)));
3842 TULexicalDecls.push_back(std::make_pair(&F, Contents));
3844 break;
3845 }
3846
3847 case UPDATE_VISIBLE: {
3848 unsigned Idx = 0;
3849 GlobalDeclID ID = ReadDeclID(F, Record, Idx);
3850 auto *Data = (const unsigned char*)Blob.data();
3851 PendingVisibleUpdates[ID].push_back(UpdateData{&F, Data});
3852 // If we've already loaded the decl, perform the updates when we finish
3853 // loading this block.
3854 if (Decl *D = GetExistingDecl(ID))
3855 PendingUpdateRecords.push_back(
3856 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3857 break;
3858 }
3859
3861 unsigned Idx = 0;
3862 GlobalDeclID ID = ReadDeclID(F, Record, Idx);
3863 auto *Data = (const unsigned char *)Blob.data();
3864 PendingModuleLocalVisibleUpdates[ID].push_back(UpdateData{&F, Data});
3865 // If we've already loaded the decl, perform the updates when we finish
3866 // loading this block.
3867 if (Decl *D = GetExistingDecl(ID))
3868 PendingUpdateRecords.push_back(
3869 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3870 break;
3871 }
3872
3874 if (F.Kind != MK_MainFile)
3875 break;
3876 unsigned Idx = 0;
3877 GlobalDeclID ID = ReadDeclID(F, Record, Idx);
3878 auto *Data = (const unsigned char *)Blob.data();
3879 TULocalUpdates[ID].push_back(UpdateData{&F, Data});
3880 // If we've already loaded the decl, perform the updates when we finish
3881 // loading this block.
3882 if (Decl *D = GetExistingDecl(ID))
3883 PendingUpdateRecords.push_back(
3884 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3885 break;
3886 }
3887
3889 unsigned Idx = 0;
3890 GlobalDeclID ID = ReadDeclID(F, Record, Idx);
3891 auto *Data = (const unsigned char *)Blob.data();
3892 PendingSpecializationsUpdates[ID].push_back(UpdateData{&F, Data});
3893 // If we've already loaded the decl, perform the updates when we finish
3894 // loading this block.
3895 if (Decl *D = GetExistingDecl(ID))
3896 PendingUpdateRecords.push_back(
3897 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3898 break;
3899 }
3900
3902 unsigned Idx = 0;
3903 GlobalDeclID ID = ReadDeclID(F, Record, Idx);
3904 auto *Data = (const unsigned char *)Blob.data();
3905 PendingPartialSpecializationsUpdates[ID].push_back(UpdateData{&F, Data});
3906 // If we've already loaded the decl, perform the updates when we finish
3907 // loading this block.
3908 if (Decl *D = GetExistingDecl(ID))
3909 PendingUpdateRecords.push_back(
3910 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3911 break;
3912 }
3913
3914 case IDENTIFIER_TABLE:
3916 reinterpret_cast<const unsigned char *>(Blob.data());
3917 if (Record[0]) {
3918 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
3920 F.IdentifierTableData + sizeof(uint32_t),
3922 ASTIdentifierLookupTrait(*this, F));
3923
3924 PP.getIdentifierTable().setExternalIdentifierLookup(this);
3925 }
3926 break;
3927
3928 case IDENTIFIER_OFFSET: {
3929 if (F.LocalNumIdentifiers != 0)
3930 return llvm::createStringError(
3931 std::errc::illegal_byte_sequence,
3932 "duplicate IDENTIFIER_OFFSET record in AST file");
3933 F.IdentifierOffsets = (const uint32_t *)Blob.data();
3935 F.BaseIdentifierID = getTotalNumIdentifiers();
3936
3937 if (F.LocalNumIdentifiers > 0)
3938 IdentifiersLoaded.resize(IdentifiersLoaded.size()
3940 break;
3941 }
3942
3944 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
3945 break;
3946
3948 // FIXME: Skip reading this record if our ASTConsumer doesn't care
3949 // about "interesting" decls (for instance, if we're building a module).
3950 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
3951 EagerlyDeserializedDecls.push_back(ReadDeclID(F, Record, I));
3952 break;
3953
3955 // FIXME: Skip reading this record if our ASTConsumer doesn't care about
3956 // them (ie: if we're not codegenerating this module).
3957 if (F.Kind == MK_MainFile ||
3958 getContext().getLangOpts().BuildingPCHWithObjectFile)
3959 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
3960 EagerlyDeserializedDecls.push_back(ReadDeclID(F, Record, I));
3961 break;
3962
3963 case SPECIAL_TYPES:
3964 if (SpecialTypes.empty()) {
3965 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3966 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
3967 break;
3968 }
3969
3970 if (Record.empty())
3971 break;
3972
3973 if (SpecialTypes.size() != Record.size())
3974 return llvm::createStringError(std::errc::illegal_byte_sequence,
3975 "invalid special-types record");
3976
3977 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
3978 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
3979 if (!SpecialTypes[I])
3980 SpecialTypes[I] = ID;
3981 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
3982 // merge step?
3983 }
3984 break;
3985
3986 case STATISTICS:
3987 TotalNumStatements += Record[0];
3988 TotalNumMacros += Record[1];
3989 TotalLexicalDeclContexts += Record[2];
3990 TotalVisibleDeclContexts += Record[3];
3991 TotalModuleLocalVisibleDeclContexts += Record[4];
3992 TotalTULocalVisibleDeclContexts += Record[5];
3993 break;
3994
3996 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
3997 UnusedFileScopedDecls.push_back(ReadDeclID(F, Record, I));
3998 break;
3999
4000 case DELEGATING_CTORS:
4001 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4002 DelegatingCtorDecls.push_back(ReadDeclID(F, Record, I));
4003 break;
4004
4006 if (Record.size() % 3 != 0)
4007 return llvm::createStringError(std::errc::illegal_byte_sequence,
4008 "invalid weak identifiers record");
4009
4010 // FIXME: Ignore weak undeclared identifiers from non-original PCH
4011 // files. This isn't the way to do it :)
4012 WeakUndeclaredIdentifiers.clear();
4013
4014 // Translate the weak, undeclared identifiers into global IDs.
4015 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
4016 WeakUndeclaredIdentifiers.push_back(
4017 getGlobalIdentifierID(F, Record[I++]));
4018 WeakUndeclaredIdentifiers.push_back(
4019 getGlobalIdentifierID(F, Record[I++]));
4020 WeakUndeclaredIdentifiers.push_back(
4021 ReadSourceLocation(F, Record, I).getRawEncoding());
4022 }
4023 break;
4024
4025 case SELECTOR_OFFSETS: {
4026 F.SelectorOffsets = (const uint32_t *)Blob.data();
4028 unsigned LocalBaseSelectorID = Record[1];
4029 F.BaseSelectorID = getTotalNumSelectors();
4030
4031 if (F.LocalNumSelectors > 0) {
4032 // Introduce the global -> local mapping for selectors within this
4033 // module.
4034 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
4035
4036 // Introduce the local -> global mapping for selectors within this
4037 // module.
4039 std::make_pair(LocalBaseSelectorID,
4040 F.BaseSelectorID - LocalBaseSelectorID));
4041
4042 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
4043 }
4044 break;
4045 }
4046
4047 case METHOD_POOL:
4048 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
4049 if (Record[0])
4051 = ASTSelectorLookupTable::Create(
4054 ASTSelectorLookupTrait(*this, F));
4055 TotalNumMethodPoolEntries += Record[1];
4056 break;
4057
4059 if (!Record.empty()) {
4060 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
4061 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
4062 Record[Idx++]));
4063 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
4064 getRawEncoding());
4065 }
4066 }
4067 break;
4068
4069 case PP_ASSUME_NONNULL_LOC: {
4070 unsigned Idx = 0;
4071 if (!Record.empty())
4072 PP.setPreambleRecordedPragmaAssumeNonNullLoc(
4073 ReadSourceLocation(F, Record, Idx));
4074 break;
4075 }
4076
4078 if (!Record.empty()) {
4079 SmallVector<SourceLocation, 64> SrcLocs;
4080 unsigned Idx = 0;
4081 while (Idx < Record.size())
4082 SrcLocs.push_back(ReadSourceLocation(F, Record, Idx));
4083 PP.setDeserializedSafeBufferOptOutMap(SrcLocs);
4084 }
4085 break;
4086 }
4087
4089 if (!Record.empty()) {
4090 unsigned Idx = 0, End = Record.size() - 1;
4091 bool ReachedEOFWhileSkipping = Record[Idx++];
4092 std::optional<Preprocessor::PreambleSkipInfo> SkipInfo;
4093 if (ReachedEOFWhileSkipping) {
4094 SourceLocation HashToken = ReadSourceLocation(F, Record, Idx);
4095 SourceLocation IfTokenLoc = ReadSourceLocation(F, Record, Idx);
4096 bool FoundNonSkipPortion = Record[Idx++];
4097 bool FoundElse = Record[Idx++];
4098 SourceLocation ElseLoc = ReadSourceLocation(F, Record, Idx);
4099 SkipInfo.emplace(HashToken, IfTokenLoc, FoundNonSkipPortion,
4100 FoundElse, ElseLoc);
4101 }
4102 SmallVector<PPConditionalInfo, 4> ConditionalStack;
4103 while (Idx < End) {
4104 auto Loc = ReadSourceLocation(F, Record, Idx);
4105 bool WasSkipping = Record[Idx++];
4106 bool FoundNonSkip = Record[Idx++];
4107 bool FoundElse = Record[Idx++];
4108 ConditionalStack.push_back(
4109 {Loc, WasSkipping, FoundNonSkip, FoundElse});
4110 }
4111 PP.setReplayablePreambleConditionalStack(ConditionalStack, SkipInfo);
4112 }
4113 break;
4114
4115 case PP_COUNTER_VALUE:
4116 if (!Record.empty() && Listener)
4117 Listener->ReadCounter(F, Record[0]);
4118 break;
4119
4120 case FILE_SORTED_DECLS:
4121 F.FileSortedDecls = (const unaligned_decl_id_t *)Blob.data();
4123 break;
4124
4126 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
4128 SourceLocation::UIntTy SLocSpaceSize = Record[1];
4130 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
4131 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
4132 SLocSpaceSize);
4133 if (!F.SLocEntryBaseID) {
4134 Diags.Report(SourceLocation(), diag::remark_sloc_usage);
4135 SourceMgr.noteSLocAddressSpaceUsage(Diags);
4136 return llvm::createStringError(std::errc::invalid_argument,
4137 "ran out of source locations");
4138 }
4139 // Make our entry in the range map. BaseID is negative and growing, so
4140 // we invert it. Because we invert it, though, we need the other end of
4141 // the range.
4142 unsigned RangeStart =
4143 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
4144 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
4146
4147 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
4148 assert((F.SLocEntryBaseOffset & SourceLocation::MacroIDBit) == 0);
4149 GlobalSLocOffsetMap.insert(
4150 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
4151 - SLocSpaceSize,&F));
4152
4153 TotalNumSLocEntries += F.LocalNumSLocEntries;
4154 break;
4155 }
4156
4157 case MODULE_OFFSET_MAP:
4158 F.ModuleOffsetMap = Blob;
4159 break;
4160
4162 ParseLineTable(F, Record);
4163 break;
4164
4165 case EXT_VECTOR_DECLS:
4166 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4167 ExtVectorDecls.push_back(ReadDeclID(F, Record, I));
4168 break;
4169
4170 case VTABLE_USES:
4171 if (Record.size() % 3 != 0)
4172 return llvm::createStringError(std::errc::illegal_byte_sequence,
4173 "Invalid VTABLE_USES record");
4174
4175 // Later tables overwrite earlier ones.
4176 // FIXME: Modules will have some trouble with this. This is clearly not
4177 // the right way to do this.
4178 VTableUses.clear();
4179
4180 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
4181 VTableUses.push_back(
4182 {ReadDeclID(F, Record, Idx),
4183 ReadSourceLocation(F, Record, Idx).getRawEncoding(),
4184 (bool)Record[Idx++]});
4185 }
4186 break;
4187
4189
4190 if (Record.size() % 2 != 0)
4191 return llvm::createStringError(
4192 std::errc::illegal_byte_sequence,
4193 "Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
4194
4195 // For standard C++20 module, we will only reads the instantiations
4196 // if it is the main file.
4197 if (!F.StandardCXXModule || F.Kind == MK_MainFile) {
4198 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
4199 PendingInstantiations.push_back(
4200 {ReadDeclID(F, Record, I),
4201 ReadSourceLocation(F, Record, I).getRawEncoding()});
4202 }
4203 }
4204 break;
4205
4206 case SEMA_DECL_REFS:
4207 if (Record.size() != 3)
4208 return llvm::createStringError(std::errc::illegal_byte_sequence,
4209 "Invalid SEMA_DECL_REFS block");
4210 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4211 SemaDeclRefs.push_back(ReadDeclID(F, Record, I));
4212 break;
4213
4214 case PPD_ENTITIES_OFFSETS: {
4215 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
4216 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
4217 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
4218
4219 unsigned StartingID;
4220 if (!PP.getPreprocessingRecord())
4221 PP.createPreprocessingRecord();
4222 if (!PP.getPreprocessingRecord()->getExternalSource())
4223 PP.getPreprocessingRecord()->SetExternalSource(*this);
4224 StartingID
4225 = PP.getPreprocessingRecord()
4226 ->allocateLoadedEntities(F.NumPreprocessedEntities);
4227 F.BasePreprocessedEntityID = StartingID;
4228
4229 if (F.NumPreprocessedEntities > 0) {
4230 // Introduce the global -> local mapping for preprocessed entities in
4231 // this module.
4232 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
4233 }
4234
4235 break;
4236 }
4237
4238 case PPD_SKIPPED_RANGES: {
4239 F.PreprocessedSkippedRangeOffsets = (const PPSkippedRange*)Blob.data();
4240 assert(Blob.size() % sizeof(PPSkippedRange) == 0);
4241 F.NumPreprocessedSkippedRanges = Blob.size() / sizeof(PPSkippedRange);
4242
4243 if (!PP.getPreprocessingRecord())
4244 PP.createPreprocessingRecord();
4245 if (!PP.getPreprocessingRecord()->getExternalSource())
4246 PP.getPreprocessingRecord()->SetExternalSource(*this);
4247 F.BasePreprocessedSkippedRangeID = PP.getPreprocessingRecord()
4248 ->allocateSkippedRanges(F.NumPreprocessedSkippedRanges);
4249
4251 GlobalSkippedRangeMap.insert(
4252 std::make_pair(F.BasePreprocessedSkippedRangeID, &F));
4253 break;
4254 }
4255
4257 if (Record.size() % 2 != 0)
4258 return llvm::createStringError(
4259 std::errc::illegal_byte_sequence,
4260 "invalid DECL_UPDATE_OFFSETS block in AST file");
4261 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/) {
4262 GlobalDeclID ID = ReadDeclID(F, Record, I);
4263 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I++]));
4264
4265 // If we've already loaded the decl, perform the updates when we finish
4266 // loading this block.
4267 if (Decl *D = GetExistingDecl(ID))
4268 PendingUpdateRecords.push_back(
4269 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
4270 }
4271 break;
4272
4274 if (Record.size() % 5 != 0)
4275 return llvm::createStringError(
4276 std::errc::illegal_byte_sequence,
4277 "invalid DELAYED_NAMESPACE_LEXICAL_VISIBLE_RECORD block in AST "
4278 "file");
4279 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/) {
4280 GlobalDeclID ID = ReadDeclID(F, Record, I);
4281
4282 uint64_t BaseOffset = F.DeclsBlockStartOffset;
4283 assert(BaseOffset && "Invalid DeclsBlockStartOffset for module file!");
4284 uint64_t LocalLexicalOffset = Record[I++];
4285 uint64_t LexicalOffset =
4286 LocalLexicalOffset ? BaseOffset + LocalLexicalOffset : 0;
4287 uint64_t LocalVisibleOffset = Record[I++];
4288 uint64_t VisibleOffset =
4289 LocalVisibleOffset ? BaseOffset + LocalVisibleOffset : 0;
4290 uint64_t LocalModuleLocalOffset = Record[I++];
4291 uint64_t ModuleLocalOffset =
4292 LocalModuleLocalOffset ? BaseOffset + LocalModuleLocalOffset : 0;
4293 uint64_t TULocalLocalOffset = Record[I++];
4294 uint64_t TULocalOffset =
4295 TULocalLocalOffset ? BaseOffset + TULocalLocalOffset : 0;
4296
4297 DelayedNamespaceOffsetMap[ID] = {
4298 {VisibleOffset, ModuleLocalOffset, TULocalOffset}, LexicalOffset};
4299
4300 assert(!GetExistingDecl(ID) &&
4301 "We shouldn't load the namespace in the front of delayed "
4302 "namespace lexical and visible block");
4303 }
4304 break;
4305 }
4306
4307 case RELATED_DECLS_MAP:
4308 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/) {
4309 GlobalDeclID ID = ReadDeclID(F, Record, I);
4310 auto &RelatedDecls = RelatedDeclsMap[ID];
4311 unsigned NN = Record[I++];
4312 RelatedDecls.reserve(NN);
4313 for (unsigned II = 0; II < NN; II++)
4314 RelatedDecls.push_back(ReadDeclID(F, Record, I));
4315 }
4316 break;
4317
4319 if (F.LocalNumObjCCategoriesInMap != 0)
4320 return llvm::createStringError(
4321 std::errc::illegal_byte_sequence,
4322 "duplicate OBJC_CATEGORIES_MAP record in AST file");
4323
4325 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
4326 break;
4327
4328 case OBJC_CATEGORIES:
4329 F.ObjCCategories.swap(Record);
4330 break;
4331
4333 // Later tables overwrite earlier ones.
4334 // FIXME: Modules will have trouble with this.
4335 CUDASpecialDeclRefs.clear();
4336 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4337 CUDASpecialDeclRefs.push_back(ReadDeclID(F, Record, I));
4338 break;
4339
4341 F.HeaderFileInfoTableData = Blob.data();
4343 if (Record[0]) {
4344 F.HeaderFileInfoTable = HeaderFileInfoLookupTable::Create(
4345 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
4346 (const unsigned char *)F.HeaderFileInfoTableData,
4347 HeaderFileInfoTrait(*this, F));
4348
4349 PP.getHeaderSearchInfo().SetExternalSource(this);
4350 if (!PP.getHeaderSearchInfo().getExternalLookup())
4351 PP.getHeaderSearchInfo().SetExternalLookup(this);
4352 }
4353 break;
4354
4355 case FP_PRAGMA_OPTIONS:
4356 // Later tables overwrite earlier ones.
4357 FPPragmaOptions.swap(Record);
4358 break;
4359
4361 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4362 DeclsWithEffectsToVerify.push_back(ReadDeclID(F, Record, I));
4363 break;
4364
4365 case OPENCL_EXTENSIONS:
4366 for (unsigned I = 0, E = Record.size(); I != E; ) {
4367 auto Name = ReadString(Record, I);
4368 auto &OptInfo = OpenCLExtensions.OptMap[Name];
4369 OptInfo.Supported = Record[I++] != 0;
4370 OptInfo.Enabled = Record[I++] != 0;
4371 OptInfo.WithPragma = Record[I++] != 0;
4372 OptInfo.Avail = Record[I++];
4373 OptInfo.Core = Record[I++];
4374 OptInfo.Opt = Record[I++];
4375 }
4376 break;
4377
4379 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4380 TentativeDefinitions.push_back(ReadDeclID(F, Record, I));
4381 break;
4382
4383 case KNOWN_NAMESPACES:
4384 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4385 KnownNamespaces.push_back(ReadDeclID(F, Record, I));
4386 break;
4387
4388 case UNDEFINED_BUT_USED:
4389 if (Record.size() % 2 != 0)
4390 return llvm::createStringError(std::errc::illegal_byte_sequence,
4391 "invalid undefined-but-used record");
4392 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
4393 UndefinedButUsed.push_back(
4394 {ReadDeclID(F, Record, I),
4395 ReadSourceLocation(F, Record, I).getRawEncoding()});
4396 }
4397 break;
4398
4400 for (unsigned I = 0, N = Record.size(); I != N;) {
4401 DelayedDeleteExprs.push_back(ReadDeclID(F, Record, I).getRawValue());
4402 const uint64_t Count = Record[I++];
4403 DelayedDeleteExprs.push_back(Count);
4404 for (uint64_t C = 0; C < Count; ++C) {
4405 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
4406 bool IsArrayForm = Record[I++] == 1;
4407 DelayedDeleteExprs.push_back(IsArrayForm);
4408 }
4409 }
4410 break;
4411
4412 case VTABLES_TO_EMIT:
4413 if (F.Kind == MK_MainFile ||
4414 getContext().getLangOpts().BuildingPCHWithObjectFile)
4415 for (unsigned I = 0, N = Record.size(); I != N;)
4416 VTablesToEmit.push_back(ReadDeclID(F, Record, I));
4417 break;
4418
4419 case IMPORTED_MODULES:
4420 if (!F.isModule()) {
4421 // If we aren't loading a module (which has its own exports), make
4422 // all of the imported modules visible.
4423 // FIXME: Deal with macros-only imports.
4424 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
4425 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
4426 SourceLocation Loc = ReadSourceLocation(F, Record, I);
4427 if (GlobalID) {
4428 PendingImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
4429 if (DeserializationListener)
4430 DeserializationListener->ModuleImportRead(GlobalID, Loc);
4431 }
4432 }
4433 }
4434 break;
4435
4436 case MACRO_OFFSET: {
4437 if (F.LocalNumMacros != 0)
4438 return llvm::createStringError(
4439 std::errc::illegal_byte_sequence,
4440 "duplicate MACRO_OFFSET record in AST file");
4441 F.MacroOffsets = (const uint32_t *)Blob.data();
4442 F.LocalNumMacros = Record[0];
4444 F.BaseMacroID = getTotalNumMacros();
4445
4446 if (F.LocalNumMacros > 0)
4447 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
4448 break;
4449 }
4450
4452 LateParsedTemplates.emplace_back(
4453 std::piecewise_construct, std::forward_as_tuple(&F),
4454 std::forward_as_tuple(Record.begin(), Record.end()));
4455 break;
4456
4458 if (Record.size() != 1)
4459 return llvm::createStringError(std::errc::illegal_byte_sequence,
4460 "invalid pragma optimize record");
4461 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
4462 break;
4463
4465 if (Record.size() != 1)
4466 return llvm::createStringError(std::errc::illegal_byte_sequence,
4467 "invalid pragma ms_struct record");
4468 PragmaMSStructState = Record[0];
4469 break;
4470
4472 if (Record.size() != 2)
4473 return llvm::createStringError(
4474 std::errc::illegal_byte_sequence,
4475 "invalid pragma pointers to members record");
4476 PragmaMSPointersToMembersState = Record[0];
4477 PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]);
4478 break;
4479
4481 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4482 UnusedLocalTypedefNameCandidates.push_back(ReadDeclID(F, Record, I));
4483 break;
4484
4486 if (Record.size() != 1)
4487 return llvm::createStringError(std::errc::illegal_byte_sequence,
4488 "invalid cuda pragma options record");
4489 ForceHostDeviceDepth = Record[0];
4490 break;
4491
4493 if (Record.size() < 3)
4494 return llvm::createStringError(std::errc::illegal_byte_sequence,
4495 "invalid pragma pack record");
4496 PragmaAlignPackCurrentValue = ReadAlignPackInfo(Record[0]);
4497 PragmaAlignPackCurrentLocation = ReadSourceLocation(F, Record[1]);
4498 unsigned NumStackEntries = Record[2];
4499 unsigned Idx = 3;
4500 // Reset the stack when importing a new module.
4501 PragmaAlignPackStack.clear();
4502 for (unsigned I = 0; I < NumStackEntries; ++I) {
4503 PragmaAlignPackStackEntry Entry;
4504 Entry.Value = ReadAlignPackInfo(Record[Idx++]);
4505 Entry.Location = ReadSourceLocation(F, Record[Idx++]);
4506 Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]);
4507 PragmaAlignPackStrings.push_back(ReadString(Record, Idx));
4508 Entry.SlotLabel = PragmaAlignPackStrings.back();
4509 PragmaAlignPackStack.push_back(Entry);
4510 }
4511 break;
4512 }
4513
4515 if (Record.size() < 3)
4516 return llvm::createStringError(std::errc::illegal_byte_sequence,
4517 "invalid pragma float control record");
4518 FpPragmaCurrentValue = FPOptionsOverride::getFromOpaqueInt(Record[0]);
4519 FpPragmaCurrentLocation = ReadSourceLocation(F, Record[1]);
4520 unsigned NumStackEntries = Record[2];
4521 unsigned Idx = 3;
4522 // Reset the stack when importing a new module.
4523 FpPragmaStack.clear();
4524 for (unsigned I = 0; I < NumStackEntries; ++I) {
4525 FpPragmaStackEntry Entry;
4526 Entry.Value = FPOptionsOverride::getFromOpaqueInt(Record[Idx++]);
4527 Entry.Location = ReadSourceLocation(F, Record[Idx++]);
4528 Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]);
4529 FpPragmaStrings.push_back(ReadString(Record, Idx));
4530 Entry.SlotLabel = FpPragmaStrings.back();
4531 FpPragmaStack.push_back(Entry);
4532 }
4533 break;
4534 }
4535
4537 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4538 DeclsToCheckForDeferredDiags.insert(ReadDeclID(F, Record, I));
4539 break;
4540
4542 unsigned NumRecords = Record.front();
4543 // Last record which is used to keep number of valid records.
4544 if (Record.size() - 1 != NumRecords)
4545 return llvm::createStringError(std::errc::illegal_byte_sequence,
4546 "invalid rvv intrinsic pragma record");
4547
4548 if (RISCVVecIntrinsicPragma.empty())
4549 RISCVVecIntrinsicPragma.append(NumRecords, 0);
4550 // There might be multiple precompiled modules imported, we need to union
4551 // them all.
4552 for (unsigned i = 0; i < NumRecords; ++i)
4553 RISCVVecIntrinsicPragma[i] |= Record[i + 1];
4554 break;
4555 }
4556 }
4557 }
4558}
4559
4560void ASTReader::ReadModuleOffsetMap(ModuleFile &F) const {
4561 assert(!F.ModuleOffsetMap.empty() && "no module offset map to read");
4562
4563 // Additional remapping information.
4564 const unsigned char *Data = (const unsigned char*)F.ModuleOffsetMap.data();
4565 const unsigned char *DataEnd = Data + F.ModuleOffsetMap.size();
4566 F.ModuleOffsetMap = StringRef();
4567
4569 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
4570 RemapBuilder SelectorRemap(F.SelectorRemap);
4571
4572 auto &ImportedModuleVector = F.TransitiveImports;
4573 assert(ImportedModuleVector.empty());
4574
4575 while (Data < DataEnd) {
4576 // FIXME: Looking up dependency modules by filename is horrible. Let's
4577 // start fixing this with prebuilt, explicit and implicit modules and see
4578 // how it goes...
4579 using namespace llvm::support;
4580 ModuleKind Kind = static_cast<ModuleKind>(
4581 endian::readNext<uint8_t, llvm::endianness::little>(Data));
4582 uint16_t Len = endian::readNext<uint16_t, llvm::endianness::little>(Data);
4583 StringRef Name = StringRef((const char*)Data, Len);
4584 Data += Len;
4587 ? ModuleMgr.lookupByModuleName(Name)
4588 : ModuleMgr.lookupByFileName(Name));
4589 if (!OM) {
4590 std::string Msg = "refers to unknown module, cannot find ";
4591 Msg.append(std::string(Name));
4592 Error(Msg);
4593 return;
4594 }
4595
4596 ImportedModuleVector.push_back(OM);
4597
4598 uint32_t SubmoduleIDOffset =
4599 endian::readNext<uint32_t, llvm::endianness::little>(Data);
4600 uint32_t SelectorIDOffset =
4601 endian::readNext<uint32_t, llvm::endianness::little>(Data);
4602
4603 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
4604 RemapBuilder &Remap) {
4605 constexpr uint32_t None = std::numeric_limits<uint32_t>::max();
4606 if (Offset != None)
4607 Remap.insert(std::make_pair(Offset,
4608 static_cast<int>(BaseOffset - Offset)));
4609 };
4610
4611 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
4612 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
4613 }
4614}
4615
4617ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
4618 const ModuleFile *ImportedBy,
4619 unsigned ClientLoadCapabilities) {
4620 unsigned Idx = 0;
4621 F.ModuleMapPath = ReadPath(F, Record, Idx);
4622
4623 // Try to resolve ModuleName in the current header search context and
4624 // verify that it is found in the same module map file as we saved. If the
4625 // top-level AST file is a main file, skip this check because there is no
4626 // usable header search context.
4627 assert(!F.ModuleName.empty() &&
4628 "MODULE_NAME should come before MODULE_MAP_FILE");
4629 auto [MaybeM, IgnoreError] =
4630 getModuleForRelocationChecks(F, /*DirectoryCheck=*/false);
4631 if (MaybeM.has_value()) {
4632 // An implicitly-loaded module file should have its module listed in some
4633 // module map file that we've already loaded.
4634 Module *M = MaybeM.value();
4635 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
4636 OptionalFileEntryRef ModMap =
4637 M ? Map.getModuleMapFileForUniquing(M) : std::nullopt;
4638 if (!IgnoreError && !ModMap) {
4639 if (M && M->Directory)
4640 Diag(diag::remark_module_relocated)
4641 << F.ModuleName << F.BaseDirectory << M->Directory->getName();
4642
4643 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities)) {
4644 if (auto ASTFE = M ? M->getASTFile() : std::nullopt) {
4645 // This module was defined by an imported (explicit) module.
4646 Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
4647 << ASTFE->getName();
4648 // TODO: Add a note with the module map paths if they differ.
4649 } else {
4650 // This module was built with a different module map.
4651 Diag(diag::err_imported_module_not_found)
4652 << F.ModuleName << F.FileName
4653 << (ImportedBy ? ImportedBy->FileName : "") << F.ModuleMapPath
4654 << !ImportedBy;
4655 // In case it was imported by a PCH, there's a chance the user is
4656 // just missing to include the search path to the directory containing
4657 // the modulemap.
4658 if (ImportedBy && ImportedBy->Kind == MK_PCH)
4659 Diag(diag::note_imported_by_pch_module_not_found)
4660 << llvm::sys::path::parent_path(F.ModuleMapPath);
4661 }
4662 }
4663 return OutOfDate;
4664 }
4665
4666 assert(M && M->Name == F.ModuleName && "found module with different name");
4667
4668 // Check the primary module map file.
4669 auto StoredModMap = FileMgr.getOptionalFileRef(F.ModuleMapPath);
4670 if (!StoredModMap || *StoredModMap != ModMap) {
4671 assert(ModMap && "found module is missing module map file");
4672 assert((ImportedBy || F.Kind == MK_ImplicitModule) &&
4673 "top-level import should be verified");
4674 bool NotImported = F.Kind == MK_ImplicitModule && !ImportedBy;
4675 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4676 Diag(diag::err_imported_module_modmap_changed)
4677 << F.ModuleName << (NotImported ? F.FileName : ImportedBy->FileName)
4678 << ModMap->getName() << F.ModuleMapPath << NotImported;
4679 return OutOfDate;
4680 }
4681
4682 ModuleMap::AdditionalModMapsSet AdditionalStoredMaps;
4683 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
4684 // FIXME: we should use input files rather than storing names.
4685 std::string Filename = ReadPath(F, Record, Idx);
4686 auto SF = FileMgr.getOptionalFileRef(Filename, false, false);
4687 if (!SF) {
4688 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4689 Error("could not find file '" + Filename +"' referenced by AST file");
4690 return OutOfDate;
4691 }
4692 AdditionalStoredMaps.insert(*SF);
4693 }
4694
4695 // Check any additional module map files (e.g. module.private.modulemap)
4696 // that are not in the pcm.
4697 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
4698 for (FileEntryRef ModMap : *AdditionalModuleMaps) {
4699 // Remove files that match
4700 // Note: SmallPtrSet::erase is really remove
4701 if (!AdditionalStoredMaps.erase(ModMap)) {
4702 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4703 Diag(diag::err_module_different_modmap)
4704 << F.ModuleName << /*new*/0 << ModMap.getName();
4705 return OutOfDate;
4706 }
4707 }
4708 }
4709
4710 // Check any additional module map files that are in the pcm, but not
4711 // found in header search. Cases that match are already removed.
4712 for (FileEntryRef ModMap : AdditionalStoredMaps) {
4713 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4714 Diag(diag::err_module_different_modmap)
4715 << F.ModuleName << /*not new*/1 << ModMap.getName();
4716 return OutOfDate;
4717 }
4718 }
4719
4720 if (Listener)
4721 Listener->ReadModuleMapFile(F.ModuleMapPath);
4722 return Success;
4723}
4724
4725/// Move the given method to the back of the global list of methods.
4727 // Find the entry for this selector in the method pool.
4728 SemaObjC::GlobalMethodPool::iterator Known =
4729 S.ObjC().MethodPool.find(Method->getSelector());
4730 if (Known == S.ObjC().MethodPool.end())
4731 return;
4732
4733 // Retrieve the appropriate method list.
4734 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
4735 : Known->second.second;
4736 bool Found = false;
4737 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
4738 if (!Found) {
4739 if (List->getMethod() == Method) {
4740 Found = true;
4741 } else {
4742 // Keep searching.
4743 continue;
4744 }
4745 }
4746
4747 if (List->getNext())
4748 List->setMethod(List->getNext()->getMethod());
4749 else
4750 List->setMethod(Method);
4751 }
4752}
4753
4754void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
4755 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
4756 for (Decl *D : Names) {
4757 bool wasHidden = !D->isUnconditionallyVisible();
4759
4760 if (wasHidden && SemaObj) {
4761 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
4763 }
4764 }
4765 }
4766}
4767
4769 Module::NameVisibilityKind NameVisibility,
4770 SourceLocation ImportLoc) {
4773 Stack.push_back(Mod);
4774 while (!Stack.empty()) {
4775 Mod = Stack.pop_back_val();
4776
4777 if (NameVisibility <= Mod->NameVisibility) {
4778 // This module already has this level of visibility (or greater), so
4779 // there is nothing more to do.
4780 continue;
4781 }
4782
4783 if (Mod->isUnimportable()) {
4784 // Modules that aren't importable cannot be made visible.
4785 continue;
4786 }
4787
4788 // Update the module's name visibility.
4789 Mod->NameVisibility = NameVisibility;
4790
4791 // If we've already deserialized any names from this module,
4792 // mark them as visible.
4793 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
4794 if (Hidden != HiddenNamesMap.end()) {
4795 auto HiddenNames = std::move(*Hidden);
4796 HiddenNamesMap.erase(Hidden);
4797 makeNamesVisible(HiddenNames.second, HiddenNames.first);
4798 assert(!HiddenNamesMap.contains(Mod) &&
4799 "making names visible added hidden names");
4800 }
4801
4802 // Push any exported modules onto the stack to be marked as visible.
4804 Mod->getExportedModules(Exports);
4806 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
4807 Module *Exported = *I;
4808 if (Visited.insert(Exported).second)
4809 Stack.push_back(Exported);
4810 }
4811 }
4812}
4813
4814/// We've merged the definition \p MergedDef into the existing definition
4815/// \p Def. Ensure that \p Def is made visible whenever \p MergedDef is made
4816/// visible.
4818 NamedDecl *MergedDef) {
4819 if (!Def->isUnconditionallyVisible()) {
4820 // If MergedDef is visible or becomes visible, make the definition visible.
4821 if (MergedDef->isUnconditionallyVisible())
4823 else {
4824 getContext().mergeDefinitionIntoModule(
4825 Def, MergedDef->getImportedOwningModule(),
4826 /*NotifyListeners*/ false);
4827 PendingMergedDefinitionsToDeduplicate.insert(Def);
4828 }
4829 }
4830}
4831
4833 if (GlobalIndex)
4834 return false;
4835
4836 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
4837 !PP.getLangOpts().Modules)
4838 return true;
4839
4840 // Try to load the global index.
4841 TriedLoadingGlobalIndex = true;
4842 StringRef SpecificModuleCachePath =
4843 getPreprocessor().getHeaderSearchInfo().getSpecificModuleCachePath();
4844 std::pair<GlobalModuleIndex *, llvm::Error> Result =
4845 GlobalModuleIndex::readIndex(SpecificModuleCachePath);
4846 if (llvm::Error Err = std::move(Result.second)) {
4847 assert(!Result.first);
4848 consumeError(std::move(Err)); // FIXME this drops errors on the floor.
4849 return true;
4850 }
4851
4852 GlobalIndex.reset(Result.first);
4853 ModuleMgr.setGlobalIndex(GlobalIndex.get());
4854 return false;
4855}
4856
4858 return PP.getLangOpts().Modules && UseGlobalIndex &&
4859 !hasGlobalIndex() && TriedLoadingGlobalIndex;
4860}
4861
4862/// Given a cursor at the start of an AST file, scan ahead and drop the
4863/// cursor into the start of the given block ID, returning false on success and
4864/// true on failure.
4865static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
4866 while (true) {
4867 Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
4868 if (!MaybeEntry) {
4869 // FIXME this drops errors on the floor.
4870 consumeError(MaybeEntry.takeError());
4871 return true;
4872 }
4873 llvm::BitstreamEntry Entry = MaybeEntry.get();
4874
4875 switch (Entry.Kind) {
4876 case llvm::BitstreamEntry::Error:
4877 case llvm::BitstreamEntry::EndBlock:
4878 return true;
4879
4880 case llvm::BitstreamEntry::Record:
4881 // Ignore top-level records.
4882 if (Expected<unsigned> Skipped = Cursor.skipRecord(Entry.ID))
4883 break;
4884 else {
4885 // FIXME this drops errors on the floor.
4886 consumeError(Skipped.takeError());
4887 return true;
4888 }
4889
4890 case llvm::BitstreamEntry::SubBlock:
4891 if (Entry.ID == BlockID) {
4892 if (llvm::Error Err = Cursor.EnterSubBlock(BlockID)) {
4893 // FIXME this drops the error on the floor.
4894 consumeError(std::move(Err));
4895 return true;
4896 }
4897 // Found it!
4898 return false;
4899 }
4900
4901 if (llvm::Error Err = Cursor.SkipBlock()) {
4902 // FIXME this drops the error on the floor.
4903 consumeError(std::move(Err));
4904 return true;
4905 }
4906 }
4907 }
4908}
4909
4911 SourceLocation ImportLoc,
4912 unsigned ClientLoadCapabilities,
4913 ModuleFile **NewLoadedModuleFile) {
4914 llvm::TimeTraceScope scope("ReadAST", FileName);
4915
4916 llvm::SaveAndRestore SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
4918 CurrentDeserializingModuleKind, Type);
4919
4920 // Defer any pending actions until we get to the end of reading the AST file.
4921 Deserializing AnASTFile(this);
4922
4923 // Bump the generation number.
4924 unsigned PreviousGeneration = 0;
4925 if (ContextObj)
4926 PreviousGeneration = incrementGeneration(*ContextObj);
4927
4928 unsigned NumModules = ModuleMgr.size();
4930 if (ASTReadResult ReadResult =
4931 ReadASTCore(FileName, Type, ImportLoc,
4932 /*ImportedBy=*/nullptr, Loaded, 0, 0, ASTFileSignature(),
4933 ClientLoadCapabilities)) {
4934 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules);
4935
4936 // If we find that any modules are unusable, the global index is going
4937 // to be out-of-date. Just remove it.
4938 GlobalIndex.reset();
4939 ModuleMgr.setGlobalIndex(nullptr);
4940 return ReadResult;
4941 }
4942
4943 if (NewLoadedModuleFile && !Loaded.empty())
4944 *NewLoadedModuleFile = Loaded.back().Mod;
4945
4946 // Here comes stuff that we only do once the entire chain is loaded. Do *not*
4947 // remove modules from this point. Various fields are updated during reading
4948 // the AST block and removing the modules would result in dangling pointers.
4949 // They are generally only incidentally dereferenced, ie. a binary search
4950 // runs over `GlobalSLocEntryMap`, which could cause an invalid module to
4951 // be dereferenced but it wouldn't actually be used.
4952
4953 // Load the AST blocks of all of the modules that we loaded. We can still
4954 // hit errors parsing the ASTs at this point.
4955 for (ImportedModule &M : Loaded) {
4956 ModuleFile &F = *M.Mod;
4957 llvm::TimeTraceScope Scope2("Read Loaded AST", F.ModuleName);
4958
4959 // Read the AST block.
4960 if (llvm::Error Err = ReadASTBlock(F, ClientLoadCapabilities)) {
4961 Error(std::move(Err));
4962 return Failure;
4963 }
4964
4965 // The AST block should always have a definition for the main module.
4966 if (F.isModule() && !F.DidReadTopLevelSubmodule) {
4967 Error(diag::err_module_file_missing_top_level_submodule, F.FileName);
4968 return Failure;
4969 }
4970
4971 // Read the extension blocks.
4973 if (llvm::Error Err = ReadExtensionBlock(F)) {
4974 Error(std::move(Err));
4975 return Failure;
4976 }
4977 }
4978
4979 // Once read, set the ModuleFile bit base offset and update the size in
4980 // bits of all files we've seen.
4981 F.GlobalBitOffset = TotalModulesSizeInBits;
4982 TotalModulesSizeInBits += F.SizeInBits;
4983 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
4984 }
4985
4986 // Preload source locations and interesting indentifiers.
4987 for (ImportedModule &M : Loaded) {
4988 ModuleFile &F = *M.Mod;
4989
4990 // Map the original source file ID into the ID space of the current
4991 // compilation.
4994
4995 for (auto Offset : F.PreloadIdentifierOffsets) {
4996 const unsigned char *Data = F.IdentifierTableData + Offset;
4997
4998 ASTIdentifierLookupTrait Trait(*this, F);
4999 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
5000 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
5001
5002 IdentifierInfo *II;
5003 if (!PP.getLangOpts().CPlusPlus) {
5004 // Identifiers present in both the module file and the importing
5005 // instance are marked out-of-date so that they can be deserialized
5006 // on next use via ASTReader::updateOutOfDateIdentifier().
5007 // Identifiers present in the module file but not in the importing
5008 // instance are ignored for now, preventing growth of the identifier
5009 // table. They will be deserialized on first use via ASTReader::get().
5010 auto It = PP.getIdentifierTable().find(Key);
5011 if (It == PP.getIdentifierTable().end())
5012 continue;
5013 II = It->second;
5014 } else {
5015 // With C++ modules, not many identifiers are considered interesting.
5016 // All identifiers in the module file can be placed into the identifier
5017 // table of the importing instance and marked as out-of-date. This makes
5018 // ASTReader::get() a no-op, and deserialization will take place on
5019 // first/next use via ASTReader::updateOutOfDateIdentifier().
5020 II = &PP.getIdentifierTable().getOwn(Key);
5021 }
5022
5023 II->setOutOfDate(true);
5024
5025 // Mark this identifier as being from an AST file so that we can track
5026 // whether we need to serialize it.
5027 markIdentifierFromAST(*this, *II, /*IsModule=*/true);
5028
5029 // Associate the ID with the identifier so that the writer can reuse it.
5030 auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
5031 SetIdentifierInfo(ID, II);
5032 }
5033 }
5034
5035 // Builtins and library builtins have already been initialized. Mark all
5036 // identifiers as out-of-date, so that they are deserialized on first use.
5037 if (Type == MK_PCH || Type == MK_Preamble || Type == MK_MainFile)
5038 for (auto &Id : PP.getIdentifierTable())
5039 Id.second->setOutOfDate(true);
5040
5041 // Mark selectors as out of date.
5042 for (const auto &Sel : SelectorGeneration)
5043 SelectorOutOfDate[Sel.first] = true;
5044
5045 // Setup the import locations and notify the module manager that we've
5046 // committed to these module files.
5047 for (ImportedModule &M : Loaded) {
5048 ModuleFile &F = *M.Mod;
5049
5050 ModuleMgr.moduleFileAccepted(&F);
5051
5052 // Set the import location.
5053 F.DirectImportLoc = ImportLoc;
5054 // FIXME: We assume that locations from PCH / preamble do not need
5055 // any translation.
5056 if (!M.ImportedBy)
5057 F.ImportLoc = M.ImportLoc;
5058 else
5059 F.ImportLoc = TranslateSourceLocation(*M.ImportedBy, M.ImportLoc);
5060 }
5061
5062 // Resolve any unresolved module exports.
5063 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
5064 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
5066 Module *ResolvedMod = getSubmodule(GlobalID);
5067
5068 switch (Unresolved.Kind) {
5069 case UnresolvedModuleRef::Conflict:
5070 if (ResolvedMod) {
5071 Module::Conflict Conflict;
5072 Conflict.Other = ResolvedMod;
5073 Conflict.Message = Unresolved.String.str();
5074 Unresolved.Mod->Conflicts.push_back(Conflict);
5075 }
5076 continue;
5077
5078 case UnresolvedModuleRef::Import:
5079 if (ResolvedMod)
5080 Unresolved.Mod->Imports.insert(ResolvedMod);
5081 continue;
5082
5083 case UnresolvedModuleRef::Affecting:
5084 if (ResolvedMod)
5085 Unresolved.Mod->AffectingClangModules.insert(ResolvedMod);
5086 continue;
5087
5088 case UnresolvedModuleRef::Export:
5089 if (ResolvedMod || Unresolved.IsWildcard)
5090 Unresolved.Mod->Exports.push_back(
5091 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
5092 continue;
5093 }
5094 }
5095 UnresolvedModuleRefs.clear();
5096
5097 // FIXME: How do we load the 'use'd modules? They may not be submodules.
5098 // Might be unnecessary as use declarations are only used to build the
5099 // module itself.
5100
5101 if (ContextObj)
5103
5104 if (SemaObj)
5105 UpdateSema();
5106
5107 if (DeserializationListener)
5108 DeserializationListener->ReaderInitialized(this);
5109
5110 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
5111 if (PrimaryModule.OriginalSourceFileID.isValid()) {
5112 // If this AST file is a precompiled preamble, then set the
5113 // preamble file ID of the source manager to the file source file
5114 // from which the preamble was built.
5115 if (Type == MK_Preamble) {
5116 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
5117 } else if (Type == MK_MainFile) {
5118 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
5119 }
5120 }
5121
5122 // For any Objective-C class definitions we have already loaded, make sure
5123 // that we load any additional categories.
5124 if (ContextObj) {
5125 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
5126 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
5127 ObjCClassesLoaded[I], PreviousGeneration);
5128 }
5129 }
5130
5131 const HeaderSearchOptions &HSOpts =
5132 PP.getHeaderSearchInfo().getHeaderSearchOpts();
5134 // Now we are certain that the module and all modules it depends on are
5135 // up-to-date. For implicitly-built module files, ensure the corresponding
5136 // timestamp files are up-to-date in this build session.
5137 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
5138 ImportedModule &M = Loaded[I];
5139 if (M.Mod->Kind == MK_ImplicitModule &&
5141 getModuleManager().getModuleCache().updateModuleTimestamp(
5142 M.Mod->FileName);
5143 }
5144 }
5145
5146 return Success;
5147}
5148
5149static ASTFileSignature readASTFileSignature(StringRef PCH);
5150
5151/// Whether \p Stream doesn't start with the AST file magic number 'CPCH'.
5152static llvm::Error doesntStartWithASTFileMagic(BitstreamCursor &Stream) {
5153 // FIXME checking magic headers is done in other places such as
5154 // SerializedDiagnosticReader and GlobalModuleIndex, but error handling isn't
5155 // always done the same. Unify it all with a helper.
5156 if (!Stream.canSkipToPos(4))
5157 return llvm::createStringError(
5158 std::errc::illegal_byte_sequence,
5159 "file too small to contain precompiled file magic");
5160 for (unsigned C : {'C', 'P', 'C', 'H'})
5161 if (Expected<llvm::SimpleBitstreamCursor::word_t> Res = Stream.Read(8)) {
5162 if (Res.get() != C)
5163 return llvm::createStringError(
5164 std::errc::illegal_byte_sequence,
5165 "file doesn't start with precompiled file magic");
5166 } else
5167 return Res.takeError();
5168 return llvm::Error::success();
5169}
5170
5172 switch (Kind) {
5173 case MK_PCH:
5174 return 0; // PCH
5175 case MK_ImplicitModule:
5176 case MK_ExplicitModule:
5177 case MK_PrebuiltModule:
5178 return 1; // module
5179 case MK_MainFile:
5180 case MK_Preamble:
5181 return 2; // main source file
5182 }
5183 llvm_unreachable("unknown module kind");
5184}
5185
5189 SourceLocation ImportLoc,
5190 ModuleFile *ImportedBy,
5192 off_t ExpectedSize, time_t ExpectedModTime,
5193 ASTFileSignature ExpectedSignature,
5194 unsigned ClientLoadCapabilities) {
5195 ModuleFile *M;
5196 std::string ErrorStr;
5198 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
5199 getGeneration(), ExpectedSize, ExpectedModTime,
5200 ExpectedSignature, readASTFileSignature,
5201 M, ErrorStr);
5202
5203 switch (AddResult) {
5205 Diag(diag::remark_module_import)
5206 << M->ModuleName << M->FileName << (ImportedBy ? true : false)
5207 << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());
5208 return Success;
5209
5211 // Load module file below.
5212 break;
5213
5215 // The module file was missing; if the client can handle that, return
5216 // it.
5217 if (ClientLoadCapabilities & ARR_Missing)
5218 return Missing;
5219
5220 // Otherwise, return an error.
5221 Diag(diag::err_ast_file_not_found)
5222 << moduleKindForDiagnostic(Type) << FileName << !ErrorStr.empty()
5223 << ErrorStr;
5224 return Failure;
5225
5227 // We couldn't load the module file because it is out-of-date. If the
5228 // client can handle out-of-date, return it.
5229 if (ClientLoadCapabilities & ARR_OutOfDate)
5230 return OutOfDate;
5231
5232 // Otherwise, return an error.
5233 Diag(diag::err_ast_file_out_of_date)
5234 << moduleKindForDiagnostic(Type) << FileName << !ErrorStr.empty()
5235 << ErrorStr;
5236 return Failure;
5237 }
5238
5239 assert(M && "Missing module file");
5240
5241 bool ShouldFinalizePCM = false;
5242 llvm::scope_exit FinalizeOrDropPCM([&]() {
5243 auto &MC = getModuleManager().getModuleCache().getInMemoryModuleCache();
5244 if (ShouldFinalizePCM)
5245 MC.finalizePCM(FileName);
5246 else
5247 MC.tryToDropPCM(FileName);
5248 });
5249 ModuleFile &F = *M;
5250 BitstreamCursor &Stream = F.Stream;
5251 Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(*F.Buffer));
5252 F.SizeInBits = F.Buffer->getBufferSize() * 8;
5253
5254 // Sniff for the signature.
5255 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5256 Diag(diag::err_ast_file_invalid)
5257 << moduleKindForDiagnostic(Type) << FileName << std::move(Err);
5258 return Failure;
5259 }
5260
5261 // This is used for compatibility with older PCH formats.
5262 bool HaveReadControlBlock = false;
5263 while (true) {
5264 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5265 if (!MaybeEntry) {
5266 Error(MaybeEntry.takeError());
5267 return Failure;
5268 }
5269 llvm::BitstreamEntry Entry = MaybeEntry.get();
5270
5271 switch (Entry.Kind) {
5272 case llvm::BitstreamEntry::Error:
5273 case llvm::BitstreamEntry::Record:
5274 case llvm::BitstreamEntry::EndBlock:
5275 Error("invalid record at top-level of AST file");
5276 return Failure;
5277
5278 case llvm::BitstreamEntry::SubBlock:
5279 break;
5280 }
5281
5282 switch (Entry.ID) {
5283 case CONTROL_BLOCK_ID:
5284 HaveReadControlBlock = true;
5285 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
5286 case Success:
5287 // Check that we didn't try to load a non-module AST file as a module.
5288 //
5289 // FIXME: Should we also perform the converse check? Loading a module as
5290 // a PCH file sort of works, but it's a bit wonky.
5292 Type == MK_PrebuiltModule) &&
5293 F.ModuleName.empty()) {
5295 if (Result != OutOfDate ||
5296 (ClientLoadCapabilities & ARR_OutOfDate) == 0)
5297 Diag(diag::err_module_file_not_module) << FileName;
5298 return Result;
5299 }
5300 break;
5301
5302 case Failure: return Failure;
5303 case Missing: return Missing;
5304 case OutOfDate: return OutOfDate;
5305 case VersionMismatch: return VersionMismatch;
5307 case HadErrors: return HadErrors;
5308 }
5309 break;
5310
5311 case AST_BLOCK_ID:
5312 if (!HaveReadControlBlock) {
5313 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
5314 Diag(diag::err_ast_file_version_too_old)
5316 return VersionMismatch;
5317 }
5318
5319 // Record that we've loaded this module.
5320 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
5321 ShouldFinalizePCM = true;
5322 return Success;
5323
5324 default:
5325 if (llvm::Error Err = Stream.SkipBlock()) {
5326 Error(std::move(Err));
5327 return Failure;
5328 }
5329 break;
5330 }
5331 }
5332
5333 llvm_unreachable("unexpected break; expected return");
5334}
5335
5337ASTReader::readUnhashedControlBlock(ModuleFile &F, bool WasImportedBy,
5338 unsigned ClientLoadCapabilities) {
5339 const HeaderSearchOptions &HSOpts =
5340 PP.getHeaderSearchInfo().getHeaderSearchOpts();
5341 bool AllowCompatibleConfigurationMismatch =
5343 bool DisableValidation = shouldDisableValidationForFile(F);
5344
5345 ASTReadResult Result = readUnhashedControlBlockImpl(
5346 &F, F.Data, F.FileName, ClientLoadCapabilities,
5347 AllowCompatibleConfigurationMismatch, Listener.get(),
5348 WasImportedBy ? false : HSOpts.ModulesValidateDiagnosticOptions);
5349
5350 // If F was directly imported by another module, it's implicitly validated by
5351 // the importing module.
5352 if (DisableValidation || WasImportedBy ||
5353 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
5354 return Success;
5355
5356 if (Result == Failure) {
5357 Error("malformed block record in AST file");
5358 return Failure;
5359 }
5360
5361 if (Result == OutOfDate && F.Kind == MK_ImplicitModule) {
5362 // If this module has already been finalized in the ModuleCache, we're stuck
5363 // with it; we can only load a single version of each module.
5364 //
5365 // This can happen when a module is imported in two contexts: in one, as a
5366 // user module; in another, as a system module (due to an import from
5367 // another module marked with the [system] flag). It usually indicates a
5368 // bug in the module map: this module should also be marked with [system].
5369 //
5370 // If -Wno-system-headers (the default), and the first import is as a
5371 // system module, then validation will fail during the as-user import,
5372 // since -Werror flags won't have been validated. However, it's reasonable
5373 // to treat this consistently as a system module.
5374 //
5375 // If -Wsystem-headers, the PCM on disk was built with
5376 // -Wno-system-headers, and the first import is as a user module, then
5377 // validation will fail during the as-system import since the PCM on disk
5378 // doesn't guarantee that -Werror was respected. However, the -Werror
5379 // flags were checked during the initial as-user import.
5380 if (getModuleManager().getModuleCache().getInMemoryModuleCache().isPCMFinal(
5381 F.FileName)) {
5382 Diag(diag::warn_module_system_bit_conflict) << F.FileName;
5383 return Success;
5384 }
5385 }
5386
5387 return Result;
5388}
5389
5390ASTReader::ASTReadResult ASTReader::readUnhashedControlBlockImpl(
5391 ModuleFile *F, llvm::StringRef StreamData, StringRef Filename,
5392 unsigned ClientLoadCapabilities, bool AllowCompatibleConfigurationMismatch,
5393 ASTReaderListener *Listener, bool ValidateDiagnosticOptions) {
5394 // Initialize a stream.
5395 BitstreamCursor Stream(StreamData);
5396
5397 // Sniff for the signature.
5398 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5399 // FIXME this drops the error on the floor.
5400 consumeError(std::move(Err));
5401 return Failure;
5402 }
5403
5404 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
5406 return Failure;
5407
5408 // Read all of the records in the options block.
5409 RecordData Record;
5410 ASTReadResult Result = Success;
5411 while (true) {
5412 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5413 if (!MaybeEntry) {
5414 // FIXME this drops the error on the floor.
5415 consumeError(MaybeEntry.takeError());
5416 return Failure;
5417 }
5418 llvm::BitstreamEntry Entry = MaybeEntry.get();
5419
5420 switch (Entry.Kind) {
5421 case llvm::BitstreamEntry::Error:
5422 case llvm::BitstreamEntry::SubBlock:
5423 return Failure;
5424
5425 case llvm::BitstreamEntry::EndBlock:
5426 return Result;
5427
5428 case llvm::BitstreamEntry::Record:
5429 // The interesting case.
5430 break;
5431 }
5432
5433 // Read and process a record.
5434 Record.clear();
5435 StringRef Blob;
5436 Expected<unsigned> MaybeRecordType =
5437 Stream.readRecord(Entry.ID, Record, &Blob);
5438 if (!MaybeRecordType) {
5439 // FIXME this drops the error.
5440 return Failure;
5441 }
5442 switch ((UnhashedControlBlockRecordTypes)MaybeRecordType.get()) {
5443 case SIGNATURE:
5444 if (F) {
5445 F->Signature = ASTFileSignature::create(Blob.begin(), Blob.end());
5447 "Dummy AST file signature not backpatched in ASTWriter.");
5448 }
5449 break;
5450 case AST_BLOCK_HASH:
5451 if (F) {
5452 F->ASTBlockHash = ASTFileSignature::create(Blob.begin(), Blob.end());
5454 "Dummy AST block hash not backpatched in ASTWriter.");
5455 }
5456 break;
5457 case DIAGNOSTIC_OPTIONS: {
5458 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
5459 if (Listener && ValidateDiagnosticOptions &&
5460 !AllowCompatibleConfigurationMismatch &&
5461 ParseDiagnosticOptions(Record, Filename, Complain, *Listener))
5462 Result = OutOfDate; // Don't return early. Read the signature.
5463 break;
5464 }
5465 case HEADER_SEARCH_PATHS: {
5466 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
5467 if (Listener && !AllowCompatibleConfigurationMismatch &&
5468 ParseHeaderSearchPaths(Record, Complain, *Listener))
5469 Result = ConfigurationMismatch;
5470 break;
5471 }
5473 if (!F)
5474 break;
5475 if (F->PragmaDiagMappings.empty())
5476 F->PragmaDiagMappings.swap(Record);
5477 else
5478 F->PragmaDiagMappings.insert(F->PragmaDiagMappings.end(),
5479 Record.begin(), Record.end());
5480 break;
5482 if (F)
5483 F->SearchPathUsage = ReadBitVector(Record, Blob);
5484 break;
5485 case VFS_USAGE:
5486 if (F)
5487 F->VFSUsage = ReadBitVector(Record, Blob);
5488 break;
5489 }
5490 }
5491}
5492
5493/// Parse a record and blob containing module file extension metadata.
5496 StringRef Blob,
5497 ModuleFileExtensionMetadata &Metadata) {
5498 if (Record.size() < 4) return true;
5499
5500 Metadata.MajorVersion = Record[0];
5501 Metadata.MinorVersion = Record[1];
5502
5503 unsigned BlockNameLen = Record[2];
5504 unsigned UserInfoLen = Record[3];
5505
5506 if (BlockNameLen + UserInfoLen > Blob.size()) return true;
5507
5508 Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
5509 Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,
5510 Blob.data() + BlockNameLen + UserInfoLen);
5511 return false;
5512}
5513
5514llvm::Error ASTReader::ReadExtensionBlock(ModuleFile &F) {
5515 BitstreamCursor &Stream = F.Stream;
5516
5517 RecordData Record;
5518 while (true) {
5519 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5520 if (!MaybeEntry)
5521 return MaybeEntry.takeError();
5522 llvm::BitstreamEntry Entry = MaybeEntry.get();
5523
5524 switch (Entry.Kind) {
5525 case llvm::BitstreamEntry::SubBlock:
5526 if (llvm::Error Err = Stream.SkipBlock())
5527 return Err;
5528 continue;
5529 case llvm::BitstreamEntry::EndBlock:
5530 return llvm::Error::success();
5531 case llvm::BitstreamEntry::Error:
5532 return llvm::createStringError(std::errc::illegal_byte_sequence,
5533 "malformed block record in AST file");
5534 case llvm::BitstreamEntry::Record:
5535 break;
5536 }
5537
5538 Record.clear();
5539 StringRef Blob;
5540 Expected<unsigned> MaybeRecCode =
5541 Stream.readRecord(Entry.ID, Record, &Blob);
5542 if (!MaybeRecCode)
5543 return MaybeRecCode.takeError();
5544 switch (MaybeRecCode.get()) {
5545 case EXTENSION_METADATA: {
5546 ModuleFileExtensionMetadata Metadata;
5547 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
5548 return llvm::createStringError(
5549 std::errc::illegal_byte_sequence,
5550 "malformed EXTENSION_METADATA in AST file");
5551
5552 // Find a module file extension with this block name.
5553 auto Known = ModuleFileExtensions.find(Metadata.BlockName);
5554 if (Known == ModuleFileExtensions.end()) break;
5555
5556 // Form a reader.
5557 if (auto Reader = Known->second->createExtensionReader(Metadata, *this,
5558 F, Stream)) {
5559 F.ExtensionReaders.push_back(std::move(Reader));
5560 }
5561
5562 break;
5563 }
5564 }
5565 }
5566
5567 llvm_unreachable("ReadExtensionBlock should return from while loop");
5568}
5569
5571 assert(ContextObj && "no context to initialize");
5572 ASTContext &Context = *ContextObj;
5573
5574 // If there's a listener, notify them that we "read" the translation unit.
5575 if (DeserializationListener)
5576 DeserializationListener->DeclRead(
5578 Context.getTranslationUnitDecl());
5579
5580 // FIXME: Find a better way to deal with collisions between these
5581 // built-in types. Right now, we just ignore the problem.
5582
5583 // Load the special types.
5584 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
5585 if (TypeID String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
5586 if (!Context.CFConstantStringTypeDecl)
5587 Context.setCFConstantStringType(GetType(String));
5588 }
5589
5590 if (TypeID File = SpecialTypes[SPECIAL_TYPE_FILE]) {
5591 QualType FileType = GetType(File);
5592 if (FileType.isNull()) {
5593 Error("FILE type is NULL");
5594 return;
5595 }
5596
5597 if (!Context.FILEDecl) {
5598 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
5599 Context.setFILEDecl(Typedef->getDecl());
5600 else {
5601 const TagType *Tag = FileType->getAs<TagType>();
5602 if (!Tag) {
5603 Error("Invalid FILE type in AST file");
5604 return;
5605 }
5606 Context.setFILEDecl(Tag->getDecl());
5607 }
5608 }
5609 }
5610
5611 if (TypeID Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
5612 QualType Jmp_bufType = GetType(Jmp_buf);
5613 if (Jmp_bufType.isNull()) {
5614 Error("jmp_buf type is NULL");
5615 return;
5616 }
5617
5618 if (!Context.jmp_bufDecl) {
5619 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
5620 Context.setjmp_bufDecl(Typedef->getDecl());
5621 else {
5622 const TagType *Tag = Jmp_bufType->getAs<TagType>();
5623 if (!Tag) {
5624 Error("Invalid jmp_buf type in AST file");
5625 return;
5626 }
5627 Context.setjmp_bufDecl(Tag->getDecl());
5628 }
5629 }
5630 }
5631
5632 if (TypeID Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
5633 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
5634 if (Sigjmp_bufType.isNull()) {
5635 Error("sigjmp_buf type is NULL");
5636 return;
5637 }
5638
5639 if (!Context.sigjmp_bufDecl) {
5640 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
5641 Context.setsigjmp_bufDecl(Typedef->getDecl());
5642 else {
5643 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
5644 assert(Tag && "Invalid sigjmp_buf type in AST file");
5645 Context.setsigjmp_bufDecl(Tag->getDecl());
5646 }
5647 }
5648 }
5649
5650 if (TypeID ObjCIdRedef = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
5651 if (Context.ObjCIdRedefinitionType.isNull())
5652 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
5653 }
5654
5655 if (TypeID ObjCClassRedef =
5657 if (Context.ObjCClassRedefinitionType.isNull())
5658 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
5659 }
5660
5661 if (TypeID ObjCSelRedef =
5662 SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
5663 if (Context.ObjCSelRedefinitionType.isNull())
5664 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
5665 }
5666
5667 if (TypeID Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
5668 QualType Ucontext_tType = GetType(Ucontext_t);
5669 if (Ucontext_tType.isNull()) {
5670 Error("ucontext_t type is NULL");
5671 return;
5672 }
5673
5674 if (!Context.ucontext_tDecl) {
5675 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
5676 Context.setucontext_tDecl(Typedef->getDecl());
5677 else {
5678 const TagType *Tag = Ucontext_tType->getAs<TagType>();
5679 assert(Tag && "Invalid ucontext_t type in AST file");
5680 Context.setucontext_tDecl(Tag->getDecl());
5681 }
5682 }
5683 }
5684 }
5685
5686 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
5687
5688 // If there were any CUDA special declarations, deserialize them.
5689 if (!CUDASpecialDeclRefs.empty()) {
5690 assert(CUDASpecialDeclRefs.size() == 3 && "More decl refs than expected!");
5691 Context.setcudaConfigureCallDecl(
5692 cast_or_null<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
5693 Context.setcudaGetParameterBufferDecl(
5694 cast_or_null<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[1])));
5695 Context.setcudaLaunchDeviceDecl(
5696 cast_or_null<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[2])));
5697 }
5698
5699 // Re-export any modules that were imported by a non-module AST file.
5700 // FIXME: This does not make macro-only imports visible again.
5701 for (auto &Import : PendingImportedModules) {
5702 if (Module *Imported = getSubmodule(Import.ID)) {
5704 /*ImportLoc=*/Import.ImportLoc);
5705 if (Import.ImportLoc.isValid())
5706 PP.makeModuleVisible(Imported, Import.ImportLoc);
5707 // This updates visibility for Preprocessor only. For Sema, which can be
5708 // nullptr here, we do the same later, in UpdateSema().
5709 }
5710 }
5711
5712 // Hand off these modules to Sema.
5713 PendingImportedModulesSema.append(PendingImportedModules);
5714 PendingImportedModules.clear();
5715}
5716
5718 // Nothing to do for now.
5719}
5720
5721/// Reads and return the signature record from \p PCH's control block, or
5722/// else returns 0.
5724 BitstreamCursor Stream(PCH);
5725 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5726 // FIXME this drops the error on the floor.
5727 consumeError(std::move(Err));
5728 return ASTFileSignature();
5729 }
5730
5731 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
5733 return ASTFileSignature();
5734
5735 // Scan for SIGNATURE inside the diagnostic options block.
5737 while (true) {
5739 Stream.advanceSkippingSubblocks();
5740 if (!MaybeEntry) {
5741 // FIXME this drops the error on the floor.
5742 consumeError(MaybeEntry.takeError());
5743 return ASTFileSignature();
5744 }
5745 llvm::BitstreamEntry Entry = MaybeEntry.get();
5746
5747 if (Entry.Kind != llvm::BitstreamEntry::Record)
5748 return ASTFileSignature();
5749
5750 Record.clear();
5751 StringRef Blob;
5752 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);
5753 if (!MaybeRecord) {
5754 // FIXME this drops the error on the floor.
5755 consumeError(MaybeRecord.takeError());
5756 return ASTFileSignature();
5757 }
5758 if (SIGNATURE == MaybeRecord.get()) {
5759 auto Signature = ASTFileSignature::create(Blob.begin(), Blob.end());
5760 assert(Signature != ASTFileSignature::createDummy() &&
5761 "Dummy AST file signature not backpatched in ASTWriter.");
5762 return Signature;
5763 }
5764 }
5765}
5766
5767/// Retrieve the name of the original source file name
5768/// directly from the AST file, without actually loading the AST
5769/// file.
5771 const std::string &ASTFileName, FileManager &FileMgr,
5772 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
5773 // Open the AST file.
5774 auto Buffer = FileMgr.getBufferForFile(ASTFileName, /*IsVolatile=*/false,
5775 /*RequiresNullTerminator=*/false,
5776 /*MaybeLimit=*/std::nullopt,
5777 /*IsText=*/false);
5778 if (!Buffer) {
5779 Diags.Report(diag::err_fe_unable_to_read_pch_file)
5780 << ASTFileName << Buffer.getError().message();
5781 return std::string();
5782 }
5783
5784 // Initialize the stream
5785 BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer));
5786
5787 // Sniff for the signature.
5788 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5789 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName << std::move(Err);
5790 return std::string();
5791 }
5792
5793 // Scan for the CONTROL_BLOCK_ID block.
5794 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
5795 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
5796 return std::string();
5797 }
5798
5799 // Scan for ORIGINAL_FILE inside the control block.
5801 while (true) {
5803 Stream.advanceSkippingSubblocks();
5804 if (!MaybeEntry) {
5805 // FIXME this drops errors on the floor.
5806 consumeError(MaybeEntry.takeError());
5807 return std::string();
5808 }
5809 llvm::BitstreamEntry Entry = MaybeEntry.get();
5810
5811 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
5812 return std::string();
5813
5814 if (Entry.Kind != llvm::BitstreamEntry::Record) {
5815 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
5816 return std::string();
5817 }
5818
5819 Record.clear();
5820 StringRef Blob;
5821 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);
5822 if (!MaybeRecord) {
5823 // FIXME this drops the errors on the floor.
5824 consumeError(MaybeRecord.takeError());
5825 return std::string();
5826 }
5827 if (ORIGINAL_FILE == MaybeRecord.get())
5828 return Blob.str();
5829 }
5830}
5831
5832namespace {
5833
5834 class SimplePCHValidator : public ASTReaderListener {
5835 const LangOptions &ExistingLangOpts;
5836 const CodeGenOptions &ExistingCGOpts;
5837 const TargetOptions &ExistingTargetOpts;
5838 const PreprocessorOptions &ExistingPPOpts;
5839 const HeaderSearchOptions &ExistingHSOpts;
5840 std::string ExistingSpecificModuleCachePath;
5842 bool StrictOptionMatches;
5843
5844 public:
5845 SimplePCHValidator(const LangOptions &ExistingLangOpts,
5846 const CodeGenOptions &ExistingCGOpts,
5847 const TargetOptions &ExistingTargetOpts,
5848 const PreprocessorOptions &ExistingPPOpts,
5849 const HeaderSearchOptions &ExistingHSOpts,
5850 StringRef ExistingSpecificModuleCachePath,
5851 FileManager &FileMgr, bool StrictOptionMatches)
5852 : ExistingLangOpts(ExistingLangOpts), ExistingCGOpts(ExistingCGOpts),
5853 ExistingTargetOpts(ExistingTargetOpts),
5854 ExistingPPOpts(ExistingPPOpts), ExistingHSOpts(ExistingHSOpts),
5855 ExistingSpecificModuleCachePath(ExistingSpecificModuleCachePath),
5856 FileMgr(FileMgr), StrictOptionMatches(StrictOptionMatches) {}
5857
5858 bool ReadLanguageOptions(const LangOptions &LangOpts,
5859 StringRef ModuleFilename, bool Complain,
5860 bool AllowCompatibleDifferences) override {
5861 return checkLanguageOptions(ExistingLangOpts, LangOpts, ModuleFilename,
5862 nullptr, AllowCompatibleDifferences);
5863 }
5864
5865 bool ReadCodeGenOptions(const CodeGenOptions &CGOpts,
5866 StringRef ModuleFilename, bool Complain,
5867 bool AllowCompatibleDifferences) override {
5868 return checkCodegenOptions(ExistingCGOpts, CGOpts, ModuleFilename,
5869 nullptr, AllowCompatibleDifferences);
5870 }
5871
5872 bool ReadTargetOptions(const TargetOptions &TargetOpts,
5873 StringRef ModuleFilename, bool Complain,
5874 bool AllowCompatibleDifferences) override {
5875 return checkTargetOptions(ExistingTargetOpts, TargetOpts, ModuleFilename,
5876 nullptr, AllowCompatibleDifferences);
5877 }
5878
5879 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
5880 StringRef ASTFilename,
5881 StringRef SpecificModuleCachePath,
5882 bool Complain) override {
5883 return checkModuleCachePath(
5884 FileMgr.getVirtualFileSystem(), SpecificModuleCachePath,
5885 ExistingSpecificModuleCachePath, ASTFilename, nullptr,
5886 ExistingLangOpts, ExistingPPOpts, ExistingHSOpts, HSOpts);
5887 }
5888
5889 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
5890 StringRef ModuleFilename, bool ReadMacros,
5891 bool Complain,
5892 std::string &SuggestedPredefines) override {
5894 PPOpts, ExistingPPOpts, ModuleFilename, ReadMacros, /*Diags=*/nullptr,
5895 FileMgr, SuggestedPredefines, ExistingLangOpts,
5896 StrictOptionMatches ? OptionValidateStrictMatches
5898 }
5899 };
5900
5901} // namespace
5902
5904 StringRef Filename, FileManager &FileMgr, const ModuleCache &ModCache,
5905 const PCHContainerReader &PCHContainerRdr, bool FindModuleFileExtensions,
5906 ASTReaderListener &Listener, bool ValidateDiagnosticOptions,
5907 unsigned ClientLoadCapabilities) {
5908 // Open the AST file.
5909 std::unique_ptr<llvm::MemoryBuffer> OwnedBuffer;
5910 llvm::MemoryBuffer *Buffer =
5911 ModCache.getInMemoryModuleCache().lookupPCM(Filename);
5912 if (!Buffer) {
5913 // FIXME: We should add the pcm to the InMemoryModuleCache if it could be
5914 // read again later, but we do not have the context here to determine if it
5915 // is safe to change the result of InMemoryModuleCache::getPCMState().
5916
5917 // FIXME: This allows use of the VFS; we do not allow use of the
5918 // VFS when actually loading a module.
5919 auto Entry =
5920 Filename == "-" ? FileMgr.getSTDIN() : FileMgr.getFileRef(Filename);
5921 if (!Entry) {
5922 llvm::consumeError(Entry.takeError());
5923 return true;
5924 }
5925 auto BufferOrErr = FileMgr.getBufferForFile(*Entry);
5926 if (!BufferOrErr)
5927 return true;
5928 OwnedBuffer = std::move(*BufferOrErr);
5929 Buffer = OwnedBuffer.get();
5930 }
5931
5932 // Initialize the stream
5933 StringRef Bytes = PCHContainerRdr.ExtractPCH(*Buffer);
5934 BitstreamCursor Stream(Bytes);
5935
5936 // Sniff for the signature.
5937 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5938 consumeError(std::move(Err)); // FIXME this drops errors on the floor.
5939 return true;
5940 }
5941
5942 // Scan for the CONTROL_BLOCK_ID block.
5944 return true;
5945
5946 bool NeedsInputFiles = Listener.needsInputFileVisitation();
5947 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
5948 bool NeedsImports = Listener.needsImportVisitation();
5949 BitstreamCursor InputFilesCursor;
5950 uint64_t InputFilesOffsetBase = 0;
5951
5953 std::string ModuleDir;
5954 bool DoneWithControlBlock = false;
5955 SmallString<0> PathBuf;
5956 PathBuf.reserve(256);
5957 // Additional path buffer to use when multiple paths need to be resolved.
5958 // For example, when deserializing input files that contains a path that was
5959 // resolved from a vfs overlay and an external location.
5960 SmallString<0> AdditionalPathBuf;
5961 AdditionalPathBuf.reserve(256);
5962 while (!DoneWithControlBlock) {
5963 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5964 if (!MaybeEntry) {
5965 // FIXME this drops the error on the floor.
5966 consumeError(MaybeEntry.takeError());
5967 return true;
5968 }
5969 llvm::BitstreamEntry Entry = MaybeEntry.get();
5970
5971 switch (Entry.Kind) {
5972 case llvm::BitstreamEntry::SubBlock: {
5973 switch (Entry.ID) {
5974 case OPTIONS_BLOCK_ID: {
5975 std::string IgnoredSuggestedPredefines;
5976 if (ReadOptionsBlock(Stream, Filename, ClientLoadCapabilities,
5977 /*AllowCompatibleConfigurationMismatch*/ false,
5978 Listener, IgnoredSuggestedPredefines) != Success)
5979 return true;
5980 break;
5981 }
5982
5984 InputFilesCursor = Stream;
5985 if (llvm::Error Err = Stream.SkipBlock()) {
5986 // FIXME this drops the error on the floor.
5987 consumeError(std::move(Err));
5988 return true;
5989 }
5990 if (NeedsInputFiles &&
5991 ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID))
5992 return true;
5993 InputFilesOffsetBase = InputFilesCursor.GetCurrentBitNo();
5994 break;
5995
5996 default:
5997 if (llvm::Error Err = Stream.SkipBlock()) {
5998 // FIXME this drops the error on the floor.
5999 consumeError(std::move(Err));
6000 return true;
6001 }
6002 break;
6003 }
6004
6005 continue;
6006 }
6007
6008 case llvm::BitstreamEntry::EndBlock:
6009 DoneWithControlBlock = true;
6010 break;
6011
6012 case llvm::BitstreamEntry::Error:
6013 return true;
6014
6015 case llvm::BitstreamEntry::Record:
6016 break;
6017 }
6018
6019 if (DoneWithControlBlock) break;
6020
6021 Record.clear();
6022 StringRef Blob;
6023 Expected<unsigned> MaybeRecCode =
6024 Stream.readRecord(Entry.ID, Record, &Blob);
6025 if (!MaybeRecCode) {
6026 // FIXME this drops the error.
6027 return Failure;
6028 }
6029 switch ((ControlRecordTypes)MaybeRecCode.get()) {
6030 case METADATA:
6031 if (Record[0] != VERSION_MAJOR)
6032 return true;
6033 if (Listener.ReadFullVersionInformation(Blob))
6034 return true;
6035 break;
6036 case MODULE_NAME:
6037 Listener.ReadModuleName(Blob);
6038 break;
6039 case MODULE_DIRECTORY:
6040 ModuleDir = std::string(Blob);
6041 break;
6042 case MODULE_MAP_FILE: {
6043 unsigned Idx = 0;
6044 std::string PathStr = ReadString(Record, Idx);
6045 auto Path = ResolveImportedPath(PathBuf, PathStr, ModuleDir);
6046 Listener.ReadModuleMapFile(*Path);
6047 break;
6048 }
6049 case INPUT_FILE_OFFSETS: {
6050 if (!NeedsInputFiles)
6051 break;
6052
6053 unsigned NumInputFiles = Record[0];
6054 unsigned NumUserFiles = Record[1];
6055 const llvm::support::unaligned_uint64_t *InputFileOffs =
6056 (const llvm::support::unaligned_uint64_t *)Blob.data();
6057 for (unsigned I = 0; I != NumInputFiles; ++I) {
6058 // Go find this input file.
6059 bool isSystemFile = I >= NumUserFiles;
6060
6061 if (isSystemFile && !NeedsSystemInputFiles)
6062 break; // the rest are system input files
6063
6064 BitstreamCursor &Cursor = InputFilesCursor;
6065 SavedStreamPosition SavedPosition(Cursor);
6066 if (llvm::Error Err =
6067 Cursor.JumpToBit(InputFilesOffsetBase + InputFileOffs[I])) {
6068 // FIXME this drops errors on the floor.
6069 consumeError(std::move(Err));
6070 }
6071
6072 Expected<unsigned> MaybeCode = Cursor.ReadCode();
6073 if (!MaybeCode) {
6074 // FIXME this drops errors on the floor.
6075 consumeError(MaybeCode.takeError());
6076 }
6077 unsigned Code = MaybeCode.get();
6078
6080 StringRef Blob;
6081 bool shouldContinue = false;
6082 Expected<unsigned> MaybeRecordType =
6083 Cursor.readRecord(Code, Record, &Blob);
6084 if (!MaybeRecordType) {
6085 // FIXME this drops errors on the floor.
6086 consumeError(MaybeRecordType.takeError());
6087 }
6088 switch ((InputFileRecordTypes)MaybeRecordType.get()) {
6089 case INPUT_FILE_HASH:
6090 break;
6091 case INPUT_FILE:
6092 time_t StoredTime = static_cast<time_t>(Record[2]);
6093 bool Overridden = static_cast<bool>(Record[3]);
6094 auto [UnresolvedFilenameAsRequested, UnresolvedFilename] =
6096 auto FilenameAsRequestedBuf = ResolveImportedPath(
6097 PathBuf, UnresolvedFilenameAsRequested, ModuleDir);
6098 StringRef Filename;
6099 if (UnresolvedFilename.empty())
6100 Filename = *FilenameAsRequestedBuf;
6101 else {
6102 auto FilenameBuf = ResolveImportedPath(
6103 AdditionalPathBuf, UnresolvedFilename, ModuleDir);
6104 Filename = *FilenameBuf;
6105 }
6106 shouldContinue = Listener.visitInputFileAsRequested(
6107 *FilenameAsRequestedBuf, Filename, isSystemFile, Overridden,
6108 StoredTime, /*IsExplicitModule=*/false);
6109 break;
6110 }
6111 if (!shouldContinue)
6112 break;
6113 }
6114 break;
6115 }
6116
6117 case IMPORT: {
6118 if (!NeedsImports)
6119 break;
6120
6121 unsigned Idx = 0;
6122 // Read information about the AST file.
6123
6124 // Skip Kind
6125 Idx++;
6126
6127 // Skip ImportLoc
6128 Idx++;
6129
6130 StringRef ModuleName = ReadStringBlob(Record, Idx, Blob);
6131
6132 bool IsStandardCXXModule = Record[Idx++];
6133
6134 // In C++20 Modules, we don't record the path to imported
6135 // modules in the BMI files.
6136 if (IsStandardCXXModule) {
6137 Listener.visitImport(ModuleName, /*Filename=*/"");
6138 continue;
6139 }
6140
6141 // Skip Size and ModTime.
6142 Idx += 1 + 1;
6143 // Skip signature.
6144 Blob = Blob.substr(ASTFileSignature::size);
6145
6146 StringRef FilenameStr = ReadStringBlob(Record, Idx, Blob);
6147 auto Filename = ResolveImportedPath(PathBuf, FilenameStr, ModuleDir);
6148 Listener.visitImport(ModuleName, *Filename);
6149 break;
6150 }
6151
6152 default:
6153 // No other validation to perform.
6154 break;
6155 }
6156 }
6157
6158 // Look for module file extension blocks, if requested.
6159 if (FindModuleFileExtensions) {
6160 BitstreamCursor SavedStream = Stream;
6161 while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {
6162 bool DoneWithExtensionBlock = false;
6163 while (!DoneWithExtensionBlock) {
6164 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
6165 if (!MaybeEntry) {
6166 // FIXME this drops the error.
6167 return true;
6168 }
6169 llvm::BitstreamEntry Entry = MaybeEntry.get();
6170
6171 switch (Entry.Kind) {
6172 case llvm::BitstreamEntry::SubBlock:
6173 if (llvm::Error Err = Stream.SkipBlock()) {
6174 // FIXME this drops the error on the floor.
6175 consumeError(std::move(Err));
6176 return true;
6177 }
6178 continue;
6179
6180 case llvm::BitstreamEntry::EndBlock:
6181 DoneWithExtensionBlock = true;
6182 continue;
6183
6184 case llvm::BitstreamEntry::Error:
6185 return true;
6186
6187 case llvm::BitstreamEntry::Record:
6188 break;
6189 }
6190
6191 Record.clear();
6192 StringRef Blob;
6193 Expected<unsigned> MaybeRecCode =
6194 Stream.readRecord(Entry.ID, Record, &Blob);
6195 if (!MaybeRecCode) {
6196 // FIXME this drops the error.
6197 return true;
6198 }
6199 switch (MaybeRecCode.get()) {
6200 case EXTENSION_METADATA: {
6202 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
6203 return true;
6204
6205 Listener.readModuleFileExtension(Metadata);
6206 break;
6207 }
6208 }
6209 }
6210 }
6211 Stream = std::move(SavedStream);
6212 }
6213
6214 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
6215 if (readUnhashedControlBlockImpl(
6216 nullptr, Bytes, Filename, ClientLoadCapabilities,
6217 /*AllowCompatibleConfigurationMismatch*/ false, &Listener,
6218 ValidateDiagnosticOptions) != Success)
6219 return true;
6220
6221 return false;
6222}
6223
6225 StringRef Filename, FileManager &FileMgr, const ModuleCache &ModCache,
6226 const PCHContainerReader &PCHContainerRdr, const LangOptions &LangOpts,
6227 const CodeGenOptions &CGOpts, const TargetOptions &TargetOpts,
6228 const PreprocessorOptions &PPOpts, const HeaderSearchOptions &HSOpts,
6229 StringRef SpecificModuleCachePath, bool RequireStrictOptionMatches) {
6230 SimplePCHValidator validator(LangOpts, CGOpts, TargetOpts, PPOpts, HSOpts,
6231 SpecificModuleCachePath, FileMgr,
6232 RequireStrictOptionMatches);
6233 return !readASTFileControlBlock(Filename, FileMgr, ModCache, PCHContainerRdr,
6234 /*FindModuleFileExtensions=*/false, validator,
6235 /*ValidateDiagnosticOptions=*/true);
6236}
6237
6238llvm::Error ASTReader::ReadSubmoduleBlock(ModuleFile &F,
6239 unsigned ClientLoadCapabilities) {
6240 // Enter the submodule block.
6241 if (llvm::Error Err = F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID))
6242 return Err;
6243
6244 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
6245 bool KnowsTopLevelModule = ModMap.findModule(F.ModuleName) != nullptr;
6246 // If we don't know the top-level module, there's no point in doing qualified
6247 // lookup of its submodules; it won't find anything anywhere within this tree.
6248 // Let's skip that and avoid some string lookups.
6249 auto CreateModule = !KnowsTopLevelModule
6252
6253 bool First = true;
6254 Module *CurrentModule = nullptr;
6255 RecordData Record;
6256 while (true) {
6258 F.Stream.advanceSkippingSubblocks();
6259 if (!MaybeEntry)
6260 return MaybeEntry.takeError();
6261 llvm::BitstreamEntry Entry = MaybeEntry.get();
6262
6263 switch (Entry.Kind) {
6264 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
6265 case llvm::BitstreamEntry::Error:
6266 return llvm::createStringError(std::errc::illegal_byte_sequence,
6267 "malformed block record in AST file");
6268 case llvm::BitstreamEntry::EndBlock:
6269 return llvm::Error::success();
6270 case llvm::BitstreamEntry::Record:
6271 // The interesting case.
6272 break;
6273 }
6274
6275 // Read a record.
6276 StringRef Blob;
6277 Record.clear();
6278 Expected<unsigned> MaybeKind = F.Stream.readRecord(Entry.ID, Record, &Blob);
6279 if (!MaybeKind)
6280 return MaybeKind.takeError();
6281 unsigned Kind = MaybeKind.get();
6282
6283 if ((Kind == SUBMODULE_METADATA) != First)
6284 return llvm::createStringError(
6285 std::errc::illegal_byte_sequence,
6286 "submodule metadata record should be at beginning of block");
6287 First = false;
6288
6289 // Submodule information is only valid if we have a current module.
6290 // FIXME: Should we error on these cases?
6291 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
6292 Kind != SUBMODULE_DEFINITION)
6293 continue;
6294
6295 switch (Kind) {
6296 default: // Default behavior: ignore.
6297 break;
6298
6299 case SUBMODULE_DEFINITION: {
6300 if (Record.size() < 13)
6301 return llvm::createStringError(std::errc::illegal_byte_sequence,
6302 "malformed module definition");
6303
6304 StringRef Name = Blob;
6305 unsigned Idx = 0;
6306 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
6307 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
6309 SourceLocation DefinitionLoc = ReadSourceLocation(F, Record[Idx++]);
6310 FileID InferredAllowedBy = ReadFileID(F, Record, Idx);
6311 bool IsFramework = Record[Idx++];
6312 bool IsExplicit = Record[Idx++];
6313 bool IsSystem = Record[Idx++];
6314 bool IsExternC = Record[Idx++];
6315 bool InferSubmodules = Record[Idx++];
6316 bool InferExplicitSubmodules = Record[Idx++];
6317 bool InferExportWildcard = Record[Idx++];
6318 bool ConfigMacrosExhaustive = Record[Idx++];
6319 bool ModuleMapIsPrivate = Record[Idx++];
6320 bool NamedModuleHasInit = Record[Idx++];
6321
6322 Module *ParentModule = nullptr;
6323 if (Parent)
6324 ParentModule = getSubmodule(Parent);
6325
6326 CurrentModule = std::invoke(CreateModule, &ModMap, Name, ParentModule,
6327 IsFramework, IsExplicit);
6328
6329 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
6330 if (GlobalIndex >= SubmodulesLoaded.size() ||
6331 SubmodulesLoaded[GlobalIndex])
6332 return llvm::createStringError(std::errc::invalid_argument,
6333 "too many submodules");
6334
6335 if (!ParentModule) {
6336 if (OptionalFileEntryRef CurFile = CurrentModule->getASTFile()) {
6337 // Don't emit module relocation error if we have -fno-validate-pch
6338 if (!bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation &
6340 assert(CurFile != F.File && "ModuleManager did not de-duplicate");
6341
6342 Diag(diag::err_module_file_conflict)
6343 << CurrentModule->getTopLevelModuleName() << CurFile->getName()
6344 << F.File.getName();
6345
6346 auto CurModMapFile =
6347 ModMap.getContainingModuleMapFile(CurrentModule);
6348 auto ModMapFile = FileMgr.getOptionalFileRef(F.ModuleMapPath);
6349 if (CurModMapFile && ModMapFile && CurModMapFile != ModMapFile)
6350 Diag(diag::note_module_file_conflict)
6351 << CurModMapFile->getName() << ModMapFile->getName();
6352
6353 return llvm::make_error<AlreadyReportedDiagnosticError>();
6354 }
6355 }
6356
6357 F.DidReadTopLevelSubmodule = true;
6358 CurrentModule->setASTFile(F.File);
6359 CurrentModule->PresumedModuleMapFile = F.ModuleMapPath;
6360 }
6361
6362 CurrentModule->Kind = Kind;
6363 // Note that we may be rewriting an existing location and it is important
6364 // to keep doing that. In particular, we would like to prefer a
6365 // `DefinitionLoc` loaded from the module file instead of the location
6366 // created in the current source manager, because it allows the new
6367 // location to be marked as "unaffecting" when writing and avoid creating
6368 // duplicate locations for the same module map file.
6369 CurrentModule->DefinitionLoc = DefinitionLoc;
6370 CurrentModule->Signature = F.Signature;
6371 CurrentModule->IsFromModuleFile = true;
6372 if (InferredAllowedBy.isValid())
6373 ModMap.setInferredModuleAllowedBy(CurrentModule, InferredAllowedBy);
6374 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
6375 CurrentModule->IsExternC = IsExternC;
6376 CurrentModule->InferSubmodules = InferSubmodules;
6377 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
6378 CurrentModule->InferExportWildcard = InferExportWildcard;
6379 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
6380 CurrentModule->ModuleMapIsPrivate = ModuleMapIsPrivate;
6381 CurrentModule->NamedModuleHasInit = NamedModuleHasInit;
6382
6383 if (!ParentModule && !F.BaseDirectory.empty()) {
6384 if (auto Dir = FileMgr.getOptionalDirectoryRef(F.BaseDirectory))
6385 CurrentModule->Directory = *Dir;
6386 } else if (ParentModule && ParentModule->Directory) {
6387 // Submodules inherit the directory from their parent.
6388 CurrentModule->Directory = ParentModule->Directory;
6389 }
6390
6391 if (DeserializationListener)
6392 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
6393
6394 SubmodulesLoaded[GlobalIndex] = CurrentModule;
6395
6396 // Clear out data that will be replaced by what is in the module file.
6397 CurrentModule->LinkLibraries.clear();
6398 CurrentModule->ConfigMacros.clear();
6399 CurrentModule->UnresolvedConflicts.clear();
6400 CurrentModule->Conflicts.clear();
6401
6402 // The module is available unless it's missing a requirement; relevant
6403 // requirements will be (re-)added by SUBMODULE_REQUIRES records.
6404 // Missing headers that were present when the module was built do not
6405 // make it unavailable -- if we got this far, this must be an explicitly
6406 // imported module file.
6407 CurrentModule->Requirements.clear();
6408 CurrentModule->MissingHeaders.clear();
6409 CurrentModule->IsUnimportable =
6410 ParentModule && ParentModule->IsUnimportable;
6411 CurrentModule->IsAvailable = !CurrentModule->IsUnimportable;
6412 break;
6413 }
6414
6416 SmallString<128> RelativePathName;
6417 if (auto Umbrella = ModMap.findUmbrellaHeaderForModule(
6418 CurrentModule, Blob.str(), RelativePathName)) {
6419 if (!CurrentModule->getUmbrellaHeaderAsWritten()) {
6420 ModMap.setUmbrellaHeaderAsWritten(CurrentModule, *Umbrella, Blob,
6421 RelativePathName);
6422 }
6423 // Note that it's too late at this point to return out of date if the
6424 // name from the PCM doesn't match up with the one in the module map,
6425 // but also quite unlikely since we will have already checked the
6426 // modification time and size of the module map file itself.
6427 }
6428 break;
6429 }
6430
6431 case SUBMODULE_HEADER:
6434 // We lazily associate headers with their modules via the HeaderInfo table.
6435 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
6436 // of complete filenames or remove it entirely.
6437 break;
6438
6441 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
6442 // them here.
6443 break;
6444
6445 case SUBMODULE_TOPHEADER: {
6446 auto HeaderName = ResolveImportedPath(PathBuf, Blob, F);
6447 CurrentModule->addTopHeaderFilename(*HeaderName);
6448 break;
6449 }
6450
6452 auto Dirname = ResolveImportedPath(PathBuf, Blob, F);
6453 if (auto Umbrella =
6454 PP.getFileManager().getOptionalDirectoryRef(*Dirname)) {
6455 if (!CurrentModule->getUmbrellaDirAsWritten()) {
6456 // FIXME: NameAsWritten
6457 ModMap.setUmbrellaDirAsWritten(CurrentModule, *Umbrella, Blob, "");
6458 }
6459 }
6460 break;
6461 }
6462
6463 case SUBMODULE_METADATA: {
6464 F.BaseSubmoduleID = getTotalNumSubmodules();
6466 unsigned LocalBaseSubmoduleID = Record[1];
6467 if (F.LocalNumSubmodules > 0) {
6468 // Introduce the global -> local mapping for submodules within this
6469 // module.
6470 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
6471
6472 // Introduce the local -> global mapping for submodules within this
6473 // module.
6475 std::make_pair(LocalBaseSubmoduleID,
6476 F.BaseSubmoduleID - LocalBaseSubmoduleID));
6477
6478 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
6479 }
6480 break;
6481 }
6482
6483 case SUBMODULE_IMPORTS:
6484 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
6485 UnresolvedModuleRef Unresolved;
6486 Unresolved.File = &F;
6487 Unresolved.Mod = CurrentModule;
6488 Unresolved.ID = Record[Idx];
6489 Unresolved.Kind = UnresolvedModuleRef::Import;
6490 Unresolved.IsWildcard = false;
6491 UnresolvedModuleRefs.push_back(Unresolved);
6492 }
6493 break;
6494
6496 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
6497 UnresolvedModuleRef Unresolved;
6498 Unresolved.File = &F;
6499 Unresolved.Mod = CurrentModule;
6500 Unresolved.ID = Record[Idx];
6501 Unresolved.Kind = UnresolvedModuleRef::Affecting;
6502 Unresolved.IsWildcard = false;
6503 UnresolvedModuleRefs.push_back(Unresolved);
6504 }
6505 break;
6506
6507 case SUBMODULE_EXPORTS:
6508 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
6509 UnresolvedModuleRef Unresolved;
6510 Unresolved.File = &F;
6511 Unresolved.Mod = CurrentModule;
6512 Unresolved.ID = Record[Idx];
6513 Unresolved.Kind = UnresolvedModuleRef::Export;
6514 Unresolved.IsWildcard = Record[Idx + 1];
6515 UnresolvedModuleRefs.push_back(Unresolved);
6516 }
6517
6518 // Once we've loaded the set of exports, there's no reason to keep
6519 // the parsed, unresolved exports around.
6520 CurrentModule->UnresolvedExports.clear();
6521 break;
6522
6523 case SUBMODULE_REQUIRES:
6524 CurrentModule->addRequirement(Blob, Record[0], PP.getLangOpts(),
6525 PP.getTargetInfo());
6526 break;
6527
6529 ModMap.resolveLinkAsDependencies(CurrentModule);
6530 CurrentModule->LinkLibraries.push_back(
6531 Module::LinkLibrary(std::string(Blob), Record[0]));
6532 break;
6533
6535 CurrentModule->ConfigMacros.push_back(Blob.str());
6536 break;
6537
6538 case SUBMODULE_CONFLICT: {
6539 UnresolvedModuleRef Unresolved;
6540 Unresolved.File = &F;
6541 Unresolved.Mod = CurrentModule;
6542 Unresolved.ID = Record[0];
6543 Unresolved.Kind = UnresolvedModuleRef::Conflict;
6544 Unresolved.IsWildcard = false;
6545 Unresolved.String = Blob;
6546 UnresolvedModuleRefs.push_back(Unresolved);
6547 break;
6548 }
6549
6551 if (!ContextObj)
6552 break;
6553 // Standard C++ module has its own way to initialize variables.
6554 if (!F.StandardCXXModule || F.Kind == MK_MainFile) {
6555 SmallVector<GlobalDeclID, 16> Inits;
6556 for (unsigned I = 0; I < Record.size(); /*in loop*/)
6557 Inits.push_back(ReadDeclID(F, Record, I));
6558 ContextObj->addLazyModuleInitializers(CurrentModule, Inits);
6559 }
6560 break;
6561 }
6562
6564 CurrentModule->ExportAsModule = Blob.str();
6565 ModMap.addLinkAsDependency(CurrentModule);
6566 break;
6567 }
6568 }
6569}
6570
6571/// Parse the record that corresponds to a LangOptions data
6572/// structure.
6573///
6574/// This routine parses the language options from the AST file and then gives
6575/// them to the AST listener if one is set.
6576///
6577/// \returns true if the listener deems the file unacceptable, false otherwise.
6578bool ASTReader::ParseLanguageOptions(const RecordData &Record,
6579 StringRef ModuleFilename, bool Complain,
6580 ASTReaderListener &Listener,
6581 bool AllowCompatibleDifferences) {
6582 LangOptions LangOpts;
6583 unsigned Idx = 0;
6584#define LANGOPT(Name, Bits, Default, Compatibility, Description) \
6585 LangOpts.Name = Record[Idx++];
6586#define ENUM_LANGOPT(Name, Type, Bits, Default, Compatibility, Description) \
6587 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
6588#include "clang/Basic/LangOptions.def"
6589#define SANITIZER(NAME, ID) \
6590 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
6591#include "clang/Basic/Sanitizers.def"
6592
6593 for (unsigned N = Record[Idx++]; N; --N)
6594 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
6595
6596 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
6597 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
6598 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
6599
6600 LangOpts.CurrentModule = ReadString(Record, Idx);
6601
6602 // Comment options.
6603 for (unsigned N = Record[Idx++]; N; --N) {
6604 LangOpts.CommentOpts.BlockCommandNames.push_back(
6605 ReadString(Record, Idx));
6606 }
6607 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
6608
6609 // OpenMP offloading options.
6610 for (unsigned N = Record[Idx++]; N; --N) {
6611 LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx)));
6612 }
6613
6614 LangOpts.OMPHostIRFile = ReadString(Record, Idx);
6615
6616 return Listener.ReadLanguageOptions(LangOpts, ModuleFilename, Complain,
6617 AllowCompatibleDifferences);
6618}
6619
6620bool ASTReader::ParseCodeGenOptions(const RecordData &Record,
6621 StringRef ModuleFilename, bool Complain,
6622 ASTReaderListener &Listener,
6623 bool AllowCompatibleDifferences) {
6624 unsigned Idx = 0;
6625 CodeGenOptions CGOpts;
6627#define CODEGENOPT(Name, Bits, Default, Compatibility) \
6628 if constexpr (CK::Compatibility != CK::Benign) \
6629 CGOpts.Name = static_cast<unsigned>(Record[Idx++]);
6630#define ENUM_CODEGENOPT(Name, Type, Bits, Default, Compatibility) \
6631 if constexpr (CK::Compatibility != CK::Benign) \
6632 CGOpts.set##Name(static_cast<clang::CodeGenOptions::Type>(Record[Idx++]));
6633#define DEBUGOPT(Name, Bits, Default, Compatibility)
6634#define VALUE_DEBUGOPT(Name, Bits, Default, Compatibility)
6635#define ENUM_DEBUGOPT(Name, Type, Bits, Default, Compatibility)
6636#include "clang/Basic/CodeGenOptions.def"
6637
6638 return Listener.ReadCodeGenOptions(CGOpts, ModuleFilename, Complain,
6639 AllowCompatibleDifferences);
6640}
6641
6642bool ASTReader::ParseTargetOptions(const RecordData &Record,
6643 StringRef ModuleFilename, bool Complain,
6644 ASTReaderListener &Listener,
6645 bool AllowCompatibleDifferences) {
6646 unsigned Idx = 0;
6647 TargetOptions TargetOpts;
6648 TargetOpts.Triple = ReadString(Record, Idx);
6649 TargetOpts.CPU = ReadString(Record, Idx);
6650 TargetOpts.TuneCPU = ReadString(Record, Idx);
6651 TargetOpts.ABI = ReadString(Record, Idx);
6652 for (unsigned N = Record[Idx++]; N; --N) {
6653 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
6654 }
6655 for (unsigned N = Record[Idx++]; N; --N) {
6656 TargetOpts.Features.push_back(ReadString(Record, Idx));
6657 }
6658
6659 return Listener.ReadTargetOptions(TargetOpts, ModuleFilename, Complain,
6660 AllowCompatibleDifferences);
6661}
6662
6663bool ASTReader::ParseDiagnosticOptions(const RecordData &Record,
6664 StringRef ModuleFilename, bool Complain,
6665 ASTReaderListener &Listener) {
6666 DiagnosticOptions DiagOpts;
6667 unsigned Idx = 0;
6668#define DIAGOPT(Name, Bits, Default) DiagOpts.Name = Record[Idx++];
6669#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
6670 DiagOpts.set##Name(static_cast<Type>(Record[Idx++]));
6671#include "clang/Basic/DiagnosticOptions.def"
6672
6673 for (unsigned N = Record[Idx++]; N; --N)
6674 DiagOpts.Warnings.push_back(ReadString(Record, Idx));
6675 for (unsigned N = Record[Idx++]; N; --N)
6676 DiagOpts.Remarks.push_back(ReadString(Record, Idx));
6677
6678 return Listener.ReadDiagnosticOptions(DiagOpts, ModuleFilename, Complain);
6679}
6680
6681bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
6682 ASTReaderListener &Listener) {
6683 FileSystemOptions FSOpts;
6684 unsigned Idx = 0;
6685 FSOpts.WorkingDir = ReadString(Record, Idx);
6686 return Listener.ReadFileSystemOptions(FSOpts, Complain);
6687}
6688
6689bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
6690 StringRef ModuleFilename,
6691 bool Complain,
6692 ASTReaderListener &Listener) {
6693 HeaderSearchOptions HSOpts;
6694 unsigned Idx = 0;
6695 HSOpts.Sysroot = ReadString(Record, Idx);
6696
6697 HSOpts.ResourceDir = ReadString(Record, Idx);
6698 HSOpts.ModuleCachePath = ReadString(Record, Idx);
6699 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
6700 HSOpts.DisableModuleHash = Record[Idx++];
6701 HSOpts.ImplicitModuleMaps = Record[Idx++];
6702 HSOpts.ModuleMapFileHomeIsCwd = Record[Idx++];
6703 HSOpts.EnablePrebuiltImplicitModules = Record[Idx++];
6704 HSOpts.UseBuiltinIncludes = Record[Idx++];
6705 HSOpts.UseStandardSystemIncludes = Record[Idx++];
6706 HSOpts.UseStandardCXXIncludes = Record[Idx++];
6707 HSOpts.UseLibcxx = Record[Idx++];
6708 std::string SpecificModuleCachePath = ReadString(Record, Idx);
6709
6710 return Listener.ReadHeaderSearchOptions(HSOpts, ModuleFilename,
6711 SpecificModuleCachePath, Complain);
6712}
6713
6714bool ASTReader::ParseHeaderSearchPaths(const RecordData &Record, bool Complain,
6715 ASTReaderListener &Listener) {
6716 HeaderSearchOptions HSOpts;
6717 unsigned Idx = 0;
6718
6719 // Include entries.
6720 for (unsigned N = Record[Idx++]; N; --N) {
6721 std::string Path = ReadString(Record, Idx);
6723 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
6724 bool IsFramework = Record[Idx++];
6725 bool IgnoreSysRoot = Record[Idx++];
6726 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
6727 IgnoreSysRoot);
6728 }
6729
6730 // System header prefixes.
6731 for (unsigned N = Record[Idx++]; N; --N) {
6732 std::string Prefix = ReadString(Record, Idx);
6733 bool IsSystemHeader = Record[Idx++];
6734 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
6735 }
6736
6737 // VFS overlay files.
6738 for (unsigned N = Record[Idx++]; N; --N) {
6739 std::string VFSOverlayFile = ReadString(Record, Idx);
6740 HSOpts.VFSOverlayFiles.emplace_back(std::move(VFSOverlayFile));
6741 }
6742
6743 return Listener.ReadHeaderSearchPaths(HSOpts, Complain);
6744}
6745
6746bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
6747 StringRef ModuleFilename,
6748 bool Complain,
6749 ASTReaderListener &Listener,
6750 std::string &SuggestedPredefines) {
6751 PreprocessorOptions PPOpts;
6752 unsigned Idx = 0;
6753
6754 // Macro definitions/undefs
6755 bool ReadMacros = Record[Idx++];
6756 if (ReadMacros) {
6757 for (unsigned N = Record[Idx++]; N; --N) {
6758 std::string Macro = ReadString(Record, Idx);
6759 bool IsUndef = Record[Idx++];
6760 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
6761 }
6762 }
6763
6764 // Includes
6765 for (unsigned N = Record[Idx++]; N; --N) {
6766 PPOpts.Includes.push_back(ReadString(Record, Idx));
6767 }
6768
6769 // Macro Includes
6770 for (unsigned N = Record[Idx++]; N; --N) {
6771 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
6772 }
6773
6774 PPOpts.UsePredefines = Record[Idx++];
6775 PPOpts.DetailedRecord = Record[Idx++];
6776 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
6778 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
6779 SuggestedPredefines.clear();
6780 return Listener.ReadPreprocessorOptions(PPOpts, ModuleFilename, ReadMacros,
6781 Complain, SuggestedPredefines);
6782}
6783
6784std::pair<ModuleFile *, unsigned>
6785ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
6786 GlobalPreprocessedEntityMapType::iterator
6787 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
6788 assert(I != GlobalPreprocessedEntityMap.end() &&
6789 "Corrupted global preprocessed entity map");
6790 ModuleFile *M = I->second;
6791 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
6792 return std::make_pair(M, LocalIndex);
6793}
6794
6795llvm::iterator_range<PreprocessingRecord::iterator>
6796ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
6797 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
6798 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
6800
6801 return llvm::make_range(PreprocessingRecord::iterator(),
6802 PreprocessingRecord::iterator());
6803}
6804
6805bool ASTReader::canRecoverFromOutOfDate(StringRef ModuleFileName,
6806 unsigned int ClientLoadCapabilities) {
6807 return ClientLoadCapabilities & ARR_OutOfDate &&
6808 !getModuleManager()
6809 .getModuleCache()
6810 .getInMemoryModuleCache()
6811 .isPCMFinal(ModuleFileName);
6812}
6813
6814llvm::iterator_range<ASTReader::ModuleDeclIterator>
6816 return llvm::make_range(
6817 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
6818 ModuleDeclIterator(this, &Mod,
6820}
6821
6823 auto I = GlobalSkippedRangeMap.find(GlobalIndex);
6824 assert(I != GlobalSkippedRangeMap.end() &&
6825 "Corrupted global skipped range map");
6826 ModuleFile *M = I->second;
6827 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedSkippedRangeID;
6828 assert(LocalIndex < M->NumPreprocessedSkippedRanges);
6829 PPSkippedRange RawRange = M->PreprocessedSkippedRangeOffsets[LocalIndex];
6830 SourceRange Range(ReadSourceLocation(*M, RawRange.getBegin()),
6831 ReadSourceLocation(*M, RawRange.getEnd()));
6832 assert(Range.isValid());
6833 return Range;
6834}
6835
6836unsigned
6837ASTReader::translatePreprocessedEntityIDToIndex(PreprocessedEntityID ID) const {
6838 unsigned ModuleFileIndex = ID >> 32;
6839 assert(ModuleFileIndex && "not translating loaded MacroID?");
6840 assert(getModuleManager().size() > ModuleFileIndex - 1);
6841 ModuleFile &MF = getModuleManager()[ModuleFileIndex - 1];
6842
6843 ID &= llvm::maskTrailingOnes<PreprocessedEntityID>(32);
6844 return MF.BasePreprocessedEntityID + ID;
6845}
6846
6848 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
6849 ModuleFile &M = *PPInfo.first;
6850 unsigned LocalIndex = PPInfo.second;
6852 (static_cast<PreprocessedEntityID>(M.Index + 1) << 32) | LocalIndex;
6853 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
6854
6855 if (!PP.getPreprocessingRecord()) {
6856 Error("no preprocessing record");
6857 return nullptr;
6858 }
6859
6861 if (llvm::Error Err = M.PreprocessorDetailCursor.JumpToBit(
6862 M.MacroOffsetsBase + PPOffs.getOffset())) {
6863 Error(std::move(Err));
6864 return nullptr;
6865 }
6866
6868 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
6869 if (!MaybeEntry) {
6870 Error(MaybeEntry.takeError());
6871 return nullptr;
6872 }
6873 llvm::BitstreamEntry Entry = MaybeEntry.get();
6874
6875 if (Entry.Kind != llvm::BitstreamEntry::Record)
6876 return nullptr;
6877
6878 // Read the record.
6879 SourceRange Range(ReadSourceLocation(M, PPOffs.getBegin()),
6880 ReadSourceLocation(M, PPOffs.getEnd()));
6881 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
6882 StringRef Blob;
6884 Expected<unsigned> MaybeRecType =
6885 M.PreprocessorDetailCursor.readRecord(Entry.ID, Record, &Blob);
6886 if (!MaybeRecType) {
6887 Error(MaybeRecType.takeError());
6888 return nullptr;
6889 }
6890 switch ((PreprocessorDetailRecordTypes)MaybeRecType.get()) {
6891 case PPD_MACRO_EXPANSION: {
6892 bool isBuiltin = Record[0];
6893 IdentifierInfo *Name = nullptr;
6894 MacroDefinitionRecord *Def = nullptr;
6895 if (isBuiltin)
6896 Name = getLocalIdentifier(M, Record[1]);
6897 else {
6898 PreprocessedEntityID GlobalID =
6900 unsigned Index = translatePreprocessedEntityIDToIndex(GlobalID);
6901 Def =
6902 cast<MacroDefinitionRecord>(PPRec.getLoadedPreprocessedEntity(Index));
6903 }
6904
6905 MacroExpansion *ME;
6906 if (isBuiltin)
6907 ME = new (PPRec) MacroExpansion(Name, Range);
6908 else
6909 ME = new (PPRec) MacroExpansion(Def, Range);
6910
6911 return ME;
6912 }
6913
6914 case PPD_MACRO_DEFINITION: {
6915 // Decode the identifier info and then check again; if the macro is
6916 // still defined and associated with the identifier,
6918 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
6919
6920 if (DeserializationListener)
6921 DeserializationListener->MacroDefinitionRead(PPID, MD);
6922
6923 return MD;
6924 }
6925
6927 const char *FullFileNameStart = Blob.data() + Record[0];
6928 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
6930 if (!FullFileName.empty())
6931 File = PP.getFileManager().getOptionalFileRef(FullFileName);
6932
6933 // FIXME: Stable encoding
6935 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
6937 = new (PPRec) InclusionDirective(PPRec, Kind,
6938 StringRef(Blob.data(), Record[0]),
6939 Record[1], Record[3],
6940 File,
6941 Range);
6942 return ID;
6943 }
6944 }
6945
6946 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
6947}
6948
6949/// Find the next module that contains entities and return the ID
6950/// of the first entry.
6951///
6952/// \param SLocMapI points at a chunk of a module that contains no
6953/// preprocessed entities or the entities it contains are not the ones we are
6954/// looking for.
6955unsigned ASTReader::findNextPreprocessedEntity(
6956 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
6957 ++SLocMapI;
6958 for (GlobalSLocOffsetMapType::const_iterator
6959 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
6960 ModuleFile &M = *SLocMapI->second;
6962 return M.BasePreprocessedEntityID;
6963 }
6964
6965 return getTotalNumPreprocessedEntities();
6966}
6967
6968namespace {
6969
6970struct PPEntityComp {
6971 const ASTReader &Reader;
6972 ModuleFile &M;
6973
6974 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) {}
6975
6976 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
6977 SourceLocation LHS = getLoc(L);
6978 SourceLocation RHS = getLoc(R);
6979 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6980 }
6981
6982 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
6983 SourceLocation LHS = getLoc(L);
6984 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6985 }
6986
6987 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
6988 SourceLocation RHS = getLoc(R);
6989 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6990 }
6991
6992 SourceLocation getLoc(const PPEntityOffset &PPE) const {
6993 return Reader.ReadSourceLocation(M, PPE.getBegin());
6994 }
6995};
6996
6997} // namespace
6998
6999unsigned ASTReader::findPreprocessedEntity(SourceLocation Loc,
7000 bool EndsAfter) const {
7001 if (SourceMgr.isLocalSourceLocation(Loc))
7002 return getTotalNumPreprocessedEntities();
7003
7004 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
7005 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
7006 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
7007 "Corrupted global sloc offset map");
7008
7009 if (SLocMapI->second->NumPreprocessedEntities == 0)
7010 return findNextPreprocessedEntity(SLocMapI);
7011
7012 ModuleFile &M = *SLocMapI->second;
7013
7014 using pp_iterator = const PPEntityOffset *;
7015
7016 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
7017 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
7018
7019 size_t Count = M.NumPreprocessedEntities;
7020 size_t Half;
7021 pp_iterator First = pp_begin;
7022 pp_iterator PPI;
7023
7024 if (EndsAfter) {
7025 PPI = std::upper_bound(pp_begin, pp_end, Loc,
7026 PPEntityComp(*this, M));
7027 } else {
7028 // Do a binary search manually instead of using std::lower_bound because
7029 // The end locations of entities may be unordered (when a macro expansion
7030 // is inside another macro argument), but for this case it is not important
7031 // whether we get the first macro expansion or its containing macro.
7032 while (Count > 0) {
7033 Half = Count / 2;
7034 PPI = First;
7035 std::advance(PPI, Half);
7036 if (SourceMgr.isBeforeInTranslationUnit(
7037 ReadSourceLocation(M, PPI->getEnd()), Loc)) {
7038 First = PPI;
7039 ++First;
7040 Count = Count - Half - 1;
7041 } else
7042 Count = Half;
7043 }
7044 }
7045
7046 if (PPI == pp_end)
7047 return findNextPreprocessedEntity(SLocMapI);
7048
7049 return M.BasePreprocessedEntityID + (PPI - pp_begin);
7050}
7051
7052/// Returns a pair of [Begin, End) indices of preallocated
7053/// preprocessed entities that \arg Range encompasses.
7054std::pair<unsigned, unsigned>
7056 if (Range.isInvalid())
7057 return std::make_pair(0,0);
7058 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
7059
7060 unsigned BeginID = findPreprocessedEntity(Range.getBegin(), false);
7061 unsigned EndID = findPreprocessedEntity(Range.getEnd(), true);
7062 return std::make_pair(BeginID, EndID);
7063}
7064
7065/// Optionally returns true or false if the preallocated preprocessed
7066/// entity with index \arg Index came from file \arg FID.
7067std::optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
7068 FileID FID) {
7069 if (FID.isInvalid())
7070 return false;
7071
7072 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
7073 ModuleFile &M = *PPInfo.first;
7074 unsigned LocalIndex = PPInfo.second;
7075 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
7076
7077 SourceLocation Loc = ReadSourceLocation(M, PPOffs.getBegin());
7078 if (Loc.isInvalid())
7079 return false;
7080
7081 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
7082 return true;
7083 else
7084 return false;
7085}
7086
7087namespace {
7088
7089 /// Visitor used to search for information about a header file.
7090 class HeaderFileInfoVisitor {
7091 FileEntryRef FE;
7092 std::optional<HeaderFileInfo> HFI;
7093
7094 public:
7095 explicit HeaderFileInfoVisitor(FileEntryRef FE) : FE(FE) {}
7096
7097 bool operator()(ModuleFile &M) {
7100 if (!Table)
7101 return false;
7102
7103 // Look in the on-disk hash table for an entry for this file name.
7104 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
7105 if (Pos == Table->end())
7106 return false;
7107
7108 HFI = *Pos;
7109 return true;
7110 }
7111
7112 std::optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
7113 };
7114
7115} // namespace
7116
7118 HeaderFileInfoVisitor Visitor(FE);
7119 ModuleMgr.visit(Visitor);
7120 if (std::optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
7121 return *HFI;
7122
7123 return HeaderFileInfo();
7124}
7125
7127 using DiagState = DiagnosticsEngine::DiagState;
7129
7130 for (ModuleFile &F : ModuleMgr) {
7131 unsigned Idx = 0;
7132 auto &Record = F.PragmaDiagMappings;
7133 if (Record.empty())
7134 continue;
7135
7136 DiagStates.clear();
7137
7138 auto ReadDiagState = [&](const DiagState &BasedOn,
7139 bool IncludeNonPragmaStates) {
7140 unsigned BackrefID = Record[Idx++];
7141 if (BackrefID != 0)
7142 return DiagStates[BackrefID - 1];
7143
7144 // A new DiagState was created here.
7145 Diag.DiagStates.push_back(BasedOn);
7146 DiagState *NewState = &Diag.DiagStates.back();
7147 DiagStates.push_back(NewState);
7148 unsigned Size = Record[Idx++];
7149 assert(Idx + Size * 2 <= Record.size() &&
7150 "Invalid data, not enough diag/map pairs");
7151 while (Size--) {
7152 unsigned DiagID = Record[Idx++];
7153 DiagnosticMapping NewMapping =
7155 if (!NewMapping.isPragma() && !IncludeNonPragmaStates)
7156 continue;
7157
7158 DiagnosticMapping &Mapping = NewState->getOrAddMapping(DiagID);
7159
7160 // If this mapping was specified as a warning but the severity was
7161 // upgraded due to diagnostic settings, simulate the current diagnostic
7162 // settings (and use a warning).
7163 if (NewMapping.wasUpgradedFromWarning() && !Mapping.isErrorOrFatal()) {
7165 NewMapping.setUpgradedFromWarning(false);
7166 }
7167
7168 Mapping = NewMapping;
7169 }
7170 return NewState;
7171 };
7172
7173 // Read the first state.
7174 DiagState *FirstState;
7175 if (F.Kind == MK_ImplicitModule) {
7176 // Implicitly-built modules are reused with different diagnostic
7177 // settings. Use the initial diagnostic state from Diag to simulate this
7178 // compilation's diagnostic settings.
7179 FirstState = Diag.DiagStatesByLoc.FirstDiagState;
7180 DiagStates.push_back(FirstState);
7181
7182 // Skip the initial diagnostic state from the serialized module.
7183 assert(Record[1] == 0 &&
7184 "Invalid data, unexpected backref in initial state");
7185 Idx = 3 + Record[2] * 2;
7186 assert(Idx < Record.size() &&
7187 "Invalid data, not enough state change pairs in initial state");
7188 } else if (F.isModule()) {
7189 // For an explicit module, preserve the flags from the module build
7190 // command line (-w, -Weverything, -Werror, ...) along with any explicit
7191 // -Wblah flags.
7192 unsigned Flags = Record[Idx++];
7193 DiagState Initial(*Diag.getDiagnosticIDs());
7194 Initial.SuppressSystemWarnings = Flags & 1; Flags >>= 1;
7195 Initial.ErrorsAsFatal = Flags & 1; Flags >>= 1;
7196 Initial.WarningsAsErrors = Flags & 1; Flags >>= 1;
7197 Initial.EnableAllWarnings = Flags & 1; Flags >>= 1;
7198 Initial.IgnoreAllWarnings = Flags & 1; Flags >>= 1;
7199 Initial.ExtBehavior = (diag::Severity)Flags;
7200 FirstState = ReadDiagState(Initial, true);
7201
7202 assert(F.OriginalSourceFileID.isValid());
7203
7204 // Set up the root buffer of the module to start with the initial
7205 // diagnostic state of the module itself, to cover files that contain no
7206 // explicit transitions (for which we did not serialize anything).
7207 Diag.DiagStatesByLoc.Files[F.OriginalSourceFileID]
7208 .StateTransitions.push_back({FirstState, 0});
7209 } else {
7210 // For prefix ASTs, start with whatever the user configured on the
7211 // command line.
7212 Idx++; // Skip flags.
7213 FirstState = ReadDiagState(*Diag.DiagStatesByLoc.CurDiagState, false);
7214 }
7215
7216 // Read the state transitions.
7217 unsigned NumLocations = Record[Idx++];
7218 while (NumLocations--) {
7219 assert(Idx < Record.size() &&
7220 "Invalid data, missing pragma diagnostic states");
7221 FileID FID = ReadFileID(F, Record, Idx);
7222 assert(FID.isValid() && "invalid FileID for transition");
7223 unsigned Transitions = Record[Idx++];
7224
7225 // Note that we don't need to set up Parent/ParentOffset here, because
7226 // we won't be changing the diagnostic state within imported FileIDs
7227 // (other than perhaps appending to the main source file, which has no
7228 // parent).
7229 auto &F = Diag.DiagStatesByLoc.Files[FID];
7230 F.StateTransitions.reserve(F.StateTransitions.size() + Transitions);
7231 for (unsigned I = 0; I != Transitions; ++I) {
7232 unsigned Offset = Record[Idx++];
7233 auto *State = ReadDiagState(*FirstState, false);
7234 F.StateTransitions.push_back({State, Offset});
7235 }
7236 }
7237
7238 // Read the final state.
7239 assert(Idx < Record.size() &&
7240 "Invalid data, missing final pragma diagnostic state");
7241 SourceLocation CurStateLoc = ReadSourceLocation(F, Record[Idx++]);
7242 auto *CurState = ReadDiagState(*FirstState, false);
7243
7244 if (!F.isModule()) {
7245 Diag.DiagStatesByLoc.CurDiagState = CurState;
7246 Diag.DiagStatesByLoc.CurDiagStateLoc = CurStateLoc;
7247
7248 // Preserve the property that the imaginary root file describes the
7249 // current state.
7250 FileID NullFile;
7251 auto &T = Diag.DiagStatesByLoc.Files[NullFile].StateTransitions;
7252 if (T.empty())
7253 T.push_back({CurState, 0});
7254 else
7255 T[0].State = CurState;
7256 }
7257
7258 // Don't try to read these mappings again.
7259 Record.clear();
7260 }
7261}
7262
7263/// Get the correct cursor and offset for loading a type.
7264ASTReader::RecordLocation ASTReader::TypeCursorForIndex(TypeID ID) {
7265 auto [M, Index] = translateTypeIDToIndex(ID);
7266 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex].get() +
7268}
7269
7270static std::optional<Type::TypeClass> getTypeClassForCode(TypeCode code) {
7271 switch (code) {
7272#define TYPE_BIT_CODE(CLASS_ID, CODE_ID, CODE_VALUE) \
7273 case TYPE_##CODE_ID: return Type::CLASS_ID;
7274#include "clang/Serialization/TypeBitCodes.def"
7275 default:
7276 return std::nullopt;
7277 }
7278}
7279
7280/// Read and return the type with the given index..
7281///
7282/// The index is the type ID, shifted and minus the number of predefs. This
7283/// routine actually reads the record corresponding to the type at the given
7284/// location. It is a helper routine for GetType, which deals with reading type
7285/// IDs.
7286QualType ASTReader::readTypeRecord(TypeID ID) {
7287 assert(ContextObj && "reading type with no AST context");
7288 ASTContext &Context = *ContextObj;
7289 RecordLocation Loc = TypeCursorForIndex(ID);
7290 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
7291
7292 // Keep track of where we are in the stream, then jump back there
7293 // after reading this type.
7294 SavedStreamPosition SavedPosition(DeclsCursor);
7295
7296 ReadingKindTracker ReadingKind(Read_Type, *this);
7297
7298 // Note that we are loading a type record.
7299 Deserializing AType(this);
7300
7301 if (llvm::Error Err = DeclsCursor.JumpToBit(Loc.Offset)) {
7302 Error(std::move(Err));
7303 return QualType();
7304 }
7305 Expected<unsigned> RawCode = DeclsCursor.ReadCode();
7306 if (!RawCode) {
7307 Error(RawCode.takeError());
7308 return QualType();
7309 }
7310
7311 ASTRecordReader Record(*this, *Loc.F);
7312 Expected<unsigned> Code = Record.readRecord(DeclsCursor, RawCode.get());
7313 if (!Code) {
7314 Error(Code.takeError());
7315 return QualType();
7316 }
7317 if (Code.get() == TYPE_EXT_QUAL) {
7318 QualType baseType = Record.readQualType();
7319 Qualifiers quals = Record.readQualifiers();
7320 return Context.getQualifiedType(baseType, quals);
7321 }
7322
7323 auto maybeClass = getTypeClassForCode((TypeCode) Code.get());
7324 if (!maybeClass) {
7325 Error("Unexpected code for type");
7326 return QualType();
7327 }
7328
7329 serialization::AbstractTypeReader<ASTRecordReader> TypeReader(Record);
7330 return TypeReader.read(*maybeClass);
7331}
7332
7333namespace clang {
7334
7335class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
7336 ASTRecordReader &Reader;
7337
7338 SourceLocation readSourceLocation() { return Reader.readSourceLocation(); }
7339 SourceRange readSourceRange() { return Reader.readSourceRange(); }
7340
7341 TypeSourceInfo *GetTypeSourceInfo() {
7342 return Reader.readTypeSourceInfo();
7343 }
7344
7345 NestedNameSpecifierLoc ReadNestedNameSpecifierLoc() {
7346 return Reader.readNestedNameSpecifierLoc();
7347 }
7348
7349 Attr *ReadAttr() {
7350 return Reader.readAttr();
7351 }
7352
7353public:
7354 TypeLocReader(ASTRecordReader &Reader) : Reader(Reader) {}
7355
7356 // We want compile-time assurance that we've enumerated all of
7357 // these, so unfortunately we have to declare them first, then
7358 // define them out-of-line.
7359#define ABSTRACT_TYPELOC(CLASS, PARENT)
7360#define TYPELOC(CLASS, PARENT) \
7361 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
7362#include "clang/AST/TypeLocNodes.def"
7363
7366 void VisitTagTypeLoc(TagTypeLoc TL);
7367};
7368
7369} // namespace clang
7370
7371void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
7372 // nothing to do
7373}
7374
7375void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
7376 TL.setBuiltinLoc(readSourceLocation());
7377 if (TL.needsExtraLocalData()) {
7378 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Reader.readInt()));
7379 TL.setWrittenSignSpec(static_cast<TypeSpecifierSign>(Reader.readInt()));
7380 TL.setWrittenWidthSpec(static_cast<TypeSpecifierWidth>(Reader.readInt()));
7381 TL.setModeAttr(Reader.readInt());
7382 }
7383}
7384
7385void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
7386 TL.setNameLoc(readSourceLocation());
7387}
7388
7389void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
7390 TL.setStarLoc(readSourceLocation());
7391}
7392
7393void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
7394 // nothing to do
7395}
7396
7397void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
7398 // nothing to do
7399}
7400
7401void TypeLocReader::VisitArrayParameterTypeLoc(ArrayParameterTypeLoc TL) {
7402 // nothing to do
7403}
7404
7405void TypeLocReader::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
7406 TL.setExpansionLoc(readSourceLocation());
7407}
7408
7409void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
7410 TL.setCaretLoc(readSourceLocation());
7411}
7412
7413void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
7414 TL.setAmpLoc(readSourceLocation());
7415}
7416
7417void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
7418 TL.setAmpAmpLoc(readSourceLocation());
7419}
7420
7421void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
7422 TL.setStarLoc(readSourceLocation());
7423 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
7424}
7425
7427 TL.setLBracketLoc(readSourceLocation());
7428 TL.setRBracketLoc(readSourceLocation());
7429 if (Reader.readBool())
7430 TL.setSizeExpr(Reader.readExpr());
7431 else
7432 TL.setSizeExpr(nullptr);
7433}
7434
7435void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
7436 VisitArrayTypeLoc(TL);
7437}
7438
7439void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
7440 VisitArrayTypeLoc(TL);
7441}
7442
7443void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
7444 VisitArrayTypeLoc(TL);
7445}
7446
7447void TypeLocReader::VisitDependentSizedArrayTypeLoc(
7448 DependentSizedArrayTypeLoc TL) {
7449 VisitArrayTypeLoc(TL);
7450}
7451
7452void TypeLocReader::VisitDependentAddressSpaceTypeLoc(
7453 DependentAddressSpaceTypeLoc TL) {
7454
7455 TL.setAttrNameLoc(readSourceLocation());
7456 TL.setAttrOperandParensRange(readSourceRange());
7457 TL.setAttrExprOperand(Reader.readExpr());
7458}
7459
7460void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
7461 DependentSizedExtVectorTypeLoc TL) {
7462 TL.setNameLoc(readSourceLocation());
7463}
7464
7465void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
7466 TL.setNameLoc(readSourceLocation());
7467}
7468
7469void TypeLocReader::VisitDependentVectorTypeLoc(
7470 DependentVectorTypeLoc TL) {
7471 TL.setNameLoc(readSourceLocation());
7472}
7473
7474void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
7475 TL.setNameLoc(readSourceLocation());
7476}
7477
7478void TypeLocReader::VisitConstantMatrixTypeLoc(ConstantMatrixTypeLoc TL) {
7479 TL.setAttrNameLoc(readSourceLocation());
7480 TL.setAttrOperandParensRange(readSourceRange());
7481 TL.setAttrRowOperand(Reader.readExpr());
7482 TL.setAttrColumnOperand(Reader.readExpr());
7483}
7484
7485void TypeLocReader::VisitDependentSizedMatrixTypeLoc(
7486 DependentSizedMatrixTypeLoc TL) {
7487 TL.setAttrNameLoc(readSourceLocation());
7488 TL.setAttrOperandParensRange(readSourceRange());
7489 TL.setAttrRowOperand(Reader.readExpr());
7490 TL.setAttrColumnOperand(Reader.readExpr());
7491}
7492
7494 TL.setLocalRangeBegin(readSourceLocation());
7495 TL.setLParenLoc(readSourceLocation());
7496 TL.setRParenLoc(readSourceLocation());
7497 TL.setExceptionSpecRange(readSourceRange());
7498 TL.setLocalRangeEnd(readSourceLocation());
7499 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
7500 TL.setParam(i, Reader.readDeclAs<ParmVarDecl>());
7501 }
7502}
7503
7504void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
7505 VisitFunctionTypeLoc(TL);
7506}
7507
7508void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
7509 VisitFunctionTypeLoc(TL);
7510}
7511
7512void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
7513 SourceLocation ElaboratedKeywordLoc = readSourceLocation();
7514 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc();
7515 SourceLocation NameLoc = readSourceLocation();
7516 TL.set(ElaboratedKeywordLoc, QualifierLoc, NameLoc);
7517}
7518
7519void TypeLocReader::VisitUsingTypeLoc(UsingTypeLoc TL) {
7520 SourceLocation ElaboratedKeywordLoc = readSourceLocation();
7521 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc();
7522 SourceLocation NameLoc = readSourceLocation();
7523 TL.set(ElaboratedKeywordLoc, QualifierLoc, NameLoc);
7524}
7525
7526void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
7527 SourceLocation ElaboratedKeywordLoc = readSourceLocation();
7528 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc();
7529 SourceLocation NameLoc = readSourceLocation();
7530 TL.set(ElaboratedKeywordLoc, QualifierLoc, NameLoc);
7531}
7532
7533void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
7534 TL.setTypeofLoc(readSourceLocation());
7535 TL.setLParenLoc(readSourceLocation());
7536 TL.setRParenLoc(readSourceLocation());
7537}
7538
7539void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
7540 TL.setTypeofLoc(readSourceLocation());
7541 TL.setLParenLoc(readSourceLocation());
7542 TL.setRParenLoc(readSourceLocation());
7543 TL.setUnmodifiedTInfo(GetTypeSourceInfo());
7544}
7545
7546void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
7547 TL.setDecltypeLoc(readSourceLocation());
7548 TL.setRParenLoc(readSourceLocation());
7549}
7550
7551void TypeLocReader::VisitPackIndexingTypeLoc(PackIndexingTypeLoc TL) {
7552 TL.setEllipsisLoc(readSourceLocation());
7553}
7554
7555void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
7556 TL.setKWLoc(readSourceLocation());
7557 TL.setLParenLoc(readSourceLocation());
7558 TL.setRParenLoc(readSourceLocation());
7559 TL.setUnderlyingTInfo(GetTypeSourceInfo());
7560}
7561
7563 auto NNS = readNestedNameSpecifierLoc();
7564 auto TemplateKWLoc = readSourceLocation();
7565 auto ConceptNameLoc = readDeclarationNameInfo();
7566 auto FoundDecl = readDeclAs<NamedDecl>();
7567 auto NamedConcept = readDeclAs<ConceptDecl>();
7568 auto *CR = ConceptReference::Create(
7569 getContext(), NNS, TemplateKWLoc, ConceptNameLoc, FoundDecl, NamedConcept,
7570 (readBool() ? readASTTemplateArgumentListInfo() : nullptr));
7571 return CR;
7572}
7573
7574void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
7575 TL.setNameLoc(readSourceLocation());
7576 if (Reader.readBool())
7577 TL.setConceptReference(Reader.readConceptReference());
7578 if (Reader.readBool())
7579 TL.setRParenLoc(readSourceLocation());
7580}
7581
7582void TypeLocReader::VisitDeducedTemplateSpecializationTypeLoc(
7584 TL.setElaboratedKeywordLoc(readSourceLocation());
7585 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
7586 TL.setTemplateNameLoc(readSourceLocation());
7587}
7588
7590 TL.setElaboratedKeywordLoc(readSourceLocation());
7591 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
7592 TL.setNameLoc(readSourceLocation());
7593}
7594
7595void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
7596 VisitTagTypeLoc(TL);
7597}
7598
7599void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
7600 VisitTagTypeLoc(TL);
7601}
7602
7603void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) { VisitTagTypeLoc(TL); }
7604
7605void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
7606 TL.setAttr(ReadAttr());
7607}
7608
7609void TypeLocReader::VisitCountAttributedTypeLoc(CountAttributedTypeLoc TL) {
7610 // Nothing to do
7611}
7612
7613void TypeLocReader::VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) {
7614 // Nothing to do.
7615}
7616
7617void TypeLocReader::VisitOverflowBehaviorTypeLoc(OverflowBehaviorTypeLoc TL) {
7618 TL.setAttrLoc(readSourceLocation());
7619}
7620
7621void TypeLocReader::VisitHLSLAttributedResourceTypeLoc(
7622 HLSLAttributedResourceTypeLoc TL) {
7623 // Nothing to do.
7624}
7625
7626void TypeLocReader::VisitHLSLInlineSpirvTypeLoc(HLSLInlineSpirvTypeLoc TL) {
7627 // Nothing to do.
7628}
7629
7630void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
7631 TL.setNameLoc(readSourceLocation());
7632}
7633
7634void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
7635 SubstTemplateTypeParmTypeLoc TL) {
7636 TL.setNameLoc(readSourceLocation());
7637}
7638
7639void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
7640 SubstTemplateTypeParmPackTypeLoc TL) {
7641 TL.setNameLoc(readSourceLocation());
7642}
7643
7644void TypeLocReader::VisitSubstBuiltinTemplatePackTypeLoc(
7645 SubstBuiltinTemplatePackTypeLoc TL) {
7646 TL.setNameLoc(readSourceLocation());
7647}
7648
7649void TypeLocReader::VisitTemplateSpecializationTypeLoc(
7650 TemplateSpecializationTypeLoc TL) {
7651 SourceLocation ElaboratedKeywordLoc = readSourceLocation();
7652 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc();
7653 SourceLocation TemplateKeywordLoc = readSourceLocation();
7654 SourceLocation NameLoc = readSourceLocation();
7655 SourceLocation LAngleLoc = readSourceLocation();
7656 SourceLocation RAngleLoc = readSourceLocation();
7657 TL.set(ElaboratedKeywordLoc, QualifierLoc, TemplateKeywordLoc, NameLoc,
7658 LAngleLoc, RAngleLoc);
7659 MutableArrayRef<TemplateArgumentLocInfo> Args = TL.getArgLocInfos();
7660 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
7661 Args[I] = Reader.readTemplateArgumentLocInfo(
7662 TL.getTypePtr()->template_arguments()[I].getKind());
7663}
7664
7665void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
7666 TL.setLParenLoc(readSourceLocation());
7667 TL.setRParenLoc(readSourceLocation());
7668}
7669
7670void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
7671 TL.setElaboratedKeywordLoc(readSourceLocation());
7672 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
7673 TL.setNameLoc(readSourceLocation());
7674}
7675
7676void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
7677 TL.setEllipsisLoc(readSourceLocation());
7678}
7679
7680void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
7681 TL.setNameLoc(readSourceLocation());
7682 TL.setNameEndLoc(readSourceLocation());
7683}
7684
7685void TypeLocReader::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
7686 if (TL.getNumProtocols()) {
7687 TL.setProtocolLAngleLoc(readSourceLocation());
7688 TL.setProtocolRAngleLoc(readSourceLocation());
7689 }
7690 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
7691 TL.setProtocolLoc(i, readSourceLocation());
7692}
7693
7694void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
7695 TL.setHasBaseTypeAsWritten(Reader.readBool());
7696 TL.setTypeArgsLAngleLoc(readSourceLocation());
7697 TL.setTypeArgsRAngleLoc(readSourceLocation());
7698 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
7699 TL.setTypeArgTInfo(i, GetTypeSourceInfo());
7700 TL.setProtocolLAngleLoc(readSourceLocation());
7701 TL.setProtocolRAngleLoc(readSourceLocation());
7702 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
7703 TL.setProtocolLoc(i, readSourceLocation());
7704}
7705
7706void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
7707 TL.setStarLoc(readSourceLocation());
7708}
7709
7710void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
7711 TL.setKWLoc(readSourceLocation());
7712 TL.setLParenLoc(readSourceLocation());
7713 TL.setRParenLoc(readSourceLocation());
7714}
7715
7716void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) {
7717 TL.setKWLoc(readSourceLocation());
7718}
7719
7720void TypeLocReader::VisitBitIntTypeLoc(clang::BitIntTypeLoc TL) {
7721 TL.setNameLoc(readSourceLocation());
7722}
7723
7724void TypeLocReader::VisitDependentBitIntTypeLoc(
7725 clang::DependentBitIntTypeLoc TL) {
7726 TL.setNameLoc(readSourceLocation());
7727}
7728
7729void TypeLocReader::VisitPredefinedSugarTypeLoc(PredefinedSugarTypeLoc TL) {
7730 // Nothing to do.
7731}
7732
7734 TypeLocReader TLR(*this);
7735 for (; !TL.isNull(); TL = TL.getNextTypeLoc())
7736 TLR.Visit(TL);
7737}
7738
7740 QualType InfoTy = readType();
7741 if (InfoTy.isNull())
7742 return nullptr;
7743
7744 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
7745 readTypeLoc(TInfo->getTypeLoc());
7746 return TInfo;
7747}
7748
7750 return (ID & llvm::maskTrailingOnes<TypeID>(32)) >> Qualifiers::FastWidth;
7751}
7752
7754 return ID >> 32;
7755}
7756
7758 // We don't need to erase the higher bits since if these bits are not 0,
7759 // it must be larger than NUM_PREDEF_TYPE_IDS.
7761}
7762
7763std::pair<ModuleFile *, unsigned>
7764ASTReader::translateTypeIDToIndex(serialization::TypeID ID) const {
7765 assert(!isPredefinedType(ID) &&
7766 "Predefined type shouldn't be in TypesLoaded");
7767 unsigned ModuleFileIndex = getModuleFileIndexForTypeID(ID);
7768 assert(ModuleFileIndex && "Untranslated Local Decl?");
7769
7770 ModuleFile *OwningModuleFile = &getModuleManager()[ModuleFileIndex - 1];
7771 assert(OwningModuleFile &&
7772 "untranslated type ID or local type ID shouldn't be in TypesLoaded");
7773
7774 return {OwningModuleFile,
7775 OwningModuleFile->BaseTypeIndex + getIndexForTypeID(ID)};
7776}
7777
7779 assert(ContextObj && "reading type with no AST context");
7780 ASTContext &Context = *ContextObj;
7781
7782 unsigned FastQuals = ID & Qualifiers::FastMask;
7783
7784 if (isPredefinedType(ID)) {
7785 QualType T;
7786 unsigned Index = getIndexForTypeID(ID);
7787 switch ((PredefinedTypeIDs)Index) {
7789 // We should never use this one.
7790 llvm_unreachable("Invalid predefined type");
7791 break;
7793 return QualType();
7795 T = Context.VoidTy;
7796 break;
7798 T = Context.BoolTy;
7799 break;
7802 // FIXME: Check that the signedness of CharTy is correct!
7803 T = Context.CharTy;
7804 break;
7806 T = Context.UnsignedCharTy;
7807 break;
7809 T = Context.UnsignedShortTy;
7810 break;
7812 T = Context.UnsignedIntTy;
7813 break;
7815 T = Context.UnsignedLongTy;
7816 break;
7818 T = Context.UnsignedLongLongTy;
7819 break;
7821 T = Context.UnsignedInt128Ty;
7822 break;
7824 T = Context.SignedCharTy;
7825 break;
7827 T = Context.WCharTy;
7828 break;
7830 T = Context.ShortTy;
7831 break;
7832 case PREDEF_TYPE_INT_ID:
7833 T = Context.IntTy;
7834 break;
7836 T = Context.LongTy;
7837 break;
7839 T = Context.LongLongTy;
7840 break;
7842 T = Context.Int128Ty;
7843 break;
7845 T = Context.BFloat16Ty;
7846 break;
7848 T = Context.HalfTy;
7849 break;
7851 T = Context.FloatTy;
7852 break;
7854 T = Context.DoubleTy;
7855 break;
7857 T = Context.LongDoubleTy;
7858 break;
7860 T = Context.ShortAccumTy;
7861 break;
7863 T = Context.AccumTy;
7864 break;
7866 T = Context.LongAccumTy;
7867 break;
7869 T = Context.UnsignedShortAccumTy;
7870 break;
7872 T = Context.UnsignedAccumTy;
7873 break;
7875 T = Context.UnsignedLongAccumTy;
7876 break;
7878 T = Context.ShortFractTy;
7879 break;
7881 T = Context.FractTy;
7882 break;
7884 T = Context.LongFractTy;
7885 break;
7887 T = Context.UnsignedShortFractTy;
7888 break;
7890 T = Context.UnsignedFractTy;
7891 break;
7893 T = Context.UnsignedLongFractTy;
7894 break;
7896 T = Context.SatShortAccumTy;
7897 break;
7899 T = Context.SatAccumTy;
7900 break;
7902 T = Context.SatLongAccumTy;
7903 break;
7905 T = Context.SatUnsignedShortAccumTy;
7906 break;
7908 T = Context.SatUnsignedAccumTy;
7909 break;
7911 T = Context.SatUnsignedLongAccumTy;
7912 break;
7914 T = Context.SatShortFractTy;
7915 break;
7917 T = Context.SatFractTy;
7918 break;
7920 T = Context.SatLongFractTy;
7921 break;
7923 T = Context.SatUnsignedShortFractTy;
7924 break;
7926 T = Context.SatUnsignedFractTy;
7927 break;
7929 T = Context.SatUnsignedLongFractTy;
7930 break;
7932 T = Context.Float16Ty;
7933 break;
7935 T = Context.Float128Ty;
7936 break;
7938 T = Context.Ibm128Ty;
7939 break;
7941 T = Context.OverloadTy;
7942 break;
7944 T = Context.UnresolvedTemplateTy;
7945 break;
7947 T = Context.BoundMemberTy;
7948 break;
7950 T = Context.PseudoObjectTy;
7951 break;
7953 T = Context.DependentTy;
7954 break;
7956 T = Context.UnknownAnyTy;
7957 break;
7959 T = Context.NullPtrTy;
7960 break;
7962 T = Context.Char8Ty;
7963 break;
7965 T = Context.Char16Ty;
7966 break;
7968 T = Context.Char32Ty;
7969 break;
7971 T = Context.ObjCBuiltinIdTy;
7972 break;
7974 T = Context.ObjCBuiltinClassTy;
7975 break;
7977 T = Context.ObjCBuiltinSelTy;
7978 break;
7979#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7980 case PREDEF_TYPE_##Id##_ID: \
7981 T = Context.SingletonId; \
7982 break;
7983#include "clang/Basic/OpenCLImageTypes.def"
7984#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
7985 case PREDEF_TYPE_##Id##_ID: \
7986 T = Context.Id##Ty; \
7987 break;
7988#include "clang/Basic/OpenCLExtensionTypes.def"
7990 T = Context.OCLSamplerTy;
7991 break;
7993 T = Context.OCLEventTy;
7994 break;
7996 T = Context.OCLClkEventTy;
7997 break;
7999 T = Context.OCLQueueTy;
8000 break;
8002 T = Context.OCLReserveIDTy;
8003 break;
8005 T = Context.getAutoDeductType();
8006 break;
8008 T = Context.getAutoRRefDeductType();
8009 break;
8011 T = Context.ARCUnbridgedCastTy;
8012 break;
8014 T = Context.BuiltinFnTy;
8015 break;
8017 T = Context.IncompleteMatrixIdxTy;
8018 break;
8020 T = Context.ArraySectionTy;
8021 break;
8023 T = Context.OMPArrayShapingTy;
8024 break;
8026 T = Context.OMPIteratorTy;
8027 break;
8028#define SVE_TYPE(Name, Id, SingletonId) \
8029 case PREDEF_TYPE_##Id##_ID: \
8030 T = Context.SingletonId; \
8031 break;
8032#include "clang/Basic/AArch64ACLETypes.def"
8033#define PPC_VECTOR_TYPE(Name, Id, Size) \
8034 case PREDEF_TYPE_##Id##_ID: \
8035 T = Context.Id##Ty; \
8036 break;
8037#include "clang/Basic/PPCTypes.def"
8038#define RVV_TYPE(Name, Id, SingletonId) \
8039 case PREDEF_TYPE_##Id##_ID: \
8040 T = Context.SingletonId; \
8041 break;
8042#include "clang/Basic/RISCVVTypes.def"
8043#define WASM_TYPE(Name, Id, SingletonId) \
8044 case PREDEF_TYPE_##Id##_ID: \
8045 T = Context.SingletonId; \
8046 break;
8047#include "clang/Basic/WebAssemblyReferenceTypes.def"
8048#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) \
8049 case PREDEF_TYPE_##Id##_ID: \
8050 T = Context.SingletonId; \
8051 break;
8052#include "clang/Basic/AMDGPUTypes.def"
8053#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
8054 case PREDEF_TYPE_##Id##_ID: \
8055 T = Context.SingletonId; \
8056 break;
8057#include "clang/Basic/HLSLIntangibleTypes.def"
8058 }
8059
8060 assert(!T.isNull() && "Unknown predefined type");
8061 return T.withFastQualifiers(FastQuals);
8062 }
8063
8064 unsigned Index = translateTypeIDToIndex(ID).second;
8065
8066 assert(Index < TypesLoaded.size() && "Type index out-of-range");
8067 if (TypesLoaded[Index].isNull()) {
8068 TypesLoaded[Index] = readTypeRecord(ID);
8069 if (TypesLoaded[Index].isNull())
8070 return QualType();
8071
8072 TypesLoaded[Index]->setFromAST();
8073 if (DeserializationListener)
8074 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
8075 TypesLoaded[Index]);
8076 }
8077
8078 return TypesLoaded[Index].withFastQualifiers(FastQuals);
8079}
8080
8082 return GetType(getGlobalTypeID(F, LocalID));
8083}
8084
8086 LocalTypeID LocalID) const {
8087 if (isPredefinedType(LocalID))
8088 return LocalID;
8089
8090 if (!F.ModuleOffsetMap.empty())
8091 ReadModuleOffsetMap(F);
8092
8093 unsigned ModuleFileIndex = getModuleFileIndexForTypeID(LocalID);
8094 LocalID &= llvm::maskTrailingOnes<TypeID>(32);
8095
8096 if (ModuleFileIndex == 0)
8098
8099 ModuleFile &MF =
8100 ModuleFileIndex ? *F.TransitiveImports[ModuleFileIndex - 1] : F;
8101 ModuleFileIndex = MF.Index + 1;
8102 return ((uint64_t)ModuleFileIndex << 32) | LocalID;
8103}
8104
8107 switch (Kind) {
8109 return readExpr();
8111 return readTypeSourceInfo();
8114 SourceLocation TemplateKWLoc = readSourceLocation();
8116 SourceLocation TemplateNameLoc = readSourceLocation();
8119 : SourceLocation();
8120 return TemplateArgumentLocInfo(getASTContext(), TemplateKWLoc, QualifierLoc,
8121 TemplateNameLoc, EllipsisLoc);
8122 }
8129 // FIXME: Is this right?
8130 return TemplateArgumentLocInfo();
8131 }
8132 llvm_unreachable("unexpected template argument loc");
8133}
8134
8144
8147 Result.setLAngleLoc(readSourceLocation());
8148 Result.setRAngleLoc(readSourceLocation());
8149 unsigned NumArgsAsWritten = readInt();
8150 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
8151 Result.addArgument(readTemplateArgumentLoc());
8152}
8153
8160
8162
8164 if (NumCurrentElementsDeserializing) {
8165 // We arrange to not care about the complete redeclaration chain while we're
8166 // deserializing. Just remember that the AST has marked this one as complete
8167 // but that it's not actually complete yet, so we know we still need to
8168 // complete it later.
8169 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
8170 return;
8171 }
8172
8173 if (!D->getDeclContext()) {
8174 assert(isa<TranslationUnitDecl>(D) && "Not a TU?");
8175 return;
8176 }
8177
8178 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
8179
8180 // If this is a named declaration, complete it by looking it up
8181 // within its context.
8182 //
8183 // FIXME: Merging a function definition should merge
8184 // all mergeable entities within it.
8186 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
8187 if (!getContext().getLangOpts().CPlusPlus &&
8189 // Outside of C++, we don't have a lookup table for the TU, so update
8190 // the identifier instead. (For C++ modules, we don't store decls
8191 // in the serialized identifier table, so we do the lookup in the TU.)
8192 auto *II = Name.getAsIdentifierInfo();
8193 assert(II && "non-identifier name in C?");
8194 if (II->isOutOfDate())
8196 } else
8197 DC->lookup(Name);
8199 // Find all declarations of this kind from the relevant context.
8200 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
8201 auto *DC = cast<DeclContext>(DCDecl);
8204 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
8205 }
8206 }
8207 }
8208
8211 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
8212 Template = CTSD->getSpecializedTemplate();
8213 Args = CTSD->getTemplateArgs().asArray();
8214 } else if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D)) {
8215 Template = VTSD->getSpecializedTemplate();
8216 Args = VTSD->getTemplateArgs().asArray();
8217 } else if (auto *FD = dyn_cast<FunctionDecl>(D)) {
8218 if (auto *Tmplt = FD->getPrimaryTemplate()) {
8219 Template = Tmplt;
8220 Args = FD->getTemplateSpecializationArgs()->asArray();
8221 }
8222 }
8223
8224 if (Template)
8225 Template->loadLazySpecializationsImpl(Args);
8226}
8227
8230 RecordLocation Loc = getLocalBitOffset(Offset);
8231 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
8232 SavedStreamPosition SavedPosition(Cursor);
8233 if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {
8234 Error(std::move(Err));
8235 return nullptr;
8236 }
8237 ReadingKindTracker ReadingKind(Read_Decl, *this);
8238 Deserializing D(this);
8239
8240 Expected<unsigned> MaybeCode = Cursor.ReadCode();
8241 if (!MaybeCode) {
8242 Error(MaybeCode.takeError());
8243 return nullptr;
8244 }
8245 unsigned Code = MaybeCode.get();
8246
8247 ASTRecordReader Record(*this, *Loc.F);
8248 Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code);
8249 if (!MaybeRecCode) {
8250 Error(MaybeRecCode.takeError());
8251 return nullptr;
8252 }
8253 if (MaybeRecCode.get() != DECL_CXX_CTOR_INITIALIZERS) {
8254 Error("malformed AST file: missing C++ ctor initializers");
8255 return nullptr;
8256 }
8257
8258 return Record.readCXXCtorInitializers();
8259}
8260
8262 assert(ContextObj && "reading base specifiers with no AST context");
8263 ASTContext &Context = *ContextObj;
8264
8265 RecordLocation Loc = getLocalBitOffset(Offset);
8266 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
8267 SavedStreamPosition SavedPosition(Cursor);
8268 if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {
8269 Error(std::move(Err));
8270 return nullptr;
8271 }
8272 ReadingKindTracker ReadingKind(Read_Decl, *this);
8273 Deserializing D(this);
8274
8275 Expected<unsigned> MaybeCode = Cursor.ReadCode();
8276 if (!MaybeCode) {
8277 Error(MaybeCode.takeError());
8278 return nullptr;
8279 }
8280 unsigned Code = MaybeCode.get();
8281
8282 ASTRecordReader Record(*this, *Loc.F);
8283 Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code);
8284 if (!MaybeRecCode) {
8285 Error(MaybeCode.takeError());
8286 return nullptr;
8287 }
8288 unsigned RecCode = MaybeRecCode.get();
8289
8290 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
8291 Error("malformed AST file: missing C++ base specifiers");
8292 return nullptr;
8293 }
8294
8295 unsigned NumBases = Record.readInt();
8296 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
8297 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
8298 for (unsigned I = 0; I != NumBases; ++I)
8299 Bases[I] = Record.readCXXBaseSpecifier();
8300 return Bases;
8301}
8302
8304 LocalDeclID LocalID) const {
8305 if (LocalID < NUM_PREDEF_DECL_IDS)
8306 return GlobalDeclID(LocalID.getRawValue());
8307
8308 unsigned OwningModuleFileIndex = LocalID.getModuleFileIndex();
8309 DeclID ID = LocalID.getLocalDeclIndex();
8310
8311 if (!F.ModuleOffsetMap.empty())
8312 ReadModuleOffsetMap(F);
8313
8314 ModuleFile *OwningModuleFile =
8315 OwningModuleFileIndex == 0
8316 ? &F
8317 : F.TransitiveImports[OwningModuleFileIndex - 1];
8318
8319 if (OwningModuleFileIndex == 0)
8320 ID -= NUM_PREDEF_DECL_IDS;
8321
8322 uint64_t NewModuleFileIndex = OwningModuleFile->Index + 1;
8323 return GlobalDeclID(NewModuleFileIndex, ID);
8324}
8325
8327 // Predefined decls aren't from any module.
8328 if (ID < NUM_PREDEF_DECL_IDS)
8329 return false;
8330
8331 unsigned ModuleFileIndex = ID.getModuleFileIndex();
8332 return M.Index == ModuleFileIndex - 1;
8333}
8334
8336 // Predefined decls aren't from any module.
8337 if (ID < NUM_PREDEF_DECL_IDS)
8338 return nullptr;
8339
8340 uint64_t ModuleFileIndex = ID.getModuleFileIndex();
8341 assert(ModuleFileIndex && "Untranslated Local Decl?");
8342
8343 return &getModuleManager()[ModuleFileIndex - 1];
8344}
8345
8347 if (!D->isFromASTFile())
8348 return nullptr;
8349
8350 return getOwningModuleFile(D->getGlobalID());
8351}
8352
8354 if (ID < NUM_PREDEF_DECL_IDS)
8355 return SourceLocation();
8356
8357 if (Decl *D = GetExistingDecl(ID))
8358 return D->getLocation();
8359
8360 SourceLocation Loc;
8361 DeclCursorForID(ID, Loc);
8362 return Loc;
8363}
8364
8365Decl *ASTReader::getPredefinedDecl(PredefinedDeclIDs ID) {
8366 assert(ContextObj && "reading predefined decl without AST context");
8367 ASTContext &Context = *ContextObj;
8368 Decl *NewLoaded = nullptr;
8369 switch (ID) {
8371 return nullptr;
8372
8374 return Context.getTranslationUnitDecl();
8375
8377 if (Context.ObjCIdDecl)
8378 return Context.ObjCIdDecl;
8379 NewLoaded = Context.getObjCIdDecl();
8380 break;
8381
8383 if (Context.ObjCSelDecl)
8384 return Context.ObjCSelDecl;
8385 NewLoaded = Context.getObjCSelDecl();
8386 break;
8387
8389 if (Context.ObjCClassDecl)
8390 return Context.ObjCClassDecl;
8391 NewLoaded = Context.getObjCClassDecl();
8392 break;
8393
8395 if (Context.ObjCProtocolClassDecl)
8396 return Context.ObjCProtocolClassDecl;
8397 NewLoaded = Context.getObjCProtocolDecl();
8398 break;
8399
8401 if (Context.Int128Decl)
8402 return Context.Int128Decl;
8403 NewLoaded = Context.getInt128Decl();
8404 break;
8405
8407 if (Context.UInt128Decl)
8408 return Context.UInt128Decl;
8409 NewLoaded = Context.getUInt128Decl();
8410 break;
8411
8413 if (Context.ObjCInstanceTypeDecl)
8414 return Context.ObjCInstanceTypeDecl;
8415 NewLoaded = Context.getObjCInstanceTypeDecl();
8416 break;
8417
8419 if (Context.BuiltinVaListDecl)
8420 return Context.BuiltinVaListDecl;
8421 NewLoaded = Context.getBuiltinVaListDecl();
8422 break;
8423
8425 if (Context.VaListTagDecl)
8426 return Context.VaListTagDecl;
8427 NewLoaded = Context.getVaListTagDecl();
8428 break;
8429
8431 if (Context.BuiltinMSVaListDecl)
8432 return Context.BuiltinMSVaListDecl;
8433 NewLoaded = Context.getBuiltinMSVaListDecl();
8434 break;
8435
8437 // ASTContext::getMSGuidTagDecl won't create MSGuidTagDecl conditionally.
8438 return Context.getMSGuidTagDecl();
8439
8441 if (Context.ExternCContext)
8442 return Context.ExternCContext;
8443 NewLoaded = Context.getExternCContextDecl();
8444 break;
8445
8447 if (Context.CFConstantStringTypeDecl)
8448 return Context.CFConstantStringTypeDecl;
8449 NewLoaded = Context.getCFConstantStringDecl();
8450 break;
8451
8453 if (Context.CFConstantStringTagDecl)
8454 return Context.CFConstantStringTagDecl;
8455 NewLoaded = Context.getCFConstantStringTagDecl();
8456 break;
8457
8459 return Context.getMSTypeInfoTagDecl();
8460
8461#define BuiltinTemplate(BTName) \
8462 case PREDEF_DECL##BTName##_ID: \
8463 if (Context.Decl##BTName) \
8464 return Context.Decl##BTName; \
8465 NewLoaded = Context.get##BTName##Decl(); \
8466 break;
8467#include "clang/Basic/BuiltinTemplates.inc"
8468
8470 llvm_unreachable("Invalid decl ID");
8471 break;
8472 }
8473
8474 assert(NewLoaded && "Failed to load predefined decl?");
8475
8476 if (DeserializationListener)
8477 DeserializationListener->PredefinedDeclBuilt(ID, NewLoaded);
8478
8479 return NewLoaded;
8480}
8481
8482unsigned ASTReader::translateGlobalDeclIDToIndex(GlobalDeclID GlobalID) const {
8483 ModuleFile *OwningModuleFile = getOwningModuleFile(GlobalID);
8484 if (!OwningModuleFile) {
8485 assert(GlobalID < NUM_PREDEF_DECL_IDS && "Untransalted Global ID?");
8486 return GlobalID.getRawValue();
8487 }
8488
8489 return OwningModuleFile->BaseDeclIndex + GlobalID.getLocalDeclIndex();
8490}
8491
8493 assert(ContextObj && "reading decl with no AST context");
8494
8495 if (ID < NUM_PREDEF_DECL_IDS) {
8496 Decl *D = getPredefinedDecl((PredefinedDeclIDs)ID);
8497 if (D) {
8498 // Track that we have merged the declaration with ID \p ID into the
8499 // pre-existing predefined declaration \p D.
8500 auto &Merged = KeyDecls[D->getCanonicalDecl()];
8501 if (Merged.empty())
8502 Merged.push_back(ID);
8503 }
8504 return D;
8505 }
8506
8507 unsigned Index = translateGlobalDeclIDToIndex(ID);
8508
8509 if (Index >= DeclsLoaded.size()) {
8510 assert(0 && "declaration ID out-of-range for AST file");
8511 Error("declaration ID out-of-range for AST file");
8512 return nullptr;
8513 }
8514
8515 return DeclsLoaded[Index];
8516}
8517
8519 if (ID < NUM_PREDEF_DECL_IDS)
8520 return GetExistingDecl(ID);
8521
8522 unsigned Index = translateGlobalDeclIDToIndex(ID);
8523
8524 if (Index >= DeclsLoaded.size()) {
8525 assert(0 && "declaration ID out-of-range for AST file");
8526 Error("declaration ID out-of-range for AST file");
8527 return nullptr;
8528 }
8529
8530 if (!DeclsLoaded[Index]) {
8531 ReadDeclRecord(ID);
8532 if (DeserializationListener)
8533 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
8534 }
8535
8536 return DeclsLoaded[Index];
8537}
8538
8540 GlobalDeclID GlobalID) {
8541 if (GlobalID < NUM_PREDEF_DECL_IDS)
8542 return LocalDeclID::get(*this, M, GlobalID.getRawValue());
8543
8544 if (!M.ModuleOffsetMap.empty())
8545 ReadModuleOffsetMap(M);
8546
8547 ModuleFile *Owner = getOwningModuleFile(GlobalID);
8548 DeclID ID = GlobalID.getLocalDeclIndex();
8549
8550 if (Owner == &M) {
8551 ID += NUM_PREDEF_DECL_IDS;
8552 return LocalDeclID::get(*this, M, ID);
8553 }
8554
8555 uint64_t OrignalModuleFileIndex = 0;
8556 for (unsigned I = 0; I < M.TransitiveImports.size(); I++)
8557 if (M.TransitiveImports[I] == Owner) {
8558 OrignalModuleFileIndex = I + 1;
8559 break;
8560 }
8561
8562 if (!OrignalModuleFileIndex)
8563 return LocalDeclID();
8564
8565 return LocalDeclID::get(*this, M, OrignalModuleFileIndex, ID);
8566}
8567
8569 unsigned &Idx) {
8570 if (Idx >= Record.size()) {
8571 Error("Corrupted AST file");
8572 return GlobalDeclID(0);
8573 }
8574
8575 return getGlobalDeclID(F, LocalDeclID::get(*this, F, Record[Idx++]));
8576}
8577
8578/// Resolve the offset of a statement into a statement.
8579///
8580/// This operation will read a new statement from the external
8581/// source each time it is called, and is meant to be used via a
8582/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
8584 // Switch case IDs are per Decl.
8586
8587 // Offset here is a global offset across the entire chain.
8588 RecordLocation Loc = getLocalBitOffset(Offset);
8589 if (llvm::Error Err = Loc.F->DeclsCursor.JumpToBit(Loc.Offset)) {
8590 Error(std::move(Err));
8591 return nullptr;
8592 }
8593 assert(NumCurrentElementsDeserializing == 0 &&
8594 "should not be called while already deserializing");
8595 Deserializing D(this);
8596 return ReadStmtFromStream(*Loc.F);
8597}
8598
8599bool ASTReader::LoadExternalSpecializationsImpl(SpecLookupTableTy &SpecLookups,
8600 const Decl *D) {
8601 assert(D);
8602
8603 auto It = SpecLookups.find(D);
8604 if (It == SpecLookups.end())
8605 return false;
8606
8607 // Get Decl may violate the iterator from SpecializationsLookups so we store
8608 // the DeclIDs in ahead.
8610 It->second.Table.findAll();
8611
8612 // Since we've loaded all the specializations, we can erase it from
8613 // the lookup table.
8614 SpecLookups.erase(It);
8615
8616 bool NewSpecsFound = false;
8617 Deserializing LookupResults(this);
8618 for (auto &Info : Infos) {
8619 if (GetExistingDecl(Info))
8620 continue;
8621 NewSpecsFound = true;
8622 GetDecl(Info);
8623 }
8624
8625 return NewSpecsFound;
8626}
8627
8628bool ASTReader::LoadExternalSpecializations(const Decl *D, bool OnlyPartial) {
8629 assert(D);
8630
8632 bool NewSpecsFound =
8633 LoadExternalSpecializationsImpl(PartialSpecializationsLookups, D);
8634 if (OnlyPartial)
8635 return NewSpecsFound;
8636
8637 NewSpecsFound |= LoadExternalSpecializationsImpl(SpecializationsLookups, D);
8638 return NewSpecsFound;
8639}
8640
8641bool ASTReader::LoadExternalSpecializationsImpl(
8642 SpecLookupTableTy &SpecLookups, const Decl *D,
8643 ArrayRef<TemplateArgument> TemplateArgs) {
8644 assert(D);
8645
8646 reader::LazySpecializationInfoLookupTable *LookupTable = nullptr;
8647 if (auto It = SpecLookups.find(D); It != SpecLookups.end())
8648 LookupTable = &It->getSecond();
8649 if (!LookupTable)
8650 return false;
8651
8652 // NOTE: The getNameForDiagnostic usage in the lambda may mutate the
8653 // `SpecLookups` object.
8654 llvm::TimeTraceScope TimeScope("Load External Specializations for ", [&] {
8655 std::string Name;
8656 llvm::raw_string_ostream OS(Name);
8657 auto *ND = cast<NamedDecl>(D);
8659 /*Qualified=*/true);
8660 return Name;
8661 });
8662
8663 Deserializing LookupResults(this);
8664 auto HashValue = StableHashForTemplateArguments(TemplateArgs);
8665
8666 // Get Decl may violate the iterator from SpecLookups
8668 LookupTable->Table.find(HashValue);
8669
8670 bool NewSpecsFound = false;
8671 for (auto &Info : Infos) {
8672 if (GetExistingDecl(Info))
8673 continue;
8674 NewSpecsFound = true;
8675 GetDecl(Info);
8676 }
8677
8678 return NewSpecsFound;
8679}
8680
8682 const Decl *D, ArrayRef<TemplateArgument> TemplateArgs) {
8683 assert(D);
8684
8685 bool NewDeclsFound = LoadExternalSpecializationsImpl(
8686 PartialSpecializationsLookups, D, TemplateArgs);
8687 NewDeclsFound |=
8688 LoadExternalSpecializationsImpl(SpecializationsLookups, D, TemplateArgs);
8689
8690 return NewDeclsFound;
8691}
8692
8694 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
8695 SmallVectorImpl<Decl *> &Decls) {
8696 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
8697
8698 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
8699 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
8700 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
8701 auto K = (Decl::Kind)+LexicalDecls[I];
8702 if (!IsKindWeWant(K))
8703 continue;
8704
8705 auto ID = (DeclID) + LexicalDecls[I + 1];
8706
8707 // Don't add predefined declarations to the lexical context more
8708 // than once.
8709 if (ID < NUM_PREDEF_DECL_IDS) {
8710 if (PredefsVisited[ID])
8711 continue;
8712
8713 PredefsVisited[ID] = true;
8714 }
8715
8716 if (Decl *D = GetLocalDecl(*M, LocalDeclID::get(*this, *M, ID))) {
8717 assert(D->getKind() == K && "wrong kind for lexical decl");
8718 if (!DC->isDeclInLexicalTraversal(D))
8719 Decls.push_back(D);
8720 }
8721 }
8722 };
8723
8724 if (isa<TranslationUnitDecl>(DC)) {
8725 for (const auto &Lexical : TULexicalDecls)
8726 Visit(Lexical.first, Lexical.second);
8727 } else {
8728 auto I = LexicalDecls.find(DC);
8729 if (I != LexicalDecls.end())
8730 Visit(I->second.first, I->second.second);
8731 }
8732
8733 ++NumLexicalDeclContextsRead;
8734}
8735
8736namespace {
8737
8738class UnalignedDeclIDComp {
8739 ASTReader &Reader;
8740 ModuleFile &Mod;
8741
8742public:
8743 UnalignedDeclIDComp(ASTReader &Reader, ModuleFile &M)
8744 : Reader(Reader), Mod(M) {}
8745
8746 bool operator()(unaligned_decl_id_t L, unaligned_decl_id_t R) const {
8747 SourceLocation LHS = getLocation(L);
8748 SourceLocation RHS = getLocation(R);
8749 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
8750 }
8751
8752 bool operator()(SourceLocation LHS, unaligned_decl_id_t R) const {
8753 SourceLocation RHS = getLocation(R);
8754 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
8755 }
8756
8757 bool operator()(unaligned_decl_id_t L, SourceLocation RHS) const {
8758 SourceLocation LHS = getLocation(L);
8759 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
8760 }
8761
8762 SourceLocation getLocation(unaligned_decl_id_t ID) const {
8763 return Reader.getSourceManager().getFileLoc(
8765 Reader.getGlobalDeclID(Mod, LocalDeclID::get(Reader, Mod, ID))));
8766 }
8767};
8768
8769} // namespace
8770
8772 unsigned Offset, unsigned Length,
8773 SmallVectorImpl<Decl *> &Decls) {
8775
8776 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
8777 if (I == FileDeclIDs.end())
8778 return;
8779
8780 FileDeclsInfo &DInfo = I->second;
8781 if (DInfo.Decls.empty())
8782 return;
8783
8785 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
8786 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
8787
8788 UnalignedDeclIDComp DIDComp(*this, *DInfo.Mod);
8790 llvm::lower_bound(DInfo.Decls, BeginLoc, DIDComp);
8791 if (BeginIt != DInfo.Decls.begin())
8792 --BeginIt;
8793
8794 // If we are pointing at a top-level decl inside an objc container, we need
8795 // to backtrack until we find it otherwise we will fail to report that the
8796 // region overlaps with an objc container.
8797 while (BeginIt != DInfo.Decls.begin() &&
8798 GetDecl(getGlobalDeclID(*DInfo.Mod,
8799 LocalDeclID::get(*this, *DInfo.Mod, *BeginIt)))
8800 ->isTopLevelDeclInObjCContainer())
8801 --BeginIt;
8802
8804 llvm::upper_bound(DInfo.Decls, EndLoc, DIDComp);
8805 if (EndIt != DInfo.Decls.end())
8806 ++EndIt;
8807
8808 for (ArrayRef<unaligned_decl_id_t>::iterator DIt = BeginIt; DIt != EndIt;
8809 ++DIt)
8810 Decls.push_back(GetDecl(getGlobalDeclID(
8811 *DInfo.Mod, LocalDeclID::get(*this, *DInfo.Mod, *DIt))));
8812}
8813
8815 DeclarationName Name,
8816 const DeclContext *OriginalDC) {
8817 assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
8818 "DeclContext has no visible decls in storage");
8819 if (!Name)
8820 return false;
8821
8822 // Load the list of declarations.
8823 DeclsSet DS;
8824
8825 auto Find = [&, this](auto &&Table, auto &&Key) {
8826 for (GlobalDeclID ID : Table.find(Key)) {
8828 if (ND->getDeclName() != Name)
8829 continue;
8830 // Special case for namespaces: There can be a lot of redeclarations of
8831 // some namespaces, and we import a "key declaration" per imported module.
8832 // Since all declarations of a namespace are essentially interchangeable,
8833 // we can optimize namespace look-up by only storing the key declaration
8834 // of the current TU, rather than storing N key declarations where N is
8835 // the # of imported modules that declare that namespace.
8836 // TODO: Try to generalize this optimization to other redeclarable decls.
8837 if (isa<NamespaceDecl>(ND))
8839 DS.insert(ND);
8840 }
8841 };
8842
8843 Deserializing LookupResults(this);
8844
8845 // FIXME: Clear the redundancy with templated lambda in C++20 when that's
8846 // available.
8847 if (auto It = Lookups.find(DC); It != Lookups.end()) {
8848 ++NumVisibleDeclContextsRead;
8849 Find(It->second.Table, Name);
8850 }
8851
8852 auto FindModuleLocalLookup = [&, this](Module *NamedModule) {
8853 if (auto It = ModuleLocalLookups.find(DC); It != ModuleLocalLookups.end()) {
8854 ++NumModuleLocalVisibleDeclContexts;
8855 Find(It->second.Table, std::make_pair(Name, NamedModule));
8856 }
8857 };
8858 if (auto *NamedModule =
8859 OriginalDC ? cast<Decl>(OriginalDC)->getTopLevelOwningNamedModule()
8860 : nullptr)
8861 FindModuleLocalLookup(NamedModule);
8862 // See clang/test/Modules/ModulesLocalNamespace.cppm for the motiviation case.
8863 // We're going to find a decl but the decl context of the lookup is
8864 // unspecified. In this case, the OriginalDC may be the decl context in other
8865 // module.
8866 if (ContextObj && ContextObj->getCurrentNamedModule())
8867 FindModuleLocalLookup(ContextObj->getCurrentNamedModule());
8868
8869 if (auto It = TULocalLookups.find(DC); It != TULocalLookups.end()) {
8870 ++NumTULocalVisibleDeclContexts;
8871 Find(It->second.Table, Name);
8872 }
8873
8874 SetExternalVisibleDeclsForName(DC, Name, DS);
8875 return !DS.empty();
8876}
8877
8879 if (!DC->hasExternalVisibleStorage())
8880 return;
8881
8882 DeclsMap Decls;
8883
8884 auto findAll = [&](auto &LookupTables, unsigned &NumRead) {
8885 auto It = LookupTables.find(DC);
8886 if (It == LookupTables.end())
8887 return;
8888
8889 NumRead++;
8890
8891 for (GlobalDeclID ID : It->second.Table.findAll()) {
8893 // Special case for namespaces: There can be a lot of redeclarations of
8894 // some namespaces, and we import a "key declaration" per imported module.
8895 // Since all declarations of a namespace are essentially interchangeable,
8896 // we can optimize namespace look-up by only storing the key declaration
8897 // of the current TU, rather than storing N key declarations where N is
8898 // the # of imported modules that declare that namespace.
8899 // TODO: Try to generalize this optimization to other redeclarable decls.
8900 if (isa<NamespaceDecl>(ND))
8902 Decls[ND->getDeclName()].insert(ND);
8903 }
8904
8905 // FIXME: Why a PCH test is failing if we remove the iterator after findAll?
8906 };
8907
8908 findAll(Lookups, NumVisibleDeclContextsRead);
8909 findAll(ModuleLocalLookups, NumModuleLocalVisibleDeclContexts);
8910 findAll(TULocalLookups, NumTULocalVisibleDeclContexts);
8911
8912 for (auto &[Name, DS] : Decls)
8913 SetExternalVisibleDeclsForName(DC, Name, DS);
8914
8915 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
8916}
8917
8920 auto I = Lookups.find(Primary);
8921 return I == Lookups.end() ? nullptr : &I->second;
8922}
8923
8926 auto I = ModuleLocalLookups.find(Primary);
8927 return I == ModuleLocalLookups.end() ? nullptr : &I->second;
8928}
8929
8932 auto I = TULocalLookups.find(Primary);
8933 return I == TULocalLookups.end() ? nullptr : &I->second;
8934}
8935
8938 assert(D->isCanonicalDecl());
8939 auto &LookupTable =
8940 IsPartial ? PartialSpecializationsLookups : SpecializationsLookups;
8941 auto I = LookupTable.find(D);
8942 return I == LookupTable.end() ? nullptr : &I->second;
8943}
8944
8946 assert(D->isCanonicalDecl());
8947 return PartialSpecializationsLookups.contains(D) ||
8948 SpecializationsLookups.contains(D);
8949}
8950
8951/// Under non-PCH compilation the consumer receives the objc methods
8952/// before receiving the implementation, and codegen depends on this.
8953/// We simulate this by deserializing and passing to consumer the methods of the
8954/// implementation before passing the deserialized implementation decl.
8956 ASTConsumer *Consumer) {
8957 assert(ImplD && Consumer);
8958
8959 for (auto *I : ImplD->methods())
8960 Consumer->HandleInterestingDecl(DeclGroupRef(I));
8961
8962 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
8963}
8964
8965void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
8966 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
8967 PassObjCImplDeclToConsumer(ImplD, Consumer);
8968 else
8969 Consumer->HandleInterestingDecl(DeclGroupRef(D));
8970}
8971
8972void ASTReader::PassVTableToConsumer(CXXRecordDecl *RD) {
8973 Consumer->HandleVTable(RD);
8974}
8975
8977 this->Consumer = Consumer;
8978
8979 if (Consumer)
8980 PassInterestingDeclsToConsumer();
8981
8982 if (DeserializationListener)
8983 DeserializationListener->ReaderInitialized(this);
8984}
8985
8987 std::fprintf(stderr, "*** AST File Statistics:\n");
8988
8989 unsigned NumTypesLoaded =
8990 TypesLoaded.size() - llvm::count(TypesLoaded.materialized(), QualType());
8991 unsigned NumDeclsLoaded =
8992 DeclsLoaded.size() -
8993 llvm::count(DeclsLoaded.materialized(), (Decl *)nullptr);
8994 unsigned NumIdentifiersLoaded =
8995 IdentifiersLoaded.size() -
8996 llvm::count(IdentifiersLoaded, (IdentifierInfo *)nullptr);
8997 unsigned NumMacrosLoaded =
8998 MacrosLoaded.size() - llvm::count(MacrosLoaded, (MacroInfo *)nullptr);
8999 unsigned NumSelectorsLoaded =
9000 SelectorsLoaded.size() - llvm::count(SelectorsLoaded, Selector());
9001
9002 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
9003 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
9004 NumSLocEntriesRead, TotalNumSLocEntries,
9005 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
9006 if (!TypesLoaded.empty())
9007 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
9008 NumTypesLoaded, (unsigned)TypesLoaded.size(),
9009 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
9010 if (!DeclsLoaded.empty())
9011 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
9012 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
9013 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
9014 if (!IdentifiersLoaded.empty())
9015 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
9016 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
9017 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
9018 if (!MacrosLoaded.empty())
9019 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
9020 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
9021 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
9022 if (!SelectorsLoaded.empty())
9023 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
9024 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
9025 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
9026 if (TotalNumStatements)
9027 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
9028 NumStatementsRead, TotalNumStatements,
9029 ((float)NumStatementsRead/TotalNumStatements * 100));
9030 if (TotalNumMacros)
9031 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
9032 NumMacrosRead, TotalNumMacros,
9033 ((float)NumMacrosRead/TotalNumMacros * 100));
9034 if (TotalLexicalDeclContexts)
9035 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
9036 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
9037 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
9038 * 100));
9039 if (TotalVisibleDeclContexts)
9040 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
9041 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
9042 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
9043 * 100));
9044 if (TotalModuleLocalVisibleDeclContexts)
9045 std::fprintf(
9046 stderr, " %u/%u module local visible declcontexts read (%f%%)\n",
9047 NumModuleLocalVisibleDeclContexts, TotalModuleLocalVisibleDeclContexts,
9048 ((float)NumModuleLocalVisibleDeclContexts /
9049 TotalModuleLocalVisibleDeclContexts * 100));
9050 if (TotalTULocalVisibleDeclContexts)
9051 std::fprintf(stderr, " %u/%u visible declcontexts in GMF read (%f%%)\n",
9052 NumTULocalVisibleDeclContexts, TotalTULocalVisibleDeclContexts,
9053 ((float)NumTULocalVisibleDeclContexts /
9054 TotalTULocalVisibleDeclContexts * 100));
9055 if (TotalNumMethodPoolEntries)
9056 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
9057 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
9058 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
9059 * 100));
9060 if (NumMethodPoolLookups)
9061 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
9062 NumMethodPoolHits, NumMethodPoolLookups,
9063 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
9064 if (NumMethodPoolTableLookups)
9065 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
9066 NumMethodPoolTableHits, NumMethodPoolTableLookups,
9067 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
9068 * 100.0));
9069 if (NumIdentifierLookupHits)
9070 std::fprintf(stderr,
9071 " %u / %u identifier table lookups succeeded (%f%%)\n",
9072 NumIdentifierLookupHits, NumIdentifierLookups,
9073 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
9074
9075 if (GlobalIndex) {
9076 std::fprintf(stderr, "\n");
9077 GlobalIndex->printStats();
9078 }
9079
9080 std::fprintf(stderr, "\n");
9081 dump();
9082 std::fprintf(stderr, "\n");
9083}
9084
9085template<typename Key, typename ModuleFile, unsigned InitialCapacity>
9086LLVM_DUMP_METHOD static void
9087dumpModuleIDMap(StringRef Name,
9088 const ContinuousRangeMap<Key, ModuleFile *,
9089 InitialCapacity> &Map) {
9090 if (Map.begin() == Map.end())
9091 return;
9092
9094
9095 llvm::errs() << Name << ":\n";
9096 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
9097 I != IEnd; ++I)
9098 llvm::errs() << " " << (DeclID)I->first << " -> " << I->second->FileName
9099 << "\n";
9100}
9101
9102LLVM_DUMP_METHOD void ASTReader::dump() {
9103 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
9104 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
9105 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
9106 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
9107 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
9108 dumpModuleIDMap("Global preprocessed entity map",
9109 GlobalPreprocessedEntityMap);
9110
9111 llvm::errs() << "\n*** PCH/Modules Loaded:";
9112 for (ModuleFile &M : ModuleMgr)
9113 M.dump();
9114}
9115
9116/// Return the amount of memory used by memory buffers, breaking down
9117/// by heap-backed versus mmap'ed memory.
9119 for (ModuleFile &I : ModuleMgr) {
9120 if (llvm::MemoryBuffer *buf = I.Buffer) {
9121 size_t bytes = buf->getBufferSize();
9122 switch (buf->getBufferKind()) {
9123 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
9124 sizes.malloc_bytes += bytes;
9125 break;
9126 case llvm::MemoryBuffer::MemoryBuffer_MMap:
9127 sizes.mmap_bytes += bytes;
9128 break;
9129 }
9130 }
9131 }
9132}
9133
9135 SemaObj = &S;
9136 S.addExternalSource(this);
9137
9138 // Makes sure any declarations that were deserialized "too early"
9139 // still get added to the identifier's declaration chains.
9140 for (GlobalDeclID ID : PreloadedDeclIDs) {
9142 pushExternalDeclIntoScope(D, D->getDeclName());
9143 }
9144 PreloadedDeclIDs.clear();
9145
9146 // FIXME: What happens if these are changed by a module import?
9147 if (!FPPragmaOptions.empty()) {
9148 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
9149 FPOptionsOverride NewOverrides =
9150 FPOptionsOverride::getFromOpaqueInt(FPPragmaOptions[0]);
9151 SemaObj->CurFPFeatures =
9152 NewOverrides.applyOverrides(SemaObj->getLangOpts());
9153 }
9154
9155 for (GlobalDeclID ID : DeclsWithEffectsToVerify) {
9156 Decl *D = GetDecl(ID);
9157 if (auto *FD = dyn_cast<FunctionDecl>(D))
9158 SemaObj->addDeclWithEffects(FD, FD->getFunctionEffects());
9159 else if (auto *BD = dyn_cast<BlockDecl>(D))
9160 SemaObj->addDeclWithEffects(BD, BD->getFunctionEffects());
9161 else
9162 llvm_unreachable("unexpected Decl type in DeclsWithEffectsToVerify");
9163 }
9164 DeclsWithEffectsToVerify.clear();
9165
9166 SemaObj->OpenCLFeatures = OpenCLExtensions;
9167
9168 UpdateSema();
9169}
9170
9172 assert(SemaObj && "no Sema to update");
9173
9174 // Load the offsets of the declarations that Sema references.
9175 // They will be lazily deserialized when needed.
9176 if (!SemaDeclRefs.empty()) {
9177 assert(SemaDeclRefs.size() % 3 == 0);
9178 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 3) {
9179 if (!SemaObj->StdNamespace)
9180 SemaObj->StdNamespace = SemaDeclRefs[I].getRawValue();
9181 if (!SemaObj->StdBadAlloc)
9182 SemaObj->StdBadAlloc = SemaDeclRefs[I + 1].getRawValue();
9183 if (!SemaObj->StdAlignValT)
9184 SemaObj->StdAlignValT = SemaDeclRefs[I + 2].getRawValue();
9185 }
9186 SemaDeclRefs.clear();
9187 }
9188
9189 // Update the state of pragmas. Use the same API as if we had encountered the
9190 // pragma in the source.
9191 if(OptimizeOffPragmaLocation.isValid())
9192 SemaObj->ActOnPragmaOptimize(/* On = */ false, OptimizeOffPragmaLocation);
9193 if (PragmaMSStructState != -1)
9194 SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState);
9195 if (PointersToMembersPragmaLocation.isValid()) {
9196 SemaObj->ActOnPragmaMSPointersToMembers(
9198 PragmaMSPointersToMembersState,
9199 PointersToMembersPragmaLocation);
9200 }
9201 SemaObj->CUDA().ForceHostDeviceDepth = ForceHostDeviceDepth;
9202 if (!RISCVVecIntrinsicPragma.empty()) {
9203 assert(RISCVVecIntrinsicPragma.size() == 3 &&
9204 "Wrong number of RISCVVecIntrinsicPragma");
9205 SemaObj->RISCV().DeclareRVVBuiltins = RISCVVecIntrinsicPragma[0];
9206 SemaObj->RISCV().DeclareSiFiveVectorBuiltins = RISCVVecIntrinsicPragma[1];
9207 SemaObj->RISCV().DeclareAndesVectorBuiltins = RISCVVecIntrinsicPragma[2];
9208 }
9209
9210 if (PragmaAlignPackCurrentValue) {
9211 // The bottom of the stack might have a default value. It must be adjusted
9212 // to the current value to ensure that the packing state is preserved after
9213 // popping entries that were included/imported from a PCH/module.
9214 bool DropFirst = false;
9215 if (!PragmaAlignPackStack.empty() &&
9216 PragmaAlignPackStack.front().Location.isInvalid()) {
9217 assert(PragmaAlignPackStack.front().Value ==
9218 SemaObj->AlignPackStack.DefaultValue &&
9219 "Expected a default alignment value");
9220 SemaObj->AlignPackStack.Stack.emplace_back(
9221 PragmaAlignPackStack.front().SlotLabel,
9222 SemaObj->AlignPackStack.CurrentValue,
9223 SemaObj->AlignPackStack.CurrentPragmaLocation,
9224 PragmaAlignPackStack.front().PushLocation);
9225 DropFirst = true;
9226 }
9227 for (const auto &Entry :
9228 llvm::ArrayRef(PragmaAlignPackStack).drop_front(DropFirst ? 1 : 0)) {
9229 SemaObj->AlignPackStack.Stack.emplace_back(
9230 Entry.SlotLabel, Entry.Value, Entry.Location, Entry.PushLocation);
9231 }
9232 if (PragmaAlignPackCurrentLocation.isInvalid()) {
9233 assert(*PragmaAlignPackCurrentValue ==
9234 SemaObj->AlignPackStack.DefaultValue &&
9235 "Expected a default align and pack value");
9236 // Keep the current values.
9237 } else {
9238 SemaObj->AlignPackStack.CurrentValue = *PragmaAlignPackCurrentValue;
9239 SemaObj->AlignPackStack.CurrentPragmaLocation =
9240 PragmaAlignPackCurrentLocation;
9241 }
9242 }
9243 if (FpPragmaCurrentValue) {
9244 // The bottom of the stack might have a default value. It must be adjusted
9245 // to the current value to ensure that fp-pragma state is preserved after
9246 // popping entries that were included/imported from a PCH/module.
9247 bool DropFirst = false;
9248 if (!FpPragmaStack.empty() && FpPragmaStack.front().Location.isInvalid()) {
9249 assert(FpPragmaStack.front().Value ==
9250 SemaObj->FpPragmaStack.DefaultValue &&
9251 "Expected a default pragma float_control value");
9252 SemaObj->FpPragmaStack.Stack.emplace_back(
9253 FpPragmaStack.front().SlotLabel, SemaObj->FpPragmaStack.CurrentValue,
9254 SemaObj->FpPragmaStack.CurrentPragmaLocation,
9255 FpPragmaStack.front().PushLocation);
9256 DropFirst = true;
9257 }
9258 for (const auto &Entry :
9259 llvm::ArrayRef(FpPragmaStack).drop_front(DropFirst ? 1 : 0))
9260 SemaObj->FpPragmaStack.Stack.emplace_back(
9261 Entry.SlotLabel, Entry.Value, Entry.Location, Entry.PushLocation);
9262 if (FpPragmaCurrentLocation.isInvalid()) {
9263 assert(*FpPragmaCurrentValue == SemaObj->FpPragmaStack.DefaultValue &&
9264 "Expected a default pragma float_control value");
9265 // Keep the current values.
9266 } else {
9267 SemaObj->FpPragmaStack.CurrentValue = *FpPragmaCurrentValue;
9268 SemaObj->FpPragmaStack.CurrentPragmaLocation = FpPragmaCurrentLocation;
9269 }
9270 }
9271
9272 // For non-modular AST files, restore visiblity of modules.
9273 for (auto &Import : PendingImportedModulesSema) {
9274 if (Import.ImportLoc.isInvalid())
9275 continue;
9276 if (Module *Imported = getSubmodule(Import.ID)) {
9277 SemaObj->makeModuleVisible(Imported, Import.ImportLoc);
9278 }
9279 }
9280 PendingImportedModulesSema.clear();
9281}
9282
9284 // Note that we are loading an identifier.
9285 Deserializing AnIdentifier(this);
9286
9287 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
9288 NumIdentifierLookups,
9289 NumIdentifierLookupHits);
9290
9291 // We don't need to do identifier table lookups in C++ modules (we preload
9292 // all interesting declarations, and don't need to use the scope for name
9293 // lookups). Perform the lookup in PCH files, though, since we don't build
9294 // a complete initial identifier table if we're carrying on from a PCH.
9295 if (PP.getLangOpts().CPlusPlus) {
9296 for (auto *F : ModuleMgr.pch_modules())
9297 if (Visitor(*F))
9298 break;
9299 } else {
9300 // If there is a global index, look there first to determine which modules
9301 // provably do not have any results for this identifier.
9303 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
9304 if (!loadGlobalIndex()) {
9305 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
9306 HitsPtr = &Hits;
9307 }
9308 }
9309
9310 ModuleMgr.visit(Visitor, HitsPtr);
9311 }
9312
9313 IdentifierInfo *II = Visitor.getIdentifierInfo();
9315 return II;
9316}
9317
9318namespace clang {
9319
9320 /// An identifier-lookup iterator that enumerates all of the
9321 /// identifiers stored within a set of AST files.
9323 /// The AST reader whose identifiers are being enumerated.
9324 const ASTReader &Reader;
9325
9326 /// The current index into the chain of AST files stored in
9327 /// the AST reader.
9328 unsigned Index;
9329
9330 /// The current position within the identifier lookup table
9331 /// of the current AST file.
9332 ASTIdentifierLookupTable::key_iterator Current;
9333
9334 /// The end position within the identifier lookup table of
9335 /// the current AST file.
9336 ASTIdentifierLookupTable::key_iterator End;
9337
9338 /// Whether to skip any modules in the ASTReader.
9339 bool SkipModules;
9340
9341 public:
9342 explicit ASTIdentifierIterator(const ASTReader &Reader,
9343 bool SkipModules = false);
9344
9345 StringRef Next() override;
9346 };
9347
9348} // namespace clang
9349
9351 bool SkipModules)
9352 : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) {
9353}
9354
9356 while (Current == End) {
9357 // If we have exhausted all of our AST files, we're done.
9358 if (Index == 0)
9359 return StringRef();
9360
9361 --Index;
9362 ModuleFile &F = Reader.ModuleMgr[Index];
9363 if (SkipModules && F.isModule())
9364 continue;
9365
9366 ASTIdentifierLookupTable *IdTable =
9368 Current = IdTable->key_begin();
9369 End = IdTable->key_end();
9370 }
9371
9372 // We have any identifiers remaining in the current AST file; return
9373 // the next one.
9374 StringRef Result = *Current;
9375 ++Current;
9376 return Result;
9377}
9378
9379namespace {
9380
9381/// A utility for appending two IdentifierIterators.
9382class ChainedIdentifierIterator : public IdentifierIterator {
9383 std::unique_ptr<IdentifierIterator> Current;
9384 std::unique_ptr<IdentifierIterator> Queued;
9385
9386public:
9387 ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First,
9388 std::unique_ptr<IdentifierIterator> Second)
9389 : Current(std::move(First)), Queued(std::move(Second)) {}
9390
9391 StringRef Next() override {
9392 if (!Current)
9393 return StringRef();
9394
9395 StringRef result = Current->Next();
9396 if (!result.empty())
9397 return result;
9398
9399 // Try the queued iterator, which may itself be empty.
9400 Current.reset();
9401 std::swap(Current, Queued);
9402 return Next();
9403 }
9404};
9405
9406} // namespace
9407
9409 if (!loadGlobalIndex()) {
9410 std::unique_ptr<IdentifierIterator> ReaderIter(
9411 new ASTIdentifierIterator(*this, /*SkipModules=*/true));
9412 std::unique_ptr<IdentifierIterator> ModulesIter(
9413 GlobalIndex->createIdentifierIterator());
9414 return new ChainedIdentifierIterator(std::move(ReaderIter),
9415 std::move(ModulesIter));
9416 }
9417
9418 return new ASTIdentifierIterator(*this);
9419}
9420
9421namespace clang {
9422namespace serialization {
9423
9425 ASTReader &Reader;
9426 Selector Sel;
9427 unsigned PriorGeneration;
9428 unsigned InstanceBits = 0;
9429 unsigned FactoryBits = 0;
9430 bool InstanceHasMoreThanOneDecl = false;
9431 bool FactoryHasMoreThanOneDecl = false;
9432 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
9433 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
9434
9435 public:
9437 unsigned PriorGeneration)
9438 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration) {}
9439
9441 if (!M.SelectorLookupTable)
9442 return false;
9443
9444 // If we've already searched this module file, skip it now.
9445 if (M.Generation <= PriorGeneration)
9446 return true;
9447
9448 ++Reader.NumMethodPoolTableLookups;
9449 ASTSelectorLookupTable *PoolTable
9451 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
9452 if (Pos == PoolTable->end())
9453 return false;
9454
9455 ++Reader.NumMethodPoolTableHits;
9456 ++Reader.NumSelectorsRead;
9457 // FIXME: Not quite happy with the statistics here. We probably should
9458 // disable this tracking when called via LoadSelector.
9459 // Also, should entries without methods count as misses?
9460 ++Reader.NumMethodPoolEntriesRead;
9462 if (Reader.DeserializationListener)
9463 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
9464
9465 // Append methods in the reverse order, so that later we can process them
9466 // in the order they appear in the source code by iterating through
9467 // the vector in the reverse order.
9468 InstanceMethods.append(Data.Instance.rbegin(), Data.Instance.rend());
9469 FactoryMethods.append(Data.Factory.rbegin(), Data.Factory.rend());
9470 InstanceBits = Data.InstanceBits;
9471 FactoryBits = Data.FactoryBits;
9472 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
9473 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
9474 return false;
9475 }
9476
9477 /// Retrieve the instance methods found by this visitor.
9479 return InstanceMethods;
9480 }
9481
9482 /// Retrieve the instance methods found by this visitor.
9484 return FactoryMethods;
9485 }
9486
9487 unsigned getInstanceBits() const { return InstanceBits; }
9488 unsigned getFactoryBits() const { return FactoryBits; }
9489
9491 return InstanceHasMoreThanOneDecl;
9492 }
9493
9494 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
9495 };
9496
9497} // namespace serialization
9498} // namespace clang
9499
9500/// Add the given set of methods to the method list.
9502 ObjCMethodList &List) {
9503 for (ObjCMethodDecl *M : llvm::reverse(Methods))
9504 S.ObjC().addMethodToGlobalList(&List, M);
9505}
9506
9508 // Get the selector generation and update it to the current generation.
9509 unsigned &Generation = SelectorGeneration[Sel];
9510 unsigned PriorGeneration = Generation;
9511 Generation = getGeneration();
9512 SelectorOutOfDate[Sel] = false;
9513
9514 // Search for methods defined with this selector.
9515 ++NumMethodPoolLookups;
9516 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
9517 ModuleMgr.visit(Visitor);
9518
9519 if (Visitor.getInstanceMethods().empty() &&
9520 Visitor.getFactoryMethods().empty())
9521 return;
9522
9523 ++NumMethodPoolHits;
9524
9525 if (!getSema())
9526 return;
9527
9528 Sema &S = *getSema();
9529 auto &Methods = S.ObjC().MethodPool[Sel];
9530
9531 Methods.first.setBits(Visitor.getInstanceBits());
9532 Methods.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
9533 Methods.second.setBits(Visitor.getFactoryBits());
9534 Methods.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
9535
9536 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
9537 // when building a module we keep every method individually and may need to
9538 // update hasMoreThanOneDecl as we add the methods.
9539 addMethodsToPool(S, Visitor.getInstanceMethods(), Methods.first);
9540 addMethodsToPool(S, Visitor.getFactoryMethods(), Methods.second);
9541}
9542
9544 if (SelectorOutOfDate[Sel])
9545 ReadMethodPool(Sel);
9546}
9547
9550 Namespaces.clear();
9551
9552 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
9553 if (NamespaceDecl *Namespace
9554 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
9555 Namespaces.push_back(Namespace);
9556 }
9557}
9558
9560 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {
9561 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
9562 UndefinedButUsedDecl &U = UndefinedButUsed[Idx++];
9565 Undefined.insert(std::make_pair(D, Loc));
9566 }
9567 UndefinedButUsed.clear();
9568}
9569
9571 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
9572 Exprs) {
9573 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
9574 FieldDecl *FD =
9575 cast<FieldDecl>(GetDecl(GlobalDeclID(DelayedDeleteExprs[Idx++])));
9576 uint64_t Count = DelayedDeleteExprs[Idx++];
9577 for (uint64_t C = 0; C < Count; ++C) {
9578 SourceLocation DeleteLoc =
9579 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
9580 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
9581 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
9582 }
9583 }
9584}
9585
9587 SmallVectorImpl<VarDecl *> &TentativeDefs) {
9588 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
9589 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
9590 if (Var)
9591 TentativeDefs.push_back(Var);
9592 }
9593 TentativeDefinitions.clear();
9594}
9595
9598 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
9600 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
9601 if (D)
9602 Decls.push_back(D);
9603 }
9604 UnusedFileScopedDecls.clear();
9605}
9606
9609 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
9611 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
9612 if (D)
9613 Decls.push_back(D);
9614 }
9615 DelegatingCtorDecls.clear();
9616}
9617
9619 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
9621 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
9622 if (D)
9623 Decls.push_back(D);
9624 }
9625 ExtVectorDecls.clear();
9626}
9627
9630 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
9631 ++I) {
9632 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
9633 GetDecl(UnusedLocalTypedefNameCandidates[I]));
9634 if (D)
9635 Decls.insert(D);
9636 }
9637 UnusedLocalTypedefNameCandidates.clear();
9638}
9639
9642 for (auto I : DeclsToCheckForDeferredDiags) {
9643 auto *D = dyn_cast_or_null<Decl>(GetDecl(I));
9644 if (D)
9645 Decls.insert(D);
9646 }
9647 DeclsToCheckForDeferredDiags.clear();
9648}
9649
9651 SmallVectorImpl<std::pair<Selector, SourceLocation>> &Sels) {
9652 if (ReferencedSelectorsData.empty())
9653 return;
9654
9655 // If there are @selector references added them to its pool. This is for
9656 // implementation of -Wselector.
9657 unsigned int DataSize = ReferencedSelectorsData.size()-1;
9658 unsigned I = 0;
9659 while (I < DataSize) {
9660 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
9661 SourceLocation SelLoc
9662 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
9663 Sels.push_back(std::make_pair(Sel, SelLoc));
9664 }
9665 ReferencedSelectorsData.clear();
9666}
9667
9669 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo>> &WeakIDs) {
9670 if (WeakUndeclaredIdentifiers.empty())
9671 return;
9672
9673 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
9674 IdentifierInfo *WeakId
9675 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
9676 IdentifierInfo *AliasId
9677 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
9678 SourceLocation Loc =
9679 SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
9680 WeakInfo WI(AliasId, Loc);
9681 WeakIDs.push_back(std::make_pair(WeakId, WI));
9682 }
9683 WeakUndeclaredIdentifiers.clear();
9684}
9685
9687 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
9689 VTableUse &TableInfo = VTableUses[Idx++];
9690 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(TableInfo.ID));
9691 VT.Location = SourceLocation::getFromRawEncoding(TableInfo.RawLoc);
9692 VT.DefinitionRequired = TableInfo.Used;
9693 VTables.push_back(VT);
9694 }
9695
9696 VTableUses.clear();
9697}
9698
9700 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation>> &Pending) {
9701 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
9702 PendingInstantiation &Inst = PendingInstantiations[Idx++];
9703 ValueDecl *D = cast<ValueDecl>(GetDecl(Inst.ID));
9705
9706 Pending.push_back(std::make_pair(D, Loc));
9707 }
9708 PendingInstantiations.clear();
9709}
9710
9712 llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>>
9713 &LPTMap) {
9714 for (auto &LPT : LateParsedTemplates) {
9715 ModuleFile *FMod = LPT.first;
9716 RecordDataImpl &LateParsed = LPT.second;
9717 for (unsigned Idx = 0, N = LateParsed.size(); Idx < N;
9718 /* In loop */) {
9719 FunctionDecl *FD = ReadDeclAs<FunctionDecl>(*FMod, LateParsed, Idx);
9720
9721 auto LT = std::make_unique<LateParsedTemplate>();
9722 LT->D = ReadDecl(*FMod, LateParsed, Idx);
9723 LT->FPO = FPOptions::getFromOpaqueInt(LateParsed[Idx++]);
9724
9725 ModuleFile *F = getOwningModuleFile(LT->D);
9726 assert(F && "No module");
9727
9728 unsigned TokN = LateParsed[Idx++];
9729 LT->Toks.reserve(TokN);
9730 for (unsigned T = 0; T < TokN; ++T)
9731 LT->Toks.push_back(ReadToken(*F, LateParsed, Idx));
9732
9733 LPTMap.insert(std::make_pair(FD, std::move(LT)));
9734 }
9735 }
9736
9737 LateParsedTemplates.clear();
9738}
9739
9741 if (!Lambda->getLambdaContextDecl())
9742 return;
9743
9744 auto LambdaInfo =
9745 std::make_pair(Lambda->getLambdaContextDecl()->getCanonicalDecl(),
9746 Lambda->getLambdaIndexInContext());
9747
9748 // Handle the import and then include case for lambdas.
9749 if (auto Iter = LambdaDeclarationsForMerging.find(LambdaInfo);
9750 Iter != LambdaDeclarationsForMerging.end() &&
9751 Iter->second->isFromASTFile() && Lambda->getFirstDecl() == Lambda) {
9753 cast<CXXRecordDecl>(Iter->second)->getMostRecentDecl();
9754 Lambda->setPreviousDecl(Previous);
9755 return;
9756 }
9757
9758 // Keep track of this lambda so it can be merged with another lambda that
9759 // is loaded later.
9760 LambdaDeclarationsForMerging.insert({LambdaInfo, Lambda});
9761}
9762
9764 // It would be complicated to avoid reading the methods anyway. So don't.
9765 ReadMethodPool(Sel);
9766}
9767
9769 assert(ID && "Non-zero identifier ID required");
9770 unsigned Index = translateIdentifierIDToIndex(ID).second;
9771 assert(Index < IdentifiersLoaded.size() && "identifier ID out of range");
9772 IdentifiersLoaded[Index] = II;
9773 if (DeserializationListener)
9774 DeserializationListener->IdentifierRead(ID, II);
9775}
9776
9777/// Set the globally-visible declarations associated with the given
9778/// identifier.
9779///
9780/// If the AST reader is currently in a state where the given declaration IDs
9781/// cannot safely be resolved, they are queued until it is safe to resolve
9782/// them.
9783///
9784/// \param II an IdentifierInfo that refers to one or more globally-visible
9785/// declarations.
9786///
9787/// \param DeclIDs the set of declaration IDs with the name @p II that are
9788/// visible at global scope.
9789///
9790/// \param Decls if non-null, this vector will be populated with the set of
9791/// deserialized declarations. These declarations will not be pushed into
9792/// scope.
9795 SmallVectorImpl<Decl *> *Decls) {
9796 if (NumCurrentElementsDeserializing && !Decls) {
9797 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
9798 return;
9799 }
9800
9801 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
9802 if (!SemaObj) {
9803 // Queue this declaration so that it will be added to the
9804 // translation unit scope and identifier's declaration chain
9805 // once a Sema object is known.
9806 PreloadedDeclIDs.push_back(DeclIDs[I]);
9807 continue;
9808 }
9809
9810 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
9811
9812 // If we're simply supposed to record the declarations, do so now.
9813 if (Decls) {
9814 Decls->push_back(D);
9815 continue;
9816 }
9817
9818 // Introduce this declaration into the translation-unit scope
9819 // and add it to the declaration chain for this identifier, so
9820 // that (unqualified) name lookup will find it.
9821 pushExternalDeclIntoScope(D, II);
9822 }
9823}
9824
9825std::pair<ModuleFile *, unsigned>
9826ASTReader::translateIdentifierIDToIndex(IdentifierID ID) const {
9827 if (ID == 0)
9828 return {nullptr, 0};
9829
9830 unsigned ModuleFileIndex = ID >> 32;
9831 unsigned LocalID = ID & llvm::maskTrailingOnes<IdentifierID>(32);
9832
9833 assert(ModuleFileIndex && "not translating loaded IdentifierID?");
9834 assert(getModuleManager().size() > ModuleFileIndex - 1);
9835
9836 ModuleFile &MF = getModuleManager()[ModuleFileIndex - 1];
9837 assert(LocalID < MF.LocalNumIdentifiers);
9838 return {&MF, MF.BaseIdentifierID + LocalID};
9839}
9840
9842 if (ID == 0)
9843 return nullptr;
9844
9845 if (IdentifiersLoaded.empty()) {
9846 Error("no identifier table in AST file");
9847 return nullptr;
9848 }
9849
9850 auto [M, Index] = translateIdentifierIDToIndex(ID);
9851 if (!IdentifiersLoaded[Index]) {
9852 assert(M != nullptr && "Untranslated Identifier ID?");
9853 assert(Index >= M->BaseIdentifierID);
9854 unsigned LocalIndex = Index - M->BaseIdentifierID;
9855 const unsigned char *Data =
9856 M->IdentifierTableData + M->IdentifierOffsets[LocalIndex];
9857
9858 ASTIdentifierLookupTrait Trait(*this, *M);
9859 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
9860 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
9861 auto &II = PP.getIdentifierTable().get(Key);
9862 IdentifiersLoaded[Index] = &II;
9863 bool IsModule = getPreprocessor().getCurrentModule() != nullptr;
9864 markIdentifierFromAST(*this, II, IsModule);
9865 if (DeserializationListener)
9866 DeserializationListener->IdentifierRead(ID, &II);
9867 }
9868
9869 return IdentifiersLoaded[Index];
9870}
9871
9875
9877 if (LocalID < NUM_PREDEF_IDENT_IDS)
9878 return LocalID;
9879
9880 if (!M.ModuleOffsetMap.empty())
9881 ReadModuleOffsetMap(M);
9882
9883 unsigned ModuleFileIndex = LocalID >> 32;
9884 LocalID &= llvm::maskTrailingOnes<IdentifierID>(32);
9885 ModuleFile *MF =
9886 ModuleFileIndex ? M.TransitiveImports[ModuleFileIndex - 1] : &M;
9887 assert(MF && "malformed identifier ID encoding?");
9888
9889 if (!ModuleFileIndex)
9890 LocalID -= NUM_PREDEF_IDENT_IDS;
9891
9892 return ((IdentifierID)(MF->Index + 1) << 32) | LocalID;
9893}
9894
9895std::pair<ModuleFile *, unsigned>
9896ASTReader::translateMacroIDToIndex(MacroID ID) const {
9897 if (ID == 0)
9898 return {nullptr, 0};
9899
9900 unsigned ModuleFileIndex = ID >> 32;
9901 assert(ModuleFileIndex && "not translating loaded MacroID?");
9902 assert(getModuleManager().size() > ModuleFileIndex - 1);
9903 ModuleFile &MF = getModuleManager()[ModuleFileIndex - 1];
9904
9905 unsigned LocalID = ID & llvm::maskTrailingOnes<MacroID>(32);
9906 assert(LocalID < MF.LocalNumMacros);
9907 return {&MF, MF.BaseMacroID + LocalID};
9908}
9909
9911 if (ID == 0)
9912 return nullptr;
9913
9914 if (MacrosLoaded.empty()) {
9915 Error("no macro table in AST file");
9916 return nullptr;
9917 }
9918
9919 auto [M, Index] = translateMacroIDToIndex(ID);
9920 if (!MacrosLoaded[Index]) {
9921 assert(M != nullptr && "Untranslated Macro ID?");
9922 assert(Index >= M->BaseMacroID);
9923 unsigned LocalIndex = Index - M->BaseMacroID;
9924 uint64_t DataOffset = M->MacroOffsetsBase + M->MacroOffsets[LocalIndex];
9925 MacrosLoaded[Index] = ReadMacroRecord(*M, DataOffset);
9926
9927 if (DeserializationListener)
9928 DeserializationListener->MacroRead(ID, MacrosLoaded[Index]);
9929 }
9930
9931 return MacrosLoaded[Index];
9932}
9933
9935 if (LocalID < NUM_PREDEF_MACRO_IDS)
9936 return LocalID;
9937
9938 if (!M.ModuleOffsetMap.empty())
9939 ReadModuleOffsetMap(M);
9940
9941 unsigned ModuleFileIndex = LocalID >> 32;
9942 LocalID &= llvm::maskTrailingOnes<MacroID>(32);
9943 ModuleFile *MF =
9944 ModuleFileIndex ? M.TransitiveImports[ModuleFileIndex - 1] : &M;
9945 assert(MF && "malformed identifier ID encoding?");
9946
9947 if (!ModuleFileIndex) {
9948 assert(LocalID >= NUM_PREDEF_MACRO_IDS);
9949 LocalID -= NUM_PREDEF_MACRO_IDS;
9950 }
9951
9952 return (static_cast<MacroID>(MF->Index + 1) << 32) | LocalID;
9953}
9954
9956ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) const {
9957 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
9958 return LocalID;
9959
9960 if (!M.ModuleOffsetMap.empty())
9961 ReadModuleOffsetMap(M);
9962
9965 assert(I != M.SubmoduleRemap.end()
9966 && "Invalid index into submodule index remap");
9967
9968 return LocalID + I->second;
9969}
9970
9972 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
9973 assert(GlobalID == 0 && "Unhandled global submodule ID");
9974 return nullptr;
9975 }
9976
9977 if (GlobalID > SubmodulesLoaded.size()) {
9978 Error("submodule ID out of range in AST file");
9979 return nullptr;
9980 }
9981
9982 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
9983}
9984
9986 return getSubmodule(ID);
9987}
9988
9990 if (ID & 1) {
9991 // It's a module, look it up by submodule ID.
9992 auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(M, ID >> 1));
9993 return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
9994 } else {
9995 // It's a prefix (preamble, PCH, ...). Look it up by index.
9996 int IndexFromEnd = static_cast<int>(ID >> 1);
9997 assert(IndexFromEnd && "got reference to unknown module file");
9998 return getModuleManager().pch_modules().end()[-IndexFromEnd];
9999 }
10000}
10001
10003 if (!M)
10004 return 1;
10005
10006 // For a file representing a module, use the submodule ID of the top-level
10007 // module as the file ID. For any other kind of file, the number of such
10008 // files loaded beforehand will be the same on reload.
10009 // FIXME: Is this true even if we have an explicit module file and a PCH?
10010 if (M->isModule())
10011 return ((M->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
10012
10013 auto PCHModules = getModuleManager().pch_modules();
10014 auto I = llvm::find(PCHModules, M);
10015 assert(I != PCHModules.end() && "emitting reference to unknown file");
10016 return std::distance(I, PCHModules.end()) << 1;
10017}
10018
10019std::optional<ASTSourceDescriptor> ASTReader::getSourceDescriptor(unsigned ID) {
10020 if (Module *M = getSubmodule(ID))
10021 return ASTSourceDescriptor(*M);
10022
10023 // If there is only a single PCH, return it instead.
10024 // Chained PCH are not supported.
10025 const auto &PCHChain = ModuleMgr.pch_modules();
10026 if (std::distance(std::begin(PCHChain), std::end(PCHChain))) {
10027 ModuleFile &MF = ModuleMgr.getPrimaryModule();
10028 StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName);
10029 StringRef FileName = llvm::sys::path::filename(MF.FileName);
10030 return ASTSourceDescriptor(ModuleName,
10031 llvm::sys::path::parent_path(MF.FileName),
10032 FileName, MF.Signature);
10033 }
10034 return std::nullopt;
10035}
10036
10038 auto I = DefinitionSource.find(FD);
10039 if (I == DefinitionSource.end())
10040 return EK_ReplyHazy;
10041 return I->second ? EK_Never : EK_Always;
10042}
10043
10045 return ThisDeclarationWasADefinitionSet.contains(FD);
10046}
10047
10049 return DecodeSelector(getGlobalSelectorID(M, LocalID));
10050}
10051
10053 if (ID == 0)
10054 return Selector();
10055
10056 if (ID > SelectorsLoaded.size()) {
10057 Error("selector ID out of range in AST file");
10058 return Selector();
10059 }
10060
10061 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
10062 // Load this selector from the selector table.
10063 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
10064 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
10065 ModuleFile &M = *I->second;
10066 ASTSelectorLookupTrait Trait(*this, M);
10067 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
10068 SelectorsLoaded[ID - 1] =
10069 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
10070 if (DeserializationListener)
10071 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
10072 }
10073
10074 return SelectorsLoaded[ID - 1];
10075}
10076
10080
10082 // ID 0 (the null selector) is considered an external selector.
10083 return getTotalNumSelectors() + 1;
10084}
10085
10087ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
10088 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
10089 return LocalID;
10090
10091 if (!M.ModuleOffsetMap.empty())
10092 ReadModuleOffsetMap(M);
10093
10096 assert(I != M.SelectorRemap.end()
10097 && "Invalid index into selector index remap");
10098
10099 return LocalID + I->second;
10100}
10101
10127
10129 DeclarationNameInfo NameInfo;
10130 NameInfo.setName(readDeclarationName());
10131 NameInfo.setLoc(readSourceLocation());
10132 NameInfo.setInfo(readDeclarationNameLoc(NameInfo.getName()));
10133 return NameInfo;
10134}
10135
10139
10141 auto Kind = readInt();
10142 auto ResultType = readQualType();
10143 auto Value = readAPInt();
10144 SpirvOperand Op(SpirvOperand::SpirvOperandKind(Kind), ResultType, Value);
10145 assert(Op.isValid());
10146 return Op;
10147}
10148
10151 unsigned NumTPLists = readInt();
10152 Info.NumTemplParamLists = NumTPLists;
10153 if (NumTPLists) {
10154 Info.TemplParamLists =
10155 new (getContext()) TemplateParameterList *[NumTPLists];
10156 for (unsigned i = 0; i != NumTPLists; ++i)
10158 }
10159}
10160
10163 SourceLocation TemplateLoc = readSourceLocation();
10164 SourceLocation LAngleLoc = readSourceLocation();
10165 SourceLocation RAngleLoc = readSourceLocation();
10166
10167 unsigned NumParams = readInt();
10169 Params.reserve(NumParams);
10170 while (NumParams--)
10171 Params.push_back(readDeclAs<NamedDecl>());
10172
10173 bool HasRequiresClause = readBool();
10174 Expr *RequiresClause = HasRequiresClause ? readExpr() : nullptr;
10175
10177 getContext(), TemplateLoc, LAngleLoc, Params, RAngleLoc, RequiresClause);
10178 return TemplateParams;
10179}
10180
10183 bool Canonicalize) {
10184 unsigned NumTemplateArgs = readInt();
10185 TemplArgs.reserve(NumTemplateArgs);
10186 while (NumTemplateArgs--)
10187 TemplArgs.push_back(readTemplateArgument(Canonicalize));
10188}
10189
10190/// Read a UnresolvedSet structure.
10192 unsigned NumDecls = readInt();
10193 Set.reserve(getContext(), NumDecls);
10194 while (NumDecls--) {
10195 GlobalDeclID ID = readDeclID();
10197 Set.addLazyDecl(getContext(), ID, AS);
10198 }
10199}
10200
10203 bool isVirtual = readBool();
10204 bool isBaseOfClass = readBool();
10205 AccessSpecifier AS = static_cast<AccessSpecifier>(readInt());
10206 bool inheritConstructors = readBool();
10208 SourceRange Range = readSourceRange();
10209 SourceLocation EllipsisLoc = readSourceLocation();
10210 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
10211 EllipsisLoc);
10212 Result.setInheritConstructors(inheritConstructors);
10213 return Result;
10214}
10215
10218 ASTContext &Context = getContext();
10219 unsigned NumInitializers = readInt();
10220 assert(NumInitializers && "wrote ctor initializers but have no inits");
10221 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
10222 for (unsigned i = 0; i != NumInitializers; ++i) {
10223 TypeSourceInfo *TInfo = nullptr;
10224 bool IsBaseVirtual = false;
10225 FieldDecl *Member = nullptr;
10226 IndirectFieldDecl *IndirectMember = nullptr;
10227
10229 switch (Type) {
10231 TInfo = readTypeSourceInfo();
10232 IsBaseVirtual = readBool();
10233 break;
10234
10236 TInfo = readTypeSourceInfo();
10237 break;
10238
10241 break;
10242
10244 IndirectMember = readDeclAs<IndirectFieldDecl>();
10245 break;
10246 }
10247
10248 SourceLocation MemberOrEllipsisLoc = readSourceLocation();
10249 Expr *Init = readExpr();
10250 SourceLocation LParenLoc = readSourceLocation();
10251 SourceLocation RParenLoc = readSourceLocation();
10252
10253 CXXCtorInitializer *BOMInit;
10255 BOMInit = new (Context)
10256 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
10257 RParenLoc, MemberOrEllipsisLoc);
10259 BOMInit = new (Context)
10260 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
10261 else if (Member)
10262 BOMInit = new (Context)
10263 CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc, LParenLoc,
10264 Init, RParenLoc);
10265 else
10266 BOMInit = new (Context)
10267 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
10268 LParenLoc, Init, RParenLoc);
10269
10270 if (/*IsWritten*/readBool()) {
10271 unsigned SourceOrder = readInt();
10272 BOMInit->setSourceOrder(SourceOrder);
10273 }
10274
10275 CtorInitializers[i] = BOMInit;
10276 }
10277
10278 return CtorInitializers;
10279}
10280
10283 ASTContext &Context = getContext();
10284 unsigned N = readInt();
10286 for (unsigned I = 0; I != N; ++I) {
10287 auto Kind = readNestedNameSpecifierKind();
10288 switch (Kind) {
10290 auto *NS = readDeclAs<NamespaceBaseDecl>();
10291 SourceRange Range = readSourceRange();
10292 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
10293 break;
10294 }
10295
10298 if (!T)
10299 return NestedNameSpecifierLoc();
10300 SourceLocation ColonColonLoc = readSourceLocation();
10301 Builder.Make(Context, T->getTypeLoc(), ColonColonLoc);
10302 break;
10303 }
10304
10306 SourceLocation ColonColonLoc = readSourceLocation();
10307 Builder.MakeGlobal(Context, ColonColonLoc);
10308 break;
10309 }
10310
10313 SourceRange Range = readSourceRange();
10314 Builder.MakeMicrosoftSuper(Context, RD, Range.getBegin(), Range.getEnd());
10315 break;
10316 }
10317
10319 llvm_unreachable("unexpected null nested name specifier");
10320 }
10321 }
10322
10323 return Builder.getWithLocInContext(Context);
10324}
10325
10327 unsigned &Idx) {
10330 return SourceRange(beg, end);
10331}
10332
10334 const StringRef Blob) {
10335 unsigned Count = Record[0];
10336 const char *Byte = Blob.data();
10337 llvm::BitVector Ret = llvm::BitVector(Count, false);
10338 for (unsigned I = 0; I < Count; ++Byte)
10339 for (unsigned Bit = 0; Bit < 8 && I < Count; ++Bit, ++I)
10340 if (*Byte & (1 << Bit))
10341 Ret[I] = true;
10342 return Ret;
10343}
10344
10345/// Read a floating-point value
10346llvm::APFloat ASTRecordReader::readAPFloat(const llvm::fltSemantics &Sem) {
10347 return llvm::APFloat(Sem, readAPInt());
10348}
10349
10350// Read a string
10351std::string ASTReader::ReadString(const RecordDataImpl &Record, unsigned &Idx) {
10352 unsigned Len = Record[Idx++];
10353 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
10354 Idx += Len;
10355 return Result;
10356}
10357
10358StringRef ASTReader::ReadStringBlob(const RecordDataImpl &Record, unsigned &Idx,
10359 StringRef &Blob) {
10360 unsigned Len = Record[Idx++];
10361 StringRef Result = Blob.substr(0, Len);
10362 Blob = Blob.substr(Len);
10363 return Result;
10364}
10365
10367 unsigned &Idx) {
10368 return ReadPath(F.BaseDirectory, Record, Idx);
10369}
10370
10371std::string ASTReader::ReadPath(StringRef BaseDirectory,
10372 const RecordData &Record, unsigned &Idx) {
10373 std::string Filename = ReadString(Record, Idx);
10374 return ResolveImportedPathAndAllocate(PathBuf, Filename, BaseDirectory);
10375}
10376
10377std::string ASTReader::ReadPathBlob(StringRef BaseDirectory,
10378 const RecordData &Record, unsigned &Idx,
10379 StringRef &Blob) {
10380 StringRef Filename = ReadStringBlob(Record, Idx, Blob);
10381 return ResolveImportedPathAndAllocate(PathBuf, Filename, BaseDirectory);
10382}
10383
10385 unsigned &Idx) {
10386 unsigned Major = Record[Idx++];
10387 unsigned Minor = Record[Idx++];
10388 unsigned Subminor = Record[Idx++];
10389 if (Minor == 0)
10390 return VersionTuple(Major);
10391 if (Subminor == 0)
10392 return VersionTuple(Major, Minor - 1);
10393 return VersionTuple(Major, Minor - 1, Subminor - 1);
10394}
10395
10402
10403DiagnosticBuilder ASTReader::Diag(unsigned DiagID) const {
10404 return Diag(CurrentImportLoc, DiagID);
10405}
10406
10408 return Diags.Report(Loc, DiagID);
10409}
10410
10412 llvm::function_ref<void()> Fn) {
10413 // When Sema is available, avoid duplicate errors.
10414 if (SemaObj) {
10415 SemaObj->runWithSufficientStackSpace(Loc, Fn);
10416 return;
10417 }
10418
10419 StackHandler.runWithSufficientStackSpace(Loc, Fn);
10420}
10421
10422/// Retrieve the identifier table associated with the
10423/// preprocessor.
10425 return PP.getIdentifierTable();
10426}
10427
10428/// Record that the given ID maps to the given switch-case
10429/// statement.
10431 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
10432 "Already have a SwitchCase with this ID");
10433 (*CurrSwitchCaseStmts)[ID] = SC;
10434}
10435
10436/// Retrieve the switch-case statement with the given ID.
10438 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
10439 return (*CurrSwitchCaseStmts)[ID];
10440}
10441
10443 CurrSwitchCaseStmts->clear();
10444}
10445
10447 ASTContext &Context = getContext();
10448 std::vector<RawComment *> Comments;
10449 for (SmallVectorImpl<std::pair<BitstreamCursor,
10451 I = CommentsCursors.begin(),
10452 E = CommentsCursors.end();
10453 I != E; ++I) {
10454 Comments.clear();
10455 BitstreamCursor &Cursor = I->first;
10456 serialization::ModuleFile &F = *I->second;
10457 SavedStreamPosition SavedPosition(Cursor);
10458
10460 while (true) {
10462 Cursor.advanceSkippingSubblocks(
10463 BitstreamCursor::AF_DontPopBlockAtEnd);
10464 if (!MaybeEntry) {
10465 Error(MaybeEntry.takeError());
10466 return;
10467 }
10468 llvm::BitstreamEntry Entry = MaybeEntry.get();
10469
10470 switch (Entry.Kind) {
10471 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
10472 case llvm::BitstreamEntry::Error:
10473 Error("malformed block record in AST file");
10474 return;
10475 case llvm::BitstreamEntry::EndBlock:
10476 goto NextCursor;
10477 case llvm::BitstreamEntry::Record:
10478 // The interesting case.
10479 break;
10480 }
10481
10482 // Read a record.
10483 Record.clear();
10484 Expected<unsigned> MaybeComment = Cursor.readRecord(Entry.ID, Record);
10485 if (!MaybeComment) {
10486 Error(MaybeComment.takeError());
10487 return;
10488 }
10489 switch ((CommentRecordTypes)MaybeComment.get()) {
10490 case COMMENTS_RAW_COMMENT: {
10491 unsigned Idx = 0;
10492 SourceRange SR = ReadSourceRange(F, Record, Idx);
10495 bool IsTrailingComment = Record[Idx++];
10496 bool IsAlmostTrailingComment = Record[Idx++];
10497 Comments.push_back(new (Context) RawComment(
10498 SR, Kind, IsTrailingComment, IsAlmostTrailingComment));
10499 break;
10500 }
10501 }
10502 }
10503 NextCursor:
10504 for (RawComment *C : Comments) {
10505 SourceLocation CommentLoc = C->getBeginLoc();
10506 if (CommentLoc.isValid()) {
10507 FileIDAndOffset Loc = SourceMgr.getDecomposedLoc(CommentLoc);
10508 if (Loc.first.isValid())
10509 Context.Comments.OrderedComments[Loc.first].emplace(Loc.second, C);
10510 }
10511 }
10512 }
10513}
10514
10516 serialization::ModuleFile &MF, bool IncludeSystem,
10517 llvm::function_ref<void(const serialization::InputFileInfo &IFI,
10518 bool IsSystem)>
10519 Visitor) {
10520 unsigned NumUserInputs = MF.NumUserInputFiles;
10521 unsigned NumInputs = MF.InputFilesLoaded.size();
10522 assert(NumUserInputs <= NumInputs);
10523 unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
10524 for (unsigned I = 0; I < N; ++I) {
10525 bool IsSystem = I >= NumUserInputs;
10526 InputFileInfo IFI = getInputFileInfo(MF, I+1);
10527 Visitor(IFI, IsSystem);
10528 }
10529}
10530
10532 bool IncludeSystem, bool Complain,
10533 llvm::function_ref<void(const serialization::InputFile &IF,
10534 bool isSystem)> Visitor) {
10535 unsigned NumUserInputs = MF.NumUserInputFiles;
10536 unsigned NumInputs = MF.InputFilesLoaded.size();
10537 assert(NumUserInputs <= NumInputs);
10538 unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
10539 for (unsigned I = 0; I < N; ++I) {
10540 bool IsSystem = I >= NumUserInputs;
10541 InputFile IF = getInputFile(MF, I+1, Complain);
10542 Visitor(IF, IsSystem);
10543 }
10544}
10545
10548 llvm::function_ref<void(FileEntryRef FE)> Visitor) {
10549 unsigned NumInputs = MF.InputFilesLoaded.size();
10550 for (unsigned I = 0; I < NumInputs; ++I) {
10551 InputFileInfo IFI = getInputFileInfo(MF, I + 1);
10552 if (IFI.TopLevel && IFI.ModuleMap)
10553 if (auto FE = getInputFile(MF, I + 1).getFile())
10554 Visitor(*FE);
10555 }
10556}
10557
10558void ASTReader::finishPendingActions() {
10559 while (!PendingIdentifierInfos.empty() ||
10560 !PendingDeducedFunctionTypes.empty() ||
10561 !PendingDeducedVarTypes.empty() || !PendingDeclChains.empty() ||
10562 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
10563 !PendingUpdateRecords.empty() ||
10564 !PendingObjCExtensionIvarRedeclarations.empty()) {
10565 // If any identifiers with corresponding top-level declarations have
10566 // been loaded, load those declarations now.
10567 using TopLevelDeclsMap =
10568 llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2>>;
10569 TopLevelDeclsMap TopLevelDecls;
10570
10571 while (!PendingIdentifierInfos.empty()) {
10572 IdentifierInfo *II = PendingIdentifierInfos.back().first;
10574 std::move(PendingIdentifierInfos.back().second);
10575 PendingIdentifierInfos.pop_back();
10576
10577 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
10578 }
10579
10580 // Load each function type that we deferred loading because it was a
10581 // deduced type that might refer to a local type declared within itself.
10582 for (unsigned I = 0; I != PendingDeducedFunctionTypes.size(); ++I) {
10583 auto *FD = PendingDeducedFunctionTypes[I].first;
10584 FD->setType(GetType(PendingDeducedFunctionTypes[I].second));
10585
10586 if (auto *DT = FD->getReturnType()->getContainedDeducedType()) {
10587 // If we gave a function a deduced return type, remember that we need to
10588 // propagate that along the redeclaration chain.
10589 if (DT->isDeduced()) {
10590 PendingDeducedTypeUpdates.insert(
10591 {FD->getCanonicalDecl(), FD->getReturnType()});
10592 continue;
10593 }
10594
10595 // The function has undeduced DeduceType return type. We hope we can
10596 // find the deduced type by iterating the redecls in other modules
10597 // later.
10598 PendingUndeducedFunctionDecls.push_back(FD);
10599 continue;
10600 }
10601 }
10602 PendingDeducedFunctionTypes.clear();
10603
10604 // Load each variable type that we deferred loading because it was a
10605 // deduced type that might refer to a local type declared within itself.
10606 for (unsigned I = 0; I != PendingDeducedVarTypes.size(); ++I) {
10607 auto *VD = PendingDeducedVarTypes[I].first;
10608 VD->setType(GetType(PendingDeducedVarTypes[I].second));
10609 }
10610 PendingDeducedVarTypes.clear();
10611
10612 // Load pending declaration chains.
10613 for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
10614 loadPendingDeclChain(PendingDeclChains[I].first,
10615 PendingDeclChains[I].second);
10616 PendingDeclChains.clear();
10617
10618 // Make the most recent of the top-level declarations visible.
10619 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
10620 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
10621 IdentifierInfo *II = TLD->first;
10622 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
10623 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
10624 }
10625 }
10626
10627 // Load any pending macro definitions.
10628 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
10629 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
10630 SmallVector<PendingMacroInfo, 2> GlobalIDs;
10631 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
10632 // Initialize the macro history from chained-PCHs ahead of module imports.
10633 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
10634 ++IDIdx) {
10635 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
10636 if (!Info.M->isModule())
10637 resolvePendingMacro(II, Info);
10638 }
10639 // Handle module imports.
10640 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
10641 ++IDIdx) {
10642 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
10643 if (Info.M->isModule())
10644 resolvePendingMacro(II, Info);
10645 }
10646 }
10647 PendingMacroIDs.clear();
10648
10649 // Wire up the DeclContexts for Decls that we delayed setting until
10650 // recursive loading is completed.
10651 while (!PendingDeclContextInfos.empty()) {
10652 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
10653 PendingDeclContextInfos.pop_front();
10654 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
10655 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
10656 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
10657 }
10658
10659 // Perform any pending declaration updates.
10660 while (!PendingUpdateRecords.empty()) {
10661 auto Update = PendingUpdateRecords.pop_back_val();
10662 ReadingKindTracker ReadingKind(Read_Decl, *this);
10663 loadDeclUpdateRecords(Update);
10664 }
10665
10666 while (!PendingObjCExtensionIvarRedeclarations.empty()) {
10667 auto ExtensionsPair = PendingObjCExtensionIvarRedeclarations.back().first;
10668 auto DuplicateIvars =
10669 PendingObjCExtensionIvarRedeclarations.back().second;
10671 StructuralEquivalenceContext Ctx(
10672 ContextObj->getLangOpts(), ExtensionsPair.first->getASTContext(),
10673 ExtensionsPair.second->getASTContext(), NonEquivalentDecls,
10674 StructuralEquivalenceKind::Default, /*StrictTypeSpelling =*/false,
10675 /*Complain =*/false,
10676 /*ErrorOnTagTypeMismatch =*/true);
10677 if (Ctx.IsEquivalent(ExtensionsPair.first, ExtensionsPair.second)) {
10678 // Merge redeclared ivars with their predecessors.
10679 for (auto IvarPair : DuplicateIvars) {
10680 ObjCIvarDecl *Ivar = IvarPair.first, *PrevIvar = IvarPair.second;
10681 // Change semantic DeclContext but keep the lexical one.
10682 Ivar->setDeclContextsImpl(PrevIvar->getDeclContext(),
10683 Ivar->getLexicalDeclContext(),
10684 getContext());
10685 getContext().setPrimaryMergedDecl(Ivar, PrevIvar->getCanonicalDecl());
10686 }
10687 // Invalidate duplicate extension and the cached ivar list.
10688 ExtensionsPair.first->setInvalidDecl();
10689 ExtensionsPair.second->getClassInterface()
10690 ->getDefinition()
10691 ->setIvarList(nullptr);
10692 } else {
10693 for (auto IvarPair : DuplicateIvars) {
10694 Diag(IvarPair.first->getLocation(),
10695 diag::err_duplicate_ivar_declaration)
10696 << IvarPair.first->getIdentifier();
10697 Diag(IvarPair.second->getLocation(), diag::note_previous_definition);
10698 }
10699 }
10700 PendingObjCExtensionIvarRedeclarations.pop_back();
10701 }
10702 }
10703
10704 // At this point, all update records for loaded decls are in place, so any
10705 // fake class definitions should have become real.
10706 assert(PendingFakeDefinitionData.empty() &&
10707 "faked up a class definition but never saw the real one");
10708
10709 // If we deserialized any C++ or Objective-C class definitions, any
10710 // Objective-C protocol definitions, or any redeclarable templates, make sure
10711 // that all redeclarations point to the definitions. Note that this can only
10712 // happen now, after the redeclaration chains have been fully wired.
10713 for (Decl *D : PendingDefinitions) {
10714 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
10715 if (auto *RD = dyn_cast<CXXRecordDecl>(TD)) {
10716 for (auto *R = getMostRecentExistingDecl(RD); R;
10717 R = R->getPreviousDecl()) {
10718 assert((R == D) ==
10719 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
10720 "declaration thinks it's the definition but it isn't");
10721 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
10722 }
10723 }
10724
10725 continue;
10726 }
10727
10728 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
10729 // Make sure that the ObjCInterfaceType points at the definition.
10730 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
10731 ->Decl = ID;
10732
10733 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
10734 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
10735
10736 continue;
10737 }
10738
10739 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
10740 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
10741 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
10742
10743 continue;
10744 }
10745
10746 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
10747 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
10748 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
10749 }
10750 PendingDefinitions.clear();
10751
10752 for (auto [D, Previous] : PendingWarningForDuplicatedDefsInModuleUnits) {
10753 auto hasDefinitionImpl = [this](Decl *D, auto hasDefinitionImpl) {
10754 if (auto *VD = dyn_cast<VarDecl>(D))
10755 return VD->isThisDeclarationADefinition() ||
10756 VD->isThisDeclarationADemotedDefinition();
10757
10758 if (auto *TD = dyn_cast<TagDecl>(D))
10759 return TD->isThisDeclarationADefinition() ||
10760 TD->isThisDeclarationADemotedDefinition();
10761
10762 if (auto *FD = dyn_cast<FunctionDecl>(D))
10763 return FD->isThisDeclarationADefinition() || PendingBodies.count(FD);
10764
10765 if (auto *RTD = dyn_cast<RedeclarableTemplateDecl>(D))
10766 return hasDefinitionImpl(RTD->getTemplatedDecl(), hasDefinitionImpl);
10767
10768 // Conservatively return false here.
10769 return false;
10770 };
10771
10772 auto hasDefinition = [&hasDefinitionImpl](Decl *D) {
10773 return hasDefinitionImpl(D, hasDefinitionImpl);
10774 };
10775
10776 // It is not good to prevent multiple declarations since the forward
10777 // declaration is common. Let's try to avoid duplicated definitions
10778 // only.
10780 continue;
10781
10782 Module *PM = Previous->getOwningModule();
10783 Module *DM = D->getOwningModule();
10784 Diag(D->getLocation(), diag::warn_decls_in_multiple_modules)
10786 << (DM ? DM->getTopLevelModuleName() : "global module");
10787 Diag(Previous->getLocation(), diag::note_also_found);
10788 }
10789 PendingWarningForDuplicatedDefsInModuleUnits.clear();
10790
10791 // Load the bodies of any functions or methods we've encountered. We do
10792 // this now (delayed) so that we can be sure that the declaration chains
10793 // have been fully wired up (hasBody relies on this).
10794 // FIXME: We shouldn't require complete redeclaration chains here.
10795 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
10796 PBEnd = PendingBodies.end();
10797 PB != PBEnd; ++PB) {
10798 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
10799 // FIXME: Check for =delete/=default?
10800 const FunctionDecl *Defn = nullptr;
10801 if (!getContext().getLangOpts().Modules || !FD->hasBody(Defn)) {
10802 FD->setLazyBody(PB->second);
10803 } else {
10804 auto *NonConstDefn = const_cast<FunctionDecl*>(Defn);
10805 mergeDefinitionVisibility(NonConstDefn, FD);
10806
10807 if (!FD->isLateTemplateParsed() &&
10808 !NonConstDefn->isLateTemplateParsed() &&
10809 // We only perform ODR checks for decls not in the explicit
10810 // global module fragment.
10811 !shouldSkipCheckingODR(FD) &&
10812 !shouldSkipCheckingODR(NonConstDefn) &&
10813 FD->getODRHash() != NonConstDefn->getODRHash()) {
10814 if (!isa<CXXMethodDecl>(FD)) {
10815 PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
10816 } else if (FD->getLexicalParent()->isFileContext() &&
10817 NonConstDefn->getLexicalParent()->isFileContext()) {
10818 // Only diagnose out-of-line method definitions. If they are
10819 // in class definitions, then an error will be generated when
10820 // processing the class bodies.
10821 PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
10822 }
10823 }
10824 }
10825 continue;
10826 }
10827
10828 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
10829 if (!getContext().getLangOpts().Modules || !MD->hasBody())
10830 MD->setLazyBody(PB->second);
10831 }
10832 PendingBodies.clear();
10833
10834 // Inform any classes that had members added that they now have more members.
10835 for (auto [RD, MD] : PendingAddedClassMembers) {
10836 RD->addedMember(MD);
10837 }
10838 PendingAddedClassMembers.clear();
10839
10840 // Do some cleanup.
10841 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
10843 PendingMergedDefinitionsToDeduplicate.clear();
10844
10845 // For each decl chain that we wanted to complete while deserializing, mark
10846 // it as "still needs to be completed".
10847 for (Decl *D : PendingIncompleteDeclChains)
10848 markIncompleteDeclChain(D);
10849 PendingIncompleteDeclChains.clear();
10850
10851 assert(PendingIdentifierInfos.empty() &&
10852 "Should be empty at the end of finishPendingActions");
10853 assert(PendingDeducedFunctionTypes.empty() &&
10854 "Should be empty at the end of finishPendingActions");
10855 assert(PendingDeducedVarTypes.empty() &&
10856 "Should be empty at the end of finishPendingActions");
10857 assert(PendingDeclChains.empty() &&
10858 "Should be empty at the end of finishPendingActions");
10859 assert(PendingMacroIDs.empty() &&
10860 "Should be empty at the end of finishPendingActions");
10861 assert(PendingDeclContextInfos.empty() &&
10862 "Should be empty at the end of finishPendingActions");
10863 assert(PendingUpdateRecords.empty() &&
10864 "Should be empty at the end of finishPendingActions");
10865 assert(PendingObjCExtensionIvarRedeclarations.empty() &&
10866 "Should be empty at the end of finishPendingActions");
10867 assert(PendingFakeDefinitionData.empty() &&
10868 "Should be empty at the end of finishPendingActions");
10869 assert(PendingDefinitions.empty() &&
10870 "Should be empty at the end of finishPendingActions");
10871 assert(PendingWarningForDuplicatedDefsInModuleUnits.empty() &&
10872 "Should be empty at the end of finishPendingActions");
10873 assert(PendingBodies.empty() &&
10874 "Should be empty at the end of finishPendingActions");
10875 assert(PendingAddedClassMembers.empty() &&
10876 "Should be empty at the end of finishPendingActions");
10877 assert(PendingMergedDefinitionsToDeduplicate.empty() &&
10878 "Should be empty at the end of finishPendingActions");
10879 assert(PendingIncompleteDeclChains.empty() &&
10880 "Should be empty at the end of finishPendingActions");
10881}
10882
10883void ASTReader::diagnoseOdrViolations() {
10884 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty() &&
10885 PendingRecordOdrMergeFailures.empty() &&
10886 PendingFunctionOdrMergeFailures.empty() &&
10887 PendingEnumOdrMergeFailures.empty() &&
10888 PendingObjCInterfaceOdrMergeFailures.empty() &&
10889 PendingObjCProtocolOdrMergeFailures.empty())
10890 return;
10891
10892 // Trigger the import of the full definition of each class that had any
10893 // odr-merging problems, so we can produce better diagnostics for them.
10894 // These updates may in turn find and diagnose some ODR failures, so take
10895 // ownership of the set first.
10896 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
10897 PendingOdrMergeFailures.clear();
10898 for (auto &Merge : OdrMergeFailures) {
10899 Merge.first->buildLookup();
10900 Merge.first->decls_begin();
10901 Merge.first->bases_begin();
10902 Merge.first->vbases_begin();
10903 for (auto &RecordPair : Merge.second) {
10904 auto *RD = RecordPair.first;
10905 RD->decls_begin();
10906 RD->bases_begin();
10907 RD->vbases_begin();
10908 }
10909 }
10910
10911 // Trigger the import of the full definition of each record in C/ObjC.
10912 auto RecordOdrMergeFailures = std::move(PendingRecordOdrMergeFailures);
10913 PendingRecordOdrMergeFailures.clear();
10914 for (auto &Merge : RecordOdrMergeFailures) {
10915 Merge.first->decls_begin();
10916 for (auto &D : Merge.second)
10917 D->decls_begin();
10918 }
10919
10920 // Trigger the import of the full interface definition.
10921 auto ObjCInterfaceOdrMergeFailures =
10922 std::move(PendingObjCInterfaceOdrMergeFailures);
10923 PendingObjCInterfaceOdrMergeFailures.clear();
10924 for (auto &Merge : ObjCInterfaceOdrMergeFailures) {
10925 Merge.first->decls_begin();
10926 for (auto &InterfacePair : Merge.second)
10927 InterfacePair.first->decls_begin();
10928 }
10929
10930 // Trigger the import of functions.
10931 auto FunctionOdrMergeFailures = std::move(PendingFunctionOdrMergeFailures);
10932 PendingFunctionOdrMergeFailures.clear();
10933 for (auto &Merge : FunctionOdrMergeFailures) {
10934 Merge.first->buildLookup();
10935 Merge.first->decls_begin();
10936 Merge.first->getBody();
10937 for (auto &FD : Merge.second) {
10938 FD->buildLookup();
10939 FD->decls_begin();
10940 FD->getBody();
10941 }
10942 }
10943
10944 // Trigger the import of enums.
10945 auto EnumOdrMergeFailures = std::move(PendingEnumOdrMergeFailures);
10946 PendingEnumOdrMergeFailures.clear();
10947 for (auto &Merge : EnumOdrMergeFailures) {
10948 Merge.first->decls_begin();
10949 for (auto &Enum : Merge.second) {
10950 Enum->decls_begin();
10951 }
10952 }
10953
10954 // Trigger the import of the full protocol definition.
10955 auto ObjCProtocolOdrMergeFailures =
10956 std::move(PendingObjCProtocolOdrMergeFailures);
10957 PendingObjCProtocolOdrMergeFailures.clear();
10958 for (auto &Merge : ObjCProtocolOdrMergeFailures) {
10959 Merge.first->decls_begin();
10960 for (auto &ProtocolPair : Merge.second)
10961 ProtocolPair.first->decls_begin();
10962 }
10963
10964 // For each declaration from a merged context, check that the canonical
10965 // definition of that context also contains a declaration of the same
10966 // entity.
10967 //
10968 // Caution: this loop does things that might invalidate iterators into
10969 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
10970 while (!PendingOdrMergeChecks.empty()) {
10971 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
10972
10973 // FIXME: Skip over implicit declarations for now. This matters for things
10974 // like implicitly-declared special member functions. This isn't entirely
10975 // correct; we can end up with multiple unmerged declarations of the same
10976 // implicit entity.
10977 if (D->isImplicit())
10978 continue;
10979
10980 DeclContext *CanonDef = D->getDeclContext();
10981
10982 bool Found = false;
10983 const Decl *DCanon = D->getCanonicalDecl();
10984
10985 for (auto *RI : D->redecls()) {
10986 if (RI->getLexicalDeclContext() == CanonDef) {
10987 Found = true;
10988 break;
10989 }
10990 }
10991 if (Found)
10992 continue;
10993
10994 // Quick check failed, time to do the slow thing. Note, we can't just
10995 // look up the name of D in CanonDef here, because the member that is
10996 // in CanonDef might not be found by name lookup (it might have been
10997 // replaced by a more recent declaration in the lookup table), and we
10998 // can't necessarily find it in the redeclaration chain because it might
10999 // be merely mergeable, not redeclarable.
11000 llvm::SmallVector<const NamedDecl*, 4> Candidates;
11001 for (auto *CanonMember : CanonDef->decls()) {
11002 if (CanonMember->getCanonicalDecl() == DCanon) {
11003 // This can happen if the declaration is merely mergeable and not
11004 // actually redeclarable (we looked for redeclarations earlier).
11005 //
11006 // FIXME: We should be able to detect this more efficiently, without
11007 // pulling in all of the members of CanonDef.
11008 Found = true;
11009 break;
11010 }
11011 if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
11012 if (ND->getDeclName() == D->getDeclName())
11013 Candidates.push_back(ND);
11014 }
11015
11016 if (!Found) {
11017 // The AST doesn't like TagDecls becoming invalid after they've been
11018 // completed. We only really need to mark FieldDecls as invalid here.
11019 if (!isa<TagDecl>(D))
11020 D->setInvalidDecl();
11021
11022 // Ensure we don't accidentally recursively enter deserialization while
11023 // we're producing our diagnostic.
11024 Deserializing RecursionGuard(this);
11025
11026 std::string CanonDefModule =
11028 cast<Decl>(CanonDef));
11029 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
11031 << CanonDef << CanonDefModule.empty() << CanonDefModule;
11032
11033 if (Candidates.empty())
11034 Diag(cast<Decl>(CanonDef)->getLocation(),
11035 diag::note_module_odr_violation_no_possible_decls) << D;
11036 else {
11037 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
11038 Diag(Candidates[I]->getLocation(),
11039 diag::note_module_odr_violation_possible_decl)
11040 << Candidates[I];
11041 }
11042
11043 DiagnosedOdrMergeFailures.insert(CanonDef);
11044 }
11045 }
11046
11047 if (OdrMergeFailures.empty() && RecordOdrMergeFailures.empty() &&
11048 FunctionOdrMergeFailures.empty() && EnumOdrMergeFailures.empty() &&
11049 ObjCInterfaceOdrMergeFailures.empty() &&
11050 ObjCProtocolOdrMergeFailures.empty())
11051 return;
11052
11053 ODRDiagsEmitter DiagsEmitter(Diags, getContext(),
11054 getPreprocessor().getLangOpts());
11055
11056 // Issue any pending ODR-failure diagnostics.
11057 for (auto &Merge : OdrMergeFailures) {
11058 // If we've already pointed out a specific problem with this class, don't
11059 // bother issuing a general "something's different" diagnostic.
11060 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
11061 continue;
11062
11063 bool Diagnosed = false;
11064 CXXRecordDecl *FirstRecord = Merge.first;
11065 for (auto &RecordPair : Merge.second) {
11066 if (DiagsEmitter.diagnoseMismatch(FirstRecord, RecordPair.first,
11067 RecordPair.second)) {
11068 Diagnosed = true;
11069 break;
11070 }
11071 }
11072
11073 if (!Diagnosed) {
11074 // All definitions are updates to the same declaration. This happens if a
11075 // module instantiates the declaration of a class template specialization
11076 // and two or more other modules instantiate its definition.
11077 //
11078 // FIXME: Indicate which modules had instantiations of this definition.
11079 // FIXME: How can this even happen?
11080 Diag(Merge.first->getLocation(),
11081 diag::err_module_odr_violation_different_instantiations)
11082 << Merge.first;
11083 }
11084 }
11085
11086 // Issue any pending ODR-failure diagnostics for RecordDecl in C/ObjC. Note
11087 // that in C++ this is done as a part of CXXRecordDecl ODR checking.
11088 for (auto &Merge : RecordOdrMergeFailures) {
11089 // If we've already pointed out a specific problem with this class, don't
11090 // bother issuing a general "something's different" diagnostic.
11091 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
11092 continue;
11093
11094 RecordDecl *FirstRecord = Merge.first;
11095 bool Diagnosed = false;
11096 for (auto *SecondRecord : Merge.second) {
11097 if (DiagsEmitter.diagnoseMismatch(FirstRecord, SecondRecord)) {
11098 Diagnosed = true;
11099 break;
11100 }
11101 }
11102 (void)Diagnosed;
11103 assert(Diagnosed && "Unable to emit ODR diagnostic.");
11104 }
11105
11106 // Issue ODR failures diagnostics for functions.
11107 for (auto &Merge : FunctionOdrMergeFailures) {
11108 FunctionDecl *FirstFunction = Merge.first;
11109 bool Diagnosed = false;
11110 for (auto &SecondFunction : Merge.second) {
11111 if (DiagsEmitter.diagnoseMismatch(FirstFunction, SecondFunction)) {
11112 Diagnosed = true;
11113 break;
11114 }
11115 }
11116 (void)Diagnosed;
11117 assert(Diagnosed && "Unable to emit ODR diagnostic.");
11118 }
11119
11120 // Issue ODR failures diagnostics for enums.
11121 for (auto &Merge : EnumOdrMergeFailures) {
11122 // If we've already pointed out a specific problem with this enum, don't
11123 // bother issuing a general "something's different" diagnostic.
11124 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
11125 continue;
11126
11127 EnumDecl *FirstEnum = Merge.first;
11128 bool Diagnosed = false;
11129 for (auto &SecondEnum : Merge.second) {
11130 if (DiagsEmitter.diagnoseMismatch(FirstEnum, SecondEnum)) {
11131 Diagnosed = true;
11132 break;
11133 }
11134 }
11135 (void)Diagnosed;
11136 assert(Diagnosed && "Unable to emit ODR diagnostic.");
11137 }
11138
11139 for (auto &Merge : ObjCInterfaceOdrMergeFailures) {
11140 // If we've already pointed out a specific problem with this interface,
11141 // don't bother issuing a general "something's different" diagnostic.
11142 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
11143 continue;
11144
11145 bool Diagnosed = false;
11146 ObjCInterfaceDecl *FirstID = Merge.first;
11147 for (auto &InterfacePair : Merge.second) {
11148 if (DiagsEmitter.diagnoseMismatch(FirstID, InterfacePair.first,
11149 InterfacePair.second)) {
11150 Diagnosed = true;
11151 break;
11152 }
11153 }
11154 (void)Diagnosed;
11155 assert(Diagnosed && "Unable to emit ODR diagnostic.");
11156 }
11157
11158 for (auto &Merge : ObjCProtocolOdrMergeFailures) {
11159 // If we've already pointed out a specific problem with this protocol,
11160 // don't bother issuing a general "something's different" diagnostic.
11161 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
11162 continue;
11163
11164 ObjCProtocolDecl *FirstProtocol = Merge.first;
11165 bool Diagnosed = false;
11166 for (auto &ProtocolPair : Merge.second) {
11167 if (DiagsEmitter.diagnoseMismatch(FirstProtocol, ProtocolPair.first,
11168 ProtocolPair.second)) {
11169 Diagnosed = true;
11170 break;
11171 }
11172 }
11173 (void)Diagnosed;
11174 assert(Diagnosed && "Unable to emit ODR diagnostic.");
11175 }
11176}
11177
11179 if (llvm::Timer *T = ReadTimer.get();
11180 ++NumCurrentElementsDeserializing == 1 && T)
11181 ReadTimeRegion.emplace(T);
11182}
11183
11185 assert(NumCurrentElementsDeserializing &&
11186 "FinishedDeserializing not paired with StartedDeserializing");
11187 if (NumCurrentElementsDeserializing == 1) {
11188 // We decrease NumCurrentElementsDeserializing only after pending actions
11189 // are finished, to avoid recursively re-calling finishPendingActions().
11190 finishPendingActions();
11191 }
11192 --NumCurrentElementsDeserializing;
11193
11194 if (NumCurrentElementsDeserializing == 0) {
11195 {
11196 // Guard variable to avoid recursively entering the process of passing
11197 // decls to consumer.
11198 SaveAndRestore GuardPassingDeclsToConsumer(CanPassDeclsToConsumer,
11199 /*NewValue=*/false);
11200
11201 // Propagate exception specification and deduced type updates along
11202 // redeclaration chains.
11203 //
11204 // We do this now rather than in finishPendingActions because we want to
11205 // be able to walk the complete redeclaration chains of the updated decls.
11206 while (!PendingExceptionSpecUpdates.empty() ||
11207 !PendingDeducedTypeUpdates.empty() ||
11208 !PendingUndeducedFunctionDecls.empty()) {
11209 auto ESUpdates = std::move(PendingExceptionSpecUpdates);
11210 PendingExceptionSpecUpdates.clear();
11211 for (auto Update : ESUpdates) {
11212 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
11213 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
11214 auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
11215 if (auto *Listener = getContext().getASTMutationListener())
11216 Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
11217 for (auto *Redecl : Update.second->redecls())
11219 }
11220
11221 auto DTUpdates = std::move(PendingDeducedTypeUpdates);
11222 PendingDeducedTypeUpdates.clear();
11223 for (auto Update : DTUpdates) {
11224 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
11225 // FIXME: If the return type is already deduced, check that it
11226 // matches.
11228 Update.second);
11229 }
11230
11231 auto UDTUpdates = std::move(PendingUndeducedFunctionDecls);
11232 PendingUndeducedFunctionDecls.clear();
11233 // We hope we can find the deduced type for the functions by iterating
11234 // redeclarations in other modules.
11235 for (FunctionDecl *UndeducedFD : UDTUpdates)
11236 (void)UndeducedFD->getMostRecentDecl();
11237 }
11238
11239 ReadTimeRegion.reset();
11240
11241 diagnoseOdrViolations();
11242 }
11243
11244 // We are not in recursive loading, so it's safe to pass the "interesting"
11245 // decls to the consumer.
11246 if (Consumer)
11247 PassInterestingDeclsToConsumer();
11248 }
11249}
11250
11251void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
11252 if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) {
11253 // Remove any fake results before adding any real ones.
11254 auto It = PendingFakeLookupResults.find(II);
11255 if (It != PendingFakeLookupResults.end()) {
11256 for (auto *ND : It->second)
11257 SemaObj->IdResolver.RemoveDecl(ND);
11258 // FIXME: this works around module+PCH performance issue.
11259 // Rather than erase the result from the map, which is O(n), just clear
11260 // the vector of NamedDecls.
11261 It->second.clear();
11262 }
11263 }
11264
11265 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
11266 SemaObj->TUScope->AddDecl(D);
11267 } else if (SemaObj->TUScope) {
11268 // Adding the decl to IdResolver may have failed because it was already in
11269 // (even though it was not added in scope). If it is already in, make sure
11270 // it gets in the scope as well.
11271 if (llvm::is_contained(SemaObj->IdResolver.decls(Name), D))
11272 SemaObj->TUScope->AddDecl(D);
11273 }
11274}
11275
11277 ASTContext *Context,
11278 const PCHContainerReader &PCHContainerRdr,
11279 const CodeGenOptions &CodeGenOpts,
11280 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
11281 StringRef isysroot,
11282 DisableValidationForModuleKind DisableValidationKind,
11283 bool AllowASTWithCompilerErrors,
11284 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
11285 bool ForceValidateUserInputs,
11286 bool ValidateASTInputFilesContent, bool UseGlobalIndex,
11287 std::unique_ptr<llvm::Timer> ReadTimer)
11288 : Listener(bool(DisableValidationKind & DisableValidationForModuleKind::PCH)
11290 : cast<ASTReaderListener>(new PCHValidator(PP, *this))),
11291 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
11292 PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()),
11293 StackHandler(Diags), PP(PP), ContextObj(Context),
11294 CodeGenOpts(CodeGenOpts),
11295 ModuleMgr(PP.getFileManager(), ModCache, PCHContainerRdr,
11296 PP.getHeaderSearchInfo()),
11297 DummyIdResolver(PP), ReadTimer(std::move(ReadTimer)), isysroot(isysroot),
11298 DisableValidationKind(DisableValidationKind),
11299 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
11300 AllowConfigurationMismatch(AllowConfigurationMismatch),
11301 ValidateSystemInputs(ValidateSystemInputs),
11302 ForceValidateUserInputs(ForceValidateUserInputs),
11303 ValidateASTInputFilesContent(ValidateASTInputFilesContent),
11304 UseGlobalIndex(UseGlobalIndex), CurrSwitchCaseStmts(&SwitchCaseStmts) {
11305 SourceMgr.setExternalSLocEntrySource(this);
11306
11307 PathBuf.reserve(256);
11308
11309 for (const auto &Ext : Extensions) {
11310 auto BlockName = Ext->getExtensionMetadata().BlockName;
11311 auto Known = ModuleFileExtensions.find(BlockName);
11312 if (Known != ModuleFileExtensions.end()) {
11313 Diags.Report(diag::warn_duplicate_module_file_extension)
11314 << BlockName;
11315 continue;
11316 }
11317
11318 ModuleFileExtensions.insert({BlockName, Ext});
11319 }
11320}
11321
11323 if (OwnsDeserializationListener)
11324 delete DeserializationListener;
11325}
11326
11328 return SemaObj ? SemaObj->IdResolver : DummyIdResolver;
11329}
11330
11332 unsigned AbbrevID) {
11333 Idx = 0;
11334 Record.clear();
11335 return Cursor.readRecord(AbbrevID, Record);
11336}
11337//===----------------------------------------------------------------------===//
11338//// OMPClauseReader implementation
11339////===----------------------------------------------------------------------===//
11340
11341// This has to be in namespace clang because it's friended by all
11342// of the OMP clauses.
11343namespace clang {
11344
11345class OMPClauseReader : public OMPClauseVisitor<OMPClauseReader> {
11346 ASTRecordReader &Record;
11347 ASTContext &Context;
11348
11349public:
11351 : Record(Record), Context(Record.getContext()) {}
11352#define GEN_CLANG_CLAUSE_CLASS
11353#define CLAUSE_CLASS(Enum, Str, Class) void Visit##Class(Class *C);
11354#include "llvm/Frontend/OpenMP/OMP.inc"
11358};
11359
11360} // end namespace clang
11361
11365
11367 OMPClause *C = nullptr;
11368 switch (llvm::omp::Clause(Record.readInt())) {
11369 case llvm::omp::OMPC_if:
11370 C = new (Context) OMPIfClause();
11371 break;
11372 case llvm::omp::OMPC_final:
11373 C = new (Context) OMPFinalClause();
11374 break;
11375 case llvm::omp::OMPC_num_threads:
11376 C = new (Context) OMPNumThreadsClause();
11377 break;
11378 case llvm::omp::OMPC_safelen:
11379 C = new (Context) OMPSafelenClause();
11380 break;
11381 case llvm::omp::OMPC_simdlen:
11382 C = new (Context) OMPSimdlenClause();
11383 break;
11384 case llvm::omp::OMPC_sizes: {
11385 unsigned NumSizes = Record.readInt();
11386 C = OMPSizesClause::CreateEmpty(Context, NumSizes);
11387 break;
11388 }
11389 case llvm::omp::OMPC_permutation: {
11390 unsigned NumLoops = Record.readInt();
11391 C = OMPPermutationClause::CreateEmpty(Context, NumLoops);
11392 break;
11393 }
11394 case llvm::omp::OMPC_full:
11395 C = OMPFullClause::CreateEmpty(Context);
11396 break;
11397 case llvm::omp::OMPC_partial:
11399 break;
11400 case llvm::omp::OMPC_looprange:
11402 break;
11403 case llvm::omp::OMPC_allocator:
11404 C = new (Context) OMPAllocatorClause();
11405 break;
11406 case llvm::omp::OMPC_collapse:
11407 C = new (Context) OMPCollapseClause();
11408 break;
11409 case llvm::omp::OMPC_default:
11410 C = new (Context) OMPDefaultClause();
11411 break;
11412 case llvm::omp::OMPC_proc_bind:
11413 C = new (Context) OMPProcBindClause();
11414 break;
11415 case llvm::omp::OMPC_schedule:
11416 C = new (Context) OMPScheduleClause();
11417 break;
11418 case llvm::omp::OMPC_ordered:
11419 C = OMPOrderedClause::CreateEmpty(Context, Record.readInt());
11420 break;
11421 case llvm::omp::OMPC_nowait:
11422 C = new (Context) OMPNowaitClause();
11423 break;
11424 case llvm::omp::OMPC_untied:
11425 C = new (Context) OMPUntiedClause();
11426 break;
11427 case llvm::omp::OMPC_mergeable:
11428 C = new (Context) OMPMergeableClause();
11429 break;
11430 case llvm::omp::OMPC_threadset:
11431 C = new (Context) OMPThreadsetClause();
11432 break;
11433 case llvm::omp::OMPC_transparent:
11434 C = new (Context) OMPTransparentClause();
11435 break;
11436 case llvm::omp::OMPC_read:
11437 C = new (Context) OMPReadClause();
11438 break;
11439 case llvm::omp::OMPC_write:
11440 C = new (Context) OMPWriteClause();
11441 break;
11442 case llvm::omp::OMPC_update:
11443 C = OMPUpdateClause::CreateEmpty(Context, Record.readInt());
11444 break;
11445 case llvm::omp::OMPC_capture:
11446 C = new (Context) OMPCaptureClause();
11447 break;
11448 case llvm::omp::OMPC_compare:
11449 C = new (Context) OMPCompareClause();
11450 break;
11451 case llvm::omp::OMPC_fail:
11452 C = new (Context) OMPFailClause();
11453 break;
11454 case llvm::omp::OMPC_seq_cst:
11455 C = new (Context) OMPSeqCstClause();
11456 break;
11457 case llvm::omp::OMPC_acq_rel:
11458 C = new (Context) OMPAcqRelClause();
11459 break;
11460 case llvm::omp::OMPC_absent: {
11461 unsigned NumKinds = Record.readInt();
11462 C = OMPAbsentClause::CreateEmpty(Context, NumKinds);
11463 break;
11464 }
11465 case llvm::omp::OMPC_holds:
11466 C = new (Context) OMPHoldsClause();
11467 break;
11468 case llvm::omp::OMPC_contains: {
11469 unsigned NumKinds = Record.readInt();
11470 C = OMPContainsClause::CreateEmpty(Context, NumKinds);
11471 break;
11472 }
11473 case llvm::omp::OMPC_no_openmp:
11474 C = new (Context) OMPNoOpenMPClause();
11475 break;
11476 case llvm::omp::OMPC_no_openmp_routines:
11477 C = new (Context) OMPNoOpenMPRoutinesClause();
11478 break;
11479 case llvm::omp::OMPC_no_openmp_constructs:
11480 C = new (Context) OMPNoOpenMPConstructsClause();
11481 break;
11482 case llvm::omp::OMPC_no_parallelism:
11483 C = new (Context) OMPNoParallelismClause();
11484 break;
11485 case llvm::omp::OMPC_acquire:
11486 C = new (Context) OMPAcquireClause();
11487 break;
11488 case llvm::omp::OMPC_release:
11489 C = new (Context) OMPReleaseClause();
11490 break;
11491 case llvm::omp::OMPC_relaxed:
11492 C = new (Context) OMPRelaxedClause();
11493 break;
11494 case llvm::omp::OMPC_weak:
11495 C = new (Context) OMPWeakClause();
11496 break;
11497 case llvm::omp::OMPC_threads:
11498 C = new (Context) OMPThreadsClause();
11499 break;
11500 case llvm::omp::OMPC_simd:
11501 C = new (Context) OMPSIMDClause();
11502 break;
11503 case llvm::omp::OMPC_nogroup:
11504 C = new (Context) OMPNogroupClause();
11505 break;
11506 case llvm::omp::OMPC_unified_address:
11507 C = new (Context) OMPUnifiedAddressClause();
11508 break;
11509 case llvm::omp::OMPC_unified_shared_memory:
11510 C = new (Context) OMPUnifiedSharedMemoryClause();
11511 break;
11512 case llvm::omp::OMPC_reverse_offload:
11513 C = new (Context) OMPReverseOffloadClause();
11514 break;
11515 case llvm::omp::OMPC_dynamic_allocators:
11516 C = new (Context) OMPDynamicAllocatorsClause();
11517 break;
11518 case llvm::omp::OMPC_atomic_default_mem_order:
11519 C = new (Context) OMPAtomicDefaultMemOrderClause();
11520 break;
11521 case llvm::omp::OMPC_self_maps:
11522 C = new (Context) OMPSelfMapsClause();
11523 break;
11524 case llvm::omp::OMPC_at:
11525 C = new (Context) OMPAtClause();
11526 break;
11527 case llvm::omp::OMPC_severity:
11528 C = new (Context) OMPSeverityClause();
11529 break;
11530 case llvm::omp::OMPC_message:
11531 C = new (Context) OMPMessageClause();
11532 break;
11533 case llvm::omp::OMPC_private:
11534 C = OMPPrivateClause::CreateEmpty(Context, Record.readInt());
11535 break;
11536 case llvm::omp::OMPC_firstprivate:
11537 C = OMPFirstprivateClause::CreateEmpty(Context, Record.readInt());
11538 break;
11539 case llvm::omp::OMPC_lastprivate:
11540 C = OMPLastprivateClause::CreateEmpty(Context, Record.readInt());
11541 break;
11542 case llvm::omp::OMPC_shared:
11543 C = OMPSharedClause::CreateEmpty(Context, Record.readInt());
11544 break;
11545 case llvm::omp::OMPC_reduction: {
11546 unsigned N = Record.readInt();
11547 auto Modifier = Record.readEnum<OpenMPReductionClauseModifier>();
11548 C = OMPReductionClause::CreateEmpty(Context, N, Modifier);
11549 break;
11550 }
11551 case llvm::omp::OMPC_task_reduction:
11552 C = OMPTaskReductionClause::CreateEmpty(Context, Record.readInt());
11553 break;
11554 case llvm::omp::OMPC_in_reduction:
11555 C = OMPInReductionClause::CreateEmpty(Context, Record.readInt());
11556 break;
11557 case llvm::omp::OMPC_linear:
11558 C = OMPLinearClause::CreateEmpty(Context, Record.readInt());
11559 break;
11560 case llvm::omp::OMPC_aligned:
11561 C = OMPAlignedClause::CreateEmpty(Context, Record.readInt());
11562 break;
11563 case llvm::omp::OMPC_copyin:
11564 C = OMPCopyinClause::CreateEmpty(Context, Record.readInt());
11565 break;
11566 case llvm::omp::OMPC_copyprivate:
11567 C = OMPCopyprivateClause::CreateEmpty(Context, Record.readInt());
11568 break;
11569 case llvm::omp::OMPC_flush:
11570 C = OMPFlushClause::CreateEmpty(Context, Record.readInt());
11571 break;
11572 case llvm::omp::OMPC_depobj:
11574 break;
11575 case llvm::omp::OMPC_depend: {
11576 unsigned NumVars = Record.readInt();
11577 unsigned NumLoops = Record.readInt();
11578 C = OMPDependClause::CreateEmpty(Context, NumVars, NumLoops);
11579 break;
11580 }
11581 case llvm::omp::OMPC_device:
11582 C = new (Context) OMPDeviceClause();
11583 break;
11584 case llvm::omp::OMPC_map: {
11586 Sizes.NumVars = Record.readInt();
11587 Sizes.NumUniqueDeclarations = Record.readInt();
11588 Sizes.NumComponentLists = Record.readInt();
11589 Sizes.NumComponents = Record.readInt();
11590 C = OMPMapClause::CreateEmpty(Context, Sizes);
11591 break;
11592 }
11593 case llvm::omp::OMPC_num_teams:
11594 C = OMPNumTeamsClause::CreateEmpty(Context, Record.readInt());
11595 break;
11596 case llvm::omp::OMPC_thread_limit:
11597 C = OMPThreadLimitClause::CreateEmpty(Context, Record.readInt());
11598 break;
11599 case llvm::omp::OMPC_priority:
11600 C = new (Context) OMPPriorityClause();
11601 break;
11602 case llvm::omp::OMPC_grainsize:
11603 C = new (Context) OMPGrainsizeClause();
11604 break;
11605 case llvm::omp::OMPC_num_tasks:
11606 C = new (Context) OMPNumTasksClause();
11607 break;
11608 case llvm::omp::OMPC_hint:
11609 C = new (Context) OMPHintClause();
11610 break;
11611 case llvm::omp::OMPC_dist_schedule:
11612 C = new (Context) OMPDistScheduleClause();
11613 break;
11614 case llvm::omp::OMPC_defaultmap:
11615 C = new (Context) OMPDefaultmapClause();
11616 break;
11617 case llvm::omp::OMPC_to: {
11619 Sizes.NumVars = Record.readInt();
11620 Sizes.NumUniqueDeclarations = Record.readInt();
11621 Sizes.NumComponentLists = Record.readInt();
11622 Sizes.NumComponents = Record.readInt();
11623 C = OMPToClause::CreateEmpty(Context, Sizes);
11624 break;
11625 }
11626 case llvm::omp::OMPC_from: {
11628 Sizes.NumVars = Record.readInt();
11629 Sizes.NumUniqueDeclarations = Record.readInt();
11630 Sizes.NumComponentLists = Record.readInt();
11631 Sizes.NumComponents = Record.readInt();
11632 C = OMPFromClause::CreateEmpty(Context, Sizes);
11633 break;
11634 }
11635 case llvm::omp::OMPC_use_device_ptr: {
11637 Sizes.NumVars = Record.readInt();
11638 Sizes.NumUniqueDeclarations = Record.readInt();
11639 Sizes.NumComponentLists = Record.readInt();
11640 Sizes.NumComponents = Record.readInt();
11641 C = OMPUseDevicePtrClause::CreateEmpty(Context, Sizes);
11642 break;
11643 }
11644 case llvm::omp::OMPC_use_device_addr: {
11646 Sizes.NumVars = Record.readInt();
11647 Sizes.NumUniqueDeclarations = Record.readInt();
11648 Sizes.NumComponentLists = Record.readInt();
11649 Sizes.NumComponents = Record.readInt();
11650 C = OMPUseDeviceAddrClause::CreateEmpty(Context, Sizes);
11651 break;
11652 }
11653 case llvm::omp::OMPC_is_device_ptr: {
11655 Sizes.NumVars = Record.readInt();
11656 Sizes.NumUniqueDeclarations = Record.readInt();
11657 Sizes.NumComponentLists = Record.readInt();
11658 Sizes.NumComponents = Record.readInt();
11659 C = OMPIsDevicePtrClause::CreateEmpty(Context, Sizes);
11660 break;
11661 }
11662 case llvm::omp::OMPC_has_device_addr: {
11664 Sizes.NumVars = Record.readInt();
11665 Sizes.NumUniqueDeclarations = Record.readInt();
11666 Sizes.NumComponentLists = Record.readInt();
11667 Sizes.NumComponents = Record.readInt();
11668 C = OMPHasDeviceAddrClause::CreateEmpty(Context, Sizes);
11669 break;
11670 }
11671 case llvm::omp::OMPC_allocate:
11672 C = OMPAllocateClause::CreateEmpty(Context, Record.readInt());
11673 break;
11674 case llvm::omp::OMPC_nontemporal:
11675 C = OMPNontemporalClause::CreateEmpty(Context, Record.readInt());
11676 break;
11677 case llvm::omp::OMPC_inclusive:
11678 C = OMPInclusiveClause::CreateEmpty(Context, Record.readInt());
11679 break;
11680 case llvm::omp::OMPC_exclusive:
11681 C = OMPExclusiveClause::CreateEmpty(Context, Record.readInt());
11682 break;
11683 case llvm::omp::OMPC_order:
11684 C = new (Context) OMPOrderClause();
11685 break;
11686 case llvm::omp::OMPC_init:
11687 C = OMPInitClause::CreateEmpty(Context, Record.readInt());
11688 break;
11689 case llvm::omp::OMPC_use:
11690 C = new (Context) OMPUseClause();
11691 break;
11692 case llvm::omp::OMPC_destroy:
11693 C = new (Context) OMPDestroyClause();
11694 break;
11695 case llvm::omp::OMPC_novariants:
11696 C = new (Context) OMPNovariantsClause();
11697 break;
11698 case llvm::omp::OMPC_nocontext:
11699 C = new (Context) OMPNocontextClause();
11700 break;
11701 case llvm::omp::OMPC_detach:
11702 C = new (Context) OMPDetachClause();
11703 break;
11704 case llvm::omp::OMPC_uses_allocators:
11705 C = OMPUsesAllocatorsClause::CreateEmpty(Context, Record.readInt());
11706 break;
11707 case llvm::omp::OMPC_affinity:
11708 C = OMPAffinityClause::CreateEmpty(Context, Record.readInt());
11709 break;
11710 case llvm::omp::OMPC_filter:
11711 C = new (Context) OMPFilterClause();
11712 break;
11713 case llvm::omp::OMPC_bind:
11714 C = OMPBindClause::CreateEmpty(Context);
11715 break;
11716 case llvm::omp::OMPC_align:
11717 C = new (Context) OMPAlignClause();
11718 break;
11719 case llvm::omp::OMPC_ompx_dyn_cgroup_mem:
11720 C = new (Context) OMPXDynCGroupMemClause();
11721 break;
11722 case llvm::omp::OMPC_dyn_groupprivate:
11723 C = new (Context) OMPDynGroupprivateClause();
11724 break;
11725 case llvm::omp::OMPC_doacross: {
11726 unsigned NumVars = Record.readInt();
11727 unsigned NumLoops = Record.readInt();
11728 C = OMPDoacrossClause::CreateEmpty(Context, NumVars, NumLoops);
11729 break;
11730 }
11731 case llvm::omp::OMPC_ompx_attribute:
11732 C = new (Context) OMPXAttributeClause();
11733 break;
11734 case llvm::omp::OMPC_ompx_bare:
11735 C = new (Context) OMPXBareClause();
11736 break;
11737#define OMP_CLAUSE_NO_CLASS(Enum, Str) \
11738 case llvm::omp::Enum: \
11739 break;
11740#include "llvm/Frontend/OpenMP/OMPKinds.def"
11741 default:
11742 break;
11743 }
11744 assert(C && "Unknown OMPClause type");
11745
11746 Visit(C);
11747 C->setLocStart(Record.readSourceLocation());
11748 C->setLocEnd(Record.readSourceLocation());
11749
11750 return C;
11751}
11752
11754 C->setPreInitStmt(Record.readSubStmt(),
11755 static_cast<OpenMPDirectiveKind>(Record.readInt()));
11756}
11757
11760 C->setPostUpdateExpr(Record.readSubExpr());
11761}
11762
11763void OMPClauseReader::VisitOMPIfClause(OMPIfClause *C) {
11765 C->setNameModifier(static_cast<OpenMPDirectiveKind>(Record.readInt()));
11766 C->setNameModifierLoc(Record.readSourceLocation());
11767 C->setColonLoc(Record.readSourceLocation());
11768 C->setCondition(Record.readSubExpr());
11769 C->setLParenLoc(Record.readSourceLocation());
11770}
11771
11772void OMPClauseReader::VisitOMPFinalClause(OMPFinalClause *C) {
11774 C->setCondition(Record.readSubExpr());
11775 C->setLParenLoc(Record.readSourceLocation());
11776}
11777
11778void OMPClauseReader::VisitOMPNumThreadsClause(OMPNumThreadsClause *C) {
11780 C->setModifier(Record.readEnum<OpenMPNumThreadsClauseModifier>());
11781 C->setNumThreads(Record.readSubExpr());
11782 C->setModifierLoc(Record.readSourceLocation());
11783 C->setLParenLoc(Record.readSourceLocation());
11784}
11785
11786void OMPClauseReader::VisitOMPSafelenClause(OMPSafelenClause *C) {
11787 C->setSafelen(Record.readSubExpr());
11788 C->setLParenLoc(Record.readSourceLocation());
11789}
11790
11791void OMPClauseReader::VisitOMPSimdlenClause(OMPSimdlenClause *C) {
11792 C->setSimdlen(Record.readSubExpr());
11793 C->setLParenLoc(Record.readSourceLocation());
11794}
11795
11796void OMPClauseReader::VisitOMPSizesClause(OMPSizesClause *C) {
11797 for (Expr *&E : C->getSizesRefs())
11798 E = Record.readSubExpr();
11799 C->setLParenLoc(Record.readSourceLocation());
11800}
11801
11802void OMPClauseReader::VisitOMPPermutationClause(OMPPermutationClause *C) {
11803 for (Expr *&E : C->getArgsRefs())
11804 E = Record.readSubExpr();
11805 C->setLParenLoc(Record.readSourceLocation());
11806}
11807
11808void OMPClauseReader::VisitOMPFullClause(OMPFullClause *C) {}
11809
11810void OMPClauseReader::VisitOMPPartialClause(OMPPartialClause *C) {
11811 C->setFactor(Record.readSubExpr());
11812 C->setLParenLoc(Record.readSourceLocation());
11813}
11814
11815void OMPClauseReader::VisitOMPLoopRangeClause(OMPLoopRangeClause *C) {
11816 C->setFirst(Record.readSubExpr());
11817 C->setCount(Record.readSubExpr());
11818 C->setLParenLoc(Record.readSourceLocation());
11819 C->setFirstLoc(Record.readSourceLocation());
11820 C->setCountLoc(Record.readSourceLocation());
11821}
11822
11823void OMPClauseReader::VisitOMPAllocatorClause(OMPAllocatorClause *C) {
11824 C->setAllocator(Record.readExpr());
11825 C->setLParenLoc(Record.readSourceLocation());
11826}
11827
11828void OMPClauseReader::VisitOMPCollapseClause(OMPCollapseClause *C) {
11829 C->setNumForLoops(Record.readSubExpr());
11830 C->setLParenLoc(Record.readSourceLocation());
11831}
11832
11833void OMPClauseReader::VisitOMPDefaultClause(OMPDefaultClause *C) {
11834 C->setDefaultKind(static_cast<llvm::omp::DefaultKind>(Record.readInt()));
11835 C->setLParenLoc(Record.readSourceLocation());
11836 C->setDefaultKindKwLoc(Record.readSourceLocation());
11837 C->setDefaultVariableCategory(
11838 Record.readEnum<OpenMPDefaultClauseVariableCategory>());
11839 C->setDefaultVariableCategoryLocation(Record.readSourceLocation());
11840}
11841
11842// Read the parameter of threadset clause. This will have been saved when
11843// OMPClauseWriter is called.
11844void OMPClauseReader::VisitOMPThreadsetClause(OMPThreadsetClause *C) {
11845 C->setLParenLoc(Record.readSourceLocation());
11846 SourceLocation ThreadsetKindLoc = Record.readSourceLocation();
11847 C->setThreadsetKindLoc(ThreadsetKindLoc);
11848 OpenMPThreadsetKind TKind =
11849 static_cast<OpenMPThreadsetKind>(Record.readInt());
11850 C->setThreadsetKind(TKind);
11851}
11852
11853void OMPClauseReader::VisitOMPTransparentClause(OMPTransparentClause *C) {
11854 C->setLParenLoc(Record.readSourceLocation());
11855 C->setImpexTypeKind(Record.readSubExpr());
11856}
11857
11858void OMPClauseReader::VisitOMPProcBindClause(OMPProcBindClause *C) {
11859 C->setProcBindKind(static_cast<llvm::omp::ProcBindKind>(Record.readInt()));
11860 C->setLParenLoc(Record.readSourceLocation());
11861 C->setProcBindKindKwLoc(Record.readSourceLocation());
11862}
11863
11864void OMPClauseReader::VisitOMPScheduleClause(OMPScheduleClause *C) {
11866 C->setScheduleKind(
11867 static_cast<OpenMPScheduleClauseKind>(Record.readInt()));
11868 C->setFirstScheduleModifier(
11869 static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
11870 C->setSecondScheduleModifier(
11871 static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
11872 C->setChunkSize(Record.readSubExpr());
11873 C->setLParenLoc(Record.readSourceLocation());
11874 C->setFirstScheduleModifierLoc(Record.readSourceLocation());
11875 C->setSecondScheduleModifierLoc(Record.readSourceLocation());
11876 C->setScheduleKindLoc(Record.readSourceLocation());
11877 C->setCommaLoc(Record.readSourceLocation());
11878}
11879
11880void OMPClauseReader::VisitOMPOrderedClause(OMPOrderedClause *C) {
11881 C->setNumForLoops(Record.readSubExpr());
11882 for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
11883 C->setLoopNumIterations(I, Record.readSubExpr());
11884 for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
11885 C->setLoopCounter(I, Record.readSubExpr());
11886 C->setLParenLoc(Record.readSourceLocation());
11887}
11888
11889void OMPClauseReader::VisitOMPDetachClause(OMPDetachClause *C) {
11890 C->setEventHandler(Record.readSubExpr());
11891 C->setLParenLoc(Record.readSourceLocation());
11892}
11893
11894void OMPClauseReader::VisitOMPNowaitClause(OMPNowaitClause *C) {
11895 C->setCondition(Record.readSubExpr());
11896 C->setLParenLoc(Record.readSourceLocation());
11897}
11898
11899void OMPClauseReader::VisitOMPUntiedClause(OMPUntiedClause *) {}
11900
11901void OMPClauseReader::VisitOMPMergeableClause(OMPMergeableClause *) {}
11902
11903void OMPClauseReader::VisitOMPReadClause(OMPReadClause *) {}
11904
11905void OMPClauseReader::VisitOMPWriteClause(OMPWriteClause *) {}
11906
11907void OMPClauseReader::VisitOMPUpdateClause(OMPUpdateClause *C) {
11908 if (C->isExtended()) {
11909 C->setLParenLoc(Record.readSourceLocation());
11910 C->setArgumentLoc(Record.readSourceLocation());
11911 C->setDependencyKind(Record.readEnum<OpenMPDependClauseKind>());
11912 }
11913}
11914
11915void OMPClauseReader::VisitOMPCaptureClause(OMPCaptureClause *) {}
11916
11917void OMPClauseReader::VisitOMPCompareClause(OMPCompareClause *) {}
11918
11919// Read the parameter of fail clause. This will have been saved when
11920// OMPClauseWriter is called.
11921void OMPClauseReader::VisitOMPFailClause(OMPFailClause *C) {
11922 C->setLParenLoc(Record.readSourceLocation());
11923 SourceLocation FailParameterLoc = Record.readSourceLocation();
11924 C->setFailParameterLoc(FailParameterLoc);
11925 OpenMPClauseKind CKind = Record.readEnum<OpenMPClauseKind>();
11926 C->setFailParameter(CKind);
11927}
11928
11929void OMPClauseReader::VisitOMPAbsentClause(OMPAbsentClause *C) {
11930 unsigned Count = C->getDirectiveKinds().size();
11931 C->setLParenLoc(Record.readSourceLocation());
11932 llvm::SmallVector<OpenMPDirectiveKind, 4> DKVec;
11933 DKVec.reserve(Count);
11934 for (unsigned I = 0; I < Count; I++) {
11935 DKVec.push_back(Record.readEnum<OpenMPDirectiveKind>());
11936 }
11937 C->setDirectiveKinds(DKVec);
11938}
11939
11940void OMPClauseReader::VisitOMPHoldsClause(OMPHoldsClause *C) {
11941 C->setExpr(Record.readExpr());
11942 C->setLParenLoc(Record.readSourceLocation());
11943}
11944
11945void OMPClauseReader::VisitOMPContainsClause(OMPContainsClause *C) {
11946 unsigned Count = C->getDirectiveKinds().size();
11947 C->setLParenLoc(Record.readSourceLocation());
11948 llvm::SmallVector<OpenMPDirectiveKind, 4> DKVec;
11949 DKVec.reserve(Count);
11950 for (unsigned I = 0; I < Count; I++) {
11951 DKVec.push_back(Record.readEnum<OpenMPDirectiveKind>());
11952 }
11953 C->setDirectiveKinds(DKVec);
11954}
11955
11956void OMPClauseReader::VisitOMPNoOpenMPClause(OMPNoOpenMPClause *) {}
11957
11958void OMPClauseReader::VisitOMPNoOpenMPRoutinesClause(
11959 OMPNoOpenMPRoutinesClause *) {}
11960
11961void OMPClauseReader::VisitOMPNoOpenMPConstructsClause(
11962 OMPNoOpenMPConstructsClause *) {}
11963
11964void OMPClauseReader::VisitOMPNoParallelismClause(OMPNoParallelismClause *) {}
11965
11966void OMPClauseReader::VisitOMPSeqCstClause(OMPSeqCstClause *) {}
11967
11968void OMPClauseReader::VisitOMPAcqRelClause(OMPAcqRelClause *) {}
11969
11970void OMPClauseReader::VisitOMPAcquireClause(OMPAcquireClause *) {}
11971
11972void OMPClauseReader::VisitOMPReleaseClause(OMPReleaseClause *) {}
11973
11974void OMPClauseReader::VisitOMPRelaxedClause(OMPRelaxedClause *) {}
11975
11976void OMPClauseReader::VisitOMPWeakClause(OMPWeakClause *) {}
11977
11978void OMPClauseReader::VisitOMPThreadsClause(OMPThreadsClause *) {}
11979
11980void OMPClauseReader::VisitOMPSIMDClause(OMPSIMDClause *) {}
11981
11982void OMPClauseReader::VisitOMPNogroupClause(OMPNogroupClause *) {}
11983
11984void OMPClauseReader::VisitOMPInitClause(OMPInitClause *C) {
11985 unsigned NumVars = C->varlist_size();
11986 SmallVector<Expr *, 16> Vars;
11987 Vars.reserve(NumVars);
11988 for (unsigned I = 0; I != NumVars; ++I)
11989 Vars.push_back(Record.readSubExpr());
11990 C->setVarRefs(Vars);
11991 C->setIsTarget(Record.readBool());
11992 C->setIsTargetSync(Record.readBool());
11993 C->setLParenLoc(Record.readSourceLocation());
11994 C->setVarLoc(Record.readSourceLocation());
11995}
11996
11997void OMPClauseReader::VisitOMPUseClause(OMPUseClause *C) {
11998 C->setInteropVar(Record.readSubExpr());
11999 C->setLParenLoc(Record.readSourceLocation());
12000 C->setVarLoc(Record.readSourceLocation());
12001}
12002
12003void OMPClauseReader::VisitOMPDestroyClause(OMPDestroyClause *C) {
12004 C->setInteropVar(Record.readSubExpr());
12005 C->setLParenLoc(Record.readSourceLocation());
12006 C->setVarLoc(Record.readSourceLocation());
12007}
12008
12009void OMPClauseReader::VisitOMPNovariantsClause(OMPNovariantsClause *C) {
12011 C->setCondition(Record.readSubExpr());
12012 C->setLParenLoc(Record.readSourceLocation());
12013}
12014
12015void OMPClauseReader::VisitOMPNocontextClause(OMPNocontextClause *C) {
12017 C->setCondition(Record.readSubExpr());
12018 C->setLParenLoc(Record.readSourceLocation());
12019}
12020
12021void OMPClauseReader::VisitOMPUnifiedAddressClause(OMPUnifiedAddressClause *) {}
12022
12023void OMPClauseReader::VisitOMPUnifiedSharedMemoryClause(
12024 OMPUnifiedSharedMemoryClause *) {}
12025
12026void OMPClauseReader::VisitOMPReverseOffloadClause(OMPReverseOffloadClause *) {}
12027
12028void
12029OMPClauseReader::VisitOMPDynamicAllocatorsClause(OMPDynamicAllocatorsClause *) {
12030}
12031
12032void OMPClauseReader::VisitOMPAtomicDefaultMemOrderClause(
12033 OMPAtomicDefaultMemOrderClause *C) {
12034 C->setAtomicDefaultMemOrderKind(
12035 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Record.readInt()));
12036 C->setLParenLoc(Record.readSourceLocation());
12037 C->setAtomicDefaultMemOrderKindKwLoc(Record.readSourceLocation());
12038}
12039
12040void OMPClauseReader::VisitOMPSelfMapsClause(OMPSelfMapsClause *) {}
12041
12042void OMPClauseReader::VisitOMPAtClause(OMPAtClause *C) {
12043 C->setAtKind(static_cast<OpenMPAtClauseKind>(Record.readInt()));
12044 C->setLParenLoc(Record.readSourceLocation());
12045 C->setAtKindKwLoc(Record.readSourceLocation());
12046}
12047
12048void OMPClauseReader::VisitOMPSeverityClause(OMPSeverityClause *C) {
12049 C->setSeverityKind(static_cast<OpenMPSeverityClauseKind>(Record.readInt()));
12050 C->setLParenLoc(Record.readSourceLocation());
12051 C->setSeverityKindKwLoc(Record.readSourceLocation());
12052}
12053
12054void OMPClauseReader::VisitOMPMessageClause(OMPMessageClause *C) {
12056 C->setMessageString(Record.readSubExpr());
12057 C->setLParenLoc(Record.readSourceLocation());
12058}
12059
12060void OMPClauseReader::VisitOMPPrivateClause(OMPPrivateClause *C) {
12061 C->setLParenLoc(Record.readSourceLocation());
12062 unsigned NumVars = C->varlist_size();
12063 SmallVector<Expr *, 16> Vars;
12064 Vars.reserve(NumVars);
12065 for (unsigned i = 0; i != NumVars; ++i)
12066 Vars.push_back(Record.readSubExpr());
12067 C->setVarRefs(Vars);
12068 Vars.clear();
12069 for (unsigned i = 0; i != NumVars; ++i)
12070 Vars.push_back(Record.readSubExpr());
12071 C->setPrivateCopies(Vars);
12072}
12073
12074void OMPClauseReader::VisitOMPFirstprivateClause(OMPFirstprivateClause *C) {
12076 C->setLParenLoc(Record.readSourceLocation());
12077 unsigned NumVars = C->varlist_size();
12078 SmallVector<Expr *, 16> Vars;
12079 Vars.reserve(NumVars);
12080 for (unsigned i = 0; i != NumVars; ++i)
12081 Vars.push_back(Record.readSubExpr());
12082 C->setVarRefs(Vars);
12083 Vars.clear();
12084 for (unsigned i = 0; i != NumVars; ++i)
12085 Vars.push_back(Record.readSubExpr());
12086 C->setPrivateCopies(Vars);
12087 Vars.clear();
12088 for (unsigned i = 0; i != NumVars; ++i)
12089 Vars.push_back(Record.readSubExpr());
12090 C->setInits(Vars);
12091}
12092
12093void OMPClauseReader::VisitOMPLastprivateClause(OMPLastprivateClause *C) {
12095 C->setLParenLoc(Record.readSourceLocation());
12096 C->setKind(Record.readEnum<OpenMPLastprivateModifier>());
12097 C->setKindLoc(Record.readSourceLocation());
12098 C->setColonLoc(Record.readSourceLocation());
12099 unsigned NumVars = C->varlist_size();
12100 SmallVector<Expr *, 16> Vars;
12101 Vars.reserve(NumVars);
12102 for (unsigned i = 0; i != NumVars; ++i)
12103 Vars.push_back(Record.readSubExpr());
12104 C->setVarRefs(Vars);
12105 Vars.clear();
12106 for (unsigned i = 0; i != NumVars; ++i)
12107 Vars.push_back(Record.readSubExpr());
12108 C->setPrivateCopies(Vars);
12109 Vars.clear();
12110 for (unsigned i = 0; i != NumVars; ++i)
12111 Vars.push_back(Record.readSubExpr());
12112 C->setSourceExprs(Vars);
12113 Vars.clear();
12114 for (unsigned i = 0; i != NumVars; ++i)
12115 Vars.push_back(Record.readSubExpr());
12116 C->setDestinationExprs(Vars);
12117 Vars.clear();
12118 for (unsigned i = 0; i != NumVars; ++i)
12119 Vars.push_back(Record.readSubExpr());
12120 C->setAssignmentOps(Vars);
12121}
12122
12123void OMPClauseReader::VisitOMPSharedClause(OMPSharedClause *C) {
12124 C->setLParenLoc(Record.readSourceLocation());
12125 unsigned NumVars = C->varlist_size();
12126 SmallVector<Expr *, 16> Vars;
12127 Vars.reserve(NumVars);
12128 for (unsigned i = 0; i != NumVars; ++i)
12129 Vars.push_back(Record.readSubExpr());
12130 C->setVarRefs(Vars);
12131}
12132
12133void OMPClauseReader::VisitOMPReductionClause(OMPReductionClause *C) {
12135 C->setLParenLoc(Record.readSourceLocation());
12136 C->setModifierLoc(Record.readSourceLocation());
12137 C->setColonLoc(Record.readSourceLocation());
12138 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
12139 DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
12140 C->setQualifierLoc(NNSL);
12141 C->setNameInfo(DNI);
12142
12143 unsigned NumVars = C->varlist_size();
12144 SmallVector<Expr *, 16> Vars;
12145 Vars.reserve(NumVars);
12146 for (unsigned i = 0; i != NumVars; ++i)
12147 Vars.push_back(Record.readSubExpr());
12148 C->setVarRefs(Vars);
12149 Vars.clear();
12150 for (unsigned i = 0; i != NumVars; ++i)
12151 Vars.push_back(Record.readSubExpr());
12152 C->setPrivates(Vars);
12153 Vars.clear();
12154 for (unsigned i = 0; i != NumVars; ++i)
12155 Vars.push_back(Record.readSubExpr());
12156 C->setLHSExprs(Vars);
12157 Vars.clear();
12158 for (unsigned i = 0; i != NumVars; ++i)
12159 Vars.push_back(Record.readSubExpr());
12160 C->setRHSExprs(Vars);
12161 Vars.clear();
12162 for (unsigned i = 0; i != NumVars; ++i)
12163 Vars.push_back(Record.readSubExpr());
12164 C->setReductionOps(Vars);
12165 if (C->getModifier() == OMPC_REDUCTION_inscan) {
12166 Vars.clear();
12167 for (unsigned i = 0; i != NumVars; ++i)
12168 Vars.push_back(Record.readSubExpr());
12169 C->setInscanCopyOps(Vars);
12170 Vars.clear();
12171 for (unsigned i = 0; i != NumVars; ++i)
12172 Vars.push_back(Record.readSubExpr());
12173 C->setInscanCopyArrayTemps(Vars);
12174 Vars.clear();
12175 for (unsigned i = 0; i != NumVars; ++i)
12176 Vars.push_back(Record.readSubExpr());
12177 C->setInscanCopyArrayElems(Vars);
12178 }
12179 unsigned NumFlags = Record.readInt();
12180 SmallVector<bool, 16> Flags;
12181 Flags.reserve(NumFlags);
12182 for ([[maybe_unused]] unsigned I : llvm::seq<unsigned>(NumFlags))
12183 Flags.push_back(Record.readInt());
12184 C->setPrivateVariableReductionFlags(Flags);
12185}
12186
12187void OMPClauseReader::VisitOMPTaskReductionClause(OMPTaskReductionClause *C) {
12189 C->setLParenLoc(Record.readSourceLocation());
12190 C->setColonLoc(Record.readSourceLocation());
12191 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
12192 DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
12193 C->setQualifierLoc(NNSL);
12194 C->setNameInfo(DNI);
12195
12196 unsigned NumVars = C->varlist_size();
12197 SmallVector<Expr *, 16> Vars;
12198 Vars.reserve(NumVars);
12199 for (unsigned I = 0; I != NumVars; ++I)
12200 Vars.push_back(Record.readSubExpr());
12201 C->setVarRefs(Vars);
12202 Vars.clear();
12203 for (unsigned I = 0; I != NumVars; ++I)
12204 Vars.push_back(Record.readSubExpr());
12205 C->setPrivates(Vars);
12206 Vars.clear();
12207 for (unsigned I = 0; I != NumVars; ++I)
12208 Vars.push_back(Record.readSubExpr());
12209 C->setLHSExprs(Vars);
12210 Vars.clear();
12211 for (unsigned I = 0; I != NumVars; ++I)
12212 Vars.push_back(Record.readSubExpr());
12213 C->setRHSExprs(Vars);
12214 Vars.clear();
12215 for (unsigned I = 0; I != NumVars; ++I)
12216 Vars.push_back(Record.readSubExpr());
12217 C->setReductionOps(Vars);
12218}
12219
12220void OMPClauseReader::VisitOMPInReductionClause(OMPInReductionClause *C) {
12222 C->setLParenLoc(Record.readSourceLocation());
12223 C->setColonLoc(Record.readSourceLocation());
12224 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
12225 DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
12226 C->setQualifierLoc(NNSL);
12227 C->setNameInfo(DNI);
12228
12229 unsigned NumVars = C->varlist_size();
12230 SmallVector<Expr *, 16> Vars;
12231 Vars.reserve(NumVars);
12232 for (unsigned I = 0; I != NumVars; ++I)
12233 Vars.push_back(Record.readSubExpr());
12234 C->setVarRefs(Vars);
12235 Vars.clear();
12236 for (unsigned I = 0; I != NumVars; ++I)
12237 Vars.push_back(Record.readSubExpr());
12238 C->setPrivates(Vars);
12239 Vars.clear();
12240 for (unsigned I = 0; I != NumVars; ++I)
12241 Vars.push_back(Record.readSubExpr());
12242 C->setLHSExprs(Vars);
12243 Vars.clear();
12244 for (unsigned I = 0; I != NumVars; ++I)
12245 Vars.push_back(Record.readSubExpr());
12246 C->setRHSExprs(Vars);
12247 Vars.clear();
12248 for (unsigned I = 0; I != NumVars; ++I)
12249 Vars.push_back(Record.readSubExpr());
12250 C->setReductionOps(Vars);
12251 Vars.clear();
12252 for (unsigned I = 0; I != NumVars; ++I)
12253 Vars.push_back(Record.readSubExpr());
12254 C->setTaskgroupDescriptors(Vars);
12255}
12256
12257void OMPClauseReader::VisitOMPLinearClause(OMPLinearClause *C) {
12259 C->setLParenLoc(Record.readSourceLocation());
12260 C->setColonLoc(Record.readSourceLocation());
12261 C->setModifier(static_cast<OpenMPLinearClauseKind>(Record.readInt()));
12262 C->setModifierLoc(Record.readSourceLocation());
12263 unsigned NumVars = C->varlist_size();
12264 SmallVector<Expr *, 16> Vars;
12265 Vars.reserve(NumVars);
12266 for (unsigned i = 0; i != NumVars; ++i)
12267 Vars.push_back(Record.readSubExpr());
12268 C->setVarRefs(Vars);
12269 Vars.clear();
12270 for (unsigned i = 0; i != NumVars; ++i)
12271 Vars.push_back(Record.readSubExpr());
12272 C->setPrivates(Vars);
12273 Vars.clear();
12274 for (unsigned i = 0; i != NumVars; ++i)
12275 Vars.push_back(Record.readSubExpr());
12276 C->setInits(Vars);
12277 Vars.clear();
12278 for (unsigned i = 0; i != NumVars; ++i)
12279 Vars.push_back(Record.readSubExpr());
12280 C->setUpdates(Vars);
12281 Vars.clear();
12282 for (unsigned i = 0; i != NumVars; ++i)
12283 Vars.push_back(Record.readSubExpr());
12284 C->setFinals(Vars);
12285 C->setStep(Record.readSubExpr());
12286 C->setCalcStep(Record.readSubExpr());
12287 Vars.clear();
12288 for (unsigned I = 0; I != NumVars + 1; ++I)
12289 Vars.push_back(Record.readSubExpr());
12290 C->setUsedExprs(Vars);
12291}
12292
12293void OMPClauseReader::VisitOMPAlignedClause(OMPAlignedClause *C) {
12294 C->setLParenLoc(Record.readSourceLocation());
12295 C->setColonLoc(Record.readSourceLocation());
12296 unsigned NumVars = C->varlist_size();
12297 SmallVector<Expr *, 16> Vars;
12298 Vars.reserve(NumVars);
12299 for (unsigned i = 0; i != NumVars; ++i)
12300 Vars.push_back(Record.readSubExpr());
12301 C->setVarRefs(Vars);
12302 C->setAlignment(Record.readSubExpr());
12303}
12304
12305void OMPClauseReader::VisitOMPCopyinClause(OMPCopyinClause *C) {
12306 C->setLParenLoc(Record.readSourceLocation());
12307 unsigned NumVars = C->varlist_size();
12308 SmallVector<Expr *, 16> Exprs;
12309 Exprs.reserve(NumVars);
12310 for (unsigned i = 0; i != NumVars; ++i)
12311 Exprs.push_back(Record.readSubExpr());
12312 C->setVarRefs(Exprs);
12313 Exprs.clear();
12314 for (unsigned i = 0; i != NumVars; ++i)
12315 Exprs.push_back(Record.readSubExpr());
12316 C->setSourceExprs(Exprs);
12317 Exprs.clear();
12318 for (unsigned i = 0; i != NumVars; ++i)
12319 Exprs.push_back(Record.readSubExpr());
12320 C->setDestinationExprs(Exprs);
12321 Exprs.clear();
12322 for (unsigned i = 0; i != NumVars; ++i)
12323 Exprs.push_back(Record.readSubExpr());
12324 C->setAssignmentOps(Exprs);
12325}
12326
12327void OMPClauseReader::VisitOMPCopyprivateClause(OMPCopyprivateClause *C) {
12328 C->setLParenLoc(Record.readSourceLocation());
12329 unsigned NumVars = C->varlist_size();
12330 SmallVector<Expr *, 16> Exprs;
12331 Exprs.reserve(NumVars);
12332 for (unsigned i = 0; i != NumVars; ++i)
12333 Exprs.push_back(Record.readSubExpr());
12334 C->setVarRefs(Exprs);
12335 Exprs.clear();
12336 for (unsigned i = 0; i != NumVars; ++i)
12337 Exprs.push_back(Record.readSubExpr());
12338 C->setSourceExprs(Exprs);
12339 Exprs.clear();
12340 for (unsigned i = 0; i != NumVars; ++i)
12341 Exprs.push_back(Record.readSubExpr());
12342 C->setDestinationExprs(Exprs);
12343 Exprs.clear();
12344 for (unsigned i = 0; i != NumVars; ++i)
12345 Exprs.push_back(Record.readSubExpr());
12346 C->setAssignmentOps(Exprs);
12347}
12348
12349void OMPClauseReader::VisitOMPFlushClause(OMPFlushClause *C) {
12350 C->setLParenLoc(Record.readSourceLocation());
12351 unsigned NumVars = C->varlist_size();
12352 SmallVector<Expr *, 16> Vars;
12353 Vars.reserve(NumVars);
12354 for (unsigned i = 0; i != NumVars; ++i)
12355 Vars.push_back(Record.readSubExpr());
12356 C->setVarRefs(Vars);
12357}
12358
12359void OMPClauseReader::VisitOMPDepobjClause(OMPDepobjClause *C) {
12360 C->setDepobj(Record.readSubExpr());
12361 C->setLParenLoc(Record.readSourceLocation());
12362}
12363
12364void OMPClauseReader::VisitOMPDependClause(OMPDependClause *C) {
12365 C->setLParenLoc(Record.readSourceLocation());
12366 C->setModifier(Record.readSubExpr());
12367 C->setDependencyKind(
12368 static_cast<OpenMPDependClauseKind>(Record.readInt()));
12369 C->setDependencyLoc(Record.readSourceLocation());
12370 C->setColonLoc(Record.readSourceLocation());
12371 C->setOmpAllMemoryLoc(Record.readSourceLocation());
12372 unsigned NumVars = C->varlist_size();
12373 SmallVector<Expr *, 16> Vars;
12374 Vars.reserve(NumVars);
12375 for (unsigned I = 0; I != NumVars; ++I)
12376 Vars.push_back(Record.readSubExpr());
12377 C->setVarRefs(Vars);
12378 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
12379 C->setLoopData(I, Record.readSubExpr());
12380}
12381
12382void OMPClauseReader::VisitOMPDeviceClause(OMPDeviceClause *C) {
12384 C->setModifier(Record.readEnum<OpenMPDeviceClauseModifier>());
12385 C->setDevice(Record.readSubExpr());
12386 C->setModifierLoc(Record.readSourceLocation());
12387 C->setLParenLoc(Record.readSourceLocation());
12388}
12389
12390void OMPClauseReader::VisitOMPMapClause(OMPMapClause *C) {
12391 C->setLParenLoc(Record.readSourceLocation());
12392 bool HasIteratorModifier = false;
12393 for (unsigned I = 0; I < NumberOfOMPMapClauseModifiers; ++I) {
12394 C->setMapTypeModifier(
12395 I, static_cast<OpenMPMapModifierKind>(Record.readInt()));
12396 C->setMapTypeModifierLoc(I, Record.readSourceLocation());
12397 if (C->getMapTypeModifier(I) == OMPC_MAP_MODIFIER_iterator)
12398 HasIteratorModifier = true;
12399 }
12400 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
12401 C->setMapperIdInfo(Record.readDeclarationNameInfo());
12402 C->setMapType(
12403 static_cast<OpenMPMapClauseKind>(Record.readInt()));
12404 C->setMapLoc(Record.readSourceLocation());
12405 C->setColonLoc(Record.readSourceLocation());
12406 auto NumVars = C->varlist_size();
12407 auto UniqueDecls = C->getUniqueDeclarationsNum();
12408 auto TotalLists = C->getTotalComponentListNum();
12409 auto TotalComponents = C->getTotalComponentsNum();
12410
12411 SmallVector<Expr *, 16> Vars;
12412 Vars.reserve(NumVars);
12413 for (unsigned i = 0; i != NumVars; ++i)
12414 Vars.push_back(Record.readExpr());
12415 C->setVarRefs(Vars);
12416
12417 SmallVector<Expr *, 16> UDMappers;
12418 UDMappers.reserve(NumVars);
12419 for (unsigned I = 0; I < NumVars; ++I)
12420 UDMappers.push_back(Record.readExpr());
12421 C->setUDMapperRefs(UDMappers);
12422
12423 if (HasIteratorModifier)
12424 C->setIteratorModifier(Record.readExpr());
12425
12426 SmallVector<ValueDecl *, 16> Decls;
12427 Decls.reserve(UniqueDecls);
12428 for (unsigned i = 0; i < UniqueDecls; ++i)
12429 Decls.push_back(Record.readDeclAs<ValueDecl>());
12430 C->setUniqueDecls(Decls);
12431
12432 SmallVector<unsigned, 16> ListsPerDecl;
12433 ListsPerDecl.reserve(UniqueDecls);
12434 for (unsigned i = 0; i < UniqueDecls; ++i)
12435 ListsPerDecl.push_back(Record.readInt());
12436 C->setDeclNumLists(ListsPerDecl);
12437
12438 SmallVector<unsigned, 32> ListSizes;
12439 ListSizes.reserve(TotalLists);
12440 for (unsigned i = 0; i < TotalLists; ++i)
12441 ListSizes.push_back(Record.readInt());
12442 C->setComponentListSizes(ListSizes);
12443
12444 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12445 Components.reserve(TotalComponents);
12446 for (unsigned i = 0; i < TotalComponents; ++i) {
12447 Expr *AssociatedExprPr = Record.readExpr();
12448 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12449 Components.emplace_back(AssociatedExprPr, AssociatedDecl,
12450 /*IsNonContiguous=*/false);
12451 }
12452 C->setComponents(Components, ListSizes);
12453}
12454
12455void OMPClauseReader::VisitOMPAllocateClause(OMPAllocateClause *C) {
12456 C->setFirstAllocateModifier(Record.readEnum<OpenMPAllocateClauseModifier>());
12457 C->setSecondAllocateModifier(Record.readEnum<OpenMPAllocateClauseModifier>());
12458 C->setLParenLoc(Record.readSourceLocation());
12459 C->setColonLoc(Record.readSourceLocation());
12460 C->setAllocator(Record.readSubExpr());
12461 C->setAlignment(Record.readSubExpr());
12462 unsigned NumVars = C->varlist_size();
12463 SmallVector<Expr *, 16> Vars;
12464 Vars.reserve(NumVars);
12465 for (unsigned i = 0; i != NumVars; ++i)
12466 Vars.push_back(Record.readSubExpr());
12467 C->setVarRefs(Vars);
12468}
12469
12470void OMPClauseReader::VisitOMPNumTeamsClause(OMPNumTeamsClause *C) {
12472 C->setLParenLoc(Record.readSourceLocation());
12473 unsigned NumVars = C->varlist_size();
12474 SmallVector<Expr *, 16> Vars;
12475 Vars.reserve(NumVars);
12476 for (unsigned I = 0; I != NumVars; ++I)
12477 Vars.push_back(Record.readSubExpr());
12478 C->setVarRefs(Vars);
12479}
12480
12481void OMPClauseReader::VisitOMPThreadLimitClause(OMPThreadLimitClause *C) {
12483 C->setLParenLoc(Record.readSourceLocation());
12484 unsigned NumVars = C->varlist_size();
12485 SmallVector<Expr *, 16> Vars;
12486 Vars.reserve(NumVars);
12487 for (unsigned I = 0; I != NumVars; ++I)
12488 Vars.push_back(Record.readSubExpr());
12489 C->setVarRefs(Vars);
12490}
12491
12492void OMPClauseReader::VisitOMPPriorityClause(OMPPriorityClause *C) {
12494 C->setPriority(Record.readSubExpr());
12495 C->setLParenLoc(Record.readSourceLocation());
12496}
12497
12498void OMPClauseReader::VisitOMPGrainsizeClause(OMPGrainsizeClause *C) {
12500 C->setModifier(Record.readEnum<OpenMPGrainsizeClauseModifier>());
12501 C->setGrainsize(Record.readSubExpr());
12502 C->setModifierLoc(Record.readSourceLocation());
12503 C->setLParenLoc(Record.readSourceLocation());
12504}
12505
12506void OMPClauseReader::VisitOMPNumTasksClause(OMPNumTasksClause *C) {
12508 C->setModifier(Record.readEnum<OpenMPNumTasksClauseModifier>());
12509 C->setNumTasks(Record.readSubExpr());
12510 C->setModifierLoc(Record.readSourceLocation());
12511 C->setLParenLoc(Record.readSourceLocation());
12512}
12513
12514void OMPClauseReader::VisitOMPHintClause(OMPHintClause *C) {
12515 C->setHint(Record.readSubExpr());
12516 C->setLParenLoc(Record.readSourceLocation());
12517}
12518
12519void OMPClauseReader::VisitOMPDistScheduleClause(OMPDistScheduleClause *C) {
12521 C->setDistScheduleKind(
12522 static_cast<OpenMPDistScheduleClauseKind>(Record.readInt()));
12523 C->setChunkSize(Record.readSubExpr());
12524 C->setLParenLoc(Record.readSourceLocation());
12525 C->setDistScheduleKindLoc(Record.readSourceLocation());
12526 C->setCommaLoc(Record.readSourceLocation());
12527}
12528
12529void OMPClauseReader::VisitOMPDefaultmapClause(OMPDefaultmapClause *C) {
12530 C->setDefaultmapKind(
12531 static_cast<OpenMPDefaultmapClauseKind>(Record.readInt()));
12532 C->setDefaultmapModifier(
12533 static_cast<OpenMPDefaultmapClauseModifier>(Record.readInt()));
12534 C->setLParenLoc(Record.readSourceLocation());
12535 C->setDefaultmapModifierLoc(Record.readSourceLocation());
12536 C->setDefaultmapKindLoc(Record.readSourceLocation());
12537}
12538
12539void OMPClauseReader::VisitOMPToClause(OMPToClause *C) {
12540 C->setLParenLoc(Record.readSourceLocation());
12541 for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) {
12542 C->setMotionModifier(
12543 I, static_cast<OpenMPMotionModifierKind>(Record.readInt()));
12544 C->setMotionModifierLoc(I, Record.readSourceLocation());
12545 if (C->getMotionModifier(I) == OMPC_MOTION_MODIFIER_iterator)
12546 C->setIteratorModifier(Record.readExpr());
12547 }
12548 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
12549 C->setMapperIdInfo(Record.readDeclarationNameInfo());
12550 C->setColonLoc(Record.readSourceLocation());
12551 auto NumVars = C->varlist_size();
12552 auto UniqueDecls = C->getUniqueDeclarationsNum();
12553 auto TotalLists = C->getTotalComponentListNum();
12554 auto TotalComponents = C->getTotalComponentsNum();
12555
12556 SmallVector<Expr *, 16> Vars;
12557 Vars.reserve(NumVars);
12558 for (unsigned i = 0; i != NumVars; ++i)
12559 Vars.push_back(Record.readSubExpr());
12560 C->setVarRefs(Vars);
12561
12562 SmallVector<Expr *, 16> UDMappers;
12563 UDMappers.reserve(NumVars);
12564 for (unsigned I = 0; I < NumVars; ++I)
12565 UDMappers.push_back(Record.readSubExpr());
12566 C->setUDMapperRefs(UDMappers);
12567
12568 SmallVector<ValueDecl *, 16> Decls;
12569 Decls.reserve(UniqueDecls);
12570 for (unsigned i = 0; i < UniqueDecls; ++i)
12571 Decls.push_back(Record.readDeclAs<ValueDecl>());
12572 C->setUniqueDecls(Decls);
12573
12574 SmallVector<unsigned, 16> ListsPerDecl;
12575 ListsPerDecl.reserve(UniqueDecls);
12576 for (unsigned i = 0; i < UniqueDecls; ++i)
12577 ListsPerDecl.push_back(Record.readInt());
12578 C->setDeclNumLists(ListsPerDecl);
12579
12580 SmallVector<unsigned, 32> ListSizes;
12581 ListSizes.reserve(TotalLists);
12582 for (unsigned i = 0; i < TotalLists; ++i)
12583 ListSizes.push_back(Record.readInt());
12584 C->setComponentListSizes(ListSizes);
12585
12586 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12587 Components.reserve(TotalComponents);
12588 for (unsigned i = 0; i < TotalComponents; ++i) {
12589 Expr *AssociatedExprPr = Record.readSubExpr();
12590 bool IsNonContiguous = Record.readBool();
12591 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12592 Components.emplace_back(AssociatedExprPr, AssociatedDecl, IsNonContiguous);
12593 }
12594 C->setComponents(Components, ListSizes);
12595}
12596
12597void OMPClauseReader::VisitOMPFromClause(OMPFromClause *C) {
12598 C->setLParenLoc(Record.readSourceLocation());
12599 for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) {
12600 C->setMotionModifier(
12601 I, static_cast<OpenMPMotionModifierKind>(Record.readInt()));
12602 C->setMotionModifierLoc(I, Record.readSourceLocation());
12603 if (C->getMotionModifier(I) == OMPC_MOTION_MODIFIER_iterator)
12604 C->setIteratorModifier(Record.readExpr());
12605 }
12606 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
12607 C->setMapperIdInfo(Record.readDeclarationNameInfo());
12608 C->setColonLoc(Record.readSourceLocation());
12609 auto NumVars = C->varlist_size();
12610 auto UniqueDecls = C->getUniqueDeclarationsNum();
12611 auto TotalLists = C->getTotalComponentListNum();
12612 auto TotalComponents = C->getTotalComponentsNum();
12613
12614 SmallVector<Expr *, 16> Vars;
12615 Vars.reserve(NumVars);
12616 for (unsigned i = 0; i != NumVars; ++i)
12617 Vars.push_back(Record.readSubExpr());
12618 C->setVarRefs(Vars);
12619
12620 SmallVector<Expr *, 16> UDMappers;
12621 UDMappers.reserve(NumVars);
12622 for (unsigned I = 0; I < NumVars; ++I)
12623 UDMappers.push_back(Record.readSubExpr());
12624 C->setUDMapperRefs(UDMappers);
12625
12626 SmallVector<ValueDecl *, 16> Decls;
12627 Decls.reserve(UniqueDecls);
12628 for (unsigned i = 0; i < UniqueDecls; ++i)
12629 Decls.push_back(Record.readDeclAs<ValueDecl>());
12630 C->setUniqueDecls(Decls);
12631
12632 SmallVector<unsigned, 16> ListsPerDecl;
12633 ListsPerDecl.reserve(UniqueDecls);
12634 for (unsigned i = 0; i < UniqueDecls; ++i)
12635 ListsPerDecl.push_back(Record.readInt());
12636 C->setDeclNumLists(ListsPerDecl);
12637
12638 SmallVector<unsigned, 32> ListSizes;
12639 ListSizes.reserve(TotalLists);
12640 for (unsigned i = 0; i < TotalLists; ++i)
12641 ListSizes.push_back(Record.readInt());
12642 C->setComponentListSizes(ListSizes);
12643
12644 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12645 Components.reserve(TotalComponents);
12646 for (unsigned i = 0; i < TotalComponents; ++i) {
12647 Expr *AssociatedExprPr = Record.readSubExpr();
12648 bool IsNonContiguous = Record.readBool();
12649 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12650 Components.emplace_back(AssociatedExprPr, AssociatedDecl, IsNonContiguous);
12651 }
12652 C->setComponents(Components, ListSizes);
12653}
12654
12655void OMPClauseReader::VisitOMPUseDevicePtrClause(OMPUseDevicePtrClause *C) {
12656 C->setLParenLoc(Record.readSourceLocation());
12657 C->setFallbackModifier(Record.readEnum<OpenMPUseDevicePtrFallbackModifier>());
12658 C->setFallbackModifierLoc(Record.readSourceLocation());
12659 auto NumVars = C->varlist_size();
12660 auto UniqueDecls = C->getUniqueDeclarationsNum();
12661 auto TotalLists = C->getTotalComponentListNum();
12662 auto TotalComponents = C->getTotalComponentsNum();
12663
12664 SmallVector<Expr *, 16> Vars;
12665 Vars.reserve(NumVars);
12666 for (unsigned i = 0; i != NumVars; ++i)
12667 Vars.push_back(Record.readSubExpr());
12668 C->setVarRefs(Vars);
12669 Vars.clear();
12670 for (unsigned i = 0; i != NumVars; ++i)
12671 Vars.push_back(Record.readSubExpr());
12672 C->setPrivateCopies(Vars);
12673 Vars.clear();
12674 for (unsigned i = 0; i != NumVars; ++i)
12675 Vars.push_back(Record.readSubExpr());
12676 C->setInits(Vars);
12677
12678 SmallVector<ValueDecl *, 16> Decls;
12679 Decls.reserve(UniqueDecls);
12680 for (unsigned i = 0; i < UniqueDecls; ++i)
12681 Decls.push_back(Record.readDeclAs<ValueDecl>());
12682 C->setUniqueDecls(Decls);
12683
12684 SmallVector<unsigned, 16> ListsPerDecl;
12685 ListsPerDecl.reserve(UniqueDecls);
12686 for (unsigned i = 0; i < UniqueDecls; ++i)
12687 ListsPerDecl.push_back(Record.readInt());
12688 C->setDeclNumLists(ListsPerDecl);
12689
12690 SmallVector<unsigned, 32> ListSizes;
12691 ListSizes.reserve(TotalLists);
12692 for (unsigned i = 0; i < TotalLists; ++i)
12693 ListSizes.push_back(Record.readInt());
12694 C->setComponentListSizes(ListSizes);
12695
12696 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12697 Components.reserve(TotalComponents);
12698 for (unsigned i = 0; i < TotalComponents; ++i) {
12699 auto *AssociatedExprPr = Record.readSubExpr();
12700 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12701 Components.emplace_back(AssociatedExprPr, AssociatedDecl,
12702 /*IsNonContiguous=*/false);
12703 }
12704 C->setComponents(Components, ListSizes);
12705}
12706
12707void OMPClauseReader::VisitOMPUseDeviceAddrClause(OMPUseDeviceAddrClause *C) {
12708 C->setLParenLoc(Record.readSourceLocation());
12709 auto NumVars = C->varlist_size();
12710 auto UniqueDecls = C->getUniqueDeclarationsNum();
12711 auto TotalLists = C->getTotalComponentListNum();
12712 auto TotalComponents = C->getTotalComponentsNum();
12713
12714 SmallVector<Expr *, 16> Vars;
12715 Vars.reserve(NumVars);
12716 for (unsigned i = 0; i != NumVars; ++i)
12717 Vars.push_back(Record.readSubExpr());
12718 C->setVarRefs(Vars);
12719
12720 SmallVector<ValueDecl *, 16> Decls;
12721 Decls.reserve(UniqueDecls);
12722 for (unsigned i = 0; i < UniqueDecls; ++i)
12723 Decls.push_back(Record.readDeclAs<ValueDecl>());
12724 C->setUniqueDecls(Decls);
12725
12726 SmallVector<unsigned, 16> ListsPerDecl;
12727 ListsPerDecl.reserve(UniqueDecls);
12728 for (unsigned i = 0; i < UniqueDecls; ++i)
12729 ListsPerDecl.push_back(Record.readInt());
12730 C->setDeclNumLists(ListsPerDecl);
12731
12732 SmallVector<unsigned, 32> ListSizes;
12733 ListSizes.reserve(TotalLists);
12734 for (unsigned i = 0; i < TotalLists; ++i)
12735 ListSizes.push_back(Record.readInt());
12736 C->setComponentListSizes(ListSizes);
12737
12738 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12739 Components.reserve(TotalComponents);
12740 for (unsigned i = 0; i < TotalComponents; ++i) {
12741 Expr *AssociatedExpr = Record.readSubExpr();
12742 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12743 Components.emplace_back(AssociatedExpr, AssociatedDecl,
12744 /*IsNonContiguous*/ false);
12745 }
12746 C->setComponents(Components, ListSizes);
12747}
12748
12749void OMPClauseReader::VisitOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
12750 C->setLParenLoc(Record.readSourceLocation());
12751 auto NumVars = C->varlist_size();
12752 auto UniqueDecls = C->getUniqueDeclarationsNum();
12753 auto TotalLists = C->getTotalComponentListNum();
12754 auto TotalComponents = C->getTotalComponentsNum();
12755
12756 SmallVector<Expr *, 16> Vars;
12757 Vars.reserve(NumVars);
12758 for (unsigned i = 0; i != NumVars; ++i)
12759 Vars.push_back(Record.readSubExpr());
12760 C->setVarRefs(Vars);
12761 Vars.clear();
12762
12763 SmallVector<ValueDecl *, 16> Decls;
12764 Decls.reserve(UniqueDecls);
12765 for (unsigned i = 0; i < UniqueDecls; ++i)
12766 Decls.push_back(Record.readDeclAs<ValueDecl>());
12767 C->setUniqueDecls(Decls);
12768
12769 SmallVector<unsigned, 16> ListsPerDecl;
12770 ListsPerDecl.reserve(UniqueDecls);
12771 for (unsigned i = 0; i < UniqueDecls; ++i)
12772 ListsPerDecl.push_back(Record.readInt());
12773 C->setDeclNumLists(ListsPerDecl);
12774
12775 SmallVector<unsigned, 32> ListSizes;
12776 ListSizes.reserve(TotalLists);
12777 for (unsigned i = 0; i < TotalLists; ++i)
12778 ListSizes.push_back(Record.readInt());
12779 C->setComponentListSizes(ListSizes);
12780
12781 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12782 Components.reserve(TotalComponents);
12783 for (unsigned i = 0; i < TotalComponents; ++i) {
12784 Expr *AssociatedExpr = Record.readSubExpr();
12785 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12786 Components.emplace_back(AssociatedExpr, AssociatedDecl,
12787 /*IsNonContiguous=*/false);
12788 }
12789 C->setComponents(Components, ListSizes);
12790}
12791
12792void OMPClauseReader::VisitOMPHasDeviceAddrClause(OMPHasDeviceAddrClause *C) {
12793 C->setLParenLoc(Record.readSourceLocation());
12794 auto NumVars = C->varlist_size();
12795 auto UniqueDecls = C->getUniqueDeclarationsNum();
12796 auto TotalLists = C->getTotalComponentListNum();
12797 auto TotalComponents = C->getTotalComponentsNum();
12798
12799 SmallVector<Expr *, 16> Vars;
12800 Vars.reserve(NumVars);
12801 for (unsigned I = 0; I != NumVars; ++I)
12802 Vars.push_back(Record.readSubExpr());
12803 C->setVarRefs(Vars);
12804 Vars.clear();
12805
12806 SmallVector<ValueDecl *, 16> Decls;
12807 Decls.reserve(UniqueDecls);
12808 for (unsigned I = 0; I < UniqueDecls; ++I)
12809 Decls.push_back(Record.readDeclAs<ValueDecl>());
12810 C->setUniqueDecls(Decls);
12811
12812 SmallVector<unsigned, 16> ListsPerDecl;
12813 ListsPerDecl.reserve(UniqueDecls);
12814 for (unsigned I = 0; I < UniqueDecls; ++I)
12815 ListsPerDecl.push_back(Record.readInt());
12816 C->setDeclNumLists(ListsPerDecl);
12817
12818 SmallVector<unsigned, 32> ListSizes;
12819 ListSizes.reserve(TotalLists);
12820 for (unsigned i = 0; i < TotalLists; ++i)
12821 ListSizes.push_back(Record.readInt());
12822 C->setComponentListSizes(ListSizes);
12823
12824 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12825 Components.reserve(TotalComponents);
12826 for (unsigned I = 0; I < TotalComponents; ++I) {
12827 Expr *AssociatedExpr = Record.readSubExpr();
12828 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12829 Components.emplace_back(AssociatedExpr, AssociatedDecl,
12830 /*IsNonContiguous=*/false);
12831 }
12832 C->setComponents(Components, ListSizes);
12833}
12834
12835void OMPClauseReader::VisitOMPNontemporalClause(OMPNontemporalClause *C) {
12836 C->setLParenLoc(Record.readSourceLocation());
12837 unsigned NumVars = C->varlist_size();
12838 SmallVector<Expr *, 16> Vars;
12839 Vars.reserve(NumVars);
12840 for (unsigned i = 0; i != NumVars; ++i)
12841 Vars.push_back(Record.readSubExpr());
12842 C->setVarRefs(Vars);
12843 Vars.clear();
12844 Vars.reserve(NumVars);
12845 for (unsigned i = 0; i != NumVars; ++i)
12846 Vars.push_back(Record.readSubExpr());
12847 C->setPrivateRefs(Vars);
12848}
12849
12850void OMPClauseReader::VisitOMPInclusiveClause(OMPInclusiveClause *C) {
12851 C->setLParenLoc(Record.readSourceLocation());
12852 unsigned NumVars = C->varlist_size();
12853 SmallVector<Expr *, 16> Vars;
12854 Vars.reserve(NumVars);
12855 for (unsigned i = 0; i != NumVars; ++i)
12856 Vars.push_back(Record.readSubExpr());
12857 C->setVarRefs(Vars);
12858}
12859
12860void OMPClauseReader::VisitOMPExclusiveClause(OMPExclusiveClause *C) {
12861 C->setLParenLoc(Record.readSourceLocation());
12862 unsigned NumVars = C->varlist_size();
12863 SmallVector<Expr *, 16> Vars;
12864 Vars.reserve(NumVars);
12865 for (unsigned i = 0; i != NumVars; ++i)
12866 Vars.push_back(Record.readSubExpr());
12867 C->setVarRefs(Vars);
12868}
12869
12870void OMPClauseReader::VisitOMPUsesAllocatorsClause(OMPUsesAllocatorsClause *C) {
12871 C->setLParenLoc(Record.readSourceLocation());
12872 unsigned NumOfAllocators = C->getNumberOfAllocators();
12873 SmallVector<OMPUsesAllocatorsClause::Data, 4> Data;
12874 Data.reserve(NumOfAllocators);
12875 for (unsigned I = 0; I != NumOfAllocators; ++I) {
12876 OMPUsesAllocatorsClause::Data &D = Data.emplace_back();
12877 D.Allocator = Record.readSubExpr();
12878 D.AllocatorTraits = Record.readSubExpr();
12879 D.LParenLoc = Record.readSourceLocation();
12880 D.RParenLoc = Record.readSourceLocation();
12881 }
12882 C->setAllocatorsData(Data);
12883}
12884
12885void OMPClauseReader::VisitOMPAffinityClause(OMPAffinityClause *C) {
12886 C->setLParenLoc(Record.readSourceLocation());
12887 C->setModifier(Record.readSubExpr());
12888 C->setColonLoc(Record.readSourceLocation());
12889 unsigned NumOfLocators = C->varlist_size();
12890 SmallVector<Expr *, 4> Locators;
12891 Locators.reserve(NumOfLocators);
12892 for (unsigned I = 0; I != NumOfLocators; ++I)
12893 Locators.push_back(Record.readSubExpr());
12894 C->setVarRefs(Locators);
12895}
12896
12897void OMPClauseReader::VisitOMPOrderClause(OMPOrderClause *C) {
12898 C->setKind(Record.readEnum<OpenMPOrderClauseKind>());
12899 C->setModifier(Record.readEnum<OpenMPOrderClauseModifier>());
12900 C->setLParenLoc(Record.readSourceLocation());
12901 C->setKindKwLoc(Record.readSourceLocation());
12902 C->setModifierKwLoc(Record.readSourceLocation());
12903}
12904
12905void OMPClauseReader::VisitOMPFilterClause(OMPFilterClause *C) {
12907 C->setThreadID(Record.readSubExpr());
12908 C->setLParenLoc(Record.readSourceLocation());
12909}
12910
12911void OMPClauseReader::VisitOMPBindClause(OMPBindClause *C) {
12912 C->setBindKind(Record.readEnum<OpenMPBindClauseKind>());
12913 C->setLParenLoc(Record.readSourceLocation());
12914 C->setBindKindLoc(Record.readSourceLocation());
12915}
12916
12917void OMPClauseReader::VisitOMPAlignClause(OMPAlignClause *C) {
12918 C->setAlignment(Record.readExpr());
12919 C->setLParenLoc(Record.readSourceLocation());
12920}
12921
12922void OMPClauseReader::VisitOMPXDynCGroupMemClause(OMPXDynCGroupMemClause *C) {
12924 C->setSize(Record.readSubExpr());
12925 C->setLParenLoc(Record.readSourceLocation());
12926}
12927
12928void OMPClauseReader::VisitOMPDynGroupprivateClause(
12929 OMPDynGroupprivateClause *C) {
12931 C->setDynGroupprivateModifier(
12932 Record.readEnum<OpenMPDynGroupprivateClauseModifier>());
12933 C->setDynGroupprivateFallbackModifier(
12935 C->setSize(Record.readSubExpr());
12936 C->setLParenLoc(Record.readSourceLocation());
12937 C->setDynGroupprivateModifierLoc(Record.readSourceLocation());
12938 C->setDynGroupprivateFallbackModifierLoc(Record.readSourceLocation());
12939}
12940
12941void OMPClauseReader::VisitOMPDoacrossClause(OMPDoacrossClause *C) {
12942 C->setLParenLoc(Record.readSourceLocation());
12943 C->setDependenceType(
12944 static_cast<OpenMPDoacrossClauseModifier>(Record.readInt()));
12945 C->setDependenceLoc(Record.readSourceLocation());
12946 C->setColonLoc(Record.readSourceLocation());
12947 unsigned NumVars = C->varlist_size();
12948 SmallVector<Expr *, 16> Vars;
12949 Vars.reserve(NumVars);
12950 for (unsigned I = 0; I != NumVars; ++I)
12951 Vars.push_back(Record.readSubExpr());
12952 C->setVarRefs(Vars);
12953 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
12954 C->setLoopData(I, Record.readSubExpr());
12955}
12956
12957void OMPClauseReader::VisitOMPXAttributeClause(OMPXAttributeClause *C) {
12958 AttrVec Attrs;
12959 Record.readAttributes(Attrs);
12960 C->setAttrs(Attrs);
12961 C->setLocStart(Record.readSourceLocation());
12962 C->setLParenLoc(Record.readSourceLocation());
12963 C->setLocEnd(Record.readSourceLocation());
12964}
12965
12966void OMPClauseReader::VisitOMPXBareClause(OMPXBareClause *C) {}
12967
12970 TI.Sets.resize(readUInt32());
12971 for (auto &Set : TI.Sets) {
12973 Set.Selectors.resize(readUInt32());
12974 for (auto &Selector : Set.Selectors) {
12976 Selector.ScoreOrCondition = nullptr;
12977 if (readBool())
12978 Selector.ScoreOrCondition = readExprRef();
12979 Selector.Properties.resize(readUInt32());
12980 for (auto &Property : Selector.Properties)
12982 }
12983 }
12984 return &TI;
12985}
12986
12988 if (!Data)
12989 return;
12990 if (Reader->ReadingKind == ASTReader::Read_Stmt) {
12991 // Skip NumClauses, NumChildren and HasAssociatedStmt fields.
12992 skipInts(3);
12993 }
12994 SmallVector<OMPClause *, 4> Clauses(Data->getNumClauses());
12995 for (unsigned I = 0, E = Data->getNumClauses(); I < E; ++I)
12996 Clauses[I] = readOMPClause();
12997 Data->setClauses(Clauses);
12998 if (Data->hasAssociatedStmt())
12999 Data->setAssociatedStmt(readStmt());
13000 for (unsigned I = 0, E = Data->getNumChildren(); I < E; ++I)
13001 Data->getChildren()[I] = readStmt();
13002}
13003
13005 unsigned NumVars = readInt();
13007 for (unsigned I = 0; I < NumVars; ++I)
13008 VarList.push_back(readExpr());
13009 return VarList;
13010}
13011
13013 unsigned NumExprs = readInt();
13015 for (unsigned I = 0; I < NumExprs; ++I)
13016 ExprList.push_back(readSubExpr());
13017 return ExprList;
13018}
13019
13024
13025 switch (ClauseKind) {
13027 SourceLocation LParenLoc = readSourceLocation();
13029 return OpenACCDefaultClause::Create(getContext(), DCK, BeginLoc, LParenLoc,
13030 EndLoc);
13031 }
13032 case OpenACCClauseKind::If: {
13033 SourceLocation LParenLoc = readSourceLocation();
13034 Expr *CondExpr = readSubExpr();
13035 return OpenACCIfClause::Create(getContext(), BeginLoc, LParenLoc, CondExpr,
13036 EndLoc);
13037 }
13039 SourceLocation LParenLoc = readSourceLocation();
13040 bool isConditionExprClause = readBool();
13041 if (isConditionExprClause) {
13042 Expr *CondExpr = readBool() ? readSubExpr() : nullptr;
13043 return OpenACCSelfClause::Create(getContext(), BeginLoc, LParenLoc,
13044 CondExpr, EndLoc);
13045 }
13046 unsigned NumVars = readInt();
13048 for (unsigned I = 0; I < NumVars; ++I)
13049 VarList.push_back(readSubExpr());
13050 return OpenACCSelfClause::Create(getContext(), BeginLoc, LParenLoc, VarList,
13051 EndLoc);
13052 }
13054 SourceLocation LParenLoc = readSourceLocation();
13055 unsigned NumClauses = readInt();
13057 for (unsigned I = 0; I < NumClauses; ++I)
13058 IntExprs.push_back(readSubExpr());
13059 return OpenACCNumGangsClause::Create(getContext(), BeginLoc, LParenLoc,
13060 IntExprs, EndLoc);
13061 }
13063 SourceLocation LParenLoc = readSourceLocation();
13064 Expr *IntExpr = readSubExpr();
13065 return OpenACCNumWorkersClause::Create(getContext(), BeginLoc, LParenLoc,
13066 IntExpr, EndLoc);
13067 }
13069 SourceLocation LParenLoc = readSourceLocation();
13070 Expr *IntExpr = readSubExpr();
13071 return OpenACCDeviceNumClause::Create(getContext(), BeginLoc, LParenLoc,
13072 IntExpr, EndLoc);
13073 }
13075 SourceLocation LParenLoc = readSourceLocation();
13076 Expr *IntExpr = readSubExpr();
13077 return OpenACCDefaultAsyncClause::Create(getContext(), BeginLoc, LParenLoc,
13078 IntExpr, EndLoc);
13079 }
13081 SourceLocation LParenLoc = readSourceLocation();
13082 Expr *IntExpr = readSubExpr();
13083 return OpenACCVectorLengthClause::Create(getContext(), BeginLoc, LParenLoc,
13084 IntExpr, EndLoc);
13085 }
13087 SourceLocation LParenLoc = readSourceLocation();
13089
13091 for (unsigned I = 0; I < VarList.size(); ++I) {
13092 static_assert(sizeof(OpenACCPrivateRecipe) == 1 * sizeof(int *));
13093 VarDecl *Alloca = readDeclAs<VarDecl>();
13094 RecipeList.push_back({Alloca});
13095 }
13096
13097 return OpenACCPrivateClause::Create(getContext(), BeginLoc, LParenLoc,
13098 VarList, RecipeList, EndLoc);
13099 }
13101 SourceLocation LParenLoc = readSourceLocation();
13103 return OpenACCHostClause::Create(getContext(), BeginLoc, LParenLoc, VarList,
13104 EndLoc);
13105 }
13107 SourceLocation LParenLoc = readSourceLocation();
13109 return OpenACCDeviceClause::Create(getContext(), BeginLoc, LParenLoc,
13110 VarList, EndLoc);
13111 }
13113 SourceLocation LParenLoc = readSourceLocation();
13116 for (unsigned I = 0; I < VarList.size(); ++I) {
13117 static_assert(sizeof(OpenACCFirstPrivateRecipe) == 2 * sizeof(int *));
13118 VarDecl *Recipe = readDeclAs<VarDecl>();
13119 VarDecl *RecipeTemp = readDeclAs<VarDecl>();
13120 RecipeList.push_back({Recipe, RecipeTemp});
13121 }
13122
13123 return OpenACCFirstPrivateClause::Create(getContext(), BeginLoc, LParenLoc,
13124 VarList, RecipeList, EndLoc);
13125 }
13127 SourceLocation LParenLoc = readSourceLocation();
13129 return OpenACCAttachClause::Create(getContext(), BeginLoc, LParenLoc,
13130 VarList, EndLoc);
13131 }
13133 SourceLocation LParenLoc = readSourceLocation();
13135 return OpenACCDetachClause::Create(getContext(), BeginLoc, LParenLoc,
13136 VarList, EndLoc);
13137 }
13139 SourceLocation LParenLoc = readSourceLocation();
13141 return OpenACCDeleteClause::Create(getContext(), BeginLoc, LParenLoc,
13142 VarList, EndLoc);
13143 }
13145 SourceLocation LParenLoc = readSourceLocation();
13147 return OpenACCUseDeviceClause::Create(getContext(), BeginLoc, LParenLoc,
13148 VarList, EndLoc);
13149 }
13151 SourceLocation LParenLoc = readSourceLocation();
13153 return OpenACCDevicePtrClause::Create(getContext(), BeginLoc, LParenLoc,
13154 VarList, EndLoc);
13155 }
13157 SourceLocation LParenLoc = readSourceLocation();
13159 return OpenACCNoCreateClause::Create(getContext(), BeginLoc, LParenLoc,
13160 VarList, EndLoc);
13161 }
13163 SourceLocation LParenLoc = readSourceLocation();
13165 return OpenACCPresentClause::Create(getContext(), BeginLoc, LParenLoc,
13166 VarList, EndLoc);
13167 }
13171 SourceLocation LParenLoc = readSourceLocation();
13174 return OpenACCCopyClause::Create(getContext(), ClauseKind, BeginLoc,
13175 LParenLoc, ModList, VarList, EndLoc);
13176 }
13180 SourceLocation LParenLoc = readSourceLocation();
13183 return OpenACCCopyInClause::Create(getContext(), ClauseKind, BeginLoc,
13184 LParenLoc, ModList, VarList, EndLoc);
13185 }
13189 SourceLocation LParenLoc = readSourceLocation();
13192 return OpenACCCopyOutClause::Create(getContext(), ClauseKind, BeginLoc,
13193 LParenLoc, ModList, VarList, EndLoc);
13194 }
13198 SourceLocation LParenLoc = readSourceLocation();
13201 return OpenACCCreateClause::Create(getContext(), ClauseKind, BeginLoc,
13202 LParenLoc, ModList, VarList, EndLoc);
13203 }
13205 SourceLocation LParenLoc = readSourceLocation();
13206 Expr *AsyncExpr = readBool() ? readSubExpr() : nullptr;
13207 return OpenACCAsyncClause::Create(getContext(), BeginLoc, LParenLoc,
13208 AsyncExpr, EndLoc);
13209 }
13211 SourceLocation LParenLoc = readSourceLocation();
13212 Expr *DevNumExpr = readBool() ? readSubExpr() : nullptr;
13213 SourceLocation QueuesLoc = readSourceLocation();
13215 return OpenACCWaitClause::Create(getContext(), BeginLoc, LParenLoc,
13216 DevNumExpr, QueuesLoc, QueueIdExprs,
13217 EndLoc);
13218 }
13221 SourceLocation LParenLoc = readSourceLocation();
13223 unsigned NumArchs = readInt();
13224
13225 for (unsigned I = 0; I < NumArchs; ++I) {
13226 IdentifierInfo *Ident = readBool() ? readIdentifier() : nullptr;
13228 Archs.emplace_back(Loc, Ident);
13229 }
13230
13231 return OpenACCDeviceTypeClause::Create(getContext(), ClauseKind, BeginLoc,
13232 LParenLoc, Archs, EndLoc);
13233 }
13235 SourceLocation LParenLoc = readSourceLocation();
13239
13240 for (unsigned I = 0; I < VarList.size(); ++I) {
13241 VarDecl *Recipe = readDeclAs<VarDecl>();
13242
13243 static_assert(sizeof(OpenACCReductionRecipe::CombinerRecipe) ==
13244 3 * sizeof(int *));
13245
13247 unsigned NumCombiners = readInt();
13248 for (unsigned I = 0; I < NumCombiners; ++I) {
13251 Expr *Op = readExpr();
13252
13253 Combiners.push_back({LHS, RHS, Op});
13254 }
13255
13256 RecipeList.push_back({Recipe, Combiners});
13257 }
13258
13259 return OpenACCReductionClause::Create(getContext(), BeginLoc, LParenLoc, Op,
13260 VarList, RecipeList, EndLoc);
13261 }
13263 return OpenACCSeqClause::Create(getContext(), BeginLoc, EndLoc);
13265 return OpenACCNoHostClause::Create(getContext(), BeginLoc, EndLoc);
13267 return OpenACCFinalizeClause::Create(getContext(), BeginLoc, EndLoc);
13269 return OpenACCIfPresentClause::Create(getContext(), BeginLoc, EndLoc);
13271 return OpenACCIndependentClause::Create(getContext(), BeginLoc, EndLoc);
13273 return OpenACCAutoClause::Create(getContext(), BeginLoc, EndLoc);
13275 SourceLocation LParenLoc = readSourceLocation();
13276 bool HasForce = readBool();
13277 Expr *LoopCount = readSubExpr();
13278 return OpenACCCollapseClause::Create(getContext(), BeginLoc, LParenLoc,
13279 HasForce, LoopCount, EndLoc);
13280 }
13282 SourceLocation LParenLoc = readSourceLocation();
13283 unsigned NumClauses = readInt();
13284 llvm::SmallVector<Expr *> SizeExprs;
13285 for (unsigned I = 0; I < NumClauses; ++I)
13286 SizeExprs.push_back(readSubExpr());
13287 return OpenACCTileClause::Create(getContext(), BeginLoc, LParenLoc,
13288 SizeExprs, EndLoc);
13289 }
13291 SourceLocation LParenLoc = readSourceLocation();
13292 unsigned NumExprs = readInt();
13295 for (unsigned I = 0; I < NumExprs; ++I) {
13296 GangKinds.push_back(readEnum<OpenACCGangKind>());
13297 // Can't use `readSubExpr` because this is usable from a 'decl' construct.
13298 Exprs.push_back(readExpr());
13299 }
13300 return OpenACCGangClause::Create(getContext(), BeginLoc, LParenLoc,
13301 GangKinds, Exprs, EndLoc);
13302 }
13304 SourceLocation LParenLoc = readSourceLocation();
13305 Expr *WorkerExpr = readBool() ? readSubExpr() : nullptr;
13306 return OpenACCWorkerClause::Create(getContext(), BeginLoc, LParenLoc,
13307 WorkerExpr, EndLoc);
13308 }
13310 SourceLocation LParenLoc = readSourceLocation();
13311 Expr *VectorExpr = readBool() ? readSubExpr() : nullptr;
13312 return OpenACCVectorClause::Create(getContext(), BeginLoc, LParenLoc,
13313 VectorExpr, EndLoc);
13314 }
13316 SourceLocation LParenLoc = readSourceLocation();
13318 return OpenACCLinkClause::Create(getContext(), BeginLoc, LParenLoc, VarList,
13319 EndLoc);
13320 }
13322 SourceLocation LParenLoc = readSourceLocation();
13325 LParenLoc, VarList, EndLoc);
13326 }
13327
13329 SourceLocation LParenLoc = readSourceLocation();
13330 bool IsString = readBool();
13331 if (IsString)
13332 return OpenACCBindClause::Create(getContext(), BeginLoc, LParenLoc,
13333 cast<StringLiteral>(readExpr()), EndLoc);
13334 return OpenACCBindClause::Create(getContext(), BeginLoc, LParenLoc,
13335 readIdentifier(), EndLoc);
13336 }
13339 llvm_unreachable("Clause serialization not yet implemented");
13340 }
13341 llvm_unreachable("Invalid Clause Kind");
13342}
13343
13346 for (unsigned I = 0; I < Clauses.size(); ++I)
13347 Clauses[I] = readOpenACCClause();
13348}
13349
13350void ASTRecordReader::readOpenACCRoutineDeclAttr(OpenACCRoutineDeclAttr *A) {
13351 unsigned NumVars = readInt();
13352 A->Clauses.resize(NumVars);
13353 readOpenACCClauseList(A->Clauses);
13354}
13355
13356static unsigned getStableHashForModuleName(StringRef PrimaryModuleName) {
13357 // TODO: Maybe it is better to check PrimaryModuleName is a valid
13358 // module name?
13359 llvm::FoldingSetNodeID ID;
13360 ID.AddString(PrimaryModuleName);
13361 return ID.computeStableHash();
13362}
13363
13365 if (!M)
13366 return std::nullopt;
13367
13368 if (M->isHeaderLikeModule())
13369 return std::nullopt;
13370
13371 if (M->isGlobalModule())
13372 return std::nullopt;
13373
13374 StringRef PrimaryModuleName = M->getPrimaryModuleInterfaceName();
13375 return getStableHashForModuleName(PrimaryModuleName);
13376}
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 bool checkModuleCachePath(llvm::vfs::FileSystem &VFS, StringRef SpecificModuleCachePath, 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.
static void addMethodsToPool(Sema &S, ArrayRef< ObjCMethodDecl * > Methods, ObjCMethodList &List)
Add the given set of methods to the method list.
static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags, DiagnosticsEngine &Diags, StringRef ModuleFilename, bool IsSystem, bool SystemHeaderWarningsInModule, bool Complain)
static bool isPredefinedType(serialization::TypeID ID)
static bool readBit(unsigned &Bits)
static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags, DiagnosticsEngine &Diags, StringRef ModuleFilename, bool Complain)
static std::optional< Type::TypeClass > getTypeClassForCode(TypeCode code)
static std::pair< unsigned, unsigned > readULEBKeyDataLength(const unsigned char *&P)
Read ULEB-encoded key length and data length.
static unsigned getStableHashForModuleName(StringRef PrimaryModuleName)
static LLVM_DUMP_METHOD void dumpModuleIDMap(StringRef Name, const ContinuousRangeMap< Key, ModuleFile *, InitialCapacity > &Map)
OptionValidation
@ OptionValidateStrictMatches
@ OptionValidateNone
@ OptionValidateContradictions
static bool checkTargetOptions(const TargetOptions &TargetOpts, const TargetOptions &ExistingTargetOpts, StringRef ModuleFilename, DiagnosticsEngine *Diags, bool AllowCompatibleDifferences=true)
Compare the given set of target options against an existing set of target options.
static bool checkLanguageOptions(const LangOptions &LangOpts, const LangOptions &ExistingLangOpts, StringRef ModuleFilename, DiagnosticsEngine *Diags, bool AllowCompatibleDifferences=true)
Compare the given set of language options against an existing set of language options.
static std::pair< StringRef, StringRef > getUnresolvedInputFilenames(const ASTReader::RecordData &Record, const StringRef InputBlob)
#define CHECK_TARGET_OPT(Field, Name)
static ASTFileSignature readASTFileSignature(StringRef PCH)
Reads and return the signature record from PCH's control block, or else returns 0.
static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID)
Given a cursor at the start of an AST file, scan ahead and drop the cursor into the start of the give...
static unsigned getIndexForTypeID(serialization::TypeID ID)
static uint64_t readULEB(const unsigned char *&P)
Defines the clang::ASTSourceDescriptor class, which abstracts clang modules and precompiled header fi...
static StringRef bytes(const std::vector< T, Allocator > &v)
Defines the Diagnostic-related interfaces.
Defines the clang::CommentOptions interface.
static void dump(llvm::raw_ostream &OS, StringRef FunctionName, ArrayRef< CounterExpression > Expressions, ArrayRef< CounterMappingRegion > Regions)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the C++ template declaration subclasses.
Defines the Diagnostic IDs-related interfaces.
static bool hasDefinition(const ObjCObjectPointerType *ObjPtr)
Defines the clang::Expr interface and subclasses for C++ expressions.
Defines the clang::FileManager interface and associated types.
Defines the clang::FileSystemOptions interface.
Token Tok
The Token.
FormatToken * Previous
The previous token in the unwrapped line.
FormatToken * Next
The next token in the unwrapped line.
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the clang::LangOptions interface.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Record Record
Definition MachO.h:31
Defines the clang::MacroInfo and clang::MacroDirective classes.
Defines the clang::Module class, which describes a module in the source code.
Defines types useful for describing an Objective-C runtime.
#define SM(sm)
Defines some OpenACC-specific enums and functions.
This file defines OpenMP AST classes for clauses.
Defines some OpenMP-specific enums and functions.
Defines an enumeration for C++ overloaded operators.
Defines the clang::Preprocessor interface.
Defines the clang::SanitizerKind enum.
This file declares semantic analysis for CUDA constructs.
This file declares semantic analysis for Objective-C.
Defines the clang::SourceLocation class and associated facilities.
Defines implementation details of the clang::SourceManager class.
Defines the SourceManager interface.
Defines various enumerations that describe declaration and type specifiers.
Defines the clang::TargetOptions class.
#define IMPORT(DERIVED, BASE)
Definition Template.h:631
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:850
void deduplicateMergedDefinitionsFor(NamedDecl *ND)
Clean up the merged definition list.
void adjustDeducedFunctionResultType(FunctionDecl *FD, QualType ResultType)
Change the result type of a function type once it is deduced.
void setPrimaryMergedDecl(Decl *D, Decl *Primary)
ASTIdentifierIterator(const ASTReader &Reader, bool SkipModules=false)
StringRef Next() override
Retrieve the next string in the identifier table and advances the iterator for the following string.
Abstract interface for callback invocations by the ASTReader.
Definition ASTReader.h:117
virtual void ReadModuleMapFile(StringRef ModuleMapPath)
Definition ASTReader.h:130
virtual bool needsInputFileVisitation()
Returns true if this ASTReaderListener wants to receive the input files of the AST file via visitInpu...
Definition ASTReader.h:232
virtual bool ReadDiagnosticOptions(DiagnosticOptions &DiagOpts, StringRef ModuleFilename, bool Complain)
Receives the diagnostic options.
Definition ASTReader.h:164
virtual bool ReadTargetOptions(const TargetOptions &TargetOpts, StringRef ModuleFilename, bool Complain, bool AllowCompatibleDifferences)
Receives the target options.
Definition ASTReader.h:154
virtual bool visitInputFile(StringRef Filename, bool isSystem, bool isOverridden, bool isExplicitModule)
if needsInputFileVisitation returns true, this is called for each non-system input file of the AST Fi...
Definition ASTReader.h:244
virtual bool ReadHeaderSearchPaths(const HeaderSearchOptions &HSOpts, bool Complain)
Receives the header search paths.
Definition ASTReader.h:202
virtual bool ReadFileSystemOptions(const FileSystemOptions &FSOpts, bool Complain)
Receives the file system options.
Definition ASTReader.h:173
virtual bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, StringRef ModuleFilename, bool ReadMacros, bool Complain, std::string &SuggestedPredefines)
Receives the preprocessor options.
Definition ASTReader.h:215
virtual bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, StringRef ModuleFilename, StringRef SpecificModuleCachePath, bool Complain)
Receives the header search options.
Definition ASTReader.h:186
virtual bool ReadLanguageOptions(const LangOptions &LangOpts, StringRef ModuleFilename, bool Complain, bool AllowCompatibleDifferences)
Receives the language options.
Definition ASTReader.h:135
virtual void visitModuleFile(StringRef Filename, serialization::ModuleKind Kind)
This is called for each AST file loaded.
Definition ASTReader.h:227
virtual void ReadModuleName(StringRef ModuleName)
Definition ASTReader.h:129
virtual void ReadCounter(const serialization::ModuleFile &M, uint32_t Value)
Receives COUNTER value.
Definition ASTReader.h:223
virtual bool needsSystemInputFileVisitation()
Returns true if this ASTReaderListener wants to receive the system input files of the AST file via vi...
Definition ASTReader.h:236
virtual bool ReadCodeGenOptions(const CodeGenOptions &CGOpts, StringRef ModuleFilename, bool Complain, bool AllowCompatibleDifferences)
Receives the codegen options.
Definition ASTReader.h:144
Reads an AST files chain containing the contents of a translation unit.
Definition ASTReader.h:430
std::optional< bool > isPreprocessedEntityInFileID(unsigned Index, FileID FID) override
Optionally returns true or false if the preallocated preprocessed entity with index Index came from f...
PreprocessedEntity * ReadPreprocessedEntity(unsigned Index) override
Read a preallocated preprocessed entity from the external source.
void markIdentifierUpToDate(const IdentifierInfo *II)
Note that this identifier is up-to-date.
void visitTopLevelModuleMaps(serialization::ModuleFile &MF, llvm::function_ref< void(FileEntryRef)> Visitor)
Visit all the top-level module maps loaded when building the given module file.
void setDeserializationListener(ASTDeserializationListener *Listener, bool TakeOwnership=false)
Set the AST deserialization listener.
SmallVectorImpl< uint64_t > RecordDataImpl
Definition ASTReader.h:446
serialization::SubmoduleID getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) const
Retrieve the global submodule ID given a module and its local ID number.
ExtKind hasExternalDefinitions(const Decl *D) override
IdentifierTable & getIdentifierTable()
Retrieve the identifier table associated with the preprocessor.
ModuleManager & getModuleManager()
Retrieve the module manager.
Definition ASTReader.h:2008
bool isDeclIDFromModule(GlobalDeclID ID, ModuleFile &M) const
Returns true if global DeclID ID originated from module M.
friend class ASTIdentifierIterator
Definition ASTReader.h:435
bool ReadSLocEntry(int ID) override
Read the source location entry with index ID.
void RecordSwitchCaseID(SwitchCase *SC, unsigned ID)
Record that the given ID maps to the given switch-case statement.
DiagnosticBuilder Diag(unsigned DiagID) const
Report a diagnostic.
ASTContext & getContext()
Retrieve the AST context that this AST reader supplements.
Definition ASTReader.h:2627
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:2201
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:1850
@ ARR_ConfigurationMismatch
The client can handle an AST file that cannot load because it's compiled configuration doesn't match ...
Definition ASTReader.h:1863
@ 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:1854
@ 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:1858
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:2661
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:2211
QualType getLocalType(ModuleFile &F, serialization::LocalTypeID LocalID)
Resolve a local type ID within a given AST file into a type.
friend class LocalDeclID
Definition ASTReader.h:443
void SetGloballyVisibleDecls(IdentifierInfo *II, const SmallVectorImpl< GlobalDeclID > &DeclIDs, SmallVectorImpl< Decl * > *Decls=nullptr)
Set the globally-visible declarations associated with the given identifier.
serialization::ModuleKind ModuleKind
Definition ASTReader.h:477
bool loadGlobalIndex()
Attempts to load the global index.
void ReadComments() override
Loads comments ranges.
SourceManager & getSourceManager() const
Definition ASTReader.h:1834
const serialization::reader::ModuleLocalLookupTable * getModuleLocalLookupTables(DeclContext *Primary) const
SourceLocation getSourceLocationForDeclID(GlobalDeclID ID)
Returns the source location for the decl ID.
void makeModuleVisible(Module *Mod, Module::NameVisibilityKind NameVisibility, SourceLocation ImportLoc)
Make the entities in the given module and any of its (non-explicit) submodules visible to name lookup...
SourceRange ReadSourceRange(ModuleFile &F, const RecordData &Record, unsigned &Idx)
Read a source range.
bool LoadExternalSpecializations(const Decl *D, bool OnlyPartial) override
Load all the external specializations for the Decl.
void finalizeForWriting()
Finalizes the AST reader's state before writing an AST file to disk.
Sema * getSema()
Retrieve the semantic analysis object used to analyze the translation unit in which the precompiled h...
Definition ASTReader.h:2639
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:2077
void StartTranslationUnit(ASTConsumer *Consumer) override
Function that will be invoked when we begin parsing a new translation unit involving this external AS...
LocalDeclID mapGlobalIDToModuleFileGlobalID(ModuleFile &M, GlobalDeclID GlobalID)
Map a global declaration ID into the declaration ID used to refer to this declaration within the give...
void resolvePendingMacro(IdentifierInfo *II, const PendingMacroInfo &PMInfo)
void ReadTentativeDefinitions(SmallVectorImpl< VarDecl * > &TentativeDefs) override
Read the set of tentative definitions known to the external Sema source.
Decl * GetExternalDecl(GlobalDeclID ID) override
Resolve a declaration ID into a declaration, potentially building a new declaration.
serialization::MacroID ReadMacroID(ModuleFile &F, const RecordDataImpl &Record, unsigned &Idx)
Reads a macro ID from the given position in a record in the given module.
GlobalDeclID ReadDeclID(ModuleFile &F, const RecordDataImpl &Record, unsigned &Idx)
Reads a declaration ID from the given position in a record in the given module.
llvm::Expected< SourceLocation::UIntTy > readSLocOffset(ModuleFile *F, unsigned Index)
Try to read the offset of the SLocEntry at the given index in the given module file.
~ASTReader() override
bool haveUnloadedSpecializations(const Decl *D) const
If we have any unloaded specialization for D.
friend class PCHValidator
Definition ASTReader.h:439
friend class serialization::ReadMethodPoolVisitor
Definition ASTReader.h:441
void CompleteRedeclChain(const Decl *D) override
If any redeclarations of D have been imported since it was last checked, this digs out those redeclar...
SourceLocation TranslateSourceLocation(ModuleFile &ModuleFile, SourceLocation Loc) const
Translate a source location from another module file's source location space into ours.
Definition ASTReader.h:2513
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:2107
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:2634
std::pair< SourceLocation, StringRef > getModuleImportLoc(int ID) override
Retrieve the module import location and module name for the given source manager entry ID.
void ReadUnusedFileScopedDecls(SmallVectorImpl< const DeclaratorDecl * > &Decls) override
Read the set of unused file-scope declarations known to the external Sema source.
void ReadReferencedSelectors(SmallVectorImpl< std::pair< Selector, SourceLocation > > &Sels) override
Read the set of referenced selectors known to the external Sema source.
Selector DecodeSelector(serialization::SelectorID Idx)
ASTReadResult ReadAST(StringRef FileName, ModuleKind Type, SourceLocation ImportLoc, unsigned ClientLoadCapabilities, ModuleFile **NewLoadedModuleFile=nullptr)
Load the AST file designated by the given file name.
StringRef getOriginalSourceFile()
Retrieve the name of the original source file name for the primary module file.
Definition ASTReader.h:2016
std::string ReadPath(ModuleFile &F, const RecordData &Record, unsigned &Idx)
friend class serialization::reader::ASTIdentifierLookupTrait
Definition ASTReader.h:440
unsigned getModuleFileID(ModuleFile *M)
Get an ID for the given module file.
Decl * getKeyDeclaration(Decl *D)
Returns the first key declaration for the given declaration.
Definition ASTReader.h:1499
bool FindExternalVisibleDeclsByName(const DeclContext *DC, DeclarationName Name, const DeclContext *OriginalDC) override
Finds all the visible declarations with a given name.
IdentifierInfo * DecodeIdentifierInfo(serialization::IdentifierID ID)
ASTReadResult
The result of reading the control block of an AST file, which can fail for various reasons.
Definition ASTReader.h:450
@ Success
The control block was read successfully.
Definition ASTReader.h:453
@ ConfigurationMismatch
The AST file was written with a different language/target configuration.
Definition ASTReader.h:470
@ OutOfDate
The AST file is out-of-date relative to its input files, and needs to be regenerated.
Definition ASTReader.h:463
@ Failure
The AST file itself appears corrupted.
Definition ASTReader.h:456
@ VersionMismatch
The AST file was written by a different version of Clang.
Definition ASTReader.h:466
@ HadErrors
The AST file has errors.
Definition ASTReader.h:473
@ Missing
The AST file was missing.
Definition ASTReader.h:459
static VersionTuple ReadVersionTuple(const RecordData &Record, unsigned &Idx)
Read a version tuple.
Token ReadToken(ModuleFile &M, const RecordDataImpl &Record, unsigned &Idx)
Reads a token out of a record.
SwitchCase * getSwitchCaseWithID(unsigned ID)
Retrieve the switch-case statement with the given ID.
serialization::IdentifierID getGlobalIdentifierID(ModuleFile &M, uint64_t LocalID)
FileID TranslateFileID(ModuleFile &F, FileID FID) const
Translate a FileID from another module file's FileID space into ours.
Definition ASTReader.h:2541
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:2165
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:2497
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:2012
ASTReadResult ReadASTCore(StringRef FileName, ModuleKind Type, SourceLocation ImportLoc, ModuleFile *ImportedBy, SmallVectorImpl< ImportedModule > &Loaded, off_t ExpectedSize, time_t ExpectedModTime, ASTFileSignature ExpectedSignature, unsigned ClientLoadCapabilities)
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:436
SmallVector< uint64_t, 64 > RecordData
Definition ASTReader.h:445
FileID ReadFileID(ModuleFile &F, const RecordDataImpl &Record, unsigned &Idx) const
Read a FileID.
Definition ASTReader.h:2535
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:1835
bool wasThisDeclarationADefinition(const FunctionDecl *FD) override
True if this function declaration was a definition before in its own module.
void FinishedDeserializing() override
Notify ASTReader that we finished the deserialization of a decl or type.
void updateOutOfDateIdentifier(const IdentifierInfo &II) override
Update an out-of-date identifier.
void ReadDefinedMacros() override
Read the set of macros defined by this external macro source.
HeaderFileInfo GetHeaderFileInfo(FileEntryRef FE) override
Read the header file information for the given file entry.
void getMemoryBufferSizes(MemoryBufferSizes &sizes) const override
Return the amount of memory used by memory buffers, breaking down by heap-backed versus mmap'ed memor...
serialization::ModuleFile ModuleFile
Definition ASTReader.h:476
bool hasGlobalIndex() const
Determine whether this AST reader has a global index.
Definition ASTReader.h:1971
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.
bool ReadFullVersionInformation(StringRef FullVersion) override
Receives the full Clang version information.
bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, StringRef ModuleFilename, StringRef SpecificModuleCachePath, bool Complain) override
Receives the header search options.
bool ReadFileSystemOptions(const FileSystemOptions &FSOpts, bool Complain) override
Receives the file system options.
void ReadModuleMapFile(StringRef ModuleMapPath) override
bool ReadLanguageOptions(const LangOptions &LangOpts, StringRef ModuleFilename, bool Complain, bool AllowCompatibleDifferences) override
Receives the language options.
bool ReadTargetOptions(const TargetOptions &TargetOpts, StringRef ModuleFilename, bool Complain, bool AllowCompatibleDifferences) override
Receives the target options.
void ReadModuleName(StringRef ModuleName) override
bool needsInputFileVisitation() override
Returns true if this ASTReaderListener wants to receive the input files of the AST file via visitInpu...
bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, StringRef ModuleFilename, bool ReadMacros, bool Complain, std::string &SuggestedPredefines) override
Receives the preprocessor options.
void readModuleFileExtension(const ModuleFileExtensionMetadata &Metadata) override
Indicates that a particular module file extension has been read.
void visitModuleFile(StringRef Filename, serialization::ModuleKind Kind) override
This is called for each AST file loaded.
bool needsSystemInputFileVisitation() override
Returns true if this ASTReaderListener wants to receive the system input files of the AST file via vi...
bool ReadDiagnosticOptions(DiagnosticOptions &DiagOpts, StringRef ModuleFilename, bool Complain) override
Receives the diagnostic options.
CompatibilityKind
For ASTs produced with different option value, signifies their level of compatibility.
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
A reference to a concept and its template args, as it appears in the code.
Definition ASTConcept.h:130
static ConceptReference * Create(const ASTContext &C, NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc, DeclarationNameInfo ConceptNameInfo, NamedDecl *FoundDecl, TemplateDecl *NamedConcept, const ASTTemplateArgumentListInfo *ArgsAsWritten)
const TypeClass * getTypePtr() const
Definition TypeLoc.h:433
A map from continuous integer ranges to some value, with a very specialized interface.
void insertOrReplace(const value_type &Val)
typename Representation::iterator iterator
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1449
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
bool hasExternalVisibleStorage() const
Whether this DeclContext has external storage containing additional declarations that are visible in ...
Definition DeclBase.h:2700
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
void setMustBuildLookupTable()
Mark that there are external lexical declarations that we need to include in our lookup table (and th...
Definition DeclBase.h:2673
bool hasExternalLexicalStorage() const
Whether this DeclContext has external storage containing additional declarations that are lexically i...
Definition DeclBase.h:2688
DeclContext * getPrimaryContext()
getPrimaryContext - There may be many different declarations of the same entity (including forward de...
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition DeclBase.h:2373
void setHasExternalLexicalStorage(bool ES=true) const
State whether this DeclContext has external storage for declarations lexically in this context.
Definition DeclBase.h:2694
bool isDeclInLexicalTraversal(const Decl *D) const
Determine whether the given declaration is stored in the list of declarations lexically within this c...
Definition DeclBase.h:2714
decl_iterator decls_begin() const
unsigned getModuleFileIndex() const
Definition DeclID.h:125
DeclID getRawValue() const
Definition DeclID.h:115
unsigned getLocalDeclIndex() const
uint64_t DeclID
An ID number that refers to a declaration in an AST file.
Definition DeclID.h:108
TypeSpecifierType TST
Definition DeclSpec.h: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:3160
A reference to a FileEntry that includes the name of the file as it was accessed by the FileManager's...
Definition FileEntry.h:57
time_t getModificationTime() const
Definition FileEntry.h:354
off_t getSize() const
Definition FileEntry.h:346
StringRef getName() const
The name of this FileEntry.
Definition FileEntry.h:61
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
bool isValid() const
bool isInvalid() const
Implements support for file system lookup, file system caching, and directory search management.
Definition FileManager.h:53
llvm::vfs::FileSystem & getVirtualFileSystem() const
llvm::ErrorOr< std::unique_ptr< llvm::MemoryBuffer > > getBufferForFile(FileEntryRef Entry, bool isVolatile=false, bool RequiresNullTerminator=true, std::optional< int64_t > MaybeLimit=std::nullopt, bool IsText=true)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful,...
OptionalFileEntryRef getOptionalFileRef(StringRef Filename, bool OpenFile=false, bool CacheFailure=true)
Get a FileEntryRef if it exists, without doing anything on error.
FileEntryRef getVirtualFileRef(StringRef Filename, off_t Size, time_t ModificationTime)
Retrieve a file entry for a "virtual" file that acts as if there were a file with the given name on d...
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:2000
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5315
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5604
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 module cache path with the context hash (unless suppressed).
One of these records is kept for each identifier that is lexed.
unsigned getBuiltinID() const
Return a value indicating whether this is a builtin function.
bool isCPlusPlusOperatorKeyword() const
tok::TokenKind getTokenID() const
If this is a source-language token (e.g.
bool hadMacroDefinition() const
Returns true if this identifier was #defined to some value at any moment.
void setIsPoisoned(bool Value=true)
setIsPoisoned - Mark this identifier as poisoned.
bool isFromAST() const
Return true if the identifier in its current state was loaded from an AST file.
bool isPoisoned() const
Return true if this token has been poisoned.
bool hasRevertedTokenIDToIdentifier() const
True if revertTokenIDToIdentifier() was called.
tok::NotableIdentifierKind getNotableIdentifierID() const
void setOutOfDate(bool OOD)
Set whether the information for this identifier is out of date with respect to the external source.
tok::ObjCKeywordKind getObjCKeywordID() const
Return the Objective-C keyword ID for the this identifier.
void setObjCOrBuiltinID(unsigned ID)
void revertTokenIDToIdentifier()
Revert TokenID to tok::identifier; used for GNU libstdc++ 4.2 compatibility.
bool isOutOfDate() const
Determine whether the information for this identifier is out of date with respect to the external sou...
void setChangedSinceDeserialization()
Note that this identifier has changed since it was loaded from an AST file.
void * getFETokenInfo() const
Get and set FETokenInfo.
StringRef getName() const
Return the actual identifier string.
bool isExtensionToken() const
get/setExtension - Initialize information about whether or not this language token is an extension.
An iterator that walks over all of the known identifiers in the lookup table.
IdentifierResolver - Keeps track of shadowed decls on enclosing scopes.
void RemoveDecl(NamedDecl *D)
RemoveDecl - Unlink the decl from its shadowed decl chain.
Implements an efficient mapping from strings to IdentifierInfo nodes.
llvm::MemoryBuffer * lookupPCM(llvm::StringRef Filename) const
Get a pointer to the pCM if it exists; else nullptr.
Record the location of an inclusion directive, such as an #include or #import statement.
InclusionKind
The kind of inclusion directives known to the preprocessor.
Represents a field injected from an anonymous union/struct into the parent scope.
Definition Decl.h:3467
Wrapper for source info for injected class names of class templates.
Definition TypeLoc.h:872
void setAmpLoc(SourceLocation Loc)
Definition TypeLoc.h: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.
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:144
StringRef getTopLevelModuleName() const
Retrieve the name of the top-level module.
Definition Module.h:732
void addRequirement(StringRef Feature, bool RequiredState, const LangOptions &LangOpts, const TargetInfo &Target)
Add the given feature requirement to the list of features required by this module.
Definition Module.cpp:313
unsigned InferSubmodules
Whether we should infer submodules for this module based on the headers.
Definition Module.h:406
std::vector< std::string > ConfigMacros
The set of "configuration macros", which are macros that (intentionally) change how this module is bu...
Definition Module.h:528
unsigned IsUnimportable
Whether this module has declared itself unimportable, either because it's missing a requirement from ...
Definition Module.h:361
NameVisibilityKind NameVisibility
The visibility of names within this particular module.
Definition Module.h:451
NameVisibilityKind
Describes the visibility of the various names within a particular module.
Definition Module.h:443
@ Hidden
All of the names in this module are hidden.
Definition Module.h:445
@ AllVisible
All of the names in this module are visible.
Definition Module.h:447
SourceLocation DefinitionLoc
The location of the module definition.
Definition Module.h:150
SmallVector< UnresolvedHeaderDirective, 1 > MissingHeaders
Headers that are mentioned in the module map file but could not be found on the file system.
Definition Module.h:341
ModuleKind Kind
The kind of this module.
Definition Module.h:189
void addTopHeaderFilename(StringRef Filename)
Add a top-level header filename associated with this module.
Definition Module.h:772
bool isUnimportable() const
Determine whether this module has been declared unimportable.
Definition Module.h:563
void setASTFile(OptionalFileEntryRef File)
Set the serialized AST file for the top-level module of this module.
Definition Module.h:742
unsigned IsSystem
Whether this is a "system" module (which assumes that all headers in it are system headers).
Definition Module.h:389
std::string Name
The name of this module.
Definition Module.h:147
unsigned IsExternC
Whether this is an 'extern "C"' module (which implicitly puts all headers in it within an 'extern "C"...
Definition Module.h:395
unsigned ModuleMapIsPrivate
Whether this module came from a "private" module map, found next to a regular (public) module map.
Definition Module.h:434
llvm::SmallVector< LinkLibrary, 2 > LinkLibraries
The set of libraries or frameworks to link against when an entity from this module is used.
Definition Module.h:520
SmallVector< UnresolvedExportDecl, 2 > UnresolvedExports
The set of export declarations that have yet to be resolved.
Definition Module.h:489
std::optional< Header > getUmbrellaHeaderAsWritten() const
Retrieve the umbrella header as written.
Definition Module.h:756
SmallVector< Requirement, 2 > Requirements
The set of language features required to use this module.
Definition Module.h:352
bool isHeaderLikeModule() const
Is this module have similar semantics as headers.
Definition Module.h:648
OptionalDirectoryEntryRef Directory
The build directory of this module.
Definition Module.h:198
unsigned NamedModuleHasInit
Whether this C++20 named modules doesn't need an initializer.
Definition Module.h:439
StringRef getPrimaryModuleInterfaceName() const
Get the primary module interface name from a partition.
Definition Module.h:687
unsigned ConfigMacrosExhaustive
Whether the set of configuration macros is exhaustive.
Definition Module.h:424
std::string PresumedModuleMapFile
The presumed file name for the module map defining this module.
Definition Module.h:202
ASTFileSignature Signature
The module signature.
Definition Module.h:208
bool isGlobalModule() const
Does this Module scope describe a fragment of the global module within some C++ module.
Definition Module.h:239
unsigned InferExportWildcard
Whether, when inferring submodules, the inferr submodules should export all modules they import (e....
Definition Module.h:416
void getExportedModules(SmallVectorImpl< Module * > &Exported) const
Appends this module's list of exported modules to Exported.
Definition Module.cpp:383
std::vector< UnresolvedConflict > UnresolvedConflicts
The list of conflicts for which the module-id has not yet been resolved.
Definition Module.h:541
unsigned IsFromModuleFile
Whether this module was loaded from a module file.
Definition Module.h:376
llvm::PointerIntPair< Module *, 1, bool > ExportDecl
Describes an exported module.
Definition Module.h:468
std::optional< DirectoryName > getUmbrellaDirAsWritten() const
Retrieve the umbrella directory as written.
Definition Module.h:748
std::string ExportAsModule
The module through which entities defined in this module will eventually be exposed,...
Definition Module.h:218
unsigned IsAvailable
Whether this module is available in the current translation unit.
Definition Module.h:372
unsigned InferExplicitSubmodules
Whether, when inferring submodules, the inferred submodules should be explicit.
Definition Module.h:411
OptionalFileEntryRef getASTFile() const
The serialized AST file for this module, if one was created.
Definition Module.h:737
std::vector< Conflict > Conflicts
The list of conflicts.
Definition Module.h:553
This represents a decl that may have a name.
Definition Decl.h:274
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
virtual void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const
Appends a human-readable name for this declaration into the given stream.
Definition Decl.cpp: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.
bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, StringRef ModuleFilename, StringRef SpecificModuleCachePath, bool Complain) override
Receives the header search options.
void ReadCounter(const serialization::ModuleFile &M, uint32_t Value) override
Receives COUNTER value.
bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, StringRef ModuleFilename, bool ReadMacros, bool Complain, std::string &SuggestedPredefines) override
Receives the preprocessor options.
bool ReadCodeGenOptions(const CodeGenOptions &CGOpts, StringRef ModuleFilename, bool Complain, bool AllowCompatibleDifferences) override
Receives the codegen options.
bool ReadTargetOptions(const TargetOptions &TargetOpts, StringRef ModuleFilename, bool Complain, bool AllowCompatibleDifferences) override
Receives the target options.
void setEllipsisLoc(SourceLocation Loc)
Definition TypeLoc.h: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:1790
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:5332
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:1510
void addExternalSource(IntrusiveRefCntPtr< ExternalSemaSource > E)
Registers an external source.
Definition Sema.cpp:655
IdentifierResolver IdResolver
Definition Sema.h:3511
PragmaMsStackAction
Definition Sema.h:1841
ASTReaderListenter implementation to set SuggestedPredefines of ASTReader which is required to use a ...
Definition ASTReader.h:362
bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, StringRef ModuleFilename, bool ReadMacros, bool Complain, std::string &SuggestedPredefines) override
Receives the preprocessor options.
Encodes a location in the source.
static SourceLocation getFromRawEncoding(UIntTy Encoding)
Turn a raw encoding of a SourceLocation object into a real SourceLocation.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
This class handles loading and caching of source files into memory.
SourceLocation getFileLoc(SourceLocation Loc) const
Given Loc, if it is a macro location return the expansion location or the spelling location,...
bool isBeforeInTranslationUnit(SourceLocation LHS, SourceLocation RHS) const
Determines the order of 2 source locations in the translation unit.
A trivial tuple used to represent a source range.
One instance of this struct is kept for every file loaded or used.
OptionalFileEntryRef ContentsEntry
References the file which the contents were actually loaded from.
std::optional< llvm::MemoryBufferRef > getBufferIfLoaded() const
Return the buffer, only if it has been loaded.
unsigned BufferOverridden
Indicates whether the buffer itself was provided to override the actual file contents.
OptionalFileEntryRef OrigEntry
Reference to the file entry representing this ContentCache.
Information about a FileID, basically just the logical file that it represents and include stack info...
void setHasLineDirectives()
Set the flag that indicates that this FileID has line table entries associated with it.
Stmt - This represents one statement.
Definition Stmt.h: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:3364
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:8359
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:1839
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9218
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3562
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:395
void * IdentifierLookupTable
A pointer to an on-disk hash table of opaque type IdentifierHashTable.
Definition ModuleFile.h:350
void * SelectorLookupTable
A pointer to an on-disk hash table of opaque type ASTSelectorLookupTable.
Definition ModuleFile.h:458
std::vector< std::unique_ptr< ModuleFileExtensionReader > > ExtensionReaders
The list of extension readers that are attached to this module file.
Definition ModuleFile.h:261
SourceLocation DirectImportLoc
The source location where the module was explicitly or implicitly imported in the local translation u...
Definition ModuleFile.h:251
StringRef Data
The serialized bitstream data for this file.
Definition ModuleFile.h:237
const serialization::ObjCCategoriesInfo * ObjCCategoriesMap
Array of category list location information within this module file, sorted by the definition ID.
Definition ModuleFile.h:486
int SLocEntryBaseID
The base ID in the source manager's view of this module.
Definition ModuleFile.h:314
serialization::IdentifierID BaseIdentifierID
Base identifier ID for identifiers local to this module.
Definition ModuleFile.h:340
serialization::PreprocessedEntityID BasePreprocessedEntityID
Base preprocessed entity ID for preprocessed entities local to this module.
Definition ModuleFile.h:393
serialization::TypeID BaseTypeIndex
Base type ID for types local to this module as represented in the global type ID space.
Definition ModuleFile.h:506
unsigned LocalNumObjCCategoriesInMap
The number of redeclaration info entries in ObjCCategoriesMap.
Definition ModuleFile.h:489
uint64_t MacroOffsetsBase
Base file offset for the offsets in MacroOffsets.
Definition ModuleFile.h:367
const llvm::support::unaligned_uint64_t * InputFileOffsets
Relative offsets for all of the input file entries in the AST file.
Definition ModuleFile.h:276
std::vector< unsigned > PreloadIdentifierOffsets
Offsets of identifiers that we're going to preload within IdentifierTableData.
Definition ModuleFile.h:354
unsigned LocalNumIdentifiers
The number of identifiers in this AST file.
Definition ModuleFile.h:330
llvm::BitstreamCursor DeclsCursor
DeclsCursor - This is a cursor to the start of the DECLTYPES_BLOCK block.
Definition ModuleFile.h:465
const unsigned char * IdentifierTableData
Actual data for the on-disk hash table of identifiers.
Definition ModuleFile.h:346
uint64_t SLocEntryOffsetsBase
Base file offset for the offsets in SLocEntryOffsets.
Definition ModuleFile.h:321
llvm::BitstreamCursor InputFilesCursor
The cursor to the start of the input-files block.
Definition ModuleFile.h:270
std::vector< InputFile > InputFilesLoaded
The input files that have been loaded from this AST file.
Definition ModuleFile.h:279
serialization::SelectorID BaseSelectorID
Base selector ID for selectors local to this module.
Definition ModuleFile.h:443
llvm::SetVector< ModuleFile * > ImportedBy
List of modules which depend on this module.
Definition ModuleFile.h:514
const char * HeaderFileInfoTableData
Actual data for the on-disk hash table of header file information.
Definition ModuleFile.h:414
SourceLocation ImportLoc
The source location where this module was first imported.
Definition ModuleFile.h:254
const serialization::unaligned_decl_id_t * FileSortedDecls
Array of file-level DeclIDs sorted by file.
Definition ModuleFile.h:481
const uint32_t * SLocEntryOffsets
Offsets for all of the source location entries in the AST file.
Definition ModuleFile.h:325
llvm::BitstreamCursor MacroCursor
The cursor to the start of the preprocessor block, which stores all of the macro definitions.
Definition ModuleFile.h:360
FileID OriginalSourceFileID
The file ID for the original source file that was used to build this AST file.
Definition ModuleFile.h:183
FileEntryRef File
The file entry for the module file.
Definition ModuleFile.h:200
std::string ActualOriginalSourceFileName
The actual original source file name that was used to build this AST file.
Definition ModuleFile.h:179
uint64_t PreprocessorDetailStartOffset
The offset of the start of the preprocessor detail cursor.
Definition ModuleFile.h:389
std::vector< InputFileInfo > InputFileInfosLoaded
The input file infos that have been loaded from this AST file.
Definition ModuleFile.h:282
unsigned LocalNumSubmodules
The number of submodules in this module.
Definition ModuleFile.h:423
SourceLocation FirstLoc
The first source location in this module.
Definition ModuleFile.h:257
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:208
uint64_t SourceManagerBlockStartOffset
The bit offset to the start of the SOURCE_MANAGER_BLOCK.
Definition ModuleFile.h:308
bool DidReadTopLevelSubmodule
Whether the top-level module has been read from the AST file.
Definition ModuleFile.h:197
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:175
bool isModule() const
Is this a module file for a module (rather than a PCH or similar).
Definition ModuleFile.h:532
bool HasTimestamps
Whether timestamps are included in this module file.
Definition ModuleFile.h:194
uint64_t InputFilesOffsetBase
Absolute offset of the start of the input-files block.
Definition ModuleFile.h:273
llvm::BitstreamCursor SLocEntryCursor
Cursor used to read source location entries.
Definition ModuleFile.h:305
bool RelocatablePCH
Whether this precompiled header is a relocatable PCH file.
Definition ModuleFile.h:188
const uint32_t * SelectorOffsets
Offsets into the selector lookup table's data array where each selector resides.
Definition ModuleFile.h:440
unsigned BaseDeclIndex
Base declaration index in ASTReader for declarations local to this module.
Definition ModuleFile.h:478
unsigned LocalNumSLocEntries
The number of source location entries in this AST file.
Definition ModuleFile.h:311
void * HeaderFileInfoTable
The on-disk hash table that contains information about each of the header files.
Definition ModuleFile.h:418
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:240
serialization::SubmoduleID BaseSubmoduleID
Base submodule ID for submodules local to this module.
Definition ModuleFile.h:426
uint64_t SizeInBits
The size of this file, in bits.
Definition ModuleFile.h:228
const UnalignedUInt64 * TypeOffsets
Offset of each type within the bitstream, indexed by the type ID, or the representation of a Type*.
Definition ModuleFile.h:502
uint64_t GlobalBitOffset
The global bit offset (or base) of this module.
Definition ModuleFile.h:231
bool StandardCXXModule
Whether this module file is a standard C++ module.
Definition ModuleFile.h:191
unsigned LocalNumTypes
The number of types in this AST file.
Definition ModuleFile.h:498
StringRef ModuleOffsetMap
The module offset map data for this file.
Definition ModuleFile.h:265
const PPSkippedRange * PreprocessedSkippedRangeOffsets
Definition ModuleFile.h:401
std::string FileName
The file name of the module file.
Definition ModuleFile.h:160
uint64_t InputFilesValidationTimestamp
If non-zero, specifies the time when we last validated input files.
Definition ModuleFile.h:292
llvm::BitstreamCursor PreprocessorDetailCursor
The cursor to the start of the (optional) detailed preprocessing record block.
Definition ModuleFile.h:386
SourceLocation::UIntTy SLocEntryBaseOffset
The base offset in the source manager's view of this module.
Definition ModuleFile.h:317
const DeclOffset * DeclOffsets
Offset of each declaration within the bitstream, indexed by the declaration ID (-1).
Definition ModuleFile.h:475
uint64_t MacroStartOffset
The offset of the start of the set of defined macros.
Definition ModuleFile.h:380
ASTFileSignature Signature
The signature of the module file, which may be used instead of the size and modification time to iden...
Definition ModuleFile.h:204
unsigned LocalNumMacros
The number of macros in this AST file.
Definition ModuleFile.h:363
const unsigned char * SelectorLookupTableData
A pointer to the character data that comprises the selector table.
Definition ModuleFile.h:451
void dump()
Dump debugging output for this module.
unsigned LocalNumDecls
The number of declarations in this AST file.
Definition ModuleFile.h:471
unsigned LocalNumHeaderFileInfos
The number of local HeaderFileInfo structures.
Definition ModuleFile.h:407
llvm::BitVector SearchPathUsage
The bit vector denoting usage of each header search entry (true = used).
Definition ModuleFile.h:211
InputFilesValidation InputFilesValidationStatus
Captures the high-level result of validating input files.
Definition ModuleFile.h:299
unsigned Generation
The generation of which this module file is a part.
Definition ModuleFile.h:221
const uint32_t * IdentifierOffsets
Offsets into the identifier table data.
Definition ModuleFile.h:337
ContinuousRangeMap< uint32_t, int, 2 > SelectorRemap
Remapping table for selector IDs in this module.
Definition ModuleFile.h:446
const uint32_t * MacroOffsets
Offsets of macros in the preprocessor block.
Definition ModuleFile.h:374
uint64_t ASTBlockStartOffset
The bit offset of the AST block of this module.
Definition ModuleFile.h:234
ContinuousRangeMap< uint32_t, int, 2 > SubmoduleRemap
Remapping table for submodule IDs in this module.
Definition ModuleFile.h:429
llvm::BitVector VFSUsage
The bit vector denoting usage of each VFS entry (true = used).
Definition ModuleFile.h:214
uint64_t DeclsBlockStartOffset
The offset to the start of the DECLTYPES_BLOCK block.
Definition ModuleFile.h:468
SmallVector< uint64_t, 8 > PragmaDiagMappings
Diagnostic IDs and their mappings that the user changed.
Definition ModuleFile.h:511
unsigned BasePreprocessedSkippedRangeID
Base ID for preprocessed skipped ranges local to this module.
Definition ModuleFile.h:399
unsigned LocalNumSelectors
The number of selectors new to this file.
Definition ModuleFile.h:436
ModuleKind Kind
The type of this module.
Definition ModuleFile.h:157
std::string ModuleName
The name of the module.
Definition ModuleFile.h:163
serialization::MacroID BaseMacroID
Base macro ID for macros local to this module.
Definition ModuleFile.h:377
SmallVector< uint64_t, 1 > ObjCCategories
The Objective-C category lists for categories known to this module.
Definition ModuleFile.h:493
std::string BaseDirectory
The base directory of the module.
Definition ModuleFile.h:166
llvm::SmallVector< ModuleFile *, 16 > TransitiveImports
List of modules which this modules dependent on.
Definition ModuleFile.h:525
Manages the set of modules loaded by an AST reader.
AddModuleResult
The result of attempting to add a new module.
@ Missing
The module file is missing.
@ OutOfDate
The module file is out-of-date.
@ NewlyLoaded
The module file was just loaded in response to this call.
@ AlreadyLoaded
The module file had already been loaded.
llvm::iterator_range< SmallVectorImpl< ModuleFile * >::const_iterator > pch_modules() const
A range covering the PCH and preamble module files loaded.
ModuleReverseIterator rbegin()
Reverse iterator to traverse all loaded modules.
unsigned size() const
Number of modules loaded.
Source range/offset of a preprocessed entity.
RawLocEncoding getBegin() const
Source range of a skipped preprocessor region.
RawLocEncoding getBegin() const
ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel, unsigned PriorGeneration)
ArrayRef< ObjCMethodDecl * > getInstanceMethods() const
Retrieve the instance methods found by this visitor.
ArrayRef< ObjCMethodDecl * > getFactoryMethods() const
Retrieve the instance methods found by this visitor.
static TypeIdx fromTypeID(TypeID ID)
32 aligned uint64_t in the AST file.
static std::pair< unsigned, unsigned > ReadKeyDataLength(const unsigned char *&d)
void ReadDataIntoImpl(const unsigned char *d, unsigned DataLen, data_type_builder &Val)
DeclarationNameKey ReadKeyBase(const unsigned char *&d)
internal_key_type ReadKey(const unsigned char *d, unsigned)
void ReadDataInto(internal_key_type, const unsigned char *d, unsigned DataLen, data_type_builder &Val)
static std::pair< unsigned, unsigned > ReadKeyDataLength(const unsigned char *&d)
static hash_value_type ComputeHash(const internal_key_type &a)
static internal_key_type ReadKey(const unsigned char *d, unsigned n)
Class that performs lookup for an identifier stored in an AST file.
IdentifierID ReadIdentifierID(const unsigned char *d)
data_type ReadData(const internal_key_type &k, const unsigned char *d, unsigned DataLen)
Class that performs lookup for a selector's entries in the global method pool stored in an AST file.
internal_key_type ReadKey(const unsigned char *d, unsigned)
data_type ReadData(Selector, const unsigned char *d, unsigned DataLen)
static std::pair< unsigned, unsigned > ReadKeyDataLength(const unsigned char *&d)
static hash_value_type ComputeHash(Selector Sel)
static std::pair< unsigned, unsigned > ReadKeyDataLength(const unsigned char *&d)
internal_key_type GetInternalKey(external_key_type ekey)
bool EqualKey(internal_key_ref a, internal_key_ref b)
static hash_value_type ComputeHash(internal_key_ref ikey)
data_type ReadData(internal_key_ref, const unsigned char *d, unsigned DataLen)
static internal_key_type ReadKey(const unsigned char *d, unsigned)
Class that performs lookup to specialized decls.
void ReadDataInto(internal_key_type, const unsigned char *d, unsigned DataLen, data_type_builder &Val)
static std::pair< unsigned, unsigned > ReadKeyDataLength(const unsigned char *&d)
internal_key_type ReadKey(const unsigned char *d, unsigned)
std::pair< DeclarationName, const Module * > external_key_type
void ReadDataInto(internal_key_type, const unsigned char *d, unsigned DataLen, data_type_builder &Val)
std::pair< DeclarationNameKey, unsigned > internal_key_type
internal_key_type ReadKey(const unsigned char *d, unsigned)
static hash_value_type ComputeHash(const internal_key_type &Key)
static internal_key_type GetInternalKey(const external_key_type &Key)
#define bool
Definition gpuintrin.h:32
PredefinedTypeIDs
Predefined type IDs.
CtorInitializerType
The different kinds of data that can occur in a CtorInitializer.
const unsigned NUM_PREDEF_TYPE_IDS
The number of predefined type IDs that are reserved for the PREDEF_TYPE_* constants.
const unsigned NumSpecialTypeIDs
The number of special type IDs.
TypeCode
Record codes for each kind of type.
@ PREDEF_TYPE_LONG_ACCUM_ID
The 'long _Accum' type.
@ PREDEF_TYPE_SAMPLER_ID
OpenCL sampler type.
@ PREDEF_TYPE_INT128_ID
The '__int128_t' type.
@ PREDEF_TYPE_CHAR32_ID
The C++ 'char32_t' type.
@ PREDEF_TYPE_SAT_SHORT_ACCUM_ID
The '_Sat short _Accum' type.
@ PREDEF_TYPE_IBM128_ID
The '__ibm128' type.
@ PREDEF_TYPE_SHORT_FRACT_ID
The 'short _Fract' type.
@ PREDEF_TYPE_AUTO_RREF_DEDUCT
The "auto &&" deduction type.
@ PREDEF_TYPE_BOUND_MEMBER
The placeholder type for bound member functions.
@ PREDEF_TYPE_LONGLONG_ID
The (signed) 'long long' type.
@ PREDEF_TYPE_FRACT_ID
The '_Fract' type.
@ PREDEF_TYPE_ARC_UNBRIDGED_CAST
ARC's unbridged-cast placeholder type.
@ PREDEF_TYPE_USHORT_FRACT_ID
The 'unsigned short _Fract' type.
@ PREDEF_TYPE_SAT_ULONG_FRACT_ID
The '_Sat unsigned long _Fract' type.
@ PREDEF_TYPE_BOOL_ID
The 'bool' or '_Bool' type.
@ PREDEF_TYPE_SAT_LONG_ACCUM_ID
The '_Sat long _Accum' type.
@ PREDEF_TYPE_SAT_LONG_FRACT_ID
The '_Sat long _Fract' type.
@ PREDEF_TYPE_SAT_SHORT_FRACT_ID
The '_Sat short _Fract' type.
@ PREDEF_TYPE_CHAR_U_ID
The 'char' type, when it is unsigned.
@ PREDEF_TYPE_RESERVE_ID_ID
OpenCL reserve_id type.
@ PREDEF_TYPE_SAT_ACCUM_ID
The '_Sat _Accum' type.
@ PREDEF_TYPE_BUILTIN_FN
The placeholder type for builtin functions.
@ PREDEF_TYPE_SHORT_ACCUM_ID
The 'short _Accum' type.
@ PREDEF_TYPE_FLOAT_ID
The 'float' type.
@ PREDEF_TYPE_QUEUE_ID
OpenCL queue type.
@ PREDEF_TYPE_INT_ID
The (signed) 'int' type.
@ PREDEF_TYPE_OBJC_SEL
The ObjC 'SEL' type.
@ PREDEF_TYPE_BFLOAT16_ID
The '__bf16' type.
@ PREDEF_TYPE_WCHAR_ID
The C++ 'wchar_t' type.
@ PREDEF_TYPE_UCHAR_ID
The 'unsigned char' type.
@ PREDEF_TYPE_UACCUM_ID
The 'unsigned _Accum' type.
@ PREDEF_TYPE_SCHAR_ID
The 'signed char' type.
@ PREDEF_TYPE_CHAR_S_ID
The 'char' type, when it is signed.
@ PREDEF_TYPE_NULLPTR_ID
The type of 'nullptr'.
@ PREDEF_TYPE_ULONG_FRACT_ID
The 'unsigned long _Fract' type.
@ PREDEF_TYPE_FLOAT16_ID
The '_Float16' type.
@ PREDEF_TYPE_UINT_ID
The 'unsigned int' type.
@ PREDEF_TYPE_FLOAT128_ID
The '__float128' type.
@ PREDEF_TYPE_OBJC_ID
The ObjC 'id' type.
@ PREDEF_TYPE_CHAR16_ID
The C++ 'char16_t' type.
@ PREDEF_TYPE_ARRAY_SECTION
The placeholder type for an array section.
@ PREDEF_TYPE_ULONGLONG_ID
The 'unsigned long long' type.
@ PREDEF_TYPE_SAT_UFRACT_ID
The '_Sat unsigned _Fract' type.
@ PREDEF_TYPE_USHORT_ID
The 'unsigned short' type.
@ PREDEF_TYPE_SHORT_ID
The (signed) 'short' type.
@ PREDEF_TYPE_OMP_ARRAY_SHAPING
The placeholder type for OpenMP array shaping operation.
@ PREDEF_TYPE_DEPENDENT_ID
The placeholder type for dependent types.
@ PREDEF_TYPE_LONGDOUBLE_ID
The 'long double' type.
@ PREDEF_TYPE_DOUBLE_ID
The 'double' type.
@ PREDEF_TYPE_UINT128_ID
The '__uint128_t' type.
@ PREDEF_TYPE_HALF_ID
The OpenCL 'half' / ARM NEON __fp16 type.
@ PREDEF_TYPE_VOID_ID
The void type.
@ PREDEF_TYPE_SAT_USHORT_FRACT_ID
The '_Sat unsigned short _Fract' type.
@ PREDEF_TYPE_ACCUM_ID
The '_Accum' type.
@ PREDEF_TYPE_SAT_FRACT_ID
The '_Sat _Fract' type.
@ PREDEF_TYPE_NULL_ID
The NULL type.
@ PREDEF_TYPE_USHORT_ACCUM_ID
The 'unsigned short _Accum' type.
@ PREDEF_TYPE_CHAR8_ID
The C++ 'char8_t' type.
@ PREDEF_TYPE_UFRACT_ID
The 'unsigned _Fract' type.
@ PREDEF_TYPE_OVERLOAD_ID
The placeholder type for overloaded function sets.
@ PREDEF_TYPE_INCOMPLETE_MATRIX_IDX
A placeholder type for incomplete matrix index operations.
@ PREDEF_TYPE_UNRESOLVED_TEMPLATE
The placeholder type for unresolved templates.
@ PREDEF_TYPE_SAT_USHORT_ACCUM_ID
The '_Sat unsigned short _Accum' type.
@ PREDEF_TYPE_LONG_ID
The (signed) 'long' type.
@ PREDEF_TYPE_SAT_ULONG_ACCUM_ID
The '_Sat unsigned long _Accum' type.
@ PREDEF_TYPE_LONG_FRACT_ID
The 'long _Fract' type.
@ PREDEF_TYPE_UNKNOWN_ANY
The 'unknown any' placeholder type.
@ PREDEF_TYPE_OMP_ITERATOR
The placeholder type for OpenMP iterator expression.
@ PREDEF_TYPE_PSEUDO_OBJECT
The pseudo-object placeholder type.
@ PREDEF_TYPE_OBJC_CLASS
The ObjC 'Class' type.
@ PREDEF_TYPE_ULONG_ID
The 'unsigned long' type.
@ PREDEF_TYPE_SAT_UACCUM_ID
The '_Sat unsigned _Accum' type.
@ PREDEF_TYPE_CLK_EVENT_ID
OpenCL clk event type.
@ PREDEF_TYPE_EVENT_ID
OpenCL event type.
@ PREDEF_TYPE_ULONG_ACCUM_ID
The 'unsigned long _Accum' type.
@ PREDEF_TYPE_AUTO_DEDUCT
The "auto" deduction type.
@ DECL_CXX_BASE_SPECIFIERS
A record containing CXXBaseSpecifiers.
@ DECL_CONTEXT_TU_LOCAL_VISIBLE
A record that stores the set of declarations that are only visible to the TU.
@ DECL_CONTEXT_LEXICAL
A record that stores the set of declarations that are lexically stored within a given DeclContext.
@ DECL_CXX_CTOR_INITIALIZERS
A record containing CXXCtorInitializers.
@ DECL_CONTEXT_MODULE_LOCAL_VISIBLE
A record containing the set of declarations that are only visible from DeclContext in the same module...
@ DECL_CONTEXT_VISIBLE
A record that stores the set of declarations that are visible from a given DeclContext.
@ TYPE_EXT_QUAL
An ExtQualType record.
@ SPECIAL_TYPE_OBJC_SEL_REDEFINITION
Objective-C "SEL" redefinition type.
@ SPECIAL_TYPE_UCONTEXT_T
C ucontext_t typedef type.
@ SPECIAL_TYPE_JMP_BUF
C jmp_buf typedef type.
@ SPECIAL_TYPE_FILE
C FILE typedef type.
@ SPECIAL_TYPE_SIGJMP_BUF
C sigjmp_buf typedef type.
@ SPECIAL_TYPE_OBJC_CLASS_REDEFINITION
Objective-C "Class" redefinition type.
@ SPECIAL_TYPE_CF_CONSTANT_STRING
CFConstantString type.
@ SPECIAL_TYPE_OBJC_ID_REDEFINITION
Objective-C "id" redefinition type.
Defines the clang::TargetInfo interface.
CharacteristicKind
Indicates whether a file or directory holds normal user code, system code, or system code which is im...
internal::Matcher< T > findAll(const internal::Matcher< T > &Matcher)
Matches if the node or any descendant matches.
@ ModuleFile
The module file (.pcm). Required.
unsigned kind
All of the diagnostics that can be emitted by the frontend.
Severity
Enum values that allow the client to map NOTEs, WARNINGs, and EXTENSIONs to either Ignore (nothing),...
@ Warning
Present this diagnostic as a warning.
@ Error
Present this diagnostic as an error.
IncludeDirGroup
IncludeDirGroup - Identifies the group an include Entry belongs to, representing its relative positiv...
std::variant< struct RequiresDecl, struct HeaderDecl, struct UmbrellaDirDecl, struct ModuleDecl, struct ExcludeDecl, struct ExportDecl, struct ExportAsDecl, struct ExternModuleDecl, struct UseDecl, struct LinkDecl, struct ConfigMacrosDecl, struct ConflictDecl > Decl
All declarations that can appear in a module declaration.
llvm::OnDiskChainedHashTable< ASTSelectorLookupTrait > ASTSelectorLookupTable
The on-disk hash table used for the global method pool.
llvm::OnDiskChainedHashTable< HeaderFileInfoTrait > HeaderFileInfoLookupTable
The on-disk hash table used for known header files.
llvm::OnDiskIterableChainedHashTable< ASTIdentifierLookupTrait > ASTIdentifierLookupTable
The on-disk hash table used to contain information about all of the identifiers in the program.
@ EXTENSION_METADATA
Metadata describing this particular extension.
@ SUBMODULE_EXCLUDED_HEADER
Specifies a header that has been explicitly excluded from this submodule.
@ SUBMODULE_TOPHEADER
Specifies a top-level header that falls into this (sub)module.
@ SUBMODULE_PRIVATE_TEXTUAL_HEADER
Specifies a header that is private to this submodule but must be textually included.
@ SUBMODULE_HEADER
Specifies a header that falls into this (sub)module.
@ SUBMODULE_EXPORT_AS
Specifies the name of the module that will eventually re-export the entities in this module.
@ SUBMODULE_UMBRELLA_DIR
Specifies an umbrella directory.
@ SUBMODULE_UMBRELLA_HEADER
Specifies the umbrella header used to create this module, if any.
@ SUBMODULE_METADATA
Metadata for submodules as a whole.
@ SUBMODULE_REQUIRES
Specifies a required feature.
@ SUBMODULE_PRIVATE_HEADER
Specifies a header that is private to this submodule.
@ SUBMODULE_IMPORTS
Specifies the submodules that are imported by this submodule.
@ SUBMODULE_CONFLICT
Specifies a conflict with another module.
@ SUBMODULE_INITIALIZERS
Specifies some declarations with initializers that must be emitted to initialize the module.
@ SUBMODULE_DEFINITION
Defines the major attributes of a submodule, including its name and parent.
@ SUBMODULE_LINK_LIBRARY
Specifies a library or framework to link against.
@ SUBMODULE_CONFIG_MACRO
Specifies a configuration macro for this module.
@ SUBMODULE_EXPORTS
Specifies the submodules that are re-exported from this submodule.
@ SUBMODULE_TEXTUAL_HEADER
Specifies a header that is part of the module but must be textually included.
@ SUBMODULE_AFFECTING_MODULES
Specifies affecting modules that were not imported.
uint32_t SelectorID
An ID number that refers to an ObjC selector in an AST file.
@ 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:3828
@ 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.
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:2731
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:5928
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:58
static constexpr size_t size
Definition Module.h:61
static ASTFileSignature create(std::array< uint8_t, 20 > Bytes)
Definition Module.h:81
static ASTFileSignature createDummy()
Definition Module.h:91
Represents an explicit template argument list in C++, e.g., the "<int>" in "sort<int>".
static const ASTTemplateArgumentListInfo * Create(const ASTContext &C, const TemplateArgumentListInfo &List)
bool ParseAllComments
Treat ordinary comments as documentation comments.
BlockCommandNamesTy BlockCommandNames
Command names to treat as block commands in comments.
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
DeclarationName getName() const
getName - Returns the embedded declaration name.
void setLoc(SourceLocation L)
setLoc - Sets the main location of the declaration name.
void setInfo(const DeclarationNameLoc &Info)
void setName(DeclarationName N)
setName - Sets the embedded declaration name.
A simple structure that captures a vtable use for the purposes of the ExternalSemaSource.
The preprocessor keeps track of this information for each file that is #included.
void mergeModuleMembership(ModuleMap::ModuleHeaderRole Role)
Update the module membership bits based on the header role.
LazyIdentifierInfoPtr LazyControllingMacro
If this file has a #ifndef XXX (or equivalent) guard that protects the entire contents of the file,...
unsigned DirInfo
Keep track of whether this is a system header, and if so, whether it is C++ clean or not.
unsigned isPragmaOnce
True if this is a #pragma once file.
unsigned IsValid
Whether this file has been looked up as a header.
unsigned isImport
True if this is a #import'd file.
unsigned External
Whether this header file info was supplied by an external source, and has not changed since.
static LineEntry get(unsigned Offs, unsigned Line, int Filename, SrcMgr::CharacteristicKind FileKind, unsigned IncludeOffset)
Metadata for a module file extension.
unsigned MajorVersion
The major version of the extension data.
std::string UserInfo
A string containing additional user information that will be stored with the metadata.
std::string BlockName
The name used to identify this particular extension block within the resulting module file.
unsigned MinorVersion
The minor version of the extension data.
A conflict between two modules.
Definition Module.h:544
Module * Other
The module that this module conflicts with.
Definition Module.h:546
std::string Message
The message provided to the user when there is a conflict.
Definition Module.h:549
Information about a header directive as found in the module map file.
Definition Module.h:287
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:1852
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