1 //===- ASTReader.cpp - AST File Reader ------------------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file defines the ASTReader class, which reads AST files.
11 //===----------------------------------------------------------------------===//
13 #include "ASTCommon.h"
14 #include "ASTReaderInternals.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTMutationListener.h"
18 #include "clang/AST/ASTUnresolvedSet.h"
19 #include "clang/AST/AbstractTypeReader.h"
20 #include "clang/AST/Decl.h"
21 #include "clang/AST/DeclBase.h"
22 #include "clang/AST/DeclCXX.h"
23 #include "clang/AST/DeclFriend.h"
24 #include "clang/AST/DeclGroup.h"
25 #include "clang/AST/DeclObjC.h"
26 #include "clang/AST/DeclTemplate.h"
27 #include "clang/AST/DeclarationName.h"
28 #include "clang/AST/Expr.h"
29 #include "clang/AST/ExprCXX.h"
30 #include "clang/AST/ExternalASTSource.h"
31 #include "clang/AST/NestedNameSpecifier.h"
32 #include "clang/AST/ODRHash.h"
33 #include "clang/AST/OpenMPClause.h"
34 #include "clang/AST/RawCommentList.h"
35 #include "clang/AST/TemplateBase.h"
36 #include "clang/AST/TemplateName.h"
37 #include "clang/AST/Type.h"
38 #include "clang/AST/TypeLoc.h"
39 #include "clang/AST/TypeLocVisitor.h"
40 #include "clang/AST/UnresolvedSet.h"
41 #include "clang/Basic/CommentOptions.h"
42 #include "clang/Basic/Diagnostic.h"
43 #include "clang/Basic/DiagnosticError.h"
44 #include "clang/Basic/DiagnosticOptions.h"
45 #include "clang/Basic/ExceptionSpecificationType.h"
46 #include "clang/Basic/FileManager.h"
47 #include "clang/Basic/FileSystemOptions.h"
48 #include "clang/Basic/IdentifierTable.h"
49 #include "clang/Basic/LLVM.h"
50 #include "clang/Basic/LangOptions.h"
51 #include "clang/Basic/Module.h"
52 #include "clang/Basic/ObjCRuntime.h"
53 #include "clang/Basic/OpenMPKinds.h"
54 #include "clang/Basic/OperatorKinds.h"
55 #include "clang/Basic/PragmaKinds.h"
56 #include "clang/Basic/Sanitizers.h"
57 #include "clang/Basic/SourceLocation.h"
58 #include "clang/Basic/SourceManager.h"
59 #include "clang/Basic/SourceManagerInternals.h"
60 #include "clang/Basic/Specifiers.h"
61 #include "clang/Basic/TargetInfo.h"
62 #include "clang/Basic/TargetOptions.h"
63 #include "clang/Basic/TokenKinds.h"
64 #include "clang/Basic/Version.h"
65 #include "clang/Lex/HeaderSearch.h"
66 #include "clang/Lex/HeaderSearchOptions.h"
67 #include "clang/Lex/MacroInfo.h"
68 #include "clang/Lex/ModuleMap.h"
69 #include "clang/Lex/PreprocessingRecord.h"
70 #include "clang/Lex/Preprocessor.h"
71 #include "clang/Lex/PreprocessorOptions.h"
72 #include "clang/Lex/Token.h"
73 #include "clang/Sema/ObjCMethodList.h"
74 #include "clang/Sema/Scope.h"
75 #include "clang/Sema/Sema.h"
76 #include "clang/Sema/Weak.h"
77 #include "clang/Serialization/ASTBitCodes.h"
78 #include "clang/Serialization/ASTDeserializationListener.h"
79 #include "clang/Serialization/ASTRecordReader.h"
80 #include "clang/Serialization/ContinuousRangeMap.h"
81 #include "clang/Serialization/GlobalModuleIndex.h"
82 #include "clang/Serialization/InMemoryModuleCache.h"
83 #include "clang/Serialization/ModuleFile.h"
84 #include "clang/Serialization/ModuleFileExtension.h"
85 #include "clang/Serialization/ModuleManager.h"
86 #include "clang/Serialization/PCHContainerOperations.h"
87 #include "clang/Serialization/SerializationDiagnostic.h"
88 #include "llvm/ADT/APFloat.h"
89 #include "llvm/ADT/APInt.h"
90 #include "llvm/ADT/APSInt.h"
91 #include "llvm/ADT/ArrayRef.h"
92 #include "llvm/ADT/DenseMap.h"
93 #include "llvm/ADT/FloatingPointMode.h"
94 #include "llvm/ADT/FoldingSet.h"
95 #include "llvm/ADT/Hashing.h"
96 #include "llvm/ADT/IntrusiveRefCntPtr.h"
97 #include "llvm/ADT/None.h"
98 #include "llvm/ADT/Optional.h"
99 #include "llvm/ADT/STLExtras.h"
100 #include "llvm/ADT/ScopeExit.h"
101 #include "llvm/ADT/SmallPtrSet.h"
102 #include "llvm/ADT/SmallString.h"
103 #include "llvm/ADT/SmallVector.h"
104 #include "llvm/ADT/StringExtras.h"
105 #include "llvm/ADT/StringMap.h"
106 #include "llvm/ADT/StringRef.h"
107 #include "llvm/ADT/Triple.h"
108 #include "llvm/ADT/iterator_range.h"
109 #include "llvm/Bitstream/BitstreamReader.h"
110 #include "llvm/Support/Casting.h"
111 #include "llvm/Support/Compiler.h"
112 #include "llvm/Support/Compression.h"
113 #include "llvm/Support/DJB.h"
114 #include "llvm/Support/Endian.h"
115 #include "llvm/Support/Error.h"
116 #include "llvm/Support/ErrorHandling.h"
117 #include "llvm/Support/FileSystem.h"
118 #include "llvm/Support/LEB128.h"
119 #include "llvm/Support/MemoryBuffer.h"
120 #include "llvm/Support/Path.h"
121 #include "llvm/Support/SaveAndRestore.h"
122 #include "llvm/Support/Timer.h"
123 #include "llvm/Support/VersionTuple.h"
124 #include "llvm/Support/raw_ostream.h"
136 #include <system_error>
141 using namespace clang;
142 using namespace clang::serialization;
143 using namespace clang::serialization::reader;
144 using llvm::BitstreamCursor;
146 //===----------------------------------------------------------------------===//
147 // ChainedASTReaderListener implementation
148 //===----------------------------------------------------------------------===//
151 ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
152 return First->ReadFullVersionInformation(FullVersion) ||
153 Second->ReadFullVersionInformation(FullVersion);
156 void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
157 First->ReadModuleName(ModuleName);
158 Second->ReadModuleName(ModuleName);
161 void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
162 First->ReadModuleMapFile(ModuleMapPath);
163 Second->ReadModuleMapFile(ModuleMapPath);
167 ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
169 bool AllowCompatibleDifferences) {
170 return First->ReadLanguageOptions(LangOpts, Complain,
171 AllowCompatibleDifferences) ||
172 Second->ReadLanguageOptions(LangOpts, Complain,
173 AllowCompatibleDifferences);
176 bool ChainedASTReaderListener::ReadTargetOptions(
177 const TargetOptions &TargetOpts, bool Complain,
178 bool AllowCompatibleDifferences) {
179 return First->ReadTargetOptions(TargetOpts, Complain,
180 AllowCompatibleDifferences) ||
181 Second->ReadTargetOptions(TargetOpts, Complain,
182 AllowCompatibleDifferences);
185 bool ChainedASTReaderListener::ReadDiagnosticOptions(
186 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
187 return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
188 Second->ReadDiagnosticOptions(DiagOpts, Complain);
192 ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
194 return First->ReadFileSystemOptions(FSOpts, Complain) ||
195 Second->ReadFileSystemOptions(FSOpts, Complain);
198 bool ChainedASTReaderListener::ReadHeaderSearchOptions(
199 const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath,
201 return First->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
203 Second->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
207 bool ChainedASTReaderListener::ReadPreprocessorOptions(
208 const PreprocessorOptions &PPOpts, bool Complain,
209 std::string &SuggestedPredefines) {
210 return First->ReadPreprocessorOptions(PPOpts, Complain,
211 SuggestedPredefines) ||
212 Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
215 void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
217 First->ReadCounter(M, Value);
218 Second->ReadCounter(M, Value);
221 bool ChainedASTReaderListener::needsInputFileVisitation() {
222 return First->needsInputFileVisitation() ||
223 Second->needsInputFileVisitation();
226 bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
227 return First->needsSystemInputFileVisitation() ||
228 Second->needsSystemInputFileVisitation();
231 void ChainedASTReaderListener::visitModuleFile(StringRef Filename,
233 First->visitModuleFile(Filename, Kind);
234 Second->visitModuleFile(Filename, Kind);
237 bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
240 bool isExplicitModule) {
241 bool Continue = false;
242 if (First->needsInputFileVisitation() &&
243 (!isSystem || First->needsSystemInputFileVisitation()))
244 Continue |= First->visitInputFile(Filename, isSystem, isOverridden,
246 if (Second->needsInputFileVisitation() &&
247 (!isSystem || Second->needsSystemInputFileVisitation()))
248 Continue |= Second->visitInputFile(Filename, isSystem, isOverridden,
253 void ChainedASTReaderListener::readModuleFileExtension(
254 const ModuleFileExtensionMetadata &Metadata) {
255 First->readModuleFileExtension(Metadata);
256 Second->readModuleFileExtension(Metadata);
259 //===----------------------------------------------------------------------===//
260 // PCH validator implementation
261 //===----------------------------------------------------------------------===//
263 ASTReaderListener::~ASTReaderListener() = default;
265 /// Compare the given set of language options against an existing set of
266 /// language options.
268 /// \param Diags If non-NULL, diagnostics will be emitted via this engine.
269 /// \param AllowCompatibleDifferences If true, differences between compatible
270 /// language options will be permitted.
272 /// \returns true if the languagae options mis-match, false otherwise.
273 static bool checkLanguageOptions(const LangOptions &LangOpts,
274 const LangOptions &ExistingLangOpts,
275 DiagnosticsEngine *Diags,
276 bool AllowCompatibleDifferences = true) {
277 #define LANGOPT(Name, Bits, Default, Description) \
278 if (ExistingLangOpts.Name != LangOpts.Name) { \
280 Diags->Report(diag::err_pch_langopt_mismatch) \
281 << Description << LangOpts.Name << ExistingLangOpts.Name; \
285 #define VALUE_LANGOPT(Name, Bits, Default, Description) \
286 if (ExistingLangOpts.Name != LangOpts.Name) { \
288 Diags->Report(diag::err_pch_langopt_value_mismatch) \
293 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
294 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
296 Diags->Report(diag::err_pch_langopt_value_mismatch) \
301 #define COMPATIBLE_LANGOPT(Name, Bits, Default, Description) \
302 if (!AllowCompatibleDifferences) \
303 LANGOPT(Name, Bits, Default, Description)
305 #define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description) \
306 if (!AllowCompatibleDifferences) \
307 ENUM_LANGOPT(Name, Bits, Default, Description)
309 #define COMPATIBLE_VALUE_LANGOPT(Name, Bits, Default, Description) \
310 if (!AllowCompatibleDifferences) \
311 VALUE_LANGOPT(Name, Bits, Default, Description)
313 #define BENIGN_LANGOPT(Name, Bits, Default, Description)
314 #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
315 #define BENIGN_VALUE_LANGOPT(Name, Type, Bits, Default, Description)
316 #include "clang/Basic/LangOptions.def"
318 if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) {
320 Diags->Report(diag::err_pch_langopt_value_mismatch) << "module features";
324 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
326 Diags->Report(diag::err_pch_langopt_value_mismatch)
327 << "target Objective-C runtime";
331 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
332 LangOpts.CommentOpts.BlockCommandNames) {
334 Diags->Report(diag::err_pch_langopt_value_mismatch)
335 << "block command names";
339 // Sanitizer feature mismatches are treated as compatible differences. If
340 // compatible differences aren't allowed, we still only want to check for
341 // mismatches of non-modular sanitizers (the only ones which can affect AST
343 if (!AllowCompatibleDifferences) {
344 SanitizerMask ModularSanitizers = getPPTransparentSanitizers();
345 SanitizerSet ExistingSanitizers = ExistingLangOpts.Sanitize;
346 SanitizerSet ImportedSanitizers = LangOpts.Sanitize;
347 ExistingSanitizers.clear(ModularSanitizers);
348 ImportedSanitizers.clear(ModularSanitizers);
349 if (ExistingSanitizers.Mask != ImportedSanitizers.Mask) {
350 const std::string Flag = "-fsanitize=";
352 #define SANITIZER(NAME, ID) \
354 bool InExistingModule = ExistingSanitizers.has(SanitizerKind::ID); \
355 bool InImportedModule = ImportedSanitizers.has(SanitizerKind::ID); \
356 if (InExistingModule != InImportedModule) \
357 Diags->Report(diag::err_pch_targetopt_feature_mismatch) \
358 << InExistingModule << (Flag + NAME); \
360 #include "clang/Basic/Sanitizers.def"
369 /// Compare the given set of target options against an existing set of
372 /// \param Diags If non-NULL, diagnostics will be emitted via this engine.
374 /// \returns true if the target options mis-match, false otherwise.
375 static bool checkTargetOptions(const TargetOptions &TargetOpts,
376 const TargetOptions &ExistingTargetOpts,
377 DiagnosticsEngine *Diags,
378 bool AllowCompatibleDifferences = true) {
379 #define CHECK_TARGET_OPT(Field, Name) \
380 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
382 Diags->Report(diag::err_pch_targetopt_mismatch) \
383 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
387 // The triple and ABI must match exactly.
388 CHECK_TARGET_OPT(Triple, "target");
389 CHECK_TARGET_OPT(ABI, "target ABI");
391 // We can tolerate different CPUs in many cases, notably when one CPU
392 // supports a strict superset of another. When allowing compatible
393 // differences skip this check.
394 if (!AllowCompatibleDifferences) {
395 CHECK_TARGET_OPT(CPU, "target CPU");
396 CHECK_TARGET_OPT(TuneCPU, "tune CPU");
399 #undef CHECK_TARGET_OPT
401 // Compare feature sets.
402 SmallVector<StringRef, 4> ExistingFeatures(
403 ExistingTargetOpts.FeaturesAsWritten.begin(),
404 ExistingTargetOpts.FeaturesAsWritten.end());
405 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
406 TargetOpts.FeaturesAsWritten.end());
407 llvm::sort(ExistingFeatures);
408 llvm::sort(ReadFeatures);
410 // We compute the set difference in both directions explicitly so that we can
411 // diagnose the differences differently.
412 SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
414 ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
415 ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
416 std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
417 ExistingFeatures.begin(), ExistingFeatures.end(),
418 std::back_inserter(UnmatchedReadFeatures));
420 // If we are allowing compatible differences and the read feature set is
421 // a strict subset of the existing feature set, there is nothing to diagnose.
422 if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
426 for (StringRef Feature : UnmatchedReadFeatures)
427 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
428 << /* is-existing-feature */ false << Feature;
429 for (StringRef Feature : UnmatchedExistingFeatures)
430 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
431 << /* is-existing-feature */ true << Feature;
434 return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
438 PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
440 bool AllowCompatibleDifferences) {
441 const LangOptions &ExistingLangOpts = PP.getLangOpts();
442 return checkLanguageOptions(LangOpts, ExistingLangOpts,
443 Complain ? &Reader.Diags : nullptr,
444 AllowCompatibleDifferences);
447 bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
449 bool AllowCompatibleDifferences) {
450 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
451 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
452 Complain ? &Reader.Diags : nullptr,
453 AllowCompatibleDifferences);
458 using MacroDefinitionsMap =
459 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>;
460 using DeclsMap = llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8>>;
464 static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
465 DiagnosticsEngine &Diags,
467 using Level = DiagnosticsEngine::Level;
469 // Check current mappings for new -Werror mappings, and the stored mappings
470 // for cases that were explicitly mapped to *not* be errors that are now
471 // errors because of options like -Werror.
472 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
474 for (DiagnosticsEngine *MappingSource : MappingSources) {
475 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
476 diag::kind DiagID = DiagIDMappingPair.first;
477 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
478 if (CurLevel < DiagnosticsEngine::Error)
479 continue; // not significant
481 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
482 if (StoredLevel < DiagnosticsEngine::Error) {
484 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
485 Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
494 static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
495 diag::Severity Ext = Diags.getExtensionHandlingBehavior();
496 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
498 return Ext >= diag::Severity::Error;
501 static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
502 DiagnosticsEngine &Diags,
503 bool IsSystem, bool Complain) {
506 if (Diags.getSuppressSystemWarnings())
508 // If -Wsystem-headers was not enabled before, be conservative
509 if (StoredDiags.getSuppressSystemWarnings()) {
511 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
516 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
518 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
522 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
523 !StoredDiags.getEnableAllWarnings()) {
525 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
529 if (isExtHandlingFromDiagsError(Diags) &&
530 !isExtHandlingFromDiagsError(StoredDiags)) {
532 Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
536 return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
539 /// Return the top import module if it is implicit, nullptr otherwise.
540 static Module *getTopImportImplicitModule(ModuleManager &ModuleMgr,
542 // If the original import came from a file explicitly generated by the user,
543 // don't check the diagnostic mappings.
544 // FIXME: currently this is approximated by checking whether this is not a
545 // module import of an implicitly-loaded module file.
546 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
547 // the transitive closure of its imports, since unrelated modules cannot be
548 // imported until after this module finishes validation.
549 ModuleFile *TopImport = &*ModuleMgr.rbegin();
550 while (!TopImport->ImportedBy.empty())
551 TopImport = TopImport->ImportedBy[0];
552 if (TopImport->Kind != MK_ImplicitModule)
555 StringRef ModuleName = TopImport->ModuleName;
556 assert(!ModuleName.empty() && "diagnostic options read before module name");
559 PP.getHeaderSearchInfo().lookupModule(ModuleName, TopImport->ImportLoc);
560 assert(M && "missing module");
564 bool PCHValidator::ReadDiagnosticOptions(
565 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
566 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
567 IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
568 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
569 new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
570 // This should never fail, because we would have processed these options
571 // before writing them to an ASTFile.
572 ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
574 ModuleManager &ModuleMgr = Reader.getModuleManager();
575 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
577 Module *TopM = getTopImportImplicitModule(ModuleMgr, PP);
581 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
582 // contains the union of their flags.
583 return checkDiagnosticMappings(*Diags, ExistingDiags, TopM->IsSystem,
587 /// Collect the macro definitions provided by the given preprocessor
590 collectMacroDefinitions(const PreprocessorOptions &PPOpts,
591 MacroDefinitionsMap &Macros,
592 SmallVectorImpl<StringRef> *MacroNames = nullptr) {
593 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
594 StringRef Macro = PPOpts.Macros[I].first;
595 bool IsUndef = PPOpts.Macros[I].second;
597 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
598 StringRef MacroName = MacroPair.first;
599 StringRef MacroBody = MacroPair.second;
601 // For an #undef'd macro, we only care about the name.
603 if (MacroNames && !Macros.count(MacroName))
604 MacroNames->push_back(MacroName);
606 Macros[MacroName] = std::make_pair("", true);
610 // For a #define'd macro, figure out the actual definition.
611 if (MacroName.size() == Macro.size())
614 // Note: GCC drops anything following an end-of-line character.
615 StringRef::size_type End = MacroBody.find_first_of("\n\r");
616 MacroBody = MacroBody.substr(0, End);
619 if (MacroNames && !Macros.count(MacroName))
620 MacroNames->push_back(MacroName);
621 Macros[MacroName] = std::make_pair(MacroBody, false);
625 /// Check the preprocessor options deserialized from the control block
626 /// against the preprocessor options in an existing preprocessor.
628 /// \param Diags If non-null, produce diagnostics for any mismatches incurred.
629 /// \param Validate If true, validate preprocessor options. If false, allow
630 /// macros defined by \p ExistingPPOpts to override those defined by
631 /// \p PPOpts in SuggestedPredefines.
632 static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
633 const PreprocessorOptions &ExistingPPOpts,
634 DiagnosticsEngine *Diags,
635 FileManager &FileMgr,
636 std::string &SuggestedPredefines,
637 const LangOptions &LangOpts,
638 bool Validate = true) {
639 // Check macro definitions.
640 MacroDefinitionsMap ASTFileMacros;
641 collectMacroDefinitions(PPOpts, ASTFileMacros);
642 MacroDefinitionsMap ExistingMacros;
643 SmallVector<StringRef, 4> ExistingMacroNames;
644 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
646 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
647 // Dig out the macro definition in the existing preprocessor options.
648 StringRef MacroName = ExistingMacroNames[I];
649 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
651 // Check whether we know anything about this macro name or not.
652 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>::iterator Known =
653 ASTFileMacros.find(MacroName);
654 if (!Validate || Known == ASTFileMacros.end()) {
655 // FIXME: Check whether this identifier was referenced anywhere in the
656 // AST file. If so, we should reject the AST file. Unfortunately, this
657 // information isn't in the control block. What shall we do about it?
659 if (Existing.second) {
660 SuggestedPredefines += "#undef ";
661 SuggestedPredefines += MacroName.str();
662 SuggestedPredefines += '\n';
664 SuggestedPredefines += "#define ";
665 SuggestedPredefines += MacroName.str();
666 SuggestedPredefines += ' ';
667 SuggestedPredefines += Existing.first.str();
668 SuggestedPredefines += '\n';
673 // If the macro was defined in one but undef'd in the other, we have a
675 if (Existing.second != Known->second.second) {
677 Diags->Report(diag::err_pch_macro_def_undef)
678 << MacroName << Known->second.second;
683 // If the macro was #undef'd in both, or if the macro bodies are identical,
685 if (Existing.second || Existing.first == Known->second.first)
688 // The macro bodies differ; complain.
690 Diags->Report(diag::err_pch_macro_def_conflict)
691 << MacroName << Known->second.first << Existing.first;
696 // Check whether we're using predefines.
697 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines && Validate) {
699 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
704 // Detailed record is important since it is used for the module cache hash.
705 if (LangOpts.Modules &&
706 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord && Validate) {
708 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
713 // Compute the #include and #include_macros lines we need.
714 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
715 StringRef File = ExistingPPOpts.Includes[I];
717 if (!ExistingPPOpts.ImplicitPCHInclude.empty() &&
718 !ExistingPPOpts.PCHThroughHeader.empty()) {
719 // In case the through header is an include, we must add all the includes
720 // to the predefines so the start point can be determined.
721 SuggestedPredefines += "#include \"";
722 SuggestedPredefines += File;
723 SuggestedPredefines += "\"\n";
727 if (File == ExistingPPOpts.ImplicitPCHInclude)
730 if (llvm::is_contained(PPOpts.Includes, File))
733 SuggestedPredefines += "#include \"";
734 SuggestedPredefines += File;
735 SuggestedPredefines += "\"\n";
738 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
739 StringRef File = ExistingPPOpts.MacroIncludes[I];
740 if (llvm::is_contained(PPOpts.MacroIncludes, File))
743 SuggestedPredefines += "#__include_macros \"";
744 SuggestedPredefines += File;
745 SuggestedPredefines += "\"\n##\n";
751 bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
753 std::string &SuggestedPredefines) {
754 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
756 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
757 Complain? &Reader.Diags : nullptr,
763 bool SimpleASTReaderListener::ReadPreprocessorOptions(
764 const PreprocessorOptions &PPOpts,
766 std::string &SuggestedPredefines) {
767 return checkPreprocessorOptions(PPOpts,
768 PP.getPreprocessorOpts(),
776 /// Check the header search options deserialized from the control block
777 /// against the header search options in an existing preprocessor.
779 /// \param Diags If non-null, produce diagnostics for any mismatches incurred.
780 static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
781 StringRef SpecificModuleCachePath,
782 StringRef ExistingModuleCachePath,
783 DiagnosticsEngine *Diags,
784 const LangOptions &LangOpts,
785 const PreprocessorOptions &PPOpts) {
786 if (LangOpts.Modules) {
787 if (SpecificModuleCachePath != ExistingModuleCachePath &&
788 !PPOpts.AllowPCHWithDifferentModulesCachePath) {
790 Diags->Report(diag::err_pch_modulecache_mismatch)
791 << SpecificModuleCachePath << ExistingModuleCachePath;
799 bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
800 StringRef SpecificModuleCachePath,
802 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
803 PP.getHeaderSearchInfo().getModuleCachePath(),
804 Complain ? &Reader.Diags : nullptr,
805 PP.getLangOpts(), PP.getPreprocessorOpts());
808 void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
809 PP.setCounterValue(Value);
812 //===----------------------------------------------------------------------===//
813 // AST reader implementation
814 //===----------------------------------------------------------------------===//
816 static uint64_t readULEB(const unsigned char *&P) {
818 const char *Error = nullptr;
820 uint64_t Val = llvm::decodeULEB128(P, &Length, nullptr, &Error);
822 llvm::report_fatal_error(Error);
827 /// Read ULEB-encoded key length and data length.
828 static std::pair<unsigned, unsigned>
829 readULEBKeyDataLength(const unsigned char *&P) {
830 unsigned KeyLen = readULEB(P);
831 if ((unsigned)KeyLen != KeyLen)
832 llvm::report_fatal_error("key too large");
834 unsigned DataLen = readULEB(P);
835 if ((unsigned)DataLen != DataLen)
836 llvm::report_fatal_error("data too large");
838 return std::make_pair(KeyLen, DataLen);
841 void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
842 bool TakeOwnership) {
843 DeserializationListener = Listener;
844 OwnsDeserializationListener = TakeOwnership;
847 unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
848 return serialization::ComputeHash(Sel);
851 std::pair<unsigned, unsigned>
852 ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
853 return readULEBKeyDataLength(d);
856 ASTSelectorLookupTrait::internal_key_type
857 ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
858 using namespace llvm::support;
860 SelectorTable &SelTable = Reader.getContext().Selectors;
861 unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
862 IdentifierInfo *FirstII = Reader.getLocalIdentifier(
863 F, endian::readNext<uint32_t, little, unaligned>(d));
865 return SelTable.getNullarySelector(FirstII);
867 return SelTable.getUnarySelector(FirstII);
869 SmallVector<IdentifierInfo *, 16> Args;
870 Args.push_back(FirstII);
871 for (unsigned I = 1; I != N; ++I)
872 Args.push_back(Reader.getLocalIdentifier(
873 F, endian::readNext<uint32_t, little, unaligned>(d)));
875 return SelTable.getSelector(N, Args.data());
878 ASTSelectorLookupTrait::data_type
879 ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
881 using namespace llvm::support;
885 Result.ID = Reader.getGlobalSelectorID(
886 F, endian::readNext<uint32_t, little, unaligned>(d));
887 unsigned FullInstanceBits = endian::readNext<uint16_t, little, unaligned>(d);
888 unsigned FullFactoryBits = endian::readNext<uint16_t, little, unaligned>(d);
889 Result.InstanceBits = FullInstanceBits & 0x3;
890 Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
891 Result.FactoryBits = FullFactoryBits & 0x3;
892 Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
893 unsigned NumInstanceMethods = FullInstanceBits >> 3;
894 unsigned NumFactoryMethods = FullFactoryBits >> 3;
896 // Load instance methods
897 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
898 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
899 F, endian::readNext<uint32_t, little, unaligned>(d)))
900 Result.Instance.push_back(Method);
903 // Load factory methods
904 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
905 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
906 F, endian::readNext<uint32_t, little, unaligned>(d)))
907 Result.Factory.push_back(Method);
913 unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
914 return llvm::djbHash(a);
917 std::pair<unsigned, unsigned>
918 ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
919 return readULEBKeyDataLength(d);
922 ASTIdentifierLookupTraitBase::internal_key_type
923 ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
924 assert(n >= 2 && d[n-1] == '\0');
925 return StringRef((const char*) d, n-1);
928 /// Whether the given identifier is "interesting".
929 static bool isInterestingIdentifier(ASTReader &Reader, IdentifierInfo &II,
931 return II.hadMacroDefinition() || II.isPoisoned() ||
932 (!IsModule && II.getObjCOrBuiltinID()) ||
933 II.hasRevertedTokenIDToIdentifier() ||
934 (!(IsModule && Reader.getPreprocessor().getLangOpts().CPlusPlus) &&
935 II.getFETokenInfo());
938 static bool readBit(unsigned &Bits) {
939 bool Value = Bits & 0x1;
944 IdentID ASTIdentifierLookupTrait::ReadIdentifierID(const unsigned char *d) {
945 using namespace llvm::support;
947 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
948 return Reader.getGlobalIdentifierID(F, RawID >> 1);
951 static void markIdentifierFromAST(ASTReader &Reader, IdentifierInfo &II) {
952 if (!II.isFromAST()) {
954 bool IsModule = Reader.getPreprocessor().getCurrentModule() != nullptr;
955 if (isInterestingIdentifier(Reader, II, IsModule))
956 II.setChangedSinceDeserialization();
960 IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
961 const unsigned char* d,
963 using namespace llvm::support;
965 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
966 bool IsInteresting = RawID & 0x01;
968 // Wipe out the "is interesting" bit.
971 // Build the IdentifierInfo and link the identifier ID with it.
972 IdentifierInfo *II = KnownII;
974 II = &Reader.getIdentifierTable().getOwn(k);
977 markIdentifierFromAST(Reader, *II);
978 Reader.markIdentifierUpToDate(II);
980 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
981 if (!IsInteresting) {
982 // For uninteresting identifiers, there's nothing else to do. Just notify
983 // the reader that we've finished loading this identifier.
984 Reader.SetIdentifierInfo(ID, II);
988 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
989 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
990 bool CPlusPlusOperatorKeyword = readBit(Bits);
991 bool HasRevertedTokenIDToIdentifier = readBit(Bits);
992 bool Poisoned = readBit(Bits);
993 bool ExtensionToken = readBit(Bits);
994 bool HadMacroDefinition = readBit(Bits);
996 assert(Bits == 0 && "Extra bits in the identifier?");
999 // Set or check the various bits in the IdentifierInfo structure.
1000 // Token IDs are read-only.
1001 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
1002 II->revertTokenIDToIdentifier();
1004 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
1005 assert(II->isExtensionToken() == ExtensionToken &&
1006 "Incorrect extension token flag");
1007 (void)ExtensionToken;
1009 II->setIsPoisoned(true);
1010 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
1011 "Incorrect C++ operator keyword flag");
1012 (void)CPlusPlusOperatorKeyword;
1014 // If this identifier is a macro, deserialize the macro
1016 if (HadMacroDefinition) {
1017 uint32_t MacroDirectivesOffset =
1018 endian::readNext<uint32_t, little, unaligned>(d);
1021 Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
1024 Reader.SetIdentifierInfo(ID, II);
1026 // Read all of the declarations visible at global scope with this
1029 SmallVector<uint32_t, 4> DeclIDs;
1030 for (; DataLen > 0; DataLen -= 4)
1031 DeclIDs.push_back(Reader.getGlobalDeclID(
1032 F, endian::readNext<uint32_t, little, unaligned>(d)));
1033 Reader.SetGloballyVisibleDecls(II, DeclIDs);
1039 DeclarationNameKey::DeclarationNameKey(DeclarationName Name)
1040 : Kind(Name.getNameKind()) {
1042 case DeclarationName::Identifier:
1043 Data = (uint64_t)Name.getAsIdentifierInfo();
1045 case DeclarationName::ObjCZeroArgSelector:
1046 case DeclarationName::ObjCOneArgSelector:
1047 case DeclarationName::ObjCMultiArgSelector:
1048 Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
1050 case DeclarationName::CXXOperatorName:
1051 Data = Name.getCXXOverloadedOperator();
1053 case DeclarationName::CXXLiteralOperatorName:
1054 Data = (uint64_t)Name.getCXXLiteralIdentifier();
1056 case DeclarationName::CXXDeductionGuideName:
1057 Data = (uint64_t)Name.getCXXDeductionGuideTemplate()
1058 ->getDeclName().getAsIdentifierInfo();
1060 case DeclarationName::CXXConstructorName:
1061 case DeclarationName::CXXDestructorName:
1062 case DeclarationName::CXXConversionFunctionName:
1063 case DeclarationName::CXXUsingDirective:
1069 unsigned DeclarationNameKey::getHash() const {
1070 llvm::FoldingSetNodeID ID;
1071 ID.AddInteger(Kind);
1074 case DeclarationName::Identifier:
1075 case DeclarationName::CXXLiteralOperatorName:
1076 case DeclarationName::CXXDeductionGuideName:
1077 ID.AddString(((IdentifierInfo*)Data)->getName());
1079 case DeclarationName::ObjCZeroArgSelector:
1080 case DeclarationName::ObjCOneArgSelector:
1081 case DeclarationName::ObjCMultiArgSelector:
1082 ID.AddInteger(serialization::ComputeHash(Selector(Data)));
1084 case DeclarationName::CXXOperatorName:
1085 ID.AddInteger((OverloadedOperatorKind)Data);
1087 case DeclarationName::CXXConstructorName:
1088 case DeclarationName::CXXDestructorName:
1089 case DeclarationName::CXXConversionFunctionName:
1090 case DeclarationName::CXXUsingDirective:
1094 return ID.ComputeHash();
1098 ASTDeclContextNameLookupTrait::ReadFileRef(const unsigned char *&d) {
1099 using namespace llvm::support;
1101 uint32_t ModuleFileID = endian::readNext<uint32_t, little, unaligned>(d);
1102 return Reader.getLocalModuleFile(F, ModuleFileID);
1105 std::pair<unsigned, unsigned>
1106 ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char *&d) {
1107 return readULEBKeyDataLength(d);
1110 ASTDeclContextNameLookupTrait::internal_key_type
1111 ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
1112 using namespace llvm::support;
1114 auto Kind = (DeclarationName::NameKind)*d++;
1117 case DeclarationName::Identifier:
1118 case DeclarationName::CXXLiteralOperatorName:
1119 case DeclarationName::CXXDeductionGuideName:
1120 Data = (uint64_t)Reader.getLocalIdentifier(
1121 F, endian::readNext<uint32_t, little, unaligned>(d));
1123 case DeclarationName::ObjCZeroArgSelector:
1124 case DeclarationName::ObjCOneArgSelector:
1125 case DeclarationName::ObjCMultiArgSelector:
1127 (uint64_t)Reader.getLocalSelector(
1128 F, endian::readNext<uint32_t, little, unaligned>(
1129 d)).getAsOpaquePtr();
1131 case DeclarationName::CXXOperatorName:
1132 Data = *d++; // OverloadedOperatorKind
1134 case DeclarationName::CXXConstructorName:
1135 case DeclarationName::CXXDestructorName:
1136 case DeclarationName::CXXConversionFunctionName:
1137 case DeclarationName::CXXUsingDirective:
1142 return DeclarationNameKey(Kind, Data);
1145 void ASTDeclContextNameLookupTrait::ReadDataInto(internal_key_type,
1146 const unsigned char *d,
1148 data_type_builder &Val) {
1149 using namespace llvm::support;
1151 for (unsigned NumDecls = DataLen / 4; NumDecls; --NumDecls) {
1152 uint32_t LocalID = endian::readNext<uint32_t, little, unaligned>(d);
1153 Val.insert(Reader.getGlobalDeclID(F, LocalID));
1157 bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
1158 BitstreamCursor &Cursor,
1161 assert(Offset != 0);
1163 SavedStreamPosition SavedPosition(Cursor);
1164 if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1165 Error(std::move(Err));
1171 Expected<unsigned> MaybeCode = Cursor.ReadCode();
1173 Error(MaybeCode.takeError());
1176 unsigned Code = MaybeCode.get();
1178 Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
1179 if (!MaybeRecCode) {
1180 Error(MaybeRecCode.takeError());
1183 unsigned RecCode = MaybeRecCode.get();
1184 if (RecCode != DECL_CONTEXT_LEXICAL) {
1185 Error("Expected lexical block");
1189 assert(!isa<TranslationUnitDecl>(DC) &&
1190 "expected a TU_UPDATE_LEXICAL record for TU");
1191 // If we are handling a C++ class template instantiation, we can see multiple
1192 // lexical updates for the same record. It's important that we select only one
1193 // of them, so that field numbering works properly. Just pick the first one we
1195 auto &Lex = LexicalDecls[DC];
1197 Lex = std::make_pair(
1198 &M, llvm::makeArrayRef(
1199 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
1203 DC->setHasExternalLexicalStorage(true);
1207 bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M,
1208 BitstreamCursor &Cursor,
1211 assert(Offset != 0);
1213 SavedStreamPosition SavedPosition(Cursor);
1214 if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1215 Error(std::move(Err));
1221 Expected<unsigned> MaybeCode = Cursor.ReadCode();
1223 Error(MaybeCode.takeError());
1226 unsigned Code = MaybeCode.get();
1228 Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
1229 if (!MaybeRecCode) {
1230 Error(MaybeRecCode.takeError());
1233 unsigned RecCode = MaybeRecCode.get();
1234 if (RecCode != DECL_CONTEXT_VISIBLE) {
1235 Error("Expected visible lookup table block");
1239 // We can't safely determine the primary context yet, so delay attaching the
1240 // lookup table until we're done with recursive deserialization.
1241 auto *Data = (const unsigned char*)Blob.data();
1242 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&M, Data});
1246 void ASTReader::Error(StringRef Msg) const {
1247 Error(diag::err_fe_pch_malformed, Msg);
1248 if (PP.getLangOpts().Modules && !Diags.isDiagnosticInFlight() &&
1249 !PP.getHeaderSearchInfo().getModuleCachePath().empty()) {
1250 Diag(diag::note_module_cache_path)
1251 << PP.getHeaderSearchInfo().getModuleCachePath();
1255 void ASTReader::Error(unsigned DiagID, StringRef Arg1, StringRef Arg2,
1256 StringRef Arg3) const {
1257 if (Diags.isDiagnosticInFlight())
1258 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2, Arg3);
1260 Diag(DiagID) << Arg1 << Arg2 << Arg3;
1263 void ASTReader::Error(llvm::Error &&Err) const {
1264 llvm::Error RemainingErr =
1265 handleErrors(std::move(Err), [this](const DiagnosticError &E) {
1266 auto Diag = E.getDiagnostic().second;
1268 // Ideally we'd just emit it, but have to handle a possible in-flight
1269 // diagnostic. Note that the location is currently ignored as well.
1270 auto NumArgs = Diag.getStorage()->NumDiagArgs;
1271 assert(NumArgs <= 3 && "Can only have up to 3 arguments");
1272 StringRef Arg1, Arg2, Arg3;
1275 Arg3 = Diag.getStringArg(2);
1278 Arg2 = Diag.getStringArg(1);
1281 Arg1 = Diag.getStringArg(0);
1283 Error(Diag.getDiagID(), Arg1, Arg2, Arg3);
1286 Error(toString(std::move(RemainingErr)));
1289 //===----------------------------------------------------------------------===//
1290 // Source Manager Deserialization
1291 //===----------------------------------------------------------------------===//
1293 /// Read the line table in the source manager block.
1294 void ASTReader::ParseLineTable(ModuleFile &F, const RecordData &Record) {
1296 LineTableInfo &LineTable = SourceMgr.getLineTable();
1298 // Parse the file names
1299 std::map<int, int> FileIDs;
1300 FileIDs[-1] = -1; // For unspecified filenames.
1301 for (unsigned I = 0; Record[Idx]; ++I) {
1302 // Extract the file name
1303 auto Filename = ReadPath(F, Record, Idx);
1304 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1308 // Parse the line entries
1309 std::vector<LineEntry> Entries;
1310 while (Idx < Record.size()) {
1311 int FID = Record[Idx++];
1312 assert(FID >= 0 && "Serialized line entries for non-local file.");
1313 // Remap FileID from 1-based old view.
1314 FID += F.SLocEntryBaseID - 1;
1316 // Extract the line entries
1317 unsigned NumEntries = Record[Idx++];
1318 assert(NumEntries && "no line entries for file ID");
1320 Entries.reserve(NumEntries);
1321 for (unsigned I = 0; I != NumEntries; ++I) {
1322 unsigned FileOffset = Record[Idx++];
1323 unsigned LineNo = Record[Idx++];
1324 int FilenameID = FileIDs[Record[Idx++]];
1325 SrcMgr::CharacteristicKind FileKind
1326 = (SrcMgr::CharacteristicKind)Record[Idx++];
1327 unsigned IncludeOffset = Record[Idx++];
1328 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1329 FileKind, IncludeOffset));
1331 LineTable.AddEntry(FileID::get(FID), Entries);
1335 /// Read a source manager block
1336 llvm::Error ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1337 using namespace SrcMgr;
1339 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
1341 // Set the source-location entry cursor to the current position in
1342 // the stream. This cursor will be used to read the contents of the
1343 // source manager block initially, and then lazily read
1344 // source-location entries as needed.
1345 SLocEntryCursor = F.Stream;
1347 // The stream itself is going to skip over the source manager block.
1348 if (llvm::Error Err = F.Stream.SkipBlock())
1351 // Enter the source manager block.
1352 if (llvm::Error Err = SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID))
1354 F.SourceManagerBlockStartOffset = SLocEntryCursor.GetCurrentBitNo();
1358 Expected<llvm::BitstreamEntry> MaybeE =
1359 SLocEntryCursor.advanceSkippingSubblocks();
1361 return MaybeE.takeError();
1362 llvm::BitstreamEntry E = MaybeE.get();
1365 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1366 case llvm::BitstreamEntry::Error:
1367 return llvm::createStringError(std::errc::illegal_byte_sequence,
1368 "malformed block record in AST file");
1369 case llvm::BitstreamEntry::EndBlock:
1370 return llvm::Error::success();
1371 case llvm::BitstreamEntry::Record:
1372 // The interesting case.
1379 Expected<unsigned> MaybeRecord =
1380 SLocEntryCursor.readRecord(E.ID, Record, &Blob);
1382 return MaybeRecord.takeError();
1383 switch (MaybeRecord.get()) {
1384 default: // Default behavior: ignore.
1387 case SM_SLOC_FILE_ENTRY:
1388 case SM_SLOC_BUFFER_ENTRY:
1389 case SM_SLOC_EXPANSION_ENTRY:
1390 // Once we hit one of the source location entries, we're done.
1391 return llvm::Error::success();
1396 /// If a header file is not found at the path that we expect it to be
1397 /// and the PCH file was moved from its original location, try to resolve the
1398 /// file by assuming that header+PCH were moved together and the header is in
1399 /// the same place relative to the PCH.
1401 resolveFileRelativeToOriginalDir(const std::string &Filename,
1402 const std::string &OriginalDir,
1403 const std::string &CurrDir) {
1404 assert(OriginalDir != CurrDir &&
1405 "No point trying to resolve the file if the PCH dir didn't change");
1407 using namespace llvm::sys;
1409 SmallString<128> filePath(Filename);
1410 fs::make_absolute(filePath);
1411 assert(path::is_absolute(OriginalDir));
1412 SmallString<128> currPCHPath(CurrDir);
1414 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1415 fileDirE = path::end(path::parent_path(filePath));
1416 path::const_iterator origDirI = path::begin(OriginalDir),
1417 origDirE = path::end(OriginalDir);
1418 // Skip the common path components from filePath and OriginalDir.
1419 while (fileDirI != fileDirE && origDirI != origDirE &&
1420 *fileDirI == *origDirI) {
1424 for (; origDirI != origDirE; ++origDirI)
1425 path::append(currPCHPath, "..");
1426 path::append(currPCHPath, fileDirI, fileDirE);
1427 path::append(currPCHPath, path::filename(Filename));
1428 return std::string(currPCHPath.str());
1431 bool ASTReader::ReadSLocEntry(int ID) {
1435 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1436 Error("source location entry ID out-of-range for AST file");
1440 // Local helper to read the (possibly-compressed) buffer data following the
1442 auto ReadBuffer = [this](
1443 BitstreamCursor &SLocEntryCursor,
1444 StringRef Name) -> std::unique_ptr<llvm::MemoryBuffer> {
1447 Expected<unsigned> MaybeCode = SLocEntryCursor.ReadCode();
1449 Error(MaybeCode.takeError());
1452 unsigned Code = MaybeCode.get();
1454 Expected<unsigned> MaybeRecCode =
1455 SLocEntryCursor.readRecord(Code, Record, &Blob);
1456 if (!MaybeRecCode) {
1457 Error(MaybeRecCode.takeError());
1460 unsigned RecCode = MaybeRecCode.get();
1462 if (RecCode == SM_SLOC_BUFFER_BLOB_COMPRESSED) {
1463 if (!llvm::zlib::isAvailable()) {
1464 Error("zlib is not available");
1467 SmallString<0> Uncompressed;
1469 llvm::zlib::uncompress(Blob, Uncompressed, Record[0])) {
1470 Error("could not decompress embedded file contents: " +
1471 llvm::toString(std::move(E)));
1474 return llvm::MemoryBuffer::getMemBufferCopy(Uncompressed, Name);
1475 } else if (RecCode == SM_SLOC_BUFFER_BLOB) {
1476 return llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name, true);
1478 Error("AST record has invalid code");
1483 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1484 if (llvm::Error Err = F->SLocEntryCursor.JumpToBit(
1485 F->SLocEntryOffsetsBase +
1486 F->SLocEntryOffsets[ID - F->SLocEntryBaseID])) {
1487 Error(std::move(Err));
1491 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
1492 SourceLocation::UIntTy BaseOffset = F->SLocEntryBaseOffset;
1494 ++NumSLocEntriesRead;
1495 Expected<llvm::BitstreamEntry> MaybeEntry = SLocEntryCursor.advance();
1497 Error(MaybeEntry.takeError());
1500 llvm::BitstreamEntry Entry = MaybeEntry.get();
1502 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1503 Error("incorrectly-formatted source location entry in AST file");
1509 Expected<unsigned> MaybeSLOC =
1510 SLocEntryCursor.readRecord(Entry.ID, Record, &Blob);
1512 Error(MaybeSLOC.takeError());
1515 switch (MaybeSLOC.get()) {
1517 Error("incorrectly-formatted source location entry in AST file");
1520 case SM_SLOC_FILE_ENTRY: {
1521 // We will detect whether a file changed and return 'Failure' for it, but
1522 // we will also try to fail gracefully by setting up the SLocEntry.
1523 unsigned InputID = Record[4];
1524 InputFile IF = getInputFile(*F, InputID);
1525 Optional<FileEntryRef> File = IF.getFile();
1526 bool OverriddenBuffer = IF.isOverridden();
1528 // Note that we only check if a File was returned. If it was out-of-date
1529 // we have complained but we will continue creating a FileID to recover
1534 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1535 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1536 // This is the module's main file.
1537 IncludeLoc = getImportLocation(F);
1539 SrcMgr::CharacteristicKind
1540 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1541 FileID FID = SourceMgr.createFileID(*File, IncludeLoc, FileCharacter, ID,
1542 BaseOffset + Record[0]);
1543 SrcMgr::FileInfo &FileInfo =
1544 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1545 FileInfo.NumCreatedFIDs = Record[5];
1547 FileInfo.setHasLineDirectives();
1549 unsigned NumFileDecls = Record[7];
1550 if (NumFileDecls && ContextObj) {
1551 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1552 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1553 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1557 const SrcMgr::ContentCache &ContentCache =
1558 SourceMgr.getOrCreateContentCache(*File, isSystem(FileCharacter));
1559 if (OverriddenBuffer && !ContentCache.BufferOverridden &&
1560 ContentCache.ContentsEntry == ContentCache.OrigEntry &&
1561 !ContentCache.getBufferIfLoaded()) {
1562 auto Buffer = ReadBuffer(SLocEntryCursor, File->getName());
1565 SourceMgr.overrideFileContents(*File, std::move(Buffer));
1571 case SM_SLOC_BUFFER_ENTRY: {
1572 const char *Name = Blob.data();
1573 unsigned Offset = Record[0];
1574 SrcMgr::CharacteristicKind
1575 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1576 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1577 if (IncludeLoc.isInvalid() && F->isModule()) {
1578 IncludeLoc = getImportLocation(F);
1581 auto Buffer = ReadBuffer(SLocEntryCursor, Name);
1584 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
1585 BaseOffset + Offset, IncludeLoc);
1589 case SM_SLOC_EXPANSION_ENTRY: {
1590 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1591 SourceMgr.createExpansionLoc(SpellingLoc,
1592 ReadSourceLocation(*F, Record[2]),
1593 ReadSourceLocation(*F, Record[3]),
1597 BaseOffset + Record[0]);
1605 std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1607 return std::make_pair(SourceLocation(), "");
1609 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1610 Error("source location entry ID out-of-range for AST file");
1611 return std::make_pair(SourceLocation(), "");
1614 // Find which module file this entry lands in.
1615 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
1617 return std::make_pair(SourceLocation(), "");
1619 // FIXME: Can we map this down to a particular submodule? That would be
1621 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
1624 /// Find the location where the module F is imported.
1625 SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1626 if (F->ImportLoc.isValid())
1627 return F->ImportLoc;
1629 // Otherwise we have a PCH. It's considered to be "imported" at the first
1630 // location of its includer.
1631 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
1632 // Main file is the importer.
1633 assert(SourceMgr.getMainFileID().isValid() && "missing main file");
1634 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
1636 return F->ImportedBy[0]->FirstLoc;
1639 /// Enter a subblock of the specified BlockID with the specified cursor. Read
1640 /// the abbreviations that are at the top of the block and then leave the cursor
1641 /// pointing into the block.
1642 llvm::Error ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor,
1644 uint64_t *StartOfBlockOffset) {
1645 if (llvm::Error Err = Cursor.EnterSubBlock(BlockID))
1648 if (StartOfBlockOffset)
1649 *StartOfBlockOffset = Cursor.GetCurrentBitNo();
1652 uint64_t Offset = Cursor.GetCurrentBitNo();
1653 Expected<unsigned> MaybeCode = Cursor.ReadCode();
1655 return MaybeCode.takeError();
1656 unsigned Code = MaybeCode.get();
1658 // We expect all abbrevs to be at the start of the block.
1659 if (Code != llvm::bitc::DEFINE_ABBREV) {
1660 if (llvm::Error Err = Cursor.JumpToBit(Offset))
1662 return llvm::Error::success();
1664 if (llvm::Error Err = Cursor.ReadAbbrevRecord())
1669 Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
1673 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1674 Tok.setLength(Record[Idx++]);
1675 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1676 Tok.setIdentifierInfo(II);
1677 Tok.setKind((tok::TokenKind)Record[Idx++]);
1678 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1682 MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
1683 BitstreamCursor &Stream = F.MacroCursor;
1685 // Keep track of where we are in the stream, then jump back there
1686 // after reading this macro.
1687 SavedStreamPosition SavedPosition(Stream);
1689 if (llvm::Error Err = Stream.JumpToBit(Offset)) {
1690 // FIXME this drops errors on the floor.
1691 consumeError(std::move(Err));
1695 SmallVector<IdentifierInfo*, 16> MacroParams;
1696 MacroInfo *Macro = nullptr;
1699 // Advance to the next record, but if we get to the end of the block, don't
1700 // pop it (removing all the abbreviations from the cursor) since we want to
1701 // be able to reseek within the block and read entries.
1702 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
1703 Expected<llvm::BitstreamEntry> MaybeEntry =
1704 Stream.advanceSkippingSubblocks(Flags);
1706 Error(MaybeEntry.takeError());
1709 llvm::BitstreamEntry Entry = MaybeEntry.get();
1711 switch (Entry.Kind) {
1712 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1713 case llvm::BitstreamEntry::Error:
1714 Error("malformed block record in AST file");
1716 case llvm::BitstreamEntry::EndBlock:
1718 case llvm::BitstreamEntry::Record:
1719 // The interesting case.
1725 PreprocessorRecordTypes RecType;
1726 if (Expected<unsigned> MaybeRecType = Stream.readRecord(Entry.ID, Record))
1727 RecType = (PreprocessorRecordTypes)MaybeRecType.get();
1729 Error(MaybeRecType.takeError());
1733 case PP_MODULE_MACRO:
1734 case PP_MACRO_DIRECTIVE_HISTORY:
1737 case PP_MACRO_OBJECT_LIKE:
1738 case PP_MACRO_FUNCTION_LIKE: {
1739 // If we already have a macro, that means that we've hit the end
1740 // of the definition of the macro we were looking for. We're
1745 unsigned NextIndex = 1; // Skip identifier ID.
1746 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
1747 MacroInfo *MI = PP.AllocateMacroInfo(Loc);
1748 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
1749 MI->setIsUsed(Record[NextIndex++]);
1750 MI->setUsedForHeaderGuard(Record[NextIndex++]);
1752 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1753 // Decode function-like macro info.
1754 bool isC99VarArgs = Record[NextIndex++];
1755 bool isGNUVarArgs = Record[NextIndex++];
1756 bool hasCommaPasting = Record[NextIndex++];
1757 MacroParams.clear();
1758 unsigned NumArgs = Record[NextIndex++];
1759 for (unsigned i = 0; i != NumArgs; ++i)
1760 MacroParams.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1762 // Install function-like macro info.
1763 MI->setIsFunctionLike();
1764 if (isC99VarArgs) MI->setIsC99Varargs();
1765 if (isGNUVarArgs) MI->setIsGNUVarargs();
1766 if (hasCommaPasting) MI->setHasCommaPasting();
1767 MI->setParameterList(MacroParams, PP.getPreprocessorAllocator());
1770 // Remember that we saw this macro last so that we add the tokens that
1771 // form its body to it.
1774 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1775 Record[NextIndex]) {
1776 // We have a macro definition. Register the association
1777 PreprocessedEntityID
1778 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1779 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
1780 PreprocessingRecord::PPEntityID PPID =
1781 PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
1782 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
1783 PPRec.getPreprocessedEntity(PPID));
1785 PPRec.RegisterMacroDefinition(Macro, PPDef);
1793 // If we see a TOKEN before a PP_MACRO_*, then the file is
1794 // erroneous, just pretend we didn't see this.
1798 Token Tok = ReadToken(F, Record, Idx);
1799 Macro->AddTokenToBody(Tok);
1806 PreprocessedEntityID
1807 ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M,
1808 unsigned LocalID) const {
1809 if (!M.ModuleOffsetMap.empty())
1810 ReadModuleOffsetMap(M);
1812 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1813 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1814 assert(I != M.PreprocessedEntityRemap.end()
1815 && "Invalid index into preprocessed entity index remap");
1817 return LocalID + I->second;
1820 unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1821 return llvm::hash_combine(ikey.Size, ikey.ModTime);
1824 HeaderFileInfoTrait::internal_key_type
1825 HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
1826 internal_key_type ikey = {FE->getSize(),
1827 M.HasTimestamps ? FE->getModificationTime() : 0,
1828 FE->getName(), /*Imported*/ false};
1832 bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
1833 if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime))
1836 if (llvm::sys::path::is_absolute(a.Filename) && a.Filename == b.Filename)
1839 // Determine whether the actual files are equivalent.
1840 FileManager &FileMgr = Reader.getFileManager();
1841 auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
1842 if (!Key.Imported) {
1843 if (auto File = FileMgr.getFile(Key.Filename))
1848 std::string Resolved = std::string(Key.Filename);
1849 Reader.ResolveImportedPath(M, Resolved);
1850 if (auto File = FileMgr.getFile(Resolved))
1855 const FileEntry *FEA = GetFile(a);
1856 const FileEntry *FEB = GetFile(b);
1857 return FEA && FEA == FEB;
1860 std::pair<unsigned, unsigned>
1861 HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
1862 return readULEBKeyDataLength(d);
1865 HeaderFileInfoTrait::internal_key_type
1866 HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
1867 using namespace llvm::support;
1869 internal_key_type ikey;
1870 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1871 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
1872 ikey.Filename = (const char *)d;
1873 ikey.Imported = true;
1877 HeaderFileInfoTrait::data_type
1878 HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
1880 using namespace llvm::support;
1882 const unsigned char *End = d + DataLen;
1884 unsigned Flags = *d++;
1885 // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
1886 HFI.isImport |= (Flags >> 5) & 0x01;
1887 HFI.isPragmaOnce |= (Flags >> 4) & 0x01;
1888 HFI.DirInfo = (Flags >> 1) & 0x07;
1889 HFI.IndexHeaderMapHeader = Flags & 0x01;
1890 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1891 M, endian::readNext<uint32_t, little, unaligned>(d));
1892 if (unsigned FrameworkOffset =
1893 endian::readNext<uint32_t, little, unaligned>(d)) {
1894 // The framework offset is 1 greater than the actual offset,
1895 // since 0 is used as an indicator for "no framework name".
1896 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1897 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1900 assert((End - d) % 4 == 0 &&
1901 "Wrong data length in HeaderFileInfo deserialization");
1903 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
1904 auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 3);
1907 // This header is part of a module. Associate it with the module to enable
1908 // implicit module import.
1909 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1910 Module *Mod = Reader.getSubmodule(GlobalSMID);
1911 FileManager &FileMgr = Reader.getFileManager();
1913 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1915 std::string Filename = std::string(key.Filename);
1917 Reader.ResolveImportedPath(M, Filename);
1918 // FIXME: NameAsWritten
1919 Module::Header H = {std::string(key.Filename), "",
1920 *FileMgr.getFile(Filename)};
1921 ModMap.addHeader(Mod, H, HeaderRole, /*Imported*/true);
1922 HFI.isModuleHeader |= !(HeaderRole & ModuleMap::TextualHeader);
1925 // This HeaderFileInfo was externally loaded.
1926 HFI.External = true;
1931 void ASTReader::addPendingMacro(IdentifierInfo *II, ModuleFile *M,
1932 uint32_t MacroDirectivesOffset) {
1933 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1934 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
1937 void ASTReader::ReadDefinedMacros() {
1938 // Note that we are loading defined macros.
1939 Deserializing Macros(this);
1941 for (ModuleFile &I : llvm::reverse(ModuleMgr)) {
1942 BitstreamCursor &MacroCursor = I.MacroCursor;
1944 // If there was no preprocessor block, skip this file.
1945 if (MacroCursor.getBitcodeBytes().empty())
1948 BitstreamCursor Cursor = MacroCursor;
1949 if (llvm::Error Err = Cursor.JumpToBit(I.MacroStartOffset)) {
1950 Error(std::move(Err));
1956 Expected<llvm::BitstreamEntry> MaybeE = Cursor.advanceSkippingSubblocks();
1958 Error(MaybeE.takeError());
1961 llvm::BitstreamEntry E = MaybeE.get();
1964 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1965 case llvm::BitstreamEntry::Error:
1966 Error("malformed block record in AST file");
1968 case llvm::BitstreamEntry::EndBlock:
1971 case llvm::BitstreamEntry::Record: {
1973 Expected<unsigned> MaybeRecord = Cursor.readRecord(E.ID, Record);
1975 Error(MaybeRecord.takeError());
1978 switch (MaybeRecord.get()) {
1979 default: // Default behavior: ignore.
1982 case PP_MACRO_OBJECT_LIKE:
1983 case PP_MACRO_FUNCTION_LIKE: {
1984 IdentifierInfo *II = getLocalIdentifier(I, Record[0]);
1985 if (II->isOutOfDate())
1986 updateOutOfDateIdentifier(*II);
2004 /// Visitor class used to look up identifirs in an AST file.
2005 class IdentifierLookupVisitor {
2008 unsigned PriorGeneration;
2009 unsigned &NumIdentifierLookups;
2010 unsigned &NumIdentifierLookupHits;
2011 IdentifierInfo *Found = nullptr;
2014 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
2015 unsigned &NumIdentifierLookups,
2016 unsigned &NumIdentifierLookupHits)
2017 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
2018 PriorGeneration(PriorGeneration),
2019 NumIdentifierLookups(NumIdentifierLookups),
2020 NumIdentifierLookupHits(NumIdentifierLookupHits) {}
2022 bool operator()(ModuleFile &M) {
2023 // If we've already searched this module file, skip it now.
2024 if (M.Generation <= PriorGeneration)
2027 ASTIdentifierLookupTable *IdTable
2028 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
2032 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
2034 ++NumIdentifierLookups;
2035 ASTIdentifierLookupTable::iterator Pos =
2036 IdTable->find_hashed(Name, NameHash, &Trait);
2037 if (Pos == IdTable->end())
2040 // Dereferencing the iterator has the effect of building the
2041 // IdentifierInfo node and populating it with the various
2042 // declarations it needs.
2043 ++NumIdentifierLookupHits;
2048 // Retrieve the identifier info found within the module
2050 IdentifierInfo *getIdentifierInfo() const { return Found; }
2055 void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
2056 // Note that we are loading an identifier.
2057 Deserializing AnIdentifier(this);
2059 unsigned PriorGeneration = 0;
2060 if (getContext().getLangOpts().Modules)
2061 PriorGeneration = IdentifierGeneration[&II];
2063 // If there is a global index, look there first to determine which modules
2064 // provably do not have any results for this identifier.
2065 GlobalModuleIndex::HitSet Hits;
2066 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
2067 if (!loadGlobalIndex()) {
2068 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
2073 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
2074 NumIdentifierLookups,
2075 NumIdentifierLookupHits);
2076 ModuleMgr.visit(Visitor, HitsPtr);
2077 markIdentifierUpToDate(&II);
2080 void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
2084 II->setOutOfDate(false);
2086 // Update the generation for this identifier.
2087 if (getContext().getLangOpts().Modules)
2088 IdentifierGeneration[II] = getGeneration();
2091 void ASTReader::resolvePendingMacro(IdentifierInfo *II,
2092 const PendingMacroInfo &PMInfo) {
2093 ModuleFile &M = *PMInfo.M;
2095 BitstreamCursor &Cursor = M.MacroCursor;
2096 SavedStreamPosition SavedPosition(Cursor);
2097 if (llvm::Error Err =
2098 Cursor.JumpToBit(M.MacroOffsetsBase + PMInfo.MacroDirectivesOffset)) {
2099 Error(std::move(Err));
2103 struct ModuleMacroRecord {
2104 SubmoduleID SubModID;
2106 SmallVector<SubmoduleID, 8> Overrides;
2108 llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
2110 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
2111 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
2115 Expected<llvm::BitstreamEntry> MaybeEntry =
2116 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
2118 Error(MaybeEntry.takeError());
2121 llvm::BitstreamEntry Entry = MaybeEntry.get();
2123 if (Entry.Kind != llvm::BitstreamEntry::Record) {
2124 Error("malformed block record in AST file");
2129 Expected<unsigned> MaybePP = Cursor.readRecord(Entry.ID, Record);
2131 Error(MaybePP.takeError());
2134 switch ((PreprocessorRecordTypes)MaybePP.get()) {
2135 case PP_MACRO_DIRECTIVE_HISTORY:
2138 case PP_MODULE_MACRO: {
2139 ModuleMacros.push_back(ModuleMacroRecord());
2140 auto &Info = ModuleMacros.back();
2141 Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
2142 Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
2143 for (int I = 2, N = Record.size(); I != N; ++I)
2144 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
2149 Error("malformed block record in AST file");
2153 // We found the macro directive history; that's the last record
2158 // Module macros are listed in reverse dependency order.
2160 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
2161 llvm::SmallVector<ModuleMacro*, 8> Overrides;
2162 for (auto &MMR : ModuleMacros) {
2164 for (unsigned ModID : MMR.Overrides) {
2165 Module *Mod = getSubmodule(ModID);
2166 auto *Macro = PP.getModuleMacro(Mod, II);
2167 assert(Macro && "missing definition for overridden macro");
2168 Overrides.push_back(Macro);
2171 bool Inserted = false;
2172 Module *Owner = getSubmodule(MMR.SubModID);
2173 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
2177 // Don't read the directive history for a module; we don't have anywhere
2182 // Deserialize the macro directives history in reverse source-order.
2183 MacroDirective *Latest = nullptr, *Earliest = nullptr;
2184 unsigned Idx = 0, N = Record.size();
2186 MacroDirective *MD = nullptr;
2187 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
2188 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
2190 case MacroDirective::MD_Define: {
2191 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
2192 MD = PP.AllocateDefMacroDirective(MI, Loc);
2195 case MacroDirective::MD_Undefine:
2196 MD = PP.AllocateUndefMacroDirective(Loc);
2198 case MacroDirective::MD_Visibility:
2199 bool isPublic = Record[Idx++];
2200 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
2207 Earliest->setPrevious(MD);
2212 PP.setLoadedMacroDirective(II, Earliest, Latest);
2215 bool ASTReader::shouldDisableValidationForFile(
2216 const serialization::ModuleFile &M) const {
2217 if (DisableValidationKind == DisableValidationForModuleKind::None)
2220 // If a PCH is loaded and validation is disabled for PCH then disable
2221 // validation for the PCH and the modules it loads.
2222 ModuleKind K = CurrentDeserializingModuleKind.getValueOr(M.Kind);
2228 return bool(DisableValidationKind & DisableValidationForModuleKind::PCH);
2229 case MK_ImplicitModule:
2230 case MK_ExplicitModule:
2231 case MK_PrebuiltModule:
2232 return bool(DisableValidationKind & DisableValidationForModuleKind::Module);
2238 ASTReader::InputFileInfo
2239 ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
2240 // Go find this input file.
2241 BitstreamCursor &Cursor = F.InputFilesCursor;
2242 SavedStreamPosition SavedPosition(Cursor);
2243 if (llvm::Error Err = Cursor.JumpToBit(F.InputFileOffsets[ID - 1])) {
2244 // FIXME this drops errors on the floor.
2245 consumeError(std::move(Err));
2248 Expected<unsigned> MaybeCode = Cursor.ReadCode();
2250 // FIXME this drops errors on the floor.
2251 consumeError(MaybeCode.takeError());
2253 unsigned Code = MaybeCode.get();
2257 if (Expected<unsigned> Maybe = Cursor.readRecord(Code, Record, &Blob))
2258 assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE &&
2259 "invalid record type for input file");
2261 // FIXME this drops errors on the floor.
2262 consumeError(Maybe.takeError());
2265 assert(Record[0] == ID && "Bogus stored ID or offset");
2267 R.StoredSize = static_cast<off_t>(Record[1]);
2268 R.StoredTime = static_cast<time_t>(Record[2]);
2269 R.Overridden = static_cast<bool>(Record[3]);
2270 R.Transient = static_cast<bool>(Record[4]);
2271 R.TopLevelModuleMap = static_cast<bool>(Record[5]);
2272 R.Filename = std::string(Blob);
2273 ResolveImportedPath(F, R.Filename);
2275 Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
2276 if (!MaybeEntry) // FIXME this drops errors on the floor.
2277 consumeError(MaybeEntry.takeError());
2278 llvm::BitstreamEntry Entry = MaybeEntry.get();
2279 assert(Entry.Kind == llvm::BitstreamEntry::Record &&
2280 "expected record type for input file hash");
2283 if (Expected<unsigned> Maybe = Cursor.readRecord(Entry.ID, Record))
2284 assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE_HASH &&
2285 "invalid record type for input file hash");
2287 // FIXME this drops errors on the floor.
2288 consumeError(Maybe.takeError());
2290 R.ContentHash = (static_cast<uint64_t>(Record[1]) << 32) |
2291 static_cast<uint64_t>(Record[0]);
2295 static unsigned moduleKindForDiagnostic(ModuleKind Kind);
2296 InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
2297 // If this ID is bogus, just return an empty input file.
2298 if (ID == 0 || ID > F.InputFilesLoaded.size())
2301 // If we've already loaded this input file, return it.
2302 if (F.InputFilesLoaded[ID-1].getFile())
2303 return F.InputFilesLoaded[ID-1];
2305 if (F.InputFilesLoaded[ID-1].isNotFound())
2308 // Go find this input file.
2309 BitstreamCursor &Cursor = F.InputFilesCursor;
2310 SavedStreamPosition SavedPosition(Cursor);
2311 if (llvm::Error Err = Cursor.JumpToBit(F.InputFileOffsets[ID - 1])) {
2312 // FIXME this drops errors on the floor.
2313 consumeError(std::move(Err));
2316 InputFileInfo FI = readInputFileInfo(F, ID);
2317 off_t StoredSize = FI.StoredSize;
2318 time_t StoredTime = FI.StoredTime;
2319 bool Overridden = FI.Overridden;
2320 bool Transient = FI.Transient;
2321 StringRef Filename = FI.Filename;
2322 uint64_t StoredContentHash = FI.ContentHash;
2324 OptionalFileEntryRefDegradesToFileEntryPtr File =
2325 expectedToOptional(FileMgr.getFileRef(Filename, /*OpenFile=*/false));
2327 // If we didn't find the file, resolve it relative to the
2328 // original directory from which this AST file was created.
2329 if (!File && !F.OriginalDir.empty() && !F.BaseDirectory.empty() &&
2330 F.OriginalDir != F.BaseDirectory) {
2331 std::string Resolved = resolveFileRelativeToOriginalDir(
2332 std::string(Filename), F.OriginalDir, F.BaseDirectory);
2333 if (!Resolved.empty())
2334 File = expectedToOptional(FileMgr.getFileRef(Resolved));
2337 // For an overridden file, create a virtual file with the stored
2339 if ((Overridden || Transient) && !File)
2340 File = FileMgr.getVirtualFileRef(Filename, StoredSize, StoredTime);
2344 std::string ErrorStr = "could not find file '";
2345 ErrorStr += Filename;
2346 ErrorStr += "' referenced by AST file '";
2347 ErrorStr += F.FileName;
2351 // Record that we didn't find the file.
2352 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
2356 // Check if there was a request to override the contents of the file
2357 // that was part of the precompiled header. Overriding such a file
2358 // can lead to problems when lexing using the source locations from the
2360 SourceManager &SM = getSourceManager();
2361 // FIXME: Reject if the overrides are different.
2362 if ((!Overridden && !Transient) && SM.isFileOverridden(File)) {
2364 Error(diag::err_fe_pch_file_overridden, Filename);
2366 // After emitting the diagnostic, bypass the overriding file to recover
2367 // (this creates a separate FileEntry).
2368 File = SM.bypassFileContentsOverride(*File);
2370 F.InputFilesLoaded[ID - 1] = InputFile::getNotFound();
2376 enum ModificationKind {
2382 llvm::Optional<int64_t> Old = llvm::None;
2383 llvm::Optional<int64_t> New = llvm::None;
2385 auto HasInputFileChanged = [&]() {
2386 if (StoredSize != File->getSize())
2387 return Change{Change::Size, StoredSize, File->getSize()};
2388 if (!shouldDisableValidationForFile(F) && StoredTime &&
2389 StoredTime != File->getModificationTime()) {
2390 Change MTimeChange = {Change::ModTime, StoredTime,
2391 File->getModificationTime()};
2393 // In case the modification time changes but not the content,
2394 // accept the cached file as legit.
2395 if (ValidateASTInputFilesContent &&
2396 StoredContentHash != static_cast<uint64_t>(llvm::hash_code(-1))) {
2397 auto MemBuffOrError = FileMgr.getBufferForFile(File);
2398 if (!MemBuffOrError) {
2401 std::string ErrorStr = "could not get buffer for file '";
2402 ErrorStr += File->getName();
2408 // FIXME: hash_value is not guaranteed to be stable!
2409 auto ContentHash = hash_value(MemBuffOrError.get()->getBuffer());
2410 if (StoredContentHash == static_cast<uint64_t>(ContentHash))
2411 return Change{Change::None};
2413 return Change{Change::Content};
2417 return Change{Change::None};
2420 bool IsOutOfDate = false;
2421 auto FileChange = HasInputFileChanged();
2422 // For an overridden file, there is nothing to validate.
2423 if (!Overridden && FileChange.Kind != Change::None) {
2424 if (Complain && !Diags.isDiagnosticInFlight()) {
2425 // Build a list of the PCH imports that got us here (in reverse).
2426 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2427 while (!ImportStack.back()->ImportedBy.empty())
2428 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
2430 // The top-level PCH is stale.
2431 StringRef TopLevelPCHName(ImportStack.back()->FileName);
2432 Diag(diag::err_fe_ast_file_modified)
2433 << Filename << moduleKindForDiagnostic(ImportStack.back()->Kind)
2434 << TopLevelPCHName << FileChange.Kind
2435 << (FileChange.Old && FileChange.New)
2436 << llvm::itostr(FileChange.Old.getValueOr(0))
2437 << llvm::itostr(FileChange.New.getValueOr(0));
2439 // Print the import stack.
2440 if (ImportStack.size() > 1) {
2441 Diag(diag::note_pch_required_by)
2442 << Filename << ImportStack[0]->FileName;
2443 for (unsigned I = 1; I < ImportStack.size(); ++I)
2444 Diag(diag::note_pch_required_by)
2445 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
2448 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
2453 // FIXME: If the file is overridden and we've already opened it,
2454 // issue an error (or split it into a separate FileEntry).
2456 InputFile IF = InputFile(*File, Overridden || Transient, IsOutOfDate);
2458 // Note that we've loaded this input file.
2459 F.InputFilesLoaded[ID-1] = IF;
2463 /// If we are loading a relocatable PCH or module file, and the filename
2464 /// is not an absolute path, add the system or module root to the beginning of
2466 void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2467 // Resolve relative to the base directory, if we have one.
2468 if (!M.BaseDirectory.empty())
2469 return ResolveImportedPath(Filename, M.BaseDirectory);
2472 void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
2473 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2476 SmallString<128> Buffer;
2477 llvm::sys::path::append(Buffer, Prefix, Filename);
2478 Filename.assign(Buffer.begin(), Buffer.end());
2481 static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
2483 case ASTReader::Failure: return true;
2484 case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
2485 case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
2486 case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch);
2487 case ASTReader::ConfigurationMismatch:
2488 return !(Caps & ASTReader::ARR_ConfigurationMismatch);
2489 case ASTReader::HadErrors: return true;
2490 case ASTReader::Success: return false;
2493 llvm_unreachable("unknown ASTReadResult");
2496 ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(
2497 BitstreamCursor &Stream, unsigned ClientLoadCapabilities,
2498 bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener,
2499 std::string &SuggestedPredefines) {
2500 if (llvm::Error Err = Stream.EnterSubBlock(OPTIONS_BLOCK_ID)) {
2501 // FIXME this drops errors on the floor.
2502 consumeError(std::move(Err));
2506 // Read all of the records in the options block.
2508 ASTReadResult Result = Success;
2510 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
2512 // FIXME this drops errors on the floor.
2513 consumeError(MaybeEntry.takeError());
2516 llvm::BitstreamEntry Entry = MaybeEntry.get();
2518 switch (Entry.Kind) {
2519 case llvm::BitstreamEntry::Error:
2520 case llvm::BitstreamEntry::SubBlock:
2523 case llvm::BitstreamEntry::EndBlock:
2526 case llvm::BitstreamEntry::Record:
2527 // The interesting case.
2531 // Read and process a record.
2533 Expected<unsigned> MaybeRecordType = Stream.readRecord(Entry.ID, Record);
2534 if (!MaybeRecordType) {
2535 // FIXME this drops errors on the floor.
2536 consumeError(MaybeRecordType.takeError());
2539 switch ((OptionsRecordTypes)MaybeRecordType.get()) {
2540 case LANGUAGE_OPTIONS: {
2541 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2542 if (ParseLanguageOptions(Record, Complain, Listener,
2543 AllowCompatibleConfigurationMismatch))
2544 Result = ConfigurationMismatch;
2548 case TARGET_OPTIONS: {
2549 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2550 if (ParseTargetOptions(Record, Complain, Listener,
2551 AllowCompatibleConfigurationMismatch))
2552 Result = ConfigurationMismatch;
2556 case FILE_SYSTEM_OPTIONS: {
2557 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2558 if (!AllowCompatibleConfigurationMismatch &&
2559 ParseFileSystemOptions(Record, Complain, Listener))
2560 Result = ConfigurationMismatch;
2564 case HEADER_SEARCH_OPTIONS: {
2565 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2566 if (!AllowCompatibleConfigurationMismatch &&
2567 ParseHeaderSearchOptions(Record, Complain, Listener))
2568 Result = ConfigurationMismatch;
2572 case PREPROCESSOR_OPTIONS:
2573 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2574 if (!AllowCompatibleConfigurationMismatch &&
2575 ParsePreprocessorOptions(Record, Complain, Listener,
2576 SuggestedPredefines))
2577 Result = ConfigurationMismatch;
2583 ASTReader::ASTReadResult
2584 ASTReader::ReadControlBlock(ModuleFile &F,
2585 SmallVectorImpl<ImportedModule> &Loaded,
2586 const ModuleFile *ImportedBy,
2587 unsigned ClientLoadCapabilities) {
2588 BitstreamCursor &Stream = F.Stream;
2590 if (llvm::Error Err = Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2591 Error(std::move(Err));
2595 // Lambda to read the unhashed control block the first time it's called.
2597 // For PCM files, the unhashed control block cannot be read until after the
2598 // MODULE_NAME record. However, PCH files have no MODULE_NAME, and yet still
2599 // need to look ahead before reading the IMPORTS record. For consistency,
2600 // this block is always read somehow (see BitstreamEntry::EndBlock).
2601 bool HasReadUnhashedControlBlock = false;
2602 auto readUnhashedControlBlockOnce = [&]() {
2603 if (!HasReadUnhashedControlBlock) {
2604 HasReadUnhashedControlBlock = true;
2605 if (ASTReadResult Result =
2606 readUnhashedControlBlock(F, ImportedBy, ClientLoadCapabilities))
2612 bool DisableValidation = shouldDisableValidationForFile(F);
2614 // Read all of the records and blocks in the control block.
2616 unsigned NumInputs = 0;
2617 unsigned NumUserInputs = 0;
2618 StringRef BaseDirectoryAsWritten;
2620 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
2622 Error(MaybeEntry.takeError());
2625 llvm::BitstreamEntry Entry = MaybeEntry.get();
2627 switch (Entry.Kind) {
2628 case llvm::BitstreamEntry::Error:
2629 Error("malformed block record in AST file");
2631 case llvm::BitstreamEntry::EndBlock: {
2632 // Validate the module before returning. This call catches an AST with
2633 // no module name and no imports.
2634 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2637 // Validate input files.
2638 const HeaderSearchOptions &HSOpts =
2639 PP.getHeaderSearchInfo().getHeaderSearchOpts();
2641 // All user input files reside at the index range [0, NumUserInputs), and
2642 // system input files reside at [NumUserInputs, NumInputs). For explicitly
2643 // loaded module files, ignore missing inputs.
2644 if (!DisableValidation && F.Kind != MK_ExplicitModule &&
2645 F.Kind != MK_PrebuiltModule) {
2646 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
2648 // If we are reading a module, we will create a verification timestamp,
2649 // so we verify all input files. Otherwise, verify only user input
2652 unsigned N = NumUserInputs;
2653 if (ValidateSystemInputs ||
2654 (HSOpts.ModulesValidateOncePerBuildSession &&
2655 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
2656 F.Kind == MK_ImplicitModule))
2659 for (unsigned I = 0; I < N; ++I) {
2660 InputFile IF = getInputFile(F, I+1, Complain);
2661 if (!IF.getFile() || IF.isOutOfDate())
2667 Listener->visitModuleFile(F.FileName, F.Kind);
2669 if (Listener && Listener->needsInputFileVisitation()) {
2670 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2672 for (unsigned I = 0; I < N; ++I) {
2673 bool IsSystem = I >= NumUserInputs;
2674 InputFileInfo FI = readInputFileInfo(F, I+1);
2675 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden,
2676 F.Kind == MK_ExplicitModule ||
2677 F.Kind == MK_PrebuiltModule);
2684 case llvm::BitstreamEntry::SubBlock:
2686 case INPUT_FILES_BLOCK_ID:
2687 F.InputFilesCursor = Stream;
2688 if (llvm::Error Err = Stream.SkipBlock()) {
2689 Error(std::move(Err));
2692 if (ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2693 Error("malformed block record in AST file");
2698 case OPTIONS_BLOCK_ID:
2699 // If we're reading the first module for this group, check its options
2700 // are compatible with ours. For modules it imports, no further checking
2701 // is required, because we checked them when we built it.
2702 if (Listener && !ImportedBy) {
2703 // Should we allow the configuration of the module file to differ from
2704 // the configuration of the current translation unit in a compatible
2707 // FIXME: Allow this for files explicitly specified with -include-pch.
2708 bool AllowCompatibleConfigurationMismatch =
2709 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
2711 ASTReadResult Result =
2712 ReadOptionsBlock(Stream, ClientLoadCapabilities,
2713 AllowCompatibleConfigurationMismatch, *Listener,
2714 SuggestedPredefines);
2715 if (Result == Failure) {
2716 Error("malformed block record in AST file");
2720 if (DisableValidation ||
2721 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
2724 // If we can't load the module, exit early since we likely
2725 // will rebuild the module anyway. The stream may be in the
2726 // middle of a block.
2727 if (Result != Success)
2729 } else if (llvm::Error Err = Stream.SkipBlock()) {
2730 Error(std::move(Err));
2736 if (llvm::Error Err = Stream.SkipBlock()) {
2737 Error(std::move(Err));
2743 case llvm::BitstreamEntry::Record:
2744 // The interesting case.
2748 // Read and process a record.
2751 Expected<unsigned> MaybeRecordType =
2752 Stream.readRecord(Entry.ID, Record, &Blob);
2753 if (!MaybeRecordType) {
2754 Error(MaybeRecordType.takeError());
2757 switch ((ControlRecordTypes)MaybeRecordType.get()) {
2759 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2760 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
2761 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2762 : diag::err_pch_version_too_new);
2763 return VersionMismatch;
2766 bool hasErrors = Record[6];
2767 if (hasErrors && !DisableValidation) {
2768 // If requested by the caller and the module hasn't already been read
2769 // or compiled, mark modules on error as out-of-date.
2770 if ((ClientLoadCapabilities & ARR_TreatModuleWithErrorsAsOutOfDate) &&
2771 canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
2774 if (!AllowASTWithCompilerErrors) {
2775 Diag(diag::err_pch_with_compiler_errors);
2780 Diags.ErrorOccurred = true;
2781 Diags.UncompilableErrorOccurred = true;
2782 Diags.UnrecoverableErrorOccurred = true;
2785 F.RelocatablePCH = Record[4];
2786 // Relative paths in a relocatable PCH are relative to our sysroot.
2787 if (F.RelocatablePCH)
2788 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
2790 F.HasTimestamps = Record[5];
2792 const std::string &CurBranch = getClangFullRepositoryVersion();
2793 StringRef ASTBranch = Blob;
2794 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2795 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
2796 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
2797 return VersionMismatch;
2803 // Validate the AST before processing any imports (otherwise, untangling
2804 // them can be error-prone and expensive). A module will have a name and
2805 // will already have been validated, but this catches the PCH case.
2806 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2809 // Load each of the imported PCH files.
2810 unsigned Idx = 0, N = Record.size();
2812 // Read information about the AST file.
2813 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2814 // The import location will be the local one for now; we will adjust
2815 // all import locations of module imports after the global source
2816 // location info are setup, in ReadAST.
2817 SourceLocation ImportLoc =
2818 ReadUntranslatedSourceLocation(Record[Idx++]);
2819 off_t StoredSize = (off_t)Record[Idx++];
2820 time_t StoredModTime = (time_t)Record[Idx++];
2821 auto FirstSignatureByte = Record.begin() + Idx;
2822 ASTFileSignature StoredSignature = ASTFileSignature::create(
2823 FirstSignatureByte, FirstSignatureByte + ASTFileSignature::size);
2824 Idx += ASTFileSignature::size;
2826 std::string ImportedName = ReadString(Record, Idx);
2827 std::string ImportedFile;
2829 // For prebuilt and explicit modules first consult the file map for
2830 // an override. Note that here we don't search prebuilt module
2831 // directories, only the explicit name to file mappings. Also, we will
2832 // still verify the size/signature making sure it is essentially the
2833 // same file but perhaps in a different location.
2834 if (ImportedKind == MK_PrebuiltModule || ImportedKind == MK_ExplicitModule)
2835 ImportedFile = PP.getHeaderSearchInfo().getPrebuiltModuleFileName(
2836 ImportedName, /*FileMapOnly*/ true);
2838 if (ImportedFile.empty())
2839 // Use BaseDirectoryAsWritten to ensure we use the same path in the
2840 // ModuleCache as when writing.
2841 ImportedFile = ReadPath(BaseDirectoryAsWritten, Record, Idx);
2843 SkipPath(Record, Idx);
2845 // If our client can't cope with us being out of date, we can't cope with
2846 // our dependency being missing.
2847 unsigned Capabilities = ClientLoadCapabilities;
2848 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2849 Capabilities &= ~ARR_Missing;
2851 // Load the AST file.
2852 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
2853 Loaded, StoredSize, StoredModTime,
2854 StoredSignature, Capabilities);
2856 // If we diagnosed a problem, produce a backtrace.
2857 bool recompilingFinalized =
2858 Result == OutOfDate && (Capabilities & ARR_OutOfDate) &&
2859 getModuleManager().getModuleCache().isPCMFinal(F.FileName);
2860 if (isDiagnosedResult(Result, Capabilities) || recompilingFinalized)
2861 Diag(diag::note_module_file_imported_by)
2862 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
2863 if (recompilingFinalized)
2864 Diag(diag::note_module_file_conflict);
2867 case Failure: return Failure;
2868 // If we have to ignore the dependency, we'll have to ignore this too.
2870 case OutOfDate: return OutOfDate;
2871 case VersionMismatch: return VersionMismatch;
2872 case ConfigurationMismatch: return ConfigurationMismatch;
2873 case HadErrors: return HadErrors;
2874 case Success: break;
2881 F.OriginalSourceFileID = FileID::get(Record[0]);
2882 F.ActualOriginalSourceFileName = std::string(Blob);
2883 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
2884 ResolveImportedPath(F, F.OriginalSourceFileName);
2887 case ORIGINAL_FILE_ID:
2888 F.OriginalSourceFileID = FileID::get(Record[0]);
2891 case ORIGINAL_PCH_DIR:
2892 F.OriginalDir = std::string(Blob);
2896 F.ModuleName = std::string(Blob);
2897 Diag(diag::remark_module_import)
2898 << F.ModuleName << F.FileName << (ImportedBy ? true : false)
2899 << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());
2901 Listener->ReadModuleName(F.ModuleName);
2903 // Validate the AST as soon as we have a name so we can exit early on
2905 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2910 case MODULE_DIRECTORY: {
2911 // Save the BaseDirectory as written in the PCM for computing the module
2912 // filename for the ModuleCache.
2913 BaseDirectoryAsWritten = Blob;
2914 assert(!F.ModuleName.empty() &&
2915 "MODULE_DIRECTORY found before MODULE_NAME");
2916 // If we've already loaded a module map file covering this module, we may
2917 // have a better path for it (relative to the current build).
2918 Module *M = PP.getHeaderSearchInfo().lookupModule(
2919 F.ModuleName, SourceLocation(), /*AllowSearch*/ true,
2920 /*AllowExtraModuleMapSearch*/ true);
2921 if (M && M->Directory) {
2922 // If we're implicitly loading a module, the base directory can't
2923 // change between the build and use.
2924 // Don't emit module relocation error if we have -fno-validate-pch
2925 if (!bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation &
2926 DisableValidationForModuleKind::Module) &&
2927 F.Kind != MK_ExplicitModule && F.Kind != MK_PrebuiltModule) {
2928 auto BuildDir = PP.getFileManager().getDirectory(Blob);
2929 if (!BuildDir || *BuildDir != M->Directory) {
2930 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
2931 Diag(diag::err_imported_module_relocated)
2932 << F.ModuleName << Blob << M->Directory->getName();
2936 F.BaseDirectory = std::string(M->Directory->getName());
2938 F.BaseDirectory = std::string(Blob);
2943 case MODULE_MAP_FILE:
2944 if (ASTReadResult Result =
2945 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2949 case INPUT_FILE_OFFSETS:
2950 NumInputs = Record[0];
2951 NumUserInputs = Record[1];
2952 F.InputFileOffsets =
2953 (const llvm::support::unaligned_uint64_t *)Blob.data();
2954 F.InputFilesLoaded.resize(NumInputs);
2955 F.NumUserInputFiles = NumUserInputs;
2961 void ASTReader::readIncludedFiles(ModuleFile &F, StringRef Blob,
2963 using namespace llvm::support;
2965 const unsigned char *D = (const unsigned char *)Blob.data();
2966 unsigned FileCount = endian::readNext<uint32_t, little, unaligned>(D);
2968 for (unsigned I = 0; I < FileCount; ++I) {
2969 size_t ID = endian::readNext<uint32_t, little, unaligned>(D);
2970 InputFileInfo IFI = readInputFileInfo(F, ID);
2971 if (llvm::ErrorOr<const FileEntry *> File =
2972 PP.getFileManager().getFile(IFI.Filename))
2973 PP.getIncludedFiles().insert(*File);
2977 llvm::Error ASTReader::ReadASTBlock(ModuleFile &F,
2978 unsigned ClientLoadCapabilities) {
2979 BitstreamCursor &Stream = F.Stream;
2981 if (llvm::Error Err = Stream.EnterSubBlock(AST_BLOCK_ID))
2983 F.ASTBlockStartOffset = Stream.GetCurrentBitNo();
2985 // Read all of the records and blocks for the AST file.
2988 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
2990 return MaybeEntry.takeError();
2991 llvm::BitstreamEntry Entry = MaybeEntry.get();
2993 switch (Entry.Kind) {
2994 case llvm::BitstreamEntry::Error:
2995 return llvm::createStringError(
2996 std::errc::illegal_byte_sequence,
2997 "error at end of module block in AST file");
2998 case llvm::BitstreamEntry::EndBlock:
2999 // Outside of C++, we do not store a lookup map for the translation unit.
3000 // Instead, mark it as needing a lookup map to be built if this module
3001 // contains any declarations lexically within it (which it always does!).
3002 // This usually has no cost, since we very rarely need the lookup map for
3003 // the translation unit outside C++.
3004 if (ASTContext *Ctx = ContextObj) {
3005 DeclContext *DC = Ctx->getTranslationUnitDecl();
3006 if (DC->hasExternalLexicalStorage() && !Ctx->getLangOpts().CPlusPlus)
3007 DC->setMustBuildLookupTable();
3010 return llvm::Error::success();
3011 case llvm::BitstreamEntry::SubBlock:
3013 case DECLTYPES_BLOCK_ID:
3014 // We lazily load the decls block, but we want to set up the
3015 // DeclsCursor cursor to point into it. Clone our current bitcode
3016 // cursor to it, enter the block and read the abbrevs in that block.
3017 // With the main cursor, we just skip over it.
3018 F.DeclsCursor = Stream;
3019 if (llvm::Error Err = Stream.SkipBlock())
3021 if (llvm::Error Err = ReadBlockAbbrevs(
3022 F.DeclsCursor, DECLTYPES_BLOCK_ID, &F.DeclsBlockStartOffset))
3026 case PREPROCESSOR_BLOCK_ID:
3027 F.MacroCursor = Stream;
3028 if (!PP.getExternalSource())
3029 PP.setExternalSource(this);
3031 if (llvm::Error Err = Stream.SkipBlock())
3033 if (llvm::Error Err =
3034 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID))
3036 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
3039 case PREPROCESSOR_DETAIL_BLOCK_ID:
3040 F.PreprocessorDetailCursor = Stream;
3042 if (llvm::Error Err = Stream.SkipBlock()) {
3045 if (llvm::Error Err = ReadBlockAbbrevs(F.PreprocessorDetailCursor,
3046 PREPROCESSOR_DETAIL_BLOCK_ID))
3048 F.PreprocessorDetailStartOffset
3049 = F.PreprocessorDetailCursor.GetCurrentBitNo();
3051 if (!PP.getPreprocessingRecord())
3052 PP.createPreprocessingRecord();
3053 if (!PP.getPreprocessingRecord()->getExternalSource())
3054 PP.getPreprocessingRecord()->SetExternalSource(*this);
3057 case SOURCE_MANAGER_BLOCK_ID:
3058 if (llvm::Error Err = ReadSourceManagerBlock(F))
3062 case SUBMODULE_BLOCK_ID:
3063 if (llvm::Error Err = ReadSubmoduleBlock(F, ClientLoadCapabilities))
3067 case COMMENTS_BLOCK_ID: {
3068 BitstreamCursor C = Stream;
3070 if (llvm::Error Err = Stream.SkipBlock())
3072 if (llvm::Error Err = ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID))
3074 CommentsCursors.push_back(std::make_pair(C, &F));
3079 if (llvm::Error Err = Stream.SkipBlock())
3085 case llvm::BitstreamEntry::Record:
3086 // The interesting case.
3090 // Read and process a record.
3093 Expected<unsigned> MaybeRecordType =
3094 Stream.readRecord(Entry.ID, Record, &Blob);
3095 if (!MaybeRecordType)
3096 return MaybeRecordType.takeError();
3097 ASTRecordTypes RecordType = (ASTRecordTypes)MaybeRecordType.get();
3099 // If we're not loading an AST context, we don't care about most records.
3101 switch (RecordType) {
3102 case IDENTIFIER_TABLE:
3103 case IDENTIFIER_OFFSET:
3104 case INTERESTING_IDENTIFIERS:
3106 case PP_CONDITIONAL_STACK:
3107 case PP_COUNTER_VALUE:
3108 case SOURCE_LOCATION_OFFSETS:
3109 case MODULE_OFFSET_MAP:
3110 case SOURCE_MANAGER_LINE_TABLE:
3111 case SOURCE_LOCATION_PRELOADS:
3112 case PPD_ENTITIES_OFFSETS:
3113 case HEADER_SEARCH_TABLE:
3114 case IMPORTED_MODULES:
3122 switch (RecordType) {
3123 default: // Default behavior: ignore.
3127 if (F.LocalNumTypes != 0)
3128 return llvm::createStringError(
3129 std::errc::illegal_byte_sequence,
3130 "duplicate TYPE_OFFSET record in AST file");
3131 F.TypeOffsets = reinterpret_cast<const UnderalignedInt64 *>(Blob.data());
3132 F.LocalNumTypes = Record[0];
3133 unsigned LocalBaseTypeIndex = Record[1];
3134 F.BaseTypeIndex = getTotalNumTypes();
3136 if (F.LocalNumTypes > 0) {
3137 // Introduce the global -> local mapping for types within this module.
3138 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
3140 // Introduce the local -> global mapping for types within this module.
3141 F.TypeRemap.insertOrReplace(
3142 std::make_pair(LocalBaseTypeIndex,
3143 F.BaseTypeIndex - LocalBaseTypeIndex));
3145 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
3151 if (F.LocalNumDecls != 0)
3152 return llvm::createStringError(
3153 std::errc::illegal_byte_sequence,
3154 "duplicate DECL_OFFSET record in AST file");
3155 F.DeclOffsets = (const DeclOffset *)Blob.data();
3156 F.LocalNumDecls = Record[0];
3157 unsigned LocalBaseDeclID = Record[1];
3158 F.BaseDeclID = getTotalNumDecls();
3160 if (F.LocalNumDecls > 0) {
3161 // Introduce the global -> local mapping for declarations within this
3163 GlobalDeclMap.insert(
3164 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
3166 // Introduce the local -> global mapping for declarations within this
3168 F.DeclRemap.insertOrReplace(
3169 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
3171 // Introduce the global -> local mapping for declarations within this
3173 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
3175 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
3180 case TU_UPDATE_LEXICAL: {
3181 DeclContext *TU = ContextObj->getTranslationUnitDecl();
3182 LexicalContents Contents(
3183 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
3185 static_cast<unsigned int>(Blob.size() / 4));
3186 TULexicalDecls.push_back(std::make_pair(&F, Contents));
3187 TU->setHasExternalLexicalStorage(true);
3191 case UPDATE_VISIBLE: {
3193 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
3194 auto *Data = (const unsigned char*)Blob.data();
3195 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&F, Data});
3196 // If we've already loaded the decl, perform the updates when we finish
3197 // loading this block.
3198 if (Decl *D = GetExistingDecl(ID))
3199 PendingUpdateRecords.push_back(
3200 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3204 case IDENTIFIER_TABLE:
3205 F.IdentifierTableData =
3206 reinterpret_cast<const unsigned char *>(Blob.data());
3208 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
3209 F.IdentifierTableData + Record[0],
3210 F.IdentifierTableData + sizeof(uint32_t),
3211 F.IdentifierTableData,
3212 ASTIdentifierLookupTrait(*this, F));
3214 PP.getIdentifierTable().setExternalIdentifierLookup(this);
3218 case IDENTIFIER_OFFSET: {
3219 if (F.LocalNumIdentifiers != 0)
3220 return llvm::createStringError(
3221 std::errc::illegal_byte_sequence,
3222 "duplicate IDENTIFIER_OFFSET record in AST file");
3223 F.IdentifierOffsets = (const uint32_t *)Blob.data();
3224 F.LocalNumIdentifiers = Record[0];
3225 unsigned LocalBaseIdentifierID = Record[1];
3226 F.BaseIdentifierID = getTotalNumIdentifiers();
3228 if (F.LocalNumIdentifiers > 0) {
3229 // Introduce the global -> local mapping for identifiers within this
3231 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
3234 // Introduce the local -> global mapping for identifiers within this
3236 F.IdentifierRemap.insertOrReplace(
3237 std::make_pair(LocalBaseIdentifierID,
3238 F.BaseIdentifierID - LocalBaseIdentifierID));
3240 IdentifiersLoaded.resize(IdentifiersLoaded.size()
3241 + F.LocalNumIdentifiers);
3246 case INTERESTING_IDENTIFIERS:
3247 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
3250 case EAGERLY_DESERIALIZED_DECLS:
3251 // FIXME: Skip reading this record if our ASTConsumer doesn't care
3252 // about "interesting" decls (for instance, if we're building a module).
3253 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3254 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
3257 case MODULAR_CODEGEN_DECLS:
3258 // FIXME: Skip reading this record if our ASTConsumer doesn't care about
3259 // them (ie: if we're not codegenerating this module).
3260 if (F.Kind == MK_MainFile ||
3261 getContext().getLangOpts().BuildingPCHWithObjectFile)
3262 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3263 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
3267 if (SpecialTypes.empty()) {
3268 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3269 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
3273 if (SpecialTypes.size() != Record.size())
3274 return llvm::createStringError(std::errc::illegal_byte_sequence,
3275 "invalid special-types record");
3277 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
3278 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
3279 if (!SpecialTypes[I])
3280 SpecialTypes[I] = ID;
3281 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
3287 TotalNumStatements += Record[0];
3288 TotalNumMacros += Record[1];
3289 TotalLexicalDeclContexts += Record[2];
3290 TotalVisibleDeclContexts += Record[3];
3293 case UNUSED_FILESCOPED_DECLS:
3294 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3295 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
3298 case DELEGATING_CTORS:
3299 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3300 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
3303 case WEAK_UNDECLARED_IDENTIFIERS:
3304 if (Record.size() % 4 != 0)
3305 return llvm::createStringError(std::errc::illegal_byte_sequence,
3306 "invalid weak identifiers record");
3308 // FIXME: Ignore weak undeclared identifiers from non-original PCH
3309 // files. This isn't the way to do it :)
3310 WeakUndeclaredIdentifiers.clear();
3312 // Translate the weak, undeclared identifiers into global IDs.
3313 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
3314 WeakUndeclaredIdentifiers.push_back(
3315 getGlobalIdentifierID(F, Record[I++]));
3316 WeakUndeclaredIdentifiers.push_back(
3317 getGlobalIdentifierID(F, Record[I++]));
3318 WeakUndeclaredIdentifiers.push_back(
3319 ReadSourceLocation(F, Record, I).getRawEncoding());
3320 WeakUndeclaredIdentifiers.push_back(Record[I++]);
3324 case SELECTOR_OFFSETS: {
3325 F.SelectorOffsets = (const uint32_t *)Blob.data();
3326 F.LocalNumSelectors = Record[0];
3327 unsigned LocalBaseSelectorID = Record[1];
3328 F.BaseSelectorID = getTotalNumSelectors();
3330 if (F.LocalNumSelectors > 0) {
3331 // Introduce the global -> local mapping for selectors within this
3333 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
3335 // Introduce the local -> global mapping for selectors within this
3337 F.SelectorRemap.insertOrReplace(
3338 std::make_pair(LocalBaseSelectorID,
3339 F.BaseSelectorID - LocalBaseSelectorID));
3341 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
3347 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
3349 F.SelectorLookupTable
3350 = ASTSelectorLookupTable::Create(
3351 F.SelectorLookupTableData + Record[0],
3352 F.SelectorLookupTableData,
3353 ASTSelectorLookupTrait(*this, F));
3354 TotalNumMethodPoolEntries += Record[1];
3357 case REFERENCED_SELECTOR_POOL:
3358 if (!Record.empty()) {
3359 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
3360 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
3362 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
3368 case PP_CONDITIONAL_STACK:
3369 if (!Record.empty()) {
3370 unsigned Idx = 0, End = Record.size() - 1;
3371 bool ReachedEOFWhileSkipping = Record[Idx++];
3372 llvm::Optional<Preprocessor::PreambleSkipInfo> SkipInfo;
3373 if (ReachedEOFWhileSkipping) {
3374 SourceLocation HashToken = ReadSourceLocation(F, Record, Idx);
3375 SourceLocation IfTokenLoc = ReadSourceLocation(F, Record, Idx);
3376 bool FoundNonSkipPortion = Record[Idx++];
3377 bool FoundElse = Record[Idx++];
3378 SourceLocation ElseLoc = ReadSourceLocation(F, Record, Idx);
3379 SkipInfo.emplace(HashToken, IfTokenLoc, FoundNonSkipPortion,
3380 FoundElse, ElseLoc);
3382 SmallVector<PPConditionalInfo, 4> ConditionalStack;
3384 auto Loc = ReadSourceLocation(F, Record, Idx);
3385 bool WasSkipping = Record[Idx++];
3386 bool FoundNonSkip = Record[Idx++];
3387 bool FoundElse = Record[Idx++];
3388 ConditionalStack.push_back(
3389 {Loc, WasSkipping, FoundNonSkip, FoundElse});
3391 PP.setReplayablePreambleConditionalStack(ConditionalStack, SkipInfo);
3395 case PP_COUNTER_VALUE:
3396 if (!Record.empty() && Listener)
3397 Listener->ReadCounter(F, Record[0]);
3400 case FILE_SORTED_DECLS:
3401 F.FileSortedDecls = (const DeclID *)Blob.data();
3402 F.NumFileSortedDecls = Record[0];
3405 case SOURCE_LOCATION_OFFSETS: {
3406 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
3407 F.LocalNumSLocEntries = Record[0];
3408 SourceLocation::UIntTy SLocSpaceSize = Record[1];
3409 F.SLocEntryOffsetsBase = Record[2] + F.SourceManagerBlockStartOffset;
3410 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
3411 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
3413 if (!F.SLocEntryBaseID)
3414 return llvm::createStringError(std::errc::invalid_argument,
3415 "ran out of source locations");
3416 // Make our entry in the range map. BaseID is negative and growing, so
3417 // we invert it. Because we invert it, though, we need the other end of
3419 unsigned RangeStart =
3420 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
3421 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
3422 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
3424 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
3425 assert((F.SLocEntryBaseOffset & SourceLocation::MacroIDBit) == 0);
3426 GlobalSLocOffsetMap.insert(
3427 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
3428 - SLocSpaceSize,&F));
3430 // Initialize the remapping table.
3431 // Invalid stays invalid.
3432 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
3433 // This module. Base was 2 when being compiled.
3434 F.SLocRemap.insertOrReplace(std::make_pair(
3435 2U, static_cast<SourceLocation::IntTy>(F.SLocEntryBaseOffset - 2)));
3437 TotalNumSLocEntries += F.LocalNumSLocEntries;
3441 case MODULE_OFFSET_MAP:
3442 F.ModuleOffsetMap = Blob;
3445 case SOURCE_MANAGER_LINE_TABLE:
3446 ParseLineTable(F, Record);
3449 case SOURCE_LOCATION_PRELOADS: {
3450 // Need to transform from the local view (1-based IDs) to the global view,
3451 // which is based off F.SLocEntryBaseID.
3452 if (!F.PreloadSLocEntries.empty())
3453 return llvm::createStringError(
3454 std::errc::illegal_byte_sequence,
3455 "Multiple SOURCE_LOCATION_PRELOADS records in AST file");
3457 F.PreloadSLocEntries.swap(Record);
3461 case EXT_VECTOR_DECLS:
3462 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3463 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
3467 if (Record.size() % 3 != 0)
3468 return llvm::createStringError(std::errc::illegal_byte_sequence,
3469 "Invalid VTABLE_USES record");
3471 // Later tables overwrite earlier ones.
3472 // FIXME: Modules will have some trouble with this. This is clearly not
3473 // the right way to do this.
3476 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
3477 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
3478 VTableUses.push_back(
3479 ReadSourceLocation(F, Record, Idx).getRawEncoding());
3480 VTableUses.push_back(Record[Idx++]);
3484 case PENDING_IMPLICIT_INSTANTIATIONS:
3485 if (PendingInstantiations.size() % 2 != 0)
3486 return llvm::createStringError(
3487 std::errc::illegal_byte_sequence,
3488 "Invalid existing PendingInstantiations");
3490 if (Record.size() % 2 != 0)
3491 return llvm::createStringError(
3492 std::errc::illegal_byte_sequence,
3493 "Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
3495 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3496 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
3497 PendingInstantiations.push_back(
3498 ReadSourceLocation(F, Record, I).getRawEncoding());
3502 case SEMA_DECL_REFS:
3503 if (Record.size() != 3)
3504 return llvm::createStringError(std::errc::illegal_byte_sequence,
3505 "Invalid SEMA_DECL_REFS block");
3506 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3507 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3510 case PPD_ENTITIES_OFFSETS: {
3511 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3512 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3513 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
3515 unsigned LocalBasePreprocessedEntityID = Record[0];
3517 unsigned StartingID;
3518 if (!PP.getPreprocessingRecord())
3519 PP.createPreprocessingRecord();
3520 if (!PP.getPreprocessingRecord()->getExternalSource())
3521 PP.getPreprocessingRecord()->SetExternalSource(*this);
3523 = PP.getPreprocessingRecord()
3524 ->allocateLoadedEntities(F.NumPreprocessedEntities);
3525 F.BasePreprocessedEntityID = StartingID;
3527 if (F.NumPreprocessedEntities > 0) {
3528 // Introduce the global -> local mapping for preprocessed entities in
3530 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
3532 // Introduce the local -> global mapping for preprocessed entities in
3534 F.PreprocessedEntityRemap.insertOrReplace(
3535 std::make_pair(LocalBasePreprocessedEntityID,
3536 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3542 case PPD_SKIPPED_RANGES: {
3543 F.PreprocessedSkippedRangeOffsets = (const PPSkippedRange*)Blob.data();
3544 assert(Blob.size() % sizeof(PPSkippedRange) == 0);
3545 F.NumPreprocessedSkippedRanges = Blob.size() / sizeof(PPSkippedRange);
3547 if (!PP.getPreprocessingRecord())
3548 PP.createPreprocessingRecord();
3549 if (!PP.getPreprocessingRecord()->getExternalSource())
3550 PP.getPreprocessingRecord()->SetExternalSource(*this);
3551 F.BasePreprocessedSkippedRangeID = PP.getPreprocessingRecord()
3552 ->allocateSkippedRanges(F.NumPreprocessedSkippedRanges);
3554 if (F.NumPreprocessedSkippedRanges > 0)
3555 GlobalSkippedRangeMap.insert(
3556 std::make_pair(F.BasePreprocessedSkippedRangeID, &F));
3560 case DECL_UPDATE_OFFSETS:
3561 if (Record.size() % 2 != 0)
3562 return llvm::createStringError(
3563 std::errc::illegal_byte_sequence,
3564 "invalid DECL_UPDATE_OFFSETS block in AST file");
3565 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3566 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3567 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3569 // If we've already loaded the decl, perform the updates when we finish
3570 // loading this block.
3571 if (Decl *D = GetExistingDecl(ID))
3572 PendingUpdateRecords.push_back(
3573 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3577 case OBJC_CATEGORIES_MAP:
3578 if (F.LocalNumObjCCategoriesInMap != 0)
3579 return llvm::createStringError(
3580 std::errc::illegal_byte_sequence,
3581 "duplicate OBJC_CATEGORIES_MAP record in AST file");
3583 F.LocalNumObjCCategoriesInMap = Record[0];
3584 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
3587 case OBJC_CATEGORIES:
3588 F.ObjCCategories.swap(Record);
3591 case CUDA_SPECIAL_DECL_REFS:
3592 // Later tables overwrite earlier ones.
3593 // FIXME: Modules will have trouble with this.
3594 CUDASpecialDeclRefs.clear();
3595 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3596 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3599 case HEADER_SEARCH_TABLE:
3600 F.HeaderFileInfoTableData = Blob.data();
3601 F.LocalNumHeaderFileInfos = Record[1];
3603 F.HeaderFileInfoTable
3604 = HeaderFileInfoLookupTable::Create(
3605 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3606 (const unsigned char *)F.HeaderFileInfoTableData,
3607 HeaderFileInfoTrait(*this, F,
3608 &PP.getHeaderSearchInfo(),
3609 Blob.data() + Record[2]));
3611 PP.getHeaderSearchInfo().SetExternalSource(this);
3612 if (!PP.getHeaderSearchInfo().getExternalLookup())
3613 PP.getHeaderSearchInfo().SetExternalLookup(this);
3617 case FP_PRAGMA_OPTIONS:
3618 // Later tables overwrite earlier ones.
3619 FPPragmaOptions.swap(Record);
3622 case OPENCL_EXTENSIONS:
3623 for (unsigned I = 0, E = Record.size(); I != E; ) {
3624 auto Name = ReadString(Record, I);
3625 auto &OptInfo = OpenCLExtensions.OptMap[Name];
3626 OptInfo.Supported = Record[I++] != 0;
3627 OptInfo.Enabled = Record[I++] != 0;
3628 OptInfo.WithPragma = Record[I++] != 0;
3629 OptInfo.Avail = Record[I++];
3630 OptInfo.Core = Record[I++];
3631 OptInfo.Opt = Record[I++];
3635 case TENTATIVE_DEFINITIONS:
3636 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3637 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3640 case KNOWN_NAMESPACES:
3641 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3642 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3645 case UNDEFINED_BUT_USED:
3646 if (UndefinedButUsed.size() % 2 != 0)
3647 return llvm::createStringError(std::errc::illegal_byte_sequence,
3648 "Invalid existing UndefinedButUsed");
3650 if (Record.size() % 2 != 0)
3651 return llvm::createStringError(std::errc::illegal_byte_sequence,
3652 "invalid undefined-but-used record");
3653 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3654 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3655 UndefinedButUsed.push_back(
3656 ReadSourceLocation(F, Record, I).getRawEncoding());
3660 case DELETE_EXPRS_TO_ANALYZE:
3661 for (unsigned I = 0, N = Record.size(); I != N;) {
3662 DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
3663 const uint64_t Count = Record[I++];
3664 DelayedDeleteExprs.push_back(Count);
3665 for (uint64_t C = 0; C < Count; ++C) {
3666 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3667 bool IsArrayForm = Record[I++] == 1;
3668 DelayedDeleteExprs.push_back(IsArrayForm);
3673 case IMPORTED_MODULES:
3674 if (!F.isModule()) {
3675 // If we aren't loading a module (which has its own exports), make
3676 // all of the imported modules visible.
3677 // FIXME: Deal with macros-only imports.
3678 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3679 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3680 SourceLocation Loc = ReadSourceLocation(F, Record, I);
3682 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
3683 if (DeserializationListener)
3684 DeserializationListener->ModuleImportRead(GlobalID, Loc);
3690 case MACRO_OFFSET: {
3691 if (F.LocalNumMacros != 0)
3692 return llvm::createStringError(
3693 std::errc::illegal_byte_sequence,
3694 "duplicate MACRO_OFFSET record in AST file");
3695 F.MacroOffsets = (const uint32_t *)Blob.data();
3696 F.LocalNumMacros = Record[0];
3697 unsigned LocalBaseMacroID = Record[1];
3698 F.MacroOffsetsBase = Record[2] + F.ASTBlockStartOffset;
3699 F.BaseMacroID = getTotalNumMacros();
3701 if (F.LocalNumMacros > 0) {
3702 // Introduce the global -> local mapping for macros within this module.
3703 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3705 // Introduce the local -> global mapping for macros within this module.
3706 F.MacroRemap.insertOrReplace(
3707 std::make_pair(LocalBaseMacroID,
3708 F.BaseMacroID - LocalBaseMacroID));
3710 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
3715 case PP_INCLUDED_FILES:
3716 readIncludedFiles(F, Blob, PP);
3719 case LATE_PARSED_TEMPLATE:
3720 LateParsedTemplates.emplace_back(
3721 std::piecewise_construct, std::forward_as_tuple(&F),
3722 std::forward_as_tuple(Record.begin(), Record.end()));
3725 case OPTIMIZE_PRAGMA_OPTIONS:
3726 if (Record.size() != 1)
3727 return llvm::createStringError(std::errc::illegal_byte_sequence,
3728 "invalid pragma optimize record");
3729 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3732 case MSSTRUCT_PRAGMA_OPTIONS:
3733 if (Record.size() != 1)
3734 return llvm::createStringError(std::errc::illegal_byte_sequence,
3735 "invalid pragma ms_struct record");
3736 PragmaMSStructState = Record[0];
3739 case POINTERS_TO_MEMBERS_PRAGMA_OPTIONS:
3740 if (Record.size() != 2)
3741 return llvm::createStringError(
3742 std::errc::illegal_byte_sequence,
3743 "invalid pragma pointers to members record");
3744 PragmaMSPointersToMembersState = Record[0];
3745 PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]);
3748 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3749 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3750 UnusedLocalTypedefNameCandidates.push_back(
3751 getGlobalDeclID(F, Record[I]));
3754 case CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH:
3755 if (Record.size() != 1)
3756 return llvm::createStringError(std::errc::illegal_byte_sequence,
3757 "invalid cuda pragma options record");
3758 ForceCUDAHostDeviceDepth = Record[0];
3761 case ALIGN_PACK_PRAGMA_OPTIONS: {
3762 if (Record.size() < 3)
3763 return llvm::createStringError(std::errc::illegal_byte_sequence,
3764 "invalid pragma pack record");
3765 PragmaAlignPackCurrentValue = ReadAlignPackInfo(Record[0]);
3766 PragmaAlignPackCurrentLocation = ReadSourceLocation(F, Record[1]);
3767 unsigned NumStackEntries = Record[2];
3769 // Reset the stack when importing a new module.
3770 PragmaAlignPackStack.clear();
3771 for (unsigned I = 0; I < NumStackEntries; ++I) {
3772 PragmaAlignPackStackEntry Entry;
3773 Entry.Value = ReadAlignPackInfo(Record[Idx++]);
3774 Entry.Location = ReadSourceLocation(F, Record[Idx++]);
3775 Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]);
3776 PragmaAlignPackStrings.push_back(ReadString(Record, Idx));
3777 Entry.SlotLabel = PragmaAlignPackStrings.back();
3778 PragmaAlignPackStack.push_back(Entry);
3783 case FLOAT_CONTROL_PRAGMA_OPTIONS: {
3784 if (Record.size() < 3)
3785 return llvm::createStringError(std::errc::illegal_byte_sequence,
3786 "invalid pragma float control record");
3787 FpPragmaCurrentValue = FPOptionsOverride::getFromOpaqueInt(Record[0]);
3788 FpPragmaCurrentLocation = ReadSourceLocation(F, Record[1]);
3789 unsigned NumStackEntries = Record[2];
3791 // Reset the stack when importing a new module.
3792 FpPragmaStack.clear();
3793 for (unsigned I = 0; I < NumStackEntries; ++I) {
3794 FpPragmaStackEntry Entry;
3795 Entry.Value = FPOptionsOverride::getFromOpaqueInt(Record[Idx++]);
3796 Entry.Location = ReadSourceLocation(F, Record[Idx++]);
3797 Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]);
3798 FpPragmaStrings.push_back(ReadString(Record, Idx));
3799 Entry.SlotLabel = FpPragmaStrings.back();
3800 FpPragmaStack.push_back(Entry);
3805 case DECLS_TO_CHECK_FOR_DEFERRED_DIAGS:
3806 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3807 DeclsToCheckForDeferredDiags.insert(getGlobalDeclID(F, Record[I]));
3813 void ASTReader::ReadModuleOffsetMap(ModuleFile &F) const {
3814 assert(!F.ModuleOffsetMap.empty() && "no module offset map to read");
3816 // Additional remapping information.
3817 const unsigned char *Data = (const unsigned char*)F.ModuleOffsetMap.data();
3818 const unsigned char *DataEnd = Data + F.ModuleOffsetMap.size();
3819 F.ModuleOffsetMap = StringRef();
3821 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
3822 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
3823 F.SLocRemap.insert(std::make_pair(0U, 0));
3824 F.SLocRemap.insert(std::make_pair(2U, 1));
3827 // Continuous range maps we may be updating in our module.
3828 using SLocRemapBuilder =
3829 ContinuousRangeMap<SourceLocation::UIntTy, SourceLocation::IntTy,
3831 using RemapBuilder = ContinuousRangeMap<uint32_t, int, 2>::Builder;
3832 SLocRemapBuilder SLocRemap(F.SLocRemap);
3833 RemapBuilder IdentifierRemap(F.IdentifierRemap);
3834 RemapBuilder MacroRemap(F.MacroRemap);
3835 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
3836 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
3837 RemapBuilder SelectorRemap(F.SelectorRemap);
3838 RemapBuilder DeclRemap(F.DeclRemap);
3839 RemapBuilder TypeRemap(F.TypeRemap);
3841 while (Data < DataEnd) {
3842 // FIXME: Looking up dependency modules by filename is horrible. Let's
3843 // start fixing this with prebuilt, explicit and implicit modules and see
3845 using namespace llvm::support;
3846 ModuleKind Kind = static_cast<ModuleKind>(
3847 endian::readNext<uint8_t, little, unaligned>(Data));
3848 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
3849 StringRef Name = StringRef((const char*)Data, Len);
3851 ModuleFile *OM = (Kind == MK_PrebuiltModule || Kind == MK_ExplicitModule ||
3852 Kind == MK_ImplicitModule
3853 ? ModuleMgr.lookupByModuleName(Name)
3854 : ModuleMgr.lookupByFileName(Name));
3857 "SourceLocation remap refers to unknown module, cannot find ";
3858 Msg.append(std::string(Name));
3863 SourceLocation::UIntTy SLocOffset =
3864 endian::readNext<uint32_t, little, unaligned>(Data);
3865 uint32_t IdentifierIDOffset =
3866 endian::readNext<uint32_t, little, unaligned>(Data);
3867 uint32_t MacroIDOffset =
3868 endian::readNext<uint32_t, little, unaligned>(Data);
3869 uint32_t PreprocessedEntityIDOffset =
3870 endian::readNext<uint32_t, little, unaligned>(Data);
3871 uint32_t SubmoduleIDOffset =
3872 endian::readNext<uint32_t, little, unaligned>(Data);
3873 uint32_t SelectorIDOffset =
3874 endian::readNext<uint32_t, little, unaligned>(Data);
3875 uint32_t DeclIDOffset =
3876 endian::readNext<uint32_t, little, unaligned>(Data);
3877 uint32_t TypeIndexOffset =
3878 endian::readNext<uint32_t, little, unaligned>(Data);
3880 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
3881 RemapBuilder &Remap) {
3882 constexpr uint32_t None = std::numeric_limits<uint32_t>::max();
3884 Remap.insert(std::make_pair(Offset,
3885 static_cast<int>(BaseOffset - Offset)));
3888 constexpr SourceLocation::UIntTy SLocNone =
3889 std::numeric_limits<SourceLocation::UIntTy>::max();
3890 if (SLocOffset != SLocNone)
3891 SLocRemap.insert(std::make_pair(
3892 SLocOffset, static_cast<SourceLocation::IntTy>(
3893 OM->SLocEntryBaseOffset - SLocOffset)));
3895 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
3896 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
3897 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
3898 PreprocessedEntityRemap);
3899 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
3900 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
3901 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
3902 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
3904 // Global -> local mappings.
3905 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
3909 ASTReader::ASTReadResult
3910 ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3911 const ModuleFile *ImportedBy,
3912 unsigned ClientLoadCapabilities) {
3914 F.ModuleMapPath = ReadPath(F, Record, Idx);
3916 // Try to resolve ModuleName in the current header search context and
3917 // verify that it is found in the same module map file as we saved. If the
3918 // top-level AST file is a main file, skip this check because there is no
3919 // usable header search context.
3920 assert(!F.ModuleName.empty() &&
3921 "MODULE_NAME should come before MODULE_MAP_FILE");
3922 if (F.Kind == MK_ImplicitModule && ModuleMgr.begin()->Kind != MK_MainFile) {
3923 // An implicitly-loaded module file should have its module listed in some
3924 // module map file that we've already loaded.
3926 PP.getHeaderSearchInfo().lookupModule(F.ModuleName, F.ImportLoc);
3927 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3928 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3929 // Don't emit module relocation error if we have -fno-validate-pch
3930 if (!bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation &
3931 DisableValidationForModuleKind::Module) &&
3933 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities)) {
3934 if (auto ASTFE = M ? M->getASTFile() : None) {
3935 // This module was defined by an imported (explicit) module.
3936 Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
3937 << ASTFE->getName();
3939 // This module was built with a different module map.
3940 Diag(diag::err_imported_module_not_found)
3941 << F.ModuleName << F.FileName
3942 << (ImportedBy ? ImportedBy->FileName : "") << F.ModuleMapPath
3944 // In case it was imported by a PCH, there's a chance the user is
3945 // just missing to include the search path to the directory containing
3947 if (ImportedBy && ImportedBy->Kind == MK_PCH)
3948 Diag(diag::note_imported_by_pch_module_not_found)
3949 << llvm::sys::path::parent_path(F.ModuleMapPath);
3955 assert(M && M->Name == F.ModuleName && "found module with different name");
3957 // Check the primary module map file.
3958 auto StoredModMap = FileMgr.getFile(F.ModuleMapPath);
3959 if (!StoredModMap || *StoredModMap != ModMap) {
3960 assert(ModMap && "found module is missing module map file");
3961 assert((ImportedBy || F.Kind == MK_ImplicitModule) &&
3962 "top-level import should be verified");
3963 bool NotImported = F.Kind == MK_ImplicitModule && !ImportedBy;
3964 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
3965 Diag(diag::err_imported_module_modmap_changed)
3966 << F.ModuleName << (NotImported ? F.FileName : ImportedBy->FileName)
3967 << ModMap->getName() << F.ModuleMapPath << NotImported;
3971 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3972 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3973 // FIXME: we should use input files rather than storing names.
3974 std::string Filename = ReadPath(F, Record, Idx);
3975 auto SF = FileMgr.getFile(Filename, false, false);
3977 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
3978 Error("could not find file '" + Filename +"' referenced by AST file");
3981 AdditionalStoredMaps.insert(*SF);
3984 // Check any additional module map files (e.g. module.private.modulemap)
3985 // that are not in the pcm.
3986 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
3987 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
3988 // Remove files that match
3989 // Note: SmallPtrSet::erase is really remove
3990 if (!AdditionalStoredMaps.erase(ModMap)) {
3991 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
3992 Diag(diag::err_module_different_modmap)
3993 << F.ModuleName << /*new*/0 << ModMap->getName();
3999 // Check any additional module map files that are in the pcm, but not
4000 // found in header search. Cases that match are already removed.
4001 for (const FileEntry *ModMap : AdditionalStoredMaps) {
4002 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4003 Diag(diag::err_module_different_modmap)
4004 << F.ModuleName << /*not new*/1 << ModMap->getName();
4010 Listener->ReadModuleMapFile(F.ModuleMapPath);
4014 /// Move the given method to the back of the global list of methods.
4015 static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
4016 // Find the entry for this selector in the method pool.
4017 Sema::GlobalMethodPool::iterator Known
4018 = S.MethodPool.find(Method->getSelector());
4019 if (Known == S.MethodPool.end())
4022 // Retrieve the appropriate method list.
4023 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
4024 : Known->second.second;
4026 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
4028 if (List->getMethod() == Method) {
4036 if (List->getNext())
4037 List->setMethod(List->getNext()->getMethod());
4039 List->setMethod(Method);
4043 void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
4044 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
4045 for (Decl *D : Names) {
4046 bool wasHidden = !D->isUnconditionallyVisible();
4047 D->setVisibleDespiteOwningModule();
4049 if (wasHidden && SemaObj) {
4050 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
4051 moveMethodToBackOfGlobalList(*SemaObj, Method);
4057 void ASTReader::makeModuleVisible(Module *Mod,
4058 Module::NameVisibilityKind NameVisibility,
4059 SourceLocation ImportLoc) {
4060 llvm::SmallPtrSet<Module *, 4> Visited;
4061 SmallVector<Module *, 4> Stack;
4062 Stack.push_back(Mod);
4063 while (!Stack.empty()) {
4064 Mod = Stack.pop_back_val();
4066 if (NameVisibility <= Mod->NameVisibility) {
4067 // This module already has this level of visibility (or greater), so
4068 // there is nothing more to do.
4072 if (Mod->isUnimportable()) {
4073 // Modules that aren't importable cannot be made visible.
4077 // Update the module's name visibility.
4078 Mod->NameVisibility = NameVisibility;
4080 // If we've already deserialized any names from this module,
4081 // mark them as visible.
4082 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
4083 if (Hidden != HiddenNamesMap.end()) {
4084 auto HiddenNames = std::move(*Hidden);
4085 HiddenNamesMap.erase(Hidden);
4086 makeNamesVisible(HiddenNames.second, HiddenNames.first);
4087 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
4088 "making names visible added hidden names");
4091 // Push any exported modules onto the stack to be marked as visible.
4092 SmallVector<Module *, 16> Exports;
4093 Mod->getExportedModules(Exports);
4094 for (SmallVectorImpl<Module *>::iterator
4095 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
4096 Module *Exported = *I;
4097 if (Visited.insert(Exported).second)
4098 Stack.push_back(Exported);
4103 /// We've merged the definition \p MergedDef into the existing definition
4104 /// \p Def. Ensure that \p Def is made visible whenever \p MergedDef is made
4106 void ASTReader::mergeDefinitionVisibility(NamedDecl *Def,
4107 NamedDecl *MergedDef) {
4108 if (!Def->isUnconditionallyVisible()) {
4109 // If MergedDef is visible or becomes visible, make the definition visible.
4110 if (MergedDef->isUnconditionallyVisible())
4111 Def->setVisibleDespiteOwningModule();
4113 getContext().mergeDefinitionIntoModule(
4114 Def, MergedDef->getImportedOwningModule(),
4115 /*NotifyListeners*/ false);
4116 PendingMergedDefinitionsToDeduplicate.insert(Def);
4121 bool ASTReader::loadGlobalIndex() {
4125 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
4126 !PP.getLangOpts().Modules)
4129 // Try to load the global index.
4130 TriedLoadingGlobalIndex = true;
4131 StringRef ModuleCachePath
4132 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
4133 std::pair<GlobalModuleIndex *, llvm::Error> Result =
4134 GlobalModuleIndex::readIndex(ModuleCachePath);
4135 if (llvm::Error Err = std::move(Result.second)) {
4136 assert(!Result.first);
4137 consumeError(std::move(Err)); // FIXME this drops errors on the floor.
4141 GlobalIndex.reset(Result.first);
4142 ModuleMgr.setGlobalIndex(GlobalIndex.get());
4146 bool ASTReader::isGlobalIndexUnavailable() const {
4147 return PP.getLangOpts().Modules && UseGlobalIndex &&
4148 !hasGlobalIndex() && TriedLoadingGlobalIndex;
4151 static void updateModuleTimestamp(ModuleFile &MF) {
4152 // Overwrite the timestamp file contents so that file's mtime changes.
4153 std::string TimestampFilename = MF.getTimestampFilename();
4155 llvm::raw_fd_ostream OS(TimestampFilename, EC,
4156 llvm::sys::fs::OF_TextWithCRLF);
4159 OS << "Timestamp file\n";
4161 OS.clear_error(); // Avoid triggering a fatal error.
4164 /// Given a cursor at the start of an AST file, scan ahead and drop the
4165 /// cursor into the start of the given block ID, returning false on success and
4166 /// true on failure.
4167 static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
4169 Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
4171 // FIXME this drops errors on the floor.
4172 consumeError(MaybeEntry.takeError());
4175 llvm::BitstreamEntry Entry = MaybeEntry.get();
4177 switch (Entry.Kind) {
4178 case llvm::BitstreamEntry::Error:
4179 case llvm::BitstreamEntry::EndBlock:
4182 case llvm::BitstreamEntry::Record:
4183 // Ignore top-level records.
4184 if (Expected<unsigned> Skipped = Cursor.skipRecord(Entry.ID))
4187 // FIXME this drops errors on the floor.
4188 consumeError(Skipped.takeError());
4192 case llvm::BitstreamEntry::SubBlock:
4193 if (Entry.ID == BlockID) {
4194 if (llvm::Error Err = Cursor.EnterSubBlock(BlockID)) {
4195 // FIXME this drops the error on the floor.
4196 consumeError(std::move(Err));
4203 if (llvm::Error Err = Cursor.SkipBlock()) {
4204 // FIXME this drops the error on the floor.
4205 consumeError(std::move(Err));
4212 ASTReader::ASTReadResult ASTReader::ReadAST(StringRef FileName,
4214 SourceLocation ImportLoc,
4215 unsigned ClientLoadCapabilities,
4216 SmallVectorImpl<ImportedSubmodule> *Imported) {
4217 llvm::SaveAndRestore<SourceLocation>
4218 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
4219 llvm::SaveAndRestore<Optional<ModuleKind>> SetCurModuleKindRAII(
4220 CurrentDeserializingModuleKind, Type);
4222 // Defer any pending actions until we get to the end of reading the AST file.
4223 Deserializing AnASTFile(this);
4225 // Bump the generation number.
4226 unsigned PreviousGeneration = 0;
4228 PreviousGeneration = incrementGeneration(*ContextObj);
4230 unsigned NumModules = ModuleMgr.size();
4231 SmallVector<ImportedModule, 4> Loaded;
4232 if (ASTReadResult ReadResult =
4233 ReadASTCore(FileName, Type, ImportLoc,
4234 /*ImportedBy=*/nullptr, Loaded, 0, 0, ASTFileSignature(),
4235 ClientLoadCapabilities)) {
4236 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules,
4237 PP.getLangOpts().Modules
4238 ? &PP.getHeaderSearchInfo().getModuleMap()
4241 // If we find that any modules are unusable, the global index is going
4242 // to be out-of-date. Just remove it.
4243 GlobalIndex.reset();
4244 ModuleMgr.setGlobalIndex(nullptr);
4248 // Here comes stuff that we only do once the entire chain is loaded. Do *not*
4249 // remove modules from this point. Various fields are updated during reading
4250 // the AST block and removing the modules would result in dangling pointers.
4251 // They are generally only incidentally dereferenced, ie. a binary search
4252 // runs over `GlobalSLocEntryMap`, which could cause an invalid module to
4253 // be dereferenced but it wouldn't actually be used.
4255 // Load the AST blocks of all of the modules that we loaded. We can still
4256 // hit errors parsing the ASTs at this point.
4257 for (ImportedModule &M : Loaded) {
4258 ModuleFile &F = *M.Mod;
4260 // Read the AST block.
4261 if (llvm::Error Err = ReadASTBlock(F, ClientLoadCapabilities)) {
4262 Error(std::move(Err));
4266 // The AST block should always have a definition for the main module.
4267 if (F.isModule() && !F.DidReadTopLevelSubmodule) {
4268 Error(diag::err_module_file_missing_top_level_submodule, F.FileName);
4272 // Read the extension blocks.
4273 while (!SkipCursorToBlock(F.Stream, EXTENSION_BLOCK_ID)) {
4274 if (llvm::Error Err = ReadExtensionBlock(F)) {
4275 Error(std::move(Err));
4280 // Once read, set the ModuleFile bit base offset and update the size in
4281 // bits of all files we've seen.
4282 F.GlobalBitOffset = TotalModulesSizeInBits;
4283 TotalModulesSizeInBits += F.SizeInBits;
4284 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
4287 // Preload source locations and interesting indentifiers.
4288 for (ImportedModule &M : Loaded) {
4289 ModuleFile &F = *M.Mod;
4291 // Preload SLocEntries.
4292 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
4293 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
4294 // Load it through the SourceManager and don't call ReadSLocEntry()
4295 // directly because the entry may have already been loaded in which case
4296 // calling ReadSLocEntry() directly would trigger an assertion in
4298 SourceMgr.getLoadedSLocEntryByID(Index);
4301 // Map the original source file ID into the ID space of the current
4303 if (F.OriginalSourceFileID.isValid()) {
4304 F.OriginalSourceFileID = FileID::get(
4305 F.SLocEntryBaseID + F.OriginalSourceFileID.getOpaqueValue() - 1);
4308 // Preload all the pending interesting identifiers by marking them out of
4310 for (auto Offset : F.PreloadIdentifierOffsets) {
4311 const unsigned char *Data = F.IdentifierTableData + Offset;
4313 ASTIdentifierLookupTrait Trait(*this, F);
4314 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
4315 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
4316 auto &II = PP.getIdentifierTable().getOwn(Key);
4317 II.setOutOfDate(true);
4319 // Mark this identifier as being from an AST file so that we can track
4320 // whether we need to serialize it.
4321 markIdentifierFromAST(*this, II);
4323 // Associate the ID with the identifier so that the writer can reuse it.
4324 auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
4325 SetIdentifierInfo(ID, &II);
4329 // Setup the import locations and notify the module manager that we've
4330 // committed to these module files.
4331 for (ImportedModule &M : Loaded) {
4332 ModuleFile &F = *M.Mod;
4334 ModuleMgr.moduleFileAccepted(&F);
4336 // Set the import location.
4337 F.DirectImportLoc = ImportLoc;
4338 // FIXME: We assume that locations from PCH / preamble do not need
4341 F.ImportLoc = M.ImportLoc;
4343 F.ImportLoc = TranslateSourceLocation(*M.ImportedBy, M.ImportLoc);
4346 if (!PP.getLangOpts().CPlusPlus ||
4347 (Type != MK_ImplicitModule && Type != MK_ExplicitModule &&
4348 Type != MK_PrebuiltModule)) {
4349 // Mark all of the identifiers in the identifier table as being out of date,
4350 // so that various accessors know to check the loaded modules when the
4351 // identifier is used.
4353 // For C++ modules, we don't need information on many identifiers (just
4354 // those that provide macros or are poisoned), so we mark all of
4355 // the interesting ones via PreloadIdentifierOffsets.
4356 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
4357 IdEnd = PP.getIdentifierTable().end();
4359 Id->second->setOutOfDate(true);
4361 // Mark selectors as out of date.
4362 for (auto Sel : SelectorGeneration)
4363 SelectorOutOfDate[Sel.first] = true;
4365 // Resolve any unresolved module exports.
4366 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
4367 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
4368 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
4369 Module *ResolvedMod = getSubmodule(GlobalID);
4371 switch (Unresolved.Kind) {
4372 case UnresolvedModuleRef::Conflict:
4374 Module::Conflict Conflict;
4375 Conflict.Other = ResolvedMod;
4376 Conflict.Message = Unresolved.String.str();
4377 Unresolved.Mod->Conflicts.push_back(Conflict);
4381 case UnresolvedModuleRef::Import:
4383 Unresolved.Mod->Imports.insert(ResolvedMod);
4386 case UnresolvedModuleRef::Export:
4387 if (ResolvedMod || Unresolved.IsWildcard)
4388 Unresolved.Mod->Exports.push_back(
4389 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
4393 UnresolvedModuleRefs.clear();
4396 Imported->append(ImportedModules.begin(),
4397 ImportedModules.end());
4399 // FIXME: How do we load the 'use'd modules? They may not be submodules.
4400 // Might be unnecessary as use declarations are only used to build the
4404 InitializeContext();
4409 if (DeserializationListener)
4410 DeserializationListener->ReaderInitialized(this);
4412 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
4413 if (PrimaryModule.OriginalSourceFileID.isValid()) {
4414 // If this AST file is a precompiled preamble, then set the
4415 // preamble file ID of the source manager to the file source file
4416 // from which the preamble was built.
4417 if (Type == MK_Preamble) {
4418 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
4419 } else if (Type == MK_MainFile) {
4420 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
4424 // For any Objective-C class definitions we have already loaded, make sure
4425 // that we load any additional categories.
4427 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
4428 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
4429 ObjCClassesLoaded[I],
4430 PreviousGeneration);
4434 if (PP.getHeaderSearchInfo()
4435 .getHeaderSearchOpts()
4436 .ModulesValidateOncePerBuildSession) {
4437 // Now we are certain that the module and all modules it depends on are
4438 // up to date. Create or update timestamp files for modules that are
4439 // located in the module cache (not for PCH files that could be anywhere
4440 // in the filesystem).
4441 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
4442 ImportedModule &M = Loaded[I];
4443 if (M.Mod->Kind == MK_ImplicitModule) {
4444 updateModuleTimestamp(*M.Mod);
4452 static ASTFileSignature readASTFileSignature(StringRef PCH);
4454 /// Whether \p Stream doesn't start with the AST/PCH file magic number 'CPCH'.
4455 static llvm::Error doesntStartWithASTFileMagic(BitstreamCursor &Stream) {
4456 // FIXME checking magic headers is done in other places such as
4457 // SerializedDiagnosticReader and GlobalModuleIndex, but error handling isn't
4458 // always done the same. Unify it all with a helper.
4459 if (!Stream.canSkipToPos(4))
4460 return llvm::createStringError(std::errc::illegal_byte_sequence,
4461 "file too small to contain AST file magic");
4462 for (unsigned C : {'C', 'P', 'C', 'H'})
4463 if (Expected<llvm::SimpleBitstreamCursor::word_t> Res = Stream.Read(8)) {
4465 return llvm::createStringError(
4466 std::errc::illegal_byte_sequence,
4467 "file doesn't start with AST file magic");
4469 return Res.takeError();
4470 return llvm::Error::success();
4473 static unsigned moduleKindForDiagnostic(ModuleKind Kind) {
4477 case MK_ImplicitModule:
4478 case MK_ExplicitModule:
4479 case MK_PrebuiltModule:
4483 return 2; // main source file
4485 llvm_unreachable("unknown module kind");
4488 ASTReader::ASTReadResult
4489 ASTReader::ReadASTCore(StringRef FileName,
4491 SourceLocation ImportLoc,
4492 ModuleFile *ImportedBy,
4493 SmallVectorImpl<ImportedModule> &Loaded,
4494 off_t ExpectedSize, time_t ExpectedModTime,
4495 ASTFileSignature ExpectedSignature,
4496 unsigned ClientLoadCapabilities) {
4498 std::string ErrorStr;
4499 ModuleManager::AddModuleResult AddResult
4500 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
4501 getGeneration(), ExpectedSize, ExpectedModTime,
4502 ExpectedSignature, readASTFileSignature,
4505 switch (AddResult) {
4506 case ModuleManager::AlreadyLoaded:
4507 Diag(diag::remark_module_import)
4508 << M->ModuleName << M->FileName << (ImportedBy ? true : false)
4509 << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());
4512 case ModuleManager::NewlyLoaded:
4513 // Load module file below.
4516 case ModuleManager::Missing:
4517 // The module file was missing; if the client can handle that, return
4519 if (ClientLoadCapabilities & ARR_Missing)
4522 // Otherwise, return an error.
4523 Diag(diag::err_ast_file_not_found)
4524 << moduleKindForDiagnostic(Type) << FileName << !ErrorStr.empty()
4528 case ModuleManager::OutOfDate:
4529 // We couldn't load the module file because it is out-of-date. If the
4530 // client can handle out-of-date, return it.
4531 if (ClientLoadCapabilities & ARR_OutOfDate)
4534 // Otherwise, return an error.
4535 Diag(diag::err_ast_file_out_of_date)
4536 << moduleKindForDiagnostic(Type) << FileName << !ErrorStr.empty()
4541 assert(M && "Missing module file");
4543 bool ShouldFinalizePCM = false;
4544 auto FinalizeOrDropPCM = llvm::make_scope_exit([&]() {
4545 auto &MC = getModuleManager().getModuleCache();
4546 if (ShouldFinalizePCM)
4547 MC.finalizePCM(FileName);
4549 MC.tryToDropPCM(FileName);
4552 BitstreamCursor &Stream = F.Stream;
4553 Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(*F.Buffer));
4554 F.SizeInBits = F.Buffer->getBufferSize() * 8;
4556 // Sniff for the signature.
4557 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
4558 Diag(diag::err_ast_file_invalid)
4559 << moduleKindForDiagnostic(Type) << FileName << std::move(Err);
4563 // This is used for compatibility with older PCH formats.
4564 bool HaveReadControlBlock = false;
4566 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4568 Error(MaybeEntry.takeError());
4571 llvm::BitstreamEntry Entry = MaybeEntry.get();
4573 switch (Entry.Kind) {
4574 case llvm::BitstreamEntry::Error:
4575 case llvm::BitstreamEntry::Record:
4576 case llvm::BitstreamEntry::EndBlock:
4577 Error("invalid record at top-level of AST file");
4580 case llvm::BitstreamEntry::SubBlock:
4585 case CONTROL_BLOCK_ID:
4586 HaveReadControlBlock = true;
4587 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
4589 // Check that we didn't try to load a non-module AST file as a module.
4591 // FIXME: Should we also perform the converse check? Loading a module as
4592 // a PCH file sort of works, but it's a bit wonky.
4593 if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule ||
4594 Type == MK_PrebuiltModule) &&
4595 F.ModuleName.empty()) {
4596 auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
4597 if (Result != OutOfDate ||
4598 (ClientLoadCapabilities & ARR_OutOfDate) == 0)
4599 Diag(diag::err_module_file_not_module) << FileName;
4604 case Failure: return Failure;
4605 case Missing: return Missing;
4606 case OutOfDate: return OutOfDate;
4607 case VersionMismatch: return VersionMismatch;
4608 case ConfigurationMismatch: return ConfigurationMismatch;
4609 case HadErrors: return HadErrors;
4614 if (!HaveReadControlBlock) {
4615 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
4616 Diag(diag::err_pch_version_too_old);
4617 return VersionMismatch;
4620 // Record that we've loaded this module.
4621 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
4622 ShouldFinalizePCM = true;
4625 case UNHASHED_CONTROL_BLOCK_ID:
4626 // This block is handled using look-ahead during ReadControlBlock. We
4627 // shouldn't get here!
4628 Error("malformed block record in AST file");
4632 if (llvm::Error Err = Stream.SkipBlock()) {
4633 Error(std::move(Err));
4640 llvm_unreachable("unexpected break; expected return");
4643 ASTReader::ASTReadResult
4644 ASTReader::readUnhashedControlBlock(ModuleFile &F, bool WasImportedBy,
4645 unsigned ClientLoadCapabilities) {
4646 const HeaderSearchOptions &HSOpts =
4647 PP.getHeaderSearchInfo().getHeaderSearchOpts();
4648 bool AllowCompatibleConfigurationMismatch =
4649 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
4650 bool DisableValidation = shouldDisableValidationForFile(F);
4652 ASTReadResult Result = readUnhashedControlBlockImpl(
4653 &F, F.Data, ClientLoadCapabilities, AllowCompatibleConfigurationMismatch,
4655 WasImportedBy ? false : HSOpts.ModulesValidateDiagnosticOptions);
4657 // If F was directly imported by another module, it's implicitly validated by
4658 // the importing module.
4659 if (DisableValidation || WasImportedBy ||
4660 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
4663 if (Result == Failure) {
4664 Error("malformed block record in AST file");
4668 if (Result == OutOfDate && F.Kind == MK_ImplicitModule) {
4669 // If this module has already been finalized in the ModuleCache, we're stuck
4670 // with it; we can only load a single version of each module.
4672 // This can happen when a module is imported in two contexts: in one, as a
4673 // user module; in another, as a system module (due to an import from
4674 // another module marked with the [system] flag). It usually indicates a
4675 // bug in the module map: this module should also be marked with [system].
4677 // If -Wno-system-headers (the default), and the first import is as a
4678 // system module, then validation will fail during the as-user import,
4679 // since -Werror flags won't have been validated. However, it's reasonable
4680 // to treat this consistently as a system module.
4682 // If -Wsystem-headers, the PCM on disk was built with
4683 // -Wno-system-headers, and the first import is as a user module, then
4684 // validation will fail during the as-system import since the PCM on disk
4685 // doesn't guarantee that -Werror was respected. However, the -Werror
4686 // flags were checked during the initial as-user import.
4687 if (getModuleManager().getModuleCache().isPCMFinal(F.FileName)) {
4688 Diag(diag::warn_module_system_bit_conflict) << F.FileName;
4696 ASTReader::ASTReadResult ASTReader::readUnhashedControlBlockImpl(
4697 ModuleFile *F, llvm::StringRef StreamData, unsigned ClientLoadCapabilities,
4698 bool AllowCompatibleConfigurationMismatch, ASTReaderListener *Listener,
4699 bool ValidateDiagnosticOptions) {
4700 // Initialize a stream.
4701 BitstreamCursor Stream(StreamData);
4703 // Sniff for the signature.
4704 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
4705 // FIXME this drops the error on the floor.
4706 consumeError(std::move(Err));
4710 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4711 if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
4714 // Read all of the records in the options block.
4716 ASTReadResult Result = Success;
4718 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4720 // FIXME this drops the error on the floor.
4721 consumeError(MaybeEntry.takeError());
4724 llvm::BitstreamEntry Entry = MaybeEntry.get();
4726 switch (Entry.Kind) {
4727 case llvm::BitstreamEntry::Error:
4728 case llvm::BitstreamEntry::SubBlock:
4731 case llvm::BitstreamEntry::EndBlock:
4734 case llvm::BitstreamEntry::Record:
4735 // The interesting case.
4739 // Read and process a record.
4742 Expected<unsigned> MaybeRecordType =
4743 Stream.readRecord(Entry.ID, Record, &Blob);
4744 if (!MaybeRecordType) {
4745 // FIXME this drops the error.
4748 switch ((UnhashedControlBlockRecordTypes)MaybeRecordType.get()) {
4751 F->Signature = ASTFileSignature::create(Record.begin(), Record.end());
4753 case AST_BLOCK_HASH:
4756 ASTFileSignature::create(Record.begin(), Record.end());
4758 case DIAGNOSTIC_OPTIONS: {
4759 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
4760 if (Listener && ValidateDiagnosticOptions &&
4761 !AllowCompatibleConfigurationMismatch &&
4762 ParseDiagnosticOptions(Record, Complain, *Listener))
4763 Result = OutOfDate; // Don't return early. Read the signature.
4766 case DIAG_PRAGMA_MAPPINGS:
4769 if (F->PragmaDiagMappings.empty())
4770 F->PragmaDiagMappings.swap(Record);
4772 F->PragmaDiagMappings.insert(F->PragmaDiagMappings.end(),
4773 Record.begin(), Record.end());
4775 case HEADER_SEARCH_ENTRY_USAGE:
4778 unsigned Count = Record[0];
4779 const char *Byte = Blob.data();
4780 F->SearchPathUsage = llvm::BitVector(Count, false);
4781 for (unsigned I = 0; I < Count; ++Byte)
4782 for (unsigned Bit = 0; Bit < 8 && I < Count; ++Bit, ++I)
4783 if (*Byte & (1 << Bit))
4784 F->SearchPathUsage[I] = true;
4790 /// Parse a record and blob containing module file extension metadata.
4791 static bool parseModuleFileExtensionMetadata(
4792 const SmallVectorImpl<uint64_t> &Record,
4794 ModuleFileExtensionMetadata &Metadata) {
4795 if (Record.size() < 4) return true;
4797 Metadata.MajorVersion = Record[0];
4798 Metadata.MinorVersion = Record[1];
4800 unsigned BlockNameLen = Record[2];
4801 unsigned UserInfoLen = Record[3];
4803 if (BlockNameLen + UserInfoLen > Blob.size()) return true;
4805 Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
4806 Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,
4807 Blob.data() + BlockNameLen + UserInfoLen);
4811 llvm::Error ASTReader::ReadExtensionBlock(ModuleFile &F) {
4812 BitstreamCursor &Stream = F.Stream;
4816 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4818 return MaybeEntry.takeError();
4819 llvm::BitstreamEntry Entry = MaybeEntry.get();
4821 switch (Entry.Kind) {
4822 case llvm::BitstreamEntry::SubBlock:
4823 if (llvm::Error Err = Stream.SkipBlock())
4826 case llvm::BitstreamEntry::EndBlock:
4827 return llvm::Error::success();
4828 case llvm::BitstreamEntry::Error:
4829 return llvm::createStringError(std::errc::illegal_byte_sequence,
4830 "malformed block record in AST file");
4831 case llvm::BitstreamEntry::Record:
4837 Expected<unsigned> MaybeRecCode =
4838 Stream.readRecord(Entry.ID, Record, &Blob);
4840 return MaybeRecCode.takeError();
4841 switch (MaybeRecCode.get()) {
4842 case EXTENSION_METADATA: {
4843 ModuleFileExtensionMetadata Metadata;
4844 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
4845 return llvm::createStringError(
4846 std::errc::illegal_byte_sequence,
4847 "malformed EXTENSION_METADATA in AST file");
4849 // Find a module file extension with this block name.
4850 auto Known = ModuleFileExtensions.find(Metadata.BlockName);
4851 if (Known == ModuleFileExtensions.end()) break;
4854 if (auto Reader = Known->second->createExtensionReader(Metadata, *this,
4856 F.ExtensionReaders.push_back(std::move(Reader));
4864 return llvm::Error::success();
4867 void ASTReader::InitializeContext() {
4868 assert(ContextObj && "no context to initialize");
4869 ASTContext &Context = *ContextObj;
4871 // If there's a listener, notify them that we "read" the translation unit.
4872 if (DeserializationListener)
4873 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
4874 Context.getTranslationUnitDecl());
4876 // FIXME: Find a better way to deal with collisions between these
4877 // built-in types. Right now, we just ignore the problem.
4879 // Load the special types.
4880 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
4881 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
4882 if (!Context.CFConstantStringTypeDecl)
4883 Context.setCFConstantStringType(GetType(String));
4886 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
4887 QualType FileType = GetType(File);
4888 if (FileType.isNull()) {
4889 Error("FILE type is NULL");
4893 if (!Context.FILEDecl) {
4894 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
4895 Context.setFILEDecl(Typedef->getDecl());
4897 const TagType *Tag = FileType->getAs<TagType>();
4899 Error("Invalid FILE type in AST file");
4902 Context.setFILEDecl(Tag->getDecl());
4907 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
4908 QualType Jmp_bufType = GetType(Jmp_buf);
4909 if (Jmp_bufType.isNull()) {
4910 Error("jmp_buf type is NULL");
4914 if (!Context.jmp_bufDecl) {
4915 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
4916 Context.setjmp_bufDecl(Typedef->getDecl());
4918 const TagType *Tag = Jmp_bufType->getAs<TagType>();
4920 Error("Invalid jmp_buf type in AST file");
4923 Context.setjmp_bufDecl(Tag->getDecl());
4928 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
4929 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
4930 if (Sigjmp_bufType.isNull()) {
4931 Error("sigjmp_buf type is NULL");
4935 if (!Context.sigjmp_bufDecl) {
4936 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
4937 Context.setsigjmp_bufDecl(Typedef->getDecl());
4939 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
4940 assert(Tag && "Invalid sigjmp_buf type in AST file");
4941 Context.setsigjmp_bufDecl(Tag->getDecl());
4946 if (unsigned ObjCIdRedef
4947 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
4948 if (Context.ObjCIdRedefinitionType.isNull())
4949 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
4952 if (unsigned ObjCClassRedef
4953 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
4954 if (Context.ObjCClassRedefinitionType.isNull())
4955 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
4958 if (unsigned ObjCSelRedef
4959 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
4960 if (Context.ObjCSelRedefinitionType.isNull())
4961 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
4964 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
4965 QualType Ucontext_tType = GetType(Ucontext_t);
4966 if (Ucontext_tType.isNull()) {
4967 Error("ucontext_t type is NULL");
4971 if (!Context.ucontext_tDecl) {
4972 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
4973 Context.setucontext_tDecl(Typedef->getDecl());
4975 const TagType *Tag = Ucontext_tType->getAs<TagType>();
4976 assert(Tag && "Invalid ucontext_t type in AST file");
4977 Context.setucontext_tDecl(Tag->getDecl());
4983 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
4985 // If there were any CUDA special declarations, deserialize them.
4986 if (!CUDASpecialDeclRefs.empty()) {
4987 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
4988 Context.setcudaConfigureCallDecl(
4989 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
4992 // Re-export any modules that were imported by a non-module AST file.
4993 // FIXME: This does not make macro-only imports visible again.
4994 for (auto &Import : ImportedModules) {
4995 if (Module *Imported = getSubmodule(Import.ID)) {
4996 makeModuleVisible(Imported, Module::AllVisible,
4997 /*ImportLoc=*/Import.ImportLoc);
4998 if (Import.ImportLoc.isValid())
4999 PP.makeModuleVisible(Imported, Import.ImportLoc);
5000 // This updates visibility for Preprocessor only. For Sema, which can be
5001 // nullptr here, we do the same later, in UpdateSema().
5006 void ASTReader::finalizeForWriting() {
5007 // Nothing to do for now.
5010 /// Reads and return the signature record from \p PCH's control block, or
5012 static ASTFileSignature readASTFileSignature(StringRef PCH) {
5013 BitstreamCursor Stream(PCH);
5014 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5015 // FIXME this drops the error on the floor.
5016 consumeError(std::move(Err));
5017 return ASTFileSignature();
5020 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
5021 if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
5022 return ASTFileSignature();
5024 // Scan for SIGNATURE inside the diagnostic options block.
5025 ASTReader::RecordData Record;
5027 Expected<llvm::BitstreamEntry> MaybeEntry =
5028 Stream.advanceSkippingSubblocks();
5030 // FIXME this drops the error on the floor.
5031 consumeError(MaybeEntry.takeError());
5032 return ASTFileSignature();
5034 llvm::BitstreamEntry Entry = MaybeEntry.get();
5036 if (Entry.Kind != llvm::BitstreamEntry::Record)
5037 return ASTFileSignature();
5041 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);
5043 // FIXME this drops the error on the floor.
5044 consumeError(MaybeRecord.takeError());
5045 return ASTFileSignature();
5047 if (SIGNATURE == MaybeRecord.get())
5048 return ASTFileSignature::create(Record.begin(),
5049 Record.begin() + ASTFileSignature::size);
5053 /// Retrieve the name of the original source file name
5054 /// directly from the AST file, without actually loading the AST
5056 std::string ASTReader::getOriginalSourceFile(
5057 const std::string &ASTFileName, FileManager &FileMgr,
5058 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
5059 // Open the AST file.
5060 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
5062 Diags.Report(diag::err_fe_unable_to_read_pch_file)
5063 << ASTFileName << Buffer.getError().message();
5064 return std::string();
5067 // Initialize the stream
5068 BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer));
5070 // Sniff for the signature.
5071 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5072 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName << std::move(Err);
5073 return std::string();
5076 // Scan for the CONTROL_BLOCK_ID block.
5077 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
5078 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
5079 return std::string();
5082 // Scan for ORIGINAL_FILE inside the control block.
5085 Expected<llvm::BitstreamEntry> MaybeEntry =
5086 Stream.advanceSkippingSubblocks();
5088 // FIXME this drops errors on the floor.
5089 consumeError(MaybeEntry.takeError());
5090 return std::string();
5092 llvm::BitstreamEntry Entry = MaybeEntry.get();
5094 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
5095 return std::string();
5097 if (Entry.Kind != llvm::BitstreamEntry::Record) {
5098 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
5099 return std::string();
5104 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);
5106 // FIXME this drops the errors on the floor.
5107 consumeError(MaybeRecord.takeError());
5108 return std::string();
5110 if (ORIGINAL_FILE == MaybeRecord.get())
5117 class SimplePCHValidator : public ASTReaderListener {
5118 const LangOptions &ExistingLangOpts;
5119 const TargetOptions &ExistingTargetOpts;
5120 const PreprocessorOptions &ExistingPPOpts;
5121 std::string ExistingModuleCachePath;
5122 FileManager &FileMgr;
5125 SimplePCHValidator(const LangOptions &ExistingLangOpts,
5126 const TargetOptions &ExistingTargetOpts,
5127 const PreprocessorOptions &ExistingPPOpts,
5128 StringRef ExistingModuleCachePath, FileManager &FileMgr)
5129 : ExistingLangOpts(ExistingLangOpts),
5130 ExistingTargetOpts(ExistingTargetOpts),
5131 ExistingPPOpts(ExistingPPOpts),
5132 ExistingModuleCachePath(ExistingModuleCachePath), FileMgr(FileMgr) {}
5134 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
5135 bool AllowCompatibleDifferences) override {
5136 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
5137 AllowCompatibleDifferences);
5140 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
5141 bool AllowCompatibleDifferences) override {
5142 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
5143 AllowCompatibleDifferences);
5146 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
5147 StringRef SpecificModuleCachePath,
5148 bool Complain) override {
5149 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
5150 ExistingModuleCachePath, nullptr,
5151 ExistingLangOpts, ExistingPPOpts);
5154 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
5156 std::string &SuggestedPredefines) override {
5157 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
5158 SuggestedPredefines, ExistingLangOpts);
5164 bool ASTReader::readASTFileControlBlock(
5165 StringRef Filename, FileManager &FileMgr,
5166 const PCHContainerReader &PCHContainerRdr,
5167 bool FindModuleFileExtensions,
5168 ASTReaderListener &Listener, bool ValidateDiagnosticOptions) {
5169 // Open the AST file.
5170 // FIXME: This allows use of the VFS; we do not allow use of the
5171 // VFS when actually loading a module.
5172 auto Buffer = FileMgr.getBufferForFile(Filename);
5177 // Initialize the stream
5178 StringRef Bytes = PCHContainerRdr.ExtractPCH(**Buffer);
5179 BitstreamCursor Stream(Bytes);
5181 // Sniff for the signature.
5182 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5183 consumeError(std::move(Err)); // FIXME this drops errors on the floor.
5187 // Scan for the CONTROL_BLOCK_ID block.
5188 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
5191 bool NeedsInputFiles = Listener.needsInputFileVisitation();
5192 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
5193 bool NeedsImports = Listener.needsImportVisitation();
5194 BitstreamCursor InputFilesCursor;
5197 std::string ModuleDir;
5198 bool DoneWithControlBlock = false;
5199 while (!DoneWithControlBlock) {
5200 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5202 // FIXME this drops the error on the floor.
5203 consumeError(MaybeEntry.takeError());
5206 llvm::BitstreamEntry Entry = MaybeEntry.get();
5208 switch (Entry.Kind) {
5209 case llvm::BitstreamEntry::SubBlock: {
5211 case OPTIONS_BLOCK_ID: {
5212 std::string IgnoredSuggestedPredefines;
5213 if (ReadOptionsBlock(Stream, ARR_ConfigurationMismatch | ARR_OutOfDate,
5214 /*AllowCompatibleConfigurationMismatch*/ false,
5215 Listener, IgnoredSuggestedPredefines) != Success)
5220 case INPUT_FILES_BLOCK_ID:
5221 InputFilesCursor = Stream;
5222 if (llvm::Error Err = Stream.SkipBlock()) {
5223 // FIXME this drops the error on the floor.
5224 consumeError(std::move(Err));
5227 if (NeedsInputFiles &&
5228 ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID))
5233 if (llvm::Error Err = Stream.SkipBlock()) {
5234 // FIXME this drops the error on the floor.
5235 consumeError(std::move(Err));
5244 case llvm::BitstreamEntry::EndBlock:
5245 DoneWithControlBlock = true;
5248 case llvm::BitstreamEntry::Error:
5251 case llvm::BitstreamEntry::Record:
5255 if (DoneWithControlBlock) break;
5259 Expected<unsigned> MaybeRecCode =
5260 Stream.readRecord(Entry.ID, Record, &Blob);
5261 if (!MaybeRecCode) {
5262 // FIXME this drops the error.
5265 switch ((ControlRecordTypes)MaybeRecCode.get()) {
5267 if (Record[0] != VERSION_MAJOR)
5269 if (Listener.ReadFullVersionInformation(Blob))
5273 Listener.ReadModuleName(Blob);
5275 case MODULE_DIRECTORY:
5276 ModuleDir = std::string(Blob);
5278 case MODULE_MAP_FILE: {
5280 auto Path = ReadString(Record, Idx);
5281 ResolveImportedPath(Path, ModuleDir);
5282 Listener.ReadModuleMapFile(Path);
5285 case INPUT_FILE_OFFSETS: {
5286 if (!NeedsInputFiles)
5289 unsigned NumInputFiles = Record[0];
5290 unsigned NumUserFiles = Record[1];
5291 const llvm::support::unaligned_uint64_t *InputFileOffs =
5292 (const llvm::support::unaligned_uint64_t *)Blob.data();
5293 for (unsigned I = 0; I != NumInputFiles; ++I) {
5294 // Go find this input file.
5295 bool isSystemFile = I >= NumUserFiles;
5297 if (isSystemFile && !NeedsSystemInputFiles)
5298 break; // the rest are system input files
5300 BitstreamCursor &Cursor = InputFilesCursor;
5301 SavedStreamPosition SavedPosition(Cursor);
5302 if (llvm::Error Err = Cursor.JumpToBit(InputFileOffs[I])) {
5303 // FIXME this drops errors on the floor.
5304 consumeError(std::move(Err));
5307 Expected<unsigned> MaybeCode = Cursor.ReadCode();
5309 // FIXME this drops errors on the floor.
5310 consumeError(MaybeCode.takeError());
5312 unsigned Code = MaybeCode.get();
5316 bool shouldContinue = false;
5317 Expected<unsigned> MaybeRecordType =
5318 Cursor.readRecord(Code, Record, &Blob);
5319 if (!MaybeRecordType) {
5320 // FIXME this drops errors on the floor.
5321 consumeError(MaybeRecordType.takeError());
5323 switch ((InputFileRecordTypes)MaybeRecordType.get()) {
5324 case INPUT_FILE_HASH:
5327 bool Overridden = static_cast<bool>(Record[3]);
5328 std::string Filename = std::string(Blob);
5329 ResolveImportedPath(Filename, ModuleDir);
5330 shouldContinue = Listener.visitInputFile(
5331 Filename, isSystemFile, Overridden, /*IsExplicitModule*/false);
5334 if (!shouldContinue)
5344 unsigned Idx = 0, N = Record.size();
5346 // Read information about the AST file.
5349 ASTFileSignature::size; // Kind, ImportLoc, Size, ModTime, Signature
5350 std::string ModuleName = ReadString(Record, Idx);
5351 std::string Filename = ReadString(Record, Idx);
5352 ResolveImportedPath(Filename, ModuleDir);
5353 Listener.visitImport(ModuleName, Filename);
5359 // No other validation to perform.
5364 // Look for module file extension blocks, if requested.
5365 if (FindModuleFileExtensions) {
5366 BitstreamCursor SavedStream = Stream;
5367 while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {
5368 bool DoneWithExtensionBlock = false;
5369 while (!DoneWithExtensionBlock) {
5370 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5372 // FIXME this drops the error.
5375 llvm::BitstreamEntry Entry = MaybeEntry.get();
5377 switch (Entry.Kind) {
5378 case llvm::BitstreamEntry::SubBlock:
5379 if (llvm::Error Err = Stream.SkipBlock()) {
5380 // FIXME this drops the error on the floor.
5381 consumeError(std::move(Err));
5386 case llvm::BitstreamEntry::EndBlock:
5387 DoneWithExtensionBlock = true;
5390 case llvm::BitstreamEntry::Error:
5393 case llvm::BitstreamEntry::Record:
5399 Expected<unsigned> MaybeRecCode =
5400 Stream.readRecord(Entry.ID, Record, &Blob);
5401 if (!MaybeRecCode) {
5402 // FIXME this drops the error.
5405 switch (MaybeRecCode.get()) {
5406 case EXTENSION_METADATA: {
5407 ModuleFileExtensionMetadata Metadata;
5408 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
5411 Listener.readModuleFileExtension(Metadata);
5417 Stream = SavedStream;
5420 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
5421 if (readUnhashedControlBlockImpl(
5422 nullptr, Bytes, ARR_ConfigurationMismatch | ARR_OutOfDate,
5423 /*AllowCompatibleConfigurationMismatch*/ false, &Listener,
5424 ValidateDiagnosticOptions) != Success)
5430 bool ASTReader::isAcceptableASTFile(StringRef Filename, FileManager &FileMgr,
5431 const PCHContainerReader &PCHContainerRdr,
5432 const LangOptions &LangOpts,
5433 const TargetOptions &TargetOpts,
5434 const PreprocessorOptions &PPOpts,
5435 StringRef ExistingModuleCachePath) {
5436 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
5437 ExistingModuleCachePath, FileMgr);
5438 return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr,
5439 /*FindModuleFileExtensions=*/false,
5441 /*ValidateDiagnosticOptions=*/true);
5444 llvm::Error ASTReader::ReadSubmoduleBlock(ModuleFile &F,
5445 unsigned ClientLoadCapabilities) {
5446 // Enter the submodule block.
5447 if (llvm::Error Err = F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID))
5450 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
5452 Module *CurrentModule = nullptr;
5455 Expected<llvm::BitstreamEntry> MaybeEntry =
5456 F.Stream.advanceSkippingSubblocks();
5458 return MaybeEntry.takeError();
5459 llvm::BitstreamEntry Entry = MaybeEntry.get();
5461 switch (Entry.Kind) {
5462 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
5463 case llvm::BitstreamEntry::Error:
5464 return llvm::createStringError(std::errc::illegal_byte_sequence,
5465 "malformed block record in AST file");
5466 case llvm::BitstreamEntry::EndBlock:
5467 return llvm::Error::success();
5468 case llvm::BitstreamEntry::Record:
5469 // The interesting case.
5476 Expected<unsigned> MaybeKind = F.Stream.readRecord(Entry.ID, Record, &Blob);
5478 return MaybeKind.takeError();
5479 unsigned Kind = MaybeKind.get();
5481 if ((Kind == SUBMODULE_METADATA) != First)
5482 return llvm::createStringError(
5483 std::errc::illegal_byte_sequence,
5484 "submodule metadata record should be at beginning of block");
5487 // Submodule information is only valid if we have a current module.
5488 // FIXME: Should we error on these cases?
5489 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
5490 Kind != SUBMODULE_DEFINITION)
5494 default: // Default behavior: ignore.
5497 case SUBMODULE_DEFINITION: {
5498 if (Record.size() < 12)
5499 return llvm::createStringError(std::errc::illegal_byte_sequence,
5500 "malformed module definition");
5502 StringRef Name = Blob;
5504 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
5505 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
5506 Module::ModuleKind Kind = (Module::ModuleKind)Record[Idx++];
5507 bool IsFramework = Record[Idx++];
5508 bool IsExplicit = Record[Idx++];
5509 bool IsSystem = Record[Idx++];
5510 bool IsExternC = Record[Idx++];
5511 bool InferSubmodules = Record[Idx++];
5512 bool InferExplicitSubmodules = Record[Idx++];
5513 bool InferExportWildcard = Record[Idx++];
5514 bool ConfigMacrosExhaustive = Record[Idx++];
5515 bool ModuleMapIsPrivate = Record[Idx++];
5517 Module *ParentModule = nullptr;
5519 ParentModule = getSubmodule(Parent);
5521 // Retrieve this (sub)module from the module map, creating it if
5524 ModMap.findOrCreateModule(Name, ParentModule, IsFramework, IsExplicit)
5527 // FIXME: set the definition loc for CurrentModule, or call
5528 // ModMap.setInferredModuleAllowedBy()
5530 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
5531 if (GlobalIndex >= SubmodulesLoaded.size() ||
5532 SubmodulesLoaded[GlobalIndex])
5533 return llvm::createStringError(std::errc::invalid_argument,
5534 "too many submodules");
5536 if (!ParentModule) {
5537 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
5538 // Don't emit module relocation error if we have -fno-validate-pch
5539 if (!bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation &
5540 DisableValidationForModuleKind::Module) &&
5541 CurFile != F.File) {
5542 auto ConflictError =
5543 PartialDiagnostic(diag::err_module_file_conflict,
5544 ContextObj->DiagAllocator)
5545 << CurrentModule->getTopLevelModuleName() << CurFile->getName()
5546 << F.File->getName();
5547 return DiagnosticError::create(CurrentImportLoc, ConflictError);
5551 F.DidReadTopLevelSubmodule = true;
5552 CurrentModule->setASTFile(F.File);
5553 CurrentModule->PresumedModuleMapFile = F.ModuleMapPath;
5556 CurrentModule->Kind = Kind;
5557 CurrentModule->Signature = F.Signature;
5558 CurrentModule->IsFromModuleFile = true;
5559 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
5560 CurrentModule->IsExternC = IsExternC;
5561 CurrentModule->InferSubmodules = InferSubmodules;
5562 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
5563 CurrentModule->InferExportWildcard = InferExportWildcard;
5564 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
5565 CurrentModule->ModuleMapIsPrivate = ModuleMapIsPrivate;
5566 if (DeserializationListener)
5567 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
5569 SubmodulesLoaded[GlobalIndex] = CurrentModule;
5571 // Clear out data that will be replaced by what is in the module file.
5572 CurrentModule->LinkLibraries.clear();
5573 CurrentModule->ConfigMacros.clear();
5574 CurrentModule->UnresolvedConflicts.clear();
5575 CurrentModule->Conflicts.clear();
5577 // The module is available unless it's missing a requirement; relevant
5578 // requirements will be (re-)added by SUBMODULE_REQUIRES records.
5579 // Missing headers that were present when the module was built do not
5580 // make it unavailable -- if we got this far, this must be an explicitly
5581 // imported module file.
5582 CurrentModule->Requirements.clear();
5583 CurrentModule->MissingHeaders.clear();
5584 CurrentModule->IsUnimportable =
5585 ParentModule && ParentModule->IsUnimportable;
5586 CurrentModule->IsAvailable = !CurrentModule->IsUnimportable;
5590 case SUBMODULE_UMBRELLA_HEADER: {
5591 // FIXME: This doesn't work for framework modules as `Filename` is the
5592 // name as written in the module file and does not include
5593 // `Headers/`, so this path will never exist.
5594 std::string Filename = std::string(Blob);
5595 ResolveImportedPath(F, Filename);
5596 if (auto Umbrella = PP.getFileManager().getFile(Filename)) {
5597 if (!CurrentModule->getUmbrellaHeader()) {
5598 // FIXME: NameAsWritten
5599 ModMap.setUmbrellaHeader(CurrentModule, *Umbrella, Blob, "");
5601 // Note that it's too late at this point to return out of date if the
5602 // name from the PCM doesn't match up with the one in the module map,
5603 // but also quite unlikely since we will have already checked the
5604 // modification time and size of the module map file itself.
5609 case SUBMODULE_HEADER:
5610 case SUBMODULE_EXCLUDED_HEADER:
5611 case SUBMODULE_PRIVATE_HEADER:
5612 // We lazily associate headers with their modules via the HeaderInfo table.
5613 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
5614 // of complete filenames or remove it entirely.
5617 case SUBMODULE_TEXTUAL_HEADER:
5618 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
5619 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
5623 case SUBMODULE_TOPHEADER:
5624 CurrentModule->addTopHeaderFilename(Blob);
5627 case SUBMODULE_UMBRELLA_DIR: {
5628 // See comments in SUBMODULE_UMBRELLA_HEADER
5629 std::string Dirname = std::string(Blob);
5630 ResolveImportedPath(F, Dirname);
5631 if (auto Umbrella = PP.getFileManager().getDirectory(Dirname)) {
5632 if (!CurrentModule->getUmbrellaDir()) {
5633 // FIXME: NameAsWritten
5634 ModMap.setUmbrellaDir(CurrentModule, *Umbrella, Blob, "");
5640 case SUBMODULE_METADATA: {
5641 F.BaseSubmoduleID = getTotalNumSubmodules();
5642 F.LocalNumSubmodules = Record[0];
5643 unsigned LocalBaseSubmoduleID = Record[1];
5644 if (F.LocalNumSubmodules > 0) {
5645 // Introduce the global -> local mapping for submodules within this
5647 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
5649 // Introduce the local -> global mapping for submodules within this
5651 F.SubmoduleRemap.insertOrReplace(
5652 std::make_pair(LocalBaseSubmoduleID,
5653 F.BaseSubmoduleID - LocalBaseSubmoduleID));
5655 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
5660 case SUBMODULE_IMPORTS:
5661 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
5662 UnresolvedModuleRef Unresolved;
5663 Unresolved.File = &F;
5664 Unresolved.Mod = CurrentModule;
5665 Unresolved.ID = Record[Idx];
5666 Unresolved.Kind = UnresolvedModuleRef::Import;
5667 Unresolved.IsWildcard = false;
5668 UnresolvedModuleRefs.push_back(Unresolved);
5672 case SUBMODULE_EXPORTS:
5673 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
5674 UnresolvedModuleRef Unresolved;
5675 Unresolved.File = &F;
5676 Unresolved.Mod = CurrentModule;
5677 Unresolved.ID = Record[Idx];
5678 Unresolved.Kind = UnresolvedModuleRef::Export;
5679 Unresolved.IsWildcard = Record[Idx + 1];
5680 UnresolvedModuleRefs.push_back(Unresolved);
5683 // Once we've loaded the set of exports, there's no reason to keep
5684 // the parsed, unresolved exports around.
5685 CurrentModule->UnresolvedExports.clear();
5688 case SUBMODULE_REQUIRES:
5689 CurrentModule->addRequirement(Blob, Record[0], PP.getLangOpts(),
5690 PP.getTargetInfo());
5693 case SUBMODULE_LINK_LIBRARY:
5694 ModMap.resolveLinkAsDependencies(CurrentModule);
5695 CurrentModule->LinkLibraries.push_back(
5696 Module::LinkLibrary(std::string(Blob), Record[0]));
5699 case SUBMODULE_CONFIG_MACRO:
5700 CurrentModule->ConfigMacros.push_back(Blob.str());
5703 case SUBMODULE_CONFLICT: {
5704 UnresolvedModuleRef Unresolved;
5705 Unresolved.File = &F;
5706 Unresolved.Mod = CurrentModule;
5707 Unresolved.ID = Record[0];
5708 Unresolved.Kind = UnresolvedModuleRef::Conflict;
5709 Unresolved.IsWildcard = false;
5710 Unresolved.String = Blob;
5711 UnresolvedModuleRefs.push_back(Unresolved);
5715 case SUBMODULE_INITIALIZERS: {
5718 SmallVector<uint32_t, 16> Inits;
5719 for (auto &ID : Record)
5720 Inits.push_back(getGlobalDeclID(F, ID));
5721 ContextObj->addLazyModuleInitializers(CurrentModule, Inits);
5725 case SUBMODULE_EXPORT_AS:
5726 CurrentModule->ExportAsModule = Blob.str();
5727 ModMap.addLinkAsDependency(CurrentModule);
5733 /// Parse the record that corresponds to a LangOptions data
5736 /// This routine parses the language options from the AST file and then gives
5737 /// them to the AST listener if one is set.
5739 /// \returns true if the listener deems the file unacceptable, false otherwise.
5740 bool ASTReader::ParseLanguageOptions(const RecordData &Record,
5742 ASTReaderListener &Listener,
5743 bool AllowCompatibleDifferences) {
5744 LangOptions LangOpts;
5746 #define LANGOPT(Name, Bits, Default, Description) \
5747 LangOpts.Name = Record[Idx++];
5748 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
5749 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
5750 #include "clang/Basic/LangOptions.def"
5751 #define SANITIZER(NAME, ID) \
5752 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
5753 #include "clang/Basic/Sanitizers.def"
5755 for (unsigned N = Record[Idx++]; N; --N)
5756 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
5758 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
5759 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
5760 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
5762 LangOpts.CurrentModule = ReadString(Record, Idx);
5765 for (unsigned N = Record[Idx++]; N; --N) {
5766 LangOpts.CommentOpts.BlockCommandNames.push_back(
5767 ReadString(Record, Idx));
5769 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
5771 // OpenMP offloading options.
5772 for (unsigned N = Record[Idx++]; N; --N) {
5773 LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx)));
5776 LangOpts.OMPHostIRFile = ReadString(Record, Idx);
5778 return Listener.ReadLanguageOptions(LangOpts, Complain,
5779 AllowCompatibleDifferences);
5782 bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
5783 ASTReaderListener &Listener,
5784 bool AllowCompatibleDifferences) {
5786 TargetOptions TargetOpts;
5787 TargetOpts.Triple = ReadString(Record, Idx);
5788 TargetOpts.CPU = ReadString(Record, Idx);
5789 TargetOpts.TuneCPU = ReadString(Record, Idx);
5790 TargetOpts.ABI = ReadString(Record, Idx);
5791 for (unsigned N = Record[Idx++]; N; --N) {
5792 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
5794 for (unsigned N = Record[Idx++]; N; --N) {
5795 TargetOpts.Features.push_back(ReadString(Record, Idx));
5798 return Listener.ReadTargetOptions(TargetOpts, Complain,
5799 AllowCompatibleDifferences);
5802 bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
5803 ASTReaderListener &Listener) {
5804 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
5806 #define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
5807 #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
5808 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
5809 #include "clang/Basic/DiagnosticOptions.def"
5811 for (unsigned N = Record[Idx++]; N; --N)
5812 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
5813 for (unsigned N = Record[Idx++]; N; --N)
5814 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
5816 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
5819 bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
5820 ASTReaderListener &Listener) {
5821 FileSystemOptions FSOpts;
5823 FSOpts.WorkingDir = ReadString(Record, Idx);
5824 return Listener.ReadFileSystemOptions(FSOpts, Complain);
5827 bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
5829 ASTReaderListener &Listener) {
5830 HeaderSearchOptions HSOpts;
5832 HSOpts.Sysroot = ReadString(Record, Idx);
5835 for (unsigned N = Record[Idx++]; N; --N) {
5836 std::string Path = ReadString(Record, Idx);
5837 frontend::IncludeDirGroup Group
5838 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
5839 bool IsFramework = Record[Idx++];
5840 bool IgnoreSysRoot = Record[Idx++];
5841 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
5845 // System header prefixes.
5846 for (unsigned N = Record[Idx++]; N; --N) {
5847 std::string Prefix = ReadString(Record, Idx);
5848 bool IsSystemHeader = Record[Idx++];
5849 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
5852 HSOpts.ResourceDir = ReadString(Record, Idx);
5853 HSOpts.ModuleCachePath = ReadString(Record, Idx);
5854 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
5855 HSOpts.DisableModuleHash = Record[Idx++];
5856 HSOpts.ImplicitModuleMaps = Record[Idx++];
5857 HSOpts.ModuleMapFileHomeIsCwd = Record[Idx++];
5858 HSOpts.EnablePrebuiltImplicitModules = Record[Idx++];
5859 HSOpts.UseBuiltinIncludes = Record[Idx++];
5860 HSOpts.UseStandardSystemIncludes = Record[Idx++];
5861 HSOpts.UseStandardCXXIncludes = Record[Idx++];
5862 HSOpts.UseLibcxx = Record[Idx++];
5863 std::string SpecificModuleCachePath = ReadString(Record, Idx);
5865 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
5869 bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
5871 ASTReaderListener &Listener,
5872 std::string &SuggestedPredefines) {
5873 PreprocessorOptions PPOpts;
5876 // Macro definitions/undefs
5877 for (unsigned N = Record[Idx++]; N; --N) {
5878 std::string Macro = ReadString(Record, Idx);
5879 bool IsUndef = Record[Idx++];
5880 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
5884 for (unsigned N = Record[Idx++]; N; --N) {
5885 PPOpts.Includes.push_back(ReadString(Record, Idx));
5889 for (unsigned N = Record[Idx++]; N; --N) {
5890 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
5893 PPOpts.UsePredefines = Record[Idx++];
5894 PPOpts.DetailedRecord = Record[Idx++];
5895 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
5896 PPOpts.ObjCXXARCStandardLibrary =
5897 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
5898 SuggestedPredefines.clear();
5899 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
5900 SuggestedPredefines);
5903 std::pair<ModuleFile *, unsigned>
5904 ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
5905 GlobalPreprocessedEntityMapType::iterator
5906 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
5907 assert(I != GlobalPreprocessedEntityMap.end() &&
5908 "Corrupted global preprocessed entity map");
5909 ModuleFile *M = I->second;
5910 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
5911 return std::make_pair(M, LocalIndex);
5914 llvm::iterator_range<PreprocessingRecord::iterator>
5915 ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
5916 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
5917 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
5918 Mod.NumPreprocessedEntities);
5920 return llvm::make_range(PreprocessingRecord::iterator(),
5921 PreprocessingRecord::iterator());
5924 bool ASTReader::canRecoverFromOutOfDate(StringRef ModuleFileName,
5925 unsigned int ClientLoadCapabilities) {
5926 return ClientLoadCapabilities & ARR_OutOfDate &&
5927 !getModuleManager().getModuleCache().isPCMFinal(ModuleFileName);
5930 llvm::iterator_range<ASTReader::ModuleDeclIterator>
5931 ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
5932 return llvm::make_range(
5933 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
5934 ModuleDeclIterator(this, &Mod,
5935 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
5938 SourceRange ASTReader::ReadSkippedRange(unsigned GlobalIndex) {
5939 auto I = GlobalSkippedRangeMap.find(GlobalIndex);
5940 assert(I != GlobalSkippedRangeMap.end() &&
5941 "Corrupted global skipped range map");
5942 ModuleFile *M = I->second;
5943 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedSkippedRangeID;
5944 assert(LocalIndex < M->NumPreprocessedSkippedRanges);
5945 PPSkippedRange RawRange = M->PreprocessedSkippedRangeOffsets[LocalIndex];
5946 SourceRange Range(TranslateSourceLocation(*M, RawRange.getBegin()),
5947 TranslateSourceLocation(*M, RawRange.getEnd()));
5948 assert(Range.isValid());
5952 PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
5953 PreprocessedEntityID PPID = Index+1;
5954 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5955 ModuleFile &M = *PPInfo.first;
5956 unsigned LocalIndex = PPInfo.second;
5957 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
5959 if (!PP.getPreprocessingRecord()) {
5960 Error("no preprocessing record");
5964 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
5965 if (llvm::Error Err = M.PreprocessorDetailCursor.JumpToBit(
5966 M.MacroOffsetsBase + PPOffs.BitOffset)) {
5967 Error(std::move(Err));
5971 Expected<llvm::BitstreamEntry> MaybeEntry =
5972 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
5974 Error(MaybeEntry.takeError());
5977 llvm::BitstreamEntry Entry = MaybeEntry.get();
5979 if (Entry.Kind != llvm::BitstreamEntry::Record)
5983 SourceRange Range(TranslateSourceLocation(M, PPOffs.getBegin()),
5984 TranslateSourceLocation(M, PPOffs.getEnd()));
5985 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
5988 Expected<unsigned> MaybeRecType =
5989 M.PreprocessorDetailCursor.readRecord(Entry.ID, Record, &Blob);
5990 if (!MaybeRecType) {
5991 Error(MaybeRecType.takeError());
5994 switch ((PreprocessorDetailRecordTypes)MaybeRecType.get()) {
5995 case PPD_MACRO_EXPANSION: {
5996 bool isBuiltin = Record[0];
5997 IdentifierInfo *Name = nullptr;
5998 MacroDefinitionRecord *Def = nullptr;
6000 Name = getLocalIdentifier(M, Record[1]);
6002 PreprocessedEntityID GlobalID =
6003 getGlobalPreprocessedEntityID(M, Record[1]);
6004 Def = cast<MacroDefinitionRecord>(
6005 PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
6010 ME = new (PPRec) MacroExpansion(Name, Range);
6012 ME = new (PPRec) MacroExpansion(Def, Range);
6017 case PPD_MACRO_DEFINITION: {
6018 // Decode the identifier info and then check again; if the macro is
6019 // still defined and associated with the identifier,
6020 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
6021 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
6023 if (DeserializationListener)
6024 DeserializationListener->MacroDefinitionRead(PPID, MD);
6029 case PPD_INCLUSION_DIRECTIVE: {
6030 const char *FullFileNameStart = Blob.data() + Record[0];
6031 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
6032 const FileEntry *File = nullptr;
6033 if (!FullFileName.empty())
6034 if (auto FE = PP.getFileManager().getFile(FullFileName))
6037 // FIXME: Stable encoding
6038 InclusionDirective::InclusionKind Kind
6039 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
6040 InclusionDirective *ID
6041 = new (PPRec) InclusionDirective(PPRec, Kind,
6042 StringRef(Blob.data(), Record[0]),
6043 Record[1], Record[3],
6050 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
6053 /// Find the next module that contains entities and return the ID
6054 /// of the first entry.
6056 /// \param SLocMapI points at a chunk of a module that contains no
6057 /// preprocessed entities or the entities it contains are not the ones we are
6059 PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
6060 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
6062 for (GlobalSLocOffsetMapType::const_iterator
6063 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
6064 ModuleFile &M = *SLocMapI->second;
6065 if (M.NumPreprocessedEntities)
6066 return M.BasePreprocessedEntityID;
6069 return getTotalNumPreprocessedEntities();
6074 struct PPEntityComp {
6075 const ASTReader &Reader;
6078 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) {}
6080 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
6081 SourceLocation LHS = getLoc(L);
6082 SourceLocation RHS = getLoc(R);
6083 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6086 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
6087 SourceLocation LHS = getLoc(L);
6088 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6091 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
6092 SourceLocation RHS = getLoc(R);
6093 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6096 SourceLocation getLoc(const PPEntityOffset &PPE) const {
6097 return Reader.TranslateSourceLocation(M, PPE.getBegin());
6103 PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
6104 bool EndsAfter) const {
6105 if (SourceMgr.isLocalSourceLocation(Loc))
6106 return getTotalNumPreprocessedEntities();
6108 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
6109 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
6110 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
6111 "Corrupted global sloc offset map");
6113 if (SLocMapI->second->NumPreprocessedEntities == 0)
6114 return findNextPreprocessedEntity(SLocMapI);
6116 ModuleFile &M = *SLocMapI->second;
6118 using pp_iterator = const PPEntityOffset *;
6120 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
6121 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
6123 size_t Count = M.NumPreprocessedEntities;
6125 pp_iterator First = pp_begin;
6129 PPI = std::upper_bound(pp_begin, pp_end, Loc,
6130 PPEntityComp(*this, M));
6132 // Do a binary search manually instead of using std::lower_bound because
6133 // The end locations of entities may be unordered (when a macro expansion
6134 // is inside another macro argument), but for this case it is not important
6135 // whether we get the first macro expansion or its containing macro.
6139 std::advance(PPI, Half);
6140 if (SourceMgr.isBeforeInTranslationUnit(
6141 TranslateSourceLocation(M, PPI->getEnd()), Loc)) {
6144 Count = Count - Half - 1;
6151 return findNextPreprocessedEntity(SLocMapI);
6153 return M.BasePreprocessedEntityID + (PPI - pp_begin);
6156 /// Returns a pair of [Begin, End) indices of preallocated
6157 /// preprocessed entities that \arg Range encompasses.
6158 std::pair<unsigned, unsigned>
6159 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
6160 if (Range.isInvalid())
6161 return std::make_pair(0,0);
6162 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
6164 PreprocessedEntityID BeginID =
6165 findPreprocessedEntity(Range.getBegin(), false);
6166 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
6167 return std::make_pair(BeginID, EndID);
6170 /// Optionally returns true or false if the preallocated preprocessed
6171 /// entity with index \arg Index came from file \arg FID.
6172 Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
6174 if (FID.isInvalid())
6177 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
6178 ModuleFile &M = *PPInfo.first;
6179 unsigned LocalIndex = PPInfo.second;
6180 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
6182 SourceLocation Loc = TranslateSourceLocation(M, PPOffs.getBegin());
6183 if (Loc.isInvalid())
6186 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
6194 /// Visitor used to search for information about a header file.
6195 class HeaderFileInfoVisitor {
6196 const FileEntry *FE;
6197 Optional<HeaderFileInfo> HFI;
6200 explicit HeaderFileInfoVisitor(const FileEntry *FE) : FE(FE) {}
6202 bool operator()(ModuleFile &M) {
6203 HeaderFileInfoLookupTable *Table
6204 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
6208 // Look in the on-disk hash table for an entry for this file name.
6209 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
6210 if (Pos == Table->end())
6217 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
6222 HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
6223 HeaderFileInfoVisitor Visitor(FE);
6224 ModuleMgr.visit(Visitor);
6225 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
6228 return HeaderFileInfo();
6231 void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
6232 using DiagState = DiagnosticsEngine::DiagState;
6233 SmallVector<DiagState *, 32> DiagStates;
6235 for (ModuleFile &F : ModuleMgr) {
6237 auto &Record = F.PragmaDiagMappings;
6243 auto ReadDiagState =
6244 [&](const DiagState &BasedOn, SourceLocation Loc,
6245 bool IncludeNonPragmaStates) -> DiagnosticsEngine::DiagState * {
6246 unsigned BackrefID = Record[Idx++];
6248 return DiagStates[BackrefID - 1];
6250 // A new DiagState was created here.
6251 Diag.DiagStates.push_back(BasedOn);
6252 DiagState *NewState = &Diag.DiagStates.back();
6253 DiagStates.push_back(NewState);
6254 unsigned Size = Record[Idx++];
6255 assert(Idx + Size * 2 <= Record.size() &&
6256 "Invalid data, not enough diag/map pairs");
6258 unsigned DiagID = Record[Idx++];
6259 DiagnosticMapping NewMapping =
6260 DiagnosticMapping::deserialize(Record[Idx++]);
6261 if (!NewMapping.isPragma() && !IncludeNonPragmaStates)
6264 DiagnosticMapping &Mapping = NewState->getOrAddMapping(DiagID);
6266 // If this mapping was specified as a warning but the severity was
6267 // upgraded due to diagnostic settings, simulate the current diagnostic
6268 // settings (and use a warning).
6269 if (NewMapping.wasUpgradedFromWarning() && !Mapping.isErrorOrFatal()) {
6270 NewMapping.setSeverity(diag::Severity::Warning);
6271 NewMapping.setUpgradedFromWarning(false);
6274 Mapping = NewMapping;
6279 // Read the first state.
6280 DiagState *FirstState;
6281 if (F.Kind == MK_ImplicitModule) {
6282 // Implicitly-built modules are reused with different diagnostic
6283 // settings. Use the initial diagnostic state from Diag to simulate this
6284 // compilation's diagnostic settings.
6285 FirstState = Diag.DiagStatesByLoc.FirstDiagState;
6286 DiagStates.push_back(FirstState);
6288 // Skip the initial diagnostic state from the serialized module.
6289 assert(Record[1] == 0 &&
6290 "Invalid data, unexpected backref in initial state");
6291 Idx = 3 + Record[2] * 2;
6292 assert(Idx < Record.size() &&
6293 "Invalid data, not enough state change pairs in initial state");
6294 } else if (F.isModule()) {
6295 // For an explicit module, preserve the flags from the module build
6296 // command line (-w, -Weverything, -Werror, ...) along with any explicit
6298 unsigned Flags = Record[Idx++];
6300 Initial.SuppressSystemWarnings = Flags & 1; Flags >>= 1;
6301 Initial.ErrorsAsFatal = Flags & 1; Flags >>= 1;
6302 Initial.WarningsAsErrors = Flags & 1; Flags >>= 1;
6303 Initial.EnableAllWarnings = Flags & 1; Flags >>= 1;
6304 Initial.IgnoreAllWarnings = Flags & 1; Flags >>= 1;
6305 Initial.ExtBehavior = (diag::Severity)Flags;
6306 FirstState = ReadDiagState(Initial, SourceLocation(), true);
6308 assert(F.OriginalSourceFileID.isValid());
6310 // Set up the root buffer of the module to start with the initial
6311 // diagnostic state of the module itself, to cover files that contain no
6312 // explicit transitions (for which we did not serialize anything).
6313 Diag.DiagStatesByLoc.Files[F.OriginalSourceFileID]
6314 .StateTransitions.push_back({FirstState, 0});
6316 // For prefix ASTs, start with whatever the user configured on the
6318 Idx++; // Skip flags.
6319 FirstState = ReadDiagState(*Diag.DiagStatesByLoc.CurDiagState,
6320 SourceLocation(), false);
6323 // Read the state transitions.
6324 unsigned NumLocations = Record[Idx++];
6325 while (NumLocations--) {
6326 assert(Idx < Record.size() &&
6327 "Invalid data, missing pragma diagnostic states");
6328 SourceLocation Loc = ReadSourceLocation(F, Record[Idx++]);
6329 auto IDAndOffset = SourceMgr.getDecomposedLoc(Loc);
6330 assert(IDAndOffset.first.isValid() && "invalid FileID for transition");
6331 assert(IDAndOffset.second == 0 && "not a start location for a FileID");
6332 unsigned Transitions = Record[Idx++];
6334 // Note that we don't need to set up Parent/ParentOffset here, because
6335 // we won't be changing the diagnostic state within imported FileIDs
6336 // (other than perhaps appending to the main source file, which has no
6338 auto &F = Diag.DiagStatesByLoc.Files[IDAndOffset.first];
6339 F.StateTransitions.reserve(F.StateTransitions.size() + Transitions);
6340 for (unsigned I = 0; I != Transitions; ++I) {
6341 unsigned Offset = Record[Idx++];
6343 ReadDiagState(*FirstState, Loc.getLocWithOffset(Offset), false);
6344 F.StateTransitions.push_back({State, Offset});
6348 // Read the final state.
6349 assert(Idx < Record.size() &&
6350 "Invalid data, missing final pragma diagnostic state");
6351 SourceLocation CurStateLoc =
6352 ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
6353 auto *CurState = ReadDiagState(*FirstState, CurStateLoc, false);
6355 if (!F.isModule()) {
6356 Diag.DiagStatesByLoc.CurDiagState = CurState;
6357 Diag.DiagStatesByLoc.CurDiagStateLoc = CurStateLoc;
6359 // Preserve the property that the imaginary root file describes the
6362 auto &T = Diag.DiagStatesByLoc.Files[NullFile].StateTransitions;
6364 T.push_back({CurState, 0});
6366 T[0].State = CurState;
6369 // Don't try to read these mappings again.
6374 /// Get the correct cursor and offset for loading a type.
6375 ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
6376 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
6377 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
6378 ModuleFile *M = I->second;
6379 return RecordLocation(
6380 M, M->TypeOffsets[Index - M->BaseTypeIndex].getBitOffset() +
6381 M->DeclsBlockStartOffset);
6384 static llvm::Optional<Type::TypeClass> getTypeClassForCode(TypeCode code) {
6386 #define TYPE_BIT_CODE(CLASS_ID, CODE_ID, CODE_VALUE) \
6387 case TYPE_##CODE_ID: return Type::CLASS_ID;
6388 #include "clang/Serialization/TypeBitCodes.def"
6389 default: return llvm::None;
6393 /// Read and return the type with the given index..
6395 /// The index is the type ID, shifted and minus the number of predefs. This
6396 /// routine actually reads the record corresponding to the type at the given
6397 /// location. It is a helper routine for GetType, which deals with reading type
6399 QualType ASTReader::readTypeRecord(unsigned Index) {
6400 assert(ContextObj && "reading type with no AST context");
6401 ASTContext &Context = *ContextObj;
6402 RecordLocation Loc = TypeCursorForIndex(Index);
6403 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
6405 // Keep track of where we are in the stream, then jump back there
6406 // after reading this type.
6407 SavedStreamPosition SavedPosition(DeclsCursor);
6409 ReadingKindTracker ReadingKind(Read_Type, *this);
6411 // Note that we are loading a type record.
6412 Deserializing AType(this);
6414 if (llvm::Error Err = DeclsCursor.JumpToBit(Loc.Offset)) {
6415 Error(std::move(Err));
6418 Expected<unsigned> RawCode = DeclsCursor.ReadCode();
6420 Error(RawCode.takeError());
6424 ASTRecordReader Record(*this, *Loc.F);
6425 Expected<unsigned> Code = Record.readRecord(DeclsCursor, RawCode.get());
6427 Error(Code.takeError());
6430 if (Code.get() == TYPE_EXT_QUAL) {
6431 QualType baseType = Record.readQualType();
6432 Qualifiers quals = Record.readQualifiers();
6433 return Context.getQualifiedType(baseType, quals);
6436 auto maybeClass = getTypeClassForCode((TypeCode) Code.get());
6438 Error("Unexpected code for type");
6442 serialization::AbstractTypeReader<ASTRecordReader> TypeReader(Record);
6443 return TypeReader.read(*maybeClass);
6448 class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
6449 ASTRecordReader &Reader;
6451 SourceLocation readSourceLocation() {
6452 return Reader.readSourceLocation();
6455 TypeSourceInfo *GetTypeSourceInfo() {
6456 return Reader.readTypeSourceInfo();
6459 NestedNameSpecifierLoc ReadNestedNameSpecifierLoc() {
6460 return Reader.readNestedNameSpecifierLoc();
6464 return Reader.readAttr();
6468 TypeLocReader(ASTRecordReader &Reader) : Reader(Reader) {}
6470 // We want compile-time assurance that we've enumerated all of
6471 // these, so unfortunately we have to declare them first, then
6472 // define them out-of-line.
6473 #define ABSTRACT_TYPELOC(CLASS, PARENT)
6474 #define TYPELOC(CLASS, PARENT) \
6475 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
6476 #include "clang/AST/TypeLocNodes.def"
6478 void VisitFunctionTypeLoc(FunctionTypeLoc);
6479 void VisitArrayTypeLoc(ArrayTypeLoc);
6482 } // namespace clang
6484 void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
6488 void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
6489 TL.setBuiltinLoc(readSourceLocation());
6490 if (TL.needsExtraLocalData()) {
6491 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Reader.readInt()));
6492 TL.setWrittenSignSpec(static_cast<TypeSpecifierSign>(Reader.readInt()));
6493 TL.setWrittenWidthSpec(static_cast<TypeSpecifierWidth>(Reader.readInt()));
6494 TL.setModeAttr(Reader.readInt());
6498 void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
6499 TL.setNameLoc(readSourceLocation());
6502 void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
6503 TL.setStarLoc(readSourceLocation());
6506 void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
6510 void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
6514 void TypeLocReader::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
6515 TL.setExpansionLoc(readSourceLocation());
6518 void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
6519 TL.setCaretLoc(readSourceLocation());
6522 void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
6523 TL.setAmpLoc(readSourceLocation());
6526 void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
6527 TL.setAmpAmpLoc(readSourceLocation());
6530 void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
6531 TL.setStarLoc(readSourceLocation());
6532 TL.setClassTInfo(GetTypeSourceInfo());
6535 void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
6536 TL.setLBracketLoc(readSourceLocation());
6537 TL.setRBracketLoc(readSourceLocation());
6538 if (Reader.readBool())
6539 TL.setSizeExpr(Reader.readExpr());
6541 TL.setSizeExpr(nullptr);
6544 void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
6545 VisitArrayTypeLoc(TL);
6548 void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
6549 VisitArrayTypeLoc(TL);
6552 void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
6553 VisitArrayTypeLoc(TL);
6556 void TypeLocReader::VisitDependentSizedArrayTypeLoc(
6557 DependentSizedArrayTypeLoc TL) {
6558 VisitArrayTypeLoc(TL);
6561 void TypeLocReader::VisitDependentAddressSpaceTypeLoc(
6562 DependentAddressSpaceTypeLoc TL) {
6564 TL.setAttrNameLoc(readSourceLocation());
6565 TL.setAttrOperandParensRange(Reader.readSourceRange());
6566 TL.setAttrExprOperand(Reader.readExpr());
6569 void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
6570 DependentSizedExtVectorTypeLoc TL) {
6571 TL.setNameLoc(readSourceLocation());
6574 void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
6575 TL.setNameLoc(readSourceLocation());
6578 void TypeLocReader::VisitDependentVectorTypeLoc(
6579 DependentVectorTypeLoc TL) {
6580 TL.setNameLoc(readSourceLocation());
6583 void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
6584 TL.setNameLoc(readSourceLocation());
6587 void TypeLocReader::VisitConstantMatrixTypeLoc(ConstantMatrixTypeLoc TL) {
6588 TL.setAttrNameLoc(readSourceLocation());
6589 TL.setAttrOperandParensRange(Reader.readSourceRange());
6590 TL.setAttrRowOperand(Reader.readExpr());
6591 TL.setAttrColumnOperand(Reader.readExpr());
6594 void TypeLocReader::VisitDependentSizedMatrixTypeLoc(
6595 DependentSizedMatrixTypeLoc TL) {
6596 TL.setAttrNameLoc(readSourceLocation());
6597 TL.setAttrOperandParensRange(Reader.readSourceRange());
6598 TL.setAttrRowOperand(Reader.readExpr());
6599 TL.setAttrColumnOperand(Reader.readExpr());
6602 void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
6603 TL.setLocalRangeBegin(readSourceLocation());
6604 TL.setLParenLoc(readSourceLocation());
6605 TL.setRParenLoc(readSourceLocation());
6606 TL.setExceptionSpecRange(Reader.readSourceRange());
6607 TL.setLocalRangeEnd(readSourceLocation());
6608 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
6609 TL.setParam(i, Reader.readDeclAs<ParmVarDecl>());
6613 void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
6614 VisitFunctionTypeLoc(TL);
6617 void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
6618 VisitFunctionTypeLoc(TL);
6621 void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
6622 TL.setNameLoc(readSourceLocation());
6625 void TypeLocReader::VisitUsingTypeLoc(UsingTypeLoc TL) {
6626 TL.setNameLoc(readSourceLocation());
6629 void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
6630 TL.setNameLoc(readSourceLocation());
6633 void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
6634 TL.setTypeofLoc(readSourceLocation());
6635 TL.setLParenLoc(readSourceLocation());
6636 TL.setRParenLoc(readSourceLocation());
6639 void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
6640 TL.setTypeofLoc(readSourceLocation());
6641 TL.setLParenLoc(readSourceLocation());
6642 TL.setRParenLoc(readSourceLocation());
6643 TL.setUnderlyingTInfo(GetTypeSourceInfo());
6646 void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
6647 TL.setDecltypeLoc(readSourceLocation());
6648 TL.setRParenLoc(readSourceLocation());
6651 void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
6652 TL.setKWLoc(readSourceLocation());
6653 TL.setLParenLoc(readSourceLocation());
6654 TL.setRParenLoc(readSourceLocation());
6655 TL.setUnderlyingTInfo(GetTypeSourceInfo());
6658 void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
6659 TL.setNameLoc(readSourceLocation());
6660 if (Reader.readBool()) {
6661 TL.setNestedNameSpecifierLoc(ReadNestedNameSpecifierLoc());
6662 TL.setTemplateKWLoc(readSourceLocation());
6663 TL.setConceptNameLoc(readSourceLocation());
6664 TL.setFoundDecl(Reader.readDeclAs<NamedDecl>());
6665 TL.setLAngleLoc(readSourceLocation());
6666 TL.setRAngleLoc(readSourceLocation());
6667 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
6668 TL.setArgLocInfo(i, Reader.readTemplateArgumentLocInfo(
6669 TL.getTypePtr()->getArg(i).getKind()));
6671 if (Reader.readBool())
6672 TL.setRParenLoc(readSourceLocation());
6675 void TypeLocReader::VisitDeducedTemplateSpecializationTypeLoc(
6676 DeducedTemplateSpecializationTypeLoc TL) {
6677 TL.setTemplateNameLoc(readSourceLocation());
6680 void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
6681 TL.setNameLoc(readSourceLocation());
6684 void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
6685 TL.setNameLoc(readSourceLocation());
6688 void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
6689 TL.setAttr(ReadAttr());
6692 void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
6693 TL.setNameLoc(readSourceLocation());
6696 void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
6697 SubstTemplateTypeParmTypeLoc TL) {
6698 TL.setNameLoc(readSourceLocation());
6701 void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
6702 SubstTemplateTypeParmPackTypeLoc TL) {
6703 TL.setNameLoc(readSourceLocation());
6706 void TypeLocReader::VisitTemplateSpecializationTypeLoc(
6707 TemplateSpecializationTypeLoc TL) {
6708 TL.setTemplateKeywordLoc(readSourceLocation());
6709 TL.setTemplateNameLoc(readSourceLocation());
6710 TL.setLAngleLoc(readSourceLocation());
6711 TL.setRAngleLoc(readSourceLocation());
6712 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
6715 Reader.readTemplateArgumentLocInfo(
6716 TL.getTypePtr()->getArg(i).getKind()));
6719 void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
6720 TL.setLParenLoc(readSourceLocation());
6721 TL.setRParenLoc(readSourceLocation());
6724 void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
6725 TL.setElaboratedKeywordLoc(readSourceLocation());
6726 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
6729 void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
6730 TL.setNameLoc(readSourceLocation());
6733 void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
6734 TL.setElaboratedKeywordLoc(readSourceLocation());
6735 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
6736 TL.setNameLoc(readSourceLocation());
6739 void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
6740 DependentTemplateSpecializationTypeLoc TL) {
6741 TL.setElaboratedKeywordLoc(readSourceLocation());
6742 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
6743 TL.setTemplateKeywordLoc(readSourceLocation());
6744 TL.setTemplateNameLoc(readSourceLocation());
6745 TL.setLAngleLoc(readSourceLocation());
6746 TL.setRAngleLoc(readSourceLocation());
6747 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
6750 Reader.readTemplateArgumentLocInfo(
6751 TL.getTypePtr()->getArg(I).getKind()));
6754 void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
6755 TL.setEllipsisLoc(readSourceLocation());
6758 void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
6759 TL.setNameLoc(readSourceLocation());
6762 void TypeLocReader::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
6763 if (TL.getNumProtocols()) {
6764 TL.setProtocolLAngleLoc(readSourceLocation());
6765 TL.setProtocolRAngleLoc(readSourceLocation());
6767 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
6768 TL.setProtocolLoc(i, readSourceLocation());
6771 void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
6772 TL.setHasBaseTypeAsWritten(Reader.readBool());
6773 TL.setTypeArgsLAngleLoc(readSourceLocation());
6774 TL.setTypeArgsRAngleLoc(readSourceLocation());
6775 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
6776 TL.setTypeArgTInfo(i, GetTypeSourceInfo());
6777 TL.setProtocolLAngleLoc(readSourceLocation());
6778 TL.setProtocolRAngleLoc(readSourceLocation());
6779 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
6780 TL.setProtocolLoc(i, readSourceLocation());
6783 void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
6784 TL.setStarLoc(readSourceLocation());
6787 void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
6788 TL.setKWLoc(readSourceLocation());
6789 TL.setLParenLoc(readSourceLocation());
6790 TL.setRParenLoc(readSourceLocation());
6793 void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) {
6794 TL.setKWLoc(readSourceLocation());
6797 void TypeLocReader::VisitBitIntTypeLoc(clang::BitIntTypeLoc TL) {
6798 TL.setNameLoc(readSourceLocation());
6800 void TypeLocReader::VisitDependentBitIntTypeLoc(
6801 clang::DependentBitIntTypeLoc TL) {
6802 TL.setNameLoc(readSourceLocation());
6806 void ASTRecordReader::readTypeLoc(TypeLoc TL) {
6807 TypeLocReader TLR(*this);
6808 for (; !TL.isNull(); TL = TL.getNextTypeLoc())
6812 TypeSourceInfo *ASTRecordReader::readTypeSourceInfo() {
6813 QualType InfoTy = readType();
6814 if (InfoTy.isNull())
6817 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
6818 readTypeLoc(TInfo->getTypeLoc());
6822 QualType ASTReader::GetType(TypeID ID) {
6823 assert(ContextObj && "reading type with no AST context");
6824 ASTContext &Context = *ContextObj;
6826 unsigned FastQuals = ID & Qualifiers::FastMask;
6827 unsigned Index = ID >> Qualifiers::FastWidth;
6829 if (Index < NUM_PREDEF_TYPE_IDS) {
6831 switch ((PredefinedTypeIDs)Index) {
6832 case PREDEF_TYPE_NULL_ID:
6834 case PREDEF_TYPE_VOID_ID:
6837 case PREDEF_TYPE_BOOL_ID:
6840 case PREDEF_TYPE_CHAR_U_ID:
6841 case PREDEF_TYPE_CHAR_S_ID:
6842 // FIXME: Check that the signedness of CharTy is correct!
6845 case PREDEF_TYPE_UCHAR_ID:
6846 T = Context.UnsignedCharTy;
6848 case PREDEF_TYPE_USHORT_ID:
6849 T = Context.UnsignedShortTy;
6851 case PREDEF_TYPE_UINT_ID:
6852 T = Context.UnsignedIntTy;
6854 case PREDEF_TYPE_ULONG_ID:
6855 T = Context.UnsignedLongTy;
6857 case PREDEF_TYPE_ULONGLONG_ID:
6858 T = Context.UnsignedLongLongTy;
6860 case PREDEF_TYPE_UINT128_ID:
6861 T = Context.UnsignedInt128Ty;
6863 case PREDEF_TYPE_SCHAR_ID:
6864 T = Context.SignedCharTy;
6866 case PREDEF_TYPE_WCHAR_ID:
6867 T = Context.WCharTy;
6869 case PREDEF_TYPE_SHORT_ID:
6870 T = Context.ShortTy;
6872 case PREDEF_TYPE_INT_ID:
6875 case PREDEF_TYPE_LONG_ID:
6878 case PREDEF_TYPE_LONGLONG_ID:
6879 T = Context.LongLongTy;
6881 case PREDEF_TYPE_INT128_ID:
6882 T = Context.Int128Ty;
6884 case PREDEF_TYPE_BFLOAT16_ID:
6885 T = Context.BFloat16Ty;
6887 case PREDEF_TYPE_HALF_ID:
6890 case PREDEF_TYPE_FLOAT_ID:
6891 T = Context.FloatTy;
6893 case PREDEF_TYPE_DOUBLE_ID:
6894 T = Context.DoubleTy;
6896 case PREDEF_TYPE_LONGDOUBLE_ID:
6897 T = Context.LongDoubleTy;
6899 case PREDEF_TYPE_SHORT_ACCUM_ID:
6900 T = Context.ShortAccumTy;
6902 case PREDEF_TYPE_ACCUM_ID:
6903 T = Context.AccumTy;
6905 case PREDEF_TYPE_LONG_ACCUM_ID:
6906 T = Context.LongAccumTy;
6908 case PREDEF_TYPE_USHORT_ACCUM_ID:
6909 T = Context.UnsignedShortAccumTy;
6911 case PREDEF_TYPE_UACCUM_ID:
6912 T = Context.UnsignedAccumTy;
6914 case PREDEF_TYPE_ULONG_ACCUM_ID:
6915 T = Context.UnsignedLongAccumTy;
6917 case PREDEF_TYPE_SHORT_FRACT_ID:
6918 T = Context.ShortFractTy;
6920 case PREDEF_TYPE_FRACT_ID:
6921 T = Context.FractTy;
6923 case PREDEF_TYPE_LONG_FRACT_ID:
6924 T = Context.LongFractTy;
6926 case PREDEF_TYPE_USHORT_FRACT_ID:
6927 T = Context.UnsignedShortFractTy;
6929 case PREDEF_TYPE_UFRACT_ID:
6930 T = Context.UnsignedFractTy;
6932 case PREDEF_TYPE_ULONG_FRACT_ID:
6933 T = Context.UnsignedLongFractTy;
6935 case PREDEF_TYPE_SAT_SHORT_ACCUM_ID:
6936 T = Context.SatShortAccumTy;
6938 case PREDEF_TYPE_SAT_ACCUM_ID:
6939 T = Context.SatAccumTy;
6941 case PREDEF_TYPE_SAT_LONG_ACCUM_ID:
6942 T = Context.SatLongAccumTy;
6944 case PREDEF_TYPE_SAT_USHORT_ACCUM_ID:
6945 T = Context.SatUnsignedShortAccumTy;
6947 case PREDEF_TYPE_SAT_UACCUM_ID:
6948 T = Context.SatUnsignedAccumTy;
6950 case PREDEF_TYPE_SAT_ULONG_ACCUM_ID:
6951 T = Context.SatUnsignedLongAccumTy;
6953 case PREDEF_TYPE_SAT_SHORT_FRACT_ID:
6954 T = Context.SatShortFractTy;
6956 case PREDEF_TYPE_SAT_FRACT_ID:
6957 T = Context.SatFractTy;
6959 case PREDEF_TYPE_SAT_LONG_FRACT_ID:
6960 T = Context.SatLongFractTy;
6962 case PREDEF_TYPE_SAT_USHORT_FRACT_ID:
6963 T = Context.SatUnsignedShortFractTy;
6965 case PREDEF_TYPE_SAT_UFRACT_ID:
6966 T = Context.SatUnsignedFractTy;
6968 case PREDEF_TYPE_SAT_ULONG_FRACT_ID:
6969 T = Context.SatUnsignedLongFractTy;
6971 case PREDEF_TYPE_FLOAT16_ID:
6972 T = Context.Float16Ty;
6974 case PREDEF_TYPE_FLOAT128_ID:
6975 T = Context.Float128Ty;
6977 case PREDEF_TYPE_IBM128_ID:
6978 T = Context.Ibm128Ty;
6980 case PREDEF_TYPE_OVERLOAD_ID:
6981 T = Context.OverloadTy;
6983 case PREDEF_TYPE_BOUND_MEMBER:
6984 T = Context.BoundMemberTy;
6986 case PREDEF_TYPE_PSEUDO_OBJECT:
6987 T = Context.PseudoObjectTy;
6989 case PREDEF_TYPE_DEPENDENT_ID:
6990 T = Context.DependentTy;
6992 case PREDEF_TYPE_UNKNOWN_ANY:
6993 T = Context.UnknownAnyTy;
6995 case PREDEF_TYPE_NULLPTR_ID:
6996 T = Context.NullPtrTy;
6998 case PREDEF_TYPE_CHAR8_ID:
6999 T = Context.Char8Ty;
7001 case PREDEF_TYPE_CHAR16_ID:
7002 T = Context.Char16Ty;
7004 case PREDEF_TYPE_CHAR32_ID:
7005 T = Context.Char32Ty;
7007 case PREDEF_TYPE_OBJC_ID:
7008 T = Context.ObjCBuiltinIdTy;
7010 case PREDEF_TYPE_OBJC_CLASS:
7011 T = Context.ObjCBuiltinClassTy;
7013 case PREDEF_TYPE_OBJC_SEL:
7014 T = Context.ObjCBuiltinSelTy;
7016 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7017 case PREDEF_TYPE_##Id##_ID: \
7018 T = Context.SingletonId; \
7020 #include "clang/Basic/OpenCLImageTypes.def"
7021 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
7022 case PREDEF_TYPE_##Id##_ID: \
7023 T = Context.Id##Ty; \
7025 #include "clang/Basic/OpenCLExtensionTypes.def"
7026 case PREDEF_TYPE_SAMPLER_ID:
7027 T = Context.OCLSamplerTy;
7029 case PREDEF_TYPE_EVENT_ID:
7030 T = Context.OCLEventTy;
7032 case PREDEF_TYPE_CLK_EVENT_ID:
7033 T = Context.OCLClkEventTy;
7035 case PREDEF_TYPE_QUEUE_ID:
7036 T = Context.OCLQueueTy;
7038 case PREDEF_TYPE_RESERVE_ID_ID:
7039 T = Context.OCLReserveIDTy;
7041 case PREDEF_TYPE_AUTO_DEDUCT:
7042 T = Context.getAutoDeductType();
7044 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
7045 T = Context.getAutoRRefDeductType();
7047 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
7048 T = Context.ARCUnbridgedCastTy;
7050 case PREDEF_TYPE_BUILTIN_FN:
7051 T = Context.BuiltinFnTy;
7053 case PREDEF_TYPE_INCOMPLETE_MATRIX_IDX:
7054 T = Context.IncompleteMatrixIdxTy;
7056 case PREDEF_TYPE_OMP_ARRAY_SECTION:
7057 T = Context.OMPArraySectionTy;
7059 case PREDEF_TYPE_OMP_ARRAY_SHAPING:
7060 T = Context.OMPArraySectionTy;
7062 case PREDEF_TYPE_OMP_ITERATOR:
7063 T = Context.OMPIteratorTy;
7065 #define SVE_TYPE(Name, Id, SingletonId) \
7066 case PREDEF_TYPE_##Id##_ID: \
7067 T = Context.SingletonId; \
7069 #include "clang/Basic/AArch64SVEACLETypes.def"
7070 #define PPC_VECTOR_TYPE(Name, Id, Size) \
7071 case PREDEF_TYPE_##Id##_ID: \
7072 T = Context.Id##Ty; \
7074 #include "clang/Basic/PPCTypes.def"
7075 #define RVV_TYPE(Name, Id, SingletonId) \
7076 case PREDEF_TYPE_##Id##_ID: \
7077 T = Context.SingletonId; \
7079 #include "clang/Basic/RISCVVTypes.def"
7082 assert(!T.isNull() && "Unknown predefined type");
7083 return T.withFastQualifiers(FastQuals);
7086 Index -= NUM_PREDEF_TYPE_IDS;
7087 assert(Index < TypesLoaded.size() && "Type index out-of-range");
7088 if (TypesLoaded[Index].isNull()) {
7089 TypesLoaded[Index] = readTypeRecord(Index);
7090 if (TypesLoaded[Index].isNull())
7093 TypesLoaded[Index]->setFromAST();
7094 if (DeserializationListener)
7095 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
7096 TypesLoaded[Index]);
7099 return TypesLoaded[Index].withFastQualifiers(FastQuals);
7102 QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
7103 return GetType(getGlobalTypeID(F, LocalID));
7106 serialization::TypeID
7107 ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
7108 unsigned FastQuals = LocalID & Qualifiers::FastMask;
7109 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
7111 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
7114 if (!F.ModuleOffsetMap.empty())
7115 ReadModuleOffsetMap(F);
7117 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7118 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
7119 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
7121 unsigned GlobalIndex = LocalIndex + I->second;
7122 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
7125 TemplateArgumentLocInfo
7126 ASTRecordReader::readTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind) {
7128 case TemplateArgument::Expression:
7130 case TemplateArgument::Type:
7131 return readTypeSourceInfo();
7132 case TemplateArgument::Template: {
7133 NestedNameSpecifierLoc QualifierLoc =
7134 readNestedNameSpecifierLoc();
7135 SourceLocation TemplateNameLoc = readSourceLocation();
7136 return TemplateArgumentLocInfo(getASTContext(), QualifierLoc,
7137 TemplateNameLoc, SourceLocation());
7139 case TemplateArgument::TemplateExpansion: {
7140 NestedNameSpecifierLoc QualifierLoc = readNestedNameSpecifierLoc();
7141 SourceLocation TemplateNameLoc = readSourceLocation();
7142 SourceLocation EllipsisLoc = readSourceLocation();
7143 return TemplateArgumentLocInfo(getASTContext(), QualifierLoc,
7144 TemplateNameLoc, EllipsisLoc);
7146 case TemplateArgument::Null:
7147 case TemplateArgument::Integral:
7148 case TemplateArgument::Declaration:
7149 case TemplateArgument::NullPtr:
7150 case TemplateArgument::Pack:
7151 // FIXME: Is this right?
7152 return TemplateArgumentLocInfo();
7154 llvm_unreachable("unexpected template argument loc");
7157 TemplateArgumentLoc ASTRecordReader::readTemplateArgumentLoc() {
7158 TemplateArgument Arg = readTemplateArgument();
7160 if (Arg.getKind() == TemplateArgument::Expression) {
7161 if (readBool()) // bool InfoHasSameExpr.
7162 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
7164 return TemplateArgumentLoc(Arg, readTemplateArgumentLocInfo(Arg.getKind()));
7167 const ASTTemplateArgumentListInfo *
7168 ASTRecordReader::readASTTemplateArgumentListInfo() {
7169 SourceLocation LAngleLoc = readSourceLocation();
7170 SourceLocation RAngleLoc = readSourceLocation();
7171 unsigned NumArgsAsWritten = readInt();
7172 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
7173 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
7174 TemplArgsInfo.addArgument(readTemplateArgumentLoc());
7175 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
7178 Decl *ASTReader::GetExternalDecl(uint32_t ID) {
7182 void ASTReader::CompleteRedeclChain(const Decl *D) {
7183 if (NumCurrentElementsDeserializing) {
7184 // We arrange to not care about the complete redeclaration chain while we're
7185 // deserializing. Just remember that the AST has marked this one as complete
7186 // but that it's not actually complete yet, so we know we still need to
7187 // complete it later.
7188 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
7192 if (!D->getDeclContext()) {
7193 assert(isa<TranslationUnitDecl>(D) && "Not a TU?");
7197 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
7199 // If this is a named declaration, complete it by looking it up
7200 // within its context.
7202 // FIXME: Merging a function definition should merge
7203 // all mergeable entities within it.
7204 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
7205 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
7206 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
7207 if (!getContext().getLangOpts().CPlusPlus &&
7208 isa<TranslationUnitDecl>(DC)) {
7209 // Outside of C++, we don't have a lookup table for the TU, so update
7210 // the identifier instead. (For C++ modules, we don't store decls
7211 // in the serialized identifier table, so we do the lookup in the TU.)
7212 auto *II = Name.getAsIdentifierInfo();
7213 assert(II && "non-identifier name in C?");
7214 if (II->isOutOfDate())
7215 updateOutOfDateIdentifier(*II);
7218 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
7219 // Find all declarations of this kind from the relevant context.
7220 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
7221 auto *DC = cast<DeclContext>(DCDecl);
7222 SmallVector<Decl*, 8> Decls;
7223 FindExternalLexicalDecls(
7224 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
7229 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
7230 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
7231 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
7232 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
7233 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
7234 if (auto *Template = FD->getPrimaryTemplate())
7235 Template->LoadLazySpecializations();
7239 CXXCtorInitializer **
7240 ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
7241 RecordLocation Loc = getLocalBitOffset(Offset);
7242 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
7243 SavedStreamPosition SavedPosition(Cursor);
7244 if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {
7245 Error(std::move(Err));
7248 ReadingKindTracker ReadingKind(Read_Decl, *this);
7250 Expected<unsigned> MaybeCode = Cursor.ReadCode();
7252 Error(MaybeCode.takeError());
7255 unsigned Code = MaybeCode.get();
7257 ASTRecordReader Record(*this, *Loc.F);
7258 Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code);
7259 if (!MaybeRecCode) {
7260 Error(MaybeRecCode.takeError());
7263 if (MaybeRecCode.get() != DECL_CXX_CTOR_INITIALIZERS) {
7264 Error("malformed AST file: missing C++ ctor initializers");
7268 return Record.readCXXCtorInitializers();
7271 CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
7272 assert(ContextObj && "reading base specifiers with no AST context");
7273 ASTContext &Context = *ContextObj;
7275 RecordLocation Loc = getLocalBitOffset(Offset);
7276 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
7277 SavedStreamPosition SavedPosition(Cursor);
7278 if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {
7279 Error(std::move(Err));
7282 ReadingKindTracker ReadingKind(Read_Decl, *this);
7284 Expected<unsigned> MaybeCode = Cursor.ReadCode();
7286 Error(MaybeCode.takeError());
7289 unsigned Code = MaybeCode.get();
7291 ASTRecordReader Record(*this, *Loc.F);
7292 Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code);
7293 if (!MaybeRecCode) {
7294 Error(MaybeCode.takeError());
7297 unsigned RecCode = MaybeRecCode.get();
7299 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
7300 Error("malformed AST file: missing C++ base specifiers");
7304 unsigned NumBases = Record.readInt();
7305 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
7306 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
7307 for (unsigned I = 0; I != NumBases; ++I)
7308 Bases[I] = Record.readCXXBaseSpecifier();
7312 serialization::DeclID
7313 ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
7314 if (LocalID < NUM_PREDEF_DECL_IDS)
7317 if (!F.ModuleOffsetMap.empty())
7318 ReadModuleOffsetMap(F);
7320 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7321 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
7322 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
7324 return LocalID + I->second;
7327 bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
7328 ModuleFile &M) const {
7329 // Predefined decls aren't from any module.
7330 if (ID < NUM_PREDEF_DECL_IDS)
7333 return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
7334 ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
7337 ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
7338 if (!D->isFromASTFile())
7340 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
7341 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
7345 SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
7346 if (ID < NUM_PREDEF_DECL_IDS)
7347 return SourceLocation();
7349 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7351 if (Index > DeclsLoaded.size()) {
7352 Error("declaration ID out-of-range for AST file");
7353 return SourceLocation();
7356 if (Decl *D = DeclsLoaded[Index])
7357 return D->getLocation();
7360 DeclCursorForID(ID, Loc);
7364 static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
7366 case PREDEF_DECL_NULL_ID:
7369 case PREDEF_DECL_TRANSLATION_UNIT_ID:
7370 return Context.getTranslationUnitDecl();
7372 case PREDEF_DECL_OBJC_ID_ID:
7373 return Context.getObjCIdDecl();
7375 case PREDEF_DECL_OBJC_SEL_ID:
7376 return Context.getObjCSelDecl();
7378 case PREDEF_DECL_OBJC_CLASS_ID:
7379 return Context.getObjCClassDecl();
7381 case PREDEF_DECL_OBJC_PROTOCOL_ID:
7382 return Context.getObjCProtocolDecl();
7384 case PREDEF_DECL_INT_128_ID:
7385 return Context.getInt128Decl();
7387 case PREDEF_DECL_UNSIGNED_INT_128_ID:
7388 return Context.getUInt128Decl();
7390 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
7391 return Context.getObjCInstanceTypeDecl();
7393 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
7394 return Context.getBuiltinVaListDecl();
7396 case PREDEF_DECL_VA_LIST_TAG:
7397 return Context.getVaListTagDecl();
7399 case PREDEF_DECL_BUILTIN_MS_VA_LIST_ID:
7400 return Context.getBuiltinMSVaListDecl();
7402 case PREDEF_DECL_BUILTIN_MS_GUID_ID:
7403 return Context.getMSGuidTagDecl();
7405 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
7406 return Context.getExternCContextDecl();
7408 case PREDEF_DECL_MAKE_INTEGER_SEQ_ID:
7409 return Context.getMakeIntegerSeqDecl();
7411 case PREDEF_DECL_CF_CONSTANT_STRING_ID:
7412 return Context.getCFConstantStringDecl();
7414 case PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID:
7415 return Context.getCFConstantStringTagDecl();
7417 case PREDEF_DECL_TYPE_PACK_ELEMENT_ID:
7418 return Context.getTypePackElementDecl();
7420 llvm_unreachable("PredefinedDeclIDs unknown enum value");
7423 Decl *ASTReader::GetExistingDecl(DeclID ID) {
7424 assert(ContextObj && "reading decl with no AST context");
7425 if (ID < NUM_PREDEF_DECL_IDS) {
7426 Decl *D = getPredefinedDecl(*ContextObj, (PredefinedDeclIDs)ID);
7428 // Track that we have merged the declaration with ID \p ID into the
7429 // pre-existing predefined declaration \p D.
7430 auto &Merged = KeyDecls[D->getCanonicalDecl()];
7432 Merged.push_back(ID);
7437 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7439 if (Index >= DeclsLoaded.size()) {
7440 assert(0 && "declaration ID out-of-range for AST file");
7441 Error("declaration ID out-of-range for AST file");
7445 return DeclsLoaded[Index];
7448 Decl *ASTReader::GetDecl(DeclID ID) {
7449 if (ID < NUM_PREDEF_DECL_IDS)
7450 return GetExistingDecl(ID);
7452 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7454 if (Index >= DeclsLoaded.size()) {
7455 assert(0 && "declaration ID out-of-range for AST file");
7456 Error("declaration ID out-of-range for AST file");
7460 if (!DeclsLoaded[Index]) {
7462 if (DeserializationListener)
7463 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
7466 return DeclsLoaded[Index];
7469 DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
7471 if (GlobalID < NUM_PREDEF_DECL_IDS)
7474 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
7475 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
7476 ModuleFile *Owner = I->second;
7478 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
7479 = M.GlobalToLocalDeclIDs.find(Owner);
7480 if (Pos == M.GlobalToLocalDeclIDs.end())
7483 return GlobalID - Owner->BaseDeclID + Pos->second;
7486 serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
7487 const RecordData &Record,
7489 if (Idx >= Record.size()) {
7490 Error("Corrupted AST file");
7494 return getGlobalDeclID(F, Record[Idx++]);
7497 /// Resolve the offset of a statement into a statement.
7499 /// This operation will read a new statement from the external
7500 /// source each time it is called, and is meant to be used via a
7501 /// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
7502 Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
7503 // Switch case IDs are per Decl.
7504 ClearSwitchCaseIDs();
7506 // Offset here is a global offset across the entire chain.
7507 RecordLocation Loc = getLocalBitOffset(Offset);
7508 if (llvm::Error Err = Loc.F->DeclsCursor.JumpToBit(Loc.Offset)) {
7509 Error(std::move(Err));
7512 assert(NumCurrentElementsDeserializing == 0 &&
7513 "should not be called while already deserializing");
7514 Deserializing D(this);
7515 return ReadStmtFromStream(*Loc.F);
7518 void ASTReader::FindExternalLexicalDecls(
7519 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
7520 SmallVectorImpl<Decl *> &Decls) {
7521 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
7523 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
7524 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
7525 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
7526 auto K = (Decl::Kind)+LexicalDecls[I];
7527 if (!IsKindWeWant(K))
7530 auto ID = (serialization::DeclID)+LexicalDecls[I + 1];
7532 // Don't add predefined declarations to the lexical context more
7534 if (ID < NUM_PREDEF_DECL_IDS) {
7535 if (PredefsVisited[ID])
7538 PredefsVisited[ID] = true;
7541 if (Decl *D = GetLocalDecl(*M, ID)) {
7542 assert(D->getKind() == K && "wrong kind for lexical decl");
7543 if (!DC->isDeclInLexicalTraversal(D))
7549 if (isa<TranslationUnitDecl>(DC)) {
7550 for (auto Lexical : TULexicalDecls)
7551 Visit(Lexical.first, Lexical.second);
7553 auto I = LexicalDecls.find(DC);
7554 if (I != LexicalDecls.end())
7555 Visit(I->second.first, I->second.second);
7558 ++NumLexicalDeclContextsRead;
7568 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
7570 bool operator()(LocalDeclID L, LocalDeclID R) const {
7571 SourceLocation LHS = getLocation(L);
7572 SourceLocation RHS = getLocation(R);
7573 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7576 bool operator()(SourceLocation LHS, LocalDeclID R) const {
7577 SourceLocation RHS = getLocation(R);
7578 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7581 bool operator()(LocalDeclID L, SourceLocation RHS) const {
7582 SourceLocation LHS = getLocation(L);
7583 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7586 SourceLocation getLocation(LocalDeclID ID) const {
7587 return Reader.getSourceManager().getFileLoc(
7588 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
7594 void ASTReader::FindFileRegionDecls(FileID File,
7595 unsigned Offset, unsigned Length,
7596 SmallVectorImpl<Decl *> &Decls) {
7597 SourceManager &SM = getSourceManager();
7599 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
7600 if (I == FileDeclIDs.end())
7603 FileDeclsInfo &DInfo = I->second;
7604 if (DInfo.Decls.empty())
7608 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
7609 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
7611 DeclIDComp DIDComp(*this, *DInfo.Mod);
7612 ArrayRef<serialization::LocalDeclID>::iterator BeginIt =
7613 llvm::lower_bound(DInfo.Decls, BeginLoc, DIDComp);
7614 if (BeginIt != DInfo.Decls.begin())
7617 // If we are pointing at a top-level decl inside an objc container, we need
7618 // to backtrack until we find it otherwise we will fail to report that the
7619 // region overlaps with an objc container.
7620 while (BeginIt != DInfo.Decls.begin() &&
7621 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
7622 ->isTopLevelDeclInObjCContainer())
7625 ArrayRef<serialization::LocalDeclID>::iterator EndIt =
7626 llvm::upper_bound(DInfo.Decls, EndLoc, DIDComp);
7627 if (EndIt != DInfo.Decls.end())
7630 for (ArrayRef<serialization::LocalDeclID>::iterator
7631 DIt = BeginIt; DIt != EndIt; ++DIt)
7632 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
7636 ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
7637 DeclarationName Name) {
7638 assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
7639 "DeclContext has no visible decls in storage");
7643 auto It = Lookups.find(DC);
7644 if (It == Lookups.end())
7647 Deserializing LookupResults(this);
7649 // Load the list of declarations.
7650 SmallVector<NamedDecl *, 64> Decls;
7651 llvm::SmallPtrSet<NamedDecl *, 8> Found;
7652 for (DeclID ID : It->second.Table.find(Name)) {
7653 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
7654 if (ND->getDeclName() == Name && Found.insert(ND).second)
7655 Decls.push_back(ND);
7658 ++NumVisibleDeclContextsRead;
7659 SetExternalVisibleDeclsForName(DC, Name, Decls);
7660 return !Decls.empty();
7663 void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
7664 if (!DC->hasExternalVisibleStorage())
7667 auto It = Lookups.find(DC);
7668 assert(It != Lookups.end() &&
7669 "have external visible storage but no lookup tables");
7673 for (DeclID ID : It->second.Table.findAll()) {
7674 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
7675 Decls[ND->getDeclName()].push_back(ND);
7678 ++NumVisibleDeclContextsRead;
7680 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
7681 SetExternalVisibleDeclsForName(DC, I->first, I->second);
7683 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
7686 const serialization::reader::DeclContextLookupTable *
7687 ASTReader::getLoadedLookupTables(DeclContext *Primary) const {
7688 auto I = Lookups.find(Primary);
7689 return I == Lookups.end() ? nullptr : &I->second;
7692 /// Under non-PCH compilation the consumer receives the objc methods
7693 /// before receiving the implementation, and codegen depends on this.
7694 /// We simulate this by deserializing and passing to consumer the methods of the
7695 /// implementation before passing the deserialized implementation decl.
7696 static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
7697 ASTConsumer *Consumer) {
7698 assert(ImplD && Consumer);
7700 for (auto *I : ImplD->methods())
7701 Consumer->HandleInterestingDecl(DeclGroupRef(I));
7703 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
7706 void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
7707 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
7708 PassObjCImplDeclToConsumer(ImplD, Consumer);
7710 Consumer->HandleInterestingDecl(DeclGroupRef(D));
7713 void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
7714 this->Consumer = Consumer;
7717 PassInterestingDeclsToConsumer();
7719 if (DeserializationListener)
7720 DeserializationListener->ReaderInitialized(this);
7723 void ASTReader::PrintStats() {
7724 std::fprintf(stderr, "*** AST File Statistics:\n");
7726 unsigned NumTypesLoaded =
7727 TypesLoaded.size() - llvm::count(TypesLoaded, QualType());
7728 unsigned NumDeclsLoaded =
7729 DeclsLoaded.size() - llvm::count(DeclsLoaded, (Decl *)nullptr);
7730 unsigned NumIdentifiersLoaded =
7731 IdentifiersLoaded.size() -
7732 llvm::count(IdentifiersLoaded, (IdentifierInfo *)nullptr);
7733 unsigned NumMacrosLoaded =
7734 MacrosLoaded.size() - llvm::count(MacrosLoaded, (MacroInfo *)nullptr);
7735 unsigned NumSelectorsLoaded =
7736 SelectorsLoaded.size() - llvm::count(SelectorsLoaded, Selector());
7738 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
7739 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
7740 NumSLocEntriesRead, TotalNumSLocEntries,
7741 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
7742 if (!TypesLoaded.empty())
7743 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
7744 NumTypesLoaded, (unsigned)TypesLoaded.size(),
7745 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
7746 if (!DeclsLoaded.empty())
7747 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
7748 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
7749 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
7750 if (!IdentifiersLoaded.empty())
7751 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
7752 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
7753 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
7754 if (!MacrosLoaded.empty())
7755 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
7756 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
7757 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
7758 if (!SelectorsLoaded.empty())
7759 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
7760 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
7761 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
7762 if (TotalNumStatements)
7763 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
7764 NumStatementsRead, TotalNumStatements,
7765 ((float)NumStatementsRead/TotalNumStatements * 100));
7767 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
7768 NumMacrosRead, TotalNumMacros,
7769 ((float)NumMacrosRead/TotalNumMacros * 100));
7770 if (TotalLexicalDeclContexts)
7771 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
7772 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
7773 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
7775 if (TotalVisibleDeclContexts)
7776 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
7777 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
7778 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
7780 if (TotalNumMethodPoolEntries)
7781 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
7782 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
7783 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
7785 if (NumMethodPoolLookups)
7786 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
7787 NumMethodPoolHits, NumMethodPoolLookups,
7788 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
7789 if (NumMethodPoolTableLookups)
7790 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
7791 NumMethodPoolTableHits, NumMethodPoolTableLookups,
7792 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
7794 if (NumIdentifierLookupHits)
7795 std::fprintf(stderr,
7796 " %u / %u identifier table lookups succeeded (%f%%)\n",
7797 NumIdentifierLookupHits, NumIdentifierLookups,
7798 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
7801 std::fprintf(stderr, "\n");
7802 GlobalIndex->printStats();
7805 std::fprintf(stderr, "\n");
7807 std::fprintf(stderr, "\n");
7810 template<typename Key, typename ModuleFile, unsigned InitialCapacity>
7811 LLVM_DUMP_METHOD static void
7812 dumpModuleIDMap(StringRef Name,
7813 const ContinuousRangeMap<Key, ModuleFile *,
7814 InitialCapacity> &Map) {
7815 if (Map.begin() == Map.end())
7818 using MapType = ContinuousRangeMap<Key, ModuleFile *, InitialCapacity>;
7820 llvm::errs() << Name << ":\n";
7821 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
7823 llvm::errs() << " " << I->first << " -> " << I->second->FileName
7828 LLVM_DUMP_METHOD void ASTReader::dump() {
7829 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
7830 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
7831 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
7832 dumpModuleIDMap("Global type map", GlobalTypeMap);
7833 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
7834 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
7835 dumpModuleIDMap("Global macro map", GlobalMacroMap);
7836 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
7837 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
7838 dumpModuleIDMap("Global preprocessed entity map",
7839 GlobalPreprocessedEntityMap);
7841 llvm::errs() << "\n*** PCH/Modules Loaded:";
7842 for (ModuleFile &M : ModuleMgr)
7846 /// Return the amount of memory used by memory buffers, breaking down
7847 /// by heap-backed versus mmap'ed memory.
7848 void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
7849 for (ModuleFile &I : ModuleMgr) {
7850 if (llvm::MemoryBuffer *buf = I.Buffer) {
7851 size_t bytes = buf->getBufferSize();
7852 switch (buf->getBufferKind()) {
7853 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
7854 sizes.malloc_bytes += bytes;
7856 case llvm::MemoryBuffer::MemoryBuffer_MMap:
7857 sizes.mmap_bytes += bytes;
7864 void ASTReader::InitializeSema(Sema &S) {
7866 S.addExternalSource(this);
7868 // Makes sure any declarations that were deserialized "too early"
7869 // still get added to the identifier's declaration chains.
7870 for (uint64_t ID : PreloadedDeclIDs) {
7871 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
7872 pushExternalDeclIntoScope(D, D->getDeclName());
7874 PreloadedDeclIDs.clear();
7876 // FIXME: What happens if these are changed by a module import?
7877 if (!FPPragmaOptions.empty()) {
7878 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
7879 FPOptionsOverride NewOverrides =
7880 FPOptionsOverride::getFromOpaqueInt(FPPragmaOptions[0]);
7881 SemaObj->CurFPFeatures =
7882 NewOverrides.applyOverrides(SemaObj->getLangOpts());
7885 SemaObj->OpenCLFeatures = OpenCLExtensions;
7890 void ASTReader::UpdateSema() {
7891 assert(SemaObj && "no Sema to update");
7893 // Load the offsets of the declarations that Sema references.
7894 // They will be lazily deserialized when needed.
7895 if (!SemaDeclRefs.empty()) {
7896 assert(SemaDeclRefs.size() % 3 == 0);
7897 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 3) {
7898 if (!SemaObj->StdNamespace)
7899 SemaObj->StdNamespace = SemaDeclRefs[I];
7900 if (!SemaObj->StdBadAlloc)
7901 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
7902 if (!SemaObj->StdAlignValT)
7903 SemaObj->StdAlignValT = SemaDeclRefs[I+2];
7905 SemaDeclRefs.clear();
7908 // Update the state of pragmas. Use the same API as if we had encountered the
7909 // pragma in the source.
7910 if(OptimizeOffPragmaLocation.isValid())
7911 SemaObj->ActOnPragmaOptimize(/* On = */ false, OptimizeOffPragmaLocation);
7912 if (PragmaMSStructState != -1)
7913 SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState);
7914 if (PointersToMembersPragmaLocation.isValid()) {
7915 SemaObj->ActOnPragmaMSPointersToMembers(
7916 (LangOptions::PragmaMSPointersToMembersKind)
7917 PragmaMSPointersToMembersState,
7918 PointersToMembersPragmaLocation);
7920 SemaObj->ForceCUDAHostDeviceDepth = ForceCUDAHostDeviceDepth;
7922 if (PragmaAlignPackCurrentValue) {
7923 // The bottom of the stack might have a default value. It must be adjusted
7924 // to the current value to ensure that the packing state is preserved after
7925 // popping entries that were included/imported from a PCH/module.
7926 bool DropFirst = false;
7927 if (!PragmaAlignPackStack.empty() &&
7928 PragmaAlignPackStack.front().Location.isInvalid()) {
7929 assert(PragmaAlignPackStack.front().Value ==
7930 SemaObj->AlignPackStack.DefaultValue &&
7931 "Expected a default alignment value");
7932 SemaObj->AlignPackStack.Stack.emplace_back(
7933 PragmaAlignPackStack.front().SlotLabel,
7934 SemaObj->AlignPackStack.CurrentValue,
7935 SemaObj->AlignPackStack.CurrentPragmaLocation,
7936 PragmaAlignPackStack.front().PushLocation);
7939 for (const auto &Entry : llvm::makeArrayRef(PragmaAlignPackStack)
7940 .drop_front(DropFirst ? 1 : 0)) {
7941 SemaObj->AlignPackStack.Stack.emplace_back(
7942 Entry.SlotLabel, Entry.Value, Entry.Location, Entry.PushLocation);
7944 if (PragmaAlignPackCurrentLocation.isInvalid()) {
7945 assert(*PragmaAlignPackCurrentValue ==
7946 SemaObj->AlignPackStack.DefaultValue &&
7947 "Expected a default align and pack value");
7948 // Keep the current values.
7950 SemaObj->AlignPackStack.CurrentValue = *PragmaAlignPackCurrentValue;
7951 SemaObj->AlignPackStack.CurrentPragmaLocation =
7952 PragmaAlignPackCurrentLocation;
7955 if (FpPragmaCurrentValue) {
7956 // The bottom of the stack might have a default value. It must be adjusted
7957 // to the current value to ensure that fp-pragma state is preserved after
7958 // popping entries that were included/imported from a PCH/module.
7959 bool DropFirst = false;
7960 if (!FpPragmaStack.empty() && FpPragmaStack.front().Location.isInvalid()) {
7961 assert(FpPragmaStack.front().Value ==
7962 SemaObj->FpPragmaStack.DefaultValue &&
7963 "Expected a default pragma float_control value");
7964 SemaObj->FpPragmaStack.Stack.emplace_back(
7965 FpPragmaStack.front().SlotLabel, SemaObj->FpPragmaStack.CurrentValue,
7966 SemaObj->FpPragmaStack.CurrentPragmaLocation,
7967 FpPragmaStack.front().PushLocation);
7970 for (const auto &Entry :
7971 llvm::makeArrayRef(FpPragmaStack).drop_front(DropFirst ? 1 : 0))
7972 SemaObj->FpPragmaStack.Stack.emplace_back(
7973 Entry.SlotLabel, Entry.Value, Entry.Location, Entry.PushLocation);
7974 if (FpPragmaCurrentLocation.isInvalid()) {
7975 assert(*FpPragmaCurrentValue == SemaObj->FpPragmaStack.DefaultValue &&
7976 "Expected a default pragma float_control value");
7977 // Keep the current values.
7979 SemaObj->FpPragmaStack.CurrentValue = *FpPragmaCurrentValue;
7980 SemaObj->FpPragmaStack.CurrentPragmaLocation = FpPragmaCurrentLocation;
7984 // For non-modular AST files, restore visiblity of modules.
7985 for (auto &Import : ImportedModules) {
7986 if (Import.ImportLoc.isInvalid())
7988 if (Module *Imported = getSubmodule(Import.ID)) {
7989 SemaObj->makeModuleVisible(Imported, Import.ImportLoc);
7994 IdentifierInfo *ASTReader::get(StringRef Name) {
7995 // Note that we are loading an identifier.
7996 Deserializing AnIdentifier(this);
7998 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
7999 NumIdentifierLookups,
8000 NumIdentifierLookupHits);
8002 // We don't need to do identifier table lookups in C++ modules (we preload
8003 // all interesting declarations, and don't need to use the scope for name
8004 // lookups). Perform the lookup in PCH files, though, since we don't build
8005 // a complete initial identifier table if we're carrying on from a PCH.
8006 if (PP.getLangOpts().CPlusPlus) {
8007 for (auto F : ModuleMgr.pch_modules())
8011 // If there is a global index, look there first to determine which modules
8012 // provably do not have any results for this identifier.
8013 GlobalModuleIndex::HitSet Hits;
8014 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
8015 if (!loadGlobalIndex()) {
8016 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
8021 ModuleMgr.visit(Visitor, HitsPtr);
8024 IdentifierInfo *II = Visitor.getIdentifierInfo();
8025 markIdentifierUpToDate(II);
8031 /// An identifier-lookup iterator that enumerates all of the
8032 /// identifiers stored within a set of AST files.
8033 class ASTIdentifierIterator : public IdentifierIterator {
8034 /// The AST reader whose identifiers are being enumerated.
8035 const ASTReader &Reader;
8037 /// The current index into the chain of AST files stored in
8041 /// The current position within the identifier lookup table
8042 /// of the current AST file.
8043 ASTIdentifierLookupTable::key_iterator Current;
8045 /// The end position within the identifier lookup table of
8046 /// the current AST file.
8047 ASTIdentifierLookupTable::key_iterator End;
8049 /// Whether to skip any modules in the ASTReader.
8053 explicit ASTIdentifierIterator(const ASTReader &Reader,
8054 bool SkipModules = false);
8056 StringRef Next() override;
8059 } // namespace clang
8061 ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader,
8063 : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) {
8066 StringRef ASTIdentifierIterator::Next() {
8067 while (Current == End) {
8068 // If we have exhausted all of our AST files, we're done.
8073 ModuleFile &F = Reader.ModuleMgr[Index];
8074 if (SkipModules && F.isModule())
8077 ASTIdentifierLookupTable *IdTable =
8078 (ASTIdentifierLookupTable *)F.IdentifierLookupTable;
8079 Current = IdTable->key_begin();
8080 End = IdTable->key_end();
8083 // We have any identifiers remaining in the current AST file; return
8085 StringRef Result = *Current;
8092 /// A utility for appending two IdentifierIterators.
8093 class ChainedIdentifierIterator : public IdentifierIterator {
8094 std::unique_ptr<IdentifierIterator> Current;
8095 std::unique_ptr<IdentifierIterator> Queued;
8098 ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First,
8099 std::unique_ptr<IdentifierIterator> Second)
8100 : Current(std::move(First)), Queued(std::move(Second)) {}
8102 StringRef Next() override {
8106 StringRef result = Current->Next();
8107 if (!result.empty())
8110 // Try the queued iterator, which may itself be empty.
8112 std::swap(Current, Queued);
8119 IdentifierIterator *ASTReader::getIdentifiers() {
8120 if (!loadGlobalIndex()) {
8121 std::unique_ptr<IdentifierIterator> ReaderIter(
8122 new ASTIdentifierIterator(*this, /*SkipModules=*/true));
8123 std::unique_ptr<IdentifierIterator> ModulesIter(
8124 GlobalIndex->createIdentifierIterator());
8125 return new ChainedIdentifierIterator(std::move(ReaderIter),
8126 std::move(ModulesIter));
8129 return new ASTIdentifierIterator(*this);
8133 namespace serialization {
8135 class ReadMethodPoolVisitor {
8138 unsigned PriorGeneration;
8139 unsigned InstanceBits = 0;
8140 unsigned FactoryBits = 0;
8141 bool InstanceHasMoreThanOneDecl = false;
8142 bool FactoryHasMoreThanOneDecl = false;
8143 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
8144 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
8147 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
8148 unsigned PriorGeneration)
8149 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration) {}
8151 bool operator()(ModuleFile &M) {
8152 if (!M.SelectorLookupTable)
8155 // If we've already searched this module file, skip it now.
8156 if (M.Generation <= PriorGeneration)
8159 ++Reader.NumMethodPoolTableLookups;
8160 ASTSelectorLookupTable *PoolTable
8161 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
8162 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
8163 if (Pos == PoolTable->end())
8166 ++Reader.NumMethodPoolTableHits;
8167 ++Reader.NumSelectorsRead;
8168 // FIXME: Not quite happy with the statistics here. We probably should
8169 // disable this tracking when called via LoadSelector.
8170 // Also, should entries without methods count as misses?
8171 ++Reader.NumMethodPoolEntriesRead;
8172 ASTSelectorLookupTrait::data_type Data = *Pos;
8173 if (Reader.DeserializationListener)
8174 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
8176 // Append methods in the reverse order, so that later we can process them
8177 // in the order they appear in the source code by iterating through
8178 // the vector in the reverse order.
8179 InstanceMethods.append(Data.Instance.rbegin(), Data.Instance.rend());
8180 FactoryMethods.append(Data.Factory.rbegin(), Data.Factory.rend());
8181 InstanceBits = Data.InstanceBits;
8182 FactoryBits = Data.FactoryBits;
8183 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
8184 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
8188 /// Retrieve the instance methods found by this visitor.
8189 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
8190 return InstanceMethods;
8193 /// Retrieve the instance methods found by this visitor.
8194 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
8195 return FactoryMethods;
8198 unsigned getInstanceBits() const { return InstanceBits; }
8199 unsigned getFactoryBits() const { return FactoryBits; }
8201 bool instanceHasMoreThanOneDecl() const {
8202 return InstanceHasMoreThanOneDecl;
8205 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
8208 } // namespace serialization
8209 } // namespace clang
8211 /// Add the given set of methods to the method list.
8212 static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
8213 ObjCMethodList &List) {
8214 for (auto I = Methods.rbegin(), E = Methods.rend(); I != E; ++I)
8215 S.addMethodToGlobalList(&List, *I);
8218 void ASTReader::ReadMethodPool(Selector Sel) {
8219 // Get the selector generation and update it to the current generation.
8220 unsigned &Generation = SelectorGeneration[Sel];
8221 unsigned PriorGeneration = Generation;
8222 Generation = getGeneration();
8223 SelectorOutOfDate[Sel] = false;
8225 // Search for methods defined with this selector.
8226 ++NumMethodPoolLookups;
8227 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
8228 ModuleMgr.visit(Visitor);
8230 if (Visitor.getInstanceMethods().empty() &&
8231 Visitor.getFactoryMethods().empty())
8234 ++NumMethodPoolHits;
8239 Sema &S = *getSema();
8240 Sema::GlobalMethodPool::iterator Pos =
8241 S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethodPool::Lists()))
8244 Pos->second.first.setBits(Visitor.getInstanceBits());
8245 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
8246 Pos->second.second.setBits(Visitor.getFactoryBits());
8247 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
8249 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
8250 // when building a module we keep every method individually and may need to
8251 // update hasMoreThanOneDecl as we add the methods.
8252 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
8253 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
8256 void ASTReader::updateOutOfDateSelector(Selector Sel) {
8257 if (SelectorOutOfDate[Sel])
8258 ReadMethodPool(Sel);
8261 void ASTReader::ReadKnownNamespaces(
8262 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
8265 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
8266 if (NamespaceDecl *Namespace
8267 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
8268 Namespaces.push_back(Namespace);
8272 void ASTReader::ReadUndefinedButUsed(
8273 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {
8274 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
8275 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
8276 SourceLocation Loc =
8277 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
8278 Undefined.insert(std::make_pair(D, Loc));
8282 void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
8283 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
8285 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
8286 FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
8287 uint64_t Count = DelayedDeleteExprs[Idx++];
8288 for (uint64_t C = 0; C < Count; ++C) {
8289 SourceLocation DeleteLoc =
8290 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
8291 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
8292 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
8297 void ASTReader::ReadTentativeDefinitions(
8298 SmallVectorImpl<VarDecl *> &TentativeDefs) {
8299 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
8300 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
8302 TentativeDefs.push_back(Var);
8304 TentativeDefinitions.clear();
8307 void ASTReader::ReadUnusedFileScopedDecls(
8308 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
8309 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
8311 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
8315 UnusedFileScopedDecls.clear();
8318 void ASTReader::ReadDelegatingConstructors(
8319 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
8320 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
8321 CXXConstructorDecl *D
8322 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
8326 DelegatingCtorDecls.clear();
8329 void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
8330 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
8332 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
8336 ExtVectorDecls.clear();
8339 void ASTReader::ReadUnusedLocalTypedefNameCandidates(
8340 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
8341 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
8343 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
8344 GetDecl(UnusedLocalTypedefNameCandidates[I]));
8348 UnusedLocalTypedefNameCandidates.clear();
8351 void ASTReader::ReadDeclsToCheckForDeferredDiags(
8352 llvm::SmallSetVector<Decl *, 4> &Decls) {
8353 for (auto I : DeclsToCheckForDeferredDiags) {
8354 auto *D = dyn_cast_or_null<Decl>(GetDecl(I));
8358 DeclsToCheckForDeferredDiags.clear();
8361 void ASTReader::ReadReferencedSelectors(
8362 SmallVectorImpl<std::pair<Selector, SourceLocation>> &Sels) {
8363 if (ReferencedSelectorsData.empty())
8366 // If there are @selector references added them to its pool. This is for
8367 // implementation of -Wselector.
8368 unsigned int DataSize = ReferencedSelectorsData.size()-1;
8370 while (I < DataSize) {
8371 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
8372 SourceLocation SelLoc
8373 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
8374 Sels.push_back(std::make_pair(Sel, SelLoc));
8376 ReferencedSelectorsData.clear();
8379 void ASTReader::ReadWeakUndeclaredIdentifiers(
8380 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo>> &WeakIDs) {
8381 if (WeakUndeclaredIdentifiers.empty())
8384 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
8385 IdentifierInfo *WeakId
8386 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
8387 IdentifierInfo *AliasId
8388 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
8390 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
8391 bool Used = WeakUndeclaredIdentifiers[I++];
8392 WeakInfo WI(AliasId, Loc);
8394 WeakIDs.push_back(std::make_pair(WeakId, WI));
8396 WeakUndeclaredIdentifiers.clear();
8399 void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
8400 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
8401 ExternalVTableUse VT;
8402 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
8403 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
8404 VT.DefinitionRequired = VTableUses[Idx++];
8405 VTables.push_back(VT);
8411 void ASTReader::ReadPendingInstantiations(
8412 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation>> &Pending) {
8413 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
8414 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
8416 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
8418 Pending.push_back(std::make_pair(D, Loc));
8420 PendingInstantiations.clear();
8423 void ASTReader::ReadLateParsedTemplates(
8424 llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>>
8426 for (auto &LPT : LateParsedTemplates) {
8427 ModuleFile *FMod = LPT.first;
8428 RecordDataImpl &LateParsed = LPT.second;
8429 for (unsigned Idx = 0, N = LateParsed.size(); Idx < N;
8432 cast<FunctionDecl>(GetLocalDecl(*FMod, LateParsed[Idx++]));
8434 auto LT = std::make_unique<LateParsedTemplate>();
8435 LT->D = GetLocalDecl(*FMod, LateParsed[Idx++]);
8437 ModuleFile *F = getOwningModuleFile(LT->D);
8438 assert(F && "No module");
8440 unsigned TokN = LateParsed[Idx++];
8441 LT->Toks.reserve(TokN);
8442 for (unsigned T = 0; T < TokN; ++T)
8443 LT->Toks.push_back(ReadToken(*F, LateParsed, Idx));
8445 LPTMap.insert(std::make_pair(FD, std::move(LT)));
8449 LateParsedTemplates.clear();
8452 void ASTReader::LoadSelector(Selector Sel) {
8453 // It would be complicated to avoid reading the methods anyway. So don't.
8454 ReadMethodPool(Sel);
8457 void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
8458 assert(ID && "Non-zero identifier ID required");
8459 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
8460 IdentifiersLoaded[ID - 1] = II;
8461 if (DeserializationListener)
8462 DeserializationListener->IdentifierRead(ID, II);
8465 /// Set the globally-visible declarations associated with the given
8468 /// If the AST reader is currently in a state where the given declaration IDs
8469 /// cannot safely be resolved, they are queued until it is safe to resolve
8472 /// \param II an IdentifierInfo that refers to one or more globally-visible
8475 /// \param DeclIDs the set of declaration IDs with the name @p II that are
8476 /// visible at global scope.
8478 /// \param Decls if non-null, this vector will be populated with the set of
8479 /// deserialized declarations. These declarations will not be pushed into
8482 ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
8483 const SmallVectorImpl<uint32_t> &DeclIDs,
8484 SmallVectorImpl<Decl *> *Decls) {
8485 if (NumCurrentElementsDeserializing && !Decls) {
8486 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
8490 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
8492 // Queue this declaration so that it will be added to the
8493 // translation unit scope and identifier's declaration chain
8494 // once a Sema object is known.
8495 PreloadedDeclIDs.push_back(DeclIDs[I]);
8499 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
8501 // If we're simply supposed to record the declarations, do so now.
8503 Decls->push_back(D);
8507 // Introduce this declaration into the translation-unit scope
8508 // and add it to the declaration chain for this identifier, so
8509 // that (unqualified) name lookup will find it.
8510 pushExternalDeclIntoScope(D, II);
8514 IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
8518 if (IdentifiersLoaded.empty()) {
8519 Error("no identifier table in AST file");
8524 if (!IdentifiersLoaded[ID]) {
8525 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
8526 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
8527 ModuleFile *M = I->second;
8528 unsigned Index = ID - M->BaseIdentifierID;
8529 const unsigned char *Data =
8530 M->IdentifierTableData + M->IdentifierOffsets[Index];
8532 ASTIdentifierLookupTrait Trait(*this, *M);
8533 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
8534 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
8535 auto &II = PP.getIdentifierTable().get(Key);
8536 IdentifiersLoaded[ID] = &II;
8537 markIdentifierFromAST(*this, II);
8538 if (DeserializationListener)
8539 DeserializationListener->IdentifierRead(ID + 1, &II);
8542 return IdentifiersLoaded[ID];
8545 IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
8546 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
8549 IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
8550 if (LocalID < NUM_PREDEF_IDENT_IDS)
8553 if (!M.ModuleOffsetMap.empty())
8554 ReadModuleOffsetMap(M);
8556 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8557 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
8558 assert(I != M.IdentifierRemap.end()
8559 && "Invalid index into identifier index remap");
8561 return LocalID + I->second;
8564 MacroInfo *ASTReader::getMacro(MacroID ID) {
8568 if (MacrosLoaded.empty()) {
8569 Error("no macro table in AST file");
8573 ID -= NUM_PREDEF_MACRO_IDS;
8574 if (!MacrosLoaded[ID]) {
8575 GlobalMacroMapType::iterator I
8576 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
8577 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
8578 ModuleFile *M = I->second;
8579 unsigned Index = ID - M->BaseMacroID;
8581 ReadMacroRecord(*M, M->MacroOffsetsBase + M->MacroOffsets[Index]);
8583 if (DeserializationListener)
8584 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
8588 return MacrosLoaded[ID];
8591 MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
8592 if (LocalID < NUM_PREDEF_MACRO_IDS)
8595 if (!M.ModuleOffsetMap.empty())
8596 ReadModuleOffsetMap(M);
8598 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8599 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
8600 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
8602 return LocalID + I->second;
8605 serialization::SubmoduleID
8606 ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
8607 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
8610 if (!M.ModuleOffsetMap.empty())
8611 ReadModuleOffsetMap(M);
8613 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8614 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
8615 assert(I != M.SubmoduleRemap.end()
8616 && "Invalid index into submodule index remap");
8618 return LocalID + I->second;
8621 Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
8622 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
8623 assert(GlobalID == 0 && "Unhandled global submodule ID");
8627 if (GlobalID > SubmodulesLoaded.size()) {
8628 Error("submodule ID out of range in AST file");
8632 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
8635 Module *ASTReader::getModule(unsigned ID) {
8636 return getSubmodule(ID);
8639 ModuleFile *ASTReader::getLocalModuleFile(ModuleFile &F, unsigned ID) {
8641 // It's a module, look it up by submodule ID.
8642 auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(F, ID >> 1));
8643 return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
8645 // It's a prefix (preamble, PCH, ...). Look it up by index.
8646 unsigned IndexFromEnd = ID >> 1;
8647 assert(IndexFromEnd && "got reference to unknown module file");
8648 return getModuleManager().pch_modules().end()[-IndexFromEnd];
8652 unsigned ASTReader::getModuleFileID(ModuleFile *F) {
8656 // For a file representing a module, use the submodule ID of the top-level
8657 // module as the file ID. For any other kind of file, the number of such
8658 // files loaded beforehand will be the same on reload.
8659 // FIXME: Is this true even if we have an explicit module file and a PCH?
8661 return ((F->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
8663 auto PCHModules = getModuleManager().pch_modules();
8664 auto I = llvm::find(PCHModules, F);
8665 assert(I != PCHModules.end() && "emitting reference to unknown file");
8666 return (I - PCHModules.end()) << 1;
8669 llvm::Optional<ASTSourceDescriptor>
8670 ASTReader::getSourceDescriptor(unsigned ID) {
8671 if (Module *M = getSubmodule(ID))
8672 return ASTSourceDescriptor(*M);
8674 // If there is only a single PCH, return it instead.
8675 // Chained PCH are not supported.
8676 const auto &PCHChain = ModuleMgr.pch_modules();
8677 if (std::distance(std::begin(PCHChain), std::end(PCHChain))) {
8678 ModuleFile &MF = ModuleMgr.getPrimaryModule();
8679 StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName);
8680 StringRef FileName = llvm::sys::path::filename(MF.FileName);
8681 return ASTSourceDescriptor(ModuleName, MF.OriginalDir, FileName,
8687 ExternalASTSource::ExtKind ASTReader::hasExternalDefinitions(const Decl *FD) {
8688 auto I = DefinitionSource.find(FD);
8689 if (I == DefinitionSource.end())
8690 return EK_ReplyHazy;
8691 return I->second ? EK_Never : EK_Always;
8694 Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
8695 return DecodeSelector(getGlobalSelectorID(M, LocalID));
8698 Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
8702 if (ID > SelectorsLoaded.size()) {
8703 Error("selector ID out of range in AST file");
8707 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
8708 // Load this selector from the selector table.
8709 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
8710 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
8711 ModuleFile &M = *I->second;
8712 ASTSelectorLookupTrait Trait(*this, M);
8713 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
8714 SelectorsLoaded[ID - 1] =
8715 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
8716 if (DeserializationListener)
8717 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
8720 return SelectorsLoaded[ID - 1];
8723 Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
8724 return DecodeSelector(ID);
8727 uint32_t ASTReader::GetNumExternalSelectors() {
8728 // ID 0 (the null selector) is considered an external selector.
8729 return getTotalNumSelectors() + 1;
8732 serialization::SelectorID
8733 ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
8734 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
8737 if (!M.ModuleOffsetMap.empty())
8738 ReadModuleOffsetMap(M);
8740 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8741 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
8742 assert(I != M.SelectorRemap.end()
8743 && "Invalid index into selector index remap");
8745 return LocalID + I->second;
8749 ASTRecordReader::readDeclarationNameLoc(DeclarationName Name) {
8750 switch (Name.getNameKind()) {
8751 case DeclarationName::CXXConstructorName:
8752 case DeclarationName::CXXDestructorName:
8753 case DeclarationName::CXXConversionFunctionName:
8754 return DeclarationNameLoc::makeNamedTypeLoc(readTypeSourceInfo());
8756 case DeclarationName::CXXOperatorName:
8757 return DeclarationNameLoc::makeCXXOperatorNameLoc(readSourceRange());
8759 case DeclarationName::CXXLiteralOperatorName:
8760 return DeclarationNameLoc::makeCXXLiteralOperatorNameLoc(
8761 readSourceLocation());
8763 case DeclarationName::Identifier:
8764 case DeclarationName::ObjCZeroArgSelector:
8765 case DeclarationName::ObjCOneArgSelector:
8766 case DeclarationName::ObjCMultiArgSelector:
8767 case DeclarationName::CXXUsingDirective:
8768 case DeclarationName::CXXDeductionGuideName:
8771 return DeclarationNameLoc();
8774 DeclarationNameInfo ASTRecordReader::readDeclarationNameInfo() {
8775 DeclarationNameInfo NameInfo;
8776 NameInfo.setName(readDeclarationName());
8777 NameInfo.setLoc(readSourceLocation());
8778 NameInfo.setInfo(readDeclarationNameLoc(NameInfo.getName()));
8782 void ASTRecordReader::readQualifierInfo(QualifierInfo &Info) {
8783 Info.QualifierLoc = readNestedNameSpecifierLoc();
8784 unsigned NumTPLists = readInt();
8785 Info.NumTemplParamLists = NumTPLists;
8787 Info.TemplParamLists =
8788 new (getContext()) TemplateParameterList *[NumTPLists];
8789 for (unsigned i = 0; i != NumTPLists; ++i)
8790 Info.TemplParamLists[i] = readTemplateParameterList();
8794 TemplateParameterList *
8795 ASTRecordReader::readTemplateParameterList() {
8796 SourceLocation TemplateLoc = readSourceLocation();
8797 SourceLocation LAngleLoc = readSourceLocation();
8798 SourceLocation RAngleLoc = readSourceLocation();
8800 unsigned NumParams = readInt();
8801 SmallVector<NamedDecl *, 16> Params;
8802 Params.reserve(NumParams);
8804 Params.push_back(readDeclAs<NamedDecl>());
8806 bool HasRequiresClause = readBool();
8807 Expr *RequiresClause = HasRequiresClause ? readExpr() : nullptr;
8809 TemplateParameterList *TemplateParams = TemplateParameterList::Create(
8810 getContext(), TemplateLoc, LAngleLoc, Params, RAngleLoc, RequiresClause);
8811 return TemplateParams;
8814 void ASTRecordReader::readTemplateArgumentList(
8815 SmallVectorImpl<TemplateArgument> &TemplArgs,
8816 bool Canonicalize) {
8817 unsigned NumTemplateArgs = readInt();
8818 TemplArgs.reserve(NumTemplateArgs);
8819 while (NumTemplateArgs--)
8820 TemplArgs.push_back(readTemplateArgument(Canonicalize));
8823 /// Read a UnresolvedSet structure.
8824 void ASTRecordReader::readUnresolvedSet(LazyASTUnresolvedSet &Set) {
8825 unsigned NumDecls = readInt();
8826 Set.reserve(getContext(), NumDecls);
8827 while (NumDecls--) {
8828 DeclID ID = readDeclID();
8829 AccessSpecifier AS = (AccessSpecifier) readInt();
8830 Set.addLazyDecl(getContext(), ID, AS);
8835 ASTRecordReader::readCXXBaseSpecifier() {
8836 bool isVirtual = readBool();
8837 bool isBaseOfClass = readBool();
8838 AccessSpecifier AS = static_cast<AccessSpecifier>(readInt());
8839 bool inheritConstructors = readBool();
8840 TypeSourceInfo *TInfo = readTypeSourceInfo();
8841 SourceRange Range = readSourceRange();
8842 SourceLocation EllipsisLoc = readSourceLocation();
8843 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
8845 Result.setInheritConstructors(inheritConstructors);
8849 CXXCtorInitializer **
8850 ASTRecordReader::readCXXCtorInitializers() {
8851 ASTContext &Context = getContext();
8852 unsigned NumInitializers = readInt();
8853 assert(NumInitializers && "wrote ctor initializers but have no inits");
8854 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
8855 for (unsigned i = 0; i != NumInitializers; ++i) {
8856 TypeSourceInfo *TInfo = nullptr;
8857 bool IsBaseVirtual = false;
8858 FieldDecl *Member = nullptr;
8859 IndirectFieldDecl *IndirectMember = nullptr;
8861 CtorInitializerType Type = (CtorInitializerType) readInt();
8863 case CTOR_INITIALIZER_BASE:
8864 TInfo = readTypeSourceInfo();
8865 IsBaseVirtual = readBool();
8868 case CTOR_INITIALIZER_DELEGATING:
8869 TInfo = readTypeSourceInfo();
8872 case CTOR_INITIALIZER_MEMBER:
8873 Member = readDeclAs<FieldDecl>();
8876 case CTOR_INITIALIZER_INDIRECT_MEMBER:
8877 IndirectMember = readDeclAs<IndirectFieldDecl>();
8881 SourceLocation MemberOrEllipsisLoc = readSourceLocation();
8882 Expr *Init = readExpr();
8883 SourceLocation LParenLoc = readSourceLocation();
8884 SourceLocation RParenLoc = readSourceLocation();
8886 CXXCtorInitializer *BOMInit;
8887 if (Type == CTOR_INITIALIZER_BASE)
8888 BOMInit = new (Context)
8889 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
8890 RParenLoc, MemberOrEllipsisLoc);
8891 else if (Type == CTOR_INITIALIZER_DELEGATING)
8892 BOMInit = new (Context)
8893 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
8895 BOMInit = new (Context)
8896 CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc, LParenLoc,
8899 BOMInit = new (Context)
8900 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
8901 LParenLoc, Init, RParenLoc);
8903 if (/*IsWritten*/readBool()) {
8904 unsigned SourceOrder = readInt();
8905 BOMInit->setSourceOrder(SourceOrder);
8908 CtorInitializers[i] = BOMInit;
8911 return CtorInitializers;
8914 NestedNameSpecifierLoc
8915 ASTRecordReader::readNestedNameSpecifierLoc() {
8916 ASTContext &Context = getContext();
8917 unsigned N = readInt();
8918 NestedNameSpecifierLocBuilder Builder;
8919 for (unsigned I = 0; I != N; ++I) {
8920 auto Kind = readNestedNameSpecifierKind();
8922 case NestedNameSpecifier::Identifier: {
8923 IdentifierInfo *II = readIdentifier();
8924 SourceRange Range = readSourceRange();
8925 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
8929 case NestedNameSpecifier::Namespace: {
8930 NamespaceDecl *NS = readDeclAs<NamespaceDecl>();
8931 SourceRange Range = readSourceRange();
8932 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
8936 case NestedNameSpecifier::NamespaceAlias: {
8937 NamespaceAliasDecl *Alias = readDeclAs<NamespaceAliasDecl>();
8938 SourceRange Range = readSourceRange();
8939 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
8943 case NestedNameSpecifier::TypeSpec:
8944 case NestedNameSpecifier::TypeSpecWithTemplate: {
8945 bool Template = readBool();
8946 TypeSourceInfo *T = readTypeSourceInfo();
8948 return NestedNameSpecifierLoc();
8949 SourceLocation ColonColonLoc = readSourceLocation();
8951 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
8952 Builder.Extend(Context,
8953 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
8954 T->getTypeLoc(), ColonColonLoc);
8958 case NestedNameSpecifier::Global: {
8959 SourceLocation ColonColonLoc = readSourceLocation();
8960 Builder.MakeGlobal(Context, ColonColonLoc);
8964 case NestedNameSpecifier::Super: {
8965 CXXRecordDecl *RD = readDeclAs<CXXRecordDecl>();
8966 SourceRange Range = readSourceRange();
8967 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
8973 return Builder.getWithLocInContext(Context);
8977 ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
8979 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
8980 SourceLocation end = ReadSourceLocation(F, Record, Idx);
8981 return SourceRange(beg, end);
8984 /// Read a floating-point value
8985 llvm::APFloat ASTRecordReader::readAPFloat(const llvm::fltSemantics &Sem) {
8986 return llvm::APFloat(Sem, readAPInt());
8990 std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
8991 unsigned Len = Record[Idx++];
8992 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
8997 std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
8999 std::string Filename = ReadString(Record, Idx);
9000 ResolveImportedPath(F, Filename);
9004 std::string ASTReader::ReadPath(StringRef BaseDirectory,
9005 const RecordData &Record, unsigned &Idx) {
9006 std::string Filename = ReadString(Record, Idx);
9007 if (!BaseDirectory.empty())
9008 ResolveImportedPath(Filename, BaseDirectory);
9012 VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
9014 unsigned Major = Record[Idx++];
9015 unsigned Minor = Record[Idx++];
9016 unsigned Subminor = Record[Idx++];
9018 return VersionTuple(Major);
9020 return VersionTuple(Major, Minor - 1);
9021 return VersionTuple(Major, Minor - 1, Subminor - 1);
9024 CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
9025 const RecordData &Record,
9027 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
9028 return CXXTemporary::Create(getContext(), Decl);
9031 DiagnosticBuilder ASTReader::Diag(unsigned DiagID) const {
9032 return Diag(CurrentImportLoc, DiagID);
9035 DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) const {
9036 return Diags.Report(Loc, DiagID);
9039 /// Retrieve the identifier table associated with the
9041 IdentifierTable &ASTReader::getIdentifierTable() {
9042 return PP.getIdentifierTable();
9045 /// Record that the given ID maps to the given switch-case
9047 void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
9048 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
9049 "Already have a SwitchCase with this ID");
9050 (*CurrSwitchCaseStmts)[ID] = SC;
9053 /// Retrieve the switch-case statement with the given ID.
9054 SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
9055 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
9056 return (*CurrSwitchCaseStmts)[ID];
9059 void ASTReader::ClearSwitchCaseIDs() {
9060 CurrSwitchCaseStmts->clear();
9063 void ASTReader::ReadComments() {
9064 ASTContext &Context = getContext();
9065 std::vector<RawComment *> Comments;
9066 for (SmallVectorImpl<std::pair<BitstreamCursor,
9067 serialization::ModuleFile *>>::iterator
9068 I = CommentsCursors.begin(),
9069 E = CommentsCursors.end();
9072 BitstreamCursor &Cursor = I->first;
9073 serialization::ModuleFile &F = *I->second;
9074 SavedStreamPosition SavedPosition(Cursor);
9078 Expected<llvm::BitstreamEntry> MaybeEntry =
9079 Cursor.advanceSkippingSubblocks(
9080 BitstreamCursor::AF_DontPopBlockAtEnd);
9082 Error(MaybeEntry.takeError());
9085 llvm::BitstreamEntry Entry = MaybeEntry.get();
9087 switch (Entry.Kind) {
9088 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
9089 case llvm::BitstreamEntry::Error:
9090 Error("malformed block record in AST file");
9092 case llvm::BitstreamEntry::EndBlock:
9094 case llvm::BitstreamEntry::Record:
9095 // The interesting case.
9101 Expected<unsigned> MaybeComment = Cursor.readRecord(Entry.ID, Record);
9102 if (!MaybeComment) {
9103 Error(MaybeComment.takeError());
9106 switch ((CommentRecordTypes)MaybeComment.get()) {
9107 case COMMENTS_RAW_COMMENT: {
9109 SourceRange SR = ReadSourceRange(F, Record, Idx);
9110 RawComment::CommentKind Kind =
9111 (RawComment::CommentKind) Record[Idx++];
9112 bool IsTrailingComment = Record[Idx++];
9113 bool IsAlmostTrailingComment = Record[Idx++];
9114 Comments.push_back(new (Context) RawComment(
9115 SR, Kind, IsTrailingComment, IsAlmostTrailingComment));
9121 llvm::DenseMap<FileID, std::map<unsigned, RawComment *>>
9122 FileToOffsetToComment;
9123 for (RawComment *C : Comments) {
9124 SourceLocation CommentLoc = C->getBeginLoc();
9125 if (CommentLoc.isValid()) {
9126 std::pair<FileID, unsigned> Loc =
9127 SourceMgr.getDecomposedLoc(CommentLoc);
9128 if (Loc.first.isValid())
9129 Context.Comments.OrderedComments[Loc.first].emplace(Loc.second, C);
9135 void ASTReader::visitInputFiles(serialization::ModuleFile &MF,
9136 bool IncludeSystem, bool Complain,
9137 llvm::function_ref<void(const serialization::InputFile &IF,
9138 bool isSystem)> Visitor) {
9139 unsigned NumUserInputs = MF.NumUserInputFiles;
9140 unsigned NumInputs = MF.InputFilesLoaded.size();
9141 assert(NumUserInputs <= NumInputs);
9142 unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
9143 for (unsigned I = 0; I < N; ++I) {
9144 bool IsSystem = I >= NumUserInputs;
9145 InputFile IF = getInputFile(MF, I+1, Complain);
9146 Visitor(IF, IsSystem);
9150 void ASTReader::visitTopLevelModuleMaps(
9151 serialization::ModuleFile &MF,
9152 llvm::function_ref<void(const FileEntry *FE)> Visitor) {
9153 unsigned NumInputs = MF.InputFilesLoaded.size();
9154 for (unsigned I = 0; I < NumInputs; ++I) {
9155 InputFileInfo IFI = readInputFileInfo(MF, I + 1);
9156 if (IFI.TopLevelModuleMap)
9157 // FIXME: This unnecessarily re-reads the InputFileInfo.
9158 if (auto FE = getInputFile(MF, I + 1).getFile())
9163 std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
9164 // If we know the owning module, use it.
9165 if (Module *M = D->getImportedOwningModule())
9166 return M->getFullModuleName();
9168 // Otherwise, use the name of the top-level module the decl is within.
9169 if (ModuleFile *M = getOwningModuleFile(D))
9170 return M->ModuleName;
9172 // Not from a module.
9176 void ASTReader::finishPendingActions() {
9177 while (!PendingIdentifierInfos.empty() || !PendingFunctionTypes.empty() ||
9178 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
9179 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
9180 !PendingUpdateRecords.empty()) {
9181 // If any identifiers with corresponding top-level declarations have
9182 // been loaded, load those declarations now.
9183 using TopLevelDeclsMap =
9184 llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2>>;
9185 TopLevelDeclsMap TopLevelDecls;
9187 while (!PendingIdentifierInfos.empty()) {
9188 IdentifierInfo *II = PendingIdentifierInfos.back().first;
9189 SmallVector<uint32_t, 4> DeclIDs =
9190 std::move(PendingIdentifierInfos.back().second);
9191 PendingIdentifierInfos.pop_back();
9193 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
9196 // Load each function type that we deferred loading because it was a
9197 // deduced type that might refer to a local type declared within itself.
9198 for (unsigned I = 0; I != PendingFunctionTypes.size(); ++I) {
9199 auto *FD = PendingFunctionTypes[I].first;
9200 FD->setType(GetType(PendingFunctionTypes[I].second));
9202 // If we gave a function a deduced return type, remember that we need to
9203 // propagate that along the redeclaration chain.
9204 auto *DT = FD->getReturnType()->getContainedDeducedType();
9205 if (DT && DT->isDeduced())
9206 PendingDeducedTypeUpdates.insert(
9207 {FD->getCanonicalDecl(), FD->getReturnType()});
9209 PendingFunctionTypes.clear();
9211 // For each decl chain that we wanted to complete while deserializing, mark
9212 // it as "still needs to be completed".
9213 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
9214 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
9216 PendingIncompleteDeclChains.clear();
9218 // Load pending declaration chains.
9219 for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
9220 loadPendingDeclChain(PendingDeclChains[I].first,
9221 PendingDeclChains[I].second);
9222 PendingDeclChains.clear();
9224 // Make the most recent of the top-level declarations visible.
9225 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
9226 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
9227 IdentifierInfo *II = TLD->first;
9228 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
9229 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
9233 // Load any pending macro definitions.
9234 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
9235 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
9236 SmallVector<PendingMacroInfo, 2> GlobalIDs;
9237 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
9238 // Initialize the macro history from chained-PCHs ahead of module imports.
9239 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
9241 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
9242 if (!Info.M->isModule())
9243 resolvePendingMacro(II, Info);
9245 // Handle module imports.
9246 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
9248 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
9249 if (Info.M->isModule())
9250 resolvePendingMacro(II, Info);
9253 PendingMacroIDs.clear();
9255 // Wire up the DeclContexts for Decls that we delayed setting until
9256 // recursive loading is completed.
9257 while (!PendingDeclContextInfos.empty()) {
9258 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
9259 PendingDeclContextInfos.pop_front();
9260 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
9261 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
9262 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
9265 // Perform any pending declaration updates.
9266 while (!PendingUpdateRecords.empty()) {
9267 auto Update = PendingUpdateRecords.pop_back_val();
9268 ReadingKindTracker ReadingKind(Read_Decl, *this);
9269 loadDeclUpdateRecords(Update);
9273 // At this point, all update records for loaded decls are in place, so any
9274 // fake class definitions should have become real.
9275 assert(PendingFakeDefinitionData.empty() &&
9276 "faked up a class definition but never saw the real one");
9278 // If we deserialized any C++ or Objective-C class definitions, any
9279 // Objective-C protocol definitions, or any redeclarable templates, make sure
9280 // that all redeclarations point to the definitions. Note that this can only
9281 // happen now, after the redeclaration chains have been fully wired.
9282 for (Decl *D : PendingDefinitions) {
9283 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
9284 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
9285 // Make sure that the TagType points at the definition.
9286 const_cast<TagType*>(TagT)->decl = TD;
9289 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
9290 for (auto *R = getMostRecentExistingDecl(RD); R;
9291 R = R->getPreviousDecl()) {
9293 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
9294 "declaration thinks it's the definition but it isn't");
9295 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
9302 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
9303 // Make sure that the ObjCInterfaceType points at the definition.
9304 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
9307 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
9308 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
9313 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
9314 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
9315 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
9320 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
9321 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
9322 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
9324 PendingDefinitions.clear();
9326 // Load the bodies of any functions or methods we've encountered. We do
9327 // this now (delayed) so that we can be sure that the declaration chains
9328 // have been fully wired up (hasBody relies on this).
9329 // FIXME: We shouldn't require complete redeclaration chains here.
9330 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
9331 PBEnd = PendingBodies.end();
9332 PB != PBEnd; ++PB) {
9333 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
9334 // For a function defined inline within a class template, force the
9335 // canonical definition to be the one inside the canonical definition of
9336 // the template. This ensures that we instantiate from a correct view
9339 // Sadly we can't do this more generally: we can't be sure that all
9340 // copies of an arbitrary class definition will have the same members
9341 // defined (eg, some member functions may not be instantiated, and some
9342 // special members may or may not have been implicitly defined).
9343 if (auto *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalParent()))
9344 if (RD->isDependentContext() && !RD->isThisDeclarationADefinition())
9347 // FIXME: Check for =delete/=default?
9348 // FIXME: Complain about ODR violations here?
9349 const FunctionDecl *Defn = nullptr;
9350 if (!getContext().getLangOpts().Modules || !FD->hasBody(Defn)) {
9351 FD->setLazyBody(PB->second);
9353 auto *NonConstDefn = const_cast<FunctionDecl*>(Defn);
9354 mergeDefinitionVisibility(NonConstDefn, FD);
9356 if (!FD->isLateTemplateParsed() &&
9357 !NonConstDefn->isLateTemplateParsed() &&
9358 FD->getODRHash() != NonConstDefn->getODRHash()) {
9359 if (!isa<CXXMethodDecl>(FD)) {
9360 PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
9361 } else if (FD->getLexicalParent()->isFileContext() &&
9362 NonConstDefn->getLexicalParent()->isFileContext()) {
9363 // Only diagnose out-of-line method definitions. If they are
9364 // in class definitions, then an error will be generated when
9365 // processing the class bodies.
9366 PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
9373 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
9374 if (!getContext().getLangOpts().Modules || !MD->hasBody())
9375 MD->setLazyBody(PB->second);
9377 PendingBodies.clear();
9380 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
9381 getContext().deduplicateMergedDefinitonsFor(ND);
9382 PendingMergedDefinitionsToDeduplicate.clear();
9385 void ASTReader::diagnoseOdrViolations() {
9386 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty() &&
9387 PendingFunctionOdrMergeFailures.empty() &&
9388 PendingEnumOdrMergeFailures.empty())
9391 // Trigger the import of the full definition of each class that had any
9392 // odr-merging problems, so we can produce better diagnostics for them.
9393 // These updates may in turn find and diagnose some ODR failures, so take
9394 // ownership of the set first.
9395 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
9396 PendingOdrMergeFailures.clear();
9397 for (auto &Merge : OdrMergeFailures) {
9398 Merge.first->buildLookup();
9399 Merge.first->decls_begin();
9400 Merge.first->bases_begin();
9401 Merge.first->vbases_begin();
9402 for (auto &RecordPair : Merge.second) {
9403 auto *RD = RecordPair.first;
9410 // Trigger the import of functions.
9411 auto FunctionOdrMergeFailures = std::move(PendingFunctionOdrMergeFailures);
9412 PendingFunctionOdrMergeFailures.clear();
9413 for (auto &Merge : FunctionOdrMergeFailures) {
9414 Merge.first->buildLookup();
9415 Merge.first->decls_begin();
9416 Merge.first->getBody();
9417 for (auto &FD : Merge.second) {
9424 // Trigger the import of enums.
9425 auto EnumOdrMergeFailures = std::move(PendingEnumOdrMergeFailures);
9426 PendingEnumOdrMergeFailures.clear();
9427 for (auto &Merge : EnumOdrMergeFailures) {
9428 Merge.first->decls_begin();
9429 for (auto &Enum : Merge.second) {
9430 Enum->decls_begin();
9434 // For each declaration from a merged context, check that the canonical
9435 // definition of that context also contains a declaration of the same
9438 // Caution: this loop does things that might invalidate iterators into
9439 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
9440 while (!PendingOdrMergeChecks.empty()) {
9441 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
9443 // FIXME: Skip over implicit declarations for now. This matters for things
9444 // like implicitly-declared special member functions. This isn't entirely
9445 // correct; we can end up with multiple unmerged declarations of the same
9447 if (D->isImplicit())
9450 DeclContext *CanonDef = D->getDeclContext();
9453 const Decl *DCanon = D->getCanonicalDecl();
9455 for (auto RI : D->redecls()) {
9456 if (RI->getLexicalDeclContext() == CanonDef) {
9464 // Quick check failed, time to do the slow thing. Note, we can't just
9465 // look up the name of D in CanonDef here, because the member that is
9466 // in CanonDef might not be found by name lookup (it might have been
9467 // replaced by a more recent declaration in the lookup table), and we
9468 // can't necessarily find it in the redeclaration chain because it might
9469 // be merely mergeable, not redeclarable.
9470 llvm::SmallVector<const NamedDecl*, 4> Candidates;
9471 for (auto *CanonMember : CanonDef->decls()) {
9472 if (CanonMember->getCanonicalDecl() == DCanon) {
9473 // This can happen if the declaration is merely mergeable and not
9474 // actually redeclarable (we looked for redeclarations earlier).
9476 // FIXME: We should be able to detect this more efficiently, without
9477 // pulling in all of the members of CanonDef.
9481 if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
9482 if (ND->getDeclName() == D->getDeclName())
9483 Candidates.push_back(ND);
9487 // The AST doesn't like TagDecls becoming invalid after they've been
9488 // completed. We only really need to mark FieldDecls as invalid here.
9489 if (!isa<TagDecl>(D))
9490 D->setInvalidDecl();
9492 // Ensure we don't accidentally recursively enter deserialization while
9493 // we're producing our diagnostic.
9494 Deserializing RecursionGuard(this);
9496 std::string CanonDefModule =
9497 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
9498 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
9499 << D << getOwningModuleNameForDiagnostic(D)
9500 << CanonDef << CanonDefModule.empty() << CanonDefModule;
9502 if (Candidates.empty())
9503 Diag(cast<Decl>(CanonDef)->getLocation(),
9504 diag::note_module_odr_violation_no_possible_decls) << D;
9506 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
9507 Diag(Candidates[I]->getLocation(),
9508 diag::note_module_odr_violation_possible_decl)
9512 DiagnosedOdrMergeFailures.insert(CanonDef);
9516 if (OdrMergeFailures.empty() && FunctionOdrMergeFailures.empty() &&
9517 EnumOdrMergeFailures.empty())
9520 // Ensure we don't accidentally recursively enter deserialization while
9521 // we're producing our diagnostics.
9522 Deserializing RecursionGuard(this);
9524 // Common code for hashing helpers.
9526 auto ComputeQualTypeODRHash = [&Hash](QualType Ty) {
9528 Hash.AddQualType(Ty);
9529 return Hash.CalculateHash();
9532 auto ComputeODRHash = [&Hash](const Stmt *S) {
9536 return Hash.CalculateHash();
9539 auto ComputeSubDeclODRHash = [&Hash](const Decl *D) {
9543 return Hash.CalculateHash();
9546 auto ComputeTemplateArgumentODRHash = [&Hash](const TemplateArgument &TA) {
9548 Hash.AddTemplateArgument(TA);
9549 return Hash.CalculateHash();
9552 auto ComputeTemplateParameterListODRHash =
9553 [&Hash](const TemplateParameterList *TPL) {
9556 Hash.AddTemplateParameterList(TPL);
9557 return Hash.CalculateHash();
9560 // Used with err_module_odr_violation_mismatch_decl and
9561 // note_module_odr_violation_mismatch_decl
9562 // This list should be the same Decl's as in ODRHash::isDeclToBeProcessed
9563 enum ODRMismatchDecl {
9579 // Used with err_module_odr_violation_mismatch_decl_diff and
9580 // note_module_odr_violation_mismatch_decl_diff
9581 enum ODRMismatchDeclDifference {
9582 StaticAssertCondition,
9583 StaticAssertMessage,
9584 StaticAssertOnlyMessage,
9587 FieldSingleBitField,
9588 FieldDifferentWidthBitField,
9590 FieldSingleInitializer,
9591 FieldDifferentInitializers,
9600 MethodNumberParameters,
9601 MethodParameterType,
9602 MethodParameterName,
9603 MethodParameterSingleDefaultArgument,
9604 MethodParameterDifferentDefaultArgument,
9605 MethodNoTemplateArguments,
9606 MethodDifferentNumberTemplateArguments,
9607 MethodDifferentTemplateArgument,
9609 MethodDifferentBody,
9614 VarSingleInitializer,
9615 VarDifferentInitializer,
9620 FunctionTemplateDifferentNumberParameters,
9621 FunctionTemplateParameterDifferentKind,
9622 FunctionTemplateParameterName,
9623 FunctionTemplateParameterSingleDefaultArgument,
9624 FunctionTemplateParameterDifferentDefaultArgument,
9625 FunctionTemplateParameterDifferentType,
9626 FunctionTemplatePackParameter,
9629 // These lambdas have the common portions of the ODR diagnostics. This
9630 // has the same return as Diag(), so addition parameters can be passed
9631 // in with operator<<
9632 auto ODRDiagDeclError = [this](NamedDecl *FirstRecord, StringRef FirstModule,
9633 SourceLocation Loc, SourceRange Range,
9634 ODRMismatchDeclDifference DiffType) {
9635 return Diag(Loc, diag::err_module_odr_violation_mismatch_decl_diff)
9636 << FirstRecord << FirstModule.empty() << FirstModule << Range
9639 auto ODRDiagDeclNote = [this](StringRef SecondModule, SourceLocation Loc,
9640 SourceRange Range, ODRMismatchDeclDifference DiffType) {
9641 return Diag(Loc, diag::note_module_odr_violation_mismatch_decl_diff)
9642 << SecondModule << Range << DiffType;
9645 auto ODRDiagField = [this, &ODRDiagDeclError, &ODRDiagDeclNote,
9646 &ComputeQualTypeODRHash, &ComputeODRHash](
9647 NamedDecl *FirstRecord, StringRef FirstModule,
9648 StringRef SecondModule, FieldDecl *FirstField,
9649 FieldDecl *SecondField) {
9650 IdentifierInfo *FirstII = FirstField->getIdentifier();
9651 IdentifierInfo *SecondII = SecondField->getIdentifier();
9652 if (FirstII->getName() != SecondII->getName()) {
9653 ODRDiagDeclError(FirstRecord, FirstModule, FirstField->getLocation(),
9654 FirstField->getSourceRange(), FieldName)
9656 ODRDiagDeclNote(SecondModule, SecondField->getLocation(),
9657 SecondField->getSourceRange(), FieldName)
9663 assert(getContext().hasSameType(FirstField->getType(),
9664 SecondField->getType()));
9666 QualType FirstType = FirstField->getType();
9667 QualType SecondType = SecondField->getType();
9668 if (ComputeQualTypeODRHash(FirstType) !=
9669 ComputeQualTypeODRHash(SecondType)) {
9670 ODRDiagDeclError(FirstRecord, FirstModule, FirstField->getLocation(),
9671 FirstField->getSourceRange(), FieldTypeName)
9672 << FirstII << FirstType;
9673 ODRDiagDeclNote(SecondModule, SecondField->getLocation(),
9674 SecondField->getSourceRange(), FieldTypeName)
9675 << SecondII << SecondType;
9680 const bool IsFirstBitField = FirstField->isBitField();
9681 const bool IsSecondBitField = SecondField->isBitField();
9682 if (IsFirstBitField != IsSecondBitField) {
9683 ODRDiagDeclError(FirstRecord, FirstModule, FirstField->getLocation(),
9684 FirstField->getSourceRange(), FieldSingleBitField)
9685 << FirstII << IsFirstBitField;
9686 ODRDiagDeclNote(SecondModule, SecondField->getLocation(),
9687 SecondField->getSourceRange(), FieldSingleBitField)
9688 << SecondII << IsSecondBitField;
9692 if (IsFirstBitField && IsSecondBitField) {
9693 unsigned FirstBitWidthHash =
9694 ComputeODRHash(FirstField->getBitWidth());
9695 unsigned SecondBitWidthHash =
9696 ComputeODRHash(SecondField->getBitWidth());
9697 if (FirstBitWidthHash != SecondBitWidthHash) {
9698 ODRDiagDeclError(FirstRecord, FirstModule, FirstField->getLocation(),
9699 FirstField->getSourceRange(),
9700 FieldDifferentWidthBitField)
9701 << FirstII << FirstField->getBitWidth()->getSourceRange();
9702 ODRDiagDeclNote(SecondModule, SecondField->getLocation(),
9703 SecondField->getSourceRange(),
9704 FieldDifferentWidthBitField)
9705 << SecondII << SecondField->getBitWidth()->getSourceRange();
9710 if (!PP.getLangOpts().CPlusPlus)
9713 const bool IsFirstMutable = FirstField->isMutable();
9714 const bool IsSecondMutable = SecondField->isMutable();
9715 if (IsFirstMutable != IsSecondMutable) {
9716 ODRDiagDeclError(FirstRecord, FirstModule, FirstField->getLocation(),
9717 FirstField->getSourceRange(), FieldSingleMutable)
9718 << FirstII << IsFirstMutable;
9719 ODRDiagDeclNote(SecondModule, SecondField->getLocation(),
9720 SecondField->getSourceRange(), FieldSingleMutable)
9721 << SecondII << IsSecondMutable;
9725 const Expr *FirstInitializer = FirstField->getInClassInitializer();
9726 const Expr *SecondInitializer = SecondField->getInClassInitializer();
9727 if ((!FirstInitializer && SecondInitializer) ||
9728 (FirstInitializer && !SecondInitializer)) {
9729 ODRDiagDeclError(FirstRecord, FirstModule, FirstField->getLocation(),
9730 FirstField->getSourceRange(), FieldSingleInitializer)
9731 << FirstII << (FirstInitializer != nullptr);
9732 ODRDiagDeclNote(SecondModule, SecondField->getLocation(),
9733 SecondField->getSourceRange(), FieldSingleInitializer)
9734 << SecondII << (SecondInitializer != nullptr);
9738 if (FirstInitializer && SecondInitializer) {
9739 unsigned FirstInitHash = ComputeODRHash(FirstInitializer);
9740 unsigned SecondInitHash = ComputeODRHash(SecondInitializer);
9741 if (FirstInitHash != SecondInitHash) {
9742 ODRDiagDeclError(FirstRecord, FirstModule, FirstField->getLocation(),
9743 FirstField->getSourceRange(),
9744 FieldDifferentInitializers)
9745 << FirstII << FirstInitializer->getSourceRange();
9746 ODRDiagDeclNote(SecondModule, SecondField->getLocation(),
9747 SecondField->getSourceRange(),
9748 FieldDifferentInitializers)
9749 << SecondII << SecondInitializer->getSourceRange();
9757 auto ODRDiagTypeDefOrAlias =
9758 [&ODRDiagDeclError, &ODRDiagDeclNote, &ComputeQualTypeODRHash](
9759 NamedDecl *FirstRecord, StringRef FirstModule, StringRef SecondModule,
9760 TypedefNameDecl *FirstTD, TypedefNameDecl *SecondTD,
9762 auto FirstName = FirstTD->getDeclName();
9763 auto SecondName = SecondTD->getDeclName();
9764 if (FirstName != SecondName) {
9765 ODRDiagDeclError(FirstRecord, FirstModule, FirstTD->getLocation(),
9766 FirstTD->getSourceRange(), TypedefName)
9767 << IsTypeAlias << FirstName;
9768 ODRDiagDeclNote(SecondModule, SecondTD->getLocation(),
9769 SecondTD->getSourceRange(), TypedefName)
9770 << IsTypeAlias << SecondName;
9774 QualType FirstType = FirstTD->getUnderlyingType();
9775 QualType SecondType = SecondTD->getUnderlyingType();
9776 if (ComputeQualTypeODRHash(FirstType) !=
9777 ComputeQualTypeODRHash(SecondType)) {
9778 ODRDiagDeclError(FirstRecord, FirstModule, FirstTD->getLocation(),
9779 FirstTD->getSourceRange(), TypedefType)
9780 << IsTypeAlias << FirstName << FirstType;
9781 ODRDiagDeclNote(SecondModule, SecondTD->getLocation(),
9782 SecondTD->getSourceRange(), TypedefType)
9783 << IsTypeAlias << SecondName << SecondType;
9790 auto ODRDiagVar = [&ODRDiagDeclError, &ODRDiagDeclNote,
9791 &ComputeQualTypeODRHash, &ComputeODRHash,
9792 this](NamedDecl *FirstRecord, StringRef FirstModule,
9793 StringRef SecondModule, VarDecl *FirstVD,
9794 VarDecl *SecondVD) {
9795 auto FirstName = FirstVD->getDeclName();
9796 auto SecondName = SecondVD->getDeclName();
9797 if (FirstName != SecondName) {
9798 ODRDiagDeclError(FirstRecord, FirstModule, FirstVD->getLocation(),
9799 FirstVD->getSourceRange(), VarName)
9801 ODRDiagDeclNote(SecondModule, SecondVD->getLocation(),
9802 SecondVD->getSourceRange(), VarName)
9807 QualType FirstType = FirstVD->getType();
9808 QualType SecondType = SecondVD->getType();
9809 if (ComputeQualTypeODRHash(FirstType) !=
9810 ComputeQualTypeODRHash(SecondType)) {
9811 ODRDiagDeclError(FirstRecord, FirstModule, FirstVD->getLocation(),
9812 FirstVD->getSourceRange(), VarType)
9813 << FirstName << FirstType;
9814 ODRDiagDeclNote(SecondModule, SecondVD->getLocation(),
9815 SecondVD->getSourceRange(), VarType)
9816 << SecondName << SecondType;
9820 if (!PP.getLangOpts().CPlusPlus)
9823 const Expr *FirstInit = FirstVD->getInit();
9824 const Expr *SecondInit = SecondVD->getInit();
9825 if ((FirstInit == nullptr) != (SecondInit == nullptr)) {
9826 ODRDiagDeclError(FirstRecord, FirstModule, FirstVD->getLocation(),
9827 FirstVD->getSourceRange(), VarSingleInitializer)
9828 << FirstName << (FirstInit == nullptr)
9829 << (FirstInit ? FirstInit->getSourceRange() : SourceRange());
9830 ODRDiagDeclNote(SecondModule, SecondVD->getLocation(),
9831 SecondVD->getSourceRange(), VarSingleInitializer)
9832 << SecondName << (SecondInit == nullptr)
9833 << (SecondInit ? SecondInit->getSourceRange() : SourceRange());
9837 if (FirstInit && SecondInit &&
9838 ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
9839 ODRDiagDeclError(FirstRecord, FirstModule, FirstVD->getLocation(),
9840 FirstVD->getSourceRange(), VarDifferentInitializer)
9841 << FirstName << FirstInit->getSourceRange();
9842 ODRDiagDeclNote(SecondModule, SecondVD->getLocation(),
9843 SecondVD->getSourceRange(), VarDifferentInitializer)
9844 << SecondName << SecondInit->getSourceRange();
9848 const bool FirstIsConstexpr = FirstVD->isConstexpr();
9849 const bool SecondIsConstexpr = SecondVD->isConstexpr();
9850 if (FirstIsConstexpr != SecondIsConstexpr) {
9851 ODRDiagDeclError(FirstRecord, FirstModule, FirstVD->getLocation(),
9852 FirstVD->getSourceRange(), VarConstexpr)
9853 << FirstName << FirstIsConstexpr;
9854 ODRDiagDeclNote(SecondModule, SecondVD->getLocation(),
9855 SecondVD->getSourceRange(), VarConstexpr)
9856 << SecondName << SecondIsConstexpr;
9862 auto DifferenceSelector = [](Decl *D) {
9863 assert(D && "valid Decl required");
9864 switch (D->getKind()) {
9867 case Decl::AccessSpec:
9868 switch (D->getAccess()) {
9870 return PublicSpecifer;
9872 return PrivateSpecifer;
9874 return ProtectedSpecifer;
9878 llvm_unreachable("Invalid access specifier");
9879 case Decl::StaticAssert:
9880 return StaticAssert;
9883 case Decl::CXXMethod:
9884 case Decl::CXXConstructor:
9885 case Decl::CXXDestructor:
9887 case Decl::TypeAlias:
9895 case Decl::FunctionTemplate:
9896 return FunctionTemplate;
9900 using DeclHashes = llvm::SmallVector<std::pair<Decl *, unsigned>, 4>;
9901 auto PopulateHashes = [&ComputeSubDeclODRHash](DeclHashes &Hashes,
9903 const DeclContext *DC) {
9904 for (auto *D : Record->decls()) {
9905 if (!ODRHash::isDeclToBeProcessed(D, DC))
9907 Hashes.emplace_back(D, ComputeSubDeclODRHash(D));
9912 Decl *FirstDecl = nullptr, *SecondDecl = nullptr;
9913 ODRMismatchDecl FirstDiffType = Other, SecondDiffType = Other;
9916 // If there is a diagnoseable difference, FirstDiffType and
9917 // SecondDiffType will not be Other and FirstDecl and SecondDecl will be
9918 // filled in if not EndOfClass.
9919 auto FindTypeDiffs = [&DifferenceSelector](DeclHashes &FirstHashes,
9920 DeclHashes &SecondHashes) {
9922 auto FirstIt = FirstHashes.begin();
9923 auto SecondIt = SecondHashes.begin();
9924 while (FirstIt != FirstHashes.end() || SecondIt != SecondHashes.end()) {
9925 if (FirstIt != FirstHashes.end() && SecondIt != SecondHashes.end() &&
9926 FirstIt->second == SecondIt->second) {
9932 DR.FirstDecl = FirstIt == FirstHashes.end() ? nullptr : FirstIt->first;
9934 SecondIt == SecondHashes.end() ? nullptr : SecondIt->first;
9937 DR.FirstDecl ? DifferenceSelector(DR.FirstDecl) : EndOfClass;
9939 DR.SecondDecl ? DifferenceSelector(DR.SecondDecl) : EndOfClass;
9945 // Use this to diagnose that an unexpected Decl was encountered
9946 // or no difference was detected. This causes a generic error
9947 // message to be emitted.
9948 auto DiagnoseODRUnexpected = [this](DiffResult &DR, NamedDecl *FirstRecord,
9949 StringRef FirstModule,
9950 NamedDecl *SecondRecord,
9951 StringRef SecondModule) {
9952 Diag(FirstRecord->getLocation(),
9953 diag::err_module_odr_violation_different_definitions)
9954 << FirstRecord << FirstModule.empty() << FirstModule;
9957 Diag(DR.FirstDecl->getLocation(), diag::note_first_module_difference)
9958 << FirstRecord << DR.FirstDecl->getSourceRange();
9961 Diag(SecondRecord->getLocation(),
9962 diag::note_module_odr_violation_different_definitions)
9965 if (DR.SecondDecl) {
9966 Diag(DR.SecondDecl->getLocation(), diag::note_second_module_difference)
9967 << DR.SecondDecl->getSourceRange();
9971 auto DiagnoseODRMismatch =
9972 [this](DiffResult &DR, NamedDecl *FirstRecord, StringRef FirstModule,
9973 NamedDecl *SecondRecord, StringRef SecondModule) {
9974 SourceLocation FirstLoc;
9975 SourceRange FirstRange;
9976 auto *FirstTag = dyn_cast<TagDecl>(FirstRecord);
9977 if (DR.FirstDiffType == EndOfClass && FirstTag) {
9978 FirstLoc = FirstTag->getBraceRange().getEnd();
9980 FirstLoc = DR.FirstDecl->getLocation();
9981 FirstRange = DR.FirstDecl->getSourceRange();
9983 Diag(FirstLoc, diag::err_module_odr_violation_mismatch_decl)
9984 << FirstRecord << FirstModule.empty() << FirstModule << FirstRange
9985 << DR.FirstDiffType;
9987 SourceLocation SecondLoc;
9988 SourceRange SecondRange;
9989 auto *SecondTag = dyn_cast<TagDecl>(SecondRecord);
9990 if (DR.SecondDiffType == EndOfClass && SecondTag) {
9991 SecondLoc = SecondTag->getBraceRange().getEnd();
9993 SecondLoc = DR.SecondDecl->getLocation();
9994 SecondRange = DR.SecondDecl->getSourceRange();
9996 Diag(SecondLoc, diag::note_module_odr_violation_mismatch_decl)
9997 << SecondModule << SecondRange << DR.SecondDiffType;
10000 // Issue any pending ODR-failure diagnostics.
10001 for (auto &Merge : OdrMergeFailures) {
10002 // If we've already pointed out a specific problem with this class, don't
10003 // bother issuing a general "something's different" diagnostic.
10004 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
10007 bool Diagnosed = false;
10008 CXXRecordDecl *FirstRecord = Merge.first;
10009 std::string FirstModule = getOwningModuleNameForDiagnostic(FirstRecord);
10010 for (auto &RecordPair : Merge.second) {
10011 CXXRecordDecl *SecondRecord = RecordPair.first;
10012 // Multiple different declarations got merged together; tell the user
10013 // where they came from.
10014 if (FirstRecord == SecondRecord)
10017 std::string SecondModule = getOwningModuleNameForDiagnostic(SecondRecord);
10019 auto *FirstDD = FirstRecord->DefinitionData;
10020 auto *SecondDD = RecordPair.second;
10022 assert(FirstDD && SecondDD && "Definitions without DefinitionData");
10024 // Diagnostics from DefinitionData are emitted here.
10025 if (FirstDD != SecondDD) {
10026 enum ODRDefinitionDataDifference {
10033 auto ODRDiagBaseError = [FirstRecord, &FirstModule,
10034 this](SourceLocation Loc, SourceRange Range,
10035 ODRDefinitionDataDifference DiffType) {
10036 return Diag(Loc, diag::err_module_odr_violation_definition_data)
10037 << FirstRecord << FirstModule.empty() << FirstModule << Range
10040 auto ODRDiagBaseNote = [&SecondModule,
10041 this](SourceLocation Loc, SourceRange Range,
10042 ODRDefinitionDataDifference DiffType) {
10043 return Diag(Loc, diag::note_module_odr_violation_definition_data)
10044 << SecondModule << Range << DiffType;
10047 unsigned FirstNumBases = FirstDD->NumBases;
10048 unsigned FirstNumVBases = FirstDD->NumVBases;
10049 unsigned SecondNumBases = SecondDD->NumBases;
10050 unsigned SecondNumVBases = SecondDD->NumVBases;
10052 auto GetSourceRange = [](struct CXXRecordDecl::DefinitionData *DD) {
10053 unsigned NumBases = DD->NumBases;
10054 if (NumBases == 0) return SourceRange();
10055 auto bases = DD->bases();
10056 return SourceRange(bases[0].getBeginLoc(),
10057 bases[NumBases - 1].getEndLoc());
10060 if (FirstNumBases != SecondNumBases) {
10061 ODRDiagBaseError(FirstRecord->getLocation(), GetSourceRange(FirstDD),
10064 ODRDiagBaseNote(SecondRecord->getLocation(), GetSourceRange(SecondDD),
10071 if (FirstNumVBases != SecondNumVBases) {
10072 ODRDiagBaseError(FirstRecord->getLocation(), GetSourceRange(FirstDD),
10075 ODRDiagBaseNote(SecondRecord->getLocation(), GetSourceRange(SecondDD),
10077 << SecondNumVBases;
10082 auto FirstBases = FirstDD->bases();
10083 auto SecondBases = SecondDD->bases();
10085 for (i = 0; i < FirstNumBases; ++i) {
10086 auto FirstBase = FirstBases[i];
10087 auto SecondBase = SecondBases[i];
10088 if (ComputeQualTypeODRHash(FirstBase.getType()) !=
10089 ComputeQualTypeODRHash(SecondBase.getType())) {
10090 ODRDiagBaseError(FirstRecord->getLocation(),
10091 FirstBase.getSourceRange(), BaseType)
10092 << (i + 1) << FirstBase.getType();
10093 ODRDiagBaseNote(SecondRecord->getLocation(),
10094 SecondBase.getSourceRange(), BaseType)
10095 << (i + 1) << SecondBase.getType();
10099 if (FirstBase.isVirtual() != SecondBase.isVirtual()) {
10100 ODRDiagBaseError(FirstRecord->getLocation(),
10101 FirstBase.getSourceRange(), BaseVirtual)
10102 << (i + 1) << FirstBase.isVirtual() << FirstBase.getType();
10103 ODRDiagBaseNote(SecondRecord->getLocation(),
10104 SecondBase.getSourceRange(), BaseVirtual)
10105 << (i + 1) << SecondBase.isVirtual() << SecondBase.getType();
10109 if (FirstBase.getAccessSpecifierAsWritten() !=
10110 SecondBase.getAccessSpecifierAsWritten()) {
10111 ODRDiagBaseError(FirstRecord->getLocation(),
10112 FirstBase.getSourceRange(), BaseAccess)
10113 << (i + 1) << FirstBase.getType()
10114 << (int)FirstBase.getAccessSpecifierAsWritten();
10115 ODRDiagBaseNote(SecondRecord->getLocation(),
10116 SecondBase.getSourceRange(), BaseAccess)
10117 << (i + 1) << SecondBase.getType()
10118 << (int)SecondBase.getAccessSpecifierAsWritten();
10123 if (i != FirstNumBases) {
10129 const ClassTemplateDecl *FirstTemplate =
10130 FirstRecord->getDescribedClassTemplate();
10131 const ClassTemplateDecl *SecondTemplate =
10132 SecondRecord->getDescribedClassTemplate();
10134 assert(!FirstTemplate == !SecondTemplate &&
10135 "Both pointers should be null or non-null");
10137 enum ODRTemplateDifference {
10140 ParamSingleDefaultArgument,
10141 ParamDifferentDefaultArgument,
10144 if (FirstTemplate && SecondTemplate) {
10145 DeclHashes FirstTemplateHashes;
10146 DeclHashes SecondTemplateHashes;
10148 auto PopulateTemplateParameterHashs =
10149 [&ComputeSubDeclODRHash](DeclHashes &Hashes,
10150 const ClassTemplateDecl *TD) {
10151 for (auto *D : TD->getTemplateParameters()->asArray()) {
10152 Hashes.emplace_back(D, ComputeSubDeclODRHash(D));
10156 PopulateTemplateParameterHashs(FirstTemplateHashes, FirstTemplate);
10157 PopulateTemplateParameterHashs(SecondTemplateHashes, SecondTemplate);
10159 assert(FirstTemplateHashes.size() == SecondTemplateHashes.size() &&
10160 "Number of template parameters should be equal.");
10162 auto FirstIt = FirstTemplateHashes.begin();
10163 auto FirstEnd = FirstTemplateHashes.end();
10164 auto SecondIt = SecondTemplateHashes.begin();
10165 for (; FirstIt != FirstEnd; ++FirstIt, ++SecondIt) {
10166 if (FirstIt->second == SecondIt->second)
10169 auto ODRDiagTemplateError = [FirstRecord, &FirstModule, this](
10170 SourceLocation Loc, SourceRange Range,
10171 ODRTemplateDifference DiffType) {
10172 return Diag(Loc, diag::err_module_odr_violation_template_parameter)
10173 << FirstRecord << FirstModule.empty() << FirstModule << Range
10176 auto ODRDiagTemplateNote = [&SecondModule, this](
10177 SourceLocation Loc, SourceRange Range,
10178 ODRTemplateDifference DiffType) {
10179 return Diag(Loc, diag::note_module_odr_violation_template_parameter)
10180 << SecondModule << Range << DiffType;
10183 const NamedDecl* FirstDecl = cast<NamedDecl>(FirstIt->first);
10184 const NamedDecl* SecondDecl = cast<NamedDecl>(SecondIt->first);
10186 assert(FirstDecl->getKind() == SecondDecl->getKind() &&
10187 "Parameter Decl's should be the same kind.");
10189 DeclarationName FirstName = FirstDecl->getDeclName();
10190 DeclarationName SecondName = SecondDecl->getDeclName();
10192 if (FirstName != SecondName) {
10193 const bool FirstNameEmpty =
10194 FirstName.isIdentifier() && !FirstName.getAsIdentifierInfo();
10195 const bool SecondNameEmpty =
10196 SecondName.isIdentifier() && !SecondName.getAsIdentifierInfo();
10197 assert((!FirstNameEmpty || !SecondNameEmpty) &&
10198 "Both template parameters cannot be unnamed.");
10199 ODRDiagTemplateError(FirstDecl->getLocation(),
10200 FirstDecl->getSourceRange(),
10201 FirstNameEmpty ? ParamEmptyName : ParamName)
10203 ODRDiagTemplateNote(SecondDecl->getLocation(),
10204 SecondDecl->getSourceRange(),
10205 SecondNameEmpty ? ParamEmptyName : ParamName)
10210 switch (FirstDecl->getKind()) {
10212 llvm_unreachable("Invalid template parameter type.");
10213 case Decl::TemplateTypeParm: {
10214 const auto *FirstParam = cast<TemplateTypeParmDecl>(FirstDecl);
10215 const auto *SecondParam = cast<TemplateTypeParmDecl>(SecondDecl);
10216 const bool HasFirstDefaultArgument =
10217 FirstParam->hasDefaultArgument() &&
10218 !FirstParam->defaultArgumentWasInherited();
10219 const bool HasSecondDefaultArgument =
10220 SecondParam->hasDefaultArgument() &&
10221 !SecondParam->defaultArgumentWasInherited();
10223 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
10224 ODRDiagTemplateError(FirstDecl->getLocation(),
10225 FirstDecl->getSourceRange(),
10226 ParamSingleDefaultArgument)
10227 << HasFirstDefaultArgument;
10228 ODRDiagTemplateNote(SecondDecl->getLocation(),
10229 SecondDecl->getSourceRange(),
10230 ParamSingleDefaultArgument)
10231 << HasSecondDefaultArgument;
10235 assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
10236 "Expecting default arguments.");
10238 ODRDiagTemplateError(FirstDecl->getLocation(),
10239 FirstDecl->getSourceRange(),
10240 ParamDifferentDefaultArgument);
10241 ODRDiagTemplateNote(SecondDecl->getLocation(),
10242 SecondDecl->getSourceRange(),
10243 ParamDifferentDefaultArgument);
10247 case Decl::NonTypeTemplateParm: {
10248 const auto *FirstParam = cast<NonTypeTemplateParmDecl>(FirstDecl);
10249 const auto *SecondParam = cast<NonTypeTemplateParmDecl>(SecondDecl);
10250 const bool HasFirstDefaultArgument =
10251 FirstParam->hasDefaultArgument() &&
10252 !FirstParam->defaultArgumentWasInherited();
10253 const bool HasSecondDefaultArgument =
10254 SecondParam->hasDefaultArgument() &&
10255 !SecondParam->defaultArgumentWasInherited();
10257 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
10258 ODRDiagTemplateError(FirstDecl->getLocation(),
10259 FirstDecl->getSourceRange(),
10260 ParamSingleDefaultArgument)
10261 << HasFirstDefaultArgument;
10262 ODRDiagTemplateNote(SecondDecl->getLocation(),
10263 SecondDecl->getSourceRange(),
10264 ParamSingleDefaultArgument)
10265 << HasSecondDefaultArgument;
10269 assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
10270 "Expecting default arguments.");
10272 ODRDiagTemplateError(FirstDecl->getLocation(),
10273 FirstDecl->getSourceRange(),
10274 ParamDifferentDefaultArgument);
10275 ODRDiagTemplateNote(SecondDecl->getLocation(),
10276 SecondDecl->getSourceRange(),
10277 ParamDifferentDefaultArgument);
10281 case Decl::TemplateTemplateParm: {
10282 const auto *FirstParam = cast<TemplateTemplateParmDecl>(FirstDecl);
10283 const auto *SecondParam =
10284 cast<TemplateTemplateParmDecl>(SecondDecl);
10285 const bool HasFirstDefaultArgument =
10286 FirstParam->hasDefaultArgument() &&
10287 !FirstParam->defaultArgumentWasInherited();
10288 const bool HasSecondDefaultArgument =
10289 SecondParam->hasDefaultArgument() &&
10290 !SecondParam->defaultArgumentWasInherited();
10292 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
10293 ODRDiagTemplateError(FirstDecl->getLocation(),
10294 FirstDecl->getSourceRange(),
10295 ParamSingleDefaultArgument)
10296 << HasFirstDefaultArgument;
10297 ODRDiagTemplateNote(SecondDecl->getLocation(),
10298 SecondDecl->getSourceRange(),
10299 ParamSingleDefaultArgument)
10300 << HasSecondDefaultArgument;
10304 assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
10305 "Expecting default arguments.");
10307 ODRDiagTemplateError(FirstDecl->getLocation(),
10308 FirstDecl->getSourceRange(),
10309 ParamDifferentDefaultArgument);
10310 ODRDiagTemplateNote(SecondDecl->getLocation(),
10311 SecondDecl->getSourceRange(),
10312 ParamDifferentDefaultArgument);
10321 if (FirstIt != FirstEnd) {
10327 DeclHashes FirstHashes;
10328 DeclHashes SecondHashes;
10329 const DeclContext *DC = FirstRecord;
10330 PopulateHashes(FirstHashes, FirstRecord, DC);
10331 PopulateHashes(SecondHashes, SecondRecord, DC);
10333 auto DR = FindTypeDiffs(FirstHashes, SecondHashes);
10334 ODRMismatchDecl FirstDiffType = DR.FirstDiffType;
10335 ODRMismatchDecl SecondDiffType = DR.SecondDiffType;
10336 Decl *FirstDecl = DR.FirstDecl;
10337 Decl *SecondDecl = DR.SecondDecl;
10339 if (FirstDiffType == Other || SecondDiffType == Other) {
10340 DiagnoseODRUnexpected(DR, FirstRecord, FirstModule, SecondRecord,
10346 if (FirstDiffType != SecondDiffType) {
10347 DiagnoseODRMismatch(DR, FirstRecord, FirstModule, SecondRecord,
10353 assert(FirstDiffType == SecondDiffType);
10355 switch (FirstDiffType) {
10358 case PublicSpecifer:
10359 case PrivateSpecifer:
10360 case ProtectedSpecifer:
10361 llvm_unreachable("Invalid diff type");
10363 case StaticAssert: {
10364 StaticAssertDecl *FirstSA = cast<StaticAssertDecl>(FirstDecl);
10365 StaticAssertDecl *SecondSA = cast<StaticAssertDecl>(SecondDecl);
10367 Expr *FirstExpr = FirstSA->getAssertExpr();
10368 Expr *SecondExpr = SecondSA->getAssertExpr();
10369 unsigned FirstODRHash = ComputeODRHash(FirstExpr);
10370 unsigned SecondODRHash = ComputeODRHash(SecondExpr);
10371 if (FirstODRHash != SecondODRHash) {
10372 ODRDiagDeclError(FirstRecord, FirstModule, FirstExpr->getBeginLoc(),
10373 FirstExpr->getSourceRange(), StaticAssertCondition);
10374 ODRDiagDeclNote(SecondModule, SecondExpr->getBeginLoc(),
10375 SecondExpr->getSourceRange(), StaticAssertCondition);
10380 StringLiteral *FirstStr = FirstSA->getMessage();
10381 StringLiteral *SecondStr = SecondSA->getMessage();
10382 assert((FirstStr || SecondStr) && "Both messages cannot be empty");
10383 if ((FirstStr && !SecondStr) || (!FirstStr && SecondStr)) {
10384 SourceLocation FirstLoc, SecondLoc;
10385 SourceRange FirstRange, SecondRange;
10387 FirstLoc = FirstStr->getBeginLoc();
10388 FirstRange = FirstStr->getSourceRange();
10390 FirstLoc = FirstSA->getBeginLoc();
10391 FirstRange = FirstSA->getSourceRange();
10394 SecondLoc = SecondStr->getBeginLoc();
10395 SecondRange = SecondStr->getSourceRange();
10397 SecondLoc = SecondSA->getBeginLoc();
10398 SecondRange = SecondSA->getSourceRange();
10400 ODRDiagDeclError(FirstRecord, FirstModule, FirstLoc, FirstRange,
10401 StaticAssertOnlyMessage)
10402 << (FirstStr == nullptr);
10403 ODRDiagDeclNote(SecondModule, SecondLoc, SecondRange,
10404 StaticAssertOnlyMessage)
10405 << (SecondStr == nullptr);
10410 if (FirstStr && SecondStr &&
10411 FirstStr->getString() != SecondStr->getString()) {
10412 ODRDiagDeclError(FirstRecord, FirstModule, FirstStr->getBeginLoc(),
10413 FirstStr->getSourceRange(), StaticAssertMessage);
10414 ODRDiagDeclNote(SecondModule, SecondStr->getBeginLoc(),
10415 SecondStr->getSourceRange(), StaticAssertMessage);
10422 Diagnosed = ODRDiagField(FirstRecord, FirstModule, SecondModule,
10423 cast<FieldDecl>(FirstDecl),
10424 cast<FieldDecl>(SecondDecl));
10434 auto GetMethodTypeForDiagnostics = [](const CXXMethodDecl* D) {
10435 if (isa<CXXConstructorDecl>(D)) return DiagConstructor;
10436 if (isa<CXXDestructorDecl>(D)) return DiagDestructor;
10439 const CXXMethodDecl *FirstMethod = cast<CXXMethodDecl>(FirstDecl);
10440 const CXXMethodDecl *SecondMethod = cast<CXXMethodDecl>(SecondDecl);
10441 FirstMethodType = GetMethodTypeForDiagnostics(FirstMethod);
10442 SecondMethodType = GetMethodTypeForDiagnostics(SecondMethod);
10443 auto FirstName = FirstMethod->getDeclName();
10444 auto SecondName = SecondMethod->getDeclName();
10445 if (FirstMethodType != SecondMethodType || FirstName != SecondName) {
10446 ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(),
10447 FirstMethod->getSourceRange(), MethodName)
10448 << FirstMethodType << FirstName;
10449 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10450 SecondMethod->getSourceRange(), MethodName)
10451 << SecondMethodType << SecondName;
10457 const bool FirstDeleted = FirstMethod->isDeletedAsWritten();
10458 const bool SecondDeleted = SecondMethod->isDeletedAsWritten();
10459 if (FirstDeleted != SecondDeleted) {
10460 ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(),
10461 FirstMethod->getSourceRange(), MethodDeleted)
10462 << FirstMethodType << FirstName << FirstDeleted;
10464 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10465 SecondMethod->getSourceRange(), MethodDeleted)
10466 << SecondMethodType << SecondName << SecondDeleted;
10471 const bool FirstDefaulted = FirstMethod->isExplicitlyDefaulted();
10472 const bool SecondDefaulted = SecondMethod->isExplicitlyDefaulted();
10473 if (FirstDefaulted != SecondDefaulted) {
10474 ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(),
10475 FirstMethod->getSourceRange(), MethodDefaulted)
10476 << FirstMethodType << FirstName << FirstDefaulted;
10478 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10479 SecondMethod->getSourceRange(), MethodDefaulted)
10480 << SecondMethodType << SecondName << SecondDefaulted;
10485 const bool FirstVirtual = FirstMethod->isVirtualAsWritten();
10486 const bool SecondVirtual = SecondMethod->isVirtualAsWritten();
10487 const bool FirstPure = FirstMethod->isPure();
10488 const bool SecondPure = SecondMethod->isPure();
10489 if ((FirstVirtual || SecondVirtual) &&
10490 (FirstVirtual != SecondVirtual || FirstPure != SecondPure)) {
10491 ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(),
10492 FirstMethod->getSourceRange(), MethodVirtual)
10493 << FirstMethodType << FirstName << FirstPure << FirstVirtual;
10494 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10495 SecondMethod->getSourceRange(), MethodVirtual)
10496 << SecondMethodType << SecondName << SecondPure << SecondVirtual;
10501 // CXXMethodDecl::isStatic uses the canonical Decl. With Decl merging,
10502 // FirstDecl is the canonical Decl of SecondDecl, so the storage
10503 // class needs to be checked instead.
10504 const auto FirstStorage = FirstMethod->getStorageClass();
10505 const auto SecondStorage = SecondMethod->getStorageClass();
10506 const bool FirstStatic = FirstStorage == SC_Static;
10507 const bool SecondStatic = SecondStorage == SC_Static;
10508 if (FirstStatic != SecondStatic) {
10509 ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(),
10510 FirstMethod->getSourceRange(), MethodStatic)
10511 << FirstMethodType << FirstName << FirstStatic;
10512 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10513 SecondMethod->getSourceRange(), MethodStatic)
10514 << SecondMethodType << SecondName << SecondStatic;
10519 const bool FirstVolatile = FirstMethod->isVolatile();
10520 const bool SecondVolatile = SecondMethod->isVolatile();
10521 if (FirstVolatile != SecondVolatile) {
10522 ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(),
10523 FirstMethod->getSourceRange(), MethodVolatile)
10524 << FirstMethodType << FirstName << FirstVolatile;
10525 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10526 SecondMethod->getSourceRange(), MethodVolatile)
10527 << SecondMethodType << SecondName << SecondVolatile;
10532 const bool FirstConst = FirstMethod->isConst();
10533 const bool SecondConst = SecondMethod->isConst();
10534 if (FirstConst != SecondConst) {
10535 ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(),
10536 FirstMethod->getSourceRange(), MethodConst)
10537 << FirstMethodType << FirstName << FirstConst;
10538 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10539 SecondMethod->getSourceRange(), MethodConst)
10540 << SecondMethodType << SecondName << SecondConst;
10545 const bool FirstInline = FirstMethod->isInlineSpecified();
10546 const bool SecondInline = SecondMethod->isInlineSpecified();
10547 if (FirstInline != SecondInline) {
10548 ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(),
10549 FirstMethod->getSourceRange(), MethodInline)
10550 << FirstMethodType << FirstName << FirstInline;
10551 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10552 SecondMethod->getSourceRange(), MethodInline)
10553 << SecondMethodType << SecondName << SecondInline;
10558 const unsigned FirstNumParameters = FirstMethod->param_size();
10559 const unsigned SecondNumParameters = SecondMethod->param_size();
10560 if (FirstNumParameters != SecondNumParameters) {
10561 ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(),
10562 FirstMethod->getSourceRange(),
10563 MethodNumberParameters)
10564 << FirstMethodType << FirstName << FirstNumParameters;
10565 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10566 SecondMethod->getSourceRange(),
10567 MethodNumberParameters)
10568 << SecondMethodType << SecondName << SecondNumParameters;
10573 // Need this status boolean to know when break out of the switch.
10574 bool ParameterMismatch = false;
10575 for (unsigned I = 0; I < FirstNumParameters; ++I) {
10576 const ParmVarDecl *FirstParam = FirstMethod->getParamDecl(I);
10577 const ParmVarDecl *SecondParam = SecondMethod->getParamDecl(I);
10579 QualType FirstParamType = FirstParam->getType();
10580 QualType SecondParamType = SecondParam->getType();
10581 if (FirstParamType != SecondParamType &&
10582 ComputeQualTypeODRHash(FirstParamType) !=
10583 ComputeQualTypeODRHash(SecondParamType)) {
10584 if (const DecayedType *ParamDecayedType =
10585 FirstParamType->getAs<DecayedType>()) {
10587 FirstRecord, FirstModule, FirstMethod->getLocation(),
10588 FirstMethod->getSourceRange(), MethodParameterType)
10589 << FirstMethodType << FirstName << (I + 1) << FirstParamType
10590 << true << ParamDecayedType->getOriginalType();
10593 FirstRecord, FirstModule, FirstMethod->getLocation(),
10594 FirstMethod->getSourceRange(), MethodParameterType)
10595 << FirstMethodType << FirstName << (I + 1) << FirstParamType
10599 if (const DecayedType *ParamDecayedType =
10600 SecondParamType->getAs<DecayedType>()) {
10601 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10602 SecondMethod->getSourceRange(),
10603 MethodParameterType)
10604 << SecondMethodType << SecondName << (I + 1)
10605 << SecondParamType << true
10606 << ParamDecayedType->getOriginalType();
10608 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10609 SecondMethod->getSourceRange(),
10610 MethodParameterType)
10611 << SecondMethodType << SecondName << (I + 1)
10612 << SecondParamType << false;
10614 ParameterMismatch = true;
10618 DeclarationName FirstParamName = FirstParam->getDeclName();
10619 DeclarationName SecondParamName = SecondParam->getDeclName();
10620 if (FirstParamName != SecondParamName) {
10621 ODRDiagDeclError(FirstRecord, FirstModule,
10622 FirstMethod->getLocation(),
10623 FirstMethod->getSourceRange(), MethodParameterName)
10624 << FirstMethodType << FirstName << (I + 1) << FirstParamName;
10625 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10626 SecondMethod->getSourceRange(), MethodParameterName)
10627 << SecondMethodType << SecondName << (I + 1) << SecondParamName;
10628 ParameterMismatch = true;
10632 const Expr *FirstInit = FirstParam->getInit();
10633 const Expr *SecondInit = SecondParam->getInit();
10634 if ((FirstInit == nullptr) != (SecondInit == nullptr)) {
10635 ODRDiagDeclError(FirstRecord, FirstModule,
10636 FirstMethod->getLocation(),
10637 FirstMethod->getSourceRange(),
10638 MethodParameterSingleDefaultArgument)
10639 << FirstMethodType << FirstName << (I + 1)
10640 << (FirstInit == nullptr)
10641 << (FirstInit ? FirstInit->getSourceRange() : SourceRange());
10642 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10643 SecondMethod->getSourceRange(),
10644 MethodParameterSingleDefaultArgument)
10645 << SecondMethodType << SecondName << (I + 1)
10646 << (SecondInit == nullptr)
10647 << (SecondInit ? SecondInit->getSourceRange() : SourceRange());
10648 ParameterMismatch = true;
10652 if (FirstInit && SecondInit &&
10653 ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
10654 ODRDiagDeclError(FirstRecord, FirstModule,
10655 FirstMethod->getLocation(),
10656 FirstMethod->getSourceRange(),
10657 MethodParameterDifferentDefaultArgument)
10658 << FirstMethodType << FirstName << (I + 1)
10659 << FirstInit->getSourceRange();
10660 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10661 SecondMethod->getSourceRange(),
10662 MethodParameterDifferentDefaultArgument)
10663 << SecondMethodType << SecondName << (I + 1)
10664 << SecondInit->getSourceRange();
10665 ParameterMismatch = true;
10671 if (ParameterMismatch) {
10676 const auto *FirstTemplateArgs =
10677 FirstMethod->getTemplateSpecializationArgs();
10678 const auto *SecondTemplateArgs =
10679 SecondMethod->getTemplateSpecializationArgs();
10681 if ((FirstTemplateArgs && !SecondTemplateArgs) ||
10682 (!FirstTemplateArgs && SecondTemplateArgs)) {
10683 ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(),
10684 FirstMethod->getSourceRange(),
10685 MethodNoTemplateArguments)
10686 << FirstMethodType << FirstName << (FirstTemplateArgs != nullptr);
10687 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10688 SecondMethod->getSourceRange(),
10689 MethodNoTemplateArguments)
10690 << SecondMethodType << SecondName
10691 << (SecondTemplateArgs != nullptr);
10697 if (FirstTemplateArgs && SecondTemplateArgs) {
10698 // Remove pack expansions from argument list.
10699 auto ExpandTemplateArgumentList =
10700 [](const TemplateArgumentList *TAL) {
10701 llvm::SmallVector<const TemplateArgument *, 8> ExpandedList;
10702 for (const TemplateArgument &TA : TAL->asArray()) {
10703 if (TA.getKind() != TemplateArgument::Pack) {
10704 ExpandedList.push_back(&TA);
10707 for (const TemplateArgument &PackTA : TA.getPackAsArray()) {
10708 ExpandedList.push_back(&PackTA);
10711 return ExpandedList;
10713 llvm::SmallVector<const TemplateArgument *, 8> FirstExpandedList =
10714 ExpandTemplateArgumentList(FirstTemplateArgs);
10715 llvm::SmallVector<const TemplateArgument *, 8> SecondExpandedList =
10716 ExpandTemplateArgumentList(SecondTemplateArgs);
10718 if (FirstExpandedList.size() != SecondExpandedList.size()) {
10719 ODRDiagDeclError(FirstRecord, FirstModule,
10720 FirstMethod->getLocation(),
10721 FirstMethod->getSourceRange(),
10722 MethodDifferentNumberTemplateArguments)
10723 << FirstMethodType << FirstName
10724 << (unsigned)FirstExpandedList.size();
10725 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10726 SecondMethod->getSourceRange(),
10727 MethodDifferentNumberTemplateArguments)
10728 << SecondMethodType << SecondName
10729 << (unsigned)SecondExpandedList.size();
10735 bool TemplateArgumentMismatch = false;
10736 for (unsigned i = 0, e = FirstExpandedList.size(); i != e; ++i) {
10737 const TemplateArgument &FirstTA = *FirstExpandedList[i],
10738 &SecondTA = *SecondExpandedList[i];
10739 if (ComputeTemplateArgumentODRHash(FirstTA) ==
10740 ComputeTemplateArgumentODRHash(SecondTA)) {
10745 FirstRecord, FirstModule, FirstMethod->getLocation(),
10746 FirstMethod->getSourceRange(), MethodDifferentTemplateArgument)
10747 << FirstMethodType << FirstName << FirstTA << i + 1;
10748 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10749 SecondMethod->getSourceRange(),
10750 MethodDifferentTemplateArgument)
10751 << SecondMethodType << SecondName << SecondTA << i + 1;
10753 TemplateArgumentMismatch = true;
10757 if (TemplateArgumentMismatch) {
10763 // Compute the hash of the method as if it has no body.
10764 auto ComputeCXXMethodODRHash = [&Hash](const CXXMethodDecl *D) {
10766 Hash.AddFunctionDecl(D, true /*SkipBody*/);
10767 return Hash.CalculateHash();
10770 // Compare the hash generated to the hash stored. A difference means
10771 // that a body was present in the original source. Due to merging,
10772 // the stardard way of detecting a body will not work.
10773 const bool HasFirstBody =
10774 ComputeCXXMethodODRHash(FirstMethod) != FirstMethod->getODRHash();
10775 const bool HasSecondBody =
10776 ComputeCXXMethodODRHash(SecondMethod) != SecondMethod->getODRHash();
10778 if (HasFirstBody != HasSecondBody) {
10779 ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(),
10780 FirstMethod->getSourceRange(), MethodSingleBody)
10781 << FirstMethodType << FirstName << HasFirstBody;
10782 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10783 SecondMethod->getSourceRange(), MethodSingleBody)
10784 << SecondMethodType << SecondName << HasSecondBody;
10789 if (HasFirstBody && HasSecondBody) {
10790 ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(),
10791 FirstMethod->getSourceRange(), MethodDifferentBody)
10792 << FirstMethodType << FirstName;
10793 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10794 SecondMethod->getSourceRange(), MethodDifferentBody)
10795 << SecondMethodType << SecondName;
10804 Diagnosed = ODRDiagTypeDefOrAlias(
10805 FirstRecord, FirstModule, SecondModule,
10806 cast<TypedefNameDecl>(FirstDecl), cast<TypedefNameDecl>(SecondDecl),
10807 FirstDiffType == TypeAlias);
10812 ODRDiagVar(FirstRecord, FirstModule, SecondModule,
10813 cast<VarDecl>(FirstDecl), cast<VarDecl>(SecondDecl));
10817 FriendDecl *FirstFriend = cast<FriendDecl>(FirstDecl);
10818 FriendDecl *SecondFriend = cast<FriendDecl>(SecondDecl);
10820 NamedDecl *FirstND = FirstFriend->getFriendDecl();
10821 NamedDecl *SecondND = SecondFriend->getFriendDecl();
10823 TypeSourceInfo *FirstTSI = FirstFriend->getFriendType();
10824 TypeSourceInfo *SecondTSI = SecondFriend->getFriendType();
10826 if (FirstND && SecondND) {
10827 ODRDiagDeclError(FirstRecord, FirstModule,
10828 FirstFriend->getFriendLoc(),
10829 FirstFriend->getSourceRange(), FriendFunction)
10831 ODRDiagDeclNote(SecondModule, SecondFriend->getFriendLoc(),
10832 SecondFriend->getSourceRange(), FriendFunction)
10839 if (FirstTSI && SecondTSI) {
10840 QualType FirstFriendType = FirstTSI->getType();
10841 QualType SecondFriendType = SecondTSI->getType();
10842 assert(ComputeQualTypeODRHash(FirstFriendType) !=
10843 ComputeQualTypeODRHash(SecondFriendType));
10844 ODRDiagDeclError(FirstRecord, FirstModule,
10845 FirstFriend->getFriendLoc(),
10846 FirstFriend->getSourceRange(), FriendType)
10847 << FirstFriendType;
10848 ODRDiagDeclNote(SecondModule, SecondFriend->getFriendLoc(),
10849 SecondFriend->getSourceRange(), FriendType)
10850 << SecondFriendType;
10855 ODRDiagDeclError(FirstRecord, FirstModule, FirstFriend->getFriendLoc(),
10856 FirstFriend->getSourceRange(), FriendTypeFunction)
10857 << (FirstTSI == nullptr);
10858 ODRDiagDeclNote(SecondModule, SecondFriend->getFriendLoc(),
10859 SecondFriend->getSourceRange(), FriendTypeFunction)
10860 << (SecondTSI == nullptr);
10865 case FunctionTemplate: {
10866 FunctionTemplateDecl *FirstTemplate =
10867 cast<FunctionTemplateDecl>(FirstDecl);
10868 FunctionTemplateDecl *SecondTemplate =
10869 cast<FunctionTemplateDecl>(SecondDecl);
10871 TemplateParameterList *FirstTPL =
10872 FirstTemplate->getTemplateParameters();
10873 TemplateParameterList *SecondTPL =
10874 SecondTemplate->getTemplateParameters();
10876 if (FirstTPL->size() != SecondTPL->size()) {
10877 ODRDiagDeclError(FirstRecord, FirstModule,
10878 FirstTemplate->getLocation(),
10879 FirstTemplate->getSourceRange(),
10880 FunctionTemplateDifferentNumberParameters)
10881 << FirstTemplate << FirstTPL->size();
10882 ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(),
10883 SecondTemplate->getSourceRange(),
10884 FunctionTemplateDifferentNumberParameters)
10885 << SecondTemplate << SecondTPL->size();
10891 bool ParameterMismatch = false;
10892 for (unsigned i = 0, e = FirstTPL->size(); i != e; ++i) {
10893 NamedDecl *FirstParam = FirstTPL->getParam(i);
10894 NamedDecl *SecondParam = SecondTPL->getParam(i);
10896 if (FirstParam->getKind() != SecondParam->getKind()) {
10898 TemplateTypeParameter,
10899 NonTypeTemplateParameter,
10900 TemplateTemplateParameter,
10902 auto GetParamType = [](NamedDecl *D) {
10903 switch (D->getKind()) {
10905 llvm_unreachable("Unexpected template parameter type");
10906 case Decl::TemplateTypeParm:
10907 return TemplateTypeParameter;
10908 case Decl::NonTypeTemplateParm:
10909 return NonTypeTemplateParameter;
10910 case Decl::TemplateTemplateParm:
10911 return TemplateTemplateParameter;
10915 ODRDiagDeclError(FirstRecord, FirstModule,
10916 FirstTemplate->getLocation(),
10917 FirstTemplate->getSourceRange(),
10918 FunctionTemplateParameterDifferentKind)
10919 << FirstTemplate << (i + 1) << GetParamType(FirstParam);
10920 ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(),
10921 SecondTemplate->getSourceRange(),
10922 FunctionTemplateParameterDifferentKind)
10923 << SecondTemplate << (i + 1) << GetParamType(SecondParam);
10925 ParameterMismatch = true;
10929 if (FirstParam->getName() != SecondParam->getName()) {
10931 FirstRecord, FirstModule, FirstTemplate->getLocation(),
10932 FirstTemplate->getSourceRange(), FunctionTemplateParameterName)
10933 << FirstTemplate << (i + 1) << (bool)FirstParam->getIdentifier()
10935 ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(),
10936 SecondTemplate->getSourceRange(),
10937 FunctionTemplateParameterName)
10938 << SecondTemplate << (i + 1)
10939 << (bool)SecondParam->getIdentifier() << SecondParam;
10940 ParameterMismatch = true;
10944 if (isa<TemplateTypeParmDecl>(FirstParam) &&
10945 isa<TemplateTypeParmDecl>(SecondParam)) {
10946 TemplateTypeParmDecl *FirstTTPD =
10947 cast<TemplateTypeParmDecl>(FirstParam);
10948 TemplateTypeParmDecl *SecondTTPD =
10949 cast<TemplateTypeParmDecl>(SecondParam);
10950 bool HasFirstDefaultArgument =
10951 FirstTTPD->hasDefaultArgument() &&
10952 !FirstTTPD->defaultArgumentWasInherited();
10953 bool HasSecondDefaultArgument =
10954 SecondTTPD->hasDefaultArgument() &&
10955 !SecondTTPD->defaultArgumentWasInherited();
10956 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
10957 ODRDiagDeclError(FirstRecord, FirstModule,
10958 FirstTemplate->getLocation(),
10959 FirstTemplate->getSourceRange(),
10960 FunctionTemplateParameterSingleDefaultArgument)
10961 << FirstTemplate << (i + 1) << HasFirstDefaultArgument;
10962 ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(),
10963 SecondTemplate->getSourceRange(),
10964 FunctionTemplateParameterSingleDefaultArgument)
10965 << SecondTemplate << (i + 1) << HasSecondDefaultArgument;
10966 ParameterMismatch = true;
10970 if (HasFirstDefaultArgument && HasSecondDefaultArgument) {
10971 QualType FirstType = FirstTTPD->getDefaultArgument();
10972 QualType SecondType = SecondTTPD->getDefaultArgument();
10973 if (ComputeQualTypeODRHash(FirstType) !=
10974 ComputeQualTypeODRHash(SecondType)) {
10976 FirstRecord, FirstModule, FirstTemplate->getLocation(),
10977 FirstTemplate->getSourceRange(),
10978 FunctionTemplateParameterDifferentDefaultArgument)
10979 << FirstTemplate << (i + 1) << FirstType;
10981 SecondModule, SecondTemplate->getLocation(),
10982 SecondTemplate->getSourceRange(),
10983 FunctionTemplateParameterDifferentDefaultArgument)
10984 << SecondTemplate << (i + 1) << SecondType;
10985 ParameterMismatch = true;
10990 if (FirstTTPD->isParameterPack() !=
10991 SecondTTPD->isParameterPack()) {
10992 ODRDiagDeclError(FirstRecord, FirstModule,
10993 FirstTemplate->getLocation(),
10994 FirstTemplate->getSourceRange(),
10995 FunctionTemplatePackParameter)
10996 << FirstTemplate << (i + 1) << FirstTTPD->isParameterPack();
10997 ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(),
10998 SecondTemplate->getSourceRange(),
10999 FunctionTemplatePackParameter)
11000 << SecondTemplate << (i + 1) << SecondTTPD->isParameterPack();
11001 ParameterMismatch = true;
11006 if (isa<TemplateTemplateParmDecl>(FirstParam) &&
11007 isa<TemplateTemplateParmDecl>(SecondParam)) {
11008 TemplateTemplateParmDecl *FirstTTPD =
11009 cast<TemplateTemplateParmDecl>(FirstParam);
11010 TemplateTemplateParmDecl *SecondTTPD =
11011 cast<TemplateTemplateParmDecl>(SecondParam);
11013 TemplateParameterList *FirstTPL =
11014 FirstTTPD->getTemplateParameters();
11015 TemplateParameterList *SecondTPL =
11016 SecondTTPD->getTemplateParameters();
11018 if (ComputeTemplateParameterListODRHash(FirstTPL) !=
11019 ComputeTemplateParameterListODRHash(SecondTPL)) {
11020 ODRDiagDeclError(FirstRecord, FirstModule,
11021 FirstTemplate->getLocation(),
11022 FirstTemplate->getSourceRange(),
11023 FunctionTemplateParameterDifferentType)
11024 << FirstTemplate << (i + 1);
11025 ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(),
11026 SecondTemplate->getSourceRange(),
11027 FunctionTemplateParameterDifferentType)
11028 << SecondTemplate << (i + 1);
11029 ParameterMismatch = true;
11033 bool HasFirstDefaultArgument =
11034 FirstTTPD->hasDefaultArgument() &&
11035 !FirstTTPD->defaultArgumentWasInherited();
11036 bool HasSecondDefaultArgument =
11037 SecondTTPD->hasDefaultArgument() &&
11038 !SecondTTPD->defaultArgumentWasInherited();
11039 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
11040 ODRDiagDeclError(FirstRecord, FirstModule,
11041 FirstTemplate->getLocation(),
11042 FirstTemplate->getSourceRange(),
11043 FunctionTemplateParameterSingleDefaultArgument)
11044 << FirstTemplate << (i + 1) << HasFirstDefaultArgument;
11045 ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(),
11046 SecondTemplate->getSourceRange(),
11047 FunctionTemplateParameterSingleDefaultArgument)
11048 << SecondTemplate << (i + 1) << HasSecondDefaultArgument;
11049 ParameterMismatch = true;
11053 if (HasFirstDefaultArgument && HasSecondDefaultArgument) {
11054 TemplateArgument FirstTA =
11055 FirstTTPD->getDefaultArgument().getArgument();
11056 TemplateArgument SecondTA =
11057 SecondTTPD->getDefaultArgument().getArgument();
11058 if (ComputeTemplateArgumentODRHash(FirstTA) !=
11059 ComputeTemplateArgumentODRHash(SecondTA)) {
11061 FirstRecord, FirstModule, FirstTemplate->getLocation(),
11062 FirstTemplate->getSourceRange(),
11063 FunctionTemplateParameterDifferentDefaultArgument)
11064 << FirstTemplate << (i + 1) << FirstTA;
11066 SecondModule, SecondTemplate->getLocation(),
11067 SecondTemplate->getSourceRange(),
11068 FunctionTemplateParameterDifferentDefaultArgument)
11069 << SecondTemplate << (i + 1) << SecondTA;
11070 ParameterMismatch = true;
11075 if (FirstTTPD->isParameterPack() !=
11076 SecondTTPD->isParameterPack()) {
11077 ODRDiagDeclError(FirstRecord, FirstModule,
11078 FirstTemplate->getLocation(),
11079 FirstTemplate->getSourceRange(),
11080 FunctionTemplatePackParameter)
11081 << FirstTemplate << (i + 1) << FirstTTPD->isParameterPack();
11082 ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(),
11083 SecondTemplate->getSourceRange(),
11084 FunctionTemplatePackParameter)
11085 << SecondTemplate << (i + 1) << SecondTTPD->isParameterPack();
11086 ParameterMismatch = true;
11091 if (isa<NonTypeTemplateParmDecl>(FirstParam) &&
11092 isa<NonTypeTemplateParmDecl>(SecondParam)) {
11093 NonTypeTemplateParmDecl *FirstNTTPD =
11094 cast<NonTypeTemplateParmDecl>(FirstParam);
11095 NonTypeTemplateParmDecl *SecondNTTPD =
11096 cast<NonTypeTemplateParmDecl>(SecondParam);
11098 QualType FirstType = FirstNTTPD->getType();
11099 QualType SecondType = SecondNTTPD->getType();
11100 if (ComputeQualTypeODRHash(FirstType) !=
11101 ComputeQualTypeODRHash(SecondType)) {
11102 ODRDiagDeclError(FirstRecord, FirstModule,
11103 FirstTemplate->getLocation(),
11104 FirstTemplate->getSourceRange(),
11105 FunctionTemplateParameterDifferentType)
11106 << FirstTemplate << (i + 1);
11107 ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(),
11108 SecondTemplate->getSourceRange(),
11109 FunctionTemplateParameterDifferentType)
11110 << SecondTemplate << (i + 1);
11111 ParameterMismatch = true;
11115 bool HasFirstDefaultArgument =
11116 FirstNTTPD->hasDefaultArgument() &&
11117 !FirstNTTPD->defaultArgumentWasInherited();
11118 bool HasSecondDefaultArgument =
11119 SecondNTTPD->hasDefaultArgument() &&
11120 !SecondNTTPD->defaultArgumentWasInherited();
11121 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
11122 ODRDiagDeclError(FirstRecord, FirstModule,
11123 FirstTemplate->getLocation(),
11124 FirstTemplate->getSourceRange(),
11125 FunctionTemplateParameterSingleDefaultArgument)
11126 << FirstTemplate << (i + 1) << HasFirstDefaultArgument;
11127 ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(),
11128 SecondTemplate->getSourceRange(),
11129 FunctionTemplateParameterSingleDefaultArgument)
11130 << SecondTemplate << (i + 1) << HasSecondDefaultArgument;
11131 ParameterMismatch = true;
11135 if (HasFirstDefaultArgument && HasSecondDefaultArgument) {
11136 Expr *FirstDefaultArgument = FirstNTTPD->getDefaultArgument();
11137 Expr *SecondDefaultArgument = SecondNTTPD->getDefaultArgument();
11138 if (ComputeODRHash(FirstDefaultArgument) !=
11139 ComputeODRHash(SecondDefaultArgument)) {
11141 FirstRecord, FirstModule, FirstTemplate->getLocation(),
11142 FirstTemplate->getSourceRange(),
11143 FunctionTemplateParameterDifferentDefaultArgument)
11144 << FirstTemplate << (i + 1) << FirstDefaultArgument;
11146 SecondModule, SecondTemplate->getLocation(),
11147 SecondTemplate->getSourceRange(),
11148 FunctionTemplateParameterDifferentDefaultArgument)
11149 << SecondTemplate << (i + 1) << SecondDefaultArgument;
11150 ParameterMismatch = true;
11155 if (FirstNTTPD->isParameterPack() !=
11156 SecondNTTPD->isParameterPack()) {
11157 ODRDiagDeclError(FirstRecord, FirstModule,
11158 FirstTemplate->getLocation(),
11159 FirstTemplate->getSourceRange(),
11160 FunctionTemplatePackParameter)
11161 << FirstTemplate << (i + 1) << FirstNTTPD->isParameterPack();
11162 ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(),
11163 SecondTemplate->getSourceRange(),
11164 FunctionTemplatePackParameter)
11165 << SecondTemplate << (i + 1)
11166 << SecondNTTPD->isParameterPack();
11167 ParameterMismatch = true;
11173 if (ParameterMismatch) {
11185 Diag(FirstDecl->getLocation(),
11186 diag::err_module_odr_violation_mismatch_decl_unknown)
11187 << FirstRecord << FirstModule.empty() << FirstModule << FirstDiffType
11188 << FirstDecl->getSourceRange();
11189 Diag(SecondDecl->getLocation(),
11190 diag::note_module_odr_violation_mismatch_decl_unknown)
11191 << SecondModule << FirstDiffType << SecondDecl->getSourceRange();
11196 // All definitions are updates to the same declaration. This happens if a
11197 // module instantiates the declaration of a class template specialization
11198 // and two or more other modules instantiate its definition.
11200 // FIXME: Indicate which modules had instantiations of this definition.
11201 // FIXME: How can this even happen?
11202 Diag(Merge.first->getLocation(),
11203 diag::err_module_odr_violation_different_instantiations)
11208 // Issue ODR failures diagnostics for functions.
11209 for (auto &Merge : FunctionOdrMergeFailures) {
11210 enum ODRFunctionDifference {
11214 ParameterSingleDefaultArgument,
11215 ParameterDifferentDefaultArgument,
11219 FunctionDecl *FirstFunction = Merge.first;
11220 std::string FirstModule = getOwningModuleNameForDiagnostic(FirstFunction);
11222 bool Diagnosed = false;
11223 for (auto &SecondFunction : Merge.second) {
11225 if (FirstFunction == SecondFunction)
11228 std::string SecondModule =
11229 getOwningModuleNameForDiagnostic(SecondFunction);
11231 auto ODRDiagError = [FirstFunction, &FirstModule,
11232 this](SourceLocation Loc, SourceRange Range,
11233 ODRFunctionDifference DiffType) {
11234 return Diag(Loc, diag::err_module_odr_violation_function)
11235 << FirstFunction << FirstModule.empty() << FirstModule << Range
11238 auto ODRDiagNote = [&SecondModule, this](SourceLocation Loc,
11240 ODRFunctionDifference DiffType) {
11241 return Diag(Loc, diag::note_module_odr_violation_function)
11242 << SecondModule << Range << DiffType;
11245 if (ComputeQualTypeODRHash(FirstFunction->getReturnType()) !=
11246 ComputeQualTypeODRHash(SecondFunction->getReturnType())) {
11247 ODRDiagError(FirstFunction->getReturnTypeSourceRange().getBegin(),
11248 FirstFunction->getReturnTypeSourceRange(), ReturnType)
11249 << FirstFunction->getReturnType();
11250 ODRDiagNote(SecondFunction->getReturnTypeSourceRange().getBegin(),
11251 SecondFunction->getReturnTypeSourceRange(), ReturnType)
11252 << SecondFunction->getReturnType();
11257 assert(FirstFunction->param_size() == SecondFunction->param_size() &&
11258 "Merged functions with different number of parameters");
11260 auto ParamSize = FirstFunction->param_size();
11261 bool ParameterMismatch = false;
11262 for (unsigned I = 0; I < ParamSize; ++I) {
11263 auto *FirstParam = FirstFunction->getParamDecl(I);
11264 auto *SecondParam = SecondFunction->getParamDecl(I);
11266 assert(getContext().hasSameType(FirstParam->getType(),
11267 SecondParam->getType()) &&
11268 "Merged function has different parameter types.");
11270 if (FirstParam->getDeclName() != SecondParam->getDeclName()) {
11271 ODRDiagError(FirstParam->getLocation(), FirstParam->getSourceRange(),
11273 << I + 1 << FirstParam->getDeclName();
11274 ODRDiagNote(SecondParam->getLocation(), SecondParam->getSourceRange(),
11276 << I + 1 << SecondParam->getDeclName();
11277 ParameterMismatch = true;
11281 QualType FirstParamType = FirstParam->getType();
11282 QualType SecondParamType = SecondParam->getType();
11283 if (FirstParamType != SecondParamType &&
11284 ComputeQualTypeODRHash(FirstParamType) !=
11285 ComputeQualTypeODRHash(SecondParamType)) {
11286 if (const DecayedType *ParamDecayedType =
11287 FirstParamType->getAs<DecayedType>()) {
11288 ODRDiagError(FirstParam->getLocation(),
11289 FirstParam->getSourceRange(), ParameterType)
11290 << (I + 1) << FirstParamType << true
11291 << ParamDecayedType->getOriginalType();
11293 ODRDiagError(FirstParam->getLocation(),
11294 FirstParam->getSourceRange(), ParameterType)
11295 << (I + 1) << FirstParamType << false;
11298 if (const DecayedType *ParamDecayedType =
11299 SecondParamType->getAs<DecayedType>()) {
11300 ODRDiagNote(SecondParam->getLocation(),
11301 SecondParam->getSourceRange(), ParameterType)
11302 << (I + 1) << SecondParamType << true
11303 << ParamDecayedType->getOriginalType();
11305 ODRDiagNote(SecondParam->getLocation(),
11306 SecondParam->getSourceRange(), ParameterType)
11307 << (I + 1) << SecondParamType << false;
11309 ParameterMismatch = true;
11313 const Expr *FirstInit = FirstParam->getInit();
11314 const Expr *SecondInit = SecondParam->getInit();
11315 if ((FirstInit == nullptr) != (SecondInit == nullptr)) {
11316 ODRDiagError(FirstParam->getLocation(), FirstParam->getSourceRange(),
11317 ParameterSingleDefaultArgument)
11318 << (I + 1) << (FirstInit == nullptr)
11319 << (FirstInit ? FirstInit->getSourceRange() : SourceRange());
11320 ODRDiagNote(SecondParam->getLocation(), SecondParam->getSourceRange(),
11321 ParameterSingleDefaultArgument)
11322 << (I + 1) << (SecondInit == nullptr)
11323 << (SecondInit ? SecondInit->getSourceRange() : SourceRange());
11324 ParameterMismatch = true;
11328 if (FirstInit && SecondInit &&
11329 ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
11330 ODRDiagError(FirstParam->getLocation(), FirstParam->getSourceRange(),
11331 ParameterDifferentDefaultArgument)
11332 << (I + 1) << FirstInit->getSourceRange();
11333 ODRDiagNote(SecondParam->getLocation(), SecondParam->getSourceRange(),
11334 ParameterDifferentDefaultArgument)
11335 << (I + 1) << SecondInit->getSourceRange();
11336 ParameterMismatch = true;
11340 assert(ComputeSubDeclODRHash(FirstParam) ==
11341 ComputeSubDeclODRHash(SecondParam) &&
11342 "Undiagnosed parameter difference.");
11345 if (ParameterMismatch) {
11350 // If no error has been generated before now, assume the problem is in
11351 // the body and generate a message.
11352 ODRDiagError(FirstFunction->getLocation(),
11353 FirstFunction->getSourceRange(), FunctionBody);
11354 ODRDiagNote(SecondFunction->getLocation(),
11355 SecondFunction->getSourceRange(), FunctionBody);
11360 assert(Diagnosed && "Unable to emit ODR diagnostic.");
11363 // Issue ODR failures diagnostics for enums.
11364 for (auto &Merge : EnumOdrMergeFailures) {
11365 enum ODREnumDifference {
11367 EnumTagKeywordMismatch,
11368 SingleSpecifiedType,
11369 DifferentSpecifiedTypes,
11370 DifferentNumberEnumConstants,
11372 EnumConstantSingleInitilizer,
11373 EnumConstantDifferentInitilizer,
11376 // If we've already pointed out a specific problem with this enum, don't
11377 // bother issuing a general "something's different" diagnostic.
11378 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
11381 EnumDecl *FirstEnum = Merge.first;
11382 std::string FirstModule = getOwningModuleNameForDiagnostic(FirstEnum);
11385 llvm::SmallVector<std::pair<EnumConstantDecl *, unsigned>, 4>;
11386 auto PopulateHashes = [&ComputeSubDeclODRHash, FirstEnum](
11387 DeclHashes &Hashes, EnumDecl *Enum) {
11388 for (auto *D : Enum->decls()) {
11389 // Due to decl merging, the first EnumDecl is the parent of
11390 // Decls in both records.
11391 if (!ODRHash::isDeclToBeProcessed(D, FirstEnum))
11393 assert(isa<EnumConstantDecl>(D) && "Unexpected Decl kind");
11394 Hashes.emplace_back(cast<EnumConstantDecl>(D),
11395 ComputeSubDeclODRHash(D));
11398 DeclHashes FirstHashes;
11399 PopulateHashes(FirstHashes, FirstEnum);
11400 bool Diagnosed = false;
11401 for (auto &SecondEnum : Merge.second) {
11403 if (FirstEnum == SecondEnum)
11406 std::string SecondModule =
11407 getOwningModuleNameForDiagnostic(SecondEnum);
11409 auto ODRDiagError = [FirstEnum, &FirstModule,
11410 this](SourceLocation Loc, SourceRange Range,
11411 ODREnumDifference DiffType) {
11412 return Diag(Loc, diag::err_module_odr_violation_enum)
11413 << FirstEnum << FirstModule.empty() << FirstModule << Range
11416 auto ODRDiagNote = [&SecondModule, this](SourceLocation Loc,
11418 ODREnumDifference DiffType) {
11419 return Diag(Loc, diag::note_module_odr_violation_enum)
11420 << SecondModule << Range << DiffType;
11423 if (FirstEnum->isScoped() != SecondEnum->isScoped()) {
11424 ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
11426 << FirstEnum->isScoped();
11427 ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
11429 << SecondEnum->isScoped();
11434 if (FirstEnum->isScoped() && SecondEnum->isScoped()) {
11435 if (FirstEnum->isScopedUsingClassTag() !=
11436 SecondEnum->isScopedUsingClassTag()) {
11437 ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
11438 EnumTagKeywordMismatch)
11439 << FirstEnum->isScopedUsingClassTag();
11440 ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
11441 EnumTagKeywordMismatch)
11442 << SecondEnum->isScopedUsingClassTag();
11448 QualType FirstUnderlyingType =
11449 FirstEnum->getIntegerTypeSourceInfo()
11450 ? FirstEnum->getIntegerTypeSourceInfo()->getType()
11452 QualType SecondUnderlyingType =
11453 SecondEnum->getIntegerTypeSourceInfo()
11454 ? SecondEnum->getIntegerTypeSourceInfo()->getType()
11456 if (FirstUnderlyingType.isNull() != SecondUnderlyingType.isNull()) {
11457 ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
11458 SingleSpecifiedType)
11459 << !FirstUnderlyingType.isNull();
11460 ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
11461 SingleSpecifiedType)
11462 << !SecondUnderlyingType.isNull();
11467 if (!FirstUnderlyingType.isNull() && !SecondUnderlyingType.isNull()) {
11468 if (ComputeQualTypeODRHash(FirstUnderlyingType) !=
11469 ComputeQualTypeODRHash(SecondUnderlyingType)) {
11470 ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
11471 DifferentSpecifiedTypes)
11472 << FirstUnderlyingType;
11473 ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
11474 DifferentSpecifiedTypes)
11475 << SecondUnderlyingType;
11481 DeclHashes SecondHashes;
11482 PopulateHashes(SecondHashes, SecondEnum);
11484 if (FirstHashes.size() != SecondHashes.size()) {
11485 ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
11486 DifferentNumberEnumConstants)
11487 << (int)FirstHashes.size();
11488 ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
11489 DifferentNumberEnumConstants)
11490 << (int)SecondHashes.size();
11495 for (unsigned I = 0; I < FirstHashes.size(); ++I) {
11496 if (FirstHashes[I].second == SecondHashes[I].second)
11498 const EnumConstantDecl *FirstEnumConstant = FirstHashes[I].first;
11499 const EnumConstantDecl *SecondEnumConstant = SecondHashes[I].first;
11501 if (FirstEnumConstant->getDeclName() !=
11502 SecondEnumConstant->getDeclName()) {
11504 ODRDiagError(FirstEnumConstant->getLocation(),
11505 FirstEnumConstant->getSourceRange(), EnumConstantName)
11506 << I + 1 << FirstEnumConstant;
11507 ODRDiagNote(SecondEnumConstant->getLocation(),
11508 SecondEnumConstant->getSourceRange(), EnumConstantName)
11509 << I + 1 << SecondEnumConstant;
11514 const Expr *FirstInit = FirstEnumConstant->getInitExpr();
11515 const Expr *SecondInit = SecondEnumConstant->getInitExpr();
11516 if (!FirstInit && !SecondInit)
11519 if (!FirstInit || !SecondInit) {
11520 ODRDiagError(FirstEnumConstant->getLocation(),
11521 FirstEnumConstant->getSourceRange(),
11522 EnumConstantSingleInitilizer)
11523 << I + 1 << FirstEnumConstant << (FirstInit != nullptr);
11524 ODRDiagNote(SecondEnumConstant->getLocation(),
11525 SecondEnumConstant->getSourceRange(),
11526 EnumConstantSingleInitilizer)
11527 << I + 1 << SecondEnumConstant << (SecondInit != nullptr);
11532 if (ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
11533 ODRDiagError(FirstEnumConstant->getLocation(),
11534 FirstEnumConstant->getSourceRange(),
11535 EnumConstantDifferentInitilizer)
11536 << I + 1 << FirstEnumConstant;
11537 ODRDiagNote(SecondEnumConstant->getLocation(),
11538 SecondEnumConstant->getSourceRange(),
11539 EnumConstantDifferentInitilizer)
11540 << I + 1 << SecondEnumConstant;
11548 assert(Diagnosed && "Unable to emit ODR diagnostic.");
11552 void ASTReader::StartedDeserializing() {
11553 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
11554 ReadTimer->startTimer();
11557 void ASTReader::FinishedDeserializing() {
11558 assert(NumCurrentElementsDeserializing &&
11559 "FinishedDeserializing not paired with StartedDeserializing");
11560 if (NumCurrentElementsDeserializing == 1) {
11561 // We decrease NumCurrentElementsDeserializing only after pending actions
11562 // are finished, to avoid recursively re-calling finishPendingActions().
11563 finishPendingActions();
11565 --NumCurrentElementsDeserializing;
11567 if (NumCurrentElementsDeserializing == 0) {
11568 // Propagate exception specification and deduced type updates along
11569 // redeclaration chains.
11571 // We do this now rather than in finishPendingActions because we want to
11572 // be able to walk the complete redeclaration chains of the updated decls.
11573 while (!PendingExceptionSpecUpdates.empty() ||
11574 !PendingDeducedTypeUpdates.empty()) {
11575 auto ESUpdates = std::move(PendingExceptionSpecUpdates);
11576 PendingExceptionSpecUpdates.clear();
11577 for (auto Update : ESUpdates) {
11578 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
11579 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
11580 auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
11581 if (auto *Listener = getContext().getASTMutationListener())
11582 Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
11583 for (auto *Redecl : Update.second->redecls())
11584 getContext().adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
11587 auto DTUpdates = std::move(PendingDeducedTypeUpdates);
11588 PendingDeducedTypeUpdates.clear();
11589 for (auto Update : DTUpdates) {
11590 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
11591 // FIXME: If the return type is already deduced, check that it matches.
11592 getContext().adjustDeducedFunctionResultType(Update.first,
11598 ReadTimer->stopTimer();
11600 diagnoseOdrViolations();
11602 // We are not in recursive loading, so it's safe to pass the "interesting"
11603 // decls to the consumer.
11605 PassInterestingDeclsToConsumer();
11609 void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
11610 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
11611 // Remove any fake results before adding any real ones.
11612 auto It = PendingFakeLookupResults.find(II);
11613 if (It != PendingFakeLookupResults.end()) {
11614 for (auto *ND : It->second)
11615 SemaObj->IdResolver.RemoveDecl(ND);
11616 // FIXME: this works around module+PCH performance issue.
11617 // Rather than erase the result from the map, which is O(n), just clear
11618 // the vector of NamedDecls.
11619 It->second.clear();
11623 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
11624 SemaObj->TUScope->AddDecl(D);
11625 } else if (SemaObj->TUScope) {
11626 // Adding the decl to IdResolver may have failed because it was already in
11627 // (even though it was not added in scope). If it is already in, make sure
11628 // it gets in the scope as well.
11629 if (std::find(SemaObj->IdResolver.begin(Name),
11630 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
11631 SemaObj->TUScope->AddDecl(D);
11635 ASTReader::ASTReader(Preprocessor &PP, InMemoryModuleCache &ModuleCache,
11636 ASTContext *Context,
11637 const PCHContainerReader &PCHContainerRdr,
11638 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
11639 StringRef isysroot,
11640 DisableValidationForModuleKind DisableValidationKind,
11641 bool AllowASTWithCompilerErrors,
11642 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
11643 bool ValidateASTInputFilesContent, bool UseGlobalIndex,
11644 std::unique_ptr<llvm::Timer> ReadTimer)
11645 : Listener(bool(DisableValidationKind &DisableValidationForModuleKind::PCH)
11646 ? cast<ASTReaderListener>(new SimpleASTReaderListener(PP))
11647 : cast<ASTReaderListener>(new PCHValidator(PP, *this))),
11648 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
11649 PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()), PP(PP),
11650 ContextObj(Context), ModuleMgr(PP.getFileManager(), ModuleCache,
11651 PCHContainerRdr, PP.getHeaderSearchInfo()),
11652 DummyIdResolver(PP), ReadTimer(std::move(ReadTimer)), isysroot(isysroot),
11653 DisableValidationKind(DisableValidationKind),
11654 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
11655 AllowConfigurationMismatch(AllowConfigurationMismatch),
11656 ValidateSystemInputs(ValidateSystemInputs),
11657 ValidateASTInputFilesContent(ValidateASTInputFilesContent),
11658 UseGlobalIndex(UseGlobalIndex), CurrSwitchCaseStmts(&SwitchCaseStmts) {
11659 SourceMgr.setExternalSLocEntrySource(this);
11661 for (const auto &Ext : Extensions) {
11662 auto BlockName = Ext->getExtensionMetadata().BlockName;
11663 auto Known = ModuleFileExtensions.find(BlockName);
11664 if (Known != ModuleFileExtensions.end()) {
11665 Diags.Report(diag::warn_duplicate_module_file_extension)
11670 ModuleFileExtensions.insert({BlockName, Ext});
11674 ASTReader::~ASTReader() {
11675 if (OwnsDeserializationListener)
11676 delete DeserializationListener;
11679 IdentifierResolver &ASTReader::getIdResolver() {
11680 return SemaObj ? SemaObj->IdResolver : DummyIdResolver;
11683 Expected<unsigned> ASTRecordReader::readRecord(llvm::BitstreamCursor &Cursor,
11684 unsigned AbbrevID) {
11687 return Cursor.readRecord(AbbrevID, Record);
11689 //===----------------------------------------------------------------------===//
11690 //// OMPClauseReader implementation
11691 ////===----------------------------------------------------------------------===//
11693 // This has to be in namespace clang because it's friended by all
11694 // of the OMP clauses.
11697 class OMPClauseReader : public OMPClauseVisitor<OMPClauseReader> {
11698 ASTRecordReader &Record;
11699 ASTContext &Context;
11702 OMPClauseReader(ASTRecordReader &Record)
11703 : Record(Record), Context(Record.getContext()) {}
11704 #define GEN_CLANG_CLAUSE_CLASS
11705 #define CLAUSE_CLASS(Enum, Str, Class) void Visit##Class(Class *C);
11706 #include "llvm/Frontend/OpenMP/OMP.inc"
11707 OMPClause *readClause();
11708 void VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C);
11709 void VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C);
11712 } // end namespace clang
11714 OMPClause *ASTRecordReader::readOMPClause() {
11715 return OMPClauseReader(*this).readClause();
11718 OMPClause *OMPClauseReader::readClause() {
11719 OMPClause *C = nullptr;
11720 switch (llvm::omp::Clause(Record.readInt())) {
11721 case llvm::omp::OMPC_if:
11722 C = new (Context) OMPIfClause();
11724 case llvm::omp::OMPC_final:
11725 C = new (Context) OMPFinalClause();
11727 case llvm::omp::OMPC_num_threads:
11728 C = new (Context) OMPNumThreadsClause();
11730 case llvm::omp::OMPC_safelen:
11731 C = new (Context) OMPSafelenClause();
11733 case llvm::omp::OMPC_simdlen:
11734 C = new (Context) OMPSimdlenClause();
11736 case llvm::omp::OMPC_sizes: {
11737 unsigned NumSizes = Record.readInt();
11738 C = OMPSizesClause::CreateEmpty(Context, NumSizes);
11741 case llvm::omp::OMPC_full:
11742 C = OMPFullClause::CreateEmpty(Context);
11744 case llvm::omp::OMPC_partial:
11745 C = OMPPartialClause::CreateEmpty(Context);
11747 case llvm::omp::OMPC_allocator:
11748 C = new (Context) OMPAllocatorClause();
11750 case llvm::omp::OMPC_collapse:
11751 C = new (Context) OMPCollapseClause();
11753 case llvm::omp::OMPC_default:
11754 C = new (Context) OMPDefaultClause();
11756 case llvm::omp::OMPC_proc_bind:
11757 C = new (Context) OMPProcBindClause();
11759 case llvm::omp::OMPC_schedule:
11760 C = new (Context) OMPScheduleClause();
11762 case llvm::omp::OMPC_ordered:
11763 C = OMPOrderedClause::CreateEmpty(Context, Record.readInt());
11765 case llvm::omp::OMPC_nowait:
11766 C = new (Context) OMPNowaitClause();
11768 case llvm::omp::OMPC_untied:
11769 C = new (Context) OMPUntiedClause();
11771 case llvm::omp::OMPC_mergeable:
11772 C = new (Context) OMPMergeableClause();
11774 case llvm::omp::OMPC_read:
11775 C = new (Context) OMPReadClause();
11777 case llvm::omp::OMPC_write:
11778 C = new (Context) OMPWriteClause();
11780 case llvm::omp::OMPC_update:
11781 C = OMPUpdateClause::CreateEmpty(Context, Record.readInt());
11783 case llvm::omp::OMPC_capture:
11784 C = new (Context) OMPCaptureClause();
11786 case llvm::omp::OMPC_compare:
11787 C = new (Context) OMPCompareClause();
11789 case llvm::omp::OMPC_seq_cst:
11790 C = new (Context) OMPSeqCstClause();
11792 case llvm::omp::OMPC_acq_rel:
11793 C = new (Context) OMPAcqRelClause();
11795 case llvm::omp::OMPC_acquire:
11796 C = new (Context) OMPAcquireClause();
11798 case llvm::omp::OMPC_release:
11799 C = new (Context) OMPReleaseClause();
11801 case llvm::omp::OMPC_relaxed:
11802 C = new (Context) OMPRelaxedClause();
11804 case llvm::omp::OMPC_threads:
11805 C = new (Context) OMPThreadsClause();
11807 case llvm::omp::OMPC_simd:
11808 C = new (Context) OMPSIMDClause();
11810 case llvm::omp::OMPC_nogroup:
11811 C = new (Context) OMPNogroupClause();
11813 case llvm::omp::OMPC_unified_address:
11814 C = new (Context) OMPUnifiedAddressClause();
11816 case llvm::omp::OMPC_unified_shared_memory:
11817 C = new (Context) OMPUnifiedSharedMemoryClause();
11819 case llvm::omp::OMPC_reverse_offload:
11820 C = new (Context) OMPReverseOffloadClause();
11822 case llvm::omp::OMPC_dynamic_allocators:
11823 C = new (Context) OMPDynamicAllocatorsClause();
11825 case llvm::omp::OMPC_atomic_default_mem_order:
11826 C = new (Context) OMPAtomicDefaultMemOrderClause();
11828 case llvm::omp::OMPC_private:
11829 C = OMPPrivateClause::CreateEmpty(Context, Record.readInt());
11831 case llvm::omp::OMPC_firstprivate:
11832 C = OMPFirstprivateClause::CreateEmpty(Context, Record.readInt());
11834 case llvm::omp::OMPC_lastprivate:
11835 C = OMPLastprivateClause::CreateEmpty(Context, Record.readInt());
11837 case llvm::omp::OMPC_shared:
11838 C = OMPSharedClause::CreateEmpty(Context, Record.readInt());
11840 case llvm::omp::OMPC_reduction: {
11841 unsigned N = Record.readInt();
11842 auto Modifier = Record.readEnum<OpenMPReductionClauseModifier>();
11843 C = OMPReductionClause::CreateEmpty(Context, N, Modifier);
11846 case llvm::omp::OMPC_task_reduction:
11847 C = OMPTaskReductionClause::CreateEmpty(Context, Record.readInt());
11849 case llvm::omp::OMPC_in_reduction:
11850 C = OMPInReductionClause::CreateEmpty(Context, Record.readInt());
11852 case llvm::omp::OMPC_linear:
11853 C = OMPLinearClause::CreateEmpty(Context, Record.readInt());
11855 case llvm::omp::OMPC_aligned:
11856 C = OMPAlignedClause::CreateEmpty(Context, Record.readInt());
11858 case llvm::omp::OMPC_copyin:
11859 C = OMPCopyinClause::CreateEmpty(Context, Record.readInt());
11861 case llvm::omp::OMPC_copyprivate:
11862 C = OMPCopyprivateClause::CreateEmpty(Context, Record.readInt());
11864 case llvm::omp::OMPC_flush:
11865 C = OMPFlushClause::CreateEmpty(Context, Record.readInt());
11867 case llvm::omp::OMPC_depobj:
11868 C = OMPDepobjClause::CreateEmpty(Context);
11870 case llvm::omp::OMPC_depend: {
11871 unsigned NumVars = Record.readInt();
11872 unsigned NumLoops = Record.readInt();
11873 C = OMPDependClause::CreateEmpty(Context, NumVars, NumLoops);
11876 case llvm::omp::OMPC_device:
11877 C = new (Context) OMPDeviceClause();
11879 case llvm::omp::OMPC_map: {
11880 OMPMappableExprListSizeTy Sizes;
11881 Sizes.NumVars = Record.readInt();
11882 Sizes.NumUniqueDeclarations = Record.readInt();
11883 Sizes.NumComponentLists = Record.readInt();
11884 Sizes.NumComponents = Record.readInt();
11885 C = OMPMapClause::CreateEmpty(Context, Sizes);
11888 case llvm::omp::OMPC_num_teams:
11889 C = new (Context) OMPNumTeamsClause();
11891 case llvm::omp::OMPC_thread_limit:
11892 C = new (Context) OMPThreadLimitClause();
11894 case llvm::omp::OMPC_priority:
11895 C = new (Context) OMPPriorityClause();
11897 case llvm::omp::OMPC_grainsize:
11898 C = new (Context) OMPGrainsizeClause();
11900 case llvm::omp::OMPC_num_tasks:
11901 C = new (Context) OMPNumTasksClause();
11903 case llvm::omp::OMPC_hint:
11904 C = new (Context) OMPHintClause();
11906 case llvm::omp::OMPC_dist_schedule:
11907 C = new (Context) OMPDistScheduleClause();
11909 case llvm::omp::OMPC_defaultmap:
11910 C = new (Context) OMPDefaultmapClause();
11912 case llvm::omp::OMPC_to: {
11913 OMPMappableExprListSizeTy Sizes;
11914 Sizes.NumVars = Record.readInt();
11915 Sizes.NumUniqueDeclarations = Record.readInt();
11916 Sizes.NumComponentLists = Record.readInt();
11917 Sizes.NumComponents = Record.readInt();
11918 C = OMPToClause::CreateEmpty(Context, Sizes);
11921 case llvm::omp::OMPC_from: {
11922 OMPMappableExprListSizeTy Sizes;
11923 Sizes.NumVars = Record.readInt();
11924 Sizes.NumUniqueDeclarations = Record.readInt();
11925 Sizes.NumComponentLists = Record.readInt();
11926 Sizes.NumComponents = Record.readInt();
11927 C = OMPFromClause::CreateEmpty(Context, Sizes);
11930 case llvm::omp::OMPC_use_device_ptr: {
11931 OMPMappableExprListSizeTy Sizes;
11932 Sizes.NumVars = Record.readInt();
11933 Sizes.NumUniqueDeclarations = Record.readInt();
11934 Sizes.NumComponentLists = Record.readInt();
11935 Sizes.NumComponents = Record.readInt();
11936 C = OMPUseDevicePtrClause::CreateEmpty(Context, Sizes);
11939 case llvm::omp::OMPC_use_device_addr: {
11940 OMPMappableExprListSizeTy Sizes;
11941 Sizes.NumVars = Record.readInt();
11942 Sizes.NumUniqueDeclarations = Record.readInt();
11943 Sizes.NumComponentLists = Record.readInt();
11944 Sizes.NumComponents = Record.readInt();
11945 C = OMPUseDeviceAddrClause::CreateEmpty(Context, Sizes);
11948 case llvm::omp::OMPC_is_device_ptr: {
11949 OMPMappableExprListSizeTy Sizes;
11950 Sizes.NumVars = Record.readInt();
11951 Sizes.NumUniqueDeclarations = Record.readInt();
11952 Sizes.NumComponentLists = Record.readInt();
11953 Sizes.NumComponents = Record.readInt();
11954 C = OMPIsDevicePtrClause::CreateEmpty(Context, Sizes);
11957 case llvm::omp::OMPC_allocate:
11958 C = OMPAllocateClause::CreateEmpty(Context, Record.readInt());
11960 case llvm::omp::OMPC_nontemporal:
11961 C = OMPNontemporalClause::CreateEmpty(Context, Record.readInt());
11963 case llvm::omp::OMPC_inclusive:
11964 C = OMPInclusiveClause::CreateEmpty(Context, Record.readInt());
11966 case llvm::omp::OMPC_exclusive:
11967 C = OMPExclusiveClause::CreateEmpty(Context, Record.readInt());
11969 case llvm::omp::OMPC_order:
11970 C = new (Context) OMPOrderClause();
11972 case llvm::omp::OMPC_init:
11973 C = OMPInitClause::CreateEmpty(Context, Record.readInt());
11975 case llvm::omp::OMPC_use:
11976 C = new (Context) OMPUseClause();
11978 case llvm::omp::OMPC_destroy:
11979 C = new (Context) OMPDestroyClause();
11981 case llvm::omp::OMPC_novariants:
11982 C = new (Context) OMPNovariantsClause();
11984 case llvm::omp::OMPC_nocontext:
11985 C = new (Context) OMPNocontextClause();
11987 case llvm::omp::OMPC_detach:
11988 C = new (Context) OMPDetachClause();
11990 case llvm::omp::OMPC_uses_allocators:
11991 C = OMPUsesAllocatorsClause::CreateEmpty(Context, Record.readInt());
11993 case llvm::omp::OMPC_affinity:
11994 C = OMPAffinityClause::CreateEmpty(Context, Record.readInt());
11996 case llvm::omp::OMPC_filter:
11997 C = new (Context) OMPFilterClause();
11999 case llvm::omp::OMPC_bind:
12000 C = OMPBindClause::CreateEmpty(Context);
12002 case llvm::omp::OMPC_align:
12003 C = new (Context) OMPAlignClause();
12005 #define OMP_CLAUSE_NO_CLASS(Enum, Str) \
12006 case llvm::omp::Enum: \
12008 #include "llvm/Frontend/OpenMP/OMPKinds.def"
12012 assert(C && "Unknown OMPClause type");
12015 C->setLocStart(Record.readSourceLocation());
12016 C->setLocEnd(Record.readSourceLocation());
12021 void OMPClauseReader::VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C) {
12022 C->setPreInitStmt(Record.readSubStmt(),
12023 static_cast<OpenMPDirectiveKind>(Record.readInt()));
12026 void OMPClauseReader::VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C) {
12027 VisitOMPClauseWithPreInit(C);
12028 C->setPostUpdateExpr(Record.readSubExpr());
12031 void OMPClauseReader::VisitOMPIfClause(OMPIfClause *C) {
12032 VisitOMPClauseWithPreInit(C);
12033 C->setNameModifier(static_cast<OpenMPDirectiveKind>(Record.readInt()));
12034 C->setNameModifierLoc(Record.readSourceLocation());
12035 C->setColonLoc(Record.readSourceLocation());
12036 C->setCondition(Record.readSubExpr());
12037 C->setLParenLoc(Record.readSourceLocation());
12040 void OMPClauseReader::VisitOMPFinalClause(OMPFinalClause *C) {
12041 VisitOMPClauseWithPreInit(C);
12042 C->setCondition(Record.readSubExpr());
12043 C->setLParenLoc(Record.readSourceLocation());
12046 void OMPClauseReader::VisitOMPNumThreadsClause(OMPNumThreadsClause *C) {
12047 VisitOMPClauseWithPreInit(C);
12048 C->setNumThreads(Record.readSubExpr());
12049 C->setLParenLoc(Record.readSourceLocation());
12052 void OMPClauseReader::VisitOMPSafelenClause(OMPSafelenClause *C) {
12053 C->setSafelen(Record.readSubExpr());
12054 C->setLParenLoc(Record.readSourceLocation());
12057 void OMPClauseReader::VisitOMPSimdlenClause(OMPSimdlenClause *C) {
12058 C->setSimdlen(Record.readSubExpr());
12059 C->setLParenLoc(Record.readSourceLocation());
12062 void OMPClauseReader::VisitOMPSizesClause(OMPSizesClause *C) {
12063 for (Expr *&E : C->getSizesRefs())
12064 E = Record.readSubExpr();
12065 C->setLParenLoc(Record.readSourceLocation());
12068 void OMPClauseReader::VisitOMPFullClause(OMPFullClause *C) {}
12070 void OMPClauseReader::VisitOMPPartialClause(OMPPartialClause *C) {
12071 C->setFactor(Record.readSubExpr());
12072 C->setLParenLoc(Record.readSourceLocation());
12075 void OMPClauseReader::VisitOMPAllocatorClause(OMPAllocatorClause *C) {
12076 C->setAllocator(Record.readExpr());
12077 C->setLParenLoc(Record.readSourceLocation());
12080 void OMPClauseReader::VisitOMPCollapseClause(OMPCollapseClause *C) {
12081 C->setNumForLoops(Record.readSubExpr());
12082 C->setLParenLoc(Record.readSourceLocation());
12085 void OMPClauseReader::VisitOMPDefaultClause(OMPDefaultClause *C) {
12086 C->setDefaultKind(static_cast<llvm::omp::DefaultKind>(Record.readInt()));
12087 C->setLParenLoc(Record.readSourceLocation());
12088 C->setDefaultKindKwLoc(Record.readSourceLocation());
12091 void OMPClauseReader::VisitOMPProcBindClause(OMPProcBindClause *C) {
12092 C->setProcBindKind(static_cast<llvm::omp::ProcBindKind>(Record.readInt()));
12093 C->setLParenLoc(Record.readSourceLocation());
12094 C->setProcBindKindKwLoc(Record.readSourceLocation());
12097 void OMPClauseReader::VisitOMPScheduleClause(OMPScheduleClause *C) {
12098 VisitOMPClauseWithPreInit(C);
12099 C->setScheduleKind(
12100 static_cast<OpenMPScheduleClauseKind>(Record.readInt()));
12101 C->setFirstScheduleModifier(
12102 static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
12103 C->setSecondScheduleModifier(
12104 static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
12105 C->setChunkSize(Record.readSubExpr());
12106 C->setLParenLoc(Record.readSourceLocation());
12107 C->setFirstScheduleModifierLoc(Record.readSourceLocation());
12108 C->setSecondScheduleModifierLoc(Record.readSourceLocation());
12109 C->setScheduleKindLoc(Record.readSourceLocation());
12110 C->setCommaLoc(Record.readSourceLocation());
12113 void OMPClauseReader::VisitOMPOrderedClause(OMPOrderedClause *C) {
12114 C->setNumForLoops(Record.readSubExpr());
12115 for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
12116 C->setLoopNumIterations(I, Record.readSubExpr());
12117 for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
12118 C->setLoopCounter(I, Record.readSubExpr());
12119 C->setLParenLoc(Record.readSourceLocation());
12122 void OMPClauseReader::VisitOMPDetachClause(OMPDetachClause *C) {
12123 C->setEventHandler(Record.readSubExpr());
12124 C->setLParenLoc(Record.readSourceLocation());
12127 void OMPClauseReader::VisitOMPNowaitClause(OMPNowaitClause *) {}
12129 void OMPClauseReader::VisitOMPUntiedClause(OMPUntiedClause *) {}
12131 void OMPClauseReader::VisitOMPMergeableClause(OMPMergeableClause *) {}
12133 void OMPClauseReader::VisitOMPReadClause(OMPReadClause *) {}
12135 void OMPClauseReader::VisitOMPWriteClause(OMPWriteClause *) {}
12137 void OMPClauseReader::VisitOMPUpdateClause(OMPUpdateClause *C) {
12138 if (C->isExtended()) {
12139 C->setLParenLoc(Record.readSourceLocation());
12140 C->setArgumentLoc(Record.readSourceLocation());
12141 C->setDependencyKind(Record.readEnum<OpenMPDependClauseKind>());
12145 void OMPClauseReader::VisitOMPCaptureClause(OMPCaptureClause *) {}
12147 void OMPClauseReader::VisitOMPCompareClause(OMPCompareClause *) {}
12149 void OMPClauseReader::VisitOMPSeqCstClause(OMPSeqCstClause *) {}
12151 void OMPClauseReader::VisitOMPAcqRelClause(OMPAcqRelClause *) {}
12153 void OMPClauseReader::VisitOMPAcquireClause(OMPAcquireClause *) {}
12155 void OMPClauseReader::VisitOMPReleaseClause(OMPReleaseClause *) {}
12157 void OMPClauseReader::VisitOMPRelaxedClause(OMPRelaxedClause *) {}
12159 void OMPClauseReader::VisitOMPThreadsClause(OMPThreadsClause *) {}
12161 void OMPClauseReader::VisitOMPSIMDClause(OMPSIMDClause *) {}
12163 void OMPClauseReader::VisitOMPNogroupClause(OMPNogroupClause *) {}
12165 void OMPClauseReader::VisitOMPInitClause(OMPInitClause *C) {
12166 unsigned NumVars = C->varlist_size();
12167 SmallVector<Expr *, 16> Vars;
12168 Vars.reserve(NumVars);
12169 for (unsigned I = 0; I != NumVars; ++I)
12170 Vars.push_back(Record.readSubExpr());
12171 C->setVarRefs(Vars);
12172 C->setIsTarget(Record.readBool());
12173 C->setIsTargetSync(Record.readBool());
12174 C->setLParenLoc(Record.readSourceLocation());
12175 C->setVarLoc(Record.readSourceLocation());
12178 void OMPClauseReader::VisitOMPUseClause(OMPUseClause *C) {
12179 C->setInteropVar(Record.readSubExpr());
12180 C->setLParenLoc(Record.readSourceLocation());
12181 C->setVarLoc(Record.readSourceLocation());
12184 void OMPClauseReader::VisitOMPDestroyClause(OMPDestroyClause *C) {
12185 C->setInteropVar(Record.readSubExpr());
12186 C->setLParenLoc(Record.readSourceLocation());
12187 C->setVarLoc(Record.readSourceLocation());
12190 void OMPClauseReader::VisitOMPNovariantsClause(OMPNovariantsClause *C) {
12191 VisitOMPClauseWithPreInit(C);
12192 C->setCondition(Record.readSubExpr());
12193 C->setLParenLoc(Record.readSourceLocation());
12196 void OMPClauseReader::VisitOMPNocontextClause(OMPNocontextClause *C) {
12197 VisitOMPClauseWithPreInit(C);
12198 C->setCondition(Record.readSubExpr());
12199 C->setLParenLoc(Record.readSourceLocation());
12202 void OMPClauseReader::VisitOMPUnifiedAddressClause(OMPUnifiedAddressClause *) {}
12204 void OMPClauseReader::VisitOMPUnifiedSharedMemoryClause(
12205 OMPUnifiedSharedMemoryClause *) {}
12207 void OMPClauseReader::VisitOMPReverseOffloadClause(OMPReverseOffloadClause *) {}
12210 OMPClauseReader::VisitOMPDynamicAllocatorsClause(OMPDynamicAllocatorsClause *) {
12213 void OMPClauseReader::VisitOMPAtomicDefaultMemOrderClause(
12214 OMPAtomicDefaultMemOrderClause *C) {
12215 C->setAtomicDefaultMemOrderKind(
12216 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Record.readInt()));
12217 C->setLParenLoc(Record.readSourceLocation());
12218 C->setAtomicDefaultMemOrderKindKwLoc(Record.readSourceLocation());
12221 void OMPClauseReader::VisitOMPPrivateClause(OMPPrivateClause *C) {
12222 C->setLParenLoc(Record.readSourceLocation());
12223 unsigned NumVars = C->varlist_size();
12224 SmallVector<Expr *, 16> Vars;
12225 Vars.reserve(NumVars);
12226 for (unsigned i = 0; i != NumVars; ++i)
12227 Vars.push_back(Record.readSubExpr());
12228 C->setVarRefs(Vars);
12230 for (unsigned i = 0; i != NumVars; ++i)
12231 Vars.push_back(Record.readSubExpr());
12232 C->setPrivateCopies(Vars);
12235 void OMPClauseReader::VisitOMPFirstprivateClause(OMPFirstprivateClause *C) {
12236 VisitOMPClauseWithPreInit(C);
12237 C->setLParenLoc(Record.readSourceLocation());
12238 unsigned NumVars = C->varlist_size();
12239 SmallVector<Expr *, 16> Vars;
12240 Vars.reserve(NumVars);
12241 for (unsigned i = 0; i != NumVars; ++i)
12242 Vars.push_back(Record.readSubExpr());
12243 C->setVarRefs(Vars);
12245 for (unsigned i = 0; i != NumVars; ++i)
12246 Vars.push_back(Record.readSubExpr());
12247 C->setPrivateCopies(Vars);
12249 for (unsigned i = 0; i != NumVars; ++i)
12250 Vars.push_back(Record.readSubExpr());
12254 void OMPClauseReader::VisitOMPLastprivateClause(OMPLastprivateClause *C) {
12255 VisitOMPClauseWithPostUpdate(C);
12256 C->setLParenLoc(Record.readSourceLocation());
12257 C->setKind(Record.readEnum<OpenMPLastprivateModifier>());
12258 C->setKindLoc(Record.readSourceLocation());
12259 C->setColonLoc(Record.readSourceLocation());
12260 unsigned NumVars = C->varlist_size();
12261 SmallVector<Expr *, 16> Vars;
12262 Vars.reserve(NumVars);
12263 for (unsigned i = 0; i != NumVars; ++i)
12264 Vars.push_back(Record.readSubExpr());
12265 C->setVarRefs(Vars);
12267 for (unsigned i = 0; i != NumVars; ++i)
12268 Vars.push_back(Record.readSubExpr());
12269 C->setPrivateCopies(Vars);
12271 for (unsigned i = 0; i != NumVars; ++i)
12272 Vars.push_back(Record.readSubExpr());
12273 C->setSourceExprs(Vars);
12275 for (unsigned i = 0; i != NumVars; ++i)
12276 Vars.push_back(Record.readSubExpr());
12277 C->setDestinationExprs(Vars);
12279 for (unsigned i = 0; i != NumVars; ++i)
12280 Vars.push_back(Record.readSubExpr());
12281 C->setAssignmentOps(Vars);
12284 void OMPClauseReader::VisitOMPSharedClause(OMPSharedClause *C) {
12285 C->setLParenLoc(Record.readSourceLocation());
12286 unsigned NumVars = C->varlist_size();
12287 SmallVector<Expr *, 16> Vars;
12288 Vars.reserve(NumVars);
12289 for (unsigned i = 0; i != NumVars; ++i)
12290 Vars.push_back(Record.readSubExpr());
12291 C->setVarRefs(Vars);
12294 void OMPClauseReader::VisitOMPReductionClause(OMPReductionClause *C) {
12295 VisitOMPClauseWithPostUpdate(C);
12296 C->setLParenLoc(Record.readSourceLocation());
12297 C->setModifierLoc(Record.readSourceLocation());
12298 C->setColonLoc(Record.readSourceLocation());
12299 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
12300 DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
12301 C->setQualifierLoc(NNSL);
12302 C->setNameInfo(DNI);
12304 unsigned NumVars = C->varlist_size();
12305 SmallVector<Expr *, 16> Vars;
12306 Vars.reserve(NumVars);
12307 for (unsigned i = 0; i != NumVars; ++i)
12308 Vars.push_back(Record.readSubExpr());
12309 C->setVarRefs(Vars);
12311 for (unsigned i = 0; i != NumVars; ++i)
12312 Vars.push_back(Record.readSubExpr());
12313 C->setPrivates(Vars);
12315 for (unsigned i = 0; i != NumVars; ++i)
12316 Vars.push_back(Record.readSubExpr());
12317 C->setLHSExprs(Vars);
12319 for (unsigned i = 0; i != NumVars; ++i)
12320 Vars.push_back(Record.readSubExpr());
12321 C->setRHSExprs(Vars);
12323 for (unsigned i = 0; i != NumVars; ++i)
12324 Vars.push_back(Record.readSubExpr());
12325 C->setReductionOps(Vars);
12326 if (C->getModifier() == OMPC_REDUCTION_inscan) {
12328 for (unsigned i = 0; i != NumVars; ++i)
12329 Vars.push_back(Record.readSubExpr());
12330 C->setInscanCopyOps(Vars);
12332 for (unsigned i = 0; i != NumVars; ++i)
12333 Vars.push_back(Record.readSubExpr());
12334 C->setInscanCopyArrayTemps(Vars);
12336 for (unsigned i = 0; i != NumVars; ++i)
12337 Vars.push_back(Record.readSubExpr());
12338 C->setInscanCopyArrayElems(Vars);
12342 void OMPClauseReader::VisitOMPTaskReductionClause(OMPTaskReductionClause *C) {
12343 VisitOMPClauseWithPostUpdate(C);
12344 C->setLParenLoc(Record.readSourceLocation());
12345 C->setColonLoc(Record.readSourceLocation());
12346 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
12347 DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
12348 C->setQualifierLoc(NNSL);
12349 C->setNameInfo(DNI);
12351 unsigned NumVars = C->varlist_size();
12352 SmallVector<Expr *, 16> Vars;
12353 Vars.reserve(NumVars);
12354 for (unsigned I = 0; I != NumVars; ++I)
12355 Vars.push_back(Record.readSubExpr());
12356 C->setVarRefs(Vars);
12358 for (unsigned I = 0; I != NumVars; ++I)
12359 Vars.push_back(Record.readSubExpr());
12360 C->setPrivates(Vars);
12362 for (unsigned I = 0; I != NumVars; ++I)
12363 Vars.push_back(Record.readSubExpr());
12364 C->setLHSExprs(Vars);
12366 for (unsigned I = 0; I != NumVars; ++I)
12367 Vars.push_back(Record.readSubExpr());
12368 C->setRHSExprs(Vars);
12370 for (unsigned I = 0; I != NumVars; ++I)
12371 Vars.push_back(Record.readSubExpr());
12372 C->setReductionOps(Vars);
12375 void OMPClauseReader::VisitOMPInReductionClause(OMPInReductionClause *C) {
12376 VisitOMPClauseWithPostUpdate(C);
12377 C->setLParenLoc(Record.readSourceLocation());
12378 C->setColonLoc(Record.readSourceLocation());
12379 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
12380 DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
12381 C->setQualifierLoc(NNSL);
12382 C->setNameInfo(DNI);
12384 unsigned NumVars = C->varlist_size();
12385 SmallVector<Expr *, 16> Vars;
12386 Vars.reserve(NumVars);
12387 for (unsigned I = 0; I != NumVars; ++I)
12388 Vars.push_back(Record.readSubExpr());
12389 C->setVarRefs(Vars);
12391 for (unsigned I = 0; I != NumVars; ++I)
12392 Vars.push_back(Record.readSubExpr());
12393 C->setPrivates(Vars);
12395 for (unsigned I = 0; I != NumVars; ++I)
12396 Vars.push_back(Record.readSubExpr());
12397 C->setLHSExprs(Vars);
12399 for (unsigned I = 0; I != NumVars; ++I)
12400 Vars.push_back(Record.readSubExpr());
12401 C->setRHSExprs(Vars);
12403 for (unsigned I = 0; I != NumVars; ++I)
12404 Vars.push_back(Record.readSubExpr());
12405 C->setReductionOps(Vars);
12407 for (unsigned I = 0; I != NumVars; ++I)
12408 Vars.push_back(Record.readSubExpr());
12409 C->setTaskgroupDescriptors(Vars);
12412 void OMPClauseReader::VisitOMPLinearClause(OMPLinearClause *C) {
12413 VisitOMPClauseWithPostUpdate(C);
12414 C->setLParenLoc(Record.readSourceLocation());
12415 C->setColonLoc(Record.readSourceLocation());
12416 C->setModifier(static_cast<OpenMPLinearClauseKind>(Record.readInt()));
12417 C->setModifierLoc(Record.readSourceLocation());
12418 unsigned NumVars = C->varlist_size();
12419 SmallVector<Expr *, 16> Vars;
12420 Vars.reserve(NumVars);
12421 for (unsigned i = 0; i != NumVars; ++i)
12422 Vars.push_back(Record.readSubExpr());
12423 C->setVarRefs(Vars);
12425 for (unsigned i = 0; i != NumVars; ++i)
12426 Vars.push_back(Record.readSubExpr());
12427 C->setPrivates(Vars);
12429 for (unsigned i = 0; i != NumVars; ++i)
12430 Vars.push_back(Record.readSubExpr());
12433 for (unsigned i = 0; i != NumVars; ++i)
12434 Vars.push_back(Record.readSubExpr());
12435 C->setUpdates(Vars);
12437 for (unsigned i = 0; i != NumVars; ++i)
12438 Vars.push_back(Record.readSubExpr());
12439 C->setFinals(Vars);
12440 C->setStep(Record.readSubExpr());
12441 C->setCalcStep(Record.readSubExpr());
12443 for (unsigned I = 0; I != NumVars + 1; ++I)
12444 Vars.push_back(Record.readSubExpr());
12445 C->setUsedExprs(Vars);
12448 void OMPClauseReader::VisitOMPAlignedClause(OMPAlignedClause *C) {
12449 C->setLParenLoc(Record.readSourceLocation());
12450 C->setColonLoc(Record.readSourceLocation());
12451 unsigned NumVars = C->varlist_size();
12452 SmallVector<Expr *, 16> Vars;
12453 Vars.reserve(NumVars);
12454 for (unsigned i = 0; i != NumVars; ++i)
12455 Vars.push_back(Record.readSubExpr());
12456 C->setVarRefs(Vars);
12457 C->setAlignment(Record.readSubExpr());
12460 void OMPClauseReader::VisitOMPCopyinClause(OMPCopyinClause *C) {
12461 C->setLParenLoc(Record.readSourceLocation());
12462 unsigned NumVars = C->varlist_size();
12463 SmallVector<Expr *, 16> Exprs;
12464 Exprs.reserve(NumVars);
12465 for (unsigned i = 0; i != NumVars; ++i)
12466 Exprs.push_back(Record.readSubExpr());
12467 C->setVarRefs(Exprs);
12469 for (unsigned i = 0; i != NumVars; ++i)
12470 Exprs.push_back(Record.readSubExpr());
12471 C->setSourceExprs(Exprs);
12473 for (unsigned i = 0; i != NumVars; ++i)
12474 Exprs.push_back(Record.readSubExpr());
12475 C->setDestinationExprs(Exprs);
12477 for (unsigned i = 0; i != NumVars; ++i)
12478 Exprs.push_back(Record.readSubExpr());
12479 C->setAssignmentOps(Exprs);
12482 void OMPClauseReader::VisitOMPCopyprivateClause(OMPCopyprivateClause *C) {
12483 C->setLParenLoc(Record.readSourceLocation());
12484 unsigned NumVars = C->varlist_size();
12485 SmallVector<Expr *, 16> Exprs;
12486 Exprs.reserve(NumVars);
12487 for (unsigned i = 0; i != NumVars; ++i)
12488 Exprs.push_back(Record.readSubExpr());
12489 C->setVarRefs(Exprs);
12491 for (unsigned i = 0; i != NumVars; ++i)
12492 Exprs.push_back(Record.readSubExpr());
12493 C->setSourceExprs(Exprs);
12495 for (unsigned i = 0; i != NumVars; ++i)
12496 Exprs.push_back(Record.readSubExpr());
12497 C->setDestinationExprs(Exprs);
12499 for (unsigned i = 0; i != NumVars; ++i)
12500 Exprs.push_back(Record.readSubExpr());
12501 C->setAssignmentOps(Exprs);
12504 void OMPClauseReader::VisitOMPFlushClause(OMPFlushClause *C) {
12505 C->setLParenLoc(Record.readSourceLocation());
12506 unsigned NumVars = C->varlist_size();
12507 SmallVector<Expr *, 16> Vars;
12508 Vars.reserve(NumVars);
12509 for (unsigned i = 0; i != NumVars; ++i)
12510 Vars.push_back(Record.readSubExpr());
12511 C->setVarRefs(Vars);
12514 void OMPClauseReader::VisitOMPDepobjClause(OMPDepobjClause *C) {
12515 C->setDepobj(Record.readSubExpr());
12516 C->setLParenLoc(Record.readSourceLocation());
12519 void OMPClauseReader::VisitOMPDependClause(OMPDependClause *C) {
12520 C->setLParenLoc(Record.readSourceLocation());
12521 C->setModifier(Record.readSubExpr());
12522 C->setDependencyKind(
12523 static_cast<OpenMPDependClauseKind>(Record.readInt()));
12524 C->setDependencyLoc(Record.readSourceLocation());
12525 C->setColonLoc(Record.readSourceLocation());
12526 unsigned NumVars = C->varlist_size();
12527 SmallVector<Expr *, 16> Vars;
12528 Vars.reserve(NumVars);
12529 for (unsigned I = 0; I != NumVars; ++I)
12530 Vars.push_back(Record.readSubExpr());
12531 C->setVarRefs(Vars);
12532 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
12533 C->setLoopData(I, Record.readSubExpr());
12536 void OMPClauseReader::VisitOMPDeviceClause(OMPDeviceClause *C) {
12537 VisitOMPClauseWithPreInit(C);
12538 C->setModifier(Record.readEnum<OpenMPDeviceClauseModifier>());
12539 C->setDevice(Record.readSubExpr());
12540 C->setModifierLoc(Record.readSourceLocation());
12541 C->setLParenLoc(Record.readSourceLocation());
12544 void OMPClauseReader::VisitOMPMapClause(OMPMapClause *C) {
12545 C->setLParenLoc(Record.readSourceLocation());
12546 for (unsigned I = 0; I < NumberOfOMPMapClauseModifiers; ++I) {
12547 C->setMapTypeModifier(
12548 I, static_cast<OpenMPMapModifierKind>(Record.readInt()));
12549 C->setMapTypeModifierLoc(I, Record.readSourceLocation());
12551 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
12552 C->setMapperIdInfo(Record.readDeclarationNameInfo());
12554 static_cast<OpenMPMapClauseKind>(Record.readInt()));
12555 C->setMapLoc(Record.readSourceLocation());
12556 C->setColonLoc(Record.readSourceLocation());
12557 auto NumVars = C->varlist_size();
12558 auto UniqueDecls = C->getUniqueDeclarationsNum();
12559 auto TotalLists = C->getTotalComponentListNum();
12560 auto TotalComponents = C->getTotalComponentsNum();
12562 SmallVector<Expr *, 16> Vars;
12563 Vars.reserve(NumVars);
12564 for (unsigned i = 0; i != NumVars; ++i)
12565 Vars.push_back(Record.readExpr());
12566 C->setVarRefs(Vars);
12568 SmallVector<Expr *, 16> UDMappers;
12569 UDMappers.reserve(NumVars);
12570 for (unsigned I = 0; I < NumVars; ++I)
12571 UDMappers.push_back(Record.readExpr());
12572 C->setUDMapperRefs(UDMappers);
12574 SmallVector<ValueDecl *, 16> Decls;
12575 Decls.reserve(UniqueDecls);
12576 for (unsigned i = 0; i < UniqueDecls; ++i)
12577 Decls.push_back(Record.readDeclAs<ValueDecl>());
12578 C->setUniqueDecls(Decls);
12580 SmallVector<unsigned, 16> ListsPerDecl;
12581 ListsPerDecl.reserve(UniqueDecls);
12582 for (unsigned i = 0; i < UniqueDecls; ++i)
12583 ListsPerDecl.push_back(Record.readInt());
12584 C->setDeclNumLists(ListsPerDecl);
12586 SmallVector<unsigned, 32> ListSizes;
12587 ListSizes.reserve(TotalLists);
12588 for (unsigned i = 0; i < TotalLists; ++i)
12589 ListSizes.push_back(Record.readInt());
12590 C->setComponentListSizes(ListSizes);
12592 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12593 Components.reserve(TotalComponents);
12594 for (unsigned i = 0; i < TotalComponents; ++i) {
12595 Expr *AssociatedExprPr = Record.readExpr();
12596 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12597 Components.emplace_back(AssociatedExprPr, AssociatedDecl,
12598 /*IsNonContiguous=*/false);
12600 C->setComponents(Components, ListSizes);
12603 void OMPClauseReader::VisitOMPAllocateClause(OMPAllocateClause *C) {
12604 C->setLParenLoc(Record.readSourceLocation());
12605 C->setColonLoc(Record.readSourceLocation());
12606 C->setAllocator(Record.readSubExpr());
12607 unsigned NumVars = C->varlist_size();
12608 SmallVector<Expr *, 16> Vars;
12609 Vars.reserve(NumVars);
12610 for (unsigned i = 0; i != NumVars; ++i)
12611 Vars.push_back(Record.readSubExpr());
12612 C->setVarRefs(Vars);
12615 void OMPClauseReader::VisitOMPNumTeamsClause(OMPNumTeamsClause *C) {
12616 VisitOMPClauseWithPreInit(C);
12617 C->setNumTeams(Record.readSubExpr());
12618 C->setLParenLoc(Record.readSourceLocation());
12621 void OMPClauseReader::VisitOMPThreadLimitClause(OMPThreadLimitClause *C) {
12622 VisitOMPClauseWithPreInit(C);
12623 C->setThreadLimit(Record.readSubExpr());
12624 C->setLParenLoc(Record.readSourceLocation());
12627 void OMPClauseReader::VisitOMPPriorityClause(OMPPriorityClause *C) {
12628 VisitOMPClauseWithPreInit(C);
12629 C->setPriority(Record.readSubExpr());
12630 C->setLParenLoc(Record.readSourceLocation());
12633 void OMPClauseReader::VisitOMPGrainsizeClause(OMPGrainsizeClause *C) {
12634 VisitOMPClauseWithPreInit(C);
12635 C->setGrainsize(Record.readSubExpr());
12636 C->setLParenLoc(Record.readSourceLocation());
12639 void OMPClauseReader::VisitOMPNumTasksClause(OMPNumTasksClause *C) {
12640 VisitOMPClauseWithPreInit(C);
12641 C->setNumTasks(Record.readSubExpr());
12642 C->setLParenLoc(Record.readSourceLocation());
12645 void OMPClauseReader::VisitOMPHintClause(OMPHintClause *C) {
12646 C->setHint(Record.readSubExpr());
12647 C->setLParenLoc(Record.readSourceLocation());
12650 void OMPClauseReader::VisitOMPDistScheduleClause(OMPDistScheduleClause *C) {
12651 VisitOMPClauseWithPreInit(C);
12652 C->setDistScheduleKind(
12653 static_cast<OpenMPDistScheduleClauseKind>(Record.readInt()));
12654 C->setChunkSize(Record.readSubExpr());
12655 C->setLParenLoc(Record.readSourceLocation());
12656 C->setDistScheduleKindLoc(Record.readSourceLocation());
12657 C->setCommaLoc(Record.readSourceLocation());
12660 void OMPClauseReader::VisitOMPDefaultmapClause(OMPDefaultmapClause *C) {
12661 C->setDefaultmapKind(
12662 static_cast<OpenMPDefaultmapClauseKind>(Record.readInt()));
12663 C->setDefaultmapModifier(
12664 static_cast<OpenMPDefaultmapClauseModifier>(Record.readInt()));
12665 C->setLParenLoc(Record.readSourceLocation());
12666 C->setDefaultmapModifierLoc(Record.readSourceLocation());
12667 C->setDefaultmapKindLoc(Record.readSourceLocation());
12670 void OMPClauseReader::VisitOMPToClause(OMPToClause *C) {
12671 C->setLParenLoc(Record.readSourceLocation());
12672 for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) {
12673 C->setMotionModifier(
12674 I, static_cast<OpenMPMotionModifierKind>(Record.readInt()));
12675 C->setMotionModifierLoc(I, Record.readSourceLocation());
12677 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
12678 C->setMapperIdInfo(Record.readDeclarationNameInfo());
12679 C->setColonLoc(Record.readSourceLocation());
12680 auto NumVars = C->varlist_size();
12681 auto UniqueDecls = C->getUniqueDeclarationsNum();
12682 auto TotalLists = C->getTotalComponentListNum();
12683 auto TotalComponents = C->getTotalComponentsNum();
12685 SmallVector<Expr *, 16> Vars;
12686 Vars.reserve(NumVars);
12687 for (unsigned i = 0; i != NumVars; ++i)
12688 Vars.push_back(Record.readSubExpr());
12689 C->setVarRefs(Vars);
12691 SmallVector<Expr *, 16> UDMappers;
12692 UDMappers.reserve(NumVars);
12693 for (unsigned I = 0; I < NumVars; ++I)
12694 UDMappers.push_back(Record.readSubExpr());
12695 C->setUDMapperRefs(UDMappers);
12697 SmallVector<ValueDecl *, 16> Decls;
12698 Decls.reserve(UniqueDecls);
12699 for (unsigned i = 0; i < UniqueDecls; ++i)
12700 Decls.push_back(Record.readDeclAs<ValueDecl>());
12701 C->setUniqueDecls(Decls);
12703 SmallVector<unsigned, 16> ListsPerDecl;
12704 ListsPerDecl.reserve(UniqueDecls);
12705 for (unsigned i = 0; i < UniqueDecls; ++i)
12706 ListsPerDecl.push_back(Record.readInt());
12707 C->setDeclNumLists(ListsPerDecl);
12709 SmallVector<unsigned, 32> ListSizes;
12710 ListSizes.reserve(TotalLists);
12711 for (unsigned i = 0; i < TotalLists; ++i)
12712 ListSizes.push_back(Record.readInt());
12713 C->setComponentListSizes(ListSizes);
12715 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12716 Components.reserve(TotalComponents);
12717 for (unsigned i = 0; i < TotalComponents; ++i) {
12718 Expr *AssociatedExprPr = Record.readSubExpr();
12719 bool IsNonContiguous = Record.readBool();
12720 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12721 Components.emplace_back(AssociatedExprPr, AssociatedDecl, IsNonContiguous);
12723 C->setComponents(Components, ListSizes);
12726 void OMPClauseReader::VisitOMPFromClause(OMPFromClause *C) {
12727 C->setLParenLoc(Record.readSourceLocation());
12728 for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) {
12729 C->setMotionModifier(
12730 I, static_cast<OpenMPMotionModifierKind>(Record.readInt()));
12731 C->setMotionModifierLoc(I, Record.readSourceLocation());
12733 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
12734 C->setMapperIdInfo(Record.readDeclarationNameInfo());
12735 C->setColonLoc(Record.readSourceLocation());
12736 auto NumVars = C->varlist_size();
12737 auto UniqueDecls = C->getUniqueDeclarationsNum();
12738 auto TotalLists = C->getTotalComponentListNum();
12739 auto TotalComponents = C->getTotalComponentsNum();
12741 SmallVector<Expr *, 16> Vars;
12742 Vars.reserve(NumVars);
12743 for (unsigned i = 0; i != NumVars; ++i)
12744 Vars.push_back(Record.readSubExpr());
12745 C->setVarRefs(Vars);
12747 SmallVector<Expr *, 16> UDMappers;
12748 UDMappers.reserve(NumVars);
12749 for (unsigned I = 0; I < NumVars; ++I)
12750 UDMappers.push_back(Record.readSubExpr());
12751 C->setUDMapperRefs(UDMappers);
12753 SmallVector<ValueDecl *, 16> Decls;
12754 Decls.reserve(UniqueDecls);
12755 for (unsigned i = 0; i < UniqueDecls; ++i)
12756 Decls.push_back(Record.readDeclAs<ValueDecl>());
12757 C->setUniqueDecls(Decls);
12759 SmallVector<unsigned, 16> ListsPerDecl;
12760 ListsPerDecl.reserve(UniqueDecls);
12761 for (unsigned i = 0; i < UniqueDecls; ++i)
12762 ListsPerDecl.push_back(Record.readInt());
12763 C->setDeclNumLists(ListsPerDecl);
12765 SmallVector<unsigned, 32> ListSizes;
12766 ListSizes.reserve(TotalLists);
12767 for (unsigned i = 0; i < TotalLists; ++i)
12768 ListSizes.push_back(Record.readInt());
12769 C->setComponentListSizes(ListSizes);
12771 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12772 Components.reserve(TotalComponents);
12773 for (unsigned i = 0; i < TotalComponents; ++i) {
12774 Expr *AssociatedExprPr = Record.readSubExpr();
12775 bool IsNonContiguous = Record.readBool();
12776 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12777 Components.emplace_back(AssociatedExprPr, AssociatedDecl, IsNonContiguous);
12779 C->setComponents(Components, ListSizes);
12782 void OMPClauseReader::VisitOMPUseDevicePtrClause(OMPUseDevicePtrClause *C) {
12783 C->setLParenLoc(Record.readSourceLocation());
12784 auto NumVars = C->varlist_size();
12785 auto UniqueDecls = C->getUniqueDeclarationsNum();
12786 auto TotalLists = C->getTotalComponentListNum();
12787 auto TotalComponents = C->getTotalComponentsNum();
12789 SmallVector<Expr *, 16> Vars;
12790 Vars.reserve(NumVars);
12791 for (unsigned i = 0; i != NumVars; ++i)
12792 Vars.push_back(Record.readSubExpr());
12793 C->setVarRefs(Vars);
12795 for (unsigned i = 0; i != NumVars; ++i)
12796 Vars.push_back(Record.readSubExpr());
12797 C->setPrivateCopies(Vars);
12799 for (unsigned i = 0; i != NumVars; ++i)
12800 Vars.push_back(Record.readSubExpr());
12803 SmallVector<ValueDecl *, 16> Decls;
12804 Decls.reserve(UniqueDecls);
12805 for (unsigned i = 0; i < UniqueDecls; ++i)
12806 Decls.push_back(Record.readDeclAs<ValueDecl>());
12807 C->setUniqueDecls(Decls);
12809 SmallVector<unsigned, 16> ListsPerDecl;
12810 ListsPerDecl.reserve(UniqueDecls);
12811 for (unsigned i = 0; i < UniqueDecls; ++i)
12812 ListsPerDecl.push_back(Record.readInt());
12813 C->setDeclNumLists(ListsPerDecl);
12815 SmallVector<unsigned, 32> ListSizes;
12816 ListSizes.reserve(TotalLists);
12817 for (unsigned i = 0; i < TotalLists; ++i)
12818 ListSizes.push_back(Record.readInt());
12819 C->setComponentListSizes(ListSizes);
12821 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12822 Components.reserve(TotalComponents);
12823 for (unsigned i = 0; i < TotalComponents; ++i) {
12824 auto *AssociatedExprPr = Record.readSubExpr();
12825 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12826 Components.emplace_back(AssociatedExprPr, AssociatedDecl,
12827 /*IsNonContiguous=*/false);
12829 C->setComponents(Components, ListSizes);
12832 void OMPClauseReader::VisitOMPUseDeviceAddrClause(OMPUseDeviceAddrClause *C) {
12833 C->setLParenLoc(Record.readSourceLocation());
12834 auto NumVars = C->varlist_size();
12835 auto UniqueDecls = C->getUniqueDeclarationsNum();
12836 auto TotalLists = C->getTotalComponentListNum();
12837 auto TotalComponents = C->getTotalComponentsNum();
12839 SmallVector<Expr *, 16> Vars;
12840 Vars.reserve(NumVars);
12841 for (unsigned i = 0; i != NumVars; ++i)
12842 Vars.push_back(Record.readSubExpr());
12843 C->setVarRefs(Vars);
12845 SmallVector<ValueDecl *, 16> Decls;
12846 Decls.reserve(UniqueDecls);
12847 for (unsigned i = 0; i < UniqueDecls; ++i)
12848 Decls.push_back(Record.readDeclAs<ValueDecl>());
12849 C->setUniqueDecls(Decls);
12851 SmallVector<unsigned, 16> ListsPerDecl;
12852 ListsPerDecl.reserve(UniqueDecls);
12853 for (unsigned i = 0; i < UniqueDecls; ++i)
12854 ListsPerDecl.push_back(Record.readInt());
12855 C->setDeclNumLists(ListsPerDecl);
12857 SmallVector<unsigned, 32> ListSizes;
12858 ListSizes.reserve(TotalLists);
12859 for (unsigned i = 0; i < TotalLists; ++i)
12860 ListSizes.push_back(Record.readInt());
12861 C->setComponentListSizes(ListSizes);
12863 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12864 Components.reserve(TotalComponents);
12865 for (unsigned i = 0; i < TotalComponents; ++i) {
12866 Expr *AssociatedExpr = Record.readSubExpr();
12867 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12868 Components.emplace_back(AssociatedExpr, AssociatedDecl,
12869 /*IsNonContiguous*/ false);
12871 C->setComponents(Components, ListSizes);
12874 void OMPClauseReader::VisitOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
12875 C->setLParenLoc(Record.readSourceLocation());
12876 auto NumVars = C->varlist_size();
12877 auto UniqueDecls = C->getUniqueDeclarationsNum();
12878 auto TotalLists = C->getTotalComponentListNum();
12879 auto TotalComponents = C->getTotalComponentsNum();
12881 SmallVector<Expr *, 16> Vars;
12882 Vars.reserve(NumVars);
12883 for (unsigned i = 0; i != NumVars; ++i)
12884 Vars.push_back(Record.readSubExpr());
12885 C->setVarRefs(Vars);
12888 SmallVector<ValueDecl *, 16> Decls;
12889 Decls.reserve(UniqueDecls);
12890 for (unsigned i = 0; i < UniqueDecls; ++i)
12891 Decls.push_back(Record.readDeclAs<ValueDecl>());
12892 C->setUniqueDecls(Decls);
12894 SmallVector<unsigned, 16> ListsPerDecl;
12895 ListsPerDecl.reserve(UniqueDecls);
12896 for (unsigned i = 0; i < UniqueDecls; ++i)
12897 ListsPerDecl.push_back(Record.readInt());
12898 C->setDeclNumLists(ListsPerDecl);
12900 SmallVector<unsigned, 32> ListSizes;
12901 ListSizes.reserve(TotalLists);
12902 for (unsigned i = 0; i < TotalLists; ++i)
12903 ListSizes.push_back(Record.readInt());
12904 C->setComponentListSizes(ListSizes);
12906 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12907 Components.reserve(TotalComponents);
12908 for (unsigned i = 0; i < TotalComponents; ++i) {
12909 Expr *AssociatedExpr = Record.readSubExpr();
12910 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12911 Components.emplace_back(AssociatedExpr, AssociatedDecl,
12912 /*IsNonContiguous=*/false);
12914 C->setComponents(Components, ListSizes);
12917 void OMPClauseReader::VisitOMPNontemporalClause(OMPNontemporalClause *C) {
12918 C->setLParenLoc(Record.readSourceLocation());
12919 unsigned NumVars = C->varlist_size();
12920 SmallVector<Expr *, 16> Vars;
12921 Vars.reserve(NumVars);
12922 for (unsigned i = 0; i != NumVars; ++i)
12923 Vars.push_back(Record.readSubExpr());
12924 C->setVarRefs(Vars);
12926 Vars.reserve(NumVars);
12927 for (unsigned i = 0; i != NumVars; ++i)
12928 Vars.push_back(Record.readSubExpr());
12929 C->setPrivateRefs(Vars);
12932 void OMPClauseReader::VisitOMPInclusiveClause(OMPInclusiveClause *C) {
12933 C->setLParenLoc(Record.readSourceLocation());
12934 unsigned NumVars = C->varlist_size();
12935 SmallVector<Expr *, 16> Vars;
12936 Vars.reserve(NumVars);
12937 for (unsigned i = 0; i != NumVars; ++i)
12938 Vars.push_back(Record.readSubExpr());
12939 C->setVarRefs(Vars);
12942 void OMPClauseReader::VisitOMPExclusiveClause(OMPExclusiveClause *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);
12952 void OMPClauseReader::VisitOMPUsesAllocatorsClause(OMPUsesAllocatorsClause *C) {
12953 C->setLParenLoc(Record.readSourceLocation());
12954 unsigned NumOfAllocators = C->getNumberOfAllocators();
12955 SmallVector<OMPUsesAllocatorsClause::Data, 4> Data;
12956 Data.reserve(NumOfAllocators);
12957 for (unsigned I = 0; I != NumOfAllocators; ++I) {
12958 OMPUsesAllocatorsClause::Data &D = Data.emplace_back();
12959 D.Allocator = Record.readSubExpr();
12960 D.AllocatorTraits = Record.readSubExpr();
12961 D.LParenLoc = Record.readSourceLocation();
12962 D.RParenLoc = Record.readSourceLocation();
12964 C->setAllocatorsData(Data);
12967 void OMPClauseReader::VisitOMPAffinityClause(OMPAffinityClause *C) {
12968 C->setLParenLoc(Record.readSourceLocation());
12969 C->setModifier(Record.readSubExpr());
12970 C->setColonLoc(Record.readSourceLocation());
12971 unsigned NumOfLocators = C->varlist_size();
12972 SmallVector<Expr *, 4> Locators;
12973 Locators.reserve(NumOfLocators);
12974 for (unsigned I = 0; I != NumOfLocators; ++I)
12975 Locators.push_back(Record.readSubExpr());
12976 C->setVarRefs(Locators);
12979 void OMPClauseReader::VisitOMPOrderClause(OMPOrderClause *C) {
12980 C->setKind(Record.readEnum<OpenMPOrderClauseKind>());
12981 C->setLParenLoc(Record.readSourceLocation());
12982 C->setKindKwLoc(Record.readSourceLocation());
12985 void OMPClauseReader::VisitOMPFilterClause(OMPFilterClause *C) {
12986 VisitOMPClauseWithPreInit(C);
12987 C->setThreadID(Record.readSubExpr());
12988 C->setLParenLoc(Record.readSourceLocation());
12991 void OMPClauseReader::VisitOMPBindClause(OMPBindClause *C) {
12992 C->setBindKind(Record.readEnum<OpenMPBindClauseKind>());
12993 C->setLParenLoc(Record.readSourceLocation());
12994 C->setBindKindLoc(Record.readSourceLocation());
12997 void OMPClauseReader::VisitOMPAlignClause(OMPAlignClause *C) {
12998 C->setAlignment(Record.readExpr());
12999 C->setLParenLoc(Record.readSourceLocation());
13002 OMPTraitInfo *ASTRecordReader::readOMPTraitInfo() {
13003 OMPTraitInfo &TI = getContext().getNewOMPTraitInfo();
13004 TI.Sets.resize(readUInt32());
13005 for (auto &Set : TI.Sets) {
13006 Set.Kind = readEnum<llvm::omp::TraitSet>();
13007 Set.Selectors.resize(readUInt32());
13008 for (auto &Selector : Set.Selectors) {
13009 Selector.Kind = readEnum<llvm::omp::TraitSelector>();
13010 Selector.ScoreOrCondition = nullptr;
13012 Selector.ScoreOrCondition = readExprRef();
13013 Selector.Properties.resize(readUInt32());
13014 for (auto &Property : Selector.Properties)
13015 Property.Kind = readEnum<llvm::omp::TraitProperty>();
13021 void ASTRecordReader::readOMPChildren(OMPChildren *Data) {
13024 if (Reader->ReadingKind == ASTReader::Read_Stmt) {
13025 // Skip NumClauses, NumChildren and HasAssociatedStmt fields.
13028 SmallVector<OMPClause *, 4> Clauses(Data->getNumClauses());
13029 for (unsigned I = 0, E = Data->getNumClauses(); I < E; ++I)
13030 Clauses[I] = readOMPClause();
13031 Data->setClauses(Clauses);
13032 if (Data->hasAssociatedStmt())
13033 Data->setAssociatedStmt(readStmt());
13034 for (unsigned I = 0, E = Data->getNumChildren(); I < E; ++I)
13035 Data->getChildren()[I] = readStmt();