clang 23.0.0git
ASTReader.cpp
Go to the documentation of this file.
1//===- ASTReader.cpp - AST File Reader ------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the ASTReader class, which reads AST files.
10//
11//===----------------------------------------------------------------------===//
12
13#include "ASTCommon.h"
14#include "ASTReaderInternals.h"
22#include "clang/AST/Attr.h"
23#include "clang/AST/Decl.h"
24#include "clang/AST/DeclBase.h"
25#include "clang/AST/DeclCXX.h"
27#include "clang/AST/DeclGroup.h"
28#include "clang/AST/DeclObjC.h"
31#include "clang/AST/Expr.h"
32#include "clang/AST/ExprCXX.h"
41#include "clang/AST/Type.h"
42#include "clang/AST/TypeLoc.h"
54#include "clang/Basic/LLVM.h"
56#include "clang/Basic/Module.h"
70#include "clang/Basic/Version.h"
73#include "clang/Lex/MacroInfo.h"
74#include "clang/Lex/ModuleMap.h"
78#include "clang/Lex/Token.h"
80#include "clang/Sema/Scope.h"
81#include "clang/Sema/Sema.h"
82#include "clang/Sema/SemaCUDA.h"
83#include "clang/Sema/SemaObjC.h"
84#include "clang/Sema/Weak.h"
97#include "llvm/ADT/APFloat.h"
98#include "llvm/ADT/APInt.h"
99#include "llvm/ADT/ArrayRef.h"
100#include "llvm/ADT/DenseMap.h"
101#include "llvm/ADT/FoldingSet.h"
102#include "llvm/ADT/IntrusiveRefCntPtr.h"
103#include "llvm/ADT/STLExtras.h"
104#include "llvm/ADT/ScopeExit.h"
105#include "llvm/ADT/Sequence.h"
106#include "llvm/ADT/SmallPtrSet.h"
107#include "llvm/ADT/SmallVector.h"
108#include "llvm/ADT/StringExtras.h"
109#include "llvm/ADT/StringMap.h"
110#include "llvm/ADT/StringRef.h"
111#include "llvm/ADT/iterator_range.h"
112#include "llvm/Bitstream/BitstreamReader.h"
113#include "llvm/Support/Compiler.h"
114#include "llvm/Support/Compression.h"
115#include "llvm/Support/DJB.h"
116#include "llvm/Support/Endian.h"
117#include "llvm/Support/Error.h"
118#include "llvm/Support/ErrorHandling.h"
119#include "llvm/Support/LEB128.h"
120#include "llvm/Support/MemoryBuffer.h"
121#include "llvm/Support/Path.h"
122#include "llvm/Support/SaveAndRestore.h"
123#include "llvm/Support/TimeProfiler.h"
124#include "llvm/Support/Timer.h"
125#include "llvm/Support/VersionTuple.h"
126#include "llvm/Support/raw_ostream.h"
127#include "llvm/TargetParser/Triple.h"
128#include <algorithm>
129#include <cassert>
130#include <cstddef>
131#include <cstdint>
132#include <cstdio>
133#include <ctime>
134#include <iterator>
135#include <limits>
136#include <map>
137#include <memory>
138#include <optional>
139#include <string>
140#include <system_error>
141#include <tuple>
142#include <utility>
143#include <vector>
144
145using namespace clang;
146using namespace clang::serialization;
147using namespace clang::serialization::reader;
148using llvm::BitstreamCursor;
149
150//===----------------------------------------------------------------------===//
151// ChainedASTReaderListener implementation
152//===----------------------------------------------------------------------===//
153
154bool
156 return First->ReadFullVersionInformation(FullVersion) ||
157 Second->ReadFullVersionInformation(FullVersion);
158}
159
161 First->ReadModuleName(ModuleName);
162 Second->ReadModuleName(ModuleName);
163}
164
165void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
166 First->ReadModuleMapFile(ModuleMapPath);
167 Second->ReadModuleMapFile(ModuleMapPath);
168}
169
171 const LangOptions &LangOpts, StringRef ModuleFilename, bool Complain,
172 bool AllowCompatibleDifferences) {
173 return First->ReadLanguageOptions(LangOpts, ModuleFilename, Complain,
174 AllowCompatibleDifferences) ||
175 Second->ReadLanguageOptions(LangOpts, ModuleFilename, Complain,
176 AllowCompatibleDifferences);
177}
178
180 const CodeGenOptions &CGOpts, StringRef ModuleFilename, bool Complain,
181 bool AllowCompatibleDifferences) {
182 return First->ReadCodeGenOptions(CGOpts, ModuleFilename, Complain,
183 AllowCompatibleDifferences) ||
184 Second->ReadCodeGenOptions(CGOpts, ModuleFilename, Complain,
185 AllowCompatibleDifferences);
186}
187
189 const TargetOptions &TargetOpts, StringRef ModuleFilename, bool Complain,
190 bool AllowCompatibleDifferences) {
191 return First->ReadTargetOptions(TargetOpts, ModuleFilename, Complain,
192 AllowCompatibleDifferences) ||
193 Second->ReadTargetOptions(TargetOpts, ModuleFilename, Complain,
194 AllowCompatibleDifferences);
195}
196
198 DiagnosticOptions &DiagOpts, StringRef ModuleFilename, bool Complain) {
199 return First->ReadDiagnosticOptions(DiagOpts, ModuleFilename, Complain) ||
200 Second->ReadDiagnosticOptions(DiagOpts, ModuleFilename, Complain);
201}
202
203bool
205 bool Complain) {
206 return First->ReadFileSystemOptions(FSOpts, Complain) ||
207 Second->ReadFileSystemOptions(FSOpts, Complain);
208}
209
211 const HeaderSearchOptions &HSOpts, StringRef ModuleFilename,
212 StringRef ContextHash, bool Complain) {
213 return First->ReadHeaderSearchOptions(HSOpts, ModuleFilename, ContextHash,
214 Complain) ||
215 Second->ReadHeaderSearchOptions(HSOpts, ModuleFilename, ContextHash,
216 Complain);
217}
218
220 const PreprocessorOptions &PPOpts, StringRef ModuleFilename,
221 bool ReadMacros, bool Complain, std::string &SuggestedPredefines) {
222 return First->ReadPreprocessorOptions(PPOpts, ModuleFilename, ReadMacros,
223 Complain, SuggestedPredefines) ||
224 Second->ReadPreprocessorOptions(PPOpts, ModuleFilename, ReadMacros,
225 Complain, SuggestedPredefines);
226}
227
229 uint32_t Value) {
230 First->ReadCounter(M, Value);
231 Second->ReadCounter(M, Value);
232}
233
235 return First->needsInputFileVisitation() ||
236 Second->needsInputFileVisitation();
237}
238
240 return First->needsSystemInputFileVisitation() ||
241 Second->needsSystemInputFileVisitation();
242}
243
245 ModuleKind Kind,
246 bool DirectlyImported) {
247 First->visitModuleFile(Filename, Kind, DirectlyImported);
248 Second->visitModuleFile(Filename, Kind, DirectlyImported);
249}
250
252 bool isSystem,
253 bool isOverridden,
254 bool isExplicitModule) {
255 bool Continue = false;
256 if (First->needsInputFileVisitation() &&
257 (!isSystem || First->needsSystemInputFileVisitation()))
258 Continue |= First->visitInputFile(Filename, isSystem, isOverridden,
259 isExplicitModule);
260 if (Second->needsInputFileVisitation() &&
261 (!isSystem || Second->needsSystemInputFileVisitation()))
262 Continue |= Second->visitInputFile(Filename, isSystem, isOverridden,
263 isExplicitModule);
264 return Continue;
265}
266
268 const ModuleFileExtensionMetadata &Metadata) {
269 First->readModuleFileExtension(Metadata);
270 Second->readModuleFileExtension(Metadata);
271}
272
273//===----------------------------------------------------------------------===//
274// PCH validator implementation
275//===----------------------------------------------------------------------===//
276
278
279/// Compare the given set of language options against an existing set of
280/// language options.
281///
282/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
283/// \param AllowCompatibleDifferences If true, differences between compatible
284/// language options will be permitted.
285///
286/// \returns true if the languagae options mis-match, false otherwise.
287static bool checkLanguageOptions(const LangOptions &LangOpts,
288 const LangOptions &ExistingLangOpts,
289 StringRef ModuleFilename,
290 DiagnosticsEngine *Diags,
291 bool AllowCompatibleDifferences = true) {
292 // FIXME: Replace with C++20 `using enum LangOptions::CompatibilityKind`.
294
295#define LANGOPT(Name, Bits, Default, Compatibility, Description) \
296 if constexpr (CK::Compatibility != CK::Benign) { \
297 if ((CK::Compatibility == CK::NotCompatible) || \
298 (CK::Compatibility == CK::Compatible && \
299 !AllowCompatibleDifferences)) { \
300 if (ExistingLangOpts.Name != LangOpts.Name) { \
301 if (Diags) { \
302 if (Bits == 1) \
303 Diags->Report(diag::err_ast_file_langopt_mismatch) \
304 << Description << LangOpts.Name << ExistingLangOpts.Name \
305 << ModuleFilename; \
306 else \
307 Diags->Report(diag::err_ast_file_langopt_value_mismatch) \
308 << Description << ModuleFilename; \
309 } \
310 return true; \
311 } \
312 } \
313 }
314
315#define VALUE_LANGOPT(Name, Bits, Default, Compatibility, Description) \
316 if constexpr (CK::Compatibility != CK::Benign) { \
317 if ((CK::Compatibility == CK::NotCompatible) || \
318 (CK::Compatibility == CK::Compatible && \
319 !AllowCompatibleDifferences)) { \
320 if (ExistingLangOpts.Name != LangOpts.Name) { \
321 if (Diags) \
322 Diags->Report(diag::err_ast_file_langopt_value_mismatch) \
323 << Description << ModuleFilename; \
324 return true; \
325 } \
326 } \
327 }
328
329#define ENUM_LANGOPT(Name, Type, Bits, Default, Compatibility, Description) \
330 if constexpr (CK::Compatibility != CK::Benign) { \
331 if ((CK::Compatibility == CK::NotCompatible) || \
332 (CK::Compatibility == CK::Compatible && \
333 !AllowCompatibleDifferences)) { \
334 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
335 if (Diags) \
336 Diags->Report(diag::err_ast_file_langopt_value_mismatch) \
337 << Description << ModuleFilename; \
338 return true; \
339 } \
340 } \
341 }
342
343#include "clang/Basic/LangOptions.def"
344
345 if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) {
346 if (Diags)
347 Diags->Report(diag::err_ast_file_langopt_value_mismatch)
348 << "module features" << ModuleFilename;
349 return true;
350 }
351
352 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
353 if (Diags)
354 Diags->Report(diag::err_ast_file_langopt_value_mismatch)
355 << "target Objective-C runtime" << ModuleFilename;
356 return true;
357 }
358
359 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
361 if (Diags)
362 Diags->Report(diag::err_ast_file_langopt_value_mismatch)
363 << "block command names" << ModuleFilename;
364 return true;
365 }
366
367 // Sanitizer feature mismatches are treated as compatible differences. If
368 // compatible differences aren't allowed, we still only want to check for
369 // mismatches of non-modular sanitizers (the only ones which can affect AST
370 // generation).
371 if (!AllowCompatibleDifferences) {
372 SanitizerMask ModularSanitizers = getPPTransparentSanitizers();
373 SanitizerSet ExistingSanitizers = ExistingLangOpts.Sanitize;
374 SanitizerSet ImportedSanitizers = LangOpts.Sanitize;
375 ExistingSanitizers.clear(ModularSanitizers);
376 ImportedSanitizers.clear(ModularSanitizers);
377 if (ExistingSanitizers.Mask != ImportedSanitizers.Mask) {
378 const std::string Flag = "-fsanitize=";
379 if (Diags) {
380#define SANITIZER(NAME, ID) \
381 { \
382 bool InExistingModule = ExistingSanitizers.has(SanitizerKind::ID); \
383 bool InImportedModule = ImportedSanitizers.has(SanitizerKind::ID); \
384 if (InExistingModule != InImportedModule) \
385 Diags->Report(diag::err_ast_file_targetopt_feature_mismatch) \
386 << InExistingModule << ModuleFilename << (Flag + NAME); \
387 }
388#include "clang/Basic/Sanitizers.def"
389 }
390 return true;
391 }
392 }
393
394 return false;
395}
396
397static bool checkCodegenOptions(const CodeGenOptions &CGOpts,
398 const CodeGenOptions &ExistingCGOpts,
399 StringRef ModuleFilename,
400 DiagnosticsEngine *Diags,
401 bool AllowCompatibleDifferences = true) {
402 // FIXME: Specify and print a description for each option instead of the name.
403 // FIXME: Replace with C++20 `using enum CodeGenOptions::CompatibilityKind`.
405#define CODEGENOPT(Name, Bits, Default, Compatibility) \
406 if constexpr (CK::Compatibility != CK::Benign) { \
407 if ((CK::Compatibility == CK::NotCompatible) || \
408 (CK::Compatibility == CK::Compatible && \
409 !AllowCompatibleDifferences)) { \
410 if (ExistingCGOpts.Name != CGOpts.Name) { \
411 if (Diags) { \
412 if (Bits == 1) \
413 Diags->Report(diag::err_ast_file_codegenopt_mismatch) \
414 << #Name << CGOpts.Name << ExistingCGOpts.Name \
415 << ModuleFilename; \
416 else \
417 Diags->Report(diag::err_ast_file_codegenopt_value_mismatch) \
418 << #Name << ModuleFilename; \
419 } \
420 return true; \
421 } \
422 } \
423 }
424
425#define VALUE_CODEGENOPT(Name, Bits, Default, Compatibility) \
426 if constexpr (CK::Compatibility != CK::Benign) { \
427 if ((CK::Compatibility == CK::NotCompatible) || \
428 (CK::Compatibility == CK::Compatible && \
429 !AllowCompatibleDifferences)) { \
430 if (ExistingCGOpts.Name != CGOpts.Name) { \
431 if (Diags) \
432 Diags->Report(diag::err_ast_file_codegenopt_value_mismatch) \
433 << #Name << ModuleFilename; \
434 return true; \
435 } \
436 } \
437 }
438#define ENUM_CODEGENOPT(Name, Type, Bits, Default, Compatibility) \
439 if constexpr (CK::Compatibility != CK::Benign) { \
440 if ((CK::Compatibility == CK::NotCompatible) || \
441 (CK::Compatibility == CK::Compatible && \
442 !AllowCompatibleDifferences)) { \
443 if (ExistingCGOpts.get##Name() != CGOpts.get##Name()) { \
444 if (Diags) \
445 Diags->Report(diag::err_ast_file_codegenopt_value_mismatch) \
446 << #Name << ModuleFilename; \
447 return true; \
448 } \
449 } \
450 }
451#define DEBUGOPT(Name, Bits, Default, Compatibility)
452#define VALUE_DEBUGOPT(Name, Bits, Default, Compatibility)
453#define ENUM_DEBUGOPT(Name, Type, Bits, Default, Compatibility)
454#include "clang/Basic/CodeGenOptions.def"
455
456 return false;
457}
458
459/// Compare the given set of target options against an existing set of
460/// target options.
461///
462/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
463///
464/// \returns true if the target options mis-match, false otherwise.
465static bool checkTargetOptions(const TargetOptions &TargetOpts,
466 const TargetOptions &ExistingTargetOpts,
467 StringRef ModuleFilename,
468 DiagnosticsEngine *Diags,
469 bool AllowCompatibleDifferences = true) {
470#define CHECK_TARGET_OPT(Field, Name) \
471 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
472 if (Diags) \
473 Diags->Report(diag::err_ast_file_targetopt_mismatch) \
474 << ModuleFilename << Name << TargetOpts.Field \
475 << ExistingTargetOpts.Field; \
476 return true; \
477 }
478
479 // The triple and ABI must match exactly.
480 CHECK_TARGET_OPT(Triple, "target");
481 CHECK_TARGET_OPT(ABI, "target ABI");
482
483 // We can tolerate different CPUs in many cases, notably when one CPU
484 // supports a strict superset of another. When allowing compatible
485 // differences skip this check.
486 if (!AllowCompatibleDifferences) {
487 CHECK_TARGET_OPT(CPU, "target CPU");
488 CHECK_TARGET_OPT(TuneCPU, "tune CPU");
489 }
490
491#undef CHECK_TARGET_OPT
492
493 // Compare feature sets.
494 SmallVector<StringRef, 4> ExistingFeatures(
495 ExistingTargetOpts.FeaturesAsWritten.begin(),
496 ExistingTargetOpts.FeaturesAsWritten.end());
497 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
498 TargetOpts.FeaturesAsWritten.end());
499 llvm::sort(ExistingFeatures);
500 ExistingFeatures.erase(llvm::unique(ExistingFeatures),
501 ExistingFeatures.end());
502 llvm::sort(ReadFeatures);
503 ReadFeatures.erase(llvm::unique(ReadFeatures), ReadFeatures.end());
504
505 // We compute the set difference in both directions explicitly so that we can
506 // diagnose the differences differently.
507 SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
508 std::set_difference(
509 ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
510 ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
511 std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
512 ExistingFeatures.begin(), ExistingFeatures.end(),
513 std::back_inserter(UnmatchedReadFeatures));
514
515 // If we are allowing compatible differences and the read feature set is
516 // a strict subset of the existing feature set, there is nothing to diagnose.
517 if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
518 return false;
519
520 if (Diags) {
521 for (StringRef Feature : UnmatchedReadFeatures)
522 Diags->Report(diag::err_ast_file_targetopt_feature_mismatch)
523 << /* is-existing-feature */ false << ModuleFilename << Feature;
524 for (StringRef Feature : UnmatchedExistingFeatures)
525 Diags->Report(diag::err_ast_file_targetopt_feature_mismatch)
526 << /* is-existing-feature */ true << ModuleFilename << Feature;
527 }
528
529 return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
530}
531
533 StringRef ModuleFilename, bool Complain,
534 bool AllowCompatibleDifferences) {
535 const LangOptions &ExistingLangOpts = PP.getLangOpts();
536 return checkLanguageOptions(LangOpts, ExistingLangOpts, ModuleFilename,
537 Complain ? &Reader.Diags : nullptr,
538 AllowCompatibleDifferences);
539}
540
542 StringRef ModuleFilename, bool Complain,
543 bool AllowCompatibleDifferences) {
544 const CodeGenOptions &ExistingCGOpts = Reader.getCodeGenOpts();
545 return checkCodegenOptions(ExistingCGOpts, CGOpts, ModuleFilename,
546 Complain ? &Reader.Diags : nullptr,
547 AllowCompatibleDifferences);
548}
549
551 StringRef ModuleFilename, bool Complain,
552 bool AllowCompatibleDifferences) {
553 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
554 return checkTargetOptions(TargetOpts, ExistingTargetOpts, ModuleFilename,
555 Complain ? &Reader.Diags : nullptr,
556 AllowCompatibleDifferences);
557}
558
559namespace {
560
561using MacroDefinitionsMap =
562 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>;
563
564class DeclsSet {
567
568public:
569 operator ArrayRef<NamedDecl *>() const { return Decls; }
570
571 bool empty() const { return Decls.empty(); }
572
573 bool insert(NamedDecl *ND) {
574 auto [_, Inserted] = Found.insert(ND);
575 if (Inserted)
576 Decls.push_back(ND);
577 return Inserted;
578 }
579};
580
581using DeclsMap = llvm::DenseMap<DeclarationName, DeclsSet>;
582
583} // namespace
584
586 DiagnosticsEngine &Diags,
587 StringRef ModuleFilename,
588 bool Complain) {
589 using Level = DiagnosticsEngine::Level;
590
591 // Check current mappings for new -Werror mappings, and the stored mappings
592 // for cases that were explicitly mapped to *not* be errors that are now
593 // errors because of options like -Werror.
594 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
595
596 for (DiagnosticsEngine *MappingSource : MappingSources) {
597 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
598 diag::kind DiagID = DiagIDMappingPair.first;
599 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
600 if (CurLevel < DiagnosticsEngine::Error)
601 continue; // not significant
602 Level StoredLevel =
603 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
604 if (StoredLevel < DiagnosticsEngine::Error) {
605 if (Complain)
606 Diags.Report(diag::err_ast_file_diagopt_mismatch)
607 << "-Werror=" + Diags.getDiagnosticIDs()
608 ->getWarningOptionForDiag(DiagID)
609 .str()
610 << ModuleFilename;
611 return true;
612 }
613 }
614 }
615
616 return false;
617}
618
621 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
622 return true;
623 return Ext >= diag::Severity::Error;
624}
625
627 DiagnosticsEngine &Diags,
628 StringRef ModuleFilename, bool IsSystem,
629 bool SystemHeaderWarningsInModule,
630 bool Complain) {
631 // Top-level options
632 if (IsSystem) {
633 if (Diags.getSuppressSystemWarnings())
634 return false;
635 // If -Wsystem-headers was not enabled before, and it was not explicit,
636 // be conservative
637 if (StoredDiags.getSuppressSystemWarnings() &&
638 !SystemHeaderWarningsInModule) {
639 if (Complain)
640 Diags.Report(diag::err_ast_file_diagopt_mismatch)
641 << "-Wsystem-headers" << ModuleFilename;
642 return true;
643 }
644 }
645
646 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
647 if (Complain)
648 Diags.Report(diag::err_ast_file_diagopt_mismatch)
649 << "-Werror" << ModuleFilename;
650 return true;
651 }
652
653 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
654 !StoredDiags.getEnableAllWarnings()) {
655 if (Complain)
656 Diags.Report(diag::err_ast_file_diagopt_mismatch)
657 << "-Weverything -Werror" << ModuleFilename;
658 return true;
659 }
660
661 if (isExtHandlingFromDiagsError(Diags) &&
662 !isExtHandlingFromDiagsError(StoredDiags)) {
663 if (Complain)
664 Diags.Report(diag::err_ast_file_diagopt_mismatch)
665 << "-pedantic-errors" << ModuleFilename;
666 return true;
667 }
668
669 return checkDiagnosticGroupMappings(StoredDiags, Diags, ModuleFilename,
670 Complain);
671}
672
673/// Return the top import module if it is implicit, nullptr otherwise.
675 Preprocessor &PP) {
676 // If the original import came from a file explicitly generated by the user,
677 // don't check the diagnostic mappings.
678 // FIXME: currently this is approximated by checking whether this is not a
679 // module import of an implicitly-loaded module file.
680 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
681 // the transitive closure of its imports, since unrelated modules cannot be
682 // imported until after this module finishes validation.
683 ModuleFile *TopImport = &*ModuleMgr.rbegin();
684 while (!TopImport->ImportedBy.empty())
685 TopImport = TopImport->ImportedBy[0];
686 if (TopImport->Kind != MK_ImplicitModule)
687 return nullptr;
688
689 StringRef ModuleName = TopImport->ModuleName;
690 assert(!ModuleName.empty() && "diagnostic options read before module name");
691
692 Module *M =
693 PP.getHeaderSearchInfo().lookupModule(ModuleName, TopImport->ImportLoc);
694 assert(M && "missing module");
695 return M;
696}
697
699 StringRef ModuleFilename,
700 bool Complain) {
701 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
703 auto Diags = llvm::makeIntrusiveRefCnt<DiagnosticsEngine>(DiagIDs, DiagOpts);
704 // This should never fail, because we would have processed these options
705 // before writing them to an ASTFile.
706 ProcessWarningOptions(*Diags, DiagOpts,
707 PP.getFileManager().getVirtualFileSystem(),
708 /*Report*/ false);
709
710 ModuleManager &ModuleMgr = Reader.getModuleManager();
711 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
712
713 Module *TopM = getTopImportImplicitModule(ModuleMgr, PP);
714 if (!TopM)
715 return false;
716
717 Module *Importer = PP.getCurrentModule();
718
719 DiagnosticOptions &ExistingOpts = ExistingDiags.getDiagnosticOptions();
720 bool SystemHeaderWarningsInModule =
721 Importer && llvm::is_contained(ExistingOpts.SystemHeaderWarningsModules,
722 Importer->Name);
723
724 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
725 // contains the union of their flags.
726 return checkDiagnosticMappings(*Diags, ExistingDiags, ModuleFilename,
727 TopM->IsSystem, SystemHeaderWarningsInModule,
728 Complain);
729}
730
731/// Collect the macro definitions provided by the given preprocessor
732/// options.
733static void
735 MacroDefinitionsMap &Macros,
736 SmallVectorImpl<StringRef> *MacroNames = nullptr) {
737 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
738 StringRef Macro = PPOpts.Macros[I].first;
739 bool IsUndef = PPOpts.Macros[I].second;
740
741 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
742 StringRef MacroName = MacroPair.first;
743 StringRef MacroBody = MacroPair.second;
744
745 // For an #undef'd macro, we only care about the name.
746 if (IsUndef) {
747 auto [It, Inserted] = Macros.try_emplace(MacroName);
748 if (MacroNames && Inserted)
749 MacroNames->push_back(MacroName);
750
751 It->second = std::make_pair("", true);
752 continue;
753 }
754
755 // For a #define'd macro, figure out the actual definition.
756 if (MacroName.size() == Macro.size())
757 MacroBody = "1";
758 else {
759 // Note: GCC drops anything following an end-of-line character.
760 StringRef::size_type End = MacroBody.find_first_of("\n\r");
761 MacroBody = MacroBody.substr(0, End);
762 }
763
764 auto [It, Inserted] = Macros.try_emplace(MacroName);
765 if (MacroNames && Inserted)
766 MacroNames->push_back(MacroName);
767 It->second = std::make_pair(MacroBody, false);
768 }
769}
770
776
777/// Check the preprocessor options deserialized from the control block
778/// against the preprocessor options in an existing preprocessor.
779///
780/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
781/// \param Validation If set to OptionValidateNone, ignore differences in
782/// preprocessor options. If set to OptionValidateContradictions,
783/// require that options passed both in the AST file and on the command
784/// line (-D or -U) match, but tolerate options missing in one or the
785/// other. If set to OptionValidateContradictions, require that there
786/// are no differences in the options between the two.
788 const PreprocessorOptions &PPOpts,
789 const PreprocessorOptions &ExistingPPOpts, StringRef ModuleFilename,
790 bool ReadMacros, DiagnosticsEngine *Diags, FileManager &FileMgr,
791 std::string &SuggestedPredefines, const LangOptions &LangOpts,
793 if (ReadMacros) {
794 // Check macro definitions.
795 MacroDefinitionsMap ASTFileMacros;
796 collectMacroDefinitions(PPOpts, ASTFileMacros);
797 MacroDefinitionsMap ExistingMacros;
798 SmallVector<StringRef, 4> ExistingMacroNames;
799 collectMacroDefinitions(ExistingPPOpts, ExistingMacros,
800 &ExistingMacroNames);
801
802 // Use a line marker to enter the <command line> file, as the defines and
803 // undefines here will have come from the command line.
804 SuggestedPredefines += "# 1 \"<command line>\" 1\n";
805
806 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
807 // Dig out the macro definition in the existing preprocessor options.
808 StringRef MacroName = ExistingMacroNames[I];
809 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
810
811 // Check whether we know anything about this macro name or not.
812 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>::iterator Known =
813 ASTFileMacros.find(MacroName);
814 if (Validation == OptionValidateNone || Known == ASTFileMacros.end()) {
815 if (Validation == OptionValidateStrictMatches) {
816 // If strict matches are requested, don't tolerate any extra defines
817 // on the command line that are missing in the AST file.
818 if (Diags) {
819 Diags->Report(diag::err_ast_file_macro_def_undef)
820 << MacroName << true << ModuleFilename;
821 }
822 return true;
823 }
824 // FIXME: Check whether this identifier was referenced anywhere in the
825 // AST file. If so, we should reject the AST file. Unfortunately, this
826 // information isn't in the control block. What shall we do about it?
827
828 if (Existing.second) {
829 SuggestedPredefines += "#undef ";
830 SuggestedPredefines += MacroName.str();
831 SuggestedPredefines += '\n';
832 } else {
833 SuggestedPredefines += "#define ";
834 SuggestedPredefines += MacroName.str();
835 SuggestedPredefines += ' ';
836 SuggestedPredefines += Existing.first.str();
837 SuggestedPredefines += '\n';
838 }
839 continue;
840 }
841
842 // If the macro was defined in one but undef'd in the other, we have a
843 // conflict.
844 if (Existing.second != Known->second.second) {
845 if (Diags) {
846 Diags->Report(diag::err_ast_file_macro_def_undef)
847 << MacroName << Known->second.second << ModuleFilename;
848 }
849 return true;
850 }
851
852 // If the macro was #undef'd in both, or if the macro bodies are
853 // identical, it's fine.
854 if (Existing.second || Existing.first == Known->second.first) {
855 ASTFileMacros.erase(Known);
856 continue;
857 }
858
859 // The macro bodies differ; complain.
860 if (Diags) {
861 Diags->Report(diag::err_ast_file_macro_def_conflict)
862 << MacroName << Known->second.first << Existing.first
863 << ModuleFilename;
864 }
865 return true;
866 }
867
868 // Leave the <command line> file and return to <built-in>.
869 SuggestedPredefines += "# 1 \"<built-in>\" 2\n";
870
871 if (Validation == OptionValidateStrictMatches) {
872 // If strict matches are requested, don't tolerate any extra defines in
873 // the AST file that are missing on the command line.
874 for (const auto &MacroName : ASTFileMacros.keys()) {
875 if (Diags) {
876 Diags->Report(diag::err_ast_file_macro_def_undef)
877 << MacroName << false << ModuleFilename;
878 }
879 return true;
880 }
881 }
882 }
883
884 // Check whether we're using predefines.
885 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines &&
886 Validation != OptionValidateNone) {
887 if (Diags) {
888 Diags->Report(diag::err_ast_file_undef)
889 << ExistingPPOpts.UsePredefines << ModuleFilename;
890 }
891 return true;
892 }
893
894 // Detailed record is important since it is used for the module cache hash.
895 if (LangOpts.Modules &&
896 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord &&
897 Validation != OptionValidateNone) {
898 if (Diags) {
899 Diags->Report(diag::err_ast_file_pp_detailed_record)
900 << PPOpts.DetailedRecord << ModuleFilename;
901 }
902 return true;
903 }
904
905 // Compute the #include and #include_macros lines we need.
906 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
907 StringRef File = ExistingPPOpts.Includes[I];
908
909 if (!ExistingPPOpts.ImplicitPCHInclude.empty() &&
910 !ExistingPPOpts.PCHThroughHeader.empty()) {
911 // In case the through header is an include, we must add all the includes
912 // to the predefines so the start point can be determined.
913 SuggestedPredefines += "#include \"";
914 SuggestedPredefines += File;
915 SuggestedPredefines += "\"\n";
916 continue;
917 }
918
919 if (File == ExistingPPOpts.ImplicitPCHInclude)
920 continue;
921
922 if (llvm::is_contained(PPOpts.Includes, File))
923 continue;
924
925 SuggestedPredefines += "#include \"";
926 SuggestedPredefines += File;
927 SuggestedPredefines += "\"\n";
928 }
929
930 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
931 StringRef File = ExistingPPOpts.MacroIncludes[I];
932 if (llvm::is_contained(PPOpts.MacroIncludes, File))
933 continue;
934
935 SuggestedPredefines += "#__include_macros \"";
936 SuggestedPredefines += File;
937 SuggestedPredefines += "\"\n##\n";
938 }
939
940 return false;
941}
942
944 StringRef ModuleFilename,
945 bool ReadMacros, bool Complain,
946 std::string &SuggestedPredefines) {
947 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
948
950 PPOpts, ExistingPPOpts, ModuleFilename, ReadMacros,
951 Complain ? &Reader.Diags : nullptr, PP.getFileManager(),
952 SuggestedPredefines, PP.getLangOpts());
953}
954
956 const PreprocessorOptions &PPOpts, StringRef ModuleFilename,
957 bool ReadMacros, bool Complain, std::string &SuggestedPredefines) {
958 return checkPreprocessorOptions(PPOpts, PP.getPreprocessorOpts(),
959 ModuleFilename, ReadMacros, nullptr,
960 PP.getFileManager(), SuggestedPredefines,
961 PP.getLangOpts(), OptionValidateNone);
962}
963
964/// Check that the specified and the existing module cache paths are equivalent.
965///
966/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
967/// \returns true when the module cache paths differ.
968static bool checkModuleCachePath(FileManager &FileMgr, StringRef ContextHash,
969 StringRef ExistingSpecificModuleCachePath,
970 StringRef ASTFilename,
971 DiagnosticsEngine *Diags,
972 const LangOptions &LangOpts,
973 const PreprocessorOptions &PPOpts,
974 const HeaderSearchOptions &HSOpts,
975 const HeaderSearchOptions &ASTFileHSOpts) {
976 std::string SpecificModuleCachePath = createSpecificModuleCachePath(
977 FileMgr, ASTFileHSOpts.ModuleCachePath, ASTFileHSOpts.DisableModuleHash,
978 std::string(ContextHash));
979
980 if (!LangOpts.Modules || PPOpts.AllowPCHWithDifferentModulesCachePath ||
981 SpecificModuleCachePath == ExistingSpecificModuleCachePath)
982 return false;
983 auto EqualOrErr = FileMgr.getVirtualFileSystem().equivalent(
984 SpecificModuleCachePath, ExistingSpecificModuleCachePath);
985 if (EqualOrErr && *EqualOrErr)
986 return false;
987 if (Diags) {
988 // If the module cache arguments provided from the command line are the
989 // same, the mismatch must come from other arguments of the configuration
990 // and not directly the cache path.
991 EqualOrErr = FileMgr.getVirtualFileSystem().equivalent(
992 ASTFileHSOpts.ModuleCachePath, HSOpts.ModuleCachePath);
993 if (EqualOrErr && *EqualOrErr)
994 Diags->Report(clang::diag::warn_ast_file_config_mismatch) << ASTFilename;
995 else
996 Diags->Report(diag::err_ast_file_modulecache_mismatch)
997 << SpecificModuleCachePath << ExistingSpecificModuleCachePath
998 << ASTFilename;
999 }
1000 return true;
1001}
1002
1004 StringRef ASTFilename,
1005 StringRef ContextHash,
1006 bool Complain) {
1007 const HeaderSearch &HeaderSearchInfo = PP.getHeaderSearchInfo();
1008 return checkModuleCachePath(Reader.getFileManager(), ContextHash,
1009 HeaderSearchInfo.getSpecificModuleCachePath(),
1010 ASTFilename, Complain ? &Reader.Diags : nullptr,
1011 PP.getLangOpts(), PP.getPreprocessorOpts(),
1012 HeaderSearchInfo.getHeaderSearchOpts(), HSOpts);
1013}
1014
1016 PP.setCounterValue(Value);
1017}
1018
1019//===----------------------------------------------------------------------===//
1020// AST reader implementation
1021//===----------------------------------------------------------------------===//
1022
1023static uint64_t readULEB(const unsigned char *&P) {
1024 unsigned Length = 0;
1025 const char *Error = nullptr;
1026
1027 uint64_t Val = llvm::decodeULEB128(P, &Length, nullptr, &Error);
1028 if (Error)
1029 llvm::report_fatal_error(Error);
1030 P += Length;
1031 return Val;
1032}
1033
1034/// Read ULEB-encoded key length and data length.
1035static std::pair<unsigned, unsigned>
1036readULEBKeyDataLength(const unsigned char *&P) {
1037 unsigned KeyLen = readULEB(P);
1038 if ((unsigned)KeyLen != KeyLen)
1039 llvm::report_fatal_error("key too large");
1040
1041 unsigned DataLen = readULEB(P);
1042 if ((unsigned)DataLen != DataLen)
1043 llvm::report_fatal_error("data too large");
1044
1045 return std::make_pair(KeyLen, DataLen);
1046}
1047
1049 bool TakeOwnership) {
1050 DeserializationListener = Listener;
1051 OwnsDeserializationListener = TakeOwnership;
1052}
1053
1057
1059 LocalDeclID ID(Value);
1060#ifndef NDEBUG
1061 if (!MF.ModuleOffsetMap.empty())
1062 Reader.ReadModuleOffsetMap(MF);
1063
1064 unsigned ModuleFileIndex = ID.getModuleFileIndex();
1065 unsigned LocalDeclID = ID.getLocalDeclIndex();
1066
1067 assert(ModuleFileIndex <= MF.TransitiveImports.size());
1068
1069 ModuleFile *OwningModuleFile =
1070 ModuleFileIndex == 0 ? &MF : MF.TransitiveImports[ModuleFileIndex - 1];
1071 assert(OwningModuleFile);
1072
1073 unsigned LocalNumDecls = OwningModuleFile->LocalNumDecls;
1074
1075 if (!ModuleFileIndex)
1076 LocalNumDecls += NUM_PREDEF_DECL_IDS;
1077
1078 assert(LocalDeclID < LocalNumDecls);
1079#endif
1080 (void)Reader;
1081 (void)MF;
1082 return ID;
1083}
1084
1085LocalDeclID LocalDeclID::get(ASTReader &Reader, ModuleFile &MF,
1086 unsigned ModuleFileIndex, unsigned LocalDeclID) {
1087 DeclID Value = (DeclID)ModuleFileIndex << 32 | (DeclID)LocalDeclID;
1088 return LocalDeclID::get(Reader, MF, Value);
1089}
1090
1091std::pair<unsigned, unsigned>
1093 return readULEBKeyDataLength(d);
1094}
1095
1097ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
1098 using namespace llvm::support;
1099
1100 SelectorTable &SelTable = Reader.getContext().Selectors;
1101 unsigned N = endian::readNext<uint16_t, llvm::endianness::little>(d);
1102 const IdentifierInfo *FirstII = Reader.getLocalIdentifier(
1103 F, endian::readNext<IdentifierID, llvm::endianness::little>(d));
1104 if (N == 0)
1105 return SelTable.getNullarySelector(FirstII);
1106 else if (N == 1)
1107 return SelTable.getUnarySelector(FirstII);
1108
1110 Args.push_back(FirstII);
1111 for (unsigned I = 1; I != N; ++I)
1112 Args.push_back(Reader.getLocalIdentifier(
1113 F, endian::readNext<IdentifierID, llvm::endianness::little>(d)));
1114
1115 return SelTable.getSelector(N, Args.data());
1116}
1117
1120 unsigned DataLen) {
1121 using namespace llvm::support;
1122
1124
1125 Result.ID = Reader.getGlobalSelectorID(
1126 F, endian::readNext<uint32_t, llvm::endianness::little>(d));
1127 unsigned FullInstanceBits =
1128 endian::readNext<uint16_t, llvm::endianness::little>(d);
1129 unsigned FullFactoryBits =
1130 endian::readNext<uint16_t, llvm::endianness::little>(d);
1131 Result.InstanceBits = FullInstanceBits & 0x3;
1132 Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
1133 Result.FactoryBits = FullFactoryBits & 0x3;
1134 Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
1135 unsigned NumInstanceMethods = FullInstanceBits >> 3;
1136 unsigned NumFactoryMethods = FullFactoryBits >> 3;
1137
1138 // Load instance methods
1139 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
1140 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
1142 Reader, F,
1143 endian::readNext<DeclID, llvm::endianness::little>(d))))
1144 Result.Instance.push_back(Method);
1145 }
1146
1147 // Load factory methods
1148 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
1149 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
1151 Reader, F,
1152 endian::readNext<DeclID, llvm::endianness::little>(d))))
1153 Result.Factory.push_back(Method);
1154 }
1155
1156 return Result;
1157}
1158
1160 return llvm::djbHash(a);
1161}
1162
1163std::pair<unsigned, unsigned>
1165 return readULEBKeyDataLength(d);
1166}
1167
1169ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
1170 assert(n >= 2 && d[n-1] == '\0');
1171 return StringRef((const char*) d, n-1);
1172}
1173
1174/// Whether the given identifier is "interesting".
1175static bool isInterestingIdentifier(ASTReader &Reader, const IdentifierInfo &II,
1176 bool IsModule) {
1177 bool IsInteresting =
1178 II.getNotableIdentifierID() != tok::NotableIdentifierKind::not_notable ||
1180 II.getObjCKeywordID() != tok::ObjCKeywordKind::objc_not_keyword;
1181 return II.hadMacroDefinition() || II.isPoisoned() ||
1182 (!IsModule && IsInteresting) || II.hasRevertedTokenIDToIdentifier() ||
1183 (!(IsModule && Reader.getPreprocessor().getLangOpts().CPlusPlus) &&
1184 II.getFETokenInfo());
1185}
1186
1187static bool readBit(unsigned &Bits) {
1188 bool Value = Bits & 0x1;
1189 Bits >>= 1;
1190 return Value;
1191}
1192
1194 using namespace llvm::support;
1195
1196 IdentifierID RawID =
1197 endian::readNext<IdentifierID, llvm::endianness::little>(d);
1198 return Reader.getGlobalIdentifierID(F, RawID >> 1);
1199}
1200
1202 bool IsModule) {
1203 if (!II.isFromAST()) {
1204 II.setIsFromAST();
1205 if (isInterestingIdentifier(Reader, II, IsModule))
1207 }
1208}
1209
1211 const unsigned char* d,
1212 unsigned DataLen) {
1213 using namespace llvm::support;
1214
1215 IdentifierID RawID =
1216 endian::readNext<IdentifierID, llvm::endianness::little>(d);
1217 bool IsInteresting = RawID & 0x01;
1218
1219 DataLen -= sizeof(IdentifierID);
1220
1221 // Wipe out the "is interesting" bit.
1222 RawID = RawID >> 1;
1223
1224 // Build the IdentifierInfo and link the identifier ID with it.
1225 IdentifierInfo *II = KnownII;
1226 if (!II) {
1227 II = &Reader.getIdentifierTable().getOwn(k);
1228 KnownII = II;
1229 }
1230 bool IsModule = Reader.getPreprocessor().getCurrentModule() != nullptr;
1231 markIdentifierFromAST(Reader, *II, IsModule);
1232 Reader.markIdentifierUpToDate(II);
1233
1234 IdentifierID ID = Reader.getGlobalIdentifierID(F, RawID);
1235 if (!IsInteresting) {
1236 // For uninteresting identifiers, there's nothing else to do. Just notify
1237 // the reader that we've finished loading this identifier.
1238 Reader.SetIdentifierInfo(ID, II);
1239 return II;
1240 }
1241
1242 unsigned ObjCOrBuiltinID =
1243 endian::readNext<uint16_t, llvm::endianness::little>(d);
1244 unsigned Bits = endian::readNext<uint16_t, llvm::endianness::little>(d);
1245 bool CPlusPlusOperatorKeyword = readBit(Bits);
1246 bool HasRevertedTokenIDToIdentifier = readBit(Bits);
1247 bool Poisoned = readBit(Bits);
1248 bool ExtensionToken = readBit(Bits);
1249 bool HasMacroDefinition = readBit(Bits);
1250
1251 assert(Bits == 0 && "Extra bits in the identifier?");
1252 DataLen -= sizeof(uint16_t) * 2;
1253
1254 // Set or check the various bits in the IdentifierInfo structure.
1255 // Token IDs are read-only.
1256 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
1258 if (!F.isModule())
1259 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
1260 assert(II->isExtensionToken() == ExtensionToken &&
1261 "Incorrect extension token flag");
1262 (void)ExtensionToken;
1263 if (Poisoned)
1264 II->setIsPoisoned(true);
1265 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
1266 "Incorrect C++ operator keyword flag");
1267 (void)CPlusPlusOperatorKeyword;
1268
1269 // If this identifier has a macro definition, deserialize it or notify the
1270 // visitor the actual definition is in a different module.
1271 if (HasMacroDefinition) {
1272 uint32_t MacroDirectivesOffset =
1273 endian::readNext<uint32_t, llvm::endianness::little>(d);
1274 DataLen -= 4;
1275
1276 if (MacroDirectivesOffset)
1277 Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
1278 else
1279 hasMacroDefinitionInDependencies = true;
1280 }
1281
1282 Reader.SetIdentifierInfo(ID, II);
1283
1284 // Read all of the declarations visible at global scope with this
1285 // name.
1286 if (DataLen > 0) {
1288 for (; DataLen > 0; DataLen -= sizeof(DeclID))
1289 DeclIDs.push_back(Reader.getGlobalDeclID(
1291 Reader, F,
1292 endian::readNext<DeclID, llvm::endianness::little>(d))));
1293 Reader.SetGloballyVisibleDecls(II, DeclIDs);
1294 }
1295
1296 return II;
1297}
1298
1300 : Kind(Name.getNameKind()) {
1301 switch (Kind) {
1303 Data = (uint64_t)Name.getAsIdentifierInfo();
1304 break;
1308 Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
1309 break;
1311 Data = Name.getCXXOverloadedOperator();
1312 break;
1314 Data = (uint64_t)Name.getCXXLiteralIdentifier();
1315 break;
1317 Data = (uint64_t)Name.getCXXDeductionGuideTemplate()
1319 break;
1324 Data = 0;
1325 break;
1326 }
1327}
1328
1330 llvm::FoldingSetNodeID ID;
1331 ID.AddInteger(Kind);
1332
1333 switch (Kind) {
1337 ID.AddString(((IdentifierInfo*)Data)->getName());
1338 break;
1342 ID.AddInteger(serialization::ComputeHash(Selector(Data)));
1343 break;
1345 ID.AddInteger((OverloadedOperatorKind)Data);
1346 break;
1351 break;
1352 }
1353
1354 return ID.computeStableHash();
1355}
1356
1357ModuleFile *
1359 using namespace llvm::support;
1360
1361 uint32_t ModuleFileID =
1362 endian::readNext<uint32_t, llvm::endianness::little>(d);
1363 return Reader.getLocalModuleFile(F, ModuleFileID);
1364}
1365
1366std::pair<unsigned, unsigned>
1370
1373 using namespace llvm::support;
1374
1375 auto Kind = (DeclarationName::NameKind)*d++;
1376 uint64_t Data;
1377 switch (Kind) {
1381 Data = (uint64_t)Reader.getLocalIdentifier(
1382 F, endian::readNext<IdentifierID, llvm::endianness::little>(d));
1383 break;
1387 Data = (uint64_t)Reader
1388 .getLocalSelector(
1389 F, endian::readNext<uint32_t, llvm::endianness::little>(d))
1390 .getAsOpaquePtr();
1391 break;
1393 Data = *d++; // OverloadedOperatorKind
1394 break;
1399 Data = 0;
1400 break;
1401 }
1402
1403 return DeclarationNameKey(Kind, Data);
1404}
1405
1407ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
1408 return ReadKeyBase(d);
1409}
1410
1412 const unsigned char *d, unsigned DataLen, data_type_builder &Val) {
1413 using namespace llvm::support;
1414
1415 for (unsigned NumDecls = DataLen / sizeof(DeclID); NumDecls; --NumDecls) {
1417 Reader, F, endian::readNext<DeclID, llvm::endianness::little>(d));
1418 Val.insert(Reader.getGlobalDeclID(F, ID));
1419 }
1420}
1421
1423 const unsigned char *d,
1424 unsigned DataLen,
1425 data_type_builder &Val) {
1426 ReadDataIntoImpl(d, DataLen, Val);
1427}
1428
1431 llvm::FoldingSetNodeID ID;
1432 ID.AddInteger(Key.first.getHash());
1433 ID.AddInteger(Key.second);
1434 return ID.computeStableHash();
1435}
1436
1439 DeclarationNameKey Name(Key.first);
1440
1441 UnsignedOrNone ModuleHash = getPrimaryModuleHash(Key.second);
1442 if (!ModuleHash)
1443 return {Name, 0};
1444
1445 return {Name, *ModuleHash};
1446}
1447
1449ModuleLocalNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
1451 unsigned PrimaryModuleHash =
1452 llvm::support::endian::readNext<uint32_t, llvm::endianness::little>(d);
1453 return {Name, PrimaryModuleHash};
1454}
1455
1457 const unsigned char *d,
1458 unsigned DataLen,
1459 data_type_builder &Val) {
1460 ReadDataIntoImpl(d, DataLen, Val);
1461}
1462
1463ModuleFile *
1465 using namespace llvm::support;
1466
1467 uint32_t ModuleFileID =
1468 endian::readNext<uint32_t, llvm::endianness::little, unaligned>(d);
1469 return Reader.getLocalModuleFile(F, ModuleFileID);
1470}
1471
1473LazySpecializationInfoLookupTrait::ReadKey(const unsigned char *d, unsigned) {
1474 using namespace llvm::support;
1475 return endian::readNext<uint32_t, llvm::endianness::little, unaligned>(d);
1476}
1477
1478std::pair<unsigned, unsigned>
1482
1484 const unsigned char *d,
1485 unsigned DataLen,
1486 data_type_builder &Val) {
1487 using namespace llvm::support;
1488
1489 for (unsigned NumDecls =
1491 NumDecls; --NumDecls) {
1492 LocalDeclID LocalID = LocalDeclID::get(
1493 Reader, F,
1494 endian::readNext<DeclID, llvm::endianness::little, unaligned>(d));
1495 Val.insert(Reader.getGlobalDeclID(F, LocalID));
1496 }
1497}
1498
1499bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
1500 BitstreamCursor &Cursor,
1501 uint64_t Offset,
1502 DeclContext *DC) {
1503 assert(Offset != 0);
1504
1505 SavedStreamPosition SavedPosition(Cursor);
1506 if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1507 Error(std::move(Err));
1508 return true;
1509 }
1510
1511 RecordData Record;
1512 StringRef Blob;
1513 Expected<unsigned> MaybeCode = Cursor.ReadCode();
1514 if (!MaybeCode) {
1515 Error(MaybeCode.takeError());
1516 return true;
1517 }
1518 unsigned Code = MaybeCode.get();
1519
1520 Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
1521 if (!MaybeRecCode) {
1522 Error(MaybeRecCode.takeError());
1523 return true;
1524 }
1525 unsigned RecCode = MaybeRecCode.get();
1526 if (RecCode != DECL_CONTEXT_LEXICAL) {
1527 Error("Expected lexical block");
1528 return true;
1529 }
1530
1531 assert(!isa<TranslationUnitDecl>(DC) &&
1532 "expected a TU_UPDATE_LEXICAL record for TU");
1533 // If we are handling a C++ class template instantiation, we can see multiple
1534 // lexical updates for the same record. It's important that we select only one
1535 // of them, so that field numbering works properly. Just pick the first one we
1536 // see.
1537 auto &Lex = LexicalDecls[DC];
1538 if (!Lex.first) {
1539 Lex = std::make_pair(
1540 &M, llvm::ArrayRef(
1541 reinterpret_cast<const unaligned_decl_id_t *>(Blob.data()),
1542 Blob.size() / sizeof(DeclID)));
1543 }
1545 return false;
1546}
1547
1548bool ASTReader::ReadVisibleDeclContextStorage(
1549 ModuleFile &M, BitstreamCursor &Cursor, uint64_t Offset, GlobalDeclID ID,
1550 ASTReader::VisibleDeclContextStorageKind VisibleKind) {
1551 assert(Offset != 0);
1552
1553 SavedStreamPosition SavedPosition(Cursor);
1554 if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1555 Error(std::move(Err));
1556 return true;
1557 }
1558
1559 RecordData Record;
1560 StringRef Blob;
1561 Expected<unsigned> MaybeCode = Cursor.ReadCode();
1562 if (!MaybeCode) {
1563 Error(MaybeCode.takeError());
1564 return true;
1565 }
1566 unsigned Code = MaybeCode.get();
1567
1568 Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
1569 if (!MaybeRecCode) {
1570 Error(MaybeRecCode.takeError());
1571 return true;
1572 }
1573 unsigned RecCode = MaybeRecCode.get();
1574 switch (VisibleKind) {
1575 case VisibleDeclContextStorageKind::GenerallyVisible:
1576 if (RecCode != DECL_CONTEXT_VISIBLE) {
1577 Error("Expected visible lookup table block");
1578 return true;
1579 }
1580 break;
1581 case VisibleDeclContextStorageKind::ModuleLocalVisible:
1582 if (RecCode != DECL_CONTEXT_MODULE_LOCAL_VISIBLE) {
1583 Error("Expected module local visible lookup table block");
1584 return true;
1585 }
1586 break;
1587 case VisibleDeclContextStorageKind::TULocalVisible:
1588 if (RecCode != DECL_CONTEXT_TU_LOCAL_VISIBLE) {
1589 Error("Expected TU local lookup table block");
1590 return true;
1591 }
1592 break;
1593 }
1594
1595 // We can't safely determine the primary context yet, so delay attaching the
1596 // lookup table until we're done with recursive deserialization.
1597 auto *Data = (const unsigned char*)Blob.data();
1598 switch (VisibleKind) {
1599 case VisibleDeclContextStorageKind::GenerallyVisible:
1600 PendingVisibleUpdates[ID].push_back(UpdateData{&M, Data});
1601 break;
1602 case VisibleDeclContextStorageKind::ModuleLocalVisible:
1603 PendingModuleLocalVisibleUpdates[ID].push_back(UpdateData{&M, Data});
1604 break;
1605 case VisibleDeclContextStorageKind::TULocalVisible:
1606 if (M.Kind == MK_MainFile)
1607 TULocalUpdates[ID].push_back(UpdateData{&M, Data});
1608 break;
1609 }
1610 return false;
1611}
1612
1613void ASTReader::AddSpecializations(const Decl *D, const unsigned char *Data,
1614 ModuleFile &M, bool IsPartial) {
1615 D = D->getCanonicalDecl();
1616 auto &SpecLookups =
1617 IsPartial ? PartialSpecializationsLookups : SpecializationsLookups;
1618 SpecLookups[D].Table.add(&M, Data,
1620}
1621
1622bool ASTReader::ReadSpecializations(ModuleFile &M, BitstreamCursor &Cursor,
1623 uint64_t Offset, Decl *D, bool IsPartial) {
1624 assert(Offset != 0);
1625
1626 SavedStreamPosition SavedPosition(Cursor);
1627 if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1628 Error(std::move(Err));
1629 return true;
1630 }
1631
1632 RecordData Record;
1633 StringRef Blob;
1634 Expected<unsigned> MaybeCode = Cursor.ReadCode();
1635 if (!MaybeCode) {
1636 Error(MaybeCode.takeError());
1637 return true;
1638 }
1639 unsigned Code = MaybeCode.get();
1640
1641 Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
1642 if (!MaybeRecCode) {
1643 Error(MaybeRecCode.takeError());
1644 return true;
1645 }
1646 unsigned RecCode = MaybeRecCode.get();
1647 if (RecCode != DECL_SPECIALIZATIONS &&
1648 RecCode != DECL_PARTIAL_SPECIALIZATIONS) {
1649 Error("Expected decl specs block");
1650 return true;
1651 }
1652
1653 auto *Data = (const unsigned char *)Blob.data();
1654 AddSpecializations(D, Data, M, IsPartial);
1655 return false;
1656}
1657
1658void ASTReader::Error(StringRef Msg) const {
1659 Error(diag::err_fe_ast_file_malformed, Msg);
1660 if (PP.getLangOpts().Modules &&
1661 !PP.getHeaderSearchInfo().getSpecificModuleCachePath().empty()) {
1662 Diag(diag::note_module_cache_path)
1663 << PP.getHeaderSearchInfo().getSpecificModuleCachePath();
1664 }
1665}
1666
1667void ASTReader::Error(unsigned DiagID, StringRef Arg1, StringRef Arg2,
1668 StringRef Arg3) const {
1669 Diag(DiagID) << Arg1 << Arg2 << Arg3;
1670}
1671
1672namespace {
1673struct AlreadyReportedDiagnosticError
1674 : llvm::ErrorInfo<AlreadyReportedDiagnosticError> {
1675 static char ID;
1676
1677 void log(raw_ostream &OS) const override {
1678 llvm_unreachable("reporting an already-reported diagnostic error");
1679 }
1680
1681 std::error_code convertToErrorCode() const override {
1682 return llvm::inconvertibleErrorCode();
1683 }
1684};
1685
1686char AlreadyReportedDiagnosticError::ID = 0;
1687} // namespace
1688
1689void ASTReader::Error(llvm::Error &&Err) const {
1690 handleAllErrors(
1691 std::move(Err), [](AlreadyReportedDiagnosticError &) {},
1692 [&](llvm::ErrorInfoBase &E) { return Error(E.message()); });
1693}
1694
1695//===----------------------------------------------------------------------===//
1696// Source Manager Deserialization
1697//===----------------------------------------------------------------------===//
1698
1699/// Read the line table in the source manager block.
1700void ASTReader::ParseLineTable(ModuleFile &F, const RecordData &Record) {
1701 unsigned Idx = 0;
1702 LineTableInfo &LineTable = SourceMgr.getLineTable();
1703
1704 // Parse the file names
1705 std::map<int, int> FileIDs;
1706 FileIDs[-1] = -1; // For unspecified filenames.
1707 for (unsigned I = 0; Record[Idx]; ++I) {
1708 // Extract the file name
1709 auto Filename = ReadPath(F, Record, Idx);
1710 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1711 }
1712 ++Idx;
1713
1714 // Parse the line entries
1715 std::vector<LineEntry> Entries;
1716 while (Idx < Record.size()) {
1717 FileID FID = ReadFileID(F, Record, Idx);
1718
1719 // Extract the line entries
1720 unsigned NumEntries = Record[Idx++];
1721 assert(NumEntries && "no line entries for file ID");
1722 Entries.clear();
1723 Entries.reserve(NumEntries);
1724 for (unsigned I = 0; I != NumEntries; ++I) {
1725 unsigned FileOffset = Record[Idx++];
1726 unsigned LineNo = Record[Idx++];
1727 int FilenameID = FileIDs[Record[Idx++]];
1730 unsigned IncludeOffset = Record[Idx++];
1731 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1732 FileKind, IncludeOffset));
1733 }
1734 LineTable.AddEntry(FID, Entries);
1735 }
1736}
1737
1738/// Read a source manager block
1739llvm::Error ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1740 using namespace SrcMgr;
1741
1742 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
1743
1744 // Set the source-location entry cursor to the current position in
1745 // the stream. This cursor will be used to read the contents of the
1746 // source manager block initially, and then lazily read
1747 // source-location entries as needed.
1748 SLocEntryCursor = F.Stream;
1749
1750 // The stream itself is going to skip over the source manager block.
1751 if (llvm::Error Err = F.Stream.SkipBlock())
1752 return Err;
1753
1754 // Enter the source manager block.
1755 if (llvm::Error Err = SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID))
1756 return Err;
1757 F.SourceManagerBlockStartOffset = SLocEntryCursor.GetCurrentBitNo();
1758
1759 RecordData Record;
1760 while (true) {
1761 Expected<llvm::BitstreamEntry> MaybeE =
1762 SLocEntryCursor.advanceSkippingSubblocks();
1763 if (!MaybeE)
1764 return MaybeE.takeError();
1765 llvm::BitstreamEntry E = MaybeE.get();
1766
1767 switch (E.Kind) {
1768 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1769 case llvm::BitstreamEntry::Error:
1770 return llvm::createStringError(std::errc::illegal_byte_sequence,
1771 "malformed block record in AST file");
1772 case llvm::BitstreamEntry::EndBlock:
1773 return llvm::Error::success();
1774 case llvm::BitstreamEntry::Record:
1775 // The interesting case.
1776 break;
1777 }
1778
1779 // Read a record.
1780 Record.clear();
1781 StringRef Blob;
1782 Expected<unsigned> MaybeRecord =
1783 SLocEntryCursor.readRecord(E.ID, Record, &Blob);
1784 if (!MaybeRecord)
1785 return MaybeRecord.takeError();
1786 switch (MaybeRecord.get()) {
1787 default: // Default behavior: ignore.
1788 break;
1789
1790 case SM_SLOC_FILE_ENTRY:
1793 // Once we hit one of the source location entries, we're done.
1794 return llvm::Error::success();
1795 }
1796 }
1797}
1798
1799llvm::Expected<SourceLocation::UIntTy>
1801 BitstreamCursor &Cursor = F->SLocEntryCursor;
1802 SavedStreamPosition SavedPosition(Cursor);
1803 if (llvm::Error Err = Cursor.JumpToBit(F->SLocEntryOffsetsBase +
1804 F->SLocEntryOffsets[Index]))
1805 return std::move(Err);
1806
1807 Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
1808 if (!MaybeEntry)
1809 return MaybeEntry.takeError();
1810
1811 llvm::BitstreamEntry Entry = MaybeEntry.get();
1812 if (Entry.Kind != llvm::BitstreamEntry::Record)
1813 return llvm::createStringError(
1814 std::errc::illegal_byte_sequence,
1815 "incorrectly-formatted source location entry in AST file");
1816
1818 StringRef Blob;
1819 Expected<unsigned> MaybeSLOC = Cursor.readRecord(Entry.ID, Record, &Blob);
1820 if (!MaybeSLOC)
1821 return MaybeSLOC.takeError();
1822
1823 switch (MaybeSLOC.get()) {
1824 default:
1825 return llvm::createStringError(
1826 std::errc::illegal_byte_sequence,
1827 "incorrectly-formatted source location entry in AST file");
1828 case SM_SLOC_FILE_ENTRY:
1831 return F->SLocEntryBaseOffset + Record[0];
1832 }
1833}
1834
1836 auto SLocMapI =
1837 GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset - SLocOffset - 1);
1838 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
1839 "Corrupted global sloc offset map");
1840 ModuleFile *F = SLocMapI->second;
1841
1842 bool Invalid = false;
1843
1844 auto It = llvm::upper_bound(
1845 llvm::index_range(0, F->LocalNumSLocEntries), SLocOffset,
1846 [&](SourceLocation::UIntTy Offset, std::size_t LocalIndex) {
1847 int ID = F->SLocEntryBaseID + LocalIndex;
1848 std::size_t Index = -ID - 2;
1849 if (!SourceMgr.SLocEntryOffsetLoaded[Index]) {
1850 assert(!SourceMgr.SLocEntryLoaded[Index]);
1851 auto MaybeEntryOffset = readSLocOffset(F, LocalIndex);
1852 if (!MaybeEntryOffset) {
1853 Error(MaybeEntryOffset.takeError());
1854 Invalid = true;
1855 return true;
1856 }
1857 SourceMgr.LoadedSLocEntryTable[Index] =
1858 SrcMgr::SLocEntry::getOffsetOnly(*MaybeEntryOffset);
1859 SourceMgr.SLocEntryOffsetLoaded[Index] = true;
1860 }
1861 return Offset < SourceMgr.LoadedSLocEntryTable[Index].getOffset();
1862 });
1863
1864 if (Invalid)
1865 return 0;
1866
1867 // The iterator points to the first entry with start offset greater than the
1868 // offset of interest. The previous entry must contain the offset of interest.
1869 return F->SLocEntryBaseID + *std::prev(It);
1870}
1871
1873 if (ID == 0)
1874 return false;
1875
1876 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1877 Error("source location entry ID out-of-range for AST file");
1878 return true;
1879 }
1880
1881 // Local helper to read the (possibly-compressed) buffer data following the
1882 // entry record.
1883 auto ReadBuffer = [this](
1884 BitstreamCursor &SLocEntryCursor,
1885 StringRef Name) -> std::unique_ptr<llvm::MemoryBuffer> {
1887 StringRef Blob;
1888 Expected<unsigned> MaybeCode = SLocEntryCursor.ReadCode();
1889 if (!MaybeCode) {
1890 Error(MaybeCode.takeError());
1891 return nullptr;
1892 }
1893 unsigned Code = MaybeCode.get();
1894
1895 Expected<unsigned> MaybeRecCode =
1896 SLocEntryCursor.readRecord(Code, Record, &Blob);
1897 if (!MaybeRecCode) {
1898 Error(MaybeRecCode.takeError());
1899 return nullptr;
1900 }
1901 unsigned RecCode = MaybeRecCode.get();
1902
1903 if (RecCode == SM_SLOC_BUFFER_BLOB_COMPRESSED) {
1904 // Inspect the first byte to differentiate zlib (\x78) and zstd
1905 // (little-endian 0xFD2FB528).
1906 const llvm::compression::Format F =
1907 Blob.size() > 0 && Blob.data()[0] == 0x78
1908 ? llvm::compression::Format::Zlib
1909 : llvm::compression::Format::Zstd;
1910 if (const char *Reason = llvm::compression::getReasonIfUnsupported(F)) {
1911 Error(Reason);
1912 return nullptr;
1913 }
1914 SmallVector<uint8_t, 0> Decompressed;
1915 if (llvm::Error E = llvm::compression::decompress(
1916 F, llvm::arrayRefFromStringRef(Blob), Decompressed, Record[0])) {
1917 Error("could not decompress embedded file contents: " +
1918 llvm::toString(std::move(E)));
1919 return nullptr;
1920 }
1921 return llvm::MemoryBuffer::getMemBufferCopy(
1922 llvm::toStringRef(Decompressed), Name);
1923 } else if (RecCode == SM_SLOC_BUFFER_BLOB) {
1924 return llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name, true);
1925 } else {
1926 Error("AST record has invalid code");
1927 return nullptr;
1928 }
1929 };
1930
1931 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1932 if (llvm::Error Err = F->SLocEntryCursor.JumpToBit(
1934 F->SLocEntryOffsets[ID - F->SLocEntryBaseID])) {
1935 Error(std::move(Err));
1936 return true;
1937 }
1938
1939 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
1941
1942 ++NumSLocEntriesRead;
1943 Expected<llvm::BitstreamEntry> MaybeEntry = SLocEntryCursor.advance();
1944 if (!MaybeEntry) {
1945 Error(MaybeEntry.takeError());
1946 return true;
1947 }
1948 llvm::BitstreamEntry Entry = MaybeEntry.get();
1949
1950 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1951 Error("incorrectly-formatted source location entry in AST file");
1952 return true;
1953 }
1954
1956 StringRef Blob;
1957 Expected<unsigned> MaybeSLOC =
1958 SLocEntryCursor.readRecord(Entry.ID, Record, &Blob);
1959 if (!MaybeSLOC) {
1960 Error(MaybeSLOC.takeError());
1961 return true;
1962 }
1963 switch (MaybeSLOC.get()) {
1964 default:
1965 Error("incorrectly-formatted source location entry in AST file");
1966 return true;
1967
1968 case SM_SLOC_FILE_ENTRY: {
1969 // We will detect whether a file changed and return 'Failure' for it, but
1970 // we will also try to fail gracefully by setting up the SLocEntry.
1971 unsigned InputID = Record[4];
1972 InputFile IF = getInputFile(*F, InputID);
1974 bool OverriddenBuffer = IF.isOverridden();
1975
1976 // Note that we only check if a File was returned. If it was out-of-date
1977 // we have complained but we will continue creating a FileID to recover
1978 // gracefully.
1979 if (!File)
1980 return true;
1981
1982 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1983 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1984 // This is the module's main file.
1985 IncludeLoc = getImportLocation(F);
1986 }
1988 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1989 FileID FID = SourceMgr.createFileID(*File, IncludeLoc, FileCharacter, ID,
1990 BaseOffset + Record[0]);
1991 SrcMgr::FileInfo &FileInfo = SourceMgr.getSLocEntry(FID).getFile();
1992 FileInfo.NumCreatedFIDs = Record[5];
1993 if (Record[3])
1994 FileInfo.setHasLineDirectives();
1995
1996 unsigned NumFileDecls = Record[7];
1997 if (NumFileDecls && ContextObj) {
1998 const unaligned_decl_id_t *FirstDecl = F->FileSortedDecls + Record[6];
1999 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
2000 FileDeclIDs[FID] =
2001 FileDeclsInfo(F, llvm::ArrayRef(FirstDecl, NumFileDecls));
2002 }
2003
2004 const SrcMgr::ContentCache &ContentCache =
2005 SourceMgr.getOrCreateContentCache(*File, isSystem(FileCharacter));
2006 if (OverriddenBuffer && !ContentCache.BufferOverridden &&
2007 ContentCache.ContentsEntry == ContentCache.OrigEntry &&
2008 !ContentCache.getBufferIfLoaded()) {
2009 auto Buffer = ReadBuffer(SLocEntryCursor, File->getName());
2010 if (!Buffer)
2011 return true;
2012 SourceMgr.overrideFileContents(*File, std::move(Buffer));
2013 }
2014
2015 break;
2016 }
2017
2018 case SM_SLOC_BUFFER_ENTRY: {
2019 const char *Name = Blob.data();
2020 unsigned Offset = Record[0];
2022 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
2023 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
2024 if (IncludeLoc.isInvalid() && F->isModule()) {
2025 IncludeLoc = getImportLocation(F);
2026 }
2027
2028 auto Buffer = ReadBuffer(SLocEntryCursor, Name);
2029 if (!Buffer)
2030 return true;
2031 FileID FID = SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
2032 BaseOffset + Offset, IncludeLoc);
2033 if (Record[3]) {
2034 auto &FileInfo = SourceMgr.getSLocEntry(FID).getFile();
2035 FileInfo.setHasLineDirectives();
2036 }
2037 break;
2038 }
2039
2041 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
2042 SourceLocation ExpansionBegin = ReadSourceLocation(*F, Record[2]);
2043 SourceLocation ExpansionEnd = ReadSourceLocation(*F, Record[3]);
2044 SourceMgr.createExpansionLoc(SpellingLoc, ExpansionBegin, ExpansionEnd,
2045 Record[5], Record[4], ID,
2046 BaseOffset + Record[0]);
2047 break;
2048 }
2049 }
2050
2051 return false;
2052}
2053
2054std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
2055 if (ID == 0)
2056 return std::make_pair(SourceLocation(), "");
2057
2058 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
2059 Error("source location entry ID out-of-range for AST file");
2060 return std::make_pair(SourceLocation(), "");
2061 }
2062
2063 // Find which module file this entry lands in.
2064 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
2065 if (!M->isModule())
2066 return std::make_pair(SourceLocation(), "");
2067
2068 // FIXME: Can we map this down to a particular submodule? That would be
2069 // ideal.
2070 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
2071}
2072
2073/// Find the location where the module F is imported.
2074SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
2075 if (F->ImportLoc.isValid())
2076 return F->ImportLoc;
2077
2078 // Otherwise we have a PCH. It's considered to be "imported" at the first
2079 // location of its includer.
2080 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
2081 // Main file is the importer.
2082 assert(SourceMgr.getMainFileID().isValid() && "missing main file");
2083 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
2084 }
2085 return F->ImportedBy[0]->FirstLoc;
2086}
2087
2088/// Enter a subblock of the specified BlockID with the specified cursor. Read
2089/// the abbreviations that are at the top of the block and then leave the cursor
2090/// pointing into the block.
2091llvm::Error ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor,
2092 unsigned BlockID,
2093 uint64_t *StartOfBlockOffset) {
2094 if (llvm::Error Err = Cursor.EnterSubBlock(BlockID))
2095 return Err;
2096
2097 if (StartOfBlockOffset)
2098 *StartOfBlockOffset = Cursor.GetCurrentBitNo();
2099
2100 while (true) {
2101 uint64_t Offset = Cursor.GetCurrentBitNo();
2102 Expected<unsigned> MaybeCode = Cursor.ReadCode();
2103 if (!MaybeCode)
2104 return MaybeCode.takeError();
2105 unsigned Code = MaybeCode.get();
2106
2107 // We expect all abbrevs to be at the start of the block.
2108 if (Code != llvm::bitc::DEFINE_ABBREV) {
2109 if (llvm::Error Err = Cursor.JumpToBit(Offset))
2110 return Err;
2111 return llvm::Error::success();
2112 }
2113 if (llvm::Error Err = Cursor.ReadAbbrevRecord())
2114 return Err;
2115 }
2116}
2117
2119 unsigned &Idx) {
2120 Token Tok;
2121 Tok.startToken();
2122 Tok.setLocation(ReadSourceLocation(M, Record, Idx));
2123 Tok.setKind((tok::TokenKind)Record[Idx++]);
2124 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
2125
2126 if (Tok.isAnnotation()) {
2127 Tok.setAnnotationEndLoc(ReadSourceLocation(M, Record, Idx));
2128 switch (Tok.getKind()) {
2129 case tok::annot_pragma_loop_hint: {
2130 auto *Info = new (PP.getPreprocessorAllocator()) PragmaLoopHintInfo;
2131 Info->PragmaName = ReadToken(M, Record, Idx);
2132 Info->Option = ReadToken(M, Record, Idx);
2133 unsigned NumTokens = Record[Idx++];
2135 Toks.reserve(NumTokens);
2136 for (unsigned I = 0; I < NumTokens; ++I)
2137 Toks.push_back(ReadToken(M, Record, Idx));
2138 Info->Toks = llvm::ArrayRef(Toks).copy(PP.getPreprocessorAllocator());
2139 Tok.setAnnotationValue(static_cast<void *>(Info));
2140 break;
2141 }
2142 case tok::annot_pragma_pack: {
2143 auto *Info = new (PP.getPreprocessorAllocator()) Sema::PragmaPackInfo;
2144 Info->Action = static_cast<Sema::PragmaMsStackAction>(Record[Idx++]);
2145 auto SlotLabel = ReadString(Record, Idx);
2146 Info->SlotLabel =
2147 llvm::StringRef(SlotLabel).copy(PP.getPreprocessorAllocator());
2148 Info->Alignment = ReadToken(M, Record, Idx);
2149 Tok.setAnnotationValue(static_cast<void *>(Info));
2150 break;
2151 }
2152 // Some annotation tokens do not use the PtrData field.
2153 case tok::annot_pragma_openmp:
2154 case tok::annot_pragma_openmp_end:
2155 case tok::annot_pragma_unused:
2156 case tok::annot_pragma_openacc:
2157 case tok::annot_pragma_openacc_end:
2158 case tok::annot_repl_input_end:
2159 break;
2160 default:
2161 llvm_unreachable("missing deserialization code for annotation token");
2162 }
2163 } else {
2164 Tok.setLength(Record[Idx++]);
2165 if (IdentifierInfo *II = getLocalIdentifier(M, Record[Idx++]))
2166 Tok.setIdentifierInfo(II);
2167 }
2168 return Tok;
2169}
2170
2172 BitstreamCursor &Stream = F.MacroCursor;
2173
2174 // Keep track of where we are in the stream, then jump back there
2175 // after reading this macro.
2176 SavedStreamPosition SavedPosition(Stream);
2177
2178 if (llvm::Error Err = Stream.JumpToBit(Offset)) {
2179 // FIXME this drops errors on the floor.
2180 consumeError(std::move(Err));
2181 return nullptr;
2182 }
2185 MacroInfo *Macro = nullptr;
2186 llvm::MutableArrayRef<Token> MacroTokens;
2187
2188 while (true) {
2189 // Advance to the next record, but if we get to the end of the block, don't
2190 // pop it (removing all the abbreviations from the cursor) since we want to
2191 // be able to reseek within the block and read entries.
2192 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
2194 Stream.advanceSkippingSubblocks(Flags);
2195 if (!MaybeEntry) {
2196 Error(MaybeEntry.takeError());
2197 return Macro;
2198 }
2199 llvm::BitstreamEntry Entry = MaybeEntry.get();
2200
2201 switch (Entry.Kind) {
2202 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
2203 case llvm::BitstreamEntry::Error:
2204 Error("malformed block record in AST file");
2205 return Macro;
2206 case llvm::BitstreamEntry::EndBlock:
2207 return Macro;
2208 case llvm::BitstreamEntry::Record:
2209 // The interesting case.
2210 break;
2211 }
2212
2213 // Read a record.
2214 Record.clear();
2216 if (Expected<unsigned> MaybeRecType = Stream.readRecord(Entry.ID, Record))
2217 RecType = (PreprocessorRecordTypes)MaybeRecType.get();
2218 else {
2219 Error(MaybeRecType.takeError());
2220 return Macro;
2221 }
2222 switch (RecType) {
2223 case PP_MODULE_MACRO:
2225 return Macro;
2226
2229 // If we already have a macro, that means that we've hit the end
2230 // of the definition of the macro we were looking for. We're
2231 // done.
2232 if (Macro)
2233 return Macro;
2234
2235 unsigned NextIndex = 1; // Skip identifier ID.
2236 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
2237 MacroInfo *MI = PP.AllocateMacroInfo(Loc);
2238 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
2239 MI->setIsUsed(Record[NextIndex++]);
2240 MI->setUsedForHeaderGuard(Record[NextIndex++]);
2241 MacroTokens = MI->allocateTokens(Record[NextIndex++],
2242 PP.getPreprocessorAllocator());
2243 if (RecType == PP_MACRO_FUNCTION_LIKE) {
2244 // Decode function-like macro info.
2245 bool isC99VarArgs = Record[NextIndex++];
2246 bool isGNUVarArgs = Record[NextIndex++];
2247 bool hasCommaPasting = Record[NextIndex++];
2248 MacroParams.clear();
2249 unsigned NumArgs = Record[NextIndex++];
2250 for (unsigned i = 0; i != NumArgs; ++i)
2251 MacroParams.push_back(getLocalIdentifier(F, Record[NextIndex++]));
2252
2253 // Install function-like macro info.
2254 MI->setIsFunctionLike();
2255 if (isC99VarArgs) MI->setIsC99Varargs();
2256 if (isGNUVarArgs) MI->setIsGNUVarargs();
2257 if (hasCommaPasting) MI->setHasCommaPasting();
2258 MI->setParameterList(MacroParams, PP.getPreprocessorAllocator());
2259 }
2260
2261 // Remember that we saw this macro last so that we add the tokens that
2262 // form its body to it.
2263 Macro = MI;
2264
2265 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
2266 Record[NextIndex]) {
2267 // We have a macro definition. Register the association
2269 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
2270 unsigned Index = translatePreprocessedEntityIDToIndex(GlobalID);
2271 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
2272 PreprocessingRecord::PPEntityID PPID =
2273 PPRec.getPPEntityID(Index, /*isLoaded=*/true);
2274 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
2275 PPRec.getPreprocessedEntity(PPID));
2276 if (PPDef)
2277 PPRec.RegisterMacroDefinition(Macro, PPDef);
2278 }
2279
2280 ++NumMacrosRead;
2281 break;
2282 }
2283
2284 case PP_TOKEN: {
2285 // If we see a TOKEN before a PP_MACRO_*, then the file is
2286 // erroneous, just pretend we didn't see this.
2287 if (!Macro) break;
2288 if (MacroTokens.empty()) {
2289 Error("unexpected number of macro tokens for a macro in AST file");
2290 return Macro;
2291 }
2292
2293 unsigned Idx = 0;
2294 MacroTokens[0] = ReadToken(F, Record, Idx);
2295 MacroTokens = MacroTokens.drop_front();
2296 break;
2297 }
2298 }
2299 }
2300}
2301
2304 PreprocessedEntityID LocalID) const {
2305 if (!M.ModuleOffsetMap.empty())
2306 ReadModuleOffsetMap(M);
2307
2308 unsigned ModuleFileIndex = LocalID >> 32;
2309 LocalID &= llvm::maskTrailingOnes<PreprocessedEntityID>(32);
2310 ModuleFile *MF =
2311 ModuleFileIndex ? M.TransitiveImports[ModuleFileIndex - 1] : &M;
2312 assert(MF && "malformed identifier ID encoding?");
2313
2314 if (!ModuleFileIndex) {
2315 assert(LocalID >= NUM_PREDEF_PP_ENTITY_IDS);
2316 LocalID -= NUM_PREDEF_PP_ENTITY_IDS;
2317 }
2318
2319 return (static_cast<PreprocessedEntityID>(MF->Index + 1) << 32) | LocalID;
2320}
2321
2323HeaderFileInfoTrait::getFile(const internal_key_type &Key) {
2324 FileManager &FileMgr = Reader.getFileManager();
2325 if (!Key.Imported)
2326 return FileMgr.getOptionalFileRef(Key.Filename);
2327
2328 auto Resolved =
2329 ASTReader::ResolveImportedPath(Reader.getPathBuf(), Key.Filename, M);
2330 return FileMgr.getOptionalFileRef(*Resolved);
2331}
2332
2334 uint8_t buf[sizeof(ikey.Size) + sizeof(ikey.ModTime)];
2335 memcpy(buf, &ikey.Size, sizeof(ikey.Size));
2336 memcpy(buf + sizeof(ikey.Size), &ikey.ModTime, sizeof(ikey.ModTime));
2337 return llvm::xxh3_64bits(buf);
2338}
2339
2342 internal_key_type ikey = {ekey.getSize(),
2343 M.HasTimestamps ? ekey.getModificationTime() : 0,
2344 ekey.getName(), /*Imported*/ false};
2345 return ikey;
2346}
2347
2349 if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime))
2350 return false;
2351
2352 if (llvm::sys::path::is_absolute(a.Filename) && a.Filename == b.Filename)
2353 return true;
2354
2355 // Determine whether the actual files are equivalent.
2356 OptionalFileEntryRef FEA = getFile(a);
2357 OptionalFileEntryRef FEB = getFile(b);
2358 return FEA && FEA == FEB;
2359}
2360
2361std::pair<unsigned, unsigned>
2363 return readULEBKeyDataLength(d);
2364}
2365
2367HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
2368 using namespace llvm::support;
2369
2370 internal_key_type ikey;
2371 ikey.Size = off_t(endian::readNext<uint64_t, llvm::endianness::little>(d));
2372 ikey.ModTime =
2373 time_t(endian::readNext<uint64_t, llvm::endianness::little>(d));
2374 ikey.Filename = (const char *)d;
2375 ikey.Imported = true;
2376 return ikey;
2377}
2378
2381 unsigned DataLen) {
2382 using namespace llvm::support;
2383
2384 const unsigned char *End = d + DataLen;
2385 HeaderFileInfo HFI;
2386 unsigned Flags = *d++;
2387
2389 bool Included = (Flags >> 6) & 0x01;
2390 if (Included)
2391 if ((FE = getFile(key)))
2392 // Not using \c Preprocessor::markIncluded(), since that would attempt to
2393 // deserialize this header file info again.
2394 Reader.getPreprocessor().getIncludedFiles().insert(*FE);
2395
2396 // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
2397 HFI.isImport |= (Flags >> 5) & 0x01;
2398 HFI.isPragmaOnce |= (Flags >> 4) & 0x01;
2399 HFI.DirInfo = (Flags >> 1) & 0x07;
2400 HFI.LazyControllingMacro = Reader.getGlobalIdentifierID(
2401 M, endian::readNext<IdentifierID, llvm::endianness::little>(d));
2402
2403 assert((End - d) % 4 == 0 &&
2404 "Wrong data length in HeaderFileInfo deserialization");
2405 while (d != End) {
2406 uint32_t LocalSMID =
2407 endian::readNext<uint32_t, llvm::endianness::little>(d);
2408 auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 7);
2409 LocalSMID >>= 3;
2410
2411 // This header is part of a module. Associate it with the module to enable
2412 // implicit module import.
2413 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
2414 Module *Mod = Reader.getSubmodule(GlobalSMID);
2415 ModuleMap &ModMap =
2416 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
2417
2418 if (FE || (FE = getFile(key))) {
2419 // FIXME: NameAsWritten
2420 Module::Header H = {std::string(key.Filename), "", *FE};
2421 ModMap.addHeader(Mod, H, HeaderRole, /*Imported=*/true);
2422 }
2423 HFI.mergeModuleMembership(HeaderRole);
2424 }
2425
2426 // This HeaderFileInfo was externally loaded.
2427 HFI.External = true;
2428 HFI.IsValid = true;
2429 return HFI;
2430}
2431
2433 uint32_t MacroDirectivesOffset) {
2434 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
2435 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
2436}
2437
2439 // Note that we are loading defined macros.
2440 Deserializing Macros(this);
2441
2442 for (ModuleFile &I : llvm::reverse(ModuleMgr)) {
2443 BitstreamCursor &MacroCursor = I.MacroCursor;
2444
2445 // If there was no preprocessor block, skip this file.
2446 if (MacroCursor.getBitcodeBytes().empty())
2447 continue;
2448
2449 BitstreamCursor Cursor = MacroCursor;
2450 if (llvm::Error Err = Cursor.JumpToBit(I.MacroStartOffset)) {
2451 Error(std::move(Err));
2452 return;
2453 }
2454
2456 while (true) {
2457 Expected<llvm::BitstreamEntry> MaybeE = Cursor.advanceSkippingSubblocks();
2458 if (!MaybeE) {
2459 Error(MaybeE.takeError());
2460 return;
2461 }
2462 llvm::BitstreamEntry E = MaybeE.get();
2463
2464 switch (E.Kind) {
2465 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
2466 case llvm::BitstreamEntry::Error:
2467 Error("malformed block record in AST file");
2468 return;
2469 case llvm::BitstreamEntry::EndBlock:
2470 goto NextCursor;
2471
2472 case llvm::BitstreamEntry::Record: {
2473 Record.clear();
2474 Expected<unsigned> MaybeRecord = Cursor.readRecord(E.ID, Record);
2475 if (!MaybeRecord) {
2476 Error(MaybeRecord.takeError());
2477 return;
2478 }
2479 switch (MaybeRecord.get()) {
2480 default: // Default behavior: ignore.
2481 break;
2482
2486 if (II->isOutOfDate())
2488 break;
2489 }
2490
2491 case PP_TOKEN:
2492 // Ignore tokens.
2493 break;
2494 }
2495 break;
2496 }
2497 }
2498 }
2499 NextCursor: ;
2500 }
2501}
2502
2503namespace {
2504
2505 /// Visitor class used to look up identifirs in an AST file.
2506 class IdentifierLookupVisitor {
2507 StringRef Name;
2508 unsigned NameHash;
2509 unsigned PriorGeneration;
2510 unsigned &NumIdentifierLookups;
2511 unsigned &NumIdentifierLookupHits;
2512 IdentifierInfo *Found = nullptr;
2513
2514 public:
2515 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
2516 unsigned &NumIdentifierLookups,
2517 unsigned &NumIdentifierLookupHits)
2518 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
2519 PriorGeneration(PriorGeneration),
2520 NumIdentifierLookups(NumIdentifierLookups),
2521 NumIdentifierLookupHits(NumIdentifierLookupHits) {}
2522
2523 bool operator()(ModuleFile &M) {
2524 // If we've already searched this module file, skip it now.
2525 if (M.Generation <= PriorGeneration)
2526 return true;
2527
2530 if (!IdTable)
2531 return false;
2532
2533 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
2534 Found);
2535 ++NumIdentifierLookups;
2536 ASTIdentifierLookupTable::iterator Pos =
2537 IdTable->find_hashed(Name, NameHash, &Trait);
2538 if (Pos == IdTable->end())
2539 return false;
2540
2541 // Dereferencing the iterator has the effect of building the
2542 // IdentifierInfo node and populating it with the various
2543 // declarations it needs.
2544 ++NumIdentifierLookupHits;
2545 Found = *Pos;
2546 if (Trait.hasMoreInformationInDependencies()) {
2547 // Look for the identifier in extra modules as they contain more info.
2548 return false;
2549 }
2550 return true;
2551 }
2552
2553 // Retrieve the identifier info found within the module
2554 // files.
2555 IdentifierInfo *getIdentifierInfo() const { return Found; }
2556 };
2557
2558} // namespace
2559
2561 // Note that we are loading an identifier.
2562 Deserializing AnIdentifier(this);
2563
2564 unsigned PriorGeneration = 0;
2565 if (getContext().getLangOpts().Modules)
2566 PriorGeneration = IdentifierGeneration[&II];
2567
2568 // If there is a global index, look there first to determine which modules
2569 // provably do not have any results for this identifier.
2571 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
2572 if (!loadGlobalIndex()) {
2573 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
2574 HitsPtr = &Hits;
2575 }
2576 }
2577
2578 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
2579 NumIdentifierLookups,
2580 NumIdentifierLookupHits);
2581 ModuleMgr.visit(Visitor, HitsPtr);
2583}
2584
2586 if (!II)
2587 return;
2588
2589 const_cast<IdentifierInfo *>(II)->setOutOfDate(false);
2590
2591 // Update the generation for this identifier.
2592 if (getContext().getLangOpts().Modules)
2593 IdentifierGeneration[II] = getGeneration();
2594}
2595
2597 unsigned &Idx) {
2598 uint64_t ModuleFileIndex = Record[Idx++] << 32;
2599 uint64_t LocalIndex = Record[Idx++];
2600 return getGlobalMacroID(F, (ModuleFileIndex | LocalIndex));
2601}
2602
2604 const PendingMacroInfo &PMInfo) {
2605 ModuleFile &M = *PMInfo.M;
2606
2607 BitstreamCursor &Cursor = M.MacroCursor;
2608 SavedStreamPosition SavedPosition(Cursor);
2609 if (llvm::Error Err =
2610 Cursor.JumpToBit(M.MacroOffsetsBase + PMInfo.MacroDirectivesOffset)) {
2611 Error(std::move(Err));
2612 return;
2613 }
2614
2615 struct ModuleMacroRecord {
2616 SubmoduleID SubModID;
2617 MacroInfo *MI;
2619 };
2621
2622 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
2623 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
2624 // macro histroy.
2626 while (true) {
2628 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
2629 if (!MaybeEntry) {
2630 Error(MaybeEntry.takeError());
2631 return;
2632 }
2633 llvm::BitstreamEntry Entry = MaybeEntry.get();
2634
2635 if (Entry.Kind != llvm::BitstreamEntry::Record) {
2636 Error("malformed block record in AST file");
2637 return;
2638 }
2639
2640 Record.clear();
2641 Expected<unsigned> MaybePP = Cursor.readRecord(Entry.ID, Record);
2642 if (!MaybePP) {
2643 Error(MaybePP.takeError());
2644 return;
2645 }
2646 switch ((PreprocessorRecordTypes)MaybePP.get()) {
2648 break;
2649
2650 case PP_MODULE_MACRO: {
2651 ModuleMacros.push_back(ModuleMacroRecord());
2652 auto &Info = ModuleMacros.back();
2653 unsigned Idx = 0;
2654 Info.SubModID = getGlobalSubmoduleID(M, Record[Idx++]);
2655 Info.MI = getMacro(ReadMacroID(M, Record, Idx));
2656 for (int I = Idx, N = Record.size(); I != N; ++I)
2657 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
2658 continue;
2659 }
2660
2661 default:
2662 Error("malformed block record in AST file");
2663 return;
2664 }
2665
2666 // We found the macro directive history; that's the last record
2667 // for this macro.
2668 break;
2669 }
2670
2671 // Module macros are listed in reverse dependency order.
2672 {
2673 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
2675 for (auto &MMR : ModuleMacros) {
2676 Overrides.clear();
2677 for (unsigned ModID : MMR.Overrides) {
2678 Module *Mod = getSubmodule(ModID);
2679 auto *Macro = PP.getModuleMacro(Mod, II);
2680 assert(Macro && "missing definition for overridden macro");
2681 Overrides.push_back(Macro);
2682 }
2683
2684 bool Inserted = false;
2685 Module *Owner = getSubmodule(MMR.SubModID);
2686 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
2687 }
2688 }
2689
2690 // Don't read the directive history for a module; we don't have anywhere
2691 // to put it.
2692 if (M.isModule())
2693 return;
2694
2695 // Deserialize the macro directives history in reverse source-order.
2696 MacroDirective *Latest = nullptr, *Earliest = nullptr;
2697 unsigned Idx = 0, N = Record.size();
2698 while (Idx < N) {
2699 MacroDirective *MD = nullptr;
2702 switch (K) {
2704 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
2705 MD = PP.AllocateDefMacroDirective(MI, Loc);
2706 break;
2707 }
2709 MD = PP.AllocateUndefMacroDirective(Loc);
2710 break;
2712 bool isPublic = Record[Idx++];
2713 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
2714 break;
2715 }
2716
2717 if (!Latest)
2718 Latest = MD;
2719 if (Earliest)
2720 Earliest->setPrevious(MD);
2721 Earliest = MD;
2722 }
2723
2724 if (Latest)
2725 PP.setLoadedMacroDirective(II, Earliest, Latest);
2726}
2727
2728bool ASTReader::shouldDisableValidationForFile(
2729 const serialization::ModuleFile &M) const {
2730 if (DisableValidationKind == DisableValidationForModuleKind::None)
2731 return false;
2732
2733 // If a PCH is loaded and validation is disabled for PCH then disable
2734 // validation for the PCH and the modules it loads.
2735 ModuleKind K = CurrentDeserializingModuleKind.value_or(M.Kind);
2736
2737 switch (K) {
2738 case MK_MainFile:
2739 case MK_Preamble:
2740 case MK_PCH:
2741 return bool(DisableValidationKind & DisableValidationForModuleKind::PCH);
2742 case MK_ImplicitModule:
2743 case MK_ExplicitModule:
2744 case MK_PrebuiltModule:
2745 return bool(DisableValidationKind & DisableValidationForModuleKind::Module);
2746 }
2747
2748 return false;
2749}
2750
2751static std::pair<StringRef, StringRef>
2753 const StringRef InputBlob) {
2754 uint16_t AsRequestedLength = Record[7];
2755 return {InputBlob.substr(0, AsRequestedLength),
2756 InputBlob.substr(AsRequestedLength)};
2757}
2758
2759InputFileInfo ASTReader::getInputFileInfo(ModuleFile &F, unsigned ID) {
2760 // If this ID is bogus, just return an empty input file.
2761 if (ID == 0 || ID > F.InputFileInfosLoaded.size())
2762 return InputFileInfo();
2763
2764 // If we've already loaded this input file, return it.
2765 if (F.InputFileInfosLoaded[ID - 1].isValid())
2766 return F.InputFileInfosLoaded[ID - 1];
2767
2768 // Go find this input file.
2769 BitstreamCursor &Cursor = F.InputFilesCursor;
2770 SavedStreamPosition SavedPosition(Cursor);
2771 if (llvm::Error Err = Cursor.JumpToBit(F.InputFilesOffsetBase +
2772 F.InputFileOffsets[ID - 1])) {
2773 // FIXME this drops errors on the floor.
2774 consumeError(std::move(Err));
2775 }
2776
2777 Expected<unsigned> MaybeCode = Cursor.ReadCode();
2778 if (!MaybeCode) {
2779 // FIXME this drops errors on the floor.
2780 consumeError(MaybeCode.takeError());
2781 }
2782 unsigned Code = MaybeCode.get();
2783 RecordData Record;
2784 StringRef Blob;
2785
2786 if (Expected<unsigned> Maybe = Cursor.readRecord(Code, Record, &Blob))
2787 assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE &&
2788 "invalid record type for input file");
2789 else {
2790 // FIXME this drops errors on the floor.
2791 consumeError(Maybe.takeError());
2792 }
2793
2794 assert(Record[0] == ID && "Bogus stored ID or offset");
2796 R.StoredSize = static_cast<off_t>(Record[1]);
2797 R.StoredTime = static_cast<time_t>(Record[2]);
2798 R.Overridden = static_cast<bool>(Record[3]);
2799 R.Transient = static_cast<bool>(Record[4]);
2800 R.TopLevel = static_cast<bool>(Record[5]);
2801 R.ModuleMap = static_cast<bool>(Record[6]);
2802 auto [UnresolvedFilenameAsRequested, UnresolvedFilename] =
2804 R.UnresolvedImportedFilenameAsRequested = UnresolvedFilenameAsRequested;
2805 R.UnresolvedImportedFilename = UnresolvedFilename.empty()
2806 ? UnresolvedFilenameAsRequested
2807 : UnresolvedFilename;
2808
2809 Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
2810 if (!MaybeEntry) // FIXME this drops errors on the floor.
2811 consumeError(MaybeEntry.takeError());
2812 llvm::BitstreamEntry Entry = MaybeEntry.get();
2813 assert(Entry.Kind == llvm::BitstreamEntry::Record &&
2814 "expected record type for input file hash");
2815
2816 Record.clear();
2817 if (Expected<unsigned> Maybe = Cursor.readRecord(Entry.ID, Record))
2818 assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE_HASH &&
2819 "invalid record type for input file hash");
2820 else {
2821 // FIXME this drops errors on the floor.
2822 consumeError(Maybe.takeError());
2823 }
2824 R.ContentHash = (static_cast<uint64_t>(Record[1]) << 32) |
2825 static_cast<uint64_t>(Record[0]);
2826
2827 // Note that we've loaded this input file info.
2828 F.InputFileInfosLoaded[ID - 1] = R;
2829 return R;
2830}
2831
2832static unsigned moduleKindForDiagnostic(ModuleKind Kind);
2833InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
2834 // If this ID is bogus, just return an empty input file.
2835 if (ID == 0 || ID > F.InputFilesLoaded.size())
2836 return InputFile();
2837
2838 // If we've already loaded this input file, return it.
2839 if (F.InputFilesLoaded[ID-1].getFile())
2840 return F.InputFilesLoaded[ID-1];
2841
2842 if (F.InputFilesLoaded[ID-1].isNotFound())
2843 return InputFile();
2844
2845 // Go find this input file.
2846 BitstreamCursor &Cursor = F.InputFilesCursor;
2847 SavedStreamPosition SavedPosition(Cursor);
2848 if (llvm::Error Err = Cursor.JumpToBit(F.InputFilesOffsetBase +
2849 F.InputFileOffsets[ID - 1])) {
2850 // FIXME this drops errors on the floor.
2851 consumeError(std::move(Err));
2852 }
2853
2854 InputFileInfo FI = getInputFileInfo(F, ID);
2855 off_t StoredSize = FI.StoredSize;
2856 time_t StoredTime = FI.StoredTime;
2857 bool Overridden = FI.Overridden;
2858 bool Transient = FI.Transient;
2859 auto Filename =
2860 ResolveImportedPath(PathBuf, FI.UnresolvedImportedFilenameAsRequested, F);
2861 uint64_t StoredContentHash = FI.ContentHash;
2862
2863 // For standard C++ modules, we don't need to check the inputs.
2864 bool SkipChecks = F.StandardCXXModule;
2865
2866 const HeaderSearchOptions &HSOpts =
2867 PP.getHeaderSearchInfo().getHeaderSearchOpts();
2868
2869 // The option ForceCheckCXX20ModulesInputFiles is only meaningful for C++20
2870 // modules.
2872 SkipChecks = false;
2873 Overridden = false;
2874 }
2875
2876 auto File = FileMgr.getOptionalFileRef(*Filename, /*OpenFile=*/false);
2877
2878 // For an overridden file, create a virtual file with the stored
2879 // size/timestamp.
2880 if ((Overridden || Transient || SkipChecks) && !File)
2881 File = FileMgr.getVirtualFileRef(*Filename, StoredSize, StoredTime);
2882
2883 if (!File) {
2884 if (Complain) {
2885 std::string ErrorStr = "could not find file '";
2886 ErrorStr += *Filename;
2887 ErrorStr += "' referenced by AST file '";
2888 ErrorStr += F.FileName.str();
2889 ErrorStr += "'";
2890 Error(ErrorStr);
2891 }
2892 // Record that we didn't find the file.
2894 return InputFile();
2895 }
2896
2897 // Check if there was a request to override the contents of the file
2898 // that was part of the precompiled header. Overriding such a file
2899 // can lead to problems when lexing using the source locations from the
2900 // PCH.
2901 SourceManager &SM = getSourceManager();
2902 // FIXME: Reject if the overrides are different.
2903 if ((!Overridden && !Transient) && !SkipChecks &&
2904 SM.isFileOverridden(*File)) {
2905 if (Complain)
2906 Error(diag::err_fe_pch_file_overridden, *Filename);
2907
2908 // After emitting the diagnostic, bypass the overriding file to recover
2909 // (this creates a separate FileEntry).
2910 File = SM.bypassFileContentsOverride(*File);
2911 if (!File) {
2913 return InputFile();
2914 }
2915 }
2916
2917 auto HasInputContentChanged = [&](Change OriginalChange) {
2918 assert(ValidateASTInputFilesContent &&
2919 "We should only check the content of the inputs with "
2920 "ValidateASTInputFilesContent enabled.");
2921
2922 if (StoredContentHash == 0)
2923 return OriginalChange;
2924
2925 auto MemBuffOrError = FileMgr.getBufferForFile(*File);
2926 if (!MemBuffOrError) {
2927 if (!Complain)
2928 return OriginalChange;
2929 std::string ErrorStr = "could not get buffer for file '";
2930 ErrorStr += File->getName();
2931 ErrorStr += "'";
2932 Error(ErrorStr);
2933 return OriginalChange;
2934 }
2935
2936 auto ContentHash = xxh3_64bits(MemBuffOrError.get()->getBuffer());
2937 if (StoredContentHash == static_cast<uint64_t>(ContentHash))
2938 return Change{Change::None};
2939
2940 return Change{Change::Content};
2941 };
2942 auto HasInputFileChanged = [&]() {
2943 if (StoredSize != File->getSize())
2944 return Change{Change::Size, StoredSize, File->getSize()};
2945 if (!shouldDisableValidationForFile(F) && StoredTime &&
2946 StoredTime != File->getModificationTime()) {
2947 Change MTimeChange = {Change::ModTime, StoredTime,
2948 File->getModificationTime()};
2949
2950 // In case the modification time changes but not the content,
2951 // accept the cached file as legit.
2952 if (ValidateASTInputFilesContent)
2953 return HasInputContentChanged(MTimeChange);
2954
2955 return MTimeChange;
2956 }
2957 return Change{Change::None};
2958 };
2959
2960 bool IsOutOfDate = false;
2961 auto FileChange = SkipChecks ? Change{Change::None} : HasInputFileChanged();
2962 // When ForceCheckCXX20ModulesInputFiles and ValidateASTInputFilesContent
2963 // enabled, it is better to check the contents of the inputs. Since we can't
2964 // get correct modified time information for inputs from overriden inputs.
2965 if (HSOpts.ForceCheckCXX20ModulesInputFiles && ValidateASTInputFilesContent &&
2966 F.StandardCXXModule && FileChange.Kind == Change::None)
2967 FileChange = HasInputContentChanged(FileChange);
2968
2969 // When we have StoredTime equal to zero and ValidateASTInputFilesContent,
2970 // it is better to check the content of the input files because we cannot rely
2971 // on the file modification time, which will be the same (zero) for these
2972 // files.
2973 if (!StoredTime && ValidateASTInputFilesContent &&
2974 FileChange.Kind == Change::None)
2975 FileChange = HasInputContentChanged(FileChange);
2976
2977 // For an overridden file, there is nothing to validate.
2978 if (!Overridden && FileChange.Kind != Change::None) {
2979 if (Complain) {
2980 // Build a list of the PCH imports that got us here (in reverse).
2981 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2982 while (!ImportStack.back()->ImportedBy.empty())
2983 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
2984
2985 // The top-level AST file is stale.
2986 StringRef TopLevelASTFileName(ImportStack.back()->FileName);
2987 Diag(diag::err_fe_ast_file_modified)
2988 << *Filename << moduleKindForDiagnostic(ImportStack.back()->Kind)
2989 << TopLevelASTFileName;
2990 Diag(diag::note_fe_ast_file_modified)
2991 << FileChange.Kind << (FileChange.Old && FileChange.New)
2992 << llvm::itostr(FileChange.Old.value_or(0))
2993 << llvm::itostr(FileChange.New.value_or(0));
2994
2995 // Print the import stack.
2996 if (ImportStack.size() > 1) {
2997 Diag(diag::note_ast_file_required_by)
2998 << *Filename << ImportStack[0]->FileName;
2999 for (unsigned I = 1; I < ImportStack.size(); ++I)
3000 Diag(diag::note_ast_file_required_by)
3001 << ImportStack[I - 1]->FileName << ImportStack[I]->FileName;
3002 }
3003
3005 Diag(diag::note_ast_file_rebuild_required) << TopLevelASTFileName;
3006 Diag(diag::note_ast_file_input_files_validation_status)
3008 }
3009
3010 IsOutOfDate = true;
3011 }
3012 // FIXME: If the file is overridden and we've already opened it,
3013 // issue an error (or split it into a separate FileEntry).
3014
3015 InputFile IF = InputFile(*File, Overridden || Transient, IsOutOfDate);
3016
3017 // Note that we've loaded this input file.
3018 F.InputFilesLoaded[ID-1] = IF;
3019 return IF;
3020}
3021
3022ASTReader::TemporarilyOwnedStringRef
3024 ModuleFile &ModF) {
3025 return ResolveImportedPath(Buf, Path, ModF.BaseDirectory);
3026}
3027
3028ASTReader::TemporarilyOwnedStringRef
3030 StringRef Prefix) {
3031 assert(Buf.capacity() != 0 && "Overlapping ResolveImportedPath calls");
3032
3033 if (Prefix.empty() || Path.empty() || llvm::sys::path::is_absolute(Path) ||
3034 Path == "<built-in>" || Path == "<command line>")
3035 return {Path, Buf};
3036
3037 Buf.clear();
3038 llvm::sys::path::append(Buf, Prefix, Path);
3039 StringRef ResolvedPath{Buf.data(), Buf.size()};
3040 return {ResolvedPath, Buf};
3041}
3042
3044 StringRef P,
3045 ModuleFile &ModF) {
3046 return ResolveImportedPathAndAllocate(Buf, P, ModF.BaseDirectory);
3047}
3048
3050 StringRef P,
3051 StringRef Prefix) {
3052 auto ResolvedPath = ResolveImportedPath(Buf, P, Prefix);
3053 return ResolvedPath->str();
3054}
3055
3056static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
3057 switch (ARR) {
3058 case ASTReader::Failure: return true;
3059 case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
3060 case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
3063 return !(Caps & ASTReader::ARR_ConfigurationMismatch);
3064 case ASTReader::HadErrors: return true;
3065 case ASTReader::Success: return false;
3066 }
3067
3068 llvm_unreachable("unknown ASTReadResult");
3069}
3070
3071ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(
3072 BitstreamCursor &Stream, StringRef Filename,
3073 unsigned ClientLoadCapabilities, bool AllowCompatibleConfigurationMismatch,
3074 ASTReaderListener &Listener, std::string &SuggestedPredefines) {
3075 if (llvm::Error Err = Stream.EnterSubBlock(OPTIONS_BLOCK_ID)) {
3076 // FIXME this drops errors on the floor.
3077 consumeError(std::move(Err));
3078 return Failure;
3079 }
3080
3081 // Read all of the records in the options block.
3082 RecordData Record;
3083 ASTReadResult Result = Success;
3084 while (true) {
3085 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
3086 if (!MaybeEntry) {
3087 // FIXME this drops errors on the floor.
3088 consumeError(MaybeEntry.takeError());
3089 return Failure;
3090 }
3091 llvm::BitstreamEntry Entry = MaybeEntry.get();
3092
3093 switch (Entry.Kind) {
3094 case llvm::BitstreamEntry::Error:
3095 case llvm::BitstreamEntry::SubBlock:
3096 return Failure;
3097
3098 case llvm::BitstreamEntry::EndBlock:
3099 return Result;
3100
3101 case llvm::BitstreamEntry::Record:
3102 // The interesting case.
3103 break;
3104 }
3105
3106 // Read and process a record.
3107 Record.clear();
3108 Expected<unsigned> MaybeRecordType = Stream.readRecord(Entry.ID, Record);
3109 if (!MaybeRecordType) {
3110 // FIXME this drops errors on the floor.
3111 consumeError(MaybeRecordType.takeError());
3112 return Failure;
3113 }
3114 switch ((OptionsRecordTypes)MaybeRecordType.get()) {
3115 case LANGUAGE_OPTIONS: {
3116 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
3117 if (ParseLanguageOptions(Record, Filename, Complain, Listener,
3118 AllowCompatibleConfigurationMismatch))
3119 Result = ConfigurationMismatch;
3120 break;
3121 }
3122
3123 case CODEGEN_OPTIONS: {
3124 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
3125 if (ParseCodeGenOptions(Record, Filename, Complain, Listener,
3126 AllowCompatibleConfigurationMismatch))
3127 Result = ConfigurationMismatch;
3128 break;
3129 }
3130
3131 case TARGET_OPTIONS: {
3132 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
3133 if (ParseTargetOptions(Record, Filename, Complain, Listener,
3134 AllowCompatibleConfigurationMismatch))
3135 Result = ConfigurationMismatch;
3136 break;
3137 }
3138
3139 case FILE_SYSTEM_OPTIONS: {
3140 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
3141 if (!AllowCompatibleConfigurationMismatch &&
3142 ParseFileSystemOptions(Record, Complain, Listener))
3143 Result = ConfigurationMismatch;
3144 break;
3145 }
3146
3147 case HEADER_SEARCH_OPTIONS: {
3148 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
3149 if (!AllowCompatibleConfigurationMismatch &&
3150 ParseHeaderSearchOptions(Record, Filename, Complain, Listener))
3151 Result = ConfigurationMismatch;
3152 break;
3153 }
3154
3156 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
3157 if (!AllowCompatibleConfigurationMismatch &&
3158 ParsePreprocessorOptions(Record, Filename, Complain, Listener,
3159 SuggestedPredefines))
3160 Result = ConfigurationMismatch;
3161 break;
3162 }
3163 }
3164}
3165
3166ASTReader::RelocationResult
3167ASTReader::getModuleForRelocationChecks(ModuleFile &F, bool DirectoryCheck) {
3168 // Don't emit module relocation errors if we have -fno-validate-pch.
3169 const bool IgnoreError =
3170 bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation &
3172
3173 if (!PP.getPreprocessorOpts().ModulesCheckRelocated)
3174 return {std::nullopt, IgnoreError};
3175
3176 const bool IsImplicitModule = F.Kind == MK_ImplicitModule;
3177
3178 if (!DirectoryCheck &&
3179 (!IsImplicitModule || ModuleMgr.begin()->Kind == MK_MainFile))
3180 return {std::nullopt, IgnoreError};
3181
3182 const HeaderSearchOptions &HSOpts =
3183 PP.getHeaderSearchInfo().getHeaderSearchOpts();
3184
3185 // When only validating modules once per build session,
3186 // Skip check if the timestamp is up to date or module was built in same build
3187 // session.
3188 if (HSOpts.ModulesValidateOncePerBuildSession && IsImplicitModule) {
3190 return {std::nullopt, IgnoreError};
3191 if (static_cast<uint64_t>(F.ModTime) >= 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, F.isDirectlyImported());
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 unsigned ImplicitModuleSuffixLength = 0;
3475 ASTFileSignature StoredSignature;
3476 ModuleFileName ImportedFile;
3477 std::string StoredFile;
3478 bool IgnoreImportedByNote = false;
3479
3480 // For prebuilt and explicit modules first consult the file map for
3481 // an override. Note that here we don't search prebuilt module
3482 // directories if we're not importing standard c++ module, only the
3483 // explicit name to file mappings. Also, we will still verify the
3484 // size/signature making sure it is essentially the same file but
3485 // perhaps in a different location.
3486 if (ImportedKind == MK_PrebuiltModule || ImportedKind == MK_ExplicitModule)
3487 ImportedFile = PP.getHeaderSearchInfo().getPrebuiltModuleFileName(
3488 ImportedName, /*FileMapOnly*/ !IsImportingStdCXXModule);
3489
3490 if (IsImportingStdCXXModule && ImportedFile.empty()) {
3491 Diag(diag::err_failed_to_find_module_file) << ImportedName;
3492 return Missing;
3493 }
3494
3495 if (!IsImportingStdCXXModule) {
3496 StoredSize = (off_t)Record[Idx++];
3497 StoredModTime = (time_t)Record[Idx++];
3498 ImplicitModuleSuffixLength = (unsigned)Record[Idx++];
3499
3500 StringRef SignatureBytes = Blob.substr(0, ASTFileSignature::size);
3501 StoredSignature = ASTFileSignature::create(SignatureBytes.begin(),
3502 SignatureBytes.end());
3503 Blob = Blob.substr(ASTFileSignature::size);
3504
3505 StoredFile = ReadPathBlob(BaseDirectoryAsWritten, Record, Idx, Blob);
3506 if (ImportedFile.empty()) {
3507 ImportedFile = ImplicitModuleSuffixLength
3509 StoredFile, ImplicitModuleSuffixLength)
3510 : ModuleFileName::makeExplicit(StoredFile);
3511 assert((ImportedKind == MK_ImplicitModule) ==
3512 (ImplicitModuleSuffixLength != 0));
3513 } else if (!getDiags().isIgnored(
3514 diag::warn_module_file_mapping_mismatch,
3515 CurrentImportLoc)) {
3516 auto ImportedFileRef =
3517 PP.getFileManager().getOptionalFileRef(ImportedFile);
3518 auto StoredFileRef =
3519 PP.getFileManager().getOptionalFileRef(StoredFile);
3520 if ((ImportedFileRef && StoredFileRef) &&
3521 (*ImportedFileRef != *StoredFileRef)) {
3522 Diag(diag::warn_module_file_mapping_mismatch)
3523 << ImportedFile << StoredFile;
3524 Diag(diag::note_module_file_imported_by)
3525 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
3526 IgnoreImportedByNote = true;
3527 }
3528 }
3529 }
3530
3531 // If our client can't cope with us being out of date, we can't cope with
3532 // our dependency being missing.
3533 unsigned Capabilities = ClientLoadCapabilities;
3534 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3535 Capabilities &= ~ARR_Missing;
3536
3537 // Load the AST file.
3538 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
3539 Loaded, StoredSize, StoredModTime,
3540 StoredSignature, Capabilities);
3541
3542 // Check the AST we just read from ImportedFile contains a different
3543 // module than we expected (ImportedName). This can occur for C++20
3544 // Modules when given a mismatch via -fmodule-file=<name>=<file>
3545 if (IsImportingStdCXXModule) {
3546 if (const auto *Imported =
3547 getModuleManager().lookupByFileName(ImportedFile);
3548 Imported != nullptr && Imported->ModuleName != ImportedName) {
3549 Diag(diag::err_failed_to_find_module_file) << ImportedName;
3550 Result = Missing;
3551 }
3552 }
3553
3554 // If we diagnosed a problem, produce a backtrace.
3555 bool recompilingFinalized = Result == OutOfDate &&
3556 (Capabilities & ARR_OutOfDate) &&
3557 getModuleManager()
3558 .getModuleCache()
3559 .getInMemoryModuleCache()
3560 .isPCMFinal(F.FileName);
3561 if (!IgnoreImportedByNote &&
3562 (isDiagnosedResult(Result, Capabilities) || recompilingFinalized))
3563 Diag(diag::note_module_file_imported_by)
3564 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
3565
3566 switch (Result) {
3567 case Failure: return Failure;
3568 // If we have to ignore the dependency, we'll have to ignore this too.
3569 case Missing:
3570 case OutOfDate: return OutOfDate;
3571 case VersionMismatch: return VersionMismatch;
3572 case ConfigurationMismatch: return ConfigurationMismatch;
3573 case HadErrors: return HadErrors;
3574 case Success: break;
3575 }
3576 break;
3577 }
3578
3579 case ORIGINAL_FILE:
3580 F.OriginalSourceFileID = FileID::get(Record[0]);
3581 F.ActualOriginalSourceFileName = std::string(Blob);
3582 F.OriginalSourceFileName = ResolveImportedPathAndAllocate(
3583 PathBuf, F.ActualOriginalSourceFileName, F);
3584 break;
3585
3586 case ORIGINAL_FILE_ID:
3587 F.OriginalSourceFileID = FileID::get(Record[0]);
3588 break;
3589
3590 case MODULE_NAME:
3591 F.ModuleName = std::string(Blob);
3592 Diag(diag::remark_module_import)
3593 << F.ModuleName << F.FileName << (ImportedBy ? true : false)
3594 << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());
3595 if (Listener)
3596 Listener->ReadModuleName(F.ModuleName);
3597
3598 // Validate the AST as soon as we have a name so we can exit early on
3599 // failure.
3600 if (ASTReadResult Result = readUnhashedControlBlockOnce())
3601 return Result;
3602
3603 break;
3604
3605 case MODULE_DIRECTORY: {
3606 // Save the BaseDirectory as written in the PCM for computing the module
3607 // filename for the ModuleCache.
3608 BaseDirectoryAsWritten = Blob;
3609 assert(!F.ModuleName.empty() &&
3610 "MODULE_DIRECTORY found before MODULE_NAME");
3611 F.BaseDirectory = std::string(Blob);
3612
3613 auto [MaybeM, IgnoreError] =
3614 getModuleForRelocationChecks(F, /*DirectoryCheck=*/true);
3615 if (!MaybeM.has_value())
3616 break;
3617
3618 Module *M = MaybeM.value();
3619 if (!M || !M->Directory)
3620 break;
3621 if (IgnoreError) {
3622 F.BaseDirectory = std::string(M->Directory->getName());
3623 break;
3624 }
3625 if ((F.Kind == MK_ExplicitModule) || (F.Kind == MK_PrebuiltModule))
3626 break;
3627
3628 // If we're implicitly loading a module, the base directory can't
3629 // change between the build and use.
3630 auto BuildDir = PP.getFileManager().getOptionalDirectoryRef(Blob);
3631 if (BuildDir && (*BuildDir == M->Directory)) {
3632 F.BaseDirectory = std::string(M->Directory->getName());
3633 break;
3634 }
3635 Diag(diag::remark_module_relocated)
3636 << F.ModuleName << Blob << M->Directory->getName();
3637
3638 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
3639 Diag(diag::err_imported_module_relocated)
3640 << F.ModuleName << Blob << M->Directory->getName();
3641 return OutOfDate;
3642 }
3643
3644 case MODULE_MAP_FILE:
3645 if (ASTReadResult Result =
3646 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
3647 return Result;
3648 break;
3649
3650 case INPUT_FILE_OFFSETS:
3651 NumInputs = Record[0];
3652 NumUserInputs = Record[1];
3654 (const llvm::support::unaligned_uint64_t *)Blob.data();
3655 F.InputFilesLoaded.resize(NumInputs);
3656 F.InputFileInfosLoaded.resize(NumInputs);
3657 F.NumUserInputFiles = NumUserInputs;
3658 break;
3659 }
3660 }
3661}
3662
3663llvm::Error ASTReader::ReadASTBlock(ModuleFile &F,
3664 unsigned ClientLoadCapabilities) {
3665 BitstreamCursor &Stream = F.Stream;
3666
3667 if (llvm::Error Err = Stream.EnterSubBlock(AST_BLOCK_ID))
3668 return Err;
3669 F.ASTBlockStartOffset = Stream.GetCurrentBitNo();
3670
3671 // Read all of the records and blocks for the AST file.
3672 RecordData Record;
3673 while (true) {
3674 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
3675 if (!MaybeEntry)
3676 return MaybeEntry.takeError();
3677 llvm::BitstreamEntry Entry = MaybeEntry.get();
3678
3679 switch (Entry.Kind) {
3680 case llvm::BitstreamEntry::Error:
3681 return llvm::createStringError(
3682 std::errc::illegal_byte_sequence,
3683 "error at end of module block in AST file");
3684 case llvm::BitstreamEntry::EndBlock:
3685 // Outside of C++, we do not store a lookup map for the translation unit.
3686 // Instead, mark it as needing a lookup map to be built if this module
3687 // contains any declarations lexically within it (which it always does!).
3688 // This usually has no cost, since we very rarely need the lookup map for
3689 // the translation unit outside C++.
3690 if (ASTContext *Ctx = ContextObj) {
3691 DeclContext *DC = Ctx->getTranslationUnitDecl();
3692 if (DC->hasExternalLexicalStorage() && !Ctx->getLangOpts().CPlusPlus)
3694 }
3695
3696 return llvm::Error::success();
3697 case llvm::BitstreamEntry::SubBlock:
3698 switch (Entry.ID) {
3699 case DECLTYPES_BLOCK_ID:
3700 // We lazily load the decls block, but we want to set up the
3701 // DeclsCursor cursor to point into it. Clone our current bitcode
3702 // cursor to it, enter the block and read the abbrevs in that block.
3703 // With the main cursor, we just skip over it.
3704 F.DeclsCursor = Stream;
3705 if (llvm::Error Err = Stream.SkipBlock())
3706 return Err;
3707 if (llvm::Error Err = ReadBlockAbbrevs(
3709 return Err;
3710 break;
3711
3713 F.MacroCursor = Stream;
3714 if (!PP.getExternalSource())
3715 PP.setExternalSource(this);
3716
3717 if (llvm::Error Err = Stream.SkipBlock())
3718 return Err;
3719 if (llvm::Error Err =
3720 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID))
3721 return Err;
3722 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
3723 break;
3724
3726 F.PreprocessorDetailCursor = Stream;
3727
3728 if (llvm::Error Err = Stream.SkipBlock()) {
3729 return Err;
3730 }
3731 if (llvm::Error Err = ReadBlockAbbrevs(F.PreprocessorDetailCursor,
3733 return Err;
3735 = F.PreprocessorDetailCursor.GetCurrentBitNo();
3736
3737 if (!PP.getPreprocessingRecord())
3738 PP.createPreprocessingRecord();
3739 if (!PP.getPreprocessingRecord()->getExternalSource())
3740 PP.getPreprocessingRecord()->SetExternalSource(*this);
3741 break;
3742
3744 if (llvm::Error Err = ReadSourceManagerBlock(F))
3745 return Err;
3746 break;
3747
3748 case SUBMODULE_BLOCK_ID:
3749 if (llvm::Error Err = ReadSubmoduleBlock(F, ClientLoadCapabilities))
3750 return Err;
3751 break;
3752
3753 case COMMENTS_BLOCK_ID: {
3754 BitstreamCursor C = Stream;
3755
3756 if (llvm::Error Err = Stream.SkipBlock())
3757 return Err;
3758 if (llvm::Error Err = ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID))
3759 return Err;
3760 CommentsCursors.push_back(std::make_pair(C, &F));
3761 break;
3762 }
3763
3764 default:
3765 if (llvm::Error Err = Stream.SkipBlock())
3766 return Err;
3767 break;
3768 }
3769 continue;
3770
3771 case llvm::BitstreamEntry::Record:
3772 // The interesting case.
3773 break;
3774 }
3775
3776 // Read and process a record.
3777 Record.clear();
3778 StringRef Blob;
3779 Expected<unsigned> MaybeRecordType =
3780 Stream.readRecord(Entry.ID, Record, &Blob);
3781 if (!MaybeRecordType)
3782 return MaybeRecordType.takeError();
3783 ASTRecordTypes RecordType = (ASTRecordTypes)MaybeRecordType.get();
3784
3785 // If we're not loading an AST context, we don't care about most records.
3786 if (!ContextObj) {
3787 switch (RecordType) {
3788 case IDENTIFIER_TABLE:
3789 case IDENTIFIER_OFFSET:
3791 case STATISTICS:
3794 case PP_COUNTER_VALUE:
3796 case MODULE_OFFSET_MAP:
3800 case IMPORTED_MODULES:
3801 case MACRO_OFFSET:
3802 break;
3803 default:
3804 continue;
3805 }
3806 }
3807
3808 switch (RecordType) {
3809 default: // Default behavior: ignore.
3810 break;
3811
3812 case TYPE_OFFSET: {
3813 if (F.LocalNumTypes != 0)
3814 return llvm::createStringError(
3815 std::errc::illegal_byte_sequence,
3816 "duplicate TYPE_OFFSET record in AST file");
3817 F.TypeOffsets = reinterpret_cast<const UnalignedUInt64 *>(Blob.data());
3818 F.LocalNumTypes = Record[0];
3819 F.BaseTypeIndex = getTotalNumTypes();
3820
3821 if (F.LocalNumTypes > 0)
3822 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
3823
3824 break;
3825 }
3826
3827 case DECL_OFFSET: {
3828 if (F.LocalNumDecls != 0)
3829 return llvm::createStringError(
3830 std::errc::illegal_byte_sequence,
3831 "duplicate DECL_OFFSET record in AST file");
3832 F.DeclOffsets = (const DeclOffset *)Blob.data();
3833 F.LocalNumDecls = Record[0];
3834 F.BaseDeclIndex = getTotalNumDecls();
3835
3836 if (F.LocalNumDecls > 0)
3837 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
3838
3839 break;
3840 }
3841
3842 case TU_UPDATE_LEXICAL: {
3843 DeclContext *TU = ContextObj->getTranslationUnitDecl();
3844 LexicalContents Contents(
3845 reinterpret_cast<const unaligned_decl_id_t *>(Blob.data()),
3846 static_cast<unsigned int>(Blob.size() / sizeof(DeclID)));
3847 TULexicalDecls.push_back(std::make_pair(&F, Contents));
3849 break;
3850 }
3851
3852 case UPDATE_VISIBLE: {
3853 unsigned Idx = 0;
3854 GlobalDeclID ID = ReadDeclID(F, Record, Idx);
3855 auto *Data = (const unsigned char*)Blob.data();
3856 PendingVisibleUpdates[ID].push_back(UpdateData{&F, Data});
3857 // If we've already loaded the decl, perform the updates when we finish
3858 // loading this block.
3859 if (Decl *D = GetExistingDecl(ID))
3860 PendingUpdateRecords.push_back(
3861 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3862 break;
3863 }
3864
3866 unsigned Idx = 0;
3867 GlobalDeclID ID = ReadDeclID(F, Record, Idx);
3868 auto *Data = (const unsigned char *)Blob.data();
3869 PendingModuleLocalVisibleUpdates[ID].push_back(UpdateData{&F, Data});
3870 // If we've already loaded the decl, perform the updates when we finish
3871 // loading this block.
3872 if (Decl *D = GetExistingDecl(ID))
3873 PendingUpdateRecords.push_back(
3874 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3875 break;
3876 }
3877
3879 if (F.Kind != MK_MainFile)
3880 break;
3881 unsigned Idx = 0;
3882 GlobalDeclID ID = ReadDeclID(F, Record, Idx);
3883 auto *Data = (const unsigned char *)Blob.data();
3884 TULocalUpdates[ID].push_back(UpdateData{&F, Data});
3885 // If we've already loaded the decl, perform the updates when we finish
3886 // loading this block.
3887 if (Decl *D = GetExistingDecl(ID))
3888 PendingUpdateRecords.push_back(
3889 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3890 break;
3891 }
3892
3894 unsigned Idx = 0;
3895 GlobalDeclID ID = ReadDeclID(F, Record, Idx);
3896 auto *Data = (const unsigned char *)Blob.data();
3897 PendingSpecializationsUpdates[ID].push_back(UpdateData{&F, Data});
3898 // If we've already loaded the decl, perform the updates when we finish
3899 // loading this block.
3900 if (Decl *D = GetExistingDecl(ID))
3901 PendingUpdateRecords.push_back(
3902 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3903 break;
3904 }
3905
3907 unsigned Idx = 0;
3908 GlobalDeclID ID = ReadDeclID(F, Record, Idx);
3909 auto *Data = (const unsigned char *)Blob.data();
3910 PendingPartialSpecializationsUpdates[ID].push_back(UpdateData{&F, Data});
3911 // If we've already loaded the decl, perform the updates when we finish
3912 // loading this block.
3913 if (Decl *D = GetExistingDecl(ID))
3914 PendingUpdateRecords.push_back(
3915 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3916 break;
3917 }
3918
3919 case IDENTIFIER_TABLE:
3921 reinterpret_cast<const unsigned char *>(Blob.data());
3922 if (Record[0]) {
3923 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
3925 F.IdentifierTableData + sizeof(uint32_t),
3927 ASTIdentifierLookupTrait(*this, F));
3928
3929 PP.getIdentifierTable().setExternalIdentifierLookup(this);
3930 }
3931 break;
3932
3933 case IDENTIFIER_OFFSET: {
3934 if (F.LocalNumIdentifiers != 0)
3935 return llvm::createStringError(
3936 std::errc::illegal_byte_sequence,
3937 "duplicate IDENTIFIER_OFFSET record in AST file");
3938 F.IdentifierOffsets = (const uint32_t *)Blob.data();
3940 F.BaseIdentifierID = getTotalNumIdentifiers();
3941
3942 if (F.LocalNumIdentifiers > 0)
3943 IdentifiersLoaded.resize(IdentifiersLoaded.size()
3945 break;
3946 }
3947
3949 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
3950 break;
3951
3953 // FIXME: Skip reading this record if our ASTConsumer doesn't care
3954 // about "interesting" decls (for instance, if we're building a module).
3955 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
3956 EagerlyDeserializedDecls.push_back(ReadDeclID(F, Record, I));
3957 break;
3958
3960 // FIXME: Skip reading this record if our ASTConsumer doesn't care about
3961 // them (ie: if we're not codegenerating this module).
3962 if (F.Kind == MK_MainFile ||
3963 getContext().getLangOpts().BuildingPCHWithObjectFile)
3964 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
3965 EagerlyDeserializedDecls.push_back(ReadDeclID(F, Record, I));
3966 break;
3967
3968 case SPECIAL_TYPES:
3969 if (SpecialTypes.empty()) {
3970 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3971 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
3972 break;
3973 }
3974
3975 if (Record.empty())
3976 break;
3977
3978 if (SpecialTypes.size() != Record.size())
3979 return llvm::createStringError(std::errc::illegal_byte_sequence,
3980 "invalid special-types record");
3981
3982 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
3983 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
3984 if (!SpecialTypes[I])
3985 SpecialTypes[I] = ID;
3986 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
3987 // merge step?
3988 }
3989 break;
3990
3991 case STATISTICS:
3992 TotalNumStatements += Record[0];
3993 TotalNumMacros += Record[1];
3994 TotalLexicalDeclContexts += Record[2];
3995 TotalVisibleDeclContexts += Record[3];
3996 TotalModuleLocalVisibleDeclContexts += Record[4];
3997 TotalTULocalVisibleDeclContexts += Record[5];
3998 break;
3999
4001 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4002 UnusedFileScopedDecls.push_back(ReadDeclID(F, Record, I));
4003 break;
4004
4005 case DELEGATING_CTORS:
4006 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4007 DelegatingCtorDecls.push_back(ReadDeclID(F, Record, I));
4008 break;
4009
4011 if (Record.size() % 3 != 0)
4012 return llvm::createStringError(std::errc::illegal_byte_sequence,
4013 "invalid weak identifiers record");
4014
4015 // FIXME: Ignore weak undeclared identifiers from non-original PCH
4016 // files. This isn't the way to do it :)
4017 WeakUndeclaredIdentifiers.clear();
4018
4019 // Translate the weak, undeclared identifiers into global IDs.
4020 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
4021 WeakUndeclaredIdentifiers.push_back(
4022 getGlobalIdentifierID(F, Record[I++]));
4023 WeakUndeclaredIdentifiers.push_back(
4024 getGlobalIdentifierID(F, Record[I++]));
4025 WeakUndeclaredIdentifiers.push_back(
4026 ReadSourceLocation(F, Record, I).getRawEncoding());
4027 }
4028 break;
4029
4031 if (Record.size() % 3 != 0)
4032 return llvm::createStringError(std::errc::illegal_byte_sequence,
4033 "invalid extname identifiers record");
4034
4035 // FIXME: Ignore #pragma redefine_extname'd, undeclared identifiers from
4036 // non-original PCH files. This isn't the way to do it :)
4037 ExtnameUndeclaredIdentifiers.clear();
4038
4039 // Translate the #pragma redefine_extname'd, undeclared identifiers into
4040 // global IDs.
4041 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
4042 ExtnameUndeclaredIdentifiers.push_back(
4043 getGlobalIdentifierID(F, Record[I++]));
4044 ExtnameUndeclaredIdentifiers.push_back(
4045 getGlobalIdentifierID(F, Record[I++]));
4046 ExtnameUndeclaredIdentifiers.push_back(
4047 ReadSourceLocation(F, Record, I).getRawEncoding());
4048 }
4049 break;
4050
4051 case SELECTOR_OFFSETS: {
4052 F.SelectorOffsets = (const uint32_t *)Blob.data();
4054 unsigned LocalBaseSelectorID = Record[1];
4055 F.BaseSelectorID = getTotalNumSelectors();
4056
4057 if (F.LocalNumSelectors > 0) {
4058 // Introduce the global -> local mapping for selectors within this
4059 // module.
4060 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
4061
4062 // Introduce the local -> global mapping for selectors within this
4063 // module.
4065 std::make_pair(LocalBaseSelectorID,
4066 F.BaseSelectorID - LocalBaseSelectorID));
4067
4068 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
4069 }
4070 break;
4071 }
4072
4073 case METHOD_POOL:
4074 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
4075 if (Record[0])
4077 = ASTSelectorLookupTable::Create(
4080 ASTSelectorLookupTrait(*this, F));
4081 TotalNumMethodPoolEntries += Record[1];
4082 break;
4083
4085 if (!Record.empty()) {
4086 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
4087 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
4088 Record[Idx++]));
4089 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
4090 getRawEncoding());
4091 }
4092 }
4093 break;
4094
4095 case PP_ASSUME_NONNULL_LOC: {
4096 unsigned Idx = 0;
4097 if (!Record.empty())
4098 PP.setPreambleRecordedPragmaAssumeNonNullLoc(
4099 ReadSourceLocation(F, Record, Idx));
4100 break;
4101 }
4102
4104 if (!Record.empty()) {
4105 SmallVector<SourceLocation, 64> SrcLocs;
4106 unsigned Idx = 0;
4107 while (Idx < Record.size())
4108 SrcLocs.push_back(ReadSourceLocation(F, Record, Idx));
4109 PP.setDeserializedSafeBufferOptOutMap(SrcLocs);
4110 }
4111 break;
4112 }
4113
4115 if (!Record.empty()) {
4116 unsigned Idx = 0, End = Record.size() - 1;
4117 bool ReachedEOFWhileSkipping = Record[Idx++];
4118 std::optional<Preprocessor::PreambleSkipInfo> SkipInfo;
4119 if (ReachedEOFWhileSkipping) {
4120 SourceLocation HashToken = ReadSourceLocation(F, Record, Idx);
4121 SourceLocation IfTokenLoc = ReadSourceLocation(F, Record, Idx);
4122 bool FoundNonSkipPortion = Record[Idx++];
4123 bool FoundElse = Record[Idx++];
4124 SourceLocation ElseLoc = ReadSourceLocation(F, Record, Idx);
4125 SkipInfo.emplace(HashToken, IfTokenLoc, FoundNonSkipPortion,
4126 FoundElse, ElseLoc);
4127 }
4128 SmallVector<PPConditionalInfo, 4> ConditionalStack;
4129 while (Idx < End) {
4130 auto Loc = ReadSourceLocation(F, Record, Idx);
4131 bool WasSkipping = Record[Idx++];
4132 bool FoundNonSkip = Record[Idx++];
4133 bool FoundElse = Record[Idx++];
4134 ConditionalStack.push_back(
4135 {Loc, WasSkipping, FoundNonSkip, FoundElse});
4136 }
4137 PP.setReplayablePreambleConditionalStack(ConditionalStack, SkipInfo);
4138 }
4139 break;
4140
4141 case PP_COUNTER_VALUE:
4142 if (!Record.empty() && Listener)
4143 Listener->ReadCounter(F, Record[0]);
4144 break;
4145
4146 case FILE_SORTED_DECLS:
4147 F.FileSortedDecls = (const unaligned_decl_id_t *)Blob.data();
4149 break;
4150
4152 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
4154 SourceLocation::UIntTy SLocSpaceSize = Record[1];
4156 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
4157 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
4158 SLocSpaceSize);
4159 if (!F.SLocEntryBaseID) {
4160 Diags.Report(SourceLocation(), diag::remark_sloc_usage);
4161 SourceMgr.noteSLocAddressSpaceUsage(Diags);
4162 return llvm::createStringError(std::errc::invalid_argument,
4163 "ran out of source locations");
4164 }
4165 // Make our entry in the range map. BaseID is negative and growing, so
4166 // we invert it. Because we invert it, though, we need the other end of
4167 // the range.
4168 unsigned RangeStart =
4169 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
4170 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
4172
4173 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
4174 assert((F.SLocEntryBaseOffset & SourceLocation::MacroIDBit) == 0);
4175 GlobalSLocOffsetMap.insert(
4176 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
4177 - SLocSpaceSize,&F));
4178
4179 TotalNumSLocEntries += F.LocalNumSLocEntries;
4180 break;
4181 }
4182
4183 case MODULE_OFFSET_MAP:
4184 F.ModuleOffsetMap = Blob;
4185 break;
4186
4188 ParseLineTable(F, Record);
4189 break;
4190
4191 case EXT_VECTOR_DECLS:
4192 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4193 ExtVectorDecls.push_back(ReadDeclID(F, Record, I));
4194 break;
4195
4196 case VTABLE_USES:
4197 if (Record.size() % 3 != 0)
4198 return llvm::createStringError(std::errc::illegal_byte_sequence,
4199 "Invalid VTABLE_USES record");
4200
4201 // Later tables overwrite earlier ones.
4202 // FIXME: Modules will have some trouble with this. This is clearly not
4203 // the right way to do this.
4204 VTableUses.clear();
4205
4206 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
4207 VTableUses.push_back(
4208 {ReadDeclID(F, Record, Idx),
4209 ReadSourceLocation(F, Record, Idx).getRawEncoding(),
4210 (bool)Record[Idx++]});
4211 }
4212 break;
4213
4215
4216 if (Record.size() % 2 != 0)
4217 return llvm::createStringError(
4218 std::errc::illegal_byte_sequence,
4219 "Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
4220
4221 // For standard C++20 module, we will only reads the instantiations
4222 // if it is the main file.
4223 if (!F.StandardCXXModule || F.Kind == MK_MainFile) {
4224 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
4225 PendingInstantiations.push_back(
4226 {ReadDeclID(F, Record, I),
4227 ReadSourceLocation(F, Record, I).getRawEncoding()});
4228 }
4229 }
4230 break;
4231
4232 case SEMA_DECL_REFS:
4233 if (Record.size() != 3)
4234 return llvm::createStringError(std::errc::illegal_byte_sequence,
4235 "Invalid SEMA_DECL_REFS block");
4236 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4237 SemaDeclRefs.push_back(ReadDeclID(F, Record, I));
4238 break;
4239
4240 case PPD_ENTITIES_OFFSETS: {
4241 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
4242 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
4243 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
4244
4245 unsigned StartingID;
4246 if (!PP.getPreprocessingRecord())
4247 PP.createPreprocessingRecord();
4248 if (!PP.getPreprocessingRecord()->getExternalSource())
4249 PP.getPreprocessingRecord()->SetExternalSource(*this);
4250 StartingID
4251 = PP.getPreprocessingRecord()
4252 ->allocateLoadedEntities(F.NumPreprocessedEntities);
4253 F.BasePreprocessedEntityID = StartingID;
4254
4255 if (F.NumPreprocessedEntities > 0) {
4256 // Introduce the global -> local mapping for preprocessed entities in
4257 // this module.
4258 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
4259 }
4260
4261 break;
4262 }
4263
4264 case PPD_SKIPPED_RANGES: {
4265 F.PreprocessedSkippedRangeOffsets = (const PPSkippedRange*)Blob.data();
4266 assert(Blob.size() % sizeof(PPSkippedRange) == 0);
4267 F.NumPreprocessedSkippedRanges = Blob.size() / sizeof(PPSkippedRange);
4268
4269 if (!PP.getPreprocessingRecord())
4270 PP.createPreprocessingRecord();
4271 if (!PP.getPreprocessingRecord()->getExternalSource())
4272 PP.getPreprocessingRecord()->SetExternalSource(*this);
4273 F.BasePreprocessedSkippedRangeID = PP.getPreprocessingRecord()
4274 ->allocateSkippedRanges(F.NumPreprocessedSkippedRanges);
4275
4277 GlobalSkippedRangeMap.insert(
4278 std::make_pair(F.BasePreprocessedSkippedRangeID, &F));
4279 break;
4280 }
4281
4283 if (Record.size() % 2 != 0)
4284 return llvm::createStringError(
4285 std::errc::illegal_byte_sequence,
4286 "invalid DECL_UPDATE_OFFSETS block in AST file");
4287 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/) {
4288 GlobalDeclID ID = ReadDeclID(F, Record, I);
4289 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I++]));
4290
4291 // If we've already loaded the decl, perform the updates when we finish
4292 // loading this block.
4293 if (Decl *D = GetExistingDecl(ID))
4294 PendingUpdateRecords.push_back(
4295 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
4296 }
4297 break;
4298
4300 if (Record.size() % 5 != 0)
4301 return llvm::createStringError(
4302 std::errc::illegal_byte_sequence,
4303 "invalid DELAYED_NAMESPACE_LEXICAL_VISIBLE_RECORD block in AST "
4304 "file");
4305 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/) {
4306 GlobalDeclID ID = ReadDeclID(F, Record, I);
4307
4308 uint64_t BaseOffset = F.DeclsBlockStartOffset;
4309 assert(BaseOffset && "Invalid DeclsBlockStartOffset for module file!");
4310 uint64_t LocalLexicalOffset = Record[I++];
4311 uint64_t LexicalOffset =
4312 LocalLexicalOffset ? BaseOffset + LocalLexicalOffset : 0;
4313 uint64_t LocalVisibleOffset = Record[I++];
4314 uint64_t VisibleOffset =
4315 LocalVisibleOffset ? BaseOffset + LocalVisibleOffset : 0;
4316 uint64_t LocalModuleLocalOffset = Record[I++];
4317 uint64_t ModuleLocalOffset =
4318 LocalModuleLocalOffset ? BaseOffset + LocalModuleLocalOffset : 0;
4319 uint64_t TULocalLocalOffset = Record[I++];
4320 uint64_t TULocalOffset =
4321 TULocalLocalOffset ? BaseOffset + TULocalLocalOffset : 0;
4322
4323 DelayedNamespaceOffsetMap[ID] = {
4324 {VisibleOffset, ModuleLocalOffset, TULocalOffset}, LexicalOffset};
4325
4326 assert(!GetExistingDecl(ID) &&
4327 "We shouldn't load the namespace in the front of delayed "
4328 "namespace lexical and visible block");
4329 }
4330 break;
4331 }
4332
4333 case RELATED_DECLS_MAP:
4334 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/) {
4335 GlobalDeclID ID = ReadDeclID(F, Record, I);
4336 auto &RelatedDecls = RelatedDeclsMap[ID];
4337 unsigned NN = Record[I++];
4338 RelatedDecls.reserve(NN);
4339 for (unsigned II = 0; II < NN; II++)
4340 RelatedDecls.push_back(ReadDeclID(F, Record, I));
4341 }
4342 break;
4343
4345 if (F.LocalNumObjCCategoriesInMap != 0)
4346 return llvm::createStringError(
4347 std::errc::illegal_byte_sequence,
4348 "duplicate OBJC_CATEGORIES_MAP record in AST file");
4349
4351 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
4352 break;
4353
4354 case OBJC_CATEGORIES:
4355 F.ObjCCategories.swap(Record);
4356 break;
4357
4359 // Later tables overwrite earlier ones.
4360 // FIXME: Modules will have trouble with this.
4361 CUDASpecialDeclRefs.clear();
4362 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4363 CUDASpecialDeclRefs.push_back(ReadDeclID(F, Record, I));
4364 break;
4365
4367 F.HeaderFileInfoTableData = Blob.data();
4369 if (Record[0]) {
4370 F.HeaderFileInfoTable = HeaderFileInfoLookupTable::Create(
4371 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
4372 (const unsigned char *)F.HeaderFileInfoTableData,
4373 HeaderFileInfoTrait(*this, F));
4374
4375 PP.getHeaderSearchInfo().SetExternalSource(this);
4376 if (!PP.getHeaderSearchInfo().getExternalLookup())
4377 PP.getHeaderSearchInfo().SetExternalLookup(this);
4378 }
4379 break;
4380
4381 case FP_PRAGMA_OPTIONS:
4382 // Later tables overwrite earlier ones.
4383 FPPragmaOptions.swap(Record);
4384 break;
4385
4387 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4388 DeclsWithEffectsToVerify.push_back(ReadDeclID(F, Record, I));
4389 break;
4390
4391 case OPENCL_EXTENSIONS:
4392 for (unsigned I = 0, E = Record.size(); I != E; ) {
4393 auto Name = ReadString(Record, I);
4394 auto &OptInfo = OpenCLExtensions.OptMap[Name];
4395 OptInfo.Supported = Record[I++] != 0;
4396 OptInfo.Enabled = Record[I++] != 0;
4397 OptInfo.WithPragma = Record[I++] != 0;
4398 OptInfo.Avail = Record[I++];
4399 OptInfo.Core = Record[I++];
4400 OptInfo.Opt = Record[I++];
4401 }
4402 break;
4403
4405 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4406 TentativeDefinitions.push_back(ReadDeclID(F, Record, I));
4407 break;
4408
4409 case KNOWN_NAMESPACES:
4410 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4411 KnownNamespaces.push_back(ReadDeclID(F, Record, I));
4412 break;
4413
4414 case UNDEFINED_BUT_USED:
4415 if (Record.size() % 2 != 0)
4416 return llvm::createStringError(std::errc::illegal_byte_sequence,
4417 "invalid undefined-but-used record");
4418 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
4419 UndefinedButUsed.push_back(
4420 {ReadDeclID(F, Record, I),
4421 ReadSourceLocation(F, Record, I).getRawEncoding()});
4422 }
4423 break;
4424
4426 for (unsigned I = 0, N = Record.size(); I != N;) {
4427 DelayedDeleteExprs.push_back(ReadDeclID(F, Record, I).getRawValue());
4428 const uint64_t Count = Record[I++];
4429 DelayedDeleteExprs.push_back(Count);
4430 for (uint64_t C = 0; C < Count; ++C) {
4431 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
4432 bool IsArrayForm = Record[I++] == 1;
4433 DelayedDeleteExprs.push_back(IsArrayForm);
4434 }
4435 }
4436 break;
4437
4438 case VTABLES_TO_EMIT:
4439 if (F.Kind == MK_MainFile ||
4440 getContext().getLangOpts().BuildingPCHWithObjectFile)
4441 for (unsigned I = 0, N = Record.size(); I != N;)
4442 VTablesToEmit.push_back(ReadDeclID(F, Record, I));
4443 break;
4444
4445 case IMPORTED_MODULES:
4446 if (!F.isModule()) {
4447 // If we aren't loading a module (which has its own exports), make
4448 // all of the imported modules visible.
4449 // FIXME: Deal with macros-only imports.
4450 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
4451 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
4452 SourceLocation Loc = ReadSourceLocation(F, Record, I);
4453 if (GlobalID) {
4454 PendingImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
4455 if (DeserializationListener)
4456 DeserializationListener->ModuleImportRead(GlobalID, Loc);
4457 }
4458 }
4459 }
4460 break;
4461
4462 case MACRO_OFFSET: {
4463 if (F.LocalNumMacros != 0)
4464 return llvm::createStringError(
4465 std::errc::illegal_byte_sequence,
4466 "duplicate MACRO_OFFSET record in AST file");
4467 F.MacroOffsets = (const uint32_t *)Blob.data();
4468 F.LocalNumMacros = Record[0];
4470 F.BaseMacroID = getTotalNumMacros();
4471
4472 if (F.LocalNumMacros > 0)
4473 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
4474 break;
4475 }
4476
4478 LateParsedTemplates.emplace_back(
4479 std::piecewise_construct, std::forward_as_tuple(&F),
4480 std::forward_as_tuple(Record.begin(), Record.end()));
4481 break;
4482
4484 if (Record.size() != 1)
4485 return llvm::createStringError(std::errc::illegal_byte_sequence,
4486 "invalid pragma optimize record");
4487 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
4488 break;
4489
4491 if (Record.size() != 1)
4492 return llvm::createStringError(std::errc::illegal_byte_sequence,
4493 "invalid pragma ms_struct record");
4494 PragmaMSStructState = Record[0];
4495 break;
4496
4498 if (Record.size() != 2)
4499 return llvm::createStringError(
4500 std::errc::illegal_byte_sequence,
4501 "invalid pragma pointers to members record");
4502 PragmaMSPointersToMembersState = Record[0];
4503 PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]);
4504 break;
4505
4507 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4508 UnusedLocalTypedefNameCandidates.push_back(ReadDeclID(F, Record, I));
4509 break;
4510
4512 if (Record.size() != 1)
4513 return llvm::createStringError(std::errc::illegal_byte_sequence,
4514 "invalid cuda pragma options record");
4515 ForceHostDeviceDepth = Record[0];
4516 break;
4517
4519 if (Record.size() < 3)
4520 return llvm::createStringError(std::errc::illegal_byte_sequence,
4521 "invalid pragma pack record");
4522 PragmaAlignPackCurrentValue = ReadAlignPackInfo(Record[0]);
4523 PragmaAlignPackCurrentLocation = ReadSourceLocation(F, Record[1]);
4524 unsigned NumStackEntries = Record[2];
4525 unsigned Idx = 3;
4526 // Reset the stack when importing a new module.
4527 PragmaAlignPackStack.clear();
4528 for (unsigned I = 0; I < NumStackEntries; ++I) {
4529 PragmaAlignPackStackEntry Entry;
4530 Entry.Value = ReadAlignPackInfo(Record[Idx++]);
4531 Entry.Location = ReadSourceLocation(F, Record[Idx++]);
4532 Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]);
4533 PragmaAlignPackStrings.push_back(ReadString(Record, Idx));
4534 Entry.SlotLabel = PragmaAlignPackStrings.back();
4535 PragmaAlignPackStack.push_back(Entry);
4536 }
4537 break;
4538 }
4539
4541 if (Record.size() < 3)
4542 return llvm::createStringError(std::errc::illegal_byte_sequence,
4543 "invalid pragma float control record");
4544 FpPragmaCurrentValue = FPOptionsOverride::getFromOpaqueInt(Record[0]);
4545 FpPragmaCurrentLocation = ReadSourceLocation(F, Record[1]);
4546 unsigned NumStackEntries = Record[2];
4547 unsigned Idx = 3;
4548 // Reset the stack when importing a new module.
4549 FpPragmaStack.clear();
4550 for (unsigned I = 0; I < NumStackEntries; ++I) {
4551 FpPragmaStackEntry Entry;
4552 Entry.Value = FPOptionsOverride::getFromOpaqueInt(Record[Idx++]);
4553 Entry.Location = ReadSourceLocation(F, Record[Idx++]);
4554 Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]);
4555 FpPragmaStrings.push_back(ReadString(Record, Idx));
4556 Entry.SlotLabel = FpPragmaStrings.back();
4557 FpPragmaStack.push_back(Entry);
4558 }
4559 break;
4560 }
4561
4563 for (unsigned I = 0, N = Record.size(); I != N; /*in loop*/)
4564 DeclsToCheckForDeferredDiags.insert(ReadDeclID(F, Record, I));
4565 break;
4566
4568 unsigned NumRecords = Record.front();
4569 // Last record which is used to keep number of valid records.
4570 if (Record.size() - 1 != NumRecords)
4571 return llvm::createStringError(std::errc::illegal_byte_sequence,
4572 "invalid rvv intrinsic pragma record");
4573
4574 if (RISCVVecIntrinsicPragma.empty())
4575 RISCVVecIntrinsicPragma.append(NumRecords, 0);
4576 // There might be multiple precompiled modules imported, we need to union
4577 // them all.
4578 for (unsigned i = 0; i < NumRecords; ++i)
4579 RISCVVecIntrinsicPragma[i] |= Record[i + 1];
4580 break;
4581 }
4582 }
4583 }
4584}
4585
4586void ASTReader::ReadModuleOffsetMap(ModuleFile &F) const {
4587 assert(!F.ModuleOffsetMap.empty() && "no module offset map to read");
4588
4589 // Additional remapping information.
4590 const unsigned char *Data = (const unsigned char*)F.ModuleOffsetMap.data();
4591 const unsigned char *DataEnd = Data + F.ModuleOffsetMap.size();
4592 F.ModuleOffsetMap = StringRef();
4593
4595 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
4596 RemapBuilder SelectorRemap(F.SelectorRemap);
4597
4598 auto &ImportedModuleVector = F.TransitiveImports;
4599 assert(ImportedModuleVector.empty());
4600
4601 while (Data < DataEnd) {
4602 // FIXME: Looking up dependency modules by filename is horrible. Let's
4603 // start fixing this with prebuilt, explicit and implicit modules and see
4604 // how it goes...
4605 using namespace llvm::support;
4606 ModuleKind Kind = static_cast<ModuleKind>(
4607 endian::readNext<uint8_t, llvm::endianness::little>(Data));
4608 uint16_t Len = endian::readNext<uint16_t, llvm::endianness::little>(Data);
4609 StringRef Name = StringRef((const char*)Data, Len);
4610 Data += Len;
4611 ModuleFile *OM =
4614 ? ModuleMgr.lookupByModuleName(Name)
4615 : ModuleMgr.lookupByFileName(ModuleFileName::makeExplicit(Name)));
4616 if (!OM) {
4617 std::string Msg = "refers to unknown module, cannot find ";
4618 Msg.append(std::string(Name));
4619 Error(Msg);
4620 return;
4621 }
4622
4623 ImportedModuleVector.push_back(OM);
4624
4625 uint32_t SubmoduleIDOffset =
4626 endian::readNext<uint32_t, llvm::endianness::little>(Data);
4627 uint32_t SelectorIDOffset =
4628 endian::readNext<uint32_t, llvm::endianness::little>(Data);
4629
4630 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
4631 RemapBuilder &Remap) {
4632 constexpr uint32_t None = std::numeric_limits<uint32_t>::max();
4633 if (Offset != None)
4634 Remap.insert(std::make_pair(Offset,
4635 static_cast<int>(BaseOffset - Offset)));
4636 };
4637
4638 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
4639 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
4640 }
4641}
4642
4644ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
4645 const ModuleFile *ImportedBy,
4646 unsigned ClientLoadCapabilities) {
4647 unsigned Idx = 0;
4648 F.ModuleMapPath = ReadPath(F, Record, Idx);
4649
4650 // Try to resolve ModuleName in the current header search context and
4651 // verify that it is found in the same module map file as we saved. If the
4652 // top-level AST file is a main file, skip this check because there is no
4653 // usable header search context.
4654 assert(!F.ModuleName.empty() &&
4655 "MODULE_NAME should come before MODULE_MAP_FILE");
4656 auto [MaybeM, IgnoreError] =
4657 getModuleForRelocationChecks(F, /*DirectoryCheck=*/false);
4658 if (MaybeM.has_value()) {
4659 // An implicitly-loaded module file should have its module listed in some
4660 // module map file that we've already loaded.
4661 Module *M = MaybeM.value();
4662 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
4663 OptionalFileEntryRef ModMap =
4664 M ? Map.getModuleMapFileForUniquing(M) : std::nullopt;
4665 if (!IgnoreError && !ModMap) {
4666 if (M && M->Directory)
4667 Diag(diag::remark_module_relocated)
4668 << F.ModuleName << F.BaseDirectory << M->Directory->getName();
4669
4670 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities)) {
4671 if (auto ASTFileName = M ? M->getASTFileName() : nullptr) {
4672 // This module was defined by an imported (explicit) module.
4673 Diag(diag::err_module_file_conflict)
4674 << F.ModuleName << F.FileName << *ASTFileName;
4675 // TODO: Add a note with the module map paths if they differ.
4676 } else {
4677 // This module was built with a different module map.
4678 Diag(diag::err_imported_module_not_found)
4679 << F.ModuleName << F.FileName
4680 << (ImportedBy ? ImportedBy->FileName.str() : "")
4681 << F.ModuleMapPath << !ImportedBy;
4682 // In case it was imported by a PCH, there's a chance the user is
4683 // just missing to include the search path to the directory containing
4684 // the modulemap.
4685 if (ImportedBy && ImportedBy->Kind == MK_PCH)
4686 Diag(diag::note_imported_by_pch_module_not_found)
4687 << llvm::sys::path::parent_path(F.ModuleMapPath);
4688 }
4689 }
4690 return OutOfDate;
4691 }
4692
4693 assert(M && M->Name == F.ModuleName && "found module with different name");
4694
4695 // Check the primary module map file.
4696 auto StoredModMap = FileMgr.getOptionalFileRef(F.ModuleMapPath);
4697 if (!StoredModMap || *StoredModMap != ModMap) {
4698 assert(ModMap && "found module is missing module map file");
4699 assert((ImportedBy || F.Kind == MK_ImplicitModule) &&
4700 "top-level import should be verified");
4701 bool NotImported = F.Kind == MK_ImplicitModule && !ImportedBy;
4702 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4703 Diag(diag::err_imported_module_modmap_changed)
4704 << F.ModuleName << (NotImported ? F.FileName : ImportedBy->FileName)
4705 << ModMap->getName() << F.ModuleMapPath << NotImported;
4706 return OutOfDate;
4707 }
4708
4709 ModuleMap::AdditionalModMapsSet AdditionalStoredMaps;
4710 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
4711 // FIXME: we should use input files rather than storing names.
4712 std::string Filename = ReadPath(F, Record, Idx);
4713 auto SF = FileMgr.getOptionalFileRef(Filename, false, false);
4714 if (!SF) {
4715 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4716 Error("could not find file '" + Filename +"' referenced by AST file");
4717 return OutOfDate;
4718 }
4719 AdditionalStoredMaps.insert(*SF);
4720 }
4721
4722 // Check any additional module map files (e.g. module.private.modulemap)
4723 // that are not in the pcm.
4724 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
4725 for (FileEntryRef ModMap : *AdditionalModuleMaps) {
4726 // Remove files that match
4727 // Note: SmallPtrSet::erase is really remove
4728 if (!AdditionalStoredMaps.erase(ModMap)) {
4729 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4730 Diag(diag::err_module_different_modmap)
4731 << F.ModuleName << /*new*/0 << ModMap.getName();
4732 return OutOfDate;
4733 }
4734 }
4735 }
4736
4737 // Check any additional module map files that are in the pcm, but not
4738 // found in header search. Cases that match are already removed.
4739 for (FileEntryRef ModMap : AdditionalStoredMaps) {
4740 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4741 Diag(diag::err_module_different_modmap)
4742 << F.ModuleName << /*not new*/1 << ModMap.getName();
4743 return OutOfDate;
4744 }
4745 }
4746
4747 if (Listener)
4748 Listener->ReadModuleMapFile(F.ModuleMapPath);
4749 return Success;
4750}
4751
4752/// Move the given method to the back of the global list of methods.
4754 // Find the entry for this selector in the method pool.
4755 SemaObjC::GlobalMethodPool::iterator Known =
4756 S.ObjC().MethodPool.find(Method->getSelector());
4757 if (Known == S.ObjC().MethodPool.end())
4758 return;
4759
4760 // Retrieve the appropriate method list.
4761 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
4762 : Known->second.second;
4763 bool Found = false;
4764 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
4765 if (!Found) {
4766 if (List->getMethod() == Method) {
4767 Found = true;
4768 } else {
4769 // Keep searching.
4770 continue;
4771 }
4772 }
4773
4774 if (List->getNext())
4775 List->setMethod(List->getNext()->getMethod());
4776 else
4777 List->setMethod(Method);
4778 }
4779}
4780
4781void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
4782 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
4783 for (Decl *D : Names) {
4784 bool wasHidden = !D->isUnconditionallyVisible();
4786
4787 if (wasHidden && SemaObj) {
4788 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
4790 }
4791 }
4792 }
4793}
4794
4796 Module::NameVisibilityKind NameVisibility,
4797 SourceLocation ImportLoc) {
4800 Stack.push_back(Mod);
4801 while (!Stack.empty()) {
4802 Mod = Stack.pop_back_val();
4803
4804 if (NameVisibility <= Mod->NameVisibility) {
4805 // This module already has this level of visibility (or greater), so
4806 // there is nothing more to do.
4807 continue;
4808 }
4809
4810 if (Mod->isUnimportable()) {
4811 // Modules that aren't importable cannot be made visible.
4812 continue;
4813 }
4814
4815 // Update the module's name visibility.
4816 Mod->NameVisibility = NameVisibility;
4817
4818 // If we've already deserialized any names from this module,
4819 // mark them as visible.
4820 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
4821 if (Hidden != HiddenNamesMap.end()) {
4822 auto HiddenNames = std::move(*Hidden);
4823 HiddenNamesMap.erase(Hidden);
4824 makeNamesVisible(HiddenNames.second, HiddenNames.first);
4825 assert(!HiddenNamesMap.contains(Mod) &&
4826 "making names visible added hidden names");
4827 }
4828
4829 // Push any exported modules onto the stack to be marked as visible.
4831 Mod->getExportedModules(Exports);
4833 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
4834 Module *Exported = *I;
4835 if (Visited.insert(Exported).second)
4836 Stack.push_back(Exported);
4837 }
4838 }
4839}
4840
4841/// We've merged the definition \p MergedDef into the existing definition
4842/// \p Def. Ensure that \p Def is made visible whenever \p MergedDef is made
4843/// visible.
4845 NamedDecl *MergedDef) {
4846 if (!Def->isUnconditionallyVisible()) {
4847 // If MergedDef is visible or becomes visible, make the definition visible.
4848 if (MergedDef->isUnconditionallyVisible())
4850 else {
4851 getContext().mergeDefinitionIntoModule(
4852 Def, MergedDef->getImportedOwningModule(),
4853 /*NotifyListeners*/ false);
4854 PendingMergedDefinitionsToDeduplicate.insert(Def);
4855 }
4856 }
4857}
4858
4860 if (GlobalIndex)
4861 return false;
4862
4863 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
4864 !PP.getLangOpts().Modules)
4865 return true;
4866
4867 // Try to load the global index.
4868 TriedLoadingGlobalIndex = true;
4869 StringRef SpecificModuleCachePath =
4870 getPreprocessor().getHeaderSearchInfo().getSpecificModuleCachePath();
4871 std::pair<GlobalModuleIndex *, llvm::Error> Result =
4872 GlobalModuleIndex::readIndex(SpecificModuleCachePath);
4873 if (llvm::Error Err = std::move(Result.second)) {
4874 assert(!Result.first);
4875 consumeError(std::move(Err)); // FIXME this drops errors on the floor.
4876 return true;
4877 }
4878
4879 GlobalIndex.reset(Result.first);
4880 ModuleMgr.setGlobalIndex(GlobalIndex.get());
4881 return false;
4882}
4883
4885 return PP.getLangOpts().Modules && UseGlobalIndex &&
4886 !hasGlobalIndex() && TriedLoadingGlobalIndex;
4887}
4888
4889/// Given a cursor at the start of an AST file, scan ahead and drop the
4890/// cursor into the start of the given block ID, returning false on success and
4891/// true on failure.
4892static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
4893 while (true) {
4894 Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
4895 if (!MaybeEntry) {
4896 // FIXME this drops errors on the floor.
4897 consumeError(MaybeEntry.takeError());
4898 return true;
4899 }
4900 llvm::BitstreamEntry Entry = MaybeEntry.get();
4901
4902 switch (Entry.Kind) {
4903 case llvm::BitstreamEntry::Error:
4904 case llvm::BitstreamEntry::EndBlock:
4905 return true;
4906
4907 case llvm::BitstreamEntry::Record:
4908 // Ignore top-level records.
4909 if (Expected<unsigned> Skipped = Cursor.skipRecord(Entry.ID))
4910 break;
4911 else {
4912 // FIXME this drops errors on the floor.
4913 consumeError(Skipped.takeError());
4914 return true;
4915 }
4916
4917 case llvm::BitstreamEntry::SubBlock:
4918 if (Entry.ID == BlockID) {
4919 if (llvm::Error Err = Cursor.EnterSubBlock(BlockID)) {
4920 // FIXME this drops the error on the floor.
4921 consumeError(std::move(Err));
4922 return true;
4923 }
4924 // Found it!
4925 return false;
4926 }
4927
4928 if (llvm::Error Err = Cursor.SkipBlock()) {
4929 // FIXME this drops the error on the floor.
4930 consumeError(std::move(Err));
4931 return true;
4932 }
4933 }
4934 }
4935}
4936
4939 SourceLocation ImportLoc,
4940 unsigned ClientLoadCapabilities,
4941 ModuleFile **NewLoadedModuleFile) {
4942 llvm::TimeTraceScope scope("ReadAST", FileName);
4943
4944 llvm::SaveAndRestore SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
4946 CurrentDeserializingModuleKind, Type);
4947
4948 // Defer any pending actions until we get to the end of reading the AST file.
4949 Deserializing AnASTFile(this);
4950
4951 // Bump the generation number.
4952 unsigned PreviousGeneration = 0;
4953 if (ContextObj)
4954 PreviousGeneration = incrementGeneration(*ContextObj);
4955
4956 unsigned NumModules = ModuleMgr.size();
4958 if (ASTReadResult ReadResult =
4959 ReadASTCore(FileName, Type, ImportLoc,
4960 /*ImportedBy=*/nullptr, Loaded, 0, 0, ASTFileSignature(),
4961 ClientLoadCapabilities)) {
4962 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules);
4963
4964 // If we find that any modules are unusable, the global index is going
4965 // to be out-of-date. Just remove it.
4966 GlobalIndex.reset();
4967 ModuleMgr.setGlobalIndex(nullptr);
4968 return ReadResult;
4969 }
4970
4971 if (NewLoadedModuleFile && !Loaded.empty())
4972 *NewLoadedModuleFile = Loaded.back().Mod;
4973
4974 // Here comes stuff that we only do once the entire chain is loaded. Do *not*
4975 // remove modules from this point. Various fields are updated during reading
4976 // the AST block and removing the modules would result in dangling pointers.
4977 // They are generally only incidentally dereferenced, ie. a binary search
4978 // runs over `GlobalSLocEntryMap`, which could cause an invalid module to
4979 // be dereferenced but it wouldn't actually be used.
4980
4981 // Load the AST blocks of all of the modules that we loaded. We can still
4982 // hit errors parsing the ASTs at this point.
4983 for (ImportedModule &M : Loaded) {
4984 ModuleFile &F = *M.Mod;
4985 llvm::TimeTraceScope Scope2("Read Loaded AST", F.ModuleName);
4986
4987 // Read the AST block.
4988 if (llvm::Error Err = ReadASTBlock(F, ClientLoadCapabilities)) {
4989 Error(std::move(Err));
4990 return Failure;
4991 }
4992
4993 // The AST block should always have a definition for the main module.
4994 if (F.isModule() && !F.DidReadTopLevelSubmodule) {
4995 Error(diag::err_module_file_missing_top_level_submodule, F.FileName);
4996 return Failure;
4997 }
4998
4999 // Read the extension blocks.
5001 if (llvm::Error Err = ReadExtensionBlock(F)) {
5002 Error(std::move(Err));
5003 return Failure;
5004 }
5005 }
5006
5007 // Once read, set the ModuleFile bit base offset and update the size in
5008 // bits of all files we've seen.
5009 F.GlobalBitOffset = TotalModulesSizeInBits;
5010 TotalModulesSizeInBits += F.SizeInBits;
5011 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
5012 }
5013
5014 // Preload source locations and interesting indentifiers.
5015 for (ImportedModule &M : Loaded) {
5016 ModuleFile &F = *M.Mod;
5017
5018 // Map the original source file ID into the ID space of the current
5019 // compilation.
5022
5023 for (auto Offset : F.PreloadIdentifierOffsets) {
5024 const unsigned char *Data = F.IdentifierTableData + Offset;
5025
5026 ASTIdentifierLookupTrait Trait(*this, F);
5027 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
5028 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
5029
5030 IdentifierInfo *II;
5031 if (!PP.getLangOpts().CPlusPlus) {
5032 // Identifiers present in both the module file and the importing
5033 // instance are marked out-of-date so that they can be deserialized
5034 // on next use via ASTReader::updateOutOfDateIdentifier().
5035 // Identifiers present in the module file but not in the importing
5036 // instance are ignored for now, preventing growth of the identifier
5037 // table. They will be deserialized on first use via ASTReader::get().
5038 auto It = PP.getIdentifierTable().find(Key);
5039 if (It == PP.getIdentifierTable().end())
5040 continue;
5041 II = It->second;
5042 } else {
5043 // With C++ modules, not many identifiers are considered interesting.
5044 // All identifiers in the module file can be placed into the identifier
5045 // table of the importing instance and marked as out-of-date. This makes
5046 // ASTReader::get() a no-op, and deserialization will take place on
5047 // first/next use via ASTReader::updateOutOfDateIdentifier().
5048 II = &PP.getIdentifierTable().getOwn(Key);
5049 }
5050
5051 II->setOutOfDate(true);
5052
5053 // Mark this identifier as being from an AST file so that we can track
5054 // whether we need to serialize it.
5055 markIdentifierFromAST(*this, *II, /*IsModule=*/true);
5056
5057 // Associate the ID with the identifier so that the writer can reuse it.
5058 auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
5059 SetIdentifierInfo(ID, II);
5060 }
5061 }
5062
5063 // Builtins and library builtins have already been initialized. Mark all
5064 // identifiers as out-of-date, so that they are deserialized on first use.
5065 if (Type == MK_PCH || Type == MK_Preamble || Type == MK_MainFile)
5066 for (auto &Id : PP.getIdentifierTable())
5067 Id.second->setOutOfDate(true);
5068
5069 // Mark selectors as out of date.
5070 for (const auto &Sel : SelectorGeneration)
5071 SelectorOutOfDate[Sel.first] = true;
5072
5073 // Setup the import locations and notify the module manager that we've
5074 // committed to these module files.
5075 for (ImportedModule &M : Loaded) {
5076 ModuleFile &F = *M.Mod;
5077
5078 ModuleMgr.moduleFileAccepted(&F);
5079
5080 // Set the import location.
5081 F.DirectImportLoc = ImportLoc;
5082 // FIXME: We assume that locations from PCH / preamble do not need
5083 // any translation.
5084 if (!M.ImportedBy)
5085 F.ImportLoc = M.ImportLoc;
5086 else
5087 F.ImportLoc = TranslateSourceLocation(*M.ImportedBy, M.ImportLoc);
5088 }
5089
5090 // Resolve any unresolved module exports.
5091 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
5092 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
5094 Module *ResolvedMod = getSubmodule(GlobalID);
5095
5096 switch (Unresolved.Kind) {
5097 case UnresolvedModuleRef::Conflict:
5098 if (ResolvedMod) {
5099 Module::Conflict Conflict;
5100 Conflict.Other = ResolvedMod;
5101 Conflict.Message = Unresolved.String.str();
5102 Unresolved.Mod->Conflicts.push_back(Conflict);
5103 }
5104 continue;
5105
5106 case UnresolvedModuleRef::Import:
5107 if (ResolvedMod)
5108 Unresolved.Mod->Imports.insert(ResolvedMod);
5109 continue;
5110
5111 case UnresolvedModuleRef::Affecting:
5112 if (ResolvedMod)
5113 Unresolved.Mod->AffectingClangModules.insert(ResolvedMod);
5114 continue;
5115
5116 case UnresolvedModuleRef::Export:
5117 if (ResolvedMod || Unresolved.IsWildcard)
5118 Unresolved.Mod->Exports.push_back(
5119 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
5120 continue;
5121 }
5122 }
5123 UnresolvedModuleRefs.clear();
5124
5125 // FIXME: How do we load the 'use'd modules? They may not be submodules.
5126 // Might be unnecessary as use declarations are only used to build the
5127 // module itself.
5128
5129 if (ContextObj)
5131
5132 if (SemaObj)
5133 UpdateSema();
5134
5135 if (DeserializationListener)
5136 DeserializationListener->ReaderInitialized(this);
5137
5138 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
5139 if (PrimaryModule.OriginalSourceFileID.isValid()) {
5140 // If this AST file is a precompiled preamble, then set the
5141 // preamble file ID of the source manager to the file source file
5142 // from which the preamble was built.
5143 if (Type == MK_Preamble) {
5144 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
5145 } else if (Type == MK_MainFile) {
5146 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
5147 }
5148 }
5149
5150 // For any Objective-C class definitions we have already loaded, make sure
5151 // that we load any additional categories.
5152 if (ContextObj) {
5153 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
5154 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
5155 ObjCClassesLoaded[I], PreviousGeneration);
5156 }
5157 }
5158
5159 const HeaderSearchOptions &HSOpts =
5160 PP.getHeaderSearchInfo().getHeaderSearchOpts();
5162 // Now we are certain that the module and all modules it depends on are
5163 // up-to-date. For implicitly-built module files, ensure the corresponding
5164 // timestamp files are up-to-date in this build session.
5165 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
5166 ImportedModule &M = Loaded[I];
5167 if (M.Mod->Kind == MK_ImplicitModule &&
5169 getModuleManager().getModuleCache().updateModuleTimestamp(
5170 M.Mod->FileName);
5171 }
5172 }
5173
5174 return Success;
5175}
5176
5177static ASTFileSignature readASTFileSignature(StringRef PCH);
5178
5179/// Whether \p Stream doesn't start with the AST file magic number 'CPCH'.
5180static llvm::Error doesntStartWithASTFileMagic(BitstreamCursor &Stream) {
5181 // FIXME checking magic headers is done in other places such as
5182 // SerializedDiagnosticReader and GlobalModuleIndex, but error handling isn't
5183 // always done the same. Unify it all with a helper.
5184 if (!Stream.canSkipToPos(4))
5185 return llvm::createStringError(
5186 std::errc::illegal_byte_sequence,
5187 "file too small to contain precompiled file magic");
5188 for (unsigned C : {'C', 'P', 'C', 'H'})
5189 if (Expected<llvm::SimpleBitstreamCursor::word_t> Res = Stream.Read(8)) {
5190 if (Res.get() != C)
5191 return llvm::createStringError(
5192 std::errc::illegal_byte_sequence,
5193 "file doesn't start with precompiled file magic");
5194 } else
5195 return Res.takeError();
5196 return llvm::Error::success();
5197}
5198
5200 switch (Kind) {
5201 case MK_PCH:
5202 return 0; // PCH
5203 case MK_ImplicitModule:
5204 case MK_ExplicitModule:
5205 case MK_PrebuiltModule:
5206 return 1; // module
5207 case MK_MainFile:
5208 case MK_Preamble:
5209 return 2; // main source file
5210 }
5211 llvm_unreachable("unknown module kind");
5212}
5213
5216 ModuleFile *ImportedBy, SmallVectorImpl<ImportedModule> &Loaded,
5217 off_t ExpectedSize, time_t ExpectedModTime,
5218 ASTFileSignature ExpectedSignature, unsigned ClientLoadCapabilities) {
5219 auto Result = ModuleMgr.addModule(
5220 FileName, Type, ImportLoc, ImportedBy, getGeneration(), ExpectedSize,
5221 ExpectedModTime, ExpectedSignature, readASTFileSignature);
5222 ModuleFile *M = Result.getModule();
5223
5224 switch (Result.getKind()) {
5226 Diag(diag::remark_module_import)
5227 << M->ModuleName << M->FileName << (ImportedBy ? true : false)
5228 << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());
5229 return Success;
5230 }
5231
5233 // Load module file below.
5234 break;
5235
5237 // The module file was missing; if the client can handle that, return
5238 // it.
5239 if (ClientLoadCapabilities & ARR_Missing)
5240 return Missing;
5241
5242 // Otherwise, return an error.
5243 Diag(diag::err_ast_file_not_found)
5245 if (!Result.getBufferError().empty())
5246 Diag(diag::note_ast_file_buffer_failed) << Result.getBufferError();
5247 return Failure;
5248
5250 // We couldn't load the module file because it is out-of-date. If the
5251 // client can handle out-of-date, return it.
5252 if (ClientLoadCapabilities & ARR_OutOfDate)
5253 return OutOfDate;
5254
5255 // Otherwise, return an error.
5256 Diag(diag::err_ast_file_out_of_date)
5258 for (const auto &C : Result.getChanges()) {
5259 Diag(diag::note_fe_ast_file_modified)
5260 << C.Kind << (C.Old && C.New) << llvm::itostr(C.Old.value_or(0))
5261 << llvm::itostr(C.New.value_or(0));
5262 }
5263 Diag(diag::note_ast_file_input_files_validation_status)
5264 << Result.getValidationStatus();
5265 if (!Result.getSignatureError().empty())
5266 Diag(diag::note_ast_file_signature_failed) << Result.getSignatureError();
5267 return Failure;
5268
5270 llvm_unreachable("Unexpected value from adding module.");
5271 }
5272
5273 assert(M && "Missing module file");
5274
5275 bool ShouldFinalizePCM = false;
5276 llvm::scope_exit FinalizeOrDropPCM([&]() {
5277 auto &MC = getModuleManager().getModuleCache().getInMemoryModuleCache();
5278 if (ShouldFinalizePCM)
5279 MC.finalizePCM(FileName);
5280 else
5281 MC.tryToDropPCM(FileName);
5282 });
5283 ModuleFile &F = *M;
5284 BitstreamCursor &Stream = F.Stream;
5285 Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(*F.Buffer));
5286 F.SizeInBits = F.Buffer->getBufferSize() * 8;
5287
5288 // Sniff for the signature.
5289 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5290 Diag(diag::err_ast_file_invalid)
5291 << moduleKindForDiagnostic(Type) << FileName << std::move(Err);
5292 return Failure;
5293 }
5294
5295 // This is used for compatibility with older PCH formats.
5296 bool HaveReadControlBlock = false;
5297 while (true) {
5298 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5299 if (!MaybeEntry) {
5300 Error(MaybeEntry.takeError());
5301 return Failure;
5302 }
5303 llvm::BitstreamEntry Entry = MaybeEntry.get();
5304
5305 switch (Entry.Kind) {
5306 case llvm::BitstreamEntry::Error:
5307 case llvm::BitstreamEntry::Record:
5308 case llvm::BitstreamEntry::EndBlock:
5309 Error("invalid record at top-level of AST file");
5310 return Failure;
5311
5312 case llvm::BitstreamEntry::SubBlock:
5313 break;
5314 }
5315
5316 switch (Entry.ID) {
5317 case CONTROL_BLOCK_ID:
5318 HaveReadControlBlock = true;
5319 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
5320 case Success:
5321 // Check that we didn't try to load a non-module AST file as a module.
5322 //
5323 // FIXME: Should we also perform the converse check? Loading a module as
5324 // a PCH file sort of works, but it's a bit wonky.
5326 Type == MK_PrebuiltModule) &&
5327 F.ModuleName.empty()) {
5329 if (Result != OutOfDate ||
5330 (ClientLoadCapabilities & ARR_OutOfDate) == 0)
5331 Diag(diag::err_module_file_not_module) << FileName;
5332 return Result;
5333 }
5334 break;
5335
5336 case Failure: return Failure;
5337 case Missing: return Missing;
5338 case OutOfDate: return OutOfDate;
5339 case VersionMismatch: return VersionMismatch;
5341 case HadErrors: return HadErrors;
5342 }
5343 break;
5344
5345 case AST_BLOCK_ID:
5346 if (!HaveReadControlBlock) {
5347 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
5348 Diag(diag::err_ast_file_version_too_old)
5350 return VersionMismatch;
5351 }
5352
5353 // Record that we've loaded this module.
5354 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
5355 ShouldFinalizePCM = true;
5356 return Success;
5357
5358 default:
5359 if (llvm::Error Err = Stream.SkipBlock()) {
5360 Error(std::move(Err));
5361 return Failure;
5362 }
5363 break;
5364 }
5365 }
5366
5367 llvm_unreachable("unexpected break; expected return");
5368}
5369
5371ASTReader::readUnhashedControlBlock(ModuleFile &F, bool WasImportedBy,
5372 unsigned ClientLoadCapabilities) {
5373 const HeaderSearchOptions &HSOpts =
5374 PP.getHeaderSearchInfo().getHeaderSearchOpts();
5375 bool AllowCompatibleConfigurationMismatch =
5377 bool DisableValidation = shouldDisableValidationForFile(F);
5378
5379 ASTReadResult Result = readUnhashedControlBlockImpl(
5380 &F, F.Data, F.FileName, ClientLoadCapabilities,
5381 AllowCompatibleConfigurationMismatch, Listener.get(),
5382 WasImportedBy ? false : HSOpts.ModulesValidateDiagnosticOptions);
5383
5384 // If F was directly imported by another module, it's implicitly validated by
5385 // the importing module.
5386 if (DisableValidation || WasImportedBy ||
5387 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
5388 return Success;
5389
5390 if (Result == Failure) {
5391 Error("malformed block record in AST file");
5392 return Failure;
5393 }
5394
5395 if (Result == OutOfDate && F.Kind == MK_ImplicitModule) {
5396 // If this module has already been finalized in the ModuleCache, we're stuck
5397 // with it; we can only load a single version of each module.
5398 //
5399 // This can happen when a module is imported in two contexts: in one, as a
5400 // user module; in another, as a system module (due to an import from
5401 // another module marked with the [system] flag). It usually indicates a
5402 // bug in the module map: this module should also be marked with [system].
5403 //
5404 // If -Wno-system-headers (the default), and the first import is as a
5405 // system module, then validation will fail during the as-user import,
5406 // since -Werror flags won't have been validated. However, it's reasonable
5407 // to treat this consistently as a system module.
5408 //
5409 // If -Wsystem-headers, the PCM on disk was built with
5410 // -Wno-system-headers, and the first import is as a user module, then
5411 // validation will fail during the as-system import since the PCM on disk
5412 // doesn't guarantee that -Werror was respected. However, the -Werror
5413 // flags were checked during the initial as-user import.
5414 if (getModuleManager().getModuleCache().getInMemoryModuleCache().isPCMFinal(
5415 F.FileName)) {
5416 Diag(diag::warn_module_system_bit_conflict) << F.FileName;
5417 return Success;
5418 }
5419 }
5420
5421 return Result;
5422}
5423
5424ASTReader::ASTReadResult ASTReader::readUnhashedControlBlockImpl(
5425 ModuleFile *F, llvm::StringRef StreamData, StringRef Filename,
5426 unsigned ClientLoadCapabilities, bool AllowCompatibleConfigurationMismatch,
5427 ASTReaderListener *Listener, bool ValidateDiagnosticOptions) {
5428 // Initialize a stream.
5429 BitstreamCursor Stream(StreamData);
5430
5431 // Sniff for the signature.
5432 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5433 // FIXME this drops the error on the floor.
5434 consumeError(std::move(Err));
5435 return Failure;
5436 }
5437
5438 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
5440 return Failure;
5441
5442 // Read all of the records in the options block.
5443 RecordData Record;
5444 ASTReadResult Result = Success;
5445 while (true) {
5446 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5447 if (!MaybeEntry) {
5448 // FIXME this drops the error on the floor.
5449 consumeError(MaybeEntry.takeError());
5450 return Failure;
5451 }
5452 llvm::BitstreamEntry Entry = MaybeEntry.get();
5453
5454 switch (Entry.Kind) {
5455 case llvm::BitstreamEntry::Error:
5456 case llvm::BitstreamEntry::SubBlock:
5457 return Failure;
5458
5459 case llvm::BitstreamEntry::EndBlock:
5460 return Result;
5461
5462 case llvm::BitstreamEntry::Record:
5463 // The interesting case.
5464 break;
5465 }
5466
5467 // Read and process a record.
5468 Record.clear();
5469 StringRef Blob;
5470 Expected<unsigned> MaybeRecordType =
5471 Stream.readRecord(Entry.ID, Record, &Blob);
5472 if (!MaybeRecordType) {
5473 // FIXME this drops the error.
5474 return Failure;
5475 }
5476 switch ((UnhashedControlBlockRecordTypes)MaybeRecordType.get()) {
5477 case SIGNATURE:
5478 if (F) {
5479 F->Signature = ASTFileSignature::create(Blob.begin(), Blob.end());
5481 "Dummy AST file signature not backpatched in ASTWriter.");
5482 }
5483 break;
5484 case AST_BLOCK_HASH:
5485 if (F) {
5486 F->ASTBlockHash = ASTFileSignature::create(Blob.begin(), Blob.end());
5488 "Dummy AST block hash not backpatched in ASTWriter.");
5489 }
5490 break;
5491 case DIAGNOSTIC_OPTIONS: {
5492 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
5493 if (Listener && ValidateDiagnosticOptions &&
5494 !AllowCompatibleConfigurationMismatch &&
5495 ParseDiagnosticOptions(Record, Filename, Complain, *Listener))
5496 Result = OutOfDate; // Don't return early. Read the signature.
5497 break;
5498 }
5499 case HEADER_SEARCH_PATHS: {
5500 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
5501 if (Listener && !AllowCompatibleConfigurationMismatch &&
5502 ParseHeaderSearchPaths(Record, Complain, *Listener))
5503 Result = ConfigurationMismatch;
5504 break;
5505 }
5507 if (!F)
5508 break;
5509 if (F->PragmaDiagMappings.empty())
5510 F->PragmaDiagMappings.swap(Record);
5511 else
5512 F->PragmaDiagMappings.insert(F->PragmaDiagMappings.end(),
5513 Record.begin(), Record.end());
5514 break;
5516 if (F)
5517 F->SearchPathUsage = ReadBitVector(Record, Blob);
5518 break;
5519 case VFS_USAGE:
5520 if (F)
5521 F->VFSUsage = ReadBitVector(Record, Blob);
5522 break;
5523 }
5524 }
5525}
5526
5527/// Parse a record and blob containing module file extension metadata.
5530 StringRef Blob,
5531 ModuleFileExtensionMetadata &Metadata) {
5532 if (Record.size() < 4) return true;
5533
5534 Metadata.MajorVersion = Record[0];
5535 Metadata.MinorVersion = Record[1];
5536
5537 unsigned BlockNameLen = Record[2];
5538 unsigned UserInfoLen = Record[3];
5539
5540 if (BlockNameLen + UserInfoLen > Blob.size()) return true;
5541
5542 Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
5543 Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,
5544 Blob.data() + BlockNameLen + UserInfoLen);
5545 return false;
5546}
5547
5548llvm::Error ASTReader::ReadExtensionBlock(ModuleFile &F) {
5549 BitstreamCursor &Stream = F.Stream;
5550
5551 RecordData Record;
5552 while (true) {
5553 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5554 if (!MaybeEntry)
5555 return MaybeEntry.takeError();
5556 llvm::BitstreamEntry Entry = MaybeEntry.get();
5557
5558 switch (Entry.Kind) {
5559 case llvm::BitstreamEntry::SubBlock:
5560 if (llvm::Error Err = Stream.SkipBlock())
5561 return Err;
5562 continue;
5563 case llvm::BitstreamEntry::EndBlock:
5564 return llvm::Error::success();
5565 case llvm::BitstreamEntry::Error:
5566 return llvm::createStringError(std::errc::illegal_byte_sequence,
5567 "malformed block record in AST file");
5568 case llvm::BitstreamEntry::Record:
5569 break;
5570 }
5571
5572 Record.clear();
5573 StringRef Blob;
5574 Expected<unsigned> MaybeRecCode =
5575 Stream.readRecord(Entry.ID, Record, &Blob);
5576 if (!MaybeRecCode)
5577 return MaybeRecCode.takeError();
5578 switch (MaybeRecCode.get()) {
5579 case EXTENSION_METADATA: {
5580 ModuleFileExtensionMetadata Metadata;
5581 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
5582 return llvm::createStringError(
5583 std::errc::illegal_byte_sequence,
5584 "malformed EXTENSION_METADATA in AST file");
5585
5586 // Find a module file extension with this block name.
5587 auto Known = ModuleFileExtensions.find(Metadata.BlockName);
5588 if (Known == ModuleFileExtensions.end()) break;
5589
5590 // Form a reader.
5591 if (auto Reader = Known->second->createExtensionReader(Metadata, *this,
5592 F, Stream)) {
5593 F.ExtensionReaders.push_back(std::move(Reader));
5594 }
5595
5596 break;
5597 }
5598 }
5599 }
5600
5601 llvm_unreachable("ReadExtensionBlock should return from while loop");
5602}
5603
5605 assert(ContextObj && "no context to initialize");
5606 ASTContext &Context = *ContextObj;
5607
5608 // If there's a listener, notify them that we "read" the translation unit.
5609 if (DeserializationListener)
5610 DeserializationListener->DeclRead(
5612 Context.getTranslationUnitDecl());
5613
5614 // FIXME: Find a better way to deal with collisions between these
5615 // built-in types. Right now, we just ignore the problem.
5616
5617 // Load the special types.
5618 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
5619 if (TypeID String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
5620 if (!Context.CFConstantStringTypeDecl)
5621 Context.setCFConstantStringType(GetType(String));
5622 }
5623
5624 if (TypeID File = SpecialTypes[SPECIAL_TYPE_FILE]) {
5625 QualType FileType = GetType(File);
5626 if (FileType.isNull()) {
5627 Error("FILE type is NULL");
5628 return;
5629 }
5630
5631 if (!Context.FILEDecl) {
5632 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
5633 Context.setFILEDecl(Typedef->getDecl());
5634 else {
5635 const TagType *Tag = FileType->getAs<TagType>();
5636 if (!Tag) {
5637 Error("Invalid FILE type in AST file");
5638 return;
5639 }
5640 Context.setFILEDecl(Tag->getDecl());
5641 }
5642 }
5643 }
5644
5645 if (TypeID Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
5646 QualType Jmp_bufType = GetType(Jmp_buf);
5647 if (Jmp_bufType.isNull()) {
5648 Error("jmp_buf type is NULL");
5649 return;
5650 }
5651
5652 if (!Context.jmp_bufDecl) {
5653 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
5654 Context.setjmp_bufDecl(Typedef->getDecl());
5655 else {
5656 const TagType *Tag = Jmp_bufType->getAs<TagType>();
5657 if (!Tag) {
5658 Error("Invalid jmp_buf type in AST file");
5659 return;
5660 }
5661 Context.setjmp_bufDecl(Tag->getDecl());
5662 }
5663 }
5664 }
5665
5666 if (TypeID Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
5667 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
5668 if (Sigjmp_bufType.isNull()) {
5669 Error("sigjmp_buf type is NULL");
5670 return;
5671 }
5672
5673 if (!Context.sigjmp_bufDecl) {
5674 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
5675 Context.setsigjmp_bufDecl(Typedef->getDecl());
5676 else {
5677 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
5678 assert(Tag && "Invalid sigjmp_buf type in AST file");
5679 Context.setsigjmp_bufDecl(Tag->getDecl());
5680 }
5681 }
5682 }
5683
5684 if (TypeID ObjCIdRedef = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
5685 if (Context.ObjCIdRedefinitionType.isNull())
5686 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
5687 }
5688
5689 if (TypeID ObjCClassRedef =
5691 if (Context.ObjCClassRedefinitionType.isNull())
5692 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
5693 }
5694
5695 if (TypeID ObjCSelRedef =
5696 SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
5697 if (Context.ObjCSelRedefinitionType.isNull())
5698 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
5699 }
5700
5701 if (TypeID Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
5702 QualType Ucontext_tType = GetType(Ucontext_t);
5703 if (Ucontext_tType.isNull()) {
5704 Error("ucontext_t type is NULL");
5705 return;
5706 }
5707
5708 if (!Context.ucontext_tDecl) {
5709 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
5710 Context.setucontext_tDecl(Typedef->getDecl());
5711 else {
5712 const TagType *Tag = Ucontext_tType->getAs<TagType>();
5713 assert(Tag && "Invalid ucontext_t type in AST file");
5714 Context.setucontext_tDecl(Tag->getDecl());
5715 }
5716 }
5717 }
5718 }
5719
5720 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
5721
5722 // If there were any CUDA special declarations, deserialize them.
5723 if (!CUDASpecialDeclRefs.empty()) {
5724 assert(CUDASpecialDeclRefs.size() == 3 && "More decl refs than expected!");
5725 Context.setcudaConfigureCallDecl(
5726 cast_or_null<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
5727 Context.setcudaGetParameterBufferDecl(
5728 cast_or_null<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[1])));
5729 Context.setcudaLaunchDeviceDecl(
5730 cast_or_null<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[2])));
5731 }
5732
5733 // Re-export any modules that were imported by a non-module AST file.
5734 // FIXME: This does not make macro-only imports visible again.
5735 for (auto &Import : PendingImportedModules) {
5736 if (Module *Imported = getSubmodule(Import.ID)) {
5738 /*ImportLoc=*/Import.ImportLoc);
5739 if (Import.ImportLoc.isValid())
5740 PP.makeModuleVisible(Imported, Import.ImportLoc);
5741 // This updates visibility for Preprocessor only. For Sema, which can be
5742 // nullptr here, we do the same later, in UpdateSema().
5743 }
5744 }
5745
5746 // Hand off these modules to Sema.
5747 PendingImportedModulesSema.append(PendingImportedModules);
5748 PendingImportedModules.clear();
5749}
5750
5752 // Nothing to do for now.
5753}
5754
5755/// Reads and return the signature record from \p PCH's control block, or
5756/// else returns 0.
5758 BitstreamCursor Stream(PCH);
5759 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5760 // FIXME this drops the error on the floor.
5761 consumeError(std::move(Err));
5762 return ASTFileSignature();
5763 }
5764
5765 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
5767 return ASTFileSignature();
5768
5769 // Scan for SIGNATURE inside the diagnostic options block.
5771 while (true) {
5773 Stream.advanceSkippingSubblocks();
5774 if (!MaybeEntry) {
5775 // FIXME this drops the error on the floor.
5776 consumeError(MaybeEntry.takeError());
5777 return ASTFileSignature();
5778 }
5779 llvm::BitstreamEntry Entry = MaybeEntry.get();
5780
5781 if (Entry.Kind != llvm::BitstreamEntry::Record)
5782 return ASTFileSignature();
5783
5784 Record.clear();
5785 StringRef Blob;
5786 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);
5787 if (!MaybeRecord) {
5788 // FIXME this drops the error on the floor.
5789 consumeError(MaybeRecord.takeError());
5790 return ASTFileSignature();
5791 }
5792 if (SIGNATURE == MaybeRecord.get()) {
5793 auto Signature = ASTFileSignature::create(Blob.begin(), Blob.end());
5794 assert(Signature != ASTFileSignature::createDummy() &&
5795 "Dummy AST file signature not backpatched in ASTWriter.");
5796 return Signature;
5797 }
5798 }
5799}
5800
5801/// Retrieve the name of the original source file name
5802/// directly from the AST file, without actually loading the AST
5803/// file.
5805 const std::string &ASTFileName, FileManager &FileMgr,
5806 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
5807 // Open the AST file.
5808 auto Buffer = FileMgr.getBufferForFile(ASTFileName, /*IsVolatile=*/false,
5809 /*RequiresNullTerminator=*/false,
5810 /*MaybeLimit=*/std::nullopt,
5811 /*IsText=*/false);
5812 if (!Buffer) {
5813 Diags.Report(diag::err_fe_unable_to_read_pch_file)
5814 << ASTFileName << Buffer.getError().message();
5815 return std::string();
5816 }
5817
5818 // Initialize the stream
5819 BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer));
5820
5821 // Sniff for the signature.
5822 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5823 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName << std::move(Err);
5824 return std::string();
5825 }
5826
5827 // Scan for the CONTROL_BLOCK_ID block.
5828 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
5829 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
5830 return std::string();
5831 }
5832
5833 // Scan for ORIGINAL_FILE inside the control block.
5835 while (true) {
5837 Stream.advanceSkippingSubblocks();
5838 if (!MaybeEntry) {
5839 // FIXME this drops errors on the floor.
5840 consumeError(MaybeEntry.takeError());
5841 return std::string();
5842 }
5843 llvm::BitstreamEntry Entry = MaybeEntry.get();
5844
5845 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
5846 return std::string();
5847
5848 if (Entry.Kind != llvm::BitstreamEntry::Record) {
5849 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
5850 return std::string();
5851 }
5852
5853 Record.clear();
5854 StringRef Blob;
5855 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);
5856 if (!MaybeRecord) {
5857 // FIXME this drops the errors on the floor.
5858 consumeError(MaybeRecord.takeError());
5859 return std::string();
5860 }
5861 if (ORIGINAL_FILE == MaybeRecord.get())
5862 return Blob.str();
5863 }
5864}
5865
5866namespace {
5867
5868 class SimplePCHValidator : public ASTReaderListener {
5869 const LangOptions &ExistingLangOpts;
5870 const CodeGenOptions &ExistingCGOpts;
5871 const TargetOptions &ExistingTargetOpts;
5872 const PreprocessorOptions &ExistingPPOpts;
5873 const HeaderSearchOptions &ExistingHSOpts;
5874 std::string ExistingSpecificModuleCachePath;
5876 bool StrictOptionMatches;
5877
5878 public:
5879 SimplePCHValidator(const LangOptions &ExistingLangOpts,
5880 const CodeGenOptions &ExistingCGOpts,
5881 const TargetOptions &ExistingTargetOpts,
5882 const PreprocessorOptions &ExistingPPOpts,
5883 const HeaderSearchOptions &ExistingHSOpts,
5884 StringRef ExistingSpecificModuleCachePath,
5885 FileManager &FileMgr, bool StrictOptionMatches)
5886 : ExistingLangOpts(ExistingLangOpts), ExistingCGOpts(ExistingCGOpts),
5887 ExistingTargetOpts(ExistingTargetOpts),
5888 ExistingPPOpts(ExistingPPOpts), ExistingHSOpts(ExistingHSOpts),
5889 ExistingSpecificModuleCachePath(ExistingSpecificModuleCachePath),
5890 FileMgr(FileMgr), StrictOptionMatches(StrictOptionMatches) {}
5891
5892 bool ReadLanguageOptions(const LangOptions &LangOpts,
5893 StringRef ModuleFilename, bool Complain,
5894 bool AllowCompatibleDifferences) override {
5895 return checkLanguageOptions(ExistingLangOpts, LangOpts, ModuleFilename,
5896 nullptr, AllowCompatibleDifferences);
5897 }
5898
5899 bool ReadCodeGenOptions(const CodeGenOptions &CGOpts,
5900 StringRef ModuleFilename, bool Complain,
5901 bool AllowCompatibleDifferences) override {
5902 return checkCodegenOptions(ExistingCGOpts, CGOpts, ModuleFilename,
5903 nullptr, AllowCompatibleDifferences);
5904 }
5905
5906 bool ReadTargetOptions(const TargetOptions &TargetOpts,
5907 StringRef ModuleFilename, bool Complain,
5908 bool AllowCompatibleDifferences) override {
5909 return checkTargetOptions(TargetOpts, ExistingTargetOpts, ModuleFilename,
5910 nullptr, AllowCompatibleDifferences);
5911 }
5912
5913 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
5914 StringRef ASTFilename, StringRef ContextHash,
5915 bool Complain) override {
5916 return checkModuleCachePath(
5917 FileMgr, ContextHash, ExistingSpecificModuleCachePath, ASTFilename,
5918 nullptr, ExistingLangOpts, ExistingPPOpts, ExistingHSOpts, HSOpts);
5919 }
5920
5921 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
5922 StringRef ModuleFilename, bool ReadMacros,
5923 bool Complain,
5924 std::string &SuggestedPredefines) override {
5926 PPOpts, ExistingPPOpts, ModuleFilename, ReadMacros, /*Diags=*/nullptr,
5927 FileMgr, SuggestedPredefines, ExistingLangOpts,
5928 StrictOptionMatches ? OptionValidateStrictMatches
5930 }
5931 };
5932
5933} // namespace
5934
5936 StringRef Filename, FileManager &FileMgr, const ModuleCache &ModCache,
5937 const PCHContainerReader &PCHContainerRdr, bool FindModuleFileExtensions,
5938 ASTReaderListener &Listener, bool ValidateDiagnosticOptions,
5939 unsigned ClientLoadCapabilities) {
5940 // Open the AST file.
5941 off_t Size;
5942 time_t ModTime;
5943 std::unique_ptr<llvm::MemoryBuffer> OwnedBuffer;
5944 llvm::MemoryBuffer *Buffer =
5945 ModCache.getInMemoryModuleCache().lookupPCM(Filename, Size, ModTime);
5946 if (!Buffer) {
5947 // FIXME: We should add the pcm to the InMemoryModuleCache if it could be
5948 // read again later, but we do not have the context here to determine if it
5949 // is safe to change the result of InMemoryModuleCache::getPCMState().
5950
5951 // FIXME: This allows use of the VFS; we do not allow use of the
5952 // VFS when actually loading a module.
5953 auto Entry = Filename == "-" ? FileMgr.getSTDIN()
5954 : FileMgr.getFileRef(Filename,
5955 /*OpenFile=*/false,
5956 /*CacheFailure=*/true,
5957 /*IsText=*/false);
5958 if (!Entry) {
5959 llvm::consumeError(Entry.takeError());
5960 return true;
5961 }
5962 auto BufferOrErr =
5963 FileMgr.getBufferForFile(*Entry,
5964 /*IsVolatile=*/false,
5965 /*RequiresNullTerminator=*/false,
5966 /*MaybeLimit=*/std::nullopt,
5967 /*IsText=*/false);
5968 if (!BufferOrErr)
5969 return true;
5970 OwnedBuffer = std::move(*BufferOrErr);
5971 Buffer = OwnedBuffer.get();
5972 }
5973
5974 // Initialize the stream
5975 StringRef Bytes = PCHContainerRdr.ExtractPCH(*Buffer);
5976 BitstreamCursor Stream(Bytes);
5977
5978 // Sniff for the signature.
5979 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5980 consumeError(std::move(Err)); // FIXME this drops errors on the floor.
5981 return true;
5982 }
5983
5984 // Scan for the CONTROL_BLOCK_ID block.
5986 return true;
5987
5988 bool NeedsInputFiles = Listener.needsInputFileVisitation();
5989 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
5990 bool NeedsImports = Listener.needsImportVisitation();
5991 BitstreamCursor InputFilesCursor;
5992 uint64_t InputFilesOffsetBase = 0;
5993
5995 std::string ModuleDir;
5996 bool DoneWithControlBlock = false;
5997 SmallString<0> PathBuf;
5998 PathBuf.reserve(256);
5999 // Additional path buffer to use when multiple paths need to be resolved.
6000 // For example, when deserializing input files that contains a path that was
6001 // resolved from a vfs overlay and an external location.
6002 SmallString<0> AdditionalPathBuf;
6003 AdditionalPathBuf.reserve(256);
6004 while (!DoneWithControlBlock) {
6005 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
6006 if (!MaybeEntry) {
6007 // FIXME this drops the error on the floor.
6008 consumeError(MaybeEntry.takeError());
6009 return true;
6010 }
6011 llvm::BitstreamEntry Entry = MaybeEntry.get();
6012
6013 switch (Entry.Kind) {
6014 case llvm::BitstreamEntry::SubBlock: {
6015 switch (Entry.ID) {
6016 case OPTIONS_BLOCK_ID: {
6017 std::string IgnoredSuggestedPredefines;
6018 if (ReadOptionsBlock(Stream, Filename, ClientLoadCapabilities,
6019 /*AllowCompatibleConfigurationMismatch*/ false,
6020 Listener, IgnoredSuggestedPredefines) != Success)
6021 return true;
6022 break;
6023 }
6024
6026 InputFilesCursor = Stream;
6027 if (llvm::Error Err = Stream.SkipBlock()) {
6028 // FIXME this drops the error on the floor.
6029 consumeError(std::move(Err));
6030 return true;
6031 }
6032 if (NeedsInputFiles &&
6033 ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID))
6034 return true;
6035 InputFilesOffsetBase = InputFilesCursor.GetCurrentBitNo();
6036 break;
6037
6038 default:
6039 if (llvm::Error Err = Stream.SkipBlock()) {
6040 // FIXME this drops the error on the floor.
6041 consumeError(std::move(Err));
6042 return true;
6043 }
6044 break;
6045 }
6046
6047 continue;
6048 }
6049
6050 case llvm::BitstreamEntry::EndBlock:
6051 DoneWithControlBlock = true;
6052 break;
6053
6054 case llvm::BitstreamEntry::Error:
6055 return true;
6056
6057 case llvm::BitstreamEntry::Record:
6058 break;
6059 }
6060
6061 if (DoneWithControlBlock) break;
6062
6063 Record.clear();
6064 StringRef Blob;
6065 Expected<unsigned> MaybeRecCode =
6066 Stream.readRecord(Entry.ID, Record, &Blob);
6067 if (!MaybeRecCode) {
6068 // FIXME this drops the error.
6069 return Failure;
6070 }
6071 switch ((ControlRecordTypes)MaybeRecCode.get()) {
6072 case METADATA:
6073 if (Record[0] != VERSION_MAJOR)
6074 return true;
6075 if (Listener.ReadFullVersionInformation(Blob))
6076 return true;
6077 break;
6078 case MODULE_NAME:
6079 Listener.ReadModuleName(Blob);
6080 break;
6081 case MODULE_DIRECTORY:
6082 ModuleDir = std::string(Blob);
6083 break;
6084 case MODULE_MAP_FILE: {
6085 unsigned Idx = 0;
6086 std::string PathStr = ReadString(Record, Idx);
6087 auto Path = ResolveImportedPath(PathBuf, PathStr, ModuleDir);
6088 Listener.ReadModuleMapFile(*Path);
6089 break;
6090 }
6091 case INPUT_FILE_OFFSETS: {
6092 if (!NeedsInputFiles)
6093 break;
6094
6095 unsigned NumInputFiles = Record[0];
6096 unsigned NumUserFiles = Record[1];
6097 const llvm::support::unaligned_uint64_t *InputFileOffs =
6098 (const llvm::support::unaligned_uint64_t *)Blob.data();
6099 for (unsigned I = 0; I != NumInputFiles; ++I) {
6100 // Go find this input file.
6101 bool isSystemFile = I >= NumUserFiles;
6102
6103 if (isSystemFile && !NeedsSystemInputFiles)
6104 break; // the rest are system input files
6105
6106 BitstreamCursor &Cursor = InputFilesCursor;
6107 SavedStreamPosition SavedPosition(Cursor);
6108 if (llvm::Error Err =
6109 Cursor.JumpToBit(InputFilesOffsetBase + InputFileOffs[I])) {
6110 // FIXME this drops errors on the floor.
6111 consumeError(std::move(Err));
6112 }
6113
6114 Expected<unsigned> MaybeCode = Cursor.ReadCode();
6115 if (!MaybeCode) {
6116 // FIXME this drops errors on the floor.
6117 consumeError(MaybeCode.takeError());
6118 }
6119 unsigned Code = MaybeCode.get();
6120
6122 StringRef Blob;
6123 bool shouldContinue = false;
6124 Expected<unsigned> MaybeRecordType =
6125 Cursor.readRecord(Code, Record, &Blob);
6126 if (!MaybeRecordType) {
6127 // FIXME this drops errors on the floor.
6128 consumeError(MaybeRecordType.takeError());
6129 }
6130 switch ((InputFileRecordTypes)MaybeRecordType.get()) {
6131 case INPUT_FILE_HASH:
6132 break;
6133 case INPUT_FILE:
6134 time_t StoredTime = static_cast<time_t>(Record[2]);
6135 bool Overridden = static_cast<bool>(Record[3]);
6136 auto [UnresolvedFilenameAsRequested, UnresolvedFilename] =
6138 auto FilenameAsRequestedBuf = ResolveImportedPath(
6139 PathBuf, UnresolvedFilenameAsRequested, ModuleDir);
6140 StringRef Filename;
6141 if (UnresolvedFilename.empty())
6142 Filename = *FilenameAsRequestedBuf;
6143 else {
6144 auto FilenameBuf = ResolveImportedPath(
6145 AdditionalPathBuf, UnresolvedFilename, ModuleDir);
6146 Filename = *FilenameBuf;
6147 }
6148 shouldContinue = Listener.visitInputFileAsRequested(
6149 *FilenameAsRequestedBuf, Filename, isSystemFile, Overridden,
6150 StoredTime, /*IsExplicitModule=*/false);
6151 break;
6152 }
6153 if (!shouldContinue)
6154 break;
6155 }
6156 break;
6157 }
6158
6159 case IMPORT: {
6160 if (!NeedsImports)
6161 break;
6162
6163 unsigned Idx = 0;
6164 // Read information about the AST file.
6165
6166 // Skip Kind
6167 Idx++;
6168
6169 // Skip ImportLoc
6170 Idx++;
6171
6172 StringRef ModuleName = ReadStringBlob(Record, Idx, Blob);
6173
6174 bool IsStandardCXXModule = Record[Idx++];
6175
6176 // In C++20 Modules, we don't record the path to imported
6177 // modules in the BMI files.
6178 if (IsStandardCXXModule) {
6179 Listener.visitImport(ModuleName, /*Filename=*/"");
6180 continue;
6181 }
6182
6183 // Skip Size, ModTime and ImplicitModuleSuffix.
6184 Idx += 1 + 1 + 1;
6185 // Skip signature.
6186 Blob = Blob.substr(ASTFileSignature::size);
6187
6188 StringRef FilenameStr = ReadStringBlob(Record, Idx, Blob);
6189 auto Filename = ResolveImportedPath(PathBuf, FilenameStr, ModuleDir);
6190 Listener.visitImport(ModuleName, *Filename);
6191 break;
6192 }
6193
6194 default:
6195 // No other validation to perform.
6196 break;
6197 }
6198 }
6199
6200 // Look for module file extension blocks, if requested.
6201 if (FindModuleFileExtensions) {
6202 BitstreamCursor SavedStream = Stream;
6203 while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {
6204 bool DoneWithExtensionBlock = false;
6205 while (!DoneWithExtensionBlock) {
6206 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
6207 if (!MaybeEntry) {
6208 // FIXME this drops the error.
6209 return true;
6210 }
6211 llvm::BitstreamEntry Entry = MaybeEntry.get();
6212
6213 switch (Entry.Kind) {
6214 case llvm::BitstreamEntry::SubBlock:
6215 if (llvm::Error Err = Stream.SkipBlock()) {
6216 // FIXME this drops the error on the floor.
6217 consumeError(std::move(Err));
6218 return true;
6219 }
6220 continue;
6221
6222 case llvm::BitstreamEntry::EndBlock:
6223 DoneWithExtensionBlock = true;
6224 continue;
6225
6226 case llvm::BitstreamEntry::Error:
6227 return true;
6228
6229 case llvm::BitstreamEntry::Record:
6230 break;
6231 }
6232
6233 Record.clear();
6234 StringRef Blob;
6235 Expected<unsigned> MaybeRecCode =
6236 Stream.readRecord(Entry.ID, Record, &Blob);
6237 if (!MaybeRecCode) {
6238 // FIXME this drops the error.
6239 return true;
6240 }
6241 switch (MaybeRecCode.get()) {
6242 case EXTENSION_METADATA: {
6244 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
6245 return true;
6246
6247 Listener.readModuleFileExtension(Metadata);
6248 break;
6249 }
6250 }
6251 }
6252 }
6253 Stream = std::move(SavedStream);
6254 }
6255
6256 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
6257 if (readUnhashedControlBlockImpl(
6258 nullptr, Bytes, Filename, ClientLoadCapabilities,
6259 /*AllowCompatibleConfigurationMismatch*/ false, &Listener,
6260 ValidateDiagnosticOptions) != Success)
6261 return true;
6262
6263 return false;
6264}
6265
6267 StringRef Filename, FileManager &FileMgr, const ModuleCache &ModCache,
6268 const PCHContainerReader &PCHContainerRdr, const LangOptions &LangOpts,
6269 const CodeGenOptions &CGOpts, const TargetOptions &TargetOpts,
6270 const PreprocessorOptions &PPOpts, const HeaderSearchOptions &HSOpts,
6271 StringRef SpecificModuleCachePath, bool RequireStrictOptionMatches) {
6272 SimplePCHValidator validator(LangOpts, CGOpts, TargetOpts, PPOpts, HSOpts,
6273 SpecificModuleCachePath, FileMgr,
6274 RequireStrictOptionMatches);
6275 return !readASTFileControlBlock(Filename, FileMgr, ModCache, PCHContainerRdr,
6276 /*FindModuleFileExtensions=*/false, validator,
6277 /*ValidateDiagnosticOptions=*/true);
6278}
6279
6280llvm::Error ASTReader::ReadSubmoduleBlock(ModuleFile &F,
6281 unsigned ClientLoadCapabilities) {
6282 // Enter the submodule block.
6283 if (llvm::Error Err = F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID))
6284 return Err;
6285
6286 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
6287 bool KnowsTopLevelModule = ModMap.findModule(F.ModuleName) != nullptr;
6288 // If we don't know the top-level module, there's no point in doing qualified
6289 // lookup of its submodules; it won't find anything anywhere within this tree.
6290 // Let's skip that and avoid some string lookups.
6291 auto CreateModule = !KnowsTopLevelModule
6294
6295 bool First = true;
6296 Module *CurrentModule = nullptr;
6297 RecordData Record;
6298 while (true) {
6300 F.Stream.advanceSkippingSubblocks();
6301 if (!MaybeEntry)
6302 return MaybeEntry.takeError();
6303 llvm::BitstreamEntry Entry = MaybeEntry.get();
6304
6305 switch (Entry.Kind) {
6306 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
6307 case llvm::BitstreamEntry::Error:
6308 return llvm::createStringError(std::errc::illegal_byte_sequence,
6309 "malformed block record in AST file");
6310 case llvm::BitstreamEntry::EndBlock:
6311 return llvm::Error::success();
6312 case llvm::BitstreamEntry::Record:
6313 // The interesting case.
6314 break;
6315 }
6316
6317 // Read a record.
6318 StringRef Blob;
6319 Record.clear();
6320 Expected<unsigned> MaybeKind = F.Stream.readRecord(Entry.ID, Record, &Blob);
6321 if (!MaybeKind)
6322 return MaybeKind.takeError();
6323 unsigned Kind = MaybeKind.get();
6324
6325 if ((Kind == SUBMODULE_METADATA) != First)
6326 return llvm::createStringError(
6327 std::errc::illegal_byte_sequence,
6328 "submodule metadata record should be at beginning of block");
6329 First = false;
6330
6331 // Submodule information is only valid if we have a current module.
6332 // FIXME: Should we error on these cases?
6333 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
6334 Kind != SUBMODULE_DEFINITION)
6335 continue;
6336
6337 switch (Kind) {
6338 default: // Default behavior: ignore.
6339 break;
6340
6341 case SUBMODULE_DEFINITION: {
6342 if (Record.size() < 13)
6343 return llvm::createStringError(std::errc::illegal_byte_sequence,
6344 "malformed module definition");
6345
6346 StringRef Name = Blob;
6347 unsigned Idx = 0;
6348 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
6349 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
6351 SourceLocation DefinitionLoc = ReadSourceLocation(F, Record[Idx++]);
6352 FileID InferredAllowedBy = ReadFileID(F, Record, Idx);
6353 bool IsFramework = Record[Idx++];
6354 bool IsExplicit = Record[Idx++];
6355 bool IsSystem = Record[Idx++];
6356 bool IsExternC = Record[Idx++];
6357 bool InferSubmodules = Record[Idx++];
6358 bool InferExplicitSubmodules = Record[Idx++];
6359 bool InferExportWildcard = Record[Idx++];
6360 bool ConfigMacrosExhaustive = Record[Idx++];
6361 bool ModuleMapIsPrivate = Record[Idx++];
6362 bool NamedModuleHasInit = Record[Idx++];
6363
6364 Module *ParentModule = nullptr;
6365 if (Parent)
6366 ParentModule = getSubmodule(Parent);
6367
6368 CurrentModule = std::invoke(CreateModule, &ModMap, Name, ParentModule,
6369 IsFramework, IsExplicit);
6370
6371 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
6372 if (GlobalIndex >= SubmodulesLoaded.size() ||
6373 SubmodulesLoaded[GlobalIndex])
6374 return llvm::createStringError(std::errc::invalid_argument,
6375 "too many submodules");
6376
6377 if (!ParentModule) {
6378 if ([[maybe_unused]] const ModuleFileKey *CurFileKey =
6379 CurrentModule->getASTFileKey()) {
6380 // Don't emit module relocation error if we have -fno-validate-pch
6381 if (!bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation &
6383 assert(*CurFileKey != F.FileKey &&
6384 "ModuleManager did not de-duplicate");
6385
6386 Diag(diag::err_module_file_conflict)
6387 << CurrentModule->getTopLevelModuleName()
6388 << *CurrentModule->getASTFileName() << F.FileName;
6389
6390 auto CurModMapFile =
6391 ModMap.getContainingModuleMapFile(CurrentModule);
6392 auto ModMapFile = FileMgr.getOptionalFileRef(F.ModuleMapPath);
6393 if (CurModMapFile && ModMapFile && CurModMapFile != ModMapFile)
6394 Diag(diag::note_module_file_conflict)
6395 << CurModMapFile->getName() << ModMapFile->getName();
6396
6397 return llvm::make_error<AlreadyReportedDiagnosticError>();
6398 }
6399 }
6400
6401 F.DidReadTopLevelSubmodule = true;
6402 CurrentModule->setASTFileNameAndKey(F.FileName, F.FileKey);
6403 CurrentModule->PresumedModuleMapFile = F.ModuleMapPath;
6404 }
6405
6406 CurrentModule->Kind = Kind;
6407 // Note that we may be rewriting an existing location and it is important
6408 // to keep doing that. In particular, we would like to prefer a
6409 // `DefinitionLoc` loaded from the module file instead of the location
6410 // created in the current source manager, because it allows the new
6411 // location to be marked as "unaffecting" when writing and avoid creating
6412 // duplicate locations for the same module map file.
6413 CurrentModule->DefinitionLoc = DefinitionLoc;
6414 CurrentModule->Signature = F.Signature;
6415 CurrentModule->IsFromModuleFile = true;
6416 if (InferredAllowedBy.isValid())
6417 ModMap.setInferredModuleAllowedBy(CurrentModule, InferredAllowedBy);
6418 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
6419 CurrentModule->IsExternC = IsExternC;
6420 CurrentModule->InferSubmodules = InferSubmodules;
6421 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
6422 CurrentModule->InferExportWildcard = InferExportWildcard;
6423 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
6424 CurrentModule->ModuleMapIsPrivate = ModuleMapIsPrivate;
6425 CurrentModule->NamedModuleHasInit = NamedModuleHasInit;
6426
6427 if (!ParentModule && !F.BaseDirectory.empty()) {
6428 if (auto Dir = FileMgr.getOptionalDirectoryRef(F.BaseDirectory))
6429 CurrentModule->Directory = *Dir;
6430 } else if (ParentModule && ParentModule->Directory) {
6431 // Submodules inherit the directory from their parent.
6432 CurrentModule->Directory = ParentModule->Directory;
6433 }
6434
6435 if (DeserializationListener)
6436 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
6437
6438 SubmodulesLoaded[GlobalIndex] = CurrentModule;
6439
6440 // Clear out data that will be replaced by what is in the module file.
6441 CurrentModule->LinkLibraries.clear();
6442 CurrentModule->ConfigMacros.clear();
6443 CurrentModule->UnresolvedConflicts.clear();
6444 CurrentModule->Conflicts.clear();
6445
6446 // The module is available unless it's missing a requirement; relevant
6447 // requirements will be (re-)added by SUBMODULE_REQUIRES records.
6448 // Missing headers that were present when the module was built do not
6449 // make it unavailable -- if we got this far, this must be an explicitly
6450 // imported module file.
6451 CurrentModule->Requirements.clear();
6452 CurrentModule->MissingHeaders.clear();
6453 CurrentModule->IsUnimportable =
6454 ParentModule && ParentModule->IsUnimportable;
6455 CurrentModule->IsAvailable = !CurrentModule->IsUnimportable;
6456 break;
6457 }
6458
6460 SmallString<128> RelativePathName;
6461 if (auto Umbrella = ModMap.findUmbrellaHeaderForModule(
6462 CurrentModule, Blob.str(), RelativePathName)) {
6463 if (!CurrentModule->getUmbrellaHeaderAsWritten()) {
6464 ModMap.setUmbrellaHeaderAsWritten(CurrentModule, *Umbrella, Blob,
6465 RelativePathName);
6466 }
6467 // Note that it's too late at this point to return out of date if the
6468 // name from the PCM doesn't match up with the one in the module map,
6469 // but also quite unlikely since we will have already checked the
6470 // modification time and size of the module map file itself.
6471 }
6472 break;
6473 }
6474
6475 case SUBMODULE_HEADER:
6478 // We lazily associate headers with their modules via the HeaderInfo table.
6479 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
6480 // of complete filenames or remove it entirely.
6481 break;
6482
6485 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
6486 // them here.
6487 break;
6488
6489 case SUBMODULE_TOPHEADER: {
6490 auto HeaderName = ResolveImportedPath(PathBuf, Blob, F);
6491 CurrentModule->addTopHeaderFilename(*HeaderName);
6492 break;
6493 }
6494
6496 auto Dirname = ResolveImportedPath(PathBuf, Blob, F);
6497 if (auto Umbrella =
6498 PP.getFileManager().getOptionalDirectoryRef(*Dirname)) {
6499 if (!CurrentModule->getUmbrellaDirAsWritten()) {
6500 // FIXME: NameAsWritten
6501 ModMap.setUmbrellaDirAsWritten(CurrentModule, *Umbrella, Blob, "");
6502 }
6503 }
6504 break;
6505 }
6506
6507 case SUBMODULE_METADATA: {
6508 F.BaseSubmoduleID = getTotalNumSubmodules();
6510 unsigned LocalBaseSubmoduleID = Record[1];
6511 if (F.LocalNumSubmodules > 0) {
6512 // Introduce the global -> local mapping for submodules within this
6513 // module.
6514 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
6515
6516 // Introduce the local -> global mapping for submodules within this
6517 // module.
6519 std::make_pair(LocalBaseSubmoduleID,
6520 F.BaseSubmoduleID - LocalBaseSubmoduleID));
6521
6522 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
6523 }
6524 break;
6525 }
6526
6527 case SUBMODULE_IMPORTS:
6528 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
6529 UnresolvedModuleRef Unresolved;
6530 Unresolved.File = &F;
6531 Unresolved.Mod = CurrentModule;
6532 Unresolved.ID = Record[Idx];
6533 Unresolved.Kind = UnresolvedModuleRef::Import;
6534 Unresolved.IsWildcard = false;
6535 UnresolvedModuleRefs.push_back(Unresolved);
6536 }
6537 break;
6538
6540 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
6541 UnresolvedModuleRef Unresolved;
6542 Unresolved.File = &F;
6543 Unresolved.Mod = CurrentModule;
6544 Unresolved.ID = Record[Idx];
6545 Unresolved.Kind = UnresolvedModuleRef::Affecting;
6546 Unresolved.IsWildcard = false;
6547 UnresolvedModuleRefs.push_back(Unresolved);
6548 }
6549 break;
6550
6551 case SUBMODULE_EXPORTS:
6552 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
6553 UnresolvedModuleRef Unresolved;
6554 Unresolved.File = &F;
6555 Unresolved.Mod = CurrentModule;
6556 Unresolved.ID = Record[Idx];
6557 Unresolved.Kind = UnresolvedModuleRef::Export;
6558 Unresolved.IsWildcard = Record[Idx + 1];
6559 UnresolvedModuleRefs.push_back(Unresolved);
6560 }
6561
6562 // Once we've loaded the set of exports, there's no reason to keep
6563 // the parsed, unresolved exports around.
6564 CurrentModule->UnresolvedExports.clear();
6565 break;
6566
6567 case SUBMODULE_REQUIRES:
6568 CurrentModule->addRequirement(Blob, Record[0], PP.getLangOpts(),
6569 PP.getTargetInfo());
6570 break;
6571
6573 ModMap.resolveLinkAsDependencies(CurrentModule);
6574 CurrentModule->LinkLibraries.push_back(
6575 Module::LinkLibrary(std::string(Blob), Record[0]));
6576 break;
6577
6579 CurrentModule->ConfigMacros.push_back(Blob.str());
6580 break;
6581
6582 case SUBMODULE_CONFLICT: {
6583 UnresolvedModuleRef Unresolved;
6584 Unresolved.File = &F;
6585 Unresolved.Mod = CurrentModule;
6586 Unresolved.ID = Record[0];
6587 Unresolved.Kind = UnresolvedModuleRef::Conflict;
6588 Unresolved.IsWildcard = false;
6589 Unresolved.String = Blob;
6590 UnresolvedModuleRefs.push_back(Unresolved);
6591 break;
6592 }
6593
6595 if (!ContextObj)
6596 break;
6597 // Standard C++ module has its own way to initialize variables.
6598 if (!F.StandardCXXModule || F.Kind == MK_MainFile) {
6599 SmallVector<GlobalDeclID, 16> Inits;
6600 for (unsigned I = 0; I < Record.size(); /*in loop*/)
6601 Inits.push_back(ReadDeclID(F, Record, I));
6602 ContextObj->addLazyModuleInitializers(CurrentModule, Inits);
6603 }
6604 break;
6605 }
6606
6608 CurrentModule->ExportAsModule = Blob.str();
6609 ModMap.addLinkAsDependency(CurrentModule);
6610 break;
6611 }
6612 }
6613}
6614
6615/// Parse the record that corresponds to a LangOptions data
6616/// structure.
6617///
6618/// This routine parses the language options from the AST file and then gives
6619/// them to the AST listener if one is set.
6620///
6621/// \returns true if the listener deems the file unacceptable, false otherwise.
6622bool ASTReader::ParseLanguageOptions(const RecordData &Record,
6623 StringRef ModuleFilename, bool Complain,
6624 ASTReaderListener &Listener,
6625 bool AllowCompatibleDifferences) {
6626 LangOptions LangOpts;
6627 unsigned Idx = 0;
6628#define LANGOPT(Name, Bits, Default, Compatibility, Description) \
6629 LangOpts.Name = Record[Idx++];
6630#define ENUM_LANGOPT(Name, Type, Bits, Default, Compatibility, Description) \
6631 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
6632#include "clang/Basic/LangOptions.def"
6633#define SANITIZER(NAME, ID) \
6634 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
6635#include "clang/Basic/Sanitizers.def"
6636
6637 for (unsigned N = Record[Idx++]; N; --N)
6638 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
6639
6640 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
6641 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
6642 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
6643
6644 LangOpts.CurrentModule = ReadString(Record, Idx);
6645
6646 // Comment options.
6647 for (unsigned N = Record[Idx++]; N; --N) {
6648 LangOpts.CommentOpts.BlockCommandNames.push_back(
6649 ReadString(Record, Idx));
6650 }
6651 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
6652
6653 // OpenMP offloading options.
6654 for (unsigned N = Record[Idx++]; N; --N) {
6655 LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx)));
6656 }
6657
6658 LangOpts.OMPHostIRFile = ReadString(Record, Idx);
6659
6660 return Listener.ReadLanguageOptions(LangOpts, ModuleFilename, Complain,
6661 AllowCompatibleDifferences);
6662}
6663
6664bool ASTReader::ParseCodeGenOptions(const RecordData &Record,
6665 StringRef ModuleFilename, bool Complain,
6666 ASTReaderListener &Listener,
6667 bool AllowCompatibleDifferences) {
6668 unsigned Idx = 0;
6669 CodeGenOptions CGOpts;
6671#define CODEGENOPT(Name, Bits, Default, Compatibility) \
6672 if constexpr (CK::Compatibility != CK::Benign) \
6673 CGOpts.Name = static_cast<unsigned>(Record[Idx++]);
6674#define ENUM_CODEGENOPT(Name, Type, Bits, Default, Compatibility) \
6675 if constexpr (CK::Compatibility != CK::Benign) \
6676 CGOpts.set##Name(static_cast<clang::CodeGenOptions::Type>(Record[Idx++]));
6677#define DEBUGOPT(Name, Bits, Default, Compatibility)
6678#define VALUE_DEBUGOPT(Name, Bits, Default, Compatibility)
6679#define ENUM_DEBUGOPT(Name, Type, Bits, Default, Compatibility)
6680#include "clang/Basic/CodeGenOptions.def"
6681
6682 return Listener.ReadCodeGenOptions(CGOpts, ModuleFilename, Complain,
6683 AllowCompatibleDifferences);
6684}
6685
6686bool ASTReader::ParseTargetOptions(const RecordData &Record,
6687 StringRef ModuleFilename, bool Complain,
6688 ASTReaderListener &Listener,
6689 bool AllowCompatibleDifferences) {
6690 unsigned Idx = 0;
6691 TargetOptions TargetOpts;
6692 TargetOpts.Triple = ReadString(Record, Idx);
6693 TargetOpts.CPU = ReadString(Record, Idx);
6694 TargetOpts.TuneCPU = ReadString(Record, Idx);
6695 TargetOpts.ABI = ReadString(Record, Idx);
6696 for (unsigned N = Record[Idx++]; N; --N) {
6697 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
6698 }
6699 for (unsigned N = Record[Idx++]; N; --N) {
6700 TargetOpts.Features.push_back(ReadString(Record, Idx));
6701 }
6702
6703 return Listener.ReadTargetOptions(TargetOpts, ModuleFilename, Complain,
6704 AllowCompatibleDifferences);
6705}
6706
6707bool ASTReader::ParseDiagnosticOptions(const RecordData &Record,
6708 StringRef ModuleFilename, bool Complain,
6709 ASTReaderListener &Listener) {
6710 DiagnosticOptions DiagOpts;
6711 unsigned Idx = 0;
6712#define DIAGOPT(Name, Bits, Default) DiagOpts.Name = Record[Idx++];
6713#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
6714 DiagOpts.set##Name(static_cast<Type>(Record[Idx++]));
6715#include "clang/Basic/DiagnosticOptions.def"
6716
6717 for (unsigned N = Record[Idx++]; N; --N)
6718 DiagOpts.Warnings.push_back(ReadString(Record, Idx));
6719 for (unsigned N = Record[Idx++]; N; --N)
6720 DiagOpts.Remarks.push_back(ReadString(Record, Idx));
6721
6722 return Listener.ReadDiagnosticOptions(DiagOpts, ModuleFilename, Complain);
6723}
6724
6725bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
6726 ASTReaderListener &Listener) {
6727 FileSystemOptions FSOpts;
6728 unsigned Idx = 0;
6729 FSOpts.WorkingDir = ReadString(Record, Idx);
6730 return Listener.ReadFileSystemOptions(FSOpts, Complain);
6731}
6732
6733bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
6734 StringRef ModuleFilename,
6735 bool Complain,
6736 ASTReaderListener &Listener) {
6737 HeaderSearchOptions HSOpts;
6738 unsigned Idx = 0;
6739 HSOpts.Sysroot = ReadString(Record, Idx);
6740
6741 HSOpts.ResourceDir = ReadString(Record, Idx);
6742 HSOpts.ModuleCachePath = ReadString(Record, Idx);
6743 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
6744 HSOpts.DisableModuleHash = Record[Idx++];
6745 HSOpts.ImplicitModuleMaps = Record[Idx++];
6746 HSOpts.ModuleMapFileHomeIsCwd = Record[Idx++];
6747 HSOpts.EnablePrebuiltImplicitModules = Record[Idx++];
6748 HSOpts.UseBuiltinIncludes = Record[Idx++];
6749 HSOpts.UseStandardSystemIncludes = Record[Idx++];
6750 HSOpts.UseStandardCXXIncludes = Record[Idx++];
6751 HSOpts.UseLibcxx = Record[Idx++];
6752 std::string ContextHash = ReadString(Record, Idx);
6753
6754 return Listener.ReadHeaderSearchOptions(HSOpts, ModuleFilename, ContextHash,
6755 Complain);
6756}
6757
6758bool ASTReader::ParseHeaderSearchPaths(const RecordData &Record, bool Complain,
6759 ASTReaderListener &Listener) {
6760 HeaderSearchOptions HSOpts;
6761 unsigned Idx = 0;
6762
6763 // Include entries.
6764 for (unsigned N = Record[Idx++]; N; --N) {
6765 std::string Path = ReadString(Record, Idx);
6767 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
6768 bool IsFramework = Record[Idx++];
6769 bool IgnoreSysRoot = Record[Idx++];
6770 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
6771 IgnoreSysRoot);
6772 }
6773
6774 // System header prefixes.
6775 for (unsigned N = Record[Idx++]; N; --N) {
6776 std::string Prefix = ReadString(Record, Idx);
6777 bool IsSystemHeader = Record[Idx++];
6778 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
6779 }
6780
6781 // VFS overlay files.
6782 for (unsigned N = Record[Idx++]; N; --N) {
6783 std::string VFSOverlayFile = ReadString(Record, Idx);
6784 HSOpts.VFSOverlayFiles.emplace_back(std::move(VFSOverlayFile));
6785 }
6786
6787 return Listener.ReadHeaderSearchPaths(HSOpts, Complain);
6788}
6789
6790bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
6791 StringRef ModuleFilename,
6792 bool Complain,
6793 ASTReaderListener &Listener,
6794 std::string &SuggestedPredefines) {
6795 PreprocessorOptions PPOpts;
6796 unsigned Idx = 0;
6797
6798 // Macro definitions/undefs
6799 bool ReadMacros = Record[Idx++];
6800 if (ReadMacros) {
6801 for (unsigned N = Record[Idx++]; N; --N) {
6802 std::string Macro = ReadString(Record, Idx);
6803 bool IsUndef = Record[Idx++];
6804 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
6805 }
6806 }
6807
6808 // Includes
6809 for (unsigned N = Record[Idx++]; N; --N) {
6810 PPOpts.Includes.push_back(ReadString(Record, Idx));
6811 }
6812
6813 // Macro Includes
6814 for (unsigned N = Record[Idx++]; N; --N) {
6815 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
6816 }
6817
6818 PPOpts.UsePredefines = Record[Idx++];
6819 PPOpts.DetailedRecord = Record[Idx++];
6820 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
6822 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
6823 SuggestedPredefines.clear();
6824 return Listener.ReadPreprocessorOptions(PPOpts, ModuleFilename, ReadMacros,
6825 Complain, SuggestedPredefines);
6826}
6827
6828std::pair<ModuleFile *, unsigned>
6829ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
6830 GlobalPreprocessedEntityMapType::iterator
6831 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
6832 assert(I != GlobalPreprocessedEntityMap.end() &&
6833 "Corrupted global preprocessed entity map");
6834 ModuleFile *M = I->second;
6835 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
6836 return std::make_pair(M, LocalIndex);
6837}
6838
6839llvm::iterator_range<PreprocessingRecord::iterator>
6840ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
6841 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
6842 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
6844
6845 return llvm::make_range(PreprocessingRecord::iterator(),
6846 PreprocessingRecord::iterator());
6847}
6848
6849bool ASTReader::canRecoverFromOutOfDate(StringRef ModuleFileName,
6850 unsigned int ClientLoadCapabilities) {
6851 return ClientLoadCapabilities & ARR_OutOfDate &&
6852 !getModuleManager()
6853 .getModuleCache()
6854 .getInMemoryModuleCache()
6855 .isPCMFinal(ModuleFileName);
6856}
6857
6858llvm::iterator_range<ASTReader::ModuleDeclIterator>
6860 return llvm::make_range(
6861 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
6862 ModuleDeclIterator(this, &Mod,
6864}
6865
6867 auto I = GlobalSkippedRangeMap.find(GlobalIndex);
6868 assert(I != GlobalSkippedRangeMap.end() &&
6869 "Corrupted global skipped range map");
6870 ModuleFile *M = I->second;
6871 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedSkippedRangeID;
6872 assert(LocalIndex < M->NumPreprocessedSkippedRanges);
6873 PPSkippedRange RawRange = M->PreprocessedSkippedRangeOffsets[LocalIndex];
6874 SourceRange Range(ReadSourceLocation(*M, RawRange.getBegin()),
6875 ReadSourceLocation(*M, RawRange.getEnd()));
6876 assert(Range.isValid());
6877 return Range;
6878}
6879
6880unsigned
6881ASTReader::translatePreprocessedEntityIDToIndex(PreprocessedEntityID ID) const {
6882 unsigned ModuleFileIndex = ID >> 32;
6883 assert(ModuleFileIndex && "not translating loaded MacroID?");
6884 assert(getModuleManager().size() > ModuleFileIndex - 1);
6885 ModuleFile &MF = getModuleManager()[ModuleFileIndex - 1];
6886
6887 ID &= llvm::maskTrailingOnes<PreprocessedEntityID>(32);
6888 return MF.BasePreprocessedEntityID + ID;
6889}
6890
6892 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
6893 ModuleFile &M = *PPInfo.first;
6894 unsigned LocalIndex = PPInfo.second;
6896 (static_cast<PreprocessedEntityID>(M.Index + 1) << 32) | LocalIndex;
6897 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
6898
6899 if (!PP.getPreprocessingRecord()) {
6900 Error("no preprocessing record");
6901 return nullptr;
6902 }
6903
6905 if (llvm::Error Err = M.PreprocessorDetailCursor.JumpToBit(
6906 M.MacroOffsetsBase + PPOffs.getOffset())) {
6907 Error(std::move(Err));
6908 return nullptr;
6909 }
6910
6912 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
6913 if (!MaybeEntry) {
6914 Error(MaybeEntry.takeError());
6915 return nullptr;
6916 }
6917 llvm::BitstreamEntry Entry = MaybeEntry.get();
6918
6919 if (Entry.Kind != llvm::BitstreamEntry::Record)
6920 return nullptr;
6921
6922 // Read the record.
6923 SourceRange Range(ReadSourceLocation(M, PPOffs.getBegin()),
6924 ReadSourceLocation(M, PPOffs.getEnd()));
6925 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
6926 StringRef Blob;
6928 Expected<unsigned> MaybeRecType =
6929 M.PreprocessorDetailCursor.readRecord(Entry.ID, Record, &Blob);
6930 if (!MaybeRecType) {
6931 Error(MaybeRecType.takeError());
6932 return nullptr;
6933 }
6934 switch ((PreprocessorDetailRecordTypes)MaybeRecType.get()) {
6935 case PPD_MACRO_EXPANSION: {
6936 bool isBuiltin = Record[0];
6937 IdentifierInfo *Name = nullptr;
6938 MacroDefinitionRecord *Def = nullptr;
6939 if (isBuiltin)
6940 Name = getLocalIdentifier(M, Record[1]);
6941 else {
6942 PreprocessedEntityID GlobalID =
6944 unsigned Index = translatePreprocessedEntityIDToIndex(GlobalID);
6945 Def =
6946 cast<MacroDefinitionRecord>(PPRec.getLoadedPreprocessedEntity(Index));
6947 }
6948
6949 MacroExpansion *ME;
6950 if (isBuiltin)
6951 ME = new (PPRec) MacroExpansion(Name, Range);
6952 else
6953 ME = new (PPRec) MacroExpansion(Def, Range);
6954
6955 return ME;
6956 }
6957
6958 case PPD_MACRO_DEFINITION: {
6959 // Decode the identifier info and then check again; if the macro is
6960 // still defined and associated with the identifier,
6962 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
6963
6964 if (DeserializationListener)
6965 DeserializationListener->MacroDefinitionRead(PPID, MD);
6966
6967 return MD;
6968 }
6969
6971 const char *FullFileNameStart = Blob.data() + Record[0];
6972 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
6974 if (!FullFileName.empty())
6975 File = PP.getFileManager().getOptionalFileRef(FullFileName);
6976
6977 // FIXME: Stable encoding
6979 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
6981 = new (PPRec) InclusionDirective(PPRec, Kind,
6982 StringRef(Blob.data(), Record[0]),
6983 Record[1], Record[3],
6984 File,
6985 Range);
6986 return ID;
6987 }
6988 }
6989
6990 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
6991}
6992
6993/// Find the next module that contains entities and return the ID
6994/// of the first entry.
6995///
6996/// \param SLocMapI points at a chunk of a module that contains no
6997/// preprocessed entities or the entities it contains are not the ones we are
6998/// looking for.
6999unsigned ASTReader::findNextPreprocessedEntity(
7000 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
7001 ++SLocMapI;
7002 for (GlobalSLocOffsetMapType::const_iterator
7003 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
7004 ModuleFile &M = *SLocMapI->second;
7006 return M.BasePreprocessedEntityID;
7007 }
7008
7009 return getTotalNumPreprocessedEntities();
7010}
7011
7012namespace {
7013
7014struct PPEntityComp {
7015 const ASTReader &Reader;
7016 ModuleFile &M;
7017
7018 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) {}
7019
7020 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
7021 SourceLocation LHS = getLoc(L);
7022 SourceLocation RHS = getLoc(R);
7023 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7024 }
7025
7026 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
7027 SourceLocation LHS = getLoc(L);
7028 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7029 }
7030
7031 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
7032 SourceLocation RHS = getLoc(R);
7033 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7034 }
7035
7036 SourceLocation getLoc(const PPEntityOffset &PPE) const {
7037 return Reader.ReadSourceLocation(M, PPE.getBegin());
7038 }
7039};
7040
7041} // namespace
7042
7043unsigned ASTReader::findPreprocessedEntity(SourceLocation Loc,
7044 bool EndsAfter) const {
7045 if (SourceMgr.isLocalSourceLocation(Loc))
7046 return getTotalNumPreprocessedEntities();
7047
7048 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
7049 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
7050 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
7051 "Corrupted global sloc offset map");
7052
7053 if (SLocMapI->second->NumPreprocessedEntities == 0)
7054 return findNextPreprocessedEntity(SLocMapI);
7055
7056 ModuleFile &M = *SLocMapI->second;
7057
7058 using pp_iterator = const PPEntityOffset *;
7059
7060 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
7061 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
7062
7063 size_t Count = M.NumPreprocessedEntities;
7064 size_t Half;
7065 pp_iterator First = pp_begin;
7066 pp_iterator PPI;
7067
7068 if (EndsAfter) {
7069 PPI = std::upper_bound(pp_begin, pp_end, Loc,
7070 PPEntityComp(*this, M));
7071 } else {
7072 // Do a binary search manually instead of using std::lower_bound because
7073 // The end locations of entities may be unordered (when a macro expansion
7074 // is inside another macro argument), but for this case it is not important
7075 // whether we get the first macro expansion or its containing macro.
7076 while (Count > 0) {
7077 Half = Count / 2;
7078 PPI = First;
7079 std::advance(PPI, Half);
7080 if (SourceMgr.isBeforeInTranslationUnit(
7081 ReadSourceLocation(M, PPI->getEnd()), Loc)) {
7082 First = PPI;
7083 ++First;
7084 Count = Count - Half - 1;
7085 } else
7086 Count = Half;
7087 }
7088 }
7089
7090 if (PPI == pp_end)
7091 return findNextPreprocessedEntity(SLocMapI);
7092
7093 return M.BasePreprocessedEntityID + (PPI - pp_begin);
7094}
7095
7096/// Returns a pair of [Begin, End) indices of preallocated
7097/// preprocessed entities that \arg Range encompasses.
7098std::pair<unsigned, unsigned>
7100 if (Range.isInvalid())
7101 return std::make_pair(0,0);
7102 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
7103
7104 unsigned BeginID = findPreprocessedEntity(Range.getBegin(), false);
7105 unsigned EndID = findPreprocessedEntity(Range.getEnd(), true);
7106 return std::make_pair(BeginID, EndID);
7107}
7108
7109/// Optionally returns true or false if the preallocated preprocessed
7110/// entity with index \arg Index came from file \arg FID.
7111std::optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
7112 FileID FID) {
7113 if (FID.isInvalid())
7114 return false;
7115
7116 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
7117 ModuleFile &M = *PPInfo.first;
7118 unsigned LocalIndex = PPInfo.second;
7119 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
7120
7121 SourceLocation Loc = ReadSourceLocation(M, PPOffs.getBegin());
7122 if (Loc.isInvalid())
7123 return false;
7124
7125 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
7126 return true;
7127 else
7128 return false;
7129}
7130
7131namespace {
7132
7133 /// Visitor used to search for information about a header file.
7134 class HeaderFileInfoVisitor {
7135 FileEntryRef FE;
7136 std::optional<HeaderFileInfo> HFI;
7137
7138 public:
7139 explicit HeaderFileInfoVisitor(FileEntryRef FE) : FE(FE) {}
7140
7141 bool operator()(ModuleFile &M) {
7144 if (!Table)
7145 return false;
7146
7147 // Look in the on-disk hash table for an entry for this file name.
7148 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
7149 if (Pos == Table->end())
7150 return false;
7151
7152 HFI = *Pos;
7153 return true;
7154 }
7155
7156 std::optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
7157 };
7158
7159} // namespace
7160
7162 HeaderFileInfoVisitor Visitor(FE);
7163 ModuleMgr.visit(Visitor);
7164 if (std::optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
7165 return *HFI;
7166
7167 return HeaderFileInfo();
7168}
7169
7171 using DiagState = DiagnosticsEngine::DiagState;
7173
7174 for (ModuleFile &F : ModuleMgr) {
7175 unsigned Idx = 0;
7176 auto &Record = F.PragmaDiagMappings;
7177 if (Record.empty())
7178 continue;
7179
7180 DiagStates.clear();
7181
7182 auto ReadDiagState = [&](const DiagState &BasedOn,
7183 bool IncludeNonPragmaStates) {
7184 unsigned BackrefID = Record[Idx++];
7185 if (BackrefID != 0)
7186 return DiagStates[BackrefID - 1];
7187
7188 // A new DiagState was created here.
7189 Diag.DiagStates.push_back(BasedOn);
7190 DiagState *NewState = &Diag.DiagStates.back();
7191 DiagStates.push_back(NewState);
7192 unsigned Size = Record[Idx++];
7193 assert(Idx + Size * 2 <= Record.size() &&
7194 "Invalid data, not enough diag/map pairs");
7195 while (Size--) {
7196 unsigned DiagID = Record[Idx++];
7197 DiagnosticMapping NewMapping =
7199 if (!NewMapping.isPragma() && !IncludeNonPragmaStates)
7200 continue;
7201
7202 DiagnosticMapping &Mapping = NewState->getOrAddMapping(DiagID);
7203
7204 // If this mapping was specified as a warning but the severity was
7205 // upgraded due to diagnostic settings, simulate the current diagnostic
7206 // settings (and use a warning).
7207 if (NewMapping.wasUpgradedFromWarning() && !Mapping.isErrorOrFatal()) {
7209 NewMapping.setUpgradedFromWarning(false);
7210 }
7211
7212 Mapping = NewMapping;
7213 }
7214 return NewState;
7215 };
7216
7217 // Read the first state.
7218 DiagState *FirstState;
7219 if (F.Kind == MK_ImplicitModule) {
7220 // Implicitly-built modules are reused with different diagnostic
7221 // settings. Use the initial diagnostic state from Diag to simulate this
7222 // compilation's diagnostic settings.
7223 FirstState = Diag.DiagStatesByLoc.FirstDiagState;
7224 DiagStates.push_back(FirstState);
7225
7226 // Skip the initial diagnostic state from the serialized module.
7227 assert(Record[1] == 0 &&
7228 "Invalid data, unexpected backref in initial state");
7229 Idx = 3 + Record[2] * 2;
7230 assert(Idx < Record.size() &&
7231 "Invalid data, not enough state change pairs in initial state");
7232 } else if (F.isModule()) {
7233 // For an explicit module, preserve the flags from the module build
7234 // command line (-w, -Weverything, -Werror, ...) along with any explicit
7235 // -Wblah flags.
7236 unsigned Flags = Record[Idx++];
7237 DiagState Initial(*Diag.getDiagnosticIDs());
7238 Initial.SuppressSystemWarnings = Flags & 1; Flags >>= 1;
7239 Initial.ErrorsAsFatal = Flags & 1; Flags >>= 1;
7240 Initial.WarningsAsErrors = Flags & 1; Flags >>= 1;
7241 Initial.EnableAllWarnings = Flags & 1; Flags >>= 1;
7242 Initial.IgnoreAllWarnings = Flags & 1; Flags >>= 1;
7243 Initial.ExtBehavior = (diag::Severity)Flags;
7244 FirstState = ReadDiagState(Initial, true);
7245
7246 assert(F.OriginalSourceFileID.isValid());
7247
7248 // Set up the root buffer of the module to start with the initial
7249 // diagnostic state of the module itself, to cover files that contain no
7250 // explicit transitions (for which we did not serialize anything).
7251 Diag.DiagStatesByLoc.Files[F.OriginalSourceFileID]
7252 .StateTransitions.push_back({FirstState, 0});
7253 } else {
7254 // For prefix ASTs, start with whatever the user configured on the
7255 // command line.
7256 Idx++; // Skip flags.
7257 FirstState = ReadDiagState(*Diag.DiagStatesByLoc.CurDiagState, false);
7258 }
7259
7260 // Read the state transitions.
7261 unsigned NumLocations = Record[Idx++];
7262 while (NumLocations--) {
7263 assert(Idx < Record.size() &&
7264 "Invalid data, missing pragma diagnostic states");
7265 FileID FID = ReadFileID(F, Record, Idx);
7266 assert(FID.isValid() && "invalid FileID for transition");
7267 unsigned Transitions = Record[Idx++];
7268
7269 // Note that we don't need to set up Parent/ParentOffset here, because
7270 // we won't be changing the diagnostic state within imported FileIDs
7271 // (other than perhaps appending to the main source file, which has no
7272 // parent).
7273 auto &F = Diag.DiagStatesByLoc.Files[FID];
7274 F.StateTransitions.reserve(F.StateTransitions.size() + Transitions);
7275 for (unsigned I = 0; I != Transitions; ++I) {
7276 unsigned Offset = Record[Idx++];
7277 auto *State = ReadDiagState(*FirstState, false);
7278 F.StateTransitions.push_back({State, Offset});
7279 }
7280 }
7281
7282 // Read the final state.
7283 assert(Idx < Record.size() &&
7284 "Invalid data, missing final pragma diagnostic state");
7285 SourceLocation CurStateLoc = ReadSourceLocation(F, Record[Idx++]);
7286 auto *CurState = ReadDiagState(*FirstState, false);
7287
7288 if (!F.isModule()) {
7289 Diag.DiagStatesByLoc.CurDiagState = CurState;
7290 Diag.DiagStatesByLoc.CurDiagStateLoc = CurStateLoc;
7291
7292 // Preserve the property that the imaginary root file describes the
7293 // current state.
7294 FileID NullFile;
7295 auto &T = Diag.DiagStatesByLoc.Files[NullFile].StateTransitions;
7296 if (T.empty())
7297 T.push_back({CurState, 0});
7298 else
7299 T[0].State = CurState;
7300 }
7301
7302 // Restore the push stack so that unmatched pushes from a preamble are
7303 // visible when the main file is parsed, allowing the corresponding
7304 // `#pragma diagnostic pop` to succeed.
7305 assert(Idx < Record.size() &&
7306 "Invalid data, missing diagnostic push stack");
7307 unsigned NumPushes = Record[Idx++];
7308 for (unsigned I = 0; I != NumPushes; ++I) {
7309 auto *State = ReadDiagState(*FirstState, false);
7310 if (!F.isModule())
7311 Diag.DiagStateOnPushStack.push_back(State);
7312 }
7313
7314 // Don't try to read these mappings again.
7315 Record.clear();
7316 }
7317}
7318
7319/// Get the correct cursor and offset for loading a type.
7320ASTReader::RecordLocation ASTReader::TypeCursorForIndex(TypeID ID) {
7321 auto [M, Index] = translateTypeIDToIndex(ID);
7322 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex].get() +
7324}
7325
7326static std::optional<Type::TypeClass> getTypeClassForCode(TypeCode code) {
7327 switch (code) {
7328#define TYPE_BIT_CODE(CLASS_ID, CODE_ID, CODE_VALUE) \
7329 case TYPE_##CODE_ID: return Type::CLASS_ID;
7330#include "clang/Serialization/TypeBitCodes.def"
7331 default:
7332 return std::nullopt;
7333 }
7334}
7335
7336/// Read and return the type with the given index..
7337///
7338/// The index is the type ID, shifted and minus the number of predefs. This
7339/// routine actually reads the record corresponding to the type at the given
7340/// location. It is a helper routine for GetType, which deals with reading type
7341/// IDs.
7342QualType ASTReader::readTypeRecord(TypeID ID) {
7343 assert(ContextObj && "reading type with no AST context");
7344 ASTContext &Context = *ContextObj;
7345 RecordLocation Loc = TypeCursorForIndex(ID);
7346 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
7347
7348 // Keep track of where we are in the stream, then jump back there
7349 // after reading this type.
7350 SavedStreamPosition SavedPosition(DeclsCursor);
7351
7352 ReadingKindTracker ReadingKind(Read_Type, *this);
7353
7354 // Note that we are loading a type record.
7355 Deserializing AType(this);
7356
7357 if (llvm::Error Err = DeclsCursor.JumpToBit(Loc.Offset)) {
7358 Error(std::move(Err));
7359 return QualType();
7360 }
7361 Expected<unsigned> RawCode = DeclsCursor.ReadCode();
7362 if (!RawCode) {
7363 Error(RawCode.takeError());
7364 return QualType();
7365 }
7366
7367 ASTRecordReader Record(*this, *Loc.F);
7368 Expected<unsigned> Code = Record.readRecord(DeclsCursor, RawCode.get());
7369 if (!Code) {
7370 Error(Code.takeError());
7371 return QualType();
7372 }
7373 if (Code.get() == TYPE_EXT_QUAL) {
7374 QualType baseType = Record.readQualType();
7375 Qualifiers quals = Record.readQualifiers();
7376 return Context.getQualifiedType(baseType, quals);
7377 }
7378
7379 auto maybeClass = getTypeClassForCode((TypeCode) Code.get());
7380 if (!maybeClass) {
7381 Error("Unexpected code for type");
7382 return QualType();
7383 }
7384
7385 serialization::AbstractTypeReader<ASTRecordReader> TypeReader(Record);
7386 return TypeReader.read(*maybeClass);
7387}
7388
7389namespace clang {
7390
7391class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
7392 ASTRecordReader &Reader;
7393
7394 SourceLocation readSourceLocation() { return Reader.readSourceLocation(); }
7395 SourceRange readSourceRange() { return Reader.readSourceRange(); }
7396
7397 TypeSourceInfo *GetTypeSourceInfo() {
7398 return Reader.readTypeSourceInfo();
7399 }
7400
7401 NestedNameSpecifierLoc ReadNestedNameSpecifierLoc() {
7402 return Reader.readNestedNameSpecifierLoc();
7403 }
7404
7405 Attr *ReadAttr() {
7406 return Reader.readAttr();
7407 }
7408
7409public:
7410 TypeLocReader(ASTRecordReader &Reader) : Reader(Reader) {}
7411
7412 // We want compile-time assurance that we've enumerated all of
7413 // these, so unfortunately we have to declare them first, then
7414 // define them out-of-line.
7415#define ABSTRACT_TYPELOC(CLASS, PARENT)
7416#define TYPELOC(CLASS, PARENT) \
7417 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
7418#include "clang/AST/TypeLocNodes.def"
7419
7422 void VisitTagTypeLoc(TagTypeLoc TL);
7423};
7424
7425} // namespace clang
7426
7427void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
7428 // nothing to do
7429}
7430
7431void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
7432 TL.setBuiltinLoc(readSourceLocation());
7433 if (TL.needsExtraLocalData()) {
7434 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Reader.readInt()));
7435 TL.setWrittenSignSpec(static_cast<TypeSpecifierSign>(Reader.readInt()));
7436 TL.setWrittenWidthSpec(static_cast<TypeSpecifierWidth>(Reader.readInt()));
7437 TL.setModeAttr(Reader.readInt());
7438 }
7439}
7440
7441void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
7442 TL.setNameLoc(readSourceLocation());
7443}
7444
7445void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
7446 TL.setStarLoc(readSourceLocation());
7447}
7448
7449void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
7450 // nothing to do
7451}
7452
7453void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
7454 // nothing to do
7455}
7456
7457void TypeLocReader::VisitArrayParameterTypeLoc(ArrayParameterTypeLoc TL) {
7458 // nothing to do
7459}
7460
7461void TypeLocReader::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
7462 TL.setExpansionLoc(readSourceLocation());
7463}
7464
7465void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
7466 TL.setCaretLoc(readSourceLocation());
7467}
7468
7469void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
7470 TL.setAmpLoc(readSourceLocation());
7471}
7472
7473void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
7474 TL.setAmpAmpLoc(readSourceLocation());
7475}
7476
7477void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
7478 TL.setStarLoc(readSourceLocation());
7479 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
7480}
7481
7483 TL.setLBracketLoc(readSourceLocation());
7484 TL.setRBracketLoc(readSourceLocation());
7485 if (Reader.readBool())
7486 TL.setSizeExpr(Reader.readExpr());
7487 else
7488 TL.setSizeExpr(nullptr);
7489}
7490
7491void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
7492 VisitArrayTypeLoc(TL);
7493}
7494
7495void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
7496 VisitArrayTypeLoc(TL);
7497}
7498
7499void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
7500 VisitArrayTypeLoc(TL);
7501}
7502
7503void TypeLocReader::VisitDependentSizedArrayTypeLoc(
7504 DependentSizedArrayTypeLoc TL) {
7505 VisitArrayTypeLoc(TL);
7506}
7507
7508void TypeLocReader::VisitDependentAddressSpaceTypeLoc(
7509 DependentAddressSpaceTypeLoc TL) {
7510
7511 TL.setAttrNameLoc(readSourceLocation());
7512 TL.setAttrOperandParensRange(readSourceRange());
7513 TL.setAttrExprOperand(Reader.readExpr());
7514}
7515
7516void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
7517 DependentSizedExtVectorTypeLoc TL) {
7518 TL.setNameLoc(readSourceLocation());
7519}
7520
7521void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
7522 TL.setNameLoc(readSourceLocation());
7523}
7524
7525void TypeLocReader::VisitDependentVectorTypeLoc(
7526 DependentVectorTypeLoc TL) {
7527 TL.setNameLoc(readSourceLocation());
7528}
7529
7530void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
7531 TL.setNameLoc(readSourceLocation());
7532}
7533
7534void TypeLocReader::VisitConstantMatrixTypeLoc(ConstantMatrixTypeLoc TL) {
7535 TL.setAttrNameLoc(readSourceLocation());
7536 TL.setAttrOperandParensRange(readSourceRange());
7537 TL.setAttrRowOperand(Reader.readExpr());
7538 TL.setAttrColumnOperand(Reader.readExpr());
7539}
7540
7541void TypeLocReader::VisitDependentSizedMatrixTypeLoc(
7542 DependentSizedMatrixTypeLoc TL) {
7543 TL.setAttrNameLoc(readSourceLocation());
7544 TL.setAttrOperandParensRange(readSourceRange());
7545 TL.setAttrRowOperand(Reader.readExpr());
7546 TL.setAttrColumnOperand(Reader.readExpr());
7547}
7548
7550 TL.setLocalRangeBegin(readSourceLocation());
7551 TL.setLParenLoc(readSourceLocation());
7552 TL.setRParenLoc(readSourceLocation());
7553 TL.setExceptionSpecRange(readSourceRange());
7554 TL.setLocalRangeEnd(readSourceLocation());
7555 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
7556 TL.setParam(i, Reader.readDeclAs<ParmVarDecl>());
7557 }
7558}
7559
7560void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
7561 VisitFunctionTypeLoc(TL);
7562}
7563
7564void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
7565 VisitFunctionTypeLoc(TL);
7566}
7567
7568void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
7569 SourceLocation ElaboratedKeywordLoc = readSourceLocation();
7570 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc();
7571 SourceLocation NameLoc = readSourceLocation();
7572 TL.set(ElaboratedKeywordLoc, QualifierLoc, NameLoc);
7573}
7574
7575void TypeLocReader::VisitUsingTypeLoc(UsingTypeLoc TL) {
7576 SourceLocation ElaboratedKeywordLoc = readSourceLocation();
7577 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc();
7578 SourceLocation NameLoc = readSourceLocation();
7579 TL.set(ElaboratedKeywordLoc, QualifierLoc, NameLoc);
7580}
7581
7582void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
7583 SourceLocation ElaboratedKeywordLoc = readSourceLocation();
7584 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc();
7585 SourceLocation NameLoc = readSourceLocation();
7586 TL.set(ElaboratedKeywordLoc, QualifierLoc, NameLoc);
7587}
7588
7589void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
7590 TL.setTypeofLoc(readSourceLocation());
7591 TL.setLParenLoc(readSourceLocation());
7592 TL.setRParenLoc(readSourceLocation());
7593}
7594
7595void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
7596 TL.setTypeofLoc(readSourceLocation());
7597 TL.setLParenLoc(readSourceLocation());
7598 TL.setRParenLoc(readSourceLocation());
7599 TL.setUnmodifiedTInfo(GetTypeSourceInfo());
7600}
7601
7602void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
7603 TL.setDecltypeLoc(readSourceLocation());
7604 TL.setRParenLoc(readSourceLocation());
7605}
7606
7607void TypeLocReader::VisitPackIndexingTypeLoc(PackIndexingTypeLoc TL) {
7608 TL.setEllipsisLoc(readSourceLocation());
7609}
7610
7611void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
7612 TL.setKWLoc(readSourceLocation());
7613 TL.setLParenLoc(readSourceLocation());
7614 TL.setRParenLoc(readSourceLocation());
7615 TL.setUnderlyingTInfo(GetTypeSourceInfo());
7616}
7617
7619 auto NNS = readNestedNameSpecifierLoc();
7620 auto TemplateKWLoc = readSourceLocation();
7621 auto ConceptNameLoc = readDeclarationNameInfo();
7622 auto FoundDecl = readDeclAs<NamedDecl>();
7623 auto NamedConcept = readDeclAs<ConceptDecl>();
7624 auto *CR = ConceptReference::Create(
7625 getContext(), NNS, TemplateKWLoc, ConceptNameLoc, FoundDecl, NamedConcept,
7626 (readBool() ? readASTTemplateArgumentListInfo() : nullptr));
7627 return CR;
7628}
7629
7630void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
7631 TL.setNameLoc(readSourceLocation());
7632 if (Reader.readBool())
7633 TL.setConceptReference(Reader.readConceptReference());
7634 if (Reader.readBool())
7635 TL.setRParenLoc(readSourceLocation());
7636}
7637
7638void TypeLocReader::VisitDeducedTemplateSpecializationTypeLoc(
7640 TL.setElaboratedKeywordLoc(readSourceLocation());
7641 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
7642 TL.setTemplateNameLoc(readSourceLocation());
7643}
7644
7646 TL.setElaboratedKeywordLoc(readSourceLocation());
7647 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
7648 TL.setNameLoc(readSourceLocation());
7649}
7650
7651void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
7652 VisitTagTypeLoc(TL);
7653}
7654
7655void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
7656 VisitTagTypeLoc(TL);
7657}
7658
7659void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) { VisitTagTypeLoc(TL); }
7660
7661void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
7662 TL.setAttr(ReadAttr());
7663}
7664
7665void TypeLocReader::VisitCountAttributedTypeLoc(CountAttributedTypeLoc TL) {
7666 // Nothing to do
7667}
7668
7669void TypeLocReader::VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) {
7670 // Nothing to do.
7671}
7672
7673void TypeLocReader::VisitOverflowBehaviorTypeLoc(OverflowBehaviorTypeLoc TL) {
7674 TL.setAttrLoc(readSourceLocation());
7675}
7676
7677void TypeLocReader::VisitHLSLAttributedResourceTypeLoc(
7678 HLSLAttributedResourceTypeLoc TL) {
7679 // Nothing to do.
7680}
7681
7682void TypeLocReader::VisitHLSLInlineSpirvTypeLoc(HLSLInlineSpirvTypeLoc TL) {
7683 // Nothing to do.
7684}
7685
7686void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
7687 TL.setNameLoc(readSourceLocation());
7688}
7689
7690void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
7691 SubstTemplateTypeParmTypeLoc TL) {
7692 TL.setNameLoc(readSourceLocation());
7693}
7694
7695void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
7696 SubstTemplateTypeParmPackTypeLoc TL) {
7697 TL.setNameLoc(readSourceLocation());
7698}
7699
7700void TypeLocReader::VisitSubstBuiltinTemplatePackTypeLoc(
7701 SubstBuiltinTemplatePackTypeLoc TL) {
7702 TL.setNameLoc(readSourceLocation());
7703}
7704
7705void TypeLocReader::VisitTemplateSpecializationTypeLoc(
7706 TemplateSpecializationTypeLoc TL) {
7707 SourceLocation ElaboratedKeywordLoc = readSourceLocation();
7708 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc();
7709 SourceLocation TemplateKeywordLoc = readSourceLocation();
7710 SourceLocation NameLoc = readSourceLocation();
7711 SourceLocation LAngleLoc = readSourceLocation();
7712 SourceLocation RAngleLoc = readSourceLocation();
7713 TL.set(ElaboratedKeywordLoc, QualifierLoc, TemplateKeywordLoc, NameLoc,
7714 LAngleLoc, RAngleLoc);
7715 MutableArrayRef<TemplateArgumentLocInfo> Args = TL.getArgLocInfos();
7716 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
7717 Args[I] = Reader.readTemplateArgumentLocInfo(
7718 TL.getTypePtr()->template_arguments()[I].getKind());
7719}
7720
7721void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
7722 TL.setLParenLoc(readSourceLocation());
7723 TL.setRParenLoc(readSourceLocation());
7724}
7725
7726void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
7727 TL.setElaboratedKeywordLoc(readSourceLocation());
7728 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
7729 TL.setNameLoc(readSourceLocation());
7730}
7731
7732void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
7733 TL.setEllipsisLoc(readSourceLocation());
7734}
7735
7736void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
7737 TL.setNameLoc(readSourceLocation());
7738 TL.setNameEndLoc(readSourceLocation());
7739}
7740
7741void TypeLocReader::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
7742 if (TL.getNumProtocols()) {
7743 TL.setProtocolLAngleLoc(readSourceLocation());
7744 TL.setProtocolRAngleLoc(readSourceLocation());
7745 }
7746 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
7747 TL.setProtocolLoc(i, readSourceLocation());
7748}
7749
7750void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
7751 TL.setHasBaseTypeAsWritten(Reader.readBool());
7752 TL.setTypeArgsLAngleLoc(readSourceLocation());
7753 TL.setTypeArgsRAngleLoc(readSourceLocation());
7754 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
7755 TL.setTypeArgTInfo(i, GetTypeSourceInfo());
7756 TL.setProtocolLAngleLoc(readSourceLocation());
7757 TL.setProtocolRAngleLoc(readSourceLocation());
7758 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
7759 TL.setProtocolLoc(i, readSourceLocation());
7760}
7761
7762void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
7763 TL.setStarLoc(readSourceLocation());
7764}
7765
7766void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
7767 TL.setKWLoc(readSourceLocation());
7768 TL.setLParenLoc(readSourceLocation());
7769 TL.setRParenLoc(readSourceLocation());
7770}
7771
7772void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) {
7773 TL.setKWLoc(readSourceLocation());
7774}
7775
7776void TypeLocReader::VisitBitIntTypeLoc(clang::BitIntTypeLoc TL) {
7777 TL.setNameLoc(readSourceLocation());
7778}
7779
7780void TypeLocReader::VisitDependentBitIntTypeLoc(
7781 clang::DependentBitIntTypeLoc TL) {
7782 TL.setNameLoc(readSourceLocation());
7783}
7784
7785void TypeLocReader::VisitPredefinedSugarTypeLoc(PredefinedSugarTypeLoc TL) {
7786 // Nothing to do.
7787}
7788
7790 TypeLocReader TLR(*this);
7791 for (; !TL.isNull(); TL = TL.getNextTypeLoc())
7792 TLR.Visit(TL);
7793}
7794
7796 QualType InfoTy = readType();
7797 if (InfoTy.isNull())
7798 return nullptr;
7799
7800 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
7801 readTypeLoc(TInfo->getTypeLoc());
7802 return TInfo;
7803}
7804
7806 return (ID & llvm::maskTrailingOnes<TypeID>(32)) >> Qualifiers::FastWidth;
7807}
7808
7810 return ID >> 32;
7811}
7812
7814 // We don't need to erase the higher bits since if these bits are not 0,
7815 // it must be larger than NUM_PREDEF_TYPE_IDS.
7817}
7818
7819std::pair<ModuleFile *, unsigned>
7820ASTReader::translateTypeIDToIndex(serialization::TypeID ID) const {
7821 assert(!isPredefinedType(ID) &&
7822 "Predefined type shouldn't be in TypesLoaded");
7823 unsigned ModuleFileIndex = getModuleFileIndexForTypeID(ID);
7824 assert(ModuleFileIndex && "Untranslated Local Decl?");
7825
7826 ModuleFile *OwningModuleFile = &getModuleManager()[ModuleFileIndex - 1];
7827 assert(OwningModuleFile &&
7828 "untranslated type ID or local type ID shouldn't be in TypesLoaded");
7829
7830 return {OwningModuleFile,
7831 OwningModuleFile->BaseTypeIndex + getIndexForTypeID(ID)};
7832}
7833
7835 assert(ContextObj && "reading type with no AST context");
7836 ASTContext &Context = *ContextObj;
7837
7838 unsigned FastQuals = ID & Qualifiers::FastMask;
7839
7840 if (isPredefinedType(ID)) {
7841 QualType T;
7842 unsigned Index = getIndexForTypeID(ID);
7843 switch ((PredefinedTypeIDs)Index) {
7845 // We should never use this one.
7846 llvm_unreachable("Invalid predefined type");
7847 break;
7849 return QualType();
7851 T = Context.VoidTy;
7852 break;
7854 T = Context.BoolTy;
7855 break;
7858 // FIXME: Check that the signedness of CharTy is correct!
7859 T = Context.CharTy;
7860 break;
7862 T = Context.UnsignedCharTy;
7863 break;
7865 T = Context.UnsignedShortTy;
7866 break;
7868 T = Context.UnsignedIntTy;
7869 break;
7871 T = Context.UnsignedLongTy;
7872 break;
7874 T = Context.UnsignedLongLongTy;
7875 break;
7877 T = Context.UnsignedInt128Ty;
7878 break;
7880 T = Context.SignedCharTy;
7881 break;
7883 T = Context.WCharTy;
7884 break;
7886 T = Context.ShortTy;
7887 break;
7888 case PREDEF_TYPE_INT_ID:
7889 T = Context.IntTy;
7890 break;
7892 T = Context.LongTy;
7893 break;
7895 T = Context.LongLongTy;
7896 break;
7898 T = Context.Int128Ty;
7899 break;
7901 T = Context.BFloat16Ty;
7902 break;
7904 T = Context.HalfTy;
7905 break;
7907 T = Context.FloatTy;
7908 break;
7910 T = Context.DoubleTy;
7911 break;
7913 T = Context.LongDoubleTy;
7914 break;
7916 T = Context.ShortAccumTy;
7917 break;
7919 T = Context.AccumTy;
7920 break;
7922 T = Context.LongAccumTy;
7923 break;
7925 T = Context.UnsignedShortAccumTy;
7926 break;
7928 T = Context.UnsignedAccumTy;
7929 break;
7931 T = Context.UnsignedLongAccumTy;
7932 break;
7934 T = Context.ShortFractTy;
7935 break;
7937 T = Context.FractTy;
7938 break;
7940 T = Context.LongFractTy;
7941 break;
7943 T = Context.UnsignedShortFractTy;
7944 break;
7946 T = Context.UnsignedFractTy;
7947 break;
7949 T = Context.UnsignedLongFractTy;
7950 break;
7952 T = Context.SatShortAccumTy;
7953 break;
7955 T = Context.SatAccumTy;
7956 break;
7958 T = Context.SatLongAccumTy;
7959 break;
7961 T = Context.SatUnsignedShortAccumTy;
7962 break;
7964 T = Context.SatUnsignedAccumTy;
7965 break;
7967 T = Context.SatUnsignedLongAccumTy;
7968 break;
7970 T = Context.SatShortFractTy;
7971 break;
7973 T = Context.SatFractTy;
7974 break;
7976 T = Context.SatLongFractTy;
7977 break;
7979 T = Context.SatUnsignedShortFractTy;
7980 break;
7982 T = Context.SatUnsignedFractTy;
7983 break;
7985 T = Context.SatUnsignedLongFractTy;
7986 break;
7988 T = Context.Float16Ty;
7989 break;
7991 T = Context.Float128Ty;
7992 break;
7994 T = Context.Ibm128Ty;
7995 break;
7997 T = Context.OverloadTy;
7998 break;
8000 T = Context.UnresolvedTemplateTy;
8001 break;
8003 T = Context.BoundMemberTy;
8004 break;
8006 T = Context.PseudoObjectTy;
8007 break;
8009 T = Context.DependentTy;
8010 break;
8012 T = Context.UnknownAnyTy;
8013 break;
8015 T = Context.NullPtrTy;
8016 break;
8018 T = Context.Char8Ty;
8019 break;
8021 T = Context.Char16Ty;
8022 break;
8024 T = Context.Char32Ty;
8025 break;
8027 T = Context.ObjCBuiltinIdTy;
8028 break;
8030 T = Context.ObjCBuiltinClassTy;
8031 break;
8033 T = Context.ObjCBuiltinSelTy;
8034 break;
8035#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8036 case PREDEF_TYPE_##Id##_ID: \
8037 T = Context.SingletonId; \
8038 break;
8039#include "clang/Basic/OpenCLImageTypes.def"
8040#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
8041 case PREDEF_TYPE_##Id##_ID: \
8042 T = Context.Id##Ty; \
8043 break;
8044#include "clang/Basic/OpenCLExtensionTypes.def"
8046 T = Context.OCLSamplerTy;
8047 break;
8049 T = Context.OCLEventTy;
8050 break;
8052 T = Context.OCLClkEventTy;
8053 break;
8055 T = Context.OCLQueueTy;
8056 break;
8058 T = Context.OCLReserveIDTy;
8059 break;
8061 T = Context.getAutoDeductType();
8062 break;
8064 T = Context.getAutoRRefDeductType();
8065 break;
8067 T = Context.ARCUnbridgedCastTy;
8068 break;
8070 T = Context.BuiltinFnTy;
8071 break;
8073 T = Context.IncompleteMatrixIdxTy;
8074 break;
8076 T = Context.ArraySectionTy;
8077 break;
8079 T = Context.OMPArrayShapingTy;
8080 break;
8082 T = Context.OMPIteratorTy;
8083 break;
8084#define SVE_TYPE(Name, Id, SingletonId) \
8085 case PREDEF_TYPE_##Id##_ID: \
8086 T = Context.SingletonId; \
8087 break;
8088#include "clang/Basic/AArch64ACLETypes.def"
8089#define PPC_VECTOR_TYPE(Name, Id, Size) \
8090 case PREDEF_TYPE_##Id##_ID: \
8091 T = Context.Id##Ty; \
8092 break;
8093#include "clang/Basic/PPCTypes.def"
8094#define RVV_TYPE(Name, Id, SingletonId) \
8095 case PREDEF_TYPE_##Id##_ID: \
8096 T = Context.SingletonId; \
8097 break;
8098#include "clang/Basic/RISCVVTypes.def"
8099#define WASM_TYPE(Name, Id, SingletonId) \
8100 case PREDEF_TYPE_##Id##_ID: \
8101 T = Context.SingletonId; \
8102 break;
8103#include "clang/Basic/WebAssemblyReferenceTypes.def"
8104#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) \
8105 case PREDEF_TYPE_##Id##_ID: \
8106 T = Context.SingletonId; \
8107 break;
8108#include "clang/Basic/AMDGPUTypes.def"
8109#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
8110 case PREDEF_TYPE_##Id##_ID: \
8111 T = Context.SingletonId; \
8112 break;
8113#include "clang/Basic/HLSLIntangibleTypes.def"
8114 }
8115
8116 assert(!T.isNull() && "Unknown predefined type");
8117 return T.withFastQualifiers(FastQuals);
8118 }
8119
8120 unsigned Index = translateTypeIDToIndex(ID).second;
8121
8122 assert(Index < TypesLoaded.size() && "Type index out-of-range");
8123 if (TypesLoaded[Index].isNull()) {
8124 TypesLoaded[Index] = readTypeRecord(ID);
8125 if (TypesLoaded[Index].isNull())
8126 return QualType();
8127
8128 TypesLoaded[Index]->setFromAST();
8129 if (DeserializationListener)
8130 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
8131 TypesLoaded[Index]);
8132 }
8133
8134 return TypesLoaded[Index].withFastQualifiers(FastQuals);
8135}
8136
8138 return GetType(getGlobalTypeID(F, LocalID));
8139}
8140
8142 LocalTypeID LocalID) const {
8143 if (isPredefinedType(LocalID))
8144 return LocalID;
8145
8146 if (!F.ModuleOffsetMap.empty())
8147 ReadModuleOffsetMap(F);
8148
8149 unsigned ModuleFileIndex = getModuleFileIndexForTypeID(LocalID);
8150 LocalID &= llvm::maskTrailingOnes<TypeID>(32);
8151
8152 if (ModuleFileIndex == 0)
8154
8155 ModuleFile &MF =
8156 ModuleFileIndex ? *F.TransitiveImports[ModuleFileIndex - 1] : F;
8157 ModuleFileIndex = MF.Index + 1;
8158 return ((uint64_t)ModuleFileIndex << 32) | LocalID;
8159}
8160
8163 switch (Kind) {
8165 return readExpr();
8167 return readTypeSourceInfo();
8170 SourceLocation TemplateKWLoc = readSourceLocation();
8172 SourceLocation TemplateNameLoc = readSourceLocation();
8175 : SourceLocation();
8176 return TemplateArgumentLocInfo(getASTContext(), TemplateKWLoc, QualifierLoc,
8177 TemplateNameLoc, EllipsisLoc);
8178 }
8185 // FIXME: Is this right?
8186 return TemplateArgumentLocInfo();
8187 }
8188 llvm_unreachable("unexpected template argument loc");
8189}
8190
8200
8203 Result.setLAngleLoc(readSourceLocation());
8204 Result.setRAngleLoc(readSourceLocation());
8205 unsigned NumArgsAsWritten = readInt();
8206 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
8207 Result.addArgument(readTemplateArgumentLoc());
8208}
8209
8216
8218
8220 if (NumCurrentElementsDeserializing) {
8221 // We arrange to not care about the complete redeclaration chain while we're
8222 // deserializing. Just remember that the AST has marked this one as complete
8223 // but that it's not actually complete yet, so we know we still need to
8224 // complete it later.
8225 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
8226 return;
8227 }
8228
8229 if (!D->getDeclContext()) {
8230 assert(isa<TranslationUnitDecl>(D) && "Not a TU?");
8231 return;
8232 }
8233
8234 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
8235
8236 // If this is a named declaration, complete it by looking it up
8237 // within its context.
8238 //
8239 // FIXME: Merging a function definition should merge
8240 // all mergeable entities within it.
8242 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
8243 if (!getContext().getLangOpts().CPlusPlus &&
8245 // Outside of C++, we don't have a lookup table for the TU, so update
8246 // the identifier instead. (For C++ modules, we don't store decls
8247 // in the serialized identifier table, so we do the lookup in the TU.)
8248 auto *II = Name.getAsIdentifierInfo();
8249 assert(II && "non-identifier name in C?");
8250 if (II->isOutOfDate())
8252 } else
8253 DC->lookup(Name);
8255 // Find all declarations of this kind from the relevant context.
8256 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
8257 auto *DC = cast<DeclContext>(DCDecl);
8260 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
8261 }
8262 }
8263 }
8264
8267 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
8268 Template = CTSD->getSpecializedTemplate();
8269 Args = CTSD->getTemplateArgs().asArray();
8270 } else if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D)) {
8271 Template = VTSD->getSpecializedTemplate();
8272 Args = VTSD->getTemplateArgs().asArray();
8273 } else if (auto *FD = dyn_cast<FunctionDecl>(D)) {
8274 if (auto *Tmplt = FD->getPrimaryTemplate()) {
8275 Template = Tmplt;
8276 Args = FD->getTemplateSpecializationArgs()->asArray();
8277 }
8278 }
8279
8280 if (Template)
8281 Template->loadLazySpecializationsImpl(Args);
8282}
8283
8286 RecordLocation Loc = getLocalBitOffset(Offset);
8287 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
8288 SavedStreamPosition SavedPosition(Cursor);
8289 if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {
8290 Error(std::move(Err));
8291 return nullptr;
8292 }
8293 ReadingKindTracker ReadingKind(Read_Decl, *this);
8294 Deserializing D(this);
8295
8296 Expected<unsigned> MaybeCode = Cursor.ReadCode();
8297 if (!MaybeCode) {
8298 Error(MaybeCode.takeError());
8299 return nullptr;
8300 }
8301 unsigned Code = MaybeCode.get();
8302
8303 ASTRecordReader Record(*this, *Loc.F);
8304 Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code);
8305 if (!MaybeRecCode) {
8306 Error(MaybeRecCode.takeError());
8307 return nullptr;
8308 }
8309 if (MaybeRecCode.get() != DECL_CXX_CTOR_INITIALIZERS) {
8310 Error("malformed AST file: missing C++ ctor initializers");
8311 return nullptr;
8312 }
8313
8314 return Record.readCXXCtorInitializers();
8315}
8316
8318 assert(ContextObj && "reading base specifiers with no AST context");
8319 ASTContext &Context = *ContextObj;
8320
8321 RecordLocation Loc = getLocalBitOffset(Offset);
8322 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
8323 SavedStreamPosition SavedPosition(Cursor);
8324 if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {
8325 Error(std::move(Err));
8326 return nullptr;
8327 }
8328 ReadingKindTracker ReadingKind(Read_Decl, *this);
8329 Deserializing D(this);
8330
8331 Expected<unsigned> MaybeCode = Cursor.ReadCode();
8332 if (!MaybeCode) {
8333 Error(MaybeCode.takeError());
8334 return nullptr;
8335 }
8336 unsigned Code = MaybeCode.get();
8337
8338 ASTRecordReader Record(*this, *Loc.F);
8339 Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code);
8340 if (!MaybeRecCode) {
8341 Error(MaybeCode.takeError());
8342 return nullptr;
8343 }
8344 unsigned RecCode = MaybeRecCode.get();
8345
8346 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
8347 Error("malformed AST file: missing C++ base specifiers");
8348 return nullptr;
8349 }
8350
8351 unsigned NumBases = Record.readInt();
8352 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
8353 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
8354 for (unsigned I = 0; I != NumBases; ++I)
8355 Bases[I] = Record.readCXXBaseSpecifier();
8356 return Bases;
8357}
8358
8360 LocalDeclID LocalID) const {
8361 if (LocalID < NUM_PREDEF_DECL_IDS)
8362 return GlobalDeclID(LocalID.getRawValue());
8363
8364 unsigned OwningModuleFileIndex = LocalID.getModuleFileIndex();
8365 DeclID ID = LocalID.getLocalDeclIndex();
8366
8367 if (!F.ModuleOffsetMap.empty())
8368 ReadModuleOffsetMap(F);
8369
8370 ModuleFile *OwningModuleFile =
8371 OwningModuleFileIndex == 0
8372 ? &F
8373 : F.TransitiveImports[OwningModuleFileIndex - 1];
8374
8375 if (OwningModuleFileIndex == 0)
8376 ID -= NUM_PREDEF_DECL_IDS;
8377
8378 uint64_t NewModuleFileIndex = OwningModuleFile->Index + 1;
8379 return GlobalDeclID(NewModuleFileIndex, ID);
8380}
8381
8383 // Predefined decls aren't from any module.
8384 if (ID < NUM_PREDEF_DECL_IDS)
8385 return false;
8386
8387 unsigned ModuleFileIndex = ID.getModuleFileIndex();
8388 return M.Index == ModuleFileIndex - 1;
8389}
8390
8392 // Predefined decls aren't from any module.
8393 if (ID < NUM_PREDEF_DECL_IDS)
8394 return nullptr;
8395
8396 uint64_t ModuleFileIndex = ID.getModuleFileIndex();
8397 assert(ModuleFileIndex && "Untranslated Local Decl?");
8398
8399 return &getModuleManager()[ModuleFileIndex - 1];
8400}
8401
8403 if (!D->isFromASTFile())
8404 return nullptr;
8405
8406 return getOwningModuleFile(D->getGlobalID());
8407}
8408
8410 if (ID < NUM_PREDEF_DECL_IDS)
8411 return SourceLocation();
8412
8413 if (Decl *D = GetExistingDecl(ID))
8414 return D->getLocation();
8415
8416 SourceLocation Loc;
8417 DeclCursorForID(ID, Loc);
8418 return Loc;
8419}
8420
8421Decl *ASTReader::getPredefinedDecl(PredefinedDeclIDs ID) {
8422 assert(ContextObj && "reading predefined decl without AST context");
8423 ASTContext &Context = *ContextObj;
8424 Decl *NewLoaded = nullptr;
8425 switch (ID) {
8427 return nullptr;
8428
8430 return Context.getTranslationUnitDecl();
8431
8433 if (Context.ObjCIdDecl)
8434 return Context.ObjCIdDecl;
8435 NewLoaded = Context.getObjCIdDecl();
8436 break;
8437
8439 if (Context.ObjCSelDecl)
8440 return Context.ObjCSelDecl;
8441 NewLoaded = Context.getObjCSelDecl();
8442 break;
8443
8445 if (Context.ObjCClassDecl)
8446 return Context.ObjCClassDecl;
8447 NewLoaded = Context.getObjCClassDecl();
8448 break;
8449
8451 if (Context.ObjCProtocolClassDecl)
8452 return Context.ObjCProtocolClassDecl;
8453 NewLoaded = Context.getObjCProtocolDecl();
8454 break;
8455
8457 if (Context.Int128Decl)
8458 return Context.Int128Decl;
8459 NewLoaded = Context.getInt128Decl();
8460 break;
8461
8463 if (Context.UInt128Decl)
8464 return Context.UInt128Decl;
8465 NewLoaded = Context.getUInt128Decl();
8466 break;
8467
8469 if (Context.ObjCInstanceTypeDecl)
8470 return Context.ObjCInstanceTypeDecl;
8471 NewLoaded = Context.getObjCInstanceTypeDecl();
8472 break;
8473
8475 if (Context.BuiltinVaListDecl)
8476 return Context.BuiltinVaListDecl;
8477 NewLoaded = Context.getBuiltinVaListDecl();
8478 break;
8479
8481 if (Context.VaListTagDecl)
8482 return Context.VaListTagDecl;
8483 NewLoaded = Context.getVaListTagDecl();
8484 break;
8485
8487 if (Context.BuiltinMSVaListDecl)
8488 return Context.BuiltinMSVaListDecl;
8489 NewLoaded = Context.getBuiltinMSVaListDecl();
8490 break;
8491
8493 // ASTContext::getMSGuidTagDecl won't create MSGuidTagDecl conditionally.
8494 return Context.getMSGuidTagDecl();
8495
8497 if (Context.ExternCContext)
8498 return Context.ExternCContext;
8499 NewLoaded = Context.getExternCContextDecl();
8500 break;
8501
8503 if (Context.CFConstantStringTypeDecl)
8504 return Context.CFConstantStringTypeDecl;
8505 NewLoaded = Context.getCFConstantStringDecl();
8506 break;
8507
8509 if (Context.CFConstantStringTagDecl)
8510 return Context.CFConstantStringTagDecl;
8511 NewLoaded = Context.getCFConstantStringTagDecl();
8512 break;
8513
8515 return Context.getMSTypeInfoTagDecl();
8516
8517#define BuiltinTemplate(BTName) \
8518 case PREDEF_DECL##BTName##_ID: \
8519 if (Context.Decl##BTName) \
8520 return Context.Decl##BTName; \
8521 NewLoaded = Context.get##BTName##Decl(); \
8522 break;
8523#include "clang/Basic/BuiltinTemplates.inc"
8524
8526 llvm_unreachable("Invalid decl ID");
8527 break;
8528 }
8529
8530 assert(NewLoaded && "Failed to load predefined decl?");
8531
8532 if (DeserializationListener)
8533 DeserializationListener->PredefinedDeclBuilt(ID, NewLoaded);
8534
8535 return NewLoaded;
8536}
8537
8538unsigned ASTReader::translateGlobalDeclIDToIndex(GlobalDeclID GlobalID) const {
8539 ModuleFile *OwningModuleFile = getOwningModuleFile(GlobalID);
8540 if (!OwningModuleFile) {
8541 assert(GlobalID < NUM_PREDEF_DECL_IDS && "Untransalted Global ID?");
8542 return GlobalID.getRawValue();
8543 }
8544
8545 return OwningModuleFile->BaseDeclIndex + GlobalID.getLocalDeclIndex();
8546}
8547
8549 assert(ContextObj && "reading decl with no AST context");
8550
8551 if (ID < NUM_PREDEF_DECL_IDS) {
8552 Decl *D = getPredefinedDecl((PredefinedDeclIDs)ID);
8553 if (D) {
8554 // Track that we have merged the declaration with ID \p ID into the
8555 // pre-existing predefined declaration \p D.
8556 auto &Merged = KeyDecls[D->getCanonicalDecl()];
8557 if (Merged.empty())
8558 Merged.push_back(ID);
8559 }
8560 return D;
8561 }
8562
8563 unsigned Index = translateGlobalDeclIDToIndex(ID);
8564
8565 if (Index >= DeclsLoaded.size()) {
8566 assert(0 && "declaration ID out-of-range for AST file");
8567 Error("declaration ID out-of-range for AST file");
8568 return nullptr;
8569 }
8570
8571 return DeclsLoaded[Index];
8572}
8573
8575 if (ID < NUM_PREDEF_DECL_IDS)
8576 return GetExistingDecl(ID);
8577
8578 unsigned Index = translateGlobalDeclIDToIndex(ID);
8579
8580 if (Index >= DeclsLoaded.size()) {
8581 assert(0 && "declaration ID out-of-range for AST file");
8582 Error("declaration ID out-of-range for AST file");
8583 return nullptr;
8584 }
8585
8586 if (!DeclsLoaded[Index]) {
8587 ReadDeclRecord(ID);
8588 if (DeserializationListener)
8589 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
8590 }
8591
8592 return DeclsLoaded[Index];
8593}
8594
8596 GlobalDeclID GlobalID) {
8597 if (GlobalID < NUM_PREDEF_DECL_IDS)
8598 return LocalDeclID::get(*this, M, GlobalID.getRawValue());
8599
8600 if (!M.ModuleOffsetMap.empty())
8601 ReadModuleOffsetMap(M);
8602
8603 ModuleFile *Owner = getOwningModuleFile(GlobalID);
8604 DeclID ID = GlobalID.getLocalDeclIndex();
8605
8606 if (Owner == &M) {
8607 ID += NUM_PREDEF_DECL_IDS;
8608 return LocalDeclID::get(*this, M, ID);
8609 }
8610
8611 uint64_t OrignalModuleFileIndex = 0;
8612 for (unsigned I = 0; I < M.TransitiveImports.size(); I++)
8613 if (M.TransitiveImports[I] == Owner) {
8614 OrignalModuleFileIndex = I + 1;
8615 break;
8616 }
8617
8618 if (!OrignalModuleFileIndex)
8619 return LocalDeclID();
8620
8621 return LocalDeclID::get(*this, M, OrignalModuleFileIndex, ID);
8622}
8623
8625 unsigned &Idx) {
8626 if (Idx >= Record.size()) {
8627 Error("Corrupted AST file");
8628 return GlobalDeclID(0);
8629 }
8630
8631 return getGlobalDeclID(F, LocalDeclID::get(*this, F, Record[Idx++]));
8632}
8633
8634/// Resolve the offset of a statement into a statement.
8635///
8636/// This operation will read a new statement from the external
8637/// source each time it is called, and is meant to be used via a
8638/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
8640 // Switch case IDs are per Decl.
8642
8643 // Offset here is a global offset across the entire chain.
8644 RecordLocation Loc = getLocalBitOffset(Offset);
8645 if (llvm::Error Err = Loc.F->DeclsCursor.JumpToBit(Loc.Offset)) {
8646 Error(std::move(Err));
8647 return nullptr;
8648 }
8649 assert(NumCurrentElementsDeserializing == 0 &&
8650 "should not be called while already deserializing");
8651 Deserializing D(this);
8652 return ReadStmtFromStream(*Loc.F);
8653}
8654
8655bool ASTReader::LoadExternalSpecializationsImpl(SpecLookupTableTy &SpecLookups,
8656 const Decl *D) {
8657 assert(D);
8658
8659 auto It = SpecLookups.find(D);
8660 if (It == SpecLookups.end())
8661 return false;
8662
8663 // Get Decl may violate the iterator from SpecializationsLookups so we store
8664 // the DeclIDs in ahead.
8666 It->second.Table.findAll();
8667
8668 // Since we've loaded all the specializations, we can erase it from
8669 // the lookup table.
8670 SpecLookups.erase(It);
8671
8672 bool NewSpecsFound = false;
8673 Deserializing LookupResults(this);
8674 for (auto &Info : Infos) {
8675 if (GetExistingDecl(Info))
8676 continue;
8677 NewSpecsFound = true;
8678 GetDecl(Info);
8679 }
8680
8681 return NewSpecsFound;
8682}
8683
8685 assert(D);
8686
8688 bool NewSpecsFound =
8689 LoadExternalSpecializationsImpl(PartialSpecializationsLookups, D);
8690 if (OnlyPartial)
8691 return NewSpecsFound;
8692
8693 NewSpecsFound |= LoadExternalSpecializationsImpl(SpecializationsLookups, D);
8694 return NewSpecsFound;
8695}
8696
8697bool ASTReader::LoadExternalSpecializationsImpl(
8698 SpecLookupTableTy &SpecLookups, const Decl *D,
8699 ArrayRef<TemplateArgument> TemplateArgs) {
8700 assert(D);
8701
8702 reader::LazySpecializationInfoLookupTable *LookupTable = nullptr;
8703 if (auto It = SpecLookups.find(D); It != SpecLookups.end())
8704 LookupTable = &It->getSecond();
8705 if (!LookupTable)
8706 return false;
8707
8708 // NOTE: The getNameForDiagnostic usage in the lambda may mutate the
8709 // `SpecLookups` object.
8710 llvm::TimeTraceScope TimeScope("Load External Specializations for ", [&] {
8711 std::string Name;
8712 llvm::raw_string_ostream OS(Name);
8713 auto *ND = cast<NamedDecl>(D);
8715 /*Qualified=*/true);
8716 return Name;
8717 });
8718
8719 Deserializing LookupResults(this);
8720 auto HashValue = StableHashForTemplateArguments(TemplateArgs);
8721
8722 // Get Decl may violate the iterator from SpecLookups
8724 LookupTable->Table.find(HashValue);
8725
8726 bool NewSpecsFound = false;
8727 for (auto &Info : Infos) {
8728 if (GetExistingDecl(Info))
8729 continue;
8730 NewSpecsFound = true;
8731 GetDecl(Info);
8732 }
8733
8734 return NewSpecsFound;
8735}
8736
8738 const Decl *D, ArrayRef<TemplateArgument> TemplateArgs) {
8739 assert(D);
8740
8741 bool NewDeclsFound = LoadExternalSpecializationsImpl(
8742 PartialSpecializationsLookups, D, TemplateArgs);
8743 NewDeclsFound |=
8744 LoadExternalSpecializationsImpl(SpecializationsLookups, D, TemplateArgs);
8745
8746 return NewDeclsFound;
8747}
8748
8750 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
8751 SmallVectorImpl<Decl *> &Decls) {
8752 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
8753
8754 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
8755 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
8756 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
8757 auto K = (Decl::Kind)+LexicalDecls[I];
8758 if (!IsKindWeWant(K))
8759 continue;
8760
8761 auto ID = (DeclID) + LexicalDecls[I + 1];
8762
8763 // Don't add predefined declarations to the lexical context more
8764 // than once.
8765 if (ID < NUM_PREDEF_DECL_IDS) {
8766 if (PredefsVisited[ID])
8767 continue;
8768
8769 PredefsVisited[ID] = true;
8770 }
8771
8772 if (Decl *D = GetLocalDecl(*M, LocalDeclID::get(*this, *M, ID))) {
8773 assert(D->getKind() == K && "wrong kind for lexical decl");
8774 if (!DC->isDeclInLexicalTraversal(D))
8775 Decls.push_back(D);
8776 }
8777 }
8778 };
8779
8780 if (isa<TranslationUnitDecl>(DC)) {
8781 for (const auto &Lexical : TULexicalDecls)
8782 Visit(Lexical.first, Lexical.second);
8783 } else {
8784 auto I = LexicalDecls.find(DC);
8785 if (I != LexicalDecls.end())
8786 Visit(I->second.first, I->second.second);
8787 }
8788
8789 ++NumLexicalDeclContextsRead;
8790}
8791
8792namespace {
8793
8794class UnalignedDeclIDComp {
8795 ASTReader &Reader;
8796 ModuleFile &Mod;
8797
8798public:
8799 UnalignedDeclIDComp(ASTReader &Reader, ModuleFile &M)
8800 : Reader(Reader), Mod(M) {}
8801
8802 bool operator()(unaligned_decl_id_t L, unaligned_decl_id_t R) const {
8803 SourceLocation LHS = getLocation(L);
8804 SourceLocation RHS = getLocation(R);
8805 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
8806 }
8807
8808 bool operator()(SourceLocation LHS, unaligned_decl_id_t R) const {
8809 SourceLocation RHS = getLocation(R);
8810 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
8811 }
8812
8813 bool operator()(unaligned_decl_id_t L, SourceLocation RHS) const {
8814 SourceLocation LHS = getLocation(L);
8815 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
8816 }
8817
8818 SourceLocation getLocation(unaligned_decl_id_t ID) const {
8819 return Reader.getSourceManager().getFileLoc(
8821 Reader.getGlobalDeclID(Mod, LocalDeclID::get(Reader, Mod, ID))));
8822 }
8823};
8824
8825} // namespace
8826
8828 unsigned Offset, unsigned Length,
8829 SmallVectorImpl<Decl *> &Decls) {
8831
8832 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
8833 if (I == FileDeclIDs.end())
8834 return;
8835
8836 FileDeclsInfo &DInfo = I->second;
8837 if (DInfo.Decls.empty())
8838 return;
8839
8841 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
8842 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
8843
8844 UnalignedDeclIDComp DIDComp(*this, *DInfo.Mod);
8846 llvm::lower_bound(DInfo.Decls, BeginLoc, DIDComp);
8847 if (BeginIt != DInfo.Decls.begin())
8848 --BeginIt;
8849
8850 // If we are pointing at a top-level decl inside an objc container, we need
8851 // to backtrack until we find it otherwise we will fail to report that the
8852 // region overlaps with an objc container.
8853 while (BeginIt != DInfo.Decls.begin() &&
8854 GetDecl(getGlobalDeclID(*DInfo.Mod,
8855 LocalDeclID::get(*this, *DInfo.Mod, *BeginIt)))
8856 ->isTopLevelDeclInObjCContainer())
8857 --BeginIt;
8858
8860 llvm::upper_bound(DInfo.Decls, EndLoc, DIDComp);
8861 if (EndIt != DInfo.Decls.end())
8862 ++EndIt;
8863
8864 for (ArrayRef<unaligned_decl_id_t>::iterator DIt = BeginIt; DIt != EndIt;
8865 ++DIt)
8866 Decls.push_back(GetDecl(getGlobalDeclID(
8867 *DInfo.Mod, LocalDeclID::get(*this, *DInfo.Mod, *DIt))));
8868}
8869
8871 DeclarationName Name,
8872 const DeclContext *OriginalDC) {
8873 assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
8874 "DeclContext has no visible decls in storage");
8875 if (!Name)
8876 return false;
8877
8878 // Load the list of declarations.
8879 DeclsSet DS;
8880
8881 auto Find = [&, this](auto &&Table, auto &&Key) {
8882 for (GlobalDeclID ID : Table.find(Key)) {
8884 if (ND->getDeclName() != Name)
8885 continue;
8886 // Special case for namespaces: There can be a lot of redeclarations of
8887 // some namespaces, and we import a "key declaration" per imported module.
8888 // Since all declarations of a namespace are essentially interchangeable,
8889 // we can optimize namespace look-up by only storing the key declaration
8890 // of the current TU, rather than storing N key declarations where N is
8891 // the # of imported modules that declare that namespace.
8892 // TODO: Try to generalize this optimization to other redeclarable decls.
8893 if (isa<NamespaceDecl>(ND))
8895 DS.insert(ND);
8896 }
8897 };
8898
8899 Deserializing LookupResults(this);
8900
8901 // FIXME: Clear the redundancy with templated lambda in C++20 when that's
8902 // available.
8903 if (auto It = Lookups.find(DC); It != Lookups.end()) {
8904 ++NumVisibleDeclContextsRead;
8905 Find(It->second.Table, Name);
8906 }
8907
8908 auto FindModuleLocalLookup = [&, this](Module *NamedModule) {
8909 if (auto It = ModuleLocalLookups.find(DC); It != ModuleLocalLookups.end()) {
8910 ++NumModuleLocalVisibleDeclContexts;
8911 Find(It->second.Table, std::make_pair(Name, NamedModule));
8912 }
8913 };
8914 if (auto *NamedModule =
8915 OriginalDC ? cast<Decl>(OriginalDC)->getTopLevelOwningNamedModule()
8916 : nullptr)
8917 FindModuleLocalLookup(NamedModule);
8918 // See clang/test/Modules/ModulesLocalNamespace.cppm for the motiviation case.
8919 // We're going to find a decl but the decl context of the lookup is
8920 // unspecified. In this case, the OriginalDC may be the decl context in other
8921 // module.
8922 if (ContextObj && ContextObj->getCurrentNamedModule())
8923 FindModuleLocalLookup(ContextObj->getCurrentNamedModule());
8924
8925 if (auto It = TULocalLookups.find(DC); It != TULocalLookups.end()) {
8926 ++NumTULocalVisibleDeclContexts;
8927 Find(It->second.Table, Name);
8928 }
8929
8930 SetExternalVisibleDeclsForName(DC, Name, DS);
8931 return !DS.empty();
8932}
8933
8935 if (!DC->hasExternalVisibleStorage())
8936 return;
8937
8938 DeclsMap Decls;
8939
8940 auto findAll = [&](auto &LookupTables, unsigned &NumRead) {
8941 auto It = LookupTables.find(DC);
8942 if (It == LookupTables.end())
8943 return;
8944
8945 NumRead++;
8946
8947 for (GlobalDeclID ID : It->second.Table.findAll()) {
8949 // Special case for namespaces: There can be a lot of redeclarations of
8950 // some namespaces, and we import a "key declaration" per imported module.
8951 // Since all declarations of a namespace are essentially interchangeable,
8952 // we can optimize namespace look-up by only storing the key declaration
8953 // of the current TU, rather than storing N key declarations where N is
8954 // the # of imported modules that declare that namespace.
8955 // TODO: Try to generalize this optimization to other redeclarable decls.
8956 if (isa<NamespaceDecl>(ND))
8958 Decls[ND->getDeclName()].insert(ND);
8959 }
8960
8961 // FIXME: Why a PCH test is failing if we remove the iterator after findAll?
8962 };
8963
8964 findAll(Lookups, NumVisibleDeclContextsRead);
8965 findAll(ModuleLocalLookups, NumModuleLocalVisibleDeclContexts);
8966 findAll(TULocalLookups, NumTULocalVisibleDeclContexts);
8967
8968 for (auto &[Name, DS] : Decls)
8969 SetExternalVisibleDeclsForName(DC, Name, DS);
8970
8971 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
8972}
8973
8976 auto I = Lookups.find(Primary);
8977 return I == Lookups.end() ? nullptr : &I->second;
8978}
8979
8982 auto I = ModuleLocalLookups.find(Primary);
8983 return I == ModuleLocalLookups.end() ? nullptr : &I->second;
8984}
8985
8988 auto I = TULocalLookups.find(Primary);
8989 return I == TULocalLookups.end() ? nullptr : &I->second;
8990}
8991
8994 assert(D->isCanonicalDecl());
8995 auto &LookupTable =
8996 IsPartial ? PartialSpecializationsLookups : SpecializationsLookups;
8997 auto I = LookupTable.find(D);
8998 return I == LookupTable.end() ? nullptr : &I->second;
8999}
9000
9002 assert(D->isCanonicalDecl());
9003 return PartialSpecializationsLookups.contains(D) ||
9004 SpecializationsLookups.contains(D);
9005}
9006
9007/// Under non-PCH compilation the consumer receives the objc methods
9008/// before receiving the implementation, and codegen depends on this.
9009/// We simulate this by deserializing and passing to consumer the methods of the
9010/// implementation before passing the deserialized implementation decl.
9012 ASTConsumer *Consumer) {
9013 assert(ImplD && Consumer);
9014
9015 for (auto *I : ImplD->methods())
9016 Consumer->HandleInterestingDecl(DeclGroupRef(I));
9017
9018 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
9019}
9020
9021void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
9022 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
9023 PassObjCImplDeclToConsumer(ImplD, Consumer);
9024 else
9025 Consumer->HandleInterestingDecl(DeclGroupRef(D));
9026}
9027
9028void ASTReader::PassVTableToConsumer(CXXRecordDecl *RD) {
9029 Consumer->HandleVTable(RD);
9030}
9031
9033 this->Consumer = Consumer;
9034
9035 if (Consumer)
9036 PassInterestingDeclsToConsumer();
9037
9038 if (DeserializationListener)
9039 DeserializationListener->ReaderInitialized(this);
9040}
9041
9043 std::fprintf(stderr, "*** AST File Statistics:\n");
9044
9045 unsigned NumTypesLoaded =
9046 TypesLoaded.size() - llvm::count(TypesLoaded.materialized(), QualType());
9047 unsigned NumDeclsLoaded =
9048 DeclsLoaded.size() -
9049 llvm::count(DeclsLoaded.materialized(), (Decl *)nullptr);
9050 unsigned NumIdentifiersLoaded =
9051 IdentifiersLoaded.size() -
9052 llvm::count(IdentifiersLoaded, (IdentifierInfo *)nullptr);
9053 unsigned NumMacrosLoaded =
9054 MacrosLoaded.size() - llvm::count(MacrosLoaded, (MacroInfo *)nullptr);
9055 unsigned NumSelectorsLoaded =
9056 SelectorsLoaded.size() - llvm::count(SelectorsLoaded, Selector());
9057
9058 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
9059 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
9060 NumSLocEntriesRead, TotalNumSLocEntries,
9061 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
9062 if (!TypesLoaded.empty())
9063 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
9064 NumTypesLoaded, (unsigned)TypesLoaded.size(),
9065 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
9066 if (!DeclsLoaded.empty())
9067 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
9068 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
9069 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
9070 if (!IdentifiersLoaded.empty())
9071 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
9072 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
9073 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
9074 if (!MacrosLoaded.empty())
9075 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
9076 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
9077 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
9078 if (!SelectorsLoaded.empty())
9079 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
9080 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
9081 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
9082 if (TotalNumStatements)
9083 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
9084 NumStatementsRead, TotalNumStatements,
9085 ((float)NumStatementsRead/TotalNumStatements * 100));
9086 if (TotalNumMacros)
9087 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
9088 NumMacrosRead, TotalNumMacros,
9089 ((float)NumMacrosRead/TotalNumMacros * 100));
9090 if (TotalLexicalDeclContexts)
9091 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
9092 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
9093 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
9094 * 100));
9095 if (TotalVisibleDeclContexts)
9096 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
9097 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
9098 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
9099 * 100));
9100 if (TotalModuleLocalVisibleDeclContexts)
9101 std::fprintf(
9102 stderr, " %u/%u module local visible declcontexts read (%f%%)\n",
9103 NumModuleLocalVisibleDeclContexts, TotalModuleLocalVisibleDeclContexts,
9104 ((float)NumModuleLocalVisibleDeclContexts /
9105 TotalModuleLocalVisibleDeclContexts * 100));
9106 if (TotalTULocalVisibleDeclContexts)
9107 std::fprintf(stderr, " %u/%u visible declcontexts in GMF read (%f%%)\n",
9108 NumTULocalVisibleDeclContexts, TotalTULocalVisibleDeclContexts,
9109 ((float)NumTULocalVisibleDeclContexts /
9110 TotalTULocalVisibleDeclContexts * 100));
9111 if (TotalNumMethodPoolEntries)
9112 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
9113 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
9114 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
9115 * 100));
9116 if (NumMethodPoolLookups)
9117 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
9118 NumMethodPoolHits, NumMethodPoolLookups,
9119 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
9120 if (NumMethodPoolTableLookups)
9121 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
9122 NumMethodPoolTableHits, NumMethodPoolTableLookups,
9123 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
9124 * 100.0));
9125 if (NumIdentifierLookupHits)
9126 std::fprintf(stderr,
9127 " %u / %u identifier table lookups succeeded (%f%%)\n",
9128 NumIdentifierLookupHits, NumIdentifierLookups,
9129 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
9130
9131 if (GlobalIndex) {
9132 std::fprintf(stderr, "\n");
9133 GlobalIndex->printStats();
9134 }
9135
9136 std::fprintf(stderr, "\n");
9137 dump();
9138 std::fprintf(stderr, "\n");
9139}
9140
9141template<typename Key, typename ModuleFile, unsigned InitialCapacity>
9142LLVM_DUMP_METHOD static void
9143dumpModuleIDMap(StringRef Name,
9144 const ContinuousRangeMap<Key, ModuleFile *,
9145 InitialCapacity> &Map) {
9146 if (Map.begin() == Map.end())
9147 return;
9148
9150
9151 llvm::errs() << Name << ":\n";
9152 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
9153 I != IEnd; ++I)
9154 llvm::errs() << " " << (DeclID)I->first << " -> " << I->second->FileName
9155 << "\n";
9156}
9157
9158LLVM_DUMP_METHOD void ASTReader::dump() {
9159 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
9160 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
9161 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
9162 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
9163 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
9164 dumpModuleIDMap("Global preprocessed entity map",
9165 GlobalPreprocessedEntityMap);
9166
9167 llvm::errs() << "\n*** PCH/Modules Loaded:";
9168 for (ModuleFile &M : ModuleMgr)
9169 M.dump();
9170}
9171
9172/// Return the amount of memory used by memory buffers, breaking down
9173/// by heap-backed versus mmap'ed memory.
9175 for (ModuleFile &I : ModuleMgr) {
9176 if (llvm::MemoryBuffer *buf = I.Buffer) {
9177 size_t bytes = buf->getBufferSize();
9178 switch (buf->getBufferKind()) {
9179 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
9180 sizes.malloc_bytes += bytes;
9181 break;
9182 case llvm::MemoryBuffer::MemoryBuffer_MMap:
9183 sizes.mmap_bytes += bytes;
9184 break;
9185 }
9186 }
9187 }
9188}
9189
9191 SemaObj = &S;
9192 S.addExternalSource(this);
9193
9194 // Makes sure any declarations that were deserialized "too early"
9195 // still get added to the identifier's declaration chains.
9196 for (GlobalDeclID ID : PreloadedDeclIDs) {
9198 pushExternalDeclIntoScope(D, D->getDeclName());
9199 }
9200 PreloadedDeclIDs.clear();
9201
9202 // FIXME: What happens if these are changed by a module import?
9203 if (!FPPragmaOptions.empty()) {
9204 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
9205 FPOptionsOverride NewOverrides =
9206 FPOptionsOverride::getFromOpaqueInt(FPPragmaOptions[0]);
9207 SemaObj->CurFPFeatures =
9208 NewOverrides.applyOverrides(SemaObj->getLangOpts());
9209 }
9210
9211 for (GlobalDeclID ID : DeclsWithEffectsToVerify) {
9212 Decl *D = GetDecl(ID);
9213 if (auto *FD = dyn_cast<FunctionDecl>(D))
9214 SemaObj->addDeclWithEffects(FD, FD->getFunctionEffects());
9215 else if (auto *BD = dyn_cast<BlockDecl>(D))
9216 SemaObj->addDeclWithEffects(BD, BD->getFunctionEffects());
9217 else
9218 llvm_unreachable("unexpected Decl type in DeclsWithEffectsToVerify");
9219 }
9220 DeclsWithEffectsToVerify.clear();
9221
9222 SemaObj->OpenCLFeatures = OpenCLExtensions;
9223
9224 UpdateSema();
9225}
9226
9228 assert(SemaObj && "no Sema to update");
9229
9230 // Load the offsets of the declarations that Sema references.
9231 // They will be lazily deserialized when needed.
9232 if (!SemaDeclRefs.empty()) {
9233 assert(SemaDeclRefs.size() % 3 == 0);
9234 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 3) {
9235 if (!SemaObj->StdNamespace)
9236 SemaObj->StdNamespace = SemaDeclRefs[I].getRawValue();
9237 if (!SemaObj->StdBadAlloc)
9238 SemaObj->StdBadAlloc = SemaDeclRefs[I + 1].getRawValue();
9239 if (!SemaObj->StdAlignValT)
9240 SemaObj->StdAlignValT = SemaDeclRefs[I + 2].getRawValue();
9241 }
9242 SemaDeclRefs.clear();
9243 }
9244
9245 // Update the state of pragmas. Use the same API as if we had encountered the
9246 // pragma in the source.
9247 if(OptimizeOffPragmaLocation.isValid())
9248 SemaObj->ActOnPragmaOptimize(/* On = */ false, OptimizeOffPragmaLocation);
9249 if (PragmaMSStructState != -1)
9250 SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState);
9251 if (PointersToMembersPragmaLocation.isValid()) {
9252 SemaObj->ActOnPragmaMSPointersToMembers(
9254 PragmaMSPointersToMembersState,
9255 PointersToMembersPragmaLocation);
9256 }
9257 SemaObj->CUDA().ForceHostDeviceDepth = ForceHostDeviceDepth;
9258 if (!RISCVVecIntrinsicPragma.empty()) {
9259 assert(RISCVVecIntrinsicPragma.size() == 3 &&
9260 "Wrong number of RISCVVecIntrinsicPragma");
9261 SemaObj->RISCV().DeclareRVVBuiltins = RISCVVecIntrinsicPragma[0];
9262 SemaObj->RISCV().DeclareSiFiveVectorBuiltins = RISCVVecIntrinsicPragma[1];
9263 SemaObj->RISCV().DeclareAndesVectorBuiltins = RISCVVecIntrinsicPragma[2];
9264 }
9265
9266 if (PragmaAlignPackCurrentValue) {
9267 // The bottom of the stack might have a default value. It must be adjusted
9268 // to the current value to ensure that the packing state is preserved after
9269 // popping entries that were included/imported from a PCH/module.
9270 bool DropFirst = false;
9271 if (!PragmaAlignPackStack.empty() &&
9272 PragmaAlignPackStack.front().Location.isInvalid()) {
9273 assert(PragmaAlignPackStack.front().Value ==
9274 SemaObj->AlignPackStack.DefaultValue &&
9275 "Expected a default alignment value");
9276 SemaObj->AlignPackStack.Stack.emplace_back(
9277 PragmaAlignPackStack.front().SlotLabel,
9278 SemaObj->AlignPackStack.CurrentValue,
9279 SemaObj->AlignPackStack.CurrentPragmaLocation,
9280 PragmaAlignPackStack.front().PushLocation);
9281 DropFirst = true;
9282 }
9283 for (const auto &Entry :
9284 llvm::ArrayRef(PragmaAlignPackStack).drop_front(DropFirst ? 1 : 0)) {
9285 SemaObj->AlignPackStack.Stack.emplace_back(
9286 Entry.SlotLabel, Entry.Value, Entry.Location, Entry.PushLocation);
9287 }
9288 if (PragmaAlignPackCurrentLocation.isInvalid()) {
9289 assert(*PragmaAlignPackCurrentValue ==
9290 SemaObj->AlignPackStack.DefaultValue &&
9291 "Expected a default align and pack value");
9292 // Keep the current values.
9293 } else {
9294 SemaObj->AlignPackStack.CurrentValue = *PragmaAlignPackCurrentValue;
9295 SemaObj->AlignPackStack.CurrentPragmaLocation =
9296 PragmaAlignPackCurrentLocation;
9297 }
9298 }
9299 if (FpPragmaCurrentValue) {
9300 // The bottom of the stack might have a default value. It must be adjusted
9301 // to the current value to ensure that fp-pragma state is preserved after
9302 // popping entries that were included/imported from a PCH/module.
9303 bool DropFirst = false;
9304 if (!FpPragmaStack.empty() && FpPragmaStack.front().Location.isInvalid()) {
9305 assert(FpPragmaStack.front().Value ==
9306 SemaObj->FpPragmaStack.DefaultValue &&
9307 "Expected a default pragma float_control value");
9308 SemaObj->FpPragmaStack.Stack.emplace_back(
9309 FpPragmaStack.front().SlotLabel, SemaObj->FpPragmaStack.CurrentValue,
9310 SemaObj->FpPragmaStack.CurrentPragmaLocation,
9311 FpPragmaStack.front().PushLocation);
9312 DropFirst = true;
9313 }
9314 for (const auto &Entry :
9315 llvm::ArrayRef(FpPragmaStack).drop_front(DropFirst ? 1 : 0))
9316 SemaObj->FpPragmaStack.Stack.emplace_back(
9317 Entry.SlotLabel, Entry.Value, Entry.Location, Entry.PushLocation);
9318 if (FpPragmaCurrentLocation.isInvalid()) {
9319 assert(*FpPragmaCurrentValue == SemaObj->FpPragmaStack.DefaultValue &&
9320 "Expected a default pragma float_control value");
9321 // Keep the current values.
9322 } else {
9323 SemaObj->FpPragmaStack.CurrentValue = *FpPragmaCurrentValue;
9324 SemaObj->FpPragmaStack.CurrentPragmaLocation = FpPragmaCurrentLocation;
9325 }
9326 }
9327
9328 // For non-modular AST files, restore visiblity of modules.
9329 for (auto &Import : PendingImportedModulesSema) {
9330 if (Import.ImportLoc.isInvalid())
9331 continue;
9332 if (Module *Imported = getSubmodule(Import.ID)) {
9333 SemaObj->makeModuleVisible(Imported, Import.ImportLoc);
9334 }
9335 }
9336 PendingImportedModulesSema.clear();
9337}
9338
9340 // Note that we are loading an identifier.
9341 Deserializing AnIdentifier(this);
9342
9343 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
9344 NumIdentifierLookups,
9345 NumIdentifierLookupHits);
9346
9347 // We don't need to do identifier table lookups in C++ modules (we preload
9348 // all interesting declarations, and don't need to use the scope for name
9349 // lookups). Perform the lookup in PCH files, though, since we don't build
9350 // a complete initial identifier table if we're carrying on from a PCH.
9351 if (PP.getLangOpts().CPlusPlus) {
9352 for (auto *F : ModuleMgr.pch_modules())
9353 if (Visitor(*F))
9354 break;
9355 } else {
9356 // If there is a global index, look there first to determine which modules
9357 // provably do not have any results for this identifier.
9359 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
9360 if (!loadGlobalIndex()) {
9361 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
9362 HitsPtr = &Hits;
9363 }
9364 }
9365
9366 ModuleMgr.visit(Visitor, HitsPtr);
9367 }
9368
9369 IdentifierInfo *II = Visitor.getIdentifierInfo();
9371 return II;
9372}
9373
9374namespace clang {
9375
9376 /// An identifier-lookup iterator that enumerates all of the
9377 /// identifiers stored within a set of AST files.
9379 /// The AST reader whose identifiers are being enumerated.
9380 const ASTReader &Reader;
9381
9382 /// The current index into the chain of AST files stored in
9383 /// the AST reader.
9384 unsigned Index;
9385
9386 /// The current position within the identifier lookup table
9387 /// of the current AST file.
9388 ASTIdentifierLookupTable::key_iterator Current;
9389
9390 /// The end position within the identifier lookup table of
9391 /// the current AST file.
9392 ASTIdentifierLookupTable::key_iterator End;
9393
9394 /// Whether to skip any modules in the ASTReader.
9395 bool SkipModules;
9396
9397 public:
9398 explicit ASTIdentifierIterator(const ASTReader &Reader,
9399 bool SkipModules = false);
9400
9401 StringRef Next() override;
9402 };
9403
9404} // namespace clang
9405
9407 bool SkipModules)
9408 : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) {
9409}
9410
9412 while (Current == End) {
9413 // If we have exhausted all of our AST files, we're done.
9414 if (Index == 0)
9415 return StringRef();
9416
9417 --Index;
9418 ModuleFile &F = Reader.ModuleMgr[Index];
9419 if (SkipModules && F.isModule())
9420 continue;
9421
9422 ASTIdentifierLookupTable *IdTable =
9424 Current = IdTable->key_begin();
9425 End = IdTable->key_end();
9426 }
9427
9428 // We have any identifiers remaining in the current AST file; return
9429 // the next one.
9430 StringRef Result = *Current;
9431 ++Current;
9432 return Result;
9433}
9434
9435namespace {
9436
9437/// A utility for appending two IdentifierIterators.
9438class ChainedIdentifierIterator : public IdentifierIterator {
9439 std::unique_ptr<IdentifierIterator> Current;
9440 std::unique_ptr<IdentifierIterator> Queued;
9441
9442public:
9443 ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First,
9444 std::unique_ptr<IdentifierIterator> Second)
9445 : Current(std::move(First)), Queued(std::move(Second)) {}
9446
9447 StringRef Next() override {
9448 if (!Current)
9449 return StringRef();
9450
9451 StringRef result = Current->Next();
9452 if (!result.empty())
9453 return result;
9454
9455 // Try the queued iterator, which may itself be empty.
9456 Current.reset();
9457 std::swap(Current, Queued);
9458 return Next();
9459 }
9460};
9461
9462} // namespace
9463
9465 if (!loadGlobalIndex()) {
9466 std::unique_ptr<IdentifierIterator> ReaderIter(
9467 new ASTIdentifierIterator(*this, /*SkipModules=*/true));
9468 std::unique_ptr<IdentifierIterator> ModulesIter(
9469 GlobalIndex->createIdentifierIterator());
9470 return new ChainedIdentifierIterator(std::move(ReaderIter),
9471 std::move(ModulesIter));
9472 }
9473
9474 return new ASTIdentifierIterator(*this);
9475}
9476
9477namespace clang {
9478namespace serialization {
9479
9481 ASTReader &Reader;
9482 Selector Sel;
9483 unsigned PriorGeneration;
9484 unsigned InstanceBits = 0;
9485 unsigned FactoryBits = 0;
9486 bool InstanceHasMoreThanOneDecl = false;
9487 bool FactoryHasMoreThanOneDecl = false;
9488 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
9489 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
9490
9491 public:
9493 unsigned PriorGeneration)
9494 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration) {}
9495
9497 if (!M.SelectorLookupTable)
9498 return false;
9499
9500 // If we've already searched this module file, skip it now.
9501 if (M.Generation <= PriorGeneration)
9502 return true;
9503
9504 ++Reader.NumMethodPoolTableLookups;
9505 ASTSelectorLookupTable *PoolTable
9507 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
9508 if (Pos == PoolTable->end())
9509 return false;
9510
9511 ++Reader.NumMethodPoolTableHits;
9512 ++Reader.NumSelectorsRead;
9513 // FIXME: Not quite happy with the statistics here. We probably should
9514 // disable this tracking when called via LoadSelector.
9515 // Also, should entries without methods count as misses?
9516 ++Reader.NumMethodPoolEntriesRead;
9518 if (Reader.DeserializationListener)
9519 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
9520
9521 // Append methods in the reverse order, so that later we can process them
9522 // in the order they appear in the source code by iterating through
9523 // the vector in the reverse order.
9524 InstanceMethods.append(Data.Instance.rbegin(), Data.Instance.rend());
9525 FactoryMethods.append(Data.Factory.rbegin(), Data.Factory.rend());
9526 InstanceBits = Data.InstanceBits;
9527 FactoryBits = Data.FactoryBits;
9528 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
9529 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
9530 return false;
9531 }
9532
9533 /// Retrieve the instance methods found by this visitor.
9535 return InstanceMethods;
9536 }
9537
9538 /// Retrieve the instance methods found by this visitor.
9540 return FactoryMethods;
9541 }
9542
9543 unsigned getInstanceBits() const { return InstanceBits; }
9544 unsigned getFactoryBits() const { return FactoryBits; }
9545
9547 return InstanceHasMoreThanOneDecl;
9548 }
9549
9550 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
9551 };
9552
9553} // namespace serialization
9554} // namespace clang
9555
9556/// Add the given set of methods to the method list.
9558 ObjCMethodList &List) {
9559 for (ObjCMethodDecl *M : llvm::reverse(Methods))
9560 S.ObjC().addMethodToGlobalList(&List, M);
9561}
9562
9564 // Get the selector generation and update it to the current generation.
9565 unsigned &Generation = SelectorGeneration[Sel];
9566 unsigned PriorGeneration = Generation;
9567 Generation = getGeneration();
9568 SelectorOutOfDate[Sel] = false;
9569
9570 // Search for methods defined with this selector.
9571 ++NumMethodPoolLookups;
9572 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
9573 ModuleMgr.visit(Visitor);
9574
9575 if (Visitor.getInstanceMethods().empty() &&
9576 Visitor.getFactoryMethods().empty())
9577 return;
9578
9579 ++NumMethodPoolHits;
9580
9581 if (!getSema())
9582 return;
9583
9584 Sema &S = *getSema();
9585 auto &Methods = S.ObjC().MethodPool[Sel];
9586
9587 Methods.first.setBits(Visitor.getInstanceBits());
9588 Methods.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
9589 Methods.second.setBits(Visitor.getFactoryBits());
9590 Methods.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
9591
9592 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
9593 // when building a module we keep every method individually and may need to
9594 // update hasMoreThanOneDecl as we add the methods.
9595 addMethodsToPool(S, Visitor.getInstanceMethods(), Methods.first);
9596 addMethodsToPool(S, Visitor.getFactoryMethods(), Methods.second);
9597}
9598
9600 if (SelectorOutOfDate[Sel])
9601 ReadMethodPool(Sel);
9602}
9603
9606 Namespaces.clear();
9607
9608 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
9609 if (NamespaceDecl *Namespace
9610 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
9611 Namespaces.push_back(Namespace);
9612 }
9613}
9614
9616 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {
9617 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
9618 UndefinedButUsedDecl &U = UndefinedButUsed[Idx++];
9621 Undefined.insert(std::make_pair(D, Loc));
9622 }
9623 UndefinedButUsed.clear();
9624}
9625
9627 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
9628 Exprs) {
9629 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
9630 FieldDecl *FD =
9631 cast<FieldDecl>(GetDecl(GlobalDeclID(DelayedDeleteExprs[Idx++])));
9632 uint64_t Count = DelayedDeleteExprs[Idx++];
9633 for (uint64_t C = 0; C < Count; ++C) {
9634 SourceLocation DeleteLoc =
9635 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
9636 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
9637 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
9638 }
9639 }
9640}
9641
9643 SmallVectorImpl<VarDecl *> &TentativeDefs) {
9644 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
9645 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
9646 if (Var)
9647 TentativeDefs.push_back(Var);
9648 }
9649 TentativeDefinitions.clear();
9650}
9651
9654 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
9656 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
9657 if (D)
9658 Decls.push_back(D);
9659 }
9660 UnusedFileScopedDecls.clear();
9661}
9662
9665 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
9667 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
9668 if (D)
9669 Decls.push_back(D);
9670 }
9671 DelegatingCtorDecls.clear();
9672}
9673
9675 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
9677 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
9678 if (D)
9679 Decls.push_back(D);
9680 }
9681 ExtVectorDecls.clear();
9682}
9683
9686 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
9687 ++I) {
9688 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
9689 GetDecl(UnusedLocalTypedefNameCandidates[I]));
9690 if (D)
9691 Decls.insert(D);
9692 }
9693 UnusedLocalTypedefNameCandidates.clear();
9694}
9695
9698 for (auto I : DeclsToCheckForDeferredDiags) {
9699 auto *D = dyn_cast_or_null<Decl>(GetDecl(I));
9700 if (D)
9701 Decls.insert(D);
9702 }
9703 DeclsToCheckForDeferredDiags.clear();
9704}
9705
9707 SmallVectorImpl<std::pair<Selector, SourceLocation>> &Sels) {
9708 if (ReferencedSelectorsData.empty())
9709 return;
9710
9711 // If there are @selector references added them to its pool. This is for
9712 // implementation of -Wselector.
9713 unsigned int DataSize = ReferencedSelectorsData.size()-1;
9714 unsigned I = 0;
9715 while (I < DataSize) {
9716 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
9717 SourceLocation SelLoc
9718 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
9719 Sels.push_back(std::make_pair(Sel, SelLoc));
9720 }
9721 ReferencedSelectorsData.clear();
9722}
9723
9725 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo>> &WeakIDs) {
9726 if (WeakUndeclaredIdentifiers.empty())
9727 return;
9728
9729 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
9730 IdentifierInfo *WeakId
9731 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
9732 IdentifierInfo *AliasId
9733 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
9734 SourceLocation Loc =
9735 SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
9736 WeakInfo WI(AliasId, Loc);
9737 WeakIDs.push_back(std::make_pair(WeakId, WI));
9738 }
9739 WeakUndeclaredIdentifiers.clear();
9740}
9741
9743 SmallVectorImpl<std::pair<IdentifierInfo *, AsmLabelAttr *>> &ExtnameIDs) {
9744 if (ExtnameUndeclaredIdentifiers.empty())
9745 return;
9746
9747 for (unsigned I = 0, N = ExtnameUndeclaredIdentifiers.size(); I < N; I += 3) {
9748 IdentifierInfo *NameId =
9749 DecodeIdentifierInfo(ExtnameUndeclaredIdentifiers[I]);
9750 IdentifierInfo *ExtnameId =
9751 DecodeIdentifierInfo(ExtnameUndeclaredIdentifiers[I+1]);
9752 SourceLocation Loc =
9753 SourceLocation::getFromRawEncoding(ExtnameUndeclaredIdentifiers[I+2]);
9754 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
9755 getContext(), ExtnameId->getName(),
9756 AttributeCommonInfo(ExtnameId, SourceRange(Loc),
9758 ExtnameIDs.push_back(std::make_pair(NameId, Attr));
9759 }
9760 ExtnameUndeclaredIdentifiers.clear();
9761}
9762
9764 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
9766 VTableUse &TableInfo = VTableUses[Idx++];
9767 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(TableInfo.ID));
9768 VT.Location = SourceLocation::getFromRawEncoding(TableInfo.RawLoc);
9769 VT.DefinitionRequired = TableInfo.Used;
9770 VTables.push_back(VT);
9771 }
9772
9773 VTableUses.clear();
9774}
9775
9777 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation>> &Pending) {
9778 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
9779 PendingInstantiation &Inst = PendingInstantiations[Idx++];
9780 ValueDecl *D = cast<ValueDecl>(GetDecl(Inst.ID));
9782
9783 Pending.push_back(std::make_pair(D, Loc));
9784 }
9785 PendingInstantiations.clear();
9786}
9787
9789 llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>>
9790 &LPTMap) {
9791 for (auto &LPT : LateParsedTemplates) {
9792 ModuleFile *FMod = LPT.first;
9793 RecordDataImpl &LateParsed = LPT.second;
9794 for (unsigned Idx = 0, N = LateParsed.size(); Idx < N;
9795 /* In loop */) {
9796 FunctionDecl *FD = ReadDeclAs<FunctionDecl>(*FMod, LateParsed, Idx);
9797
9798 auto LT = std::make_unique<LateParsedTemplate>();
9799 LT->D = ReadDecl(*FMod, LateParsed, Idx);
9800 LT->FPO = FPOptions::getFromOpaqueInt(LateParsed[Idx++]);
9801
9802 ModuleFile *F = getOwningModuleFile(LT->D);
9803 assert(F && "No module");
9804
9805 unsigned TokN = LateParsed[Idx++];
9806 LT->Toks.reserve(TokN);
9807 for (unsigned T = 0; T < TokN; ++T)
9808 LT->Toks.push_back(ReadToken(*F, LateParsed, Idx));
9809
9810 LPTMap.insert(std::make_pair(FD, std::move(LT)));
9811 }
9812 }
9813
9814 LateParsedTemplates.clear();
9815}
9816
9818 if (!Lambda->getLambdaContextDecl())
9819 return;
9820
9821 auto LambdaInfo =
9822 std::make_pair(Lambda->getLambdaContextDecl()->getCanonicalDecl(),
9823 Lambda->getLambdaIndexInContext());
9824
9825 // Handle the import and then include case for lambdas.
9826 if (auto Iter = LambdaDeclarationsForMerging.find(LambdaInfo);
9827 Iter != LambdaDeclarationsForMerging.end() &&
9828 Iter->second->isFromASTFile() && Lambda->getFirstDecl() == Lambda) {
9830 cast<CXXRecordDecl>(Iter->second)->getMostRecentDecl();
9831 Lambda->setPreviousDecl(Previous);
9832 return;
9833 }
9834
9835 // Keep track of this lambda so it can be merged with another lambda that
9836 // is loaded later.
9837 LambdaDeclarationsForMerging.insert({LambdaInfo, Lambda});
9838}
9839
9841 // It would be complicated to avoid reading the methods anyway. So don't.
9842 ReadMethodPool(Sel);
9843}
9844
9846 assert(ID && "Non-zero identifier ID required");
9847 unsigned Index = translateIdentifierIDToIndex(ID).second;
9848 assert(Index < IdentifiersLoaded.size() && "identifier ID out of range");
9849 IdentifiersLoaded[Index] = II;
9850 if (DeserializationListener)
9851 DeserializationListener->IdentifierRead(ID, II);
9852}
9853
9854/// Set the globally-visible declarations associated with the given
9855/// identifier.
9856///
9857/// If the AST reader is currently in a state where the given declaration IDs
9858/// cannot safely be resolved, they are queued until it is safe to resolve
9859/// them.
9860///
9861/// \param II an IdentifierInfo that refers to one or more globally-visible
9862/// declarations.
9863///
9864/// \param DeclIDs the set of declaration IDs with the name @p II that are
9865/// visible at global scope.
9866///
9867/// \param Decls if non-null, this vector will be populated with the set of
9868/// deserialized declarations. These declarations will not be pushed into
9869/// scope.
9872 SmallVectorImpl<Decl *> *Decls) {
9873 if (NumCurrentElementsDeserializing && !Decls) {
9874 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
9875 return;
9876 }
9877
9878 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
9879 if (!SemaObj) {
9880 // Queue this declaration so that it will be added to the
9881 // translation unit scope and identifier's declaration chain
9882 // once a Sema object is known.
9883 PreloadedDeclIDs.push_back(DeclIDs[I]);
9884 continue;
9885 }
9886
9887 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
9888
9889 // If we're simply supposed to record the declarations, do so now.
9890 if (Decls) {
9891 Decls->push_back(D);
9892 continue;
9893 }
9894
9895 // Introduce this declaration into the translation-unit scope
9896 // and add it to the declaration chain for this identifier, so
9897 // that (unqualified) name lookup will find it.
9898 pushExternalDeclIntoScope(D, II);
9899 }
9900}
9901
9902std::pair<ModuleFile *, unsigned>
9903ASTReader::translateIdentifierIDToIndex(IdentifierID ID) const {
9904 if (ID == 0)
9905 return {nullptr, 0};
9906
9907 unsigned ModuleFileIndex = ID >> 32;
9908 unsigned LocalID = ID & llvm::maskTrailingOnes<IdentifierID>(32);
9909
9910 assert(ModuleFileIndex && "not translating loaded IdentifierID?");
9911 assert(getModuleManager().size() > ModuleFileIndex - 1);
9912
9913 ModuleFile &MF = getModuleManager()[ModuleFileIndex - 1];
9914 assert(LocalID < MF.LocalNumIdentifiers);
9915 return {&MF, MF.BaseIdentifierID + LocalID};
9916}
9917
9919 if (ID == 0)
9920 return nullptr;
9921
9922 if (IdentifiersLoaded.empty()) {
9923 Error("no identifier table in AST file");
9924 return nullptr;
9925 }
9926
9927 auto [M, Index] = translateIdentifierIDToIndex(ID);
9928 if (!IdentifiersLoaded[Index]) {
9929 assert(M != nullptr && "Untranslated Identifier ID?");
9930 assert(Index >= M->BaseIdentifierID);
9931 unsigned LocalIndex = Index - M->BaseIdentifierID;
9932 const unsigned char *Data =
9933 M->IdentifierTableData + M->IdentifierOffsets[LocalIndex];
9934
9935 ASTIdentifierLookupTrait Trait(*this, *M);
9936 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
9937 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
9938 auto &II = PP.getIdentifierTable().get(Key);
9939 IdentifiersLoaded[Index] = &II;
9940 bool IsModule = getPreprocessor().getCurrentModule() != nullptr;
9941 markIdentifierFromAST(*this, II, IsModule);
9942 if (DeserializationListener)
9943 DeserializationListener->IdentifierRead(ID, &II);
9944 }
9945
9946 return IdentifiersLoaded[Index];
9947}
9948
9952
9954 if (LocalID < NUM_PREDEF_IDENT_IDS)
9955 return LocalID;
9956
9957 if (!M.ModuleOffsetMap.empty())
9958 ReadModuleOffsetMap(M);
9959
9960 unsigned ModuleFileIndex = LocalID >> 32;
9961 LocalID &= llvm::maskTrailingOnes<IdentifierID>(32);
9962 ModuleFile *MF =
9963 ModuleFileIndex ? M.TransitiveImports[ModuleFileIndex - 1] : &M;
9964 assert(MF && "malformed identifier ID encoding?");
9965
9966 if (!ModuleFileIndex)
9967 LocalID -= NUM_PREDEF_IDENT_IDS;
9968
9969 return ((IdentifierID)(MF->Index + 1) << 32) | LocalID;
9970}
9971
9972std::pair<ModuleFile *, unsigned>
9973ASTReader::translateMacroIDToIndex(MacroID ID) const {
9974 if (ID == 0)
9975 return {nullptr, 0};
9976
9977 unsigned ModuleFileIndex = ID >> 32;
9978 assert(ModuleFileIndex && "not translating loaded MacroID?");
9979 assert(getModuleManager().size() > ModuleFileIndex - 1);
9980 ModuleFile &MF = getModuleManager()[ModuleFileIndex - 1];
9981
9982 unsigned LocalID = ID & llvm::maskTrailingOnes<MacroID>(32);
9983 assert(LocalID < MF.LocalNumMacros);
9984 return {&MF, MF.BaseMacroID + LocalID};
9985}
9986
9988 if (ID == 0)
9989 return nullptr;
9990
9991 if (MacrosLoaded.empty()) {
9992 Error("no macro table in AST file");
9993 return nullptr;
9994 }
9995
9996 auto [M, Index] = translateMacroIDToIndex(ID);
9997 if (!MacrosLoaded[Index]) {
9998 assert(M != nullptr && "Untranslated Macro ID?");
9999 assert(Index >= M->BaseMacroID);
10000 unsigned LocalIndex = Index - M->BaseMacroID;
10001 uint64_t DataOffset = M->MacroOffsetsBase + M->MacroOffsets[LocalIndex];
10002 MacrosLoaded[Index] = ReadMacroRecord(*M, DataOffset);
10003
10004 if (DeserializationListener)
10005 DeserializationListener->MacroRead(ID, MacrosLoaded[Index]);
10006 }
10007
10008 return MacrosLoaded[Index];
10009}
10010
10012 if (LocalID < NUM_PREDEF_MACRO_IDS)
10013 return LocalID;
10014
10015 if (!M.ModuleOffsetMap.empty())
10016 ReadModuleOffsetMap(M);
10017
10018 unsigned ModuleFileIndex = LocalID >> 32;
10019 LocalID &= llvm::maskTrailingOnes<MacroID>(32);
10020 ModuleFile *MF =
10021 ModuleFileIndex ? M.TransitiveImports[ModuleFileIndex - 1] : &M;
10022 assert(MF && "malformed identifier ID encoding?");
10023
10024 if (!ModuleFileIndex) {
10025 assert(LocalID >= NUM_PREDEF_MACRO_IDS);
10026 LocalID -= NUM_PREDEF_MACRO_IDS;
10027 }
10028
10029 return (static_cast<MacroID>(MF->Index + 1) << 32) | LocalID;
10030}
10031
10033ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) const {
10034 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
10035 return LocalID;
10036
10037 if (!M.ModuleOffsetMap.empty())
10038 ReadModuleOffsetMap(M);
10039
10042 assert(I != M.SubmoduleRemap.end()
10043 && "Invalid index into submodule index remap");
10044
10045 return LocalID + I->second;
10046}
10047
10049 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
10050 assert(GlobalID == 0 && "Unhandled global submodule ID");
10051 return nullptr;
10052 }
10053
10054 if (GlobalID > SubmodulesLoaded.size()) {
10055 Error("submodule ID out of range in AST file");
10056 return nullptr;
10057 }
10058
10059 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
10060}
10061
10063 return getSubmodule(ID);
10064}
10065
10067 if (ID & 1) {
10068 // It's a module, look it up by submodule ID.
10069 auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(M, ID >> 1));
10070 return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
10071 } else {
10072 // It's a prefix (preamble, PCH, ...). Look it up by index.
10073 int IndexFromEnd = static_cast<int>(ID >> 1);
10074 assert(IndexFromEnd && "got reference to unknown module file");
10075 return getModuleManager().pch_modules().end()[-IndexFromEnd];
10076 }
10077}
10078
10080 if (!M)
10081 return 1;
10082
10083 // For a file representing a module, use the submodule ID of the top-level
10084 // module as the file ID. For any other kind of file, the number of such
10085 // files loaded beforehand will be the same on reload.
10086 // FIXME: Is this true even if we have an explicit module file and a PCH?
10087 if (M->isModule())
10088 return ((M->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
10089
10090 auto PCHModules = getModuleManager().pch_modules();
10091 auto I = llvm::find(PCHModules, M);
10092 assert(I != PCHModules.end() && "emitting reference to unknown file");
10093 return std::distance(I, PCHModules.end()) << 1;
10094}
10095
10096std::optional<ASTSourceDescriptor> ASTReader::getSourceDescriptor(unsigned ID) {
10097 if (Module *M = getSubmodule(ID))
10098 return ASTSourceDescriptor(*M);
10099
10100 // If there is only a single PCH, return it instead.
10101 // Chained PCH are not supported.
10102 const auto &PCHChain = ModuleMgr.pch_modules();
10103 if (std::distance(std::begin(PCHChain), std::end(PCHChain))) {
10104 ModuleFile &MF = ModuleMgr.getPrimaryModule();
10105 StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName);
10106 StringRef FileName = llvm::sys::path::filename(MF.FileName);
10107 return ASTSourceDescriptor(ModuleName,
10108 llvm::sys::path::parent_path(MF.FileName),
10109 FileName, MF.Signature);
10110 }
10111 return std::nullopt;
10112}
10113
10115 auto I = DefinitionSource.find(FD);
10116 if (I == DefinitionSource.end())
10117 return EK_ReplyHazy;
10118 return I->second ? EK_Never : EK_Always;
10119}
10120
10122 return ThisDeclarationWasADefinitionSet.contains(FD);
10123}
10124
10126 return DecodeSelector(getGlobalSelectorID(M, LocalID));
10127}
10128
10130 if (ID == 0)
10131 return Selector();
10132
10133 if (ID > SelectorsLoaded.size()) {
10134 Error("selector ID out of range in AST file");
10135 return Selector();
10136 }
10137
10138 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
10139 // Load this selector from the selector table.
10140 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
10141 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
10142 ModuleFile &M = *I->second;
10143 ASTSelectorLookupTrait Trait(*this, M);
10144 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
10145 SelectorsLoaded[ID - 1] =
10146 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
10147 if (DeserializationListener)
10148 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
10149 }
10150
10151 return SelectorsLoaded[ID - 1];
10152}
10153
10157
10159 // ID 0 (the null selector) is considered an external selector.
10160 return getTotalNumSelectors() + 1;
10161}
10162
10164ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
10165 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
10166 return LocalID;
10167
10168 if (!M.ModuleOffsetMap.empty())
10169 ReadModuleOffsetMap(M);
10170
10173 assert(I != M.SelectorRemap.end()
10174 && "Invalid index into selector index remap");
10175
10176 return LocalID + I->second;
10177}
10178
10204
10206 DeclarationNameInfo NameInfo;
10207 NameInfo.setName(readDeclarationName());
10208 NameInfo.setLoc(readSourceLocation());
10209 NameInfo.setInfo(readDeclarationNameLoc(NameInfo.getName()));
10210 return NameInfo;
10211}
10212
10216
10218 auto Kind = readInt();
10219 auto ResultType = readQualType();
10220 auto Value = readAPInt();
10221 SpirvOperand Op(SpirvOperand::SpirvOperandKind(Kind), ResultType, Value);
10222 assert(Op.isValid());
10223 return Op;
10224}
10225
10228 unsigned NumTPLists = readInt();
10229 Info.NumTemplParamLists = NumTPLists;
10230 if (NumTPLists) {
10231 Info.TemplParamLists =
10232 new (getContext()) TemplateParameterList *[NumTPLists];
10233 for (unsigned i = 0; i != NumTPLists; ++i)
10235 }
10236}
10237
10240 SourceLocation TemplateLoc = readSourceLocation();
10241 SourceLocation LAngleLoc = readSourceLocation();
10242 SourceLocation RAngleLoc = readSourceLocation();
10243
10244 unsigned NumParams = readInt();
10246 Params.reserve(NumParams);
10247 while (NumParams--)
10248 Params.push_back(readDeclAs<NamedDecl>());
10249
10250 bool HasRequiresClause = readBool();
10251 Expr *RequiresClause = HasRequiresClause ? readExpr() : nullptr;
10252
10254 getContext(), TemplateLoc, LAngleLoc, Params, RAngleLoc, RequiresClause);
10255 return TemplateParams;
10256}
10257
10260 bool Canonicalize) {
10261 unsigned NumTemplateArgs = readInt();
10262 TemplArgs.reserve(NumTemplateArgs);
10263 while (NumTemplateArgs--)
10264 TemplArgs.push_back(readTemplateArgument(Canonicalize));
10265}
10266
10267/// Read a UnresolvedSet structure.
10269 unsigned NumDecls = readInt();
10270 Set.reserve(getContext(), NumDecls);
10271 while (NumDecls--) {
10272 GlobalDeclID ID = readDeclID();
10274 Set.addLazyDecl(getContext(), ID, AS);
10275 }
10276}
10277
10280 bool isVirtual = readBool();
10281 bool isBaseOfClass = readBool();
10282 AccessSpecifier AS = static_cast<AccessSpecifier>(readInt());
10283 bool inheritConstructors = readBool();
10285 SourceRange Range = readSourceRange();
10286 SourceLocation EllipsisLoc = readSourceLocation();
10287 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
10288 EllipsisLoc);
10289 Result.setInheritConstructors(inheritConstructors);
10290 return Result;
10291}
10292
10295 ASTContext &Context = getContext();
10296 unsigned NumInitializers = readInt();
10297 assert(NumInitializers && "wrote ctor initializers but have no inits");
10298 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
10299 for (unsigned i = 0; i != NumInitializers; ++i) {
10300 TypeSourceInfo *TInfo = nullptr;
10301 bool IsBaseVirtual = false;
10302 FieldDecl *Member = nullptr;
10303 IndirectFieldDecl *IndirectMember = nullptr;
10304
10306 switch (Type) {
10308 TInfo = readTypeSourceInfo();
10309 IsBaseVirtual = readBool();
10310 break;
10311
10313 TInfo = readTypeSourceInfo();
10314 break;
10315
10318 break;
10319
10321 IndirectMember = readDeclAs<IndirectFieldDecl>();
10322 break;
10323 }
10324
10325 SourceLocation MemberOrEllipsisLoc = readSourceLocation();
10326 Expr *Init = readExpr();
10327 SourceLocation LParenLoc = readSourceLocation();
10328 SourceLocation RParenLoc = readSourceLocation();
10329
10330 CXXCtorInitializer *BOMInit;
10332 BOMInit = new (Context)
10333 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
10334 RParenLoc, MemberOrEllipsisLoc);
10336 BOMInit = new (Context)
10337 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
10338 else if (Member)
10339 BOMInit = new (Context)
10340 CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc, LParenLoc,
10341 Init, RParenLoc);
10342 else
10343 BOMInit = new (Context)
10344 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
10345 LParenLoc, Init, RParenLoc);
10346
10347 if (/*IsWritten*/readBool()) {
10348 unsigned SourceOrder = readInt();
10349 BOMInit->setSourceOrder(SourceOrder);
10350 }
10351
10352 CtorInitializers[i] = BOMInit;
10353 }
10354
10355 return CtorInitializers;
10356}
10357
10360 ASTContext &Context = getContext();
10361 unsigned N = readInt();
10363 for (unsigned I = 0; I != N; ++I) {
10364 auto Kind = readNestedNameSpecifierKind();
10365 switch (Kind) {
10367 auto *NS = readDeclAs<NamespaceBaseDecl>();
10368 SourceRange Range = readSourceRange();
10369 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
10370 break;
10371 }
10372
10375 if (!T)
10376 return NestedNameSpecifierLoc();
10377 SourceLocation ColonColonLoc = readSourceLocation();
10378 Builder.Make(Context, T->getTypeLoc(), ColonColonLoc);
10379 break;
10380 }
10381
10383 SourceLocation ColonColonLoc = readSourceLocation();
10384 Builder.MakeGlobal(Context, ColonColonLoc);
10385 break;
10386 }
10387
10390 SourceRange Range = readSourceRange();
10391 Builder.MakeMicrosoftSuper(Context, RD, Range.getBegin(), Range.getEnd());
10392 break;
10393 }
10394
10396 llvm_unreachable("unexpected null nested name specifier");
10397 }
10398 }
10399
10400 return Builder.getWithLocInContext(Context);
10401}
10402
10404 unsigned &Idx) {
10407 return SourceRange(beg, end);
10408}
10409
10411 const StringRef Blob) {
10412 unsigned Count = Record[0];
10413 const char *Byte = Blob.data();
10414 llvm::BitVector Ret = llvm::BitVector(Count, false);
10415 for (unsigned I = 0; I < Count; ++Byte)
10416 for (unsigned Bit = 0; Bit < 8 && I < Count; ++Bit, ++I)
10417 if (*Byte & (1 << Bit))
10418 Ret[I] = true;
10419 return Ret;
10420}
10421
10422/// Read a floating-point value
10423llvm::APFloat ASTRecordReader::readAPFloat(const llvm::fltSemantics &Sem) {
10424 return llvm::APFloat(Sem, readAPInt());
10425}
10426
10427// Read a string
10428std::string ASTReader::ReadString(const RecordDataImpl &Record, unsigned &Idx) {
10429 unsigned Len = Record[Idx++];
10430 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
10431 Idx += Len;
10432 return Result;
10433}
10434
10435StringRef ASTReader::ReadStringBlob(const RecordDataImpl &Record, unsigned &Idx,
10436 StringRef &Blob) {
10437 unsigned Len = Record[Idx++];
10438 StringRef Result = Blob.substr(0, Len);
10439 Blob = Blob.substr(Len);
10440 return Result;
10441}
10442
10444 unsigned &Idx) {
10445 return ReadPath(F.BaseDirectory, Record, Idx);
10446}
10447
10448std::string ASTReader::ReadPath(StringRef BaseDirectory,
10449 const RecordData &Record, unsigned &Idx) {
10450 std::string Filename = ReadString(Record, Idx);
10451 return ResolveImportedPathAndAllocate(PathBuf, Filename, BaseDirectory);
10452}
10453
10454std::string ASTReader::ReadPathBlob(StringRef BaseDirectory,
10455 const RecordData &Record, unsigned &Idx,
10456 StringRef &Blob) {
10457 StringRef Filename = ReadStringBlob(Record, Idx, Blob);
10458 return ResolveImportedPathAndAllocate(PathBuf, Filename, BaseDirectory);
10459}
10460
10462 unsigned &Idx) {
10463 unsigned Major = Record[Idx++];
10464 unsigned Minor = Record[Idx++];
10465 unsigned Subminor = Record[Idx++];
10466 if (Minor == 0)
10467 return VersionTuple(Major);
10468 if (Subminor == 0)
10469 return VersionTuple(Major, Minor - 1);
10470 return VersionTuple(Major, Minor - 1, Subminor - 1);
10471}
10472
10479
10480DiagnosticBuilder ASTReader::Diag(unsigned DiagID) const {
10481 return Diag(CurrentImportLoc, DiagID);
10482}
10483
10485 return Diags.Report(Loc, DiagID);
10486}
10487
10489 llvm::function_ref<void()> Fn) {
10490 // When Sema is available, avoid duplicate errors.
10491 if (SemaObj) {
10492 SemaObj->runWithSufficientStackSpace(Loc, Fn);
10493 return;
10494 }
10495
10496 StackHandler.runWithSufficientStackSpace(Loc, Fn);
10497}
10498
10499/// Retrieve the identifier table associated with the
10500/// preprocessor.
10502 return PP.getIdentifierTable();
10503}
10504
10505/// Record that the given ID maps to the given switch-case
10506/// statement.
10508 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
10509 "Already have a SwitchCase with this ID");
10510 (*CurrSwitchCaseStmts)[ID] = SC;
10511}
10512
10513/// Retrieve the switch-case statement with the given ID.
10515 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
10516 return (*CurrSwitchCaseStmts)[ID];
10517}
10518
10520 CurrSwitchCaseStmts->clear();
10521}
10522
10524 ASTContext &Context = getContext();
10525 std::vector<RawComment *> Comments;
10526 for (SmallVectorImpl<std::pair<BitstreamCursor,
10528 I = CommentsCursors.begin(),
10529 E = CommentsCursors.end();
10530 I != E; ++I) {
10531 Comments.clear();
10532 BitstreamCursor &Cursor = I->first;
10533 serialization::ModuleFile &F = *I->second;
10534 SavedStreamPosition SavedPosition(Cursor);
10535
10537 while (true) {
10539 Cursor.advanceSkippingSubblocks(
10540 BitstreamCursor::AF_DontPopBlockAtEnd);
10541 if (!MaybeEntry) {
10542 Error(MaybeEntry.takeError());
10543 return;
10544 }
10545 llvm::BitstreamEntry Entry = MaybeEntry.get();
10546
10547 switch (Entry.Kind) {
10548 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
10549 case llvm::BitstreamEntry::Error:
10550 Error("malformed block record in AST file");
10551 return;
10552 case llvm::BitstreamEntry::EndBlock:
10553 goto NextCursor;
10554 case llvm::BitstreamEntry::Record:
10555 // The interesting case.
10556 break;
10557 }
10558
10559 // Read a record.
10560 Record.clear();
10561 Expected<unsigned> MaybeComment = Cursor.readRecord(Entry.ID, Record);
10562 if (!MaybeComment) {
10563 Error(MaybeComment.takeError());
10564 return;
10565 }
10566 switch ((CommentRecordTypes)MaybeComment.get()) {
10567 case COMMENTS_RAW_COMMENT: {
10568 unsigned Idx = 0;
10569 SourceRange SR = ReadSourceRange(F, Record, Idx);
10572 bool IsTrailingComment = Record[Idx++];
10573 bool IsAlmostTrailingComment = Record[Idx++];
10574 Comments.push_back(new (Context) RawComment(
10575 SR, Kind, IsTrailingComment, IsAlmostTrailingComment));
10576 break;
10577 }
10578 }
10579 }
10580 NextCursor:
10581 for (RawComment *C : Comments) {
10582 SourceLocation CommentLoc = C->getBeginLoc();
10583 if (CommentLoc.isValid()) {
10584 FileIDAndOffset Loc = SourceMgr.getDecomposedLoc(CommentLoc);
10585 if (Loc.first.isValid())
10586 Context.Comments.OrderedComments[Loc.first].emplace(Loc.second, C);
10587 }
10588 }
10589 }
10590}
10591
10593 serialization::ModuleFile &MF, bool IncludeSystem,
10594 llvm::function_ref<void(const serialization::InputFileInfo &IFI,
10595 bool IsSystem)>
10596 Visitor) {
10597 unsigned NumUserInputs = MF.NumUserInputFiles;
10598 unsigned NumInputs = MF.InputFilesLoaded.size();
10599 assert(NumUserInputs <= NumInputs);
10600 unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
10601 for (unsigned I = 0; I < N; ++I) {
10602 bool IsSystem = I >= NumUserInputs;
10603 InputFileInfo IFI = getInputFileInfo(MF, I+1);
10604 Visitor(IFI, IsSystem);
10605 }
10606}
10607
10609 bool IncludeSystem, bool Complain,
10610 llvm::function_ref<void(const serialization::InputFile &IF,
10611 bool isSystem)> Visitor) {
10612 unsigned NumUserInputs = MF.NumUserInputFiles;
10613 unsigned NumInputs = MF.InputFilesLoaded.size();
10614 assert(NumUserInputs <= NumInputs);
10615 unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
10616 for (unsigned I = 0; I < N; ++I) {
10617 bool IsSystem = I >= NumUserInputs;
10618 InputFile IF = getInputFile(MF, I+1, Complain);
10619 Visitor(IF, IsSystem);
10620 }
10621}
10622
10625 llvm::function_ref<void(FileEntryRef FE)> Visitor) {
10626 unsigned NumInputs = MF.InputFilesLoaded.size();
10627 for (unsigned I = 0; I < NumInputs; ++I) {
10628 InputFileInfo IFI = getInputFileInfo(MF, I + 1);
10629 if (IFI.TopLevel && IFI.ModuleMap)
10630 if (auto FE = getInputFile(MF, I + 1).getFile())
10631 Visitor(*FE);
10632 }
10633}
10634
10635void ASTReader::finishPendingActions() {
10636 while (!PendingIdentifierInfos.empty() ||
10637 !PendingDeducedFunctionTypes.empty() ||
10638 !PendingDeducedVarTypes.empty() || !PendingDeclChains.empty() ||
10639 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
10640 !PendingUpdateRecords.empty() ||
10641 !PendingObjCExtensionIvarRedeclarations.empty()) {
10642 // If any identifiers with corresponding top-level declarations have
10643 // been loaded, load those declarations now.
10644 using TopLevelDeclsMap =
10645 llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2>>;
10646 TopLevelDeclsMap TopLevelDecls;
10647
10648 while (!PendingIdentifierInfos.empty()) {
10649 IdentifierInfo *II = PendingIdentifierInfos.back().first;
10651 std::move(PendingIdentifierInfos.back().second);
10652 PendingIdentifierInfos.pop_back();
10653
10654 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
10655 }
10656
10657 // Load each function type that we deferred loading because it was a
10658 // deduced type that might refer to a local type declared within itself.
10659 for (unsigned I = 0; I != PendingDeducedFunctionTypes.size(); ++I) {
10660 auto *FD = PendingDeducedFunctionTypes[I].first;
10661 FD->setType(GetType(PendingDeducedFunctionTypes[I].second));
10662
10663 if (auto *DT = FD->getReturnType()->getContainedDeducedType()) {
10664 // If we gave a function a deduced return type, remember that we need to
10665 // propagate that along the redeclaration chain.
10666 if (DT->isDeduced()) {
10667 PendingDeducedTypeUpdates.insert(
10668 {FD->getCanonicalDecl(), FD->getReturnType()});
10669 continue;
10670 }
10671
10672 // The function has undeduced DeduceType return type. We hope we can
10673 // find the deduced type by iterating the redecls in other modules
10674 // later.
10675 PendingUndeducedFunctionDecls.push_back(FD);
10676 continue;
10677 }
10678 }
10679 PendingDeducedFunctionTypes.clear();
10680
10681 // Load each variable type that we deferred loading because it was a
10682 // deduced type that might refer to a local type declared within itself.
10683 for (unsigned I = 0; I != PendingDeducedVarTypes.size(); ++I) {
10684 auto *VD = PendingDeducedVarTypes[I].first;
10685 VD->setType(GetType(PendingDeducedVarTypes[I].second));
10686 }
10687 PendingDeducedVarTypes.clear();
10688
10689 // Load pending declaration chains.
10690 for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
10691 loadPendingDeclChain(PendingDeclChains[I].first,
10692 PendingDeclChains[I].second);
10693 PendingDeclChains.clear();
10694
10695 // Make the most recent of the top-level declarations visible.
10696 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
10697 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
10698 IdentifierInfo *II = TLD->first;
10699 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
10700 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
10701 }
10702 }
10703
10704 // Load any pending macro definitions.
10705 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
10706 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
10707 SmallVector<PendingMacroInfo, 2> GlobalIDs;
10708 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
10709 // Initialize the macro history from chained-PCHs ahead of module imports.
10710 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
10711 ++IDIdx) {
10712 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
10713 if (!Info.M->isModule())
10714 resolvePendingMacro(II, Info);
10715 }
10716 // Handle module imports.
10717 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
10718 ++IDIdx) {
10719 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
10720 if (Info.M->isModule())
10721 resolvePendingMacro(II, Info);
10722 }
10723 }
10724 PendingMacroIDs.clear();
10725
10726 // Wire up the DeclContexts for Decls that we delayed setting until
10727 // recursive loading is completed.
10728 while (!PendingDeclContextInfos.empty()) {
10729 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
10730 PendingDeclContextInfos.pop_front();
10731 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
10732 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
10733 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
10734 }
10735
10736 // Perform any pending declaration updates.
10737 while (!PendingUpdateRecords.empty()) {
10738 auto Update = PendingUpdateRecords.pop_back_val();
10739 ReadingKindTracker ReadingKind(Read_Decl, *this);
10740 loadDeclUpdateRecords(Update);
10741 }
10742
10743 while (!PendingObjCExtensionIvarRedeclarations.empty()) {
10744 auto ExtensionsPair = PendingObjCExtensionIvarRedeclarations.back().first;
10745 auto DuplicateIvars =
10746 PendingObjCExtensionIvarRedeclarations.back().second;
10748 StructuralEquivalenceContext Ctx(
10749 ContextObj->getLangOpts(), ExtensionsPair.first->getASTContext(),
10750 ExtensionsPair.second->getASTContext(), NonEquivalentDecls,
10751 StructuralEquivalenceKind::Default, /*StrictTypeSpelling =*/false,
10752 /*Complain =*/false,
10753 /*ErrorOnTagTypeMismatch =*/true);
10754 if (Ctx.IsEquivalent(ExtensionsPair.first, ExtensionsPair.second)) {
10755 // Merge redeclared ivars with their predecessors.
10756 for (auto IvarPair : DuplicateIvars) {
10757 ObjCIvarDecl *Ivar = IvarPair.first, *PrevIvar = IvarPair.second;
10758 // Change semantic DeclContext but keep the lexical one.
10759 Ivar->setDeclContextsImpl(PrevIvar->getDeclContext(),
10760 Ivar->getLexicalDeclContext(),
10761 getContext());
10762 getContext().setPrimaryMergedDecl(Ivar, PrevIvar->getCanonicalDecl());
10763 }
10764 // Invalidate duplicate extension and the cached ivar list.
10765 ExtensionsPair.first->setInvalidDecl();
10766 ExtensionsPair.second->getClassInterface()
10767 ->getDefinition()
10768 ->setIvarList(nullptr);
10769 } else {
10770 for (auto IvarPair : DuplicateIvars) {
10771 Diag(IvarPair.first->getLocation(),
10772 diag::err_duplicate_ivar_declaration)
10773 << IvarPair.first->getIdentifier();
10774 Diag(IvarPair.second->getLocation(), diag::note_previous_definition);
10775 }
10776 }
10777 PendingObjCExtensionIvarRedeclarations.pop_back();
10778 }
10779 }
10780
10781 // At this point, all update records for loaded decls are in place, so any
10782 // fake class definitions should have become real.
10783 assert(PendingFakeDefinitionData.empty() &&
10784 "faked up a class definition but never saw the real one");
10785
10786 // If we deserialized any C++ or Objective-C class definitions, any
10787 // Objective-C protocol definitions, or any redeclarable templates, make sure
10788 // that all redeclarations point to the definitions. Note that this can only
10789 // happen now, after the redeclaration chains have been fully wired.
10790 for (Decl *D : PendingDefinitions) {
10791 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
10792 if (auto *RD = dyn_cast<CXXRecordDecl>(TD)) {
10793 for (auto *R = getMostRecentExistingDecl(RD); R;
10794 R = R->getPreviousDecl()) {
10795 assert((R == D) ==
10796 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
10797 "declaration thinks it's the definition but it isn't");
10798 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
10799 }
10800 }
10801
10802 continue;
10803 }
10804
10805 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
10806 // Make sure that the ObjCInterfaceType points at the definition.
10807 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
10808 ->Decl = ID;
10809
10810 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
10811 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
10812
10813 continue;
10814 }
10815
10816 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
10817 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
10818 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
10819
10820 continue;
10821 }
10822
10823 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
10824 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
10825 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
10826 }
10827 PendingDefinitions.clear();
10828
10829 for (auto [D, Previous] : PendingWarningForDuplicatedDefsInModuleUnits) {
10830 auto hasDefinitionImpl = [this](Decl *D, auto hasDefinitionImpl) {
10831 if (auto *VD = dyn_cast<VarDecl>(D))
10832 return VD->isThisDeclarationADefinition() ||
10833 VD->isThisDeclarationADemotedDefinition();
10834
10835 if (auto *TD = dyn_cast<TagDecl>(D))
10836 return TD->isThisDeclarationADefinition() ||
10837 TD->isThisDeclarationADemotedDefinition();
10838
10839 if (auto *FD = dyn_cast<FunctionDecl>(D))
10840 return FD->isThisDeclarationADefinition() || PendingBodies.count(FD);
10841
10842 if (auto *RTD = dyn_cast<RedeclarableTemplateDecl>(D))
10843 return hasDefinitionImpl(RTD->getTemplatedDecl(), hasDefinitionImpl);
10844
10845 // Conservatively return false here.
10846 return false;
10847 };
10848
10849 auto hasDefinition = [&hasDefinitionImpl](Decl *D) {
10850 return hasDefinitionImpl(D, hasDefinitionImpl);
10851 };
10852
10853 // It is not good to prevent multiple declarations since the forward
10854 // declaration is common. Let's try to avoid duplicated definitions
10855 // only.
10857 continue;
10858
10859 Module *PM = Previous->getOwningModule();
10860 Module *DM = D->getOwningModule();
10861 Diag(D->getLocation(), diag::warn_decls_in_multiple_modules)
10863 << (DM ? DM->getTopLevelModuleName() : "global module");
10864 Diag(Previous->getLocation(), diag::note_also_found);
10865 }
10866 PendingWarningForDuplicatedDefsInModuleUnits.clear();
10867
10868 // Load the bodies of any functions or methods we've encountered. We do
10869 // this now (delayed) so that we can be sure that the declaration chains
10870 // have been fully wired up (hasBody relies on this).
10871 // FIXME: We shouldn't require complete redeclaration chains here.
10872 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
10873 PBEnd = PendingBodies.end();
10874 PB != PBEnd; ++PB) {
10875 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
10876 // FIXME: Check for =delete/=default?
10877 const FunctionDecl *Defn = nullptr;
10878 if (!getContext().getLangOpts().Modules || !FD->hasBody(Defn)) {
10879 FD->setLazyBody(PB->second);
10880 } else {
10881 auto *NonConstDefn = const_cast<FunctionDecl*>(Defn);
10882 mergeDefinitionVisibility(NonConstDefn, FD);
10883
10884 if (!FD->isLateTemplateParsed() &&
10885 !NonConstDefn->isLateTemplateParsed() &&
10886 // We only perform ODR checks for decls not in the explicit
10887 // global module fragment.
10888 !shouldSkipCheckingODR(FD) &&
10889 !shouldSkipCheckingODR(NonConstDefn) &&
10890 FD->getODRHash() != NonConstDefn->getODRHash()) {
10891 if (!isa<CXXMethodDecl>(FD)) {
10892 PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
10893 } else if (FD->getLexicalParent()->isFileContext() &&
10894 NonConstDefn->getLexicalParent()->isFileContext()) {
10895 // Only diagnose out-of-line method definitions. If they are
10896 // in class definitions, then an error will be generated when
10897 // processing the class bodies.
10898 PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
10899 }
10900 }
10901 }
10902 continue;
10903 }
10904
10905 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
10906 if (!getContext().getLangOpts().Modules || !MD->hasBody())
10907 MD->setLazyBody(PB->second);
10908 }
10909 PendingBodies.clear();
10910
10911 // Inform any classes that had members added that they now have more members.
10912 for (auto [RD, MD] : PendingAddedClassMembers) {
10913 RD->addedMember(MD);
10914 }
10915 PendingAddedClassMembers.clear();
10916
10917 // Do some cleanup.
10918 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
10920 PendingMergedDefinitionsToDeduplicate.clear();
10921
10922 // For each decl chain that we wanted to complete while deserializing, mark
10923 // it as "still needs to be completed".
10924 for (Decl *D : PendingIncompleteDeclChains)
10925 markIncompleteDeclChain(D);
10926 PendingIncompleteDeclChains.clear();
10927
10928 assert(PendingIdentifierInfos.empty() &&
10929 "Should be empty at the end of finishPendingActions");
10930 assert(PendingDeducedFunctionTypes.empty() &&
10931 "Should be empty at the end of finishPendingActions");
10932 assert(PendingDeducedVarTypes.empty() &&
10933 "Should be empty at the end of finishPendingActions");
10934 assert(PendingDeclChains.empty() &&
10935 "Should be empty at the end of finishPendingActions");
10936 assert(PendingMacroIDs.empty() &&
10937 "Should be empty at the end of finishPendingActions");
10938 assert(PendingDeclContextInfos.empty() &&
10939 "Should be empty at the end of finishPendingActions");
10940 assert(PendingUpdateRecords.empty() &&
10941 "Should be empty at the end of finishPendingActions");
10942 assert(PendingObjCExtensionIvarRedeclarations.empty() &&
10943 "Should be empty at the end of finishPendingActions");
10944 assert(PendingFakeDefinitionData.empty() &&
10945 "Should be empty at the end of finishPendingActions");
10946 assert(PendingDefinitions.empty() &&
10947 "Should be empty at the end of finishPendingActions");
10948 assert(PendingWarningForDuplicatedDefsInModuleUnits.empty() &&
10949 "Should be empty at the end of finishPendingActions");
10950 assert(PendingBodies.empty() &&
10951 "Should be empty at the end of finishPendingActions");
10952 assert(PendingAddedClassMembers.empty() &&
10953 "Should be empty at the end of finishPendingActions");
10954 assert(PendingMergedDefinitionsToDeduplicate.empty() &&
10955 "Should be empty at the end of finishPendingActions");
10956 assert(PendingIncompleteDeclChains.empty() &&
10957 "Should be empty at the end of finishPendingActions");
10958}
10959
10960void ASTReader::diagnoseOdrViolations() {
10961 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty() &&
10962 PendingRecordOdrMergeFailures.empty() &&
10963 PendingFunctionOdrMergeFailures.empty() &&
10964 PendingEnumOdrMergeFailures.empty() &&
10965 PendingObjCInterfaceOdrMergeFailures.empty() &&
10966 PendingObjCProtocolOdrMergeFailures.empty())
10967 return;
10968
10969 // Trigger the import of the full definition of each class that had any
10970 // odr-merging problems, so we can produce better diagnostics for them.
10971 // These updates may in turn find and diagnose some ODR failures, so take
10972 // ownership of the set first.
10973 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
10974 PendingOdrMergeFailures.clear();
10975 for (auto &Merge : OdrMergeFailures) {
10976 Merge.first->buildLookup();
10977 Merge.first->decls_begin();
10978 Merge.first->bases_begin();
10979 Merge.first->vbases_begin();
10980 for (auto &RecordPair : Merge.second) {
10981 auto *RD = RecordPair.first;
10982 RD->decls_begin();
10983 RD->bases_begin();
10984 RD->vbases_begin();
10985 }
10986 }
10987
10988 // Trigger the import of the full definition of each record in C/ObjC.
10989 auto RecordOdrMergeFailures = std::move(PendingRecordOdrMergeFailures);
10990 PendingRecordOdrMergeFailures.clear();
10991 for (auto &Merge : RecordOdrMergeFailures) {
10992 Merge.first->decls_begin();
10993 for (auto &D : Merge.second)
10994 D->decls_begin();
10995 }
10996
10997 // Trigger the import of the full interface definition.
10998 auto ObjCInterfaceOdrMergeFailures =
10999 std::move(PendingObjCInterfaceOdrMergeFailures);
11000 PendingObjCInterfaceOdrMergeFailures.clear();
11001 for (auto &Merge : ObjCInterfaceOdrMergeFailures) {
11002 Merge.first->decls_begin();
11003 for (auto &InterfacePair : Merge.second)
11004 InterfacePair.first->decls_begin();
11005 }
11006
11007 // Trigger the import of functions.
11008 auto FunctionOdrMergeFailures = std::move(PendingFunctionOdrMergeFailures);
11009 PendingFunctionOdrMergeFailures.clear();
11010 for (auto &Merge : FunctionOdrMergeFailures) {
11011 Merge.first->buildLookup();
11012 Merge.first->decls_begin();
11013 Merge.first->getBody();
11014 for (auto &FD : Merge.second) {
11015 FD->buildLookup();
11016 FD->decls_begin();
11017 FD->getBody();
11018 }
11019 }
11020
11021 // Trigger the import of enums.
11022 auto EnumOdrMergeFailures = std::move(PendingEnumOdrMergeFailures);
11023 PendingEnumOdrMergeFailures.clear();
11024 for (auto &Merge : EnumOdrMergeFailures) {
11025 Merge.first->decls_begin();
11026 for (auto &Enum : Merge.second) {
11027 Enum->decls_begin();
11028 }
11029 }
11030
11031 // Trigger the import of the full protocol definition.
11032 auto ObjCProtocolOdrMergeFailures =
11033 std::move(PendingObjCProtocolOdrMergeFailures);
11034 PendingObjCProtocolOdrMergeFailures.clear();
11035 for (auto &Merge : ObjCProtocolOdrMergeFailures) {
11036 Merge.first->decls_begin();
11037 for (auto &ProtocolPair : Merge.second)
11038 ProtocolPair.first->decls_begin();
11039 }
11040
11041 // For each declaration from a merged context, check that the canonical
11042 // definition of that context also contains a declaration of the same
11043 // entity.
11044 //
11045 // Caution: this loop does things that might invalidate iterators into
11046 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
11047 while (!PendingOdrMergeChecks.empty()) {
11048 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
11049
11050 // FIXME: Skip over implicit declarations for now. This matters for things
11051 // like implicitly-declared special member functions. This isn't entirely
11052 // correct; we can end up with multiple unmerged declarations of the same
11053 // implicit entity.
11054 if (D->isImplicit())
11055 continue;
11056
11057 DeclContext *CanonDef = D->getDeclContext();
11058
11059 bool Found = false;
11060 const Decl *DCanon = D->getCanonicalDecl();
11061
11062 for (auto *RI : D->redecls()) {
11063 if (RI->getLexicalDeclContext() == CanonDef) {
11064 Found = true;
11065 break;
11066 }
11067 }
11068 if (Found)
11069 continue;
11070
11071 // Quick check failed, time to do the slow thing. Note, we can't just
11072 // look up the name of D in CanonDef here, because the member that is
11073 // in CanonDef might not be found by name lookup (it might have been
11074 // replaced by a more recent declaration in the lookup table), and we
11075 // can't necessarily find it in the redeclaration chain because it might
11076 // be merely mergeable, not redeclarable.
11077 llvm::SmallVector<const NamedDecl*, 4> Candidates;
11078 for (auto *CanonMember : CanonDef->decls()) {
11079 if (CanonMember->getCanonicalDecl() == DCanon) {
11080 // This can happen if the declaration is merely mergeable and not
11081 // actually redeclarable (we looked for redeclarations earlier).
11082 //
11083 // FIXME: We should be able to detect this more efficiently, without
11084 // pulling in all of the members of CanonDef.
11085 Found = true;
11086 break;
11087 }
11088 if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
11089 if (ND->getDeclName() == D->getDeclName())
11090 Candidates.push_back(ND);
11091 }
11092
11093 if (!Found) {
11094 // The AST doesn't like TagDecls becoming invalid after they've been
11095 // completed. We only really need to mark FieldDecls as invalid here.
11096 if (!isa<TagDecl>(D))
11097 D->setInvalidDecl();
11098
11099 // Ensure we don't accidentally recursively enter deserialization while
11100 // we're producing our diagnostic.
11101 Deserializing RecursionGuard(this);
11102
11103 std::string CanonDefModule =
11105 cast<Decl>(CanonDef));
11106 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
11108 << CanonDef << CanonDefModule.empty() << CanonDefModule;
11109
11110 if (Candidates.empty())
11111 Diag(cast<Decl>(CanonDef)->getLocation(),
11112 diag::note_module_odr_violation_no_possible_decls) << D;
11113 else {
11114 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
11115 Diag(Candidates[I]->getLocation(),
11116 diag::note_module_odr_violation_possible_decl)
11117 << Candidates[I];
11118 }
11119
11120 DiagnosedOdrMergeFailures.insert(CanonDef);
11121 }
11122 }
11123
11124 if (OdrMergeFailures.empty() && RecordOdrMergeFailures.empty() &&
11125 FunctionOdrMergeFailures.empty() && EnumOdrMergeFailures.empty() &&
11126 ObjCInterfaceOdrMergeFailures.empty() &&
11127 ObjCProtocolOdrMergeFailures.empty())
11128 return;
11129
11130 ODRDiagsEmitter DiagsEmitter(Diags, getContext(),
11131 getPreprocessor().getLangOpts());
11132
11133 // Issue any pending ODR-failure diagnostics.
11134 for (auto &Merge : OdrMergeFailures) {
11135 // If we've already pointed out a specific problem with this class, don't
11136 // bother issuing a general "something's different" diagnostic.
11137 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
11138 continue;
11139
11140 bool Diagnosed = false;
11141 CXXRecordDecl *FirstRecord = Merge.first;
11142 for (auto &RecordPair : Merge.second) {
11143 if (DiagsEmitter.diagnoseMismatch(FirstRecord, RecordPair.first,
11144 RecordPair.second)) {
11145 Diagnosed = true;
11146 break;
11147 }
11148 }
11149
11150 if (!Diagnosed) {
11151 // All definitions are updates to the same declaration. This happens if a
11152 // module instantiates the declaration of a class template specialization
11153 // and two or more other modules instantiate its definition.
11154 //
11155 // FIXME: Indicate which modules had instantiations of this definition.
11156 // FIXME: How can this even happen?
11157 Diag(Merge.first->getLocation(),
11158 diag::err_module_odr_violation_different_instantiations)
11159 << Merge.first;
11160 }
11161 }
11162
11163 // Issue any pending ODR-failure diagnostics for RecordDecl in C/ObjC. Note
11164 // that in C++ this is done as a part of CXXRecordDecl ODR checking.
11165 for (auto &Merge : RecordOdrMergeFailures) {
11166 // If we've already pointed out a specific problem with this class, don't
11167 // bother issuing a general "something's different" diagnostic.
11168 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
11169 continue;
11170
11171 RecordDecl *FirstRecord = Merge.first;
11172 bool Diagnosed = false;
11173 for (auto *SecondRecord : Merge.second) {
11174 if (DiagsEmitter.diagnoseMismatch(FirstRecord, SecondRecord)) {
11175 Diagnosed = true;
11176 break;
11177 }
11178 }
11179 (void)Diagnosed;
11180 assert(Diagnosed && "Unable to emit ODR diagnostic.");
11181 }
11182
11183 // Issue ODR failures diagnostics for functions.
11184 for (auto &Merge : FunctionOdrMergeFailures) {
11185 FunctionDecl *FirstFunction = Merge.first;
11186 bool Diagnosed = false;
11187 for (auto &SecondFunction : Merge.second) {
11188 if (DiagsEmitter.diagnoseMismatch(FirstFunction, SecondFunction)) {
11189 Diagnosed = true;
11190 break;
11191 }
11192 }
11193 (void)Diagnosed;
11194 assert(Diagnosed && "Unable to emit ODR diagnostic.");
11195 }
11196
11197 // Issue ODR failures diagnostics for enums.
11198 for (auto &Merge : EnumOdrMergeFailures) {
11199 // If we've already pointed out a specific problem with this enum, don't
11200 // bother issuing a general "something's different" diagnostic.
11201 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
11202 continue;
11203
11204 EnumDecl *FirstEnum = Merge.first;
11205 bool Diagnosed = false;
11206 for (auto &SecondEnum : Merge.second) {
11207 if (DiagsEmitter.diagnoseMismatch(FirstEnum, SecondEnum)) {
11208 Diagnosed = true;
11209 break;
11210 }
11211 }
11212 (void)Diagnosed;
11213 assert(Diagnosed && "Unable to emit ODR diagnostic.");
11214 }
11215
11216 for (auto &Merge : ObjCInterfaceOdrMergeFailures) {
11217 // If we've already pointed out a specific problem with this interface,
11218 // don't bother issuing a general "something's different" diagnostic.
11219 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
11220 continue;
11221
11222 bool Diagnosed = false;
11223 ObjCInterfaceDecl *FirstID = Merge.first;
11224 for (auto &InterfacePair : Merge.second) {
11225 if (DiagsEmitter.diagnoseMismatch(FirstID, InterfacePair.first,
11226 InterfacePair.second)) {
11227 Diagnosed = true;
11228 break;
11229 }
11230 }
11231 (void)Diagnosed;
11232 assert(Diagnosed && "Unable to emit ODR diagnostic.");
11233 }
11234
11235 for (auto &Merge : ObjCProtocolOdrMergeFailures) {
11236 // If we've already pointed out a specific problem with this protocol,
11237 // don't bother issuing a general "something's different" diagnostic.
11238 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
11239 continue;
11240
11241 ObjCProtocolDecl *FirstProtocol = Merge.first;
11242 bool Diagnosed = false;
11243 for (auto &ProtocolPair : Merge.second) {
11244 if (DiagsEmitter.diagnoseMismatch(FirstProtocol, ProtocolPair.first,
11245 ProtocolPair.second)) {
11246 Diagnosed = true;
11247 break;
11248 }
11249 }
11250 (void)Diagnosed;
11251 assert(Diagnosed && "Unable to emit ODR diagnostic.");
11252 }
11253}
11254
11256 if (llvm::Timer *T = ReadTimer.get();
11257 ++NumCurrentElementsDeserializing == 1 && T)
11258 ReadTimeRegion.emplace(T);
11259}
11260
11262 assert(NumCurrentElementsDeserializing &&
11263 "FinishedDeserializing not paired with StartedDeserializing");
11264 if (NumCurrentElementsDeserializing == 1) {
11265 // We decrease NumCurrentElementsDeserializing only after pending actions
11266 // are finished, to avoid recursively re-calling finishPendingActions().
11267 finishPendingActions();
11268 }
11269 --NumCurrentElementsDeserializing;
11270
11271 if (NumCurrentElementsDeserializing == 0) {
11272 {
11273 // Guard variable to avoid recursively entering the process of passing
11274 // decls to consumer.
11275 SaveAndRestore GuardPassingDeclsToConsumer(CanPassDeclsToConsumer,
11276 /*NewValue=*/false);
11277
11278 // Propagate exception specification and deduced type updates along
11279 // redeclaration chains.
11280 //
11281 // We do this now rather than in finishPendingActions because we want to
11282 // be able to walk the complete redeclaration chains of the updated decls.
11283 while (!PendingExceptionSpecUpdates.empty() ||
11284 !PendingDeducedTypeUpdates.empty() ||
11285 !PendingUndeducedFunctionDecls.empty()) {
11286 auto ESUpdates = std::move(PendingExceptionSpecUpdates);
11287 PendingExceptionSpecUpdates.clear();
11288 for (auto Update : ESUpdates) {
11289 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
11290 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
11291 auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
11292 if (auto *Listener = getContext().getASTMutationListener())
11293 Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
11294 for (auto *Redecl : Update.second->redecls())
11296 }
11297
11298 auto DTUpdates = std::move(PendingDeducedTypeUpdates);
11299 PendingDeducedTypeUpdates.clear();
11300 for (auto Update : DTUpdates) {
11301 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
11302 // FIXME: If the return type is already deduced, check that it
11303 // matches.
11305 Update.second);
11306 }
11307
11308 auto UDTUpdates = std::move(PendingUndeducedFunctionDecls);
11309 PendingUndeducedFunctionDecls.clear();
11310 // We hope we can find the deduced type for the functions by iterating
11311 // redeclarations in other modules.
11312 for (FunctionDecl *UndeducedFD : UDTUpdates)
11313 (void)UndeducedFD->getMostRecentDecl();
11314 }
11315
11316 ReadTimeRegion.reset();
11317
11318 diagnoseOdrViolations();
11319 }
11320
11321 // We are not in recursive loading, so it's safe to pass the "interesting"
11322 // decls to the consumer.
11323 if (Consumer)
11324 PassInterestingDeclsToConsumer();
11325 }
11326}
11327
11328void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
11329 if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) {
11330 // Remove any fake results before adding any real ones.
11331 auto It = PendingFakeLookupResults.find(II);
11332 if (It != PendingFakeLookupResults.end()) {
11333 for (auto *ND : It->second)
11334 SemaObj->IdResolver.RemoveDecl(ND);
11335 // FIXME: this works around module+PCH performance issue.
11336 // Rather than erase the result from the map, which is O(n), just clear
11337 // the vector of NamedDecls.
11338 It->second.clear();
11339 }
11340 }
11341
11342 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
11343 SemaObj->TUScope->AddDecl(D);
11344 } else if (SemaObj->TUScope) {
11345 // Adding the decl to IdResolver may have failed because it was already in
11346 // (even though it was not added in scope). If it is already in, make sure
11347 // it gets in the scope as well.
11348 if (llvm::is_contained(SemaObj->IdResolver.decls(Name), D))
11349 SemaObj->TUScope->AddDecl(D);
11350 }
11351}
11352
11354 ASTContext *Context,
11355 const PCHContainerReader &PCHContainerRdr,
11356 const CodeGenOptions &CodeGenOpts,
11357 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
11358 StringRef isysroot,
11359 DisableValidationForModuleKind DisableValidationKind,
11360 bool AllowASTWithCompilerErrors,
11361 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
11362 bool ForceValidateUserInputs,
11363 bool ValidateASTInputFilesContent, bool UseGlobalIndex,
11364 std::unique_ptr<llvm::Timer> ReadTimer)
11365 : Listener(bool(DisableValidationKind & DisableValidationForModuleKind::PCH)
11367 : cast<ASTReaderListener>(new PCHValidator(PP, *this))),
11368 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
11369 PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()),
11370 StackHandler(Diags), PP(PP), ContextObj(Context),
11371 CodeGenOpts(CodeGenOpts),
11372 ModuleMgr(PP.getFileManager(), ModCache, PCHContainerRdr,
11373 PP.getHeaderSearchInfo()),
11374 DummyIdResolver(PP), ReadTimer(std::move(ReadTimer)), isysroot(isysroot),
11375 DisableValidationKind(DisableValidationKind),
11376 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
11377 AllowConfigurationMismatch(AllowConfigurationMismatch),
11378 ValidateSystemInputs(ValidateSystemInputs),
11379 ForceValidateUserInputs(ForceValidateUserInputs),
11380 ValidateASTInputFilesContent(ValidateASTInputFilesContent),
11381 UseGlobalIndex(UseGlobalIndex), CurrSwitchCaseStmts(&SwitchCaseStmts) {
11382 SourceMgr.setExternalSLocEntrySource(this);
11383
11384 PathBuf.reserve(256);
11385
11386 for (const auto &Ext : Extensions) {
11387 auto BlockName = Ext->getExtensionMetadata().BlockName;
11388 auto Known = ModuleFileExtensions.find(BlockName);
11389 if (Known != ModuleFileExtensions.end()) {
11390 Diags.Report(diag::warn_duplicate_module_file_extension)
11391 << BlockName;
11392 continue;
11393 }
11394
11395 ModuleFileExtensions.insert({BlockName, Ext});
11396 }
11397}
11398
11400 if (OwnsDeserializationListener)
11401 delete DeserializationListener;
11402}
11403
11405 return SemaObj ? SemaObj->IdResolver : DummyIdResolver;
11406}
11407
11409 unsigned AbbrevID) {
11410 Idx = 0;
11411 Record.clear();
11412 return Cursor.readRecord(AbbrevID, Record);
11413}
11414//===----------------------------------------------------------------------===//
11415//// OMPClauseReader implementation
11416////===----------------------------------------------------------------------===//
11417
11418// This has to be in namespace clang because it's friended by all
11419// of the OMP clauses.
11420namespace clang {
11421
11422class OMPClauseReader : public OMPClauseVisitor<OMPClauseReader> {
11423 ASTRecordReader &Record;
11424 ASTContext &Context;
11425
11426public:
11428 : Record(Record), Context(Record.getContext()) {}
11429#define GEN_CLANG_CLAUSE_CLASS
11430#define CLAUSE_CLASS(Enum, Str, Class) void Visit##Class(Class *C);
11431#include "llvm/Frontend/OpenMP/OMP.inc"
11435};
11436
11437} // end namespace clang
11438
11442
11444 OMPClause *C = nullptr;
11445 switch (llvm::omp::Clause(Record.readInt())) {
11446 case llvm::omp::OMPC_if:
11447 C = new (Context) OMPIfClause();
11448 break;
11449 case llvm::omp::OMPC_final:
11450 C = new (Context) OMPFinalClause();
11451 break;
11452 case llvm::omp::OMPC_num_threads:
11453 C = new (Context) OMPNumThreadsClause();
11454 break;
11455 case llvm::omp::OMPC_safelen:
11456 C = new (Context) OMPSafelenClause();
11457 break;
11458 case llvm::omp::OMPC_simdlen:
11459 C = new (Context) OMPSimdlenClause();
11460 break;
11461 case llvm::omp::OMPC_sizes: {
11462 unsigned NumSizes = Record.readInt();
11463 C = OMPSizesClause::CreateEmpty(Context, NumSizes);
11464 break;
11465 }
11466 case llvm::omp::OMPC_counts: {
11467 unsigned NumCounts = Record.readInt();
11468 C = OMPCountsClause::CreateEmpty(Context, NumCounts);
11469 break;
11470 }
11471 case llvm::omp::OMPC_permutation: {
11472 unsigned NumLoops = Record.readInt();
11473 C = OMPPermutationClause::CreateEmpty(Context, NumLoops);
11474 break;
11475 }
11476 case llvm::omp::OMPC_full:
11477 C = OMPFullClause::CreateEmpty(Context);
11478 break;
11479 case llvm::omp::OMPC_partial:
11481 break;
11482 case llvm::omp::OMPC_looprange:
11484 break;
11485 case llvm::omp::OMPC_allocator:
11486 C = new (Context) OMPAllocatorClause();
11487 break;
11488 case llvm::omp::OMPC_collapse:
11489 C = new (Context) OMPCollapseClause();
11490 break;
11491 case llvm::omp::OMPC_default:
11492 C = new (Context) OMPDefaultClause();
11493 break;
11494 case llvm::omp::OMPC_proc_bind:
11495 C = new (Context) OMPProcBindClause();
11496 break;
11497 case llvm::omp::OMPC_schedule:
11498 C = new (Context) OMPScheduleClause();
11499 break;
11500 case llvm::omp::OMPC_ordered:
11501 C = OMPOrderedClause::CreateEmpty(Context, Record.readInt());
11502 break;
11503 case llvm::omp::OMPC_nowait:
11504 C = new (Context) OMPNowaitClause();
11505 break;
11506 case llvm::omp::OMPC_untied:
11507 C = new (Context) OMPUntiedClause();
11508 break;
11509 case llvm::omp::OMPC_mergeable:
11510 C = new (Context) OMPMergeableClause();
11511 break;
11512 case llvm::omp::OMPC_threadset:
11513 C = new (Context) OMPThreadsetClause();
11514 break;
11515 case llvm::omp::OMPC_transparent:
11516 C = new (Context) OMPTransparentClause();
11517 break;
11518 case llvm::omp::OMPC_read:
11519 C = new (Context) OMPReadClause();
11520 break;
11521 case llvm::omp::OMPC_write:
11522 C = new (Context) OMPWriteClause();
11523 break;
11524 case llvm::omp::OMPC_update:
11525 C = OMPUpdateClause::CreateEmpty(Context, Record.readInt());
11526 break;
11527 case llvm::omp::OMPC_capture:
11528 C = new (Context) OMPCaptureClause();
11529 break;
11530 case llvm::omp::OMPC_compare:
11531 C = new (Context) OMPCompareClause();
11532 break;
11533 case llvm::omp::OMPC_fail:
11534 C = new (Context) OMPFailClause();
11535 break;
11536 case llvm::omp::OMPC_seq_cst:
11537 C = new (Context) OMPSeqCstClause();
11538 break;
11539 case llvm::omp::OMPC_acq_rel:
11540 C = new (Context) OMPAcqRelClause();
11541 break;
11542 case llvm::omp::OMPC_absent: {
11543 unsigned NumKinds = Record.readInt();
11544 C = OMPAbsentClause::CreateEmpty(Context, NumKinds);
11545 break;
11546 }
11547 case llvm::omp::OMPC_holds:
11548 C = new (Context) OMPHoldsClause();
11549 break;
11550 case llvm::omp::OMPC_contains: {
11551 unsigned NumKinds = Record.readInt();
11552 C = OMPContainsClause::CreateEmpty(Context, NumKinds);
11553 break;
11554 }
11555 case llvm::omp::OMPC_no_openmp:
11556 C = new (Context) OMPNoOpenMPClause();
11557 break;
11558 case llvm::omp::OMPC_no_openmp_routines:
11559 C = new (Context) OMPNoOpenMPRoutinesClause();
11560 break;
11561 case llvm::omp::OMPC_no_openmp_constructs:
11562 C = new (Context) OMPNoOpenMPConstructsClause();
11563 break;
11564 case llvm::omp::OMPC_no_parallelism:
11565 C = new (Context) OMPNoParallelismClause();
11566 break;
11567 case llvm::omp::OMPC_acquire:
11568 C = new (Context) OMPAcquireClause();
11569 break;
11570 case llvm::omp::OMPC_release:
11571 C = new (Context) OMPReleaseClause();
11572 break;
11573 case llvm::omp::OMPC_relaxed:
11574 C = new (Context) OMPRelaxedClause();
11575 break;
11576 case llvm::omp::OMPC_weak:
11577 C = new (Context) OMPWeakClause();
11578 break;
11579 case llvm::omp::OMPC_threads:
11580 C = new (Context) OMPThreadsClause();
11581 break;
11582 case llvm::omp::OMPC_simd:
11583 C = new (Context) OMPSIMDClause();
11584 break;
11585 case llvm::omp::OMPC_nogroup:
11586 C = new (Context) OMPNogroupClause();
11587 break;
11588 case llvm::omp::OMPC_unified_address:
11589 C = new (Context) OMPUnifiedAddressClause();
11590 break;
11591 case llvm::omp::OMPC_unified_shared_memory:
11592 C = new (Context) OMPUnifiedSharedMemoryClause();
11593 break;
11594 case llvm::omp::OMPC_reverse_offload:
11595 C = new (Context) OMPReverseOffloadClause();
11596 break;
11597 case llvm::omp::OMPC_dynamic_allocators:
11598 C = new (Context) OMPDynamicAllocatorsClause();
11599 break;
11600 case llvm::omp::OMPC_atomic_default_mem_order:
11601 C = new (Context) OMPAtomicDefaultMemOrderClause();
11602 break;
11603 case llvm::omp::OMPC_self_maps:
11604 C = new (Context) OMPSelfMapsClause();
11605 break;
11606 case llvm::omp::OMPC_at:
11607 C = new (Context) OMPAtClause();
11608 break;
11609 case llvm::omp::OMPC_severity:
11610 C = new (Context) OMPSeverityClause();
11611 break;
11612 case llvm::omp::OMPC_message:
11613 C = new (Context) OMPMessageClause();
11614 break;
11615 case llvm::omp::OMPC_private:
11616 C = OMPPrivateClause::CreateEmpty(Context, Record.readInt());
11617 break;
11618 case llvm::omp::OMPC_firstprivate:
11619 C = OMPFirstprivateClause::CreateEmpty(Context, Record.readInt());
11620 break;
11621 case llvm::omp::OMPC_lastprivate:
11622 C = OMPLastprivateClause::CreateEmpty(Context, Record.readInt());
11623 break;
11624 case llvm::omp::OMPC_shared:
11625 C = OMPSharedClause::CreateEmpty(Context, Record.readInt());
11626 break;
11627 case llvm::omp::OMPC_reduction: {
11628 unsigned N = Record.readInt();
11629 auto Modifier = Record.readEnum<OpenMPReductionClauseModifier>();
11630 C = OMPReductionClause::CreateEmpty(Context, N, Modifier);
11631 break;
11632 }
11633 case llvm::omp::OMPC_task_reduction:
11634 C = OMPTaskReductionClause::CreateEmpty(Context, Record.readInt());
11635 break;
11636 case llvm::omp::OMPC_in_reduction:
11637 C = OMPInReductionClause::CreateEmpty(Context, Record.readInt());
11638 break;
11639 case llvm::omp::OMPC_linear:
11640 C = OMPLinearClause::CreateEmpty(Context, Record.readInt());
11641 break;
11642 case llvm::omp::OMPC_aligned:
11643 C = OMPAlignedClause::CreateEmpty(Context, Record.readInt());
11644 break;
11645 case llvm::omp::OMPC_copyin:
11646 C = OMPCopyinClause::CreateEmpty(Context, Record.readInt());
11647 break;
11648 case llvm::omp::OMPC_copyprivate:
11649 C = OMPCopyprivateClause::CreateEmpty(Context, Record.readInt());
11650 break;
11651 case llvm::omp::OMPC_flush:
11652 C = OMPFlushClause::CreateEmpty(Context, Record.readInt());
11653 break;
11654 case llvm::omp::OMPC_depobj:
11656 break;
11657 case llvm::omp::OMPC_depend: {
11658 unsigned NumVars = Record.readInt();
11659 unsigned NumLoops = Record.readInt();
11660 C = OMPDependClause::CreateEmpty(Context, NumVars, NumLoops);
11661 break;
11662 }
11663 case llvm::omp::OMPC_device:
11664 C = new (Context) OMPDeviceClause();
11665 break;
11666 case llvm::omp::OMPC_map: {
11668 Sizes.NumVars = Record.readInt();
11669 Sizes.NumUniqueDeclarations = Record.readInt();
11670 Sizes.NumComponentLists = Record.readInt();
11671 Sizes.NumComponents = Record.readInt();
11672 C = OMPMapClause::CreateEmpty(Context, Sizes);
11673 break;
11674 }
11675 case llvm::omp::OMPC_num_teams:
11676 C = OMPNumTeamsClause::CreateEmpty(Context, Record.readInt());
11677 break;
11678 case llvm::omp::OMPC_thread_limit:
11679 C = OMPThreadLimitClause::CreateEmpty(Context, Record.readInt());
11680 break;
11681 case llvm::omp::OMPC_priority:
11682 C = new (Context) OMPPriorityClause();
11683 break;
11684 case llvm::omp::OMPC_grainsize:
11685 C = new (Context) OMPGrainsizeClause();
11686 break;
11687 case llvm::omp::OMPC_num_tasks:
11688 C = new (Context) OMPNumTasksClause();
11689 break;
11690 case llvm::omp::OMPC_hint:
11691 C = new (Context) OMPHintClause();
11692 break;
11693 case llvm::omp::OMPC_dist_schedule:
11694 C = new (Context) OMPDistScheduleClause();
11695 break;
11696 case llvm::omp::OMPC_defaultmap:
11697 C = new (Context) OMPDefaultmapClause();
11698 break;
11699 case llvm::omp::OMPC_to: {
11701 Sizes.NumVars = Record.readInt();
11702 Sizes.NumUniqueDeclarations = Record.readInt();
11703 Sizes.NumComponentLists = Record.readInt();
11704 Sizes.NumComponents = Record.readInt();
11705 C = OMPToClause::CreateEmpty(Context, Sizes);
11706 break;
11707 }
11708 case llvm::omp::OMPC_from: {
11710 Sizes.NumVars = Record.readInt();
11711 Sizes.NumUniqueDeclarations = Record.readInt();
11712 Sizes.NumComponentLists = Record.readInt();
11713 Sizes.NumComponents = Record.readInt();
11714 C = OMPFromClause::CreateEmpty(Context, Sizes);
11715 break;
11716 }
11717 case llvm::omp::OMPC_use_device_ptr: {
11719 Sizes.NumVars = Record.readInt();
11720 Sizes.NumUniqueDeclarations = Record.readInt();
11721 Sizes.NumComponentLists = Record.readInt();
11722 Sizes.NumComponents = Record.readInt();
11723 C = OMPUseDevicePtrClause::CreateEmpty(Context, Sizes);
11724 break;
11725 }
11726 case llvm::omp::OMPC_use_device_addr: {
11728 Sizes.NumVars = Record.readInt();
11729 Sizes.NumUniqueDeclarations = Record.readInt();
11730 Sizes.NumComponentLists = Record.readInt();
11731 Sizes.NumComponents = Record.readInt();
11732 C = OMPUseDeviceAddrClause::CreateEmpty(Context, Sizes);
11733 break;
11734 }
11735 case llvm::omp::OMPC_is_device_ptr: {
11737 Sizes.NumVars = Record.readInt();
11738 Sizes.NumUniqueDeclarations = Record.readInt();
11739 Sizes.NumComponentLists = Record.readInt();
11740 Sizes.NumComponents = Record.readInt();
11741 C = OMPIsDevicePtrClause::CreateEmpty(Context, Sizes);
11742 break;
11743 }
11744 case llvm::omp::OMPC_has_device_addr: {
11746 Sizes.NumVars = Record.readInt();
11747 Sizes.NumUniqueDeclarations = Record.readInt();
11748 Sizes.NumComponentLists = Record.readInt();
11749 Sizes.NumComponents = Record.readInt();
11750 C = OMPHasDeviceAddrClause::CreateEmpty(Context, Sizes);
11751 break;
11752 }
11753 case llvm::omp::OMPC_allocate:
11754 C = OMPAllocateClause::CreateEmpty(Context, Record.readInt());
11755 break;
11756 case llvm::omp::OMPC_nontemporal:
11757 C = OMPNontemporalClause::CreateEmpty(Context, Record.readInt());
11758 break;
11759 case llvm::omp::OMPC_inclusive:
11760 C = OMPInclusiveClause::CreateEmpty(Context, Record.readInt());
11761 break;
11762 case llvm::omp::OMPC_exclusive:
11763 C = OMPExclusiveClause::CreateEmpty(Context, Record.readInt());
11764 break;
11765 case llvm::omp::OMPC_order:
11766 C = new (Context) OMPOrderClause();
11767 break;
11768 case llvm::omp::OMPC_init:
11769 C = OMPInitClause::CreateEmpty(Context, Record.readInt());
11770 break;
11771 case llvm::omp::OMPC_use:
11772 C = new (Context) OMPUseClause();
11773 break;
11774 case llvm::omp::OMPC_destroy:
11775 C = new (Context) OMPDestroyClause();
11776 break;
11777 case llvm::omp::OMPC_novariants:
11778 C = new (Context) OMPNovariantsClause();
11779 break;
11780 case llvm::omp::OMPC_nocontext:
11781 C = new (Context) OMPNocontextClause();
11782 break;
11783 case llvm::omp::OMPC_detach:
11784 C = new (Context) OMPDetachClause();
11785 break;
11786 case llvm::omp::OMPC_uses_allocators:
11787 C = OMPUsesAllocatorsClause::CreateEmpty(Context, Record.readInt());
11788 break;
11789 case llvm::omp::OMPC_affinity:
11790 C = OMPAffinityClause::CreateEmpty(Context, Record.readInt());
11791 break;
11792 case llvm::omp::OMPC_filter:
11793 C = new (Context) OMPFilterClause();
11794 break;
11795 case llvm::omp::OMPC_bind:
11796 C = OMPBindClause::CreateEmpty(Context);
11797 break;
11798 case llvm::omp::OMPC_align:
11799 C = new (Context) OMPAlignClause();
11800 break;
11801 case llvm::omp::OMPC_ompx_dyn_cgroup_mem:
11802 C = new (Context) OMPXDynCGroupMemClause();
11803 break;
11804 case llvm::omp::OMPC_dyn_groupprivate:
11805 C = new (Context) OMPDynGroupprivateClause();
11806 break;
11807 case llvm::omp::OMPC_doacross: {
11808 unsigned NumVars = Record.readInt();
11809 unsigned NumLoops = Record.readInt();
11810 C = OMPDoacrossClause::CreateEmpty(Context, NumVars, NumLoops);
11811 break;
11812 }
11813 case llvm::omp::OMPC_ompx_attribute:
11814 C = new (Context) OMPXAttributeClause();
11815 break;
11816 case llvm::omp::OMPC_ompx_bare:
11817 C = new (Context) OMPXBareClause();
11818 break;
11819#define OMP_CLAUSE_NO_CLASS(Enum, Str) \
11820 case llvm::omp::Enum: \
11821 break;
11822#include "llvm/Frontend/OpenMP/OMPKinds.def"
11823 default:
11824 break;
11825 }
11826 assert(C && "Unknown OMPClause type");
11827
11828 Visit(C);
11829 C->setLocStart(Record.readSourceLocation());
11830 C->setLocEnd(Record.readSourceLocation());
11831
11832 return C;
11833}
11834
11836 C->setPreInitStmt(Record.readSubStmt(),
11837 static_cast<OpenMPDirectiveKind>(Record.readInt()));
11838}
11839
11842 C->setPostUpdateExpr(Record.readSubExpr());
11843}
11844
11845void OMPClauseReader::VisitOMPIfClause(OMPIfClause *C) {
11847 C->setNameModifier(static_cast<OpenMPDirectiveKind>(Record.readInt()));
11848 C->setNameModifierLoc(Record.readSourceLocation());
11849 C->setColonLoc(Record.readSourceLocation());
11850 C->setCondition(Record.readSubExpr());
11851 C->setLParenLoc(Record.readSourceLocation());
11852}
11853
11854void OMPClauseReader::VisitOMPFinalClause(OMPFinalClause *C) {
11856 C->setCondition(Record.readSubExpr());
11857 C->setLParenLoc(Record.readSourceLocation());
11858}
11859
11860void OMPClauseReader::VisitOMPNumThreadsClause(OMPNumThreadsClause *C) {
11862 C->setModifier(Record.readEnum<OpenMPNumThreadsClauseModifier>());
11863 C->setNumThreads(Record.readSubExpr());
11864 C->setModifierLoc(Record.readSourceLocation());
11865 C->setLParenLoc(Record.readSourceLocation());
11866}
11867
11868void OMPClauseReader::VisitOMPSafelenClause(OMPSafelenClause *C) {
11869 C->setSafelen(Record.readSubExpr());
11870 C->setLParenLoc(Record.readSourceLocation());
11871}
11872
11873void OMPClauseReader::VisitOMPSimdlenClause(OMPSimdlenClause *C) {
11874 C->setSimdlen(Record.readSubExpr());
11875 C->setLParenLoc(Record.readSourceLocation());
11876}
11877
11878void OMPClauseReader::VisitOMPSizesClause(OMPSizesClause *C) {
11879 for (Expr *&E : C->getSizesRefs())
11880 E = Record.readSubExpr();
11881 C->setLParenLoc(Record.readSourceLocation());
11882}
11883
11884void OMPClauseReader::VisitOMPCountsClause(OMPCountsClause *C) {
11885 bool HasFill = Record.readBool();
11886 if (HasFill)
11887 C->setOmpFillIndex(Record.readInt());
11888 C->setOmpFillLoc(Record.readSourceLocation());
11889 for (Expr *&E : C->getCountsRefs())
11890 E = Record.readSubExpr();
11891 C->setLParenLoc(Record.readSourceLocation());
11892}
11893
11894void OMPClauseReader::VisitOMPPermutationClause(OMPPermutationClause *C) {
11895 for (Expr *&E : C->getArgsRefs())
11896 E = Record.readSubExpr();
11897 C->setLParenLoc(Record.readSourceLocation());
11898}
11899
11900void OMPClauseReader::VisitOMPFullClause(OMPFullClause *C) {}
11901
11902void OMPClauseReader::VisitOMPPartialClause(OMPPartialClause *C) {
11903 C->setFactor(Record.readSubExpr());
11904 C->setLParenLoc(Record.readSourceLocation());
11905}
11906
11907void OMPClauseReader::VisitOMPLoopRangeClause(OMPLoopRangeClause *C) {
11908 C->setFirst(Record.readSubExpr());
11909 C->setCount(Record.readSubExpr());
11910 C->setLParenLoc(Record.readSourceLocation());
11911 C->setFirstLoc(Record.readSourceLocation());
11912 C->setCountLoc(Record.readSourceLocation());
11913}
11914
11915void OMPClauseReader::VisitOMPAllocatorClause(OMPAllocatorClause *C) {
11916 C->setAllocator(Record.readExpr());
11917 C->setLParenLoc(Record.readSourceLocation());
11918}
11919
11920void OMPClauseReader::VisitOMPCollapseClause(OMPCollapseClause *C) {
11921 C->setNumForLoops(Record.readSubExpr());
11922 C->setLParenLoc(Record.readSourceLocation());
11923}
11924
11925void OMPClauseReader::VisitOMPDefaultClause(OMPDefaultClause *C) {
11926 C->setDefaultKind(static_cast<llvm::omp::DefaultKind>(Record.readInt()));
11927 C->setLParenLoc(Record.readSourceLocation());
11928 C->setDefaultKindKwLoc(Record.readSourceLocation());
11929 C->setDefaultVariableCategory(
11930 Record.readEnum<OpenMPDefaultClauseVariableCategory>());
11931 C->setDefaultVariableCategoryLocation(Record.readSourceLocation());
11932}
11933
11934// Read the parameter of threadset clause. This will have been saved when
11935// OMPClauseWriter is called.
11936void OMPClauseReader::VisitOMPThreadsetClause(OMPThreadsetClause *C) {
11937 C->setLParenLoc(Record.readSourceLocation());
11938 SourceLocation ThreadsetKindLoc = Record.readSourceLocation();
11939 C->setThreadsetKindLoc(ThreadsetKindLoc);
11940 OpenMPThreadsetKind TKind =
11941 static_cast<OpenMPThreadsetKind>(Record.readInt());
11942 C->setThreadsetKind(TKind);
11943}
11944
11945void OMPClauseReader::VisitOMPTransparentClause(OMPTransparentClause *C) {
11946 C->setLParenLoc(Record.readSourceLocation());
11947 C->setImpexTypeKind(Record.readSubExpr());
11948}
11949
11950void OMPClauseReader::VisitOMPProcBindClause(OMPProcBindClause *C) {
11951 C->setProcBindKind(static_cast<llvm::omp::ProcBindKind>(Record.readInt()));
11952 C->setLParenLoc(Record.readSourceLocation());
11953 C->setProcBindKindKwLoc(Record.readSourceLocation());
11954}
11955
11956void OMPClauseReader::VisitOMPScheduleClause(OMPScheduleClause *C) {
11958 C->setScheduleKind(
11959 static_cast<OpenMPScheduleClauseKind>(Record.readInt()));
11960 C->setFirstScheduleModifier(
11961 static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
11962 C->setSecondScheduleModifier(
11963 static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
11964 C->setChunkSize(Record.readSubExpr());
11965 C->setLParenLoc(Record.readSourceLocation());
11966 C->setFirstScheduleModifierLoc(Record.readSourceLocation());
11967 C->setSecondScheduleModifierLoc(Record.readSourceLocation());
11968 C->setScheduleKindLoc(Record.readSourceLocation());
11969 C->setCommaLoc(Record.readSourceLocation());
11970}
11971
11972void OMPClauseReader::VisitOMPOrderedClause(OMPOrderedClause *C) {
11973 C->setNumForLoops(Record.readSubExpr());
11974 for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
11975 C->setLoopNumIterations(I, Record.readSubExpr());
11976 for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
11977 C->setLoopCounter(I, Record.readSubExpr());
11978 C->setLParenLoc(Record.readSourceLocation());
11979}
11980
11981void OMPClauseReader::VisitOMPDetachClause(OMPDetachClause *C) {
11982 C->setEventHandler(Record.readSubExpr());
11983 C->setLParenLoc(Record.readSourceLocation());
11984}
11985
11986void OMPClauseReader::VisitOMPNowaitClause(OMPNowaitClause *C) {
11987 C->setCondition(Record.readSubExpr());
11988 C->setLParenLoc(Record.readSourceLocation());
11989}
11990
11991void OMPClauseReader::VisitOMPUntiedClause(OMPUntiedClause *) {}
11992
11993void OMPClauseReader::VisitOMPMergeableClause(OMPMergeableClause *) {}
11994
11995void OMPClauseReader::VisitOMPReadClause(OMPReadClause *) {}
11996
11997void OMPClauseReader::VisitOMPWriteClause(OMPWriteClause *) {}
11998
11999void OMPClauseReader::VisitOMPUpdateClause(OMPUpdateClause *C) {
12000 if (C->isExtended()) {
12001 C->setLParenLoc(Record.readSourceLocation());
12002 C->setArgumentLoc(Record.readSourceLocation());
12003 C->setDependencyKind(Record.readEnum<OpenMPDependClauseKind>());
12004 }
12005}
12006
12007void OMPClauseReader::VisitOMPCaptureClause(OMPCaptureClause *) {}
12008
12009void OMPClauseReader::VisitOMPCompareClause(OMPCompareClause *) {}
12010
12011// Read the parameter of fail clause. This will have been saved when
12012// OMPClauseWriter is called.
12013void OMPClauseReader::VisitOMPFailClause(OMPFailClause *C) {
12014 C->setLParenLoc(Record.readSourceLocation());
12015 SourceLocation FailParameterLoc = Record.readSourceLocation();
12016 C->setFailParameterLoc(FailParameterLoc);
12017 OpenMPClauseKind CKind = Record.readEnum<OpenMPClauseKind>();
12018 C->setFailParameter(CKind);
12019}
12020
12021void OMPClauseReader::VisitOMPAbsentClause(OMPAbsentClause *C) {
12022 unsigned Count = C->getDirectiveKinds().size();
12023 C->setLParenLoc(Record.readSourceLocation());
12024 llvm::SmallVector<OpenMPDirectiveKind, 4> DKVec;
12025 DKVec.reserve(Count);
12026 for (unsigned I = 0; I < Count; I++) {
12027 DKVec.push_back(Record.readEnum<OpenMPDirectiveKind>());
12028 }
12029 C->setDirectiveKinds(DKVec);
12030}
12031
12032void OMPClauseReader::VisitOMPHoldsClause(OMPHoldsClause *C) {
12033 C->setExpr(Record.readExpr());
12034 C->setLParenLoc(Record.readSourceLocation());
12035}
12036
12037void OMPClauseReader::VisitOMPContainsClause(OMPContainsClause *C) {
12038 unsigned Count = C->getDirectiveKinds().size();
12039 C->setLParenLoc(Record.readSourceLocation());
12040 llvm::SmallVector<OpenMPDirectiveKind, 4> DKVec;
12041 DKVec.reserve(Count);
12042 for (unsigned I = 0; I < Count; I++) {
12043 DKVec.push_back(Record.readEnum<OpenMPDirectiveKind>());
12044 }
12045 C->setDirectiveKinds(DKVec);
12046}
12047
12048void OMPClauseReader::VisitOMPNoOpenMPClause(OMPNoOpenMPClause *) {}
12049
12050void OMPClauseReader::VisitOMPNoOpenMPRoutinesClause(
12051 OMPNoOpenMPRoutinesClause *) {}
12052
12053void OMPClauseReader::VisitOMPNoOpenMPConstructsClause(
12054 OMPNoOpenMPConstructsClause *) {}
12055
12056void OMPClauseReader::VisitOMPNoParallelismClause(OMPNoParallelismClause *) {}
12057
12058void OMPClauseReader::VisitOMPSeqCstClause(OMPSeqCstClause *) {}
12059
12060void OMPClauseReader::VisitOMPAcqRelClause(OMPAcqRelClause *) {}
12061
12062void OMPClauseReader::VisitOMPAcquireClause(OMPAcquireClause *) {}
12063
12064void OMPClauseReader::VisitOMPReleaseClause(OMPReleaseClause *) {}
12065
12066void OMPClauseReader::VisitOMPRelaxedClause(OMPRelaxedClause *) {}
12067
12068void OMPClauseReader::VisitOMPWeakClause(OMPWeakClause *) {}
12069
12070void OMPClauseReader::VisitOMPThreadsClause(OMPThreadsClause *) {}
12071
12072void OMPClauseReader::VisitOMPSIMDClause(OMPSIMDClause *) {}
12073
12074void OMPClauseReader::VisitOMPNogroupClause(OMPNogroupClause *) {}
12075
12076void OMPClauseReader::VisitOMPInitClause(OMPInitClause *C) {
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 C->setIsTarget(Record.readBool());
12084 C->setIsTargetSync(Record.readBool());
12085 C->setLParenLoc(Record.readSourceLocation());
12086 C->setVarLoc(Record.readSourceLocation());
12087}
12088
12089void OMPClauseReader::VisitOMPUseClause(OMPUseClause *C) {
12090 C->setInteropVar(Record.readSubExpr());
12091 C->setLParenLoc(Record.readSourceLocation());
12092 C->setVarLoc(Record.readSourceLocation());
12093}
12094
12095void OMPClauseReader::VisitOMPDestroyClause(OMPDestroyClause *C) {
12096 C->setInteropVar(Record.readSubExpr());
12097 C->setLParenLoc(Record.readSourceLocation());
12098 C->setVarLoc(Record.readSourceLocation());
12099}
12100
12101void OMPClauseReader::VisitOMPNovariantsClause(OMPNovariantsClause *C) {
12103 C->setCondition(Record.readSubExpr());
12104 C->setLParenLoc(Record.readSourceLocation());
12105}
12106
12107void OMPClauseReader::VisitOMPNocontextClause(OMPNocontextClause *C) {
12109 C->setCondition(Record.readSubExpr());
12110 C->setLParenLoc(Record.readSourceLocation());
12111}
12112
12113void OMPClauseReader::VisitOMPUnifiedAddressClause(OMPUnifiedAddressClause *) {}
12114
12115void OMPClauseReader::VisitOMPUnifiedSharedMemoryClause(
12116 OMPUnifiedSharedMemoryClause *) {}
12117
12118void OMPClauseReader::VisitOMPReverseOffloadClause(OMPReverseOffloadClause *) {}
12119
12120void
12121OMPClauseReader::VisitOMPDynamicAllocatorsClause(OMPDynamicAllocatorsClause *) {
12122}
12123
12124void OMPClauseReader::VisitOMPAtomicDefaultMemOrderClause(
12125 OMPAtomicDefaultMemOrderClause *C) {
12126 C->setAtomicDefaultMemOrderKind(
12127 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Record.readInt()));
12128 C->setLParenLoc(Record.readSourceLocation());
12129 C->setAtomicDefaultMemOrderKindKwLoc(Record.readSourceLocation());
12130}
12131
12132void OMPClauseReader::VisitOMPSelfMapsClause(OMPSelfMapsClause *) {}
12133
12134void OMPClauseReader::VisitOMPAtClause(OMPAtClause *C) {
12135 C->setAtKind(static_cast<OpenMPAtClauseKind>(Record.readInt()));
12136 C->setLParenLoc(Record.readSourceLocation());
12137 C->setAtKindKwLoc(Record.readSourceLocation());
12138}
12139
12140void OMPClauseReader::VisitOMPSeverityClause(OMPSeverityClause *C) {
12141 C->setSeverityKind(static_cast<OpenMPSeverityClauseKind>(Record.readInt()));
12142 C->setLParenLoc(Record.readSourceLocation());
12143 C->setSeverityKindKwLoc(Record.readSourceLocation());
12144}
12145
12146void OMPClauseReader::VisitOMPMessageClause(OMPMessageClause *C) {
12148 C->setMessageString(Record.readSubExpr());
12149 C->setLParenLoc(Record.readSourceLocation());
12150}
12151
12152void OMPClauseReader::VisitOMPPrivateClause(OMPPrivateClause *C) {
12153 C->setLParenLoc(Record.readSourceLocation());
12154 unsigned NumVars = C->varlist_size();
12155 SmallVector<Expr *, 16> Vars;
12156 Vars.reserve(NumVars);
12157 for (unsigned i = 0; i != NumVars; ++i)
12158 Vars.push_back(Record.readSubExpr());
12159 C->setVarRefs(Vars);
12160 Vars.clear();
12161 for (unsigned i = 0; i != NumVars; ++i)
12162 Vars.push_back(Record.readSubExpr());
12163 C->setPrivateCopies(Vars);
12164}
12165
12166void OMPClauseReader::VisitOMPFirstprivateClause(OMPFirstprivateClause *C) {
12168 C->setLParenLoc(Record.readSourceLocation());
12169 unsigned NumVars = C->varlist_size();
12170 SmallVector<Expr *, 16> Vars;
12171 Vars.reserve(NumVars);
12172 for (unsigned i = 0; i != NumVars; ++i)
12173 Vars.push_back(Record.readSubExpr());
12174 C->setVarRefs(Vars);
12175 Vars.clear();
12176 for (unsigned i = 0; i != NumVars; ++i)
12177 Vars.push_back(Record.readSubExpr());
12178 C->setPrivateCopies(Vars);
12179 Vars.clear();
12180 for (unsigned i = 0; i != NumVars; ++i)
12181 Vars.push_back(Record.readSubExpr());
12182 C->setInits(Vars);
12183}
12184
12185void OMPClauseReader::VisitOMPLastprivateClause(OMPLastprivateClause *C) {
12187 C->setLParenLoc(Record.readSourceLocation());
12188 C->setKind(Record.readEnum<OpenMPLastprivateModifier>());
12189 C->setKindLoc(Record.readSourceLocation());
12190 C->setColonLoc(Record.readSourceLocation());
12191 unsigned NumVars = C->varlist_size();
12192 SmallVector<Expr *, 16> Vars;
12193 Vars.reserve(NumVars);
12194 for (unsigned i = 0; i != NumVars; ++i)
12195 Vars.push_back(Record.readSubExpr());
12196 C->setVarRefs(Vars);
12197 Vars.clear();
12198 for (unsigned i = 0; i != NumVars; ++i)
12199 Vars.push_back(Record.readSubExpr());
12200 C->setPrivateCopies(Vars);
12201 Vars.clear();
12202 for (unsigned i = 0; i != NumVars; ++i)
12203 Vars.push_back(Record.readSubExpr());
12204 C->setSourceExprs(Vars);
12205 Vars.clear();
12206 for (unsigned i = 0; i != NumVars; ++i)
12207 Vars.push_back(Record.readSubExpr());
12208 C->setDestinationExprs(Vars);
12209 Vars.clear();
12210 for (unsigned i = 0; i != NumVars; ++i)
12211 Vars.push_back(Record.readSubExpr());
12212 C->setAssignmentOps(Vars);
12213}
12214
12215void OMPClauseReader::VisitOMPSharedClause(OMPSharedClause *C) {
12216 C->setLParenLoc(Record.readSourceLocation());
12217 unsigned NumVars = C->varlist_size();
12218 SmallVector<Expr *, 16> Vars;
12219 Vars.reserve(NumVars);
12220 for (unsigned i = 0; i != NumVars; ++i)
12221 Vars.push_back(Record.readSubExpr());
12222 C->setVarRefs(Vars);
12223}
12224
12225void OMPClauseReader::VisitOMPReductionClause(OMPReductionClause *C) {
12227 C->setLParenLoc(Record.readSourceLocation());
12228 C->setModifierLoc(Record.readSourceLocation());
12229 C->setColonLoc(Record.readSourceLocation());
12230 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
12231 DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
12232 C->setQualifierLoc(NNSL);
12233 C->setNameInfo(DNI);
12234
12235 unsigned NumVars = C->varlist_size();
12236 SmallVector<Expr *, 16> Vars;
12237 Vars.reserve(NumVars);
12238 for (unsigned i = 0; i != NumVars; ++i)
12239 Vars.push_back(Record.readSubExpr());
12240 C->setVarRefs(Vars);
12241 Vars.clear();
12242 for (unsigned i = 0; i != NumVars; ++i)
12243 Vars.push_back(Record.readSubExpr());
12244 C->setPrivates(Vars);
12245 Vars.clear();
12246 for (unsigned i = 0; i != NumVars; ++i)
12247 Vars.push_back(Record.readSubExpr());
12248 C->setLHSExprs(Vars);
12249 Vars.clear();
12250 for (unsigned i = 0; i != NumVars; ++i)
12251 Vars.push_back(Record.readSubExpr());
12252 C->setRHSExprs(Vars);
12253 Vars.clear();
12254 for (unsigned i = 0; i != NumVars; ++i)
12255 Vars.push_back(Record.readSubExpr());
12256 C->setReductionOps(Vars);
12257 if (C->getModifier() == OMPC_REDUCTION_inscan) {
12258 Vars.clear();
12259 for (unsigned i = 0; i != NumVars; ++i)
12260 Vars.push_back(Record.readSubExpr());
12261 C->setInscanCopyOps(Vars);
12262 Vars.clear();
12263 for (unsigned i = 0; i != NumVars; ++i)
12264 Vars.push_back(Record.readSubExpr());
12265 C->setInscanCopyArrayTemps(Vars);
12266 Vars.clear();
12267 for (unsigned i = 0; i != NumVars; ++i)
12268 Vars.push_back(Record.readSubExpr());
12269 C->setInscanCopyArrayElems(Vars);
12270 }
12271 unsigned NumFlags = Record.readInt();
12272 SmallVector<bool, 16> Flags;
12273 Flags.reserve(NumFlags);
12274 for ([[maybe_unused]] unsigned I : llvm::seq<unsigned>(NumFlags))
12275 Flags.push_back(Record.readInt());
12276 C->setPrivateVariableReductionFlags(Flags);
12277}
12278
12279void OMPClauseReader::VisitOMPTaskReductionClause(OMPTaskReductionClause *C) {
12281 C->setLParenLoc(Record.readSourceLocation());
12282 C->setColonLoc(Record.readSourceLocation());
12283 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
12284 DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
12285 C->setQualifierLoc(NNSL);
12286 C->setNameInfo(DNI);
12287
12288 unsigned NumVars = C->varlist_size();
12289 SmallVector<Expr *, 16> Vars;
12290 Vars.reserve(NumVars);
12291 for (unsigned I = 0; I != NumVars; ++I)
12292 Vars.push_back(Record.readSubExpr());
12293 C->setVarRefs(Vars);
12294 Vars.clear();
12295 for (unsigned I = 0; I != NumVars; ++I)
12296 Vars.push_back(Record.readSubExpr());
12297 C->setPrivates(Vars);
12298 Vars.clear();
12299 for (unsigned I = 0; I != NumVars; ++I)
12300 Vars.push_back(Record.readSubExpr());
12301 C->setLHSExprs(Vars);
12302 Vars.clear();
12303 for (unsigned I = 0; I != NumVars; ++I)
12304 Vars.push_back(Record.readSubExpr());
12305 C->setRHSExprs(Vars);
12306 Vars.clear();
12307 for (unsigned I = 0; I != NumVars; ++I)
12308 Vars.push_back(Record.readSubExpr());
12309 C->setReductionOps(Vars);
12310}
12311
12312void OMPClauseReader::VisitOMPInReductionClause(OMPInReductionClause *C) {
12314 C->setLParenLoc(Record.readSourceLocation());
12315 C->setColonLoc(Record.readSourceLocation());
12316 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
12317 DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
12318 C->setQualifierLoc(NNSL);
12319 C->setNameInfo(DNI);
12320
12321 unsigned NumVars = C->varlist_size();
12322 SmallVector<Expr *, 16> Vars;
12323 Vars.reserve(NumVars);
12324 for (unsigned I = 0; I != NumVars; ++I)
12325 Vars.push_back(Record.readSubExpr());
12326 C->setVarRefs(Vars);
12327 Vars.clear();
12328 for (unsigned I = 0; I != NumVars; ++I)
12329 Vars.push_back(Record.readSubExpr());
12330 C->setPrivates(Vars);
12331 Vars.clear();
12332 for (unsigned I = 0; I != NumVars; ++I)
12333 Vars.push_back(Record.readSubExpr());
12334 C->setLHSExprs(Vars);
12335 Vars.clear();
12336 for (unsigned I = 0; I != NumVars; ++I)
12337 Vars.push_back(Record.readSubExpr());
12338 C->setRHSExprs(Vars);
12339 Vars.clear();
12340 for (unsigned I = 0; I != NumVars; ++I)
12341 Vars.push_back(Record.readSubExpr());
12342 C->setReductionOps(Vars);
12343 Vars.clear();
12344 for (unsigned I = 0; I != NumVars; ++I)
12345 Vars.push_back(Record.readSubExpr());
12346 C->setTaskgroupDescriptors(Vars);
12347}
12348
12349void OMPClauseReader::VisitOMPLinearClause(OMPLinearClause *C) {
12351 C->setLParenLoc(Record.readSourceLocation());
12352 C->setColonLoc(Record.readSourceLocation());
12353 C->setModifier(static_cast<OpenMPLinearClauseKind>(Record.readInt()));
12354 C->setModifierLoc(Record.readSourceLocation());
12355 unsigned NumVars = C->varlist_size();
12356 SmallVector<Expr *, 16> Vars;
12357 Vars.reserve(NumVars);
12358 for (unsigned i = 0; i != NumVars; ++i)
12359 Vars.push_back(Record.readSubExpr());
12360 C->setVarRefs(Vars);
12361 Vars.clear();
12362 for (unsigned i = 0; i != NumVars; ++i)
12363 Vars.push_back(Record.readSubExpr());
12364 C->setPrivates(Vars);
12365 Vars.clear();
12366 for (unsigned i = 0; i != NumVars; ++i)
12367 Vars.push_back(Record.readSubExpr());
12368 C->setInits(Vars);
12369 Vars.clear();
12370 for (unsigned i = 0; i != NumVars; ++i)
12371 Vars.push_back(Record.readSubExpr());
12372 C->setUpdates(Vars);
12373 Vars.clear();
12374 for (unsigned i = 0; i != NumVars; ++i)
12375 Vars.push_back(Record.readSubExpr());
12376 C->setFinals(Vars);
12377 C->setStep(Record.readSubExpr());
12378 C->setCalcStep(Record.readSubExpr());
12379 Vars.clear();
12380 for (unsigned I = 0; I != NumVars + 1; ++I)
12381 Vars.push_back(Record.readSubExpr());
12382 C->setUsedExprs(Vars);
12383}
12384
12385void OMPClauseReader::VisitOMPAlignedClause(OMPAlignedClause *C) {
12386 C->setLParenLoc(Record.readSourceLocation());
12387 C->setColonLoc(Record.readSourceLocation());
12388 unsigned NumVars = C->varlist_size();
12389 SmallVector<Expr *, 16> Vars;
12390 Vars.reserve(NumVars);
12391 for (unsigned i = 0; i != NumVars; ++i)
12392 Vars.push_back(Record.readSubExpr());
12393 C->setVarRefs(Vars);
12394 C->setAlignment(Record.readSubExpr());
12395}
12396
12397void OMPClauseReader::VisitOMPCopyinClause(OMPCopyinClause *C) {
12398 C->setLParenLoc(Record.readSourceLocation());
12399 unsigned NumVars = C->varlist_size();
12400 SmallVector<Expr *, 16> Exprs;
12401 Exprs.reserve(NumVars);
12402 for (unsigned i = 0; i != NumVars; ++i)
12403 Exprs.push_back(Record.readSubExpr());
12404 C->setVarRefs(Exprs);
12405 Exprs.clear();
12406 for (unsigned i = 0; i != NumVars; ++i)
12407 Exprs.push_back(Record.readSubExpr());
12408 C->setSourceExprs(Exprs);
12409 Exprs.clear();
12410 for (unsigned i = 0; i != NumVars; ++i)
12411 Exprs.push_back(Record.readSubExpr());
12412 C->setDestinationExprs(Exprs);
12413 Exprs.clear();
12414 for (unsigned i = 0; i != NumVars; ++i)
12415 Exprs.push_back(Record.readSubExpr());
12416 C->setAssignmentOps(Exprs);
12417}
12418
12419void OMPClauseReader::VisitOMPCopyprivateClause(OMPCopyprivateClause *C) {
12420 C->setLParenLoc(Record.readSourceLocation());
12421 unsigned NumVars = C->varlist_size();
12422 SmallVector<Expr *, 16> Exprs;
12423 Exprs.reserve(NumVars);
12424 for (unsigned i = 0; i != NumVars; ++i)
12425 Exprs.push_back(Record.readSubExpr());
12426 C->setVarRefs(Exprs);
12427 Exprs.clear();
12428 for (unsigned i = 0; i != NumVars; ++i)
12429 Exprs.push_back(Record.readSubExpr());
12430 C->setSourceExprs(Exprs);
12431 Exprs.clear();
12432 for (unsigned i = 0; i != NumVars; ++i)
12433 Exprs.push_back(Record.readSubExpr());
12434 C->setDestinationExprs(Exprs);
12435 Exprs.clear();
12436 for (unsigned i = 0; i != NumVars; ++i)
12437 Exprs.push_back(Record.readSubExpr());
12438 C->setAssignmentOps(Exprs);
12439}
12440
12441void OMPClauseReader::VisitOMPFlushClause(OMPFlushClause *C) {
12442 C->setLParenLoc(Record.readSourceLocation());
12443 unsigned NumVars = C->varlist_size();
12444 SmallVector<Expr *, 16> Vars;
12445 Vars.reserve(NumVars);
12446 for (unsigned i = 0; i != NumVars; ++i)
12447 Vars.push_back(Record.readSubExpr());
12448 C->setVarRefs(Vars);
12449}
12450
12451void OMPClauseReader::VisitOMPDepobjClause(OMPDepobjClause *C) {
12452 C->setDepobj(Record.readSubExpr());
12453 C->setLParenLoc(Record.readSourceLocation());
12454}
12455
12456void OMPClauseReader::VisitOMPDependClause(OMPDependClause *C) {
12457 C->setLParenLoc(Record.readSourceLocation());
12458 C->setModifier(Record.readSubExpr());
12459 C->setDependencyKind(
12460 static_cast<OpenMPDependClauseKind>(Record.readInt()));
12461 C->setDependencyLoc(Record.readSourceLocation());
12462 C->setColonLoc(Record.readSourceLocation());
12463 C->setOmpAllMemoryLoc(Record.readSourceLocation());
12464 unsigned NumVars = C->varlist_size();
12465 SmallVector<Expr *, 16> Vars;
12466 Vars.reserve(NumVars);
12467 for (unsigned I = 0; I != NumVars; ++I)
12468 Vars.push_back(Record.readSubExpr());
12469 C->setVarRefs(Vars);
12470 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
12471 C->setLoopData(I, Record.readSubExpr());
12472}
12473
12474void OMPClauseReader::VisitOMPDeviceClause(OMPDeviceClause *C) {
12476 C->setModifier(Record.readEnum<OpenMPDeviceClauseModifier>());
12477 C->setDevice(Record.readSubExpr());
12478 C->setModifierLoc(Record.readSourceLocation());
12479 C->setLParenLoc(Record.readSourceLocation());
12480}
12481
12482void OMPClauseReader::VisitOMPMapClause(OMPMapClause *C) {
12483 C->setLParenLoc(Record.readSourceLocation());
12484 bool HasIteratorModifier = false;
12485 for (unsigned I = 0; I < NumberOfOMPMapClauseModifiers; ++I) {
12486 C->setMapTypeModifier(
12487 I, static_cast<OpenMPMapModifierKind>(Record.readInt()));
12488 C->setMapTypeModifierLoc(I, Record.readSourceLocation());
12489 if (C->getMapTypeModifier(I) == OMPC_MAP_MODIFIER_iterator)
12490 HasIteratorModifier = true;
12491 }
12492 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
12493 C->setMapperIdInfo(Record.readDeclarationNameInfo());
12494 C->setMapType(
12495 static_cast<OpenMPMapClauseKind>(Record.readInt()));
12496 C->setMapLoc(Record.readSourceLocation());
12497 C->setColonLoc(Record.readSourceLocation());
12498 auto NumVars = C->varlist_size();
12499 auto UniqueDecls = C->getUniqueDeclarationsNum();
12500 auto TotalLists = C->getTotalComponentListNum();
12501 auto TotalComponents = C->getTotalComponentsNum();
12502
12503 SmallVector<Expr *, 16> Vars;
12504 Vars.reserve(NumVars);
12505 for (unsigned i = 0; i != NumVars; ++i)
12506 Vars.push_back(Record.readExpr());
12507 C->setVarRefs(Vars);
12508
12509 SmallVector<Expr *, 16> UDMappers;
12510 UDMappers.reserve(NumVars);
12511 for (unsigned I = 0; I < NumVars; ++I)
12512 UDMappers.push_back(Record.readExpr());
12513 C->setUDMapperRefs(UDMappers);
12514
12515 if (HasIteratorModifier)
12516 C->setIteratorModifier(Record.readExpr());
12517
12518 SmallVector<ValueDecl *, 16> Decls;
12519 Decls.reserve(UniqueDecls);
12520 for (unsigned i = 0; i < UniqueDecls; ++i)
12521 Decls.push_back(Record.readDeclAs<ValueDecl>());
12522 C->setUniqueDecls(Decls);
12523
12524 SmallVector<unsigned, 16> ListsPerDecl;
12525 ListsPerDecl.reserve(UniqueDecls);
12526 for (unsigned i = 0; i < UniqueDecls; ++i)
12527 ListsPerDecl.push_back(Record.readInt());
12528 C->setDeclNumLists(ListsPerDecl);
12529
12530 SmallVector<unsigned, 32> ListSizes;
12531 ListSizes.reserve(TotalLists);
12532 for (unsigned i = 0; i < TotalLists; ++i)
12533 ListSizes.push_back(Record.readInt());
12534 C->setComponentListSizes(ListSizes);
12535
12536 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12537 Components.reserve(TotalComponents);
12538 for (unsigned i = 0; i < TotalComponents; ++i) {
12539 Expr *AssociatedExprPr = Record.readExpr();
12540 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12541 Components.emplace_back(AssociatedExprPr, AssociatedDecl,
12542 /*IsNonContiguous=*/false);
12543 }
12544 C->setComponents(Components, ListSizes);
12545}
12546
12547void OMPClauseReader::VisitOMPAllocateClause(OMPAllocateClause *C) {
12548 C->setFirstAllocateModifier(Record.readEnum<OpenMPAllocateClauseModifier>());
12549 C->setSecondAllocateModifier(Record.readEnum<OpenMPAllocateClauseModifier>());
12550 C->setLParenLoc(Record.readSourceLocation());
12551 C->setColonLoc(Record.readSourceLocation());
12552 C->setAllocator(Record.readSubExpr());
12553 C->setAlignment(Record.readSubExpr());
12554 unsigned NumVars = C->varlist_size();
12555 SmallVector<Expr *, 16> Vars;
12556 Vars.reserve(NumVars);
12557 for (unsigned i = 0; i != NumVars; ++i)
12558 Vars.push_back(Record.readSubExpr());
12559 C->setVarRefs(Vars);
12560}
12561
12562void OMPClauseReader::VisitOMPNumTeamsClause(OMPNumTeamsClause *C) {
12564 C->setLParenLoc(Record.readSourceLocation());
12565 unsigned NumVars = C->varlist_size();
12566 SmallVector<Expr *, 16> Vars;
12567 Vars.reserve(NumVars);
12568 for (unsigned I = 0; I != NumVars; ++I)
12569 Vars.push_back(Record.readSubExpr());
12570 C->setVarRefs(Vars);
12571}
12572
12573void OMPClauseReader::VisitOMPThreadLimitClause(OMPThreadLimitClause *C) {
12575 C->setLParenLoc(Record.readSourceLocation());
12576 unsigned NumVars = C->varlist_size();
12577 SmallVector<Expr *, 16> Vars;
12578 Vars.reserve(NumVars);
12579 for (unsigned I = 0; I != NumVars; ++I)
12580 Vars.push_back(Record.readSubExpr());
12581 C->setVarRefs(Vars);
12582}
12583
12584void OMPClauseReader::VisitOMPPriorityClause(OMPPriorityClause *C) {
12586 C->setPriority(Record.readSubExpr());
12587 C->setLParenLoc(Record.readSourceLocation());
12588}
12589
12590void OMPClauseReader::VisitOMPGrainsizeClause(OMPGrainsizeClause *C) {
12592 C->setModifier(Record.readEnum<OpenMPGrainsizeClauseModifier>());
12593 C->setGrainsize(Record.readSubExpr());
12594 C->setModifierLoc(Record.readSourceLocation());
12595 C->setLParenLoc(Record.readSourceLocation());
12596}
12597
12598void OMPClauseReader::VisitOMPNumTasksClause(OMPNumTasksClause *C) {
12600 C->setModifier(Record.readEnum<OpenMPNumTasksClauseModifier>());
12601 C->setNumTasks(Record.readSubExpr());
12602 C->setModifierLoc(Record.readSourceLocation());
12603 C->setLParenLoc(Record.readSourceLocation());
12604}
12605
12606void OMPClauseReader::VisitOMPHintClause(OMPHintClause *C) {
12607 C->setHint(Record.readSubExpr());
12608 C->setLParenLoc(Record.readSourceLocation());
12609}
12610
12611void OMPClauseReader::VisitOMPDistScheduleClause(OMPDistScheduleClause *C) {
12613 C->setDistScheduleKind(
12614 static_cast<OpenMPDistScheduleClauseKind>(Record.readInt()));
12615 C->setChunkSize(Record.readSubExpr());
12616 C->setLParenLoc(Record.readSourceLocation());
12617 C->setDistScheduleKindLoc(Record.readSourceLocation());
12618 C->setCommaLoc(Record.readSourceLocation());
12619}
12620
12621void OMPClauseReader::VisitOMPDefaultmapClause(OMPDefaultmapClause *C) {
12622 C->setDefaultmapKind(
12623 static_cast<OpenMPDefaultmapClauseKind>(Record.readInt()));
12624 C->setDefaultmapModifier(
12625 static_cast<OpenMPDefaultmapClauseModifier>(Record.readInt()));
12626 C->setLParenLoc(Record.readSourceLocation());
12627 C->setDefaultmapModifierLoc(Record.readSourceLocation());
12628 C->setDefaultmapKindLoc(Record.readSourceLocation());
12629}
12630
12631void OMPClauseReader::VisitOMPToClause(OMPToClause *C) {
12632 C->setLParenLoc(Record.readSourceLocation());
12633 for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) {
12634 C->setMotionModifier(
12635 I, static_cast<OpenMPMotionModifierKind>(Record.readInt()));
12636 C->setMotionModifierLoc(I, Record.readSourceLocation());
12637 if (C->getMotionModifier(I) == OMPC_MOTION_MODIFIER_iterator)
12638 C->setIteratorModifier(Record.readExpr());
12639 }
12640 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
12641 C->setMapperIdInfo(Record.readDeclarationNameInfo());
12642 C->setColonLoc(Record.readSourceLocation());
12643 auto NumVars = C->varlist_size();
12644 auto UniqueDecls = C->getUniqueDeclarationsNum();
12645 auto TotalLists = C->getTotalComponentListNum();
12646 auto TotalComponents = C->getTotalComponentsNum();
12647
12648 SmallVector<Expr *, 16> Vars;
12649 Vars.reserve(NumVars);
12650 for (unsigned i = 0; i != NumVars; ++i)
12651 Vars.push_back(Record.readSubExpr());
12652 C->setVarRefs(Vars);
12653
12654 SmallVector<Expr *, 16> UDMappers;
12655 UDMappers.reserve(NumVars);
12656 for (unsigned I = 0; I < NumVars; ++I)
12657 UDMappers.push_back(Record.readSubExpr());
12658 C->setUDMapperRefs(UDMappers);
12659
12660 SmallVector<ValueDecl *, 16> Decls;
12661 Decls.reserve(UniqueDecls);
12662 for (unsigned i = 0; i < UniqueDecls; ++i)
12663 Decls.push_back(Record.readDeclAs<ValueDecl>());
12664 C->setUniqueDecls(Decls);
12665
12666 SmallVector<unsigned, 16> ListsPerDecl;
12667 ListsPerDecl.reserve(UniqueDecls);
12668 for (unsigned i = 0; i < UniqueDecls; ++i)
12669 ListsPerDecl.push_back(Record.readInt());
12670 C->setDeclNumLists(ListsPerDecl);
12671
12672 SmallVector<unsigned, 32> ListSizes;
12673 ListSizes.reserve(TotalLists);
12674 for (unsigned i = 0; i < TotalLists; ++i)
12675 ListSizes.push_back(Record.readInt());
12676 C->setComponentListSizes(ListSizes);
12677
12678 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12679 Components.reserve(TotalComponents);
12680 for (unsigned i = 0; i < TotalComponents; ++i) {
12681 Expr *AssociatedExprPr = Record.readSubExpr();
12682 bool IsNonContiguous = Record.readBool();
12683 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12684 Components.emplace_back(AssociatedExprPr, AssociatedDecl, IsNonContiguous);
12685 }
12686 C->setComponents(Components, ListSizes);
12687}
12688
12689void OMPClauseReader::VisitOMPFromClause(OMPFromClause *C) {
12690 C->setLParenLoc(Record.readSourceLocation());
12691 for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) {
12692 C->setMotionModifier(
12693 I, static_cast<OpenMPMotionModifierKind>(Record.readInt()));
12694 C->setMotionModifierLoc(I, Record.readSourceLocation());
12695 if (C->getMotionModifier(I) == OMPC_MOTION_MODIFIER_iterator)
12696 C->setIteratorModifier(Record.readExpr());
12697 }
12698 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
12699 C->setMapperIdInfo(Record.readDeclarationNameInfo());
12700 C->setColonLoc(Record.readSourceLocation());
12701 auto NumVars = C->varlist_size();
12702 auto UniqueDecls = C->getUniqueDeclarationsNum();
12703 auto TotalLists = C->getTotalComponentListNum();
12704 auto TotalComponents = C->getTotalComponentsNum();
12705
12706 SmallVector<Expr *, 16> Vars;
12707 Vars.reserve(NumVars);
12708 for (unsigned i = 0; i != NumVars; ++i)
12709 Vars.push_back(Record.readSubExpr());
12710 C->setVarRefs(Vars);
12711
12712 SmallVector<Expr *, 16> UDMappers;
12713 UDMappers.reserve(NumVars);
12714 for (unsigned I = 0; I < NumVars; ++I)
12715 UDMappers.push_back(Record.readSubExpr());
12716 C->setUDMapperRefs(UDMappers);
12717
12718 SmallVector<ValueDecl *, 16> Decls;
12719 Decls.reserve(UniqueDecls);
12720 for (unsigned i = 0; i < UniqueDecls; ++i)
12721 Decls.push_back(Record.readDeclAs<ValueDecl>());
12722 C->setUniqueDecls(Decls);
12723
12724 SmallVector<unsigned, 16> ListsPerDecl;
12725 ListsPerDecl.reserve(UniqueDecls);
12726 for (unsigned i = 0; i < UniqueDecls; ++i)
12727 ListsPerDecl.push_back(Record.readInt());
12728 C->setDeclNumLists(ListsPerDecl);
12729
12730 SmallVector<unsigned, 32> ListSizes;
12731 ListSizes.reserve(TotalLists);
12732 for (unsigned i = 0; i < TotalLists; ++i)
12733 ListSizes.push_back(Record.readInt());
12734 C->setComponentListSizes(ListSizes);
12735
12736 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12737 Components.reserve(TotalComponents);
12738 for (unsigned i = 0; i < TotalComponents; ++i) {
12739 Expr *AssociatedExprPr = Record.readSubExpr();
12740 bool IsNonContiguous = Record.readBool();
12741 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12742 Components.emplace_back(AssociatedExprPr, AssociatedDecl, IsNonContiguous);
12743 }
12744 C->setComponents(Components, ListSizes);
12745}
12746
12747void OMPClauseReader::VisitOMPUseDevicePtrClause(OMPUseDevicePtrClause *C) {
12748 C->setLParenLoc(Record.readSourceLocation());
12749 C->setFallbackModifier(Record.readEnum<OpenMPUseDevicePtrFallbackModifier>());
12750 C->setFallbackModifierLoc(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 for (unsigned i = 0; i != NumVars; ++i)
12763 Vars.push_back(Record.readSubExpr());
12764 C->setPrivateCopies(Vars);
12765 Vars.clear();
12766 for (unsigned i = 0; i != NumVars; ++i)
12767 Vars.push_back(Record.readSubExpr());
12768 C->setInits(Vars);
12769
12770 SmallVector<ValueDecl *, 16> Decls;
12771 Decls.reserve(UniqueDecls);
12772 for (unsigned i = 0; i < UniqueDecls; ++i)
12773 Decls.push_back(Record.readDeclAs<ValueDecl>());
12774 C->setUniqueDecls(Decls);
12775
12776 SmallVector<unsigned, 16> ListsPerDecl;
12777 ListsPerDecl.reserve(UniqueDecls);
12778 for (unsigned i = 0; i < UniqueDecls; ++i)
12779 ListsPerDecl.push_back(Record.readInt());
12780 C->setDeclNumLists(ListsPerDecl);
12781
12782 SmallVector<unsigned, 32> ListSizes;
12783 ListSizes.reserve(TotalLists);
12784 for (unsigned i = 0; i < TotalLists; ++i)
12785 ListSizes.push_back(Record.readInt());
12786 C->setComponentListSizes(ListSizes);
12787
12788 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12789 Components.reserve(TotalComponents);
12790 for (unsigned i = 0; i < TotalComponents; ++i) {
12791 auto *AssociatedExprPr = Record.readSubExpr();
12792 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12793 Components.emplace_back(AssociatedExprPr, AssociatedDecl,
12794 /*IsNonContiguous=*/false);
12795 }
12796 C->setComponents(Components, ListSizes);
12797}
12798
12799void OMPClauseReader::VisitOMPUseDeviceAddrClause(OMPUseDeviceAddrClause *C) {
12800 C->setLParenLoc(Record.readSourceLocation());
12801 auto NumVars = C->varlist_size();
12802 auto UniqueDecls = C->getUniqueDeclarationsNum();
12803 auto TotalLists = C->getTotalComponentListNum();
12804 auto TotalComponents = C->getTotalComponentsNum();
12805
12806 SmallVector<Expr *, 16> Vars;
12807 Vars.reserve(NumVars);
12808 for (unsigned i = 0; i != NumVars; ++i)
12809 Vars.push_back(Record.readSubExpr());
12810 C->setVarRefs(Vars);
12811
12812 SmallVector<ValueDecl *, 16> Decls;
12813 Decls.reserve(UniqueDecls);
12814 for (unsigned i = 0; i < UniqueDecls; ++i)
12815 Decls.push_back(Record.readDeclAs<ValueDecl>());
12816 C->setUniqueDecls(Decls);
12817
12818 SmallVector<unsigned, 16> ListsPerDecl;
12819 ListsPerDecl.reserve(UniqueDecls);
12820 for (unsigned i = 0; i < UniqueDecls; ++i)
12821 ListsPerDecl.push_back(Record.readInt());
12822 C->setDeclNumLists(ListsPerDecl);
12823
12824 SmallVector<unsigned, 32> ListSizes;
12825 ListSizes.reserve(TotalLists);
12826 for (unsigned i = 0; i < TotalLists; ++i)
12827 ListSizes.push_back(Record.readInt());
12828 C->setComponentListSizes(ListSizes);
12829
12830 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12831 Components.reserve(TotalComponents);
12832 for (unsigned i = 0; i < TotalComponents; ++i) {
12833 Expr *AssociatedExpr = Record.readSubExpr();
12834 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12835 Components.emplace_back(AssociatedExpr, AssociatedDecl,
12836 /*IsNonContiguous*/ false);
12837 }
12838 C->setComponents(Components, ListSizes);
12839}
12840
12841void OMPClauseReader::VisitOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
12842 C->setLParenLoc(Record.readSourceLocation());
12843 auto NumVars = C->varlist_size();
12844 auto UniqueDecls = C->getUniqueDeclarationsNum();
12845 auto TotalLists = C->getTotalComponentListNum();
12846 auto TotalComponents = C->getTotalComponentsNum();
12847
12848 SmallVector<Expr *, 16> Vars;
12849 Vars.reserve(NumVars);
12850 for (unsigned i = 0; i != NumVars; ++i)
12851 Vars.push_back(Record.readSubExpr());
12852 C->setVarRefs(Vars);
12853 Vars.clear();
12854
12855 SmallVector<ValueDecl *, 16> Decls;
12856 Decls.reserve(UniqueDecls);
12857 for (unsigned i = 0; i < UniqueDecls; ++i)
12858 Decls.push_back(Record.readDeclAs<ValueDecl>());
12859 C->setUniqueDecls(Decls);
12860
12861 SmallVector<unsigned, 16> ListsPerDecl;
12862 ListsPerDecl.reserve(UniqueDecls);
12863 for (unsigned i = 0; i < UniqueDecls; ++i)
12864 ListsPerDecl.push_back(Record.readInt());
12865 C->setDeclNumLists(ListsPerDecl);
12866
12867 SmallVector<unsigned, 32> ListSizes;
12868 ListSizes.reserve(TotalLists);
12869 for (unsigned i = 0; i < TotalLists; ++i)
12870 ListSizes.push_back(Record.readInt());
12871 C->setComponentListSizes(ListSizes);
12872
12873 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12874 Components.reserve(TotalComponents);
12875 for (unsigned i = 0; i < TotalComponents; ++i) {
12876 Expr *AssociatedExpr = Record.readSubExpr();
12877 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12878 Components.emplace_back(AssociatedExpr, AssociatedDecl,
12879 /*IsNonContiguous=*/false);
12880 }
12881 C->setComponents(Components, ListSizes);
12882}
12883
12884void OMPClauseReader::VisitOMPHasDeviceAddrClause(OMPHasDeviceAddrClause *C) {
12885 C->setLParenLoc(Record.readSourceLocation());
12886 auto NumVars = C->varlist_size();
12887 auto UniqueDecls = C->getUniqueDeclarationsNum();
12888 auto TotalLists = C->getTotalComponentListNum();
12889 auto TotalComponents = C->getTotalComponentsNum();
12890
12891 SmallVector<Expr *, 16> Vars;
12892 Vars.reserve(NumVars);
12893 for (unsigned I = 0; I != NumVars; ++I)
12894 Vars.push_back(Record.readSubExpr());
12895 C->setVarRefs(Vars);
12896 Vars.clear();
12897
12898 SmallVector<ValueDecl *, 16> Decls;
12899 Decls.reserve(UniqueDecls);
12900 for (unsigned I = 0; I < UniqueDecls; ++I)
12901 Decls.push_back(Record.readDeclAs<ValueDecl>());
12902 C->setUniqueDecls(Decls);
12903
12904 SmallVector<unsigned, 16> ListsPerDecl;
12905 ListsPerDecl.reserve(UniqueDecls);
12906 for (unsigned I = 0; I < UniqueDecls; ++I)
12907 ListsPerDecl.push_back(Record.readInt());
12908 C->setDeclNumLists(ListsPerDecl);
12909
12910 SmallVector<unsigned, 32> ListSizes;
12911 ListSizes.reserve(TotalLists);
12912 for (unsigned i = 0; i < TotalLists; ++i)
12913 ListSizes.push_back(Record.readInt());
12914 C->setComponentListSizes(ListSizes);
12915
12916 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12917 Components.reserve(TotalComponents);
12918 for (unsigned I = 0; I < TotalComponents; ++I) {
12919 Expr *AssociatedExpr = Record.readSubExpr();
12920 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12921 Components.emplace_back(AssociatedExpr, AssociatedDecl,
12922 /*IsNonContiguous=*/false);
12923 }
12924 C->setComponents(Components, ListSizes);
12925}
12926
12927void OMPClauseReader::VisitOMPNontemporalClause(OMPNontemporalClause *C) {
12928 C->setLParenLoc(Record.readSourceLocation());
12929 unsigned NumVars = C->varlist_size();
12930 SmallVector<Expr *, 16> Vars;
12931 Vars.reserve(NumVars);
12932 for (unsigned i = 0; i != NumVars; ++i)
12933 Vars.push_back(Record.readSubExpr());
12934 C->setVarRefs(Vars);
12935 Vars.clear();
12936 Vars.reserve(NumVars);
12937 for (unsigned i = 0; i != NumVars; ++i)
12938 Vars.push_back(Record.readSubExpr());
12939 C->setPrivateRefs(Vars);
12940}
12941
12942void OMPClauseReader::VisitOMPInclusiveClause(OMPInclusiveClause *C) {
12943 C->setLParenLoc(Record.readSourceLocation());
12944 unsigned NumVars = C->varlist_size();
12945 SmallVector<Expr *, 16> Vars;
12946 Vars.reserve(NumVars);
12947 for (unsigned i = 0; i != NumVars; ++i)
12948 Vars.push_back(Record.readSubExpr());
12949 C->setVarRefs(Vars);
12950}
12951
12952void OMPClauseReader::VisitOMPExclusiveClause(OMPExclusiveClause *C) {
12953 C->setLParenLoc(Record.readSourceLocation());
12954 unsigned NumVars = C->varlist_size();
12955 SmallVector<Expr *, 16> Vars;
12956 Vars.reserve(NumVars);
12957 for (unsigned i = 0; i != NumVars; ++i)
12958 Vars.push_back(Record.readSubExpr());
12959 C->setVarRefs(Vars);
12960}
12961
12962void OMPClauseReader::VisitOMPUsesAllocatorsClause(OMPUsesAllocatorsClause *C) {
12963 C->setLParenLoc(Record.readSourceLocation());
12964 unsigned NumOfAllocators = C->getNumberOfAllocators();
12965 SmallVector<OMPUsesAllocatorsClause::Data, 4> Data;
12966 Data.reserve(NumOfAllocators);
12967 for (unsigned I = 0; I != NumOfAllocators; ++I) {
12968 OMPUsesAllocatorsClause::Data &D = Data.emplace_back();
12969 D.Allocator = Record.readSubExpr();
12970 D.AllocatorTraits = Record.readSubExpr();
12971 D.LParenLoc = Record.readSourceLocation();
12972 D.RParenLoc = Record.readSourceLocation();
12973 }
12974 C->setAllocatorsData(Data);
12975}
12976
12977void OMPClauseReader::VisitOMPAffinityClause(OMPAffinityClause *C) {
12978 C->setLParenLoc(Record.readSourceLocation());
12979 C->setModifier(Record.readSubExpr());
12980 C->setColonLoc(Record.readSourceLocation());
12981 unsigned NumOfLocators = C->varlist_size();
12982 SmallVector<Expr *, 4> Locators;
12983 Locators.reserve(NumOfLocators);
12984 for (unsigned I = 0; I != NumOfLocators; ++I)
12985 Locators.push_back(Record.readSubExpr());
12986 C->setVarRefs(Locators);
12987}
12988
12989void OMPClauseReader::VisitOMPOrderClause(OMPOrderClause *C) {
12990 C->setKind(Record.readEnum<OpenMPOrderClauseKind>());
12991 C->setModifier(Record.readEnum<OpenMPOrderClauseModifier>());
12992 C->setLParenLoc(Record.readSourceLocation());
12993 C->setKindKwLoc(Record.readSourceLocation());
12994 C->setModifierKwLoc(Record.readSourceLocation());
12995}
12996
12997void OMPClauseReader::VisitOMPFilterClause(OMPFilterClause *C) {
12999 C->setThreadID(Record.readSubExpr());
13000 C->setLParenLoc(Record.readSourceLocation());
13001}
13002
13003void OMPClauseReader::VisitOMPBindClause(OMPBindClause *C) {
13004 C->setBindKind(Record.readEnum<OpenMPBindClauseKind>());
13005 C->setLParenLoc(Record.readSourceLocation());
13006 C->setBindKindLoc(Record.readSourceLocation());
13007}
13008
13009void OMPClauseReader::VisitOMPAlignClause(OMPAlignClause *C) {
13010 C->setAlignment(Record.readExpr());
13011 C->setLParenLoc(Record.readSourceLocation());
13012}
13013
13014void OMPClauseReader::VisitOMPXDynCGroupMemClause(OMPXDynCGroupMemClause *C) {
13016 C->setSize(Record.readSubExpr());
13017 C->setLParenLoc(Record.readSourceLocation());
13018}
13019
13020void OMPClauseReader::VisitOMPDynGroupprivateClause(
13021 OMPDynGroupprivateClause *C) {
13023 C->setDynGroupprivateModifier(
13024 Record.readEnum<OpenMPDynGroupprivateClauseModifier>());
13025 C->setDynGroupprivateFallbackModifier(
13027 C->setSize(Record.readSubExpr());
13028 C->setLParenLoc(Record.readSourceLocation());
13029 C->setDynGroupprivateModifierLoc(Record.readSourceLocation());
13030 C->setDynGroupprivateFallbackModifierLoc(Record.readSourceLocation());
13031}
13032
13033void OMPClauseReader::VisitOMPDoacrossClause(OMPDoacrossClause *C) {
13034 C->setLParenLoc(Record.readSourceLocation());
13035 C->setDependenceType(
13036 static_cast<OpenMPDoacrossClauseModifier>(Record.readInt()));
13037 C->setDependenceLoc(Record.readSourceLocation());
13038 C->setColonLoc(Record.readSourceLocation());
13039 unsigned NumVars = C->varlist_size();
13040 SmallVector<Expr *, 16> Vars;
13041 Vars.reserve(NumVars);
13042 for (unsigned I = 0; I != NumVars; ++I)
13043 Vars.push_back(Record.readSubExpr());
13044 C->setVarRefs(Vars);
13045 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
13046 C->setLoopData(I, Record.readSubExpr());
13047}
13048
13049void OMPClauseReader::VisitOMPXAttributeClause(OMPXAttributeClause *C) {
13050 AttrVec Attrs;
13051 Record.readAttributes(Attrs);
13052 C->setAttrs(Attrs);
13053 C->setLocStart(Record.readSourceLocation());
13054 C->setLParenLoc(Record.readSourceLocation());
13055 C->setLocEnd(Record.readSourceLocation());
13056}
13057
13058void OMPClauseReader::VisitOMPXBareClause(OMPXBareClause *C) {}
13059
13062 TI.Sets.resize(readUInt32());
13063 for (auto &Set : TI.Sets) {
13065 Set.Selectors.resize(readUInt32());
13066 for (auto &Selector : Set.Selectors) {
13068 Selector.ScoreOrCondition = nullptr;
13069 if (readBool())
13070 Selector.ScoreOrCondition = readExprRef();
13071 Selector.Properties.resize(readUInt32());
13072 for (auto &Property : Selector.Properties)
13074 }
13075 }
13076 return &TI;
13077}
13078
13080 if (!Data)
13081 return;
13082 if (Reader->ReadingKind == ASTReader::Read_Stmt) {
13083 // Skip NumClauses, NumChildren and HasAssociatedStmt fields.
13084 skipInts(3);
13085 }
13086 SmallVector<OMPClause *, 4> Clauses(Data->getNumClauses());
13087 for (unsigned I = 0, E = Data->getNumClauses(); I < E; ++I)
13088 Clauses[I] = readOMPClause();
13089 Data->setClauses(Clauses);
13090 if (Data->hasAssociatedStmt())
13091 Data->setAssociatedStmt(readStmt());
13092 for (unsigned I = 0, E = Data->getNumChildren(); I < E; ++I)
13093 Data->getChildren()[I] = readStmt();
13094}
13095
13097 unsigned NumVars = readInt();
13099 for (unsigned I = 0; I < NumVars; ++I)
13100 VarList.push_back(readExpr());
13101 return VarList;
13102}
13103
13105 unsigned NumExprs = readInt();
13107 for (unsigned I = 0; I < NumExprs; ++I)
13108 ExprList.push_back(readSubExpr());
13109 return ExprList;
13110}
13111
13116
13117 switch (ClauseKind) {
13119 SourceLocation LParenLoc = readSourceLocation();
13121 return OpenACCDefaultClause::Create(getContext(), DCK, BeginLoc, LParenLoc,
13122 EndLoc);
13123 }
13124 case OpenACCClauseKind::If: {
13125 SourceLocation LParenLoc = readSourceLocation();
13126 Expr *CondExpr = readSubExpr();
13127 return OpenACCIfClause::Create(getContext(), BeginLoc, LParenLoc, CondExpr,
13128 EndLoc);
13129 }
13131 SourceLocation LParenLoc = readSourceLocation();
13132 bool isConditionExprClause = readBool();
13133 if (isConditionExprClause) {
13134 Expr *CondExpr = readBool() ? readSubExpr() : nullptr;
13135 return OpenACCSelfClause::Create(getContext(), BeginLoc, LParenLoc,
13136 CondExpr, EndLoc);
13137 }
13138 unsigned NumVars = readInt();
13140 for (unsigned I = 0; I < NumVars; ++I)
13141 VarList.push_back(readSubExpr());
13142 return OpenACCSelfClause::Create(getContext(), BeginLoc, LParenLoc, VarList,
13143 EndLoc);
13144 }
13146 SourceLocation LParenLoc = readSourceLocation();
13147 unsigned NumClauses = readInt();
13149 for (unsigned I = 0; I < NumClauses; ++I)
13150 IntExprs.push_back(readSubExpr());
13151 return OpenACCNumGangsClause::Create(getContext(), BeginLoc, LParenLoc,
13152 IntExprs, EndLoc);
13153 }
13155 SourceLocation LParenLoc = readSourceLocation();
13156 Expr *IntExpr = readSubExpr();
13157 return OpenACCNumWorkersClause::Create(getContext(), BeginLoc, LParenLoc,
13158 IntExpr, EndLoc);
13159 }
13161 SourceLocation LParenLoc = readSourceLocation();
13162 Expr *IntExpr = readSubExpr();
13163 return OpenACCDeviceNumClause::Create(getContext(), BeginLoc, LParenLoc,
13164 IntExpr, EndLoc);
13165 }
13167 SourceLocation LParenLoc = readSourceLocation();
13168 Expr *IntExpr = readSubExpr();
13169 return OpenACCDefaultAsyncClause::Create(getContext(), BeginLoc, LParenLoc,
13170 IntExpr, EndLoc);
13171 }
13173 SourceLocation LParenLoc = readSourceLocation();
13174 Expr *IntExpr = readSubExpr();
13175 return OpenACCVectorLengthClause::Create(getContext(), BeginLoc, LParenLoc,
13176 IntExpr, EndLoc);
13177 }
13179 SourceLocation LParenLoc = readSourceLocation();
13181
13183 for (unsigned I = 0; I < VarList.size(); ++I) {
13184 static_assert(sizeof(OpenACCPrivateRecipe) == 1 * sizeof(int *));
13185 VarDecl *Alloca = readDeclAs<VarDecl>();
13186 RecipeList.push_back({Alloca});
13187 }
13188
13189 return OpenACCPrivateClause::Create(getContext(), BeginLoc, LParenLoc,
13190 VarList, RecipeList, EndLoc);
13191 }
13193 SourceLocation LParenLoc = readSourceLocation();
13195 return OpenACCHostClause::Create(getContext(), BeginLoc, LParenLoc, VarList,
13196 EndLoc);
13197 }
13199 SourceLocation LParenLoc = readSourceLocation();
13201 return OpenACCDeviceClause::Create(getContext(), BeginLoc, LParenLoc,
13202 VarList, EndLoc);
13203 }
13205 SourceLocation LParenLoc = readSourceLocation();
13208 for (unsigned I = 0; I < VarList.size(); ++I) {
13209 static_assert(sizeof(OpenACCFirstPrivateRecipe) == 2 * sizeof(int *));
13210 VarDecl *Recipe = readDeclAs<VarDecl>();
13211 VarDecl *RecipeTemp = readDeclAs<VarDecl>();
13212 RecipeList.push_back({Recipe, RecipeTemp});
13213 }
13214
13215 return OpenACCFirstPrivateClause::Create(getContext(), BeginLoc, LParenLoc,
13216 VarList, RecipeList, EndLoc);
13217 }
13219 SourceLocation LParenLoc = readSourceLocation();
13221 return OpenACCAttachClause::Create(getContext(), BeginLoc, LParenLoc,
13222 VarList, EndLoc);
13223 }
13225 SourceLocation LParenLoc = readSourceLocation();
13227 return OpenACCDetachClause::Create(getContext(), BeginLoc, LParenLoc,
13228 VarList, EndLoc);
13229 }
13231 SourceLocation LParenLoc = readSourceLocation();
13233 return OpenACCDeleteClause::Create(getContext(), BeginLoc, LParenLoc,
13234 VarList, EndLoc);
13235 }
13237 SourceLocation LParenLoc = readSourceLocation();
13239 return OpenACCUseDeviceClause::Create(getContext(), BeginLoc, LParenLoc,
13240 VarList, EndLoc);
13241 }
13243 SourceLocation LParenLoc = readSourceLocation();
13245 return OpenACCDevicePtrClause::Create(getContext(), BeginLoc, LParenLoc,
13246 VarList, EndLoc);
13247 }
13249 SourceLocation LParenLoc = readSourceLocation();
13251 return OpenACCNoCreateClause::Create(getContext(), BeginLoc, LParenLoc,
13252 VarList, EndLoc);
13253 }
13255 SourceLocation LParenLoc = readSourceLocation();
13257 return OpenACCPresentClause::Create(getContext(), BeginLoc, LParenLoc,
13258 VarList, EndLoc);
13259 }
13263 SourceLocation LParenLoc = readSourceLocation();
13266 return OpenACCCopyClause::Create(getContext(), ClauseKind, BeginLoc,
13267 LParenLoc, ModList, VarList, EndLoc);
13268 }
13272 SourceLocation LParenLoc = readSourceLocation();
13275 return OpenACCCopyInClause::Create(getContext(), ClauseKind, BeginLoc,
13276 LParenLoc, ModList, VarList, EndLoc);
13277 }
13281 SourceLocation LParenLoc = readSourceLocation();
13284 return OpenACCCopyOutClause::Create(getContext(), ClauseKind, BeginLoc,
13285 LParenLoc, ModList, VarList, EndLoc);
13286 }
13290 SourceLocation LParenLoc = readSourceLocation();
13293 return OpenACCCreateClause::Create(getContext(), ClauseKind, BeginLoc,
13294 LParenLoc, ModList, VarList, EndLoc);
13295 }
13297 SourceLocation LParenLoc = readSourceLocation();
13298 Expr *AsyncExpr = readBool() ? readSubExpr() : nullptr;
13299 return OpenACCAsyncClause::Create(getContext(), BeginLoc, LParenLoc,
13300 AsyncExpr, EndLoc);
13301 }
13303 SourceLocation LParenLoc = readSourceLocation();
13304 Expr *DevNumExpr = readBool() ? readSubExpr() : nullptr;
13305 SourceLocation QueuesLoc = readSourceLocation();
13307 return OpenACCWaitClause::Create(getContext(), BeginLoc, LParenLoc,
13308 DevNumExpr, QueuesLoc, QueueIdExprs,
13309 EndLoc);
13310 }
13313 SourceLocation LParenLoc = readSourceLocation();
13315 unsigned NumArchs = readInt();
13316
13317 for (unsigned I = 0; I < NumArchs; ++I) {
13318 IdentifierInfo *Ident = readBool() ? readIdentifier() : nullptr;
13320 Archs.emplace_back(Loc, Ident);
13321 }
13322
13323 return OpenACCDeviceTypeClause::Create(getContext(), ClauseKind, BeginLoc,
13324 LParenLoc, Archs, EndLoc);
13325 }
13327 SourceLocation LParenLoc = readSourceLocation();
13331
13332 for (unsigned I = 0; I < VarList.size(); ++I) {
13333 VarDecl *Recipe = readDeclAs<VarDecl>();
13334
13335 static_assert(sizeof(OpenACCReductionRecipe::CombinerRecipe) ==
13336 3 * sizeof(int *));
13337
13339 unsigned NumCombiners = readInt();
13340 for (unsigned I = 0; I < NumCombiners; ++I) {
13343 Expr *Op = readExpr();
13344
13345 Combiners.push_back({LHS, RHS, Op});
13346 }
13347
13348 RecipeList.push_back({Recipe, Combiners});
13349 }
13350
13351 return OpenACCReductionClause::Create(getContext(), BeginLoc, LParenLoc, Op,
13352 VarList, RecipeList, EndLoc);
13353 }
13355 return OpenACCSeqClause::Create(getContext(), BeginLoc, EndLoc);
13357 return OpenACCNoHostClause::Create(getContext(), BeginLoc, EndLoc);
13359 return OpenACCFinalizeClause::Create(getContext(), BeginLoc, EndLoc);
13361 return OpenACCIfPresentClause::Create(getContext(), BeginLoc, EndLoc);
13363 return OpenACCIndependentClause::Create(getContext(), BeginLoc, EndLoc);
13365 return OpenACCAutoClause::Create(getContext(), BeginLoc, EndLoc);
13367 SourceLocation LParenLoc = readSourceLocation();
13368 bool HasForce = readBool();
13369 Expr *LoopCount = readSubExpr();
13370 return OpenACCCollapseClause::Create(getContext(), BeginLoc, LParenLoc,
13371 HasForce, LoopCount, EndLoc);
13372 }
13374 SourceLocation LParenLoc = readSourceLocation();
13375 unsigned NumClauses = readInt();
13376 llvm::SmallVector<Expr *> SizeExprs;
13377 for (unsigned I = 0; I < NumClauses; ++I)
13378 SizeExprs.push_back(readSubExpr());
13379 return OpenACCTileClause::Create(getContext(), BeginLoc, LParenLoc,
13380 SizeExprs, EndLoc);
13381 }
13383 SourceLocation LParenLoc = readSourceLocation();
13384 unsigned NumExprs = readInt();
13387 for (unsigned I = 0; I < NumExprs; ++I) {
13388 GangKinds.push_back(readEnum<OpenACCGangKind>());
13389 // Can't use `readSubExpr` because this is usable from a 'decl' construct.
13390 Exprs.push_back(readExpr());
13391 }
13392 return OpenACCGangClause::Create(getContext(), BeginLoc, LParenLoc,
13393 GangKinds, Exprs, EndLoc);
13394 }
13396 SourceLocation LParenLoc = readSourceLocation();
13397 Expr *WorkerExpr = readBool() ? readSubExpr() : nullptr;
13398 return OpenACCWorkerClause::Create(getContext(), BeginLoc, LParenLoc,
13399 WorkerExpr, EndLoc);
13400 }
13402 SourceLocation LParenLoc = readSourceLocation();
13403 Expr *VectorExpr = readBool() ? readSubExpr() : nullptr;
13404 return OpenACCVectorClause::Create(getContext(), BeginLoc, LParenLoc,
13405 VectorExpr, EndLoc);
13406 }
13408 SourceLocation LParenLoc = readSourceLocation();
13410 return OpenACCLinkClause::Create(getContext(), BeginLoc, LParenLoc, VarList,
13411 EndLoc);
13412 }
13414 SourceLocation LParenLoc = readSourceLocation();
13417 LParenLoc, VarList, EndLoc);
13418 }
13419
13421 SourceLocation LParenLoc = readSourceLocation();
13422 bool IsString = readBool();
13423 if (IsString)
13424 return OpenACCBindClause::Create(getContext(), BeginLoc, LParenLoc,
13425 cast<StringLiteral>(readExpr()), EndLoc);
13426 return OpenACCBindClause::Create(getContext(), BeginLoc, LParenLoc,
13427 readIdentifier(), EndLoc);
13428 }
13431 llvm_unreachable("Clause serialization not yet implemented");
13432 }
13433 llvm_unreachable("Invalid Clause Kind");
13434}
13435
13438 for (unsigned I = 0; I < Clauses.size(); ++I)
13439 Clauses[I] = readOpenACCClause();
13440}
13441
13442void ASTRecordReader::readOpenACCRoutineDeclAttr(OpenACCRoutineDeclAttr *A) {
13443 unsigned NumVars = readInt();
13444 A->Clauses.resize(NumVars);
13445 readOpenACCClauseList(A->Clauses);
13446}
13447
13448static unsigned getStableHashForModuleName(StringRef PrimaryModuleName) {
13449 // TODO: Maybe it is better to check PrimaryModuleName is a valid
13450 // module name?
13451 llvm::FoldingSetNodeID ID;
13452 ID.AddString(PrimaryModuleName);
13453 return ID.computeStableHash();
13454}
13455
13457 if (!M)
13458 return std::nullopt;
13459
13460 if (M->isHeaderLikeModule())
13461 return std::nullopt;
13462
13463 if (M->isGlobalModule())
13464 return std::nullopt;
13465
13466 StringRef PrimaryModuleName = M->getPrimaryModuleInterfaceName();
13467 return getStableHashForModuleName(PrimaryModuleName);
13468}
Defines the clang::ASTContext interface.
static unsigned moduleKindForDiagnostic(ModuleKind Kind)
static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD, ASTConsumer *Consumer)
Under non-PCH compilation the consumer receives the objc methods before receiving the implementation,...
static bool checkCodegenOptions(const CodeGenOptions &CGOpts, const CodeGenOptions &ExistingCGOpts, StringRef ModuleFilename, DiagnosticsEngine *Diags, bool AllowCompatibleDifferences=true)
static llvm::Error doesntStartWithASTFileMagic(BitstreamCursor &Stream)
Whether Stream doesn't start with the AST file magic number 'CPCH'.
static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags)
static unsigned getModuleFileIndexForTypeID(serialization::TypeID ID)
static void collectMacroDefinitions(const PreprocessorOptions &PPOpts, MacroDefinitionsMap &Macros, SmallVectorImpl< StringRef > *MacroNames=nullptr)
Collect the macro definitions provided by the given preprocessor options.
static void markIdentifierFromAST(ASTReader &Reader, IdentifierInfo &II, bool IsModule)
static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method)
Move the given method to the back of the global list of methods.
static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps)
static bool isInterestingIdentifier(ASTReader &Reader, const IdentifierInfo &II, bool IsModule)
Whether the given identifier is "interesting".
static bool parseModuleFileExtensionMetadata(const SmallVectorImpl< uint64_t > &Record, StringRef Blob, ModuleFileExtensionMetadata &Metadata)
Parse a record and blob containing module file extension metadata.
static Module * getTopImportImplicitModule(ModuleManager &ModuleMgr, Preprocessor &PP)
Return the top import module if it is implicit, nullptr otherwise.
static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts, const PreprocessorOptions &ExistingPPOpts, StringRef ModuleFilename, bool ReadMacros, DiagnosticsEngine *Diags, FileManager &FileMgr, std::string &SuggestedPredefines, const LangOptions &LangOpts, OptionValidation Validation=OptionValidateContradictions)
Check the preprocessor options deserialized from the control block against the preprocessor options i...
static void addMethodsToPool(Sema &S, ArrayRef< ObjCMethodDecl * > Methods, ObjCMethodList &List)
Add the given set of methods to the method list.
static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags, DiagnosticsEngine &Diags, StringRef ModuleFilename, bool IsSystem, bool SystemHeaderWarningsInModule, bool Complain)
static bool isPredefinedType(serialization::TypeID ID)
static bool readBit(unsigned &Bits)
static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags, DiagnosticsEngine &Diags, StringRef ModuleFilename, bool Complain)
static std::optional< Type::TypeClass > getTypeClassForCode(TypeCode code)
static std::pair< unsigned, unsigned > readULEBKeyDataLength(const unsigned char *&P)
Read ULEB-encoded key length and data length.
static unsigned getStableHashForModuleName(StringRef PrimaryModuleName)
static LLVM_DUMP_METHOD void dumpModuleIDMap(StringRef Name, const ContinuousRangeMap< Key, ModuleFile *, InitialCapacity > &Map)
OptionValidation
@ OptionValidateStrictMatches
@ OptionValidateNone
@ OptionValidateContradictions
static bool checkTargetOptions(const TargetOptions &TargetOpts, const TargetOptions &ExistingTargetOpts, StringRef ModuleFilename, DiagnosticsEngine *Diags, bool AllowCompatibleDifferences=true)
Compare the given set of target options against an existing set of target options.
static bool checkLanguageOptions(const LangOptions &LangOpts, const LangOptions &ExistingLangOpts, StringRef ModuleFilename, DiagnosticsEngine *Diags, bool AllowCompatibleDifferences=true)
Compare the given set of language options against an existing set of language options.
static std::pair< StringRef, StringRef > getUnresolvedInputFilenames(const ASTReader::RecordData &Record, const StringRef InputBlob)
#define CHECK_TARGET_OPT(Field, Name)
static ASTFileSignature readASTFileSignature(StringRef PCH)
Reads and return the signature record from PCH's control block, or else returns 0.
static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID)
Given a cursor at the start of an AST file, scan ahead and drop the cursor into the start of the give...
static unsigned getIndexForTypeID(serialization::TypeID ID)
static uint64_t readULEB(const unsigned char *&P)
static bool checkModuleCachePath(FileManager &FileMgr, StringRef ContextHash, StringRef ExistingSpecificModuleCachePath, StringRef ASTFilename, DiagnosticsEngine *Diags, const LangOptions &LangOpts, const PreprocessorOptions &PPOpts, const HeaderSearchOptions &HSOpts, const HeaderSearchOptions &ASTFileHSOpts)
Check that the specified and the existing module cache paths are equivalent.
Defines the clang::ASTSourceDescriptor class, which abstracts clang modules and precompiled header fi...
static StringRef bytes(const std::vector< T, Allocator > &v)
Defines the Diagnostic-related interfaces.
Defines the clang::CommentOptions interface.
static void dump(llvm::raw_ostream &OS, StringRef FunctionName, ArrayRef< CounterExpression > Expressions, ArrayRef< CounterMappingRegion > Regions)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the C++ template declaration subclasses.
Defines the Diagnostic IDs-related interfaces.
static bool hasDefinition(const ObjCObjectPointerType *ObjPtr)
Defines the clang::Expr interface and subclasses for C++ expressions.
Defines the clang::FileManager interface and associated types.
Defines the clang::FileSystemOptions interface.
Token Tok
The Token.
FormatToken * Previous
The previous token in the unwrapped line.
FormatToken * Next
The next token in the unwrapped line.
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the clang::LangOptions interface.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Record Record
Definition MachO.h:31
Defines the clang::MacroInfo and clang::MacroDirective classes.
Defines the clang::Module class, which describes a module in the source code.
Defines types useful for describing an Objective-C runtime.
#define SM(sm)
Defines some OpenACC-specific enums and functions.
This file defines OpenMP AST classes for clauses.
Defines some OpenMP-specific enums and functions.
Defines an enumeration for C++ overloaded operators.
Defines the clang::Preprocessor interface.
Defines the clang::SanitizerKind enum.
This file declares semantic analysis for CUDA constructs.
This file declares semantic analysis for Objective-C.
Defines the clang::SourceLocation class and associated facilities.
Defines implementation details of the clang::SourceManager class.
Defines the SourceManager interface.
Defines various enumerations that describe declaration and type specifiers.
Defines the clang::TargetOptions class.
#define IMPORT(DERIVED, BASE)
Definition Template.h:630
Defines the clang::TokenKind enum and support functions.
Defines the clang::TypeLoc interface and its subclasses.
C Language Family Type Representation.
Defines version macros and version-related utility functions for Clang.
__DEVICE__ void * memcpy(void *__a, const void *__b, size_t __c)
__device__ __2f16 b
static OMPAffinityClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with the place for N locator items.
static OMPAlignedClause * CreateEmpty(const ASTContext &C, unsigned NumVars)
Creates an empty clause with the place for NumVars variables.
static OMPBindClause * CreateEmpty(const ASTContext &C)
Build an empty 'bind' clause.
Contains data for OpenMP directives: clauses, children expressions/statements (helpers for codegen) a...
static OMPCopyinClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with N variables.
static OMPCopyprivateClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with N variables.
This represents 'defaultmap' clause in the 'pragma omp ...' directive.
static OMPDependClause * CreateEmpty(const ASTContext &C, unsigned N, unsigned NumLoops)
Creates an empty clause with N variables.
static OMPDepobjClause * CreateEmpty(const ASTContext &C)
Creates an empty clause.
This represents 'destroy' clause in the 'pragma omp depobj' directive or the 'pragma omp interop' dir...
This represents 'detach' clause in the 'pragma omp task' directive.
This represents 'device' clause in the 'pragma omp ...' directive.
This represents 'dist_schedule' clause in the 'pragma omp ...' directive.
static OMPDoacrossClause * CreateEmpty(const ASTContext &C, unsigned N, unsigned NumLoops)
Creates an empty clause with N expressions.
This represents 'dyn_groupprivate' clause in 'pragma omp target ...' and 'pragma omp teams ....
static OMPExclusiveClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with the place for N variables.
This represents 'filter' clause in the 'pragma omp ...' directive.
static OMPFlushClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with N variables.
static OMPFromClause * CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes)
Creates an empty clause with the place for NumVars variables.
This represents 'grainsize' clause in the 'pragma omp ...' directive.
static OMPHasDeviceAddrClause * CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes)
Creates an empty clause with the place for NumVars variables.
This represents 'hint' clause in the 'pragma omp ...' directive.
static OMPInclusiveClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with the place for N variables.
static OMPInitClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with N expressions.
static OMPIsDevicePtrClause * CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes)
Creates an empty clause with the place for NumVars variables.
static OMPMapClause * CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes)
Creates an empty clause with the place for NumVars original expressions, NumUniqueDeclarations declar...
This represents 'nocontext' clause in the 'pragma omp ...' directive.
This represents 'nogroup' clause in the 'pragma omp ...' directive.
static OMPNontemporalClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with the place for N variables.
This represents 'novariants' clause in the 'pragma omp ...' directive.
This represents 'num_tasks' clause in the 'pragma omp ...' directive.
static OMPNumTeamsClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with N variables.
This represents 'order' clause in the 'pragma omp ...' directive.
This represents 'priority' clause in the 'pragma omp ...' directive.
This represents 'simd' clause in the 'pragma omp ...' directive.
static OMPThreadLimitClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with N variables.
This represents 'threads' clause in the 'pragma omp ...' directive.
static OMPToClause * CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes)
Creates an empty clause with the place for NumVars variables.
llvm::SmallVector< OMPTraitSet, 2 > Sets
The outermost level of selector sets.
This represents the 'use' clause in 'pragma omp ...' directives.
static OMPUseDeviceAddrClause * CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes)
Creates an empty clause with the place for NumVars variables.
static OMPUseDevicePtrClause * CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes)
Creates an empty clause with the place for NumVars variables.
static OMPUsesAllocatorsClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with the place for N allocators.
This represents 'ompx_attribute' clause in a directive that might generate an outlined function.
This represents 'ompx_bare' clause in the 'pragma omp target teams ...' directive.
This represents 'ompx_dyn_cgroup_mem' clause in the 'pragma omp target ...' directive.
ASTConsumer - This is an abstract interface that should be implemented by clients that read ASTs.
Definition ASTConsumer.h:35
virtual void HandleInterestingDecl(DeclGroupRef D)
HandleInterestingDecl - Handle the specified interesting declaration.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:226
OMPTraitInfo & getNewOMPTraitInfo()
Return a new OMPTraitInfo object owned by this context.
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
void adjustExceptionSpec(FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI, bool AsWritten=false)
Change the exception specification on a function once it is delay-parsed, instantiated,...
const clang::PrintingPolicy & getPrintingPolicy() const
Definition ASTContext.h:851
void deduplicateMergedDefinitionsFor(NamedDecl *ND)
Clean up the merged definition list.
void adjustDeducedFunctionResultType(FunctionDecl *FD, QualType ResultType)
Change the result type of a function type once it is deduced.
void setPrimaryMergedDecl(Decl *D, Decl *Primary)
ASTIdentifierIterator(const ASTReader &Reader, bool SkipModules=false)
StringRef Next() override
Retrieve the next string in the identifier table and advances the iterator for the following string.
Abstract interface for callback invocations by the ASTReader.
Definition ASTReader.h:117
virtual bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, StringRef ModuleFilename, StringRef ContextHash, bool Complain)
Receives the header search options.
Definition ASTReader.h:186
virtual void ReadModuleMapFile(StringRef ModuleMapPath)
Definition ASTReader.h:130
virtual bool needsInputFileVisitation()
Returns true if this ASTReaderListener wants to receive the input files of the AST file via visitInpu...
Definition ASTReader.h:232
virtual bool ReadDiagnosticOptions(DiagnosticOptions &DiagOpts, StringRef ModuleFilename, bool Complain)
Receives the diagnostic options.
Definition ASTReader.h:164
virtual bool ReadTargetOptions(const TargetOptions &TargetOpts, StringRef ModuleFilename, bool Complain, bool AllowCompatibleDifferences)
Receives the target options.
Definition ASTReader.h:154
virtual bool visitInputFile(StringRef Filename, bool isSystem, bool isOverridden, bool isExplicitModule)
if needsInputFileVisitation returns true, this is called for each non-system input file of the AST Fi...
Definition ASTReader.h:244
virtual bool ReadHeaderSearchPaths(const HeaderSearchOptions &HSOpts, bool Complain)
Receives the header search paths.
Definition ASTReader.h:201
virtual bool ReadFileSystemOptions(const FileSystemOptions &FSOpts, bool Complain)
Receives the file system options.
Definition ASTReader.h:173
virtual void visitModuleFile(ModuleFileName Filename, serialization::ModuleKind Kind, bool DirectlyImported)
This is called for each AST file loaded.
Definition ASTReader.h:226
virtual bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, StringRef ModuleFilename, bool ReadMacros, bool Complain, std::string &SuggestedPredefines)
Receives the preprocessor options.
Definition ASTReader.h:214
virtual bool ReadLanguageOptions(const LangOptions &LangOpts, StringRef ModuleFilename, bool Complain, bool AllowCompatibleDifferences)
Receives the language options.
Definition ASTReader.h:135
virtual void ReadModuleName(StringRef ModuleName)
Definition ASTReader.h:129
virtual void ReadCounter(const serialization::ModuleFile &M, uint32_t Value)
Receives COUNTER value.
Definition ASTReader.h:222
virtual bool needsSystemInputFileVisitation()
Returns true if this ASTReaderListener wants to receive the system input files of the AST file via vi...
Definition ASTReader.h:236
virtual bool ReadCodeGenOptions(const CodeGenOptions &CGOpts, StringRef ModuleFilename, bool Complain, bool AllowCompatibleDifferences)
Receives the codegen options.
Definition ASTReader.h:144
Reads an AST files chain containing the contents of a translation unit.
Definition ASTReader.h:428
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:444
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:2012
bool isDeclIDFromModule(GlobalDeclID ID, ModuleFile &M) const
Returns true if global DeclID ID originated from module M.
friend class ASTIdentifierIterator
Definition ASTReader.h:433
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:2635
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:2205
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:1854
@ ARR_ConfigurationMismatch
The client can handle an AST file that cannot load because it's compiled configuration doesn't match ...
Definition ASTReader.h:1867
@ 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:1858
@ 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:1862
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:2669
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:2215
QualType getLocalType(ModuleFile &F, serialization::LocalTypeID LocalID)
Resolve a local type ID within a given AST file into a type.
void ReadExtnameUndeclaredIdentifiers(SmallVectorImpl< std::pair< IdentifierInfo *, AsmLabelAttr * > > &ExtnameIDs) override
Read the set of pragma redefine_extname'd, undeclared identifiers known to the external Sema source.
friend class LocalDeclID
Definition ASTReader.h:441
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:475
bool loadGlobalIndex()
Attempts to load the global index.
void ReadComments() override
Loads comments ranges.
SourceManager & getSourceManager() const
Definition ASTReader.h:1838
const serialization::reader::ModuleLocalLookupTable * getModuleLocalLookupTables(DeclContext *Primary) const
SourceLocation getSourceLocationForDeclID(GlobalDeclID ID)
Returns the source location for the decl ID.
void makeModuleVisible(Module *Mod, Module::NameVisibilityKind NameVisibility, SourceLocation ImportLoc)
Make the entities in the given module and any of its (non-explicit) submodules visible to name lookup...
SourceRange ReadSourceRange(ModuleFile &F, const RecordData &Record, unsigned &Idx)
Read a source range.
bool LoadExternalSpecializations(const Decl *D, bool OnlyPartial) override
Load all the external specializations for the Decl.
ASTReadResult ReadASTCore(ModuleFileName FileName, ModuleKind Type, SourceLocation ImportLoc, ModuleFile *ImportedBy, SmallVectorImpl< ImportedModule > &Loaded, off_t ExpectedSize, time_t ExpectedModTime, ASTFileSignature ExpectedSignature, unsigned ClientLoadCapabilities)
void finalizeForWriting()
Finalizes the AST reader's state before writing an AST file to disk.
Sema * getSema()
Retrieve the semantic analysis object used to analyze the translation unit in which the precompiled h...
Definition ASTReader.h:2647
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:2081
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:437
friend class serialization::ReadMethodPoolVisitor
Definition ASTReader.h:439
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:2521
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:2111
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:2642
std::pair< SourceLocation, StringRef > getModuleImportLoc(int ID) override
Retrieve the module import location and module name for the given source manager entry ID.
void ReadUnusedFileScopedDecls(SmallVectorImpl< const DeclaratorDecl * > &Decls) override
Read the set of unused file-scope declarations known to the external Sema source.
void ReadReferencedSelectors(SmallVectorImpl< std::pair< Selector, SourceLocation > > &Sels) override
Read the set of referenced selectors known to the external Sema source.
Selector DecodeSelector(serialization::SelectorID Idx)
StringRef getOriginalSourceFile()
Retrieve the name of the original source file name for the primary module file.
Definition ASTReader.h:2020
std::string ReadPath(ModuleFile &F, const RecordData &Record, unsigned &Idx)
friend class serialization::reader::ASTIdentifierLookupTrait
Definition ASTReader.h:438
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:1503
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:448
@ Success
The control block was read successfully.
Definition ASTReader.h:451
@ ConfigurationMismatch
The AST file was written with a different language/target configuration.
Definition ASTReader.h:468
@ OutOfDate
The AST file is out-of-date relative to its input files, and needs to be regenerated.
Definition ASTReader.h:461
@ Failure
The AST file itself appears corrupted.
Definition ASTReader.h:454
@ VersionMismatch
The AST file was written by a different version of Clang.
Definition ASTReader.h:464
@ HadErrors
The AST file has errors.
Definition ASTReader.h:471
@ Missing
The AST file was missing.
Definition ASTReader.h:457
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:2549
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:2169
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:2505
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:2016
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:434
SmallVector< uint64_t, 64 > RecordData
Definition ASTReader.h:443
FileID ReadFileID(ModuleFile &F, const RecordDataImpl &Record, unsigned &Idx) const
Read a FileID.
Definition ASTReader.h:2543
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:1839
bool wasThisDeclarationADefinition(const FunctionDecl *FD) override
True if this function declaration was a definition before in its own module.
void FinishedDeserializing() override
Notify ASTReader that we finished the deserialization of a decl or type.
void updateOutOfDateIdentifier(const IdentifierInfo &II) override
Update an out-of-date identifier.
ASTReadResult ReadAST(ModuleFileName FileName, ModuleKind Type, SourceLocation ImportLoc, unsigned ClientLoadCapabilities, ModuleFile **NewLoadedModuleFile=nullptr)
Load the AST file designated by the given file name.
void ReadDefinedMacros() override
Read the set of macros defined by this external macro source.
HeaderFileInfo GetHeaderFileInfo(FileEntryRef FE) override
Read the header file information for the given file entry.
void getMemoryBufferSizes(MemoryBufferSizes &sizes) const override
Return the amount of memory used by memory buffers, breaking down by heap-backed versus mmap'ed memor...
serialization::ModuleFile ModuleFile
Definition ASTReader.h:474
bool hasGlobalIndex() const
Determine whether this AST reader has a global index.
Definition ASTReader.h:1975
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:2624
Represents a C++ base or member initializer.
Definition DeclCXX.h:2389
void setSourceOrder(int Pos)
Set the source order of this initializer.
Definition DeclCXX.h:2576
Represents a C++ destructor within a class.
Definition DeclCXX.h:2889
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
Decl * getLambdaContextDecl() const
Retrieve the declaration that provides additional context for a lambda, when the normal declaration c...
Definition DeclCXX.cpp:1834
unsigned getLambdaIndexInContext() const
Retrieve the index of this lambda within the context declaration returned by getLambdaContextDecl().
Definition DeclCXX.h:1799
base_class_iterator bases_begin()
Definition DeclCXX.h:615
base_class_iterator vbases_begin()
Definition DeclCXX.h:632
Represents a C++ temporary.
Definition ExprCXX.h:1463
static CXXTemporary * Create(const ASTContext &C, const CXXDestructorDecl *Destructor)
Definition ExprCXX.cpp:1115
void ReadCounter(const serialization::ModuleFile &M, uint32_t Value) override
Receives COUNTER value.
bool visitInputFile(StringRef Filename, bool isSystem, bool isOverridden, bool isExplicitModule) override
if needsInputFileVisitation returns true, this is called for each non-system input file of the AST Fi...
bool ReadCodeGenOptions(const CodeGenOptions &CGOpts, StringRef ModuleFilename, bool Complain, bool AllowCompatibleDifferences) override
Receives the codegen options.
bool ReadFullVersionInformation(StringRef FullVersion) override
Receives the full Clang version information.
bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, StringRef ModuleFilename, StringRef ContextHash, bool Complain) override
Receives the header search options.
bool ReadFileSystemOptions(const FileSystemOptions &FSOpts, bool Complain) override
Receives the file system options.
void ReadModuleMapFile(StringRef ModuleMapPath) override
bool ReadLanguageOptions(const LangOptions &LangOpts, StringRef ModuleFilename, bool Complain, bool AllowCompatibleDifferences) override
Receives the language options.
void visitModuleFile(ModuleFileName Filename, serialization::ModuleKind Kind, bool DirectlyImported) override
This is called for each AST file loaded.
bool ReadTargetOptions(const TargetOptions &TargetOpts, StringRef ModuleFilename, bool Complain, bool AllowCompatibleDifferences) override
Receives the target options.
void ReadModuleName(StringRef ModuleName) override
bool needsInputFileVisitation() override
Returns true if this ASTReaderListener wants to receive the input files of the AST file via visitInpu...
bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, StringRef ModuleFilename, bool ReadMacros, bool Complain, std::string &SuggestedPredefines) override
Receives the preprocessor options.
void readModuleFileExtension(const ModuleFileExtensionMetadata &Metadata) override
Indicates that a particular module file extension has been read.
bool needsSystemInputFileVisitation() override
Returns true if this ASTReaderListener wants to receive the system input files of the AST file via vi...
bool ReadDiagnosticOptions(DiagnosticOptions &DiagOpts, StringRef ModuleFilename, bool Complain) override
Receives the diagnostic options.
CompatibilityKind
For ASTs produced with different option value, signifies their level of compatibility.
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
A reference to a concept and its template args, as it appears in the code.
Definition ASTConcept.h:130
static ConceptReference * Create(const ASTContext &C, NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc, DeclarationNameInfo ConceptNameInfo, NamedDecl *FoundDecl, TemplateDecl *NamedConcept, const ASTTemplateArgumentListInfo *ArgsAsWritten)
const TypeClass * getTypePtr() const
Definition TypeLoc.h:433
A map from continuous integer ranges to some value, with a very specialized interface.
void insertOrReplace(const value_type &Val)
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:1462
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
bool hasExternalVisibleStorage() const
Whether this DeclContext has external storage containing additional declarations that are visible in ...
Definition DeclBase.h:2713
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
void setMustBuildLookupTable()
Mark that there are external lexical declarations that we need to include in our lookup table (and th...
Definition DeclBase.h:2686
bool hasExternalLexicalStorage() const
Whether this DeclContext has external storage containing additional declarations that are lexically i...
Definition DeclBase.h:2701
DeclContext * getPrimaryContext()
getPrimaryContext - There may be many different declarations of the same entity (including forward de...
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition DeclBase.h:2386
void setHasExternalLexicalStorage(bool ES=true) const
State whether this DeclContext has external storage for declarations lexically in this context.
Definition DeclBase.h:2707
bool isDeclInLexicalTraversal(const Decl *D) const
Determine whether the given declaration is stored in the list of declarations lexically within this c...
Definition DeclBase.h:2727
decl_iterator decls_begin() const
unsigned getModuleFileIndex() const
Definition DeclID.h:125
DeclID getRawValue() const
Definition DeclID.h:115
unsigned getLocalDeclIndex() const
uint64_t DeclID
An ID number that refers to a declaration in an AST file.
Definition DeclID.h:108
TypeSpecifierType TST
Definition DeclSpec.h:248
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:547
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:601
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition DeclBase.cpp:178
bool isUnconditionallyVisible() const
Determine whether this declaration is definitely visible to name lookup, independent of whether the o...
Definition DeclBase.h:867
Kind
Lists the kind of concrete classes of Decl.
Definition DeclBase.h:89
bool isCanonicalDecl() const
Whether this particular Decl is a canonical one.
Definition DeclBase.h:997
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition DeclBase.h:850
Module * getImportedOwningModule() const
Get the imported owning module, if this decl is from an imported (non-local) module.
Definition DeclBase.h:820
bool isFromASTFile() const
Determine whether this declaration came from an AST file (such as a precompiled header or module) rat...
Definition DeclBase.h:801
SourceLocation getLocation() const
Definition DeclBase.h:447
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition DeclBase.h:1062
DeclContext * getDeclContext()
Definition DeclBase.h:456
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:931
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:991
Kind getKind() const
Definition DeclBase.h:450
GlobalDeclID getGlobalID() const
Retrieve the global declaration ID associated with this declaration, which specifies where this Decl ...
Definition DeclBase.cpp:110
void setVisibleDespiteOwningModule()
Set that this declaration is globally visible, even if it came from a module that is not visible.
Definition DeclBase.h:878
DeclarationNameLoc - Additional source/type location info for a declaration name.
static DeclarationNameLoc makeNamedTypeLoc(TypeSourceInfo *TInfo)
Construct location information for a constructor, destructor or conversion operator.
static DeclarationNameLoc makeCXXLiteralOperatorNameLoc(SourceLocation Loc)
Construct location information for a literal C++ operator.
static DeclarationNameLoc makeCXXOperatorNameLoc(SourceLocation BeginLoc, SourceLocation EndLoc)
Construct location information for a non-literal C++ operator.
The name of a declaration.
IdentifierInfo * getAsIdentifierInfo() const
Retrieve the IdentifierInfo * stored in this declaration name, or null if this declaration name isn't...
TemplateDecl * getCXXDeductionGuideTemplate() const
If this name is the name of a C++ deduction guide, return the template associated with that name.
const IdentifierInfo * getCXXLiteralIdentifier() const
If this name is the name of a literal operator, retrieve the identifier associated with it.
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
NameKind
The kind of the name stored in this DeclarationName.
Selector getObjCSelector() const
Get the Objective-C selector stored in this declaration name.
NameKind getNameKind() const
Determine what kind of name this is.
Represents a ValueDecl that came out of a declarator.
Definition Decl.h:780
void setRParenLoc(SourceLocation Loc)
Definition TypeLoc.h:2291
void setDecltypeLoc(SourceLocation Loc)
Definition TypeLoc.h:2288
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition TypeLoc.h:2531
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:2513
void setTemplateNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2519
void setAttrNameLoc(SourceLocation loc)
Definition TypeLoc.h:1977
void setAttrOperandParensRange(SourceRange range)
Definition TypeLoc.h:1998
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2601
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:2581
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition TypeLoc.h:2590
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2096
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2068
A little helper class used to produce diagnostics.
bool wasUpgradedFromWarning() const
Whether this mapping attempted to map the diagnostic to a warning, but was overruled because the diag...
void setSeverity(diag::Severity Value)
static DiagnosticMapping deserialize(unsigned Bits)
Deserialize a mapping.
void setUpgradedFromWarning(bool Value)
Options for controlling the compiler diagnostics engine.
std::vector< std::string > Remarks
The list of -R... options used to alter the diagnostic mappings, with the prefixes removed.
std::vector< std::string > Warnings
The list of -W... options used to alter the diagnostic mappings, with the prefixes removed.
std::vector< std::string > SystemHeaderWarningsModules
The list of -Wsystem-headers-in-module=... options used to override whether -Wsystem-headers is enabl...
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:233
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
DiagnosticOptions & getDiagnosticOptions() const
Retrieve the diagnostic options.
Definition Diagnostic.h:603
bool getEnableAllWarnings() const
Definition Diagnostic.h:703
Level
The level of the diagnostic, after it has been through mapping.
Definition Diagnostic.h:238
Level getDiagnosticLevel(unsigned DiagID, SourceLocation Loc) const
Based on the way the client configured the DiagnosticsEngine object, classify the specified diagnosti...
Definition Diagnostic.h:975
bool getSuppressSystemWarnings() const
Definition Diagnostic.h:729
bool getWarningsAsErrors() const
Definition Diagnostic.h:711
diag::Severity getExtensionHandlingBehavior() const
Definition Diagnostic.h:819
const IntrusiveRefCntPtr< DiagnosticIDs > & getDiagnosticIDs() const
Definition Diagnostic.h:598
StringRef getName() const
void set(SourceLocation ElaboratedKeywordLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation NameLoc)
Definition TypeLoc.h:744
This represents one expression.
Definition Expr.h:112
RAII class for safely pairing a StartedDeserializing call with FinishedDeserializing.
static DeclContextLookupResult SetExternalVisibleDeclsForName(const DeclContext *DC, DeclarationName Name, ArrayRef< NamedDecl * > Decls)
uint32_t incrementGeneration(ASTContext &C)
Increment the current generation.
uint32_t getGeneration() const
Get the current generation of this AST source.
Represents difference between two FPOptions values.
static FPOptionsOverride getFromOpaqueInt(storage_type I)
FPOptions applyOverrides(FPOptions Base)
static FPOptions getFromOpaqueInt(storage_type Value)
Represents a member of a struct/union/class.
Definition Decl.h:3175
A reference to a FileEntry that includes the name of the file as it was accessed by the FileManager's...
Definition FileEntry.h:57
time_t getModificationTime() const
Definition FileEntry.h:354
off_t getSize() const
Definition FileEntry.h:346
StringRef getName() const
The name of this FileEntry.
Definition FileEntry.h:61
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
bool isValid() const
bool isInvalid() const
Implements support for file system lookup, file system caching, and directory search management.
Definition FileManager.h:53
llvm::ErrorOr< std::unique_ptr< llvm::MemoryBuffer > > getBufferForFile(FileEntryRef Entry, bool isVolatile=false, bool RequiresNullTerminator=true, std::optional< int64_t > MaybeLimit=std::nullopt, bool IsText=true)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful,...
FileEntryRef getVirtualFileRef(StringRef Filename, off_t Size, time_t ModificationTime)
Retrieve a file entry for a "virtual" file that acts as if there were a file with the given name on d...
OptionalFileEntryRef getOptionalFileRef(StringRef Filename, bool OpenFile=false, bool CacheFailure=true, bool IsText=true)
Get a FileEntryRef if it exists, without doing anything on error.
OptionalDirectoryEntryRef getOptionalDirectoryRef(StringRef DirName, bool CacheFailure=true)
Get a DirectoryEntryRef if it exists, without doing anything on error.
Keeps track of options that affect how file operations are performed.
std::string WorkingDir
If set, paths are resolved as if the working directory was set to the value of WorkingDir.
Represents a function declaration or definition.
Definition Decl.h:2015
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5357
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5646
Wrapper for source info for functions.
Definition TypeLoc.h:1644
unsigned getNumParams() const
Definition TypeLoc.h:1716
void setLocalRangeBegin(SourceLocation L)
Definition TypeLoc.h:1664
void setLParenLoc(SourceLocation Loc)
Definition TypeLoc.h:1680
void setParam(unsigned i, ParmVarDecl *VD)
Definition TypeLoc.h:1723
void setRParenLoc(SourceLocation Loc)
Definition TypeLoc.h:1688
void setLocalRangeEnd(SourceLocation L)
Definition TypeLoc.h:1672
void setExceptionSpecRange(SourceRange R)
Definition TypeLoc.h:1702
llvm::SmallPtrSet< ModuleFile *, 4 > HitSet
A set of module files in which we found a result.
static std::pair< GlobalModuleIndex *, llvm::Error > readIndex(llvm::StringRef Path)
Read a global index file for the given directory.
HeaderSearchOptions - Helper class for storing options related to the initialization of the HeaderSea...
uint64_t BuildSessionTimestamp
The time in seconds when the build session started.
unsigned ImplicitModuleMaps
Implicit module maps.
std::vector< SystemHeaderPrefix > SystemHeaderPrefixes
User-specified system header prefixes.
unsigned EnablePrebuiltImplicitModules
Also search for prebuilt implicit modules in the prebuilt module cache path.
unsigned ModuleMapFileHomeIsCwd
Set the 'home directory' of a module map file to the current working directory (or the home directory...
std::string Sysroot
If non-empty, the directory to use as a "virtual system root" for include paths.
std::string ModuleCachePath
The directory used for the module cache.
std::string ModuleUserBuildPath
The directory used for a user build.
std::vector< std::string > VFSOverlayFiles
The set of user-provided virtual filesystem overlay files.
unsigned UseLibcxx
Use libc++ instead of the default libstdc++.
unsigned UseBuiltinIncludes
Include the compiler builtin includes.
unsigned UseStandardCXXIncludes
Include the system standard C++ library include search directories.
std::vector< Entry > UserEntries
User specified include entries.
std::string ResourceDir
The directory which holds the compiler resource files (builtin includes, etc.).
unsigned UseStandardSystemIncludes
Include the system standard include search directories.
unsigned ModulesValidateOncePerBuildSession
If true, skip verifying input files used by modules if the module was already verified during this bu...
unsigned DisableModuleHash
Whether we should disable the use of the hash string within the module cache.
Encapsulates the information needed to find the file referenced by a #include or #include_next,...
Module * lookupModule(StringRef ModuleName, SourceLocation ImportLoc=SourceLocation(), bool AllowSearch=true, bool AllowExtraModuleMapSearch=false)
Lookup a module Search for a module with the given name.
const HeaderSearchOptions & getHeaderSearchOpts() const
Retrieve the header-search options with which this header search was initialized.
StringRef getSpecificModuleCachePath() const
Retrieve the specific module cache path.
One of these records is kept for each identifier that is lexed.
unsigned getBuiltinID() const
Return a value indicating whether this is a builtin function.
bool isCPlusPlusOperatorKeyword() const
tok::TokenKind getTokenID() const
If this is a source-language token (e.g.
bool hadMacroDefinition() const
Returns true if this identifier was #defined to some value at any moment.
void setIsPoisoned(bool Value=true)
setIsPoisoned - Mark this identifier as poisoned.
bool isFromAST() const
Return true if the identifier in its current state was loaded from an AST file.
bool isPoisoned() const
Return true if this token has been poisoned.
bool hasRevertedTokenIDToIdentifier() const
True if revertTokenIDToIdentifier() was called.
tok::NotableIdentifierKind getNotableIdentifierID() const
void setOutOfDate(bool OOD)
Set whether the information for this identifier is out of date with respect to the external source.
tok::ObjCKeywordKind getObjCKeywordID() const
Return the Objective-C keyword ID for the this identifier.
void setObjCOrBuiltinID(unsigned ID)
void revertTokenIDToIdentifier()
Revert TokenID to tok::identifier; used for GNU libstdc++ 4.2 compatibility.
bool isOutOfDate() const
Determine whether the information for this identifier is out of date with respect to the external sou...
void setChangedSinceDeserialization()
Note that this identifier has changed since it was loaded from an AST file.
void * getFETokenInfo() const
Get and set FETokenInfo.
StringRef getName() const
Return the actual identifier string.
bool isExtensionToken() const
get/setExtension - Initialize information about whether or not this language token is an extension.
An iterator that walks over all of the known identifiers in the lookup table.
IdentifierResolver - Keeps track of shadowed decls on enclosing scopes.
void RemoveDecl(NamedDecl *D)
RemoveDecl - Unlink the decl from its shadowed decl chain.
Implements an efficient mapping from strings to IdentifierInfo nodes.
llvm::MemoryBuffer * lookupPCM(llvm::StringRef Filename, off_t &Size, time_t &ModTime) const
Get a pointer to the PCM if it exists and set Size and ModTime to its on-disk size and modification t...
Record the location of an inclusion directive, such as an #include or #import statement.
InclusionKind
The kind of inclusion directives known to the preprocessor.
Represents a field injected from an anonymous union/struct into the parent scope.
Definition Decl.h:3482
Wrapper for source info for injected class names of class templates.
Definition TypeLoc.h:872
void setAmpLoc(SourceLocation Loc)
Definition TypeLoc.h:1614
CompatibilityKind
For ASTs produced with different option value, signifies their level of compatibility.
Definition LangOptions.h:83
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
clang::ObjCRuntime ObjCRuntime
SanitizerSet Sanitize
Set of enabled sanitizers.
CommentOptions CommentOpts
Options for parsing comments.
std::string OMPHostIRFile
Name of the IR file that contains the result of the OpenMP target host code generation.
std::vector< llvm::Triple > OMPTargetTriples
Triples of the OpenMP targets that the host code codegen should take into account in order to generat...
std::string CurrentModule
The name of the current module, of which the main source file is a part.
std::vector< std::string > ModuleFeatures
The names of any features to enable in module 'requires' decls in addition to the hard-coded list in ...
An UnresolvedSet-like class that might not have been loaded from the external AST source yet.
unsigned getLineTableFilenameID(StringRef Str)
void AddEntry(FileID FID, const std::vector< LineEntry > &Entries)
Add a new line entry that has already been encoded into the internal representation of the line table...
static LocalDeclID get(ASTReader &Reader, serialization::ModuleFile &MF, DeclID ID)
Record the location of a macro definition.
Encapsulates changes to the "macros namespace" (the location where the macro name became active,...
Definition MacroInfo.h:313
void setPrevious(MacroDirective *Prev)
Set previous definition of the macro with the same name.
Definition MacroInfo.h:351
Records the location of a macro expansion.
Encapsulates the data about a macro definition (e.g.
Definition MacroInfo.h:39
void setUsedForHeaderGuard(bool Val)
Definition MacroInfo.h:296
void setHasCommaPasting()
Definition MacroInfo.h:220
void setDefinitionEndLoc(SourceLocation EndLoc)
Set the location of the last token in the macro.
Definition MacroInfo.h:128
void setParameterList(ArrayRef< IdentifierInfo * > List, llvm::BumpPtrAllocator &PPAllocator)
Set the specified list of identifiers as the parameter list for this macro.
Definition MacroInfo.h:166
llvm::MutableArrayRef< Token > allocateTokens(unsigned NumTokens, llvm::BumpPtrAllocator &PPAllocator)
Definition MacroInfo.h:254
void setIsFunctionLike()
Function/Object-likeness.
Definition MacroInfo.h:200
void setIsGNUVarargs()
Definition MacroInfo.h:206
void setIsC99Varargs()
Varargs querying methods. This can only be set for function-like macros.
Definition MacroInfo.h:205
void setIsUsed(bool Val)
Set the value of the IsUsed flag.
Definition MacroInfo.h:154
void setExpansionLoc(SourceLocation Loc)
Definition TypeLoc.h:1383
void setAttrRowOperand(Expr *e)
Definition TypeLoc.h:2131
void setAttrColumnOperand(Expr *e)
Definition TypeLoc.h:2137
void setAttrOperandParensRange(SourceRange range)
Definition TypeLoc.h:2146
void setAttrNameLoc(SourceLocation loc)
Definition TypeLoc.h:2125
void setStarLoc(SourceLocation Loc)
Definition TypeLoc.h:1550
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition TypeLoc.h:1559
The module cache used for compiling modules implicitly.
Definition ModuleCache.h:30
virtual InMemoryModuleCache & getInMemoryModuleCache()=0
Returns this process's view of the module cache.
Deduplication key for a loaded module file in ModuleManager.
Definition Module.h:69
Identifies a module file to be loaded.
Definition Module.h:102
bool empty() const
Checks whether the module file name is empty.
Definition Module.h:150
static ModuleFileName makeImplicit(std::string Name, unsigned SuffixLength)
Creates a file name for an implicit module.
Definition Module.h:123
static ModuleFileName makeExplicit(std::string Name)
Creates a file name for an explicit module.
Definition Module.h:111
StringRef str() const
Returns the plain module file name.
Definition Module.h:144
void addLinkAsDependency(Module *Mod)
Make module to use export_as as the link dependency name if enough information is available or add it...
Definition ModuleMap.cpp:62
OptionalFileEntryRef getContainingModuleMapFile(const Module *Module) const
Module * findModule(StringRef Name) const
Retrieve a module with the given name.
void setUmbrellaHeaderAsWritten(Module *Mod, FileEntryRef UmbrellaHeader, const Twine &NameAsWritten, const Twine &PathRelativeToRootModuleDirectory, SourceLocation Loc=SourceLocation())
Sets the umbrella header of the given module to the given header.
void addHeader(Module *Mod, Module::Header Header, ModuleHeaderRole Role, bool Imported=false, SourceLocation Loc=SourceLocation())
Adds this header to the given module.
OptionalFileEntryRef findUmbrellaHeaderForModule(Module *M, std::string NameAsWritten, SmallVectorImpl< char > &RelativePathName)
Find the FileEntry for an umbrella header in a module as if it was written in the module map as a hea...
void setInferredModuleAllowedBy(Module *M, FileID ModMapFID)
void setUmbrellaDirAsWritten(Module *Mod, DirectoryEntryRef UmbrellaDir, const Twine &NameAsWritten, const Twine &PathRelativeToRootModuleDirectory, SourceLocation Loc=SourceLocation())
Sets the umbrella directory of the given module to the given directory.
llvm::DenseSet< FileEntryRef > AdditionalModMapsSet
Definition ModuleMap.h:196
Module * findOrCreateModuleFirst(StringRef Name, Module *Parent, bool IsFramework, bool IsExplicit)
Call ModuleMap::findOrCreateModule and throw away the information whether the module was found or cre...
Definition ModuleMap.h:572
Module * createModule(StringRef Name, Module *Parent, bool IsFramework, bool IsExplicit)
Create new submodule, assuming it does not exist.
void resolveLinkAsDependencies(Module *Mod)
Use PendingLinkAsModule information to mark top level link names that are going to be replaced by exp...
Definition ModuleMap.cpp:51
ModuleHeaderRole
Flags describing the role of a module header.
Definition ModuleMap.h:126
Describes a module or submodule.
Definition Module.h:246
StringRef getTopLevelModuleName() const
Retrieve the name of the top-level module.
Definition Module.h:838
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:333
unsigned InferSubmodules
Whether we should infer submodules for this module based on the headers.
Definition Module.h:512
std::vector< std::string > ConfigMacros
The set of "configuration macros", which are macros that (intentionally) change how this module is bu...
Definition Module.h:634
unsigned IsUnimportable
Whether this module has declared itself unimportable, either because it's missing a requirement from ...
Definition Module.h:467
NameVisibilityKind NameVisibility
The visibility of names within this particular module.
Definition Module.h:557
NameVisibilityKind
Describes the visibility of the various names within a particular module.
Definition Module.h:549
@ Hidden
All of the names in this module are hidden.
Definition Module.h:551
@ AllVisible
All of the names in this module are visible.
Definition Module.h:553
const ModuleFileKey * getASTFileKey() const
The serialized AST file key for this module, if one was created.
Definition Module.h:849
SourceLocation DefinitionLoc
The location of the module definition.
Definition Module.h:252
SmallVector< UnresolvedHeaderDirective, 1 > MissingHeaders
Headers that are mentioned in the module map file but could not be found on the file system.
Definition Module.h:447
ModuleKind Kind
The kind of this module.
Definition Module.h:291
void addTopHeaderFilename(StringRef Filename)
Add a top-level header filename associated with this module.
Definition Module.h:889
bool isUnimportable() const
Determine whether this module has been declared unimportable.
Definition Module.h:669
void setASTFileNameAndKey(ModuleFileName NewName, ModuleFileKey NewKey)
Set the serialized module file for the top-level module of this module.
Definition Module.h:855
unsigned IsSystem
Whether this is a "system" module (which assumes that all headers in it are system headers).
Definition Module.h:495
std::string Name
The name of this module.
Definition Module.h:249
const ModuleFileName * getASTFileName() const
The serialized AST file name for this module, if one was created.
Definition Module.h:843
unsigned IsExternC
Whether this is an 'extern "C"' module (which implicitly puts all headers in it within an 'extern "C"...
Definition Module.h:501
unsigned ModuleMapIsPrivate
Whether this module came from a "private" module map, found next to a regular (public) module map.
Definition Module.h:540
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:626
SmallVector< UnresolvedExportDecl, 2 > UnresolvedExports
The set of export declarations that have yet to be resolved.
Definition Module.h:595
std::optional< Header > getUmbrellaHeaderAsWritten() const
Retrieve the umbrella header as written.
Definition Module.h:873
SmallVector< Requirement, 2 > Requirements
The set of language features required to use this module.
Definition Module.h:458
bool isHeaderLikeModule() const
Is this module have similar semantics as headers.
Definition Module.h:754
OptionalDirectoryEntryRef Directory
The build directory of this module.
Definition Module.h:300
unsigned NamedModuleHasInit
Whether this C++20 named modules doesn't need an initializer.
Definition Module.h:545
StringRef getPrimaryModuleInterfaceName() const
Get the primary module interface name from a partition.
Definition Module.h:793
unsigned ConfigMacrosExhaustive
Whether the set of configuration macros is exhaustive.
Definition Module.h:530
std::string PresumedModuleMapFile
The presumed file name for the module map defining this module.
Definition Module.h:304
ASTFileSignature Signature
The module signature.
Definition Module.h:313
bool isGlobalModule() const
Does this Module scope describe a fragment of the global module within some C++ module.
Definition Module.h:344
unsigned InferExportWildcard
Whether, when inferring submodules, the inferr submodules should export all modules they import (e....
Definition Module.h:522
void getExportedModules(SmallVectorImpl< Module * > &Exported) const
Appends this module's list of exported modules to Exported.
Definition Module.cpp:403
std::vector< UnresolvedConflict > UnresolvedConflicts
The list of conflicts for which the module-id has not yet been resolved.
Definition Module.h:647
unsigned IsFromModuleFile
Whether this module was loaded from a module file.
Definition Module.h:482
llvm::PointerIntPair< Module *, 1, bool > ExportDecl
Describes an exported module.
Definition Module.h:574
std::optional< DirectoryName > getUmbrellaDirAsWritten() const
Retrieve the umbrella directory as written.
Definition Module.h:865
std::string ExportAsModule
The module through which entities defined in this module will eventually be exposed,...
Definition Module.h:323
unsigned IsAvailable
Whether this module is available in the current translation unit.
Definition Module.h:478
unsigned InferExplicitSubmodules
Whether, when inferring submodules, the inferred submodules should be explicit.
Definition Module.h:517
std::vector< Conflict > Conflicts
The list of conflicts.
Definition Module.h:659
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:1847
Represent a C++ namespace.
Definition Decl.h:592
Class that aids in the construction of nested-name-specifiers along with source-location information ...
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
A C++ nested-name-specifier augmented with source location information.
@ MicrosoftSuper
Microsoft's '__super' specifier, stored as a CXXRecordDecl* of the class it appeared in.
@ Global
The global specifier '::'. There is no stored value.
@ Namespace
A namespace-like entity, stored as a NamespaceBaseDecl*.
static std::string getOwningModuleNameForDiagnostic(const Decl *D)
Get the best name we know for the module that owns the given declaration, or an empty string if the d...
This represents the 'align' clause in the 'pragma omp allocate' directive.
This represents clause 'allocate' in the 'pragma omp ...' directives.
static OMPAllocateClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with the place for N variables.
This represents 'allocator' clause in the 'pragma omp ...' directive.
void VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C)
OMPClauseReader(ASTRecordReader &Record)
void VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C)
Class that handles post-update expression for some clauses, like 'lastprivate', 'reduction' etc.
Class that handles pre-initialization statement for some clauses, like 'schedule',...
This is a basic class for representing single OpenMP clause.
This represents 'collapse' clause in the 'pragma omp ...' directive.
This represents the 'counts' clause in the 'pragma omp split' directive.
static OMPCountsClause * CreateEmpty(const ASTContext &C, unsigned NumCounts)
Build an empty 'counts' AST node for deserialization.
This represents 'default' clause in the 'pragma omp ...' directive.
This represents 'final' clause in the 'pragma omp ...' directive.
Representation of the 'full' clause of the 'pragma omp unroll' directive.
static OMPFullClause * CreateEmpty(const ASTContext &C)
Build an empty 'full' AST node for deserialization.
This represents 'if' clause in the 'pragma omp ...' directive.
This class represents the 'looprange' clause in the 'pragma omp fuse' directive.
static OMPLoopRangeClause * CreateEmpty(const ASTContext &C)
Build an empty 'looprange' clause node.
This represents 'num_threads' clause in the 'pragma omp ...' directive.
Representation of the 'partial' clause of the 'pragma omp unroll' directive.
static OMPPartialClause * CreateEmpty(const ASTContext &C)
Build an empty 'partial' AST node for deserialization.
This class represents the 'permutation' clause in the 'pragma omp interchange' directive.
static OMPPermutationClause * CreateEmpty(const ASTContext &C, unsigned NumLoops)
Build an empty 'permutation' AST node for deserialization.
This represents 'safelen' clause in the 'pragma omp ...' directive.
This represents 'simdlen' clause in the 'pragma omp ...' directive.
This represents the 'sizes' clause in the 'pragma omp tile' directive.
static OMPSizesClause * CreateEmpty(const ASTContext &C, unsigned NumSizes)
Build an empty 'sizes' AST node for deserialization.
This represents 'threadset' clause in the 'pragma omp task ...' directive.
method_range methods() const
Definition DeclObjC.h:1016
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:1313
void setNameEndLoc(SourceLocation Loc)
Definition TypeLoc.h:1325
ObjCMethodDecl - Represents an instance or class method declaration.
Definition DeclObjC.h:140
bool hasBody() const override
Determine whether this method has a body.
Definition DeclObjC.h:523
void setLazyBody(uint64_t Offset)
Definition DeclObjC.h:528
void setStarLoc(SourceLocation Loc)
Definition TypeLoc.h:1592
void setTypeArgsRAngleLoc(SourceLocation Loc)
Definition TypeLoc.h:1196
unsigned getNumTypeArgs() const
Definition TypeLoc.h:1200
unsigned getNumProtocols() const
Definition TypeLoc.h:1230
void setTypeArgsLAngleLoc(SourceLocation Loc)
Definition TypeLoc.h:1188
void setTypeArgTInfo(unsigned i, TypeSourceInfo *TInfo)
Definition TypeLoc.h:1209
void setProtocolLAngleLoc(SourceLocation Loc)
Definition TypeLoc.h:1218
void setProtocolRAngleLoc(SourceLocation Loc)
Definition TypeLoc.h:1226
void setHasBaseTypeAsWritten(bool HasBaseType)
Definition TypeLoc.h:1258
void setProtocolLoc(unsigned i, SourceLocation Loc)
Definition TypeLoc.h:1239
Kind
The basic Objective-C runtimes that we know about.
Definition ObjCRuntime.h:31
unsigned getNumProtocols() const
Definition TypeLoc.h:932
void setProtocolLoc(unsigned i, SourceLocation Loc)
Definition TypeLoc.h:941
void setProtocolLAngleLoc(SourceLocation Loc)
Definition TypeLoc.h:918
void setProtocolRAngleLoc(SourceLocation Loc)
Definition TypeLoc.h:928
static OpenACCAsyncClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, Expr *IntExpr, SourceLocation EndLoc)
static OpenACCAttachClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCAutoClause * Create(const ASTContext &Ctx, SourceLocation BeginLoc, SourceLocation EndLoc)
static OpenACCBindClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, const IdentifierInfo *ID, SourceLocation EndLoc)
This is the base type for all OpenACC Clauses.
static OpenACCCollapseClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, bool HasForce, Expr *LoopCount, SourceLocation EndLoc)
static OpenACCCopyClause * Create(const ASTContext &C, OpenACCClauseKind Spelling, SourceLocation BeginLoc, SourceLocation LParenLoc, OpenACCModifierKind Mods, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCCopyInClause * Create(const ASTContext &C, OpenACCClauseKind Spelling, SourceLocation BeginLoc, SourceLocation LParenLoc, OpenACCModifierKind Mods, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCCopyOutClause * Create(const ASTContext &C, OpenACCClauseKind Spelling, SourceLocation BeginLoc, SourceLocation LParenLoc, OpenACCModifierKind Mods, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCCreateClause * Create(const ASTContext &C, OpenACCClauseKind Spelling, SourceLocation BeginLoc, SourceLocation LParenLoc, OpenACCModifierKind Mods, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCDefaultAsyncClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, Expr *IntExpr, SourceLocation EndLoc)
static OpenACCDefaultClause * Create(const ASTContext &C, OpenACCDefaultClauseKind K, SourceLocation BeginLoc, SourceLocation LParenLoc, SourceLocation EndLoc)
static OpenACCDeleteClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCDetachClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCDeviceClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCDeviceNumClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, Expr *IntExpr, SourceLocation EndLoc)
static OpenACCDevicePtrClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCDeviceResidentClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCDeviceTypeClause * Create(const ASTContext &C, OpenACCClauseKind K, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< DeviceTypeArgument > Archs, SourceLocation EndLoc)
static OpenACCFinalizeClause * Create(const ASTContext &Ctx, SourceLocation BeginLoc, SourceLocation EndLoc)
static OpenACCFirstPrivateClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, ArrayRef< OpenACCFirstPrivateRecipe > InitRecipes, SourceLocation EndLoc)
static OpenACCGangClause * Create(const ASTContext &Ctx, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< OpenACCGangKind > GangKinds, ArrayRef< Expr * > IntExprs, SourceLocation EndLoc)
static OpenACCHostClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCIfClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, Expr *ConditionExpr, SourceLocation EndLoc)
static OpenACCIfPresentClause * Create(const ASTContext &Ctx, SourceLocation BeginLoc, SourceLocation EndLoc)
static OpenACCIndependentClause * Create(const ASTContext &Ctx, SourceLocation BeginLoc, SourceLocation EndLoc)
static OpenACCLinkClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCNoCreateClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCNoHostClause * Create(const ASTContext &Ctx, SourceLocation BeginLoc, SourceLocation EndLoc)
static OpenACCNumGangsClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > IntExprs, SourceLocation EndLoc)
static OpenACCNumWorkersClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, Expr *IntExpr, SourceLocation EndLoc)
static OpenACCPresentClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCPrivateClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, ArrayRef< OpenACCPrivateRecipe > InitRecipes, SourceLocation EndLoc)
static OpenACCReductionClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, OpenACCReductionOperator Operator, ArrayRef< Expr * > VarList, ArrayRef< OpenACCReductionRecipeWithStorage > Recipes, SourceLocation EndLoc)
static OpenACCSelfClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, Expr *ConditionExpr, SourceLocation EndLoc)
static OpenACCSeqClause * Create(const ASTContext &Ctx, SourceLocation BeginLoc, SourceLocation EndLoc)
static OpenACCTileClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > SizeExprs, SourceLocation EndLoc)
static OpenACCUseDeviceClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCVectorClause * Create(const ASTContext &Ctx, SourceLocation BeginLoc, SourceLocation LParenLoc, Expr *IntExpr, SourceLocation EndLoc)
static OpenACCVectorLengthClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, Expr *IntExpr, SourceLocation EndLoc)
static OpenACCWaitClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, Expr *DevNumExpr, SourceLocation QueuesLoc, ArrayRef< Expr * > QueueIdExprs, SourceLocation EndLoc)
static OpenACCWorkerClause * Create(const ASTContext &Ctx, SourceLocation BeginLoc, SourceLocation LParenLoc, Expr *IntExpr, SourceLocation EndLoc)
void setAttrLoc(SourceLocation loc)
Definition TypeLoc.h:1099
This abstract interface provides operations for unwrapping containers for serialized ASTs (precompile...
bool ReadDiagnosticOptions(DiagnosticOptions &DiagOpts, StringRef ModuleFilename, bool Complain) override
Receives the diagnostic options.
bool ReadLanguageOptions(const LangOptions &LangOpts, StringRef ModuleFilename, bool Complain, bool AllowCompatibleDifferences) override
Receives the language options.
void ReadCounter(const serialization::ModuleFile &M, uint32_t Value) override
Receives COUNTER value.
bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, StringRef ModuleFilename, bool ReadMacros, bool Complain, std::string &SuggestedPredefines) override
Receives the preprocessor options.
bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, StringRef ModuleFilename, StringRef ContextHash, bool Complain) override
Receives the header search options.
bool ReadCodeGenOptions(const CodeGenOptions &CGOpts, StringRef ModuleFilename, bool Complain, bool AllowCompatibleDifferences) override
Receives the codegen options.
bool ReadTargetOptions(const TargetOptions &TargetOpts, StringRef ModuleFilename, bool Complain, bool AllowCompatibleDifferences) override
Receives the target options.
void setEllipsisLoc(SourceLocation Loc)
Definition TypeLoc.h:2633
void setEllipsisLoc(SourceLocation Loc)
Definition TypeLoc.h:2316
void setRParenLoc(SourceLocation Loc)
Definition TypeLoc.h:1415
void setLParenLoc(SourceLocation Loc)
Definition TypeLoc.h:1411
Represents a parameter to a function.
Definition Decl.h:1805
void setKWLoc(SourceLocation Loc)
Definition TypeLoc.h:2725
void setStarLoc(SourceLocation Loc)
Definition TypeLoc.h:1519
Base class that describes a preprocessed entity, which may be a preprocessor directive or macro expan...
A record of the steps taken while preprocessing a source file, including the various preprocessing di...
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
std::vector< std::string > MacroIncludes
std::vector< std::string > Includes
ObjCXXARCStandardLibraryKind ObjCXXARCStandardLibrary
The Objective-C++ ARC standard library that we should support, by providing appropriate definitions t...
std::string PCHThroughHeader
If non-empty, the filename used in an include directive in the primary source file (or command-line p...
bool DetailedRecord
Whether we should maintain a detailed record of all macro definitions and expansions.
std::string ImplicitPCHInclude
The implicit PCH included at the start of the translation unit, or empty.
bool AllowPCHWithDifferentModulesCachePath
When true, a PCH with modules cache path different to the current compilation will not be rejected.
bool UsePredefines
Initialize the preprocessor with the compiler and target specific predefines.
std::vector< std::pair< std::string, bool > > Macros
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Module * getCurrentModule()
Retrieves the module that we're currently building, if any.
HeaderSearch & getHeaderSearchInfo() const
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
@ FastWidth
The width of the "fast" qualifier mask.
Definition TypeBase.h:376
@ FastMask
The fast qualifier mask.
Definition TypeBase.h:379
void setAmpAmpLoc(SourceLocation Loc)
Definition TypeLoc.h:1628
Wrapper for source info for record types.
Definition TypeLoc.h:855
Declaration of a redeclarable template.
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
void setPreviousDecl(decl_type *PrevDecl)
Set the previous declaration.
Definition Decl.h:5347
This table allows us to fully hide how we implement multi-keyword caching.
Selector getNullarySelector(const IdentifierInfo *ID)
Selector getSelector(unsigned NumArgs, const IdentifierInfo **IIV)
Can create any sort of selector.
Selector getUnarySelector(const IdentifierInfo *ID)
Smart pointer class that efficiently represents Objective-C method names.
void * getAsOpaquePtr() const
void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method)
Add the given method to the list of globally-known methods.
GlobalMethodPool MethodPool
Method Pool - allows efficient lookup when typechecking messages to "id".
Definition SemaObjC.h:220
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:868
SemaObjC & ObjC()
Definition Sema.h:1518
void addExternalSource(IntrusiveRefCntPtr< ExternalSemaSource > E)
Registers an external source.
Definition Sema.cpp:661
IdentifierResolver IdResolver
Definition Sema.h:3519
PragmaMsStackAction
Definition Sema.h:1849
ASTReaderListenter implementation to set SuggestedPredefines of ASTReader which is required to use a ...
Definition ASTReader.h:360
bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, StringRef ModuleFilename, bool ReadMacros, bool Complain, std::string &SuggestedPredefines) override
Receives the preprocessor options.
Encodes a location in the source.
static SourceLocation getFromRawEncoding(UIntTy Encoding)
Turn a raw encoding of a SourceLocation object into a real SourceLocation.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
This class handles loading and caching of source files into memory.
SourceLocation getFileLoc(SourceLocation Loc) const
Given Loc, if it is a macro location return the expansion location or the spelling location,...
bool isBeforeInTranslationUnit(SourceLocation LHS, SourceLocation RHS) const
Determines the order of 2 source locations in the translation unit.
A trivial tuple used to represent a source range.
One instance of this struct is kept for every file loaded or used.
OptionalFileEntryRef ContentsEntry
References the file which the contents were actually loaded from.
std::optional< llvm::MemoryBufferRef > getBufferIfLoaded() const
Return the buffer, only if it has been loaded.
unsigned BufferOverridden
Indicates whether the buffer itself was provided to override the actual file contents.
OptionalFileEntryRef OrigEntry
Reference to the file entry representing this ContentCache.
Information about a FileID, basically just the logical file that it represents and include stack info...
void setHasLineDirectives()
Set the flag that indicates that this FileID has line table entries associated with it.
Stmt - This represents one statement.
Definition Stmt.h:86
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition TypeLoc.h:816
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:824
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:805
Options for controlling the target.
std::string Triple
The name of the target triple to compile for.
std::vector< std::string > Features
The list of target specific features to enable or disable – this should be a list of strings starting...
std::string ABI
If given, the name of the target ABI to use.
std::string TuneCPU
If given, the name of the target CPU to tune code for.
std::string CPU
If given, the name of the target CPU to generate code for.
std::vector< std::string > FeaturesAsWritten
The list of target specific features to enable or disable, as written on the command line.
A convenient class for passing around template argument information.
Location wrapper for a TemplateArgument.
Represents a template argument.
Expr * getAsExpr() const
Retrieve the template argument as an expression.
ArgKind
The kind of template argument we're storing.
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
@ Template
The template argument is a template name that was provided for a template template parameter.
@ StructuralValue
The template argument is a non-type template argument that can't be represented by the special-case D...
@ Pack
The template argument is actually a parameter pack.
@ TemplateExpansion
The template argument is a pack expansion of a template name that was provided for a template templat...
@ NullPtr
The template argument is a null pointer or null pointer to member that was provided for a non-type te...
@ Type
The template argument is a type.
@ Null
Represents an empty template argument, e.g., one that has not been deduced.
@ Integral
The template argument is an integral value stored in an llvm::APSInt that was provided for an integra...
@ Expression
The template argument is an expression, and we've not resolved it to one of the other forms yet,...
ArgKind getKind() const
Return the kind of stored template argument.
Stores a list of template parameters for a TemplateDecl and its derived classes.
static TemplateParameterList * Create(const ASTContext &C, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > Params, SourceLocation RAngleLoc, Expr *RequiresClause)
MutableArrayRef< TemplateArgumentLocInfo > getArgLocInfos()
Definition TypeLoc.h:1913
void set(SourceLocation ElaboratedKeywordLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKeywordLoc, SourceLocation NameLoc, SourceLocation LAngleLoc, SourceLocation RAngleLoc)
Definition TypeLoc.cpp:648
Token - This structure provides full information about a lexed token.
Definition Token.h:36
[BoundsSafety] Represents information of declarations referenced by the arguments of the counted_by a...
Definition TypeBase.h:3406
TypeLocReader(ASTRecordReader &Reader)
void VisitArrayTypeLoc(ArrayTypeLoc)
void VisitFunctionTypeLoc(FunctionTypeLoc)
void VisitTagTypeLoc(TagTypeLoc TL)
RetTy Visit(TypeLoc TyLoc)
Base wrapper for a particular "section" of type source info.
Definition TypeLoc.h:59
TypeLoc getNextTypeLoc() const
Get the next TypeLoc pointed by this TypeLoc, e.g for "int*" the TypeLoc is a PointerLoc and next Typ...
Definition TypeLoc.h:171
bool isNull() const
Definition TypeLoc.h:121
void setUnmodifiedTInfo(TypeSourceInfo *TI) const
Definition TypeLoc.h:2265
A container of type source information.
Definition TypeBase.h:8402
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition TypeLoc.h:267
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:551
The base class of the type hierarchy.
Definition TypeBase.h:1866
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9261
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3577
void setLParenLoc(SourceLocation Loc)
Definition TypeLoc.h:2208
void setTypeofLoc(SourceLocation Loc)
Definition TypeLoc.h:2200
void setRParenLoc(SourceLocation Loc)
Definition TypeLoc.h:2216
void setRParenLoc(SourceLocation Loc)
Definition TypeLoc.h:2350
void setKWLoc(SourceLocation Loc)
Definition TypeLoc.h:2344
void setUnderlyingTInfo(TypeSourceInfo *TInfo)
Definition TypeLoc.h:2356
void setLParenLoc(SourceLocation Loc)
Definition TypeLoc.h:2347
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
Represents a variable declaration or definition.
Definition Decl.h:926
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2045
Captures information about a #pragma weak directive.
Definition Weak.h:25
@ Missing
The module file is missing.
@ OutOfDate
The module file is out-of-date.
@ NewlyLoaded
The module file was just loaded in response to this call.
@ AlreadyLoaded
The module file had already been loaded.
Source location and bit offset of a declaration.
A key used when looking up entities by DeclarationName.
unsigned getHash() const
Compute a fingerprint of this key for use in on-disk hash table.
The input file that has been loaded from this AST file, along with bools indicating whether this was ...
Definition ModuleFile.h:85
OptionalFileEntryRef getFile() const
Definition ModuleFile.h:114
static InputFile getNotFound()
Definition ModuleFile.h:108
Information about a module that has been loaded by the ASTReader.
Definition ModuleFile.h:158
const PPEntityOffset * PreprocessedEntityOffsets
Definition ModuleFile.h:417
void * IdentifierLookupTable
A pointer to an on-disk hash table of opaque type IdentifierHashTable.
Definition ModuleFile.h:372
void * SelectorLookupTable
A pointer to an on-disk hash table of opaque type ASTSelectorLookupTable.
Definition ModuleFile.h:480
std::vector< std::unique_ptr< ModuleFileExtensionReader > > ExtensionReaders
The list of extension readers that are attached to this module file.
Definition ModuleFile.h:284
SourceLocation DirectImportLoc
The source location where the module was explicitly or implicitly imported in the local translation u...
Definition ModuleFile.h:274
StringRef Data
The serialized bitstream data for this file.
Definition ModuleFile.h:260
const serialization::ObjCCategoriesInfo * ObjCCategoriesMap
Array of category list location information within this module file, sorted by the definition ID.
Definition ModuleFile.h:508
int SLocEntryBaseID
The base ID in the source manager's view of this module.
Definition ModuleFile.h:336
ModuleFileKey FileKey
The key ModuleManager used for the module file.
Definition ModuleFile.h:180
serialization::IdentifierID BaseIdentifierID
Base identifier ID for identifiers local to this module.
Definition ModuleFile.h:362
serialization::PreprocessedEntityID BasePreprocessedEntityID
Base preprocessed entity ID for preprocessed entities local to this module.
Definition ModuleFile.h:415
serialization::TypeID BaseTypeIndex
Base type ID for types local to this module as represented in the global type ID space.
Definition ModuleFile.h:528
unsigned LocalNumObjCCategoriesInMap
The number of redeclaration info entries in ObjCCategoriesMap.
Definition ModuleFile.h:511
uint64_t MacroOffsetsBase
Base file offset for the offsets in MacroOffsets.
Definition ModuleFile.h:389
const llvm::support::unaligned_uint64_t * InputFileOffsets
Relative offsets for all of the input file entries in the AST file.
Definition ModuleFile.h:299
std::vector< unsigned > PreloadIdentifierOffsets
Offsets of identifiers that we're going to preload within IdentifierTableData.
Definition ModuleFile.h:376
unsigned LocalNumIdentifiers
The number of identifiers in this AST file.
Definition ModuleFile.h:352
llvm::BitstreamCursor DeclsCursor
DeclsCursor - This is a cursor to the start of the DECLTYPES_BLOCK block.
Definition ModuleFile.h:487
const unsigned char * IdentifierTableData
Actual data for the on-disk hash table of identifiers.
Definition ModuleFile.h:368
uint64_t SLocEntryOffsetsBase
Base file offset for the offsets in SLocEntryOffsets.
Definition ModuleFile.h:343
llvm::BitstreamCursor InputFilesCursor
The cursor to the start of the input-files block.
Definition ModuleFile.h:293
std::vector< InputFile > InputFilesLoaded
The input files that have been loaded from this AST file.
Definition ModuleFile.h:302
serialization::SelectorID BaseSelectorID
Base selector ID for selectors local to this module.
Definition ModuleFile.h:465
llvm::SetVector< ModuleFile * > ImportedBy
List of modules which depend on this module.
Definition ModuleFile.h:536
const char * HeaderFileInfoTableData
Actual data for the on-disk hash table of header file information.
Definition ModuleFile.h:436
SourceLocation ImportLoc
The source location where this module was first imported.
Definition ModuleFile.h:277
const serialization::unaligned_decl_id_t * FileSortedDecls
Array of file-level DeclIDs sorted by file.
Definition ModuleFile.h:503
const uint32_t * SLocEntryOffsets
Offsets for all of the source location entries in the AST file.
Definition ModuleFile.h:347
llvm::BitstreamCursor MacroCursor
The cursor to the start of the preprocessor block, which stores all of the macro definitions.
Definition ModuleFile.h:382
FileID OriginalSourceFileID
The file ID for the original source file that was used to build this AST file.
Definition ModuleFile.h:203
time_t ModTime
Modification of the module file.
Definition ModuleFile.h:223
std::string ActualOriginalSourceFileName
The actual original source file name that was used to build this AST file.
Definition ModuleFile.h:199
uint64_t PreprocessorDetailStartOffset
The offset of the start of the preprocessor detail cursor.
Definition ModuleFile.h:411
std::vector< InputFileInfo > InputFileInfosLoaded
The input file infos that have been loaded from this AST file.
Definition ModuleFile.h:305
unsigned LocalNumSubmodules
The number of submodules in this module.
Definition ModuleFile.h:445
SourceLocation FirstLoc
The first source location in this module.
Definition ModuleFile.h:280
ASTFileSignature ASTBlockHash
The signature of the AST block of the module file, this can be used to unique module files based on A...
Definition ModuleFile.h:231
uint64_t SourceManagerBlockStartOffset
The bit offset to the start of the SOURCE_MANAGER_BLOCK.
Definition ModuleFile.h:330
bool DidReadTopLevelSubmodule
Whether the top-level module has been read from the AST file.
Definition ModuleFile.h:217
std::string OriginalSourceFileName
The original source file name that was used to build the primary AST file, which may have been modifi...
Definition ModuleFile.h:195
bool isModule() const
Is this a module file for a module (rather than a PCH or similar).
Definition ModuleFile.h:554
bool HasTimestamps
Whether timestamps are included in this module file.
Definition ModuleFile.h:214
uint64_t InputFilesOffsetBase
Absolute offset of the start of the input-files block.
Definition ModuleFile.h:296
llvm::BitstreamCursor SLocEntryCursor
Cursor used to read source location entries.
Definition ModuleFile.h:327
bool RelocatablePCH
Whether this precompiled header is a relocatable PCH file.
Definition ModuleFile.h:208
const uint32_t * SelectorOffsets
Offsets into the selector lookup table's data array where each selector resides.
Definition ModuleFile.h:462
unsigned BaseDeclIndex
Base declaration index in ASTReader for declarations local to this module.
Definition ModuleFile.h:500
unsigned LocalNumSLocEntries
The number of source location entries in this AST file.
Definition ModuleFile.h:333
void * HeaderFileInfoTable
The on-disk hash table that contains information about each of the header files.
Definition ModuleFile.h:440
unsigned Index
The index of this module in the list of modules.
Definition ModuleFile.h:171
llvm::BitstreamCursor Stream
The main bitstream cursor for the main block.
Definition ModuleFile.h:263
serialization::SubmoduleID BaseSubmoduleID
Base submodule ID for submodules local to this module.
Definition ModuleFile.h:448
uint64_t SizeInBits
The size of this file, in bits.
Definition ModuleFile.h:251
const UnalignedUInt64 * TypeOffsets
Offset of each type within the bitstream, indexed by the type ID, or the representation of a Type*.
Definition ModuleFile.h:524
uint64_t GlobalBitOffset
The global bit offset (or base) of this module.
Definition ModuleFile.h:254
bool StandardCXXModule
Whether this module file is a standard C++ module.
Definition ModuleFile.h:211
unsigned LocalNumTypes
The number of types in this AST file.
Definition ModuleFile.h:520
StringRef ModuleOffsetMap
The module offset map data for this file.
Definition ModuleFile.h:288
const PPSkippedRange * PreprocessedSkippedRangeOffsets
Definition ModuleFile.h:423
uint64_t InputFilesValidationTimestamp
If non-zero, specifies the time when we last validated input files.
Definition ModuleFile.h:315
llvm::BitstreamCursor PreprocessorDetailCursor
The cursor to the start of the (optional) detailed preprocessing record block.
Definition ModuleFile.h:408
SourceLocation::UIntTy SLocEntryBaseOffset
The base offset in the source manager's view of this module.
Definition ModuleFile.h:339
bool isDirectlyImported() const
Determine whether this module was directly imported at any point during translation.
Definition ModuleFile.h:551
const DeclOffset * DeclOffsets
Offset of each declaration within the bitstream, indexed by the declaration ID (-1).
Definition ModuleFile.h:497
uint64_t MacroStartOffset
The offset of the start of the set of defined macros.
Definition ModuleFile.h:402
ASTFileSignature Signature
The signature of the module file, which may be used instead of the size and modification time to iden...
Definition ModuleFile.h:227
unsigned LocalNumMacros
The number of macros in this AST file.
Definition ModuleFile.h:385
const unsigned char * SelectorLookupTableData
A pointer to the character data that comprises the selector table.
Definition ModuleFile.h:473
void dump()
Dump debugging output for this module.
unsigned LocalNumDecls
The number of declarations in this AST file.
Definition ModuleFile.h:493
unsigned LocalNumHeaderFileInfos
The number of local HeaderFileInfo structures.
Definition ModuleFile.h:429
llvm::BitVector SearchPathUsage
The bit vector denoting usage of each header search entry (true = used).
Definition ModuleFile.h:234
InputFilesValidation InputFilesValidationStatus
Captures the high-level result of validating input files.
Definition ModuleFile.h:322
unsigned Generation
The generation of which this module file is a part.
Definition ModuleFile.h:244
const uint32_t * IdentifierOffsets
Offsets into the identifier table data.
Definition ModuleFile.h:359
ContinuousRangeMap< uint32_t, int, 2 > SelectorRemap
Remapping table for selector IDs in this module.
Definition ModuleFile.h:468
const uint32_t * MacroOffsets
Offsets of macros in the preprocessor block.
Definition ModuleFile.h:396
uint64_t ASTBlockStartOffset
The bit offset of the AST block of this module.
Definition ModuleFile.h:257
ModuleFileName FileName
The file name of the module file.
Definition ModuleFile.h:177
ContinuousRangeMap< uint32_t, int, 2 > SubmoduleRemap
Remapping table for submodule IDs in this module.
Definition ModuleFile.h:451
llvm::BitVector VFSUsage
The bit vector denoting usage of each VFS entry (true = used).
Definition ModuleFile.h:237
uint64_t DeclsBlockStartOffset
The offset to the start of the DECLTYPES_BLOCK block.
Definition ModuleFile.h:490
SmallVector< uint64_t, 8 > PragmaDiagMappings
Diagnostic IDs and their mappings that the user changed.
Definition ModuleFile.h:533
unsigned BasePreprocessedSkippedRangeID
Base ID for preprocessed skipped ranges local to this module.
Definition ModuleFile.h:421
unsigned LocalNumSelectors
The number of selectors new to this file.
Definition ModuleFile.h:458
ModuleKind Kind
The type of this module.
Definition ModuleFile.h:174
std::string ModuleName
The name of the module.
Definition ModuleFile.h:183
serialization::MacroID BaseMacroID
Base macro ID for macros local to this module.
Definition ModuleFile.h:399
SmallVector< uint64_t, 1 > ObjCCategories
The Objective-C category lists for categories known to this module.
Definition ModuleFile.h:515
std::string BaseDirectory
The base directory of the module.
Definition ModuleFile.h:186
llvm::SmallVector< ModuleFile *, 16 > TransitiveImports
List of modules which this modules dependent on.
Definition ModuleFile.h:547
Manages the set of modules loaded by an AST reader.
llvm::iterator_range< SmallVectorImpl< ModuleFile * >::const_iterator > pch_modules() const
A range covering the PCH and preamble module files loaded.
ModuleReverseIterator rbegin()
Reverse iterator to traverse all loaded modules.
unsigned size() const
Number of modules loaded.
Source range/offset of a preprocessed entity.
RawLocEncoding getBegin() const
Source range of a skipped preprocessor region.
RawLocEncoding getBegin() const
ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel, unsigned PriorGeneration)
ArrayRef< ObjCMethodDecl * > getInstanceMethods() const
Retrieve the instance methods found by this visitor.
ArrayRef< ObjCMethodDecl * > getFactoryMethods() const
Retrieve the instance methods found by this visitor.
static TypeIdx fromTypeID(TypeID ID)
32 aligned uint64_t in the AST file.
static std::pair< unsigned, unsigned > ReadKeyDataLength(const unsigned char *&d)
void ReadDataIntoImpl(const unsigned char *d, unsigned DataLen, data_type_builder &Val)
DeclarationNameKey ReadKeyBase(const unsigned char *&d)
internal_key_type ReadKey(const unsigned char *d, unsigned)
void ReadDataInto(internal_key_type, const unsigned char *d, unsigned DataLen, data_type_builder &Val)
static std::pair< unsigned, unsigned > ReadKeyDataLength(const unsigned char *&d)
static hash_value_type ComputeHash(const internal_key_type &a)
static internal_key_type ReadKey(const unsigned char *d, unsigned n)
Class that performs lookup for an identifier stored in an AST file.
IdentifierID ReadIdentifierID(const unsigned char *d)
data_type ReadData(const internal_key_type &k, const unsigned char *d, unsigned DataLen)
Class that performs lookup for a selector's entries in the global method pool stored in an AST file.
internal_key_type ReadKey(const unsigned char *d, unsigned)
data_type ReadData(Selector, const unsigned char *d, unsigned DataLen)
static std::pair< unsigned, unsigned > ReadKeyDataLength(const unsigned char *&d)
static hash_value_type ComputeHash(Selector Sel)
static std::pair< unsigned, unsigned > ReadKeyDataLength(const unsigned char *&d)
internal_key_type GetInternalKey(external_key_type ekey)
bool EqualKey(internal_key_ref a, internal_key_ref b)
static hash_value_type ComputeHash(internal_key_ref ikey)
data_type ReadData(internal_key_ref, const unsigned char *d, unsigned DataLen)
static internal_key_type ReadKey(const unsigned char *d, unsigned)
Class that performs lookup to specialized decls.
void ReadDataInto(internal_key_type, const unsigned char *d, unsigned DataLen, data_type_builder &Val)
static std::pair< unsigned, unsigned > ReadKeyDataLength(const unsigned char *&d)
internal_key_type ReadKey(const unsigned char *d, unsigned)
std::pair< DeclarationName, const Module * > external_key_type
void ReadDataInto(internal_key_type, const unsigned char *d, unsigned DataLen, data_type_builder &Val)
std::pair< DeclarationNameKey, unsigned > internal_key_type
internal_key_type ReadKey(const unsigned char *d, unsigned)
static hash_value_type ComputeHash(const internal_key_type &Key)
static internal_key_type GetInternalKey(const external_key_type &Key)
PredefinedTypeIDs
Predefined type IDs.
CtorInitializerType
The different kinds of data that can occur in a CtorInitializer.
const unsigned NUM_PREDEF_TYPE_IDS
The number of predefined type IDs that are reserved for the PREDEF_TYPE_* constants.
const unsigned NumSpecialTypeIDs
The number of special type IDs.
TypeCode
Record codes for each kind of type.
@ PREDEF_TYPE_LONG_ACCUM_ID
The 'long _Accum' type.
@ PREDEF_TYPE_SAMPLER_ID
OpenCL sampler type.
@ PREDEF_TYPE_INT128_ID
The '__int128_t' type.
@ PREDEF_TYPE_CHAR32_ID
The C++ 'char32_t' type.
@ PREDEF_TYPE_SAT_SHORT_ACCUM_ID
The '_Sat short _Accum' type.
@ PREDEF_TYPE_IBM128_ID
The '__ibm128' type.
@ PREDEF_TYPE_SHORT_FRACT_ID
The 'short _Fract' type.
@ PREDEF_TYPE_AUTO_RREF_DEDUCT
The "auto &&" deduction type.
@ PREDEF_TYPE_BOUND_MEMBER
The placeholder type for bound member functions.
@ PREDEF_TYPE_LONGLONG_ID
The (signed) 'long long' type.
@ PREDEF_TYPE_FRACT_ID
The '_Fract' type.
@ PREDEF_TYPE_ARC_UNBRIDGED_CAST
ARC's unbridged-cast placeholder type.
@ PREDEF_TYPE_USHORT_FRACT_ID
The 'unsigned short _Fract' type.
@ PREDEF_TYPE_SAT_ULONG_FRACT_ID
The '_Sat unsigned long _Fract' type.
@ PREDEF_TYPE_BOOL_ID
The 'bool' or '_Bool' type.
@ PREDEF_TYPE_SAT_LONG_ACCUM_ID
The '_Sat long _Accum' type.
@ PREDEF_TYPE_SAT_LONG_FRACT_ID
The '_Sat long _Fract' type.
@ PREDEF_TYPE_SAT_SHORT_FRACT_ID
The '_Sat short _Fract' type.
@ PREDEF_TYPE_CHAR_U_ID
The 'char' type, when it is unsigned.
@ PREDEF_TYPE_RESERVE_ID_ID
OpenCL reserve_id type.
@ PREDEF_TYPE_SAT_ACCUM_ID
The '_Sat _Accum' type.
@ PREDEF_TYPE_BUILTIN_FN
The placeholder type for builtin functions.
@ PREDEF_TYPE_SHORT_ACCUM_ID
The 'short _Accum' type.
@ PREDEF_TYPE_FLOAT_ID
The 'float' type.
@ PREDEF_TYPE_QUEUE_ID
OpenCL queue type.
@ PREDEF_TYPE_INT_ID
The (signed) 'int' type.
@ PREDEF_TYPE_OBJC_SEL
The ObjC 'SEL' type.
@ PREDEF_TYPE_BFLOAT16_ID
The '__bf16' type.
@ PREDEF_TYPE_WCHAR_ID
The C++ 'wchar_t' type.
@ PREDEF_TYPE_UCHAR_ID
The 'unsigned char' type.
@ PREDEF_TYPE_UACCUM_ID
The 'unsigned _Accum' type.
@ PREDEF_TYPE_SCHAR_ID
The 'signed char' type.
@ PREDEF_TYPE_CHAR_S_ID
The 'char' type, when it is signed.
@ PREDEF_TYPE_NULLPTR_ID
The type of 'nullptr'.
@ PREDEF_TYPE_ULONG_FRACT_ID
The 'unsigned long _Fract' type.
@ PREDEF_TYPE_FLOAT16_ID
The '_Float16' type.
@ PREDEF_TYPE_UINT_ID
The 'unsigned int' type.
@ PREDEF_TYPE_FLOAT128_ID
The '__float128' type.
@ PREDEF_TYPE_OBJC_ID
The ObjC 'id' type.
@ PREDEF_TYPE_CHAR16_ID
The C++ 'char16_t' type.
@ PREDEF_TYPE_ARRAY_SECTION
The placeholder type for an array section.
@ PREDEF_TYPE_ULONGLONG_ID
The 'unsigned long long' type.
@ PREDEF_TYPE_SAT_UFRACT_ID
The '_Sat unsigned _Fract' type.
@ PREDEF_TYPE_USHORT_ID
The 'unsigned short' type.
@ PREDEF_TYPE_SHORT_ID
The (signed) 'short' type.
@ PREDEF_TYPE_OMP_ARRAY_SHAPING
The placeholder type for OpenMP array shaping operation.
@ PREDEF_TYPE_DEPENDENT_ID
The placeholder type for dependent types.
@ PREDEF_TYPE_LONGDOUBLE_ID
The 'long double' type.
@ PREDEF_TYPE_DOUBLE_ID
The 'double' type.
@ PREDEF_TYPE_UINT128_ID
The '__uint128_t' type.
@ PREDEF_TYPE_HALF_ID
The OpenCL 'half' / ARM NEON __fp16 type.
@ PREDEF_TYPE_VOID_ID
The void type.
@ PREDEF_TYPE_SAT_USHORT_FRACT_ID
The '_Sat unsigned short _Fract' type.
@ PREDEF_TYPE_ACCUM_ID
The '_Accum' type.
@ PREDEF_TYPE_SAT_FRACT_ID
The '_Sat _Fract' type.
@ PREDEF_TYPE_NULL_ID
The NULL type.
@ PREDEF_TYPE_USHORT_ACCUM_ID
The 'unsigned short _Accum' type.
@ PREDEF_TYPE_CHAR8_ID
The C++ 'char8_t' type.
@ PREDEF_TYPE_UFRACT_ID
The 'unsigned _Fract' type.
@ PREDEF_TYPE_OVERLOAD_ID
The placeholder type for overloaded function sets.
@ PREDEF_TYPE_INCOMPLETE_MATRIX_IDX
A placeholder type for incomplete matrix index operations.
@ PREDEF_TYPE_UNRESOLVED_TEMPLATE
The placeholder type for unresolved templates.
@ PREDEF_TYPE_SAT_USHORT_ACCUM_ID
The '_Sat unsigned short _Accum' type.
@ PREDEF_TYPE_LONG_ID
The (signed) 'long' type.
@ PREDEF_TYPE_SAT_ULONG_ACCUM_ID
The '_Sat unsigned long _Accum' type.
@ PREDEF_TYPE_LONG_FRACT_ID
The 'long _Fract' type.
@ PREDEF_TYPE_UNKNOWN_ANY
The 'unknown any' placeholder type.
@ PREDEF_TYPE_OMP_ITERATOR
The placeholder type for OpenMP iterator expression.
@ PREDEF_TYPE_PSEUDO_OBJECT
The pseudo-object placeholder type.
@ PREDEF_TYPE_OBJC_CLASS
The ObjC 'Class' type.
@ PREDEF_TYPE_ULONG_ID
The 'unsigned long' type.
@ PREDEF_TYPE_SAT_UACCUM_ID
The '_Sat unsigned _Accum' type.
@ PREDEF_TYPE_CLK_EVENT_ID
OpenCL clk event type.
@ PREDEF_TYPE_EVENT_ID
OpenCL event type.
@ PREDEF_TYPE_ULONG_ACCUM_ID
The 'unsigned long _Accum' type.
@ PREDEF_TYPE_AUTO_DEDUCT
The "auto" deduction type.
@ DECL_CXX_BASE_SPECIFIERS
A record containing CXXBaseSpecifiers.
@ DECL_CONTEXT_TU_LOCAL_VISIBLE
A record that stores the set of declarations that are only visible to the TU.
@ DECL_CONTEXT_LEXICAL
A record that stores the set of declarations that are lexically stored within a given DeclContext.
@ DECL_CXX_CTOR_INITIALIZERS
A record containing CXXCtorInitializers.
@ DECL_CONTEXT_MODULE_LOCAL_VISIBLE
A record containing the set of declarations that are only visible from DeclContext in the same module...
@ DECL_CONTEXT_VISIBLE
A record that stores the set of declarations that are visible from a given DeclContext.
@ TYPE_EXT_QUAL
An ExtQualType record.
@ SPECIAL_TYPE_OBJC_SEL_REDEFINITION
Objective-C "SEL" redefinition type.
@ SPECIAL_TYPE_UCONTEXT_T
C ucontext_t typedef type.
@ SPECIAL_TYPE_JMP_BUF
C jmp_buf typedef type.
@ SPECIAL_TYPE_FILE
C FILE typedef type.
@ SPECIAL_TYPE_SIGJMP_BUF
C sigjmp_buf typedef type.
@ SPECIAL_TYPE_OBJC_CLASS_REDEFINITION
Objective-C "Class" redefinition type.
@ SPECIAL_TYPE_CF_CONSTANT_STRING
CFConstantString type.
@ SPECIAL_TYPE_OBJC_ID_REDEFINITION
Objective-C "id" redefinition type.
Defines the clang::TargetInfo interface.
CharacteristicKind
Indicates whether a file or directory holds normal user code, system code, or system code which is im...
internal::Matcher< T > findAll(const internal::Matcher< T > &Matcher)
Matches if the node or any descendant matches.
@ ModuleFile
The module file (.pcm). Required.
unsigned kind
All of the diagnostics that can be emitted by the frontend.
Severity
Enum values that allow the client to map NOTEs, WARNINGs, and EXTENSIONs to either Ignore (nothing),...
@ Warning
Present this diagnostic as a warning.
@ Error
Present this diagnostic as an error.
IncludeDirGroup
IncludeDirGroup - Identifies the group an include Entry belongs to, representing its relative positiv...
std::variant< struct RequiresDecl, struct HeaderDecl, struct UmbrellaDirDecl, struct ModuleDecl, struct ExcludeDecl, struct ExportDecl, struct ExportAsDecl, struct ExternModuleDecl, struct UseDecl, struct LinkDecl, struct ConfigMacrosDecl, struct ConflictDecl > Decl
All declarations that can appear in a module declaration.
llvm::OnDiskChainedHashTable< ASTSelectorLookupTrait > ASTSelectorLookupTable
The on-disk hash table used for the global method pool.
llvm::OnDiskChainedHashTable< HeaderFileInfoTrait > HeaderFileInfoLookupTable
The on-disk hash table used for known header files.
llvm::OnDiskIterableChainedHashTable< ASTIdentifierLookupTrait > ASTIdentifierLookupTable
The on-disk hash table used to contain information about all of the identifiers in the program.
@ EXTENSION_METADATA
Metadata describing this particular extension.
@ 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:144
@ AllFiles
When the validation is done both for user files and system files.
Definition ModuleFile.h:148
@ Disabled
When the validation is disabled. For example, for a precompiled header.
Definition ModuleFile.h:141
@ UserFiles
When the validation is done only for user files as an optimization.
Definition ModuleFile.h:146
const unsigned int NUM_PREDEF_IDENT_IDS
The number of predefined identifier IDs.
Definition ASTBitCodes.h:66
OptionsRecordTypes
Record types that occur within the options block inside the control block.
@ FILE_SYSTEM_OPTIONS
Record code for the filesystem options table.
@ TARGET_OPTIONS
Record code for the target options table.
@ PREPROCESSOR_OPTIONS
Record code for the preprocessor options table.
@ HEADER_SEARCH_OPTIONS
Record code for the headers search options table.
@ CODEGEN_OPTIONS
Record code for the codegen options table.
@ LANGUAGE_OPTIONS
Record code for the language options table.
const unsigned int NUM_PREDEF_PP_ENTITY_IDS
The number of predefined preprocessed entity IDs.
const unsigned int NUM_PREDEF_SUBMODULE_IDS
The number of predefined submodule IDs.
@ SUBMODULE_BLOCK_ID
The block containing the submodule structure.
@ PREPROCESSOR_DETAIL_BLOCK_ID
The block containing the detailed preprocessing record.
@ AST_BLOCK_ID
The AST block, which acts as a container around the full AST block.
@ SOURCE_MANAGER_BLOCK_ID
The block containing information about the source manager.
@ CONTROL_BLOCK_ID
The control block, which contains all of the information that needs to be validated prior to committi...
@ DECLTYPES_BLOCK_ID
The block containing the definitions of all of the types and decls used within the AST file.
@ PREPROCESSOR_BLOCK_ID
The block containing information about the preprocessor.
@ COMMENTS_BLOCK_ID
The block containing comments.
@ UNHASHED_CONTROL_BLOCK_ID
A block with unhashed content.
@ EXTENSION_BLOCK_ID
A block containing a module file extension.
@ OPTIONS_BLOCK_ID
The block of configuration options, used to check that a module is being used in a configuration comp...
@ INPUT_FILES_BLOCK_ID
The block of input files, which were used as inputs to create this AST file.
unsigned StableHashForTemplateArguments(llvm::ArrayRef< TemplateArgument > Args)
Calculate a stable hash value for template arguments.
CommentRecordTypes
Record types used within a comments block.
DeclIDBase::DeclID DeclID
An ID number that refers to a declaration in an AST file.
Definition ASTBitCodes.h:70
@ SM_SLOC_FILE_ENTRY
Describes a source location entry (SLocEntry) for a file.
@ SM_SLOC_BUFFER_BLOB_COMPRESSED
Describes a zlib-compressed blob that contains the data for a buffer entry.
@ SM_SLOC_BUFFER_ENTRY
Describes a source location entry (SLocEntry) for a buffer.
@ SM_SLOC_BUFFER_BLOB
Describes a blob that contains the data for a buffer entry.
@ SM_SLOC_EXPANSION_ENTRY
Describes a source location entry (SLocEntry) for a macro expansion.
const unsigned int NUM_PREDEF_SELECTOR_IDS
The number of predefined selector IDs.
bool needsAnonymousDeclarationNumber(const NamedDecl *D)
Determine whether the given declaration needs an anonymous declaration number.
const unsigned VERSION_MAJOR
AST file major version number supported by this version of Clang.
Definition ASTBitCodes.h:47
uint64_t PreprocessedEntityID
An ID number that refers to an entity in the detailed preprocessing record.
llvm::support::detail::packed_endian_specific_integral< serialization::DeclID, llvm::endianness::native, llvm::support::unaligned > unaligned_decl_id_t
PreprocessorRecordTypes
Record types used within a preprocessor block.
@ PP_TOKEN
Describes one token.
@ PP_MACRO_FUNCTION_LIKE
A function-like macro definition.
@ PP_MACRO_OBJECT_LIKE
An object-like macro definition.
@ PP_MACRO_DIRECTIVE_HISTORY
The macro directives history for a particular identifier.
@ PP_MODULE_MACRO
A macro directive exported by a module.
ControlRecordTypes
Record types that occur within the control block.
@ MODULE_MAP_FILE
Record code for the module map file that was used to build this AST file.
@ MODULE_DIRECTORY
Record code for the module build directory.
@ ORIGINAL_FILE_ID
Record code for file ID of the file or buffer that was used to generate the AST file.
@ MODULE_NAME
Record code for the module name.
@ ORIGINAL_FILE
Record code for the original file that was used to generate the AST file, including both its file ID ...
@ IMPORT
Record code for another AST file imported by this AST file.
@ INPUT_FILE_OFFSETS
Offsets into the input-files block where input files reside.
@ METADATA
AST file metadata, including the AST file version number and information about the compiler used to b...
UnhashedControlBlockRecordTypes
Record codes for the unhashed control block.
@ DIAGNOSTIC_OPTIONS
Record code for the diagnostic options table.
@ HEADER_SEARCH_ENTRY_USAGE
Record code for the indices of used header search entries.
@ AST_BLOCK_HASH
Record code for the content hash of the AST block.
@ DIAG_PRAGMA_MAPPINGS
Record code for #pragma diagnostic mappings.
@ SIGNATURE
Record code for the signature that identifiers this AST file.
@ HEADER_SEARCH_PATHS
Record code for the headers search paths.
@ VFS_USAGE
Record code for the indices of used VFSs.
uint64_t MacroID
An ID number that refers to a macro in an AST file.
InputFileRecordTypes
Record types that occur within the input-files block inside the control block.
@ INPUT_FILE_HASH
The input file content hash.
@ INPUT_FILE
An input file.
uint64_t TypeID
An ID number that refers to a type in an AST file.
Definition ASTBitCodes.h:88
PreprocessorDetailRecordTypes
Record types used within a preprocessor detail block.
@ PPD_INCLUSION_DIRECTIVE
Describes an inclusion directive within the preprocessing record.
@ PPD_MACRO_EXPANSION
Describes a macro expansion within the preprocessing record.
@ PPD_MACRO_DEFINITION
Describes a macro definition within the preprocessing record.
ModuleKind
Specifies the kind of module that has been loaded.
Definition ModuleFile.h:44
@ MK_PCH
File is a PCH file treated as such.
Definition ModuleFile.h:52
@ MK_Preamble
File is a PCH file treated as the preamble.
Definition ModuleFile.h:55
@ MK_MainFile
File is a PCH file treated as the actual main file.
Definition ModuleFile.h:58
@ MK_ExplicitModule
File is an explicitly-loaded module.
Definition ModuleFile.h:49
@ MK_ImplicitModule
File is an implicitly-loaded module.
Definition ModuleFile.h:46
@ MK_PrebuiltModule
File is from a prebuilt module path.
Definition ModuleFile.h:61
uint32_t SubmoduleID
An ID number that refers to a submodule in a module file.
const unsigned int NUM_PREDEF_MACRO_IDS
The number of predefined macro IDs.
ASTRecordTypes
Record types that occur within the AST block itself.
@ DECL_UPDATE_OFFSETS
Record for offsets of DECL_UPDATES records for declarations that were modified after being deserializ...
@ STATISTICS
Record code for the extra statistics we gather while generating an AST file.
@ FLOAT_CONTROL_PRAGMA_OPTIONS
Record code for #pragma float_control options.
@ KNOWN_NAMESPACES
Record code for the set of known namespaces, which are used for typo correction.
@ SPECIAL_TYPES
Record code for the set of non-builtin, special types.
@ PENDING_IMPLICIT_INSTANTIATIONS
Record code for pending implicit instantiations.
@ TYPE_OFFSET
Record code for the offsets of each type.
@ DELEGATING_CTORS
The list of delegating constructor declarations.
@ PP_ASSUME_NONNULL_LOC
ID 66 used to be the list of included files.
@ EXT_VECTOR_DECLS
Record code for the set of ext_vector type names.
@ OPENCL_EXTENSIONS
Record code for enabled OpenCL extensions.
@ FP_PRAGMA_OPTIONS
Record code for floating point #pragma options.
@ PP_UNSAFE_BUFFER_USAGE
Record code for #pragma clang unsafe_buffer_usage begin/end.
@ CXX_ADDED_TEMPLATE_PARTIAL_SPECIALIZATION
@ DECLS_WITH_EFFECTS_TO_VERIFY
Record code for Sema's vector of functions/blocks with effects to be verified.
@ VTABLE_USES
Record code for the array of VTable uses.
@ LATE_PARSED_TEMPLATE
Record code for late parsed template functions.
@ DECLS_TO_CHECK_FOR_DEFERRED_DIAGS
Record code for the Decls to be checked for deferred diags.
@ DECL_OFFSET
Record code for the offsets of each decl.
@ SOURCE_MANAGER_LINE_TABLE
Record code for the source manager line table information, which stores information about #line direc...
@ PP_COUNTER_VALUE
The value of the next COUNTER to dispense.
@ DELETE_EXPRS_TO_ANALYZE
Delete expressions that will be analyzed later.
@ EXTNAME_UNDECLARED_IDENTIFIERS
Record code for extname-redefined undeclared identifiers.
@ RELATED_DECLS_MAP
Record code for related declarations that have to be deserialized together from the same module.
@ UPDATE_VISIBLE
Record code for an update to a decl context's lookup table.
@ CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH
Number of unmatched pragma clang cuda_force_host_device begin directives we've seen.
@ MACRO_OFFSET
Record code for the table of offsets of each macro ID.
@ PPD_ENTITIES_OFFSETS
Record code for the table of offsets to entries in the preprocessing record.
@ RISCV_VECTOR_INTRINSICS_PRAGMA
Record code for pragma clang riscv intrinsic vector.
@ VTABLES_TO_EMIT
Record code for vtables to emit.
@ IDENTIFIER_OFFSET
Record code for the table of offsets of each identifier ID.
@ OBJC_CATEGORIES
Record code for the array of Objective-C categories (including extensions).
@ METHOD_POOL
Record code for the Objective-C method pool,.
@ DELAYED_NAMESPACE_LEXICAL_VISIBLE_RECORD
Record code for lexical and visible block for delayed namespace in reduced BMI.
@ PP_CONDITIONAL_STACK
The stack of open ifs/ifdefs recorded in a preamble.
@ REFERENCED_SELECTOR_POOL
Record code for referenced selector pool.
@ SOURCE_LOCATION_OFFSETS
Record code for the table of offsets into the block of source-location information.
@ WEAK_UNDECLARED_IDENTIFIERS
Record code for weak undeclared identifiers.
@ UNDEFINED_BUT_USED
Record code for undefined but used functions and variables that need a definition in this TU.
@ FILE_SORTED_DECLS
Record code for a file sorted array of DeclIDs in a module.
@ MSSTRUCT_PRAGMA_OPTIONS
Record code for #pragma ms_struct options.
@ TENTATIVE_DEFINITIONS
Record code for the array of tentative definitions.
@ UNUSED_FILESCOPED_DECLS
Record code for the array of unused file scoped decls.
@ ALIGN_PACK_PRAGMA_OPTIONS
Record code for #pragma align/pack options.
@ IMPORTED_MODULES
Record code for an array of all of the (sub)modules that were imported by the AST file.
@ SELECTOR_OFFSETS
Record code for the table of offsets into the Objective-C method pool.
@ UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES
Record code for potentially unused local typedef names.
@ EAGERLY_DESERIALIZED_DECLS
Record code for the array of eagerly deserialized decls.
@ INTERESTING_IDENTIFIERS
A list of "interesting" identifiers.
@ HEADER_SEARCH_TABLE
Record code for header search information.
@ OBJC_CATEGORIES_MAP
Record code for map of Objective-C class definition IDs to the ObjC categories in a module that are a...
@ CUDA_SPECIAL_DECL_REFS
Record code for special CUDA declarations.
@ TU_UPDATE_LEXICAL
Record code for an update to the TU's lexically contained declarations.
@ PPD_SKIPPED_RANGES
A table of skipped ranges within the preprocessing record.
@ IDENTIFIER_TABLE
Record code for the identifier table.
@ SEMA_DECL_REFS
Record code for declarations that Sema keeps references of.
@ OPTIMIZE_PRAGMA_OPTIONS
Record code for #pragma optimize options.
@ MODULE_OFFSET_MAP
Record code for the remapping information used to relate loaded modules to the various offsets and ID...
@ POINTERS_TO_MEMBERS_PRAGMA_OPTIONS
Record code for #pragma ms_struct options.
unsigned ComputeHash(Selector Sel)
TypeID LocalTypeID
Same with TypeID except that the LocalTypeID is only meaningful with the corresponding ModuleFile.
Definition ASTBitCodes.h:94
uint64_t IdentifierID
An ID number that refers to an identifier in an AST file.
Definition ASTBitCodes.h:63
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition TokenKinds.h:25
The JSON file list parser is used to communicate input to InstallAPI.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
OpenACCReductionOperator
bool isa(CodeGen::Address addr)
Definition Address.h:330
CustomizableOptional< FileEntryRef > OptionalFileEntryRef
Definition FileEntry.h:208
SanitizerMask getPPTransparentSanitizers()
Return the sanitizers which do not affect preprocessing.
Definition Sanitizers.h:230
@ CPlusPlus
OpenMPDefaultClauseVariableCategory
OpenMP variable-category for 'default' clause.
OpenACCModifierKind
OpenMPDefaultmapClauseModifier
OpenMP modifiers for 'defaultmap' clause.
OpenMPOrderClauseModifier
OpenMP modifiers for 'order' clause.
std::vector< std::string > Macros
A list of macros of the form <definition>=<expansion> .
Definition Format.h:3949
@ Success
Annotation was successful.
Definition Parser.h:65
std::pair< FileID, unsigned > FileIDAndOffset
OpenMPAtClauseKind
OpenMP attributes for 'at' clause.
OpenMPReductionClauseModifier
OpenMP modifiers for 'reduction' clause.
OpenACCClauseKind
Represents the kind of an OpenACC clause.
@ Auto
'auto' clause, allowed on 'loop' directives.
@ Bind
'bind' clause, allowed on routine constructs.
@ Gang
'gang' clause, allowed on 'loop' and Combined constructs.
@ Wait
'wait' clause, allowed on Compute, Data, 'update', and Combined constructs.
@ DevicePtr
'deviceptr' clause, allowed on Compute and Combined Constructs, plus 'data' and 'declare'.
@ PCopyOut
'copyout' clause alias 'pcopyout'. Preserved for diagnostic purposes.
@ VectorLength
'vector_length' clause, allowed on 'parallel', 'kernels', 'parallel loop', and 'kernels loop' constru...
@ Async
'async' clause, allowed on Compute, Data, 'update', 'wait', and Combined constructs.
@ PresentOrCreate
'create' clause alias 'present_or_create'.
@ Collapse
'collapse' clause, allowed on 'loop' and Combined constructs.
@ NoHost
'nohost' clause, allowed on 'routine' directives.
@ PresentOrCopy
'copy' clause alias 'present_or_copy'. Preserved for diagnostic purposes.
@ DeviceNum
'device_num' clause, allowed on 'init', 'shutdown', and 'set' constructs.
@ Private
'private' clause, allowed on 'parallel', 'serial', 'loop', 'parallel loop', and 'serial loop' constru...
@ Invalid
Represents an invalid clause, for the purposes of parsing.
@ Vector
'vector' clause, allowed on 'loop', Combined, and 'routine' directives.
@ Copy
'copy' clause, allowed on Compute and Combined Constructs, plus 'data' and 'declare'.
@ Worker
'worker' clause, allowed on 'loop', Combined, and 'routine' directives.
@ Create
'create' clause, allowed on Compute and Combined constructs, plus 'data', 'enter data',...
@ DeviceType
'device_type' clause, allowed on Compute, 'data', 'init', 'shutdown', 'set', update',...
@ DefaultAsync
'default_async' clause, allowed on 'set' construct.
@ Attach
'attach' clause, allowed on Compute and Combined constructs, plus 'data' and 'enter data'.
@ Shortloop
'shortloop' is represented in the ACC.td file, but isn't present in the standard.
@ NumGangs
'num_gangs' clause, allowed on 'parallel', 'kernels', parallel loop', and 'kernels loop' constructs.
@ If
'if' clause, allowed on all the Compute Constructs, Data Constructs, Executable Constructs,...
@ Default
'default' clause, allowed on parallel, serial, kernel (and compound) constructs.
@ UseDevice
'use_device' clause, allowed on 'host_data' construct.
@ NoCreate
'no_create' clause, allowed on allowed on Compute and Combined constructs, plus 'data'.
@ PresentOrCopyOut
'copyout' clause alias 'present_or_copyout'.
@ Link
'link' clause, allowed on 'declare' construct.
@ Reduction
'reduction' clause, allowed on Parallel, Serial, Loop, and the combined constructs.
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
@ CopyOut
'copyout' clause, allowed on Compute and Combined constructs, plus 'data', 'exit data',...
@ Seq
'seq' clause, allowed on 'loop' and 'routine' directives.
@ FirstPrivate
'firstprivate' clause, allowed on 'parallel', 'serial', 'parallel loop', and 'serial loop' constructs...
@ Host
'host' clause, allowed on 'update' construct.
@ PCopy
'copy' clause alias 'pcopy'. Preserved for diagnostic purposes.
@ Tile
'tile' clause, allowed on 'loop' and Combined constructs.
@ PCopyIn
'copyin' clause alias 'pcopyin'. Preserved for diagnostic purposes.
@ DeviceResident
'device_resident' clause, allowed on the 'declare' construct.
@ PCreate
'create' clause alias 'pcreate'. Preserved for diagnostic purposes.
@ Present
'present' clause, allowed on Compute and Combined constructs, plus 'data' and 'declare'.
@ DType
'dtype' clause, an alias for 'device_type', stored separately for diagnostic purposes.
@ CopyIn
'copyin' clause, allowed on Compute and Combined constructs, plus 'data', 'enter data',...
@ Device
'device' clause, allowed on the 'update' construct.
@ Independent
'independent' clause, allowed on 'loop' directives.
@ NumWorkers
'num_workers' clause, allowed on 'parallel', 'kernels', parallel loop', and 'kernels loop' constructs...
@ IfPresent
'if_present' clause, allowed on 'host_data' and 'update' directives.
@ Detach
'detach' clause, allowed on the 'exit data' construct.
@ Delete
'delete' clause, allowed on the 'exit data' construct.
@ PresentOrCopyIn
'copyin' clause alias 'present_or_copyin'.
@ Finalize
'finalize' clause, allowed on 'exit data' directive.
OpenMPScheduleClauseModifier
OpenMP modifiers for 'schedule' clause.
Definition OpenMPKinds.h:39
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition Specifiers.h:124
SmallVector< Attr *, 4 > AttrVec
AttrVec - A vector of Attr, which is how they are stored on the AST.
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
OpenMPDistScheduleClauseKind
OpenMP attributes for 'dist_schedule' clause.
OpenMPDoacrossClauseModifier
OpenMP dependence types for 'doacross' clause.
OpenACCDefaultClauseKind
static constexpr unsigned NumberOfOMPMapClauseModifiers
Number of allowed map-type-modifiers.
Definition OpenMPKinds.h:88
OpenMPDynGroupprivateClauseFallbackModifier
@ Module
Module linkage, which indicates that the entity can be referred to from other translation units withi...
Definition Linkage.h:54
ObjCXXARCStandardLibraryKind
Enumerate the kinds of standard library that.
PredefinedDeclIDs
Predefined declaration IDs.
Definition DeclID.h:31
@ PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID
The internal '__NSConstantString' tag type.
Definition DeclID.h:78
@ PREDEF_DECL_TRANSLATION_UNIT_ID
The translation unit.
Definition DeclID.h:36
@ PREDEF_DECL_OBJC_CLASS_ID
The Objective-C 'Class' type.
Definition DeclID.h:45
@ PREDEF_DECL_BUILTIN_MS_GUID_ID
The predeclared '_GUID' struct.
Definition DeclID.h:69
@ PREDEF_DECL_BUILTIN_MS_TYPE_INFO_TAG_ID
The predeclared 'type_info' struct.
Definition DeclID.h:81
@ PREDEF_DECL_OBJC_INSTANCETYPE_ID
The internal 'instancetype' typedef.
Definition DeclID.h:57
@ PREDEF_DECL_OBJC_PROTOCOL_ID
The Objective-C 'Protocol' type.
Definition DeclID.h:48
@ PREDEF_DECL_UNSIGNED_INT_128_ID
The unsigned 128-bit integer type.
Definition DeclID.h:54
@ PREDEF_DECL_OBJC_SEL_ID
The Objective-C 'SEL' type.
Definition DeclID.h:42
@ NUM_PREDEF_DECL_IDS
The number of declaration IDs that are predefined.
Definition DeclID.h:87
@ PREDEF_DECL_INT_128_ID
The signed 128-bit integer type.
Definition DeclID.h:51
@ PREDEF_DECL_VA_LIST_TAG
The internal '__va_list_tag' struct, if any.
Definition DeclID.h:63
@ PREDEF_DECL_BUILTIN_MS_VA_LIST_ID
The internal '__builtin_ms_va_list' typedef.
Definition DeclID.h:66
@ PREDEF_DECL_CF_CONSTANT_STRING_ID
The internal '__NSConstantString' typedef.
Definition DeclID.h:75
@ PREDEF_DECL_NULL_ID
The NULL declaration.
Definition DeclID.h:33
@ PREDEF_DECL_BUILTIN_VA_LIST_ID
The internal '__builtin_va_list' typedef.
Definition DeclID.h:60
@ PREDEF_DECL_EXTERN_C_CONTEXT_ID
The extern "C" context.
Definition DeclID.h:72
@ PREDEF_DECL_OBJC_ID_ID
The Objective-C 'id' type.
Definition DeclID.h:39
@ Property
The type of a property.
Definition TypeBase.h:911
@ Result
The result type of a method or function.
Definition TypeBase.h:905
OpenMPBindClauseKind
OpenMP bindings for the 'bind' clause.
OptionalUnsigned< unsigned > UnsignedOrNone
std::string createSpecificModuleCachePath(FileManager &FileMgr, StringRef ModuleCachePath, bool DisableModuleHash, std::string ContextHash)
OpenMPLastprivateModifier
OpenMP 'lastprivate' clause modifier.
@ Template
We are parsing a template declaration.
Definition Parser.h:81
OpenMPDependClauseKind
OpenMP attributes for 'depend' clause.
Definition OpenMPKinds.h:55
OpenMPGrainsizeClauseModifier
OpenMPNumTasksClauseModifier
OpenMPUseDevicePtrFallbackModifier
OpenMP 6.1 use_device_ptr fallback modifier.
OpenMPSeverityClauseKind
OpenMP attributes for 'severity' clause.
void ProcessWarningOptions(DiagnosticsEngine &Diags, const DiagnosticOptions &Opts, llvm::vfs::FileSystem &VFS, bool ReportDiags=true)
ProcessWarningOptions - Initialize the diagnostic client and process the warning options specified on...
Definition Warnings.cpp:46
static constexpr unsigned NumberOfOMPMotionModifiers
Number of allowed motion-modifiers.
TypeSpecifierWidth
Specifies the width of a type, e.g., short, long, or long long.
Definition Specifiers.h:48
OpenMPMotionModifierKind
OpenMP modifier kind for 'to' or 'from' clause.
Definition OpenMPKinds.h:92
PragmaMSStructKind
Definition PragmaKinds.h:23
OpenMPDefaultmapClauseKind
OpenMP attributes for 'defaultmap' clause.
OpenMPAllocateClauseModifier
OpenMP modifiers for 'allocate' clause.
OpenMPLinearClauseKind
OpenMP attributes for 'linear' clause.
Definition OpenMPKinds.h:63
llvm::omp::Directive OpenMPDirectiveKind
OpenMP directives.
Definition OpenMPKinds.h:25
TypeSpecifierSign
Specifies the signedness of a type, e.g., signed or unsigned.
Definition Specifiers.h:51
OpenMPDynGroupprivateClauseModifier
DisableValidationForModuleKind
Whether to disable the normal validation performed on precompiled headers and module files when they ...
@ None
Perform validation, don't disable it.
@ PCH
Disable validation for a precompiled header and the modules it depends on.
@ Module
Disable validation for module files.
bool shouldSkipCheckingODR(const Decl *D)
Definition ASTReader.h:2739
std::string getClangFullRepositoryVersion()
Retrieves the full repository version that is an amalgamation of the information in getClangRepositor...
Definition Version.cpp:68
OpenMPNumThreadsClauseModifier
OpenMPAtomicDefaultMemOrderClauseKind
OpenMP attributes for 'atomic_default_mem_order' clause.
U cast(CodeGen::Address addr)
Definition Address.h:327
@ None
The alignment was not explicit in code.
Definition ASTContext.h:179
OpenMPDeviceClauseModifier
OpenMP modifiers for 'device' clause.
Definition OpenMPKinds.h:48
OpenMPMapModifierKind
OpenMP modifier kind for 'map' clause.
Definition OpenMPKinds.h:79
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5970
llvm::omp::Clause OpenMPClauseKind
OpenMP clauses.
Definition OpenMPKinds.h:28
OpenMPOrderClauseKind
OpenMP attributes for 'order' clause.
OpenMPScheduleClauseKind
OpenMP attributes for 'schedule' clause.
Definition OpenMPKinds.h:31
OpenMPThreadsetKind
OpenMP modifiers for 'threadset' clause.
UnsignedOrNone getPrimaryModuleHash(const Module *M)
Calculate a hash value for the primary module name of the given module.
OpenMPMapClauseKind
OpenMP mapping kind for 'map' clause.
Definition OpenMPKinds.h:71
unsigned long uint64_t
unsigned int uint32_t
#define true
Definition stdbool.h:25
__LIBC_ATTRS FILE * stderr
This structure contains all sizes needed for by an OMPMappableExprListClause.
unsigned NumComponents
Total number of expression components.
unsigned NumUniqueDeclarations
Number of unique base declarations.
unsigned NumVars
Number of expressions listed.
unsigned NumComponentLists
Number of component lists.
Expr * AllocatorTraits
Allocator traits.
SourceLocation LParenLoc
Locations of '(' and ')' symbols.
The signature of a module, which is a hash of the AST content.
Definition Module.h:160
static constexpr size_t size
Definition Module.h:163
static ASTFileSignature create(std::array< uint8_t, 20 > Bytes)
Definition Module.h:183
static ASTFileSignature createDummy()
Definition Module.h:193
Represents an explicit template argument list in C++, e.g., the "<int>" in "sort<int>".
static const ASTTemplateArgumentListInfo * Create(const ASTContext &C, const TemplateArgumentListInfo &List)
bool ParseAllComments
Treat ordinary comments as documentation comments.
BlockCommandNamesTy BlockCommandNames
Command names to treat as block commands in comments.
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
DeclarationName getName() const
getName - Returns the embedded declaration name.
void setLoc(SourceLocation L)
setLoc - Sets the main location of the declaration name.
void setInfo(const DeclarationNameLoc &Info)
void setName(DeclarationName N)
setName - Sets the embedded declaration name.
A simple structure that captures a vtable use for the purposes of the ExternalSemaSource.
The preprocessor keeps track of this information for each file that is #included.
void mergeModuleMembership(ModuleMap::ModuleHeaderRole Role)
Update the module membership bits based on the header role.
LazyIdentifierInfoPtr LazyControllingMacro
If this file has a #ifndef XXX (or equivalent) guard that protects the entire contents of the file,...
unsigned DirInfo
Keep track of whether this is a system header, and if so, whether it is C++ clean or not.
unsigned isPragmaOnce
True if this is a #pragma once file.
unsigned IsValid
Whether this file has been looked up as a header.
unsigned isImport
True if this is a #import'd file.
unsigned External
Whether this header file info was supplied by an external source, and has not changed since.
static LineEntry get(unsigned Offs, unsigned Line, int Filename, SrcMgr::CharacteristicKind FileKind, unsigned IncludeOffset)
Metadata for a module file extension.
unsigned MajorVersion
The major version of the extension data.
std::string UserInfo
A string containing additional user information that will be stored with the metadata.
std::string BlockName
The name used to identify this particular extension block within the resulting module file.
unsigned MinorVersion
The minor version of the extension data.
A conflict between two modules.
Definition Module.h:650
Module * Other
The module that this module conflicts with.
Definition Module.h:652
std::string Message
The message provided to the user when there is a conflict.
Definition Module.h:655
Information about a header directive as found in the module map file.
Definition Module.h:393
a linked list of methods with the same selector name but different signatures.
ObjCMethodList * getNext() const
A struct with extended info about a syntactic name qualifier, to be used for the case of out-of-line ...
Definition Decl.h:753
TemplateParameterList ** TemplParamLists
A new-allocated array of size NumTemplParamLists, containing pointers to the "outer" template paramet...
Definition Decl.h:767
NestedNameSpecifierLoc QualifierLoc
Definition Decl.h:754
unsigned NumTemplParamLists
The number of "outer" template parameter lists.
Definition Decl.h:760
void clear(SanitizerMask K=SanitizerKind::All)
Disable the sanitizers specified in K.
Definition Sanitizers.h:195
SanitizerMask Mask
Bitmask of enabled sanitizers.
Definition Sanitizers.h:201
Helper class that saves the current stream position and then restores it when destroyed.
PragmaMsStackAction Action
Definition Sema.h:1860
llvm::DenseSet< std::tuple< Decl *, Decl *, int > > NonEquivalentDeclSet
Store declaration pairs already found to be non-equivalent.
Location information for a TemplateArgument.
Describes a single change detected in a module file or input file.
Definition ModuleFile.h:125
The input file info that has been loaded from an AST file.
Definition ModuleFile.h:65
Describes the categories of an Objective-C class.
MultiOnDiskHashTable< LazySpecializationInfoLookupTrait > Table
#define log(__x)
Definition tgmath.h:460