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/DeclTemplate.h"
20 #include "clang/AST/Expr.h"
21 #include "clang/AST/ExprCXX.h"
22 #include "clang/Frontend/PCHContainerOperations.h"
23 #include "clang/AST/NestedNameSpecifier.h"
24 #include "clang/AST/Type.h"
25 #include "clang/AST/TypeLocVisitor.h"
26 #include "clang/Basic/DiagnosticOptions.h"
27 #include "clang/Basic/FileManager.h"
28 #include "clang/Basic/SourceManager.h"
29 #include "clang/Basic/SourceManagerInternals.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "clang/Basic/TargetOptions.h"
32 #include "clang/Basic/Version.h"
33 #include "clang/Basic/VersionTuple.h"
34 #include "clang/Frontend/Utils.h"
35 #include "clang/Lex/HeaderSearch.h"
36 #include "clang/Lex/HeaderSearchOptions.h"
37 #include "clang/Lex/MacroInfo.h"
38 #include "clang/Lex/PreprocessingRecord.h"
39 #include "clang/Lex/Preprocessor.h"
40 #include "clang/Lex/PreprocessorOptions.h"
41 #include "clang/Sema/Scope.h"
42 #include "clang/Sema/Sema.h"
43 #include "clang/Serialization/ASTDeserializationListener.h"
44 #include "clang/Serialization/GlobalModuleIndex.h"
45 #include "clang/Serialization/ModuleManager.h"
46 #include "clang/Serialization/SerializationDiagnostic.h"
47 #include "llvm/ADT/Hashing.h"
48 #include "llvm/ADT/StringExtras.h"
49 #include "llvm/Bitcode/BitstreamReader.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/FileSystem.h"
52 #include "llvm/Support/MemoryBuffer.h"
53 #include "llvm/Support/Path.h"
54 #include "llvm/Support/SaveAndRestore.h"
55 #include "llvm/Support/raw_ostream.h"
59 #include <system_error>
61 using namespace clang;
62 using namespace clang::serialization;
63 using namespace clang::serialization::reader;
64 using llvm::BitstreamCursor;
67 //===----------------------------------------------------------------------===//
68 // ChainedASTReaderListener implementation
69 //===----------------------------------------------------------------------===//
72 ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
73 return First->ReadFullVersionInformation(FullVersion) ||
74 Second->ReadFullVersionInformation(FullVersion);
76 void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
77 First->ReadModuleName(ModuleName);
78 Second->ReadModuleName(ModuleName);
80 void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
81 First->ReadModuleMapFile(ModuleMapPath);
82 Second->ReadModuleMapFile(ModuleMapPath);
85 ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
87 bool AllowCompatibleDifferences) {
88 return First->ReadLanguageOptions(LangOpts, Complain,
89 AllowCompatibleDifferences) ||
90 Second->ReadLanguageOptions(LangOpts, Complain,
91 AllowCompatibleDifferences);
93 bool ChainedASTReaderListener::ReadTargetOptions(
94 const TargetOptions &TargetOpts, bool Complain,
95 bool AllowCompatibleDifferences) {
96 return First->ReadTargetOptions(TargetOpts, Complain,
97 AllowCompatibleDifferences) ||
98 Second->ReadTargetOptions(TargetOpts, Complain,
99 AllowCompatibleDifferences);
101 bool ChainedASTReaderListener::ReadDiagnosticOptions(
102 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
103 return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
104 Second->ReadDiagnosticOptions(DiagOpts, Complain);
107 ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
109 return First->ReadFileSystemOptions(FSOpts, Complain) ||
110 Second->ReadFileSystemOptions(FSOpts, Complain);
113 bool ChainedASTReaderListener::ReadHeaderSearchOptions(
114 const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath,
116 return First->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
118 Second->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
121 bool ChainedASTReaderListener::ReadPreprocessorOptions(
122 const PreprocessorOptions &PPOpts, bool Complain,
123 std::string &SuggestedPredefines) {
124 return First->ReadPreprocessorOptions(PPOpts, Complain,
125 SuggestedPredefines) ||
126 Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
128 void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
130 First->ReadCounter(M, Value);
131 Second->ReadCounter(M, Value);
133 bool ChainedASTReaderListener::needsInputFileVisitation() {
134 return First->needsInputFileVisitation() ||
135 Second->needsInputFileVisitation();
137 bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
138 return First->needsSystemInputFileVisitation() ||
139 Second->needsSystemInputFileVisitation();
141 void ChainedASTReaderListener::visitModuleFile(StringRef Filename) {
142 First->visitModuleFile(Filename);
143 Second->visitModuleFile(Filename);
145 bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
148 bool Continue = false;
149 if (First->needsInputFileVisitation() &&
150 (!isSystem || First->needsSystemInputFileVisitation()))
151 Continue |= First->visitInputFile(Filename, isSystem, isOverridden);
152 if (Second->needsInputFileVisitation() &&
153 (!isSystem || Second->needsSystemInputFileVisitation()))
154 Continue |= Second->visitInputFile(Filename, isSystem, isOverridden);
158 //===----------------------------------------------------------------------===//
159 // PCH validator implementation
160 //===----------------------------------------------------------------------===//
162 ASTReaderListener::~ASTReaderListener() {}
164 /// \brief Compare the given set of language options against an existing set of
165 /// language options.
167 /// \param Diags If non-NULL, diagnostics will be emitted via this engine.
168 /// \param AllowCompatibleDifferences If true, differences between compatible
169 /// language options will be permitted.
171 /// \returns true if the languagae options mis-match, false otherwise.
172 static bool checkLanguageOptions(const LangOptions &LangOpts,
173 const LangOptions &ExistingLangOpts,
174 DiagnosticsEngine *Diags,
175 bool AllowCompatibleDifferences = true) {
176 #define LANGOPT(Name, Bits, Default, Description) \
177 if (ExistingLangOpts.Name != LangOpts.Name) { \
179 Diags->Report(diag::err_pch_langopt_mismatch) \
180 << Description << LangOpts.Name << ExistingLangOpts.Name; \
184 #define VALUE_LANGOPT(Name, Bits, Default, Description) \
185 if (ExistingLangOpts.Name != LangOpts.Name) { \
187 Diags->Report(diag::err_pch_langopt_value_mismatch) \
192 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
193 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
195 Diags->Report(diag::err_pch_langopt_value_mismatch) \
200 #define COMPATIBLE_LANGOPT(Name, Bits, Default, Description) \
201 if (!AllowCompatibleDifferences) \
202 LANGOPT(Name, Bits, Default, Description)
204 #define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description) \
205 if (!AllowCompatibleDifferences) \
206 ENUM_LANGOPT(Name, Bits, Default, Description)
208 #define BENIGN_LANGOPT(Name, Bits, Default, Description)
209 #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
210 #include "clang/Basic/LangOptions.def"
212 if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) {
214 Diags->Report(diag::err_pch_langopt_value_mismatch) << "module features";
218 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
220 Diags->Report(diag::err_pch_langopt_value_mismatch)
221 << "target Objective-C runtime";
225 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
226 LangOpts.CommentOpts.BlockCommandNames) {
228 Diags->Report(diag::err_pch_langopt_value_mismatch)
229 << "block command names";
236 /// \brief Compare the given set of target options against an existing set of
239 /// \param Diags If non-NULL, diagnostics will be emitted via this engine.
241 /// \returns true if the target options mis-match, false otherwise.
242 static bool checkTargetOptions(const TargetOptions &TargetOpts,
243 const TargetOptions &ExistingTargetOpts,
244 DiagnosticsEngine *Diags,
245 bool AllowCompatibleDifferences = true) {
246 #define CHECK_TARGET_OPT(Field, Name) \
247 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
249 Diags->Report(diag::err_pch_targetopt_mismatch) \
250 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
254 // The triple and ABI must match exactly.
255 CHECK_TARGET_OPT(Triple, "target");
256 CHECK_TARGET_OPT(ABI, "target ABI");
258 // We can tolerate different CPUs in many cases, notably when one CPU
259 // supports a strict superset of another. When allowing compatible
260 // differences skip this check.
261 if (!AllowCompatibleDifferences)
262 CHECK_TARGET_OPT(CPU, "target CPU");
264 #undef CHECK_TARGET_OPT
266 // Compare feature sets.
267 SmallVector<StringRef, 4> ExistingFeatures(
268 ExistingTargetOpts.FeaturesAsWritten.begin(),
269 ExistingTargetOpts.FeaturesAsWritten.end());
270 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
271 TargetOpts.FeaturesAsWritten.end());
272 std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
273 std::sort(ReadFeatures.begin(), ReadFeatures.end());
275 // We compute the set difference in both directions explicitly so that we can
276 // diagnose the differences differently.
277 SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
279 ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
280 ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
281 std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
282 ExistingFeatures.begin(), ExistingFeatures.end(),
283 std::back_inserter(UnmatchedReadFeatures));
285 // If we are allowing compatible differences and the read feature set is
286 // a strict subset of the existing feature set, there is nothing to diagnose.
287 if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
291 for (StringRef Feature : UnmatchedReadFeatures)
292 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
293 << /* is-existing-feature */ false << Feature;
294 for (StringRef Feature : UnmatchedExistingFeatures)
295 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
296 << /* is-existing-feature */ true << Feature;
299 return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
303 PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
305 bool AllowCompatibleDifferences) {
306 const LangOptions &ExistingLangOpts = PP.getLangOpts();
307 return checkLanguageOptions(LangOpts, ExistingLangOpts,
308 Complain ? &Reader.Diags : nullptr,
309 AllowCompatibleDifferences);
312 bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
314 bool AllowCompatibleDifferences) {
315 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
316 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
317 Complain ? &Reader.Diags : nullptr,
318 AllowCompatibleDifferences);
322 typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
324 typedef llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> >
328 static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
329 DiagnosticsEngine &Diags,
331 typedef DiagnosticsEngine::Level Level;
333 // Check current mappings for new -Werror mappings, and the stored mappings
334 // for cases that were explicitly mapped to *not* be errors that are now
335 // errors because of options like -Werror.
336 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
338 for (DiagnosticsEngine *MappingSource : MappingSources) {
339 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
340 diag::kind DiagID = DiagIDMappingPair.first;
341 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
342 if (CurLevel < DiagnosticsEngine::Error)
343 continue; // not significant
345 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
346 if (StoredLevel < DiagnosticsEngine::Error) {
348 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
349 Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
358 static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
359 diag::Severity Ext = Diags.getExtensionHandlingBehavior();
360 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
362 return Ext >= diag::Severity::Error;
365 static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
366 DiagnosticsEngine &Diags,
367 bool IsSystem, bool Complain) {
370 if (Diags.getSuppressSystemWarnings())
372 // If -Wsystem-headers was not enabled before, be conservative
373 if (StoredDiags.getSuppressSystemWarnings()) {
375 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
380 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
382 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
386 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
387 !StoredDiags.getEnableAllWarnings()) {
389 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
393 if (isExtHandlingFromDiagsError(Diags) &&
394 !isExtHandlingFromDiagsError(StoredDiags)) {
396 Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
400 return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
403 bool PCHValidator::ReadDiagnosticOptions(
404 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
405 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
406 IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
407 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
408 new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
409 // This should never fail, because we would have processed these options
410 // before writing them to an ASTFile.
411 ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
413 ModuleManager &ModuleMgr = Reader.getModuleManager();
414 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
416 // If the original import came from a file explicitly generated by the user,
417 // don't check the diagnostic mappings.
418 // FIXME: currently this is approximated by checking whether this is not a
419 // module import of an implicitly-loaded module file.
420 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
421 // the transitive closure of its imports, since unrelated modules cannot be
422 // imported until after this module finishes validation.
423 ModuleFile *TopImport = *ModuleMgr.rbegin();
424 while (!TopImport->ImportedBy.empty())
425 TopImport = TopImport->ImportedBy[0];
426 if (TopImport->Kind != MK_ImplicitModule)
429 StringRef ModuleName = TopImport->ModuleName;
430 assert(!ModuleName.empty() && "diagnostic options read before module name");
432 Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
433 assert(M && "missing module");
435 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
436 // contains the union of their flags.
437 return checkDiagnosticMappings(*Diags, ExistingDiags, M->IsSystem, Complain);
440 /// \brief Collect the macro definitions provided by the given preprocessor
443 collectMacroDefinitions(const PreprocessorOptions &PPOpts,
444 MacroDefinitionsMap &Macros,
445 SmallVectorImpl<StringRef> *MacroNames = nullptr) {
446 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
447 StringRef Macro = PPOpts.Macros[I].first;
448 bool IsUndef = PPOpts.Macros[I].second;
450 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
451 StringRef MacroName = MacroPair.first;
452 StringRef MacroBody = MacroPair.second;
454 // For an #undef'd macro, we only care about the name.
456 if (MacroNames && !Macros.count(MacroName))
457 MacroNames->push_back(MacroName);
459 Macros[MacroName] = std::make_pair("", true);
463 // For a #define'd macro, figure out the actual definition.
464 if (MacroName.size() == Macro.size())
467 // Note: GCC drops anything following an end-of-line character.
468 StringRef::size_type End = MacroBody.find_first_of("\n\r");
469 MacroBody = MacroBody.substr(0, End);
472 if (MacroNames && !Macros.count(MacroName))
473 MacroNames->push_back(MacroName);
474 Macros[MacroName] = std::make_pair(MacroBody, false);
478 /// \brief Check the preprocessor options deserialized from the control block
479 /// against the preprocessor options in an existing preprocessor.
481 /// \param Diags If non-null, produce diagnostics for any mismatches incurred.
482 static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
483 const PreprocessorOptions &ExistingPPOpts,
484 DiagnosticsEngine *Diags,
485 FileManager &FileMgr,
486 std::string &SuggestedPredefines,
487 const LangOptions &LangOpts) {
488 // Check macro definitions.
489 MacroDefinitionsMap ASTFileMacros;
490 collectMacroDefinitions(PPOpts, ASTFileMacros);
491 MacroDefinitionsMap ExistingMacros;
492 SmallVector<StringRef, 4> ExistingMacroNames;
493 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
495 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
496 // Dig out the macro definition in the existing preprocessor options.
497 StringRef MacroName = ExistingMacroNames[I];
498 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
500 // Check whether we know anything about this macro name or not.
501 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
502 = ASTFileMacros.find(MacroName);
503 if (Known == ASTFileMacros.end()) {
504 // FIXME: Check whether this identifier was referenced anywhere in the
505 // AST file. If so, we should reject the AST file. Unfortunately, this
506 // information isn't in the control block. What shall we do about it?
508 if (Existing.second) {
509 SuggestedPredefines += "#undef ";
510 SuggestedPredefines += MacroName.str();
511 SuggestedPredefines += '\n';
513 SuggestedPredefines += "#define ";
514 SuggestedPredefines += MacroName.str();
515 SuggestedPredefines += ' ';
516 SuggestedPredefines += Existing.first.str();
517 SuggestedPredefines += '\n';
522 // If the macro was defined in one but undef'd in the other, we have a
524 if (Existing.second != Known->second.second) {
526 Diags->Report(diag::err_pch_macro_def_undef)
527 << MacroName << Known->second.second;
532 // If the macro was #undef'd in both, or if the macro bodies are identical,
534 if (Existing.second || Existing.first == Known->second.first)
537 // The macro bodies differ; complain.
539 Diags->Report(diag::err_pch_macro_def_conflict)
540 << MacroName << Known->second.first << Existing.first;
545 // Check whether we're using predefines.
546 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines) {
548 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
553 // Detailed record is important since it is used for the module cache hash.
554 if (LangOpts.Modules &&
555 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord) {
557 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
562 // Compute the #include and #include_macros lines we need.
563 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
564 StringRef File = ExistingPPOpts.Includes[I];
565 if (File == ExistingPPOpts.ImplicitPCHInclude)
568 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
569 != PPOpts.Includes.end())
572 SuggestedPredefines += "#include \"";
573 SuggestedPredefines += File;
574 SuggestedPredefines += "\"\n";
577 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
578 StringRef File = ExistingPPOpts.MacroIncludes[I];
579 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
581 != PPOpts.MacroIncludes.end())
584 SuggestedPredefines += "#__include_macros \"";
585 SuggestedPredefines += File;
586 SuggestedPredefines += "\"\n##\n";
592 bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
594 std::string &SuggestedPredefines) {
595 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
597 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
598 Complain? &Reader.Diags : nullptr,
604 /// Check the header search options deserialized from the control block
605 /// against the header search options in an existing preprocessor.
607 /// \param Diags If non-null, produce diagnostics for any mismatches incurred.
608 static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
609 StringRef SpecificModuleCachePath,
610 StringRef ExistingModuleCachePath,
611 DiagnosticsEngine *Diags,
612 const LangOptions &LangOpts) {
613 if (LangOpts.Modules) {
614 if (SpecificModuleCachePath != ExistingModuleCachePath) {
616 Diags->Report(diag::err_pch_modulecache_mismatch)
617 << SpecificModuleCachePath << ExistingModuleCachePath;
625 bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
626 StringRef SpecificModuleCachePath,
628 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
629 PP.getHeaderSearchInfo().getModuleCachePath(),
630 Complain ? &Reader.Diags : nullptr,
634 void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
635 PP.setCounterValue(Value);
638 //===----------------------------------------------------------------------===//
639 // AST reader implementation
640 //===----------------------------------------------------------------------===//
642 void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
643 bool TakeOwnership) {
644 DeserializationListener = Listener;
645 OwnsDeserializationListener = TakeOwnership;
650 unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
651 return serialization::ComputeHash(Sel);
655 std::pair<unsigned, unsigned>
656 ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
657 using namespace llvm::support;
658 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
659 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
660 return std::make_pair(KeyLen, DataLen);
663 ASTSelectorLookupTrait::internal_key_type
664 ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
665 using namespace llvm::support;
666 SelectorTable &SelTable = Reader.getContext().Selectors;
667 unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
668 IdentifierInfo *FirstII = Reader.getLocalIdentifier(
669 F, endian::readNext<uint32_t, little, unaligned>(d));
671 return SelTable.getNullarySelector(FirstII);
673 return SelTable.getUnarySelector(FirstII);
675 SmallVector<IdentifierInfo *, 16> Args;
676 Args.push_back(FirstII);
677 for (unsigned I = 1; I != N; ++I)
678 Args.push_back(Reader.getLocalIdentifier(
679 F, endian::readNext<uint32_t, little, unaligned>(d)));
681 return SelTable.getSelector(N, Args.data());
684 ASTSelectorLookupTrait::data_type
685 ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
687 using namespace llvm::support;
691 Result.ID = Reader.getGlobalSelectorID(
692 F, endian::readNext<uint32_t, little, unaligned>(d));
693 unsigned FullInstanceBits = endian::readNext<uint16_t, little, unaligned>(d);
694 unsigned FullFactoryBits = endian::readNext<uint16_t, little, unaligned>(d);
695 Result.InstanceBits = FullInstanceBits & 0x3;
696 Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
697 Result.FactoryBits = FullFactoryBits & 0x3;
698 Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
699 unsigned NumInstanceMethods = FullInstanceBits >> 3;
700 unsigned NumFactoryMethods = FullFactoryBits >> 3;
702 // Load instance methods
703 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
704 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
705 F, endian::readNext<uint32_t, little, unaligned>(d)))
706 Result.Instance.push_back(Method);
709 // Load factory methods
710 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
711 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
712 F, endian::readNext<uint32_t, little, unaligned>(d)))
713 Result.Factory.push_back(Method);
719 unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
720 return llvm::HashString(a);
723 std::pair<unsigned, unsigned>
724 ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
725 using namespace llvm::support;
726 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
727 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
728 return std::make_pair(KeyLen, DataLen);
731 ASTIdentifierLookupTraitBase::internal_key_type
732 ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
733 assert(n >= 2 && d[n-1] == '\0');
734 return StringRef((const char*) d, n-1);
737 /// \brief Whether the given identifier is "interesting".
738 static bool isInterestingIdentifier(IdentifierInfo &II) {
739 return II.isPoisoned() ||
740 II.isExtensionToken() ||
741 II.getObjCOrBuiltinID() ||
742 II.hasRevertedTokenIDToIdentifier() ||
743 II.hadMacroDefinition() ||
744 II.getFETokenInfo<void>();
747 IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
748 const unsigned char* d,
750 using namespace llvm::support;
751 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
752 bool IsInteresting = RawID & 0x01;
754 // Wipe out the "is interesting" bit.
757 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
758 if (!IsInteresting) {
759 // For uninteresting identifiers, just build the IdentifierInfo
760 // and associate it with the persistent ID.
761 IdentifierInfo *II = KnownII;
763 II = &Reader.getIdentifierTable().getOwn(k);
766 Reader.SetIdentifierInfo(ID, II);
767 if (!II->isFromAST()) {
768 bool WasInteresting = isInterestingIdentifier(*II);
771 II->setChangedSinceDeserialization();
773 Reader.markIdentifierUpToDate(II);
777 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
778 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
779 bool CPlusPlusOperatorKeyword = Bits & 0x01;
781 bool HasRevertedTokenIDToIdentifier = Bits & 0x01;
783 bool Poisoned = Bits & 0x01;
785 bool ExtensionToken = Bits & 0x01;
787 bool hadMacroDefinition = Bits & 0x01;
790 assert(Bits == 0 && "Extra bits in the identifier?");
793 // Build the IdentifierInfo itself and link the identifier ID with
794 // the new IdentifierInfo.
795 IdentifierInfo *II = KnownII;
797 II = &Reader.getIdentifierTable().getOwn(StringRef(k));
800 Reader.markIdentifierUpToDate(II);
801 if (!II->isFromAST()) {
802 bool WasInteresting = isInterestingIdentifier(*II);
805 II->setChangedSinceDeserialization();
808 // Set or check the various bits in the IdentifierInfo structure.
809 // Token IDs are read-only.
810 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
811 II->RevertTokenIDToIdentifier();
812 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
813 assert(II->isExtensionToken() == ExtensionToken &&
814 "Incorrect extension token flag");
815 (void)ExtensionToken;
817 II->setIsPoisoned(true);
818 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
819 "Incorrect C++ operator keyword flag");
820 (void)CPlusPlusOperatorKeyword;
822 // If this identifier is a macro, deserialize the macro
824 if (hadMacroDefinition) {
825 uint32_t MacroDirectivesOffset =
826 endian::readNext<uint32_t, little, unaligned>(d);
829 Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
832 Reader.SetIdentifierInfo(ID, II);
834 // Read all of the declarations visible at global scope with this
837 SmallVector<uint32_t, 4> DeclIDs;
838 for (; DataLen > 0; DataLen -= 4)
839 DeclIDs.push_back(Reader.getGlobalDeclID(
840 F, endian::readNext<uint32_t, little, unaligned>(d)));
841 Reader.SetGloballyVisibleDecls(II, DeclIDs);
848 ASTDeclContextNameLookupTrait::ComputeHash(const DeclNameKey &Key) const {
849 llvm::FoldingSetNodeID ID;
850 ID.AddInteger(Key.Kind);
853 case DeclarationName::Identifier:
854 case DeclarationName::CXXLiteralOperatorName:
855 ID.AddString(((IdentifierInfo*)Key.Data)->getName());
857 case DeclarationName::ObjCZeroArgSelector:
858 case DeclarationName::ObjCOneArgSelector:
859 case DeclarationName::ObjCMultiArgSelector:
860 ID.AddInteger(serialization::ComputeHash(Selector(Key.Data)));
862 case DeclarationName::CXXOperatorName:
863 ID.AddInteger((OverloadedOperatorKind)Key.Data);
865 case DeclarationName::CXXConstructorName:
866 case DeclarationName::CXXDestructorName:
867 case DeclarationName::CXXConversionFunctionName:
868 case DeclarationName::CXXUsingDirective:
872 return ID.ComputeHash();
875 ASTDeclContextNameLookupTrait::internal_key_type
876 ASTDeclContextNameLookupTrait::GetInternalKey(
877 const external_key_type& Name) const {
879 Key.Kind = Name.getNameKind();
880 switch (Name.getNameKind()) {
881 case DeclarationName::Identifier:
882 Key.Data = (uint64_t)Name.getAsIdentifierInfo();
884 case DeclarationName::ObjCZeroArgSelector:
885 case DeclarationName::ObjCOneArgSelector:
886 case DeclarationName::ObjCMultiArgSelector:
887 Key.Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
889 case DeclarationName::CXXOperatorName:
890 Key.Data = Name.getCXXOverloadedOperator();
892 case DeclarationName::CXXLiteralOperatorName:
893 Key.Data = (uint64_t)Name.getCXXLiteralIdentifier();
895 case DeclarationName::CXXConstructorName:
896 case DeclarationName::CXXDestructorName:
897 case DeclarationName::CXXConversionFunctionName:
898 case DeclarationName::CXXUsingDirective:
906 std::pair<unsigned, unsigned>
907 ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
908 using namespace llvm::support;
909 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
910 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
911 return std::make_pair(KeyLen, DataLen);
914 ASTDeclContextNameLookupTrait::internal_key_type
915 ASTDeclContextNameLookupTrait::ReadKey(const unsigned char* d, unsigned) {
916 using namespace llvm::support;
919 Key.Kind = (DeclarationName::NameKind)*d++;
921 case DeclarationName::Identifier:
922 Key.Data = (uint64_t)Reader.getLocalIdentifier(
923 F, endian::readNext<uint32_t, little, unaligned>(d));
925 case DeclarationName::ObjCZeroArgSelector:
926 case DeclarationName::ObjCOneArgSelector:
927 case DeclarationName::ObjCMultiArgSelector:
929 (uint64_t)Reader.getLocalSelector(
930 F, endian::readNext<uint32_t, little, unaligned>(
931 d)).getAsOpaquePtr();
933 case DeclarationName::CXXOperatorName:
934 Key.Data = *d++; // OverloadedOperatorKind
936 case DeclarationName::CXXLiteralOperatorName:
937 Key.Data = (uint64_t)Reader.getLocalIdentifier(
938 F, endian::readNext<uint32_t, little, unaligned>(d));
940 case DeclarationName::CXXConstructorName:
941 case DeclarationName::CXXDestructorName:
942 case DeclarationName::CXXConversionFunctionName:
943 case DeclarationName::CXXUsingDirective:
951 ASTDeclContextNameLookupTrait::data_type
952 ASTDeclContextNameLookupTrait::ReadData(internal_key_type,
953 const unsigned char* d,
955 using namespace llvm::support;
956 unsigned NumDecls = endian::readNext<uint16_t, little, unaligned>(d);
957 LE32DeclID *Start = reinterpret_cast<LE32DeclID *>(
958 const_cast<unsigned char *>(d));
959 return std::make_pair(Start, Start + NumDecls);
962 bool ASTReader::ReadDeclContextStorage(ModuleFile &M,
963 BitstreamCursor &Cursor,
964 const std::pair<uint64_t, uint64_t> &Offsets,
965 DeclContextInfo &Info) {
966 SavedStreamPosition SavedPosition(Cursor);
967 // First the lexical decls.
968 if (Offsets.first != 0) {
969 Cursor.JumpToBit(Offsets.first);
973 unsigned Code = Cursor.ReadCode();
974 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
975 if (RecCode != DECL_CONTEXT_LEXICAL) {
976 Error("Expected lexical block");
980 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair*>(Blob.data());
981 Info.NumLexicalDecls = Blob.size() / sizeof(KindDeclIDPair);
984 // Now the lookup table.
985 if (Offsets.second != 0) {
986 Cursor.JumpToBit(Offsets.second);
990 unsigned Code = Cursor.ReadCode();
991 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
992 if (RecCode != DECL_CONTEXT_VISIBLE) {
993 Error("Expected visible lookup table block");
996 Info.NameLookupTableData = ASTDeclContextNameLookupTable::Create(
997 (const unsigned char *)Blob.data() + Record[0],
998 (const unsigned char *)Blob.data() + sizeof(uint32_t),
999 (const unsigned char *)Blob.data(),
1000 ASTDeclContextNameLookupTrait(*this, M));
1006 void ASTReader::Error(StringRef Msg) {
1007 Error(diag::err_fe_pch_malformed, Msg);
1008 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight()) {
1009 Diag(diag::note_module_cache_path)
1010 << PP.getHeaderSearchInfo().getModuleCachePath();
1014 void ASTReader::Error(unsigned DiagID,
1015 StringRef Arg1, StringRef Arg2) {
1016 if (Diags.isDiagnosticInFlight())
1017 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1019 Diag(DiagID) << Arg1 << Arg2;
1022 //===----------------------------------------------------------------------===//
1023 // Source Manager Deserialization
1024 //===----------------------------------------------------------------------===//
1026 /// \brief Read the line table in the source manager block.
1027 /// \returns true if there was an error.
1028 bool ASTReader::ParseLineTable(ModuleFile &F,
1029 const RecordData &Record) {
1031 LineTableInfo &LineTable = SourceMgr.getLineTable();
1033 // Parse the file names
1034 std::map<int, int> FileIDs;
1035 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
1036 // Extract the file name
1037 auto Filename = ReadPath(F, Record, Idx);
1038 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1041 // Parse the line entries
1042 std::vector<LineEntry> Entries;
1043 while (Idx < Record.size()) {
1044 int FID = Record[Idx++];
1045 assert(FID >= 0 && "Serialized line entries for non-local file.");
1046 // Remap FileID from 1-based old view.
1047 FID += F.SLocEntryBaseID - 1;
1049 // Extract the line entries
1050 unsigned NumEntries = Record[Idx++];
1051 assert(NumEntries && "Numentries is 00000");
1053 Entries.reserve(NumEntries);
1054 for (unsigned I = 0; I != NumEntries; ++I) {
1055 unsigned FileOffset = Record[Idx++];
1056 unsigned LineNo = Record[Idx++];
1057 int FilenameID = FileIDs[Record[Idx++]];
1058 SrcMgr::CharacteristicKind FileKind
1059 = (SrcMgr::CharacteristicKind)Record[Idx++];
1060 unsigned IncludeOffset = Record[Idx++];
1061 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1062 FileKind, IncludeOffset));
1064 LineTable.AddEntry(FileID::get(FID), Entries);
1070 /// \brief Read a source manager block
1071 bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1072 using namespace SrcMgr;
1074 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
1076 // Set the source-location entry cursor to the current position in
1077 // the stream. This cursor will be used to read the contents of the
1078 // source manager block initially, and then lazily read
1079 // source-location entries as needed.
1080 SLocEntryCursor = F.Stream;
1082 // The stream itself is going to skip over the source manager block.
1083 if (F.Stream.SkipBlock()) {
1084 Error("malformed block record in AST file");
1088 // Enter the source manager block.
1089 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1090 Error("malformed source manager block record in AST file");
1096 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
1099 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1100 case llvm::BitstreamEntry::Error:
1101 Error("malformed block record in AST file");
1103 case llvm::BitstreamEntry::EndBlock:
1105 case llvm::BitstreamEntry::Record:
1106 // The interesting case.
1113 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
1114 default: // Default behavior: ignore.
1117 case SM_SLOC_FILE_ENTRY:
1118 case SM_SLOC_BUFFER_ENTRY:
1119 case SM_SLOC_EXPANSION_ENTRY:
1120 // Once we hit one of the source location entries, we're done.
1126 /// \brief If a header file is not found at the path that we expect it to be
1127 /// and the PCH file was moved from its original location, try to resolve the
1128 /// file by assuming that header+PCH were moved together and the header is in
1129 /// the same place relative to the PCH.
1131 resolveFileRelativeToOriginalDir(const std::string &Filename,
1132 const std::string &OriginalDir,
1133 const std::string &CurrDir) {
1134 assert(OriginalDir != CurrDir &&
1135 "No point trying to resolve the file if the PCH dir didn't change");
1136 using namespace llvm::sys;
1137 SmallString<128> filePath(Filename);
1138 fs::make_absolute(filePath);
1139 assert(path::is_absolute(OriginalDir));
1140 SmallString<128> currPCHPath(CurrDir);
1142 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1143 fileDirE = path::end(path::parent_path(filePath));
1144 path::const_iterator origDirI = path::begin(OriginalDir),
1145 origDirE = path::end(OriginalDir);
1146 // Skip the common path components from filePath and OriginalDir.
1147 while (fileDirI != fileDirE && origDirI != origDirE &&
1148 *fileDirI == *origDirI) {
1152 for (; origDirI != origDirE; ++origDirI)
1153 path::append(currPCHPath, "..");
1154 path::append(currPCHPath, fileDirI, fileDirE);
1155 path::append(currPCHPath, path::filename(Filename));
1156 return currPCHPath.str();
1159 bool ASTReader::ReadSLocEntry(int ID) {
1163 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1164 Error("source location entry ID out-of-range for AST file");
1168 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1169 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
1170 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
1171 unsigned BaseOffset = F->SLocEntryBaseOffset;
1173 ++NumSLocEntriesRead;
1174 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1175 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1176 Error("incorrectly-formatted source location entry in AST file");
1182 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
1184 Error("incorrectly-formatted source location entry in AST file");
1187 case SM_SLOC_FILE_ENTRY: {
1188 // We will detect whether a file changed and return 'Failure' for it, but
1189 // we will also try to fail gracefully by setting up the SLocEntry.
1190 unsigned InputID = Record[4];
1191 InputFile IF = getInputFile(*F, InputID);
1192 const FileEntry *File = IF.getFile();
1193 bool OverriddenBuffer = IF.isOverridden();
1195 // Note that we only check if a File was returned. If it was out-of-date
1196 // we have complained but we will continue creating a FileID to recover
1201 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1202 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1203 // This is the module's main file.
1204 IncludeLoc = getImportLocation(F);
1206 SrcMgr::CharacteristicKind
1207 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1208 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1209 ID, BaseOffset + Record[0]);
1210 SrcMgr::FileInfo &FileInfo =
1211 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1212 FileInfo.NumCreatedFIDs = Record[5];
1214 FileInfo.setHasLineDirectives();
1216 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1217 unsigned NumFileDecls = Record[7];
1219 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1220 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1224 const SrcMgr::ContentCache *ContentCache
1225 = SourceMgr.getOrCreateContentCache(File,
1226 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1227 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
1228 ContentCache->ContentsEntry == ContentCache->OrigEntry) {
1229 unsigned Code = SLocEntryCursor.ReadCode();
1231 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
1233 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1234 Error("AST record has invalid code");
1238 std::unique_ptr<llvm::MemoryBuffer> Buffer
1239 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), File->getName());
1240 SourceMgr.overrideFileContents(File, std::move(Buffer));
1246 case SM_SLOC_BUFFER_ENTRY: {
1247 const char *Name = Blob.data();
1248 unsigned Offset = Record[0];
1249 SrcMgr::CharacteristicKind
1250 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1251 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1252 if (IncludeLoc.isInvalid() &&
1253 (F->Kind == MK_ImplicitModule || F->Kind == MK_ExplicitModule)) {
1254 IncludeLoc = getImportLocation(F);
1256 unsigned Code = SLocEntryCursor.ReadCode();
1259 = SLocEntryCursor.readRecord(Code, Record, &Blob);
1261 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1262 Error("AST record has invalid code");
1266 std::unique_ptr<llvm::MemoryBuffer> Buffer =
1267 llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name);
1268 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
1269 BaseOffset + Offset, IncludeLoc);
1273 case SM_SLOC_EXPANSION_ENTRY: {
1274 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1275 SourceMgr.createExpansionLoc(SpellingLoc,
1276 ReadSourceLocation(*F, Record[2]),
1277 ReadSourceLocation(*F, Record[3]),
1280 BaseOffset + Record[0]);
1288 std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1290 return std::make_pair(SourceLocation(), "");
1292 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1293 Error("source location entry ID out-of-range for AST file");
1294 return std::make_pair(SourceLocation(), "");
1297 // Find which module file this entry lands in.
1298 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
1299 if (M->Kind != MK_ImplicitModule && M->Kind != MK_ExplicitModule)
1300 return std::make_pair(SourceLocation(), "");
1302 // FIXME: Can we map this down to a particular submodule? That would be
1304 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
1307 /// \brief Find the location where the module F is imported.
1308 SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1309 if (F->ImportLoc.isValid())
1310 return F->ImportLoc;
1312 // Otherwise we have a PCH. It's considered to be "imported" at the first
1313 // location of its includer.
1314 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
1315 // Main file is the importer.
1316 assert(!SourceMgr.getMainFileID().isInvalid() && "missing main file");
1317 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
1319 return F->ImportedBy[0]->FirstLoc;
1322 /// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1323 /// specified cursor. Read the abbreviations that are at the top of the block
1324 /// and then leave the cursor pointing into the block.
1325 bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
1326 if (Cursor.EnterSubBlock(BlockID)) {
1327 Error("malformed block record in AST file");
1332 uint64_t Offset = Cursor.GetCurrentBitNo();
1333 unsigned Code = Cursor.ReadCode();
1335 // We expect all abbrevs to be at the start of the block.
1336 if (Code != llvm::bitc::DEFINE_ABBREV) {
1337 Cursor.JumpToBit(Offset);
1340 Cursor.ReadAbbrevRecord();
1344 Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
1348 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1349 Tok.setLength(Record[Idx++]);
1350 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1351 Tok.setIdentifierInfo(II);
1352 Tok.setKind((tok::TokenKind)Record[Idx++]);
1353 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1357 MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
1358 BitstreamCursor &Stream = F.MacroCursor;
1360 // Keep track of where we are in the stream, then jump back there
1361 // after reading this macro.
1362 SavedStreamPosition SavedPosition(Stream);
1364 Stream.JumpToBit(Offset);
1366 SmallVector<IdentifierInfo*, 16> MacroArgs;
1367 MacroInfo *Macro = nullptr;
1370 // Advance to the next record, but if we get to the end of the block, don't
1371 // pop it (removing all the abbreviations from the cursor) since we want to
1372 // be able to reseek within the block and read entries.
1373 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
1374 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1376 switch (Entry.Kind) {
1377 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1378 case llvm::BitstreamEntry::Error:
1379 Error("malformed block record in AST file");
1381 case llvm::BitstreamEntry::EndBlock:
1383 case llvm::BitstreamEntry::Record:
1384 // The interesting case.
1390 PreprocessorRecordTypes RecType =
1391 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
1393 case PP_MODULE_MACRO:
1394 case PP_MACRO_DIRECTIVE_HISTORY:
1397 case PP_MACRO_OBJECT_LIKE:
1398 case PP_MACRO_FUNCTION_LIKE: {
1399 // If we already have a macro, that means that we've hit the end
1400 // of the definition of the macro we were looking for. We're
1405 unsigned NextIndex = 1; // Skip identifier ID.
1406 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
1407 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
1408 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
1409 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
1410 MI->setIsUsed(Record[NextIndex++]);
1411 MI->setUsedForHeaderGuard(Record[NextIndex++]);
1413 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1414 // Decode function-like macro info.
1415 bool isC99VarArgs = Record[NextIndex++];
1416 bool isGNUVarArgs = Record[NextIndex++];
1417 bool hasCommaPasting = Record[NextIndex++];
1419 unsigned NumArgs = Record[NextIndex++];
1420 for (unsigned i = 0; i != NumArgs; ++i)
1421 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1423 // Install function-like macro info.
1424 MI->setIsFunctionLike();
1425 if (isC99VarArgs) MI->setIsC99Varargs();
1426 if (isGNUVarArgs) MI->setIsGNUVarargs();
1427 if (hasCommaPasting) MI->setHasCommaPasting();
1428 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
1429 PP.getPreprocessorAllocator());
1432 // Remember that we saw this macro last so that we add the tokens that
1433 // form its body to it.
1436 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1437 Record[NextIndex]) {
1438 // We have a macro definition. Register the association
1439 PreprocessedEntityID
1440 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1441 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
1442 PreprocessingRecord::PPEntityID PPID =
1443 PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
1444 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
1445 PPRec.getPreprocessedEntity(PPID));
1447 PPRec.RegisterMacroDefinition(Macro, PPDef);
1455 // If we see a TOKEN before a PP_MACRO_*, then the file is
1456 // erroneous, just pretend we didn't see this.
1460 Token Tok = ReadToken(F, Record, Idx);
1461 Macro->AddTokenToBody(Tok);
1468 PreprocessedEntityID
1469 ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
1470 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1471 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1472 assert(I != M.PreprocessedEntityRemap.end()
1473 && "Invalid index into preprocessed entity index remap");
1475 return LocalID + I->second;
1478 unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1479 return llvm::hash_combine(ikey.Size, ikey.ModTime);
1482 HeaderFileInfoTrait::internal_key_type
1483 HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
1484 internal_key_type ikey = { FE->getSize(), FE->getModificationTime(),
1485 FE->getName(), /*Imported*/false };
1489 bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
1490 if (a.Size != b.Size || a.ModTime != b.ModTime)
1493 if (llvm::sys::path::is_absolute(a.Filename) &&
1494 strcmp(a.Filename, b.Filename) == 0)
1497 // Determine whether the actual files are equivalent.
1498 FileManager &FileMgr = Reader.getFileManager();
1499 auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
1501 return FileMgr.getFile(Key.Filename);
1503 std::string Resolved = Key.Filename;
1504 Reader.ResolveImportedPath(M, Resolved);
1505 return FileMgr.getFile(Resolved);
1508 const FileEntry *FEA = GetFile(a);
1509 const FileEntry *FEB = GetFile(b);
1510 return FEA && FEA == FEB;
1513 std::pair<unsigned, unsigned>
1514 HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
1515 using namespace llvm::support;
1516 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
1517 unsigned DataLen = (unsigned) *d++;
1518 return std::make_pair(KeyLen, DataLen);
1521 HeaderFileInfoTrait::internal_key_type
1522 HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
1523 using namespace llvm::support;
1524 internal_key_type ikey;
1525 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1526 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
1527 ikey.Filename = (const char *)d;
1528 ikey.Imported = true;
1532 HeaderFileInfoTrait::data_type
1533 HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
1535 const unsigned char *End = d + DataLen;
1536 using namespace llvm::support;
1538 unsigned Flags = *d++;
1539 HFI.HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>
1540 ((Flags >> 6) & 0x03);
1541 HFI.isImport = (Flags >> 5) & 0x01;
1542 HFI.isPragmaOnce = (Flags >> 4) & 0x01;
1543 HFI.DirInfo = (Flags >> 2) & 0x03;
1544 HFI.Resolved = (Flags >> 1) & 0x01;
1545 HFI.IndexHeaderMapHeader = Flags & 0x01;
1546 HFI.NumIncludes = endian::readNext<uint16_t, little, unaligned>(d);
1547 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1548 M, endian::readNext<uint32_t, little, unaligned>(d));
1549 if (unsigned FrameworkOffset =
1550 endian::readNext<uint32_t, little, unaligned>(d)) {
1551 // The framework offset is 1 greater than the actual offset,
1552 // since 0 is used as an indicator for "no framework name".
1553 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1554 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1558 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
1560 // This header is part of a module. Associate it with the module to enable
1561 // implicit module import.
1562 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1563 Module *Mod = Reader.getSubmodule(GlobalSMID);
1564 HFI.isModuleHeader = true;
1565 FileManager &FileMgr = Reader.getFileManager();
1567 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1568 // FIXME: This information should be propagated through the
1569 // SUBMODULE_HEADER etc records rather than from here.
1570 // FIXME: We don't ever mark excluded headers.
1571 std::string Filename = key.Filename;
1573 Reader.ResolveImportedPath(M, Filename);
1574 Module::Header H = { key.Filename, FileMgr.getFile(Filename) };
1575 ModMap.addHeader(Mod, H, HFI.getHeaderRole());
1579 assert(End == d && "Wrong data length in HeaderFileInfo deserialization");
1582 // This HeaderFileInfo was externally loaded.
1583 HFI.External = true;
1587 void ASTReader::addPendingMacro(IdentifierInfo *II,
1589 uint64_t MacroDirectivesOffset) {
1590 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1591 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
1594 void ASTReader::ReadDefinedMacros() {
1595 // Note that we are loading defined macros.
1596 Deserializing Macros(this);
1598 for (ModuleReverseIterator I = ModuleMgr.rbegin(),
1599 E = ModuleMgr.rend(); I != E; ++I) {
1600 BitstreamCursor &MacroCursor = (*I)->MacroCursor;
1602 // If there was no preprocessor block, skip this file.
1603 if (!MacroCursor.getBitStreamReader())
1606 BitstreamCursor Cursor = MacroCursor;
1607 Cursor.JumpToBit((*I)->MacroStartOffset);
1611 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1614 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1615 case llvm::BitstreamEntry::Error:
1616 Error("malformed block record in AST file");
1618 case llvm::BitstreamEntry::EndBlock:
1621 case llvm::BitstreamEntry::Record:
1623 switch (Cursor.readRecord(E.ID, Record)) {
1624 default: // Default behavior: ignore.
1627 case PP_MACRO_OBJECT_LIKE:
1628 case PP_MACRO_FUNCTION_LIKE:
1629 getLocalIdentifier(**I, Record[0]);
1644 /// \brief Visitor class used to look up identifirs in an AST file.
1645 class IdentifierLookupVisitor {
1647 unsigned PriorGeneration;
1648 unsigned &NumIdentifierLookups;
1649 unsigned &NumIdentifierLookupHits;
1650 IdentifierInfo *Found;
1653 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1654 unsigned &NumIdentifierLookups,
1655 unsigned &NumIdentifierLookupHits)
1656 : Name(Name), PriorGeneration(PriorGeneration),
1657 NumIdentifierLookups(NumIdentifierLookups),
1658 NumIdentifierLookupHits(NumIdentifierLookupHits),
1663 static bool visit(ModuleFile &M, void *UserData) {
1664 IdentifierLookupVisitor *This
1665 = static_cast<IdentifierLookupVisitor *>(UserData);
1667 // If we've already searched this module file, skip it now.
1668 if (M.Generation <= This->PriorGeneration)
1671 ASTIdentifierLookupTable *IdTable
1672 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1676 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(),
1678 ++This->NumIdentifierLookups;
1679 ASTIdentifierLookupTable::iterator Pos = IdTable->find(This->Name,&Trait);
1680 if (Pos == IdTable->end())
1683 // Dereferencing the iterator has the effect of building the
1684 // IdentifierInfo node and populating it with the various
1685 // declarations it needs.
1686 ++This->NumIdentifierLookupHits;
1691 // \brief Retrieve the identifier info found within the module
1693 IdentifierInfo *getIdentifierInfo() const { return Found; }
1697 void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1698 // Note that we are loading an identifier.
1699 Deserializing AnIdentifier(this);
1701 unsigned PriorGeneration = 0;
1702 if (getContext().getLangOpts().Modules)
1703 PriorGeneration = IdentifierGeneration[&II];
1705 // If there is a global index, look there first to determine which modules
1706 // provably do not have any results for this identifier.
1707 GlobalModuleIndex::HitSet Hits;
1708 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
1709 if (!loadGlobalIndex()) {
1710 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1715 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
1716 NumIdentifierLookups,
1717 NumIdentifierLookupHits);
1718 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
1719 markIdentifierUpToDate(&II);
1722 void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1726 II->setOutOfDate(false);
1728 // Update the generation for this identifier.
1729 if (getContext().getLangOpts().Modules)
1730 IdentifierGeneration[II] = getGeneration();
1733 void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1734 const PendingMacroInfo &PMInfo) {
1735 ModuleFile &M = *PMInfo.M;
1737 BitstreamCursor &Cursor = M.MacroCursor;
1738 SavedStreamPosition SavedPosition(Cursor);
1739 Cursor.JumpToBit(PMInfo.MacroDirectivesOffset);
1741 struct ModuleMacroRecord {
1742 SubmoduleID SubModID;
1744 SmallVector<SubmoduleID, 8> Overrides;
1746 llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
1748 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
1749 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
1753 llvm::BitstreamEntry Entry =
1754 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1755 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1756 Error("malformed block record in AST file");
1761 switch ((PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
1762 case PP_MACRO_DIRECTIVE_HISTORY:
1765 case PP_MODULE_MACRO: {
1766 ModuleMacros.push_back(ModuleMacroRecord());
1767 auto &Info = ModuleMacros.back();
1768 Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
1769 Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
1770 for (int I = 2, N = Record.size(); I != N; ++I)
1771 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
1776 Error("malformed block record in AST file");
1780 // We found the macro directive history; that's the last record
1785 // Module macros are listed in reverse dependency order.
1787 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
1788 llvm::SmallVector<ModuleMacro*, 8> Overrides;
1789 for (auto &MMR : ModuleMacros) {
1791 for (unsigned ModID : MMR.Overrides) {
1792 Module *Mod = getSubmodule(ModID);
1793 auto *Macro = PP.getModuleMacro(Mod, II);
1794 assert(Macro && "missing definition for overridden macro");
1795 Overrides.push_back(Macro);
1798 bool Inserted = false;
1799 Module *Owner = getSubmodule(MMR.SubModID);
1800 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
1804 // Don't read the directive history for a module; we don't have anywhere
1806 if (M.Kind == MK_ImplicitModule || M.Kind == MK_ExplicitModule)
1809 // Deserialize the macro directives history in reverse source-order.
1810 MacroDirective *Latest = nullptr, *Earliest = nullptr;
1811 unsigned Idx = 0, N = Record.size();
1813 MacroDirective *MD = nullptr;
1814 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
1815 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1817 case MacroDirective::MD_Define: {
1818 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
1819 MD = PP.AllocateDefMacroDirective(MI, Loc);
1822 case MacroDirective::MD_Undefine: {
1823 MD = PP.AllocateUndefMacroDirective(Loc);
1826 case MacroDirective::MD_Visibility:
1827 bool isPublic = Record[Idx++];
1828 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1835 Earliest->setPrevious(MD);
1840 PP.setLoadedMacroDirective(II, Latest);
1843 ASTReader::InputFileInfo
1844 ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
1845 // Go find this input file.
1846 BitstreamCursor &Cursor = F.InputFilesCursor;
1847 SavedStreamPosition SavedPosition(Cursor);
1848 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1850 unsigned Code = Cursor.ReadCode();
1854 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
1855 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
1856 "invalid record type for input file");
1859 std::string Filename;
1864 assert(Record[0] == ID && "Bogus stored ID or offset");
1865 StoredSize = static_cast<off_t>(Record[1]);
1866 StoredTime = static_cast<time_t>(Record[2]);
1867 Overridden = static_cast<bool>(Record[3]);
1869 ResolveImportedPath(F, Filename);
1871 InputFileInfo R = { std::move(Filename), StoredSize, StoredTime, Overridden };
1875 std::string ASTReader::getInputFileName(ModuleFile &F, unsigned int ID) {
1876 return readInputFileInfo(F, ID).Filename;
1879 InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
1880 // If this ID is bogus, just return an empty input file.
1881 if (ID == 0 || ID > F.InputFilesLoaded.size())
1884 // If we've already loaded this input file, return it.
1885 if (F.InputFilesLoaded[ID-1].getFile())
1886 return F.InputFilesLoaded[ID-1];
1888 if (F.InputFilesLoaded[ID-1].isNotFound())
1891 // Go find this input file.
1892 BitstreamCursor &Cursor = F.InputFilesCursor;
1893 SavedStreamPosition SavedPosition(Cursor);
1894 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1896 InputFileInfo FI = readInputFileInfo(F, ID);
1897 off_t StoredSize = FI.StoredSize;
1898 time_t StoredTime = FI.StoredTime;
1899 bool Overridden = FI.Overridden;
1900 StringRef Filename = FI.Filename;
1902 const FileEntry *File
1903 = Overridden? FileMgr.getVirtualFile(Filename, StoredSize, StoredTime)
1904 : FileMgr.getFile(Filename, /*OpenFile=*/false);
1906 // If we didn't find the file, resolve it relative to the
1907 // original directory from which this AST file was created.
1908 if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() &&
1909 F.OriginalDir != CurrentDir) {
1910 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
1913 if (!Resolved.empty())
1914 File = FileMgr.getFile(Resolved);
1917 // For an overridden file, create a virtual file with the stored
1919 if (Overridden && File == nullptr) {
1920 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
1923 if (File == nullptr) {
1925 std::string ErrorStr = "could not find file '";
1926 ErrorStr += Filename;
1927 ErrorStr += "' referenced by AST file";
1928 Error(ErrorStr.c_str());
1930 // Record that we didn't find the file.
1931 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
1935 // Check if there was a request to override the contents of the file
1936 // that was part of the precompiled header. Overridding such a file
1937 // can lead to problems when lexing using the source locations from the
1939 SourceManager &SM = getSourceManager();
1940 if (!Overridden && SM.isFileOverridden(File)) {
1942 Error(diag::err_fe_pch_file_overridden, Filename);
1943 // After emitting the diagnostic, recover by disabling the override so
1944 // that the original file will be used.
1945 SM.disableFileContentsOverride(File);
1946 // The FileEntry is a virtual file entry with the size of the contents
1947 // that would override the original contents. Set it to the original's
1949 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
1950 StoredSize, StoredTime);
1953 bool IsOutOfDate = false;
1955 // For an overridden file, there is nothing to validate.
1956 if (!Overridden && //
1957 (StoredSize != File->getSize() ||
1958 #if defined(LLVM_ON_WIN32)
1961 // In our regression testing, the Windows file system seems to
1962 // have inconsistent modification times that sometimes
1963 // erroneously trigger this error-handling path.
1965 // This also happens in networked file systems, so disable this
1966 // check if validation is disabled or if we have an explicitly
1969 // FIXME: Should we also do this for PCH files? They could also
1970 // reasonably get shared across a network during a distributed build.
1971 (StoredTime != File->getModificationTime() && !DisableValidation &&
1972 F.Kind != MK_ExplicitModule)
1976 // Build a list of the PCH imports that got us here (in reverse).
1977 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
1978 while (ImportStack.back()->ImportedBy.size() > 0)
1979 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
1981 // The top-level PCH is stale.
1982 StringRef TopLevelPCHName(ImportStack.back()->FileName);
1983 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
1985 // Print the import stack.
1986 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
1987 Diag(diag::note_pch_required_by)
1988 << Filename << ImportStack[0]->FileName;
1989 for (unsigned I = 1; I < ImportStack.size(); ++I)
1990 Diag(diag::note_pch_required_by)
1991 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
1994 if (!Diags.isDiagnosticInFlight())
1995 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
2001 InputFile IF = InputFile(File, Overridden, IsOutOfDate);
2003 // Note that we've loaded this input file.
2004 F.InputFilesLoaded[ID-1] = IF;
2008 /// \brief If we are loading a relocatable PCH or module file, and the filename
2009 /// is not an absolute path, add the system or module root to the beginning of
2011 void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2012 // Resolve relative to the base directory, if we have one.
2013 if (!M.BaseDirectory.empty())
2014 return ResolveImportedPath(Filename, M.BaseDirectory);
2017 void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
2018 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2021 SmallString<128> Buffer;
2022 llvm::sys::path::append(Buffer, Prefix, Filename);
2023 Filename.assign(Buffer.begin(), Buffer.end());
2026 ASTReader::ASTReadResult
2027 ASTReader::ReadControlBlock(ModuleFile &F,
2028 SmallVectorImpl<ImportedModule> &Loaded,
2029 const ModuleFile *ImportedBy,
2030 unsigned ClientLoadCapabilities) {
2031 BitstreamCursor &Stream = F.Stream;
2033 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2034 Error("malformed block record in AST file");
2038 // Should we allow the configuration of the module file to differ from the
2039 // configuration of the current translation unit in a compatible way?
2041 // FIXME: Allow this for files explicitly specified with -include-pch too.
2042 bool AllowCompatibleConfigurationMismatch = F.Kind == MK_ExplicitModule;
2044 // Read all of the records and blocks in the control block.
2046 unsigned NumInputs = 0;
2047 unsigned NumUserInputs = 0;
2049 llvm::BitstreamEntry Entry = Stream.advance();
2051 switch (Entry.Kind) {
2052 case llvm::BitstreamEntry::Error:
2053 Error("malformed block record in AST file");
2055 case llvm::BitstreamEntry::EndBlock: {
2056 // Validate input files.
2057 const HeaderSearchOptions &HSOpts =
2058 PP.getHeaderSearchInfo().getHeaderSearchOpts();
2060 // All user input files reside at the index range [0, NumUserInputs), and
2061 // system input files reside at [NumUserInputs, NumInputs).
2062 if (!DisableValidation) {
2063 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
2065 // If we are reading a module, we will create a verification timestamp,
2066 // so we verify all input files. Otherwise, verify only user input
2069 unsigned N = NumUserInputs;
2070 if (ValidateSystemInputs ||
2071 (HSOpts.ModulesValidateOncePerBuildSession &&
2072 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
2073 F.Kind == MK_ImplicitModule))
2076 for (unsigned I = 0; I < N; ++I) {
2077 InputFile IF = getInputFile(F, I+1, Complain);
2078 if (!IF.getFile() || IF.isOutOfDate())
2084 Listener->visitModuleFile(F.FileName);
2086 if (Listener && Listener->needsInputFileVisitation()) {
2087 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2089 for (unsigned I = 0; I < N; ++I) {
2090 bool IsSystem = I >= NumUserInputs;
2091 InputFileInfo FI = readInputFileInfo(F, I+1);
2092 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden);
2099 case llvm::BitstreamEntry::SubBlock:
2101 case INPUT_FILES_BLOCK_ID:
2102 F.InputFilesCursor = Stream;
2103 if (Stream.SkipBlock() || // Skip with the main cursor
2104 // Read the abbreviations
2105 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2106 Error("malformed block record in AST file");
2112 if (Stream.SkipBlock()) {
2113 Error("malformed block record in AST file");
2119 case llvm::BitstreamEntry::Record:
2120 // The interesting case.
2124 // Read and process a record.
2127 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
2129 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2130 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
2131 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2132 : diag::err_pch_version_too_new);
2133 return VersionMismatch;
2136 bool hasErrors = Record[5];
2137 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2138 Diag(diag::err_pch_with_compiler_errors);
2142 F.RelocatablePCH = Record[4];
2143 // Relative paths in a relocatable PCH are relative to our sysroot.
2144 if (F.RelocatablePCH)
2145 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
2147 const std::string &CurBranch = getClangFullRepositoryVersion();
2148 StringRef ASTBranch = Blob;
2149 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2150 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
2151 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
2152 return VersionMismatch;
2158 assert((!F.Signature || F.Signature == Record[0]) && "signature changed");
2159 F.Signature = Record[0];
2163 // Load each of the imported PCH files.
2164 unsigned Idx = 0, N = Record.size();
2166 // Read information about the AST file.
2167 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2168 // The import location will be the local one for now; we will adjust
2169 // all import locations of module imports after the global source
2170 // location info are setup.
2171 SourceLocation ImportLoc =
2172 SourceLocation::getFromRawEncoding(Record[Idx++]);
2173 off_t StoredSize = (off_t)Record[Idx++];
2174 time_t StoredModTime = (time_t)Record[Idx++];
2175 ASTFileSignature StoredSignature = Record[Idx++];
2176 auto ImportedFile = ReadPath(F, Record, Idx);
2178 // Load the AST file.
2179 switch(ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F, Loaded,
2180 StoredSize, StoredModTime, StoredSignature,
2181 ClientLoadCapabilities)) {
2182 case Failure: return Failure;
2183 // If we have to ignore the dependency, we'll have to ignore this too.
2185 case OutOfDate: return OutOfDate;
2186 case VersionMismatch: return VersionMismatch;
2187 case ConfigurationMismatch: return ConfigurationMismatch;
2188 case HadErrors: return HadErrors;
2189 case Success: break;
2195 case KNOWN_MODULE_FILES:
2198 case LANGUAGE_OPTIONS: {
2199 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2200 // FIXME: The &F == *ModuleMgr.begin() check is wrong for modules.
2201 if (Listener && &F == *ModuleMgr.begin() &&
2202 ParseLanguageOptions(Record, Complain, *Listener,
2203 AllowCompatibleConfigurationMismatch) &&
2204 !DisableValidation && !AllowConfigurationMismatch)
2205 return ConfigurationMismatch;
2209 case TARGET_OPTIONS: {
2210 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2211 if (Listener && &F == *ModuleMgr.begin() &&
2212 ParseTargetOptions(Record, Complain, *Listener,
2213 AllowCompatibleConfigurationMismatch) &&
2214 !DisableValidation && !AllowConfigurationMismatch)
2215 return ConfigurationMismatch;
2219 case DIAGNOSTIC_OPTIONS: {
2220 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate)==0;
2221 if (Listener && &F == *ModuleMgr.begin() &&
2222 !AllowCompatibleConfigurationMismatch &&
2223 ParseDiagnosticOptions(Record, Complain, *Listener) &&
2229 case FILE_SYSTEM_OPTIONS: {
2230 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2231 if (Listener && &F == *ModuleMgr.begin() &&
2232 !AllowCompatibleConfigurationMismatch &&
2233 ParseFileSystemOptions(Record, Complain, *Listener) &&
2234 !DisableValidation && !AllowConfigurationMismatch)
2235 return ConfigurationMismatch;
2239 case HEADER_SEARCH_OPTIONS: {
2240 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2241 if (Listener && &F == *ModuleMgr.begin() &&
2242 !AllowCompatibleConfigurationMismatch &&
2243 ParseHeaderSearchOptions(Record, Complain, *Listener) &&
2244 !DisableValidation && !AllowConfigurationMismatch)
2245 return ConfigurationMismatch;
2249 case PREPROCESSOR_OPTIONS: {
2250 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2251 if (Listener && &F == *ModuleMgr.begin() &&
2252 !AllowCompatibleConfigurationMismatch &&
2253 ParsePreprocessorOptions(Record, Complain, *Listener,
2254 SuggestedPredefines) &&
2255 !DisableValidation && !AllowConfigurationMismatch)
2256 return ConfigurationMismatch;
2261 F.OriginalSourceFileID = FileID::get(Record[0]);
2262 F.ActualOriginalSourceFileName = Blob;
2263 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
2264 ResolveImportedPath(F, F.OriginalSourceFileName);
2267 case ORIGINAL_FILE_ID:
2268 F.OriginalSourceFileID = FileID::get(Record[0]);
2271 case ORIGINAL_PCH_DIR:
2272 F.OriginalDir = Blob;
2276 F.ModuleName = Blob;
2278 Listener->ReadModuleName(F.ModuleName);
2281 case MODULE_DIRECTORY: {
2282 assert(!F.ModuleName.empty() &&
2283 "MODULE_DIRECTORY found before MODULE_NAME");
2284 // If we've already loaded a module map file covering this module, we may
2285 // have a better path for it (relative to the current build).
2286 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2287 if (M && M->Directory) {
2288 // If we're implicitly loading a module, the base directory can't
2289 // change between the build and use.
2290 if (F.Kind != MK_ExplicitModule) {
2291 const DirectoryEntry *BuildDir =
2292 PP.getFileManager().getDirectory(Blob);
2293 if (!BuildDir || BuildDir != M->Directory) {
2294 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2295 Diag(diag::err_imported_module_relocated)
2296 << F.ModuleName << Blob << M->Directory->getName();
2300 F.BaseDirectory = M->Directory->getName();
2302 F.BaseDirectory = Blob;
2307 case MODULE_MAP_FILE:
2308 if (ASTReadResult Result =
2309 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2313 case INPUT_FILE_OFFSETS:
2314 NumInputs = Record[0];
2315 NumUserInputs = Record[1];
2316 F.InputFileOffsets =
2317 (const llvm::support::unaligned_uint64_t *)Blob.data();
2318 F.InputFilesLoaded.resize(NumInputs);
2324 ASTReader::ASTReadResult
2325 ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
2326 BitstreamCursor &Stream = F.Stream;
2328 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2329 Error("malformed block record in AST file");
2333 // Read all of the records and blocks for the AST file.
2336 llvm::BitstreamEntry Entry = Stream.advance();
2338 switch (Entry.Kind) {
2339 case llvm::BitstreamEntry::Error:
2340 Error("error at end of module block in AST file");
2342 case llvm::BitstreamEntry::EndBlock: {
2343 // Outside of C++, we do not store a lookup map for the translation unit.
2344 // Instead, mark it as needing a lookup map to be built if this module
2345 // contains any declarations lexically within it (which it always does!).
2346 // This usually has no cost, since we very rarely need the lookup map for
2347 // the translation unit outside C++.
2348 DeclContext *DC = Context.getTranslationUnitDecl();
2349 if (DC->hasExternalLexicalStorage() &&
2350 !getContext().getLangOpts().CPlusPlus)
2351 DC->setMustBuildLookupTable();
2355 case llvm::BitstreamEntry::SubBlock:
2357 case DECLTYPES_BLOCK_ID:
2358 // We lazily load the decls block, but we want to set up the
2359 // DeclsCursor cursor to point into it. Clone our current bitcode
2360 // cursor to it, enter the block and read the abbrevs in that block.
2361 // With the main cursor, we just skip over it.
2362 F.DeclsCursor = Stream;
2363 if (Stream.SkipBlock() || // Skip with the main cursor.
2364 // Read the abbrevs.
2365 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2366 Error("malformed block record in AST file");
2371 case PREPROCESSOR_BLOCK_ID:
2372 F.MacroCursor = Stream;
2373 if (!PP.getExternalSource())
2374 PP.setExternalSource(this);
2376 if (Stream.SkipBlock() ||
2377 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2378 Error("malformed block record in AST file");
2381 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2384 case PREPROCESSOR_DETAIL_BLOCK_ID:
2385 F.PreprocessorDetailCursor = Stream;
2386 if (Stream.SkipBlock() ||
2387 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
2388 PREPROCESSOR_DETAIL_BLOCK_ID)) {
2389 Error("malformed preprocessor detail record in AST file");
2392 F.PreprocessorDetailStartOffset
2393 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2395 if (!PP.getPreprocessingRecord())
2396 PP.createPreprocessingRecord();
2397 if (!PP.getPreprocessingRecord()->getExternalSource())
2398 PP.getPreprocessingRecord()->SetExternalSource(*this);
2401 case SOURCE_MANAGER_BLOCK_ID:
2402 if (ReadSourceManagerBlock(F))
2406 case SUBMODULE_BLOCK_ID:
2407 if (ASTReadResult Result = ReadSubmoduleBlock(F, ClientLoadCapabilities))
2411 case COMMENTS_BLOCK_ID: {
2412 BitstreamCursor C = Stream;
2413 if (Stream.SkipBlock() ||
2414 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2415 Error("malformed comments block in AST file");
2418 CommentsCursors.push_back(std::make_pair(C, &F));
2423 if (Stream.SkipBlock()) {
2424 Error("malformed block record in AST file");
2431 case llvm::BitstreamEntry::Record:
2432 // The interesting case.
2436 // Read and process a record.
2439 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
2440 default: // Default behavior: ignore.
2444 if (F.LocalNumTypes != 0) {
2445 Error("duplicate TYPE_OFFSET record in AST file");
2448 F.TypeOffsets = (const uint32_t *)Blob.data();
2449 F.LocalNumTypes = Record[0];
2450 unsigned LocalBaseTypeIndex = Record[1];
2451 F.BaseTypeIndex = getTotalNumTypes();
2453 if (F.LocalNumTypes > 0) {
2454 // Introduce the global -> local mapping for types within this module.
2455 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2457 // Introduce the local -> global mapping for types within this module.
2458 F.TypeRemap.insertOrReplace(
2459 std::make_pair(LocalBaseTypeIndex,
2460 F.BaseTypeIndex - LocalBaseTypeIndex));
2462 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
2468 if (F.LocalNumDecls != 0) {
2469 Error("duplicate DECL_OFFSET record in AST file");
2472 F.DeclOffsets = (const DeclOffset *)Blob.data();
2473 F.LocalNumDecls = Record[0];
2474 unsigned LocalBaseDeclID = Record[1];
2475 F.BaseDeclID = getTotalNumDecls();
2477 if (F.LocalNumDecls > 0) {
2478 // Introduce the global -> local mapping for declarations within this
2480 GlobalDeclMap.insert(
2481 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2483 // Introduce the local -> global mapping for declarations within this
2485 F.DeclRemap.insertOrReplace(
2486 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2488 // Introduce the global -> local mapping for declarations within this
2490 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
2492 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2497 case TU_UPDATE_LEXICAL: {
2498 DeclContext *TU = Context.getTranslationUnitDecl();
2499 DeclContextInfo &Info = F.DeclContextInfos[TU];
2500 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair *>(Blob.data());
2501 Info.NumLexicalDecls
2502 = static_cast<unsigned int>(Blob.size() / sizeof(KindDeclIDPair));
2503 TU->setHasExternalLexicalStorage(true);
2507 case UPDATE_VISIBLE: {
2509 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
2510 ASTDeclContextNameLookupTable *Table =
2511 ASTDeclContextNameLookupTable::Create(
2512 (const unsigned char *)Blob.data() + Record[Idx++],
2513 (const unsigned char *)Blob.data() + sizeof(uint32_t),
2514 (const unsigned char *)Blob.data(),
2515 ASTDeclContextNameLookupTrait(*this, F));
2516 if (Decl *D = GetExistingDecl(ID)) {
2517 auto *DC = cast<DeclContext>(D);
2518 DC->getPrimaryContext()->setHasExternalVisibleStorage(true);
2519 auto *&LookupTable = F.DeclContextInfos[DC].NameLookupTableData;
2521 LookupTable = Table;
2523 PendingVisibleUpdates[ID].push_back(std::make_pair(Table, &F));
2527 case IDENTIFIER_TABLE:
2528 F.IdentifierTableData = Blob.data();
2530 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2531 (const unsigned char *)F.IdentifierTableData + Record[0],
2532 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2533 (const unsigned char *)F.IdentifierTableData,
2534 ASTIdentifierLookupTrait(*this, F));
2536 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2540 case IDENTIFIER_OFFSET: {
2541 if (F.LocalNumIdentifiers != 0) {
2542 Error("duplicate IDENTIFIER_OFFSET record in AST file");
2545 F.IdentifierOffsets = (const uint32_t *)Blob.data();
2546 F.LocalNumIdentifiers = Record[0];
2547 unsigned LocalBaseIdentifierID = Record[1];
2548 F.BaseIdentifierID = getTotalNumIdentifiers();
2550 if (F.LocalNumIdentifiers > 0) {
2551 // Introduce the global -> local mapping for identifiers within this
2553 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2556 // Introduce the local -> global mapping for identifiers within this
2558 F.IdentifierRemap.insertOrReplace(
2559 std::make_pair(LocalBaseIdentifierID,
2560 F.BaseIdentifierID - LocalBaseIdentifierID));
2562 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2563 + F.LocalNumIdentifiers);
2568 case EAGERLY_DESERIALIZED_DECLS:
2569 // FIXME: Skip reading this record if our ASTConsumer doesn't care
2570 // about "interesting" decls (for instance, if we're building a module).
2571 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2572 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
2576 if (SpecialTypes.empty()) {
2577 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2578 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2582 if (SpecialTypes.size() != Record.size()) {
2583 Error("invalid special-types record");
2587 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2588 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2589 if (!SpecialTypes[I])
2590 SpecialTypes[I] = ID;
2591 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2597 TotalNumStatements += Record[0];
2598 TotalNumMacros += Record[1];
2599 TotalLexicalDeclContexts += Record[2];
2600 TotalVisibleDeclContexts += Record[3];
2603 case UNUSED_FILESCOPED_DECLS:
2604 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2605 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2608 case DELEGATING_CTORS:
2609 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2610 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2613 case WEAK_UNDECLARED_IDENTIFIERS:
2614 if (Record.size() % 4 != 0) {
2615 Error("invalid weak identifiers record");
2619 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2620 // files. This isn't the way to do it :)
2621 WeakUndeclaredIdentifiers.clear();
2623 // Translate the weak, undeclared identifiers into global IDs.
2624 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2625 WeakUndeclaredIdentifiers.push_back(
2626 getGlobalIdentifierID(F, Record[I++]));
2627 WeakUndeclaredIdentifiers.push_back(
2628 getGlobalIdentifierID(F, Record[I++]));
2629 WeakUndeclaredIdentifiers.push_back(
2630 ReadSourceLocation(F, Record, I).getRawEncoding());
2631 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2635 case SELECTOR_OFFSETS: {
2636 F.SelectorOffsets = (const uint32_t *)Blob.data();
2637 F.LocalNumSelectors = Record[0];
2638 unsigned LocalBaseSelectorID = Record[1];
2639 F.BaseSelectorID = getTotalNumSelectors();
2641 if (F.LocalNumSelectors > 0) {
2642 // Introduce the global -> local mapping for selectors within this
2644 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2646 // Introduce the local -> global mapping for selectors within this
2648 F.SelectorRemap.insertOrReplace(
2649 std::make_pair(LocalBaseSelectorID,
2650 F.BaseSelectorID - LocalBaseSelectorID));
2652 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
2658 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
2660 F.SelectorLookupTable
2661 = ASTSelectorLookupTable::Create(
2662 F.SelectorLookupTableData + Record[0],
2663 F.SelectorLookupTableData,
2664 ASTSelectorLookupTrait(*this, F));
2665 TotalNumMethodPoolEntries += Record[1];
2668 case REFERENCED_SELECTOR_POOL:
2669 if (!Record.empty()) {
2670 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2671 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2673 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2679 case PP_COUNTER_VALUE:
2680 if (!Record.empty() && Listener)
2681 Listener->ReadCounter(F, Record[0]);
2684 case FILE_SORTED_DECLS:
2685 F.FileSortedDecls = (const DeclID *)Blob.data();
2686 F.NumFileSortedDecls = Record[0];
2689 case SOURCE_LOCATION_OFFSETS: {
2690 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
2691 F.LocalNumSLocEntries = Record[0];
2692 unsigned SLocSpaceSize = Record[1];
2693 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
2694 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
2696 // Make our entry in the range map. BaseID is negative and growing, so
2697 // we invert it. Because we invert it, though, we need the other end of
2699 unsigned RangeStart =
2700 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2701 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2702 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2704 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2705 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2706 GlobalSLocOffsetMap.insert(
2707 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2708 - SLocSpaceSize,&F));
2710 // Initialize the remapping table.
2711 // Invalid stays invalid.
2712 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
2713 // This module. Base was 2 when being compiled.
2714 F.SLocRemap.insertOrReplace(std::make_pair(2U,
2715 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2717 TotalNumSLocEntries += F.LocalNumSLocEntries;
2721 case MODULE_OFFSET_MAP: {
2722 // Additional remapping information.
2723 const unsigned char *Data = (const unsigned char*)Blob.data();
2724 const unsigned char *DataEnd = Data + Blob.size();
2726 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
2727 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
2728 F.SLocRemap.insert(std::make_pair(0U, 0));
2729 F.SLocRemap.insert(std::make_pair(2U, 1));
2732 // Continuous range maps we may be updating in our module.
2733 typedef ContinuousRangeMap<uint32_t, int, 2>::Builder
2735 RemapBuilder SLocRemap(F.SLocRemap);
2736 RemapBuilder IdentifierRemap(F.IdentifierRemap);
2737 RemapBuilder MacroRemap(F.MacroRemap);
2738 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2739 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
2740 RemapBuilder SelectorRemap(F.SelectorRemap);
2741 RemapBuilder DeclRemap(F.DeclRemap);
2742 RemapBuilder TypeRemap(F.TypeRemap);
2744 while(Data < DataEnd) {
2745 using namespace llvm::support;
2746 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
2747 StringRef Name = StringRef((const char*)Data, Len);
2749 ModuleFile *OM = ModuleMgr.lookup(Name);
2751 Error("SourceLocation remap refers to unknown module");
2755 uint32_t SLocOffset =
2756 endian::readNext<uint32_t, little, unaligned>(Data);
2757 uint32_t IdentifierIDOffset =
2758 endian::readNext<uint32_t, little, unaligned>(Data);
2759 uint32_t MacroIDOffset =
2760 endian::readNext<uint32_t, little, unaligned>(Data);
2761 uint32_t PreprocessedEntityIDOffset =
2762 endian::readNext<uint32_t, little, unaligned>(Data);
2763 uint32_t SubmoduleIDOffset =
2764 endian::readNext<uint32_t, little, unaligned>(Data);
2765 uint32_t SelectorIDOffset =
2766 endian::readNext<uint32_t, little, unaligned>(Data);
2767 uint32_t DeclIDOffset =
2768 endian::readNext<uint32_t, little, unaligned>(Data);
2769 uint32_t TypeIndexOffset =
2770 endian::readNext<uint32_t, little, unaligned>(Data);
2772 uint32_t None = std::numeric_limits<uint32_t>::max();
2774 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
2775 RemapBuilder &Remap) {
2777 Remap.insert(std::make_pair(Offset,
2778 static_cast<int>(BaseOffset - Offset)));
2780 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
2781 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
2782 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
2783 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
2784 PreprocessedEntityRemap);
2785 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
2786 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
2787 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
2788 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
2790 // Global -> local mappings.
2791 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
2796 case SOURCE_MANAGER_LINE_TABLE:
2797 if (ParseLineTable(F, Record))
2801 case SOURCE_LOCATION_PRELOADS: {
2802 // Need to transform from the local view (1-based IDs) to the global view,
2803 // which is based off F.SLocEntryBaseID.
2804 if (!F.PreloadSLocEntries.empty()) {
2805 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
2809 F.PreloadSLocEntries.swap(Record);
2813 case EXT_VECTOR_DECLS:
2814 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2815 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
2819 if (Record.size() % 3 != 0) {
2820 Error("Invalid VTABLE_USES record");
2824 // Later tables overwrite earlier ones.
2825 // FIXME: Modules will have some trouble with this. This is clearly not
2826 // the right way to do this.
2829 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
2830 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
2831 VTableUses.push_back(
2832 ReadSourceLocation(F, Record, Idx).getRawEncoding());
2833 VTableUses.push_back(Record[Idx++]);
2837 case PENDING_IMPLICIT_INSTANTIATIONS:
2838 if (PendingInstantiations.size() % 2 != 0) {
2839 Error("Invalid existing PendingInstantiations");
2843 if (Record.size() % 2 != 0) {
2844 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
2848 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
2849 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
2850 PendingInstantiations.push_back(
2851 ReadSourceLocation(F, Record, I).getRawEncoding());
2855 case SEMA_DECL_REFS:
2856 if (Record.size() != 2) {
2857 Error("Invalid SEMA_DECL_REFS block");
2860 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2861 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2864 case PPD_ENTITIES_OFFSETS: {
2865 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
2866 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
2867 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
2869 unsigned LocalBasePreprocessedEntityID = Record[0];
2871 unsigned StartingID;
2872 if (!PP.getPreprocessingRecord())
2873 PP.createPreprocessingRecord();
2874 if (!PP.getPreprocessingRecord()->getExternalSource())
2875 PP.getPreprocessingRecord()->SetExternalSource(*this);
2877 = PP.getPreprocessingRecord()
2878 ->allocateLoadedEntities(F.NumPreprocessedEntities);
2879 F.BasePreprocessedEntityID = StartingID;
2881 if (F.NumPreprocessedEntities > 0) {
2882 // Introduce the global -> local mapping for preprocessed entities in
2884 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
2886 // Introduce the local -> global mapping for preprocessed entities in
2888 F.PreprocessedEntityRemap.insertOrReplace(
2889 std::make_pair(LocalBasePreprocessedEntityID,
2890 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
2896 case DECL_UPDATE_OFFSETS: {
2897 if (Record.size() % 2 != 0) {
2898 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
2901 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
2902 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
2903 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
2905 // If we've already loaded the decl, perform the updates when we finish
2906 // loading this block.
2907 if (Decl *D = GetExistingDecl(ID))
2908 PendingUpdateRecords.push_back(std::make_pair(ID, D));
2913 case DECL_REPLACEMENTS: {
2914 if (Record.size() % 3 != 0) {
2915 Error("invalid DECL_REPLACEMENTS block in AST file");
2918 for (unsigned I = 0, N = Record.size(); I != N; I += 3)
2919 ReplacedDecls[getGlobalDeclID(F, Record[I])]
2920 = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
2924 case OBJC_CATEGORIES_MAP: {
2925 if (F.LocalNumObjCCategoriesInMap != 0) {
2926 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
2930 F.LocalNumObjCCategoriesInMap = Record[0];
2931 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
2935 case OBJC_CATEGORIES:
2936 F.ObjCCategories.swap(Record);
2939 case CXX_BASE_SPECIFIER_OFFSETS: {
2940 if (F.LocalNumCXXBaseSpecifiers != 0) {
2941 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
2945 F.LocalNumCXXBaseSpecifiers = Record[0];
2946 F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
2950 case CXX_CTOR_INITIALIZERS_OFFSETS: {
2951 if (F.LocalNumCXXCtorInitializers != 0) {
2952 Error("duplicate CXX_CTOR_INITIALIZERS_OFFSETS record in AST file");
2956 F.LocalNumCXXCtorInitializers = Record[0];
2957 F.CXXCtorInitializersOffsets = (const uint32_t *)Blob.data();
2961 case DIAG_PRAGMA_MAPPINGS:
2962 if (F.PragmaDiagMappings.empty())
2963 F.PragmaDiagMappings.swap(Record);
2965 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
2966 Record.begin(), Record.end());
2969 case CUDA_SPECIAL_DECL_REFS:
2970 // Later tables overwrite earlier ones.
2971 // FIXME: Modules will have trouble with this.
2972 CUDASpecialDeclRefs.clear();
2973 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2974 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2977 case HEADER_SEARCH_TABLE: {
2978 F.HeaderFileInfoTableData = Blob.data();
2979 F.LocalNumHeaderFileInfos = Record[1];
2981 F.HeaderFileInfoTable
2982 = HeaderFileInfoLookupTable::Create(
2983 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
2984 (const unsigned char *)F.HeaderFileInfoTableData,
2985 HeaderFileInfoTrait(*this, F,
2986 &PP.getHeaderSearchInfo(),
2987 Blob.data() + Record[2]));
2989 PP.getHeaderSearchInfo().SetExternalSource(this);
2990 if (!PP.getHeaderSearchInfo().getExternalLookup())
2991 PP.getHeaderSearchInfo().SetExternalLookup(this);
2996 case FP_PRAGMA_OPTIONS:
2997 // Later tables overwrite earlier ones.
2998 FPPragmaOptions.swap(Record);
3001 case OPENCL_EXTENSIONS:
3002 // Later tables overwrite earlier ones.
3003 OpenCLExtensions.swap(Record);
3006 case TENTATIVE_DEFINITIONS:
3007 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3008 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3011 case KNOWN_NAMESPACES:
3012 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3013 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3016 case UNDEFINED_BUT_USED:
3017 if (UndefinedButUsed.size() % 2 != 0) {
3018 Error("Invalid existing UndefinedButUsed");
3022 if (Record.size() % 2 != 0) {
3023 Error("invalid undefined-but-used record");
3026 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3027 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3028 UndefinedButUsed.push_back(
3029 ReadSourceLocation(F, Record, I).getRawEncoding());
3032 case DELETE_EXPRS_TO_ANALYZE:
3033 for (unsigned I = 0, N = Record.size(); I != N;) {
3034 DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
3035 const uint64_t Count = Record[I++];
3036 DelayedDeleteExprs.push_back(Count);
3037 for (uint64_t C = 0; C < Count; ++C) {
3038 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3039 bool IsArrayForm = Record[I++] == 1;
3040 DelayedDeleteExprs.push_back(IsArrayForm);
3045 case IMPORTED_MODULES: {
3046 if (F.Kind != MK_ImplicitModule && F.Kind != MK_ExplicitModule) {
3047 // If we aren't loading a module (which has its own exports), make
3048 // all of the imported modules visible.
3049 // FIXME: Deal with macros-only imports.
3050 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3051 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3052 SourceLocation Loc = ReadSourceLocation(F, Record, I);
3054 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
3060 case LOCAL_REDECLARATIONS: {
3061 F.RedeclarationChains.swap(Record);
3065 case LOCAL_REDECLARATIONS_MAP: {
3066 if (F.LocalNumRedeclarationsInMap != 0) {
3067 Error("duplicate LOCAL_REDECLARATIONS_MAP record in AST file");
3071 F.LocalNumRedeclarationsInMap = Record[0];
3072 F.RedeclarationsMap = (const LocalRedeclarationsInfo *)Blob.data();
3076 case MACRO_OFFSET: {
3077 if (F.LocalNumMacros != 0) {
3078 Error("duplicate MACRO_OFFSET record in AST file");
3081 F.MacroOffsets = (const uint32_t *)Blob.data();
3082 F.LocalNumMacros = Record[0];
3083 unsigned LocalBaseMacroID = Record[1];
3084 F.BaseMacroID = getTotalNumMacros();
3086 if (F.LocalNumMacros > 0) {
3087 // Introduce the global -> local mapping for macros within this module.
3088 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3090 // Introduce the local -> global mapping for macros within this module.
3091 F.MacroRemap.insertOrReplace(
3092 std::make_pair(LocalBaseMacroID,
3093 F.BaseMacroID - LocalBaseMacroID));
3095 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
3100 case LATE_PARSED_TEMPLATE: {
3101 LateParsedTemplates.append(Record.begin(), Record.end());
3105 case OPTIMIZE_PRAGMA_OPTIONS:
3106 if (Record.size() != 1) {
3107 Error("invalid pragma optimize record");
3110 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3113 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3114 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3115 UnusedLocalTypedefNameCandidates.push_back(
3116 getGlobalDeclID(F, Record[I]));
3122 ASTReader::ASTReadResult
3123 ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3124 const ModuleFile *ImportedBy,
3125 unsigned ClientLoadCapabilities) {
3127 F.ModuleMapPath = ReadPath(F, Record, Idx);
3129 if (F.Kind == MK_ExplicitModule) {
3130 // For an explicitly-loaded module, we don't care whether the original
3131 // module map file exists or matches.
3135 // Try to resolve ModuleName in the current header search context and
3136 // verify that it is found in the same module map file as we saved. If the
3137 // top-level AST file is a main file, skip this check because there is no
3138 // usable header search context.
3139 assert(!F.ModuleName.empty() &&
3140 "MODULE_NAME should come before MODULE_MAP_FILE");
3141 if (F.Kind == MK_ImplicitModule &&
3142 (*ModuleMgr.begin())->Kind != MK_MainFile) {
3143 // An implicitly-loaded module file should have its module listed in some
3144 // module map file that we've already loaded.
3145 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
3146 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3147 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3149 assert(ImportedBy && "top-level import should be verified");
3150 if ((ClientLoadCapabilities & ARR_Missing) == 0)
3151 Diag(diag::err_imported_module_not_found) << F.ModuleName << F.FileName
3152 << ImportedBy->FileName
3157 assert(M->Name == F.ModuleName && "found module with different name");
3159 // Check the primary module map file.
3160 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
3161 if (StoredModMap == nullptr || StoredModMap != ModMap) {
3162 assert(ModMap && "found module is missing module map file");
3163 assert(ImportedBy && "top-level import should be verified");
3164 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3165 Diag(diag::err_imported_module_modmap_changed)
3166 << F.ModuleName << ImportedBy->FileName
3167 << ModMap->getName() << F.ModuleMapPath;
3171 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3172 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3173 // FIXME: we should use input files rather than storing names.
3174 std::string Filename = ReadPath(F, Record, Idx);
3175 const FileEntry *F =
3176 FileMgr.getFile(Filename, false, false);
3178 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3179 Error("could not find file '" + Filename +"' referenced by AST file");
3182 AdditionalStoredMaps.insert(F);
3185 // Check any additional module map files (e.g. module.private.modulemap)
3186 // that are not in the pcm.
3187 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
3188 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
3189 // Remove files that match
3190 // Note: SmallPtrSet::erase is really remove
3191 if (!AdditionalStoredMaps.erase(ModMap)) {
3192 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3193 Diag(diag::err_module_different_modmap)
3194 << F.ModuleName << /*new*/0 << ModMap->getName();
3200 // Check any additional module map files that are in the pcm, but not
3201 // found in header search. Cases that match are already removed.
3202 for (const FileEntry *ModMap : AdditionalStoredMaps) {
3203 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3204 Diag(diag::err_module_different_modmap)
3205 << F.ModuleName << /*not new*/1 << ModMap->getName();
3211 Listener->ReadModuleMapFile(F.ModuleMapPath);
3216 /// \brief Move the given method to the back of the global list of methods.
3217 static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3218 // Find the entry for this selector in the method pool.
3219 Sema::GlobalMethodPool::iterator Known
3220 = S.MethodPool.find(Method->getSelector());
3221 if (Known == S.MethodPool.end())
3224 // Retrieve the appropriate method list.
3225 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3226 : Known->second.second;
3228 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
3230 if (List->getMethod() == Method) {
3238 if (List->getNext())
3239 List->setMethod(List->getNext()->getMethod());
3241 List->setMethod(Method);
3245 void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
3246 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
3247 for (Decl *D : Names) {
3248 bool wasHidden = D->Hidden;
3251 if (wasHidden && SemaObj) {
3252 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3253 moveMethodToBackOfGlobalList(*SemaObj, Method);
3259 void ASTReader::makeModuleVisible(Module *Mod,
3260 Module::NameVisibilityKind NameVisibility,
3261 SourceLocation ImportLoc) {
3262 llvm::SmallPtrSet<Module *, 4> Visited;
3263 SmallVector<Module *, 4> Stack;
3264 Stack.push_back(Mod);
3265 while (!Stack.empty()) {
3266 Mod = Stack.pop_back_val();
3268 if (NameVisibility <= Mod->NameVisibility) {
3269 // This module already has this level of visibility (or greater), so
3270 // there is nothing more to do.
3274 if (!Mod->isAvailable()) {
3275 // Modules that aren't available cannot be made visible.
3279 // Update the module's name visibility.
3280 Mod->NameVisibility = NameVisibility;
3282 // If we've already deserialized any names from this module,
3283 // mark them as visible.
3284 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3285 if (Hidden != HiddenNamesMap.end()) {
3286 auto HiddenNames = std::move(*Hidden);
3287 HiddenNamesMap.erase(Hidden);
3288 makeNamesVisible(HiddenNames.second, HiddenNames.first);
3289 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3290 "making names visible added hidden names");
3293 // Push any exported modules onto the stack to be marked as visible.
3294 SmallVector<Module *, 16> Exports;
3295 Mod->getExportedModules(Exports);
3296 for (SmallVectorImpl<Module *>::iterator
3297 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3298 Module *Exported = *I;
3299 if (Visited.insert(Exported).second)
3300 Stack.push_back(Exported);
3305 bool ASTReader::loadGlobalIndex() {
3309 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3310 !Context.getLangOpts().Modules)
3313 // Try to load the global index.
3314 TriedLoadingGlobalIndex = true;
3315 StringRef ModuleCachePath
3316 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3317 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
3318 = GlobalModuleIndex::readIndex(ModuleCachePath);
3322 GlobalIndex.reset(Result.first);
3323 ModuleMgr.setGlobalIndex(GlobalIndex.get());
3327 bool ASTReader::isGlobalIndexUnavailable() const {
3328 return Context.getLangOpts().Modules && UseGlobalIndex &&
3329 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3332 static void updateModuleTimestamp(ModuleFile &MF) {
3333 // Overwrite the timestamp file contents so that file's mtime changes.
3334 std::string TimestampFilename = MF.getTimestampFilename();
3336 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3339 OS << "Timestamp file\n";
3342 ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
3344 SourceLocation ImportLoc,
3345 unsigned ClientLoadCapabilities) {
3346 llvm::SaveAndRestore<SourceLocation>
3347 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3349 // Defer any pending actions until we get to the end of reading the AST file.
3350 Deserializing AnASTFile(this);
3352 // Bump the generation number.
3353 unsigned PreviousGeneration = incrementGeneration(Context);
3355 unsigned NumModules = ModuleMgr.size();
3356 SmallVector<ImportedModule, 4> Loaded;
3357 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
3358 /*ImportedBy=*/nullptr, Loaded,
3360 ClientLoadCapabilities)) {
3364 case VersionMismatch:
3365 case ConfigurationMismatch:
3367 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3368 for (const ImportedModule &IM : Loaded)
3369 LoadedSet.insert(IM.Mod);
3371 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
3373 Context.getLangOpts().Modules
3374 ? &PP.getHeaderSearchInfo().getModuleMap()
3377 // If we find that any modules are unusable, the global index is going
3378 // to be out-of-date. Just remove it.
3379 GlobalIndex.reset();
3380 ModuleMgr.setGlobalIndex(nullptr);
3387 // Here comes stuff that we only do once the entire chain is loaded.
3389 // Load the AST blocks of all of the modules that we loaded.
3390 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3391 MEnd = Loaded.end();
3393 ModuleFile &F = *M->Mod;
3395 // Read the AST block.
3396 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3399 // Once read, set the ModuleFile bit base offset and update the size in
3400 // bits of all files we've seen.
3401 F.GlobalBitOffset = TotalModulesSizeInBits;
3402 TotalModulesSizeInBits += F.SizeInBits;
3403 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3405 // Preload SLocEntries.
3406 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3407 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3408 // Load it through the SourceManager and don't call ReadSLocEntry()
3409 // directly because the entry may have already been loaded in which case
3410 // calling ReadSLocEntry() directly would trigger an assertion in
3412 SourceMgr.getLoadedSLocEntryByID(Index);
3416 // Setup the import locations and notify the module manager that we've
3417 // committed to these module files.
3418 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3419 MEnd = Loaded.end();
3421 ModuleFile &F = *M->Mod;
3423 ModuleMgr.moduleFileAccepted(&F);
3425 // Set the import location.
3426 F.DirectImportLoc = ImportLoc;
3428 F.ImportLoc = M->ImportLoc;
3430 F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
3431 M->ImportLoc.getRawEncoding());
3434 // Mark all of the identifiers in the identifier table as being out of date,
3435 // so that various accessors know to check the loaded modules when the
3436 // identifier is used.
3437 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3438 IdEnd = PP.getIdentifierTable().end();
3440 Id->second->setOutOfDate(true);
3442 // Resolve any unresolved module exports.
3443 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3444 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
3445 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3446 Module *ResolvedMod = getSubmodule(GlobalID);
3448 switch (Unresolved.Kind) {
3449 case UnresolvedModuleRef::Conflict:
3451 Module::Conflict Conflict;
3452 Conflict.Other = ResolvedMod;
3453 Conflict.Message = Unresolved.String.str();
3454 Unresolved.Mod->Conflicts.push_back(Conflict);
3458 case UnresolvedModuleRef::Import:
3460 Unresolved.Mod->Imports.insert(ResolvedMod);
3463 case UnresolvedModuleRef::Export:
3464 if (ResolvedMod || Unresolved.IsWildcard)
3465 Unresolved.Mod->Exports.push_back(
3466 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3470 UnresolvedModuleRefs.clear();
3472 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3473 // Might be unnecessary as use declarations are only used to build the
3476 InitializeContext();
3481 if (DeserializationListener)
3482 DeserializationListener->ReaderInitialized(this);
3484 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
3485 if (!PrimaryModule.OriginalSourceFileID.isInvalid()) {
3486 PrimaryModule.OriginalSourceFileID
3487 = FileID::get(PrimaryModule.SLocEntryBaseID
3488 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3490 // If this AST file is a precompiled preamble, then set the
3491 // preamble file ID of the source manager to the file source file
3492 // from which the preamble was built.
3493 if (Type == MK_Preamble) {
3494 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3495 } else if (Type == MK_MainFile) {
3496 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3500 // For any Objective-C class definitions we have already loaded, make sure
3501 // that we load any additional categories.
3502 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3503 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3504 ObjCClassesLoaded[I],
3505 PreviousGeneration);
3508 if (PP.getHeaderSearchInfo()
3509 .getHeaderSearchOpts()
3510 .ModulesValidateOncePerBuildSession) {
3511 // Now we are certain that the module and all modules it depends on are
3512 // up to date. Create or update timestamp files for modules that are
3513 // located in the module cache (not for PCH files that could be anywhere
3514 // in the filesystem).
3515 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3516 ImportedModule &M = Loaded[I];
3517 if (M.Mod->Kind == MK_ImplicitModule) {
3518 updateModuleTimestamp(*M.Mod);
3526 static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile);
3528 /// \brief Whether \p Stream starts with the AST/PCH file magic number 'CPCH'.
3529 static bool startsWithASTFileMagic(BitstreamCursor &Stream) {
3530 return Stream.Read(8) == 'C' &&
3531 Stream.Read(8) == 'P' &&
3532 Stream.Read(8) == 'C' &&
3533 Stream.Read(8) == 'H';
3536 ASTReader::ASTReadResult
3537 ASTReader::ReadASTCore(StringRef FileName,
3539 SourceLocation ImportLoc,
3540 ModuleFile *ImportedBy,
3541 SmallVectorImpl<ImportedModule> &Loaded,
3542 off_t ExpectedSize, time_t ExpectedModTime,
3543 ASTFileSignature ExpectedSignature,
3544 unsigned ClientLoadCapabilities) {
3546 std::string ErrorStr;
3547 ModuleManager::AddModuleResult AddResult
3548 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
3549 getGeneration(), ExpectedSize, ExpectedModTime,
3550 ExpectedSignature, readASTFileSignature,
3553 switch (AddResult) {
3554 case ModuleManager::AlreadyLoaded:
3557 case ModuleManager::NewlyLoaded:
3558 // Load module file below.
3561 case ModuleManager::Missing:
3562 // The module file was missing; if the client can handle that, return
3564 if (ClientLoadCapabilities & ARR_Missing)
3567 // Otherwise, return an error.
3569 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3575 case ModuleManager::OutOfDate:
3576 // We couldn't load the module file because it is out-of-date. If the
3577 // client can handle out-of-date, return it.
3578 if (ClientLoadCapabilities & ARR_OutOfDate)
3581 // Otherwise, return an error.
3583 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3590 assert(M && "Missing module file");
3592 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3594 if (FileName != "-") {
3595 CurrentDir = llvm::sys::path::parent_path(FileName);
3596 if (CurrentDir.empty()) CurrentDir = ".";
3600 BitstreamCursor &Stream = F.Stream;
3601 PCHContainerOps.ExtractPCH(F.Buffer->getMemBufferRef(), F.StreamFile);
3602 Stream.init(&F.StreamFile);
3603 F.SizeInBits = F.Buffer->getBufferSize() * 8;
3605 // Sniff for the signature.
3606 if (!startsWithASTFileMagic(Stream)) {
3607 Diag(diag::err_not_a_pch_file) << FileName;
3611 // This is used for compatibility with older PCH formats.
3612 bool HaveReadControlBlock = false;
3615 llvm::BitstreamEntry Entry = Stream.advance();
3617 switch (Entry.Kind) {
3618 case llvm::BitstreamEntry::Error:
3619 case llvm::BitstreamEntry::EndBlock:
3620 case llvm::BitstreamEntry::Record:
3621 Error("invalid record at top-level of AST file");
3624 case llvm::BitstreamEntry::SubBlock:
3628 // We only know the control subblock ID.
3630 case llvm::bitc::BLOCKINFO_BLOCK_ID:
3631 if (Stream.ReadBlockInfoBlock()) {
3632 Error("malformed BlockInfoBlock in AST file");
3636 case CONTROL_BLOCK_ID:
3637 HaveReadControlBlock = true;
3638 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
3642 case Failure: return Failure;
3643 case Missing: return Missing;
3644 case OutOfDate: return OutOfDate;
3645 case VersionMismatch: return VersionMismatch;
3646 case ConfigurationMismatch: return ConfigurationMismatch;
3647 case HadErrors: return HadErrors;
3651 if (!HaveReadControlBlock) {
3652 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
3653 Diag(diag::err_pch_version_too_old);
3654 return VersionMismatch;
3657 // Record that we've loaded this module.
3658 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3662 if (Stream.SkipBlock()) {
3663 Error("malformed block record in AST file");
3673 void ASTReader::InitializeContext() {
3674 // If there's a listener, notify them that we "read" the translation unit.
3675 if (DeserializationListener)
3676 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3677 Context.getTranslationUnitDecl());
3679 // FIXME: Find a better way to deal with collisions between these
3680 // built-in types. Right now, we just ignore the problem.
3682 // Load the special types.
3683 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3684 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3685 if (!Context.CFConstantStringTypeDecl)
3686 Context.setCFConstantStringType(GetType(String));
3689 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3690 QualType FileType = GetType(File);
3691 if (FileType.isNull()) {
3692 Error("FILE type is NULL");
3696 if (!Context.FILEDecl) {
3697 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3698 Context.setFILEDecl(Typedef->getDecl());
3700 const TagType *Tag = FileType->getAs<TagType>();
3702 Error("Invalid FILE type in AST file");
3705 Context.setFILEDecl(Tag->getDecl());
3710 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
3711 QualType Jmp_bufType = GetType(Jmp_buf);
3712 if (Jmp_bufType.isNull()) {
3713 Error("jmp_buf type is NULL");
3717 if (!Context.jmp_bufDecl) {
3718 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
3719 Context.setjmp_bufDecl(Typedef->getDecl());
3721 const TagType *Tag = Jmp_bufType->getAs<TagType>();
3723 Error("Invalid jmp_buf type in AST file");
3726 Context.setjmp_bufDecl(Tag->getDecl());
3731 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
3732 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
3733 if (Sigjmp_bufType.isNull()) {
3734 Error("sigjmp_buf type is NULL");
3738 if (!Context.sigjmp_bufDecl) {
3739 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
3740 Context.setsigjmp_bufDecl(Typedef->getDecl());
3742 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
3743 assert(Tag && "Invalid sigjmp_buf type in AST file");
3744 Context.setsigjmp_bufDecl(Tag->getDecl());
3749 if (unsigned ObjCIdRedef
3750 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
3751 if (Context.ObjCIdRedefinitionType.isNull())
3752 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
3755 if (unsigned ObjCClassRedef
3756 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
3757 if (Context.ObjCClassRedefinitionType.isNull())
3758 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
3761 if (unsigned ObjCSelRedef
3762 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
3763 if (Context.ObjCSelRedefinitionType.isNull())
3764 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
3767 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
3768 QualType Ucontext_tType = GetType(Ucontext_t);
3769 if (Ucontext_tType.isNull()) {
3770 Error("ucontext_t type is NULL");
3774 if (!Context.ucontext_tDecl) {
3775 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
3776 Context.setucontext_tDecl(Typedef->getDecl());
3778 const TagType *Tag = Ucontext_tType->getAs<TagType>();
3779 assert(Tag && "Invalid ucontext_t type in AST file");
3780 Context.setucontext_tDecl(Tag->getDecl());
3786 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
3788 // If there were any CUDA special declarations, deserialize them.
3789 if (!CUDASpecialDeclRefs.empty()) {
3790 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
3791 Context.setcudaConfigureCallDecl(
3792 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
3795 // Re-export any modules that were imported by a non-module AST file.
3796 // FIXME: This does not make macro-only imports visible again.
3797 for (auto &Import : ImportedModules) {
3798 if (Module *Imported = getSubmodule(Import.ID)) {
3799 makeModuleVisible(Imported, Module::AllVisible,
3800 /*ImportLoc=*/Import.ImportLoc);
3801 PP.makeModuleVisible(Imported, Import.ImportLoc);
3804 ImportedModules.clear();
3807 void ASTReader::finalizeForWriting() {
3808 // Nothing to do for now.
3811 /// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3812 /// cursor into the start of the given block ID, returning false on success and
3813 /// true on failure.
3814 static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
3816 llvm::BitstreamEntry Entry = Cursor.advance();
3817 switch (Entry.Kind) {
3818 case llvm::BitstreamEntry::Error:
3819 case llvm::BitstreamEntry::EndBlock:
3822 case llvm::BitstreamEntry::Record:
3823 // Ignore top-level records.
3824 Cursor.skipRecord(Entry.ID);
3827 case llvm::BitstreamEntry::SubBlock:
3828 if (Entry.ID == BlockID) {
3829 if (Cursor.EnterSubBlock(BlockID))
3835 if (Cursor.SkipBlock())
3841 /// \brief Reads and return the signature record from \p StreamFile's control
3842 /// block, or else returns 0.
3843 static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile){
3844 BitstreamCursor Stream(StreamFile);
3845 if (!startsWithASTFileMagic(Stream))
3848 // Scan for the CONTROL_BLOCK_ID block.
3849 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
3852 // Scan for SIGNATURE inside the control block.
3853 ASTReader::RecordData Record;
3855 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3856 if (Entry.Kind == llvm::BitstreamEntry::EndBlock ||
3857 Entry.Kind != llvm::BitstreamEntry::Record)
3862 if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
3867 /// \brief Retrieve the name of the original source file name
3868 /// directly from the AST file, without actually loading the AST
3870 std::string ASTReader::getOriginalSourceFile(
3871 const std::string &ASTFileName, FileManager &FileMgr,
3872 const PCHContainerOperations &PCHContainerOps, DiagnosticsEngine &Diags) {
3873 // Open the AST file.
3874 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
3876 Diags.Report(diag::err_fe_unable_to_read_pch_file)
3877 << ASTFileName << Buffer.getError().message();
3878 return std::string();
3881 // Initialize the stream
3882 llvm::BitstreamReader StreamFile;
3883 PCHContainerOps.ExtractPCH((*Buffer)->getMemBufferRef(), StreamFile);
3884 BitstreamCursor Stream(StreamFile);
3886 // Sniff for the signature.
3887 if (!startsWithASTFileMagic(Stream)) {
3888 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
3889 return std::string();
3892 // Scan for the CONTROL_BLOCK_ID block.
3893 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
3894 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3895 return std::string();
3898 // Scan for ORIGINAL_FILE inside the control block.
3901 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3902 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
3903 return std::string();
3905 if (Entry.Kind != llvm::BitstreamEntry::Record) {
3906 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3907 return std::string();
3912 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
3918 class SimplePCHValidator : public ASTReaderListener {
3919 const LangOptions &ExistingLangOpts;
3920 const TargetOptions &ExistingTargetOpts;
3921 const PreprocessorOptions &ExistingPPOpts;
3922 std::string ExistingModuleCachePath;
3923 FileManager &FileMgr;
3926 SimplePCHValidator(const LangOptions &ExistingLangOpts,
3927 const TargetOptions &ExistingTargetOpts,
3928 const PreprocessorOptions &ExistingPPOpts,
3929 StringRef ExistingModuleCachePath,
3930 FileManager &FileMgr)
3931 : ExistingLangOpts(ExistingLangOpts),
3932 ExistingTargetOpts(ExistingTargetOpts),
3933 ExistingPPOpts(ExistingPPOpts),
3934 ExistingModuleCachePath(ExistingModuleCachePath),
3939 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
3940 bool AllowCompatibleDifferences) override {
3941 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
3942 AllowCompatibleDifferences);
3944 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
3945 bool AllowCompatibleDifferences) override {
3946 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
3947 AllowCompatibleDifferences);
3949 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
3950 StringRef SpecificModuleCachePath,
3951 bool Complain) override {
3952 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
3953 ExistingModuleCachePath,
3954 nullptr, ExistingLangOpts);
3956 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
3958 std::string &SuggestedPredefines) override {
3959 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
3960 SuggestedPredefines, ExistingLangOpts);
3965 bool ASTReader::readASTFileControlBlock(
3966 StringRef Filename, FileManager &FileMgr,
3967 const PCHContainerOperations &PCHContainerOps,
3968 ASTReaderListener &Listener) {
3969 // Open the AST file.
3970 // FIXME: This allows use of the VFS; we do not allow use of the
3971 // VFS when actually loading a module.
3972 auto Buffer = FileMgr.getBufferForFile(Filename);
3977 // Initialize the stream
3978 llvm::BitstreamReader StreamFile;
3979 StreamFile.init((const unsigned char *)(*Buffer)->getBufferStart(),
3980 (const unsigned char *)(*Buffer)->getBufferEnd());
3981 BitstreamCursor Stream(StreamFile);
3983 // Sniff for the signature.
3984 if (!startsWithASTFileMagic(Stream))
3987 // Scan for the CONTROL_BLOCK_ID block.
3988 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
3991 bool NeedsInputFiles = Listener.needsInputFileVisitation();
3992 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
3993 bool NeedsImports = Listener.needsImportVisitation();
3994 BitstreamCursor InputFilesCursor;
3995 if (NeedsInputFiles) {
3996 InputFilesCursor = Stream;
3997 if (SkipCursorToBlock(InputFilesCursor, INPUT_FILES_BLOCK_ID))
4000 // Read the abbreviations
4002 uint64_t Offset = InputFilesCursor.GetCurrentBitNo();
4003 unsigned Code = InputFilesCursor.ReadCode();
4005 // We expect all abbrevs to be at the start of the block.
4006 if (Code != llvm::bitc::DEFINE_ABBREV) {
4007 InputFilesCursor.JumpToBit(Offset);
4010 InputFilesCursor.ReadAbbrevRecord();
4014 // Scan for ORIGINAL_FILE inside the control block.
4016 std::string ModuleDir;
4018 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4019 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4022 if (Entry.Kind != llvm::BitstreamEntry::Record)
4027 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4028 switch ((ControlRecordTypes)RecCode) {
4030 if (Record[0] != VERSION_MAJOR)
4033 if (Listener.ReadFullVersionInformation(Blob))
4039 Listener.ReadModuleName(Blob);
4041 case MODULE_DIRECTORY:
4044 case MODULE_MAP_FILE: {
4046 auto Path = ReadString(Record, Idx);
4047 ResolveImportedPath(Path, ModuleDir);
4048 Listener.ReadModuleMapFile(Path);
4051 case LANGUAGE_OPTIONS:
4052 if (ParseLanguageOptions(Record, false, Listener,
4053 /*AllowCompatibleConfigurationMismatch*/false))
4057 case TARGET_OPTIONS:
4058 if (ParseTargetOptions(Record, false, Listener,
4059 /*AllowCompatibleConfigurationMismatch*/ false))
4063 case DIAGNOSTIC_OPTIONS:
4064 if (ParseDiagnosticOptions(Record, false, Listener))
4068 case FILE_SYSTEM_OPTIONS:
4069 if (ParseFileSystemOptions(Record, false, Listener))
4073 case HEADER_SEARCH_OPTIONS:
4074 if (ParseHeaderSearchOptions(Record, false, Listener))
4078 case PREPROCESSOR_OPTIONS: {
4079 std::string IgnoredSuggestedPredefines;
4080 if (ParsePreprocessorOptions(Record, false, Listener,
4081 IgnoredSuggestedPredefines))
4086 case INPUT_FILE_OFFSETS: {
4087 if (!NeedsInputFiles)
4090 unsigned NumInputFiles = Record[0];
4091 unsigned NumUserFiles = Record[1];
4092 const uint64_t *InputFileOffs = (const uint64_t *)Blob.data();
4093 for (unsigned I = 0; I != NumInputFiles; ++I) {
4094 // Go find this input file.
4095 bool isSystemFile = I >= NumUserFiles;
4097 if (isSystemFile && !NeedsSystemInputFiles)
4098 break; // the rest are system input files
4100 BitstreamCursor &Cursor = InputFilesCursor;
4101 SavedStreamPosition SavedPosition(Cursor);
4102 Cursor.JumpToBit(InputFileOffs[I]);
4104 unsigned Code = Cursor.ReadCode();
4107 bool shouldContinue = false;
4108 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4110 bool Overridden = static_cast<bool>(Record[3]);
4111 std::string Filename = Blob;
4112 ResolveImportedPath(Filename, ModuleDir);
4114 Listener.visitInputFile(Filename, isSystemFile, Overridden);
4117 if (!shouldContinue)
4127 unsigned Idx = 0, N = Record.size();
4129 // Read information about the AST file.
4130 Idx += 5; // ImportLoc, Size, ModTime, Signature
4131 std::string Filename = ReadString(Record, Idx);
4132 ResolveImportedPath(Filename, ModuleDir);
4133 Listener.visitImport(Filename);
4138 case KNOWN_MODULE_FILES: {
4139 // Known-but-not-technically-used module files are treated as imports.
4143 unsigned Idx = 0, N = Record.size();
4145 std::string Filename = ReadString(Record, Idx);
4146 ResolveImportedPath(Filename, ModuleDir);
4147 Listener.visitImport(Filename);
4153 // No other validation to perform.
4159 bool ASTReader::isAcceptableASTFile(
4160 StringRef Filename, FileManager &FileMgr,
4161 const PCHContainerOperations &PCHContainerOps, const LangOptions &LangOpts,
4162 const TargetOptions &TargetOpts, const PreprocessorOptions &PPOpts,
4163 std::string ExistingModuleCachePath) {
4164 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
4165 ExistingModuleCachePath, FileMgr);
4166 return !readASTFileControlBlock(Filename, FileMgr, PCHContainerOps,
4170 ASTReader::ASTReadResult
4171 ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
4172 // Enter the submodule block.
4173 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4174 Error("malformed submodule block record in AST file");
4178 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4180 Module *CurrentModule = nullptr;
4183 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
4185 switch (Entry.Kind) {
4186 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4187 case llvm::BitstreamEntry::Error:
4188 Error("malformed block record in AST file");
4190 case llvm::BitstreamEntry::EndBlock:
4192 case llvm::BitstreamEntry::Record:
4193 // The interesting case.
4200 auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
4202 if ((Kind == SUBMODULE_METADATA) != First) {
4203 Error("submodule metadata record should be at beginning of block");
4208 // Submodule information is only valid if we have a current module.
4209 // FIXME: Should we error on these cases?
4210 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
4211 Kind != SUBMODULE_DEFINITION)
4215 default: // Default behavior: ignore.
4218 case SUBMODULE_DEFINITION: {
4219 if (Record.size() < 8) {
4220 Error("malformed module definition");
4224 StringRef Name = Blob;
4226 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4227 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4228 bool IsFramework = Record[Idx++];
4229 bool IsExplicit = Record[Idx++];
4230 bool IsSystem = Record[Idx++];
4231 bool IsExternC = Record[Idx++];
4232 bool InferSubmodules = Record[Idx++];
4233 bool InferExplicitSubmodules = Record[Idx++];
4234 bool InferExportWildcard = Record[Idx++];
4235 bool ConfigMacrosExhaustive = Record[Idx++];
4237 Module *ParentModule = nullptr;
4239 ParentModule = getSubmodule(Parent);
4241 // Retrieve this (sub)module from the module map, creating it if
4243 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule, IsFramework,
4246 // FIXME: set the definition loc for CurrentModule, or call
4247 // ModMap.setInferredModuleAllowedBy()
4249 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4250 if (GlobalIndex >= SubmodulesLoaded.size() ||
4251 SubmodulesLoaded[GlobalIndex]) {
4252 Error("too many submodules");
4256 if (!ParentModule) {
4257 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4258 if (CurFile != F.File) {
4259 if (!Diags.isDiagnosticInFlight()) {
4260 Diag(diag::err_module_file_conflict)
4261 << CurrentModule->getTopLevelModuleName()
4262 << CurFile->getName()
4263 << F.File->getName();
4269 CurrentModule->setASTFile(F.File);
4272 CurrentModule->Signature = F.Signature;
4273 CurrentModule->IsFromModuleFile = true;
4274 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
4275 CurrentModule->IsExternC = IsExternC;
4276 CurrentModule->InferSubmodules = InferSubmodules;
4277 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4278 CurrentModule->InferExportWildcard = InferExportWildcard;
4279 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
4280 if (DeserializationListener)
4281 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
4283 SubmodulesLoaded[GlobalIndex] = CurrentModule;
4285 // Clear out data that will be replaced by what is the module file.
4286 CurrentModule->LinkLibraries.clear();
4287 CurrentModule->ConfigMacros.clear();
4288 CurrentModule->UnresolvedConflicts.clear();
4289 CurrentModule->Conflicts.clear();
4293 case SUBMODULE_UMBRELLA_HEADER: {
4294 std::string Filename = Blob;
4295 ResolveImportedPath(F, Filename);
4296 if (auto *Umbrella = PP.getFileManager().getFile(Filename)) {
4297 if (!CurrentModule->getUmbrellaHeader())
4298 ModMap.setUmbrellaHeader(CurrentModule, Umbrella, Blob);
4299 else if (CurrentModule->getUmbrellaHeader().Entry != Umbrella) {
4300 // This can be a spurious difference caused by changing the VFS to
4301 // point to a different copy of the file, and it is too late to
4302 // to rebuild safely.
4303 // FIXME: If we wrote the virtual paths instead of the 'real' paths,
4304 // after input file validation only real problems would remain and we
4305 // could just error. For now, assume it's okay.
4312 case SUBMODULE_HEADER:
4313 case SUBMODULE_EXCLUDED_HEADER:
4314 case SUBMODULE_PRIVATE_HEADER:
4315 // We lazily associate headers with their modules via the HeaderInfo table.
4316 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4317 // of complete filenames or remove it entirely.
4320 case SUBMODULE_TEXTUAL_HEADER:
4321 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
4322 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
4326 case SUBMODULE_TOPHEADER: {
4327 CurrentModule->addTopHeaderFilename(Blob);
4331 case SUBMODULE_UMBRELLA_DIR: {
4332 std::string Dirname = Blob;
4333 ResolveImportedPath(F, Dirname);
4334 if (auto *Umbrella = PP.getFileManager().getDirectory(Dirname)) {
4335 if (!CurrentModule->getUmbrellaDir())
4336 ModMap.setUmbrellaDir(CurrentModule, Umbrella, Blob);
4337 else if (CurrentModule->getUmbrellaDir().Entry != Umbrella) {
4338 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4339 Error("mismatched umbrella directories in submodule");
4346 case SUBMODULE_METADATA: {
4347 F.BaseSubmoduleID = getTotalNumSubmodules();
4348 F.LocalNumSubmodules = Record[0];
4349 unsigned LocalBaseSubmoduleID = Record[1];
4350 if (F.LocalNumSubmodules > 0) {
4351 // Introduce the global -> local mapping for submodules within this
4353 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
4355 // Introduce the local -> global mapping for submodules within this
4357 F.SubmoduleRemap.insertOrReplace(
4358 std::make_pair(LocalBaseSubmoduleID,
4359 F.BaseSubmoduleID - LocalBaseSubmoduleID));
4361 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4366 case SUBMODULE_IMPORTS: {
4367 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
4368 UnresolvedModuleRef Unresolved;
4369 Unresolved.File = &F;
4370 Unresolved.Mod = CurrentModule;
4371 Unresolved.ID = Record[Idx];
4372 Unresolved.Kind = UnresolvedModuleRef::Import;
4373 Unresolved.IsWildcard = false;
4374 UnresolvedModuleRefs.push_back(Unresolved);
4379 case SUBMODULE_EXPORTS: {
4380 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
4381 UnresolvedModuleRef Unresolved;
4382 Unresolved.File = &F;
4383 Unresolved.Mod = CurrentModule;
4384 Unresolved.ID = Record[Idx];
4385 Unresolved.Kind = UnresolvedModuleRef::Export;
4386 Unresolved.IsWildcard = Record[Idx + 1];
4387 UnresolvedModuleRefs.push_back(Unresolved);
4390 // Once we've loaded the set of exports, there's no reason to keep
4391 // the parsed, unresolved exports around.
4392 CurrentModule->UnresolvedExports.clear();
4395 case SUBMODULE_REQUIRES: {
4396 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
4397 Context.getTargetInfo());
4401 case SUBMODULE_LINK_LIBRARY:
4402 CurrentModule->LinkLibraries.push_back(
4403 Module::LinkLibrary(Blob, Record[0]));
4406 case SUBMODULE_CONFIG_MACRO:
4407 CurrentModule->ConfigMacros.push_back(Blob.str());
4410 case SUBMODULE_CONFLICT: {
4411 UnresolvedModuleRef Unresolved;
4412 Unresolved.File = &F;
4413 Unresolved.Mod = CurrentModule;
4414 Unresolved.ID = Record[0];
4415 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4416 Unresolved.IsWildcard = false;
4417 Unresolved.String = Blob;
4418 UnresolvedModuleRefs.push_back(Unresolved);
4425 /// \brief Parse the record that corresponds to a LangOptions data
4428 /// This routine parses the language options from the AST file and then gives
4429 /// them to the AST listener if one is set.
4431 /// \returns true if the listener deems the file unacceptable, false otherwise.
4432 bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4434 ASTReaderListener &Listener,
4435 bool AllowCompatibleDifferences) {
4436 LangOptions LangOpts;
4438 #define LANGOPT(Name, Bits, Default, Description) \
4439 LangOpts.Name = Record[Idx++];
4440 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4441 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4442 #include "clang/Basic/LangOptions.def"
4443 #define SANITIZER(NAME, ID) \
4444 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
4445 #include "clang/Basic/Sanitizers.def"
4447 for (unsigned N = Record[Idx++]; N; --N)
4448 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
4450 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4451 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4452 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
4454 LangOpts.CurrentModule = ReadString(Record, Idx);
4457 for (unsigned N = Record[Idx++]; N; --N) {
4458 LangOpts.CommentOpts.BlockCommandNames.push_back(
4459 ReadString(Record, Idx));
4461 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
4463 return Listener.ReadLanguageOptions(LangOpts, Complain,
4464 AllowCompatibleDifferences);
4467 bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
4468 ASTReaderListener &Listener,
4469 bool AllowCompatibleDifferences) {
4471 TargetOptions TargetOpts;
4472 TargetOpts.Triple = ReadString(Record, Idx);
4473 TargetOpts.CPU = ReadString(Record, Idx);
4474 TargetOpts.ABI = ReadString(Record, Idx);
4475 for (unsigned N = Record[Idx++]; N; --N) {
4476 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4478 for (unsigned N = Record[Idx++]; N; --N) {
4479 TargetOpts.Features.push_back(ReadString(Record, Idx));
4482 return Listener.ReadTargetOptions(TargetOpts, Complain,
4483 AllowCompatibleDifferences);
4486 bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4487 ASTReaderListener &Listener) {
4488 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
4490 #define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
4491 #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
4492 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
4493 #include "clang/Basic/DiagnosticOptions.def"
4495 for (unsigned N = Record[Idx++]; N; --N)
4496 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
4497 for (unsigned N = Record[Idx++]; N; --N)
4498 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
4500 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4503 bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4504 ASTReaderListener &Listener) {
4505 FileSystemOptions FSOpts;
4507 FSOpts.WorkingDir = ReadString(Record, Idx);
4508 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4511 bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4513 ASTReaderListener &Listener) {
4514 HeaderSearchOptions HSOpts;
4516 HSOpts.Sysroot = ReadString(Record, Idx);
4519 for (unsigned N = Record[Idx++]; N; --N) {
4520 std::string Path = ReadString(Record, Idx);
4521 frontend::IncludeDirGroup Group
4522 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
4523 bool IsFramework = Record[Idx++];
4524 bool IgnoreSysRoot = Record[Idx++];
4525 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
4529 // System header prefixes.
4530 for (unsigned N = Record[Idx++]; N; --N) {
4531 std::string Prefix = ReadString(Record, Idx);
4532 bool IsSystemHeader = Record[Idx++];
4533 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
4536 HSOpts.ResourceDir = ReadString(Record, Idx);
4537 HSOpts.ModuleCachePath = ReadString(Record, Idx);
4538 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
4539 HSOpts.DisableModuleHash = Record[Idx++];
4540 HSOpts.UseBuiltinIncludes = Record[Idx++];
4541 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4542 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4543 HSOpts.UseLibcxx = Record[Idx++];
4544 std::string SpecificModuleCachePath = ReadString(Record, Idx);
4546 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4550 bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4552 ASTReaderListener &Listener,
4553 std::string &SuggestedPredefines) {
4554 PreprocessorOptions PPOpts;
4557 // Macro definitions/undefs
4558 for (unsigned N = Record[Idx++]; N; --N) {
4559 std::string Macro = ReadString(Record, Idx);
4560 bool IsUndef = Record[Idx++];
4561 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4565 for (unsigned N = Record[Idx++]; N; --N) {
4566 PPOpts.Includes.push_back(ReadString(Record, Idx));
4570 for (unsigned N = Record[Idx++]; N; --N) {
4571 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4574 PPOpts.UsePredefines = Record[Idx++];
4575 PPOpts.DetailedRecord = Record[Idx++];
4576 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4577 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4578 PPOpts.ObjCXXARCStandardLibrary =
4579 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4580 SuggestedPredefines.clear();
4581 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4582 SuggestedPredefines);
4585 std::pair<ModuleFile *, unsigned>
4586 ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4587 GlobalPreprocessedEntityMapType::iterator
4588 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4589 assert(I != GlobalPreprocessedEntityMap.end() &&
4590 "Corrupted global preprocessed entity map");
4591 ModuleFile *M = I->second;
4592 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4593 return std::make_pair(M, LocalIndex);
4596 llvm::iterator_range<PreprocessingRecord::iterator>
4597 ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4598 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4599 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4600 Mod.NumPreprocessedEntities);
4602 return llvm::make_range(PreprocessingRecord::iterator(),
4603 PreprocessingRecord::iterator());
4606 llvm::iterator_range<ASTReader::ModuleDeclIterator>
4607 ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
4608 return llvm::make_range(
4609 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4610 ModuleDeclIterator(this, &Mod,
4611 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
4614 PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4615 PreprocessedEntityID PPID = Index+1;
4616 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4617 ModuleFile &M = *PPInfo.first;
4618 unsigned LocalIndex = PPInfo.second;
4619 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4621 if (!PP.getPreprocessingRecord()) {
4622 Error("no preprocessing record");
4626 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4627 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4629 llvm::BitstreamEntry Entry =
4630 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4631 if (Entry.Kind != llvm::BitstreamEntry::Record)
4635 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
4636 ReadSourceLocation(M, PPOffs.End));
4637 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
4640 PreprocessorDetailRecordTypes RecType =
4641 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
4642 Entry.ID, Record, &Blob);
4644 case PPD_MACRO_EXPANSION: {
4645 bool isBuiltin = Record[0];
4646 IdentifierInfo *Name = nullptr;
4647 MacroDefinitionRecord *Def = nullptr;
4649 Name = getLocalIdentifier(M, Record[1]);
4651 PreprocessedEntityID GlobalID =
4652 getGlobalPreprocessedEntityID(M, Record[1]);
4653 Def = cast<MacroDefinitionRecord>(
4654 PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
4659 ME = new (PPRec) MacroExpansion(Name, Range);
4661 ME = new (PPRec) MacroExpansion(Def, Range);
4666 case PPD_MACRO_DEFINITION: {
4667 // Decode the identifier info and then check again; if the macro is
4668 // still defined and associated with the identifier,
4669 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
4670 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
4672 if (DeserializationListener)
4673 DeserializationListener->MacroDefinitionRead(PPID, MD);
4678 case PPD_INCLUSION_DIRECTIVE: {
4679 const char *FullFileNameStart = Blob.data() + Record[0];
4680 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
4681 const FileEntry *File = nullptr;
4682 if (!FullFileName.empty())
4683 File = PP.getFileManager().getFile(FullFileName);
4685 // FIXME: Stable encoding
4686 InclusionDirective::InclusionKind Kind
4687 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4688 InclusionDirective *ID
4689 = new (PPRec) InclusionDirective(PPRec, Kind,
4690 StringRef(Blob.data(), Record[0]),
4691 Record[1], Record[3],
4698 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4701 /// \brief \arg SLocMapI points at a chunk of a module that contains no
4702 /// preprocessed entities or the entities it contains are not the ones we are
4703 /// looking for. Find the next module that contains entities and return the ID
4704 /// of the first entry.
4705 PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
4706 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
4708 for (GlobalSLocOffsetMapType::const_iterator
4709 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
4710 ModuleFile &M = *SLocMapI->second;
4711 if (M.NumPreprocessedEntities)
4712 return M.BasePreprocessedEntityID;
4715 return getTotalNumPreprocessedEntities();
4720 template <unsigned PPEntityOffset::*PPLoc>
4721 struct PPEntityComp {
4722 const ASTReader &Reader;
4725 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
4727 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
4728 SourceLocation LHS = getLoc(L);
4729 SourceLocation RHS = getLoc(R);
4730 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4733 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
4734 SourceLocation LHS = getLoc(L);
4735 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4738 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
4739 SourceLocation RHS = getLoc(R);
4740 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4743 SourceLocation getLoc(const PPEntityOffset &PPE) const {
4744 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
4750 PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
4751 bool EndsAfter) const {
4752 if (SourceMgr.isLocalSourceLocation(Loc))
4753 return getTotalNumPreprocessedEntities();
4755 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
4756 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
4757 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4758 "Corrupted global sloc offset map");
4760 if (SLocMapI->second->NumPreprocessedEntities == 0)
4761 return findNextPreprocessedEntity(SLocMapI);
4763 ModuleFile &M = *SLocMapI->second;
4764 typedef const PPEntityOffset *pp_iterator;
4765 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4766 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4768 size_t Count = M.NumPreprocessedEntities;
4770 pp_iterator First = pp_begin;
4774 PPI = std::upper_bound(pp_begin, pp_end, Loc,
4775 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
4777 // Do a binary search manually instead of using std::lower_bound because
4778 // The end locations of entities may be unordered (when a macro expansion
4779 // is inside another macro argument), but for this case it is not important
4780 // whether we get the first macro expansion or its containing macro.
4784 std::advance(PPI, Half);
4785 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
4789 Count = Count - Half - 1;
4796 return findNextPreprocessedEntity(SLocMapI);
4798 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4801 /// \brief Returns a pair of [Begin, End) indices of preallocated
4802 /// preprocessed entities that \arg Range encompasses.
4803 std::pair<unsigned, unsigned>
4804 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
4805 if (Range.isInvalid())
4806 return std::make_pair(0,0);
4807 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
4809 PreprocessedEntityID BeginID =
4810 findPreprocessedEntity(Range.getBegin(), false);
4811 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
4812 return std::make_pair(BeginID, EndID);
4815 /// \brief Optionally returns true or false if the preallocated preprocessed
4816 /// entity with index \arg Index came from file \arg FID.
4817 Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
4819 if (FID.isInvalid())
4822 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4823 ModuleFile &M = *PPInfo.first;
4824 unsigned LocalIndex = PPInfo.second;
4825 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4827 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
4828 if (Loc.isInvalid())
4831 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
4838 /// \brief Visitor used to search for information about a header file.
4839 class HeaderFileInfoVisitor {
4840 const FileEntry *FE;
4842 Optional<HeaderFileInfo> HFI;
4845 explicit HeaderFileInfoVisitor(const FileEntry *FE)
4848 static bool visit(ModuleFile &M, void *UserData) {
4849 HeaderFileInfoVisitor *This
4850 = static_cast<HeaderFileInfoVisitor *>(UserData);
4852 HeaderFileInfoLookupTable *Table
4853 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
4857 // Look in the on-disk hash table for an entry for this file name.
4858 HeaderFileInfoLookupTable::iterator Pos = Table->find(This->FE);
4859 if (Pos == Table->end())
4866 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
4870 HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
4871 HeaderFileInfoVisitor Visitor(FE);
4872 ModuleMgr.visit(&HeaderFileInfoVisitor::visit, &Visitor);
4873 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
4876 return HeaderFileInfo();
4879 void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
4880 // FIXME: Make it work properly with modules.
4881 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
4882 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
4883 ModuleFile &F = *(*I);
4886 assert(!Diag.DiagStates.empty());
4887 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
4888 while (Idx < F.PragmaDiagMappings.size()) {
4889 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
4890 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
4891 if (DiagStateID != 0) {
4892 Diag.DiagStatePoints.push_back(
4893 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
4894 FullSourceLoc(Loc, SourceMgr)));
4898 assert(DiagStateID == 0);
4899 // A new DiagState was created here.
4900 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
4901 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
4902 DiagStates.push_back(NewState);
4903 Diag.DiagStatePoints.push_back(
4904 DiagnosticsEngine::DiagStatePoint(NewState,
4905 FullSourceLoc(Loc, SourceMgr)));
4907 assert(Idx < F.PragmaDiagMappings.size() &&
4908 "Invalid data, didn't find '-1' marking end of diag/map pairs");
4909 if (Idx >= F.PragmaDiagMappings.size()) {
4910 break; // Something is messed up but at least avoid infinite loop in
4913 unsigned DiagID = F.PragmaDiagMappings[Idx++];
4914 if (DiagID == (unsigned)-1) {
4915 break; // no more diag/map pairs for this location.
4917 diag::Severity Map = (diag::Severity)F.PragmaDiagMappings[Idx++];
4918 DiagnosticMapping Mapping = Diag.makeUserMapping(Map, Loc);
4919 Diag.GetCurDiagState()->setMapping(DiagID, Mapping);
4925 /// \brief Get the correct cursor and offset for loading a type.
4926 ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
4927 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
4928 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
4929 ModuleFile *M = I->second;
4930 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
4933 /// \brief Read and return the type with the given index..
4935 /// The index is the type ID, shifted and minus the number of predefs. This
4936 /// routine actually reads the record corresponding to the type at the given
4937 /// location. It is a helper routine for GetType, which deals with reading type
4939 QualType ASTReader::readTypeRecord(unsigned Index) {
4940 RecordLocation Loc = TypeCursorForIndex(Index);
4941 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
4943 // Keep track of where we are in the stream, then jump back there
4944 // after reading this type.
4945 SavedStreamPosition SavedPosition(DeclsCursor);
4947 ReadingKindTracker ReadingKind(Read_Type, *this);
4949 // Note that we are loading a type record.
4950 Deserializing AType(this);
4953 DeclsCursor.JumpToBit(Loc.Offset);
4955 unsigned Code = DeclsCursor.ReadCode();
4956 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
4957 case TYPE_EXT_QUAL: {
4958 if (Record.size() != 2) {
4959 Error("Incorrect encoding of extended qualifier type");
4962 QualType Base = readType(*Loc.F, Record, Idx);
4963 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
4964 return Context.getQualifiedType(Base, Quals);
4967 case TYPE_COMPLEX: {
4968 if (Record.size() != 1) {
4969 Error("Incorrect encoding of complex type");
4972 QualType ElemType = readType(*Loc.F, Record, Idx);
4973 return Context.getComplexType(ElemType);
4976 case TYPE_POINTER: {
4977 if (Record.size() != 1) {
4978 Error("Incorrect encoding of pointer type");
4981 QualType PointeeType = readType(*Loc.F, Record, Idx);
4982 return Context.getPointerType(PointeeType);
4985 case TYPE_DECAYED: {
4986 if (Record.size() != 1) {
4987 Error("Incorrect encoding of decayed type");
4990 QualType OriginalType = readType(*Loc.F, Record, Idx);
4991 QualType DT = Context.getAdjustedParameterType(OriginalType);
4992 if (!isa<DecayedType>(DT))
4993 Error("Decayed type does not decay");
4997 case TYPE_ADJUSTED: {
4998 if (Record.size() != 2) {
4999 Error("Incorrect encoding of adjusted type");
5002 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5003 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5004 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5007 case TYPE_BLOCK_POINTER: {
5008 if (Record.size() != 1) {
5009 Error("Incorrect encoding of block pointer type");
5012 QualType PointeeType = readType(*Loc.F, Record, Idx);
5013 return Context.getBlockPointerType(PointeeType);
5016 case TYPE_LVALUE_REFERENCE: {
5017 if (Record.size() != 2) {
5018 Error("Incorrect encoding of lvalue reference type");
5021 QualType PointeeType = readType(*Loc.F, Record, Idx);
5022 return Context.getLValueReferenceType(PointeeType, Record[1]);
5025 case TYPE_RVALUE_REFERENCE: {
5026 if (Record.size() != 1) {
5027 Error("Incorrect encoding of rvalue reference type");
5030 QualType PointeeType = readType(*Loc.F, Record, Idx);
5031 return Context.getRValueReferenceType(PointeeType);
5034 case TYPE_MEMBER_POINTER: {
5035 if (Record.size() != 2) {
5036 Error("Incorrect encoding of member pointer type");
5039 QualType PointeeType = readType(*Loc.F, Record, Idx);
5040 QualType ClassType = readType(*Loc.F, Record, Idx);
5041 if (PointeeType.isNull() || ClassType.isNull())
5044 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5047 case TYPE_CONSTANT_ARRAY: {
5048 QualType ElementType = readType(*Loc.F, Record, Idx);
5049 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5050 unsigned IndexTypeQuals = Record[2];
5052 llvm::APInt Size = ReadAPInt(Record, Idx);
5053 return Context.getConstantArrayType(ElementType, Size,
5054 ASM, IndexTypeQuals);
5057 case TYPE_INCOMPLETE_ARRAY: {
5058 QualType ElementType = readType(*Loc.F, Record, Idx);
5059 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5060 unsigned IndexTypeQuals = Record[2];
5061 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5064 case TYPE_VARIABLE_ARRAY: {
5065 QualType ElementType = readType(*Loc.F, Record, Idx);
5066 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5067 unsigned IndexTypeQuals = Record[2];
5068 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5069 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5070 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5071 ASM, IndexTypeQuals,
5072 SourceRange(LBLoc, RBLoc));
5076 if (Record.size() != 3) {
5077 Error("incorrect encoding of vector type in AST file");
5081 QualType ElementType = readType(*Loc.F, Record, Idx);
5082 unsigned NumElements = Record[1];
5083 unsigned VecKind = Record[2];
5084 return Context.getVectorType(ElementType, NumElements,
5085 (VectorType::VectorKind)VecKind);
5088 case TYPE_EXT_VECTOR: {
5089 if (Record.size() != 3) {
5090 Error("incorrect encoding of extended vector type in AST file");
5094 QualType ElementType = readType(*Loc.F, Record, Idx);
5095 unsigned NumElements = Record[1];
5096 return Context.getExtVectorType(ElementType, NumElements);
5099 case TYPE_FUNCTION_NO_PROTO: {
5100 if (Record.size() != 6) {
5101 Error("incorrect encoding of no-proto function type");
5104 QualType ResultType = readType(*Loc.F, Record, Idx);
5105 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5106 (CallingConv)Record[4], Record[5]);
5107 return Context.getFunctionNoProtoType(ResultType, Info);
5110 case TYPE_FUNCTION_PROTO: {
5111 QualType ResultType = readType(*Loc.F, Record, Idx);
5113 FunctionProtoType::ExtProtoInfo EPI;
5114 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5115 /*hasregparm*/ Record[2],
5116 /*regparm*/ Record[3],
5117 static_cast<CallingConv>(Record[4]),
5118 /*produces*/ Record[5]);
5122 EPI.Variadic = Record[Idx++];
5123 EPI.HasTrailingReturn = Record[Idx++];
5124 EPI.TypeQuals = Record[Idx++];
5125 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
5126 SmallVector<QualType, 8> ExceptionStorage;
5127 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
5129 unsigned NumParams = Record[Idx++];
5130 SmallVector<QualType, 16> ParamTypes;
5131 for (unsigned I = 0; I != NumParams; ++I)
5132 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5134 return Context.getFunctionType(ResultType, ParamTypes, EPI);
5137 case TYPE_UNRESOLVED_USING: {
5139 return Context.getTypeDeclType(
5140 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5143 case TYPE_TYPEDEF: {
5144 if (Record.size() != 2) {
5145 Error("incorrect encoding of typedef type");
5149 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5150 QualType Canonical = readType(*Loc.F, Record, Idx);
5151 if (!Canonical.isNull())
5152 Canonical = Context.getCanonicalType(Canonical);
5153 return Context.getTypedefType(Decl, Canonical);
5156 case TYPE_TYPEOF_EXPR:
5157 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5160 if (Record.size() != 1) {
5161 Error("incorrect encoding of typeof(type) in AST file");
5164 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5165 return Context.getTypeOfType(UnderlyingType);
5168 case TYPE_DECLTYPE: {
5169 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5170 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5173 case TYPE_UNARY_TRANSFORM: {
5174 QualType BaseType = readType(*Loc.F, Record, Idx);
5175 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5176 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5177 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5181 QualType Deduced = readType(*Loc.F, Record, Idx);
5182 bool IsDecltypeAuto = Record[Idx++];
5183 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
5184 return Context.getAutoType(Deduced, IsDecltypeAuto, IsDependent);
5188 if (Record.size() != 2) {
5189 Error("incorrect encoding of record type");
5193 bool IsDependent = Record[Idx++];
5194 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5195 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5196 QualType T = Context.getRecordType(RD);
5197 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5202 if (Record.size() != 2) {
5203 Error("incorrect encoding of enum type");
5207 bool IsDependent = Record[Idx++];
5209 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5210 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5214 case TYPE_ATTRIBUTED: {
5215 if (Record.size() != 3) {
5216 Error("incorrect encoding of attributed type");
5219 QualType modifiedType = readType(*Loc.F, Record, Idx);
5220 QualType equivalentType = readType(*Loc.F, Record, Idx);
5221 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5222 return Context.getAttributedType(kind, modifiedType, equivalentType);
5226 if (Record.size() != 1) {
5227 Error("incorrect encoding of paren type");
5230 QualType InnerType = readType(*Loc.F, Record, Idx);
5231 return Context.getParenType(InnerType);
5234 case TYPE_PACK_EXPANSION: {
5235 if (Record.size() != 2) {
5236 Error("incorrect encoding of pack expansion type");
5239 QualType Pattern = readType(*Loc.F, Record, Idx);
5240 if (Pattern.isNull())
5242 Optional<unsigned> NumExpansions;
5244 NumExpansions = Record[1] - 1;
5245 return Context.getPackExpansionType(Pattern, NumExpansions);
5248 case TYPE_ELABORATED: {
5250 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5251 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5252 QualType NamedType = readType(*Loc.F, Record, Idx);
5253 return Context.getElaboratedType(Keyword, NNS, NamedType);
5256 case TYPE_OBJC_INTERFACE: {
5258 ObjCInterfaceDecl *ItfD
5259 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5260 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5263 case TYPE_OBJC_OBJECT: {
5265 QualType Base = readType(*Loc.F, Record, Idx);
5266 unsigned NumProtos = Record[Idx++];
5267 SmallVector<ObjCProtocolDecl*, 4> Protos;
5268 for (unsigned I = 0; I != NumProtos; ++I)
5269 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
5270 return Context.getObjCObjectType(Base, Protos.data(), NumProtos);
5273 case TYPE_OBJC_OBJECT_POINTER: {
5275 QualType Pointee = readType(*Loc.F, Record, Idx);
5276 return Context.getObjCObjectPointerType(Pointee);
5279 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5281 QualType Parm = readType(*Loc.F, Record, Idx);
5282 QualType Replacement = readType(*Loc.F, Record, Idx);
5283 return Context.getSubstTemplateTypeParmType(
5284 cast<TemplateTypeParmType>(Parm),
5285 Context.getCanonicalType(Replacement));
5288 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5290 QualType Parm = readType(*Loc.F, Record, Idx);
5291 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5292 return Context.getSubstTemplateTypeParmPackType(
5293 cast<TemplateTypeParmType>(Parm),
5297 case TYPE_INJECTED_CLASS_NAME: {
5298 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5299 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5300 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5301 // for AST reading, too much interdependencies.
5302 const Type *T = nullptr;
5303 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
5304 if (const Type *Existing = DI->getTypeForDecl()) {
5310 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
5311 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
5312 DI->setTypeForDecl(T);
5314 return QualType(T, 0);
5317 case TYPE_TEMPLATE_TYPE_PARM: {
5319 unsigned Depth = Record[Idx++];
5320 unsigned Index = Record[Idx++];
5321 bool Pack = Record[Idx++];
5322 TemplateTypeParmDecl *D
5323 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5324 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5327 case TYPE_DEPENDENT_NAME: {
5329 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5330 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5331 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5332 QualType Canon = readType(*Loc.F, Record, Idx);
5333 if (!Canon.isNull())
5334 Canon = Context.getCanonicalType(Canon);
5335 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5338 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5340 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5341 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5342 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5343 unsigned NumArgs = Record[Idx++];
5344 SmallVector<TemplateArgument, 8> Args;
5345 Args.reserve(NumArgs);
5347 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5348 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
5349 Args.size(), Args.data());
5352 case TYPE_DEPENDENT_SIZED_ARRAY: {
5356 QualType ElementType = readType(*Loc.F, Record, Idx);
5357 ArrayType::ArraySizeModifier ASM
5358 = (ArrayType::ArraySizeModifier)Record[Idx++];
5359 unsigned IndexTypeQuals = Record[Idx++];
5361 // DependentSizedArrayType
5362 Expr *NumElts = ReadExpr(*Loc.F);
5363 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5365 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5366 IndexTypeQuals, Brackets);
5369 case TYPE_TEMPLATE_SPECIALIZATION: {
5371 bool IsDependent = Record[Idx++];
5372 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5373 SmallVector<TemplateArgument, 8> Args;
5374 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5375 QualType Underlying = readType(*Loc.F, Record, Idx);
5377 if (Underlying.isNull())
5378 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
5381 T = Context.getTemplateSpecializationType(Name, Args.data(),
5382 Args.size(), Underlying);
5383 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5388 if (Record.size() != 1) {
5389 Error("Incorrect encoding of atomic type");
5392 QualType ValueType = readType(*Loc.F, Record, Idx);
5393 return Context.getAtomicType(ValueType);
5396 llvm_unreachable("Invalid TypeCode!");
5399 void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5400 SmallVectorImpl<QualType> &Exceptions,
5401 FunctionProtoType::ExceptionSpecInfo &ESI,
5402 const RecordData &Record, unsigned &Idx) {
5403 ExceptionSpecificationType EST =
5404 static_cast<ExceptionSpecificationType>(Record[Idx++]);
5406 if (EST == EST_Dynamic) {
5407 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
5408 Exceptions.push_back(readType(ModuleFile, Record, Idx));
5409 ESI.Exceptions = Exceptions;
5410 } else if (EST == EST_ComputedNoexcept) {
5411 ESI.NoexceptExpr = ReadExpr(ModuleFile);
5412 } else if (EST == EST_Uninstantiated) {
5413 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5414 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5415 } else if (EST == EST_Unevaluated) {
5416 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5420 class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
5423 const ASTReader::RecordData &Record;
5426 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
5428 return Reader.ReadSourceLocation(F, R, I);
5431 template<typename T>
5432 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
5433 return Reader.ReadDeclAs<T>(F, Record, Idx);
5437 TypeLocReader(ASTReader &Reader, ModuleFile &F,
5438 const ASTReader::RecordData &Record, unsigned &Idx)
5439 : Reader(Reader), F(F), Record(Record), Idx(Idx)
5442 // We want compile-time assurance that we've enumerated all of
5443 // these, so unfortunately we have to declare them first, then
5444 // define them out-of-line.
5445 #define ABSTRACT_TYPELOC(CLASS, PARENT)
5446 #define TYPELOC(CLASS, PARENT) \
5447 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5448 #include "clang/AST/TypeLocNodes.def"
5450 void VisitFunctionTypeLoc(FunctionTypeLoc);
5451 void VisitArrayTypeLoc(ArrayTypeLoc);
5454 void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5457 void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5458 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
5459 if (TL.needsExtraLocalData()) {
5460 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5461 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5462 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5463 TL.setModeAttr(Record[Idx++]);
5466 void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5467 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5469 void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5470 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5472 void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5475 void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5478 void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5479 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5481 void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5482 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5484 void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5485 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5487 void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5488 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5489 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5491 void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5492 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5493 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5495 TL.setSizeExpr(Reader.ReadExpr(F));
5497 TL.setSizeExpr(nullptr);
5499 void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5500 VisitArrayTypeLoc(TL);
5502 void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5503 VisitArrayTypeLoc(TL);
5505 void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5506 VisitArrayTypeLoc(TL);
5508 void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5509 DependentSizedArrayTypeLoc TL) {
5510 VisitArrayTypeLoc(TL);
5512 void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5513 DependentSizedExtVectorTypeLoc TL) {
5514 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5516 void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5517 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5519 void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5520 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5522 void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5523 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5524 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5525 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5526 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
5527 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5528 TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
5531 void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5532 VisitFunctionTypeLoc(TL);
5534 void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5535 VisitFunctionTypeLoc(TL);
5537 void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5538 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5540 void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5541 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5543 void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5544 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5545 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5546 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5548 void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5549 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5550 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5551 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5552 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5554 void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5555 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5557 void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5558 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5559 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5560 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5561 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5563 void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5564 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5566 void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5567 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5569 void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5570 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5572 void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5573 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5574 if (TL.hasAttrOperand()) {
5576 range.setBegin(ReadSourceLocation(Record, Idx));
5577 range.setEnd(ReadSourceLocation(Record, Idx));
5578 TL.setAttrOperandParensRange(range);
5580 if (TL.hasAttrExprOperand()) {
5582 TL.setAttrExprOperand(Reader.ReadExpr(F));
5584 TL.setAttrExprOperand(nullptr);
5585 } else if (TL.hasAttrEnumOperand())
5586 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5588 void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5589 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5591 void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5592 SubstTemplateTypeParmTypeLoc TL) {
5593 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5595 void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5596 SubstTemplateTypeParmPackTypeLoc TL) {
5597 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5599 void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5600 TemplateSpecializationTypeLoc TL) {
5601 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5602 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5603 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5604 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5605 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5607 Reader.GetTemplateArgumentLocInfo(F,
5608 TL.getTypePtr()->getArg(i).getKind(),
5611 void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5612 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5613 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5615 void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5616 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5617 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5619 void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5620 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5622 void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5623 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5624 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5625 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5627 void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5628 DependentTemplateSpecializationTypeLoc TL) {
5629 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5630 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5631 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5632 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5633 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5634 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5635 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5637 Reader.GetTemplateArgumentLocInfo(F,
5638 TL.getTypePtr()->getArg(I).getKind(),
5641 void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5642 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5644 void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5645 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5647 void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5648 TL.setHasBaseTypeAsWritten(Record[Idx++]);
5649 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5650 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5651 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5652 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5654 void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5655 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5657 void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5658 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5659 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5660 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5663 TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5664 const RecordData &Record,
5666 QualType InfoTy = readType(F, Record, Idx);
5667 if (InfoTy.isNull())
5670 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5671 TypeLocReader TLR(*this, F, Record, Idx);
5672 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5677 QualType ASTReader::GetType(TypeID ID) {
5678 unsigned FastQuals = ID & Qualifiers::FastMask;
5679 unsigned Index = ID >> Qualifiers::FastWidth;
5681 if (Index < NUM_PREDEF_TYPE_IDS) {
5683 switch ((PredefinedTypeIDs)Index) {
5684 case PREDEF_TYPE_NULL_ID: return QualType();
5685 case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
5686 case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
5688 case PREDEF_TYPE_CHAR_U_ID:
5689 case PREDEF_TYPE_CHAR_S_ID:
5690 // FIXME: Check that the signedness of CharTy is correct!
5694 case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
5695 case PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
5696 case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
5697 case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
5698 case PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
5699 case PREDEF_TYPE_UINT128_ID: T = Context.UnsignedInt128Ty; break;
5700 case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
5701 case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
5702 case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
5703 case PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
5704 case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
5705 case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
5706 case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break;
5707 case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break;
5708 case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
5709 case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
5710 case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
5711 case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
5712 case PREDEF_TYPE_BOUND_MEMBER: T = Context.BoundMemberTy; break;
5713 case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy; break;
5714 case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
5715 case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break;
5716 case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break;
5717 case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break;
5718 case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break;
5719 case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break;
5720 case PREDEF_TYPE_OBJC_CLASS: T = Context.ObjCBuiltinClassTy; break;
5721 case PREDEF_TYPE_OBJC_SEL: T = Context.ObjCBuiltinSelTy; break;
5722 case PREDEF_TYPE_IMAGE1D_ID: T = Context.OCLImage1dTy; break;
5723 case PREDEF_TYPE_IMAGE1D_ARR_ID: T = Context.OCLImage1dArrayTy; break;
5724 case PREDEF_TYPE_IMAGE1D_BUFF_ID: T = Context.OCLImage1dBufferTy; break;
5725 case PREDEF_TYPE_IMAGE2D_ID: T = Context.OCLImage2dTy; break;
5726 case PREDEF_TYPE_IMAGE2D_ARR_ID: T = Context.OCLImage2dArrayTy; break;
5727 case PREDEF_TYPE_IMAGE3D_ID: T = Context.OCLImage3dTy; break;
5728 case PREDEF_TYPE_SAMPLER_ID: T = Context.OCLSamplerTy; break;
5729 case PREDEF_TYPE_EVENT_ID: T = Context.OCLEventTy; break;
5730 case PREDEF_TYPE_AUTO_DEDUCT: T = Context.getAutoDeductType(); break;
5732 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
5733 T = Context.getAutoRRefDeductType();
5736 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
5737 T = Context.ARCUnbridgedCastTy;
5740 case PREDEF_TYPE_VA_LIST_TAG:
5741 T = Context.getVaListTagType();
5744 case PREDEF_TYPE_BUILTIN_FN:
5745 T = Context.BuiltinFnTy;
5749 assert(!T.isNull() && "Unknown predefined type");
5750 return T.withFastQualifiers(FastQuals);
5753 Index -= NUM_PREDEF_TYPE_IDS;
5754 assert(Index < TypesLoaded.size() && "Type index out-of-range");
5755 if (TypesLoaded[Index].isNull()) {
5756 TypesLoaded[Index] = readTypeRecord(Index);
5757 if (TypesLoaded[Index].isNull())
5760 TypesLoaded[Index]->setFromAST();
5761 if (DeserializationListener)
5762 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
5763 TypesLoaded[Index]);
5766 return TypesLoaded[Index].withFastQualifiers(FastQuals);
5769 QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
5770 return GetType(getGlobalTypeID(F, LocalID));
5773 serialization::TypeID
5774 ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
5775 unsigned FastQuals = LocalID & Qualifiers::FastMask;
5776 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
5778 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
5781 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5782 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
5783 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
5785 unsigned GlobalIndex = LocalIndex + I->second;
5786 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
5789 TemplateArgumentLocInfo
5790 ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
5791 TemplateArgument::ArgKind Kind,
5792 const RecordData &Record,
5795 case TemplateArgument::Expression:
5797 case TemplateArgument::Type:
5798 return GetTypeSourceInfo(F, Record, Index);
5799 case TemplateArgument::Template: {
5800 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5802 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5803 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5806 case TemplateArgument::TemplateExpansion: {
5807 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5809 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5810 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
5811 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5814 case TemplateArgument::Null:
5815 case TemplateArgument::Integral:
5816 case TemplateArgument::Declaration:
5817 case TemplateArgument::NullPtr:
5818 case TemplateArgument::Pack:
5819 // FIXME: Is this right?
5820 return TemplateArgumentLocInfo();
5822 llvm_unreachable("unexpected template argument loc");
5826 ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
5827 const RecordData &Record, unsigned &Index) {
5828 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
5830 if (Arg.getKind() == TemplateArgument::Expression) {
5831 if (Record[Index++]) // bool InfoHasSameExpr.
5832 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
5834 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
5838 const ASTTemplateArgumentListInfo*
5839 ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
5840 const RecordData &Record,
5842 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
5843 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
5844 unsigned NumArgsAsWritten = Record[Index++];
5845 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
5846 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
5847 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
5848 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
5851 Decl *ASTReader::GetExternalDecl(uint32_t ID) {
5855 template<typename TemplateSpecializationDecl>
5856 static void completeRedeclChainForTemplateSpecialization(Decl *D) {
5857 if (auto *TSD = dyn_cast<TemplateSpecializationDecl>(D))
5858 TSD->getSpecializedTemplate()->LoadLazySpecializations();
5861 void ASTReader::CompleteRedeclChain(const Decl *D) {
5862 if (NumCurrentElementsDeserializing) {
5863 // We arrange to not care about the complete redeclaration chain while we're
5864 // deserializing. Just remember that the AST has marked this one as complete
5865 // but that it's not actually complete yet, so we know we still need to
5866 // complete it later.
5867 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
5871 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
5873 // If this is a named declaration, complete it by looking it up
5874 // within its context.
5876 // FIXME: Merging a function definition should merge
5877 // all mergeable entities within it.
5878 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
5879 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
5880 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
5881 auto *II = Name.getAsIdentifierInfo();
5882 if (isa<TranslationUnitDecl>(DC) && II) {
5883 // Outside of C++, we don't have a lookup table for the TU, so update
5884 // the identifier instead. In C++, either way should work fine.
5885 if (II->isOutOfDate())
5886 updateOutOfDateIdentifier(*II);
5889 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
5890 // FIXME: It'd be nice to do something a bit more targeted here.
5891 D->getDeclContext()->decls_begin();
5895 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
5896 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
5897 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
5898 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
5899 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
5900 if (auto *Template = FD->getPrimaryTemplate())
5901 Template->LoadLazySpecializations();
5905 uint64_t ASTReader::ReadCXXCtorInitializersRef(ModuleFile &M,
5906 const RecordData &Record,
5908 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXCtorInitializers) {
5909 Error("malformed AST file: missing C++ ctor initializers");
5913 unsigned LocalID = Record[Idx++];
5914 return getGlobalBitOffset(M, M.CXXCtorInitializersOffsets[LocalID - 1]);
5917 CXXCtorInitializer **
5918 ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
5919 RecordLocation Loc = getLocalBitOffset(Offset);
5920 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
5921 SavedStreamPosition SavedPosition(Cursor);
5922 Cursor.JumpToBit(Loc.Offset);
5923 ReadingKindTracker ReadingKind(Read_Decl, *this);
5926 unsigned Code = Cursor.ReadCode();
5927 unsigned RecCode = Cursor.readRecord(Code, Record);
5928 if (RecCode != DECL_CXX_CTOR_INITIALIZERS) {
5929 Error("malformed AST file: missing C++ ctor initializers");
5934 return ReadCXXCtorInitializers(*Loc.F, Record, Idx);
5937 uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M,
5938 const RecordData &Record,
5940 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXBaseSpecifiers) {
5941 Error("malformed AST file: missing C++ base specifier");
5945 unsigned LocalID = Record[Idx++];
5946 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
5949 CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
5950 RecordLocation Loc = getLocalBitOffset(Offset);
5951 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
5952 SavedStreamPosition SavedPosition(Cursor);
5953 Cursor.JumpToBit(Loc.Offset);
5954 ReadingKindTracker ReadingKind(Read_Decl, *this);
5956 unsigned Code = Cursor.ReadCode();
5957 unsigned RecCode = Cursor.readRecord(Code, Record);
5958 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
5959 Error("malformed AST file: missing C++ base specifiers");
5964 unsigned NumBases = Record[Idx++];
5965 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
5966 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
5967 for (unsigned I = 0; I != NumBases; ++I)
5968 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
5972 serialization::DeclID
5973 ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
5974 if (LocalID < NUM_PREDEF_DECL_IDS)
5977 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5978 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
5979 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
5981 return LocalID + I->second;
5984 bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
5985 ModuleFile &M) const {
5986 // Predefined decls aren't from any module.
5987 if (ID < NUM_PREDEF_DECL_IDS)
5990 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(ID);
5991 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5992 return &M == I->second;
5995 ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
5996 if (!D->isFromASTFile())
5998 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
5999 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6003 SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6004 if (ID < NUM_PREDEF_DECL_IDS)
6005 return SourceLocation();
6007 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6009 if (Index > DeclsLoaded.size()) {
6010 Error("declaration ID out-of-range for AST file");
6011 return SourceLocation();
6014 if (Decl *D = DeclsLoaded[Index])
6015 return D->getLocation();
6017 unsigned RawLocation = 0;
6018 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
6019 return ReadSourceLocation(*Rec.F, RawLocation);
6022 static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
6024 case PREDEF_DECL_NULL_ID:
6027 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6028 return Context.getTranslationUnitDecl();
6030 case PREDEF_DECL_OBJC_ID_ID:
6031 return Context.getObjCIdDecl();
6033 case PREDEF_DECL_OBJC_SEL_ID:
6034 return Context.getObjCSelDecl();
6036 case PREDEF_DECL_OBJC_CLASS_ID:
6037 return Context.getObjCClassDecl();
6039 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6040 return Context.getObjCProtocolDecl();
6042 case PREDEF_DECL_INT_128_ID:
6043 return Context.getInt128Decl();
6045 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6046 return Context.getUInt128Decl();
6048 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6049 return Context.getObjCInstanceTypeDecl();
6051 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6052 return Context.getBuiltinVaListDecl();
6054 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
6055 return Context.getExternCContextDecl();
6057 llvm_unreachable("PredefinedDeclIDs unknown enum value");
6060 Decl *ASTReader::GetExistingDecl(DeclID ID) {
6061 if (ID < NUM_PREDEF_DECL_IDS) {
6062 Decl *D = getPredefinedDecl(Context, (PredefinedDeclIDs)ID);
6064 // Track that we have merged the declaration with ID \p ID into the
6065 // pre-existing predefined declaration \p D.
6066 auto &Merged = MergedDecls[D->getCanonicalDecl()];
6068 Merged.push_back(ID);
6073 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6075 if (Index >= DeclsLoaded.size()) {
6076 assert(0 && "declaration ID out-of-range for AST file");
6077 Error("declaration ID out-of-range for AST file");
6081 return DeclsLoaded[Index];
6084 Decl *ASTReader::GetDecl(DeclID ID) {
6085 if (ID < NUM_PREDEF_DECL_IDS)
6086 return GetExistingDecl(ID);
6088 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6090 if (Index >= DeclsLoaded.size()) {
6091 assert(0 && "declaration ID out-of-range for AST file");
6092 Error("declaration ID out-of-range for AST file");
6096 if (!DeclsLoaded[Index]) {
6098 if (DeserializationListener)
6099 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6102 return DeclsLoaded[Index];
6105 DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
6107 if (GlobalID < NUM_PREDEF_DECL_IDS)
6110 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6111 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6112 ModuleFile *Owner = I->second;
6114 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6115 = M.GlobalToLocalDeclIDs.find(Owner);
6116 if (Pos == M.GlobalToLocalDeclIDs.end())
6119 return GlobalID - Owner->BaseDeclID + Pos->second;
6122 serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
6123 const RecordData &Record,
6125 if (Idx >= Record.size()) {
6126 Error("Corrupted AST file");
6130 return getGlobalDeclID(F, Record[Idx++]);
6133 /// \brief Resolve the offset of a statement into a statement.
6135 /// This operation will read a new statement from the external
6136 /// source each time it is called, and is meant to be used via a
6137 /// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6138 Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6139 // Switch case IDs are per Decl.
6140 ClearSwitchCaseIDs();
6142 // Offset here is a global offset across the entire chain.
6143 RecordLocation Loc = getLocalBitOffset(Offset);
6144 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
6145 return ReadStmtFromStream(*Loc.F);
6149 class FindExternalLexicalDeclsVisitor {
6151 const DeclContext *DC;
6152 bool (*isKindWeWant)(Decl::Kind);
6154 SmallVectorImpl<Decl*> &Decls;
6155 bool PredefsVisited[NUM_PREDEF_DECL_IDS];
6158 FindExternalLexicalDeclsVisitor(ASTReader &Reader, const DeclContext *DC,
6159 bool (*isKindWeWant)(Decl::Kind),
6160 SmallVectorImpl<Decl*> &Decls)
6161 : Reader(Reader), DC(DC), isKindWeWant(isKindWeWant), Decls(Decls)
6163 for (unsigned I = 0; I != NUM_PREDEF_DECL_IDS; ++I)
6164 PredefsVisited[I] = false;
6167 static bool visitPostorder(ModuleFile &M, void *UserData) {
6168 FindExternalLexicalDeclsVisitor *This
6169 = static_cast<FindExternalLexicalDeclsVisitor *>(UserData);
6171 ModuleFile::DeclContextInfosMap::iterator Info
6172 = M.DeclContextInfos.find(This->DC);
6173 if (Info == M.DeclContextInfos.end() || !Info->second.LexicalDecls)
6176 // Load all of the declaration IDs
6177 for (const KindDeclIDPair *ID = Info->second.LexicalDecls,
6178 *IDE = ID + Info->second.NumLexicalDecls;
6180 if (This->isKindWeWant && !This->isKindWeWant((Decl::Kind)ID->first))
6183 // Don't add predefined declarations to the lexical context more
6185 if (ID->second < NUM_PREDEF_DECL_IDS) {
6186 if (This->PredefsVisited[ID->second])
6189 This->PredefsVisited[ID->second] = true;
6192 if (Decl *D = This->Reader.GetLocalDecl(M, ID->second)) {
6193 if (!This->DC->isDeclInLexicalTraversal(D))
6194 This->Decls.push_back(D);
6203 ExternalLoadResult ASTReader::FindExternalLexicalDecls(const DeclContext *DC,
6204 bool (*isKindWeWant)(Decl::Kind),
6205 SmallVectorImpl<Decl*> &Decls) {
6206 // There might be lexical decls in multiple modules, for the TU at
6207 // least. Walk all of the modules in the order they were loaded.
6208 FindExternalLexicalDeclsVisitor Visitor(*this, DC, isKindWeWant, Decls);
6209 ModuleMgr.visitDepthFirst(
6210 nullptr, &FindExternalLexicalDeclsVisitor::visitPostorder, &Visitor);
6211 ++NumLexicalDeclContextsRead;
6222 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6224 bool operator()(LocalDeclID L, LocalDeclID R) const {
6225 SourceLocation LHS = getLocation(L);
6226 SourceLocation RHS = getLocation(R);
6227 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6230 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6231 SourceLocation RHS = getLocation(R);
6232 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6235 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6236 SourceLocation LHS = getLocation(L);
6237 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6240 SourceLocation getLocation(LocalDeclID ID) const {
6241 return Reader.getSourceManager().getFileLoc(
6242 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6248 void ASTReader::FindFileRegionDecls(FileID File,
6249 unsigned Offset, unsigned Length,
6250 SmallVectorImpl<Decl *> &Decls) {
6251 SourceManager &SM = getSourceManager();
6253 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6254 if (I == FileDeclIDs.end())
6257 FileDeclsInfo &DInfo = I->second;
6258 if (DInfo.Decls.empty())
6262 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6263 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6265 DeclIDComp DIDComp(*this, *DInfo.Mod);
6266 ArrayRef<serialization::LocalDeclID>::iterator
6267 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6269 if (BeginIt != DInfo.Decls.begin())
6272 // If we are pointing at a top-level decl inside an objc container, we need
6273 // to backtrack until we find it otherwise we will fail to report that the
6274 // region overlaps with an objc container.
6275 while (BeginIt != DInfo.Decls.begin() &&
6276 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6277 ->isTopLevelDeclInObjCContainer())
6280 ArrayRef<serialization::LocalDeclID>::iterator
6281 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6283 if (EndIt != DInfo.Decls.end())
6286 for (ArrayRef<serialization::LocalDeclID>::iterator
6287 DIt = BeginIt; DIt != EndIt; ++DIt)
6288 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6292 /// \brief ModuleFile visitor used to perform name lookup into a
6293 /// declaration context.
6294 class DeclContextNameLookupVisitor {
6296 ArrayRef<const DeclContext *> Contexts;
6297 DeclarationName Name;
6298 SmallVectorImpl<NamedDecl *> &Decls;
6299 llvm::SmallPtrSetImpl<NamedDecl *> &DeclSet;
6302 DeclContextNameLookupVisitor(ASTReader &Reader,
6303 ArrayRef<const DeclContext *> Contexts,
6304 DeclarationName Name,
6305 SmallVectorImpl<NamedDecl *> &Decls,
6306 llvm::SmallPtrSetImpl<NamedDecl *> &DeclSet)
6307 : Reader(Reader), Contexts(Contexts), Name(Name), Decls(Decls),
6308 DeclSet(DeclSet) { }
6310 static bool visit(ModuleFile &M, void *UserData) {
6311 DeclContextNameLookupVisitor *This
6312 = static_cast<DeclContextNameLookupVisitor *>(UserData);
6314 // Check whether we have any visible declaration information for
6315 // this context in this module.
6316 ModuleFile::DeclContextInfosMap::iterator Info;
6317 bool FoundInfo = false;
6318 for (auto *DC : This->Contexts) {
6319 Info = M.DeclContextInfos.find(DC);
6320 if (Info != M.DeclContextInfos.end() &&
6321 Info->second.NameLookupTableData) {
6330 // Look for this name within this module.
6331 ASTDeclContextNameLookupTable *LookupTable =
6332 Info->second.NameLookupTableData;
6333 ASTDeclContextNameLookupTable::iterator Pos
6334 = LookupTable->find(This->Name);
6335 if (Pos == LookupTable->end())
6338 bool FoundAnything = false;
6339 ASTDeclContextNameLookupTrait::data_type Data = *Pos;
6340 for (; Data.first != Data.second; ++Data.first) {
6341 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
6345 if (ND->getDeclName() != This->Name) {
6346 // A name might be null because the decl's redeclarable part is
6347 // currently read before reading its name. The lookup is triggered by
6348 // building that decl (likely indirectly), and so it is later in the
6349 // sense of "already existing" and can be ignored here.
6350 // FIXME: This should not happen; deserializing declarations should
6351 // not perform lookups since that can lead to deserialization cycles.
6355 // Record this declaration.
6356 FoundAnything = true;
6357 if (This->DeclSet.insert(ND).second)
6358 This->Decls.push_back(ND);
6361 return FoundAnything;
6366 /// \brief Retrieve the "definitive" module file for the definition of the
6367 /// given declaration context, if there is one.
6369 /// The "definitive" module file is the only place where we need to look to
6370 /// find information about the declarations within the given declaration
6371 /// context. For example, C++ and Objective-C classes, C structs/unions, and
6372 /// Objective-C protocols, categories, and extensions are all defined in a
6373 /// single place in the source code, so they have definitive module files
6374 /// associated with them. C++ namespaces, on the other hand, can have
6375 /// definitions in multiple different module files.
6377 /// Note: this needs to be kept in sync with ASTWriter::AddedVisibleDecl's
6378 /// NDEBUG checking.
6379 static ModuleFile *getDefinitiveModuleFileFor(const DeclContext *DC,
6380 ASTReader &Reader) {
6381 if (const DeclContext *DefDC = getDefinitiveDeclContext(DC))
6382 return Reader.getOwningModuleFile(cast<Decl>(DefDC));
6388 ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6389 DeclarationName Name) {
6390 assert(DC->hasExternalVisibleStorage() &&
6391 "DeclContext has no visible decls in storage");
6395 Deserializing LookupResults(this);
6397 SmallVector<NamedDecl *, 64> Decls;
6398 llvm::SmallPtrSet<NamedDecl*, 64> DeclSet;
6400 // Compute the declaration contexts we need to look into. Multiple such
6401 // declaration contexts occur when two declaration contexts from disjoint
6402 // modules get merged, e.g., when two namespaces with the same name are
6403 // independently defined in separate modules.
6404 SmallVector<const DeclContext *, 2> Contexts;
6405 Contexts.push_back(DC);
6407 if (DC->isNamespace()) {
6408 auto Merged = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6409 if (Merged != MergedDecls.end()) {
6410 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6411 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6415 auto LookUpInContexts = [&](ArrayRef<const DeclContext*> Contexts) {
6416 DeclContextNameLookupVisitor Visitor(*this, Contexts, Name, Decls, DeclSet);
6418 // If we can definitively determine which module file to look into,
6419 // only look there. Otherwise, look in all module files.
6420 ModuleFile *Definitive;
6421 if (Contexts.size() == 1 &&
6422 (Definitive = getDefinitiveModuleFileFor(Contexts[0], *this))) {
6423 DeclContextNameLookupVisitor::visit(*Definitive, &Visitor);
6425 ModuleMgr.visit(&DeclContextNameLookupVisitor::visit, &Visitor);
6429 LookUpInContexts(Contexts);
6431 // If this might be an implicit special member function, then also search
6432 // all merged definitions of the surrounding class. We need to search them
6433 // individually, because finding an entity in one of them doesn't imply that
6434 // we can't find a different entity in another one.
6435 if (isa<CXXRecordDecl>(DC)) {
6436 auto Merged = MergedLookups.find(DC);
6437 if (Merged != MergedLookups.end()) {
6438 for (unsigned I = 0; I != Merged->second.size(); ++I) {
6439 const DeclContext *Context = Merged->second[I];
6440 LookUpInContexts(Context);
6441 // We might have just added some more merged lookups. If so, our
6442 // iterator is now invalid, so grab a fresh one before continuing.
6443 Merged = MergedLookups.find(DC);
6448 ++NumVisibleDeclContextsRead;
6449 SetExternalVisibleDeclsForName(DC, Name, Decls);
6450 return !Decls.empty();
6454 /// \brief ModuleFile visitor used to retrieve all visible names in a
6455 /// declaration context.
6456 class DeclContextAllNamesVisitor {
6458 SmallVectorImpl<const DeclContext *> &Contexts;
6460 llvm::SmallPtrSet<NamedDecl *, 256> DeclSet;
6464 DeclContextAllNamesVisitor(ASTReader &Reader,
6465 SmallVectorImpl<const DeclContext *> &Contexts,
6466 DeclsMap &Decls, bool VisitAll)
6467 : Reader(Reader), Contexts(Contexts), Decls(Decls), VisitAll(VisitAll) { }
6469 static bool visit(ModuleFile &M, void *UserData) {
6470 DeclContextAllNamesVisitor *This
6471 = static_cast<DeclContextAllNamesVisitor *>(UserData);
6473 // Check whether we have any visible declaration information for
6474 // this context in this module.
6475 ModuleFile::DeclContextInfosMap::iterator Info;
6476 bool FoundInfo = false;
6477 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
6478 Info = M.DeclContextInfos.find(This->Contexts[I]);
6479 if (Info != M.DeclContextInfos.end() &&
6480 Info->second.NameLookupTableData) {
6489 ASTDeclContextNameLookupTable *LookupTable =
6490 Info->second.NameLookupTableData;
6491 bool FoundAnything = false;
6492 for (ASTDeclContextNameLookupTable::data_iterator
6493 I = LookupTable->data_begin(), E = LookupTable->data_end();
6496 ASTDeclContextNameLookupTrait::data_type Data = *I;
6497 for (; Data.first != Data.second; ++Data.first) {
6498 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M,
6503 // Record this declaration.
6504 FoundAnything = true;
6505 if (This->DeclSet.insert(ND).second)
6506 This->Decls[ND->getDeclName()].push_back(ND);
6510 return FoundAnything && !This->VisitAll;
6515 void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6516 if (!DC->hasExternalVisibleStorage())
6520 // Compute the declaration contexts we need to look into. Multiple such
6521 // declaration contexts occur when two declaration contexts from disjoint
6522 // modules get merged, e.g., when two namespaces with the same name are
6523 // independently defined in separate modules.
6524 SmallVector<const DeclContext *, 2> Contexts;
6525 Contexts.push_back(DC);
6527 if (DC->isNamespace()) {
6528 MergedDeclsMap::iterator Merged
6529 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6530 if (Merged != MergedDecls.end()) {
6531 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6532 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6536 DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls,
6537 /*VisitAll=*/DC->isFileContext());
6538 ModuleMgr.visit(&DeclContextAllNamesVisitor::visit, &Visitor);
6539 ++NumVisibleDeclContextsRead;
6541 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
6542 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6544 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6547 /// \brief Under non-PCH compilation the consumer receives the objc methods
6548 /// before receiving the implementation, and codegen depends on this.
6549 /// We simulate this by deserializing and passing to consumer the methods of the
6550 /// implementation before passing the deserialized implementation decl.
6551 static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6552 ASTConsumer *Consumer) {
6553 assert(ImplD && Consumer);
6555 for (auto *I : ImplD->methods())
6556 Consumer->HandleInterestingDecl(DeclGroupRef(I));
6558 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6561 void ASTReader::PassInterestingDeclsToConsumer() {
6564 if (PassingDeclsToConsumer)
6567 // Guard variable to avoid recursively redoing the process of passing
6568 // decls to consumer.
6569 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
6572 // Ensure that we've loaded all potentially-interesting declarations
6573 // that need to be eagerly loaded.
6574 for (auto ID : EagerlyDeserializedDecls)
6576 EagerlyDeserializedDecls.clear();
6578 while (!InterestingDecls.empty()) {
6579 Decl *D = InterestingDecls.front();
6580 InterestingDecls.pop_front();
6582 PassInterestingDeclToConsumer(D);
6586 void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6587 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6588 PassObjCImplDeclToConsumer(ImplD, Consumer);
6590 Consumer->HandleInterestingDecl(DeclGroupRef(D));
6593 void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6594 this->Consumer = Consumer;
6597 PassInterestingDeclsToConsumer();
6599 if (DeserializationListener)
6600 DeserializationListener->ReaderInitialized(this);
6603 void ASTReader::PrintStats() {
6604 std::fprintf(stderr, "*** AST File Statistics:\n");
6606 unsigned NumTypesLoaded
6607 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6609 unsigned NumDeclsLoaded
6610 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
6612 unsigned NumIdentifiersLoaded
6613 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6614 IdentifiersLoaded.end(),
6615 (IdentifierInfo *)nullptr);
6616 unsigned NumMacrosLoaded
6617 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6619 (MacroInfo *)nullptr);
6620 unsigned NumSelectorsLoaded
6621 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6622 SelectorsLoaded.end(),
6625 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6626 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6627 NumSLocEntriesRead, TotalNumSLocEntries,
6628 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6629 if (!TypesLoaded.empty())
6630 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6631 NumTypesLoaded, (unsigned)TypesLoaded.size(),
6632 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6633 if (!DeclsLoaded.empty())
6634 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6635 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6636 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6637 if (!IdentifiersLoaded.empty())
6638 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6639 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6640 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6641 if (!MacrosLoaded.empty())
6642 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6643 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6644 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6645 if (!SelectorsLoaded.empty())
6646 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
6647 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6648 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6649 if (TotalNumStatements)
6650 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
6651 NumStatementsRead, TotalNumStatements,
6652 ((float)NumStatementsRead/TotalNumStatements * 100));
6654 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6655 NumMacrosRead, TotalNumMacros,
6656 ((float)NumMacrosRead/TotalNumMacros * 100));
6657 if (TotalLexicalDeclContexts)
6658 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
6659 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6660 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6662 if (TotalVisibleDeclContexts)
6663 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
6664 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6665 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6667 if (TotalNumMethodPoolEntries) {
6668 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
6669 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6670 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6673 if (NumMethodPoolLookups) {
6674 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
6675 NumMethodPoolHits, NumMethodPoolLookups,
6676 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6678 if (NumMethodPoolTableLookups) {
6679 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
6680 NumMethodPoolTableHits, NumMethodPoolTableLookups,
6681 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6685 if (NumIdentifierLookupHits) {
6686 std::fprintf(stderr,
6687 " %u / %u identifier table lookups succeeded (%f%%)\n",
6688 NumIdentifierLookupHits, NumIdentifierLookups,
6689 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
6693 std::fprintf(stderr, "\n");
6694 GlobalIndex->printStats();
6697 std::fprintf(stderr, "\n");
6699 std::fprintf(stderr, "\n");
6702 template<typename Key, typename ModuleFile, unsigned InitialCapacity>
6704 dumpModuleIDMap(StringRef Name,
6705 const ContinuousRangeMap<Key, ModuleFile *,
6706 InitialCapacity> &Map) {
6707 if (Map.begin() == Map.end())
6710 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
6711 llvm::errs() << Name << ":\n";
6712 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6714 llvm::errs() << " " << I->first << " -> " << I->second->FileName
6719 void ASTReader::dump() {
6720 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
6721 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
6722 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
6723 dumpModuleIDMap("Global type map", GlobalTypeMap);
6724 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
6725 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
6726 dumpModuleIDMap("Global macro map", GlobalMacroMap);
6727 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
6728 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
6729 dumpModuleIDMap("Global preprocessed entity map",
6730 GlobalPreprocessedEntityMap);
6732 llvm::errs() << "\n*** PCH/Modules Loaded:";
6733 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6734 MEnd = ModuleMgr.end();
6739 /// Return the amount of memory used by memory buffers, breaking down
6740 /// by heap-backed versus mmap'ed memory.
6741 void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
6742 for (ModuleConstIterator I = ModuleMgr.begin(),
6743 E = ModuleMgr.end(); I != E; ++I) {
6744 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
6745 size_t bytes = buf->getBufferSize();
6746 switch (buf->getBufferKind()) {
6747 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6748 sizes.malloc_bytes += bytes;
6750 case llvm::MemoryBuffer::MemoryBuffer_MMap:
6751 sizes.mmap_bytes += bytes;
6758 void ASTReader::InitializeSema(Sema &S) {
6760 S.addExternalSource(this);
6762 // Makes sure any declarations that were deserialized "too early"
6763 // still get added to the identifier's declaration chains.
6764 for (uint64_t ID : PreloadedDeclIDs) {
6765 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
6766 pushExternalDeclIntoScope(D, D->getDeclName());
6768 PreloadedDeclIDs.clear();
6770 // FIXME: What happens if these are changed by a module import?
6771 if (!FPPragmaOptions.empty()) {
6772 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
6773 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
6776 // FIXME: What happens if these are changed by a module import?
6777 if (!OpenCLExtensions.empty()) {
6779 #define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
6780 #include "clang/Basic/OpenCLExtensions.def"
6782 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
6788 void ASTReader::UpdateSema() {
6789 assert(SemaObj && "no Sema to update");
6791 // Load the offsets of the declarations that Sema references.
6792 // They will be lazily deserialized when needed.
6793 if (!SemaDeclRefs.empty()) {
6794 assert(SemaDeclRefs.size() % 2 == 0);
6795 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
6796 if (!SemaObj->StdNamespace)
6797 SemaObj->StdNamespace = SemaDeclRefs[I];
6798 if (!SemaObj->StdBadAlloc)
6799 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
6801 SemaDeclRefs.clear();
6804 // Update the state of 'pragma clang optimize'. Use the same API as if we had
6805 // encountered the pragma in the source.
6806 if(OptimizeOffPragmaLocation.isValid())
6807 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
6810 IdentifierInfo* ASTReader::get(const char *NameStart, const char *NameEnd) {
6811 // Note that we are loading an identifier.
6812 Deserializing AnIdentifier(this);
6813 StringRef Name(NameStart, NameEnd - NameStart);
6815 // If there is a global index, look there first to determine which modules
6816 // provably do not have any results for this identifier.
6817 GlobalModuleIndex::HitSet Hits;
6818 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
6819 if (!loadGlobalIndex()) {
6820 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
6824 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
6825 NumIdentifierLookups,
6826 NumIdentifierLookupHits);
6827 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
6828 IdentifierInfo *II = Visitor.getIdentifierInfo();
6829 markIdentifierUpToDate(II);
6834 /// \brief An identifier-lookup iterator that enumerates all of the
6835 /// identifiers stored within a set of AST files.
6836 class ASTIdentifierIterator : public IdentifierIterator {
6837 /// \brief The AST reader whose identifiers are being enumerated.
6838 const ASTReader &Reader;
6840 /// \brief The current index into the chain of AST files stored in
6844 /// \brief The current position within the identifier lookup table
6845 /// of the current AST file.
6846 ASTIdentifierLookupTable::key_iterator Current;
6848 /// \brief The end position within the identifier lookup table of
6849 /// the current AST file.
6850 ASTIdentifierLookupTable::key_iterator End;
6853 explicit ASTIdentifierIterator(const ASTReader &Reader);
6855 StringRef Next() override;
6859 ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
6860 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
6861 ASTIdentifierLookupTable *IdTable
6862 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
6863 Current = IdTable->key_begin();
6864 End = IdTable->key_end();
6867 StringRef ASTIdentifierIterator::Next() {
6868 while (Current == End) {
6869 // If we have exhausted all of our AST files, we're done.
6874 ASTIdentifierLookupTable *IdTable
6875 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
6876 IdentifierLookupTable;
6877 Current = IdTable->key_begin();
6878 End = IdTable->key_end();
6881 // We have any identifiers remaining in the current AST file; return
6883 StringRef Result = *Current;
6888 IdentifierIterator *ASTReader::getIdentifiers() {
6889 if (!loadGlobalIndex())
6890 return GlobalIndex->createIdentifierIterator();
6892 return new ASTIdentifierIterator(*this);
6895 namespace clang { namespace serialization {
6896 class ReadMethodPoolVisitor {
6899 unsigned PriorGeneration;
6900 unsigned InstanceBits;
6901 unsigned FactoryBits;
6902 bool InstanceHasMoreThanOneDecl;
6903 bool FactoryHasMoreThanOneDecl;
6904 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
6905 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
6908 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
6909 unsigned PriorGeneration)
6910 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
6911 InstanceBits(0), FactoryBits(0), InstanceHasMoreThanOneDecl(false),
6912 FactoryHasMoreThanOneDecl(false) {}
6914 static bool visit(ModuleFile &M, void *UserData) {
6915 ReadMethodPoolVisitor *This
6916 = static_cast<ReadMethodPoolVisitor *>(UserData);
6918 if (!M.SelectorLookupTable)
6921 // If we've already searched this module file, skip it now.
6922 if (M.Generation <= This->PriorGeneration)
6925 ++This->Reader.NumMethodPoolTableLookups;
6926 ASTSelectorLookupTable *PoolTable
6927 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
6928 ASTSelectorLookupTable::iterator Pos = PoolTable->find(This->Sel);
6929 if (Pos == PoolTable->end())
6932 ++This->Reader.NumMethodPoolTableHits;
6933 ++This->Reader.NumSelectorsRead;
6934 // FIXME: Not quite happy with the statistics here. We probably should
6935 // disable this tracking when called via LoadSelector.
6936 // Also, should entries without methods count as misses?
6937 ++This->Reader.NumMethodPoolEntriesRead;
6938 ASTSelectorLookupTrait::data_type Data = *Pos;
6939 if (This->Reader.DeserializationListener)
6940 This->Reader.DeserializationListener->SelectorRead(Data.ID,
6943 This->InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
6944 This->FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
6945 This->InstanceBits = Data.InstanceBits;
6946 This->FactoryBits = Data.FactoryBits;
6947 This->InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
6948 This->FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
6952 /// \brief Retrieve the instance methods found by this visitor.
6953 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
6954 return InstanceMethods;
6957 /// \brief Retrieve the instance methods found by this visitor.
6958 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
6959 return FactoryMethods;
6962 unsigned getInstanceBits() const { return InstanceBits; }
6963 unsigned getFactoryBits() const { return FactoryBits; }
6964 bool instanceHasMoreThanOneDecl() const {
6965 return InstanceHasMoreThanOneDecl;
6967 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
6969 } } // end namespace clang::serialization
6971 /// \brief Add the given set of methods to the method list.
6972 static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
6973 ObjCMethodList &List) {
6974 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
6975 S.addMethodToGlobalList(&List, Methods[I]);
6979 void ASTReader::ReadMethodPool(Selector Sel) {
6980 // Get the selector generation and update it to the current generation.
6981 unsigned &Generation = SelectorGeneration[Sel];
6982 unsigned PriorGeneration = Generation;
6983 Generation = getGeneration();
6985 // Search for methods defined with this selector.
6986 ++NumMethodPoolLookups;
6987 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
6988 ModuleMgr.visit(&ReadMethodPoolVisitor::visit, &Visitor);
6990 if (Visitor.getInstanceMethods().empty() &&
6991 Visitor.getFactoryMethods().empty())
6994 ++NumMethodPoolHits;
6999 Sema &S = *getSema();
7000 Sema::GlobalMethodPool::iterator Pos
7001 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
7003 Pos->second.first.setBits(Visitor.getInstanceBits());
7004 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
7005 Pos->second.second.setBits(Visitor.getFactoryBits());
7006 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
7008 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
7009 // when building a module we keep every method individually and may need to
7010 // update hasMoreThanOneDecl as we add the methods.
7011 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7012 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
7015 void ASTReader::ReadKnownNamespaces(
7016 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7019 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
7020 if (NamespaceDecl *Namespace
7021 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7022 Namespaces.push_back(Namespace);
7026 void ASTReader::ReadUndefinedButUsed(
7027 llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
7028 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7029 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
7030 SourceLocation Loc =
7031 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
7032 Undefined.insert(std::make_pair(D, Loc));
7036 void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
7037 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
7039 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
7040 FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
7041 uint64_t Count = DelayedDeleteExprs[Idx++];
7042 for (uint64_t C = 0; C < Count; ++C) {
7043 SourceLocation DeleteLoc =
7044 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
7045 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
7046 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
7051 void ASTReader::ReadTentativeDefinitions(
7052 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7053 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7054 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7056 TentativeDefs.push_back(Var);
7058 TentativeDefinitions.clear();
7061 void ASTReader::ReadUnusedFileScopedDecls(
7062 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7063 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7065 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7069 UnusedFileScopedDecls.clear();
7072 void ASTReader::ReadDelegatingConstructors(
7073 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7074 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7075 CXXConstructorDecl *D
7076 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7080 DelegatingCtorDecls.clear();
7083 void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7084 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7086 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7090 ExtVectorDecls.clear();
7093 void ASTReader::ReadUnusedLocalTypedefNameCandidates(
7094 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
7095 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
7097 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
7098 GetDecl(UnusedLocalTypedefNameCandidates[I]));
7102 UnusedLocalTypedefNameCandidates.clear();
7105 void ASTReader::ReadReferencedSelectors(
7106 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7107 if (ReferencedSelectorsData.empty())
7110 // If there are @selector references added them to its pool. This is for
7111 // implementation of -Wselector.
7112 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7114 while (I < DataSize) {
7115 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7116 SourceLocation SelLoc
7117 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7118 Sels.push_back(std::make_pair(Sel, SelLoc));
7120 ReferencedSelectorsData.clear();
7123 void ASTReader::ReadWeakUndeclaredIdentifiers(
7124 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7125 if (WeakUndeclaredIdentifiers.empty())
7128 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
7129 IdentifierInfo *WeakId
7130 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7131 IdentifierInfo *AliasId
7132 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7134 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7135 bool Used = WeakUndeclaredIdentifiers[I++];
7136 WeakInfo WI(AliasId, Loc);
7138 WeakIDs.push_back(std::make_pair(WeakId, WI));
7140 WeakUndeclaredIdentifiers.clear();
7143 void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7144 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7145 ExternalVTableUse VT;
7146 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7147 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7148 VT.DefinitionRequired = VTableUses[Idx++];
7149 VTables.push_back(VT);
7155 void ASTReader::ReadPendingInstantiations(
7156 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7157 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7158 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7160 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7162 Pending.push_back(std::make_pair(D, Loc));
7164 PendingInstantiations.clear();
7167 void ASTReader::ReadLateParsedTemplates(
7168 llvm::MapVector<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
7169 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7171 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7173 LateParsedTemplate *LT = new LateParsedTemplate;
7174 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7176 ModuleFile *F = getOwningModuleFile(LT->D);
7177 assert(F && "No module");
7179 unsigned TokN = LateParsedTemplates[Idx++];
7180 LT->Toks.reserve(TokN);
7181 for (unsigned T = 0; T < TokN; ++T)
7182 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7184 LPTMap.insert(std::make_pair(FD, LT));
7187 LateParsedTemplates.clear();
7190 void ASTReader::LoadSelector(Selector Sel) {
7191 // It would be complicated to avoid reading the methods anyway. So don't.
7192 ReadMethodPool(Sel);
7195 void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7196 assert(ID && "Non-zero identifier ID required");
7197 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7198 IdentifiersLoaded[ID - 1] = II;
7199 if (DeserializationListener)
7200 DeserializationListener->IdentifierRead(ID, II);
7203 /// \brief Set the globally-visible declarations associated with the given
7206 /// If the AST reader is currently in a state where the given declaration IDs
7207 /// cannot safely be resolved, they are queued until it is safe to resolve
7210 /// \param II an IdentifierInfo that refers to one or more globally-visible
7213 /// \param DeclIDs the set of declaration IDs with the name @p II that are
7214 /// visible at global scope.
7216 /// \param Decls if non-null, this vector will be populated with the set of
7217 /// deserialized declarations. These declarations will not be pushed into
7220 ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7221 const SmallVectorImpl<uint32_t> &DeclIDs,
7222 SmallVectorImpl<Decl *> *Decls) {
7223 if (NumCurrentElementsDeserializing && !Decls) {
7224 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
7228 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
7230 // Queue this declaration so that it will be added to the
7231 // translation unit scope and identifier's declaration chain
7232 // once a Sema object is known.
7233 PreloadedDeclIDs.push_back(DeclIDs[I]);
7237 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7239 // If we're simply supposed to record the declarations, do so now.
7241 Decls->push_back(D);
7245 // Introduce this declaration into the translation-unit scope
7246 // and add it to the declaration chain for this identifier, so
7247 // that (unqualified) name lookup will find it.
7248 pushExternalDeclIntoScope(D, II);
7252 IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
7256 if (IdentifiersLoaded.empty()) {
7257 Error("no identifier table in AST file");
7262 if (!IdentifiersLoaded[ID]) {
7263 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7264 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7265 ModuleFile *M = I->second;
7266 unsigned Index = ID - M->BaseIdentifierID;
7267 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7269 // All of the strings in the AST file are preceded by a 16-bit length.
7270 // Extract that 16-bit length to avoid having to execute strlen().
7271 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7272 // unsigned integers. This is important to avoid integer overflow when
7273 // we cast them to 'unsigned'.
7274 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7275 unsigned StrLen = (((unsigned) StrLenPtr[0])
7276 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
7277 IdentifiersLoaded[ID]
7278 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
7279 if (DeserializationListener)
7280 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
7283 return IdentifiersLoaded[ID];
7286 IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7287 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
7290 IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7291 if (LocalID < NUM_PREDEF_IDENT_IDS)
7294 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7295 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
7296 assert(I != M.IdentifierRemap.end()
7297 && "Invalid index into identifier index remap");
7299 return LocalID + I->second;
7302 MacroInfo *ASTReader::getMacro(MacroID ID) {
7306 if (MacrosLoaded.empty()) {
7307 Error("no macro table in AST file");
7311 ID -= NUM_PREDEF_MACRO_IDS;
7312 if (!MacrosLoaded[ID]) {
7313 GlobalMacroMapType::iterator I
7314 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7315 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7316 ModuleFile *M = I->second;
7317 unsigned Index = ID - M->BaseMacroID;
7318 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
7320 if (DeserializationListener)
7321 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7325 return MacrosLoaded[ID];
7328 MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7329 if (LocalID < NUM_PREDEF_MACRO_IDS)
7332 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7333 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7334 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7336 return LocalID + I->second;
7339 serialization::SubmoduleID
7340 ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7341 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7344 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7345 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
7346 assert(I != M.SubmoduleRemap.end()
7347 && "Invalid index into submodule index remap");
7349 return LocalID + I->second;
7352 Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7353 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7354 assert(GlobalID == 0 && "Unhandled global submodule ID");
7358 if (GlobalID > SubmodulesLoaded.size()) {
7359 Error("submodule ID out of range in AST file");
7363 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7366 Module *ASTReader::getModule(unsigned ID) {
7367 return getSubmodule(ID);
7370 ExternalASTSource::ASTSourceDescriptor
7371 ASTReader::getSourceDescriptor(const Module &M) {
7372 StringRef Dir, Filename;
7374 Dir = M.Directory->getName();
7375 if (auto *File = M.getASTFile())
7376 Filename = File->getName();
7377 return ASTReader::ASTSourceDescriptor{
7378 M.getFullModuleName(), Dir, Filename,
7383 llvm::Optional<ExternalASTSource::ASTSourceDescriptor>
7384 ASTReader::getSourceDescriptor(unsigned ID) {
7385 if (const Module *M = getSubmodule(ID))
7386 return getSourceDescriptor(*M);
7388 // If there is only a single PCH, return it instead.
7389 // Chained PCH are not suported.
7390 if (ModuleMgr.size() == 1) {
7391 ModuleFile &MF = ModuleMgr.getPrimaryModule();
7392 return ASTReader::ASTSourceDescriptor{
7393 MF.OriginalSourceFileName, MF.OriginalDir,
7401 Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7402 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7405 Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7409 if (ID > SelectorsLoaded.size()) {
7410 Error("selector ID out of range in AST file");
7414 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
7415 // Load this selector from the selector table.
7416 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7417 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7418 ModuleFile &M = *I->second;
7419 ASTSelectorLookupTrait Trait(*this, M);
7420 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7421 SelectorsLoaded[ID - 1] =
7422 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7423 if (DeserializationListener)
7424 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7427 return SelectorsLoaded[ID - 1];
7430 Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7431 return DecodeSelector(ID);
7434 uint32_t ASTReader::GetNumExternalSelectors() {
7435 // ID 0 (the null selector) is considered an external selector.
7436 return getTotalNumSelectors() + 1;
7439 serialization::SelectorID
7440 ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7441 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7444 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7445 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
7446 assert(I != M.SelectorRemap.end()
7447 && "Invalid index into selector index remap");
7449 return LocalID + I->second;
7453 ASTReader::ReadDeclarationName(ModuleFile &F,
7454 const RecordData &Record, unsigned &Idx) {
7455 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7457 case DeclarationName::Identifier:
7458 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
7460 case DeclarationName::ObjCZeroArgSelector:
7461 case DeclarationName::ObjCOneArgSelector:
7462 case DeclarationName::ObjCMultiArgSelector:
7463 return DeclarationName(ReadSelector(F, Record, Idx));
7465 case DeclarationName::CXXConstructorName:
7466 return Context.DeclarationNames.getCXXConstructorName(
7467 Context.getCanonicalType(readType(F, Record, Idx)));
7469 case DeclarationName::CXXDestructorName:
7470 return Context.DeclarationNames.getCXXDestructorName(
7471 Context.getCanonicalType(readType(F, Record, Idx)));
7473 case DeclarationName::CXXConversionFunctionName:
7474 return Context.DeclarationNames.getCXXConversionFunctionName(
7475 Context.getCanonicalType(readType(F, Record, Idx)));
7477 case DeclarationName::CXXOperatorName:
7478 return Context.DeclarationNames.getCXXOperatorName(
7479 (OverloadedOperatorKind)Record[Idx++]);
7481 case DeclarationName::CXXLiteralOperatorName:
7482 return Context.DeclarationNames.getCXXLiteralOperatorName(
7483 GetIdentifierInfo(F, Record, Idx));
7485 case DeclarationName::CXXUsingDirective:
7486 return DeclarationName::getUsingDirectiveName();
7489 llvm_unreachable("Invalid NameKind!");
7492 void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7493 DeclarationNameLoc &DNLoc,
7494 DeclarationName Name,
7495 const RecordData &Record, unsigned &Idx) {
7496 switch (Name.getNameKind()) {
7497 case DeclarationName::CXXConstructorName:
7498 case DeclarationName::CXXDestructorName:
7499 case DeclarationName::CXXConversionFunctionName:
7500 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7503 case DeclarationName::CXXOperatorName:
7504 DNLoc.CXXOperatorName.BeginOpNameLoc
7505 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7506 DNLoc.CXXOperatorName.EndOpNameLoc
7507 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7510 case DeclarationName::CXXLiteralOperatorName:
7511 DNLoc.CXXLiteralOperatorName.OpNameLoc
7512 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7515 case DeclarationName::Identifier:
7516 case DeclarationName::ObjCZeroArgSelector:
7517 case DeclarationName::ObjCOneArgSelector:
7518 case DeclarationName::ObjCMultiArgSelector:
7519 case DeclarationName::CXXUsingDirective:
7524 void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7525 DeclarationNameInfo &NameInfo,
7526 const RecordData &Record, unsigned &Idx) {
7527 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7528 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7529 DeclarationNameLoc DNLoc;
7530 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7531 NameInfo.setInfo(DNLoc);
7534 void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7535 const RecordData &Record, unsigned &Idx) {
7536 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7537 unsigned NumTPLists = Record[Idx++];
7538 Info.NumTemplParamLists = NumTPLists;
7540 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
7541 for (unsigned i=0; i != NumTPLists; ++i)
7542 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7547 ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7549 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7551 case TemplateName::Template:
7552 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7554 case TemplateName::OverloadedTemplate: {
7555 unsigned size = Record[Idx++];
7556 UnresolvedSet<8> Decls;
7558 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7560 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7563 case TemplateName::QualifiedTemplate: {
7564 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7565 bool hasTemplKeyword = Record[Idx++];
7566 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7567 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7570 case TemplateName::DependentTemplate: {
7571 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7572 if (Record[Idx++]) // isIdentifier
7573 return Context.getDependentTemplateName(NNS,
7574 GetIdentifierInfo(F, Record,
7576 return Context.getDependentTemplateName(NNS,
7577 (OverloadedOperatorKind)Record[Idx++]);
7580 case TemplateName::SubstTemplateTemplateParm: {
7581 TemplateTemplateParmDecl *param
7582 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7583 if (!param) return TemplateName();
7584 TemplateName replacement = ReadTemplateName(F, Record, Idx);
7585 return Context.getSubstTemplateTemplateParm(param, replacement);
7588 case TemplateName::SubstTemplateTemplateParmPack: {
7589 TemplateTemplateParmDecl *Param
7590 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7592 return TemplateName();
7594 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
7595 if (ArgPack.getKind() != TemplateArgument::Pack)
7596 return TemplateName();
7598 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
7602 llvm_unreachable("Unhandled template name kind!");
7606 ASTReader::ReadTemplateArgument(ModuleFile &F,
7607 const RecordData &Record, unsigned &Idx) {
7608 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
7610 case TemplateArgument::Null:
7611 return TemplateArgument();
7612 case TemplateArgument::Type:
7613 return TemplateArgument(readType(F, Record, Idx));
7614 case TemplateArgument::Declaration: {
7615 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
7616 return TemplateArgument(D, readType(F, Record, Idx));
7618 case TemplateArgument::NullPtr:
7619 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
7620 case TemplateArgument::Integral: {
7621 llvm::APSInt Value = ReadAPSInt(Record, Idx);
7622 QualType T = readType(F, Record, Idx);
7623 return TemplateArgument(Context, Value, T);
7625 case TemplateArgument::Template:
7626 return TemplateArgument(ReadTemplateName(F, Record, Idx));
7627 case TemplateArgument::TemplateExpansion: {
7628 TemplateName Name = ReadTemplateName(F, Record, Idx);
7629 Optional<unsigned> NumTemplateExpansions;
7630 if (unsigned NumExpansions = Record[Idx++])
7631 NumTemplateExpansions = NumExpansions - 1;
7632 return TemplateArgument(Name, NumTemplateExpansions);
7634 case TemplateArgument::Expression:
7635 return TemplateArgument(ReadExpr(F));
7636 case TemplateArgument::Pack: {
7637 unsigned NumArgs = Record[Idx++];
7638 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
7639 for (unsigned I = 0; I != NumArgs; ++I)
7640 Args[I] = ReadTemplateArgument(F, Record, Idx);
7641 return TemplateArgument(Args, NumArgs);
7645 llvm_unreachable("Unhandled template argument kind!");
7648 TemplateParameterList *
7649 ASTReader::ReadTemplateParameterList(ModuleFile &F,
7650 const RecordData &Record, unsigned &Idx) {
7651 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
7652 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
7653 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
7655 unsigned NumParams = Record[Idx++];
7656 SmallVector<NamedDecl *, 16> Params;
7657 Params.reserve(NumParams);
7659 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
7661 TemplateParameterList* TemplateParams =
7662 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
7663 Params.data(), Params.size(), RAngleLoc);
7664 return TemplateParams;
7669 ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
7670 ModuleFile &F, const RecordData &Record,
7672 unsigned NumTemplateArgs = Record[Idx++];
7673 TemplArgs.reserve(NumTemplateArgs);
7674 while (NumTemplateArgs--)
7675 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx));
7678 /// \brief Read a UnresolvedSet structure.
7679 void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
7680 const RecordData &Record, unsigned &Idx) {
7681 unsigned NumDecls = Record[Idx++];
7682 Set.reserve(Context, NumDecls);
7683 while (NumDecls--) {
7684 DeclID ID = ReadDeclID(F, Record, Idx);
7685 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
7686 Set.addLazyDecl(Context, ID, AS);
7691 ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
7692 const RecordData &Record, unsigned &Idx) {
7693 bool isVirtual = static_cast<bool>(Record[Idx++]);
7694 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
7695 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
7696 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
7697 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
7698 SourceRange Range = ReadSourceRange(F, Record, Idx);
7699 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
7700 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
7702 Result.setInheritConstructors(inheritConstructors);
7706 CXXCtorInitializer **
7707 ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
7709 unsigned NumInitializers = Record[Idx++];
7710 assert(NumInitializers && "wrote ctor initializers but have no inits");
7711 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
7712 for (unsigned i = 0; i != NumInitializers; ++i) {
7713 TypeSourceInfo *TInfo = nullptr;
7714 bool IsBaseVirtual = false;
7715 FieldDecl *Member = nullptr;
7716 IndirectFieldDecl *IndirectMember = nullptr;
7718 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
7720 case CTOR_INITIALIZER_BASE:
7721 TInfo = GetTypeSourceInfo(F, Record, Idx);
7722 IsBaseVirtual = Record[Idx++];
7725 case CTOR_INITIALIZER_DELEGATING:
7726 TInfo = GetTypeSourceInfo(F, Record, Idx);
7729 case CTOR_INITIALIZER_MEMBER:
7730 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
7733 case CTOR_INITIALIZER_INDIRECT_MEMBER:
7734 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
7738 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
7739 Expr *Init = ReadExpr(F);
7740 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
7741 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
7742 bool IsWritten = Record[Idx++];
7743 unsigned SourceOrderOrNumArrayIndices;
7744 SmallVector<VarDecl *, 8> Indices;
7746 SourceOrderOrNumArrayIndices = Record[Idx++];
7748 SourceOrderOrNumArrayIndices = Record[Idx++];
7749 Indices.reserve(SourceOrderOrNumArrayIndices);
7750 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
7751 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
7754 CXXCtorInitializer *BOMInit;
7755 if (Type == CTOR_INITIALIZER_BASE) {
7756 BOMInit = new (Context)
7757 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
7758 RParenLoc, MemberOrEllipsisLoc);
7759 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
7760 BOMInit = new (Context)
7761 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
7762 } else if (IsWritten) {
7764 BOMInit = new (Context) CXXCtorInitializer(
7765 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc);
7767 BOMInit = new (Context)
7768 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
7769 LParenLoc, Init, RParenLoc);
7771 if (IndirectMember) {
7772 assert(Indices.empty() && "Indirect field improperly initialized");
7773 BOMInit = new (Context)
7774 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
7775 LParenLoc, Init, RParenLoc);
7777 BOMInit = CXXCtorInitializer::Create(
7778 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc,
7779 Indices.data(), Indices.size());
7784 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
7785 CtorInitializers[i] = BOMInit;
7788 return CtorInitializers;
7791 NestedNameSpecifier *
7792 ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
7793 const RecordData &Record, unsigned &Idx) {
7794 unsigned N = Record[Idx++];
7795 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
7796 for (unsigned I = 0; I != N; ++I) {
7797 NestedNameSpecifier::SpecifierKind Kind
7798 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7800 case NestedNameSpecifier::Identifier: {
7801 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7802 NNS = NestedNameSpecifier::Create(Context, Prev, II);
7806 case NestedNameSpecifier::Namespace: {
7807 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7808 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
7812 case NestedNameSpecifier::NamespaceAlias: {
7813 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7814 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
7818 case NestedNameSpecifier::TypeSpec:
7819 case NestedNameSpecifier::TypeSpecWithTemplate: {
7820 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
7824 bool Template = Record[Idx++];
7825 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
7829 case NestedNameSpecifier::Global: {
7830 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
7831 // No associated value, and there can't be a prefix.
7835 case NestedNameSpecifier::Super: {
7836 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
7837 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
7846 NestedNameSpecifierLoc
7847 ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
7849 unsigned N = Record[Idx++];
7850 NestedNameSpecifierLocBuilder Builder;
7851 for (unsigned I = 0; I != N; ++I) {
7852 NestedNameSpecifier::SpecifierKind Kind
7853 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7855 case NestedNameSpecifier::Identifier: {
7856 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7857 SourceRange Range = ReadSourceRange(F, Record, Idx);
7858 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
7862 case NestedNameSpecifier::Namespace: {
7863 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7864 SourceRange Range = ReadSourceRange(F, Record, Idx);
7865 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
7869 case NestedNameSpecifier::NamespaceAlias: {
7870 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7871 SourceRange Range = ReadSourceRange(F, Record, Idx);
7872 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
7876 case NestedNameSpecifier::TypeSpec:
7877 case NestedNameSpecifier::TypeSpecWithTemplate: {
7878 bool Template = Record[Idx++];
7879 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
7881 return NestedNameSpecifierLoc();
7882 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7884 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
7885 Builder.Extend(Context,
7886 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
7887 T->getTypeLoc(), ColonColonLoc);
7891 case NestedNameSpecifier::Global: {
7892 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7893 Builder.MakeGlobal(Context, ColonColonLoc);
7897 case NestedNameSpecifier::Super: {
7898 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
7899 SourceRange Range = ReadSourceRange(F, Record, Idx);
7900 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
7906 return Builder.getWithLocInContext(Context);
7910 ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
7912 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
7913 SourceLocation end = ReadSourceLocation(F, Record, Idx);
7914 return SourceRange(beg, end);
7917 /// \brief Read an integral value
7918 llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
7919 unsigned BitWidth = Record[Idx++];
7920 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
7921 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
7926 /// \brief Read a signed integral value
7927 llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
7928 bool isUnsigned = Record[Idx++];
7929 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
7932 /// \brief Read a floating-point value
7933 llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
7934 const llvm::fltSemantics &Sem,
7936 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
7939 // \brief Read a string
7940 std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
7941 unsigned Len = Record[Idx++];
7942 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
7947 std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
7949 std::string Filename = ReadString(Record, Idx);
7950 ResolveImportedPath(F, Filename);
7954 VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
7956 unsigned Major = Record[Idx++];
7957 unsigned Minor = Record[Idx++];
7958 unsigned Subminor = Record[Idx++];
7960 return VersionTuple(Major);
7962 return VersionTuple(Major, Minor - 1);
7963 return VersionTuple(Major, Minor - 1, Subminor - 1);
7966 CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
7967 const RecordData &Record,
7969 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
7970 return CXXTemporary::Create(Context, Decl);
7973 DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
7974 return Diag(CurrentImportLoc, DiagID);
7977 DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
7978 return Diags.Report(Loc, DiagID);
7981 /// \brief Retrieve the identifier table associated with the
7983 IdentifierTable &ASTReader::getIdentifierTable() {
7984 return PP.getIdentifierTable();
7987 /// \brief Record that the given ID maps to the given switch-case
7989 void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
7990 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
7991 "Already have a SwitchCase with this ID");
7992 (*CurrSwitchCaseStmts)[ID] = SC;
7995 /// \brief Retrieve the switch-case statement with the given ID.
7996 SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
7997 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
7998 return (*CurrSwitchCaseStmts)[ID];
8001 void ASTReader::ClearSwitchCaseIDs() {
8002 CurrSwitchCaseStmts->clear();
8005 void ASTReader::ReadComments() {
8006 std::vector<RawComment *> Comments;
8007 for (SmallVectorImpl<std::pair<BitstreamCursor,
8008 serialization::ModuleFile *> >::iterator
8009 I = CommentsCursors.begin(),
8010 E = CommentsCursors.end();
8013 BitstreamCursor &Cursor = I->first;
8014 serialization::ModuleFile &F = *I->second;
8015 SavedStreamPosition SavedPosition(Cursor);
8019 llvm::BitstreamEntry Entry =
8020 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
8022 switch (Entry.Kind) {
8023 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
8024 case llvm::BitstreamEntry::Error:
8025 Error("malformed block record in AST file");
8027 case llvm::BitstreamEntry::EndBlock:
8029 case llvm::BitstreamEntry::Record:
8030 // The interesting case.
8036 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
8037 case COMMENTS_RAW_COMMENT: {
8039 SourceRange SR = ReadSourceRange(F, Record, Idx);
8040 RawComment::CommentKind Kind =
8041 (RawComment::CommentKind) Record[Idx++];
8042 bool IsTrailingComment = Record[Idx++];
8043 bool IsAlmostTrailingComment = Record[Idx++];
8044 Comments.push_back(new (Context) RawComment(
8045 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8046 Context.getLangOpts().CommentOpts.ParseAllComments));
8052 Context.Comments.addDeserializedComments(Comments);
8056 void ASTReader::getInputFiles(ModuleFile &F,
8057 SmallVectorImpl<serialization::InputFile> &Files) {
8058 for (unsigned I = 0, E = F.InputFilesLoaded.size(); I != E; ++I) {
8060 Files.push_back(getInputFile(F, ID));
8064 std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
8065 // If we know the owning module, use it.
8066 if (Module *M = D->getImportedOwningModule())
8067 return M->getFullModuleName();
8069 // Otherwise, use the name of the top-level module the decl is within.
8070 if (ModuleFile *M = getOwningModuleFile(D))
8071 return M->ModuleName;
8073 // Not from a module.
8077 void ASTReader::finishPendingActions() {
8078 while (!PendingIdentifierInfos.empty() ||
8079 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
8080 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
8081 !PendingUpdateRecords.empty()) {
8082 // If any identifiers with corresponding top-level declarations have
8083 // been loaded, load those declarations now.
8084 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8086 TopLevelDeclsMap TopLevelDecls;
8088 while (!PendingIdentifierInfos.empty()) {
8089 IdentifierInfo *II = PendingIdentifierInfos.back().first;
8090 SmallVector<uint32_t, 4> DeclIDs =
8091 std::move(PendingIdentifierInfos.back().second);
8092 PendingIdentifierInfos.pop_back();
8094 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
8097 // For each decl chain that we wanted to complete while deserializing, mark
8098 // it as "still needs to be completed".
8099 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8100 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8102 PendingIncompleteDeclChains.clear();
8104 // Load pending declaration chains.
8105 for (unsigned I = 0; I != PendingDeclChains.size(); ++I) {
8106 PendingDeclChainsKnown.erase(PendingDeclChains[I]);
8107 loadPendingDeclChain(PendingDeclChains[I]);
8109 assert(PendingDeclChainsKnown.empty());
8110 PendingDeclChains.clear();
8112 // Make the most recent of the top-level declarations visible.
8113 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8114 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
8115 IdentifierInfo *II = TLD->first;
8116 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
8117 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
8121 // Load any pending macro definitions.
8122 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
8123 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8124 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8125 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8126 // Initialize the macro history from chained-PCHs ahead of module imports.
8127 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
8129 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
8130 if (Info.M->Kind != MK_ImplicitModule &&
8131 Info.M->Kind != MK_ExplicitModule)
8132 resolvePendingMacro(II, Info);
8134 // Handle module imports.
8135 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
8137 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
8138 if (Info.M->Kind == MK_ImplicitModule ||
8139 Info.M->Kind == MK_ExplicitModule)
8140 resolvePendingMacro(II, Info);
8143 PendingMacroIDs.clear();
8145 // Wire up the DeclContexts for Decls that we delayed setting until
8146 // recursive loading is completed.
8147 while (!PendingDeclContextInfos.empty()) {
8148 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8149 PendingDeclContextInfos.pop_front();
8150 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8151 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8152 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8155 // Perform any pending declaration updates.
8156 while (!PendingUpdateRecords.empty()) {
8157 auto Update = PendingUpdateRecords.pop_back_val();
8158 ReadingKindTracker ReadingKind(Read_Decl, *this);
8159 loadDeclUpdateRecords(Update.first, Update.second);
8163 // At this point, all update records for loaded decls are in place, so any
8164 // fake class definitions should have become real.
8165 assert(PendingFakeDefinitionData.empty() &&
8166 "faked up a class definition but never saw the real one");
8168 // If we deserialized any C++ or Objective-C class definitions, any
8169 // Objective-C protocol definitions, or any redeclarable templates, make sure
8170 // that all redeclarations point to the definitions. Note that this can only
8171 // happen now, after the redeclaration chains have been fully wired.
8172 for (Decl *D : PendingDefinitions) {
8173 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
8174 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
8175 // Make sure that the TagType points at the definition.
8176 const_cast<TagType*>(TagT)->decl = TD;
8179 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
8180 for (auto *R = getMostRecentExistingDecl(RD); R;
8181 R = R->getPreviousDecl()) {
8183 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
8184 "declaration thinks it's the definition but it isn't");
8185 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
8192 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
8193 // Make sure that the ObjCInterfaceType points at the definition.
8194 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8197 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
8198 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
8203 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
8204 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
8205 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
8210 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
8211 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
8212 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
8214 PendingDefinitions.clear();
8216 // Load the bodies of any functions or methods we've encountered. We do
8217 // this now (delayed) so that we can be sure that the declaration chains
8218 // have been fully wired up.
8219 // FIXME: There seems to be no point in delaying this, it does not depend
8220 // on the redecl chains having been wired up.
8221 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8222 PBEnd = PendingBodies.end();
8223 PB != PBEnd; ++PB) {
8224 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8225 // FIXME: Check for =delete/=default?
8226 // FIXME: Complain about ODR violations here?
8227 if (!getContext().getLangOpts().Modules || !FD->hasBody())
8228 FD->setLazyBody(PB->second);
8232 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8233 if (!getContext().getLangOpts().Modules || !MD->hasBody())
8234 MD->setLazyBody(PB->second);
8236 PendingBodies.clear();
8239 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
8240 getContext().deduplicateMergedDefinitonsFor(ND);
8241 PendingMergedDefinitionsToDeduplicate.clear();
8244 void ASTReader::diagnoseOdrViolations() {
8245 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty())
8248 // Trigger the import of the full definition of each class that had any
8249 // odr-merging problems, so we can produce better diagnostics for them.
8250 // These updates may in turn find and diagnose some ODR failures, so take
8251 // ownership of the set first.
8252 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
8253 PendingOdrMergeFailures.clear();
8254 for (auto &Merge : OdrMergeFailures) {
8255 Merge.first->buildLookup();
8256 Merge.first->decls_begin();
8257 Merge.first->bases_begin();
8258 Merge.first->vbases_begin();
8259 for (auto *RD : Merge.second) {
8266 // For each declaration from a merged context, check that the canonical
8267 // definition of that context also contains a declaration of the same
8270 // Caution: this loop does things that might invalidate iterators into
8271 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
8272 while (!PendingOdrMergeChecks.empty()) {
8273 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8275 // FIXME: Skip over implicit declarations for now. This matters for things
8276 // like implicitly-declared special member functions. This isn't entirely
8277 // correct; we can end up with multiple unmerged declarations of the same
8279 if (D->isImplicit())
8282 DeclContext *CanonDef = D->getDeclContext();
8285 const Decl *DCanon = D->getCanonicalDecl();
8287 for (auto RI : D->redecls()) {
8288 if (RI->getLexicalDeclContext() == CanonDef) {
8296 llvm::SmallVector<const NamedDecl*, 4> Candidates;
8297 DeclContext::lookup_result R = CanonDef->lookup(D->getDeclName());
8298 for (DeclContext::lookup_iterator I = R.begin(), E = R.end();
8299 !Found && I != E; ++I) {
8300 for (auto RI : (*I)->redecls()) {
8301 if (RI->getLexicalDeclContext() == CanonDef) {
8302 // This declaration is present in the canonical definition. If it's
8303 // in the same redecl chain, it's the one we're looking for.
8304 if (RI->getCanonicalDecl() == DCanon)
8307 Candidates.push_back(cast<NamedDecl>(RI));
8314 // The AST doesn't like TagDecls becoming invalid after they've been
8315 // completed. We only really need to mark FieldDecls as invalid here.
8316 if (!isa<TagDecl>(D))
8317 D->setInvalidDecl();
8319 // Ensure we don't accidentally recursively enter deserialization while
8320 // we're producing our diagnostic.
8321 Deserializing RecursionGuard(this);
8323 std::string CanonDefModule =
8324 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
8325 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
8326 << D << getOwningModuleNameForDiagnostic(D)
8327 << CanonDef << CanonDefModule.empty() << CanonDefModule;
8329 if (Candidates.empty())
8330 Diag(cast<Decl>(CanonDef)->getLocation(),
8331 diag::note_module_odr_violation_no_possible_decls) << D;
8333 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
8334 Diag(Candidates[I]->getLocation(),
8335 diag::note_module_odr_violation_possible_decl)
8339 DiagnosedOdrMergeFailures.insert(CanonDef);
8343 if (OdrMergeFailures.empty())
8346 // Ensure we don't accidentally recursively enter deserialization while
8347 // we're producing our diagnostics.
8348 Deserializing RecursionGuard(this);
8350 // Issue any pending ODR-failure diagnostics.
8351 for (auto &Merge : OdrMergeFailures) {
8352 // If we've already pointed out a specific problem with this class, don't
8353 // bother issuing a general "something's different" diagnostic.
8354 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
8357 bool Diagnosed = false;
8358 for (auto *RD : Merge.second) {
8359 // Multiple different declarations got merged together; tell the user
8360 // where they came from.
8361 if (Merge.first != RD) {
8362 // FIXME: Walk the definition, figure out what's different,
8363 // and diagnose that.
8365 std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
8366 Diag(Merge.first->getLocation(),
8367 diag::err_module_odr_violation_different_definitions)
8368 << Merge.first << Module.empty() << Module;
8372 Diag(RD->getLocation(),
8373 diag::note_module_odr_violation_different_definitions)
8374 << getOwningModuleNameForDiagnostic(RD);
8379 // All definitions are updates to the same declaration. This happens if a
8380 // module instantiates the declaration of a class template specialization
8381 // and two or more other modules instantiate its definition.
8383 // FIXME: Indicate which modules had instantiations of this definition.
8384 // FIXME: How can this even happen?
8385 Diag(Merge.first->getLocation(),
8386 diag::err_module_odr_violation_different_instantiations)
8392 void ASTReader::FinishedDeserializing() {
8393 assert(NumCurrentElementsDeserializing &&
8394 "FinishedDeserializing not paired with StartedDeserializing");
8395 if (NumCurrentElementsDeserializing == 1) {
8396 // We decrease NumCurrentElementsDeserializing only after pending actions
8397 // are finished, to avoid recursively re-calling finishPendingActions().
8398 finishPendingActions();
8400 --NumCurrentElementsDeserializing;
8402 if (NumCurrentElementsDeserializing == 0) {
8403 // Propagate exception specification updates along redeclaration chains.
8404 while (!PendingExceptionSpecUpdates.empty()) {
8405 auto Updates = std::move(PendingExceptionSpecUpdates);
8406 PendingExceptionSpecUpdates.clear();
8407 for (auto Update : Updates) {
8408 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
8409 SemaObj->UpdateExceptionSpec(Update.second,
8410 FPT->getExtProtoInfo().ExceptionSpec);
8414 diagnoseOdrViolations();
8416 // We are not in recursive loading, so it's safe to pass the "interesting"
8417 // decls to the consumer.
8419 PassInterestingDeclsToConsumer();
8423 void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
8424 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
8425 // Remove any fake results before adding any real ones.
8426 auto It = PendingFakeLookupResults.find(II);
8427 if (It != PendingFakeLookupResults.end()) {
8428 for (auto *ND : PendingFakeLookupResults[II])
8429 SemaObj->IdResolver.RemoveDecl(ND);
8430 // FIXME: this works around module+PCH performance issue.
8431 // Rather than erase the result from the map, which is O(n), just clear
8432 // the vector of NamedDecls.
8437 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
8438 SemaObj->TUScope->AddDecl(D);
8439 } else if (SemaObj->TUScope) {
8440 // Adding the decl to IdResolver may have failed because it was already in
8441 // (even though it was not added in scope). If it is already in, make sure
8442 // it gets in the scope as well.
8443 if (std::find(SemaObj->IdResolver.begin(Name),
8444 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
8445 SemaObj->TUScope->AddDecl(D);
8449 ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context,
8450 const PCHContainerOperations &PCHContainerOps,
8451 StringRef isysroot, bool DisableValidation,
8452 bool AllowASTWithCompilerErrors,
8453 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
8454 bool UseGlobalIndex)
8455 : Listener(new PCHValidator(PP, *this)), DeserializationListener(nullptr),
8456 OwnsDeserializationListener(false), SourceMgr(PP.getSourceManager()),
8457 FileMgr(PP.getFileManager()), PCHContainerOps(PCHContainerOps),
8458 Diags(PP.getDiagnostics()), SemaObj(nullptr), PP(PP), Context(Context),
8459 Consumer(nullptr), ModuleMgr(PP.getFileManager(), PCHContainerOps),
8460 isysroot(isysroot), DisableValidation(DisableValidation),
8461 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
8462 AllowConfigurationMismatch(AllowConfigurationMismatch),
8463 ValidateSystemInputs(ValidateSystemInputs),
8464 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
8465 CurrSwitchCaseStmts(&SwitchCaseStmts), NumSLocEntriesRead(0),
8466 TotalNumSLocEntries(0), NumStatementsRead(0), TotalNumStatements(0),
8467 NumMacrosRead(0), TotalNumMacros(0), NumIdentifierLookups(0),
8468 NumIdentifierLookupHits(0), NumSelectorsRead(0),
8469 NumMethodPoolEntriesRead(0), NumMethodPoolLookups(0),
8470 NumMethodPoolHits(0), NumMethodPoolTableLookups(0),
8471 NumMethodPoolTableHits(0), TotalNumMethodPoolEntries(0),
8472 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
8473 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
8474 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
8475 PassingDeclsToConsumer(false), ReadingKind(Read_None) {
8476 SourceMgr.setExternalSLocEntrySource(this);
8479 ASTReader::~ASTReader() {
8480 if (OwnsDeserializationListener)
8481 delete DeserializationListener;
8483 for (DeclContextVisibleUpdatesPending::iterator
8484 I = PendingVisibleUpdates.begin(),
8485 E = PendingVisibleUpdates.end();
8487 for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
8488 F = I->second.end();