1 //===-- ASTReader.cpp - AST File Reader -----------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the ASTReader class, which reads AST files.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Serialization/ASTReader.h"
15 #include "ASTCommon.h"
16 #include "ASTReaderInternals.h"
17 #include "clang/AST/ASTConsumer.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/ASTMutationListener.h"
20 #include "clang/AST/ASTUnresolvedSet.h"
21 #include "clang/AST/Decl.h"
22 #include "clang/AST/DeclCXX.h"
23 #include "clang/AST/DeclGroup.h"
24 #include "clang/AST/DeclObjC.h"
25 #include "clang/AST/DeclTemplate.h"
26 #include "clang/AST/Expr.h"
27 #include "clang/AST/ExprCXX.h"
28 #include "clang/AST/NestedNameSpecifier.h"
29 #include "clang/AST/ODRHash.h"
30 #include "clang/AST/RawCommentList.h"
31 #include "clang/AST/Type.h"
32 #include "clang/AST/TypeLocVisitor.h"
33 #include "clang/AST/UnresolvedSet.h"
34 #include "clang/Basic/CommentOptions.h"
35 #include "clang/Basic/DiagnosticOptions.h"
36 #include "clang/Basic/ExceptionSpecificationType.h"
37 #include "clang/Basic/FileManager.h"
38 #include "clang/Basic/FileSystemOptions.h"
39 #include "clang/Basic/LangOptions.h"
40 #include "clang/Basic/MemoryBufferCache.h"
41 #include "clang/Basic/ObjCRuntime.h"
42 #include "clang/Basic/OperatorKinds.h"
43 #include "clang/Basic/Sanitizers.h"
44 #include "clang/Basic/SourceManager.h"
45 #include "clang/Basic/SourceManagerInternals.h"
46 #include "clang/Basic/Specifiers.h"
47 #include "clang/Basic/TargetInfo.h"
48 #include "clang/Basic/TargetOptions.h"
49 #include "clang/Basic/TokenKinds.h"
50 #include "clang/Basic/Version.h"
51 #include "clang/Basic/VersionTuple.h"
52 #include "clang/Frontend/PCHContainerOperations.h"
53 #include "clang/Lex/HeaderSearch.h"
54 #include "clang/Lex/HeaderSearchOptions.h"
55 #include "clang/Lex/MacroInfo.h"
56 #include "clang/Lex/ModuleMap.h"
57 #include "clang/Lex/PreprocessingRecord.h"
58 #include "clang/Lex/Preprocessor.h"
59 #include "clang/Lex/PreprocessorOptions.h"
60 #include "clang/Sema/Scope.h"
61 #include "clang/Sema/Sema.h"
62 #include "clang/Sema/Weak.h"
63 #include "clang/Serialization/ASTDeserializationListener.h"
64 #include "clang/Serialization/GlobalModuleIndex.h"
65 #include "clang/Serialization/ModuleManager.h"
66 #include "clang/Serialization/SerializationDiagnostic.h"
67 #include "llvm/ADT/APFloat.h"
68 #include "llvm/ADT/APInt.h"
69 #include "llvm/ADT/APSInt.h"
70 #include "llvm/ADT/Hashing.h"
71 #include "llvm/ADT/SmallString.h"
72 #include "llvm/ADT/StringExtras.h"
73 #include "llvm/ADT/Triple.h"
74 #include "llvm/Bitcode/BitstreamReader.h"
75 #include "llvm/Support/Compression.h"
76 #include "llvm/Support/Compiler.h"
77 #include "llvm/Support/Error.h"
78 #include "llvm/Support/ErrorHandling.h"
79 #include "llvm/Support/FileSystem.h"
80 #include "llvm/Support/MemoryBuffer.h"
81 #include "llvm/Support/Path.h"
82 #include "llvm/Support/SaveAndRestore.h"
83 #include "llvm/Support/raw_ostream.h"
96 #include <system_error>
101 using namespace clang;
102 using namespace clang::serialization;
103 using namespace clang::serialization::reader;
104 using llvm::BitstreamCursor;
106 //===----------------------------------------------------------------------===//
107 // ChainedASTReaderListener implementation
108 //===----------------------------------------------------------------------===//
111 ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
112 return First->ReadFullVersionInformation(FullVersion) ||
113 Second->ReadFullVersionInformation(FullVersion);
116 void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
117 First->ReadModuleName(ModuleName);
118 Second->ReadModuleName(ModuleName);
121 void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
122 First->ReadModuleMapFile(ModuleMapPath);
123 Second->ReadModuleMapFile(ModuleMapPath);
127 ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
129 bool AllowCompatibleDifferences) {
130 return First->ReadLanguageOptions(LangOpts, Complain,
131 AllowCompatibleDifferences) ||
132 Second->ReadLanguageOptions(LangOpts, Complain,
133 AllowCompatibleDifferences);
136 bool ChainedASTReaderListener::ReadTargetOptions(
137 const TargetOptions &TargetOpts, bool Complain,
138 bool AllowCompatibleDifferences) {
139 return First->ReadTargetOptions(TargetOpts, Complain,
140 AllowCompatibleDifferences) ||
141 Second->ReadTargetOptions(TargetOpts, Complain,
142 AllowCompatibleDifferences);
145 bool ChainedASTReaderListener::ReadDiagnosticOptions(
146 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
147 return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
148 Second->ReadDiagnosticOptions(DiagOpts, Complain);
152 ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
154 return First->ReadFileSystemOptions(FSOpts, Complain) ||
155 Second->ReadFileSystemOptions(FSOpts, Complain);
158 bool ChainedASTReaderListener::ReadHeaderSearchOptions(
159 const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath,
161 return First->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
163 Second->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
167 bool ChainedASTReaderListener::ReadPreprocessorOptions(
168 const PreprocessorOptions &PPOpts, bool Complain,
169 std::string &SuggestedPredefines) {
170 return First->ReadPreprocessorOptions(PPOpts, Complain,
171 SuggestedPredefines) ||
172 Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
174 void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
176 First->ReadCounter(M, Value);
177 Second->ReadCounter(M, Value);
179 bool ChainedASTReaderListener::needsInputFileVisitation() {
180 return First->needsInputFileVisitation() ||
181 Second->needsInputFileVisitation();
183 bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
184 return First->needsSystemInputFileVisitation() ||
185 Second->needsSystemInputFileVisitation();
187 void ChainedASTReaderListener::visitModuleFile(StringRef Filename,
189 First->visitModuleFile(Filename, Kind);
190 Second->visitModuleFile(Filename, Kind);
193 bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
196 bool isExplicitModule) {
197 bool Continue = false;
198 if (First->needsInputFileVisitation() &&
199 (!isSystem || First->needsSystemInputFileVisitation()))
200 Continue |= First->visitInputFile(Filename, isSystem, isOverridden,
202 if (Second->needsInputFileVisitation() &&
203 (!isSystem || Second->needsSystemInputFileVisitation()))
204 Continue |= Second->visitInputFile(Filename, isSystem, isOverridden,
209 void ChainedASTReaderListener::readModuleFileExtension(
210 const ModuleFileExtensionMetadata &Metadata) {
211 First->readModuleFileExtension(Metadata);
212 Second->readModuleFileExtension(Metadata);
215 //===----------------------------------------------------------------------===//
216 // PCH validator implementation
217 //===----------------------------------------------------------------------===//
219 ASTReaderListener::~ASTReaderListener() {}
221 /// \brief Compare the given set of language options against an existing set of
222 /// language options.
224 /// \param Diags If non-NULL, diagnostics will be emitted via this engine.
225 /// \param AllowCompatibleDifferences If true, differences between compatible
226 /// language options will be permitted.
228 /// \returns true if the languagae options mis-match, false otherwise.
229 static bool checkLanguageOptions(const LangOptions &LangOpts,
230 const LangOptions &ExistingLangOpts,
231 DiagnosticsEngine *Diags,
232 bool AllowCompatibleDifferences = true) {
233 #define LANGOPT(Name, Bits, Default, Description) \
234 if (ExistingLangOpts.Name != LangOpts.Name) { \
236 Diags->Report(diag::err_pch_langopt_mismatch) \
237 << Description << LangOpts.Name << ExistingLangOpts.Name; \
241 #define VALUE_LANGOPT(Name, Bits, Default, Description) \
242 if (ExistingLangOpts.Name != LangOpts.Name) { \
244 Diags->Report(diag::err_pch_langopt_value_mismatch) \
249 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
250 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
252 Diags->Report(diag::err_pch_langopt_value_mismatch) \
257 #define COMPATIBLE_LANGOPT(Name, Bits, Default, Description) \
258 if (!AllowCompatibleDifferences) \
259 LANGOPT(Name, Bits, Default, Description)
261 #define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description) \
262 if (!AllowCompatibleDifferences) \
263 ENUM_LANGOPT(Name, Bits, Default, Description)
265 #define COMPATIBLE_VALUE_LANGOPT(Name, Bits, Default, Description) \
266 if (!AllowCompatibleDifferences) \
267 VALUE_LANGOPT(Name, Bits, Default, Description)
269 #define BENIGN_LANGOPT(Name, Bits, Default, Description)
270 #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
271 #define BENIGN_VALUE_LANGOPT(Name, Type, Bits, Default, Description)
272 #include "clang/Basic/LangOptions.def"
274 if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) {
276 Diags->Report(diag::err_pch_langopt_value_mismatch) << "module features";
280 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
282 Diags->Report(diag::err_pch_langopt_value_mismatch)
283 << "target Objective-C runtime";
287 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
288 LangOpts.CommentOpts.BlockCommandNames) {
290 Diags->Report(diag::err_pch_langopt_value_mismatch)
291 << "block command names";
298 /// \brief Compare the given set of target options against an existing set of
301 /// \param Diags If non-NULL, diagnostics will be emitted via this engine.
303 /// \returns true if the target options mis-match, false otherwise.
304 static bool checkTargetOptions(const TargetOptions &TargetOpts,
305 const TargetOptions &ExistingTargetOpts,
306 DiagnosticsEngine *Diags,
307 bool AllowCompatibleDifferences = true) {
308 #define CHECK_TARGET_OPT(Field, Name) \
309 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
311 Diags->Report(diag::err_pch_targetopt_mismatch) \
312 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
316 // The triple and ABI must match exactly.
317 CHECK_TARGET_OPT(Triple, "target");
318 CHECK_TARGET_OPT(ABI, "target ABI");
320 // We can tolerate different CPUs in many cases, notably when one CPU
321 // supports a strict superset of another. When allowing compatible
322 // differences skip this check.
323 if (!AllowCompatibleDifferences)
324 CHECK_TARGET_OPT(CPU, "target CPU");
326 #undef CHECK_TARGET_OPT
328 // Compare feature sets.
329 SmallVector<StringRef, 4> ExistingFeatures(
330 ExistingTargetOpts.FeaturesAsWritten.begin(),
331 ExistingTargetOpts.FeaturesAsWritten.end());
332 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
333 TargetOpts.FeaturesAsWritten.end());
334 std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
335 std::sort(ReadFeatures.begin(), ReadFeatures.end());
337 // We compute the set difference in both directions explicitly so that we can
338 // diagnose the differences differently.
339 SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
341 ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
342 ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
343 std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
344 ExistingFeatures.begin(), ExistingFeatures.end(),
345 std::back_inserter(UnmatchedReadFeatures));
347 // If we are allowing compatible differences and the read feature set is
348 // a strict subset of the existing feature set, there is nothing to diagnose.
349 if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
353 for (StringRef Feature : UnmatchedReadFeatures)
354 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
355 << /* is-existing-feature */ false << Feature;
356 for (StringRef Feature : UnmatchedExistingFeatures)
357 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
358 << /* is-existing-feature */ true << Feature;
361 return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
365 PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
367 bool AllowCompatibleDifferences) {
368 const LangOptions &ExistingLangOpts = PP.getLangOpts();
369 return checkLanguageOptions(LangOpts, ExistingLangOpts,
370 Complain ? &Reader.Diags : nullptr,
371 AllowCompatibleDifferences);
374 bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
376 bool AllowCompatibleDifferences) {
377 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
378 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
379 Complain ? &Reader.Diags : nullptr,
380 AllowCompatibleDifferences);
385 typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
387 typedef llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> >
390 } // end anonymous namespace
392 static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
393 DiagnosticsEngine &Diags,
395 typedef DiagnosticsEngine::Level Level;
397 // Check current mappings for new -Werror mappings, and the stored mappings
398 // for cases that were explicitly mapped to *not* be errors that are now
399 // errors because of options like -Werror.
400 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
402 for (DiagnosticsEngine *MappingSource : MappingSources) {
403 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
404 diag::kind DiagID = DiagIDMappingPair.first;
405 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
406 if (CurLevel < DiagnosticsEngine::Error)
407 continue; // not significant
409 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
410 if (StoredLevel < DiagnosticsEngine::Error) {
412 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
413 Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
422 static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
423 diag::Severity Ext = Diags.getExtensionHandlingBehavior();
424 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
426 return Ext >= diag::Severity::Error;
429 static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
430 DiagnosticsEngine &Diags,
431 bool IsSystem, bool Complain) {
434 if (Diags.getSuppressSystemWarnings())
436 // If -Wsystem-headers was not enabled before, be conservative
437 if (StoredDiags.getSuppressSystemWarnings()) {
439 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
444 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
446 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
450 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
451 !StoredDiags.getEnableAllWarnings()) {
453 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
457 if (isExtHandlingFromDiagsError(Diags) &&
458 !isExtHandlingFromDiagsError(StoredDiags)) {
460 Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
464 return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
467 /// Return the top import module if it is implicit, nullptr otherwise.
468 static Module *getTopImportImplicitModule(ModuleManager &ModuleMgr,
470 // If the original import came from a file explicitly generated by the user,
471 // don't check the diagnostic mappings.
472 // FIXME: currently this is approximated by checking whether this is not a
473 // module import of an implicitly-loaded module file.
474 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
475 // the transitive closure of its imports, since unrelated modules cannot be
476 // imported until after this module finishes validation.
477 ModuleFile *TopImport = &*ModuleMgr.rbegin();
478 while (!TopImport->ImportedBy.empty())
479 TopImport = TopImport->ImportedBy[0];
480 if (TopImport->Kind != MK_ImplicitModule)
483 StringRef ModuleName = TopImport->ModuleName;
484 assert(!ModuleName.empty() && "diagnostic options read before module name");
486 Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
487 assert(M && "missing module");
491 bool PCHValidator::ReadDiagnosticOptions(
492 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
493 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
494 IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
495 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
496 new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
497 // This should never fail, because we would have processed these options
498 // before writing them to an ASTFile.
499 ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
501 ModuleManager &ModuleMgr = Reader.getModuleManager();
502 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
504 Module *TopM = getTopImportImplicitModule(ModuleMgr, PP);
508 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
509 // contains the union of their flags.
510 return checkDiagnosticMappings(*Diags, ExistingDiags, TopM->IsSystem,
514 /// \brief Collect the macro definitions provided by the given preprocessor
517 collectMacroDefinitions(const PreprocessorOptions &PPOpts,
518 MacroDefinitionsMap &Macros,
519 SmallVectorImpl<StringRef> *MacroNames = nullptr) {
520 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
521 StringRef Macro = PPOpts.Macros[I].first;
522 bool IsUndef = PPOpts.Macros[I].second;
524 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
525 StringRef MacroName = MacroPair.first;
526 StringRef MacroBody = MacroPair.second;
528 // For an #undef'd macro, we only care about the name.
530 if (MacroNames && !Macros.count(MacroName))
531 MacroNames->push_back(MacroName);
533 Macros[MacroName] = std::make_pair("", true);
537 // For a #define'd macro, figure out the actual definition.
538 if (MacroName.size() == Macro.size())
541 // Note: GCC drops anything following an end-of-line character.
542 StringRef::size_type End = MacroBody.find_first_of("\n\r");
543 MacroBody = MacroBody.substr(0, End);
546 if (MacroNames && !Macros.count(MacroName))
547 MacroNames->push_back(MacroName);
548 Macros[MacroName] = std::make_pair(MacroBody, false);
552 /// \brief Check the preprocessor options deserialized from the control block
553 /// against the preprocessor options in an existing preprocessor.
555 /// \param Diags If non-null, produce diagnostics for any mismatches incurred.
556 /// \param Validate If true, validate preprocessor options. If false, allow
557 /// macros defined by \p ExistingPPOpts to override those defined by
558 /// \p PPOpts in SuggestedPredefines.
559 static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
560 const PreprocessorOptions &ExistingPPOpts,
561 DiagnosticsEngine *Diags,
562 FileManager &FileMgr,
563 std::string &SuggestedPredefines,
564 const LangOptions &LangOpts,
565 bool Validate = true) {
566 // Check macro definitions.
567 MacroDefinitionsMap ASTFileMacros;
568 collectMacroDefinitions(PPOpts, ASTFileMacros);
569 MacroDefinitionsMap ExistingMacros;
570 SmallVector<StringRef, 4> ExistingMacroNames;
571 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
573 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
574 // Dig out the macro definition in the existing preprocessor options.
575 StringRef MacroName = ExistingMacroNames[I];
576 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
578 // Check whether we know anything about this macro name or not.
579 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
580 = ASTFileMacros.find(MacroName);
581 if (!Validate || Known == ASTFileMacros.end()) {
582 // FIXME: Check whether this identifier was referenced anywhere in the
583 // AST file. If so, we should reject the AST file. Unfortunately, this
584 // information isn't in the control block. What shall we do about it?
586 if (Existing.second) {
587 SuggestedPredefines += "#undef ";
588 SuggestedPredefines += MacroName.str();
589 SuggestedPredefines += '\n';
591 SuggestedPredefines += "#define ";
592 SuggestedPredefines += MacroName.str();
593 SuggestedPredefines += ' ';
594 SuggestedPredefines += Existing.first.str();
595 SuggestedPredefines += '\n';
600 // If the macro was defined in one but undef'd in the other, we have a
602 if (Existing.second != Known->second.second) {
604 Diags->Report(diag::err_pch_macro_def_undef)
605 << MacroName << Known->second.second;
610 // If the macro was #undef'd in both, or if the macro bodies are identical,
612 if (Existing.second || Existing.first == Known->second.first)
615 // The macro bodies differ; complain.
617 Diags->Report(diag::err_pch_macro_def_conflict)
618 << MacroName << Known->second.first << Existing.first;
623 // Check whether we're using predefines.
624 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines && Validate) {
626 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
631 // Detailed record is important since it is used for the module cache hash.
632 if (LangOpts.Modules &&
633 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord && Validate) {
635 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
640 // Compute the #include and #include_macros lines we need.
641 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
642 StringRef File = ExistingPPOpts.Includes[I];
643 if (File == ExistingPPOpts.ImplicitPCHInclude)
646 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
647 != PPOpts.Includes.end())
650 SuggestedPredefines += "#include \"";
651 SuggestedPredefines += File;
652 SuggestedPredefines += "\"\n";
655 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
656 StringRef File = ExistingPPOpts.MacroIncludes[I];
657 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
659 != PPOpts.MacroIncludes.end())
662 SuggestedPredefines += "#__include_macros \"";
663 SuggestedPredefines += File;
664 SuggestedPredefines += "\"\n##\n";
670 bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
672 std::string &SuggestedPredefines) {
673 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
675 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
676 Complain? &Reader.Diags : nullptr,
682 bool SimpleASTReaderListener::ReadPreprocessorOptions(
683 const PreprocessorOptions &PPOpts,
685 std::string &SuggestedPredefines) {
686 return checkPreprocessorOptions(PPOpts,
687 PP.getPreprocessorOpts(),
695 /// Check the header search options deserialized from the control block
696 /// against the header search options in an existing preprocessor.
698 /// \param Diags If non-null, produce diagnostics for any mismatches incurred.
699 static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
700 StringRef SpecificModuleCachePath,
701 StringRef ExistingModuleCachePath,
702 DiagnosticsEngine *Diags,
703 const LangOptions &LangOpts) {
704 if (LangOpts.Modules) {
705 if (SpecificModuleCachePath != ExistingModuleCachePath) {
707 Diags->Report(diag::err_pch_modulecache_mismatch)
708 << SpecificModuleCachePath << ExistingModuleCachePath;
716 bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
717 StringRef SpecificModuleCachePath,
719 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
720 PP.getHeaderSearchInfo().getModuleCachePath(),
721 Complain ? &Reader.Diags : nullptr,
725 void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
726 PP.setCounterValue(Value);
729 //===----------------------------------------------------------------------===//
730 // AST reader implementation
731 //===----------------------------------------------------------------------===//
733 void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
734 bool TakeOwnership) {
735 DeserializationListener = Listener;
736 OwnsDeserializationListener = TakeOwnership;
739 unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
740 return serialization::ComputeHash(Sel);
743 std::pair<unsigned, unsigned>
744 ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
745 using namespace llvm::support;
746 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
747 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
748 return std::make_pair(KeyLen, DataLen);
751 ASTSelectorLookupTrait::internal_key_type
752 ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
753 using namespace llvm::support;
754 SelectorTable &SelTable = Reader.getContext().Selectors;
755 unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
756 IdentifierInfo *FirstII = Reader.getLocalIdentifier(
757 F, endian::readNext<uint32_t, little, unaligned>(d));
759 return SelTable.getNullarySelector(FirstII);
761 return SelTable.getUnarySelector(FirstII);
763 SmallVector<IdentifierInfo *, 16> Args;
764 Args.push_back(FirstII);
765 for (unsigned I = 1; I != N; ++I)
766 Args.push_back(Reader.getLocalIdentifier(
767 F, endian::readNext<uint32_t, little, unaligned>(d)));
769 return SelTable.getSelector(N, Args.data());
772 ASTSelectorLookupTrait::data_type
773 ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
775 using namespace llvm::support;
779 Result.ID = Reader.getGlobalSelectorID(
780 F, endian::readNext<uint32_t, little, unaligned>(d));
781 unsigned FullInstanceBits = endian::readNext<uint16_t, little, unaligned>(d);
782 unsigned FullFactoryBits = endian::readNext<uint16_t, little, unaligned>(d);
783 Result.InstanceBits = FullInstanceBits & 0x3;
784 Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
785 Result.FactoryBits = FullFactoryBits & 0x3;
786 Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
787 unsigned NumInstanceMethods = FullInstanceBits >> 3;
788 unsigned NumFactoryMethods = FullFactoryBits >> 3;
790 // Load instance methods
791 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
792 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
793 F, endian::readNext<uint32_t, little, unaligned>(d)))
794 Result.Instance.push_back(Method);
797 // Load factory methods
798 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
799 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
800 F, endian::readNext<uint32_t, little, unaligned>(d)))
801 Result.Factory.push_back(Method);
807 unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
808 return llvm::HashString(a);
811 std::pair<unsigned, unsigned>
812 ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
813 using namespace llvm::support;
814 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
815 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
816 return std::make_pair(KeyLen, DataLen);
819 ASTIdentifierLookupTraitBase::internal_key_type
820 ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
821 assert(n >= 2 && d[n-1] == '\0');
822 return StringRef((const char*) d, n-1);
825 /// \brief Whether the given identifier is "interesting".
826 static bool isInterestingIdentifier(ASTReader &Reader, IdentifierInfo &II,
828 return II.hadMacroDefinition() ||
830 (IsModule ? II.hasRevertedBuiltin() : II.getObjCOrBuiltinID()) ||
831 II.hasRevertedTokenIDToIdentifier() ||
832 (!(IsModule && Reader.getContext().getLangOpts().CPlusPlus) &&
833 II.getFETokenInfo<void>());
836 static bool readBit(unsigned &Bits) {
837 bool Value = Bits & 0x1;
842 IdentID ASTIdentifierLookupTrait::ReadIdentifierID(const unsigned char *d) {
843 using namespace llvm::support;
844 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
845 return Reader.getGlobalIdentifierID(F, RawID >> 1);
848 static void markIdentifierFromAST(ASTReader &Reader, IdentifierInfo &II) {
849 if (!II.isFromAST()) {
851 bool IsModule = Reader.getPreprocessor().getCurrentModule() != nullptr;
852 if (isInterestingIdentifier(Reader, II, IsModule))
853 II.setChangedSinceDeserialization();
857 IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
858 const unsigned char* d,
860 using namespace llvm::support;
861 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
862 bool IsInteresting = RawID & 0x01;
864 // Wipe out the "is interesting" bit.
867 // Build the IdentifierInfo and link the identifier ID with it.
868 IdentifierInfo *II = KnownII;
870 II = &Reader.getIdentifierTable().getOwn(k);
873 markIdentifierFromAST(Reader, *II);
874 Reader.markIdentifierUpToDate(II);
876 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
877 if (!IsInteresting) {
878 // For uninteresting identifiers, there's nothing else to do. Just notify
879 // the reader that we've finished loading this identifier.
880 Reader.SetIdentifierInfo(ID, II);
884 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
885 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
886 bool CPlusPlusOperatorKeyword = readBit(Bits);
887 bool HasRevertedTokenIDToIdentifier = readBit(Bits);
888 bool HasRevertedBuiltin = readBit(Bits);
889 bool Poisoned = readBit(Bits);
890 bool ExtensionToken = readBit(Bits);
891 bool HadMacroDefinition = readBit(Bits);
893 assert(Bits == 0 && "Extra bits in the identifier?");
896 // Set or check the various bits in the IdentifierInfo structure.
897 // Token IDs are read-only.
898 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
899 II->revertTokenIDToIdentifier();
901 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
902 else if (HasRevertedBuiltin && II->getBuiltinID()) {
904 assert((II->hasRevertedBuiltin() ||
905 II->getObjCOrBuiltinID() == ObjCOrBuiltinID) &&
906 "Incorrect ObjC keyword or builtin ID");
908 assert(II->isExtensionToken() == ExtensionToken &&
909 "Incorrect extension token flag");
910 (void)ExtensionToken;
912 II->setIsPoisoned(true);
913 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
914 "Incorrect C++ operator keyword flag");
915 (void)CPlusPlusOperatorKeyword;
917 // If this identifier is a macro, deserialize the macro
919 if (HadMacroDefinition) {
920 uint32_t MacroDirectivesOffset =
921 endian::readNext<uint32_t, little, unaligned>(d);
924 Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
927 Reader.SetIdentifierInfo(ID, II);
929 // Read all of the declarations visible at global scope with this
932 SmallVector<uint32_t, 4> DeclIDs;
933 for (; DataLen > 0; DataLen -= 4)
934 DeclIDs.push_back(Reader.getGlobalDeclID(
935 F, endian::readNext<uint32_t, little, unaligned>(d)));
936 Reader.SetGloballyVisibleDecls(II, DeclIDs);
942 DeclarationNameKey::DeclarationNameKey(DeclarationName Name)
943 : Kind(Name.getNameKind()) {
945 case DeclarationName::Identifier:
946 Data = (uint64_t)Name.getAsIdentifierInfo();
948 case DeclarationName::ObjCZeroArgSelector:
949 case DeclarationName::ObjCOneArgSelector:
950 case DeclarationName::ObjCMultiArgSelector:
951 Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
953 case DeclarationName::CXXOperatorName:
954 Data = Name.getCXXOverloadedOperator();
956 case DeclarationName::CXXLiteralOperatorName:
957 Data = (uint64_t)Name.getCXXLiteralIdentifier();
959 case DeclarationName::CXXDeductionGuideName:
960 Data = (uint64_t)Name.getCXXDeductionGuideTemplate()
961 ->getDeclName().getAsIdentifierInfo();
963 case DeclarationName::CXXConstructorName:
964 case DeclarationName::CXXDestructorName:
965 case DeclarationName::CXXConversionFunctionName:
966 case DeclarationName::CXXUsingDirective:
972 unsigned DeclarationNameKey::getHash() const {
973 llvm::FoldingSetNodeID ID;
977 case DeclarationName::Identifier:
978 case DeclarationName::CXXLiteralOperatorName:
979 case DeclarationName::CXXDeductionGuideName:
980 ID.AddString(((IdentifierInfo*)Data)->getName());
982 case DeclarationName::ObjCZeroArgSelector:
983 case DeclarationName::ObjCOneArgSelector:
984 case DeclarationName::ObjCMultiArgSelector:
985 ID.AddInteger(serialization::ComputeHash(Selector(Data)));
987 case DeclarationName::CXXOperatorName:
988 ID.AddInteger((OverloadedOperatorKind)Data);
990 case DeclarationName::CXXConstructorName:
991 case DeclarationName::CXXDestructorName:
992 case DeclarationName::CXXConversionFunctionName:
993 case DeclarationName::CXXUsingDirective:
997 return ID.ComputeHash();
1001 ASTDeclContextNameLookupTrait::ReadFileRef(const unsigned char *&d) {
1002 using namespace llvm::support;
1003 uint32_t ModuleFileID = endian::readNext<uint32_t, little, unaligned>(d);
1004 return Reader.getLocalModuleFile(F, ModuleFileID);
1007 std::pair<unsigned, unsigned>
1008 ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char *&d) {
1009 using namespace llvm::support;
1010 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
1011 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
1012 return std::make_pair(KeyLen, DataLen);
1015 ASTDeclContextNameLookupTrait::internal_key_type
1016 ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
1017 using namespace llvm::support;
1019 auto Kind = (DeclarationName::NameKind)*d++;
1022 case DeclarationName::Identifier:
1023 case DeclarationName::CXXLiteralOperatorName:
1024 case DeclarationName::CXXDeductionGuideName:
1025 Data = (uint64_t)Reader.getLocalIdentifier(
1026 F, endian::readNext<uint32_t, little, unaligned>(d));
1028 case DeclarationName::ObjCZeroArgSelector:
1029 case DeclarationName::ObjCOneArgSelector:
1030 case DeclarationName::ObjCMultiArgSelector:
1032 (uint64_t)Reader.getLocalSelector(
1033 F, endian::readNext<uint32_t, little, unaligned>(
1034 d)).getAsOpaquePtr();
1036 case DeclarationName::CXXOperatorName:
1037 Data = *d++; // OverloadedOperatorKind
1039 case DeclarationName::CXXConstructorName:
1040 case DeclarationName::CXXDestructorName:
1041 case DeclarationName::CXXConversionFunctionName:
1042 case DeclarationName::CXXUsingDirective:
1047 return DeclarationNameKey(Kind, Data);
1050 void ASTDeclContextNameLookupTrait::ReadDataInto(internal_key_type,
1051 const unsigned char *d,
1053 data_type_builder &Val) {
1054 using namespace llvm::support;
1055 for (unsigned NumDecls = DataLen / 4; NumDecls; --NumDecls) {
1056 uint32_t LocalID = endian::readNext<uint32_t, little, unaligned>(d);
1057 Val.insert(Reader.getGlobalDeclID(F, LocalID));
1061 bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
1062 BitstreamCursor &Cursor,
1065 assert(Offset != 0);
1067 SavedStreamPosition SavedPosition(Cursor);
1068 Cursor.JumpToBit(Offset);
1072 unsigned Code = Cursor.ReadCode();
1073 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
1074 if (RecCode != DECL_CONTEXT_LEXICAL) {
1075 Error("Expected lexical block");
1079 assert(!isa<TranslationUnitDecl>(DC) &&
1080 "expected a TU_UPDATE_LEXICAL record for TU");
1081 // If we are handling a C++ class template instantiation, we can see multiple
1082 // lexical updates for the same record. It's important that we select only one
1083 // of them, so that field numbering works properly. Just pick the first one we
1085 auto &Lex = LexicalDecls[DC];
1087 Lex = std::make_pair(
1088 &M, llvm::makeArrayRef(
1089 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
1093 DC->setHasExternalLexicalStorage(true);
1097 bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M,
1098 BitstreamCursor &Cursor,
1101 assert(Offset != 0);
1103 SavedStreamPosition SavedPosition(Cursor);
1104 Cursor.JumpToBit(Offset);
1108 unsigned Code = Cursor.ReadCode();
1109 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
1110 if (RecCode != DECL_CONTEXT_VISIBLE) {
1111 Error("Expected visible lookup table block");
1115 // We can't safely determine the primary context yet, so delay attaching the
1116 // lookup table until we're done with recursive deserialization.
1117 auto *Data = (const unsigned char*)Blob.data();
1118 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&M, Data});
1122 void ASTReader::Error(StringRef Msg) const {
1123 Error(diag::err_fe_pch_malformed, Msg);
1124 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight() &&
1125 !PP.getHeaderSearchInfo().getModuleCachePath().empty()) {
1126 Diag(diag::note_module_cache_path)
1127 << PP.getHeaderSearchInfo().getModuleCachePath();
1131 void ASTReader::Error(unsigned DiagID,
1132 StringRef Arg1, StringRef Arg2) const {
1133 if (Diags.isDiagnosticInFlight())
1134 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1136 Diag(DiagID) << Arg1 << Arg2;
1139 //===----------------------------------------------------------------------===//
1140 // Source Manager Deserialization
1141 //===----------------------------------------------------------------------===//
1143 /// \brief Read the line table in the source manager block.
1144 /// \returns true if there was an error.
1145 bool ASTReader::ParseLineTable(ModuleFile &F,
1146 const RecordData &Record) {
1148 LineTableInfo &LineTable = SourceMgr.getLineTable();
1150 // Parse the file names
1151 std::map<int, int> FileIDs;
1152 for (unsigned I = 0; Record[Idx]; ++I) {
1153 // Extract the file name
1154 auto Filename = ReadPath(F, Record, Idx);
1155 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1159 // Parse the line entries
1160 std::vector<LineEntry> Entries;
1161 while (Idx < Record.size()) {
1162 int FID = Record[Idx++];
1163 assert(FID >= 0 && "Serialized line entries for non-local file.");
1164 // Remap FileID from 1-based old view.
1165 FID += F.SLocEntryBaseID - 1;
1167 // Extract the line entries
1168 unsigned NumEntries = Record[Idx++];
1169 assert(NumEntries && "no line entries for file ID");
1171 Entries.reserve(NumEntries);
1172 for (unsigned I = 0; I != NumEntries; ++I) {
1173 unsigned FileOffset = Record[Idx++];
1174 unsigned LineNo = Record[Idx++];
1175 int FilenameID = FileIDs[Record[Idx++]];
1176 SrcMgr::CharacteristicKind FileKind
1177 = (SrcMgr::CharacteristicKind)Record[Idx++];
1178 unsigned IncludeOffset = Record[Idx++];
1179 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1180 FileKind, IncludeOffset));
1182 LineTable.AddEntry(FileID::get(FID), Entries);
1188 /// \brief Read a source manager block
1189 bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1190 using namespace SrcMgr;
1192 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
1194 // Set the source-location entry cursor to the current position in
1195 // the stream. This cursor will be used to read the contents of the
1196 // source manager block initially, and then lazily read
1197 // source-location entries as needed.
1198 SLocEntryCursor = F.Stream;
1200 // The stream itself is going to skip over the source manager block.
1201 if (F.Stream.SkipBlock()) {
1202 Error("malformed block record in AST file");
1206 // Enter the source manager block.
1207 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1208 Error("malformed source manager block record in AST file");
1214 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
1217 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1218 case llvm::BitstreamEntry::Error:
1219 Error("malformed block record in AST file");
1221 case llvm::BitstreamEntry::EndBlock:
1223 case llvm::BitstreamEntry::Record:
1224 // The interesting case.
1231 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
1232 default: // Default behavior: ignore.
1235 case SM_SLOC_FILE_ENTRY:
1236 case SM_SLOC_BUFFER_ENTRY:
1237 case SM_SLOC_EXPANSION_ENTRY:
1238 // Once we hit one of the source location entries, we're done.
1244 /// \brief If a header file is not found at the path that we expect it to be
1245 /// and the PCH file was moved from its original location, try to resolve the
1246 /// file by assuming that header+PCH were moved together and the header is in
1247 /// the same place relative to the PCH.
1249 resolveFileRelativeToOriginalDir(const std::string &Filename,
1250 const std::string &OriginalDir,
1251 const std::string &CurrDir) {
1252 assert(OriginalDir != CurrDir &&
1253 "No point trying to resolve the file if the PCH dir didn't change");
1254 using namespace llvm::sys;
1255 SmallString<128> filePath(Filename);
1256 fs::make_absolute(filePath);
1257 assert(path::is_absolute(OriginalDir));
1258 SmallString<128> currPCHPath(CurrDir);
1260 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1261 fileDirE = path::end(path::parent_path(filePath));
1262 path::const_iterator origDirI = path::begin(OriginalDir),
1263 origDirE = path::end(OriginalDir);
1264 // Skip the common path components from filePath and OriginalDir.
1265 while (fileDirI != fileDirE && origDirI != origDirE &&
1266 *fileDirI == *origDirI) {
1270 for (; origDirI != origDirE; ++origDirI)
1271 path::append(currPCHPath, "..");
1272 path::append(currPCHPath, fileDirI, fileDirE);
1273 path::append(currPCHPath, path::filename(Filename));
1274 return currPCHPath.str();
1277 bool ASTReader::ReadSLocEntry(int ID) {
1281 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1282 Error("source location entry ID out-of-range for AST file");
1286 // Local helper to read the (possibly-compressed) buffer data following the
1288 auto ReadBuffer = [this](
1289 BitstreamCursor &SLocEntryCursor,
1290 StringRef Name) -> std::unique_ptr<llvm::MemoryBuffer> {
1293 unsigned Code = SLocEntryCursor.ReadCode();
1294 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
1296 if (RecCode == SM_SLOC_BUFFER_BLOB_COMPRESSED) {
1297 if (!llvm::zlib::isAvailable()) {
1298 Error("zlib is not available");
1301 SmallString<0> Uncompressed;
1303 llvm::zlib::uncompress(Blob, Uncompressed, Record[0])) {
1304 Error("could not decompress embedded file contents: " +
1305 llvm::toString(std::move(E)));
1308 return llvm::MemoryBuffer::getMemBufferCopy(Uncompressed, Name);
1309 } else if (RecCode == SM_SLOC_BUFFER_BLOB) {
1310 return llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name, true);
1312 Error("AST record has invalid code");
1317 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1318 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
1319 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
1320 unsigned BaseOffset = F->SLocEntryBaseOffset;
1322 ++NumSLocEntriesRead;
1323 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1324 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1325 Error("incorrectly-formatted source location entry in AST file");
1331 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
1333 Error("incorrectly-formatted source location entry in AST file");
1336 case SM_SLOC_FILE_ENTRY: {
1337 // We will detect whether a file changed and return 'Failure' for it, but
1338 // we will also try to fail gracefully by setting up the SLocEntry.
1339 unsigned InputID = Record[4];
1340 InputFile IF = getInputFile(*F, InputID);
1341 const FileEntry *File = IF.getFile();
1342 bool OverriddenBuffer = IF.isOverridden();
1344 // Note that we only check if a File was returned. If it was out-of-date
1345 // we have complained but we will continue creating a FileID to recover
1350 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1351 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1352 // This is the module's main file.
1353 IncludeLoc = getImportLocation(F);
1355 SrcMgr::CharacteristicKind
1356 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1357 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1358 ID, BaseOffset + Record[0]);
1359 SrcMgr::FileInfo &FileInfo =
1360 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1361 FileInfo.NumCreatedFIDs = Record[5];
1363 FileInfo.setHasLineDirectives();
1365 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1366 unsigned NumFileDecls = Record[7];
1368 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1369 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1373 const SrcMgr::ContentCache *ContentCache
1374 = SourceMgr.getOrCreateContentCache(File,
1375 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1376 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
1377 ContentCache->ContentsEntry == ContentCache->OrigEntry &&
1378 !ContentCache->getRawBuffer()) {
1379 auto Buffer = ReadBuffer(SLocEntryCursor, File->getName());
1382 SourceMgr.overrideFileContents(File, std::move(Buffer));
1388 case SM_SLOC_BUFFER_ENTRY: {
1389 const char *Name = Blob.data();
1390 unsigned Offset = Record[0];
1391 SrcMgr::CharacteristicKind
1392 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1393 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1394 if (IncludeLoc.isInvalid() && F->isModule()) {
1395 IncludeLoc = getImportLocation(F);
1398 auto Buffer = ReadBuffer(SLocEntryCursor, Name);
1401 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
1402 BaseOffset + Offset, IncludeLoc);
1406 case SM_SLOC_EXPANSION_ENTRY: {
1407 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1408 SourceMgr.createExpansionLoc(SpellingLoc,
1409 ReadSourceLocation(*F, Record[2]),
1410 ReadSourceLocation(*F, Record[3]),
1413 BaseOffset + Record[0]);
1421 std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1423 return std::make_pair(SourceLocation(), "");
1425 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1426 Error("source location entry ID out-of-range for AST file");
1427 return std::make_pair(SourceLocation(), "");
1430 // Find which module file this entry lands in.
1431 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
1433 return std::make_pair(SourceLocation(), "");
1435 // FIXME: Can we map this down to a particular submodule? That would be
1437 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
1440 /// \brief Find the location where the module F is imported.
1441 SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1442 if (F->ImportLoc.isValid())
1443 return F->ImportLoc;
1445 // Otherwise we have a PCH. It's considered to be "imported" at the first
1446 // location of its includer.
1447 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
1448 // Main file is the importer.
1449 assert(SourceMgr.getMainFileID().isValid() && "missing main file");
1450 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
1452 return F->ImportedBy[0]->FirstLoc;
1455 /// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1456 /// specified cursor. Read the abbreviations that are at the top of the block
1457 /// and then leave the cursor pointing into the block.
1458 bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
1459 if (Cursor.EnterSubBlock(BlockID))
1463 uint64_t Offset = Cursor.GetCurrentBitNo();
1464 unsigned Code = Cursor.ReadCode();
1466 // We expect all abbrevs to be at the start of the block.
1467 if (Code != llvm::bitc::DEFINE_ABBREV) {
1468 Cursor.JumpToBit(Offset);
1471 Cursor.ReadAbbrevRecord();
1475 Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
1479 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1480 Tok.setLength(Record[Idx++]);
1481 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1482 Tok.setIdentifierInfo(II);
1483 Tok.setKind((tok::TokenKind)Record[Idx++]);
1484 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1488 MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
1489 BitstreamCursor &Stream = F.MacroCursor;
1491 // Keep track of where we are in the stream, then jump back there
1492 // after reading this macro.
1493 SavedStreamPosition SavedPosition(Stream);
1495 Stream.JumpToBit(Offset);
1497 SmallVector<IdentifierInfo*, 16> MacroArgs;
1498 MacroInfo *Macro = nullptr;
1501 // Advance to the next record, but if we get to the end of the block, don't
1502 // pop it (removing all the abbreviations from the cursor) since we want to
1503 // be able to reseek within the block and read entries.
1504 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
1505 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1507 switch (Entry.Kind) {
1508 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1509 case llvm::BitstreamEntry::Error:
1510 Error("malformed block record in AST file");
1512 case llvm::BitstreamEntry::EndBlock:
1514 case llvm::BitstreamEntry::Record:
1515 // The interesting case.
1521 PreprocessorRecordTypes RecType =
1522 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
1524 case PP_MODULE_MACRO:
1525 case PP_MACRO_DIRECTIVE_HISTORY:
1528 case PP_MACRO_OBJECT_LIKE:
1529 case PP_MACRO_FUNCTION_LIKE: {
1530 // If we already have a macro, that means that we've hit the end
1531 // of the definition of the macro we were looking for. We're
1536 unsigned NextIndex = 1; // Skip identifier ID.
1537 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
1538 MacroInfo *MI = PP.AllocateMacroInfo(Loc);
1539 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
1540 MI->setIsUsed(Record[NextIndex++]);
1541 MI->setUsedForHeaderGuard(Record[NextIndex++]);
1543 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1544 // Decode function-like macro info.
1545 bool isC99VarArgs = Record[NextIndex++];
1546 bool isGNUVarArgs = Record[NextIndex++];
1547 bool hasCommaPasting = Record[NextIndex++];
1549 unsigned NumArgs = Record[NextIndex++];
1550 for (unsigned i = 0; i != NumArgs; ++i)
1551 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1553 // Install function-like macro info.
1554 MI->setIsFunctionLike();
1555 if (isC99VarArgs) MI->setIsC99Varargs();
1556 if (isGNUVarArgs) MI->setIsGNUVarargs();
1557 if (hasCommaPasting) MI->setHasCommaPasting();
1558 MI->setArgumentList(MacroArgs, PP.getPreprocessorAllocator());
1561 // Remember that we saw this macro last so that we add the tokens that
1562 // form its body to it.
1565 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1566 Record[NextIndex]) {
1567 // We have a macro definition. Register the association
1568 PreprocessedEntityID
1569 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1570 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
1571 PreprocessingRecord::PPEntityID PPID =
1572 PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
1573 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
1574 PPRec.getPreprocessedEntity(PPID));
1576 PPRec.RegisterMacroDefinition(Macro, PPDef);
1584 // If we see a TOKEN before a PP_MACRO_*, then the file is
1585 // erroneous, just pretend we didn't see this.
1589 Token Tok = ReadToken(F, Record, Idx);
1590 Macro->AddTokenToBody(Tok);
1597 PreprocessedEntityID
1598 ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M,
1599 unsigned LocalID) const {
1600 if (!M.ModuleOffsetMap.empty())
1601 ReadModuleOffsetMap(M);
1603 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1604 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1605 assert(I != M.PreprocessedEntityRemap.end()
1606 && "Invalid index into preprocessed entity index remap");
1608 return LocalID + I->second;
1611 unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1612 return llvm::hash_combine(ikey.Size, ikey.ModTime);
1615 HeaderFileInfoTrait::internal_key_type
1616 HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
1617 internal_key_type ikey = {FE->getSize(),
1618 M.HasTimestamps ? FE->getModificationTime() : 0,
1619 FE->getName(), /*Imported*/ false};
1623 bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
1624 if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime))
1627 if (llvm::sys::path::is_absolute(a.Filename) && a.Filename == b.Filename)
1630 // Determine whether the actual files are equivalent.
1631 FileManager &FileMgr = Reader.getFileManager();
1632 auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
1634 return FileMgr.getFile(Key.Filename);
1636 std::string Resolved = Key.Filename;
1637 Reader.ResolveImportedPath(M, Resolved);
1638 return FileMgr.getFile(Resolved);
1641 const FileEntry *FEA = GetFile(a);
1642 const FileEntry *FEB = GetFile(b);
1643 return FEA && FEA == FEB;
1646 std::pair<unsigned, unsigned>
1647 HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
1648 using namespace llvm::support;
1649 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
1650 unsigned DataLen = (unsigned) *d++;
1651 return std::make_pair(KeyLen, DataLen);
1654 HeaderFileInfoTrait::internal_key_type
1655 HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
1656 using namespace llvm::support;
1657 internal_key_type ikey;
1658 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1659 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
1660 ikey.Filename = (const char *)d;
1661 ikey.Imported = true;
1665 HeaderFileInfoTrait::data_type
1666 HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
1668 const unsigned char *End = d + DataLen;
1669 using namespace llvm::support;
1671 unsigned Flags = *d++;
1672 // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
1673 HFI.isImport |= (Flags >> 4) & 0x01;
1674 HFI.isPragmaOnce |= (Flags >> 3) & 0x01;
1675 HFI.DirInfo = (Flags >> 1) & 0x03;
1676 HFI.IndexHeaderMapHeader = Flags & 0x01;
1677 // FIXME: Find a better way to handle this. Maybe just store a
1678 // "has been included" flag?
1679 HFI.NumIncludes = std::max(endian::readNext<uint16_t, little, unaligned>(d),
1681 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1682 M, endian::readNext<uint32_t, little, unaligned>(d));
1683 if (unsigned FrameworkOffset =
1684 endian::readNext<uint32_t, little, unaligned>(d)) {
1685 // The framework offset is 1 greater than the actual offset,
1686 // since 0 is used as an indicator for "no framework name".
1687 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1688 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1691 assert((End - d) % 4 == 0 &&
1692 "Wrong data length in HeaderFileInfo deserialization");
1694 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
1695 auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 3);
1698 // This header is part of a module. Associate it with the module to enable
1699 // implicit module import.
1700 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1701 Module *Mod = Reader.getSubmodule(GlobalSMID);
1702 FileManager &FileMgr = Reader.getFileManager();
1704 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1706 std::string Filename = key.Filename;
1708 Reader.ResolveImportedPath(M, Filename);
1709 // FIXME: This is not always the right filename-as-written, but we're not
1710 // going to use this information to rebuild the module, so it doesn't make
1711 // a lot of difference.
1712 Module::Header H = { key.Filename, FileMgr.getFile(Filename) };
1713 ModMap.addHeader(Mod, H, HeaderRole, /*Imported*/true);
1714 HFI.isModuleHeader |= !(HeaderRole & ModuleMap::TextualHeader);
1717 // This HeaderFileInfo was externally loaded.
1718 HFI.External = true;
1723 void ASTReader::addPendingMacro(IdentifierInfo *II,
1725 uint64_t MacroDirectivesOffset) {
1726 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1727 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
1730 void ASTReader::ReadDefinedMacros() {
1731 // Note that we are loading defined macros.
1732 Deserializing Macros(this);
1734 for (ModuleFile &I : llvm::reverse(ModuleMgr)) {
1735 BitstreamCursor &MacroCursor = I.MacroCursor;
1737 // If there was no preprocessor block, skip this file.
1738 if (MacroCursor.getBitcodeBytes().empty())
1741 BitstreamCursor Cursor = MacroCursor;
1742 Cursor.JumpToBit(I.MacroStartOffset);
1746 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1749 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1750 case llvm::BitstreamEntry::Error:
1751 Error("malformed block record in AST file");
1753 case llvm::BitstreamEntry::EndBlock:
1756 case llvm::BitstreamEntry::Record:
1758 switch (Cursor.readRecord(E.ID, Record)) {
1759 default: // Default behavior: ignore.
1762 case PP_MACRO_OBJECT_LIKE:
1763 case PP_MACRO_FUNCTION_LIKE: {
1764 IdentifierInfo *II = getLocalIdentifier(I, Record[0]);
1765 if (II->isOutOfDate())
1766 updateOutOfDateIdentifier(*II);
1783 /// \brief Visitor class used to look up identifirs in an AST file.
1784 class IdentifierLookupVisitor {
1787 unsigned PriorGeneration;
1788 unsigned &NumIdentifierLookups;
1789 unsigned &NumIdentifierLookupHits;
1790 IdentifierInfo *Found;
1793 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1794 unsigned &NumIdentifierLookups,
1795 unsigned &NumIdentifierLookupHits)
1796 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
1797 PriorGeneration(PriorGeneration),
1798 NumIdentifierLookups(NumIdentifierLookups),
1799 NumIdentifierLookupHits(NumIdentifierLookupHits),
1804 bool operator()(ModuleFile &M) {
1805 // If we've already searched this module file, skip it now.
1806 if (M.Generation <= PriorGeneration)
1809 ASTIdentifierLookupTable *IdTable
1810 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1814 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
1816 ++NumIdentifierLookups;
1817 ASTIdentifierLookupTable::iterator Pos =
1818 IdTable->find_hashed(Name, NameHash, &Trait);
1819 if (Pos == IdTable->end())
1822 // Dereferencing the iterator has the effect of building the
1823 // IdentifierInfo node and populating it with the various
1824 // declarations it needs.
1825 ++NumIdentifierLookupHits;
1830 // \brief Retrieve the identifier info found within the module
1832 IdentifierInfo *getIdentifierInfo() const { return Found; }
1835 } // end anonymous namespace
1837 void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1838 // Note that we are loading an identifier.
1839 Deserializing AnIdentifier(this);
1841 unsigned PriorGeneration = 0;
1842 if (getContext().getLangOpts().Modules)
1843 PriorGeneration = IdentifierGeneration[&II];
1845 // If there is a global index, look there first to determine which modules
1846 // provably do not have any results for this identifier.
1847 GlobalModuleIndex::HitSet Hits;
1848 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
1849 if (!loadGlobalIndex()) {
1850 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1855 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
1856 NumIdentifierLookups,
1857 NumIdentifierLookupHits);
1858 ModuleMgr.visit(Visitor, HitsPtr);
1859 markIdentifierUpToDate(&II);
1862 void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1866 II->setOutOfDate(false);
1868 // Update the generation for this identifier.
1869 if (getContext().getLangOpts().Modules)
1870 IdentifierGeneration[II] = getGeneration();
1873 void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1874 const PendingMacroInfo &PMInfo) {
1875 ModuleFile &M = *PMInfo.M;
1877 BitstreamCursor &Cursor = M.MacroCursor;
1878 SavedStreamPosition SavedPosition(Cursor);
1879 Cursor.JumpToBit(PMInfo.MacroDirectivesOffset);
1881 struct ModuleMacroRecord {
1882 SubmoduleID SubModID;
1884 SmallVector<SubmoduleID, 8> Overrides;
1886 llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
1888 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
1889 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
1893 llvm::BitstreamEntry Entry =
1894 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1895 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1896 Error("malformed block record in AST file");
1901 switch ((PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
1902 case PP_MACRO_DIRECTIVE_HISTORY:
1905 case PP_MODULE_MACRO: {
1906 ModuleMacros.push_back(ModuleMacroRecord());
1907 auto &Info = ModuleMacros.back();
1908 Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
1909 Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
1910 for (int I = 2, N = Record.size(); I != N; ++I)
1911 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
1916 Error("malformed block record in AST file");
1920 // We found the macro directive history; that's the last record
1925 // Module macros are listed in reverse dependency order.
1927 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
1928 llvm::SmallVector<ModuleMacro*, 8> Overrides;
1929 for (auto &MMR : ModuleMacros) {
1931 for (unsigned ModID : MMR.Overrides) {
1932 Module *Mod = getSubmodule(ModID);
1933 auto *Macro = PP.getModuleMacro(Mod, II);
1934 assert(Macro && "missing definition for overridden macro");
1935 Overrides.push_back(Macro);
1938 bool Inserted = false;
1939 Module *Owner = getSubmodule(MMR.SubModID);
1940 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
1944 // Don't read the directive history for a module; we don't have anywhere
1949 // Deserialize the macro directives history in reverse source-order.
1950 MacroDirective *Latest = nullptr, *Earliest = nullptr;
1951 unsigned Idx = 0, N = Record.size();
1953 MacroDirective *MD = nullptr;
1954 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
1955 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1957 case MacroDirective::MD_Define: {
1958 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
1959 MD = PP.AllocateDefMacroDirective(MI, Loc);
1962 case MacroDirective::MD_Undefine: {
1963 MD = PP.AllocateUndefMacroDirective(Loc);
1966 case MacroDirective::MD_Visibility:
1967 bool isPublic = Record[Idx++];
1968 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1975 Earliest->setPrevious(MD);
1980 PP.setLoadedMacroDirective(II, Earliest, Latest);
1983 ASTReader::InputFileInfo
1984 ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
1985 // Go find this input file.
1986 BitstreamCursor &Cursor = F.InputFilesCursor;
1987 SavedStreamPosition SavedPosition(Cursor);
1988 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1990 unsigned Code = Cursor.ReadCode();
1994 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
1995 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
1996 "invalid record type for input file");
1999 assert(Record[0] == ID && "Bogus stored ID or offset");
2001 R.StoredSize = static_cast<off_t>(Record[1]);
2002 R.StoredTime = static_cast<time_t>(Record[2]);
2003 R.Overridden = static_cast<bool>(Record[3]);
2004 R.Transient = static_cast<bool>(Record[4]);
2006 ResolveImportedPath(F, R.Filename);
2010 static unsigned moduleKindForDiagnostic(ModuleKind Kind);
2011 InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
2012 // If this ID is bogus, just return an empty input file.
2013 if (ID == 0 || ID > F.InputFilesLoaded.size())
2016 // If we've already loaded this input file, return it.
2017 if (F.InputFilesLoaded[ID-1].getFile())
2018 return F.InputFilesLoaded[ID-1];
2020 if (F.InputFilesLoaded[ID-1].isNotFound())
2023 // Go find this input file.
2024 BitstreamCursor &Cursor = F.InputFilesCursor;
2025 SavedStreamPosition SavedPosition(Cursor);
2026 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
2028 InputFileInfo FI = readInputFileInfo(F, ID);
2029 off_t StoredSize = FI.StoredSize;
2030 time_t StoredTime = FI.StoredTime;
2031 bool Overridden = FI.Overridden;
2032 bool Transient = FI.Transient;
2033 StringRef Filename = FI.Filename;
2035 const FileEntry *File = FileMgr.getFile(Filename, /*OpenFile=*/false);
2037 // If we didn't find the file, resolve it relative to the
2038 // original directory from which this AST file was created.
2039 if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() &&
2040 F.OriginalDir != CurrentDir) {
2041 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
2044 if (!Resolved.empty())
2045 File = FileMgr.getFile(Resolved);
2048 // For an overridden file, create a virtual file with the stored
2050 if ((Overridden || Transient) && File == nullptr)
2051 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
2053 if (File == nullptr) {
2055 std::string ErrorStr = "could not find file '";
2056 ErrorStr += Filename;
2057 ErrorStr += "' referenced by AST file '";
2058 ErrorStr += F.FileName;
2062 // Record that we didn't find the file.
2063 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
2067 // Check if there was a request to override the contents of the file
2068 // that was part of the precompiled header. Overridding such a file
2069 // can lead to problems when lexing using the source locations from the
2071 SourceManager &SM = getSourceManager();
2072 // FIXME: Reject if the overrides are different.
2073 if ((!Overridden && !Transient) && SM.isFileOverridden(File)) {
2075 Error(diag::err_fe_pch_file_overridden, Filename);
2076 // After emitting the diagnostic, recover by disabling the override so
2077 // that the original file will be used.
2079 // FIXME: This recovery is just as broken as the original state; there may
2080 // be another precompiled module that's using the overridden contents, or
2081 // we might be half way through parsing it. Instead, we should treat the
2082 // overridden contents as belonging to a separate FileEntry.
2083 SM.disableFileContentsOverride(File);
2084 // The FileEntry is a virtual file entry with the size of the contents
2085 // that would override the original contents. Set it to the original's
2087 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
2088 StoredSize, StoredTime);
2091 bool IsOutOfDate = false;
2093 // For an overridden file, there is nothing to validate.
2094 if (!Overridden && //
2095 (StoredSize != File->getSize() ||
2096 (StoredTime && StoredTime != File->getModificationTime() &&
2100 // Build a list of the PCH imports that got us here (in reverse).
2101 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2102 while (ImportStack.back()->ImportedBy.size() > 0)
2103 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
2105 // The top-level PCH is stale.
2106 StringRef TopLevelPCHName(ImportStack.back()->FileName);
2107 unsigned DiagnosticKind = moduleKindForDiagnostic(ImportStack.back()->Kind);
2108 if (DiagnosticKind == 0)
2109 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
2110 else if (DiagnosticKind == 1)
2111 Error(diag::err_fe_module_file_modified, Filename, TopLevelPCHName);
2113 Error(diag::err_fe_ast_file_modified, Filename, TopLevelPCHName);
2115 // Print the import stack.
2116 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2117 Diag(diag::note_pch_required_by)
2118 << Filename << ImportStack[0]->FileName;
2119 for (unsigned I = 1; I < ImportStack.size(); ++I)
2120 Diag(diag::note_pch_required_by)
2121 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
2124 if (!Diags.isDiagnosticInFlight())
2125 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
2130 // FIXME: If the file is overridden and we've already opened it,
2131 // issue an error (or split it into a separate FileEntry).
2133 InputFile IF = InputFile(File, Overridden || Transient, IsOutOfDate);
2135 // Note that we've loaded this input file.
2136 F.InputFilesLoaded[ID-1] = IF;
2140 /// \brief If we are loading a relocatable PCH or module file, and the filename
2141 /// is not an absolute path, add the system or module root to the beginning of
2143 void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2144 // Resolve relative to the base directory, if we have one.
2145 if (!M.BaseDirectory.empty())
2146 return ResolveImportedPath(Filename, M.BaseDirectory);
2149 void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
2150 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2153 SmallString<128> Buffer;
2154 llvm::sys::path::append(Buffer, Prefix, Filename);
2155 Filename.assign(Buffer.begin(), Buffer.end());
2158 static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
2160 case ASTReader::Failure: return true;
2161 case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
2162 case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
2163 case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch);
2164 case ASTReader::ConfigurationMismatch:
2165 return !(Caps & ASTReader::ARR_ConfigurationMismatch);
2166 case ASTReader::HadErrors: return true;
2167 case ASTReader::Success: return false;
2170 llvm_unreachable("unknown ASTReadResult");
2173 ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(
2174 BitstreamCursor &Stream, unsigned ClientLoadCapabilities,
2175 bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener,
2176 std::string &SuggestedPredefines) {
2177 if (Stream.EnterSubBlock(OPTIONS_BLOCK_ID))
2180 // Read all of the records in the options block.
2182 ASTReadResult Result = Success;
2184 llvm::BitstreamEntry Entry = Stream.advance();
2186 switch (Entry.Kind) {
2187 case llvm::BitstreamEntry::Error:
2188 case llvm::BitstreamEntry::SubBlock:
2191 case llvm::BitstreamEntry::EndBlock:
2194 case llvm::BitstreamEntry::Record:
2195 // The interesting case.
2199 // Read and process a record.
2201 switch ((OptionsRecordTypes)Stream.readRecord(Entry.ID, Record)) {
2202 case LANGUAGE_OPTIONS: {
2203 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2204 if (ParseLanguageOptions(Record, Complain, Listener,
2205 AllowCompatibleConfigurationMismatch))
2206 Result = ConfigurationMismatch;
2210 case TARGET_OPTIONS: {
2211 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2212 if (ParseTargetOptions(Record, Complain, Listener,
2213 AllowCompatibleConfigurationMismatch))
2214 Result = ConfigurationMismatch;
2218 case FILE_SYSTEM_OPTIONS: {
2219 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2220 if (!AllowCompatibleConfigurationMismatch &&
2221 ParseFileSystemOptions(Record, Complain, Listener))
2222 Result = ConfigurationMismatch;
2226 case HEADER_SEARCH_OPTIONS: {
2227 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2228 if (!AllowCompatibleConfigurationMismatch &&
2229 ParseHeaderSearchOptions(Record, Complain, Listener))
2230 Result = ConfigurationMismatch;
2234 case PREPROCESSOR_OPTIONS:
2235 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2236 if (!AllowCompatibleConfigurationMismatch &&
2237 ParsePreprocessorOptions(Record, Complain, Listener,
2238 SuggestedPredefines))
2239 Result = ConfigurationMismatch;
2245 ASTReader::ASTReadResult
2246 ASTReader::ReadControlBlock(ModuleFile &F,
2247 SmallVectorImpl<ImportedModule> &Loaded,
2248 const ModuleFile *ImportedBy,
2249 unsigned ClientLoadCapabilities) {
2250 BitstreamCursor &Stream = F.Stream;
2251 ASTReadResult Result = Success;
2253 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2254 Error("malformed block record in AST file");
2258 // Lambda to read the unhashed control block the first time it's called.
2260 // For PCM files, the unhashed control block cannot be read until after the
2261 // MODULE_NAME record. However, PCH files have no MODULE_NAME, and yet still
2262 // need to look ahead before reading the IMPORTS record. For consistency,
2263 // this block is always read somehow (see BitstreamEntry::EndBlock).
2264 bool HasReadUnhashedControlBlock = false;
2265 auto readUnhashedControlBlockOnce = [&]() {
2266 if (!HasReadUnhashedControlBlock) {
2267 HasReadUnhashedControlBlock = true;
2268 if (ASTReadResult Result =
2269 readUnhashedControlBlock(F, ImportedBy, ClientLoadCapabilities))
2275 // Read all of the records and blocks in the control block.
2277 unsigned NumInputs = 0;
2278 unsigned NumUserInputs = 0;
2280 llvm::BitstreamEntry Entry = Stream.advance();
2282 switch (Entry.Kind) {
2283 case llvm::BitstreamEntry::Error:
2284 Error("malformed block record in AST file");
2286 case llvm::BitstreamEntry::EndBlock: {
2287 // Validate the module before returning. This call catches an AST with
2288 // no module name and no imports.
2289 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2292 // Validate input files.
2293 const HeaderSearchOptions &HSOpts =
2294 PP.getHeaderSearchInfo().getHeaderSearchOpts();
2296 // All user input files reside at the index range [0, NumUserInputs), and
2297 // system input files reside at [NumUserInputs, NumInputs). For explicitly
2298 // loaded module files, ignore missing inputs.
2299 if (!DisableValidation && F.Kind != MK_ExplicitModule &&
2300 F.Kind != MK_PrebuiltModule) {
2301 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
2303 // If we are reading a module, we will create a verification timestamp,
2304 // so we verify all input files. Otherwise, verify only user input
2307 unsigned N = NumUserInputs;
2308 if (ValidateSystemInputs ||
2309 (HSOpts.ModulesValidateOncePerBuildSession &&
2310 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
2311 F.Kind == MK_ImplicitModule))
2314 for (unsigned I = 0; I < N; ++I) {
2315 InputFile IF = getInputFile(F, I+1, Complain);
2316 if (!IF.getFile() || IF.isOutOfDate())
2322 Listener->visitModuleFile(F.FileName, F.Kind);
2324 if (Listener && Listener->needsInputFileVisitation()) {
2325 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2327 for (unsigned I = 0; I < N; ++I) {
2328 bool IsSystem = I >= NumUserInputs;
2329 InputFileInfo FI = readInputFileInfo(F, I+1);
2330 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden,
2331 F.Kind == MK_ExplicitModule ||
2332 F.Kind == MK_PrebuiltModule);
2339 case llvm::BitstreamEntry::SubBlock:
2341 case INPUT_FILES_BLOCK_ID:
2342 F.InputFilesCursor = Stream;
2343 if (Stream.SkipBlock() || // Skip with the main cursor
2344 // Read the abbreviations
2345 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2346 Error("malformed block record in AST file");
2351 case OPTIONS_BLOCK_ID:
2352 // If we're reading the first module for this group, check its options
2353 // are compatible with ours. For modules it imports, no further checking
2354 // is required, because we checked them when we built it.
2355 if (Listener && !ImportedBy) {
2356 // Should we allow the configuration of the module file to differ from
2357 // the configuration of the current translation unit in a compatible
2360 // FIXME: Allow this for files explicitly specified with -include-pch.
2361 bool AllowCompatibleConfigurationMismatch =
2362 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
2364 Result = ReadOptionsBlock(Stream, ClientLoadCapabilities,
2365 AllowCompatibleConfigurationMismatch,
2366 *Listener, SuggestedPredefines);
2367 if (Result == Failure) {
2368 Error("malformed block record in AST file");
2372 if (DisableValidation ||
2373 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
2376 // If we can't load the module, exit early since we likely
2377 // will rebuild the module anyway. The stream may be in the
2378 // middle of a block.
2379 if (Result != Success)
2381 } else if (Stream.SkipBlock()) {
2382 Error("malformed block record in AST file");
2388 if (Stream.SkipBlock()) {
2389 Error("malformed block record in AST file");
2395 case llvm::BitstreamEntry::Record:
2396 // The interesting case.
2400 // Read and process a record.
2403 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
2405 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2406 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
2407 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2408 : diag::err_pch_version_too_new);
2409 return VersionMismatch;
2412 bool hasErrors = Record[6];
2413 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2414 Diag(diag::err_pch_with_compiler_errors);
2418 Diags.ErrorOccurred = true;
2419 Diags.UncompilableErrorOccurred = true;
2420 Diags.UnrecoverableErrorOccurred = true;
2423 F.RelocatablePCH = Record[4];
2424 // Relative paths in a relocatable PCH are relative to our sysroot.
2425 if (F.RelocatablePCH)
2426 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
2428 F.HasTimestamps = Record[5];
2430 const std::string &CurBranch = getClangFullRepositoryVersion();
2431 StringRef ASTBranch = Blob;
2432 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2433 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
2434 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
2435 return VersionMismatch;
2441 // Validate the AST before processing any imports (otherwise, untangling
2442 // them can be error-prone and expensive). A module will have a name and
2443 // will already have been validated, but this catches the PCH case.
2444 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2447 // Load each of the imported PCH files.
2448 unsigned Idx = 0, N = Record.size();
2450 // Read information about the AST file.
2451 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2452 // The import location will be the local one for now; we will adjust
2453 // all import locations of module imports after the global source
2454 // location info are setup, in ReadAST.
2455 SourceLocation ImportLoc =
2456 ReadUntranslatedSourceLocation(Record[Idx++]);
2457 off_t StoredSize = (off_t)Record[Idx++];
2458 time_t StoredModTime = (time_t)Record[Idx++];
2459 ASTFileSignature StoredSignature = {
2460 {{(uint32_t)Record[Idx++], (uint32_t)Record[Idx++],
2461 (uint32_t)Record[Idx++], (uint32_t)Record[Idx++],
2462 (uint32_t)Record[Idx++]}}};
2463 auto ImportedFile = ReadPath(F, Record, Idx);
2465 // If our client can't cope with us being out of date, we can't cope with
2466 // our dependency being missing.
2467 unsigned Capabilities = ClientLoadCapabilities;
2468 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2469 Capabilities &= ~ARR_Missing;
2471 // Load the AST file.
2472 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
2473 Loaded, StoredSize, StoredModTime,
2474 StoredSignature, Capabilities);
2476 // If we diagnosed a problem, produce a backtrace.
2477 if (isDiagnosedResult(Result, Capabilities))
2478 Diag(diag::note_module_file_imported_by)
2479 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
2482 case Failure: return Failure;
2483 // If we have to ignore the dependency, we'll have to ignore this too.
2485 case OutOfDate: return OutOfDate;
2486 case VersionMismatch: return VersionMismatch;
2487 case ConfigurationMismatch: return ConfigurationMismatch;
2488 case HadErrors: return HadErrors;
2489 case Success: break;
2496 F.OriginalSourceFileID = FileID::get(Record[0]);
2497 F.ActualOriginalSourceFileName = Blob;
2498 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
2499 ResolveImportedPath(F, F.OriginalSourceFileName);
2502 case ORIGINAL_FILE_ID:
2503 F.OriginalSourceFileID = FileID::get(Record[0]);
2506 case ORIGINAL_PCH_DIR:
2507 F.OriginalDir = Blob;
2511 F.ModuleName = Blob;
2513 Listener->ReadModuleName(F.ModuleName);
2515 // Validate the AST as soon as we have a name so we can exit early on
2517 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2522 case MODULE_DIRECTORY: {
2523 assert(!F.ModuleName.empty() &&
2524 "MODULE_DIRECTORY found before MODULE_NAME");
2525 // If we've already loaded a module map file covering this module, we may
2526 // have a better path for it (relative to the current build).
2527 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2528 if (M && M->Directory) {
2529 // If we're implicitly loading a module, the base directory can't
2530 // change between the build and use.
2531 if (F.Kind != MK_ExplicitModule && F.Kind != MK_PrebuiltModule) {
2532 const DirectoryEntry *BuildDir =
2533 PP.getFileManager().getDirectory(Blob);
2534 if (!BuildDir || BuildDir != M->Directory) {
2535 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2536 Diag(diag::err_imported_module_relocated)
2537 << F.ModuleName << Blob << M->Directory->getName();
2541 F.BaseDirectory = M->Directory->getName();
2543 F.BaseDirectory = Blob;
2548 case MODULE_MAP_FILE:
2549 if (ASTReadResult Result =
2550 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2554 case INPUT_FILE_OFFSETS:
2555 NumInputs = Record[0];
2556 NumUserInputs = Record[1];
2557 F.InputFileOffsets =
2558 (const llvm::support::unaligned_uint64_t *)Blob.data();
2559 F.InputFilesLoaded.resize(NumInputs);
2560 F.NumUserInputFiles = NumUserInputs;
2566 ASTReader::ASTReadResult
2567 ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
2568 BitstreamCursor &Stream = F.Stream;
2570 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2571 Error("malformed block record in AST file");
2575 // Read all of the records and blocks for the AST file.
2578 llvm::BitstreamEntry Entry = Stream.advance();
2580 switch (Entry.Kind) {
2581 case llvm::BitstreamEntry::Error:
2582 Error("error at end of module block in AST file");
2584 case llvm::BitstreamEntry::EndBlock: {
2585 // Outside of C++, we do not store a lookup map for the translation unit.
2586 // Instead, mark it as needing a lookup map to be built if this module
2587 // contains any declarations lexically within it (which it always does!).
2588 // This usually has no cost, since we very rarely need the lookup map for
2589 // the translation unit outside C++.
2590 DeclContext *DC = Context.getTranslationUnitDecl();
2591 if (DC->hasExternalLexicalStorage() &&
2592 !getContext().getLangOpts().CPlusPlus)
2593 DC->setMustBuildLookupTable();
2597 case llvm::BitstreamEntry::SubBlock:
2599 case DECLTYPES_BLOCK_ID:
2600 // We lazily load the decls block, but we want to set up the
2601 // DeclsCursor cursor to point into it. Clone our current bitcode
2602 // cursor to it, enter the block and read the abbrevs in that block.
2603 // With the main cursor, we just skip over it.
2604 F.DeclsCursor = Stream;
2605 if (Stream.SkipBlock() || // Skip with the main cursor.
2606 // Read the abbrevs.
2607 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2608 Error("malformed block record in AST file");
2613 case PREPROCESSOR_BLOCK_ID:
2614 F.MacroCursor = Stream;
2615 if (!PP.getExternalSource())
2616 PP.setExternalSource(this);
2618 if (Stream.SkipBlock() ||
2619 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2620 Error("malformed block record in AST file");
2623 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2626 case PREPROCESSOR_DETAIL_BLOCK_ID:
2627 F.PreprocessorDetailCursor = Stream;
2628 if (Stream.SkipBlock() ||
2629 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
2630 PREPROCESSOR_DETAIL_BLOCK_ID)) {
2631 Error("malformed preprocessor detail record in AST file");
2634 F.PreprocessorDetailStartOffset
2635 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2637 if (!PP.getPreprocessingRecord())
2638 PP.createPreprocessingRecord();
2639 if (!PP.getPreprocessingRecord()->getExternalSource())
2640 PP.getPreprocessingRecord()->SetExternalSource(*this);
2643 case SOURCE_MANAGER_BLOCK_ID:
2644 if (ReadSourceManagerBlock(F))
2648 case SUBMODULE_BLOCK_ID:
2649 if (ASTReadResult Result =
2650 ReadSubmoduleBlock(F, ClientLoadCapabilities))
2654 case COMMENTS_BLOCK_ID: {
2655 BitstreamCursor C = Stream;
2656 if (Stream.SkipBlock() ||
2657 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2658 Error("malformed comments block in AST file");
2661 CommentsCursors.push_back(std::make_pair(C, &F));
2666 if (Stream.SkipBlock()) {
2667 Error("malformed block record in AST file");
2674 case llvm::BitstreamEntry::Record:
2675 // The interesting case.
2679 // Read and process a record.
2682 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
2683 default: // Default behavior: ignore.
2687 if (F.LocalNumTypes != 0) {
2688 Error("duplicate TYPE_OFFSET record in AST file");
2691 F.TypeOffsets = (const uint32_t *)Blob.data();
2692 F.LocalNumTypes = Record[0];
2693 unsigned LocalBaseTypeIndex = Record[1];
2694 F.BaseTypeIndex = getTotalNumTypes();
2696 if (F.LocalNumTypes > 0) {
2697 // Introduce the global -> local mapping for types within this module.
2698 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2700 // Introduce the local -> global mapping for types within this module.
2701 F.TypeRemap.insertOrReplace(
2702 std::make_pair(LocalBaseTypeIndex,
2703 F.BaseTypeIndex - LocalBaseTypeIndex));
2705 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
2711 if (F.LocalNumDecls != 0) {
2712 Error("duplicate DECL_OFFSET record in AST file");
2715 F.DeclOffsets = (const DeclOffset *)Blob.data();
2716 F.LocalNumDecls = Record[0];
2717 unsigned LocalBaseDeclID = Record[1];
2718 F.BaseDeclID = getTotalNumDecls();
2720 if (F.LocalNumDecls > 0) {
2721 // Introduce the global -> local mapping for declarations within this
2723 GlobalDeclMap.insert(
2724 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2726 // Introduce the local -> global mapping for declarations within this
2728 F.DeclRemap.insertOrReplace(
2729 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2731 // Introduce the global -> local mapping for declarations within this
2733 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
2735 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2740 case TU_UPDATE_LEXICAL: {
2741 DeclContext *TU = Context.getTranslationUnitDecl();
2742 LexicalContents Contents(
2743 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
2745 static_cast<unsigned int>(Blob.size() / 4));
2746 TULexicalDecls.push_back(std::make_pair(&F, Contents));
2747 TU->setHasExternalLexicalStorage(true);
2751 case UPDATE_VISIBLE: {
2753 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
2754 auto *Data = (const unsigned char*)Blob.data();
2755 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&F, Data});
2756 // If we've already loaded the decl, perform the updates when we finish
2757 // loading this block.
2758 if (Decl *D = GetExistingDecl(ID))
2759 PendingUpdateRecords.push_back(
2760 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
2764 case IDENTIFIER_TABLE:
2765 F.IdentifierTableData = Blob.data();
2767 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2768 (const unsigned char *)F.IdentifierTableData + Record[0],
2769 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2770 (const unsigned char *)F.IdentifierTableData,
2771 ASTIdentifierLookupTrait(*this, F));
2773 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2777 case IDENTIFIER_OFFSET: {
2778 if (F.LocalNumIdentifiers != 0) {
2779 Error("duplicate IDENTIFIER_OFFSET record in AST file");
2782 F.IdentifierOffsets = (const uint32_t *)Blob.data();
2783 F.LocalNumIdentifiers = Record[0];
2784 unsigned LocalBaseIdentifierID = Record[1];
2785 F.BaseIdentifierID = getTotalNumIdentifiers();
2787 if (F.LocalNumIdentifiers > 0) {
2788 // Introduce the global -> local mapping for identifiers within this
2790 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2793 // Introduce the local -> global mapping for identifiers within this
2795 F.IdentifierRemap.insertOrReplace(
2796 std::make_pair(LocalBaseIdentifierID,
2797 F.BaseIdentifierID - LocalBaseIdentifierID));
2799 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2800 + F.LocalNumIdentifiers);
2805 case INTERESTING_IDENTIFIERS:
2806 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
2809 case EAGERLY_DESERIALIZED_DECLS:
2810 // FIXME: Skip reading this record if our ASTConsumer doesn't care
2811 // about "interesting" decls (for instance, if we're building a module).
2812 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2813 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
2816 case MODULAR_CODEGEN_DECLS:
2817 // FIXME: Skip reading this record if our ASTConsumer doesn't care about
2818 // them (ie: if we're not codegenerating this module).
2819 if (F.Kind == MK_MainFile)
2820 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2821 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
2825 if (SpecialTypes.empty()) {
2826 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2827 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2831 if (SpecialTypes.size() != Record.size()) {
2832 Error("invalid special-types record");
2836 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2837 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2838 if (!SpecialTypes[I])
2839 SpecialTypes[I] = ID;
2840 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2846 TotalNumStatements += Record[0];
2847 TotalNumMacros += Record[1];
2848 TotalLexicalDeclContexts += Record[2];
2849 TotalVisibleDeclContexts += Record[3];
2852 case UNUSED_FILESCOPED_DECLS:
2853 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2854 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2857 case DELEGATING_CTORS:
2858 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2859 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2862 case WEAK_UNDECLARED_IDENTIFIERS:
2863 if (Record.size() % 4 != 0) {
2864 Error("invalid weak identifiers record");
2868 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2869 // files. This isn't the way to do it :)
2870 WeakUndeclaredIdentifiers.clear();
2872 // Translate the weak, undeclared identifiers into global IDs.
2873 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2874 WeakUndeclaredIdentifiers.push_back(
2875 getGlobalIdentifierID(F, Record[I++]));
2876 WeakUndeclaredIdentifiers.push_back(
2877 getGlobalIdentifierID(F, Record[I++]));
2878 WeakUndeclaredIdentifiers.push_back(
2879 ReadSourceLocation(F, Record, I).getRawEncoding());
2880 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2884 case SELECTOR_OFFSETS: {
2885 F.SelectorOffsets = (const uint32_t *)Blob.data();
2886 F.LocalNumSelectors = Record[0];
2887 unsigned LocalBaseSelectorID = Record[1];
2888 F.BaseSelectorID = getTotalNumSelectors();
2890 if (F.LocalNumSelectors > 0) {
2891 // Introduce the global -> local mapping for selectors within this
2893 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2895 // Introduce the local -> global mapping for selectors within this
2897 F.SelectorRemap.insertOrReplace(
2898 std::make_pair(LocalBaseSelectorID,
2899 F.BaseSelectorID - LocalBaseSelectorID));
2901 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
2907 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
2909 F.SelectorLookupTable
2910 = ASTSelectorLookupTable::Create(
2911 F.SelectorLookupTableData + Record[0],
2912 F.SelectorLookupTableData,
2913 ASTSelectorLookupTrait(*this, F));
2914 TotalNumMethodPoolEntries += Record[1];
2917 case REFERENCED_SELECTOR_POOL:
2918 if (!Record.empty()) {
2919 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2920 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2922 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2928 case PP_COUNTER_VALUE:
2929 if (!Record.empty() && Listener)
2930 Listener->ReadCounter(F, Record[0]);
2933 case FILE_SORTED_DECLS:
2934 F.FileSortedDecls = (const DeclID *)Blob.data();
2935 F.NumFileSortedDecls = Record[0];
2938 case SOURCE_LOCATION_OFFSETS: {
2939 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
2940 F.LocalNumSLocEntries = Record[0];
2941 unsigned SLocSpaceSize = Record[1];
2942 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
2943 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
2945 if (!F.SLocEntryBaseID) {
2946 Error("ran out of source locations");
2949 // Make our entry in the range map. BaseID is negative and growing, so
2950 // we invert it. Because we invert it, though, we need the other end of
2952 unsigned RangeStart =
2953 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2954 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2955 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2957 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2958 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2959 GlobalSLocOffsetMap.insert(
2960 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2961 - SLocSpaceSize,&F));
2963 // Initialize the remapping table.
2964 // Invalid stays invalid.
2965 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
2966 // This module. Base was 2 when being compiled.
2967 F.SLocRemap.insertOrReplace(std::make_pair(2U,
2968 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2970 TotalNumSLocEntries += F.LocalNumSLocEntries;
2974 case MODULE_OFFSET_MAP:
2975 F.ModuleOffsetMap = Blob;
2978 case SOURCE_MANAGER_LINE_TABLE:
2979 if (ParseLineTable(F, Record))
2983 case SOURCE_LOCATION_PRELOADS: {
2984 // Need to transform from the local view (1-based IDs) to the global view,
2985 // which is based off F.SLocEntryBaseID.
2986 if (!F.PreloadSLocEntries.empty()) {
2987 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
2991 F.PreloadSLocEntries.swap(Record);
2995 case EXT_VECTOR_DECLS:
2996 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2997 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
3001 if (Record.size() % 3 != 0) {
3002 Error("Invalid VTABLE_USES record");
3006 // Later tables overwrite earlier ones.
3007 // FIXME: Modules will have some trouble with this. This is clearly not
3008 // the right way to do this.
3011 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
3012 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
3013 VTableUses.push_back(
3014 ReadSourceLocation(F, Record, Idx).getRawEncoding());
3015 VTableUses.push_back(Record[Idx++]);
3019 case PENDING_IMPLICIT_INSTANTIATIONS:
3020 if (PendingInstantiations.size() % 2 != 0) {
3021 Error("Invalid existing PendingInstantiations");
3025 if (Record.size() % 2 != 0) {
3026 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
3030 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3031 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
3032 PendingInstantiations.push_back(
3033 ReadSourceLocation(F, Record, I).getRawEncoding());
3037 case SEMA_DECL_REFS:
3038 if (Record.size() != 3) {
3039 Error("Invalid SEMA_DECL_REFS block");
3042 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3043 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3046 case PPD_ENTITIES_OFFSETS: {
3047 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3048 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3049 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
3051 unsigned LocalBasePreprocessedEntityID = Record[0];
3053 unsigned StartingID;
3054 if (!PP.getPreprocessingRecord())
3055 PP.createPreprocessingRecord();
3056 if (!PP.getPreprocessingRecord()->getExternalSource())
3057 PP.getPreprocessingRecord()->SetExternalSource(*this);
3059 = PP.getPreprocessingRecord()
3060 ->allocateLoadedEntities(F.NumPreprocessedEntities);
3061 F.BasePreprocessedEntityID = StartingID;
3063 if (F.NumPreprocessedEntities > 0) {
3064 // Introduce the global -> local mapping for preprocessed entities in
3066 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
3068 // Introduce the local -> global mapping for preprocessed entities in
3070 F.PreprocessedEntityRemap.insertOrReplace(
3071 std::make_pair(LocalBasePreprocessedEntityID,
3072 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3078 case DECL_UPDATE_OFFSETS: {
3079 if (Record.size() % 2 != 0) {
3080 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
3083 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3084 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3085 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3087 // If we've already loaded the decl, perform the updates when we finish
3088 // loading this block.
3089 if (Decl *D = GetExistingDecl(ID))
3090 PendingUpdateRecords.push_back(
3091 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3096 case OBJC_CATEGORIES_MAP: {
3097 if (F.LocalNumObjCCategoriesInMap != 0) {
3098 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
3102 F.LocalNumObjCCategoriesInMap = Record[0];
3103 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
3107 case OBJC_CATEGORIES:
3108 F.ObjCCategories.swap(Record);
3111 case CUDA_SPECIAL_DECL_REFS:
3112 // Later tables overwrite earlier ones.
3113 // FIXME: Modules will have trouble with this.
3114 CUDASpecialDeclRefs.clear();
3115 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3116 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3119 case HEADER_SEARCH_TABLE: {
3120 F.HeaderFileInfoTableData = Blob.data();
3121 F.LocalNumHeaderFileInfos = Record[1];
3123 F.HeaderFileInfoTable
3124 = HeaderFileInfoLookupTable::Create(
3125 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3126 (const unsigned char *)F.HeaderFileInfoTableData,
3127 HeaderFileInfoTrait(*this, F,
3128 &PP.getHeaderSearchInfo(),
3129 Blob.data() + Record[2]));
3131 PP.getHeaderSearchInfo().SetExternalSource(this);
3132 if (!PP.getHeaderSearchInfo().getExternalLookup())
3133 PP.getHeaderSearchInfo().SetExternalLookup(this);
3138 case FP_PRAGMA_OPTIONS:
3139 // Later tables overwrite earlier ones.
3140 FPPragmaOptions.swap(Record);
3143 case OPENCL_EXTENSIONS:
3144 for (unsigned I = 0, E = Record.size(); I != E; ) {
3145 auto Name = ReadString(Record, I);
3146 auto &Opt = OpenCLExtensions.OptMap[Name];
3147 Opt.Supported = Record[I++] != 0;
3148 Opt.Enabled = Record[I++] != 0;
3149 Opt.Avail = Record[I++];
3150 Opt.Core = Record[I++];
3154 case OPENCL_EXTENSION_TYPES:
3155 for (unsigned I = 0, E = Record.size(); I != E;) {
3156 auto TypeID = static_cast<::TypeID>(Record[I++]);
3157 auto *Type = GetType(TypeID).getTypePtr();
3158 auto NumExt = static_cast<unsigned>(Record[I++]);
3159 for (unsigned II = 0; II != NumExt; ++II) {
3160 auto Ext = ReadString(Record, I);
3161 OpenCLTypeExtMap[Type].insert(Ext);
3166 case OPENCL_EXTENSION_DECLS:
3167 for (unsigned I = 0, E = Record.size(); I != E;) {
3168 auto DeclID = static_cast<::DeclID>(Record[I++]);
3169 auto *Decl = GetDecl(DeclID);
3170 auto NumExt = static_cast<unsigned>(Record[I++]);
3171 for (unsigned II = 0; II != NumExt; ++II) {
3172 auto Ext = ReadString(Record, I);
3173 OpenCLDeclExtMap[Decl].insert(Ext);
3178 case TENTATIVE_DEFINITIONS:
3179 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3180 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3183 case KNOWN_NAMESPACES:
3184 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3185 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3188 case UNDEFINED_BUT_USED:
3189 if (UndefinedButUsed.size() % 2 != 0) {
3190 Error("Invalid existing UndefinedButUsed");
3194 if (Record.size() % 2 != 0) {
3195 Error("invalid undefined-but-used record");
3198 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3199 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3200 UndefinedButUsed.push_back(
3201 ReadSourceLocation(F, Record, I).getRawEncoding());
3204 case DELETE_EXPRS_TO_ANALYZE:
3205 for (unsigned I = 0, N = Record.size(); I != N;) {
3206 DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
3207 const uint64_t Count = Record[I++];
3208 DelayedDeleteExprs.push_back(Count);
3209 for (uint64_t C = 0; C < Count; ++C) {
3210 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3211 bool IsArrayForm = Record[I++] == 1;
3212 DelayedDeleteExprs.push_back(IsArrayForm);
3217 case IMPORTED_MODULES: {
3218 if (!F.isModule()) {
3219 // If we aren't loading a module (which has its own exports), make
3220 // all of the imported modules visible.
3221 // FIXME: Deal with macros-only imports.
3222 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3223 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3224 SourceLocation Loc = ReadSourceLocation(F, Record, I);
3226 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
3227 if (DeserializationListener)
3228 DeserializationListener->ModuleImportRead(GlobalID, Loc);
3235 case MACRO_OFFSET: {
3236 if (F.LocalNumMacros != 0) {
3237 Error("duplicate MACRO_OFFSET record in AST file");
3240 F.MacroOffsets = (const uint32_t *)Blob.data();
3241 F.LocalNumMacros = Record[0];
3242 unsigned LocalBaseMacroID = Record[1];
3243 F.BaseMacroID = getTotalNumMacros();
3245 if (F.LocalNumMacros > 0) {
3246 // Introduce the global -> local mapping for macros within this module.
3247 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3249 // Introduce the local -> global mapping for macros within this module.
3250 F.MacroRemap.insertOrReplace(
3251 std::make_pair(LocalBaseMacroID,
3252 F.BaseMacroID - LocalBaseMacroID));
3254 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
3259 case LATE_PARSED_TEMPLATE: {
3260 LateParsedTemplates.append(Record.begin(), Record.end());
3264 case OPTIMIZE_PRAGMA_OPTIONS:
3265 if (Record.size() != 1) {
3266 Error("invalid pragma optimize record");
3269 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3272 case MSSTRUCT_PRAGMA_OPTIONS:
3273 if (Record.size() != 1) {
3274 Error("invalid pragma ms_struct record");
3277 PragmaMSStructState = Record[0];
3280 case POINTERS_TO_MEMBERS_PRAGMA_OPTIONS:
3281 if (Record.size() != 2) {
3282 Error("invalid pragma ms_struct record");
3285 PragmaMSPointersToMembersState = Record[0];
3286 PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]);
3289 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3290 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3291 UnusedLocalTypedefNameCandidates.push_back(
3292 getGlobalDeclID(F, Record[I]));
3295 case CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH:
3296 if (Record.size() != 1) {
3297 Error("invalid cuda pragma options record");
3300 ForceCUDAHostDeviceDepth = Record[0];
3303 case PACK_PRAGMA_OPTIONS: {
3304 if (Record.size() < 3) {
3305 Error("invalid pragma pack record");
3308 PragmaPackCurrentValue = Record[0];
3309 PragmaPackCurrentLocation = ReadSourceLocation(F, Record[1]);
3310 unsigned NumStackEntries = Record[2];
3312 // Reset the stack when importing a new module.
3313 PragmaPackStack.clear();
3314 for (unsigned I = 0; I < NumStackEntries; ++I) {
3315 PragmaPackStackEntry Entry;
3316 Entry.Value = Record[Idx++];
3317 Entry.Location = ReadSourceLocation(F, Record[Idx++]);
3318 PragmaPackStrings.push_back(ReadString(Record, Idx));
3319 Entry.SlotLabel = PragmaPackStrings.back();
3320 PragmaPackStack.push_back(Entry);
3328 void ASTReader::ReadModuleOffsetMap(ModuleFile &F) const {
3329 assert(!F.ModuleOffsetMap.empty() && "no module offset map to read");
3331 // Additional remapping information.
3332 const unsigned char *Data = (const unsigned char*)F.ModuleOffsetMap.data();
3333 const unsigned char *DataEnd = Data + F.ModuleOffsetMap.size();
3334 F.ModuleOffsetMap = StringRef();
3336 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
3337 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
3338 F.SLocRemap.insert(std::make_pair(0U, 0));
3339 F.SLocRemap.insert(std::make_pair(2U, 1));
3342 // Continuous range maps we may be updating in our module.
3343 typedef ContinuousRangeMap<uint32_t, int, 2>::Builder
3345 RemapBuilder SLocRemap(F.SLocRemap);
3346 RemapBuilder IdentifierRemap(F.IdentifierRemap);
3347 RemapBuilder MacroRemap(F.MacroRemap);
3348 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
3349 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
3350 RemapBuilder SelectorRemap(F.SelectorRemap);
3351 RemapBuilder DeclRemap(F.DeclRemap);
3352 RemapBuilder TypeRemap(F.TypeRemap);
3354 while (Data < DataEnd) {
3355 // FIXME: Looking up dependency modules by filename is horrible.
3356 using namespace llvm::support;
3357 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
3358 StringRef Name = StringRef((const char*)Data, Len);
3360 ModuleFile *OM = ModuleMgr.lookup(Name);
3363 "SourceLocation remap refers to unknown module, cannot find ";
3369 uint32_t SLocOffset =
3370 endian::readNext<uint32_t, little, unaligned>(Data);
3371 uint32_t IdentifierIDOffset =
3372 endian::readNext<uint32_t, little, unaligned>(Data);
3373 uint32_t MacroIDOffset =
3374 endian::readNext<uint32_t, little, unaligned>(Data);
3375 uint32_t PreprocessedEntityIDOffset =
3376 endian::readNext<uint32_t, little, unaligned>(Data);
3377 uint32_t SubmoduleIDOffset =
3378 endian::readNext<uint32_t, little, unaligned>(Data);
3379 uint32_t SelectorIDOffset =
3380 endian::readNext<uint32_t, little, unaligned>(Data);
3381 uint32_t DeclIDOffset =
3382 endian::readNext<uint32_t, little, unaligned>(Data);
3383 uint32_t TypeIndexOffset =
3384 endian::readNext<uint32_t, little, unaligned>(Data);
3386 uint32_t None = std::numeric_limits<uint32_t>::max();
3388 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
3389 RemapBuilder &Remap) {
3391 Remap.insert(std::make_pair(Offset,
3392 static_cast<int>(BaseOffset - Offset)));
3394 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
3395 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
3396 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
3397 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
3398 PreprocessedEntityRemap);
3399 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
3400 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
3401 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
3402 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
3404 // Global -> local mappings.
3405 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
3409 ASTReader::ASTReadResult
3410 ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3411 const ModuleFile *ImportedBy,
3412 unsigned ClientLoadCapabilities) {
3414 F.ModuleMapPath = ReadPath(F, Record, Idx);
3416 if (F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule) {
3417 // For an explicitly-loaded module, we don't care whether the original
3418 // module map file exists or matches.
3422 // Try to resolve ModuleName in the current header search context and
3423 // verify that it is found in the same module map file as we saved. If the
3424 // top-level AST file is a main file, skip this check because there is no
3425 // usable header search context.
3426 assert(!F.ModuleName.empty() &&
3427 "MODULE_NAME should come before MODULE_MAP_FILE");
3428 if (F.Kind == MK_ImplicitModule && ModuleMgr.begin()->Kind != MK_MainFile) {
3429 // An implicitly-loaded module file should have its module listed in some
3430 // module map file that we've already loaded.
3431 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
3432 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3433 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3435 assert(ImportedBy && "top-level import should be verified");
3436 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) {
3437 if (auto *ASTFE = M ? M->getASTFile() : nullptr)
3438 // This module was defined by an imported (explicit) module.
3439 Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
3440 << ASTFE->getName();
3442 // This module was built with a different module map.
3443 Diag(diag::err_imported_module_not_found)
3444 << F.ModuleName << F.FileName << ImportedBy->FileName
3450 assert(M->Name == F.ModuleName && "found module with different name");
3452 // Check the primary module map file.
3453 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
3454 if (StoredModMap == nullptr || StoredModMap != ModMap) {
3455 assert(ModMap && "found module is missing module map file");
3456 assert(ImportedBy && "top-level import should be verified");
3457 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3458 Diag(diag::err_imported_module_modmap_changed)
3459 << F.ModuleName << ImportedBy->FileName
3460 << ModMap->getName() << F.ModuleMapPath;
3464 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3465 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3466 // FIXME: we should use input files rather than storing names.
3467 std::string Filename = ReadPath(F, Record, Idx);
3468 const FileEntry *F =
3469 FileMgr.getFile(Filename, false, false);
3471 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3472 Error("could not find file '" + Filename +"' referenced by AST file");
3475 AdditionalStoredMaps.insert(F);
3478 // Check any additional module map files (e.g. module.private.modulemap)
3479 // that are not in the pcm.
3480 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
3481 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
3482 // Remove files that match
3483 // Note: SmallPtrSet::erase is really remove
3484 if (!AdditionalStoredMaps.erase(ModMap)) {
3485 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3486 Diag(diag::err_module_different_modmap)
3487 << F.ModuleName << /*new*/0 << ModMap->getName();
3493 // Check any additional module map files that are in the pcm, but not
3494 // found in header search. Cases that match are already removed.
3495 for (const FileEntry *ModMap : AdditionalStoredMaps) {
3496 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3497 Diag(diag::err_module_different_modmap)
3498 << F.ModuleName << /*not new*/1 << ModMap->getName();
3504 Listener->ReadModuleMapFile(F.ModuleMapPath);
3509 /// \brief Move the given method to the back of the global list of methods.
3510 static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3511 // Find the entry for this selector in the method pool.
3512 Sema::GlobalMethodPool::iterator Known
3513 = S.MethodPool.find(Method->getSelector());
3514 if (Known == S.MethodPool.end())
3517 // Retrieve the appropriate method list.
3518 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3519 : Known->second.second;
3521 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
3523 if (List->getMethod() == Method) {
3531 if (List->getNext())
3532 List->setMethod(List->getNext()->getMethod());
3534 List->setMethod(Method);
3538 void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
3539 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
3540 for (Decl *D : Names) {
3541 bool wasHidden = D->Hidden;
3544 if (wasHidden && SemaObj) {
3545 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3546 moveMethodToBackOfGlobalList(*SemaObj, Method);
3552 void ASTReader::makeModuleVisible(Module *Mod,
3553 Module::NameVisibilityKind NameVisibility,
3554 SourceLocation ImportLoc) {
3555 llvm::SmallPtrSet<Module *, 4> Visited;
3556 SmallVector<Module *, 4> Stack;
3557 Stack.push_back(Mod);
3558 while (!Stack.empty()) {
3559 Mod = Stack.pop_back_val();
3561 if (NameVisibility <= Mod->NameVisibility) {
3562 // This module already has this level of visibility (or greater), so
3563 // there is nothing more to do.
3567 if (!Mod->isAvailable()) {
3568 // Modules that aren't available cannot be made visible.
3572 // Update the module's name visibility.
3573 Mod->NameVisibility = NameVisibility;
3575 // If we've already deserialized any names from this module,
3576 // mark them as visible.
3577 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3578 if (Hidden != HiddenNamesMap.end()) {
3579 auto HiddenNames = std::move(*Hidden);
3580 HiddenNamesMap.erase(Hidden);
3581 makeNamesVisible(HiddenNames.second, HiddenNames.first);
3582 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3583 "making names visible added hidden names");
3586 // Push any exported modules onto the stack to be marked as visible.
3587 SmallVector<Module *, 16> Exports;
3588 Mod->getExportedModules(Exports);
3589 for (SmallVectorImpl<Module *>::iterator
3590 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3591 Module *Exported = *I;
3592 if (Visited.insert(Exported).second)
3593 Stack.push_back(Exported);
3598 /// We've merged the definition \p MergedDef into the existing definition
3599 /// \p Def. Ensure that \p Def is made visible whenever \p MergedDef is made
3601 void ASTReader::mergeDefinitionVisibility(NamedDecl *Def,
3602 NamedDecl *MergedDef) {
3603 // FIXME: This doesn't correctly handle the case where MergedDef is visible
3604 // in modules other than its owning module. We should instead give the
3605 // ASTContext a list of merged definitions for Def.
3606 if (Def->isHidden()) {
3607 // If MergedDef is visible or becomes visible, make the definition visible.
3608 if (!MergedDef->isHidden())
3609 Def->Hidden = false;
3610 else if (getContext().getLangOpts().ModulesLocalVisibility) {
3611 getContext().mergeDefinitionIntoModule(
3612 Def, MergedDef->getImportedOwningModule(),
3613 /*NotifyListeners*/ false);
3614 PendingMergedDefinitionsToDeduplicate.insert(Def);
3616 auto SubmoduleID = MergedDef->getOwningModuleID();
3617 assert(SubmoduleID && "hidden definition in no module");
3618 HiddenNamesMap[getSubmodule(SubmoduleID)].push_back(Def);
3623 bool ASTReader::loadGlobalIndex() {
3627 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3628 !Context.getLangOpts().Modules)
3631 // Try to load the global index.
3632 TriedLoadingGlobalIndex = true;
3633 StringRef ModuleCachePath
3634 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3635 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
3636 = GlobalModuleIndex::readIndex(ModuleCachePath);
3640 GlobalIndex.reset(Result.first);
3641 ModuleMgr.setGlobalIndex(GlobalIndex.get());
3645 bool ASTReader::isGlobalIndexUnavailable() const {
3646 return Context.getLangOpts().Modules && UseGlobalIndex &&
3647 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3650 static void updateModuleTimestamp(ModuleFile &MF) {
3651 // Overwrite the timestamp file contents so that file's mtime changes.
3652 std::string TimestampFilename = MF.getTimestampFilename();
3654 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3657 OS << "Timestamp file\n";
3660 /// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3661 /// cursor into the start of the given block ID, returning false on success and
3662 /// true on failure.
3663 static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
3665 llvm::BitstreamEntry Entry = Cursor.advance();
3666 switch (Entry.Kind) {
3667 case llvm::BitstreamEntry::Error:
3668 case llvm::BitstreamEntry::EndBlock:
3671 case llvm::BitstreamEntry::Record:
3672 // Ignore top-level records.
3673 Cursor.skipRecord(Entry.ID);
3676 case llvm::BitstreamEntry::SubBlock:
3677 if (Entry.ID == BlockID) {
3678 if (Cursor.EnterSubBlock(BlockID))
3684 if (Cursor.SkipBlock())
3690 ASTReader::ASTReadResult ASTReader::ReadAST(StringRef FileName,
3692 SourceLocation ImportLoc,
3693 unsigned ClientLoadCapabilities,
3694 SmallVectorImpl<ImportedSubmodule> *Imported) {
3695 llvm::SaveAndRestore<SourceLocation>
3696 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3698 // Defer any pending actions until we get to the end of reading the AST file.
3699 Deserializing AnASTFile(this);
3701 // Bump the generation number.
3702 unsigned PreviousGeneration = incrementGeneration(Context);
3704 unsigned NumModules = ModuleMgr.size();
3705 SmallVector<ImportedModule, 4> Loaded;
3706 switch (ASTReadResult ReadResult =
3707 ReadASTCore(FileName, Type, ImportLoc,
3708 /*ImportedBy=*/nullptr, Loaded, 0, 0,
3709 ASTFileSignature(), ClientLoadCapabilities)) {
3713 case VersionMismatch:
3714 case ConfigurationMismatch:
3716 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3717 for (const ImportedModule &IM : Loaded)
3718 LoadedSet.insert(IM.Mod);
3720 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, LoadedSet,
3721 Context.getLangOpts().Modules
3722 ? &PP.getHeaderSearchInfo().getModuleMap()
3725 // If we find that any modules are unusable, the global index is going
3726 // to be out-of-date. Just remove it.
3727 GlobalIndex.reset();
3728 ModuleMgr.setGlobalIndex(nullptr);
3735 // Here comes stuff that we only do once the entire chain is loaded.
3737 // Load the AST blocks of all of the modules that we loaded.
3738 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3739 MEnd = Loaded.end();
3741 ModuleFile &F = *M->Mod;
3743 // Read the AST block.
3744 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3747 // Read the extension blocks.
3748 while (!SkipCursorToBlock(F.Stream, EXTENSION_BLOCK_ID)) {
3749 if (ASTReadResult Result = ReadExtensionBlock(F))
3753 // Once read, set the ModuleFile bit base offset and update the size in
3754 // bits of all files we've seen.
3755 F.GlobalBitOffset = TotalModulesSizeInBits;
3756 TotalModulesSizeInBits += F.SizeInBits;
3757 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3759 // Preload SLocEntries.
3760 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3761 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3762 // Load it through the SourceManager and don't call ReadSLocEntry()
3763 // directly because the entry may have already been loaded in which case
3764 // calling ReadSLocEntry() directly would trigger an assertion in
3766 SourceMgr.getLoadedSLocEntryByID(Index);
3769 // Map the original source file ID into the ID space of the current
3771 if (F.OriginalSourceFileID.isValid()) {
3772 F.OriginalSourceFileID = FileID::get(
3773 F.SLocEntryBaseID + F.OriginalSourceFileID.getOpaqueValue() - 1);
3776 // Preload all the pending interesting identifiers by marking them out of
3778 for (auto Offset : F.PreloadIdentifierOffsets) {
3779 const unsigned char *Data = reinterpret_cast<const unsigned char *>(
3780 F.IdentifierTableData + Offset);
3782 ASTIdentifierLookupTrait Trait(*this, F);
3783 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
3784 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
3785 auto &II = PP.getIdentifierTable().getOwn(Key);
3786 II.setOutOfDate(true);
3788 // Mark this identifier as being from an AST file so that we can track
3789 // whether we need to serialize it.
3790 markIdentifierFromAST(*this, II);
3792 // Associate the ID with the identifier so that the writer can reuse it.
3793 auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
3794 SetIdentifierInfo(ID, &II);
3798 // Setup the import locations and notify the module manager that we've
3799 // committed to these module files.
3800 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3801 MEnd = Loaded.end();
3803 ModuleFile &F = *M->Mod;
3805 ModuleMgr.moduleFileAccepted(&F);
3807 // Set the import location.
3808 F.DirectImportLoc = ImportLoc;
3809 // FIXME: We assume that locations from PCH / preamble do not need
3812 F.ImportLoc = M->ImportLoc;
3814 F.ImportLoc = TranslateSourceLocation(*M->ImportedBy, M->ImportLoc);
3817 if (!Context.getLangOpts().CPlusPlus ||
3818 (Type != MK_ImplicitModule && Type != MK_ExplicitModule &&
3819 Type != MK_PrebuiltModule)) {
3820 // Mark all of the identifiers in the identifier table as being out of date,
3821 // so that various accessors know to check the loaded modules when the
3822 // identifier is used.
3824 // For C++ modules, we don't need information on many identifiers (just
3825 // those that provide macros or are poisoned), so we mark all of
3826 // the interesting ones via PreloadIdentifierOffsets.
3827 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3828 IdEnd = PP.getIdentifierTable().end();
3830 Id->second->setOutOfDate(true);
3832 // Mark selectors as out of date.
3833 for (auto Sel : SelectorGeneration)
3834 SelectorOutOfDate[Sel.first] = true;
3836 // Resolve any unresolved module exports.
3837 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3838 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
3839 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3840 Module *ResolvedMod = getSubmodule(GlobalID);
3842 switch (Unresolved.Kind) {
3843 case UnresolvedModuleRef::Conflict:
3845 Module::Conflict Conflict;
3846 Conflict.Other = ResolvedMod;
3847 Conflict.Message = Unresolved.String.str();
3848 Unresolved.Mod->Conflicts.push_back(Conflict);
3852 case UnresolvedModuleRef::Import:
3854 Unresolved.Mod->Imports.insert(ResolvedMod);
3857 case UnresolvedModuleRef::Export:
3858 if (ResolvedMod || Unresolved.IsWildcard)
3859 Unresolved.Mod->Exports.push_back(
3860 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3864 UnresolvedModuleRefs.clear();
3867 Imported->append(ImportedModules.begin(),
3868 ImportedModules.end());
3870 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3871 // Might be unnecessary as use declarations are only used to build the
3874 InitializeContext();
3879 if (DeserializationListener)
3880 DeserializationListener->ReaderInitialized(this);
3882 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
3883 if (PrimaryModule.OriginalSourceFileID.isValid()) {
3884 // If this AST file is a precompiled preamble, then set the
3885 // preamble file ID of the source manager to the file source file
3886 // from which the preamble was built.
3887 if (Type == MK_Preamble) {
3888 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3889 } else if (Type == MK_MainFile) {
3890 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3894 // For any Objective-C class definitions we have already loaded, make sure
3895 // that we load any additional categories.
3896 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3897 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3898 ObjCClassesLoaded[I],
3899 PreviousGeneration);
3902 if (PP.getHeaderSearchInfo()
3903 .getHeaderSearchOpts()
3904 .ModulesValidateOncePerBuildSession) {
3905 // Now we are certain that the module and all modules it depends on are
3906 // up to date. Create or update timestamp files for modules that are
3907 // located in the module cache (not for PCH files that could be anywhere
3908 // in the filesystem).
3909 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3910 ImportedModule &M = Loaded[I];
3911 if (M.Mod->Kind == MK_ImplicitModule) {
3912 updateModuleTimestamp(*M.Mod);
3920 static ASTFileSignature readASTFileSignature(StringRef PCH);
3922 /// \brief Whether \p Stream starts with the AST/PCH file magic number 'CPCH'.
3923 static bool startsWithASTFileMagic(BitstreamCursor &Stream) {
3924 return Stream.canSkipToPos(4) &&
3925 Stream.Read(8) == 'C' &&
3926 Stream.Read(8) == 'P' &&
3927 Stream.Read(8) == 'C' &&
3928 Stream.Read(8) == 'H';
3931 static unsigned moduleKindForDiagnostic(ModuleKind Kind) {
3935 case MK_ImplicitModule:
3936 case MK_ExplicitModule:
3937 case MK_PrebuiltModule:
3941 return 2; // main source file
3943 llvm_unreachable("unknown module kind");
3946 ASTReader::ASTReadResult
3947 ASTReader::ReadASTCore(StringRef FileName,
3949 SourceLocation ImportLoc,
3950 ModuleFile *ImportedBy,
3951 SmallVectorImpl<ImportedModule> &Loaded,
3952 off_t ExpectedSize, time_t ExpectedModTime,
3953 ASTFileSignature ExpectedSignature,
3954 unsigned ClientLoadCapabilities) {
3956 std::string ErrorStr;
3957 ModuleManager::AddModuleResult AddResult
3958 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
3959 getGeneration(), ExpectedSize, ExpectedModTime,
3960 ExpectedSignature, readASTFileSignature,
3963 switch (AddResult) {
3964 case ModuleManager::AlreadyLoaded:
3967 case ModuleManager::NewlyLoaded:
3968 // Load module file below.
3971 case ModuleManager::Missing:
3972 // The module file was missing; if the client can handle that, return
3974 if (ClientLoadCapabilities & ARR_Missing)
3977 // Otherwise, return an error.
3978 Diag(diag::err_module_file_not_found) << moduleKindForDiagnostic(Type)
3979 << FileName << !ErrorStr.empty()
3983 case ModuleManager::OutOfDate:
3984 // We couldn't load the module file because it is out-of-date. If the
3985 // client can handle out-of-date, return it.
3986 if (ClientLoadCapabilities & ARR_OutOfDate)
3989 // Otherwise, return an error.
3990 Diag(diag::err_module_file_out_of_date) << moduleKindForDiagnostic(Type)
3991 << FileName << !ErrorStr.empty()
3996 assert(M && "Missing module file");
3998 // FIXME: This seems rather a hack. Should CurrentDir be part of the
4000 if (FileName != "-") {
4001 CurrentDir = llvm::sys::path::parent_path(FileName);
4002 if (CurrentDir.empty()) CurrentDir = ".";
4006 BitstreamCursor &Stream = F.Stream;
4007 Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(*F.Buffer));
4008 F.SizeInBits = F.Buffer->getBufferSize() * 8;
4010 // Sniff for the signature.
4011 if (!startsWithASTFileMagic(Stream)) {
4012 Diag(diag::err_module_file_invalid) << moduleKindForDiagnostic(Type)
4017 // This is used for compatibility with older PCH formats.
4018 bool HaveReadControlBlock = false;
4020 llvm::BitstreamEntry Entry = Stream.advance();
4022 switch (Entry.Kind) {
4023 case llvm::BitstreamEntry::Error:
4024 case llvm::BitstreamEntry::Record:
4025 case llvm::BitstreamEntry::EndBlock:
4026 Error("invalid record at top-level of AST file");
4029 case llvm::BitstreamEntry::SubBlock:
4034 case CONTROL_BLOCK_ID:
4035 HaveReadControlBlock = true;
4036 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
4038 // Check that we didn't try to load a non-module AST file as a module.
4040 // FIXME: Should we also perform the converse check? Loading a module as
4041 // a PCH file sort of works, but it's a bit wonky.
4042 if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule ||
4043 Type == MK_PrebuiltModule) &&
4044 F.ModuleName.empty()) {
4045 auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
4046 if (Result != OutOfDate ||
4047 (ClientLoadCapabilities & ARR_OutOfDate) == 0)
4048 Diag(diag::err_module_file_not_module) << FileName;
4053 case Failure: return Failure;
4054 case Missing: return Missing;
4055 case OutOfDate: return OutOfDate;
4056 case VersionMismatch: return VersionMismatch;
4057 case ConfigurationMismatch: return ConfigurationMismatch;
4058 case HadErrors: return HadErrors;
4063 if (!HaveReadControlBlock) {
4064 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
4065 Diag(diag::err_pch_version_too_old);
4066 return VersionMismatch;
4069 // Record that we've loaded this module.
4070 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
4073 case UNHASHED_CONTROL_BLOCK_ID:
4074 // This block is handled using look-ahead during ReadControlBlock. We
4075 // shouldn't get here!
4076 Error("malformed block record in AST file");
4080 if (Stream.SkipBlock()) {
4081 Error("malformed block record in AST file");
4091 ASTReader::ASTReadResult
4092 ASTReader::readUnhashedControlBlock(ModuleFile &F, bool WasImportedBy,
4093 unsigned ClientLoadCapabilities) {
4094 const HeaderSearchOptions &HSOpts =
4095 PP.getHeaderSearchInfo().getHeaderSearchOpts();
4096 bool AllowCompatibleConfigurationMismatch =
4097 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
4099 ASTReadResult Result = readUnhashedControlBlockImpl(
4100 &F, F.Data, ClientLoadCapabilities, AllowCompatibleConfigurationMismatch,
4102 WasImportedBy ? false : HSOpts.ModulesValidateDiagnosticOptions);
4104 // If F was directly imported by another module, it's implicitly validated by
4105 // the importing module.
4106 if (DisableValidation || WasImportedBy ||
4107 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
4110 if (Result == Failure) {
4111 Error("malformed block record in AST file");
4115 if (Result == OutOfDate && F.Kind == MK_ImplicitModule) {
4116 // If this module has already been finalized in the PCMCache, we're stuck
4117 // with it; we can only load a single version of each module.
4119 // This can happen when a module is imported in two contexts: in one, as a
4120 // user module; in another, as a system module (due to an import from
4121 // another module marked with the [system] flag). It usually indicates a
4122 // bug in the module map: this module should also be marked with [system].
4124 // If -Wno-system-headers (the default), and the first import is as a
4125 // system module, then validation will fail during the as-user import,
4126 // since -Werror flags won't have been validated. However, it's reasonable
4127 // to treat this consistently as a system module.
4129 // If -Wsystem-headers, the PCM on disk was built with
4130 // -Wno-system-headers, and the first import is as a user module, then
4131 // validation will fail during the as-system import since the PCM on disk
4132 // doesn't guarantee that -Werror was respected. However, the -Werror
4133 // flags were checked during the initial as-user import.
4134 if (PCMCache.isBufferFinal(F.FileName)) {
4135 Diag(diag::warn_module_system_bit_conflict) << F.FileName;
4143 ASTReader::ASTReadResult ASTReader::readUnhashedControlBlockImpl(
4144 ModuleFile *F, llvm::StringRef StreamData, unsigned ClientLoadCapabilities,
4145 bool AllowCompatibleConfigurationMismatch, ASTReaderListener *Listener,
4146 bool ValidateDiagnosticOptions) {
4147 // Initialize a stream.
4148 BitstreamCursor Stream(StreamData);
4150 // Sniff for the signature.
4151 if (!startsWithASTFileMagic(Stream))
4154 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4155 if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
4158 // Read all of the records in the options block.
4160 ASTReadResult Result = Success;
4162 llvm::BitstreamEntry Entry = Stream.advance();
4164 switch (Entry.Kind) {
4165 case llvm::BitstreamEntry::Error:
4166 case llvm::BitstreamEntry::SubBlock:
4169 case llvm::BitstreamEntry::EndBlock:
4172 case llvm::BitstreamEntry::Record:
4173 // The interesting case.
4177 // Read and process a record.
4180 (UnhashedControlBlockRecordTypes)Stream.readRecord(Entry.ID, Record)) {
4183 std::copy(Record.begin(), Record.end(), F->Signature.data());
4186 case DIAGNOSTIC_OPTIONS: {
4187 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
4188 if (Listener && ValidateDiagnosticOptions &&
4189 !AllowCompatibleConfigurationMismatch &&
4190 ParseDiagnosticOptions(Record, Complain, *Listener))
4191 Result = OutOfDate; // Don't return early. Read the signature.
4194 case DIAG_PRAGMA_MAPPINGS:
4197 if (F->PragmaDiagMappings.empty())
4198 F->PragmaDiagMappings.swap(Record);
4200 F->PragmaDiagMappings.insert(F->PragmaDiagMappings.end(),
4201 Record.begin(), Record.end());
4207 /// Parse a record and blob containing module file extension metadata.
4208 static bool parseModuleFileExtensionMetadata(
4209 const SmallVectorImpl<uint64_t> &Record,
4211 ModuleFileExtensionMetadata &Metadata) {
4212 if (Record.size() < 4) return true;
4214 Metadata.MajorVersion = Record[0];
4215 Metadata.MinorVersion = Record[1];
4217 unsigned BlockNameLen = Record[2];
4218 unsigned UserInfoLen = Record[3];
4220 if (BlockNameLen + UserInfoLen > Blob.size()) return true;
4222 Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
4223 Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,
4224 Blob.data() + BlockNameLen + UserInfoLen);
4228 ASTReader::ASTReadResult ASTReader::ReadExtensionBlock(ModuleFile &F) {
4229 BitstreamCursor &Stream = F.Stream;
4233 llvm::BitstreamEntry Entry = Stream.advance();
4234 switch (Entry.Kind) {
4235 case llvm::BitstreamEntry::SubBlock:
4236 if (Stream.SkipBlock())
4241 case llvm::BitstreamEntry::EndBlock:
4244 case llvm::BitstreamEntry::Error:
4247 case llvm::BitstreamEntry::Record:
4253 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4255 case EXTENSION_METADATA: {
4256 ModuleFileExtensionMetadata Metadata;
4257 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
4260 // Find a module file extension with this block name.
4261 auto Known = ModuleFileExtensions.find(Metadata.BlockName);
4262 if (Known == ModuleFileExtensions.end()) break;
4265 if (auto Reader = Known->second->createExtensionReader(Metadata, *this,
4267 F.ExtensionReaders.push_back(std::move(Reader));
4278 void ASTReader::InitializeContext() {
4279 // If there's a listener, notify them that we "read" the translation unit.
4280 if (DeserializationListener)
4281 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
4282 Context.getTranslationUnitDecl());
4284 // FIXME: Find a better way to deal with collisions between these
4285 // built-in types. Right now, we just ignore the problem.
4287 // Load the special types.
4288 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
4289 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
4290 if (!Context.CFConstantStringTypeDecl)
4291 Context.setCFConstantStringType(GetType(String));
4294 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
4295 QualType FileType = GetType(File);
4296 if (FileType.isNull()) {
4297 Error("FILE type is NULL");
4301 if (!Context.FILEDecl) {
4302 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
4303 Context.setFILEDecl(Typedef->getDecl());
4305 const TagType *Tag = FileType->getAs<TagType>();
4307 Error("Invalid FILE type in AST file");
4310 Context.setFILEDecl(Tag->getDecl());
4315 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
4316 QualType Jmp_bufType = GetType(Jmp_buf);
4317 if (Jmp_bufType.isNull()) {
4318 Error("jmp_buf type is NULL");
4322 if (!Context.jmp_bufDecl) {
4323 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
4324 Context.setjmp_bufDecl(Typedef->getDecl());
4326 const TagType *Tag = Jmp_bufType->getAs<TagType>();
4328 Error("Invalid jmp_buf type in AST file");
4331 Context.setjmp_bufDecl(Tag->getDecl());
4336 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
4337 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
4338 if (Sigjmp_bufType.isNull()) {
4339 Error("sigjmp_buf type is NULL");
4343 if (!Context.sigjmp_bufDecl) {
4344 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
4345 Context.setsigjmp_bufDecl(Typedef->getDecl());
4347 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
4348 assert(Tag && "Invalid sigjmp_buf type in AST file");
4349 Context.setsigjmp_bufDecl(Tag->getDecl());
4354 if (unsigned ObjCIdRedef
4355 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
4356 if (Context.ObjCIdRedefinitionType.isNull())
4357 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
4360 if (unsigned ObjCClassRedef
4361 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
4362 if (Context.ObjCClassRedefinitionType.isNull())
4363 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
4366 if (unsigned ObjCSelRedef
4367 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
4368 if (Context.ObjCSelRedefinitionType.isNull())
4369 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
4372 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
4373 QualType Ucontext_tType = GetType(Ucontext_t);
4374 if (Ucontext_tType.isNull()) {
4375 Error("ucontext_t type is NULL");
4379 if (!Context.ucontext_tDecl) {
4380 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
4381 Context.setucontext_tDecl(Typedef->getDecl());
4383 const TagType *Tag = Ucontext_tType->getAs<TagType>();
4384 assert(Tag && "Invalid ucontext_t type in AST file");
4385 Context.setucontext_tDecl(Tag->getDecl());
4391 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
4393 // If there were any CUDA special declarations, deserialize them.
4394 if (!CUDASpecialDeclRefs.empty()) {
4395 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
4396 Context.setcudaConfigureCallDecl(
4397 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
4400 // Re-export any modules that were imported by a non-module AST file.
4401 // FIXME: This does not make macro-only imports visible again.
4402 for (auto &Import : ImportedModules) {
4403 if (Module *Imported = getSubmodule(Import.ID)) {
4404 makeModuleVisible(Imported, Module::AllVisible,
4405 /*ImportLoc=*/Import.ImportLoc);
4406 if (Import.ImportLoc.isValid())
4407 PP.makeModuleVisible(Imported, Import.ImportLoc);
4408 // FIXME: should we tell Sema to make the module visible too?
4411 ImportedModules.clear();
4414 void ASTReader::finalizeForWriting() {
4415 // Nothing to do for now.
4418 /// \brief Reads and return the signature record from \p PCH's control block, or
4420 static ASTFileSignature readASTFileSignature(StringRef PCH) {
4421 BitstreamCursor Stream(PCH);
4422 if (!startsWithASTFileMagic(Stream))
4423 return ASTFileSignature();
4425 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4426 if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
4427 return ASTFileSignature();
4429 // Scan for SIGNATURE inside the diagnostic options block.
4430 ASTReader::RecordData Record;
4432 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4433 if (Entry.Kind != llvm::BitstreamEntry::Record)
4434 return ASTFileSignature();
4438 if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
4439 return {{{(uint32_t)Record[0], (uint32_t)Record[1], (uint32_t)Record[2],
4440 (uint32_t)Record[3], (uint32_t)Record[4]}}};
4444 /// \brief Retrieve the name of the original source file name
4445 /// directly from the AST file, without actually loading the AST
4447 std::string ASTReader::getOriginalSourceFile(
4448 const std::string &ASTFileName, FileManager &FileMgr,
4449 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
4450 // Open the AST file.
4451 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
4453 Diags.Report(diag::err_fe_unable_to_read_pch_file)
4454 << ASTFileName << Buffer.getError().message();
4455 return std::string();
4458 // Initialize the stream
4459 BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer));
4461 // Sniff for the signature.
4462 if (!startsWithASTFileMagic(Stream)) {
4463 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
4464 return std::string();
4467 // Scan for the CONTROL_BLOCK_ID block.
4468 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
4469 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4470 return std::string();
4473 // Scan for ORIGINAL_FILE inside the control block.
4476 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4477 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4478 return std::string();
4480 if (Entry.Kind != llvm::BitstreamEntry::Record) {
4481 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4482 return std::string();
4487 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
4494 class SimplePCHValidator : public ASTReaderListener {
4495 const LangOptions &ExistingLangOpts;
4496 const TargetOptions &ExistingTargetOpts;
4497 const PreprocessorOptions &ExistingPPOpts;
4498 std::string ExistingModuleCachePath;
4499 FileManager &FileMgr;
4502 SimplePCHValidator(const LangOptions &ExistingLangOpts,
4503 const TargetOptions &ExistingTargetOpts,
4504 const PreprocessorOptions &ExistingPPOpts,
4505 StringRef ExistingModuleCachePath,
4506 FileManager &FileMgr)
4507 : ExistingLangOpts(ExistingLangOpts),
4508 ExistingTargetOpts(ExistingTargetOpts),
4509 ExistingPPOpts(ExistingPPOpts),
4510 ExistingModuleCachePath(ExistingModuleCachePath),
4515 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
4516 bool AllowCompatibleDifferences) override {
4517 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
4518 AllowCompatibleDifferences);
4521 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
4522 bool AllowCompatibleDifferences) override {
4523 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
4524 AllowCompatibleDifferences);
4527 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
4528 StringRef SpecificModuleCachePath,
4529 bool Complain) override {
4530 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4531 ExistingModuleCachePath,
4532 nullptr, ExistingLangOpts);
4535 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
4537 std::string &SuggestedPredefines) override {
4538 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
4539 SuggestedPredefines, ExistingLangOpts);
4543 } // end anonymous namespace
4545 bool ASTReader::readASTFileControlBlock(
4546 StringRef Filename, FileManager &FileMgr,
4547 const PCHContainerReader &PCHContainerRdr,
4548 bool FindModuleFileExtensions,
4549 ASTReaderListener &Listener, bool ValidateDiagnosticOptions) {
4550 // Open the AST file.
4551 // FIXME: This allows use of the VFS; we do not allow use of the
4552 // VFS when actually loading a module.
4553 auto Buffer = FileMgr.getBufferForFile(Filename);
4558 // Initialize the stream
4559 StringRef Bytes = PCHContainerRdr.ExtractPCH(**Buffer);
4560 BitstreamCursor Stream(Bytes);
4562 // Sniff for the signature.
4563 if (!startsWithASTFileMagic(Stream))
4566 // Scan for the CONTROL_BLOCK_ID block.
4567 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
4570 bool NeedsInputFiles = Listener.needsInputFileVisitation();
4571 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
4572 bool NeedsImports = Listener.needsImportVisitation();
4573 BitstreamCursor InputFilesCursor;
4576 std::string ModuleDir;
4577 bool DoneWithControlBlock = false;
4578 while (!DoneWithControlBlock) {
4579 llvm::BitstreamEntry Entry = Stream.advance();
4581 switch (Entry.Kind) {
4582 case llvm::BitstreamEntry::SubBlock: {
4584 case OPTIONS_BLOCK_ID: {
4585 std::string IgnoredSuggestedPredefines;
4586 if (ReadOptionsBlock(Stream, ARR_ConfigurationMismatch | ARR_OutOfDate,
4587 /*AllowCompatibleConfigurationMismatch*/ false,
4588 Listener, IgnoredSuggestedPredefines) != Success)
4593 case INPUT_FILES_BLOCK_ID:
4594 InputFilesCursor = Stream;
4595 if (Stream.SkipBlock() ||
4597 ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID)))
4602 if (Stream.SkipBlock())
4610 case llvm::BitstreamEntry::EndBlock:
4611 DoneWithControlBlock = true;
4614 case llvm::BitstreamEntry::Error:
4617 case llvm::BitstreamEntry::Record:
4621 if (DoneWithControlBlock) break;
4625 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4626 switch ((ControlRecordTypes)RecCode) {
4628 if (Record[0] != VERSION_MAJOR)
4631 if (Listener.ReadFullVersionInformation(Blob))
4637 Listener.ReadModuleName(Blob);
4639 case MODULE_DIRECTORY:
4642 case MODULE_MAP_FILE: {
4644 auto Path = ReadString(Record, Idx);
4645 ResolveImportedPath(Path, ModuleDir);
4646 Listener.ReadModuleMapFile(Path);
4649 case INPUT_FILE_OFFSETS: {
4650 if (!NeedsInputFiles)
4653 unsigned NumInputFiles = Record[0];
4654 unsigned NumUserFiles = Record[1];
4655 const uint64_t *InputFileOffs = (const uint64_t *)Blob.data();
4656 for (unsigned I = 0; I != NumInputFiles; ++I) {
4657 // Go find this input file.
4658 bool isSystemFile = I >= NumUserFiles;
4660 if (isSystemFile && !NeedsSystemInputFiles)
4661 break; // the rest are system input files
4663 BitstreamCursor &Cursor = InputFilesCursor;
4664 SavedStreamPosition SavedPosition(Cursor);
4665 Cursor.JumpToBit(InputFileOffs[I]);
4667 unsigned Code = Cursor.ReadCode();
4670 bool shouldContinue = false;
4671 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4673 bool Overridden = static_cast<bool>(Record[3]);
4674 std::string Filename = Blob;
4675 ResolveImportedPath(Filename, ModuleDir);
4676 shouldContinue = Listener.visitInputFile(
4677 Filename, isSystemFile, Overridden, /*IsExplicitModule*/false);
4680 if (!shouldContinue)
4690 unsigned Idx = 0, N = Record.size();
4692 // Read information about the AST file.
4693 Idx += 5; // ImportLoc, Size, ModTime, Signature
4694 std::string Filename = ReadString(Record, Idx);
4695 ResolveImportedPath(Filename, ModuleDir);
4696 Listener.visitImport(Filename);
4702 // No other validation to perform.
4707 // Look for module file extension blocks, if requested.
4708 if (FindModuleFileExtensions) {
4709 BitstreamCursor SavedStream = Stream;
4710 while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {
4711 bool DoneWithExtensionBlock = false;
4712 while (!DoneWithExtensionBlock) {
4713 llvm::BitstreamEntry Entry = Stream.advance();
4715 switch (Entry.Kind) {
4716 case llvm::BitstreamEntry::SubBlock:
4717 if (Stream.SkipBlock())
4722 case llvm::BitstreamEntry::EndBlock:
4723 DoneWithExtensionBlock = true;
4726 case llvm::BitstreamEntry::Error:
4729 case llvm::BitstreamEntry::Record:
4735 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4737 case EXTENSION_METADATA: {
4738 ModuleFileExtensionMetadata Metadata;
4739 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
4742 Listener.readModuleFileExtension(Metadata);
4748 Stream = SavedStream;
4751 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4752 if (readUnhashedControlBlockImpl(
4753 nullptr, Bytes, ARR_ConfigurationMismatch | ARR_OutOfDate,
4754 /*AllowCompatibleConfigurationMismatch*/ false, &Listener,
4755 ValidateDiagnosticOptions) != Success)
4761 bool ASTReader::isAcceptableASTFile(StringRef Filename, FileManager &FileMgr,
4762 const PCHContainerReader &PCHContainerRdr,
4763 const LangOptions &LangOpts,
4764 const TargetOptions &TargetOpts,
4765 const PreprocessorOptions &PPOpts,
4766 StringRef ExistingModuleCachePath) {
4767 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
4768 ExistingModuleCachePath, FileMgr);
4769 return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr,
4770 /*FindModuleFileExtensions=*/false,
4772 /*ValidateDiagnosticOptions=*/true);
4775 ASTReader::ASTReadResult
4776 ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
4777 // Enter the submodule block.
4778 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4779 Error("malformed submodule block record in AST file");
4783 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4785 Module *CurrentModule = nullptr;
4786 Module::ModuleKind ModuleKind = Module::ModuleMapModule;
4789 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
4791 switch (Entry.Kind) {
4792 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4793 case llvm::BitstreamEntry::Error:
4794 Error("malformed block record in AST file");
4796 case llvm::BitstreamEntry::EndBlock:
4798 case llvm::BitstreamEntry::Record:
4799 // The interesting case.
4806 auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
4808 if ((Kind == SUBMODULE_METADATA) != First) {
4809 Error("submodule metadata record should be at beginning of block");
4814 // Submodule information is only valid if we have a current module.
4815 // FIXME: Should we error on these cases?
4816 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
4817 Kind != SUBMODULE_DEFINITION)
4821 default: // Default behavior: ignore.
4824 case SUBMODULE_DEFINITION: {
4825 if (Record.size() < 8) {
4826 Error("malformed module definition");
4830 StringRef Name = Blob;
4832 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4833 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4834 bool IsFramework = Record[Idx++];
4835 bool IsExplicit = Record[Idx++];
4836 bool IsSystem = Record[Idx++];
4837 bool IsExternC = Record[Idx++];
4838 bool InferSubmodules = Record[Idx++];
4839 bool InferExplicitSubmodules = Record[Idx++];
4840 bool InferExportWildcard = Record[Idx++];
4841 bool ConfigMacrosExhaustive = Record[Idx++];
4843 Module *ParentModule = nullptr;
4845 ParentModule = getSubmodule(Parent);
4847 // Retrieve this (sub)module from the module map, creating it if
4850 ModMap.findOrCreateModule(Name, ParentModule, IsFramework, IsExplicit)
4853 // FIXME: set the definition loc for CurrentModule, or call
4854 // ModMap.setInferredModuleAllowedBy()
4856 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4857 if (GlobalIndex >= SubmodulesLoaded.size() ||
4858 SubmodulesLoaded[GlobalIndex]) {
4859 Error("too many submodules");
4863 if (!ParentModule) {
4864 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4865 if (CurFile != F.File) {
4866 if (!Diags.isDiagnosticInFlight()) {
4867 Diag(diag::err_module_file_conflict)
4868 << CurrentModule->getTopLevelModuleName()
4869 << CurFile->getName()
4870 << F.File->getName();
4876 CurrentModule->setASTFile(F.File);
4879 CurrentModule->Kind = ModuleKind;
4880 CurrentModule->Signature = F.Signature;
4881 CurrentModule->IsFromModuleFile = true;
4882 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
4883 CurrentModule->IsExternC = IsExternC;
4884 CurrentModule->InferSubmodules = InferSubmodules;
4885 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4886 CurrentModule->InferExportWildcard = InferExportWildcard;
4887 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
4888 if (DeserializationListener)
4889 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
4891 SubmodulesLoaded[GlobalIndex] = CurrentModule;
4893 // Clear out data that will be replaced by what is in the module file.
4894 CurrentModule->LinkLibraries.clear();
4895 CurrentModule->ConfigMacros.clear();
4896 CurrentModule->UnresolvedConflicts.clear();
4897 CurrentModule->Conflicts.clear();
4899 // The module is available unless it's missing a requirement; relevant
4900 // requirements will be (re-)added by SUBMODULE_REQUIRES records.
4901 // Missing headers that were present when the module was built do not
4902 // make it unavailable -- if we got this far, this must be an explicitly
4903 // imported module file.
4904 CurrentModule->Requirements.clear();
4905 CurrentModule->MissingHeaders.clear();
4906 CurrentModule->IsMissingRequirement =
4907 ParentModule && ParentModule->IsMissingRequirement;
4908 CurrentModule->IsAvailable = !CurrentModule->IsMissingRequirement;
4912 case SUBMODULE_UMBRELLA_HEADER: {
4913 std::string Filename = Blob;
4914 ResolveImportedPath(F, Filename);
4915 if (auto *Umbrella = PP.getFileManager().getFile(Filename)) {
4916 if (!CurrentModule->getUmbrellaHeader())
4917 ModMap.setUmbrellaHeader(CurrentModule, Umbrella, Blob);
4918 else if (CurrentModule->getUmbrellaHeader().Entry != Umbrella) {
4919 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4920 Error("mismatched umbrella headers in submodule");
4927 case SUBMODULE_HEADER:
4928 case SUBMODULE_EXCLUDED_HEADER:
4929 case SUBMODULE_PRIVATE_HEADER:
4930 // We lazily associate headers with their modules via the HeaderInfo table.
4931 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4932 // of complete filenames or remove it entirely.
4935 case SUBMODULE_TEXTUAL_HEADER:
4936 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
4937 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
4941 case SUBMODULE_TOPHEADER: {
4942 CurrentModule->addTopHeaderFilename(Blob);
4946 case SUBMODULE_UMBRELLA_DIR: {
4947 std::string Dirname = Blob;
4948 ResolveImportedPath(F, Dirname);
4949 if (auto *Umbrella = PP.getFileManager().getDirectory(Dirname)) {
4950 if (!CurrentModule->getUmbrellaDir())
4951 ModMap.setUmbrellaDir(CurrentModule, Umbrella, Blob);
4952 else if (CurrentModule->getUmbrellaDir().Entry != Umbrella) {
4953 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4954 Error("mismatched umbrella directories in submodule");
4961 case SUBMODULE_METADATA: {
4962 F.BaseSubmoduleID = getTotalNumSubmodules();
4963 F.LocalNumSubmodules = Record[0];
4964 unsigned LocalBaseSubmoduleID = Record[1];
4965 if (F.LocalNumSubmodules > 0) {
4966 // Introduce the global -> local mapping for submodules within this
4968 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
4970 // Introduce the local -> global mapping for submodules within this
4972 F.SubmoduleRemap.insertOrReplace(
4973 std::make_pair(LocalBaseSubmoduleID,
4974 F.BaseSubmoduleID - LocalBaseSubmoduleID));
4976 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4978 ModuleKind = (Module::ModuleKind)Record[2];
4982 case SUBMODULE_IMPORTS: {
4983 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
4984 UnresolvedModuleRef Unresolved;
4985 Unresolved.File = &F;
4986 Unresolved.Mod = CurrentModule;
4987 Unresolved.ID = Record[Idx];
4988 Unresolved.Kind = UnresolvedModuleRef::Import;
4989 Unresolved.IsWildcard = false;
4990 UnresolvedModuleRefs.push_back(Unresolved);
4995 case SUBMODULE_EXPORTS: {
4996 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
4997 UnresolvedModuleRef Unresolved;
4998 Unresolved.File = &F;
4999 Unresolved.Mod = CurrentModule;
5000 Unresolved.ID = Record[Idx];
5001 Unresolved.Kind = UnresolvedModuleRef::Export;
5002 Unresolved.IsWildcard = Record[Idx + 1];
5003 UnresolvedModuleRefs.push_back(Unresolved);
5006 // Once we've loaded the set of exports, there's no reason to keep
5007 // the parsed, unresolved exports around.
5008 CurrentModule->UnresolvedExports.clear();
5011 case SUBMODULE_REQUIRES: {
5012 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
5013 Context.getTargetInfo());
5017 case SUBMODULE_LINK_LIBRARY:
5018 CurrentModule->LinkLibraries.push_back(
5019 Module::LinkLibrary(Blob, Record[0]));
5022 case SUBMODULE_CONFIG_MACRO:
5023 CurrentModule->ConfigMacros.push_back(Blob.str());
5026 case SUBMODULE_CONFLICT: {
5027 UnresolvedModuleRef Unresolved;
5028 Unresolved.File = &F;
5029 Unresolved.Mod = CurrentModule;
5030 Unresolved.ID = Record[0];
5031 Unresolved.Kind = UnresolvedModuleRef::Conflict;
5032 Unresolved.IsWildcard = false;
5033 Unresolved.String = Blob;
5034 UnresolvedModuleRefs.push_back(Unresolved);
5038 case SUBMODULE_INITIALIZERS:
5039 SmallVector<uint32_t, 16> Inits;
5040 for (auto &ID : Record)
5041 Inits.push_back(getGlobalDeclID(F, ID));
5042 Context.addLazyModuleInitializers(CurrentModule, Inits);
5048 /// \brief Parse the record that corresponds to a LangOptions data
5051 /// This routine parses the language options from the AST file and then gives
5052 /// them to the AST listener if one is set.
5054 /// \returns true if the listener deems the file unacceptable, false otherwise.
5055 bool ASTReader::ParseLanguageOptions(const RecordData &Record,
5057 ASTReaderListener &Listener,
5058 bool AllowCompatibleDifferences) {
5059 LangOptions LangOpts;
5061 #define LANGOPT(Name, Bits, Default, Description) \
5062 LangOpts.Name = Record[Idx++];
5063 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
5064 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
5065 #include "clang/Basic/LangOptions.def"
5066 #define SANITIZER(NAME, ID) \
5067 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
5068 #include "clang/Basic/Sanitizers.def"
5070 for (unsigned N = Record[Idx++]; N; --N)
5071 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
5073 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
5074 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
5075 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
5077 LangOpts.CurrentModule = ReadString(Record, Idx);
5080 for (unsigned N = Record[Idx++]; N; --N) {
5081 LangOpts.CommentOpts.BlockCommandNames.push_back(
5082 ReadString(Record, Idx));
5084 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
5086 // OpenMP offloading options.
5087 for (unsigned N = Record[Idx++]; N; --N) {
5088 LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx)));
5091 LangOpts.OMPHostIRFile = ReadString(Record, Idx);
5093 return Listener.ReadLanguageOptions(LangOpts, Complain,
5094 AllowCompatibleDifferences);
5097 bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
5098 ASTReaderListener &Listener,
5099 bool AllowCompatibleDifferences) {
5101 TargetOptions TargetOpts;
5102 TargetOpts.Triple = ReadString(Record, Idx);
5103 TargetOpts.CPU = ReadString(Record, Idx);
5104 TargetOpts.ABI = ReadString(Record, Idx);
5105 for (unsigned N = Record[Idx++]; N; --N) {
5106 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
5108 for (unsigned N = Record[Idx++]; N; --N) {
5109 TargetOpts.Features.push_back(ReadString(Record, Idx));
5112 return Listener.ReadTargetOptions(TargetOpts, Complain,
5113 AllowCompatibleDifferences);
5116 bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
5117 ASTReaderListener &Listener) {
5118 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
5120 #define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
5121 #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
5122 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
5123 #include "clang/Basic/DiagnosticOptions.def"
5125 for (unsigned N = Record[Idx++]; N; --N)
5126 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
5127 for (unsigned N = Record[Idx++]; N; --N)
5128 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
5130 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
5133 bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
5134 ASTReaderListener &Listener) {
5135 FileSystemOptions FSOpts;
5137 FSOpts.WorkingDir = ReadString(Record, Idx);
5138 return Listener.ReadFileSystemOptions(FSOpts, Complain);
5141 bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
5143 ASTReaderListener &Listener) {
5144 HeaderSearchOptions HSOpts;
5146 HSOpts.Sysroot = ReadString(Record, Idx);
5149 for (unsigned N = Record[Idx++]; N; --N) {
5150 std::string Path = ReadString(Record, Idx);
5151 frontend::IncludeDirGroup Group
5152 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
5153 bool IsFramework = Record[Idx++];
5154 bool IgnoreSysRoot = Record[Idx++];
5155 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
5159 // System header prefixes.
5160 for (unsigned N = Record[Idx++]; N; --N) {
5161 std::string Prefix = ReadString(Record, Idx);
5162 bool IsSystemHeader = Record[Idx++];
5163 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
5166 HSOpts.ResourceDir = ReadString(Record, Idx);
5167 HSOpts.ModuleCachePath = ReadString(Record, Idx);
5168 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
5169 HSOpts.DisableModuleHash = Record[Idx++];
5170 HSOpts.UseBuiltinIncludes = Record[Idx++];
5171 HSOpts.UseStandardSystemIncludes = Record[Idx++];
5172 HSOpts.UseStandardCXXIncludes = Record[Idx++];
5173 HSOpts.UseLibcxx = Record[Idx++];
5174 std::string SpecificModuleCachePath = ReadString(Record, Idx);
5176 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
5180 bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
5182 ASTReaderListener &Listener,
5183 std::string &SuggestedPredefines) {
5184 PreprocessorOptions PPOpts;
5187 // Macro definitions/undefs
5188 for (unsigned N = Record[Idx++]; N; --N) {
5189 std::string Macro = ReadString(Record, Idx);
5190 bool IsUndef = Record[Idx++];
5191 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
5195 for (unsigned N = Record[Idx++]; N; --N) {
5196 PPOpts.Includes.push_back(ReadString(Record, Idx));
5200 for (unsigned N = Record[Idx++]; N; --N) {
5201 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
5204 PPOpts.UsePredefines = Record[Idx++];
5205 PPOpts.DetailedRecord = Record[Idx++];
5206 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
5207 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
5208 PPOpts.ObjCXXARCStandardLibrary =
5209 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
5210 SuggestedPredefines.clear();
5211 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
5212 SuggestedPredefines);
5215 std::pair<ModuleFile *, unsigned>
5216 ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
5217 GlobalPreprocessedEntityMapType::iterator
5218 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
5219 assert(I != GlobalPreprocessedEntityMap.end() &&
5220 "Corrupted global preprocessed entity map");
5221 ModuleFile *M = I->second;
5222 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
5223 return std::make_pair(M, LocalIndex);
5226 llvm::iterator_range<PreprocessingRecord::iterator>
5227 ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
5228 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
5229 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
5230 Mod.NumPreprocessedEntities);
5232 return llvm::make_range(PreprocessingRecord::iterator(),
5233 PreprocessingRecord::iterator());
5236 llvm::iterator_range<ASTReader::ModuleDeclIterator>
5237 ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
5238 return llvm::make_range(
5239 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
5240 ModuleDeclIterator(this, &Mod,
5241 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
5244 PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
5245 PreprocessedEntityID PPID = Index+1;
5246 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5247 ModuleFile &M = *PPInfo.first;
5248 unsigned LocalIndex = PPInfo.second;
5249 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
5251 if (!PP.getPreprocessingRecord()) {
5252 Error("no preprocessing record");
5256 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
5257 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
5259 llvm::BitstreamEntry Entry =
5260 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
5261 if (Entry.Kind != llvm::BitstreamEntry::Record)
5265 SourceRange Range(TranslateSourceLocation(M, PPOffs.getBegin()),
5266 TranslateSourceLocation(M, PPOffs.getEnd()));
5267 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
5270 PreprocessorDetailRecordTypes RecType =
5271 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
5272 Entry.ID, Record, &Blob);
5274 case PPD_MACRO_EXPANSION: {
5275 bool isBuiltin = Record[0];
5276 IdentifierInfo *Name = nullptr;
5277 MacroDefinitionRecord *Def = nullptr;
5279 Name = getLocalIdentifier(M, Record[1]);
5281 PreprocessedEntityID GlobalID =
5282 getGlobalPreprocessedEntityID(M, Record[1]);
5283 Def = cast<MacroDefinitionRecord>(
5284 PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
5289 ME = new (PPRec) MacroExpansion(Name, Range);
5291 ME = new (PPRec) MacroExpansion(Def, Range);
5296 case PPD_MACRO_DEFINITION: {
5297 // Decode the identifier info and then check again; if the macro is
5298 // still defined and associated with the identifier,
5299 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
5300 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
5302 if (DeserializationListener)
5303 DeserializationListener->MacroDefinitionRead(PPID, MD);
5308 case PPD_INCLUSION_DIRECTIVE: {
5309 const char *FullFileNameStart = Blob.data() + Record[0];
5310 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
5311 const FileEntry *File = nullptr;
5312 if (!FullFileName.empty())
5313 File = PP.getFileManager().getFile(FullFileName);
5315 // FIXME: Stable encoding
5316 InclusionDirective::InclusionKind Kind
5317 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
5318 InclusionDirective *ID
5319 = new (PPRec) InclusionDirective(PPRec, Kind,
5320 StringRef(Blob.data(), Record[0]),
5321 Record[1], Record[3],
5328 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
5331 /// \brief \arg SLocMapI points at a chunk of a module that contains no
5332 /// preprocessed entities or the entities it contains are not the ones we are
5333 /// looking for. Find the next module that contains entities and return the ID
5334 /// of the first entry.
5335 PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
5336 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
5338 for (GlobalSLocOffsetMapType::const_iterator
5339 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
5340 ModuleFile &M = *SLocMapI->second;
5341 if (M.NumPreprocessedEntities)
5342 return M.BasePreprocessedEntityID;
5345 return getTotalNumPreprocessedEntities();
5350 struct PPEntityComp {
5351 const ASTReader &Reader;
5354 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
5356 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
5357 SourceLocation LHS = getLoc(L);
5358 SourceLocation RHS = getLoc(R);
5359 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5362 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
5363 SourceLocation LHS = getLoc(L);
5364 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5367 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
5368 SourceLocation RHS = getLoc(R);
5369 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5372 SourceLocation getLoc(const PPEntityOffset &PPE) const {
5373 return Reader.TranslateSourceLocation(M, PPE.getBegin());
5377 } // end anonymous namespace
5379 PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
5380 bool EndsAfter) const {
5381 if (SourceMgr.isLocalSourceLocation(Loc))
5382 return getTotalNumPreprocessedEntities();
5384 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
5385 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
5386 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
5387 "Corrupted global sloc offset map");
5389 if (SLocMapI->second->NumPreprocessedEntities == 0)
5390 return findNextPreprocessedEntity(SLocMapI);
5392 ModuleFile &M = *SLocMapI->second;
5393 typedef const PPEntityOffset *pp_iterator;
5394 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
5395 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
5397 size_t Count = M.NumPreprocessedEntities;
5399 pp_iterator First = pp_begin;
5403 PPI = std::upper_bound(pp_begin, pp_end, Loc,
5404 PPEntityComp(*this, M));
5406 // Do a binary search manually instead of using std::lower_bound because
5407 // The end locations of entities may be unordered (when a macro expansion
5408 // is inside another macro argument), but for this case it is not important
5409 // whether we get the first macro expansion or its containing macro.
5413 std::advance(PPI, Half);
5414 if (SourceMgr.isBeforeInTranslationUnit(
5415 TranslateSourceLocation(M, PPI->getEnd()), Loc)) {
5418 Count = Count - Half - 1;
5425 return findNextPreprocessedEntity(SLocMapI);
5427 return M.BasePreprocessedEntityID + (PPI - pp_begin);
5430 /// \brief Returns a pair of [Begin, End) indices of preallocated
5431 /// preprocessed entities that \arg Range encompasses.
5432 std::pair<unsigned, unsigned>
5433 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
5434 if (Range.isInvalid())
5435 return std::make_pair(0,0);
5436 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
5438 PreprocessedEntityID BeginID =
5439 findPreprocessedEntity(Range.getBegin(), false);
5440 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
5441 return std::make_pair(BeginID, EndID);
5444 /// \brief Optionally returns true or false if the preallocated preprocessed
5445 /// entity with index \arg Index came from file \arg FID.
5446 Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
5448 if (FID.isInvalid())
5451 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5452 ModuleFile &M = *PPInfo.first;
5453 unsigned LocalIndex = PPInfo.second;
5454 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
5456 SourceLocation Loc = TranslateSourceLocation(M, PPOffs.getBegin());
5457 if (Loc.isInvalid())
5460 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
5468 /// \brief Visitor used to search for information about a header file.
5469 class HeaderFileInfoVisitor {
5470 const FileEntry *FE;
5472 Optional<HeaderFileInfo> HFI;
5475 explicit HeaderFileInfoVisitor(const FileEntry *FE)
5478 bool operator()(ModuleFile &M) {
5479 HeaderFileInfoLookupTable *Table
5480 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
5484 // Look in the on-disk hash table for an entry for this file name.
5485 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
5486 if (Pos == Table->end())
5493 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
5496 } // end anonymous namespace
5498 HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
5499 HeaderFileInfoVisitor Visitor(FE);
5500 ModuleMgr.visit(Visitor);
5501 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
5504 return HeaderFileInfo();
5507 void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
5508 using DiagState = DiagnosticsEngine::DiagState;
5509 SmallVector<DiagState *, 32> DiagStates;
5511 for (ModuleFile &F : ModuleMgr) {
5513 auto &Record = F.PragmaDiagMappings;
5519 auto ReadDiagState =
5520 [&](const DiagState &BasedOn, SourceLocation Loc,
5521 bool IncludeNonPragmaStates) -> DiagnosticsEngine::DiagState * {
5522 unsigned BackrefID = Record[Idx++];
5524 return DiagStates[BackrefID - 1];
5526 // A new DiagState was created here.
5527 Diag.DiagStates.push_back(BasedOn);
5528 DiagState *NewState = &Diag.DiagStates.back();
5529 DiagStates.push_back(NewState);
5530 unsigned Size = Record[Idx++];
5531 assert(Idx + Size * 2 <= Record.size() &&
5532 "Invalid data, not enough diag/map pairs");
5534 unsigned DiagID = Record[Idx++];
5535 DiagnosticMapping NewMapping =
5536 DiagnosticMapping::deserialize(Record[Idx++]);
5537 if (!NewMapping.isPragma() && !IncludeNonPragmaStates)
5540 DiagnosticMapping &Mapping = NewState->getOrAddMapping(DiagID);
5542 // If this mapping was specified as a warning but the severity was
5543 // upgraded due to diagnostic settings, simulate the current diagnostic
5544 // settings (and use a warning).
5545 if (NewMapping.wasUpgradedFromWarning() && !Mapping.isErrorOrFatal()) {
5546 NewMapping.setSeverity(diag::Severity::Warning);
5547 NewMapping.setUpgradedFromWarning(false);
5550 Mapping = NewMapping;
5555 // Read the first state.
5556 DiagState *FirstState;
5557 if (F.Kind == MK_ImplicitModule) {
5558 // Implicitly-built modules are reused with different diagnostic
5559 // settings. Use the initial diagnostic state from Diag to simulate this
5560 // compilation's diagnostic settings.
5561 FirstState = Diag.DiagStatesByLoc.FirstDiagState;
5562 DiagStates.push_back(FirstState);
5564 // Skip the initial diagnostic state from the serialized module.
5565 assert(Record[1] == 0 &&
5566 "Invalid data, unexpected backref in initial state");
5567 Idx = 3 + Record[2] * 2;
5568 assert(Idx < Record.size() &&
5569 "Invalid data, not enough state change pairs in initial state");
5570 } else if (F.isModule()) {
5571 // For an explicit module, preserve the flags from the module build
5572 // command line (-w, -Weverything, -Werror, ...) along with any explicit
5574 unsigned Flags = Record[Idx++];
5576 Initial.SuppressSystemWarnings = Flags & 1; Flags >>= 1;
5577 Initial.ErrorsAsFatal = Flags & 1; Flags >>= 1;
5578 Initial.WarningsAsErrors = Flags & 1; Flags >>= 1;
5579 Initial.EnableAllWarnings = Flags & 1; Flags >>= 1;
5580 Initial.IgnoreAllWarnings = Flags & 1; Flags >>= 1;
5581 Initial.ExtBehavior = (diag::Severity)Flags;
5582 FirstState = ReadDiagState(Initial, SourceLocation(), true);
5584 // Set up the root buffer of the module to start with the initial
5585 // diagnostic state of the module itself, to cover files that contain no
5586 // explicit transitions (for which we did not serialize anything).
5587 Diag.DiagStatesByLoc.Files[F.OriginalSourceFileID]
5588 .StateTransitions.push_back({FirstState, 0});
5590 // For prefix ASTs, start with whatever the user configured on the
5592 Idx++; // Skip flags.
5593 FirstState = ReadDiagState(*Diag.DiagStatesByLoc.CurDiagState,
5594 SourceLocation(), false);
5597 // Read the state transitions.
5598 unsigned NumLocations = Record[Idx++];
5599 while (NumLocations--) {
5600 assert(Idx < Record.size() &&
5601 "Invalid data, missing pragma diagnostic states");
5602 SourceLocation Loc = ReadSourceLocation(F, Record[Idx++]);
5603 auto IDAndOffset = SourceMgr.getDecomposedLoc(Loc);
5604 assert(IDAndOffset.second == 0 && "not a start location for a FileID");
5605 unsigned Transitions = Record[Idx++];
5607 // Note that we don't need to set up Parent/ParentOffset here, because
5608 // we won't be changing the diagnostic state within imported FileIDs
5609 // (other than perhaps appending to the main source file, which has no
5611 auto &F = Diag.DiagStatesByLoc.Files[IDAndOffset.first];
5612 F.StateTransitions.reserve(F.StateTransitions.size() + Transitions);
5613 for (unsigned I = 0; I != Transitions; ++I) {
5614 unsigned Offset = Record[Idx++];
5616 ReadDiagState(*FirstState, Loc.getLocWithOffset(Offset), false);
5617 F.StateTransitions.push_back({State, Offset});
5621 // Read the final state.
5622 assert(Idx < Record.size() &&
5623 "Invalid data, missing final pragma diagnostic state");
5624 SourceLocation CurStateLoc =
5625 ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
5626 auto *CurState = ReadDiagState(*FirstState, CurStateLoc, false);
5628 if (!F.isModule()) {
5629 Diag.DiagStatesByLoc.CurDiagState = CurState;
5630 Diag.DiagStatesByLoc.CurDiagStateLoc = CurStateLoc;
5632 // Preserve the property that the imaginary root file describes the
5634 auto &T = Diag.DiagStatesByLoc.Files[FileID()].StateTransitions;
5636 T.push_back({CurState, 0});
5638 T[0].State = CurState;
5641 // Don't try to read these mappings again.
5646 /// \brief Get the correct cursor and offset for loading a type.
5647 ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
5648 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
5649 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
5650 ModuleFile *M = I->second;
5651 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
5654 /// \brief Read and return the type with the given index..
5656 /// The index is the type ID, shifted and minus the number of predefs. This
5657 /// routine actually reads the record corresponding to the type at the given
5658 /// location. It is a helper routine for GetType, which deals with reading type
5660 QualType ASTReader::readTypeRecord(unsigned Index) {
5661 RecordLocation Loc = TypeCursorForIndex(Index);
5662 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
5664 // Keep track of where we are in the stream, then jump back there
5665 // after reading this type.
5666 SavedStreamPosition SavedPosition(DeclsCursor);
5668 ReadingKindTracker ReadingKind(Read_Type, *this);
5670 // Note that we are loading a type record.
5671 Deserializing AType(this);
5674 DeclsCursor.JumpToBit(Loc.Offset);
5676 unsigned Code = DeclsCursor.ReadCode();
5677 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
5678 case TYPE_EXT_QUAL: {
5679 if (Record.size() != 2) {
5680 Error("Incorrect encoding of extended qualifier type");
5683 QualType Base = readType(*Loc.F, Record, Idx);
5684 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
5685 return Context.getQualifiedType(Base, Quals);
5688 case TYPE_COMPLEX: {
5689 if (Record.size() != 1) {
5690 Error("Incorrect encoding of complex type");
5693 QualType ElemType = readType(*Loc.F, Record, Idx);
5694 return Context.getComplexType(ElemType);
5697 case TYPE_POINTER: {
5698 if (Record.size() != 1) {
5699 Error("Incorrect encoding of pointer type");
5702 QualType PointeeType = readType(*Loc.F, Record, Idx);
5703 return Context.getPointerType(PointeeType);
5706 case TYPE_DECAYED: {
5707 if (Record.size() != 1) {
5708 Error("Incorrect encoding of decayed type");
5711 QualType OriginalType = readType(*Loc.F, Record, Idx);
5712 QualType DT = Context.getAdjustedParameterType(OriginalType);
5713 if (!isa<DecayedType>(DT))
5714 Error("Decayed type does not decay");
5718 case TYPE_ADJUSTED: {
5719 if (Record.size() != 2) {
5720 Error("Incorrect encoding of adjusted type");
5723 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5724 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5725 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5728 case TYPE_BLOCK_POINTER: {
5729 if (Record.size() != 1) {
5730 Error("Incorrect encoding of block pointer type");
5733 QualType PointeeType = readType(*Loc.F, Record, Idx);
5734 return Context.getBlockPointerType(PointeeType);
5737 case TYPE_LVALUE_REFERENCE: {
5738 if (Record.size() != 2) {
5739 Error("Incorrect encoding of lvalue reference type");
5742 QualType PointeeType = readType(*Loc.F, Record, Idx);
5743 return Context.getLValueReferenceType(PointeeType, Record[1]);
5746 case TYPE_RVALUE_REFERENCE: {
5747 if (Record.size() != 1) {
5748 Error("Incorrect encoding of rvalue reference type");
5751 QualType PointeeType = readType(*Loc.F, Record, Idx);
5752 return Context.getRValueReferenceType(PointeeType);
5755 case TYPE_MEMBER_POINTER: {
5756 if (Record.size() != 2) {
5757 Error("Incorrect encoding of member pointer type");
5760 QualType PointeeType = readType(*Loc.F, Record, Idx);
5761 QualType ClassType = readType(*Loc.F, Record, Idx);
5762 if (PointeeType.isNull() || ClassType.isNull())
5765 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5768 case TYPE_CONSTANT_ARRAY: {
5769 QualType ElementType = readType(*Loc.F, Record, Idx);
5770 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5771 unsigned IndexTypeQuals = Record[2];
5773 llvm::APInt Size = ReadAPInt(Record, Idx);
5774 return Context.getConstantArrayType(ElementType, Size,
5775 ASM, IndexTypeQuals);
5778 case TYPE_INCOMPLETE_ARRAY: {
5779 QualType ElementType = readType(*Loc.F, Record, Idx);
5780 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5781 unsigned IndexTypeQuals = Record[2];
5782 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5785 case TYPE_VARIABLE_ARRAY: {
5786 QualType ElementType = readType(*Loc.F, Record, Idx);
5787 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5788 unsigned IndexTypeQuals = Record[2];
5789 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5790 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5791 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5792 ASM, IndexTypeQuals,
5793 SourceRange(LBLoc, RBLoc));
5797 if (Record.size() != 3) {
5798 Error("incorrect encoding of vector type in AST file");
5802 QualType ElementType = readType(*Loc.F, Record, Idx);
5803 unsigned NumElements = Record[1];
5804 unsigned VecKind = Record[2];
5805 return Context.getVectorType(ElementType, NumElements,
5806 (VectorType::VectorKind)VecKind);
5809 case TYPE_EXT_VECTOR: {
5810 if (Record.size() != 3) {
5811 Error("incorrect encoding of extended vector type in AST file");
5815 QualType ElementType = readType(*Loc.F, Record, Idx);
5816 unsigned NumElements = Record[1];
5817 return Context.getExtVectorType(ElementType, NumElements);
5820 case TYPE_FUNCTION_NO_PROTO: {
5821 if (Record.size() != 7) {
5822 Error("incorrect encoding of no-proto function type");
5825 QualType ResultType = readType(*Loc.F, Record, Idx);
5826 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5827 (CallingConv)Record[4], Record[5], Record[6]);
5828 return Context.getFunctionNoProtoType(ResultType, Info);
5831 case TYPE_FUNCTION_PROTO: {
5832 QualType ResultType = readType(*Loc.F, Record, Idx);
5834 FunctionProtoType::ExtProtoInfo EPI;
5835 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5836 /*hasregparm*/ Record[2],
5837 /*regparm*/ Record[3],
5838 static_cast<CallingConv>(Record[4]),
5839 /*produces*/ Record[5],
5840 /*nocallersavedregs*/ Record[6]);
5844 EPI.Variadic = Record[Idx++];
5845 EPI.HasTrailingReturn = Record[Idx++];
5846 EPI.TypeQuals = Record[Idx++];
5847 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
5848 SmallVector<QualType, 8> ExceptionStorage;
5849 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
5851 unsigned NumParams = Record[Idx++];
5852 SmallVector<QualType, 16> ParamTypes;
5853 for (unsigned I = 0; I != NumParams; ++I)
5854 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5856 SmallVector<FunctionProtoType::ExtParameterInfo, 4> ExtParameterInfos;
5857 if (Idx != Record.size()) {
5858 for (unsigned I = 0; I != NumParams; ++I)
5859 ExtParameterInfos.push_back(
5860 FunctionProtoType::ExtParameterInfo
5861 ::getFromOpaqueValue(Record[Idx++]));
5862 EPI.ExtParameterInfos = ExtParameterInfos.data();
5865 assert(Idx == Record.size());
5867 return Context.getFunctionType(ResultType, ParamTypes, EPI);
5870 case TYPE_UNRESOLVED_USING: {
5872 return Context.getTypeDeclType(
5873 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5876 case TYPE_TYPEDEF: {
5877 if (Record.size() != 2) {
5878 Error("incorrect encoding of typedef type");
5882 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5883 QualType Canonical = readType(*Loc.F, Record, Idx);
5884 if (!Canonical.isNull())
5885 Canonical = Context.getCanonicalType(Canonical);
5886 return Context.getTypedefType(Decl, Canonical);
5889 case TYPE_TYPEOF_EXPR:
5890 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5893 if (Record.size() != 1) {
5894 Error("incorrect encoding of typeof(type) in AST file");
5897 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5898 return Context.getTypeOfType(UnderlyingType);
5901 case TYPE_DECLTYPE: {
5902 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5903 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5906 case TYPE_UNARY_TRANSFORM: {
5907 QualType BaseType = readType(*Loc.F, Record, Idx);
5908 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5909 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5910 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5914 QualType Deduced = readType(*Loc.F, Record, Idx);
5915 AutoTypeKeyword Keyword = (AutoTypeKeyword)Record[Idx++];
5916 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
5917 return Context.getAutoType(Deduced, Keyword, IsDependent);
5920 case TYPE_DEDUCED_TEMPLATE_SPECIALIZATION: {
5921 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5922 QualType Deduced = readType(*Loc.F, Record, Idx);
5923 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
5924 return Context.getDeducedTemplateSpecializationType(Name, Deduced,
5929 if (Record.size() != 2) {
5930 Error("incorrect encoding of record type");
5934 bool IsDependent = Record[Idx++];
5935 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5936 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5937 QualType T = Context.getRecordType(RD);
5938 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5943 if (Record.size() != 2) {
5944 Error("incorrect encoding of enum type");
5948 bool IsDependent = Record[Idx++];
5950 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5951 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5955 case TYPE_ATTRIBUTED: {
5956 if (Record.size() != 3) {
5957 Error("incorrect encoding of attributed type");
5960 QualType modifiedType = readType(*Loc.F, Record, Idx);
5961 QualType equivalentType = readType(*Loc.F, Record, Idx);
5962 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5963 return Context.getAttributedType(kind, modifiedType, equivalentType);
5967 if (Record.size() != 1) {
5968 Error("incorrect encoding of paren type");
5971 QualType InnerType = readType(*Loc.F, Record, Idx);
5972 return Context.getParenType(InnerType);
5975 case TYPE_PACK_EXPANSION: {
5976 if (Record.size() != 2) {
5977 Error("incorrect encoding of pack expansion type");
5980 QualType Pattern = readType(*Loc.F, Record, Idx);
5981 if (Pattern.isNull())
5983 Optional<unsigned> NumExpansions;
5985 NumExpansions = Record[1] - 1;
5986 return Context.getPackExpansionType(Pattern, NumExpansions);
5989 case TYPE_ELABORATED: {
5991 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5992 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5993 QualType NamedType = readType(*Loc.F, Record, Idx);
5994 return Context.getElaboratedType(Keyword, NNS, NamedType);
5997 case TYPE_OBJC_INTERFACE: {
5999 ObjCInterfaceDecl *ItfD
6000 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
6001 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
6004 case TYPE_OBJC_TYPE_PARAM: {
6006 ObjCTypeParamDecl *Decl
6007 = ReadDeclAs<ObjCTypeParamDecl>(*Loc.F, Record, Idx);
6008 unsigned NumProtos = Record[Idx++];
6009 SmallVector<ObjCProtocolDecl*, 4> Protos;
6010 for (unsigned I = 0; I != NumProtos; ++I)
6011 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
6012 return Context.getObjCTypeParamType(Decl, Protos);
6014 case TYPE_OBJC_OBJECT: {
6016 QualType Base = readType(*Loc.F, Record, Idx);
6017 unsigned NumTypeArgs = Record[Idx++];
6018 SmallVector<QualType, 4> TypeArgs;
6019 for (unsigned I = 0; I != NumTypeArgs; ++I)
6020 TypeArgs.push_back(readType(*Loc.F, Record, Idx));
6021 unsigned NumProtos = Record[Idx++];
6022 SmallVector<ObjCProtocolDecl*, 4> Protos;
6023 for (unsigned I = 0; I != NumProtos; ++I)
6024 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
6025 bool IsKindOf = Record[Idx++];
6026 return Context.getObjCObjectType(Base, TypeArgs, Protos, IsKindOf);
6029 case TYPE_OBJC_OBJECT_POINTER: {
6031 QualType Pointee = readType(*Loc.F, Record, Idx);
6032 return Context.getObjCObjectPointerType(Pointee);
6035 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
6037 QualType Parm = readType(*Loc.F, Record, Idx);
6038 QualType Replacement = readType(*Loc.F, Record, Idx);
6039 return Context.getSubstTemplateTypeParmType(
6040 cast<TemplateTypeParmType>(Parm),
6041 Context.getCanonicalType(Replacement));
6044 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
6046 QualType Parm = readType(*Loc.F, Record, Idx);
6047 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
6048 return Context.getSubstTemplateTypeParmPackType(
6049 cast<TemplateTypeParmType>(Parm),
6053 case TYPE_INJECTED_CLASS_NAME: {
6054 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
6055 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
6056 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
6057 // for AST reading, too much interdependencies.
6058 const Type *T = nullptr;
6059 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
6060 if (const Type *Existing = DI->getTypeForDecl()) {
6066 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
6067 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
6068 DI->setTypeForDecl(T);
6070 return QualType(T, 0);
6073 case TYPE_TEMPLATE_TYPE_PARM: {
6075 unsigned Depth = Record[Idx++];
6076 unsigned Index = Record[Idx++];
6077 bool Pack = Record[Idx++];
6078 TemplateTypeParmDecl *D
6079 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
6080 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
6083 case TYPE_DEPENDENT_NAME: {
6085 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
6086 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
6087 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
6088 QualType Canon = readType(*Loc.F, Record, Idx);
6089 if (!Canon.isNull())
6090 Canon = Context.getCanonicalType(Canon);
6091 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
6094 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
6096 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
6097 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
6098 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
6099 unsigned NumArgs = Record[Idx++];
6100 SmallVector<TemplateArgument, 8> Args;
6101 Args.reserve(NumArgs);
6103 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
6104 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
6108 case TYPE_DEPENDENT_SIZED_ARRAY: {
6112 QualType ElementType = readType(*Loc.F, Record, Idx);
6113 ArrayType::ArraySizeModifier ASM
6114 = (ArrayType::ArraySizeModifier)Record[Idx++];
6115 unsigned IndexTypeQuals = Record[Idx++];
6117 // DependentSizedArrayType
6118 Expr *NumElts = ReadExpr(*Loc.F);
6119 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
6121 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
6122 IndexTypeQuals, Brackets);
6125 case TYPE_TEMPLATE_SPECIALIZATION: {
6127 bool IsDependent = Record[Idx++];
6128 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
6129 SmallVector<TemplateArgument, 8> Args;
6130 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
6131 QualType Underlying = readType(*Loc.F, Record, Idx);
6133 if (Underlying.isNull())
6134 T = Context.getCanonicalTemplateSpecializationType(Name, Args);
6136 T = Context.getTemplateSpecializationType(Name, Args, Underlying);
6137 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
6142 if (Record.size() != 1) {
6143 Error("Incorrect encoding of atomic type");
6146 QualType ValueType = readType(*Loc.F, Record, Idx);
6147 return Context.getAtomicType(ValueType);
6151 if (Record.size() != 2) {
6152 Error("Incorrect encoding of pipe type");
6156 // Reading the pipe element type.
6157 QualType ElementType = readType(*Loc.F, Record, Idx);
6158 unsigned ReadOnly = Record[1];
6159 return Context.getPipeType(ElementType, ReadOnly);
6162 case TYPE_DEPENDENT_SIZED_EXT_VECTOR: {
6165 // DependentSizedExtVectorType
6166 QualType ElementType = readType(*Loc.F, Record, Idx);
6167 Expr *SizeExpr = ReadExpr(*Loc.F);
6168 SourceLocation AttrLoc = ReadSourceLocation(*Loc.F, Record, Idx);
6170 return Context.getDependentSizedExtVectorType(ElementType, SizeExpr,
6174 llvm_unreachable("Invalid TypeCode!");
6177 void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
6178 SmallVectorImpl<QualType> &Exceptions,
6179 FunctionProtoType::ExceptionSpecInfo &ESI,
6180 const RecordData &Record, unsigned &Idx) {
6181 ExceptionSpecificationType EST =
6182 static_cast<ExceptionSpecificationType>(Record[Idx++]);
6184 if (EST == EST_Dynamic) {
6185 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
6186 Exceptions.push_back(readType(ModuleFile, Record, Idx));
6187 ESI.Exceptions = Exceptions;
6188 } else if (EST == EST_ComputedNoexcept) {
6189 ESI.NoexceptExpr = ReadExpr(ModuleFile);
6190 } else if (EST == EST_Uninstantiated) {
6191 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
6192 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
6193 } else if (EST == EST_Unevaluated) {
6194 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
6198 class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
6201 const ASTReader::RecordData &Record;
6204 SourceLocation ReadSourceLocation() {
6205 return Reader->ReadSourceLocation(*F, Record, Idx);
6208 TypeSourceInfo *GetTypeSourceInfo() {
6209 return Reader->GetTypeSourceInfo(*F, Record, Idx);
6212 NestedNameSpecifierLoc ReadNestedNameSpecifierLoc() {
6213 return Reader->ReadNestedNameSpecifierLoc(*F, Record, Idx);
6217 TypeLocReader(ModuleFile &F, ASTReader &Reader,
6218 const ASTReader::RecordData &Record, unsigned &Idx)
6219 : F(&F), Reader(&Reader), Record(Record), Idx(Idx) {}
6221 // We want compile-time assurance that we've enumerated all of
6222 // these, so unfortunately we have to declare them first, then
6223 // define them out-of-line.
6224 #define ABSTRACT_TYPELOC(CLASS, PARENT)
6225 #define TYPELOC(CLASS, PARENT) \
6226 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
6227 #include "clang/AST/TypeLocNodes.def"
6229 void VisitFunctionTypeLoc(FunctionTypeLoc);
6230 void VisitArrayTypeLoc(ArrayTypeLoc);
6233 void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
6237 void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
6238 TL.setBuiltinLoc(ReadSourceLocation());
6239 if (TL.needsExtraLocalData()) {
6240 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
6241 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
6242 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
6243 TL.setModeAttr(Record[Idx++]);
6247 void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
6248 TL.setNameLoc(ReadSourceLocation());
6251 void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
6252 TL.setStarLoc(ReadSourceLocation());
6255 void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
6259 void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
6263 void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
6264 TL.setCaretLoc(ReadSourceLocation());
6267 void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
6268 TL.setAmpLoc(ReadSourceLocation());
6271 void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
6272 TL.setAmpAmpLoc(ReadSourceLocation());
6275 void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
6276 TL.setStarLoc(ReadSourceLocation());
6277 TL.setClassTInfo(GetTypeSourceInfo());
6280 void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
6281 TL.setLBracketLoc(ReadSourceLocation());
6282 TL.setRBracketLoc(ReadSourceLocation());
6284 TL.setSizeExpr(Reader->ReadExpr(*F));
6286 TL.setSizeExpr(nullptr);
6289 void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
6290 VisitArrayTypeLoc(TL);
6293 void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
6294 VisitArrayTypeLoc(TL);
6297 void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
6298 VisitArrayTypeLoc(TL);
6301 void TypeLocReader::VisitDependentSizedArrayTypeLoc(
6302 DependentSizedArrayTypeLoc TL) {
6303 VisitArrayTypeLoc(TL);
6306 void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
6307 DependentSizedExtVectorTypeLoc TL) {
6308 TL.setNameLoc(ReadSourceLocation());
6311 void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
6312 TL.setNameLoc(ReadSourceLocation());
6315 void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
6316 TL.setNameLoc(ReadSourceLocation());
6319 void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
6320 TL.setLocalRangeBegin(ReadSourceLocation());
6321 TL.setLParenLoc(ReadSourceLocation());
6322 TL.setRParenLoc(ReadSourceLocation());
6323 TL.setExceptionSpecRange(SourceRange(Reader->ReadSourceLocation(*F, Record, Idx),
6324 Reader->ReadSourceLocation(*F, Record, Idx)));
6325 TL.setLocalRangeEnd(ReadSourceLocation());
6326 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
6327 TL.setParam(i, Reader->ReadDeclAs<ParmVarDecl>(*F, Record, Idx));
6331 void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
6332 VisitFunctionTypeLoc(TL);
6335 void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
6336 VisitFunctionTypeLoc(TL);
6338 void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
6339 TL.setNameLoc(ReadSourceLocation());
6341 void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
6342 TL.setNameLoc(ReadSourceLocation());
6344 void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
6345 TL.setTypeofLoc(ReadSourceLocation());
6346 TL.setLParenLoc(ReadSourceLocation());
6347 TL.setRParenLoc(ReadSourceLocation());
6349 void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
6350 TL.setTypeofLoc(ReadSourceLocation());
6351 TL.setLParenLoc(ReadSourceLocation());
6352 TL.setRParenLoc(ReadSourceLocation());
6353 TL.setUnderlyingTInfo(GetTypeSourceInfo());
6355 void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
6356 TL.setNameLoc(ReadSourceLocation());
6359 void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
6360 TL.setKWLoc(ReadSourceLocation());
6361 TL.setLParenLoc(ReadSourceLocation());
6362 TL.setRParenLoc(ReadSourceLocation());
6363 TL.setUnderlyingTInfo(GetTypeSourceInfo());
6366 void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
6367 TL.setNameLoc(ReadSourceLocation());
6370 void TypeLocReader::VisitDeducedTemplateSpecializationTypeLoc(
6371 DeducedTemplateSpecializationTypeLoc TL) {
6372 TL.setTemplateNameLoc(ReadSourceLocation());
6375 void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
6376 TL.setNameLoc(ReadSourceLocation());
6379 void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
6380 TL.setNameLoc(ReadSourceLocation());
6383 void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
6384 TL.setAttrNameLoc(ReadSourceLocation());
6385 if (TL.hasAttrOperand()) {
6387 range.setBegin(ReadSourceLocation());
6388 range.setEnd(ReadSourceLocation());
6389 TL.setAttrOperandParensRange(range);
6391 if (TL.hasAttrExprOperand()) {
6393 TL.setAttrExprOperand(Reader->ReadExpr(*F));
6395 TL.setAttrExprOperand(nullptr);
6396 } else if (TL.hasAttrEnumOperand())
6397 TL.setAttrEnumOperandLoc(ReadSourceLocation());
6400 void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
6401 TL.setNameLoc(ReadSourceLocation());
6404 void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
6405 SubstTemplateTypeParmTypeLoc TL) {
6406 TL.setNameLoc(ReadSourceLocation());
6408 void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
6409 SubstTemplateTypeParmPackTypeLoc TL) {
6410 TL.setNameLoc(ReadSourceLocation());
6412 void TypeLocReader::VisitTemplateSpecializationTypeLoc(
6413 TemplateSpecializationTypeLoc TL) {
6414 TL.setTemplateKeywordLoc(ReadSourceLocation());
6415 TL.setTemplateNameLoc(ReadSourceLocation());
6416 TL.setLAngleLoc(ReadSourceLocation());
6417 TL.setRAngleLoc(ReadSourceLocation());
6418 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
6421 Reader->GetTemplateArgumentLocInfo(
6422 *F, TL.getTypePtr()->getArg(i).getKind(), Record, Idx));
6424 void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
6425 TL.setLParenLoc(ReadSourceLocation());
6426 TL.setRParenLoc(ReadSourceLocation());
6429 void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
6430 TL.setElaboratedKeywordLoc(ReadSourceLocation());
6431 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
6434 void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
6435 TL.setNameLoc(ReadSourceLocation());
6438 void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
6439 TL.setElaboratedKeywordLoc(ReadSourceLocation());
6440 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
6441 TL.setNameLoc(ReadSourceLocation());
6444 void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
6445 DependentTemplateSpecializationTypeLoc TL) {
6446 TL.setElaboratedKeywordLoc(ReadSourceLocation());
6447 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
6448 TL.setTemplateKeywordLoc(ReadSourceLocation());
6449 TL.setTemplateNameLoc(ReadSourceLocation());
6450 TL.setLAngleLoc(ReadSourceLocation());
6451 TL.setRAngleLoc(ReadSourceLocation());
6452 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
6455 Reader->GetTemplateArgumentLocInfo(
6456 *F, TL.getTypePtr()->getArg(I).getKind(), Record, Idx));
6459 void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
6460 TL.setEllipsisLoc(ReadSourceLocation());
6463 void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
6464 TL.setNameLoc(ReadSourceLocation());
6467 void TypeLocReader::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
6468 if (TL.getNumProtocols()) {
6469 TL.setProtocolLAngleLoc(ReadSourceLocation());
6470 TL.setProtocolRAngleLoc(ReadSourceLocation());
6472 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
6473 TL.setProtocolLoc(i, ReadSourceLocation());
6476 void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
6477 TL.setHasBaseTypeAsWritten(Record[Idx++]);
6478 TL.setTypeArgsLAngleLoc(ReadSourceLocation());
6479 TL.setTypeArgsRAngleLoc(ReadSourceLocation());
6480 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
6481 TL.setTypeArgTInfo(i, GetTypeSourceInfo());
6482 TL.setProtocolLAngleLoc(ReadSourceLocation());
6483 TL.setProtocolRAngleLoc(ReadSourceLocation());
6484 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
6485 TL.setProtocolLoc(i, ReadSourceLocation());
6488 void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
6489 TL.setStarLoc(ReadSourceLocation());
6492 void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
6493 TL.setKWLoc(ReadSourceLocation());
6494 TL.setLParenLoc(ReadSourceLocation());
6495 TL.setRParenLoc(ReadSourceLocation());
6498 void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) {
6499 TL.setKWLoc(ReadSourceLocation());
6503 ASTReader::GetTypeSourceInfo(ModuleFile &F, const ASTReader::RecordData &Record,
6505 QualType InfoTy = readType(F, Record, Idx);
6506 if (InfoTy.isNull())
6509 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
6510 TypeLocReader TLR(F, *this, Record, Idx);
6511 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
6516 QualType ASTReader::GetType(TypeID ID) {
6517 unsigned FastQuals = ID & Qualifiers::FastMask;
6518 unsigned Index = ID >> Qualifiers::FastWidth;
6520 if (Index < NUM_PREDEF_TYPE_IDS) {
6522 switch ((PredefinedTypeIDs)Index) {
6523 case PREDEF_TYPE_NULL_ID:
6525 case PREDEF_TYPE_VOID_ID:
6528 case PREDEF_TYPE_BOOL_ID:
6532 case PREDEF_TYPE_CHAR_U_ID:
6533 case PREDEF_TYPE_CHAR_S_ID:
6534 // FIXME: Check that the signedness of CharTy is correct!
6538 case PREDEF_TYPE_UCHAR_ID:
6539 T = Context.UnsignedCharTy;
6541 case PREDEF_TYPE_USHORT_ID:
6542 T = Context.UnsignedShortTy;
6544 case PREDEF_TYPE_UINT_ID:
6545 T = Context.UnsignedIntTy;
6547 case PREDEF_TYPE_ULONG_ID:
6548 T = Context.UnsignedLongTy;
6550 case PREDEF_TYPE_ULONGLONG_ID:
6551 T = Context.UnsignedLongLongTy;
6553 case PREDEF_TYPE_UINT128_ID:
6554 T = Context.UnsignedInt128Ty;
6556 case PREDEF_TYPE_SCHAR_ID:
6557 T = Context.SignedCharTy;
6559 case PREDEF_TYPE_WCHAR_ID:
6560 T = Context.WCharTy;
6562 case PREDEF_TYPE_SHORT_ID:
6563 T = Context.ShortTy;
6565 case PREDEF_TYPE_INT_ID:
6568 case PREDEF_TYPE_LONG_ID:
6571 case PREDEF_TYPE_LONGLONG_ID:
6572 T = Context.LongLongTy;
6574 case PREDEF_TYPE_INT128_ID:
6575 T = Context.Int128Ty;
6577 case PREDEF_TYPE_HALF_ID:
6580 case PREDEF_TYPE_FLOAT_ID:
6581 T = Context.FloatTy;
6583 case PREDEF_TYPE_DOUBLE_ID:
6584 T = Context.DoubleTy;
6586 case PREDEF_TYPE_LONGDOUBLE_ID:
6587 T = Context.LongDoubleTy;
6589 case PREDEF_TYPE_FLOAT128_ID:
6590 T = Context.Float128Ty;
6592 case PREDEF_TYPE_OVERLOAD_ID:
6593 T = Context.OverloadTy;
6595 case PREDEF_TYPE_BOUND_MEMBER:
6596 T = Context.BoundMemberTy;
6598 case PREDEF_TYPE_PSEUDO_OBJECT:
6599 T = Context.PseudoObjectTy;
6601 case PREDEF_TYPE_DEPENDENT_ID:
6602 T = Context.DependentTy;
6604 case PREDEF_TYPE_UNKNOWN_ANY:
6605 T = Context.UnknownAnyTy;
6607 case PREDEF_TYPE_NULLPTR_ID:
6608 T = Context.NullPtrTy;
6610 case PREDEF_TYPE_CHAR16_ID:
6611 T = Context.Char16Ty;
6613 case PREDEF_TYPE_CHAR32_ID:
6614 T = Context.Char32Ty;
6616 case PREDEF_TYPE_OBJC_ID:
6617 T = Context.ObjCBuiltinIdTy;
6619 case PREDEF_TYPE_OBJC_CLASS:
6620 T = Context.ObjCBuiltinClassTy;
6622 case PREDEF_TYPE_OBJC_SEL:
6623 T = Context.ObjCBuiltinSelTy;
6625 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6626 case PREDEF_TYPE_##Id##_ID: \
6627 T = Context.SingletonId; \
6629 #include "clang/Basic/OpenCLImageTypes.def"
6630 case PREDEF_TYPE_SAMPLER_ID:
6631 T = Context.OCLSamplerTy;
6633 case PREDEF_TYPE_EVENT_ID:
6634 T = Context.OCLEventTy;
6636 case PREDEF_TYPE_CLK_EVENT_ID:
6637 T = Context.OCLClkEventTy;
6639 case PREDEF_TYPE_QUEUE_ID:
6640 T = Context.OCLQueueTy;
6642 case PREDEF_TYPE_RESERVE_ID_ID:
6643 T = Context.OCLReserveIDTy;
6645 case PREDEF_TYPE_AUTO_DEDUCT:
6646 T = Context.getAutoDeductType();
6649 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
6650 T = Context.getAutoRRefDeductType();
6653 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
6654 T = Context.ARCUnbridgedCastTy;
6657 case PREDEF_TYPE_BUILTIN_FN:
6658 T = Context.BuiltinFnTy;
6661 case PREDEF_TYPE_OMP_ARRAY_SECTION:
6662 T = Context.OMPArraySectionTy;
6666 assert(!T.isNull() && "Unknown predefined type");
6667 return T.withFastQualifiers(FastQuals);
6670 Index -= NUM_PREDEF_TYPE_IDS;
6671 assert(Index < TypesLoaded.size() && "Type index out-of-range");
6672 if (TypesLoaded[Index].isNull()) {
6673 TypesLoaded[Index] = readTypeRecord(Index);
6674 if (TypesLoaded[Index].isNull())
6677 TypesLoaded[Index]->setFromAST();
6678 if (DeserializationListener)
6679 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
6680 TypesLoaded[Index]);
6683 return TypesLoaded[Index].withFastQualifiers(FastQuals);
6686 QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
6687 return GetType(getGlobalTypeID(F, LocalID));
6690 serialization::TypeID
6691 ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
6692 unsigned FastQuals = LocalID & Qualifiers::FastMask;
6693 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
6695 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
6698 if (!F.ModuleOffsetMap.empty())
6699 ReadModuleOffsetMap(F);
6701 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6702 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
6703 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
6705 unsigned GlobalIndex = LocalIndex + I->second;
6706 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
6709 TemplateArgumentLocInfo
6710 ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
6711 TemplateArgument::ArgKind Kind,
6712 const RecordData &Record,
6715 case TemplateArgument::Expression:
6717 case TemplateArgument::Type:
6718 return GetTypeSourceInfo(F, Record, Index);
6719 case TemplateArgument::Template: {
6720 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
6722 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6723 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6726 case TemplateArgument::TemplateExpansion: {
6727 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
6729 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6730 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
6731 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6734 case TemplateArgument::Null:
6735 case TemplateArgument::Integral:
6736 case TemplateArgument::Declaration:
6737 case TemplateArgument::NullPtr:
6738 case TemplateArgument::Pack:
6739 // FIXME: Is this right?
6740 return TemplateArgumentLocInfo();
6742 llvm_unreachable("unexpected template argument loc");
6746 ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
6747 const RecordData &Record, unsigned &Index) {
6748 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
6750 if (Arg.getKind() == TemplateArgument::Expression) {
6751 if (Record[Index++]) // bool InfoHasSameExpr.
6752 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
6754 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
6758 const ASTTemplateArgumentListInfo*
6759 ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
6760 const RecordData &Record,
6762 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
6763 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
6764 unsigned NumArgsAsWritten = Record[Index++];
6765 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
6766 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
6767 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
6768 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
6771 Decl *ASTReader::GetExternalDecl(uint32_t ID) {
6775 void ASTReader::CompleteRedeclChain(const Decl *D) {
6776 if (NumCurrentElementsDeserializing) {
6777 // We arrange to not care about the complete redeclaration chain while we're
6778 // deserializing. Just remember that the AST has marked this one as complete
6779 // but that it's not actually complete yet, so we know we still need to
6780 // complete it later.
6781 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
6785 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
6787 // If this is a named declaration, complete it by looking it up
6788 // within its context.
6790 // FIXME: Merging a function definition should merge
6791 // all mergeable entities within it.
6792 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
6793 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
6794 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
6795 if (!getContext().getLangOpts().CPlusPlus &&
6796 isa<TranslationUnitDecl>(DC)) {
6797 // Outside of C++, we don't have a lookup table for the TU, so update
6798 // the identifier instead. (For C++ modules, we don't store decls
6799 // in the serialized identifier table, so we do the lookup in the TU.)
6800 auto *II = Name.getAsIdentifierInfo();
6801 assert(II && "non-identifier name in C?");
6802 if (II->isOutOfDate())
6803 updateOutOfDateIdentifier(*II);
6806 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
6807 // Find all declarations of this kind from the relevant context.
6808 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
6809 auto *DC = cast<DeclContext>(DCDecl);
6810 SmallVector<Decl*, 8> Decls;
6811 FindExternalLexicalDecls(
6812 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
6817 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
6818 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
6819 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
6820 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
6821 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6822 if (auto *Template = FD->getPrimaryTemplate())
6823 Template->LoadLazySpecializations();
6827 CXXCtorInitializer **
6828 ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
6829 RecordLocation Loc = getLocalBitOffset(Offset);
6830 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
6831 SavedStreamPosition SavedPosition(Cursor);
6832 Cursor.JumpToBit(Loc.Offset);
6833 ReadingKindTracker ReadingKind(Read_Decl, *this);
6836 unsigned Code = Cursor.ReadCode();
6837 unsigned RecCode = Cursor.readRecord(Code, Record);
6838 if (RecCode != DECL_CXX_CTOR_INITIALIZERS) {
6839 Error("malformed AST file: missing C++ ctor initializers");
6844 return ReadCXXCtorInitializers(*Loc.F, Record, Idx);
6847 CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
6848 RecordLocation Loc = getLocalBitOffset(Offset);
6849 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
6850 SavedStreamPosition SavedPosition(Cursor);
6851 Cursor.JumpToBit(Loc.Offset);
6852 ReadingKindTracker ReadingKind(Read_Decl, *this);
6854 unsigned Code = Cursor.ReadCode();
6855 unsigned RecCode = Cursor.readRecord(Code, Record);
6856 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
6857 Error("malformed AST file: missing C++ base specifiers");
6862 unsigned NumBases = Record[Idx++];
6863 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
6864 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
6865 for (unsigned I = 0; I != NumBases; ++I)
6866 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
6870 serialization::DeclID
6871 ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
6872 if (LocalID < NUM_PREDEF_DECL_IDS)
6875 if (!F.ModuleOffsetMap.empty())
6876 ReadModuleOffsetMap(F);
6878 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6879 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
6880 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
6882 return LocalID + I->second;
6885 bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
6886 ModuleFile &M) const {
6887 // Predefined decls aren't from any module.
6888 if (ID < NUM_PREDEF_DECL_IDS)
6891 return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
6892 ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
6895 ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
6896 if (!D->isFromASTFile())
6898 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6899 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6903 SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6904 if (ID < NUM_PREDEF_DECL_IDS)
6905 return SourceLocation();
6907 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6909 if (Index > DeclsLoaded.size()) {
6910 Error("declaration ID out-of-range for AST file");
6911 return SourceLocation();
6914 if (Decl *D = DeclsLoaded[Index])
6915 return D->getLocation();
6918 DeclCursorForID(ID, Loc);
6922 static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
6924 case PREDEF_DECL_NULL_ID:
6927 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6928 return Context.getTranslationUnitDecl();
6930 case PREDEF_DECL_OBJC_ID_ID:
6931 return Context.getObjCIdDecl();
6933 case PREDEF_DECL_OBJC_SEL_ID:
6934 return Context.getObjCSelDecl();
6936 case PREDEF_DECL_OBJC_CLASS_ID:
6937 return Context.getObjCClassDecl();
6939 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6940 return Context.getObjCProtocolDecl();
6942 case PREDEF_DECL_INT_128_ID:
6943 return Context.getInt128Decl();
6945 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6946 return Context.getUInt128Decl();
6948 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6949 return Context.getObjCInstanceTypeDecl();
6951 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6952 return Context.getBuiltinVaListDecl();
6954 case PREDEF_DECL_VA_LIST_TAG:
6955 return Context.getVaListTagDecl();
6957 case PREDEF_DECL_BUILTIN_MS_VA_LIST_ID:
6958 return Context.getBuiltinMSVaListDecl();
6960 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
6961 return Context.getExternCContextDecl();
6963 case PREDEF_DECL_MAKE_INTEGER_SEQ_ID:
6964 return Context.getMakeIntegerSeqDecl();
6966 case PREDEF_DECL_CF_CONSTANT_STRING_ID:
6967 return Context.getCFConstantStringDecl();
6969 case PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID:
6970 return Context.getCFConstantStringTagDecl();
6972 case PREDEF_DECL_TYPE_PACK_ELEMENT_ID:
6973 return Context.getTypePackElementDecl();
6975 llvm_unreachable("PredefinedDeclIDs unknown enum value");
6978 Decl *ASTReader::GetExistingDecl(DeclID ID) {
6979 if (ID < NUM_PREDEF_DECL_IDS) {
6980 Decl *D = getPredefinedDecl(Context, (PredefinedDeclIDs)ID);
6982 // Track that we have merged the declaration with ID \p ID into the
6983 // pre-existing predefined declaration \p D.
6984 auto &Merged = KeyDecls[D->getCanonicalDecl()];
6986 Merged.push_back(ID);
6991 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6993 if (Index >= DeclsLoaded.size()) {
6994 assert(0 && "declaration ID out-of-range for AST file");
6995 Error("declaration ID out-of-range for AST file");
6999 return DeclsLoaded[Index];
7002 Decl *ASTReader::GetDecl(DeclID ID) {
7003 if (ID < NUM_PREDEF_DECL_IDS)
7004 return GetExistingDecl(ID);
7006 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7008 if (Index >= DeclsLoaded.size()) {
7009 assert(0 && "declaration ID out-of-range for AST file");
7010 Error("declaration ID out-of-range for AST file");
7014 if (!DeclsLoaded[Index]) {
7016 if (DeserializationListener)
7017 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
7020 return DeclsLoaded[Index];
7023 DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
7025 if (GlobalID < NUM_PREDEF_DECL_IDS)
7028 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
7029 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
7030 ModuleFile *Owner = I->second;
7032 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
7033 = M.GlobalToLocalDeclIDs.find(Owner);
7034 if (Pos == M.GlobalToLocalDeclIDs.end())
7037 return GlobalID - Owner->BaseDeclID + Pos->second;
7040 serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
7041 const RecordData &Record,
7043 if (Idx >= Record.size()) {
7044 Error("Corrupted AST file");
7048 return getGlobalDeclID(F, Record[Idx++]);
7051 /// \brief Resolve the offset of a statement into a statement.
7053 /// This operation will read a new statement from the external
7054 /// source each time it is called, and is meant to be used via a
7055 /// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
7056 Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
7057 // Switch case IDs are per Decl.
7058 ClearSwitchCaseIDs();
7060 // Offset here is a global offset across the entire chain.
7061 RecordLocation Loc = getLocalBitOffset(Offset);
7062 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
7063 assert(NumCurrentElementsDeserializing == 0 &&
7064 "should not be called while already deserializing");
7065 Deserializing D(this);
7066 return ReadStmtFromStream(*Loc.F);
7069 void ASTReader::FindExternalLexicalDecls(
7070 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
7071 SmallVectorImpl<Decl *> &Decls) {
7072 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
7074 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
7075 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
7076 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
7077 auto K = (Decl::Kind)+LexicalDecls[I];
7078 if (!IsKindWeWant(K))
7081 auto ID = (serialization::DeclID)+LexicalDecls[I + 1];
7083 // Don't add predefined declarations to the lexical context more
7085 if (ID < NUM_PREDEF_DECL_IDS) {
7086 if (PredefsVisited[ID])
7089 PredefsVisited[ID] = true;
7092 if (Decl *D = GetLocalDecl(*M, ID)) {
7093 assert(D->getKind() == K && "wrong kind for lexical decl");
7094 if (!DC->isDeclInLexicalTraversal(D))
7100 if (isa<TranslationUnitDecl>(DC)) {
7101 for (auto Lexical : TULexicalDecls)
7102 Visit(Lexical.first, Lexical.second);
7104 auto I = LexicalDecls.find(DC);
7105 if (I != LexicalDecls.end())
7106 Visit(I->second.first, I->second.second);
7109 ++NumLexicalDeclContextsRead;
7119 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
7121 bool operator()(LocalDeclID L, LocalDeclID R) const {
7122 SourceLocation LHS = getLocation(L);
7123 SourceLocation RHS = getLocation(R);
7124 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7127 bool operator()(SourceLocation LHS, LocalDeclID R) const {
7128 SourceLocation RHS = getLocation(R);
7129 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7132 bool operator()(LocalDeclID L, SourceLocation RHS) const {
7133 SourceLocation LHS = getLocation(L);
7134 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7137 SourceLocation getLocation(LocalDeclID ID) const {
7138 return Reader.getSourceManager().getFileLoc(
7139 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
7143 } // end anonymous namespace
7145 void ASTReader::FindFileRegionDecls(FileID File,
7146 unsigned Offset, unsigned Length,
7147 SmallVectorImpl<Decl *> &Decls) {
7148 SourceManager &SM = getSourceManager();
7150 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
7151 if (I == FileDeclIDs.end())
7154 FileDeclsInfo &DInfo = I->second;
7155 if (DInfo.Decls.empty())
7159 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
7160 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
7162 DeclIDComp DIDComp(*this, *DInfo.Mod);
7163 ArrayRef<serialization::LocalDeclID>::iterator
7164 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
7166 if (BeginIt != DInfo.Decls.begin())
7169 // If we are pointing at a top-level decl inside an objc container, we need
7170 // to backtrack until we find it otherwise we will fail to report that the
7171 // region overlaps with an objc container.
7172 while (BeginIt != DInfo.Decls.begin() &&
7173 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
7174 ->isTopLevelDeclInObjCContainer())
7177 ArrayRef<serialization::LocalDeclID>::iterator
7178 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
7180 if (EndIt != DInfo.Decls.end())
7183 for (ArrayRef<serialization::LocalDeclID>::iterator
7184 DIt = BeginIt; DIt != EndIt; ++DIt)
7185 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
7189 ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
7190 DeclarationName Name) {
7191 assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
7192 "DeclContext has no visible decls in storage");
7196 auto It = Lookups.find(DC);
7197 if (It == Lookups.end())
7200 Deserializing LookupResults(this);
7202 // Load the list of declarations.
7203 SmallVector<NamedDecl *, 64> Decls;
7204 for (DeclID ID : It->second.Table.find(Name)) {
7205 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
7206 if (ND->getDeclName() == Name)
7207 Decls.push_back(ND);
7210 ++NumVisibleDeclContextsRead;
7211 SetExternalVisibleDeclsForName(DC, Name, Decls);
7212 return !Decls.empty();
7215 void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
7216 if (!DC->hasExternalVisibleStorage())
7219 auto It = Lookups.find(DC);
7220 assert(It != Lookups.end() &&
7221 "have external visible storage but no lookup tables");
7225 for (DeclID ID : It->second.Table.findAll()) {
7226 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
7227 Decls[ND->getDeclName()].push_back(ND);
7230 ++NumVisibleDeclContextsRead;
7232 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
7233 SetExternalVisibleDeclsForName(DC, I->first, I->second);
7235 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
7238 const serialization::reader::DeclContextLookupTable *
7239 ASTReader::getLoadedLookupTables(DeclContext *Primary) const {
7240 auto I = Lookups.find(Primary);
7241 return I == Lookups.end() ? nullptr : &I->second;
7244 /// \brief Under non-PCH compilation the consumer receives the objc methods
7245 /// before receiving the implementation, and codegen depends on this.
7246 /// We simulate this by deserializing and passing to consumer the methods of the
7247 /// implementation before passing the deserialized implementation decl.
7248 static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
7249 ASTConsumer *Consumer) {
7250 assert(ImplD && Consumer);
7252 for (auto *I : ImplD->methods())
7253 Consumer->HandleInterestingDecl(DeclGroupRef(I));
7255 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
7258 void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
7259 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
7260 PassObjCImplDeclToConsumer(ImplD, Consumer);
7262 Consumer->HandleInterestingDecl(DeclGroupRef(D));
7265 void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
7266 this->Consumer = Consumer;
7269 PassInterestingDeclsToConsumer();
7271 if (DeserializationListener)
7272 DeserializationListener->ReaderInitialized(this);
7275 void ASTReader::PrintStats() {
7276 std::fprintf(stderr, "*** AST File Statistics:\n");
7278 unsigned NumTypesLoaded
7279 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
7281 unsigned NumDeclsLoaded
7282 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
7284 unsigned NumIdentifiersLoaded
7285 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
7286 IdentifiersLoaded.end(),
7287 (IdentifierInfo *)nullptr);
7288 unsigned NumMacrosLoaded
7289 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
7291 (MacroInfo *)nullptr);
7292 unsigned NumSelectorsLoaded
7293 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
7294 SelectorsLoaded.end(),
7297 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
7298 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
7299 NumSLocEntriesRead, TotalNumSLocEntries,
7300 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
7301 if (!TypesLoaded.empty())
7302 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
7303 NumTypesLoaded, (unsigned)TypesLoaded.size(),
7304 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
7305 if (!DeclsLoaded.empty())
7306 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
7307 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
7308 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
7309 if (!IdentifiersLoaded.empty())
7310 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
7311 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
7312 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
7313 if (!MacrosLoaded.empty())
7314 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
7315 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
7316 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
7317 if (!SelectorsLoaded.empty())
7318 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
7319 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
7320 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
7321 if (TotalNumStatements)
7322 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
7323 NumStatementsRead, TotalNumStatements,
7324 ((float)NumStatementsRead/TotalNumStatements * 100));
7326 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
7327 NumMacrosRead, TotalNumMacros,
7328 ((float)NumMacrosRead/TotalNumMacros * 100));
7329 if (TotalLexicalDeclContexts)
7330 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
7331 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
7332 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
7334 if (TotalVisibleDeclContexts)
7335 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
7336 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
7337 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
7339 if (TotalNumMethodPoolEntries) {
7340 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
7341 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
7342 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
7345 if (NumMethodPoolLookups) {
7346 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
7347 NumMethodPoolHits, NumMethodPoolLookups,
7348 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
7350 if (NumMethodPoolTableLookups) {
7351 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
7352 NumMethodPoolTableHits, NumMethodPoolTableLookups,
7353 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
7357 if (NumIdentifierLookupHits) {
7358 std::fprintf(stderr,
7359 " %u / %u identifier table lookups succeeded (%f%%)\n",
7360 NumIdentifierLookupHits, NumIdentifierLookups,
7361 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
7365 std::fprintf(stderr, "\n");
7366 GlobalIndex->printStats();
7369 std::fprintf(stderr, "\n");
7371 std::fprintf(stderr, "\n");
7374 template<typename Key, typename ModuleFile, unsigned InitialCapacity>
7375 LLVM_DUMP_METHOD static void
7376 dumpModuleIDMap(StringRef Name,
7377 const ContinuousRangeMap<Key, ModuleFile *,
7378 InitialCapacity> &Map) {
7379 if (Map.begin() == Map.end())
7382 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
7383 llvm::errs() << Name << ":\n";
7384 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
7386 llvm::errs() << " " << I->first << " -> " << I->second->FileName
7391 LLVM_DUMP_METHOD void ASTReader::dump() {
7392 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
7393 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
7394 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
7395 dumpModuleIDMap("Global type map", GlobalTypeMap);
7396 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
7397 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
7398 dumpModuleIDMap("Global macro map", GlobalMacroMap);
7399 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
7400 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
7401 dumpModuleIDMap("Global preprocessed entity map",
7402 GlobalPreprocessedEntityMap);
7404 llvm::errs() << "\n*** PCH/Modules Loaded:";
7405 for (ModuleFile &M : ModuleMgr)
7409 /// Return the amount of memory used by memory buffers, breaking down
7410 /// by heap-backed versus mmap'ed memory.
7411 void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
7412 for (ModuleFile &I : ModuleMgr) {
7413 if (llvm::MemoryBuffer *buf = I.Buffer) {
7414 size_t bytes = buf->getBufferSize();
7415 switch (buf->getBufferKind()) {
7416 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
7417 sizes.malloc_bytes += bytes;
7419 case llvm::MemoryBuffer::MemoryBuffer_MMap:
7420 sizes.mmap_bytes += bytes;
7427 void ASTReader::InitializeSema(Sema &S) {
7429 S.addExternalSource(this);
7431 // Makes sure any declarations that were deserialized "too early"
7432 // still get added to the identifier's declaration chains.
7433 for (uint64_t ID : PreloadedDeclIDs) {
7434 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
7435 pushExternalDeclIntoScope(D, D->getDeclName());
7437 PreloadedDeclIDs.clear();
7439 // FIXME: What happens if these are changed by a module import?
7440 if (!FPPragmaOptions.empty()) {
7441 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
7442 SemaObj->FPFeatures = FPOptions(FPPragmaOptions[0]);
7445 SemaObj->OpenCLFeatures.copy(OpenCLExtensions);
7446 SemaObj->OpenCLTypeExtMap = OpenCLTypeExtMap;
7447 SemaObj->OpenCLDeclExtMap = OpenCLDeclExtMap;
7452 void ASTReader::UpdateSema() {
7453 assert(SemaObj && "no Sema to update");
7455 // Load the offsets of the declarations that Sema references.
7456 // They will be lazily deserialized when needed.
7457 if (!SemaDeclRefs.empty()) {
7458 assert(SemaDeclRefs.size() % 3 == 0);
7459 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 3) {
7460 if (!SemaObj->StdNamespace)
7461 SemaObj->StdNamespace = SemaDeclRefs[I];
7462 if (!SemaObj->StdBadAlloc)
7463 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
7464 if (!SemaObj->StdAlignValT)
7465 SemaObj->StdAlignValT = SemaDeclRefs[I+2];
7467 SemaDeclRefs.clear();
7470 // Update the state of pragmas. Use the same API as if we had encountered the
7471 // pragma in the source.
7472 if(OptimizeOffPragmaLocation.isValid())
7473 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
7474 if (PragmaMSStructState != -1)
7475 SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState);
7476 if (PointersToMembersPragmaLocation.isValid()) {
7477 SemaObj->ActOnPragmaMSPointersToMembers(
7478 (LangOptions::PragmaMSPointersToMembersKind)
7479 PragmaMSPointersToMembersState,
7480 PointersToMembersPragmaLocation);
7482 SemaObj->ForceCUDAHostDeviceDepth = ForceCUDAHostDeviceDepth;
7484 if (PragmaPackCurrentValue) {
7485 // The bottom of the stack might have a default value. It must be adjusted
7486 // to the current value to ensure that the packing state is preserved after
7487 // popping entries that were included/imported from a PCH/module.
7488 bool DropFirst = false;
7489 if (!PragmaPackStack.empty() &&
7490 PragmaPackStack.front().Location.isInvalid()) {
7491 assert(PragmaPackStack.front().Value == SemaObj->PackStack.DefaultValue &&
7492 "Expected a default alignment value");
7493 SemaObj->PackStack.Stack.emplace_back(
7494 PragmaPackStack.front().SlotLabel, SemaObj->PackStack.CurrentValue,
7495 SemaObj->PackStack.CurrentPragmaLocation);
7498 for (const auto &Entry :
7499 llvm::makeArrayRef(PragmaPackStack).drop_front(DropFirst ? 1 : 0))
7500 SemaObj->PackStack.Stack.emplace_back(Entry.SlotLabel, Entry.Value,
7502 if (PragmaPackCurrentLocation.isInvalid()) {
7503 assert(*PragmaPackCurrentValue == SemaObj->PackStack.DefaultValue &&
7504 "Expected a default alignment value");
7505 // Keep the current values.
7507 SemaObj->PackStack.CurrentValue = *PragmaPackCurrentValue;
7508 SemaObj->PackStack.CurrentPragmaLocation = PragmaPackCurrentLocation;
7513 IdentifierInfo *ASTReader::get(StringRef Name) {
7514 // Note that we are loading an identifier.
7515 Deserializing AnIdentifier(this);
7517 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
7518 NumIdentifierLookups,
7519 NumIdentifierLookupHits);
7521 // We don't need to do identifier table lookups in C++ modules (we preload
7522 // all interesting declarations, and don't need to use the scope for name
7523 // lookups). Perform the lookup in PCH files, though, since we don't build
7524 // a complete initial identifier table if we're carrying on from a PCH.
7525 if (Context.getLangOpts().CPlusPlus) {
7526 for (auto F : ModuleMgr.pch_modules())
7530 // If there is a global index, look there first to determine which modules
7531 // provably do not have any results for this identifier.
7532 GlobalModuleIndex::HitSet Hits;
7533 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
7534 if (!loadGlobalIndex()) {
7535 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
7540 ModuleMgr.visit(Visitor, HitsPtr);
7543 IdentifierInfo *II = Visitor.getIdentifierInfo();
7544 markIdentifierUpToDate(II);
7550 /// \brief An identifier-lookup iterator that enumerates all of the
7551 /// identifiers stored within a set of AST files.
7552 class ASTIdentifierIterator : public IdentifierIterator {
7553 /// \brief The AST reader whose identifiers are being enumerated.
7554 const ASTReader &Reader;
7556 /// \brief The current index into the chain of AST files stored in
7560 /// \brief The current position within the identifier lookup table
7561 /// of the current AST file.
7562 ASTIdentifierLookupTable::key_iterator Current;
7564 /// \brief The end position within the identifier lookup table of
7565 /// the current AST file.
7566 ASTIdentifierLookupTable::key_iterator End;
7568 /// \brief Whether to skip any modules in the ASTReader.
7572 explicit ASTIdentifierIterator(const ASTReader &Reader,
7573 bool SkipModules = false);
7575 StringRef Next() override;
7578 } // end namespace clang
7580 ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader,
7582 : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) {
7585 StringRef ASTIdentifierIterator::Next() {
7586 while (Current == End) {
7587 // If we have exhausted all of our AST files, we're done.
7592 ModuleFile &F = Reader.ModuleMgr[Index];
7593 if (SkipModules && F.isModule())
7596 ASTIdentifierLookupTable *IdTable =
7597 (ASTIdentifierLookupTable *)F.IdentifierLookupTable;
7598 Current = IdTable->key_begin();
7599 End = IdTable->key_end();
7602 // We have any identifiers remaining in the current AST file; return
7604 StringRef Result = *Current;
7611 /// A utility for appending two IdentifierIterators.
7612 class ChainedIdentifierIterator : public IdentifierIterator {
7613 std::unique_ptr<IdentifierIterator> Current;
7614 std::unique_ptr<IdentifierIterator> Queued;
7617 ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First,
7618 std::unique_ptr<IdentifierIterator> Second)
7619 : Current(std::move(First)), Queued(std::move(Second)) {}
7621 StringRef Next() override {
7625 StringRef result = Current->Next();
7626 if (!result.empty())
7629 // Try the queued iterator, which may itself be empty.
7631 std::swap(Current, Queued);
7636 } // end anonymous namespace.
7638 IdentifierIterator *ASTReader::getIdentifiers() {
7639 if (!loadGlobalIndex()) {
7640 std::unique_ptr<IdentifierIterator> ReaderIter(
7641 new ASTIdentifierIterator(*this, /*SkipModules=*/true));
7642 std::unique_ptr<IdentifierIterator> ModulesIter(
7643 GlobalIndex->createIdentifierIterator());
7644 return new ChainedIdentifierIterator(std::move(ReaderIter),
7645 std::move(ModulesIter));
7648 return new ASTIdentifierIterator(*this);
7652 namespace serialization {
7654 class ReadMethodPoolVisitor {
7657 unsigned PriorGeneration;
7658 unsigned InstanceBits;
7659 unsigned FactoryBits;
7660 bool InstanceHasMoreThanOneDecl;
7661 bool FactoryHasMoreThanOneDecl;
7662 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
7663 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
7666 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
7667 unsigned PriorGeneration)
7668 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
7669 InstanceBits(0), FactoryBits(0), InstanceHasMoreThanOneDecl(false),
7670 FactoryHasMoreThanOneDecl(false) {}
7672 bool operator()(ModuleFile &M) {
7673 if (!M.SelectorLookupTable)
7676 // If we've already searched this module file, skip it now.
7677 if (M.Generation <= PriorGeneration)
7680 ++Reader.NumMethodPoolTableLookups;
7681 ASTSelectorLookupTable *PoolTable
7682 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
7683 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
7684 if (Pos == PoolTable->end())
7687 ++Reader.NumMethodPoolTableHits;
7688 ++Reader.NumSelectorsRead;
7689 // FIXME: Not quite happy with the statistics here. We probably should
7690 // disable this tracking when called via LoadSelector.
7691 // Also, should entries without methods count as misses?
7692 ++Reader.NumMethodPoolEntriesRead;
7693 ASTSelectorLookupTrait::data_type Data = *Pos;
7694 if (Reader.DeserializationListener)
7695 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
7697 InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
7698 FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
7699 InstanceBits = Data.InstanceBits;
7700 FactoryBits = Data.FactoryBits;
7701 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
7702 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
7706 /// \brief Retrieve the instance methods found by this visitor.
7707 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
7708 return InstanceMethods;
7711 /// \brief Retrieve the instance methods found by this visitor.
7712 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
7713 return FactoryMethods;
7716 unsigned getInstanceBits() const { return InstanceBits; }
7717 unsigned getFactoryBits() const { return FactoryBits; }
7718 bool instanceHasMoreThanOneDecl() const {
7719 return InstanceHasMoreThanOneDecl;
7721 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
7724 } // end namespace serialization
7725 } // end namespace clang
7727 /// \brief Add the given set of methods to the method list.
7728 static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
7729 ObjCMethodList &List) {
7730 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
7731 S.addMethodToGlobalList(&List, Methods[I]);
7735 void ASTReader::ReadMethodPool(Selector Sel) {
7736 // Get the selector generation and update it to the current generation.
7737 unsigned &Generation = SelectorGeneration[Sel];
7738 unsigned PriorGeneration = Generation;
7739 Generation = getGeneration();
7740 SelectorOutOfDate[Sel] = false;
7742 // Search for methods defined with this selector.
7743 ++NumMethodPoolLookups;
7744 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
7745 ModuleMgr.visit(Visitor);
7747 if (Visitor.getInstanceMethods().empty() &&
7748 Visitor.getFactoryMethods().empty())
7751 ++NumMethodPoolHits;
7756 Sema &S = *getSema();
7757 Sema::GlobalMethodPool::iterator Pos
7758 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
7760 Pos->second.first.setBits(Visitor.getInstanceBits());
7761 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
7762 Pos->second.second.setBits(Visitor.getFactoryBits());
7763 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
7765 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
7766 // when building a module we keep every method individually and may need to
7767 // update hasMoreThanOneDecl as we add the methods.
7768 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7769 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
7772 void ASTReader::updateOutOfDateSelector(Selector Sel) {
7773 if (SelectorOutOfDate[Sel])
7774 ReadMethodPool(Sel);
7777 void ASTReader::ReadKnownNamespaces(
7778 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7781 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
7782 if (NamespaceDecl *Namespace
7783 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7784 Namespaces.push_back(Namespace);
7788 void ASTReader::ReadUndefinedButUsed(
7789 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {
7790 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7791 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
7792 SourceLocation Loc =
7793 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
7794 Undefined.insert(std::make_pair(D, Loc));
7798 void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
7799 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
7801 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
7802 FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
7803 uint64_t Count = DelayedDeleteExprs[Idx++];
7804 for (uint64_t C = 0; C < Count; ++C) {
7805 SourceLocation DeleteLoc =
7806 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
7807 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
7808 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
7813 void ASTReader::ReadTentativeDefinitions(
7814 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7815 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7816 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7818 TentativeDefs.push_back(Var);
7820 TentativeDefinitions.clear();
7823 void ASTReader::ReadUnusedFileScopedDecls(
7824 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7825 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7827 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7831 UnusedFileScopedDecls.clear();
7834 void ASTReader::ReadDelegatingConstructors(
7835 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7836 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7837 CXXConstructorDecl *D
7838 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7842 DelegatingCtorDecls.clear();
7845 void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7846 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7848 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7852 ExtVectorDecls.clear();
7855 void ASTReader::ReadUnusedLocalTypedefNameCandidates(
7856 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
7857 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
7859 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
7860 GetDecl(UnusedLocalTypedefNameCandidates[I]));
7864 UnusedLocalTypedefNameCandidates.clear();
7867 void ASTReader::ReadReferencedSelectors(
7868 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7869 if (ReferencedSelectorsData.empty())
7872 // If there are @selector references added them to its pool. This is for
7873 // implementation of -Wselector.
7874 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7876 while (I < DataSize) {
7877 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7878 SourceLocation SelLoc
7879 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7880 Sels.push_back(std::make_pair(Sel, SelLoc));
7882 ReferencedSelectorsData.clear();
7885 void ASTReader::ReadWeakUndeclaredIdentifiers(
7886 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7887 if (WeakUndeclaredIdentifiers.empty())
7890 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
7891 IdentifierInfo *WeakId
7892 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7893 IdentifierInfo *AliasId
7894 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7896 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7897 bool Used = WeakUndeclaredIdentifiers[I++];
7898 WeakInfo WI(AliasId, Loc);
7900 WeakIDs.push_back(std::make_pair(WeakId, WI));
7902 WeakUndeclaredIdentifiers.clear();
7905 void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7906 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7907 ExternalVTableUse VT;
7908 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7909 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7910 VT.DefinitionRequired = VTableUses[Idx++];
7911 VTables.push_back(VT);
7917 void ASTReader::ReadPendingInstantiations(
7918 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7919 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7920 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7922 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7924 Pending.push_back(std::make_pair(D, Loc));
7926 PendingInstantiations.clear();
7929 void ASTReader::ReadLateParsedTemplates(
7930 llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>>
7932 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7934 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7936 auto LT = llvm::make_unique<LateParsedTemplate>();
7937 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7939 ModuleFile *F = getOwningModuleFile(LT->D);
7940 assert(F && "No module");
7942 unsigned TokN = LateParsedTemplates[Idx++];
7943 LT->Toks.reserve(TokN);
7944 for (unsigned T = 0; T < TokN; ++T)
7945 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7947 LPTMap.insert(std::make_pair(FD, std::move(LT)));
7950 LateParsedTemplates.clear();
7953 void ASTReader::LoadSelector(Selector Sel) {
7954 // It would be complicated to avoid reading the methods anyway. So don't.
7955 ReadMethodPool(Sel);
7958 void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7959 assert(ID && "Non-zero identifier ID required");
7960 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7961 IdentifiersLoaded[ID - 1] = II;
7962 if (DeserializationListener)
7963 DeserializationListener->IdentifierRead(ID, II);
7966 /// \brief Set the globally-visible declarations associated with the given
7969 /// If the AST reader is currently in a state where the given declaration IDs
7970 /// cannot safely be resolved, they are queued until it is safe to resolve
7973 /// \param II an IdentifierInfo that refers to one or more globally-visible
7976 /// \param DeclIDs the set of declaration IDs with the name @p II that are
7977 /// visible at global scope.
7979 /// \param Decls if non-null, this vector will be populated with the set of
7980 /// deserialized declarations. These declarations will not be pushed into
7983 ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7984 const SmallVectorImpl<uint32_t> &DeclIDs,
7985 SmallVectorImpl<Decl *> *Decls) {
7986 if (NumCurrentElementsDeserializing && !Decls) {
7987 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
7991 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
7993 // Queue this declaration so that it will be added to the
7994 // translation unit scope and identifier's declaration chain
7995 // once a Sema object is known.
7996 PreloadedDeclIDs.push_back(DeclIDs[I]);
8000 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
8002 // If we're simply supposed to record the declarations, do so now.
8004 Decls->push_back(D);
8008 // Introduce this declaration into the translation-unit scope
8009 // and add it to the declaration chain for this identifier, so
8010 // that (unqualified) name lookup will find it.
8011 pushExternalDeclIntoScope(D, II);
8015 IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
8019 if (IdentifiersLoaded.empty()) {
8020 Error("no identifier table in AST file");
8025 if (!IdentifiersLoaded[ID]) {
8026 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
8027 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
8028 ModuleFile *M = I->second;
8029 unsigned Index = ID - M->BaseIdentifierID;
8030 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
8032 // All of the strings in the AST file are preceded by a 16-bit length.
8033 // Extract that 16-bit length to avoid having to execute strlen().
8034 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
8035 // unsigned integers. This is important to avoid integer overflow when
8036 // we cast them to 'unsigned'.
8037 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
8038 unsigned StrLen = (((unsigned) StrLenPtr[0])
8039 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
8040 auto &II = PP.getIdentifierTable().get(StringRef(Str, StrLen));
8041 IdentifiersLoaded[ID] = &II;
8042 markIdentifierFromAST(*this, II);
8043 if (DeserializationListener)
8044 DeserializationListener->IdentifierRead(ID + 1, &II);
8047 return IdentifiersLoaded[ID];
8050 IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
8051 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
8054 IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
8055 if (LocalID < NUM_PREDEF_IDENT_IDS)
8058 if (!M.ModuleOffsetMap.empty())
8059 ReadModuleOffsetMap(M);
8061 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8062 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
8063 assert(I != M.IdentifierRemap.end()
8064 && "Invalid index into identifier index remap");
8066 return LocalID + I->second;
8069 MacroInfo *ASTReader::getMacro(MacroID ID) {
8073 if (MacrosLoaded.empty()) {
8074 Error("no macro table in AST file");
8078 ID -= NUM_PREDEF_MACRO_IDS;
8079 if (!MacrosLoaded[ID]) {
8080 GlobalMacroMapType::iterator I
8081 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
8082 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
8083 ModuleFile *M = I->second;
8084 unsigned Index = ID - M->BaseMacroID;
8085 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
8087 if (DeserializationListener)
8088 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
8092 return MacrosLoaded[ID];
8095 MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
8096 if (LocalID < NUM_PREDEF_MACRO_IDS)
8099 if (!M.ModuleOffsetMap.empty())
8100 ReadModuleOffsetMap(M);
8102 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8103 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
8104 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
8106 return LocalID + I->second;
8109 serialization::SubmoduleID
8110 ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
8111 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
8114 if (!M.ModuleOffsetMap.empty())
8115 ReadModuleOffsetMap(M);
8117 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8118 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
8119 assert(I != M.SubmoduleRemap.end()
8120 && "Invalid index into submodule index remap");
8122 return LocalID + I->second;
8125 Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
8126 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
8127 assert(GlobalID == 0 && "Unhandled global submodule ID");
8131 if (GlobalID > SubmodulesLoaded.size()) {
8132 Error("submodule ID out of range in AST file");
8136 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
8139 Module *ASTReader::getModule(unsigned ID) {
8140 return getSubmodule(ID);
8143 ModuleFile *ASTReader::getLocalModuleFile(ModuleFile &F, unsigned ID) {
8145 // It's a module, look it up by submodule ID.
8146 auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(F, ID >> 1));
8147 return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
8149 // It's a prefix (preamble, PCH, ...). Look it up by index.
8150 unsigned IndexFromEnd = ID >> 1;
8151 assert(IndexFromEnd && "got reference to unknown module file");
8152 return getModuleManager().pch_modules().end()[-IndexFromEnd];
8156 unsigned ASTReader::getModuleFileID(ModuleFile *F) {
8160 // For a file representing a module, use the submodule ID of the top-level
8161 // module as the file ID. For any other kind of file, the number of such
8162 // files loaded beforehand will be the same on reload.
8163 // FIXME: Is this true even if we have an explicit module file and a PCH?
8165 return ((F->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
8167 auto PCHModules = getModuleManager().pch_modules();
8168 auto I = std::find(PCHModules.begin(), PCHModules.end(), F);
8169 assert(I != PCHModules.end() && "emitting reference to unknown file");
8170 return (I - PCHModules.end()) << 1;
8173 llvm::Optional<ExternalASTSource::ASTSourceDescriptor>
8174 ASTReader::getSourceDescriptor(unsigned ID) {
8175 if (const Module *M = getSubmodule(ID))
8176 return ExternalASTSource::ASTSourceDescriptor(*M);
8178 // If there is only a single PCH, return it instead.
8179 // Chained PCH are not suported.
8180 const auto &PCHChain = ModuleMgr.pch_modules();
8181 if (std::distance(std::begin(PCHChain), std::end(PCHChain))) {
8182 ModuleFile &MF = ModuleMgr.getPrimaryModule();
8183 StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName);
8184 StringRef FileName = llvm::sys::path::filename(MF.FileName);
8185 return ASTReader::ASTSourceDescriptor(ModuleName, MF.OriginalDir, FileName,
8191 ExternalASTSource::ExtKind ASTReader::hasExternalDefinitions(const Decl *FD) {
8192 auto I = BodySource.find(FD);
8193 if (I == BodySource.end())
8194 return EK_ReplyHazy;
8195 return I->second ? EK_Never : EK_Always;
8198 Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
8199 return DecodeSelector(getGlobalSelectorID(M, LocalID));
8202 Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
8206 if (ID > SelectorsLoaded.size()) {
8207 Error("selector ID out of range in AST file");
8211 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
8212 // Load this selector from the selector table.
8213 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
8214 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
8215 ModuleFile &M = *I->second;
8216 ASTSelectorLookupTrait Trait(*this, M);
8217 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
8218 SelectorsLoaded[ID - 1] =
8219 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
8220 if (DeserializationListener)
8221 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
8224 return SelectorsLoaded[ID - 1];
8227 Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
8228 return DecodeSelector(ID);
8231 uint32_t ASTReader::GetNumExternalSelectors() {
8232 // ID 0 (the null selector) is considered an external selector.
8233 return getTotalNumSelectors() + 1;
8236 serialization::SelectorID
8237 ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
8238 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
8241 if (!M.ModuleOffsetMap.empty())
8242 ReadModuleOffsetMap(M);
8244 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8245 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
8246 assert(I != M.SelectorRemap.end()
8247 && "Invalid index into selector index remap");
8249 return LocalID + I->second;
8253 ASTReader::ReadDeclarationName(ModuleFile &F,
8254 const RecordData &Record, unsigned &Idx) {
8255 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
8257 case DeclarationName::Identifier:
8258 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
8260 case DeclarationName::ObjCZeroArgSelector:
8261 case DeclarationName::ObjCOneArgSelector:
8262 case DeclarationName::ObjCMultiArgSelector:
8263 return DeclarationName(ReadSelector(F, Record, Idx));
8265 case DeclarationName::CXXConstructorName:
8266 return Context.DeclarationNames.getCXXConstructorName(
8267 Context.getCanonicalType(readType(F, Record, Idx)));
8269 case DeclarationName::CXXDestructorName:
8270 return Context.DeclarationNames.getCXXDestructorName(
8271 Context.getCanonicalType(readType(F, Record, Idx)));
8273 case DeclarationName::CXXDeductionGuideName:
8274 return Context.DeclarationNames.getCXXDeductionGuideName(
8275 ReadDeclAs<TemplateDecl>(F, Record, Idx));
8277 case DeclarationName::CXXConversionFunctionName:
8278 return Context.DeclarationNames.getCXXConversionFunctionName(
8279 Context.getCanonicalType(readType(F, Record, Idx)));
8281 case DeclarationName::CXXOperatorName:
8282 return Context.DeclarationNames.getCXXOperatorName(
8283 (OverloadedOperatorKind)Record[Idx++]);
8285 case DeclarationName::CXXLiteralOperatorName:
8286 return Context.DeclarationNames.getCXXLiteralOperatorName(
8287 GetIdentifierInfo(F, Record, Idx));
8289 case DeclarationName::CXXUsingDirective:
8290 return DeclarationName::getUsingDirectiveName();
8293 llvm_unreachable("Invalid NameKind!");
8296 void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
8297 DeclarationNameLoc &DNLoc,
8298 DeclarationName Name,
8299 const RecordData &Record, unsigned &Idx) {
8300 switch (Name.getNameKind()) {
8301 case DeclarationName::CXXConstructorName:
8302 case DeclarationName::CXXDestructorName:
8303 case DeclarationName::CXXConversionFunctionName:
8304 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
8307 case DeclarationName::CXXOperatorName:
8308 DNLoc.CXXOperatorName.BeginOpNameLoc
8309 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
8310 DNLoc.CXXOperatorName.EndOpNameLoc
8311 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
8314 case DeclarationName::CXXLiteralOperatorName:
8315 DNLoc.CXXLiteralOperatorName.OpNameLoc
8316 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
8319 case DeclarationName::Identifier:
8320 case DeclarationName::ObjCZeroArgSelector:
8321 case DeclarationName::ObjCOneArgSelector:
8322 case DeclarationName::ObjCMultiArgSelector:
8323 case DeclarationName::CXXUsingDirective:
8324 case DeclarationName::CXXDeductionGuideName:
8329 void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
8330 DeclarationNameInfo &NameInfo,
8331 const RecordData &Record, unsigned &Idx) {
8332 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
8333 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
8334 DeclarationNameLoc DNLoc;
8335 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
8336 NameInfo.setInfo(DNLoc);
8339 void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
8340 const RecordData &Record, unsigned &Idx) {
8341 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
8342 unsigned NumTPLists = Record[Idx++];
8343 Info.NumTemplParamLists = NumTPLists;
8345 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
8346 for (unsigned i = 0; i != NumTPLists; ++i)
8347 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
8352 ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
8354 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
8356 case TemplateName::Template:
8357 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
8359 case TemplateName::OverloadedTemplate: {
8360 unsigned size = Record[Idx++];
8361 UnresolvedSet<8> Decls;
8363 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
8365 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
8368 case TemplateName::QualifiedTemplate: {
8369 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
8370 bool hasTemplKeyword = Record[Idx++];
8371 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
8372 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
8375 case TemplateName::DependentTemplate: {
8376 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
8377 if (Record[Idx++]) // isIdentifier
8378 return Context.getDependentTemplateName(NNS,
8379 GetIdentifierInfo(F, Record,
8381 return Context.getDependentTemplateName(NNS,
8382 (OverloadedOperatorKind)Record[Idx++]);
8385 case TemplateName::SubstTemplateTemplateParm: {
8386 TemplateTemplateParmDecl *param
8387 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
8388 if (!param) return TemplateName();
8389 TemplateName replacement = ReadTemplateName(F, Record, Idx);
8390 return Context.getSubstTemplateTemplateParm(param, replacement);
8393 case TemplateName::SubstTemplateTemplateParmPack: {
8394 TemplateTemplateParmDecl *Param
8395 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
8397 return TemplateName();
8399 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
8400 if (ArgPack.getKind() != TemplateArgument::Pack)
8401 return TemplateName();
8403 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
8407 llvm_unreachable("Unhandled template name kind!");
8410 TemplateArgument ASTReader::ReadTemplateArgument(ModuleFile &F,
8411 const RecordData &Record,
8413 bool Canonicalize) {
8415 // The caller wants a canonical template argument. Sometimes the AST only
8416 // wants template arguments in canonical form (particularly as the template
8417 // argument lists of template specializations) so ensure we preserve that
8418 // canonical form across serialization.
8419 TemplateArgument Arg = ReadTemplateArgument(F, Record, Idx, false);
8420 return Context.getCanonicalTemplateArgument(Arg);
8423 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
8425 case TemplateArgument::Null:
8426 return TemplateArgument();
8427 case TemplateArgument::Type:
8428 return TemplateArgument(readType(F, Record, Idx));
8429 case TemplateArgument::Declaration: {
8430 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
8431 return TemplateArgument(D, readType(F, Record, Idx));
8433 case TemplateArgument::NullPtr:
8434 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
8435 case TemplateArgument::Integral: {
8436 llvm::APSInt Value = ReadAPSInt(Record, Idx);
8437 QualType T = readType(F, Record, Idx);
8438 return TemplateArgument(Context, Value, T);
8440 case TemplateArgument::Template:
8441 return TemplateArgument(ReadTemplateName(F, Record, Idx));
8442 case TemplateArgument::TemplateExpansion: {
8443 TemplateName Name = ReadTemplateName(F, Record, Idx);
8444 Optional<unsigned> NumTemplateExpansions;
8445 if (unsigned NumExpansions = Record[Idx++])
8446 NumTemplateExpansions = NumExpansions - 1;
8447 return TemplateArgument(Name, NumTemplateExpansions);
8449 case TemplateArgument::Expression:
8450 return TemplateArgument(ReadExpr(F));
8451 case TemplateArgument::Pack: {
8452 unsigned NumArgs = Record[Idx++];
8453 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
8454 for (unsigned I = 0; I != NumArgs; ++I)
8455 Args[I] = ReadTemplateArgument(F, Record, Idx);
8456 return TemplateArgument(llvm::makeArrayRef(Args, NumArgs));
8460 llvm_unreachable("Unhandled template argument kind!");
8463 TemplateParameterList *
8464 ASTReader::ReadTemplateParameterList(ModuleFile &F,
8465 const RecordData &Record, unsigned &Idx) {
8466 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
8467 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
8468 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
8470 unsigned NumParams = Record[Idx++];
8471 SmallVector<NamedDecl *, 16> Params;
8472 Params.reserve(NumParams);
8474 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
8477 TemplateParameterList* TemplateParams =
8478 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
8479 Params, RAngleLoc, nullptr);
8480 return TemplateParams;
8485 ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
8486 ModuleFile &F, const RecordData &Record,
8487 unsigned &Idx, bool Canonicalize) {
8488 unsigned NumTemplateArgs = Record[Idx++];
8489 TemplArgs.reserve(NumTemplateArgs);
8490 while (NumTemplateArgs--)
8491 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx, Canonicalize));
8494 /// \brief Read a UnresolvedSet structure.
8495 void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
8496 const RecordData &Record, unsigned &Idx) {
8497 unsigned NumDecls = Record[Idx++];
8498 Set.reserve(Context, NumDecls);
8499 while (NumDecls--) {
8500 DeclID ID = ReadDeclID(F, Record, Idx);
8501 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
8502 Set.addLazyDecl(Context, ID, AS);
8507 ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
8508 const RecordData &Record, unsigned &Idx) {
8509 bool isVirtual = static_cast<bool>(Record[Idx++]);
8510 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
8511 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
8512 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
8513 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
8514 SourceRange Range = ReadSourceRange(F, Record, Idx);
8515 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
8516 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
8518 Result.setInheritConstructors(inheritConstructors);
8522 CXXCtorInitializer **
8523 ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
8525 unsigned NumInitializers = Record[Idx++];
8526 assert(NumInitializers && "wrote ctor initializers but have no inits");
8527 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
8528 for (unsigned i = 0; i != NumInitializers; ++i) {
8529 TypeSourceInfo *TInfo = nullptr;
8530 bool IsBaseVirtual = false;
8531 FieldDecl *Member = nullptr;
8532 IndirectFieldDecl *IndirectMember = nullptr;
8534 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
8536 case CTOR_INITIALIZER_BASE:
8537 TInfo = GetTypeSourceInfo(F, Record, Idx);
8538 IsBaseVirtual = Record[Idx++];
8541 case CTOR_INITIALIZER_DELEGATING:
8542 TInfo = GetTypeSourceInfo(F, Record, Idx);
8545 case CTOR_INITIALIZER_MEMBER:
8546 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
8549 case CTOR_INITIALIZER_INDIRECT_MEMBER:
8550 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
8554 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
8555 Expr *Init = ReadExpr(F);
8556 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
8557 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
8559 CXXCtorInitializer *BOMInit;
8560 if (Type == CTOR_INITIALIZER_BASE)
8561 BOMInit = new (Context)
8562 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
8563 RParenLoc, MemberOrEllipsisLoc);
8564 else if (Type == CTOR_INITIALIZER_DELEGATING)
8565 BOMInit = new (Context)
8566 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
8568 BOMInit = new (Context)
8569 CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc, LParenLoc,
8572 BOMInit = new (Context)
8573 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
8574 LParenLoc, Init, RParenLoc);
8576 if (/*IsWritten*/Record[Idx++]) {
8577 unsigned SourceOrder = Record[Idx++];
8578 BOMInit->setSourceOrder(SourceOrder);
8581 CtorInitializers[i] = BOMInit;
8584 return CtorInitializers;
8587 NestedNameSpecifier *
8588 ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
8589 const RecordData &Record, unsigned &Idx) {
8590 unsigned N = Record[Idx++];
8591 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
8592 for (unsigned I = 0; I != N; ++I) {
8593 NestedNameSpecifier::SpecifierKind Kind
8594 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8596 case NestedNameSpecifier::Identifier: {
8597 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
8598 NNS = NestedNameSpecifier::Create(Context, Prev, II);
8602 case NestedNameSpecifier::Namespace: {
8603 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8604 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
8608 case NestedNameSpecifier::NamespaceAlias: {
8609 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8610 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
8614 case NestedNameSpecifier::TypeSpec:
8615 case NestedNameSpecifier::TypeSpecWithTemplate: {
8616 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
8620 bool Template = Record[Idx++];
8621 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
8625 case NestedNameSpecifier::Global: {
8626 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
8627 // No associated value, and there can't be a prefix.
8631 case NestedNameSpecifier::Super: {
8632 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8633 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
8642 NestedNameSpecifierLoc
8643 ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
8645 unsigned N = Record[Idx++];
8646 NestedNameSpecifierLocBuilder Builder;
8647 for (unsigned I = 0; I != N; ++I) {
8648 NestedNameSpecifier::SpecifierKind Kind
8649 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8651 case NestedNameSpecifier::Identifier: {
8652 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
8653 SourceRange Range = ReadSourceRange(F, Record, Idx);
8654 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
8658 case NestedNameSpecifier::Namespace: {
8659 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8660 SourceRange Range = ReadSourceRange(F, Record, Idx);
8661 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
8665 case NestedNameSpecifier::NamespaceAlias: {
8666 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8667 SourceRange Range = ReadSourceRange(F, Record, Idx);
8668 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
8672 case NestedNameSpecifier::TypeSpec:
8673 case NestedNameSpecifier::TypeSpecWithTemplate: {
8674 bool Template = Record[Idx++];
8675 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
8677 return NestedNameSpecifierLoc();
8678 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8680 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
8681 Builder.Extend(Context,
8682 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
8683 T->getTypeLoc(), ColonColonLoc);
8687 case NestedNameSpecifier::Global: {
8688 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8689 Builder.MakeGlobal(Context, ColonColonLoc);
8693 case NestedNameSpecifier::Super: {
8694 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8695 SourceRange Range = ReadSourceRange(F, Record, Idx);
8696 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
8702 return Builder.getWithLocInContext(Context);
8706 ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
8708 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
8709 SourceLocation end = ReadSourceLocation(F, Record, Idx);
8710 return SourceRange(beg, end);
8713 /// \brief Read an integral value
8714 llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
8715 unsigned BitWidth = Record[Idx++];
8716 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
8717 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
8722 /// \brief Read a signed integral value
8723 llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
8724 bool isUnsigned = Record[Idx++];
8725 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
8728 /// \brief Read a floating-point value
8729 llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
8730 const llvm::fltSemantics &Sem,
8732 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
8735 // \brief Read a string
8736 std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
8737 unsigned Len = Record[Idx++];
8738 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
8743 std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
8745 std::string Filename = ReadString(Record, Idx);
8746 ResolveImportedPath(F, Filename);
8750 VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
8752 unsigned Major = Record[Idx++];
8753 unsigned Minor = Record[Idx++];
8754 unsigned Subminor = Record[Idx++];
8756 return VersionTuple(Major);
8758 return VersionTuple(Major, Minor - 1);
8759 return VersionTuple(Major, Minor - 1, Subminor - 1);
8762 CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
8763 const RecordData &Record,
8765 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
8766 return CXXTemporary::Create(Context, Decl);
8769 DiagnosticBuilder ASTReader::Diag(unsigned DiagID) const {
8770 return Diag(CurrentImportLoc, DiagID);
8773 DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) const {
8774 return Diags.Report(Loc, DiagID);
8777 /// \brief Retrieve the identifier table associated with the
8779 IdentifierTable &ASTReader::getIdentifierTable() {
8780 return PP.getIdentifierTable();
8783 /// \brief Record that the given ID maps to the given switch-case
8785 void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
8786 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
8787 "Already have a SwitchCase with this ID");
8788 (*CurrSwitchCaseStmts)[ID] = SC;
8791 /// \brief Retrieve the switch-case statement with the given ID.
8792 SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
8793 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
8794 return (*CurrSwitchCaseStmts)[ID];
8797 void ASTReader::ClearSwitchCaseIDs() {
8798 CurrSwitchCaseStmts->clear();
8801 void ASTReader::ReadComments() {
8802 std::vector<RawComment *> Comments;
8803 for (SmallVectorImpl<std::pair<BitstreamCursor,
8804 serialization::ModuleFile *> >::iterator
8805 I = CommentsCursors.begin(),
8806 E = CommentsCursors.end();
8809 BitstreamCursor &Cursor = I->first;
8810 serialization::ModuleFile &F = *I->second;
8811 SavedStreamPosition SavedPosition(Cursor);
8815 llvm::BitstreamEntry Entry =
8816 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
8818 switch (Entry.Kind) {
8819 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
8820 case llvm::BitstreamEntry::Error:
8821 Error("malformed block record in AST file");
8823 case llvm::BitstreamEntry::EndBlock:
8825 case llvm::BitstreamEntry::Record:
8826 // The interesting case.
8832 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
8833 case COMMENTS_RAW_COMMENT: {
8835 SourceRange SR = ReadSourceRange(F, Record, Idx);
8836 RawComment::CommentKind Kind =
8837 (RawComment::CommentKind) Record[Idx++];
8838 bool IsTrailingComment = Record[Idx++];
8839 bool IsAlmostTrailingComment = Record[Idx++];
8840 Comments.push_back(new (Context) RawComment(
8841 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8842 Context.getLangOpts().CommentOpts.ParseAllComments));
8848 // De-serialized SourceLocations get negative FileIDs for other modules,
8849 // potentially invalidating the original order. Sort it again.
8850 std::sort(Comments.begin(), Comments.end(),
8851 BeforeThanCompare<RawComment>(SourceMgr));
8852 Context.Comments.addDeserializedComments(Comments);
8856 void ASTReader::visitInputFiles(serialization::ModuleFile &MF,
8857 bool IncludeSystem, bool Complain,
8858 llvm::function_ref<void(const serialization::InputFile &IF,
8859 bool isSystem)> Visitor) {
8860 unsigned NumUserInputs = MF.NumUserInputFiles;
8861 unsigned NumInputs = MF.InputFilesLoaded.size();
8862 assert(NumUserInputs <= NumInputs);
8863 unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
8864 for (unsigned I = 0; I < N; ++I) {
8865 bool IsSystem = I >= NumUserInputs;
8866 InputFile IF = getInputFile(MF, I+1, Complain);
8867 Visitor(IF, IsSystem);
8871 std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
8872 // If we know the owning module, use it.
8873 if (Module *M = D->getImportedOwningModule())
8874 return M->getFullModuleName();
8876 // Otherwise, use the name of the top-level module the decl is within.
8877 if (ModuleFile *M = getOwningModuleFile(D))
8878 return M->ModuleName;
8880 // Not from a module.
8884 void ASTReader::finishPendingActions() {
8885 while (!PendingIdentifierInfos.empty() ||
8886 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
8887 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
8888 !PendingUpdateRecords.empty()) {
8889 // If any identifiers with corresponding top-level declarations have
8890 // been loaded, load those declarations now.
8891 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8893 TopLevelDeclsMap TopLevelDecls;
8895 while (!PendingIdentifierInfos.empty()) {
8896 IdentifierInfo *II = PendingIdentifierInfos.back().first;
8897 SmallVector<uint32_t, 4> DeclIDs =
8898 std::move(PendingIdentifierInfos.back().second);
8899 PendingIdentifierInfos.pop_back();
8901 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
8904 // For each decl chain that we wanted to complete while deserializing, mark
8905 // it as "still needs to be completed".
8906 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8907 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8909 PendingIncompleteDeclChains.clear();
8911 // Load pending declaration chains.
8912 for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
8913 loadPendingDeclChain(PendingDeclChains[I].first, PendingDeclChains[I].second);
8914 PendingDeclChains.clear();
8916 // Make the most recent of the top-level declarations visible.
8917 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8918 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
8919 IdentifierInfo *II = TLD->first;
8920 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
8921 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
8925 // Load any pending macro definitions.
8926 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
8927 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8928 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8929 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8930 // Initialize the macro history from chained-PCHs ahead of module imports.
8931 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
8933 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
8934 if (!Info.M->isModule())
8935 resolvePendingMacro(II, Info);
8937 // Handle module imports.
8938 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
8940 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
8941 if (Info.M->isModule())
8942 resolvePendingMacro(II, Info);
8945 PendingMacroIDs.clear();
8947 // Wire up the DeclContexts for Decls that we delayed setting until
8948 // recursive loading is completed.
8949 while (!PendingDeclContextInfos.empty()) {
8950 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8951 PendingDeclContextInfos.pop_front();
8952 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8953 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8954 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8957 // Perform any pending declaration updates.
8958 while (!PendingUpdateRecords.empty()) {
8959 auto Update = PendingUpdateRecords.pop_back_val();
8960 ReadingKindTracker ReadingKind(Read_Decl, *this);
8961 loadDeclUpdateRecords(Update);
8965 // At this point, all update records for loaded decls are in place, so any
8966 // fake class definitions should have become real.
8967 assert(PendingFakeDefinitionData.empty() &&
8968 "faked up a class definition but never saw the real one");
8970 // If we deserialized any C++ or Objective-C class definitions, any
8971 // Objective-C protocol definitions, or any redeclarable templates, make sure
8972 // that all redeclarations point to the definitions. Note that this can only
8973 // happen now, after the redeclaration chains have been fully wired.
8974 for (Decl *D : PendingDefinitions) {
8975 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
8976 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
8977 // Make sure that the TagType points at the definition.
8978 const_cast<TagType*>(TagT)->decl = TD;
8981 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
8982 for (auto *R = getMostRecentExistingDecl(RD); R;
8983 R = R->getPreviousDecl()) {
8985 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
8986 "declaration thinks it's the definition but it isn't");
8987 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
8994 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
8995 // Make sure that the ObjCInterfaceType points at the definition.
8996 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8999 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
9000 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
9005 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
9006 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
9007 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
9012 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
9013 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
9014 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
9016 PendingDefinitions.clear();
9018 // Load the bodies of any functions or methods we've encountered. We do
9019 // this now (delayed) so that we can be sure that the declaration chains
9020 // have been fully wired up (hasBody relies on this).
9021 // FIXME: We shouldn't require complete redeclaration chains here.
9022 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
9023 PBEnd = PendingBodies.end();
9024 PB != PBEnd; ++PB) {
9025 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
9026 // FIXME: Check for =delete/=default?
9027 // FIXME: Complain about ODR violations here?
9028 const FunctionDecl *Defn = nullptr;
9029 if (!getContext().getLangOpts().Modules || !FD->hasBody(Defn)) {
9030 FD->setLazyBody(PB->second);
9032 mergeDefinitionVisibility(const_cast<FunctionDecl*>(Defn), FD);
9036 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
9037 if (!getContext().getLangOpts().Modules || !MD->hasBody())
9038 MD->setLazyBody(PB->second);
9040 PendingBodies.clear();
9043 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
9044 getContext().deduplicateMergedDefinitonsFor(ND);
9045 PendingMergedDefinitionsToDeduplicate.clear();
9048 void ASTReader::diagnoseOdrViolations() {
9049 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty())
9052 // Trigger the import of the full definition of each class that had any
9053 // odr-merging problems, so we can produce better diagnostics for them.
9054 // These updates may in turn find and diagnose some ODR failures, so take
9055 // ownership of the set first.
9056 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
9057 PendingOdrMergeFailures.clear();
9058 for (auto &Merge : OdrMergeFailures) {
9059 Merge.first->buildLookup();
9060 Merge.first->decls_begin();
9061 Merge.first->bases_begin();
9062 Merge.first->vbases_begin();
9063 for (auto *RD : Merge.second) {
9070 // For each declaration from a merged context, check that the canonical
9071 // definition of that context also contains a declaration of the same
9074 // Caution: this loop does things that might invalidate iterators into
9075 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
9076 while (!PendingOdrMergeChecks.empty()) {
9077 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
9079 // FIXME: Skip over implicit declarations for now. This matters for things
9080 // like implicitly-declared special member functions. This isn't entirely
9081 // correct; we can end up with multiple unmerged declarations of the same
9083 if (D->isImplicit())
9086 DeclContext *CanonDef = D->getDeclContext();
9089 const Decl *DCanon = D->getCanonicalDecl();
9091 for (auto RI : D->redecls()) {
9092 if (RI->getLexicalDeclContext() == CanonDef) {
9100 // Quick check failed, time to do the slow thing. Note, we can't just
9101 // look up the name of D in CanonDef here, because the member that is
9102 // in CanonDef might not be found by name lookup (it might have been
9103 // replaced by a more recent declaration in the lookup table), and we
9104 // can't necessarily find it in the redeclaration chain because it might
9105 // be merely mergeable, not redeclarable.
9106 llvm::SmallVector<const NamedDecl*, 4> Candidates;
9107 for (auto *CanonMember : CanonDef->decls()) {
9108 if (CanonMember->getCanonicalDecl() == DCanon) {
9109 // This can happen if the declaration is merely mergeable and not
9110 // actually redeclarable (we looked for redeclarations earlier).
9112 // FIXME: We should be able to detect this more efficiently, without
9113 // pulling in all of the members of CanonDef.
9117 if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
9118 if (ND->getDeclName() == D->getDeclName())
9119 Candidates.push_back(ND);
9123 // The AST doesn't like TagDecls becoming invalid after they've been
9124 // completed. We only really need to mark FieldDecls as invalid here.
9125 if (!isa<TagDecl>(D))
9126 D->setInvalidDecl();
9128 // Ensure we don't accidentally recursively enter deserialization while
9129 // we're producing our diagnostic.
9130 Deserializing RecursionGuard(this);
9132 std::string CanonDefModule =
9133 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
9134 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
9135 << D << getOwningModuleNameForDiagnostic(D)
9136 << CanonDef << CanonDefModule.empty() << CanonDefModule;
9138 if (Candidates.empty())
9139 Diag(cast<Decl>(CanonDef)->getLocation(),
9140 diag::note_module_odr_violation_no_possible_decls) << D;
9142 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
9143 Diag(Candidates[I]->getLocation(),
9144 diag::note_module_odr_violation_possible_decl)
9148 DiagnosedOdrMergeFailures.insert(CanonDef);
9152 if (OdrMergeFailures.empty())
9155 // Ensure we don't accidentally recursively enter deserialization while
9156 // we're producing our diagnostics.
9157 Deserializing RecursionGuard(this);
9159 // Issue any pending ODR-failure diagnostics.
9160 for (auto &Merge : OdrMergeFailures) {
9161 // If we've already pointed out a specific problem with this class, don't
9162 // bother issuing a general "something's different" diagnostic.
9163 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
9166 bool Diagnosed = false;
9167 CXXRecordDecl *FirstRecord = Merge.first;
9168 std::string FirstModule = getOwningModuleNameForDiagnostic(FirstRecord);
9169 for (CXXRecordDecl *SecondRecord : Merge.second) {
9170 // Multiple different declarations got merged together; tell the user
9171 // where they came from.
9172 if (FirstRecord == SecondRecord)
9175 std::string SecondModule = getOwningModuleNameForDiagnostic(SecondRecord);
9176 using DeclHashes = llvm::SmallVector<std::pair<Decl *, unsigned>, 4>;
9177 DeclHashes FirstHashes;
9178 DeclHashes SecondHashes;
9181 auto PopulateHashes = [&Hash, FirstRecord](DeclHashes &Hashes,
9182 CXXRecordDecl *Record) {
9183 for (auto *D : Record->decls()) {
9184 // Due to decl merging, the first CXXRecordDecl is the parent of
9185 // Decls in both records.
9186 if (!ODRHash::isWhitelistedDecl(D, FirstRecord))
9190 Hashes.emplace_back(D, Hash.CalculateHash());
9193 PopulateHashes(FirstHashes, FirstRecord);
9194 PopulateHashes(SecondHashes, SecondRecord);
9196 // Used with err_module_odr_violation_mismatch_decl and
9197 // note_module_odr_violation_mismatch_decl
9207 } FirstDiffType = Other,
9208 SecondDiffType = Other;
9210 auto DifferenceSelector = [](Decl *D) {
9211 assert(D && "valid Decl required");
9212 switch (D->getKind()) {
9215 case Decl::AccessSpec:
9216 switch (D->getAccess()) {
9218 return PublicSpecifer;
9220 return PrivateSpecifer;
9222 return ProtectedSpecifer;
9226 llvm_unreachable("Invalid access specifier");
9227 case Decl::StaticAssert:
9228 return StaticAssert;
9231 case Decl::CXXMethod:
9236 Decl *FirstDecl = nullptr;
9237 Decl *SecondDecl = nullptr;
9238 auto FirstIt = FirstHashes.begin();
9239 auto SecondIt = SecondHashes.begin();
9241 // If there is a diagnoseable difference, FirstDiffType and
9242 // SecondDiffType will not be Other and FirstDecl and SecondDecl will be
9243 // filled in if not EndOfClass.
9244 while (FirstIt != FirstHashes.end() || SecondIt != SecondHashes.end()) {
9245 if (FirstIt != FirstHashes.end() && SecondIt != SecondHashes.end() &&
9246 FirstIt->second == SecondIt->second) {
9252 FirstDecl = FirstIt == FirstHashes.end() ? nullptr : FirstIt->first;
9253 SecondDecl = SecondIt == SecondHashes.end() ? nullptr : SecondIt->first;
9255 FirstDiffType = FirstDecl ? DifferenceSelector(FirstDecl) : EndOfClass;
9257 SecondDecl ? DifferenceSelector(SecondDecl) : EndOfClass;
9262 if (FirstDiffType == Other || SecondDiffType == Other) {
9263 // Reaching this point means an unexpected Decl was encountered
9264 // or no difference was detected. This causes a generic error
9265 // message to be emitted.
9266 Diag(FirstRecord->getLocation(),
9267 diag::err_module_odr_violation_different_definitions)
9268 << FirstRecord << FirstModule.empty() << FirstModule;
9270 Diag(SecondRecord->getLocation(),
9271 diag::note_module_odr_violation_different_definitions)
9277 if (FirstDiffType != SecondDiffType) {
9278 SourceLocation FirstLoc;
9279 SourceRange FirstRange;
9280 if (FirstDiffType == EndOfClass) {
9281 FirstLoc = FirstRecord->getBraceRange().getEnd();
9283 FirstLoc = FirstIt->first->getLocation();
9284 FirstRange = FirstIt->first->getSourceRange();
9286 Diag(FirstLoc, diag::err_module_odr_violation_mismatch_decl)
9287 << FirstRecord << FirstModule.empty() << FirstModule << FirstRange
9290 SourceLocation SecondLoc;
9291 SourceRange SecondRange;
9292 if (SecondDiffType == EndOfClass) {
9293 SecondLoc = SecondRecord->getBraceRange().getEnd();
9295 SecondLoc = SecondDecl->getLocation();
9296 SecondRange = SecondDecl->getSourceRange();
9298 Diag(SecondLoc, diag::note_module_odr_violation_mismatch_decl)
9299 << SecondModule << SecondRange << SecondDiffType;
9304 assert(FirstDiffType == SecondDiffType);
9306 // Used with err_module_odr_violation_mismatch_decl_diff and
9307 // note_module_odr_violation_mismatch_decl_diff
9308 enum ODRDeclDifference{
9309 StaticAssertCondition,
9310 StaticAssertMessage,
9311 StaticAssertOnlyMessage,
9314 FieldSingleBitField,
9315 FieldDifferentWidthBitField,
9317 FieldSingleInitializer,
9318 FieldDifferentInitializers,
9326 MethodNumberParameters,
9327 MethodParameterType,
9328 MethodParameterName,
9331 // These lambdas have the common portions of the ODR diagnostics. This
9332 // has the same return as Diag(), so addition parameters can be passed
9333 // in with operator<<
9334 auto ODRDiagError = [FirstRecord, &FirstModule, this](
9335 SourceLocation Loc, SourceRange Range, ODRDeclDifference DiffType) {
9336 return Diag(Loc, diag::err_module_odr_violation_mismatch_decl_diff)
9337 << FirstRecord << FirstModule.empty() << FirstModule << Range
9340 auto ODRDiagNote = [&SecondModule, this](
9341 SourceLocation Loc, SourceRange Range, ODRDeclDifference DiffType) {
9342 return Diag(Loc, diag::note_module_odr_violation_mismatch_decl_diff)
9343 << SecondModule << Range << DiffType;
9346 auto ComputeODRHash = [&Hash](const Stmt* S) {
9350 return Hash.CalculateHash();
9353 auto ComputeQualTypeODRHash = [&Hash](QualType Ty) {
9355 Hash.AddQualType(Ty);
9356 return Hash.CalculateHash();
9359 switch (FirstDiffType) {
9362 case PublicSpecifer:
9363 case PrivateSpecifer:
9364 case ProtectedSpecifer:
9365 llvm_unreachable("Invalid diff type");
9367 case StaticAssert: {
9368 StaticAssertDecl *FirstSA = cast<StaticAssertDecl>(FirstDecl);
9369 StaticAssertDecl *SecondSA = cast<StaticAssertDecl>(SecondDecl);
9371 Expr *FirstExpr = FirstSA->getAssertExpr();
9372 Expr *SecondExpr = SecondSA->getAssertExpr();
9373 unsigned FirstODRHash = ComputeODRHash(FirstExpr);
9374 unsigned SecondODRHash = ComputeODRHash(SecondExpr);
9375 if (FirstODRHash != SecondODRHash) {
9376 ODRDiagError(FirstExpr->getLocStart(), FirstExpr->getSourceRange(),
9377 StaticAssertCondition);
9378 ODRDiagNote(SecondExpr->getLocStart(),
9379 SecondExpr->getSourceRange(), StaticAssertCondition);
9384 StringLiteral *FirstStr = FirstSA->getMessage();
9385 StringLiteral *SecondStr = SecondSA->getMessage();
9386 assert((FirstStr || SecondStr) && "Both messages cannot be empty");
9387 if ((FirstStr && !SecondStr) || (!FirstStr && SecondStr)) {
9388 SourceLocation FirstLoc, SecondLoc;
9389 SourceRange FirstRange, SecondRange;
9391 FirstLoc = FirstStr->getLocStart();
9392 FirstRange = FirstStr->getSourceRange();
9394 FirstLoc = FirstSA->getLocStart();
9395 FirstRange = FirstSA->getSourceRange();
9398 SecondLoc = SecondStr->getLocStart();
9399 SecondRange = SecondStr->getSourceRange();
9401 SecondLoc = SecondSA->getLocStart();
9402 SecondRange = SecondSA->getSourceRange();
9404 ODRDiagError(FirstLoc, FirstRange, StaticAssertOnlyMessage)
9405 << (FirstStr == nullptr);
9406 ODRDiagNote(SecondLoc, SecondRange, StaticAssertOnlyMessage)
9407 << (SecondStr == nullptr);
9412 if (FirstStr && SecondStr &&
9413 FirstStr->getString() != SecondStr->getString()) {
9414 ODRDiagError(FirstStr->getLocStart(), FirstStr->getSourceRange(),
9415 StaticAssertMessage);
9416 ODRDiagNote(SecondStr->getLocStart(), SecondStr->getSourceRange(),
9417 StaticAssertMessage);
9424 FieldDecl *FirstField = cast<FieldDecl>(FirstDecl);
9425 FieldDecl *SecondField = cast<FieldDecl>(SecondDecl);
9426 IdentifierInfo *FirstII = FirstField->getIdentifier();
9427 IdentifierInfo *SecondII = SecondField->getIdentifier();
9428 if (FirstII->getName() != SecondII->getName()) {
9429 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
9432 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
9441 Context.hasSameType(FirstField->getType(), SecondField->getType()));
9443 QualType FirstType = FirstField->getType();
9444 QualType SecondType = SecondField->getType();
9445 if (ComputeQualTypeODRHash(FirstType) !=
9446 ComputeQualTypeODRHash(SecondType)) {
9447 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
9449 << FirstII << FirstType;
9450 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
9452 << SecondII << SecondType;
9458 const bool IsFirstBitField = FirstField->isBitField();
9459 const bool IsSecondBitField = SecondField->isBitField();
9460 if (IsFirstBitField != IsSecondBitField) {
9461 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
9462 FieldSingleBitField)
9463 << FirstII << IsFirstBitField;
9464 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
9465 FieldSingleBitField)
9466 << SecondII << IsSecondBitField;
9471 if (IsFirstBitField && IsSecondBitField) {
9472 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
9473 FieldDifferentWidthBitField)
9474 << FirstII << FirstField->getBitWidth()->getSourceRange();
9475 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
9476 FieldDifferentWidthBitField)
9477 << SecondII << SecondField->getBitWidth()->getSourceRange();
9482 const bool IsFirstMutable = FirstField->isMutable();
9483 const bool IsSecondMutable = SecondField->isMutable();
9484 if (IsFirstMutable != IsSecondMutable) {
9485 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
9487 << FirstII << IsFirstMutable;
9488 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
9490 << SecondII << IsSecondMutable;
9495 const Expr *FirstInitializer = FirstField->getInClassInitializer();
9496 const Expr *SecondInitializer = SecondField->getInClassInitializer();
9497 if ((!FirstInitializer && SecondInitializer) ||
9498 (FirstInitializer && !SecondInitializer)) {
9499 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
9500 FieldSingleInitializer)
9501 << FirstII << (FirstInitializer != nullptr);
9502 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
9503 FieldSingleInitializer)
9504 << SecondII << (SecondInitializer != nullptr);
9509 if (FirstInitializer && SecondInitializer) {
9510 unsigned FirstInitHash = ComputeODRHash(FirstInitializer);
9511 unsigned SecondInitHash = ComputeODRHash(SecondInitializer);
9512 if (FirstInitHash != SecondInitHash) {
9513 ODRDiagError(FirstField->getLocation(),
9514 FirstField->getSourceRange(),
9515 FieldDifferentInitializers)
9516 << FirstII << FirstInitializer->getSourceRange();
9517 ODRDiagNote(SecondField->getLocation(),
9518 SecondField->getSourceRange(),
9519 FieldDifferentInitializers)
9520 << SecondII << SecondInitializer->getSourceRange();
9529 const CXXMethodDecl *FirstMethod = cast<CXXMethodDecl>(FirstDecl);
9530 const CXXMethodDecl *SecondMethod = cast<CXXMethodDecl>(SecondDecl);
9531 auto FirstName = FirstMethod->getDeclName();
9532 auto SecondName = SecondMethod->getDeclName();
9533 if (FirstName != SecondName) {
9534 ODRDiagError(FirstMethod->getLocation(),
9535 FirstMethod->getSourceRange(), MethodName)
9537 ODRDiagNote(SecondMethod->getLocation(),
9538 SecondMethod->getSourceRange(), MethodName)
9545 const bool FirstDeleted = FirstMethod->isDeleted();
9546 const bool SecondDeleted = SecondMethod->isDeleted();
9547 if (FirstDeleted != SecondDeleted) {
9548 ODRDiagError(FirstMethod->getLocation(),
9549 FirstMethod->getSourceRange(), MethodDeleted)
9550 << FirstName << FirstDeleted;
9552 ODRDiagNote(SecondMethod->getLocation(),
9553 SecondMethod->getSourceRange(), MethodDeleted)
9554 << SecondName << SecondDeleted;
9559 const bool FirstVirtual = FirstMethod->isVirtualAsWritten();
9560 const bool SecondVirtual = SecondMethod->isVirtualAsWritten();
9561 const bool FirstPure = FirstMethod->isPure();
9562 const bool SecondPure = SecondMethod->isPure();
9563 if ((FirstVirtual || SecondVirtual) &&
9564 (FirstVirtual != SecondVirtual || FirstPure != SecondPure)) {
9565 ODRDiagError(FirstMethod->getLocation(),
9566 FirstMethod->getSourceRange(), MethodVirtual)
9567 << FirstName << FirstPure << FirstVirtual;
9568 ODRDiagNote(SecondMethod->getLocation(),
9569 SecondMethod->getSourceRange(), MethodVirtual)
9570 << SecondName << SecondPure << SecondVirtual;
9575 // CXXMethodDecl::isStatic uses the canonical Decl. With Decl merging,
9576 // FirstDecl is the canonical Decl of SecondDecl, so the storage
9577 // class needs to be checked instead.
9578 const auto FirstStorage = FirstMethod->getStorageClass();
9579 const auto SecondStorage = SecondMethod->getStorageClass();
9580 const bool FirstStatic = FirstStorage == SC_Static;
9581 const bool SecondStatic = SecondStorage == SC_Static;
9582 if (FirstStatic != SecondStatic) {
9583 ODRDiagError(FirstMethod->getLocation(),
9584 FirstMethod->getSourceRange(), MethodStatic)
9585 << FirstName << FirstStatic;
9586 ODRDiagNote(SecondMethod->getLocation(),
9587 SecondMethod->getSourceRange(), MethodStatic)
9588 << SecondName << SecondStatic;
9593 const bool FirstVolatile = FirstMethod->isVolatile();
9594 const bool SecondVolatile = SecondMethod->isVolatile();
9595 if (FirstVolatile != SecondVolatile) {
9596 ODRDiagError(FirstMethod->getLocation(),
9597 FirstMethod->getSourceRange(), MethodVolatile)
9598 << FirstName << FirstVolatile;
9599 ODRDiagNote(SecondMethod->getLocation(),
9600 SecondMethod->getSourceRange(), MethodVolatile)
9601 << SecondName << SecondVolatile;
9606 const bool FirstConst = FirstMethod->isConst();
9607 const bool SecondConst = SecondMethod->isConst();
9608 if (FirstConst != SecondConst) {
9609 ODRDiagError(FirstMethod->getLocation(),
9610 FirstMethod->getSourceRange(), MethodConst)
9611 << FirstName << FirstConst;
9612 ODRDiagNote(SecondMethod->getLocation(),
9613 SecondMethod->getSourceRange(), MethodConst)
9614 << SecondName << SecondConst;
9619 const bool FirstInline = FirstMethod->isInlineSpecified();
9620 const bool SecondInline = SecondMethod->isInlineSpecified();
9621 if (FirstInline != SecondInline) {
9622 ODRDiagError(FirstMethod->getLocation(),
9623 FirstMethod->getSourceRange(), MethodInline)
9624 << FirstName << FirstInline;
9625 ODRDiagNote(SecondMethod->getLocation(),
9626 SecondMethod->getSourceRange(), MethodInline)
9627 << SecondName << SecondInline;
9632 const unsigned FirstNumParameters = FirstMethod->param_size();
9633 const unsigned SecondNumParameters = SecondMethod->param_size();
9634 if (FirstNumParameters != SecondNumParameters) {
9635 ODRDiagError(FirstMethod->getLocation(),
9636 FirstMethod->getSourceRange(), MethodNumberParameters)
9637 << FirstName << FirstNumParameters;
9638 ODRDiagNote(SecondMethod->getLocation(),
9639 SecondMethod->getSourceRange(), MethodNumberParameters)
9640 << SecondName << SecondNumParameters;
9645 // Need this status boolean to know when break out of the switch.
9646 bool ParameterMismatch = false;
9647 for (unsigned I = 0; I < FirstNumParameters; ++I) {
9648 const ParmVarDecl *FirstParam = FirstMethod->getParamDecl(I);
9649 const ParmVarDecl *SecondParam = SecondMethod->getParamDecl(I);
9651 QualType FirstParamType = FirstParam->getType();
9652 QualType SecondParamType = SecondParam->getType();
9653 if (FirstParamType != SecondParamType &&
9654 ComputeQualTypeODRHash(FirstParamType) !=
9655 ComputeQualTypeODRHash(SecondParamType)) {
9656 if (const DecayedType *ParamDecayedType =
9657 FirstParamType->getAs<DecayedType>()) {
9658 ODRDiagError(FirstMethod->getLocation(),
9659 FirstMethod->getSourceRange(), MethodParameterType)
9660 << FirstName << (I + 1) << FirstParamType << true
9661 << ParamDecayedType->getOriginalType();
9663 ODRDiagError(FirstMethod->getLocation(),
9664 FirstMethod->getSourceRange(), MethodParameterType)
9665 << FirstName << (I + 1) << FirstParamType << false;
9668 if (const DecayedType *ParamDecayedType =
9669 SecondParamType->getAs<DecayedType>()) {
9670 ODRDiagNote(SecondMethod->getLocation(),
9671 SecondMethod->getSourceRange(), MethodParameterType)
9672 << SecondName << (I + 1) << SecondParamType << true
9673 << ParamDecayedType->getOriginalType();
9675 ODRDiagNote(SecondMethod->getLocation(),
9676 SecondMethod->getSourceRange(), MethodParameterType)
9677 << SecondName << (I + 1) << SecondParamType << false;
9679 ParameterMismatch = true;
9683 DeclarationName FirstParamName = FirstParam->getDeclName();
9684 DeclarationName SecondParamName = SecondParam->getDeclName();
9685 if (FirstParamName != SecondParamName) {
9686 ODRDiagError(FirstMethod->getLocation(),
9687 FirstMethod->getSourceRange(), MethodParameterName)
9688 << FirstName << (I + 1) << FirstParamName;
9689 ODRDiagNote(SecondMethod->getLocation(),
9690 SecondMethod->getSourceRange(), MethodParameterName)
9691 << SecondName << (I + 1) << SecondParamName;
9692 ParameterMismatch = true;
9697 if (ParameterMismatch) {
9706 if (Diagnosed == true)
9709 Diag(FirstRecord->getLocation(),
9710 diag::err_module_odr_violation_different_definitions)
9711 << FirstRecord << FirstModule.empty() << FirstModule;
9713 Diag(SecondRecord->getLocation(),
9714 diag::note_module_odr_violation_different_definitions)
9720 // All definitions are updates to the same declaration. This happens if a
9721 // module instantiates the declaration of a class template specialization
9722 // and two or more other modules instantiate its definition.
9724 // FIXME: Indicate which modules had instantiations of this definition.
9725 // FIXME: How can this even happen?
9726 Diag(Merge.first->getLocation(),
9727 diag::err_module_odr_violation_different_instantiations)
9733 void ASTReader::StartedDeserializing() {
9734 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
9735 ReadTimer->startTimer();
9738 void ASTReader::FinishedDeserializing() {
9739 assert(NumCurrentElementsDeserializing &&
9740 "FinishedDeserializing not paired with StartedDeserializing");
9741 if (NumCurrentElementsDeserializing == 1) {
9742 // We decrease NumCurrentElementsDeserializing only after pending actions
9743 // are finished, to avoid recursively re-calling finishPendingActions().
9744 finishPendingActions();
9746 --NumCurrentElementsDeserializing;
9748 if (NumCurrentElementsDeserializing == 0) {
9749 // Propagate exception specification updates along redeclaration chains.
9750 while (!PendingExceptionSpecUpdates.empty()) {
9751 auto Updates = std::move(PendingExceptionSpecUpdates);
9752 PendingExceptionSpecUpdates.clear();
9753 for (auto Update : Updates) {
9754 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
9755 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
9756 auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
9757 if (auto *Listener = Context.getASTMutationListener())
9758 Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
9759 for (auto *Redecl : Update.second->redecls())
9760 Context.adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
9765 ReadTimer->stopTimer();
9767 diagnoseOdrViolations();
9769 // We are not in recursive loading, so it's safe to pass the "interesting"
9770 // decls to the consumer.
9772 PassInterestingDeclsToConsumer();
9776 void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
9777 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
9778 // Remove any fake results before adding any real ones.
9779 auto It = PendingFakeLookupResults.find(II);
9780 if (It != PendingFakeLookupResults.end()) {
9781 for (auto *ND : It->second)
9782 SemaObj->IdResolver.RemoveDecl(ND);
9783 // FIXME: this works around module+PCH performance issue.
9784 // Rather than erase the result from the map, which is O(n), just clear
9785 // the vector of NamedDecls.
9790 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
9791 SemaObj->TUScope->AddDecl(D);
9792 } else if (SemaObj->TUScope) {
9793 // Adding the decl to IdResolver may have failed because it was already in
9794 // (even though it was not added in scope). If it is already in, make sure
9795 // it gets in the scope as well.
9796 if (std::find(SemaObj->IdResolver.begin(Name),
9797 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
9798 SemaObj->TUScope->AddDecl(D);
9802 ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context,
9803 const PCHContainerReader &PCHContainerRdr,
9804 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
9805 StringRef isysroot, bool DisableValidation,
9806 bool AllowASTWithCompilerErrors,
9807 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
9808 bool UseGlobalIndex,
9809 std::unique_ptr<llvm::Timer> ReadTimer)
9810 : Listener(DisableValidation
9811 ? cast<ASTReaderListener>(new SimpleASTReaderListener(PP))
9812 : cast<ASTReaderListener>(new PCHValidator(PP, *this))),
9813 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
9814 PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()), PP(PP),
9816 ModuleMgr(PP.getFileManager(), PP.getPCMCache(), PCHContainerRdr),
9817 PCMCache(PP.getPCMCache()), DummyIdResolver(PP),
9818 ReadTimer(std::move(ReadTimer)), isysroot(isysroot),
9819 DisableValidation(DisableValidation),
9820 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
9821 AllowConfigurationMismatch(AllowConfigurationMismatch),
9822 ValidateSystemInputs(ValidateSystemInputs),
9823 UseGlobalIndex(UseGlobalIndex), CurrSwitchCaseStmts(&SwitchCaseStmts) {
9824 SourceMgr.setExternalSLocEntrySource(this);
9826 for (const auto &Ext : Extensions) {
9827 auto BlockName = Ext->getExtensionMetadata().BlockName;
9828 auto Known = ModuleFileExtensions.find(BlockName);
9829 if (Known != ModuleFileExtensions.end()) {
9830 Diags.Report(diag::warn_duplicate_module_file_extension)
9835 ModuleFileExtensions.insert({BlockName, Ext});
9839 ASTReader::~ASTReader() {
9840 if (OwnsDeserializationListener)
9841 delete DeserializationListener;
9844 IdentifierResolver &ASTReader::getIdResolver() {
9845 return SemaObj ? SemaObj->IdResolver : DummyIdResolver;
9848 unsigned ASTRecordReader::readRecord(llvm::BitstreamCursor &Cursor,
9849 unsigned AbbrevID) {
9852 return Cursor.readRecord(AbbrevID, Record);