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/ASTMutationListener.h"
24 #include "clang/AST/NestedNameSpecifier.h"
25 #include "clang/AST/Type.h"
26 #include "clang/AST/TypeLocVisitor.h"
27 #include "clang/Basic/DiagnosticOptions.h"
28 #include "clang/Basic/FileManager.h"
29 #include "clang/Basic/SourceManager.h"
30 #include "clang/Basic/SourceManagerInternals.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Basic/TargetOptions.h"
33 #include "clang/Basic/Version.h"
34 #include "clang/Basic/VersionTuple.h"
35 #include "clang/Frontend/Utils.h"
36 #include "clang/Lex/HeaderSearch.h"
37 #include "clang/Lex/HeaderSearchOptions.h"
38 #include "clang/Lex/MacroInfo.h"
39 #include "clang/Lex/PreprocessingRecord.h"
40 #include "clang/Lex/Preprocessor.h"
41 #include "clang/Lex/PreprocessorOptions.h"
42 #include "clang/Sema/Scope.h"
43 #include "clang/Sema/Sema.h"
44 #include "clang/Serialization/ASTDeserializationListener.h"
45 #include "clang/Serialization/GlobalModuleIndex.h"
46 #include "clang/Serialization/ModuleManager.h"
47 #include "clang/Serialization/SerializationDiagnostic.h"
48 #include "llvm/ADT/Hashing.h"
49 #include "llvm/ADT/StringExtras.h"
50 #include "llvm/Bitcode/BitstreamReader.h"
51 #include "llvm/Support/Compression.h"
52 #include "llvm/Support/ErrorHandling.h"
53 #include "llvm/Support/FileSystem.h"
54 #include "llvm/Support/MemoryBuffer.h"
55 #include "llvm/Support/Path.h"
56 #include "llvm/Support/SaveAndRestore.h"
57 #include "llvm/Support/raw_ostream.h"
61 #include <system_error>
63 using namespace clang;
64 using namespace clang::serialization;
65 using namespace clang::serialization::reader;
66 using llvm::BitstreamCursor;
69 //===----------------------------------------------------------------------===//
70 // ChainedASTReaderListener implementation
71 //===----------------------------------------------------------------------===//
74 ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
75 return First->ReadFullVersionInformation(FullVersion) ||
76 Second->ReadFullVersionInformation(FullVersion);
78 void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
79 First->ReadModuleName(ModuleName);
80 Second->ReadModuleName(ModuleName);
82 void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
83 First->ReadModuleMapFile(ModuleMapPath);
84 Second->ReadModuleMapFile(ModuleMapPath);
87 ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
89 bool AllowCompatibleDifferences) {
90 return First->ReadLanguageOptions(LangOpts, Complain,
91 AllowCompatibleDifferences) ||
92 Second->ReadLanguageOptions(LangOpts, Complain,
93 AllowCompatibleDifferences);
95 bool ChainedASTReaderListener::ReadTargetOptions(
96 const TargetOptions &TargetOpts, bool Complain,
97 bool AllowCompatibleDifferences) {
98 return First->ReadTargetOptions(TargetOpts, Complain,
99 AllowCompatibleDifferences) ||
100 Second->ReadTargetOptions(TargetOpts, Complain,
101 AllowCompatibleDifferences);
103 bool ChainedASTReaderListener::ReadDiagnosticOptions(
104 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
105 return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
106 Second->ReadDiagnosticOptions(DiagOpts, Complain);
109 ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
111 return First->ReadFileSystemOptions(FSOpts, Complain) ||
112 Second->ReadFileSystemOptions(FSOpts, Complain);
115 bool ChainedASTReaderListener::ReadHeaderSearchOptions(
116 const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath,
118 return First->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
120 Second->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
123 bool ChainedASTReaderListener::ReadPreprocessorOptions(
124 const PreprocessorOptions &PPOpts, bool Complain,
125 std::string &SuggestedPredefines) {
126 return First->ReadPreprocessorOptions(PPOpts, Complain,
127 SuggestedPredefines) ||
128 Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
130 void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
132 First->ReadCounter(M, Value);
133 Second->ReadCounter(M, Value);
135 bool ChainedASTReaderListener::needsInputFileVisitation() {
136 return First->needsInputFileVisitation() ||
137 Second->needsInputFileVisitation();
139 bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
140 return First->needsSystemInputFileVisitation() ||
141 Second->needsSystemInputFileVisitation();
143 void ChainedASTReaderListener::visitModuleFile(StringRef Filename,
145 First->visitModuleFile(Filename, Kind);
146 Second->visitModuleFile(Filename, Kind);
148 bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
151 bool isExplicitModule) {
152 bool Continue = false;
153 if (First->needsInputFileVisitation() &&
154 (!isSystem || First->needsSystemInputFileVisitation()))
155 Continue |= First->visitInputFile(Filename, isSystem, isOverridden,
157 if (Second->needsInputFileVisitation() &&
158 (!isSystem || Second->needsSystemInputFileVisitation()))
159 Continue |= Second->visitInputFile(Filename, isSystem, isOverridden,
164 void ChainedASTReaderListener::readModuleFileExtension(
165 const ModuleFileExtensionMetadata &Metadata) {
166 First->readModuleFileExtension(Metadata);
167 Second->readModuleFileExtension(Metadata);
170 //===----------------------------------------------------------------------===//
171 // PCH validator implementation
172 //===----------------------------------------------------------------------===//
174 ASTReaderListener::~ASTReaderListener() {}
176 /// \brief Compare the given set of language options against an existing set of
177 /// language options.
179 /// \param Diags If non-NULL, diagnostics will be emitted via this engine.
180 /// \param AllowCompatibleDifferences If true, differences between compatible
181 /// language options will be permitted.
183 /// \returns true if the languagae options mis-match, false otherwise.
184 static bool checkLanguageOptions(const LangOptions &LangOpts,
185 const LangOptions &ExistingLangOpts,
186 DiagnosticsEngine *Diags,
187 bool AllowCompatibleDifferences = true) {
188 #define LANGOPT(Name, Bits, Default, Description) \
189 if (ExistingLangOpts.Name != LangOpts.Name) { \
191 Diags->Report(diag::err_pch_langopt_mismatch) \
192 << Description << LangOpts.Name << ExistingLangOpts.Name; \
196 #define VALUE_LANGOPT(Name, Bits, Default, Description) \
197 if (ExistingLangOpts.Name != LangOpts.Name) { \
199 Diags->Report(diag::err_pch_langopt_value_mismatch) \
204 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
205 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
207 Diags->Report(diag::err_pch_langopt_value_mismatch) \
212 #define COMPATIBLE_LANGOPT(Name, Bits, Default, Description) \
213 if (!AllowCompatibleDifferences) \
214 LANGOPT(Name, Bits, Default, Description)
216 #define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description) \
217 if (!AllowCompatibleDifferences) \
218 ENUM_LANGOPT(Name, Bits, Default, Description)
220 #define COMPATIBLE_VALUE_LANGOPT(Name, Bits, Default, Description) \
221 if (!AllowCompatibleDifferences) \
222 VALUE_LANGOPT(Name, Bits, Default, Description)
224 #define BENIGN_LANGOPT(Name, Bits, Default, Description)
225 #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
226 #define BENIGN_VALUE_LANGOPT(Name, Type, Bits, Default, Description)
227 #include "clang/Basic/LangOptions.def"
229 if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) {
231 Diags->Report(diag::err_pch_langopt_value_mismatch) << "module features";
235 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
237 Diags->Report(diag::err_pch_langopt_value_mismatch)
238 << "target Objective-C runtime";
242 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
243 LangOpts.CommentOpts.BlockCommandNames) {
245 Diags->Report(diag::err_pch_langopt_value_mismatch)
246 << "block command names";
253 /// \brief Compare the given set of target options against an existing set of
256 /// \param Diags If non-NULL, diagnostics will be emitted via this engine.
258 /// \returns true if the target options mis-match, false otherwise.
259 static bool checkTargetOptions(const TargetOptions &TargetOpts,
260 const TargetOptions &ExistingTargetOpts,
261 DiagnosticsEngine *Diags,
262 bool AllowCompatibleDifferences = true) {
263 #define CHECK_TARGET_OPT(Field, Name) \
264 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
266 Diags->Report(diag::err_pch_targetopt_mismatch) \
267 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
271 // The triple and ABI must match exactly.
272 CHECK_TARGET_OPT(Triple, "target");
273 CHECK_TARGET_OPT(ABI, "target ABI");
275 // We can tolerate different CPUs in many cases, notably when one CPU
276 // supports a strict superset of another. When allowing compatible
277 // differences skip this check.
278 if (!AllowCompatibleDifferences)
279 CHECK_TARGET_OPT(CPU, "target CPU");
281 #undef CHECK_TARGET_OPT
283 // Compare feature sets.
284 SmallVector<StringRef, 4> ExistingFeatures(
285 ExistingTargetOpts.FeaturesAsWritten.begin(),
286 ExistingTargetOpts.FeaturesAsWritten.end());
287 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
288 TargetOpts.FeaturesAsWritten.end());
289 std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
290 std::sort(ReadFeatures.begin(), ReadFeatures.end());
292 // We compute the set difference in both directions explicitly so that we can
293 // diagnose the differences differently.
294 SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
296 ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
297 ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
298 std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
299 ExistingFeatures.begin(), ExistingFeatures.end(),
300 std::back_inserter(UnmatchedReadFeatures));
302 // If we are allowing compatible differences and the read feature set is
303 // a strict subset of the existing feature set, there is nothing to diagnose.
304 if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
308 for (StringRef Feature : UnmatchedReadFeatures)
309 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
310 << /* is-existing-feature */ false << Feature;
311 for (StringRef Feature : UnmatchedExistingFeatures)
312 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
313 << /* is-existing-feature */ true << Feature;
316 return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
320 PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
322 bool AllowCompatibleDifferences) {
323 const LangOptions &ExistingLangOpts = PP.getLangOpts();
324 return checkLanguageOptions(LangOpts, ExistingLangOpts,
325 Complain ? &Reader.Diags : nullptr,
326 AllowCompatibleDifferences);
329 bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
331 bool AllowCompatibleDifferences) {
332 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
333 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
334 Complain ? &Reader.Diags : nullptr,
335 AllowCompatibleDifferences);
339 typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
341 typedef llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> >
345 static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
346 DiagnosticsEngine &Diags,
348 typedef DiagnosticsEngine::Level Level;
350 // Check current mappings for new -Werror mappings, and the stored mappings
351 // for cases that were explicitly mapped to *not* be errors that are now
352 // errors because of options like -Werror.
353 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
355 for (DiagnosticsEngine *MappingSource : MappingSources) {
356 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
357 diag::kind DiagID = DiagIDMappingPair.first;
358 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
359 if (CurLevel < DiagnosticsEngine::Error)
360 continue; // not significant
362 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
363 if (StoredLevel < DiagnosticsEngine::Error) {
365 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
366 Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
375 static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
376 diag::Severity Ext = Diags.getExtensionHandlingBehavior();
377 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
379 return Ext >= diag::Severity::Error;
382 static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
383 DiagnosticsEngine &Diags,
384 bool IsSystem, bool Complain) {
387 if (Diags.getSuppressSystemWarnings())
389 // If -Wsystem-headers was not enabled before, be conservative
390 if (StoredDiags.getSuppressSystemWarnings()) {
392 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
397 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
399 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
403 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
404 !StoredDiags.getEnableAllWarnings()) {
406 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
410 if (isExtHandlingFromDiagsError(Diags) &&
411 !isExtHandlingFromDiagsError(StoredDiags)) {
413 Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
417 return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
420 bool PCHValidator::ReadDiagnosticOptions(
421 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
422 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
423 IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
424 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
425 new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
426 // This should never fail, because we would have processed these options
427 // before writing them to an ASTFile.
428 ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
430 ModuleManager &ModuleMgr = Reader.getModuleManager();
431 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
433 // If the original import came from a file explicitly generated by the user,
434 // don't check the diagnostic mappings.
435 // FIXME: currently this is approximated by checking whether this is not a
436 // module import of an implicitly-loaded module file.
437 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
438 // the transitive closure of its imports, since unrelated modules cannot be
439 // imported until after this module finishes validation.
440 ModuleFile *TopImport = *ModuleMgr.rbegin();
441 while (!TopImport->ImportedBy.empty())
442 TopImport = TopImport->ImportedBy[0];
443 if (TopImport->Kind != MK_ImplicitModule)
446 StringRef ModuleName = TopImport->ModuleName;
447 assert(!ModuleName.empty() && "diagnostic options read before module name");
449 Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
450 assert(M && "missing module");
452 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
453 // contains the union of their flags.
454 return checkDiagnosticMappings(*Diags, ExistingDiags, M->IsSystem, Complain);
457 /// \brief Collect the macro definitions provided by the given preprocessor
460 collectMacroDefinitions(const PreprocessorOptions &PPOpts,
461 MacroDefinitionsMap &Macros,
462 SmallVectorImpl<StringRef> *MacroNames = nullptr) {
463 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
464 StringRef Macro = PPOpts.Macros[I].first;
465 bool IsUndef = PPOpts.Macros[I].second;
467 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
468 StringRef MacroName = MacroPair.first;
469 StringRef MacroBody = MacroPair.second;
471 // For an #undef'd macro, we only care about the name.
473 if (MacroNames && !Macros.count(MacroName))
474 MacroNames->push_back(MacroName);
476 Macros[MacroName] = std::make_pair("", true);
480 // For a #define'd macro, figure out the actual definition.
481 if (MacroName.size() == Macro.size())
484 // Note: GCC drops anything following an end-of-line character.
485 StringRef::size_type End = MacroBody.find_first_of("\n\r");
486 MacroBody = MacroBody.substr(0, End);
489 if (MacroNames && !Macros.count(MacroName))
490 MacroNames->push_back(MacroName);
491 Macros[MacroName] = std::make_pair(MacroBody, false);
495 /// \brief Check the preprocessor options deserialized from the control block
496 /// against the preprocessor options in an existing preprocessor.
498 /// \param Diags If non-null, produce diagnostics for any mismatches incurred.
499 /// \param Validate If true, validate preprocessor options. If false, allow
500 /// macros defined by \p ExistingPPOpts to override those defined by
501 /// \p PPOpts in SuggestedPredefines.
502 static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
503 const PreprocessorOptions &ExistingPPOpts,
504 DiagnosticsEngine *Diags,
505 FileManager &FileMgr,
506 std::string &SuggestedPredefines,
507 const LangOptions &LangOpts,
508 bool Validate = true) {
509 // Check macro definitions.
510 MacroDefinitionsMap ASTFileMacros;
511 collectMacroDefinitions(PPOpts, ASTFileMacros);
512 MacroDefinitionsMap ExistingMacros;
513 SmallVector<StringRef, 4> ExistingMacroNames;
514 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
516 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
517 // Dig out the macro definition in the existing preprocessor options.
518 StringRef MacroName = ExistingMacroNames[I];
519 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
521 // Check whether we know anything about this macro name or not.
522 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
523 = ASTFileMacros.find(MacroName);
524 if (!Validate || Known == ASTFileMacros.end()) {
525 // FIXME: Check whether this identifier was referenced anywhere in the
526 // AST file. If so, we should reject the AST file. Unfortunately, this
527 // information isn't in the control block. What shall we do about it?
529 if (Existing.second) {
530 SuggestedPredefines += "#undef ";
531 SuggestedPredefines += MacroName.str();
532 SuggestedPredefines += '\n';
534 SuggestedPredefines += "#define ";
535 SuggestedPredefines += MacroName.str();
536 SuggestedPredefines += ' ';
537 SuggestedPredefines += Existing.first.str();
538 SuggestedPredefines += '\n';
543 // If the macro was defined in one but undef'd in the other, we have a
545 if (Existing.second != Known->second.second) {
547 Diags->Report(diag::err_pch_macro_def_undef)
548 << MacroName << Known->second.second;
553 // If the macro was #undef'd in both, or if the macro bodies are identical,
555 if (Existing.second || Existing.first == Known->second.first)
558 // The macro bodies differ; complain.
560 Diags->Report(diag::err_pch_macro_def_conflict)
561 << MacroName << Known->second.first << Existing.first;
566 // Check whether we're using predefines.
567 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines && Validate) {
569 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
574 // Detailed record is important since it is used for the module cache hash.
575 if (LangOpts.Modules &&
576 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord && Validate) {
578 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
583 // Compute the #include and #include_macros lines we need.
584 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
585 StringRef File = ExistingPPOpts.Includes[I];
586 if (File == ExistingPPOpts.ImplicitPCHInclude)
589 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
590 != PPOpts.Includes.end())
593 SuggestedPredefines += "#include \"";
594 SuggestedPredefines += File;
595 SuggestedPredefines += "\"\n";
598 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
599 StringRef File = ExistingPPOpts.MacroIncludes[I];
600 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
602 != PPOpts.MacroIncludes.end())
605 SuggestedPredefines += "#__include_macros \"";
606 SuggestedPredefines += File;
607 SuggestedPredefines += "\"\n##\n";
613 bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
615 std::string &SuggestedPredefines) {
616 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
618 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
619 Complain? &Reader.Diags : nullptr,
625 bool SimpleASTReaderListener::ReadPreprocessorOptions(
626 const PreprocessorOptions &PPOpts,
628 std::string &SuggestedPredefines) {
629 return checkPreprocessorOptions(PPOpts,
630 PP.getPreprocessorOpts(),
638 /// Check the header search options deserialized from the control block
639 /// against the header search options in an existing preprocessor.
641 /// \param Diags If non-null, produce diagnostics for any mismatches incurred.
642 static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
643 StringRef SpecificModuleCachePath,
644 StringRef ExistingModuleCachePath,
645 DiagnosticsEngine *Diags,
646 const LangOptions &LangOpts) {
647 if (LangOpts.Modules) {
648 if (SpecificModuleCachePath != ExistingModuleCachePath) {
650 Diags->Report(diag::err_pch_modulecache_mismatch)
651 << SpecificModuleCachePath << ExistingModuleCachePath;
659 bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
660 StringRef SpecificModuleCachePath,
662 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
663 PP.getHeaderSearchInfo().getModuleCachePath(),
664 Complain ? &Reader.Diags : nullptr,
668 void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
669 PP.setCounterValue(Value);
672 //===----------------------------------------------------------------------===//
673 // AST reader implementation
674 //===----------------------------------------------------------------------===//
676 void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
677 bool TakeOwnership) {
678 DeserializationListener = Listener;
679 OwnsDeserializationListener = TakeOwnership;
684 unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
685 return serialization::ComputeHash(Sel);
689 std::pair<unsigned, unsigned>
690 ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
691 using namespace llvm::support;
692 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
693 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
694 return std::make_pair(KeyLen, DataLen);
697 ASTSelectorLookupTrait::internal_key_type
698 ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
699 using namespace llvm::support;
700 SelectorTable &SelTable = Reader.getContext().Selectors;
701 unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
702 IdentifierInfo *FirstII = Reader.getLocalIdentifier(
703 F, endian::readNext<uint32_t, little, unaligned>(d));
705 return SelTable.getNullarySelector(FirstII);
707 return SelTable.getUnarySelector(FirstII);
709 SmallVector<IdentifierInfo *, 16> Args;
710 Args.push_back(FirstII);
711 for (unsigned I = 1; I != N; ++I)
712 Args.push_back(Reader.getLocalIdentifier(
713 F, endian::readNext<uint32_t, little, unaligned>(d)));
715 return SelTable.getSelector(N, Args.data());
718 ASTSelectorLookupTrait::data_type
719 ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
721 using namespace llvm::support;
725 Result.ID = Reader.getGlobalSelectorID(
726 F, endian::readNext<uint32_t, little, unaligned>(d));
727 unsigned FullInstanceBits = endian::readNext<uint16_t, little, unaligned>(d);
728 unsigned FullFactoryBits = endian::readNext<uint16_t, little, unaligned>(d);
729 Result.InstanceBits = FullInstanceBits & 0x3;
730 Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
731 Result.FactoryBits = FullFactoryBits & 0x3;
732 Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
733 unsigned NumInstanceMethods = FullInstanceBits >> 3;
734 unsigned NumFactoryMethods = FullFactoryBits >> 3;
736 // Load instance methods
737 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
738 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
739 F, endian::readNext<uint32_t, little, unaligned>(d)))
740 Result.Instance.push_back(Method);
743 // Load factory methods
744 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
745 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
746 F, endian::readNext<uint32_t, little, unaligned>(d)))
747 Result.Factory.push_back(Method);
753 unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
754 return llvm::HashString(a);
757 std::pair<unsigned, unsigned>
758 ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
759 using namespace llvm::support;
760 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
761 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
762 return std::make_pair(KeyLen, DataLen);
765 ASTIdentifierLookupTraitBase::internal_key_type
766 ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
767 assert(n >= 2 && d[n-1] == '\0');
768 return StringRef((const char*) d, n-1);
771 /// \brief Whether the given identifier is "interesting".
772 static bool isInterestingIdentifier(ASTReader &Reader, IdentifierInfo &II,
774 return II.hadMacroDefinition() ||
776 (IsModule ? II.hasRevertedBuiltin() : II.getObjCOrBuiltinID()) ||
777 II.hasRevertedTokenIDToIdentifier() ||
778 (!(IsModule && Reader.getContext().getLangOpts().CPlusPlus) &&
779 II.getFETokenInfo<void>());
782 static bool readBit(unsigned &Bits) {
783 bool Value = Bits & 0x1;
788 IdentID ASTIdentifierLookupTrait::ReadIdentifierID(const unsigned char *d) {
789 using namespace llvm::support;
790 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
791 return Reader.getGlobalIdentifierID(F, RawID >> 1);
794 static void markIdentifierFromAST(ASTReader &Reader, IdentifierInfo &II) {
795 if (!II.isFromAST()) {
797 bool IsModule = Reader.getPreprocessor().getCurrentModule() != nullptr;
798 if (isInterestingIdentifier(Reader, II, IsModule))
799 II.setChangedSinceDeserialization();
803 IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
804 const unsigned char* d,
806 using namespace llvm::support;
807 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
808 bool IsInteresting = RawID & 0x01;
810 // Wipe out the "is interesting" bit.
813 // Build the IdentifierInfo and link the identifier ID with it.
814 IdentifierInfo *II = KnownII;
816 II = &Reader.getIdentifierTable().getOwn(k);
819 markIdentifierFromAST(Reader, *II);
820 Reader.markIdentifierUpToDate(II);
822 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
823 if (!IsInteresting) {
824 // For uninteresting identifiers, there's nothing else to do. Just notify
825 // the reader that we've finished loading this identifier.
826 Reader.SetIdentifierInfo(ID, II);
830 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
831 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
832 bool CPlusPlusOperatorKeyword = readBit(Bits);
833 bool HasRevertedTokenIDToIdentifier = readBit(Bits);
834 bool HasRevertedBuiltin = readBit(Bits);
835 bool Poisoned = readBit(Bits);
836 bool ExtensionToken = readBit(Bits);
837 bool HadMacroDefinition = readBit(Bits);
839 assert(Bits == 0 && "Extra bits in the identifier?");
842 // Set or check the various bits in the IdentifierInfo structure.
843 // Token IDs are read-only.
844 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
845 II->revertTokenIDToIdentifier();
847 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
848 else if (HasRevertedBuiltin && II->getBuiltinID()) {
850 assert((II->hasRevertedBuiltin() ||
851 II->getObjCOrBuiltinID() == ObjCOrBuiltinID) &&
852 "Incorrect ObjC keyword or builtin ID");
854 assert(II->isExtensionToken() == ExtensionToken &&
855 "Incorrect extension token flag");
856 (void)ExtensionToken;
858 II->setIsPoisoned(true);
859 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
860 "Incorrect C++ operator keyword flag");
861 (void)CPlusPlusOperatorKeyword;
863 // If this identifier is a macro, deserialize the macro
865 if (HadMacroDefinition) {
866 uint32_t MacroDirectivesOffset =
867 endian::readNext<uint32_t, little, unaligned>(d);
870 Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
873 Reader.SetIdentifierInfo(ID, II);
875 // Read all of the declarations visible at global scope with this
878 SmallVector<uint32_t, 4> DeclIDs;
879 for (; DataLen > 0; DataLen -= 4)
880 DeclIDs.push_back(Reader.getGlobalDeclID(
881 F, endian::readNext<uint32_t, little, unaligned>(d)));
882 Reader.SetGloballyVisibleDecls(II, DeclIDs);
888 DeclarationNameKey::DeclarationNameKey(DeclarationName Name)
889 : Kind(Name.getNameKind()) {
891 case DeclarationName::Identifier:
892 Data = (uint64_t)Name.getAsIdentifierInfo();
894 case DeclarationName::ObjCZeroArgSelector:
895 case DeclarationName::ObjCOneArgSelector:
896 case DeclarationName::ObjCMultiArgSelector:
897 Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
899 case DeclarationName::CXXOperatorName:
900 Data = Name.getCXXOverloadedOperator();
902 case DeclarationName::CXXLiteralOperatorName:
903 Data = (uint64_t)Name.getCXXLiteralIdentifier();
905 case DeclarationName::CXXConstructorName:
906 case DeclarationName::CXXDestructorName:
907 case DeclarationName::CXXConversionFunctionName:
908 case DeclarationName::CXXUsingDirective:
914 unsigned DeclarationNameKey::getHash() const {
915 llvm::FoldingSetNodeID ID;
919 case DeclarationName::Identifier:
920 case DeclarationName::CXXLiteralOperatorName:
921 ID.AddString(((IdentifierInfo*)Data)->getName());
923 case DeclarationName::ObjCZeroArgSelector:
924 case DeclarationName::ObjCOneArgSelector:
925 case DeclarationName::ObjCMultiArgSelector:
926 ID.AddInteger(serialization::ComputeHash(Selector(Data)));
928 case DeclarationName::CXXOperatorName:
929 ID.AddInteger((OverloadedOperatorKind)Data);
931 case DeclarationName::CXXConstructorName:
932 case DeclarationName::CXXDestructorName:
933 case DeclarationName::CXXConversionFunctionName:
934 case DeclarationName::CXXUsingDirective:
938 return ID.ComputeHash();
942 ASTDeclContextNameLookupTrait::ReadFileRef(const unsigned char *&d) {
943 using namespace llvm::support;
944 uint32_t ModuleFileID = endian::readNext<uint32_t, little, unaligned>(d);
945 return Reader.getLocalModuleFile(F, ModuleFileID);
948 std::pair<unsigned, unsigned>
949 ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char *&d) {
950 using namespace llvm::support;
951 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
952 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
953 return std::make_pair(KeyLen, DataLen);
956 ASTDeclContextNameLookupTrait::internal_key_type
957 ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
958 using namespace llvm::support;
960 auto Kind = (DeclarationName::NameKind)*d++;
963 case DeclarationName::Identifier:
964 Data = (uint64_t)Reader.getLocalIdentifier(
965 F, endian::readNext<uint32_t, little, unaligned>(d));
967 case DeclarationName::ObjCZeroArgSelector:
968 case DeclarationName::ObjCOneArgSelector:
969 case DeclarationName::ObjCMultiArgSelector:
971 (uint64_t)Reader.getLocalSelector(
972 F, endian::readNext<uint32_t, little, unaligned>(
973 d)).getAsOpaquePtr();
975 case DeclarationName::CXXOperatorName:
976 Data = *d++; // OverloadedOperatorKind
978 case DeclarationName::CXXLiteralOperatorName:
979 Data = (uint64_t)Reader.getLocalIdentifier(
980 F, endian::readNext<uint32_t, little, unaligned>(d));
982 case DeclarationName::CXXConstructorName:
983 case DeclarationName::CXXDestructorName:
984 case DeclarationName::CXXConversionFunctionName:
985 case DeclarationName::CXXUsingDirective:
990 return DeclarationNameKey(Kind, Data);
993 void ASTDeclContextNameLookupTrait::ReadDataInto(internal_key_type,
994 const unsigned char *d,
996 data_type_builder &Val) {
997 using namespace llvm::support;
998 for (unsigned NumDecls = DataLen / 4; NumDecls; --NumDecls) {
999 uint32_t LocalID = endian::readNext<uint32_t, little, unaligned>(d);
1000 Val.insert(Reader.getGlobalDeclID(F, LocalID));
1004 bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
1005 BitstreamCursor &Cursor,
1008 assert(Offset != 0);
1010 SavedStreamPosition SavedPosition(Cursor);
1011 Cursor.JumpToBit(Offset);
1015 unsigned Code = Cursor.ReadCode();
1016 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
1017 if (RecCode != DECL_CONTEXT_LEXICAL) {
1018 Error("Expected lexical block");
1022 assert(!isa<TranslationUnitDecl>(DC) &&
1023 "expected a TU_UPDATE_LEXICAL record for TU");
1024 // If we are handling a C++ class template instantiation, we can see multiple
1025 // lexical updates for the same record. It's important that we select only one
1026 // of them, so that field numbering works properly. Just pick the first one we
1028 auto &Lex = LexicalDecls[DC];
1030 Lex = std::make_pair(
1031 &M, llvm::makeArrayRef(
1032 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
1036 DC->setHasExternalLexicalStorage(true);
1040 bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M,
1041 BitstreamCursor &Cursor,
1044 assert(Offset != 0);
1046 SavedStreamPosition SavedPosition(Cursor);
1047 Cursor.JumpToBit(Offset);
1051 unsigned Code = Cursor.ReadCode();
1052 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
1053 if (RecCode != DECL_CONTEXT_VISIBLE) {
1054 Error("Expected visible lookup table block");
1058 // We can't safely determine the primary context yet, so delay attaching the
1059 // lookup table until we're done with recursive deserialization.
1060 auto *Data = (const unsigned char*)Blob.data();
1061 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&M, Data});
1065 void ASTReader::Error(StringRef Msg) {
1066 Error(diag::err_fe_pch_malformed, Msg);
1067 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight() &&
1068 !PP.getHeaderSearchInfo().getModuleCachePath().empty()) {
1069 Diag(diag::note_module_cache_path)
1070 << PP.getHeaderSearchInfo().getModuleCachePath();
1074 void ASTReader::Error(unsigned DiagID,
1075 StringRef Arg1, StringRef Arg2) {
1076 if (Diags.isDiagnosticInFlight())
1077 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1079 Diag(DiagID) << Arg1 << Arg2;
1082 //===----------------------------------------------------------------------===//
1083 // Source Manager Deserialization
1084 //===----------------------------------------------------------------------===//
1086 /// \brief Read the line table in the source manager block.
1087 /// \returns true if there was an error.
1088 bool ASTReader::ParseLineTable(ModuleFile &F,
1089 const RecordData &Record) {
1091 LineTableInfo &LineTable = SourceMgr.getLineTable();
1093 // Parse the file names
1094 std::map<int, int> FileIDs;
1095 for (unsigned I = 0; Record[Idx]; ++I) {
1096 // Extract the file name
1097 auto Filename = ReadPath(F, Record, Idx);
1098 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1102 // Parse the line entries
1103 std::vector<LineEntry> Entries;
1104 while (Idx < Record.size()) {
1105 int FID = Record[Idx++];
1106 assert(FID >= 0 && "Serialized line entries for non-local file.");
1107 // Remap FileID from 1-based old view.
1108 FID += F.SLocEntryBaseID - 1;
1110 // Extract the line entries
1111 unsigned NumEntries = Record[Idx++];
1112 assert(NumEntries && "no line entries for file ID");
1114 Entries.reserve(NumEntries);
1115 for (unsigned I = 0; I != NumEntries; ++I) {
1116 unsigned FileOffset = Record[Idx++];
1117 unsigned LineNo = Record[Idx++];
1118 int FilenameID = FileIDs[Record[Idx++]];
1119 SrcMgr::CharacteristicKind FileKind
1120 = (SrcMgr::CharacteristicKind)Record[Idx++];
1121 unsigned IncludeOffset = Record[Idx++];
1122 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1123 FileKind, IncludeOffset));
1125 LineTable.AddEntry(FileID::get(FID), Entries);
1131 /// \brief Read a source manager block
1132 bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1133 using namespace SrcMgr;
1135 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
1137 // Set the source-location entry cursor to the current position in
1138 // the stream. This cursor will be used to read the contents of the
1139 // source manager block initially, and then lazily read
1140 // source-location entries as needed.
1141 SLocEntryCursor = F.Stream;
1143 // The stream itself is going to skip over the source manager block.
1144 if (F.Stream.SkipBlock()) {
1145 Error("malformed block record in AST file");
1149 // Enter the source manager block.
1150 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1151 Error("malformed source manager block record in AST file");
1157 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
1160 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1161 case llvm::BitstreamEntry::Error:
1162 Error("malformed block record in AST file");
1164 case llvm::BitstreamEntry::EndBlock:
1166 case llvm::BitstreamEntry::Record:
1167 // The interesting case.
1174 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
1175 default: // Default behavior: ignore.
1178 case SM_SLOC_FILE_ENTRY:
1179 case SM_SLOC_BUFFER_ENTRY:
1180 case SM_SLOC_EXPANSION_ENTRY:
1181 // Once we hit one of the source location entries, we're done.
1187 /// \brief If a header file is not found at the path that we expect it to be
1188 /// and the PCH file was moved from its original location, try to resolve the
1189 /// file by assuming that header+PCH were moved together and the header is in
1190 /// the same place relative to the PCH.
1192 resolveFileRelativeToOriginalDir(const std::string &Filename,
1193 const std::string &OriginalDir,
1194 const std::string &CurrDir) {
1195 assert(OriginalDir != CurrDir &&
1196 "No point trying to resolve the file if the PCH dir didn't change");
1197 using namespace llvm::sys;
1198 SmallString<128> filePath(Filename);
1199 fs::make_absolute(filePath);
1200 assert(path::is_absolute(OriginalDir));
1201 SmallString<128> currPCHPath(CurrDir);
1203 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1204 fileDirE = path::end(path::parent_path(filePath));
1205 path::const_iterator origDirI = path::begin(OriginalDir),
1206 origDirE = path::end(OriginalDir);
1207 // Skip the common path components from filePath and OriginalDir.
1208 while (fileDirI != fileDirE && origDirI != origDirE &&
1209 *fileDirI == *origDirI) {
1213 for (; origDirI != origDirE; ++origDirI)
1214 path::append(currPCHPath, "..");
1215 path::append(currPCHPath, fileDirI, fileDirE);
1216 path::append(currPCHPath, path::filename(Filename));
1217 return currPCHPath.str();
1220 bool ASTReader::ReadSLocEntry(int ID) {
1224 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1225 Error("source location entry ID out-of-range for AST file");
1229 // Local helper to read the (possibly-compressed) buffer data following the
1231 auto ReadBuffer = [this](
1232 BitstreamCursor &SLocEntryCursor,
1233 StringRef Name) -> std::unique_ptr<llvm::MemoryBuffer> {
1236 unsigned Code = SLocEntryCursor.ReadCode();
1237 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
1239 if (RecCode == SM_SLOC_BUFFER_BLOB_COMPRESSED) {
1240 SmallString<0> Uncompressed;
1241 if (llvm::zlib::uncompress(Blob, Uncompressed, Record[0]) !=
1242 llvm::zlib::StatusOK) {
1243 Error("could not decompress embedded file contents");
1246 return llvm::MemoryBuffer::getMemBufferCopy(Uncompressed, Name);
1247 } else if (RecCode == SM_SLOC_BUFFER_BLOB) {
1248 return llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name, true);
1250 Error("AST record has invalid code");
1255 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1256 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
1257 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
1258 unsigned BaseOffset = F->SLocEntryBaseOffset;
1260 ++NumSLocEntriesRead;
1261 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1262 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1263 Error("incorrectly-formatted source location entry in AST file");
1269 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
1271 Error("incorrectly-formatted source location entry in AST file");
1274 case SM_SLOC_FILE_ENTRY: {
1275 // We will detect whether a file changed and return 'Failure' for it, but
1276 // we will also try to fail gracefully by setting up the SLocEntry.
1277 unsigned InputID = Record[4];
1278 InputFile IF = getInputFile(*F, InputID);
1279 const FileEntry *File = IF.getFile();
1280 bool OverriddenBuffer = IF.isOverridden();
1282 // Note that we only check if a File was returned. If it was out-of-date
1283 // we have complained but we will continue creating a FileID to recover
1288 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1289 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1290 // This is the module's main file.
1291 IncludeLoc = getImportLocation(F);
1293 SrcMgr::CharacteristicKind
1294 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1295 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1296 ID, BaseOffset + Record[0]);
1297 SrcMgr::FileInfo &FileInfo =
1298 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1299 FileInfo.NumCreatedFIDs = Record[5];
1301 FileInfo.setHasLineDirectives();
1303 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1304 unsigned NumFileDecls = Record[7];
1306 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1307 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1311 const SrcMgr::ContentCache *ContentCache
1312 = SourceMgr.getOrCreateContentCache(File,
1313 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1314 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
1315 ContentCache->ContentsEntry == ContentCache->OrigEntry &&
1316 !ContentCache->getRawBuffer()) {
1317 auto Buffer = ReadBuffer(SLocEntryCursor, File->getName());
1320 SourceMgr.overrideFileContents(File, std::move(Buffer));
1326 case SM_SLOC_BUFFER_ENTRY: {
1327 const char *Name = Blob.data();
1328 unsigned Offset = Record[0];
1329 SrcMgr::CharacteristicKind
1330 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1331 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1332 if (IncludeLoc.isInvalid() && F->isModule()) {
1333 IncludeLoc = getImportLocation(F);
1336 auto Buffer = ReadBuffer(SLocEntryCursor, Name);
1339 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
1340 BaseOffset + Offset, IncludeLoc);
1344 case SM_SLOC_EXPANSION_ENTRY: {
1345 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1346 SourceMgr.createExpansionLoc(SpellingLoc,
1347 ReadSourceLocation(*F, Record[2]),
1348 ReadSourceLocation(*F, Record[3]),
1351 BaseOffset + Record[0]);
1359 std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1361 return std::make_pair(SourceLocation(), "");
1363 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1364 Error("source location entry ID out-of-range for AST file");
1365 return std::make_pair(SourceLocation(), "");
1368 // Find which module file this entry lands in.
1369 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
1371 return std::make_pair(SourceLocation(), "");
1373 // FIXME: Can we map this down to a particular submodule? That would be
1375 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
1378 /// \brief Find the location where the module F is imported.
1379 SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1380 if (F->ImportLoc.isValid())
1381 return F->ImportLoc;
1383 // Otherwise we have a PCH. It's considered to be "imported" at the first
1384 // location of its includer.
1385 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
1386 // Main file is the importer.
1387 assert(SourceMgr.getMainFileID().isValid() && "missing main file");
1388 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
1390 return F->ImportedBy[0]->FirstLoc;
1393 /// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1394 /// specified cursor. Read the abbreviations that are at the top of the block
1395 /// and then leave the cursor pointing into the block.
1396 bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
1397 if (Cursor.EnterSubBlock(BlockID))
1401 uint64_t Offset = Cursor.GetCurrentBitNo();
1402 unsigned Code = Cursor.ReadCode();
1404 // We expect all abbrevs to be at the start of the block.
1405 if (Code != llvm::bitc::DEFINE_ABBREV) {
1406 Cursor.JumpToBit(Offset);
1409 Cursor.ReadAbbrevRecord();
1413 Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
1417 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1418 Tok.setLength(Record[Idx++]);
1419 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1420 Tok.setIdentifierInfo(II);
1421 Tok.setKind((tok::TokenKind)Record[Idx++]);
1422 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1426 MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
1427 BitstreamCursor &Stream = F.MacroCursor;
1429 // Keep track of where we are in the stream, then jump back there
1430 // after reading this macro.
1431 SavedStreamPosition SavedPosition(Stream);
1433 Stream.JumpToBit(Offset);
1435 SmallVector<IdentifierInfo*, 16> MacroArgs;
1436 MacroInfo *Macro = nullptr;
1439 // Advance to the next record, but if we get to the end of the block, don't
1440 // pop it (removing all the abbreviations from the cursor) since we want to
1441 // be able to reseek within the block and read entries.
1442 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
1443 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1445 switch (Entry.Kind) {
1446 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1447 case llvm::BitstreamEntry::Error:
1448 Error("malformed block record in AST file");
1450 case llvm::BitstreamEntry::EndBlock:
1452 case llvm::BitstreamEntry::Record:
1453 // The interesting case.
1459 PreprocessorRecordTypes RecType =
1460 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
1462 case PP_MODULE_MACRO:
1463 case PP_MACRO_DIRECTIVE_HISTORY:
1466 case PP_MACRO_OBJECT_LIKE:
1467 case PP_MACRO_FUNCTION_LIKE: {
1468 // If we already have a macro, that means that we've hit the end
1469 // of the definition of the macro we were looking for. We're
1474 unsigned NextIndex = 1; // Skip identifier ID.
1475 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
1476 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
1477 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
1478 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
1479 MI->setIsUsed(Record[NextIndex++]);
1480 MI->setUsedForHeaderGuard(Record[NextIndex++]);
1482 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1483 // Decode function-like macro info.
1484 bool isC99VarArgs = Record[NextIndex++];
1485 bool isGNUVarArgs = Record[NextIndex++];
1486 bool hasCommaPasting = Record[NextIndex++];
1488 unsigned NumArgs = Record[NextIndex++];
1489 for (unsigned i = 0; i != NumArgs; ++i)
1490 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1492 // Install function-like macro info.
1493 MI->setIsFunctionLike();
1494 if (isC99VarArgs) MI->setIsC99Varargs();
1495 if (isGNUVarArgs) MI->setIsGNUVarargs();
1496 if (hasCommaPasting) MI->setHasCommaPasting();
1497 MI->setArgumentList(MacroArgs, PP.getPreprocessorAllocator());
1500 // Remember that we saw this macro last so that we add the tokens that
1501 // form its body to it.
1504 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1505 Record[NextIndex]) {
1506 // We have a macro definition. Register the association
1507 PreprocessedEntityID
1508 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1509 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
1510 PreprocessingRecord::PPEntityID PPID =
1511 PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
1512 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
1513 PPRec.getPreprocessedEntity(PPID));
1515 PPRec.RegisterMacroDefinition(Macro, PPDef);
1523 // If we see a TOKEN before a PP_MACRO_*, then the file is
1524 // erroneous, just pretend we didn't see this.
1528 Token Tok = ReadToken(F, Record, Idx);
1529 Macro->AddTokenToBody(Tok);
1536 PreprocessedEntityID
1537 ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
1538 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1539 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1540 assert(I != M.PreprocessedEntityRemap.end()
1541 && "Invalid index into preprocessed entity index remap");
1543 return LocalID + I->second;
1546 unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1547 return llvm::hash_combine(ikey.Size, ikey.ModTime);
1550 HeaderFileInfoTrait::internal_key_type
1551 HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
1552 internal_key_type ikey = {FE->getSize(),
1553 M.HasTimestamps ? FE->getModificationTime() : 0,
1554 FE->getName(), /*Imported*/ false};
1558 bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
1559 if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime))
1562 if (llvm::sys::path::is_absolute(a.Filename) &&
1563 strcmp(a.Filename, b.Filename) == 0)
1566 // Determine whether the actual files are equivalent.
1567 FileManager &FileMgr = Reader.getFileManager();
1568 auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
1570 return FileMgr.getFile(Key.Filename);
1572 std::string Resolved = Key.Filename;
1573 Reader.ResolveImportedPath(M, Resolved);
1574 return FileMgr.getFile(Resolved);
1577 const FileEntry *FEA = GetFile(a);
1578 const FileEntry *FEB = GetFile(b);
1579 return FEA && FEA == FEB;
1582 std::pair<unsigned, unsigned>
1583 HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
1584 using namespace llvm::support;
1585 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
1586 unsigned DataLen = (unsigned) *d++;
1587 return std::make_pair(KeyLen, DataLen);
1590 HeaderFileInfoTrait::internal_key_type
1591 HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
1592 using namespace llvm::support;
1593 internal_key_type ikey;
1594 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1595 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
1596 ikey.Filename = (const char *)d;
1597 ikey.Imported = true;
1601 HeaderFileInfoTrait::data_type
1602 HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
1604 const unsigned char *End = d + DataLen;
1605 using namespace llvm::support;
1607 unsigned Flags = *d++;
1608 // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
1609 HFI.isImport |= (Flags >> 4) & 0x01;
1610 HFI.isPragmaOnce |= (Flags >> 3) & 0x01;
1611 HFI.DirInfo = (Flags >> 1) & 0x03;
1612 HFI.IndexHeaderMapHeader = Flags & 0x01;
1613 // FIXME: Find a better way to handle this. Maybe just store a
1614 // "has been included" flag?
1615 HFI.NumIncludes = std::max(endian::readNext<uint16_t, little, unaligned>(d),
1617 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1618 M, endian::readNext<uint32_t, little, unaligned>(d));
1619 if (unsigned FrameworkOffset =
1620 endian::readNext<uint32_t, little, unaligned>(d)) {
1621 // The framework offset is 1 greater than the actual offset,
1622 // since 0 is used as an indicator for "no framework name".
1623 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1624 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1627 assert((End - d) % 4 == 0 &&
1628 "Wrong data length in HeaderFileInfo deserialization");
1630 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
1631 auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 3);
1634 // This header is part of a module. Associate it with the module to enable
1635 // implicit module import.
1636 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1637 Module *Mod = Reader.getSubmodule(GlobalSMID);
1638 FileManager &FileMgr = Reader.getFileManager();
1640 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1642 std::string Filename = key.Filename;
1644 Reader.ResolveImportedPath(M, Filename);
1645 // FIXME: This is not always the right filename-as-written, but we're not
1646 // going to use this information to rebuild the module, so it doesn't make
1647 // a lot of difference.
1648 Module::Header H = { key.Filename, FileMgr.getFile(Filename) };
1649 ModMap.addHeader(Mod, H, HeaderRole, /*Imported*/true);
1650 HFI.isModuleHeader |= !(HeaderRole & ModuleMap::TextualHeader);
1653 // This HeaderFileInfo was externally loaded.
1654 HFI.External = true;
1659 void ASTReader::addPendingMacro(IdentifierInfo *II,
1661 uint64_t MacroDirectivesOffset) {
1662 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1663 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
1666 void ASTReader::ReadDefinedMacros() {
1667 // Note that we are loading defined macros.
1668 Deserializing Macros(this);
1670 for (auto &I : llvm::reverse(ModuleMgr)) {
1671 BitstreamCursor &MacroCursor = I->MacroCursor;
1673 // If there was no preprocessor block, skip this file.
1674 if (!MacroCursor.getBitStreamReader())
1677 BitstreamCursor Cursor = MacroCursor;
1678 Cursor.JumpToBit(I->MacroStartOffset);
1682 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1685 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1686 case llvm::BitstreamEntry::Error:
1687 Error("malformed block record in AST file");
1689 case llvm::BitstreamEntry::EndBlock:
1692 case llvm::BitstreamEntry::Record:
1694 switch (Cursor.readRecord(E.ID, Record)) {
1695 default: // Default behavior: ignore.
1698 case PP_MACRO_OBJECT_LIKE:
1699 case PP_MACRO_FUNCTION_LIKE: {
1700 IdentifierInfo *II = getLocalIdentifier(*I, Record[0]);
1701 if (II->isOutOfDate())
1702 updateOutOfDateIdentifier(*II);
1718 /// \brief Visitor class used to look up identifirs in an AST file.
1719 class IdentifierLookupVisitor {
1722 unsigned PriorGeneration;
1723 unsigned &NumIdentifierLookups;
1724 unsigned &NumIdentifierLookupHits;
1725 IdentifierInfo *Found;
1728 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1729 unsigned &NumIdentifierLookups,
1730 unsigned &NumIdentifierLookupHits)
1731 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
1732 PriorGeneration(PriorGeneration),
1733 NumIdentifierLookups(NumIdentifierLookups),
1734 NumIdentifierLookupHits(NumIdentifierLookupHits),
1739 bool operator()(ModuleFile &M) {
1740 // If we've already searched this module file, skip it now.
1741 if (M.Generation <= PriorGeneration)
1744 ASTIdentifierLookupTable *IdTable
1745 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1749 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
1751 ++NumIdentifierLookups;
1752 ASTIdentifierLookupTable::iterator Pos =
1753 IdTable->find_hashed(Name, NameHash, &Trait);
1754 if (Pos == IdTable->end())
1757 // Dereferencing the iterator has the effect of building the
1758 // IdentifierInfo node and populating it with the various
1759 // declarations it needs.
1760 ++NumIdentifierLookupHits;
1765 // \brief Retrieve the identifier info found within the module
1767 IdentifierInfo *getIdentifierInfo() const { return Found; }
1771 void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1772 // Note that we are loading an identifier.
1773 Deserializing AnIdentifier(this);
1775 unsigned PriorGeneration = 0;
1776 if (getContext().getLangOpts().Modules)
1777 PriorGeneration = IdentifierGeneration[&II];
1779 // If there is a global index, look there first to determine which modules
1780 // provably do not have any results for this identifier.
1781 GlobalModuleIndex::HitSet Hits;
1782 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
1783 if (!loadGlobalIndex()) {
1784 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1789 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
1790 NumIdentifierLookups,
1791 NumIdentifierLookupHits);
1792 ModuleMgr.visit(Visitor, HitsPtr);
1793 markIdentifierUpToDate(&II);
1796 void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1800 II->setOutOfDate(false);
1802 // Update the generation for this identifier.
1803 if (getContext().getLangOpts().Modules)
1804 IdentifierGeneration[II] = getGeneration();
1807 void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1808 const PendingMacroInfo &PMInfo) {
1809 ModuleFile &M = *PMInfo.M;
1811 BitstreamCursor &Cursor = M.MacroCursor;
1812 SavedStreamPosition SavedPosition(Cursor);
1813 Cursor.JumpToBit(PMInfo.MacroDirectivesOffset);
1815 struct ModuleMacroRecord {
1816 SubmoduleID SubModID;
1818 SmallVector<SubmoduleID, 8> Overrides;
1820 llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
1822 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
1823 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
1827 llvm::BitstreamEntry Entry =
1828 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1829 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1830 Error("malformed block record in AST file");
1835 switch ((PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
1836 case PP_MACRO_DIRECTIVE_HISTORY:
1839 case PP_MODULE_MACRO: {
1840 ModuleMacros.push_back(ModuleMacroRecord());
1841 auto &Info = ModuleMacros.back();
1842 Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
1843 Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
1844 for (int I = 2, N = Record.size(); I != N; ++I)
1845 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
1850 Error("malformed block record in AST file");
1854 // We found the macro directive history; that's the last record
1859 // Module macros are listed in reverse dependency order.
1861 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
1862 llvm::SmallVector<ModuleMacro*, 8> Overrides;
1863 for (auto &MMR : ModuleMacros) {
1865 for (unsigned ModID : MMR.Overrides) {
1866 Module *Mod = getSubmodule(ModID);
1867 auto *Macro = PP.getModuleMacro(Mod, II);
1868 assert(Macro && "missing definition for overridden macro");
1869 Overrides.push_back(Macro);
1872 bool Inserted = false;
1873 Module *Owner = getSubmodule(MMR.SubModID);
1874 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
1878 // Don't read the directive history for a module; we don't have anywhere
1883 // Deserialize the macro directives history in reverse source-order.
1884 MacroDirective *Latest = nullptr, *Earliest = nullptr;
1885 unsigned Idx = 0, N = Record.size();
1887 MacroDirective *MD = nullptr;
1888 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
1889 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1891 case MacroDirective::MD_Define: {
1892 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
1893 MD = PP.AllocateDefMacroDirective(MI, Loc);
1896 case MacroDirective::MD_Undefine: {
1897 MD = PP.AllocateUndefMacroDirective(Loc);
1900 case MacroDirective::MD_Visibility:
1901 bool isPublic = Record[Idx++];
1902 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1909 Earliest->setPrevious(MD);
1914 PP.setLoadedMacroDirective(II, Latest);
1917 ASTReader::InputFileInfo
1918 ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
1919 // Go find this input file.
1920 BitstreamCursor &Cursor = F.InputFilesCursor;
1921 SavedStreamPosition SavedPosition(Cursor);
1922 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1924 unsigned Code = Cursor.ReadCode();
1928 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
1929 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
1930 "invalid record type for input file");
1933 assert(Record[0] == ID && "Bogus stored ID or offset");
1935 R.StoredSize = static_cast<off_t>(Record[1]);
1936 R.StoredTime = static_cast<time_t>(Record[2]);
1937 R.Overridden = static_cast<bool>(Record[3]);
1938 R.Transient = static_cast<bool>(Record[4]);
1940 ResolveImportedPath(F, R.Filename);
1944 InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
1945 // If this ID is bogus, just return an empty input file.
1946 if (ID == 0 || ID > F.InputFilesLoaded.size())
1949 // If we've already loaded this input file, return it.
1950 if (F.InputFilesLoaded[ID-1].getFile())
1951 return F.InputFilesLoaded[ID-1];
1953 if (F.InputFilesLoaded[ID-1].isNotFound())
1956 // Go find this input file.
1957 BitstreamCursor &Cursor = F.InputFilesCursor;
1958 SavedStreamPosition SavedPosition(Cursor);
1959 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1961 InputFileInfo FI = readInputFileInfo(F, ID);
1962 off_t StoredSize = FI.StoredSize;
1963 time_t StoredTime = FI.StoredTime;
1964 bool Overridden = FI.Overridden;
1965 bool Transient = FI.Transient;
1966 StringRef Filename = FI.Filename;
1968 const FileEntry *File = FileMgr.getFile(Filename, /*OpenFile=*/false);
1970 // If we didn't find the file, resolve it relative to the
1971 // original directory from which this AST file was created.
1972 if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() &&
1973 F.OriginalDir != CurrentDir) {
1974 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
1977 if (!Resolved.empty())
1978 File = FileMgr.getFile(Resolved);
1981 // For an overridden file, create a virtual file with the stored
1983 if ((Overridden || Transient) && File == nullptr)
1984 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
1986 if (File == nullptr) {
1988 std::string ErrorStr = "could not find file '";
1989 ErrorStr += Filename;
1990 ErrorStr += "' referenced by AST file '";
1991 ErrorStr += F.FileName;
1993 Error(ErrorStr.c_str());
1995 // Record that we didn't find the file.
1996 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
2000 // Check if there was a request to override the contents of the file
2001 // that was part of the precompiled header. Overridding such a file
2002 // can lead to problems when lexing using the source locations from the
2004 SourceManager &SM = getSourceManager();
2005 // FIXME: Reject if the overrides are different.
2006 if ((!Overridden && !Transient) && SM.isFileOverridden(File)) {
2008 Error(diag::err_fe_pch_file_overridden, Filename);
2009 // After emitting the diagnostic, recover by disabling the override so
2010 // that the original file will be used.
2012 // FIXME: This recovery is just as broken as the original state; there may
2013 // be another precompiled module that's using the overridden contents, or
2014 // we might be half way through parsing it. Instead, we should treat the
2015 // overridden contents as belonging to a separate FileEntry.
2016 SM.disableFileContentsOverride(File);
2017 // The FileEntry is a virtual file entry with the size of the contents
2018 // that would override the original contents. Set it to the original's
2020 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
2021 StoredSize, StoredTime);
2024 bool IsOutOfDate = false;
2026 // For an overridden file, there is nothing to validate.
2027 if (!Overridden && //
2028 (StoredSize != File->getSize() ||
2029 (StoredTime && StoredTime != File->getModificationTime() &&
2033 // Build a list of the PCH imports that got us here (in reverse).
2034 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2035 while (ImportStack.back()->ImportedBy.size() > 0)
2036 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
2038 // The top-level PCH is stale.
2039 StringRef TopLevelPCHName(ImportStack.back()->FileName);
2040 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
2042 // Print the import stack.
2043 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2044 Diag(diag::note_pch_required_by)
2045 << Filename << ImportStack[0]->FileName;
2046 for (unsigned I = 1; I < ImportStack.size(); ++I)
2047 Diag(diag::note_pch_required_by)
2048 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
2051 if (!Diags.isDiagnosticInFlight())
2052 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
2057 // FIXME: If the file is overridden and we've already opened it,
2058 // issue an error (or split it into a separate FileEntry).
2060 InputFile IF = InputFile(File, Overridden || Transient, IsOutOfDate);
2062 // Note that we've loaded this input file.
2063 F.InputFilesLoaded[ID-1] = IF;
2067 /// \brief If we are loading a relocatable PCH or module file, and the filename
2068 /// is not an absolute path, add the system or module root to the beginning of
2070 void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2071 // Resolve relative to the base directory, if we have one.
2072 if (!M.BaseDirectory.empty())
2073 return ResolveImportedPath(Filename, M.BaseDirectory);
2076 void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
2077 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2080 SmallString<128> Buffer;
2081 llvm::sys::path::append(Buffer, Prefix, Filename);
2082 Filename.assign(Buffer.begin(), Buffer.end());
2085 static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
2087 case ASTReader::Failure: return true;
2088 case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
2089 case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
2090 case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch);
2091 case ASTReader::ConfigurationMismatch:
2092 return !(Caps & ASTReader::ARR_ConfigurationMismatch);
2093 case ASTReader::HadErrors: return true;
2094 case ASTReader::Success: return false;
2097 llvm_unreachable("unknown ASTReadResult");
2100 ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(
2101 BitstreamCursor &Stream, unsigned ClientLoadCapabilities,
2102 bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener,
2103 std::string &SuggestedPredefines, bool ValidateDiagnosticOptions) {
2104 if (Stream.EnterSubBlock(OPTIONS_BLOCK_ID))
2107 // Read all of the records in the options block.
2109 ASTReadResult Result = Success;
2111 llvm::BitstreamEntry Entry = Stream.advance();
2113 switch (Entry.Kind) {
2114 case llvm::BitstreamEntry::Error:
2115 case llvm::BitstreamEntry::SubBlock:
2118 case llvm::BitstreamEntry::EndBlock:
2121 case llvm::BitstreamEntry::Record:
2122 // The interesting case.
2126 // Read and process a record.
2128 switch ((OptionsRecordTypes)Stream.readRecord(Entry.ID, Record)) {
2129 case LANGUAGE_OPTIONS: {
2130 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2131 if (ParseLanguageOptions(Record, Complain, Listener,
2132 AllowCompatibleConfigurationMismatch))
2133 Result = ConfigurationMismatch;
2137 case TARGET_OPTIONS: {
2138 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2139 if (ParseTargetOptions(Record, Complain, Listener,
2140 AllowCompatibleConfigurationMismatch))
2141 Result = ConfigurationMismatch;
2145 case DIAGNOSTIC_OPTIONS: {
2146 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
2147 if (ValidateDiagnosticOptions &&
2148 !AllowCompatibleConfigurationMismatch &&
2149 ParseDiagnosticOptions(Record, Complain, Listener))
2154 case FILE_SYSTEM_OPTIONS: {
2155 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2156 if (!AllowCompatibleConfigurationMismatch &&
2157 ParseFileSystemOptions(Record, Complain, Listener))
2158 Result = ConfigurationMismatch;
2162 case HEADER_SEARCH_OPTIONS: {
2163 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2164 if (!AllowCompatibleConfigurationMismatch &&
2165 ParseHeaderSearchOptions(Record, Complain, Listener))
2166 Result = ConfigurationMismatch;
2170 case PREPROCESSOR_OPTIONS:
2171 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2172 if (!AllowCompatibleConfigurationMismatch &&
2173 ParsePreprocessorOptions(Record, Complain, Listener,
2174 SuggestedPredefines))
2175 Result = ConfigurationMismatch;
2181 ASTReader::ASTReadResult
2182 ASTReader::ReadControlBlock(ModuleFile &F,
2183 SmallVectorImpl<ImportedModule> &Loaded,
2184 const ModuleFile *ImportedBy,
2185 unsigned ClientLoadCapabilities) {
2186 BitstreamCursor &Stream = F.Stream;
2187 ASTReadResult Result = Success;
2189 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2190 Error("malformed block record in AST file");
2194 // Read all of the records and blocks in the control block.
2196 unsigned NumInputs = 0;
2197 unsigned NumUserInputs = 0;
2199 llvm::BitstreamEntry Entry = Stream.advance();
2201 switch (Entry.Kind) {
2202 case llvm::BitstreamEntry::Error:
2203 Error("malformed block record in AST file");
2205 case llvm::BitstreamEntry::EndBlock: {
2206 // Validate input files.
2207 const HeaderSearchOptions &HSOpts =
2208 PP.getHeaderSearchInfo().getHeaderSearchOpts();
2210 // All user input files reside at the index range [0, NumUserInputs), and
2211 // system input files reside at [NumUserInputs, NumInputs). For explicitly
2212 // loaded module files, ignore missing inputs.
2213 if (!DisableValidation && F.Kind != MK_ExplicitModule &&
2214 F.Kind != MK_PrebuiltModule) {
2215 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
2217 // If we are reading a module, we will create a verification timestamp,
2218 // so we verify all input files. Otherwise, verify only user input
2221 unsigned N = NumUserInputs;
2222 if (ValidateSystemInputs ||
2223 (HSOpts.ModulesValidateOncePerBuildSession &&
2224 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
2225 F.Kind == MK_ImplicitModule))
2228 for (unsigned I = 0; I < N; ++I) {
2229 InputFile IF = getInputFile(F, I+1, Complain);
2230 if (!IF.getFile() || IF.isOutOfDate())
2236 Listener->visitModuleFile(F.FileName, F.Kind);
2238 if (Listener && Listener->needsInputFileVisitation()) {
2239 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2241 for (unsigned I = 0; I < N; ++I) {
2242 bool IsSystem = I >= NumUserInputs;
2243 InputFileInfo FI = readInputFileInfo(F, I+1);
2244 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden,
2245 F.Kind == MK_ExplicitModule ||
2246 F.Kind == MK_PrebuiltModule);
2253 case llvm::BitstreamEntry::SubBlock:
2255 case INPUT_FILES_BLOCK_ID:
2256 F.InputFilesCursor = Stream;
2257 if (Stream.SkipBlock() || // Skip with the main cursor
2258 // Read the abbreviations
2259 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2260 Error("malformed block record in AST file");
2265 case OPTIONS_BLOCK_ID:
2266 // If we're reading the first module for this group, check its options
2267 // are compatible with ours. For modules it imports, no further checking
2268 // is required, because we checked them when we built it.
2269 if (Listener && !ImportedBy) {
2270 // Should we allow the configuration of the module file to differ from
2271 // the configuration of the current translation unit in a compatible
2274 // FIXME: Allow this for files explicitly specified with -include-pch.
2275 bool AllowCompatibleConfigurationMismatch =
2276 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
2277 const HeaderSearchOptions &HSOpts =
2278 PP.getHeaderSearchInfo().getHeaderSearchOpts();
2280 Result = ReadOptionsBlock(Stream, ClientLoadCapabilities,
2281 AllowCompatibleConfigurationMismatch,
2282 *Listener, SuggestedPredefines,
2283 HSOpts.ModulesValidateDiagnosticOptions);
2284 if (Result == Failure) {
2285 Error("malformed block record in AST file");
2289 if (DisableValidation ||
2290 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
2293 // If we can't load the module, exit early since we likely
2294 // will rebuild the module anyway. The stream may be in the
2295 // middle of a block.
2296 if (Result != Success)
2298 } else if (Stream.SkipBlock()) {
2299 Error("malformed block record in AST file");
2305 if (Stream.SkipBlock()) {
2306 Error("malformed block record in AST file");
2312 case llvm::BitstreamEntry::Record:
2313 // The interesting case.
2317 // Read and process a record.
2320 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
2322 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2323 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
2324 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2325 : diag::err_pch_version_too_new);
2326 return VersionMismatch;
2329 bool hasErrors = Record[6];
2330 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2331 Diag(diag::err_pch_with_compiler_errors);
2335 Diags.ErrorOccurred = true;
2336 Diags.UncompilableErrorOccurred = true;
2337 Diags.UnrecoverableErrorOccurred = true;
2340 F.RelocatablePCH = Record[4];
2341 // Relative paths in a relocatable PCH are relative to our sysroot.
2342 if (F.RelocatablePCH)
2343 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
2345 F.HasTimestamps = Record[5];
2347 const std::string &CurBranch = getClangFullRepositoryVersion();
2348 StringRef ASTBranch = Blob;
2349 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2350 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
2351 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
2352 return VersionMismatch;
2358 assert((!F.Signature || F.Signature == Record[0]) && "signature changed");
2359 F.Signature = Record[0];
2363 // Load each of the imported PCH files.
2364 unsigned Idx = 0, N = Record.size();
2366 // Read information about the AST file.
2367 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2368 // The import location will be the local one for now; we will adjust
2369 // all import locations of module imports after the global source
2370 // location info are setup, in ReadAST.
2371 SourceLocation ImportLoc =
2372 ReadUntranslatedSourceLocation(Record[Idx++]);
2373 off_t StoredSize = (off_t)Record[Idx++];
2374 time_t StoredModTime = (time_t)Record[Idx++];
2375 ASTFileSignature StoredSignature = Record[Idx++];
2376 auto ImportedFile = ReadPath(F, Record, Idx);
2378 // If our client can't cope with us being out of date, we can't cope with
2379 // our dependency being missing.
2380 unsigned Capabilities = ClientLoadCapabilities;
2381 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2382 Capabilities &= ~ARR_Missing;
2384 // Load the AST file.
2385 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
2386 Loaded, StoredSize, StoredModTime,
2387 StoredSignature, Capabilities);
2389 // If we diagnosed a problem, produce a backtrace.
2390 if (isDiagnosedResult(Result, Capabilities))
2391 Diag(diag::note_module_file_imported_by)
2392 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
2395 case Failure: return Failure;
2396 // If we have to ignore the dependency, we'll have to ignore this too.
2398 case OutOfDate: return OutOfDate;
2399 case VersionMismatch: return VersionMismatch;
2400 case ConfigurationMismatch: return ConfigurationMismatch;
2401 case HadErrors: return HadErrors;
2402 case Success: break;
2409 F.OriginalSourceFileID = FileID::get(Record[0]);
2410 F.ActualOriginalSourceFileName = Blob;
2411 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
2412 ResolveImportedPath(F, F.OriginalSourceFileName);
2415 case ORIGINAL_FILE_ID:
2416 F.OriginalSourceFileID = FileID::get(Record[0]);
2419 case ORIGINAL_PCH_DIR:
2420 F.OriginalDir = Blob;
2424 F.ModuleName = Blob;
2426 Listener->ReadModuleName(F.ModuleName);
2429 case MODULE_DIRECTORY: {
2430 assert(!F.ModuleName.empty() &&
2431 "MODULE_DIRECTORY found before MODULE_NAME");
2432 // If we've already loaded a module map file covering this module, we may
2433 // have a better path for it (relative to the current build).
2434 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2435 if (M && M->Directory) {
2436 // If we're implicitly loading a module, the base directory can't
2437 // change between the build and use.
2438 if (F.Kind != MK_ExplicitModule && F.Kind != MK_PrebuiltModule) {
2439 const DirectoryEntry *BuildDir =
2440 PP.getFileManager().getDirectory(Blob);
2441 if (!BuildDir || BuildDir != M->Directory) {
2442 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2443 Diag(diag::err_imported_module_relocated)
2444 << F.ModuleName << Blob << M->Directory->getName();
2448 F.BaseDirectory = M->Directory->getName();
2450 F.BaseDirectory = Blob;
2455 case MODULE_MAP_FILE:
2456 if (ASTReadResult Result =
2457 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2461 case INPUT_FILE_OFFSETS:
2462 NumInputs = Record[0];
2463 NumUserInputs = Record[1];
2464 F.InputFileOffsets =
2465 (const llvm::support::unaligned_uint64_t *)Blob.data();
2466 F.InputFilesLoaded.resize(NumInputs);
2472 ASTReader::ASTReadResult
2473 ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
2474 BitstreamCursor &Stream = F.Stream;
2476 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2477 Error("malformed block record in AST file");
2481 // Read all of the records and blocks for the AST file.
2484 llvm::BitstreamEntry Entry = Stream.advance();
2486 switch (Entry.Kind) {
2487 case llvm::BitstreamEntry::Error:
2488 Error("error at end of module block in AST file");
2490 case llvm::BitstreamEntry::EndBlock: {
2491 // Outside of C++, we do not store a lookup map for the translation unit.
2492 // Instead, mark it as needing a lookup map to be built if this module
2493 // contains any declarations lexically within it (which it always does!).
2494 // This usually has no cost, since we very rarely need the lookup map for
2495 // the translation unit outside C++.
2496 DeclContext *DC = Context.getTranslationUnitDecl();
2497 if (DC->hasExternalLexicalStorage() &&
2498 !getContext().getLangOpts().CPlusPlus)
2499 DC->setMustBuildLookupTable();
2503 case llvm::BitstreamEntry::SubBlock:
2505 case DECLTYPES_BLOCK_ID:
2506 // We lazily load the decls block, but we want to set up the
2507 // DeclsCursor cursor to point into it. Clone our current bitcode
2508 // cursor to it, enter the block and read the abbrevs in that block.
2509 // With the main cursor, we just skip over it.
2510 F.DeclsCursor = Stream;
2511 if (Stream.SkipBlock() || // Skip with the main cursor.
2512 // Read the abbrevs.
2513 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2514 Error("malformed block record in AST file");
2519 case PREPROCESSOR_BLOCK_ID:
2520 F.MacroCursor = Stream;
2521 if (!PP.getExternalSource())
2522 PP.setExternalSource(this);
2524 if (Stream.SkipBlock() ||
2525 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2526 Error("malformed block record in AST file");
2529 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2532 case PREPROCESSOR_DETAIL_BLOCK_ID:
2533 F.PreprocessorDetailCursor = Stream;
2534 if (Stream.SkipBlock() ||
2535 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
2536 PREPROCESSOR_DETAIL_BLOCK_ID)) {
2537 Error("malformed preprocessor detail record in AST file");
2540 F.PreprocessorDetailStartOffset
2541 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2543 if (!PP.getPreprocessingRecord())
2544 PP.createPreprocessingRecord();
2545 if (!PP.getPreprocessingRecord()->getExternalSource())
2546 PP.getPreprocessingRecord()->SetExternalSource(*this);
2549 case SOURCE_MANAGER_BLOCK_ID:
2550 if (ReadSourceManagerBlock(F))
2554 case SUBMODULE_BLOCK_ID:
2555 if (ASTReadResult Result = ReadSubmoduleBlock(F, ClientLoadCapabilities))
2559 case COMMENTS_BLOCK_ID: {
2560 BitstreamCursor C = Stream;
2561 if (Stream.SkipBlock() ||
2562 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2563 Error("malformed comments block in AST file");
2566 CommentsCursors.push_back(std::make_pair(C, &F));
2571 if (Stream.SkipBlock()) {
2572 Error("malformed block record in AST file");
2579 case llvm::BitstreamEntry::Record:
2580 // The interesting case.
2584 // Read and process a record.
2587 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
2588 default: // Default behavior: ignore.
2592 if (F.LocalNumTypes != 0) {
2593 Error("duplicate TYPE_OFFSET record in AST file");
2596 F.TypeOffsets = (const uint32_t *)Blob.data();
2597 F.LocalNumTypes = Record[0];
2598 unsigned LocalBaseTypeIndex = Record[1];
2599 F.BaseTypeIndex = getTotalNumTypes();
2601 if (F.LocalNumTypes > 0) {
2602 // Introduce the global -> local mapping for types within this module.
2603 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2605 // Introduce the local -> global mapping for types within this module.
2606 F.TypeRemap.insertOrReplace(
2607 std::make_pair(LocalBaseTypeIndex,
2608 F.BaseTypeIndex - LocalBaseTypeIndex));
2610 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
2616 if (F.LocalNumDecls != 0) {
2617 Error("duplicate DECL_OFFSET record in AST file");
2620 F.DeclOffsets = (const DeclOffset *)Blob.data();
2621 F.LocalNumDecls = Record[0];
2622 unsigned LocalBaseDeclID = Record[1];
2623 F.BaseDeclID = getTotalNumDecls();
2625 if (F.LocalNumDecls > 0) {
2626 // Introduce the global -> local mapping for declarations within this
2628 GlobalDeclMap.insert(
2629 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2631 // Introduce the local -> global mapping for declarations within this
2633 F.DeclRemap.insertOrReplace(
2634 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2636 // Introduce the global -> local mapping for declarations within this
2638 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
2640 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2645 case TU_UPDATE_LEXICAL: {
2646 DeclContext *TU = Context.getTranslationUnitDecl();
2647 LexicalContents Contents(
2648 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
2650 static_cast<unsigned int>(Blob.size() / 4));
2651 TULexicalDecls.push_back(std::make_pair(&F, Contents));
2652 TU->setHasExternalLexicalStorage(true);
2656 case UPDATE_VISIBLE: {
2658 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
2659 auto *Data = (const unsigned char*)Blob.data();
2660 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&F, Data});
2661 // If we've already loaded the decl, perform the updates when we finish
2662 // loading this block.
2663 if (Decl *D = GetExistingDecl(ID))
2664 PendingUpdateRecords.push_back(std::make_pair(ID, D));
2668 case IDENTIFIER_TABLE:
2669 F.IdentifierTableData = Blob.data();
2671 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2672 (const unsigned char *)F.IdentifierTableData + Record[0],
2673 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2674 (const unsigned char *)F.IdentifierTableData,
2675 ASTIdentifierLookupTrait(*this, F));
2677 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2681 case IDENTIFIER_OFFSET: {
2682 if (F.LocalNumIdentifiers != 0) {
2683 Error("duplicate IDENTIFIER_OFFSET record in AST file");
2686 F.IdentifierOffsets = (const uint32_t *)Blob.data();
2687 F.LocalNumIdentifiers = Record[0];
2688 unsigned LocalBaseIdentifierID = Record[1];
2689 F.BaseIdentifierID = getTotalNumIdentifiers();
2691 if (F.LocalNumIdentifiers > 0) {
2692 // Introduce the global -> local mapping for identifiers within this
2694 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2697 // Introduce the local -> global mapping for identifiers within this
2699 F.IdentifierRemap.insertOrReplace(
2700 std::make_pair(LocalBaseIdentifierID,
2701 F.BaseIdentifierID - LocalBaseIdentifierID));
2703 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2704 + F.LocalNumIdentifiers);
2709 case INTERESTING_IDENTIFIERS:
2710 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
2713 case EAGERLY_DESERIALIZED_DECLS:
2714 // FIXME: Skip reading this record if our ASTConsumer doesn't care
2715 // about "interesting" decls (for instance, if we're building a module).
2716 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2717 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
2721 if (SpecialTypes.empty()) {
2722 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2723 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2727 if (SpecialTypes.size() != Record.size()) {
2728 Error("invalid special-types record");
2732 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2733 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2734 if (!SpecialTypes[I])
2735 SpecialTypes[I] = ID;
2736 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2742 TotalNumStatements += Record[0];
2743 TotalNumMacros += Record[1];
2744 TotalLexicalDeclContexts += Record[2];
2745 TotalVisibleDeclContexts += Record[3];
2748 case UNUSED_FILESCOPED_DECLS:
2749 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2750 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2753 case DELEGATING_CTORS:
2754 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2755 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2758 case WEAK_UNDECLARED_IDENTIFIERS:
2759 if (Record.size() % 4 != 0) {
2760 Error("invalid weak identifiers record");
2764 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2765 // files. This isn't the way to do it :)
2766 WeakUndeclaredIdentifiers.clear();
2768 // Translate the weak, undeclared identifiers into global IDs.
2769 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2770 WeakUndeclaredIdentifiers.push_back(
2771 getGlobalIdentifierID(F, Record[I++]));
2772 WeakUndeclaredIdentifiers.push_back(
2773 getGlobalIdentifierID(F, Record[I++]));
2774 WeakUndeclaredIdentifiers.push_back(
2775 ReadSourceLocation(F, Record, I).getRawEncoding());
2776 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2780 case SELECTOR_OFFSETS: {
2781 F.SelectorOffsets = (const uint32_t *)Blob.data();
2782 F.LocalNumSelectors = Record[0];
2783 unsigned LocalBaseSelectorID = Record[1];
2784 F.BaseSelectorID = getTotalNumSelectors();
2786 if (F.LocalNumSelectors > 0) {
2787 // Introduce the global -> local mapping for selectors within this
2789 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2791 // Introduce the local -> global mapping for selectors within this
2793 F.SelectorRemap.insertOrReplace(
2794 std::make_pair(LocalBaseSelectorID,
2795 F.BaseSelectorID - LocalBaseSelectorID));
2797 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
2803 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
2805 F.SelectorLookupTable
2806 = ASTSelectorLookupTable::Create(
2807 F.SelectorLookupTableData + Record[0],
2808 F.SelectorLookupTableData,
2809 ASTSelectorLookupTrait(*this, F));
2810 TotalNumMethodPoolEntries += Record[1];
2813 case REFERENCED_SELECTOR_POOL:
2814 if (!Record.empty()) {
2815 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2816 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2818 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2824 case PP_COUNTER_VALUE:
2825 if (!Record.empty() && Listener)
2826 Listener->ReadCounter(F, Record[0]);
2829 case FILE_SORTED_DECLS:
2830 F.FileSortedDecls = (const DeclID *)Blob.data();
2831 F.NumFileSortedDecls = Record[0];
2834 case SOURCE_LOCATION_OFFSETS: {
2835 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
2836 F.LocalNumSLocEntries = Record[0];
2837 unsigned SLocSpaceSize = Record[1];
2838 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
2839 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
2841 if (!F.SLocEntryBaseID) {
2842 Error("ran out of source locations");
2845 // Make our entry in the range map. BaseID is negative and growing, so
2846 // we invert it. Because we invert it, though, we need the other end of
2848 unsigned RangeStart =
2849 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2850 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2851 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2853 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2854 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2855 GlobalSLocOffsetMap.insert(
2856 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2857 - SLocSpaceSize,&F));
2859 // Initialize the remapping table.
2860 // Invalid stays invalid.
2861 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
2862 // This module. Base was 2 when being compiled.
2863 F.SLocRemap.insertOrReplace(std::make_pair(2U,
2864 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2866 TotalNumSLocEntries += F.LocalNumSLocEntries;
2870 case MODULE_OFFSET_MAP: {
2871 // Additional remapping information.
2872 const unsigned char *Data = (const unsigned char*)Blob.data();
2873 const unsigned char *DataEnd = Data + Blob.size();
2875 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
2876 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
2877 F.SLocRemap.insert(std::make_pair(0U, 0));
2878 F.SLocRemap.insert(std::make_pair(2U, 1));
2881 // Continuous range maps we may be updating in our module.
2882 typedef ContinuousRangeMap<uint32_t, int, 2>::Builder
2884 RemapBuilder SLocRemap(F.SLocRemap);
2885 RemapBuilder IdentifierRemap(F.IdentifierRemap);
2886 RemapBuilder MacroRemap(F.MacroRemap);
2887 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2888 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
2889 RemapBuilder SelectorRemap(F.SelectorRemap);
2890 RemapBuilder DeclRemap(F.DeclRemap);
2891 RemapBuilder TypeRemap(F.TypeRemap);
2893 while (Data < DataEnd) {
2894 using namespace llvm::support;
2895 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
2896 StringRef Name = StringRef((const char*)Data, Len);
2898 ModuleFile *OM = ModuleMgr.lookup(Name);
2900 Error("SourceLocation remap refers to unknown module");
2904 uint32_t SLocOffset =
2905 endian::readNext<uint32_t, little, unaligned>(Data);
2906 uint32_t IdentifierIDOffset =
2907 endian::readNext<uint32_t, little, unaligned>(Data);
2908 uint32_t MacroIDOffset =
2909 endian::readNext<uint32_t, little, unaligned>(Data);
2910 uint32_t PreprocessedEntityIDOffset =
2911 endian::readNext<uint32_t, little, unaligned>(Data);
2912 uint32_t SubmoduleIDOffset =
2913 endian::readNext<uint32_t, little, unaligned>(Data);
2914 uint32_t SelectorIDOffset =
2915 endian::readNext<uint32_t, little, unaligned>(Data);
2916 uint32_t DeclIDOffset =
2917 endian::readNext<uint32_t, little, unaligned>(Data);
2918 uint32_t TypeIndexOffset =
2919 endian::readNext<uint32_t, little, unaligned>(Data);
2921 uint32_t None = std::numeric_limits<uint32_t>::max();
2923 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
2924 RemapBuilder &Remap) {
2926 Remap.insert(std::make_pair(Offset,
2927 static_cast<int>(BaseOffset - Offset)));
2929 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
2930 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
2931 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
2932 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
2933 PreprocessedEntityRemap);
2934 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
2935 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
2936 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
2937 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
2939 // Global -> local mappings.
2940 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
2945 case SOURCE_MANAGER_LINE_TABLE:
2946 if (ParseLineTable(F, Record))
2950 case SOURCE_LOCATION_PRELOADS: {
2951 // Need to transform from the local view (1-based IDs) to the global view,
2952 // which is based off F.SLocEntryBaseID.
2953 if (!F.PreloadSLocEntries.empty()) {
2954 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
2958 F.PreloadSLocEntries.swap(Record);
2962 case EXT_VECTOR_DECLS:
2963 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2964 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
2968 if (Record.size() % 3 != 0) {
2969 Error("Invalid VTABLE_USES record");
2973 // Later tables overwrite earlier ones.
2974 // FIXME: Modules will have some trouble with this. This is clearly not
2975 // the right way to do this.
2978 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
2979 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
2980 VTableUses.push_back(
2981 ReadSourceLocation(F, Record, Idx).getRawEncoding());
2982 VTableUses.push_back(Record[Idx++]);
2986 case PENDING_IMPLICIT_INSTANTIATIONS:
2987 if (PendingInstantiations.size() % 2 != 0) {
2988 Error("Invalid existing PendingInstantiations");
2992 if (Record.size() % 2 != 0) {
2993 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
2997 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
2998 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
2999 PendingInstantiations.push_back(
3000 ReadSourceLocation(F, Record, I).getRawEncoding());
3004 case SEMA_DECL_REFS:
3005 if (Record.size() != 2) {
3006 Error("Invalid SEMA_DECL_REFS block");
3009 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3010 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3013 case PPD_ENTITIES_OFFSETS: {
3014 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3015 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3016 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
3018 unsigned LocalBasePreprocessedEntityID = Record[0];
3020 unsigned StartingID;
3021 if (!PP.getPreprocessingRecord())
3022 PP.createPreprocessingRecord();
3023 if (!PP.getPreprocessingRecord()->getExternalSource())
3024 PP.getPreprocessingRecord()->SetExternalSource(*this);
3026 = PP.getPreprocessingRecord()
3027 ->allocateLoadedEntities(F.NumPreprocessedEntities);
3028 F.BasePreprocessedEntityID = StartingID;
3030 if (F.NumPreprocessedEntities > 0) {
3031 // Introduce the global -> local mapping for preprocessed entities in
3033 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
3035 // Introduce the local -> global mapping for preprocessed entities in
3037 F.PreprocessedEntityRemap.insertOrReplace(
3038 std::make_pair(LocalBasePreprocessedEntityID,
3039 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3045 case DECL_UPDATE_OFFSETS: {
3046 if (Record.size() % 2 != 0) {
3047 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
3050 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3051 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3052 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3054 // If we've already loaded the decl, perform the updates when we finish
3055 // loading this block.
3056 if (Decl *D = GetExistingDecl(ID))
3057 PendingUpdateRecords.push_back(std::make_pair(ID, D));
3062 case OBJC_CATEGORIES_MAP: {
3063 if (F.LocalNumObjCCategoriesInMap != 0) {
3064 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
3068 F.LocalNumObjCCategoriesInMap = Record[0];
3069 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
3073 case OBJC_CATEGORIES:
3074 F.ObjCCategories.swap(Record);
3077 case DIAG_PRAGMA_MAPPINGS:
3078 if (F.PragmaDiagMappings.empty())
3079 F.PragmaDiagMappings.swap(Record);
3081 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
3082 Record.begin(), Record.end());
3085 case CUDA_SPECIAL_DECL_REFS:
3086 // Later tables overwrite earlier ones.
3087 // FIXME: Modules will have trouble with this.
3088 CUDASpecialDeclRefs.clear();
3089 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3090 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3093 case HEADER_SEARCH_TABLE: {
3094 F.HeaderFileInfoTableData = Blob.data();
3095 F.LocalNumHeaderFileInfos = Record[1];
3097 F.HeaderFileInfoTable
3098 = HeaderFileInfoLookupTable::Create(
3099 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3100 (const unsigned char *)F.HeaderFileInfoTableData,
3101 HeaderFileInfoTrait(*this, F,
3102 &PP.getHeaderSearchInfo(),
3103 Blob.data() + Record[2]));
3105 PP.getHeaderSearchInfo().SetExternalSource(this);
3106 if (!PP.getHeaderSearchInfo().getExternalLookup())
3107 PP.getHeaderSearchInfo().SetExternalLookup(this);
3112 case FP_PRAGMA_OPTIONS:
3113 // Later tables overwrite earlier ones.
3114 FPPragmaOptions.swap(Record);
3117 case OPENCL_EXTENSIONS:
3118 // Later tables overwrite earlier ones.
3119 OpenCLExtensions.swap(Record);
3122 case TENTATIVE_DEFINITIONS:
3123 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3124 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3127 case KNOWN_NAMESPACES:
3128 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3129 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3132 case UNDEFINED_BUT_USED:
3133 if (UndefinedButUsed.size() % 2 != 0) {
3134 Error("Invalid existing UndefinedButUsed");
3138 if (Record.size() % 2 != 0) {
3139 Error("invalid undefined-but-used record");
3142 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3143 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3144 UndefinedButUsed.push_back(
3145 ReadSourceLocation(F, Record, I).getRawEncoding());
3148 case DELETE_EXPRS_TO_ANALYZE:
3149 for (unsigned I = 0, N = Record.size(); I != N;) {
3150 DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
3151 const uint64_t Count = Record[I++];
3152 DelayedDeleteExprs.push_back(Count);
3153 for (uint64_t C = 0; C < Count; ++C) {
3154 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3155 bool IsArrayForm = Record[I++] == 1;
3156 DelayedDeleteExprs.push_back(IsArrayForm);
3161 case IMPORTED_MODULES: {
3162 if (!F.isModule()) {
3163 // If we aren't loading a module (which has its own exports), make
3164 // all of the imported modules visible.
3165 // FIXME: Deal with macros-only imports.
3166 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3167 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3168 SourceLocation Loc = ReadSourceLocation(F, Record, I);
3170 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
3176 case MACRO_OFFSET: {
3177 if (F.LocalNumMacros != 0) {
3178 Error("duplicate MACRO_OFFSET record in AST file");
3181 F.MacroOffsets = (const uint32_t *)Blob.data();
3182 F.LocalNumMacros = Record[0];
3183 unsigned LocalBaseMacroID = Record[1];
3184 F.BaseMacroID = getTotalNumMacros();
3186 if (F.LocalNumMacros > 0) {
3187 // Introduce the global -> local mapping for macros within this module.
3188 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3190 // Introduce the local -> global mapping for macros within this module.
3191 F.MacroRemap.insertOrReplace(
3192 std::make_pair(LocalBaseMacroID,
3193 F.BaseMacroID - LocalBaseMacroID));
3195 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
3200 case LATE_PARSED_TEMPLATE: {
3201 LateParsedTemplates.append(Record.begin(), Record.end());
3205 case OPTIMIZE_PRAGMA_OPTIONS:
3206 if (Record.size() != 1) {
3207 Error("invalid pragma optimize record");
3210 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3213 case MSSTRUCT_PRAGMA_OPTIONS:
3214 if (Record.size() != 1) {
3215 Error("invalid pragma ms_struct record");
3218 PragmaMSStructState = Record[0];
3221 case POINTERS_TO_MEMBERS_PRAGMA_OPTIONS:
3222 if (Record.size() != 2) {
3223 Error("invalid pragma ms_struct record");
3226 PragmaMSPointersToMembersState = Record[0];
3227 PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]);
3230 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3231 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3232 UnusedLocalTypedefNameCandidates.push_back(
3233 getGlobalDeclID(F, Record[I]));
3239 ASTReader::ASTReadResult
3240 ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3241 const ModuleFile *ImportedBy,
3242 unsigned ClientLoadCapabilities) {
3244 F.ModuleMapPath = ReadPath(F, Record, Idx);
3246 if (F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule) {
3247 // For an explicitly-loaded module, we don't care whether the original
3248 // module map file exists or matches.
3252 // Try to resolve ModuleName in the current header search context and
3253 // verify that it is found in the same module map file as we saved. If the
3254 // top-level AST file is a main file, skip this check because there is no
3255 // usable header search context.
3256 assert(!F.ModuleName.empty() &&
3257 "MODULE_NAME should come before MODULE_MAP_FILE");
3258 if (F.Kind == MK_ImplicitModule &&
3259 (*ModuleMgr.begin())->Kind != MK_MainFile) {
3260 // An implicitly-loaded module file should have its module listed in some
3261 // module map file that we've already loaded.
3262 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
3263 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3264 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3266 assert(ImportedBy && "top-level import should be verified");
3267 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) {
3268 if (auto *ASTFE = M ? M->getASTFile() : nullptr)
3269 // This module was defined by an imported (explicit) module.
3270 Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
3271 << ASTFE->getName();
3273 // This module was built with a different module map.
3274 Diag(diag::err_imported_module_not_found)
3275 << F.ModuleName << F.FileName << ImportedBy->FileName
3281 assert(M->Name == F.ModuleName && "found module with different name");
3283 // Check the primary module map file.
3284 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
3285 if (StoredModMap == nullptr || StoredModMap != ModMap) {
3286 assert(ModMap && "found module is missing module map file");
3287 assert(ImportedBy && "top-level import should be verified");
3288 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3289 Diag(diag::err_imported_module_modmap_changed)
3290 << F.ModuleName << ImportedBy->FileName
3291 << ModMap->getName() << F.ModuleMapPath;
3295 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3296 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3297 // FIXME: we should use input files rather than storing names.
3298 std::string Filename = ReadPath(F, Record, Idx);
3299 const FileEntry *F =
3300 FileMgr.getFile(Filename, false, false);
3302 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3303 Error("could not find file '" + Filename +"' referenced by AST file");
3306 AdditionalStoredMaps.insert(F);
3309 // Check any additional module map files (e.g. module.private.modulemap)
3310 // that are not in the pcm.
3311 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
3312 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
3313 // Remove files that match
3314 // Note: SmallPtrSet::erase is really remove
3315 if (!AdditionalStoredMaps.erase(ModMap)) {
3316 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3317 Diag(diag::err_module_different_modmap)
3318 << F.ModuleName << /*new*/0 << ModMap->getName();
3324 // Check any additional module map files that are in the pcm, but not
3325 // found in header search. Cases that match are already removed.
3326 for (const FileEntry *ModMap : AdditionalStoredMaps) {
3327 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3328 Diag(diag::err_module_different_modmap)
3329 << F.ModuleName << /*not new*/1 << ModMap->getName();
3335 Listener->ReadModuleMapFile(F.ModuleMapPath);
3340 /// \brief Move the given method to the back of the global list of methods.
3341 static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3342 // Find the entry for this selector in the method pool.
3343 Sema::GlobalMethodPool::iterator Known
3344 = S.MethodPool.find(Method->getSelector());
3345 if (Known == S.MethodPool.end())
3348 // Retrieve the appropriate method list.
3349 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3350 : Known->second.second;
3352 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
3354 if (List->getMethod() == Method) {
3362 if (List->getNext())
3363 List->setMethod(List->getNext()->getMethod());
3365 List->setMethod(Method);
3369 void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
3370 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
3371 for (Decl *D : Names) {
3372 bool wasHidden = D->Hidden;
3375 if (wasHidden && SemaObj) {
3376 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3377 moveMethodToBackOfGlobalList(*SemaObj, Method);
3383 void ASTReader::makeModuleVisible(Module *Mod,
3384 Module::NameVisibilityKind NameVisibility,
3385 SourceLocation ImportLoc) {
3386 llvm::SmallPtrSet<Module *, 4> Visited;
3387 SmallVector<Module *, 4> Stack;
3388 Stack.push_back(Mod);
3389 while (!Stack.empty()) {
3390 Mod = Stack.pop_back_val();
3392 if (NameVisibility <= Mod->NameVisibility) {
3393 // This module already has this level of visibility (or greater), so
3394 // there is nothing more to do.
3398 if (!Mod->isAvailable()) {
3399 // Modules that aren't available cannot be made visible.
3403 // Update the module's name visibility.
3404 Mod->NameVisibility = NameVisibility;
3406 // If we've already deserialized any names from this module,
3407 // mark them as visible.
3408 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3409 if (Hidden != HiddenNamesMap.end()) {
3410 auto HiddenNames = std::move(*Hidden);
3411 HiddenNamesMap.erase(Hidden);
3412 makeNamesVisible(HiddenNames.second, HiddenNames.first);
3413 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3414 "making names visible added hidden names");
3417 // Push any exported modules onto the stack to be marked as visible.
3418 SmallVector<Module *, 16> Exports;
3419 Mod->getExportedModules(Exports);
3420 for (SmallVectorImpl<Module *>::iterator
3421 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3422 Module *Exported = *I;
3423 if (Visited.insert(Exported).second)
3424 Stack.push_back(Exported);
3429 bool ASTReader::loadGlobalIndex() {
3433 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3434 !Context.getLangOpts().Modules)
3437 // Try to load the global index.
3438 TriedLoadingGlobalIndex = true;
3439 StringRef ModuleCachePath
3440 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3441 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
3442 = GlobalModuleIndex::readIndex(ModuleCachePath);
3446 GlobalIndex.reset(Result.first);
3447 ModuleMgr.setGlobalIndex(GlobalIndex.get());
3451 bool ASTReader::isGlobalIndexUnavailable() const {
3452 return Context.getLangOpts().Modules && UseGlobalIndex &&
3453 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3456 static void updateModuleTimestamp(ModuleFile &MF) {
3457 // Overwrite the timestamp file contents so that file's mtime changes.
3458 std::string TimestampFilename = MF.getTimestampFilename();
3460 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3463 OS << "Timestamp file\n";
3466 /// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3467 /// cursor into the start of the given block ID, returning false on success and
3468 /// true on failure.
3469 static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
3471 llvm::BitstreamEntry Entry = Cursor.advance();
3472 switch (Entry.Kind) {
3473 case llvm::BitstreamEntry::Error:
3474 case llvm::BitstreamEntry::EndBlock:
3477 case llvm::BitstreamEntry::Record:
3478 // Ignore top-level records.
3479 Cursor.skipRecord(Entry.ID);
3482 case llvm::BitstreamEntry::SubBlock:
3483 if (Entry.ID == BlockID) {
3484 if (Cursor.EnterSubBlock(BlockID))
3490 if (Cursor.SkipBlock())
3496 ASTReader::ASTReadResult ASTReader::ReadAST(StringRef FileName,
3498 SourceLocation ImportLoc,
3499 unsigned ClientLoadCapabilities) {
3500 llvm::SaveAndRestore<SourceLocation>
3501 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3503 // Defer any pending actions until we get to the end of reading the AST file.
3504 Deserializing AnASTFile(this);
3506 // Bump the generation number.
3507 unsigned PreviousGeneration = incrementGeneration(Context);
3509 unsigned NumModules = ModuleMgr.size();
3510 SmallVector<ImportedModule, 4> Loaded;
3511 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
3512 /*ImportedBy=*/nullptr, Loaded,
3514 ClientLoadCapabilities)) {
3518 case VersionMismatch:
3519 case ConfigurationMismatch:
3521 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3522 for (const ImportedModule &IM : Loaded)
3523 LoadedSet.insert(IM.Mod);
3525 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
3527 Context.getLangOpts().Modules
3528 ? &PP.getHeaderSearchInfo().getModuleMap()
3531 // If we find that any modules are unusable, the global index is going
3532 // to be out-of-date. Just remove it.
3533 GlobalIndex.reset();
3534 ModuleMgr.setGlobalIndex(nullptr);
3541 // Here comes stuff that we only do once the entire chain is loaded.
3543 // Load the AST blocks of all of the modules that we loaded.
3544 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3545 MEnd = Loaded.end();
3547 ModuleFile &F = *M->Mod;
3549 // Read the AST block.
3550 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3553 // Read the extension blocks.
3554 while (!SkipCursorToBlock(F.Stream, EXTENSION_BLOCK_ID)) {
3555 if (ASTReadResult Result = ReadExtensionBlock(F))
3559 // Once read, set the ModuleFile bit base offset and update the size in
3560 // bits of all files we've seen.
3561 F.GlobalBitOffset = TotalModulesSizeInBits;
3562 TotalModulesSizeInBits += F.SizeInBits;
3563 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3565 // Preload SLocEntries.
3566 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3567 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3568 // Load it through the SourceManager and don't call ReadSLocEntry()
3569 // directly because the entry may have already been loaded in which case
3570 // calling ReadSLocEntry() directly would trigger an assertion in
3572 SourceMgr.getLoadedSLocEntryByID(Index);
3575 // Preload all the pending interesting identifiers by marking them out of
3577 for (auto Offset : F.PreloadIdentifierOffsets) {
3578 const unsigned char *Data = reinterpret_cast<const unsigned char *>(
3579 F.IdentifierTableData + Offset);
3581 ASTIdentifierLookupTrait Trait(*this, F);
3582 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
3583 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
3584 auto &II = PP.getIdentifierTable().getOwn(Key);
3585 II.setOutOfDate(true);
3587 // Mark this identifier as being from an AST file so that we can track
3588 // whether we need to serialize it.
3589 markIdentifierFromAST(*this, II);
3591 // Associate the ID with the identifier so that the writer can reuse it.
3592 auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
3593 SetIdentifierInfo(ID, &II);
3597 // Setup the import locations and notify the module manager that we've
3598 // committed to these module files.
3599 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3600 MEnd = Loaded.end();
3602 ModuleFile &F = *M->Mod;
3604 ModuleMgr.moduleFileAccepted(&F);
3606 // Set the import location.
3607 F.DirectImportLoc = ImportLoc;
3608 // FIXME: We assume that locations from PCH / preamble do not need
3611 F.ImportLoc = M->ImportLoc;
3613 F.ImportLoc = TranslateSourceLocation(*M->ImportedBy, M->ImportLoc);
3616 if (!Context.getLangOpts().CPlusPlus ||
3617 (Type != MK_ImplicitModule && Type != MK_ExplicitModule &&
3618 Type != MK_PrebuiltModule)) {
3619 // Mark all of the identifiers in the identifier table as being out of date,
3620 // so that various accessors know to check the loaded modules when the
3621 // identifier is used.
3623 // For C++ modules, we don't need information on many identifiers (just
3624 // those that provide macros or are poisoned), so we mark all of
3625 // the interesting ones via PreloadIdentifierOffsets.
3626 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3627 IdEnd = PP.getIdentifierTable().end();
3629 Id->second->setOutOfDate(true);
3631 // Mark selectors as out of date.
3632 for (auto Sel : SelectorGeneration)
3633 SelectorOutOfDate[Sel.first] = true;
3635 // Resolve any unresolved module exports.
3636 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3637 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
3638 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3639 Module *ResolvedMod = getSubmodule(GlobalID);
3641 switch (Unresolved.Kind) {
3642 case UnresolvedModuleRef::Conflict:
3644 Module::Conflict Conflict;
3645 Conflict.Other = ResolvedMod;
3646 Conflict.Message = Unresolved.String.str();
3647 Unresolved.Mod->Conflicts.push_back(Conflict);
3651 case UnresolvedModuleRef::Import:
3653 Unresolved.Mod->Imports.insert(ResolvedMod);
3656 case UnresolvedModuleRef::Export:
3657 if (ResolvedMod || Unresolved.IsWildcard)
3658 Unresolved.Mod->Exports.push_back(
3659 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3663 UnresolvedModuleRefs.clear();
3665 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3666 // Might be unnecessary as use declarations are only used to build the
3669 InitializeContext();
3674 if (DeserializationListener)
3675 DeserializationListener->ReaderInitialized(this);
3677 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
3678 if (PrimaryModule.OriginalSourceFileID.isValid()) {
3679 PrimaryModule.OriginalSourceFileID
3680 = FileID::get(PrimaryModule.SLocEntryBaseID
3681 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3683 // If this AST file is a precompiled preamble, then set the
3684 // preamble file ID of the source manager to the file source file
3685 // from which the preamble was built.
3686 if (Type == MK_Preamble) {
3687 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3688 } else if (Type == MK_MainFile) {
3689 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3693 // For any Objective-C class definitions we have already loaded, make sure
3694 // that we load any additional categories.
3695 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3696 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3697 ObjCClassesLoaded[I],
3698 PreviousGeneration);
3701 if (PP.getHeaderSearchInfo()
3702 .getHeaderSearchOpts()
3703 .ModulesValidateOncePerBuildSession) {
3704 // Now we are certain that the module and all modules it depends on are
3705 // up to date. Create or update timestamp files for modules that are
3706 // located in the module cache (not for PCH files that could be anywhere
3707 // in the filesystem).
3708 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3709 ImportedModule &M = Loaded[I];
3710 if (M.Mod->Kind == MK_ImplicitModule) {
3711 updateModuleTimestamp(*M.Mod);
3719 static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile);
3721 /// \brief Whether \p Stream starts with the AST/PCH file magic number 'CPCH'.
3722 static bool startsWithASTFileMagic(BitstreamCursor &Stream) {
3723 return Stream.Read(8) == 'C' &&
3724 Stream.Read(8) == 'P' &&
3725 Stream.Read(8) == 'C' &&
3726 Stream.Read(8) == 'H';
3729 static unsigned moduleKindForDiagnostic(ModuleKind Kind) {
3733 case MK_ImplicitModule:
3734 case MK_ExplicitModule:
3735 case MK_PrebuiltModule:
3739 return 2; // main source file
3741 llvm_unreachable("unknown module kind");
3744 ASTReader::ASTReadResult
3745 ASTReader::ReadASTCore(StringRef FileName,
3747 SourceLocation ImportLoc,
3748 ModuleFile *ImportedBy,
3749 SmallVectorImpl<ImportedModule> &Loaded,
3750 off_t ExpectedSize, time_t ExpectedModTime,
3751 ASTFileSignature ExpectedSignature,
3752 unsigned ClientLoadCapabilities) {
3754 std::string ErrorStr;
3755 ModuleManager::AddModuleResult AddResult
3756 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
3757 getGeneration(), ExpectedSize, ExpectedModTime,
3758 ExpectedSignature, readASTFileSignature,
3761 switch (AddResult) {
3762 case ModuleManager::AlreadyLoaded:
3765 case ModuleManager::NewlyLoaded:
3766 // Load module file below.
3769 case ModuleManager::Missing:
3770 // The module file was missing; if the client can handle that, return
3772 if (ClientLoadCapabilities & ARR_Missing)
3775 // Otherwise, return an error.
3776 Diag(diag::err_module_file_not_found) << moduleKindForDiagnostic(Type)
3777 << FileName << !ErrorStr.empty()
3781 case ModuleManager::OutOfDate:
3782 // We couldn't load the module file because it is out-of-date. If the
3783 // client can handle out-of-date, return it.
3784 if (ClientLoadCapabilities & ARR_OutOfDate)
3787 // Otherwise, return an error.
3788 Diag(diag::err_module_file_out_of_date) << moduleKindForDiagnostic(Type)
3789 << FileName << !ErrorStr.empty()
3794 assert(M && "Missing module file");
3796 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3798 if (FileName != "-") {
3799 CurrentDir = llvm::sys::path::parent_path(FileName);
3800 if (CurrentDir.empty()) CurrentDir = ".";
3804 BitstreamCursor &Stream = F.Stream;
3805 PCHContainerRdr.ExtractPCH(F.Buffer->getMemBufferRef(), F.StreamFile);
3806 Stream.init(&F.StreamFile);
3807 F.SizeInBits = F.Buffer->getBufferSize() * 8;
3809 // Sniff for the signature.
3810 if (!startsWithASTFileMagic(Stream)) {
3811 Diag(diag::err_module_file_invalid) << moduleKindForDiagnostic(Type)
3816 // This is used for compatibility with older PCH formats.
3817 bool HaveReadControlBlock = false;
3819 llvm::BitstreamEntry Entry = Stream.advance();
3821 switch (Entry.Kind) {
3822 case llvm::BitstreamEntry::Error:
3823 case llvm::BitstreamEntry::Record:
3824 case llvm::BitstreamEntry::EndBlock:
3825 Error("invalid record at top-level of AST file");
3828 case llvm::BitstreamEntry::SubBlock:
3833 case CONTROL_BLOCK_ID:
3834 HaveReadControlBlock = true;
3835 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
3837 // Check that we didn't try to load a non-module AST file as a module.
3839 // FIXME: Should we also perform the converse check? Loading a module as
3840 // a PCH file sort of works, but it's a bit wonky.
3841 if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule ||
3842 Type == MK_PrebuiltModule) &&
3843 F.ModuleName.empty()) {
3844 auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
3845 if (Result != OutOfDate ||
3846 (ClientLoadCapabilities & ARR_OutOfDate) == 0)
3847 Diag(diag::err_module_file_not_module) << FileName;
3852 case Failure: return Failure;
3853 case Missing: return Missing;
3854 case OutOfDate: return OutOfDate;
3855 case VersionMismatch: return VersionMismatch;
3856 case ConfigurationMismatch: return ConfigurationMismatch;
3857 case HadErrors: return HadErrors;
3862 if (!HaveReadControlBlock) {
3863 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
3864 Diag(diag::err_pch_version_too_old);
3865 return VersionMismatch;
3868 // Record that we've loaded this module.
3869 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3873 if (Stream.SkipBlock()) {
3874 Error("malformed block record in AST file");
3884 /// Parse a record and blob containing module file extension metadata.
3885 static bool parseModuleFileExtensionMetadata(
3886 const SmallVectorImpl<uint64_t> &Record,
3888 ModuleFileExtensionMetadata &Metadata) {
3889 if (Record.size() < 4) return true;
3891 Metadata.MajorVersion = Record[0];
3892 Metadata.MinorVersion = Record[1];
3894 unsigned BlockNameLen = Record[2];
3895 unsigned UserInfoLen = Record[3];
3897 if (BlockNameLen + UserInfoLen > Blob.size()) return true;
3899 Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
3900 Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,
3901 Blob.data() + BlockNameLen + UserInfoLen);
3905 ASTReader::ASTReadResult ASTReader::ReadExtensionBlock(ModuleFile &F) {
3906 BitstreamCursor &Stream = F.Stream;
3910 llvm::BitstreamEntry Entry = Stream.advance();
3911 switch (Entry.Kind) {
3912 case llvm::BitstreamEntry::SubBlock:
3913 if (Stream.SkipBlock())
3918 case llvm::BitstreamEntry::EndBlock:
3921 case llvm::BitstreamEntry::Error:
3924 case llvm::BitstreamEntry::Record:
3930 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
3932 case EXTENSION_METADATA: {
3933 ModuleFileExtensionMetadata Metadata;
3934 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
3937 // Find a module file extension with this block name.
3938 auto Known = ModuleFileExtensions.find(Metadata.BlockName);
3939 if (Known == ModuleFileExtensions.end()) break;
3942 if (auto Reader = Known->second->createExtensionReader(Metadata, *this,
3944 F.ExtensionReaders.push_back(std::move(Reader));
3955 void ASTReader::InitializeContext() {
3956 // If there's a listener, notify them that we "read" the translation unit.
3957 if (DeserializationListener)
3958 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3959 Context.getTranslationUnitDecl());
3961 // FIXME: Find a better way to deal with collisions between these
3962 // built-in types. Right now, we just ignore the problem.
3964 // Load the special types.
3965 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3966 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3967 if (!Context.CFConstantStringTypeDecl)
3968 Context.setCFConstantStringType(GetType(String));
3971 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3972 QualType FileType = GetType(File);
3973 if (FileType.isNull()) {
3974 Error("FILE type is NULL");
3978 if (!Context.FILEDecl) {
3979 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3980 Context.setFILEDecl(Typedef->getDecl());
3982 const TagType *Tag = FileType->getAs<TagType>();
3984 Error("Invalid FILE type in AST file");
3987 Context.setFILEDecl(Tag->getDecl());
3992 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
3993 QualType Jmp_bufType = GetType(Jmp_buf);
3994 if (Jmp_bufType.isNull()) {
3995 Error("jmp_buf type is NULL");
3999 if (!Context.jmp_bufDecl) {
4000 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
4001 Context.setjmp_bufDecl(Typedef->getDecl());
4003 const TagType *Tag = Jmp_bufType->getAs<TagType>();
4005 Error("Invalid jmp_buf type in AST file");
4008 Context.setjmp_bufDecl(Tag->getDecl());
4013 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
4014 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
4015 if (Sigjmp_bufType.isNull()) {
4016 Error("sigjmp_buf type is NULL");
4020 if (!Context.sigjmp_bufDecl) {
4021 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
4022 Context.setsigjmp_bufDecl(Typedef->getDecl());
4024 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
4025 assert(Tag && "Invalid sigjmp_buf type in AST file");
4026 Context.setsigjmp_bufDecl(Tag->getDecl());
4031 if (unsigned ObjCIdRedef
4032 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
4033 if (Context.ObjCIdRedefinitionType.isNull())
4034 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
4037 if (unsigned ObjCClassRedef
4038 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
4039 if (Context.ObjCClassRedefinitionType.isNull())
4040 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
4043 if (unsigned ObjCSelRedef
4044 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
4045 if (Context.ObjCSelRedefinitionType.isNull())
4046 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
4049 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
4050 QualType Ucontext_tType = GetType(Ucontext_t);
4051 if (Ucontext_tType.isNull()) {
4052 Error("ucontext_t type is NULL");
4056 if (!Context.ucontext_tDecl) {
4057 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
4058 Context.setucontext_tDecl(Typedef->getDecl());
4060 const TagType *Tag = Ucontext_tType->getAs<TagType>();
4061 assert(Tag && "Invalid ucontext_t type in AST file");
4062 Context.setucontext_tDecl(Tag->getDecl());
4068 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
4070 // If there were any CUDA special declarations, deserialize them.
4071 if (!CUDASpecialDeclRefs.empty()) {
4072 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
4073 Context.setcudaConfigureCallDecl(
4074 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
4077 // Re-export any modules that were imported by a non-module AST file.
4078 // FIXME: This does not make macro-only imports visible again.
4079 for (auto &Import : ImportedModules) {
4080 if (Module *Imported = getSubmodule(Import.ID)) {
4081 makeModuleVisible(Imported, Module::AllVisible,
4082 /*ImportLoc=*/Import.ImportLoc);
4083 if (Import.ImportLoc.isValid())
4084 PP.makeModuleVisible(Imported, Import.ImportLoc);
4085 // FIXME: should we tell Sema to make the module visible too?
4088 ImportedModules.clear();
4091 void ASTReader::finalizeForWriting() {
4092 // Nothing to do for now.
4095 /// \brief Reads and return the signature record from \p StreamFile's control
4096 /// block, or else returns 0.
4097 static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile){
4098 BitstreamCursor Stream(StreamFile);
4099 if (!startsWithASTFileMagic(Stream))
4102 // Scan for the CONTROL_BLOCK_ID block.
4103 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
4106 // Scan for SIGNATURE inside the control block.
4107 ASTReader::RecordData Record;
4109 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4110 if (Entry.Kind == llvm::BitstreamEntry::EndBlock ||
4111 Entry.Kind != llvm::BitstreamEntry::Record)
4116 if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
4121 /// \brief Retrieve the name of the original source file name
4122 /// directly from the AST file, without actually loading the AST
4124 std::string ASTReader::getOriginalSourceFile(
4125 const std::string &ASTFileName, FileManager &FileMgr,
4126 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
4127 // Open the AST file.
4128 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
4130 Diags.Report(diag::err_fe_unable_to_read_pch_file)
4131 << ASTFileName << Buffer.getError().message();
4132 return std::string();
4135 // Initialize the stream
4136 llvm::BitstreamReader StreamFile;
4137 PCHContainerRdr.ExtractPCH((*Buffer)->getMemBufferRef(), StreamFile);
4138 BitstreamCursor Stream(StreamFile);
4140 // Sniff for the signature.
4141 if (!startsWithASTFileMagic(Stream)) {
4142 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
4143 return std::string();
4146 // Scan for the CONTROL_BLOCK_ID block.
4147 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
4148 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4149 return std::string();
4152 // Scan for ORIGINAL_FILE inside the control block.
4155 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4156 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4157 return std::string();
4159 if (Entry.Kind != llvm::BitstreamEntry::Record) {
4160 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4161 return std::string();
4166 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
4172 class SimplePCHValidator : public ASTReaderListener {
4173 const LangOptions &ExistingLangOpts;
4174 const TargetOptions &ExistingTargetOpts;
4175 const PreprocessorOptions &ExistingPPOpts;
4176 std::string ExistingModuleCachePath;
4177 FileManager &FileMgr;
4180 SimplePCHValidator(const LangOptions &ExistingLangOpts,
4181 const TargetOptions &ExistingTargetOpts,
4182 const PreprocessorOptions &ExistingPPOpts,
4183 StringRef ExistingModuleCachePath,
4184 FileManager &FileMgr)
4185 : ExistingLangOpts(ExistingLangOpts),
4186 ExistingTargetOpts(ExistingTargetOpts),
4187 ExistingPPOpts(ExistingPPOpts),
4188 ExistingModuleCachePath(ExistingModuleCachePath),
4193 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
4194 bool AllowCompatibleDifferences) override {
4195 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
4196 AllowCompatibleDifferences);
4198 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
4199 bool AllowCompatibleDifferences) override {
4200 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
4201 AllowCompatibleDifferences);
4203 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
4204 StringRef SpecificModuleCachePath,
4205 bool Complain) override {
4206 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4207 ExistingModuleCachePath,
4208 nullptr, ExistingLangOpts);
4210 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
4212 std::string &SuggestedPredefines) override {
4213 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
4214 SuggestedPredefines, ExistingLangOpts);
4219 bool ASTReader::readASTFileControlBlock(
4220 StringRef Filename, FileManager &FileMgr,
4221 const PCHContainerReader &PCHContainerRdr,
4222 bool FindModuleFileExtensions,
4223 ASTReaderListener &Listener, bool ValidateDiagnosticOptions) {
4224 // Open the AST file.
4225 // FIXME: This allows use of the VFS; we do not allow use of the
4226 // VFS when actually loading a module.
4227 auto Buffer = FileMgr.getBufferForFile(Filename);
4232 // Initialize the stream
4233 llvm::BitstreamReader StreamFile;
4234 PCHContainerRdr.ExtractPCH((*Buffer)->getMemBufferRef(), StreamFile);
4235 BitstreamCursor Stream(StreamFile);
4237 // Sniff for the signature.
4238 if (!startsWithASTFileMagic(Stream))
4241 // Scan for the CONTROL_BLOCK_ID block.
4242 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
4245 bool NeedsInputFiles = Listener.needsInputFileVisitation();
4246 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
4247 bool NeedsImports = Listener.needsImportVisitation();
4248 BitstreamCursor InputFilesCursor;
4251 std::string ModuleDir;
4252 bool DoneWithControlBlock = false;
4253 while (!DoneWithControlBlock) {
4254 llvm::BitstreamEntry Entry = Stream.advance();
4256 switch (Entry.Kind) {
4257 case llvm::BitstreamEntry::SubBlock: {
4259 case OPTIONS_BLOCK_ID: {
4260 std::string IgnoredSuggestedPredefines;
4261 if (ReadOptionsBlock(Stream, ARR_ConfigurationMismatch | ARR_OutOfDate,
4262 /*AllowCompatibleConfigurationMismatch*/ false,
4263 Listener, IgnoredSuggestedPredefines,
4264 ValidateDiagnosticOptions) != Success)
4269 case INPUT_FILES_BLOCK_ID:
4270 InputFilesCursor = Stream;
4271 if (Stream.SkipBlock() ||
4273 ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID)))
4278 if (Stream.SkipBlock())
4286 case llvm::BitstreamEntry::EndBlock:
4287 DoneWithControlBlock = true;
4290 case llvm::BitstreamEntry::Error:
4293 case llvm::BitstreamEntry::Record:
4297 if (DoneWithControlBlock) break;
4301 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4302 switch ((ControlRecordTypes)RecCode) {
4304 if (Record[0] != VERSION_MAJOR)
4307 if (Listener.ReadFullVersionInformation(Blob))
4313 Listener.ReadModuleName(Blob);
4315 case MODULE_DIRECTORY:
4318 case MODULE_MAP_FILE: {
4320 auto Path = ReadString(Record, Idx);
4321 ResolveImportedPath(Path, ModuleDir);
4322 Listener.ReadModuleMapFile(Path);
4325 case INPUT_FILE_OFFSETS: {
4326 if (!NeedsInputFiles)
4329 unsigned NumInputFiles = Record[0];
4330 unsigned NumUserFiles = Record[1];
4331 const uint64_t *InputFileOffs = (const uint64_t *)Blob.data();
4332 for (unsigned I = 0; I != NumInputFiles; ++I) {
4333 // Go find this input file.
4334 bool isSystemFile = I >= NumUserFiles;
4336 if (isSystemFile && !NeedsSystemInputFiles)
4337 break; // the rest are system input files
4339 BitstreamCursor &Cursor = InputFilesCursor;
4340 SavedStreamPosition SavedPosition(Cursor);
4341 Cursor.JumpToBit(InputFileOffs[I]);
4343 unsigned Code = Cursor.ReadCode();
4346 bool shouldContinue = false;
4347 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4349 bool Overridden = static_cast<bool>(Record[3]);
4350 std::string Filename = Blob;
4351 ResolveImportedPath(Filename, ModuleDir);
4352 shouldContinue = Listener.visitInputFile(
4353 Filename, isSystemFile, Overridden, /*IsExplicitModule*/false);
4356 if (!shouldContinue)
4366 unsigned Idx = 0, N = Record.size();
4368 // Read information about the AST file.
4369 Idx += 5; // ImportLoc, Size, ModTime, Signature
4370 std::string Filename = ReadString(Record, Idx);
4371 ResolveImportedPath(Filename, ModuleDir);
4372 Listener.visitImport(Filename);
4378 // No other validation to perform.
4383 // Look for module file extension blocks, if requested.
4384 if (FindModuleFileExtensions) {
4385 while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {
4386 bool DoneWithExtensionBlock = false;
4387 while (!DoneWithExtensionBlock) {
4388 llvm::BitstreamEntry Entry = Stream.advance();
4390 switch (Entry.Kind) {
4391 case llvm::BitstreamEntry::SubBlock:
4392 if (Stream.SkipBlock())
4397 case llvm::BitstreamEntry::EndBlock:
4398 DoneWithExtensionBlock = true;
4401 case llvm::BitstreamEntry::Error:
4404 case llvm::BitstreamEntry::Record:
4410 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4412 case EXTENSION_METADATA: {
4413 ModuleFileExtensionMetadata Metadata;
4414 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
4417 Listener.readModuleFileExtension(Metadata);
4428 bool ASTReader::isAcceptableASTFile(
4429 StringRef Filename, FileManager &FileMgr,
4430 const PCHContainerReader &PCHContainerRdr, const LangOptions &LangOpts,
4431 const TargetOptions &TargetOpts, const PreprocessorOptions &PPOpts,
4432 std::string ExistingModuleCachePath) {
4433 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
4434 ExistingModuleCachePath, FileMgr);
4435 return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr,
4436 /*FindModuleFileExtensions=*/false,
4438 /*ValidateDiagnosticOptions=*/true);
4441 ASTReader::ASTReadResult
4442 ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
4443 // Enter the submodule block.
4444 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4445 Error("malformed submodule block record in AST file");
4449 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4451 Module *CurrentModule = nullptr;
4454 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
4456 switch (Entry.Kind) {
4457 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4458 case llvm::BitstreamEntry::Error:
4459 Error("malformed block record in AST file");
4461 case llvm::BitstreamEntry::EndBlock:
4463 case llvm::BitstreamEntry::Record:
4464 // The interesting case.
4471 auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
4473 if ((Kind == SUBMODULE_METADATA) != First) {
4474 Error("submodule metadata record should be at beginning of block");
4479 // Submodule information is only valid if we have a current module.
4480 // FIXME: Should we error on these cases?
4481 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
4482 Kind != SUBMODULE_DEFINITION)
4486 default: // Default behavior: ignore.
4489 case SUBMODULE_DEFINITION: {
4490 if (Record.size() < 8) {
4491 Error("malformed module definition");
4495 StringRef Name = Blob;
4497 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4498 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4499 bool IsFramework = Record[Idx++];
4500 bool IsExplicit = Record[Idx++];
4501 bool IsSystem = Record[Idx++];
4502 bool IsExternC = Record[Idx++];
4503 bool InferSubmodules = Record[Idx++];
4504 bool InferExplicitSubmodules = Record[Idx++];
4505 bool InferExportWildcard = Record[Idx++];
4506 bool ConfigMacrosExhaustive = Record[Idx++];
4508 Module *ParentModule = nullptr;
4510 ParentModule = getSubmodule(Parent);
4512 // Retrieve this (sub)module from the module map, creating it if
4514 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule, IsFramework,
4517 // FIXME: set the definition loc for CurrentModule, or call
4518 // ModMap.setInferredModuleAllowedBy()
4520 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4521 if (GlobalIndex >= SubmodulesLoaded.size() ||
4522 SubmodulesLoaded[GlobalIndex]) {
4523 Error("too many submodules");
4527 if (!ParentModule) {
4528 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4529 if (CurFile != F.File) {
4530 if (!Diags.isDiagnosticInFlight()) {
4531 Diag(diag::err_module_file_conflict)
4532 << CurrentModule->getTopLevelModuleName()
4533 << CurFile->getName()
4534 << F.File->getName();
4540 CurrentModule->setASTFile(F.File);
4543 CurrentModule->Signature = F.Signature;
4544 CurrentModule->IsFromModuleFile = true;
4545 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
4546 CurrentModule->IsExternC = IsExternC;
4547 CurrentModule->InferSubmodules = InferSubmodules;
4548 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4549 CurrentModule->InferExportWildcard = InferExportWildcard;
4550 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
4551 if (DeserializationListener)
4552 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
4554 SubmodulesLoaded[GlobalIndex] = CurrentModule;
4556 // Clear out data that will be replaced by what is in the module file.
4557 CurrentModule->LinkLibraries.clear();
4558 CurrentModule->ConfigMacros.clear();
4559 CurrentModule->UnresolvedConflicts.clear();
4560 CurrentModule->Conflicts.clear();
4562 // The module is available unless it's missing a requirement; relevant
4563 // requirements will be (re-)added by SUBMODULE_REQUIRES records.
4564 // Missing headers that were present when the module was built do not
4565 // make it unavailable -- if we got this far, this must be an explicitly
4566 // imported module file.
4567 CurrentModule->Requirements.clear();
4568 CurrentModule->MissingHeaders.clear();
4569 CurrentModule->IsMissingRequirement =
4570 ParentModule && ParentModule->IsMissingRequirement;
4571 CurrentModule->IsAvailable = !CurrentModule->IsMissingRequirement;
4575 case SUBMODULE_UMBRELLA_HEADER: {
4576 std::string Filename = Blob;
4577 ResolveImportedPath(F, Filename);
4578 if (auto *Umbrella = PP.getFileManager().getFile(Filename)) {
4579 if (!CurrentModule->getUmbrellaHeader())
4580 ModMap.setUmbrellaHeader(CurrentModule, Umbrella, Blob);
4581 else if (CurrentModule->getUmbrellaHeader().Entry != Umbrella) {
4582 // This can be a spurious difference caused by changing the VFS to
4583 // point to a different copy of the file, and it is too late to
4584 // to rebuild safely.
4585 // FIXME: If we wrote the virtual paths instead of the 'real' paths,
4586 // after input file validation only real problems would remain and we
4587 // could just error. For now, assume it's okay.
4594 case SUBMODULE_HEADER:
4595 case SUBMODULE_EXCLUDED_HEADER:
4596 case SUBMODULE_PRIVATE_HEADER:
4597 // We lazily associate headers with their modules via the HeaderInfo table.
4598 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4599 // of complete filenames or remove it entirely.
4602 case SUBMODULE_TEXTUAL_HEADER:
4603 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
4604 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
4608 case SUBMODULE_TOPHEADER: {
4609 CurrentModule->addTopHeaderFilename(Blob);
4613 case SUBMODULE_UMBRELLA_DIR: {
4614 std::string Dirname = Blob;
4615 ResolveImportedPath(F, Dirname);
4616 if (auto *Umbrella = PP.getFileManager().getDirectory(Dirname)) {
4617 if (!CurrentModule->getUmbrellaDir())
4618 ModMap.setUmbrellaDir(CurrentModule, Umbrella, Blob);
4619 else if (CurrentModule->getUmbrellaDir().Entry != Umbrella) {
4620 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4621 Error("mismatched umbrella directories in submodule");
4628 case SUBMODULE_METADATA: {
4629 F.BaseSubmoduleID = getTotalNumSubmodules();
4630 F.LocalNumSubmodules = Record[0];
4631 unsigned LocalBaseSubmoduleID = Record[1];
4632 if (F.LocalNumSubmodules > 0) {
4633 // Introduce the global -> local mapping for submodules within this
4635 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
4637 // Introduce the local -> global mapping for submodules within this
4639 F.SubmoduleRemap.insertOrReplace(
4640 std::make_pair(LocalBaseSubmoduleID,
4641 F.BaseSubmoduleID - LocalBaseSubmoduleID));
4643 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4648 case SUBMODULE_IMPORTS: {
4649 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
4650 UnresolvedModuleRef Unresolved;
4651 Unresolved.File = &F;
4652 Unresolved.Mod = CurrentModule;
4653 Unresolved.ID = Record[Idx];
4654 Unresolved.Kind = UnresolvedModuleRef::Import;
4655 Unresolved.IsWildcard = false;
4656 UnresolvedModuleRefs.push_back(Unresolved);
4661 case SUBMODULE_EXPORTS: {
4662 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
4663 UnresolvedModuleRef Unresolved;
4664 Unresolved.File = &F;
4665 Unresolved.Mod = CurrentModule;
4666 Unresolved.ID = Record[Idx];
4667 Unresolved.Kind = UnresolvedModuleRef::Export;
4668 Unresolved.IsWildcard = Record[Idx + 1];
4669 UnresolvedModuleRefs.push_back(Unresolved);
4672 // Once we've loaded the set of exports, there's no reason to keep
4673 // the parsed, unresolved exports around.
4674 CurrentModule->UnresolvedExports.clear();
4677 case SUBMODULE_REQUIRES: {
4678 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
4679 Context.getTargetInfo());
4683 case SUBMODULE_LINK_LIBRARY:
4684 CurrentModule->LinkLibraries.push_back(
4685 Module::LinkLibrary(Blob, Record[0]));
4688 case SUBMODULE_CONFIG_MACRO:
4689 CurrentModule->ConfigMacros.push_back(Blob.str());
4692 case SUBMODULE_CONFLICT: {
4693 UnresolvedModuleRef Unresolved;
4694 Unresolved.File = &F;
4695 Unresolved.Mod = CurrentModule;
4696 Unresolved.ID = Record[0];
4697 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4698 Unresolved.IsWildcard = false;
4699 Unresolved.String = Blob;
4700 UnresolvedModuleRefs.push_back(Unresolved);
4704 case SUBMODULE_INITIALIZERS:
4705 SmallVector<uint32_t, 16> Inits;
4706 for (auto &ID : Record)
4707 Inits.push_back(getGlobalDeclID(F, ID));
4708 Context.addLazyModuleInitializers(CurrentModule, Inits);
4714 /// \brief Parse the record that corresponds to a LangOptions data
4717 /// This routine parses the language options from the AST file and then gives
4718 /// them to the AST listener if one is set.
4720 /// \returns true if the listener deems the file unacceptable, false otherwise.
4721 bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4723 ASTReaderListener &Listener,
4724 bool AllowCompatibleDifferences) {
4725 LangOptions LangOpts;
4727 #define LANGOPT(Name, Bits, Default, Description) \
4728 LangOpts.Name = Record[Idx++];
4729 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4730 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4731 #include "clang/Basic/LangOptions.def"
4732 #define SANITIZER(NAME, ID) \
4733 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
4734 #include "clang/Basic/Sanitizers.def"
4736 for (unsigned N = Record[Idx++]; N; --N)
4737 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
4739 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4740 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4741 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
4743 LangOpts.CurrentModule = ReadString(Record, Idx);
4746 for (unsigned N = Record[Idx++]; N; --N) {
4747 LangOpts.CommentOpts.BlockCommandNames.push_back(
4748 ReadString(Record, Idx));
4750 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
4752 // OpenMP offloading options.
4753 for (unsigned N = Record[Idx++]; N; --N) {
4754 LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx)));
4757 LangOpts.OMPHostIRFile = ReadString(Record, Idx);
4759 return Listener.ReadLanguageOptions(LangOpts, Complain,
4760 AllowCompatibleDifferences);
4763 bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
4764 ASTReaderListener &Listener,
4765 bool AllowCompatibleDifferences) {
4767 TargetOptions TargetOpts;
4768 TargetOpts.Triple = ReadString(Record, Idx);
4769 TargetOpts.CPU = ReadString(Record, Idx);
4770 TargetOpts.ABI = ReadString(Record, Idx);
4771 for (unsigned N = Record[Idx++]; N; --N) {
4772 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4774 for (unsigned N = Record[Idx++]; N; --N) {
4775 TargetOpts.Features.push_back(ReadString(Record, Idx));
4778 return Listener.ReadTargetOptions(TargetOpts, Complain,
4779 AllowCompatibleDifferences);
4782 bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4783 ASTReaderListener &Listener) {
4784 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
4786 #define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
4787 #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
4788 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
4789 #include "clang/Basic/DiagnosticOptions.def"
4791 for (unsigned N = Record[Idx++]; N; --N)
4792 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
4793 for (unsigned N = Record[Idx++]; N; --N)
4794 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
4796 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4799 bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4800 ASTReaderListener &Listener) {
4801 FileSystemOptions FSOpts;
4803 FSOpts.WorkingDir = ReadString(Record, Idx);
4804 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4807 bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4809 ASTReaderListener &Listener) {
4810 HeaderSearchOptions HSOpts;
4812 HSOpts.Sysroot = ReadString(Record, Idx);
4815 for (unsigned N = Record[Idx++]; N; --N) {
4816 std::string Path = ReadString(Record, Idx);
4817 frontend::IncludeDirGroup Group
4818 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
4819 bool IsFramework = Record[Idx++];
4820 bool IgnoreSysRoot = Record[Idx++];
4821 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
4825 // System header prefixes.
4826 for (unsigned N = Record[Idx++]; N; --N) {
4827 std::string Prefix = ReadString(Record, Idx);
4828 bool IsSystemHeader = Record[Idx++];
4829 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
4832 HSOpts.ResourceDir = ReadString(Record, Idx);
4833 HSOpts.ModuleCachePath = ReadString(Record, Idx);
4834 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
4835 HSOpts.DisableModuleHash = Record[Idx++];
4836 HSOpts.UseBuiltinIncludes = Record[Idx++];
4837 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4838 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4839 HSOpts.UseLibcxx = Record[Idx++];
4840 std::string SpecificModuleCachePath = ReadString(Record, Idx);
4842 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4846 bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4848 ASTReaderListener &Listener,
4849 std::string &SuggestedPredefines) {
4850 PreprocessorOptions PPOpts;
4853 // Macro definitions/undefs
4854 for (unsigned N = Record[Idx++]; N; --N) {
4855 std::string Macro = ReadString(Record, Idx);
4856 bool IsUndef = Record[Idx++];
4857 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4861 for (unsigned N = Record[Idx++]; N; --N) {
4862 PPOpts.Includes.push_back(ReadString(Record, Idx));
4866 for (unsigned N = Record[Idx++]; N; --N) {
4867 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4870 PPOpts.UsePredefines = Record[Idx++];
4871 PPOpts.DetailedRecord = Record[Idx++];
4872 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4873 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4874 PPOpts.ObjCXXARCStandardLibrary =
4875 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4876 SuggestedPredefines.clear();
4877 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4878 SuggestedPredefines);
4881 std::pair<ModuleFile *, unsigned>
4882 ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4883 GlobalPreprocessedEntityMapType::iterator
4884 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4885 assert(I != GlobalPreprocessedEntityMap.end() &&
4886 "Corrupted global preprocessed entity map");
4887 ModuleFile *M = I->second;
4888 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4889 return std::make_pair(M, LocalIndex);
4892 llvm::iterator_range<PreprocessingRecord::iterator>
4893 ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4894 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4895 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4896 Mod.NumPreprocessedEntities);
4898 return llvm::make_range(PreprocessingRecord::iterator(),
4899 PreprocessingRecord::iterator());
4902 llvm::iterator_range<ASTReader::ModuleDeclIterator>
4903 ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
4904 return llvm::make_range(
4905 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4906 ModuleDeclIterator(this, &Mod,
4907 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
4910 PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4911 PreprocessedEntityID PPID = Index+1;
4912 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4913 ModuleFile &M = *PPInfo.first;
4914 unsigned LocalIndex = PPInfo.second;
4915 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4917 if (!PP.getPreprocessingRecord()) {
4918 Error("no preprocessing record");
4922 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4923 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4925 llvm::BitstreamEntry Entry =
4926 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4927 if (Entry.Kind != llvm::BitstreamEntry::Record)
4931 SourceRange Range(TranslateSourceLocation(M, PPOffs.getBegin()),
4932 TranslateSourceLocation(M, PPOffs.getEnd()));
4933 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
4936 PreprocessorDetailRecordTypes RecType =
4937 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
4938 Entry.ID, Record, &Blob);
4940 case PPD_MACRO_EXPANSION: {
4941 bool isBuiltin = Record[0];
4942 IdentifierInfo *Name = nullptr;
4943 MacroDefinitionRecord *Def = nullptr;
4945 Name = getLocalIdentifier(M, Record[1]);
4947 PreprocessedEntityID GlobalID =
4948 getGlobalPreprocessedEntityID(M, Record[1]);
4949 Def = cast<MacroDefinitionRecord>(
4950 PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
4955 ME = new (PPRec) MacroExpansion(Name, Range);
4957 ME = new (PPRec) MacroExpansion(Def, Range);
4962 case PPD_MACRO_DEFINITION: {
4963 // Decode the identifier info and then check again; if the macro is
4964 // still defined and associated with the identifier,
4965 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
4966 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
4968 if (DeserializationListener)
4969 DeserializationListener->MacroDefinitionRead(PPID, MD);
4974 case PPD_INCLUSION_DIRECTIVE: {
4975 const char *FullFileNameStart = Blob.data() + Record[0];
4976 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
4977 const FileEntry *File = nullptr;
4978 if (!FullFileName.empty())
4979 File = PP.getFileManager().getFile(FullFileName);
4981 // FIXME: Stable encoding
4982 InclusionDirective::InclusionKind Kind
4983 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4984 InclusionDirective *ID
4985 = new (PPRec) InclusionDirective(PPRec, Kind,
4986 StringRef(Blob.data(), Record[0]),
4987 Record[1], Record[3],
4994 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4997 /// \brief \arg SLocMapI points at a chunk of a module that contains no
4998 /// preprocessed entities or the entities it contains are not the ones we are
4999 /// looking for. Find the next module that contains entities and return the ID
5000 /// of the first entry.
5001 PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
5002 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
5004 for (GlobalSLocOffsetMapType::const_iterator
5005 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
5006 ModuleFile &M = *SLocMapI->second;
5007 if (M.NumPreprocessedEntities)
5008 return M.BasePreprocessedEntityID;
5011 return getTotalNumPreprocessedEntities();
5016 struct PPEntityComp {
5017 const ASTReader &Reader;
5020 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
5022 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
5023 SourceLocation LHS = getLoc(L);
5024 SourceLocation RHS = getLoc(R);
5025 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5028 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
5029 SourceLocation LHS = getLoc(L);
5030 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5033 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
5034 SourceLocation RHS = getLoc(R);
5035 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5038 SourceLocation getLoc(const PPEntityOffset &PPE) const {
5039 return Reader.TranslateSourceLocation(M, PPE.getBegin());
5045 PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
5046 bool EndsAfter) const {
5047 if (SourceMgr.isLocalSourceLocation(Loc))
5048 return getTotalNumPreprocessedEntities();
5050 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
5051 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
5052 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
5053 "Corrupted global sloc offset map");
5055 if (SLocMapI->second->NumPreprocessedEntities == 0)
5056 return findNextPreprocessedEntity(SLocMapI);
5058 ModuleFile &M = *SLocMapI->second;
5059 typedef const PPEntityOffset *pp_iterator;
5060 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
5061 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
5063 size_t Count = M.NumPreprocessedEntities;
5065 pp_iterator First = pp_begin;
5069 PPI = std::upper_bound(pp_begin, pp_end, Loc,
5070 PPEntityComp(*this, M));
5072 // Do a binary search manually instead of using std::lower_bound because
5073 // The end locations of entities may be unordered (when a macro expansion
5074 // is inside another macro argument), but for this case it is not important
5075 // whether we get the first macro expansion or its containing macro.
5079 std::advance(PPI, Half);
5080 if (SourceMgr.isBeforeInTranslationUnit(
5081 TranslateSourceLocation(M, PPI->getEnd()), Loc)) {
5084 Count = Count - Half - 1;
5091 return findNextPreprocessedEntity(SLocMapI);
5093 return M.BasePreprocessedEntityID + (PPI - pp_begin);
5096 /// \brief Returns a pair of [Begin, End) indices of preallocated
5097 /// preprocessed entities that \arg Range encompasses.
5098 std::pair<unsigned, unsigned>
5099 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
5100 if (Range.isInvalid())
5101 return std::make_pair(0,0);
5102 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
5104 PreprocessedEntityID BeginID =
5105 findPreprocessedEntity(Range.getBegin(), false);
5106 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
5107 return std::make_pair(BeginID, EndID);
5110 /// \brief Optionally returns true or false if the preallocated preprocessed
5111 /// entity with index \arg Index came from file \arg FID.
5112 Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
5114 if (FID.isInvalid())
5117 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5118 ModuleFile &M = *PPInfo.first;
5119 unsigned LocalIndex = PPInfo.second;
5120 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
5122 SourceLocation Loc = TranslateSourceLocation(M, PPOffs.getBegin());
5123 if (Loc.isInvalid())
5126 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
5133 /// \brief Visitor used to search for information about a header file.
5134 class HeaderFileInfoVisitor {
5135 const FileEntry *FE;
5137 Optional<HeaderFileInfo> HFI;
5140 explicit HeaderFileInfoVisitor(const FileEntry *FE)
5143 bool operator()(ModuleFile &M) {
5144 HeaderFileInfoLookupTable *Table
5145 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
5149 // Look in the on-disk hash table for an entry for this file name.
5150 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
5151 if (Pos == Table->end())
5158 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
5162 HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
5163 HeaderFileInfoVisitor Visitor(FE);
5164 ModuleMgr.visit(Visitor);
5165 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
5168 return HeaderFileInfo();
5171 void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
5172 // FIXME: Make it work properly with modules.
5173 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
5174 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
5175 ModuleFile &F = *(*I);
5178 assert(!Diag.DiagStates.empty());
5179 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
5180 while (Idx < F.PragmaDiagMappings.size()) {
5181 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
5182 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
5183 if (DiagStateID != 0) {
5184 Diag.DiagStatePoints.push_back(
5185 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
5186 FullSourceLoc(Loc, SourceMgr)));
5190 assert(DiagStateID == 0);
5191 // A new DiagState was created here.
5192 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
5193 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
5194 DiagStates.push_back(NewState);
5195 Diag.DiagStatePoints.push_back(
5196 DiagnosticsEngine::DiagStatePoint(NewState,
5197 FullSourceLoc(Loc, SourceMgr)));
5199 assert(Idx < F.PragmaDiagMappings.size() &&
5200 "Invalid data, didn't find '-1' marking end of diag/map pairs");
5201 if (Idx >= F.PragmaDiagMappings.size()) {
5202 break; // Something is messed up but at least avoid infinite loop in
5205 unsigned DiagID = F.PragmaDiagMappings[Idx++];
5206 if (DiagID == (unsigned)-1) {
5207 break; // no more diag/map pairs for this location.
5209 diag::Severity Map = (diag::Severity)F.PragmaDiagMappings[Idx++];
5210 DiagnosticMapping Mapping = Diag.makeUserMapping(Map, Loc);
5211 Diag.GetCurDiagState()->setMapping(DiagID, Mapping);
5217 /// \brief Get the correct cursor and offset for loading a type.
5218 ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
5219 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
5220 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
5221 ModuleFile *M = I->second;
5222 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
5225 /// \brief Read and return the type with the given index..
5227 /// The index is the type ID, shifted and minus the number of predefs. This
5228 /// routine actually reads the record corresponding to the type at the given
5229 /// location. It is a helper routine for GetType, which deals with reading type
5231 QualType ASTReader::readTypeRecord(unsigned Index) {
5232 RecordLocation Loc = TypeCursorForIndex(Index);
5233 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
5235 // Keep track of where we are in the stream, then jump back there
5236 // after reading this type.
5237 SavedStreamPosition SavedPosition(DeclsCursor);
5239 ReadingKindTracker ReadingKind(Read_Type, *this);
5241 // Note that we are loading a type record.
5242 Deserializing AType(this);
5245 DeclsCursor.JumpToBit(Loc.Offset);
5247 unsigned Code = DeclsCursor.ReadCode();
5248 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
5249 case TYPE_EXT_QUAL: {
5250 if (Record.size() != 2) {
5251 Error("Incorrect encoding of extended qualifier type");
5254 QualType Base = readType(*Loc.F, Record, Idx);
5255 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
5256 return Context.getQualifiedType(Base, Quals);
5259 case TYPE_COMPLEX: {
5260 if (Record.size() != 1) {
5261 Error("Incorrect encoding of complex type");
5264 QualType ElemType = readType(*Loc.F, Record, Idx);
5265 return Context.getComplexType(ElemType);
5268 case TYPE_POINTER: {
5269 if (Record.size() != 1) {
5270 Error("Incorrect encoding of pointer type");
5273 QualType PointeeType = readType(*Loc.F, Record, Idx);
5274 return Context.getPointerType(PointeeType);
5277 case TYPE_DECAYED: {
5278 if (Record.size() != 1) {
5279 Error("Incorrect encoding of decayed type");
5282 QualType OriginalType = readType(*Loc.F, Record, Idx);
5283 QualType DT = Context.getAdjustedParameterType(OriginalType);
5284 if (!isa<DecayedType>(DT))
5285 Error("Decayed type does not decay");
5289 case TYPE_ADJUSTED: {
5290 if (Record.size() != 2) {
5291 Error("Incorrect encoding of adjusted type");
5294 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5295 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5296 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5299 case TYPE_BLOCK_POINTER: {
5300 if (Record.size() != 1) {
5301 Error("Incorrect encoding of block pointer type");
5304 QualType PointeeType = readType(*Loc.F, Record, Idx);
5305 return Context.getBlockPointerType(PointeeType);
5308 case TYPE_LVALUE_REFERENCE: {
5309 if (Record.size() != 2) {
5310 Error("Incorrect encoding of lvalue reference type");
5313 QualType PointeeType = readType(*Loc.F, Record, Idx);
5314 return Context.getLValueReferenceType(PointeeType, Record[1]);
5317 case TYPE_RVALUE_REFERENCE: {
5318 if (Record.size() != 1) {
5319 Error("Incorrect encoding of rvalue reference type");
5322 QualType PointeeType = readType(*Loc.F, Record, Idx);
5323 return Context.getRValueReferenceType(PointeeType);
5326 case TYPE_MEMBER_POINTER: {
5327 if (Record.size() != 2) {
5328 Error("Incorrect encoding of member pointer type");
5331 QualType PointeeType = readType(*Loc.F, Record, Idx);
5332 QualType ClassType = readType(*Loc.F, Record, Idx);
5333 if (PointeeType.isNull() || ClassType.isNull())
5336 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5339 case TYPE_CONSTANT_ARRAY: {
5340 QualType ElementType = readType(*Loc.F, Record, Idx);
5341 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5342 unsigned IndexTypeQuals = Record[2];
5344 llvm::APInt Size = ReadAPInt(Record, Idx);
5345 return Context.getConstantArrayType(ElementType, Size,
5346 ASM, IndexTypeQuals);
5349 case TYPE_INCOMPLETE_ARRAY: {
5350 QualType ElementType = readType(*Loc.F, Record, Idx);
5351 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5352 unsigned IndexTypeQuals = Record[2];
5353 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5356 case TYPE_VARIABLE_ARRAY: {
5357 QualType ElementType = readType(*Loc.F, Record, Idx);
5358 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5359 unsigned IndexTypeQuals = Record[2];
5360 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5361 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5362 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5363 ASM, IndexTypeQuals,
5364 SourceRange(LBLoc, RBLoc));
5368 if (Record.size() != 3) {
5369 Error("incorrect encoding of vector type in AST file");
5373 QualType ElementType = readType(*Loc.F, Record, Idx);
5374 unsigned NumElements = Record[1];
5375 unsigned VecKind = Record[2];
5376 return Context.getVectorType(ElementType, NumElements,
5377 (VectorType::VectorKind)VecKind);
5380 case TYPE_EXT_VECTOR: {
5381 if (Record.size() != 3) {
5382 Error("incorrect encoding of extended vector type in AST file");
5386 QualType ElementType = readType(*Loc.F, Record, Idx);
5387 unsigned NumElements = Record[1];
5388 return Context.getExtVectorType(ElementType, NumElements);
5391 case TYPE_FUNCTION_NO_PROTO: {
5392 if (Record.size() != 6) {
5393 Error("incorrect encoding of no-proto function type");
5396 QualType ResultType = readType(*Loc.F, Record, Idx);
5397 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5398 (CallingConv)Record[4], Record[5]);
5399 return Context.getFunctionNoProtoType(ResultType, Info);
5402 case TYPE_FUNCTION_PROTO: {
5403 QualType ResultType = readType(*Loc.F, Record, Idx);
5405 FunctionProtoType::ExtProtoInfo EPI;
5406 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5407 /*hasregparm*/ Record[2],
5408 /*regparm*/ Record[3],
5409 static_cast<CallingConv>(Record[4]),
5410 /*produces*/ Record[5]);
5414 EPI.Variadic = Record[Idx++];
5415 EPI.HasTrailingReturn = Record[Idx++];
5416 EPI.TypeQuals = Record[Idx++];
5417 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
5418 SmallVector<QualType, 8> ExceptionStorage;
5419 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
5421 unsigned NumParams = Record[Idx++];
5422 SmallVector<QualType, 16> ParamTypes;
5423 for (unsigned I = 0; I != NumParams; ++I)
5424 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5426 SmallVector<FunctionProtoType::ExtParameterInfo, 4> ExtParameterInfos;
5427 if (Idx != Record.size()) {
5428 for (unsigned I = 0; I != NumParams; ++I)
5429 ExtParameterInfos.push_back(
5430 FunctionProtoType::ExtParameterInfo
5431 ::getFromOpaqueValue(Record[Idx++]));
5432 EPI.ExtParameterInfos = ExtParameterInfos.data();
5435 assert(Idx == Record.size());
5437 return Context.getFunctionType(ResultType, ParamTypes, EPI);
5440 case TYPE_UNRESOLVED_USING: {
5442 return Context.getTypeDeclType(
5443 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5446 case TYPE_TYPEDEF: {
5447 if (Record.size() != 2) {
5448 Error("incorrect encoding of typedef type");
5452 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5453 QualType Canonical = readType(*Loc.F, Record, Idx);
5454 if (!Canonical.isNull())
5455 Canonical = Context.getCanonicalType(Canonical);
5456 return Context.getTypedefType(Decl, Canonical);
5459 case TYPE_TYPEOF_EXPR:
5460 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5463 if (Record.size() != 1) {
5464 Error("incorrect encoding of typeof(type) in AST file");
5467 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5468 return Context.getTypeOfType(UnderlyingType);
5471 case TYPE_DECLTYPE: {
5472 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5473 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5476 case TYPE_UNARY_TRANSFORM: {
5477 QualType BaseType = readType(*Loc.F, Record, Idx);
5478 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5479 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5480 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5484 QualType Deduced = readType(*Loc.F, Record, Idx);
5485 AutoTypeKeyword Keyword = (AutoTypeKeyword)Record[Idx++];
5486 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
5487 return Context.getAutoType(Deduced, Keyword, IsDependent);
5491 if (Record.size() != 2) {
5492 Error("incorrect encoding of record type");
5496 bool IsDependent = Record[Idx++];
5497 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5498 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5499 QualType T = Context.getRecordType(RD);
5500 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5505 if (Record.size() != 2) {
5506 Error("incorrect encoding of enum type");
5510 bool IsDependent = Record[Idx++];
5512 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5513 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5517 case TYPE_ATTRIBUTED: {
5518 if (Record.size() != 3) {
5519 Error("incorrect encoding of attributed type");
5522 QualType modifiedType = readType(*Loc.F, Record, Idx);
5523 QualType equivalentType = readType(*Loc.F, Record, Idx);
5524 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5525 return Context.getAttributedType(kind, modifiedType, equivalentType);
5529 if (Record.size() != 1) {
5530 Error("incorrect encoding of paren type");
5533 QualType InnerType = readType(*Loc.F, Record, Idx);
5534 return Context.getParenType(InnerType);
5537 case TYPE_PACK_EXPANSION: {
5538 if (Record.size() != 2) {
5539 Error("incorrect encoding of pack expansion type");
5542 QualType Pattern = readType(*Loc.F, Record, Idx);
5543 if (Pattern.isNull())
5545 Optional<unsigned> NumExpansions;
5547 NumExpansions = Record[1] - 1;
5548 return Context.getPackExpansionType(Pattern, NumExpansions);
5551 case TYPE_ELABORATED: {
5553 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5554 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5555 QualType NamedType = readType(*Loc.F, Record, Idx);
5556 return Context.getElaboratedType(Keyword, NNS, NamedType);
5559 case TYPE_OBJC_INTERFACE: {
5561 ObjCInterfaceDecl *ItfD
5562 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5563 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5566 case TYPE_OBJC_OBJECT: {
5568 QualType Base = readType(*Loc.F, Record, Idx);
5569 unsigned NumTypeArgs = Record[Idx++];
5570 SmallVector<QualType, 4> TypeArgs;
5571 for (unsigned I = 0; I != NumTypeArgs; ++I)
5572 TypeArgs.push_back(readType(*Loc.F, Record, Idx));
5573 unsigned NumProtos = Record[Idx++];
5574 SmallVector<ObjCProtocolDecl*, 4> Protos;
5575 for (unsigned I = 0; I != NumProtos; ++I)
5576 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
5577 bool IsKindOf = Record[Idx++];
5578 return Context.getObjCObjectType(Base, TypeArgs, Protos, IsKindOf);
5581 case TYPE_OBJC_OBJECT_POINTER: {
5583 QualType Pointee = readType(*Loc.F, Record, Idx);
5584 return Context.getObjCObjectPointerType(Pointee);
5587 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5589 QualType Parm = readType(*Loc.F, Record, Idx);
5590 QualType Replacement = readType(*Loc.F, Record, Idx);
5591 return Context.getSubstTemplateTypeParmType(
5592 cast<TemplateTypeParmType>(Parm),
5593 Context.getCanonicalType(Replacement));
5596 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5598 QualType Parm = readType(*Loc.F, Record, Idx);
5599 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5600 return Context.getSubstTemplateTypeParmPackType(
5601 cast<TemplateTypeParmType>(Parm),
5605 case TYPE_INJECTED_CLASS_NAME: {
5606 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5607 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5608 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5609 // for AST reading, too much interdependencies.
5610 const Type *T = nullptr;
5611 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
5612 if (const Type *Existing = DI->getTypeForDecl()) {
5618 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
5619 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
5620 DI->setTypeForDecl(T);
5622 return QualType(T, 0);
5625 case TYPE_TEMPLATE_TYPE_PARM: {
5627 unsigned Depth = Record[Idx++];
5628 unsigned Index = Record[Idx++];
5629 bool Pack = Record[Idx++];
5630 TemplateTypeParmDecl *D
5631 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5632 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5635 case TYPE_DEPENDENT_NAME: {
5637 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5638 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5639 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
5640 QualType Canon = readType(*Loc.F, Record, Idx);
5641 if (!Canon.isNull())
5642 Canon = Context.getCanonicalType(Canon);
5643 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5646 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5648 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5649 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5650 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
5651 unsigned NumArgs = Record[Idx++];
5652 SmallVector<TemplateArgument, 8> Args;
5653 Args.reserve(NumArgs);
5655 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5656 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
5660 case TYPE_DEPENDENT_SIZED_ARRAY: {
5664 QualType ElementType = readType(*Loc.F, Record, Idx);
5665 ArrayType::ArraySizeModifier ASM
5666 = (ArrayType::ArraySizeModifier)Record[Idx++];
5667 unsigned IndexTypeQuals = Record[Idx++];
5669 // DependentSizedArrayType
5670 Expr *NumElts = ReadExpr(*Loc.F);
5671 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5673 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5674 IndexTypeQuals, Brackets);
5677 case TYPE_TEMPLATE_SPECIALIZATION: {
5679 bool IsDependent = Record[Idx++];
5680 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5681 SmallVector<TemplateArgument, 8> Args;
5682 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5683 QualType Underlying = readType(*Loc.F, Record, Idx);
5685 if (Underlying.isNull())
5686 T = Context.getCanonicalTemplateSpecializationType(Name, Args);
5688 T = Context.getTemplateSpecializationType(Name, Args, Underlying);
5689 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5694 if (Record.size() != 1) {
5695 Error("Incorrect encoding of atomic type");
5698 QualType ValueType = readType(*Loc.F, Record, Idx);
5699 return Context.getAtomicType(ValueType);
5703 if (Record.size() != 1) {
5704 Error("Incorrect encoding of pipe type");
5708 // Reading the pipe element type.
5709 QualType ElementType = readType(*Loc.F, Record, Idx);
5710 return Context.getPipeType(ElementType);
5713 llvm_unreachable("Invalid TypeCode!");
5716 void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5717 SmallVectorImpl<QualType> &Exceptions,
5718 FunctionProtoType::ExceptionSpecInfo &ESI,
5719 const RecordData &Record, unsigned &Idx) {
5720 ExceptionSpecificationType EST =
5721 static_cast<ExceptionSpecificationType>(Record[Idx++]);
5723 if (EST == EST_Dynamic) {
5724 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
5725 Exceptions.push_back(readType(ModuleFile, Record, Idx));
5726 ESI.Exceptions = Exceptions;
5727 } else if (EST == EST_ComputedNoexcept) {
5728 ESI.NoexceptExpr = ReadExpr(ModuleFile);
5729 } else if (EST == EST_Uninstantiated) {
5730 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5731 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5732 } else if (EST == EST_Unevaluated) {
5733 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5737 class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
5740 const ASTReader::RecordData &Record;
5743 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
5745 return Reader.ReadSourceLocation(F, R, I);
5748 template<typename T>
5749 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
5750 return Reader.ReadDeclAs<T>(F, Record, Idx);
5754 TypeLocReader(ASTReader &Reader, ModuleFile &F,
5755 const ASTReader::RecordData &Record, unsigned &Idx)
5756 : Reader(Reader), F(F), Record(Record), Idx(Idx)
5759 // We want compile-time assurance that we've enumerated all of
5760 // these, so unfortunately we have to declare them first, then
5761 // define them out-of-line.
5762 #define ABSTRACT_TYPELOC(CLASS, PARENT)
5763 #define TYPELOC(CLASS, PARENT) \
5764 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5765 #include "clang/AST/TypeLocNodes.def"
5767 void VisitFunctionTypeLoc(FunctionTypeLoc);
5768 void VisitArrayTypeLoc(ArrayTypeLoc);
5771 void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5774 void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5775 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
5776 if (TL.needsExtraLocalData()) {
5777 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5778 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5779 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5780 TL.setModeAttr(Record[Idx++]);
5783 void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5784 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5786 void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5787 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5789 void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5792 void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5795 void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5796 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5798 void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5799 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5801 void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5802 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5804 void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5805 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5806 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5808 void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5809 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5810 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5812 TL.setSizeExpr(Reader.ReadExpr(F));
5814 TL.setSizeExpr(nullptr);
5816 void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5817 VisitArrayTypeLoc(TL);
5819 void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5820 VisitArrayTypeLoc(TL);
5822 void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5823 VisitArrayTypeLoc(TL);
5825 void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5826 DependentSizedArrayTypeLoc TL) {
5827 VisitArrayTypeLoc(TL);
5829 void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5830 DependentSizedExtVectorTypeLoc TL) {
5831 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5833 void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5834 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5836 void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5837 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5839 void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5840 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5841 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5842 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5843 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
5844 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5845 TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
5848 void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5849 VisitFunctionTypeLoc(TL);
5851 void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5852 VisitFunctionTypeLoc(TL);
5854 void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5855 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5857 void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5858 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5860 void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5861 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5862 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5863 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5865 void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5866 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5867 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5868 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5869 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5871 void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5872 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5874 void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5875 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5876 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5877 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5878 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5880 void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5881 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5883 void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5884 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5886 void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5887 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5889 void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5890 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5891 if (TL.hasAttrOperand()) {
5893 range.setBegin(ReadSourceLocation(Record, Idx));
5894 range.setEnd(ReadSourceLocation(Record, Idx));
5895 TL.setAttrOperandParensRange(range);
5897 if (TL.hasAttrExprOperand()) {
5899 TL.setAttrExprOperand(Reader.ReadExpr(F));
5901 TL.setAttrExprOperand(nullptr);
5902 } else if (TL.hasAttrEnumOperand())
5903 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5905 void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5906 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5908 void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5909 SubstTemplateTypeParmTypeLoc TL) {
5910 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5912 void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5913 SubstTemplateTypeParmPackTypeLoc TL) {
5914 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5916 void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5917 TemplateSpecializationTypeLoc TL) {
5918 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5919 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5920 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5921 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5922 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5924 Reader.GetTemplateArgumentLocInfo(F,
5925 TL.getTypePtr()->getArg(i).getKind(),
5928 void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5929 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5930 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5932 void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5933 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5934 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5936 void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5937 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5939 void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5940 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5941 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5942 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5944 void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5945 DependentTemplateSpecializationTypeLoc TL) {
5946 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5947 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5948 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5949 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5950 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5951 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5952 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5954 Reader.GetTemplateArgumentLocInfo(F,
5955 TL.getTypePtr()->getArg(I).getKind(),
5958 void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5959 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5961 void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5962 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5964 void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5965 TL.setHasBaseTypeAsWritten(Record[Idx++]);
5966 TL.setTypeArgsLAngleLoc(ReadSourceLocation(Record, Idx));
5967 TL.setTypeArgsRAngleLoc(ReadSourceLocation(Record, Idx));
5968 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
5969 TL.setTypeArgTInfo(i, Reader.GetTypeSourceInfo(F, Record, Idx));
5970 TL.setProtocolLAngleLoc(ReadSourceLocation(Record, Idx));
5971 TL.setProtocolRAngleLoc(ReadSourceLocation(Record, Idx));
5972 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5973 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5975 void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5976 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5978 void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5979 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5980 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5981 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5983 void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) {
5984 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5987 TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5988 const RecordData &Record,
5990 QualType InfoTy = readType(F, Record, Idx);
5991 if (InfoTy.isNull())
5994 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5995 TypeLocReader TLR(*this, F, Record, Idx);
5996 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
6001 QualType ASTReader::GetType(TypeID ID) {
6002 unsigned FastQuals = ID & Qualifiers::FastMask;
6003 unsigned Index = ID >> Qualifiers::FastWidth;
6005 if (Index < NUM_PREDEF_TYPE_IDS) {
6007 switch ((PredefinedTypeIDs)Index) {
6008 case PREDEF_TYPE_NULL_ID:
6010 case PREDEF_TYPE_VOID_ID:
6013 case PREDEF_TYPE_BOOL_ID:
6017 case PREDEF_TYPE_CHAR_U_ID:
6018 case PREDEF_TYPE_CHAR_S_ID:
6019 // FIXME: Check that the signedness of CharTy is correct!
6023 case PREDEF_TYPE_UCHAR_ID:
6024 T = Context.UnsignedCharTy;
6026 case PREDEF_TYPE_USHORT_ID:
6027 T = Context.UnsignedShortTy;
6029 case PREDEF_TYPE_UINT_ID:
6030 T = Context.UnsignedIntTy;
6032 case PREDEF_TYPE_ULONG_ID:
6033 T = Context.UnsignedLongTy;
6035 case PREDEF_TYPE_ULONGLONG_ID:
6036 T = Context.UnsignedLongLongTy;
6038 case PREDEF_TYPE_UINT128_ID:
6039 T = Context.UnsignedInt128Ty;
6041 case PREDEF_TYPE_SCHAR_ID:
6042 T = Context.SignedCharTy;
6044 case PREDEF_TYPE_WCHAR_ID:
6045 T = Context.WCharTy;
6047 case PREDEF_TYPE_SHORT_ID:
6048 T = Context.ShortTy;
6050 case PREDEF_TYPE_INT_ID:
6053 case PREDEF_TYPE_LONG_ID:
6056 case PREDEF_TYPE_LONGLONG_ID:
6057 T = Context.LongLongTy;
6059 case PREDEF_TYPE_INT128_ID:
6060 T = Context.Int128Ty;
6062 case PREDEF_TYPE_HALF_ID:
6065 case PREDEF_TYPE_FLOAT_ID:
6066 T = Context.FloatTy;
6068 case PREDEF_TYPE_DOUBLE_ID:
6069 T = Context.DoubleTy;
6071 case PREDEF_TYPE_LONGDOUBLE_ID:
6072 T = Context.LongDoubleTy;
6074 case PREDEF_TYPE_FLOAT128_ID:
6075 T = Context.Float128Ty;
6077 case PREDEF_TYPE_OVERLOAD_ID:
6078 T = Context.OverloadTy;
6080 case PREDEF_TYPE_BOUND_MEMBER:
6081 T = Context.BoundMemberTy;
6083 case PREDEF_TYPE_PSEUDO_OBJECT:
6084 T = Context.PseudoObjectTy;
6086 case PREDEF_TYPE_DEPENDENT_ID:
6087 T = Context.DependentTy;
6089 case PREDEF_TYPE_UNKNOWN_ANY:
6090 T = Context.UnknownAnyTy;
6092 case PREDEF_TYPE_NULLPTR_ID:
6093 T = Context.NullPtrTy;
6095 case PREDEF_TYPE_CHAR16_ID:
6096 T = Context.Char16Ty;
6098 case PREDEF_TYPE_CHAR32_ID:
6099 T = Context.Char32Ty;
6101 case PREDEF_TYPE_OBJC_ID:
6102 T = Context.ObjCBuiltinIdTy;
6104 case PREDEF_TYPE_OBJC_CLASS:
6105 T = Context.ObjCBuiltinClassTy;
6107 case PREDEF_TYPE_OBJC_SEL:
6108 T = Context.ObjCBuiltinSelTy;
6110 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6111 case PREDEF_TYPE_##Id##_ID: \
6112 T = Context.SingletonId; \
6114 #include "clang/Basic/OpenCLImageTypes.def"
6115 case PREDEF_TYPE_SAMPLER_ID:
6116 T = Context.OCLSamplerTy;
6118 case PREDEF_TYPE_EVENT_ID:
6119 T = Context.OCLEventTy;
6121 case PREDEF_TYPE_CLK_EVENT_ID:
6122 T = Context.OCLClkEventTy;
6124 case PREDEF_TYPE_QUEUE_ID:
6125 T = Context.OCLQueueTy;
6127 case PREDEF_TYPE_NDRANGE_ID:
6128 T = Context.OCLNDRangeTy;
6130 case PREDEF_TYPE_RESERVE_ID_ID:
6131 T = Context.OCLReserveIDTy;
6133 case PREDEF_TYPE_AUTO_DEDUCT:
6134 T = Context.getAutoDeductType();
6137 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
6138 T = Context.getAutoRRefDeductType();
6141 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
6142 T = Context.ARCUnbridgedCastTy;
6145 case PREDEF_TYPE_BUILTIN_FN:
6146 T = Context.BuiltinFnTy;
6149 case PREDEF_TYPE_OMP_ARRAY_SECTION:
6150 T = Context.OMPArraySectionTy;
6154 assert(!T.isNull() && "Unknown predefined type");
6155 return T.withFastQualifiers(FastQuals);
6158 Index -= NUM_PREDEF_TYPE_IDS;
6159 assert(Index < TypesLoaded.size() && "Type index out-of-range");
6160 if (TypesLoaded[Index].isNull()) {
6161 TypesLoaded[Index] = readTypeRecord(Index);
6162 if (TypesLoaded[Index].isNull())
6165 TypesLoaded[Index]->setFromAST();
6166 if (DeserializationListener)
6167 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
6168 TypesLoaded[Index]);
6171 return TypesLoaded[Index].withFastQualifiers(FastQuals);
6174 QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
6175 return GetType(getGlobalTypeID(F, LocalID));
6178 serialization::TypeID
6179 ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
6180 unsigned FastQuals = LocalID & Qualifiers::FastMask;
6181 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
6183 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
6186 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6187 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
6188 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
6190 unsigned GlobalIndex = LocalIndex + I->second;
6191 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
6194 TemplateArgumentLocInfo
6195 ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
6196 TemplateArgument::ArgKind Kind,
6197 const RecordData &Record,
6200 case TemplateArgument::Expression:
6202 case TemplateArgument::Type:
6203 return GetTypeSourceInfo(F, Record, Index);
6204 case TemplateArgument::Template: {
6205 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
6207 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6208 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6211 case TemplateArgument::TemplateExpansion: {
6212 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
6214 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6215 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
6216 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6219 case TemplateArgument::Null:
6220 case TemplateArgument::Integral:
6221 case TemplateArgument::Declaration:
6222 case TemplateArgument::NullPtr:
6223 case TemplateArgument::Pack:
6224 // FIXME: Is this right?
6225 return TemplateArgumentLocInfo();
6227 llvm_unreachable("unexpected template argument loc");
6231 ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
6232 const RecordData &Record, unsigned &Index) {
6233 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
6235 if (Arg.getKind() == TemplateArgument::Expression) {
6236 if (Record[Index++]) // bool InfoHasSameExpr.
6237 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
6239 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
6243 const ASTTemplateArgumentListInfo*
6244 ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
6245 const RecordData &Record,
6247 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
6248 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
6249 unsigned NumArgsAsWritten = Record[Index++];
6250 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
6251 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
6252 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
6253 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
6256 Decl *ASTReader::GetExternalDecl(uint32_t ID) {
6260 template<typename TemplateSpecializationDecl>
6261 static void completeRedeclChainForTemplateSpecialization(Decl *D) {
6262 if (auto *TSD = dyn_cast<TemplateSpecializationDecl>(D))
6263 TSD->getSpecializedTemplate()->LoadLazySpecializations();
6266 void ASTReader::CompleteRedeclChain(const Decl *D) {
6267 if (NumCurrentElementsDeserializing) {
6268 // We arrange to not care about the complete redeclaration chain while we're
6269 // deserializing. Just remember that the AST has marked this one as complete
6270 // but that it's not actually complete yet, so we know we still need to
6271 // complete it later.
6272 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
6276 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
6278 // If this is a named declaration, complete it by looking it up
6279 // within its context.
6281 // FIXME: Merging a function definition should merge
6282 // all mergeable entities within it.
6283 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
6284 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
6285 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
6286 if (!getContext().getLangOpts().CPlusPlus &&
6287 isa<TranslationUnitDecl>(DC)) {
6288 // Outside of C++, we don't have a lookup table for the TU, so update
6289 // the identifier instead. (For C++ modules, we don't store decls
6290 // in the serialized identifier table, so we do the lookup in the TU.)
6291 auto *II = Name.getAsIdentifierInfo();
6292 assert(II && "non-identifier name in C?");
6293 if (II->isOutOfDate())
6294 updateOutOfDateIdentifier(*II);
6297 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
6298 // Find all declarations of this kind from the relevant context.
6299 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
6300 auto *DC = cast<DeclContext>(DCDecl);
6301 SmallVector<Decl*, 8> Decls;
6302 FindExternalLexicalDecls(
6303 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
6308 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
6309 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
6310 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
6311 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
6312 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6313 if (auto *Template = FD->getPrimaryTemplate())
6314 Template->LoadLazySpecializations();
6318 CXXCtorInitializer **
6319 ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
6320 RecordLocation Loc = getLocalBitOffset(Offset);
6321 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
6322 SavedStreamPosition SavedPosition(Cursor);
6323 Cursor.JumpToBit(Loc.Offset);
6324 ReadingKindTracker ReadingKind(Read_Decl, *this);
6327 unsigned Code = Cursor.ReadCode();
6328 unsigned RecCode = Cursor.readRecord(Code, Record);
6329 if (RecCode != DECL_CXX_CTOR_INITIALIZERS) {
6330 Error("malformed AST file: missing C++ ctor initializers");
6335 return ReadCXXCtorInitializers(*Loc.F, Record, Idx);
6338 CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
6339 RecordLocation Loc = getLocalBitOffset(Offset);
6340 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
6341 SavedStreamPosition SavedPosition(Cursor);
6342 Cursor.JumpToBit(Loc.Offset);
6343 ReadingKindTracker ReadingKind(Read_Decl, *this);
6345 unsigned Code = Cursor.ReadCode();
6346 unsigned RecCode = Cursor.readRecord(Code, Record);
6347 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
6348 Error("malformed AST file: missing C++ base specifiers");
6353 unsigned NumBases = Record[Idx++];
6354 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
6355 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
6356 for (unsigned I = 0; I != NumBases; ++I)
6357 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
6361 serialization::DeclID
6362 ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
6363 if (LocalID < NUM_PREDEF_DECL_IDS)
6366 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6367 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
6368 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
6370 return LocalID + I->second;
6373 bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
6374 ModuleFile &M) const {
6375 // Predefined decls aren't from any module.
6376 if (ID < NUM_PREDEF_DECL_IDS)
6379 return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
6380 ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
6383 ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
6384 if (!D->isFromASTFile())
6386 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6387 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6391 SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6392 if (ID < NUM_PREDEF_DECL_IDS)
6393 return SourceLocation();
6395 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6397 if (Index > DeclsLoaded.size()) {
6398 Error("declaration ID out-of-range for AST file");
6399 return SourceLocation();
6402 if (Decl *D = DeclsLoaded[Index])
6403 return D->getLocation();
6406 DeclCursorForID(ID, Loc);
6410 static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
6412 case PREDEF_DECL_NULL_ID:
6415 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6416 return Context.getTranslationUnitDecl();
6418 case PREDEF_DECL_OBJC_ID_ID:
6419 return Context.getObjCIdDecl();
6421 case PREDEF_DECL_OBJC_SEL_ID:
6422 return Context.getObjCSelDecl();
6424 case PREDEF_DECL_OBJC_CLASS_ID:
6425 return Context.getObjCClassDecl();
6427 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6428 return Context.getObjCProtocolDecl();
6430 case PREDEF_DECL_INT_128_ID:
6431 return Context.getInt128Decl();
6433 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6434 return Context.getUInt128Decl();
6436 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6437 return Context.getObjCInstanceTypeDecl();
6439 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6440 return Context.getBuiltinVaListDecl();
6442 case PREDEF_DECL_VA_LIST_TAG:
6443 return Context.getVaListTagDecl();
6445 case PREDEF_DECL_BUILTIN_MS_VA_LIST_ID:
6446 return Context.getBuiltinMSVaListDecl();
6448 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
6449 return Context.getExternCContextDecl();
6451 case PREDEF_DECL_MAKE_INTEGER_SEQ_ID:
6452 return Context.getMakeIntegerSeqDecl();
6454 case PREDEF_DECL_CF_CONSTANT_STRING_ID:
6455 return Context.getCFConstantStringDecl();
6457 case PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID:
6458 return Context.getCFConstantStringTagDecl();
6460 case PREDEF_DECL_TYPE_PACK_ELEMENT_ID:
6461 return Context.getTypePackElementDecl();
6463 llvm_unreachable("PredefinedDeclIDs unknown enum value");
6466 Decl *ASTReader::GetExistingDecl(DeclID ID) {
6467 if (ID < NUM_PREDEF_DECL_IDS) {
6468 Decl *D = getPredefinedDecl(Context, (PredefinedDeclIDs)ID);
6470 // Track that we have merged the declaration with ID \p ID into the
6471 // pre-existing predefined declaration \p D.
6472 auto &Merged = KeyDecls[D->getCanonicalDecl()];
6474 Merged.push_back(ID);
6479 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6481 if (Index >= DeclsLoaded.size()) {
6482 assert(0 && "declaration ID out-of-range for AST file");
6483 Error("declaration ID out-of-range for AST file");
6487 return DeclsLoaded[Index];
6490 Decl *ASTReader::GetDecl(DeclID ID) {
6491 if (ID < NUM_PREDEF_DECL_IDS)
6492 return GetExistingDecl(ID);
6494 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6496 if (Index >= DeclsLoaded.size()) {
6497 assert(0 && "declaration ID out-of-range for AST file");
6498 Error("declaration ID out-of-range for AST file");
6502 if (!DeclsLoaded[Index]) {
6504 if (DeserializationListener)
6505 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6508 return DeclsLoaded[Index];
6511 DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
6513 if (GlobalID < NUM_PREDEF_DECL_IDS)
6516 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6517 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6518 ModuleFile *Owner = I->second;
6520 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6521 = M.GlobalToLocalDeclIDs.find(Owner);
6522 if (Pos == M.GlobalToLocalDeclIDs.end())
6525 return GlobalID - Owner->BaseDeclID + Pos->second;
6528 serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
6529 const RecordData &Record,
6531 if (Idx >= Record.size()) {
6532 Error("Corrupted AST file");
6536 return getGlobalDeclID(F, Record[Idx++]);
6539 /// \brief Resolve the offset of a statement into a statement.
6541 /// This operation will read a new statement from the external
6542 /// source each time it is called, and is meant to be used via a
6543 /// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6544 Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6545 // Switch case IDs are per Decl.
6546 ClearSwitchCaseIDs();
6548 // Offset here is a global offset across the entire chain.
6549 RecordLocation Loc = getLocalBitOffset(Offset);
6550 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
6551 return ReadStmtFromStream(*Loc.F);
6554 void ASTReader::FindExternalLexicalDecls(
6555 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
6556 SmallVectorImpl<Decl *> &Decls) {
6557 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
6559 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
6560 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
6561 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
6562 auto K = (Decl::Kind)+LexicalDecls[I];
6563 if (!IsKindWeWant(K))
6566 auto ID = (serialization::DeclID)+LexicalDecls[I + 1];
6568 // Don't add predefined declarations to the lexical context more
6570 if (ID < NUM_PREDEF_DECL_IDS) {
6571 if (PredefsVisited[ID])
6574 PredefsVisited[ID] = true;
6577 if (Decl *D = GetLocalDecl(*M, ID)) {
6578 assert(D->getKind() == K && "wrong kind for lexical decl");
6579 if (!DC->isDeclInLexicalTraversal(D))
6585 if (isa<TranslationUnitDecl>(DC)) {
6586 for (auto Lexical : TULexicalDecls)
6587 Visit(Lexical.first, Lexical.second);
6589 auto I = LexicalDecls.find(DC);
6590 if (I != LexicalDecls.end())
6591 Visit(I->second.first, I->second.second);
6594 ++NumLexicalDeclContextsRead;
6604 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6606 bool operator()(LocalDeclID L, LocalDeclID R) const {
6607 SourceLocation LHS = getLocation(L);
6608 SourceLocation RHS = getLocation(R);
6609 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6612 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6613 SourceLocation RHS = getLocation(R);
6614 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6617 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6618 SourceLocation LHS = getLocation(L);
6619 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6622 SourceLocation getLocation(LocalDeclID ID) const {
6623 return Reader.getSourceManager().getFileLoc(
6624 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6630 void ASTReader::FindFileRegionDecls(FileID File,
6631 unsigned Offset, unsigned Length,
6632 SmallVectorImpl<Decl *> &Decls) {
6633 SourceManager &SM = getSourceManager();
6635 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6636 if (I == FileDeclIDs.end())
6639 FileDeclsInfo &DInfo = I->second;
6640 if (DInfo.Decls.empty())
6644 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6645 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6647 DeclIDComp DIDComp(*this, *DInfo.Mod);
6648 ArrayRef<serialization::LocalDeclID>::iterator
6649 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6651 if (BeginIt != DInfo.Decls.begin())
6654 // If we are pointing at a top-level decl inside an objc container, we need
6655 // to backtrack until we find it otherwise we will fail to report that the
6656 // region overlaps with an objc container.
6657 while (BeginIt != DInfo.Decls.begin() &&
6658 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6659 ->isTopLevelDeclInObjCContainer())
6662 ArrayRef<serialization::LocalDeclID>::iterator
6663 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6665 if (EndIt != DInfo.Decls.end())
6668 for (ArrayRef<serialization::LocalDeclID>::iterator
6669 DIt = BeginIt; DIt != EndIt; ++DIt)
6670 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6674 ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6675 DeclarationName Name) {
6676 assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
6677 "DeclContext has no visible decls in storage");
6681 auto It = Lookups.find(DC);
6682 if (It == Lookups.end())
6685 Deserializing LookupResults(this);
6687 // Load the list of declarations.
6688 SmallVector<NamedDecl *, 64> Decls;
6689 for (DeclID ID : It->second.Table.find(Name)) {
6690 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
6691 if (ND->getDeclName() == Name)
6692 Decls.push_back(ND);
6695 ++NumVisibleDeclContextsRead;
6696 SetExternalVisibleDeclsForName(DC, Name, Decls);
6697 return !Decls.empty();
6700 void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6701 if (!DC->hasExternalVisibleStorage())
6704 auto It = Lookups.find(DC);
6705 assert(It != Lookups.end() &&
6706 "have external visible storage but no lookup tables");
6710 for (DeclID ID : It->second.Table.findAll()) {
6711 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
6712 Decls[ND->getDeclName()].push_back(ND);
6715 ++NumVisibleDeclContextsRead;
6717 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
6718 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6720 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6723 const serialization::reader::DeclContextLookupTable *
6724 ASTReader::getLoadedLookupTables(DeclContext *Primary) const {
6725 auto I = Lookups.find(Primary);
6726 return I == Lookups.end() ? nullptr : &I->second;
6729 /// \brief Under non-PCH compilation the consumer receives the objc methods
6730 /// before receiving the implementation, and codegen depends on this.
6731 /// We simulate this by deserializing and passing to consumer the methods of the
6732 /// implementation before passing the deserialized implementation decl.
6733 static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6734 ASTConsumer *Consumer) {
6735 assert(ImplD && Consumer);
6737 for (auto *I : ImplD->methods())
6738 Consumer->HandleInterestingDecl(DeclGroupRef(I));
6740 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6743 void ASTReader::PassInterestingDeclsToConsumer() {
6746 if (PassingDeclsToConsumer)
6749 // Guard variable to avoid recursively redoing the process of passing
6750 // decls to consumer.
6751 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
6754 // Ensure that we've loaded all potentially-interesting declarations
6755 // that need to be eagerly loaded.
6756 for (auto ID : EagerlyDeserializedDecls)
6758 EagerlyDeserializedDecls.clear();
6760 while (!InterestingDecls.empty()) {
6761 Decl *D = InterestingDecls.front();
6762 InterestingDecls.pop_front();
6764 PassInterestingDeclToConsumer(D);
6768 void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6769 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6770 PassObjCImplDeclToConsumer(ImplD, Consumer);
6772 Consumer->HandleInterestingDecl(DeclGroupRef(D));
6775 void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6776 this->Consumer = Consumer;
6779 PassInterestingDeclsToConsumer();
6781 if (DeserializationListener)
6782 DeserializationListener->ReaderInitialized(this);
6785 void ASTReader::PrintStats() {
6786 std::fprintf(stderr, "*** AST File Statistics:\n");
6788 unsigned NumTypesLoaded
6789 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6791 unsigned NumDeclsLoaded
6792 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
6794 unsigned NumIdentifiersLoaded
6795 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6796 IdentifiersLoaded.end(),
6797 (IdentifierInfo *)nullptr);
6798 unsigned NumMacrosLoaded
6799 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6801 (MacroInfo *)nullptr);
6802 unsigned NumSelectorsLoaded
6803 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6804 SelectorsLoaded.end(),
6807 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6808 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6809 NumSLocEntriesRead, TotalNumSLocEntries,
6810 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6811 if (!TypesLoaded.empty())
6812 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6813 NumTypesLoaded, (unsigned)TypesLoaded.size(),
6814 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6815 if (!DeclsLoaded.empty())
6816 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6817 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6818 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6819 if (!IdentifiersLoaded.empty())
6820 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6821 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6822 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6823 if (!MacrosLoaded.empty())
6824 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6825 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6826 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6827 if (!SelectorsLoaded.empty())
6828 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
6829 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6830 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6831 if (TotalNumStatements)
6832 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
6833 NumStatementsRead, TotalNumStatements,
6834 ((float)NumStatementsRead/TotalNumStatements * 100));
6836 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6837 NumMacrosRead, TotalNumMacros,
6838 ((float)NumMacrosRead/TotalNumMacros * 100));
6839 if (TotalLexicalDeclContexts)
6840 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
6841 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6842 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6844 if (TotalVisibleDeclContexts)
6845 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
6846 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6847 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6849 if (TotalNumMethodPoolEntries) {
6850 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
6851 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6852 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6855 if (NumMethodPoolLookups) {
6856 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
6857 NumMethodPoolHits, NumMethodPoolLookups,
6858 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6860 if (NumMethodPoolTableLookups) {
6861 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
6862 NumMethodPoolTableHits, NumMethodPoolTableLookups,
6863 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6867 if (NumIdentifierLookupHits) {
6868 std::fprintf(stderr,
6869 " %u / %u identifier table lookups succeeded (%f%%)\n",
6870 NumIdentifierLookupHits, NumIdentifierLookups,
6871 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
6875 std::fprintf(stderr, "\n");
6876 GlobalIndex->printStats();
6879 std::fprintf(stderr, "\n");
6881 std::fprintf(stderr, "\n");
6884 template<typename Key, typename ModuleFile, unsigned InitialCapacity>
6886 dumpModuleIDMap(StringRef Name,
6887 const ContinuousRangeMap<Key, ModuleFile *,
6888 InitialCapacity> &Map) {
6889 if (Map.begin() == Map.end())
6892 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
6893 llvm::errs() << Name << ":\n";
6894 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6896 llvm::errs() << " " << I->first << " -> " << I->second->FileName
6901 LLVM_DUMP_METHOD void ASTReader::dump() {
6902 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
6903 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
6904 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
6905 dumpModuleIDMap("Global type map", GlobalTypeMap);
6906 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
6907 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
6908 dumpModuleIDMap("Global macro map", GlobalMacroMap);
6909 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
6910 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
6911 dumpModuleIDMap("Global preprocessed entity map",
6912 GlobalPreprocessedEntityMap);
6914 llvm::errs() << "\n*** PCH/Modules Loaded:";
6915 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6916 MEnd = ModuleMgr.end();
6921 /// Return the amount of memory used by memory buffers, breaking down
6922 /// by heap-backed versus mmap'ed memory.
6923 void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
6924 for (ModuleConstIterator I = ModuleMgr.begin(),
6925 E = ModuleMgr.end(); I != E; ++I) {
6926 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
6927 size_t bytes = buf->getBufferSize();
6928 switch (buf->getBufferKind()) {
6929 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6930 sizes.malloc_bytes += bytes;
6932 case llvm::MemoryBuffer::MemoryBuffer_MMap:
6933 sizes.mmap_bytes += bytes;
6940 void ASTReader::InitializeSema(Sema &S) {
6942 S.addExternalSource(this);
6944 // Makes sure any declarations that were deserialized "too early"
6945 // still get added to the identifier's declaration chains.
6946 for (uint64_t ID : PreloadedDeclIDs) {
6947 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
6948 pushExternalDeclIntoScope(D, D->getDeclName());
6950 PreloadedDeclIDs.clear();
6952 // FIXME: What happens if these are changed by a module import?
6953 if (!FPPragmaOptions.empty()) {
6954 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
6955 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
6958 // FIXME: What happens if these are changed by a module import?
6959 if (!OpenCLExtensions.empty()) {
6961 #define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
6962 #include "clang/Basic/OpenCLExtensions.def"
6964 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
6970 void ASTReader::UpdateSema() {
6971 assert(SemaObj && "no Sema to update");
6973 // Load the offsets of the declarations that Sema references.
6974 // They will be lazily deserialized when needed.
6975 if (!SemaDeclRefs.empty()) {
6976 assert(SemaDeclRefs.size() % 2 == 0);
6977 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
6978 if (!SemaObj->StdNamespace)
6979 SemaObj->StdNamespace = SemaDeclRefs[I];
6980 if (!SemaObj->StdBadAlloc)
6981 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
6983 SemaDeclRefs.clear();
6986 // Update the state of pragmas. Use the same API as if we had encountered the
6987 // pragma in the source.
6988 if(OptimizeOffPragmaLocation.isValid())
6989 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
6990 if (PragmaMSStructState != -1)
6991 SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState);
6992 if (PointersToMembersPragmaLocation.isValid()) {
6993 SemaObj->ActOnPragmaMSPointersToMembers(
6994 (LangOptions::PragmaMSPointersToMembersKind)
6995 PragmaMSPointersToMembersState,
6996 PointersToMembersPragmaLocation);
7000 IdentifierInfo *ASTReader::get(StringRef Name) {
7001 // Note that we are loading an identifier.
7002 Deserializing AnIdentifier(this);
7004 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
7005 NumIdentifierLookups,
7006 NumIdentifierLookupHits);
7008 // We don't need to do identifier table lookups in C++ modules (we preload
7009 // all interesting declarations, and don't need to use the scope for name
7010 // lookups). Perform the lookup in PCH files, though, since we don't build
7011 // a complete initial identifier table if we're carrying on from a PCH.
7012 if (Context.getLangOpts().CPlusPlus) {
7013 for (auto F : ModuleMgr.pch_modules())
7017 // If there is a global index, look there first to determine which modules
7018 // provably do not have any results for this identifier.
7019 GlobalModuleIndex::HitSet Hits;
7020 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
7021 if (!loadGlobalIndex()) {
7022 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
7027 ModuleMgr.visit(Visitor, HitsPtr);
7030 IdentifierInfo *II = Visitor.getIdentifierInfo();
7031 markIdentifierUpToDate(II);
7036 /// \brief An identifier-lookup iterator that enumerates all of the
7037 /// identifiers stored within a set of AST files.
7038 class ASTIdentifierIterator : public IdentifierIterator {
7039 /// \brief The AST reader whose identifiers are being enumerated.
7040 const ASTReader &Reader;
7042 /// \brief The current index into the chain of AST files stored in
7046 /// \brief The current position within the identifier lookup table
7047 /// of the current AST file.
7048 ASTIdentifierLookupTable::key_iterator Current;
7050 /// \brief The end position within the identifier lookup table of
7051 /// the current AST file.
7052 ASTIdentifierLookupTable::key_iterator End;
7054 /// \brief Whether to skip any modules in the ASTReader.
7058 explicit ASTIdentifierIterator(const ASTReader &Reader,
7059 bool SkipModules = false);
7061 StringRef Next() override;
7065 ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader,
7067 : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) {
7070 StringRef ASTIdentifierIterator::Next() {
7071 while (Current == End) {
7072 // If we have exhausted all of our AST files, we're done.
7077 ModuleFile &F = Reader.ModuleMgr[Index];
7078 if (SkipModules && F.isModule())
7081 ASTIdentifierLookupTable *IdTable =
7082 (ASTIdentifierLookupTable *)F.IdentifierLookupTable;
7083 Current = IdTable->key_begin();
7084 End = IdTable->key_end();
7087 // We have any identifiers remaining in the current AST file; return
7089 StringRef Result = *Current;
7095 /// A utility for appending two IdentifierIterators.
7096 class ChainedIdentifierIterator : public IdentifierIterator {
7097 std::unique_ptr<IdentifierIterator> Current;
7098 std::unique_ptr<IdentifierIterator> Queued;
7101 ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First,
7102 std::unique_ptr<IdentifierIterator> Second)
7103 : Current(std::move(First)), Queued(std::move(Second)) {}
7105 StringRef Next() override {
7109 StringRef result = Current->Next();
7110 if (!result.empty())
7113 // Try the queued iterator, which may itself be empty.
7115 std::swap(Current, Queued);
7119 } // end anonymous namespace.
7121 IdentifierIterator *ASTReader::getIdentifiers() {
7122 if (!loadGlobalIndex()) {
7123 std::unique_ptr<IdentifierIterator> ReaderIter(
7124 new ASTIdentifierIterator(*this, /*SkipModules=*/true));
7125 std::unique_ptr<IdentifierIterator> ModulesIter(
7126 GlobalIndex->createIdentifierIterator());
7127 return new ChainedIdentifierIterator(std::move(ReaderIter),
7128 std::move(ModulesIter));
7131 return new ASTIdentifierIterator(*this);
7134 namespace clang { namespace serialization {
7135 class ReadMethodPoolVisitor {
7138 unsigned PriorGeneration;
7139 unsigned InstanceBits;
7140 unsigned FactoryBits;
7141 bool InstanceHasMoreThanOneDecl;
7142 bool FactoryHasMoreThanOneDecl;
7143 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
7144 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
7147 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
7148 unsigned PriorGeneration)
7149 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
7150 InstanceBits(0), FactoryBits(0), InstanceHasMoreThanOneDecl(false),
7151 FactoryHasMoreThanOneDecl(false) {}
7153 bool operator()(ModuleFile &M) {
7154 if (!M.SelectorLookupTable)
7157 // If we've already searched this module file, skip it now.
7158 if (M.Generation <= PriorGeneration)
7161 ++Reader.NumMethodPoolTableLookups;
7162 ASTSelectorLookupTable *PoolTable
7163 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
7164 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
7165 if (Pos == PoolTable->end())
7168 ++Reader.NumMethodPoolTableHits;
7169 ++Reader.NumSelectorsRead;
7170 // FIXME: Not quite happy with the statistics here. We probably should
7171 // disable this tracking when called via LoadSelector.
7172 // Also, should entries without methods count as misses?
7173 ++Reader.NumMethodPoolEntriesRead;
7174 ASTSelectorLookupTrait::data_type Data = *Pos;
7175 if (Reader.DeserializationListener)
7176 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
7178 InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
7179 FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
7180 InstanceBits = Data.InstanceBits;
7181 FactoryBits = Data.FactoryBits;
7182 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
7183 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
7187 /// \brief Retrieve the instance methods found by this visitor.
7188 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
7189 return InstanceMethods;
7192 /// \brief Retrieve the instance methods found by this visitor.
7193 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
7194 return FactoryMethods;
7197 unsigned getInstanceBits() const { return InstanceBits; }
7198 unsigned getFactoryBits() const { return FactoryBits; }
7199 bool instanceHasMoreThanOneDecl() const {
7200 return InstanceHasMoreThanOneDecl;
7202 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
7204 } } // end namespace clang::serialization
7206 /// \brief Add the given set of methods to the method list.
7207 static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
7208 ObjCMethodList &List) {
7209 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
7210 S.addMethodToGlobalList(&List, Methods[I]);
7214 void ASTReader::ReadMethodPool(Selector Sel) {
7215 // Get the selector generation and update it to the current generation.
7216 unsigned &Generation = SelectorGeneration[Sel];
7217 unsigned PriorGeneration = Generation;
7218 Generation = getGeneration();
7219 SelectorOutOfDate[Sel] = false;
7221 // Search for methods defined with this selector.
7222 ++NumMethodPoolLookups;
7223 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
7224 ModuleMgr.visit(Visitor);
7226 if (Visitor.getInstanceMethods().empty() &&
7227 Visitor.getFactoryMethods().empty())
7230 ++NumMethodPoolHits;
7235 Sema &S = *getSema();
7236 Sema::GlobalMethodPool::iterator Pos
7237 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
7239 Pos->second.first.setBits(Visitor.getInstanceBits());
7240 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
7241 Pos->second.second.setBits(Visitor.getFactoryBits());
7242 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
7244 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
7245 // when building a module we keep every method individually and may need to
7246 // update hasMoreThanOneDecl as we add the methods.
7247 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7248 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
7251 void ASTReader::updateOutOfDateSelector(Selector Sel) {
7252 if (SelectorOutOfDate[Sel])
7253 ReadMethodPool(Sel);
7256 void ASTReader::ReadKnownNamespaces(
7257 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7260 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
7261 if (NamespaceDecl *Namespace
7262 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7263 Namespaces.push_back(Namespace);
7267 void ASTReader::ReadUndefinedButUsed(
7268 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {
7269 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7270 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
7271 SourceLocation Loc =
7272 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
7273 Undefined.insert(std::make_pair(D, Loc));
7277 void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
7278 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
7280 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
7281 FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
7282 uint64_t Count = DelayedDeleteExprs[Idx++];
7283 for (uint64_t C = 0; C < Count; ++C) {
7284 SourceLocation DeleteLoc =
7285 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
7286 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
7287 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
7292 void ASTReader::ReadTentativeDefinitions(
7293 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7294 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7295 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7297 TentativeDefs.push_back(Var);
7299 TentativeDefinitions.clear();
7302 void ASTReader::ReadUnusedFileScopedDecls(
7303 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7304 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7306 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7310 UnusedFileScopedDecls.clear();
7313 void ASTReader::ReadDelegatingConstructors(
7314 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7315 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7316 CXXConstructorDecl *D
7317 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7321 DelegatingCtorDecls.clear();
7324 void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7325 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7327 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7331 ExtVectorDecls.clear();
7334 void ASTReader::ReadUnusedLocalTypedefNameCandidates(
7335 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
7336 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
7338 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
7339 GetDecl(UnusedLocalTypedefNameCandidates[I]));
7343 UnusedLocalTypedefNameCandidates.clear();
7346 void ASTReader::ReadReferencedSelectors(
7347 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7348 if (ReferencedSelectorsData.empty())
7351 // If there are @selector references added them to its pool. This is for
7352 // implementation of -Wselector.
7353 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7355 while (I < DataSize) {
7356 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7357 SourceLocation SelLoc
7358 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7359 Sels.push_back(std::make_pair(Sel, SelLoc));
7361 ReferencedSelectorsData.clear();
7364 void ASTReader::ReadWeakUndeclaredIdentifiers(
7365 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7366 if (WeakUndeclaredIdentifiers.empty())
7369 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
7370 IdentifierInfo *WeakId
7371 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7372 IdentifierInfo *AliasId
7373 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7375 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7376 bool Used = WeakUndeclaredIdentifiers[I++];
7377 WeakInfo WI(AliasId, Loc);
7379 WeakIDs.push_back(std::make_pair(WeakId, WI));
7381 WeakUndeclaredIdentifiers.clear();
7384 void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7385 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7386 ExternalVTableUse VT;
7387 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7388 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7389 VT.DefinitionRequired = VTableUses[Idx++];
7390 VTables.push_back(VT);
7396 void ASTReader::ReadPendingInstantiations(
7397 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7398 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7399 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7401 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7403 Pending.push_back(std::make_pair(D, Loc));
7405 PendingInstantiations.clear();
7408 void ASTReader::ReadLateParsedTemplates(
7409 llvm::MapVector<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
7410 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7412 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7414 LateParsedTemplate *LT = new LateParsedTemplate;
7415 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7417 ModuleFile *F = getOwningModuleFile(LT->D);
7418 assert(F && "No module");
7420 unsigned TokN = LateParsedTemplates[Idx++];
7421 LT->Toks.reserve(TokN);
7422 for (unsigned T = 0; T < TokN; ++T)
7423 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7425 LPTMap.insert(std::make_pair(FD, LT));
7428 LateParsedTemplates.clear();
7431 void ASTReader::LoadSelector(Selector Sel) {
7432 // It would be complicated to avoid reading the methods anyway. So don't.
7433 ReadMethodPool(Sel);
7436 void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7437 assert(ID && "Non-zero identifier ID required");
7438 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7439 IdentifiersLoaded[ID - 1] = II;
7440 if (DeserializationListener)
7441 DeserializationListener->IdentifierRead(ID, II);
7444 /// \brief Set the globally-visible declarations associated with the given
7447 /// If the AST reader is currently in a state where the given declaration IDs
7448 /// cannot safely be resolved, they are queued until it is safe to resolve
7451 /// \param II an IdentifierInfo that refers to one or more globally-visible
7454 /// \param DeclIDs the set of declaration IDs with the name @p II that are
7455 /// visible at global scope.
7457 /// \param Decls if non-null, this vector will be populated with the set of
7458 /// deserialized declarations. These declarations will not be pushed into
7461 ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7462 const SmallVectorImpl<uint32_t> &DeclIDs,
7463 SmallVectorImpl<Decl *> *Decls) {
7464 if (NumCurrentElementsDeserializing && !Decls) {
7465 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
7469 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
7471 // Queue this declaration so that it will be added to the
7472 // translation unit scope and identifier's declaration chain
7473 // once a Sema object is known.
7474 PreloadedDeclIDs.push_back(DeclIDs[I]);
7478 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7480 // If we're simply supposed to record the declarations, do so now.
7482 Decls->push_back(D);
7486 // Introduce this declaration into the translation-unit scope
7487 // and add it to the declaration chain for this identifier, so
7488 // that (unqualified) name lookup will find it.
7489 pushExternalDeclIntoScope(D, II);
7493 IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
7497 if (IdentifiersLoaded.empty()) {
7498 Error("no identifier table in AST file");
7503 if (!IdentifiersLoaded[ID]) {
7504 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7505 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7506 ModuleFile *M = I->second;
7507 unsigned Index = ID - M->BaseIdentifierID;
7508 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7510 // All of the strings in the AST file are preceded by a 16-bit length.
7511 // Extract that 16-bit length to avoid having to execute strlen().
7512 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7513 // unsigned integers. This is important to avoid integer overflow when
7514 // we cast them to 'unsigned'.
7515 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7516 unsigned StrLen = (((unsigned) StrLenPtr[0])
7517 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
7518 auto &II = PP.getIdentifierTable().get(StringRef(Str, StrLen));
7519 IdentifiersLoaded[ID] = &II;
7520 markIdentifierFromAST(*this, II);
7521 if (DeserializationListener)
7522 DeserializationListener->IdentifierRead(ID + 1, &II);
7525 return IdentifiersLoaded[ID];
7528 IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7529 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
7532 IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7533 if (LocalID < NUM_PREDEF_IDENT_IDS)
7536 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7537 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
7538 assert(I != M.IdentifierRemap.end()
7539 && "Invalid index into identifier index remap");
7541 return LocalID + I->second;
7544 MacroInfo *ASTReader::getMacro(MacroID ID) {
7548 if (MacrosLoaded.empty()) {
7549 Error("no macro table in AST file");
7553 ID -= NUM_PREDEF_MACRO_IDS;
7554 if (!MacrosLoaded[ID]) {
7555 GlobalMacroMapType::iterator I
7556 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7557 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7558 ModuleFile *M = I->second;
7559 unsigned Index = ID - M->BaseMacroID;
7560 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
7562 if (DeserializationListener)
7563 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7567 return MacrosLoaded[ID];
7570 MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7571 if (LocalID < NUM_PREDEF_MACRO_IDS)
7574 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7575 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7576 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7578 return LocalID + I->second;
7581 serialization::SubmoduleID
7582 ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7583 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7586 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7587 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
7588 assert(I != M.SubmoduleRemap.end()
7589 && "Invalid index into submodule index remap");
7591 return LocalID + I->second;
7594 Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7595 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7596 assert(GlobalID == 0 && "Unhandled global submodule ID");
7600 if (GlobalID > SubmodulesLoaded.size()) {
7601 Error("submodule ID out of range in AST file");
7605 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7608 Module *ASTReader::getModule(unsigned ID) {
7609 return getSubmodule(ID);
7612 ModuleFile *ASTReader::getLocalModuleFile(ModuleFile &F, unsigned ID) {
7614 // It's a module, look it up by submodule ID.
7615 auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(F, ID >> 1));
7616 return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
7618 // It's a prefix (preamble, PCH, ...). Look it up by index.
7619 unsigned IndexFromEnd = ID >> 1;
7620 assert(IndexFromEnd && "got reference to unknown module file");
7621 return getModuleManager().pch_modules().end()[-IndexFromEnd];
7625 unsigned ASTReader::getModuleFileID(ModuleFile *F) {
7629 // For a file representing a module, use the submodule ID of the top-level
7630 // module as the file ID. For any other kind of file, the number of such
7631 // files loaded beforehand will be the same on reload.
7632 // FIXME: Is this true even if we have an explicit module file and a PCH?
7634 return ((F->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
7636 auto PCHModules = getModuleManager().pch_modules();
7637 auto I = std::find(PCHModules.begin(), PCHModules.end(), F);
7638 assert(I != PCHModules.end() && "emitting reference to unknown file");
7639 return (I - PCHModules.end()) << 1;
7642 llvm::Optional<ExternalASTSource::ASTSourceDescriptor>
7643 ASTReader::getSourceDescriptor(unsigned ID) {
7644 if (const Module *M = getSubmodule(ID))
7645 return ExternalASTSource::ASTSourceDescriptor(*M);
7647 // If there is only a single PCH, return it instead.
7648 // Chained PCH are not suported.
7649 if (ModuleMgr.size() == 1) {
7650 ModuleFile &MF = ModuleMgr.getPrimaryModule();
7651 StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName);
7652 StringRef FileName = llvm::sys::path::filename(MF.FileName);
7653 return ASTReader::ASTSourceDescriptor(ModuleName, MF.OriginalDir, FileName,
7659 Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7660 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7663 Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7667 if (ID > SelectorsLoaded.size()) {
7668 Error("selector ID out of range in AST file");
7672 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
7673 // Load this selector from the selector table.
7674 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7675 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7676 ModuleFile &M = *I->second;
7677 ASTSelectorLookupTrait Trait(*this, M);
7678 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7679 SelectorsLoaded[ID - 1] =
7680 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7681 if (DeserializationListener)
7682 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7685 return SelectorsLoaded[ID - 1];
7688 Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7689 return DecodeSelector(ID);
7692 uint32_t ASTReader::GetNumExternalSelectors() {
7693 // ID 0 (the null selector) is considered an external selector.
7694 return getTotalNumSelectors() + 1;
7697 serialization::SelectorID
7698 ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7699 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7702 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7703 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
7704 assert(I != M.SelectorRemap.end()
7705 && "Invalid index into selector index remap");
7707 return LocalID + I->second;
7711 ASTReader::ReadDeclarationName(ModuleFile &F,
7712 const RecordData &Record, unsigned &Idx) {
7713 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7715 case DeclarationName::Identifier:
7716 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
7718 case DeclarationName::ObjCZeroArgSelector:
7719 case DeclarationName::ObjCOneArgSelector:
7720 case DeclarationName::ObjCMultiArgSelector:
7721 return DeclarationName(ReadSelector(F, Record, Idx));
7723 case DeclarationName::CXXConstructorName:
7724 return Context.DeclarationNames.getCXXConstructorName(
7725 Context.getCanonicalType(readType(F, Record, Idx)));
7727 case DeclarationName::CXXDestructorName:
7728 return Context.DeclarationNames.getCXXDestructorName(
7729 Context.getCanonicalType(readType(F, Record, Idx)));
7731 case DeclarationName::CXXConversionFunctionName:
7732 return Context.DeclarationNames.getCXXConversionFunctionName(
7733 Context.getCanonicalType(readType(F, Record, Idx)));
7735 case DeclarationName::CXXOperatorName:
7736 return Context.DeclarationNames.getCXXOperatorName(
7737 (OverloadedOperatorKind)Record[Idx++]);
7739 case DeclarationName::CXXLiteralOperatorName:
7740 return Context.DeclarationNames.getCXXLiteralOperatorName(
7741 GetIdentifierInfo(F, Record, Idx));
7743 case DeclarationName::CXXUsingDirective:
7744 return DeclarationName::getUsingDirectiveName();
7747 llvm_unreachable("Invalid NameKind!");
7750 void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7751 DeclarationNameLoc &DNLoc,
7752 DeclarationName Name,
7753 const RecordData &Record, unsigned &Idx) {
7754 switch (Name.getNameKind()) {
7755 case DeclarationName::CXXConstructorName:
7756 case DeclarationName::CXXDestructorName:
7757 case DeclarationName::CXXConversionFunctionName:
7758 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7761 case DeclarationName::CXXOperatorName:
7762 DNLoc.CXXOperatorName.BeginOpNameLoc
7763 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7764 DNLoc.CXXOperatorName.EndOpNameLoc
7765 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7768 case DeclarationName::CXXLiteralOperatorName:
7769 DNLoc.CXXLiteralOperatorName.OpNameLoc
7770 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7773 case DeclarationName::Identifier:
7774 case DeclarationName::ObjCZeroArgSelector:
7775 case DeclarationName::ObjCOneArgSelector:
7776 case DeclarationName::ObjCMultiArgSelector:
7777 case DeclarationName::CXXUsingDirective:
7782 void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7783 DeclarationNameInfo &NameInfo,
7784 const RecordData &Record, unsigned &Idx) {
7785 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7786 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7787 DeclarationNameLoc DNLoc;
7788 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7789 NameInfo.setInfo(DNLoc);
7792 void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7793 const RecordData &Record, unsigned &Idx) {
7794 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7795 unsigned NumTPLists = Record[Idx++];
7796 Info.NumTemplParamLists = NumTPLists;
7798 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
7799 for (unsigned i=0; i != NumTPLists; ++i)
7800 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7805 ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7807 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7809 case TemplateName::Template:
7810 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7812 case TemplateName::OverloadedTemplate: {
7813 unsigned size = Record[Idx++];
7814 UnresolvedSet<8> Decls;
7816 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7818 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7821 case TemplateName::QualifiedTemplate: {
7822 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7823 bool hasTemplKeyword = Record[Idx++];
7824 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7825 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7828 case TemplateName::DependentTemplate: {
7829 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7830 if (Record[Idx++]) // isIdentifier
7831 return Context.getDependentTemplateName(NNS,
7832 GetIdentifierInfo(F, Record,
7834 return Context.getDependentTemplateName(NNS,
7835 (OverloadedOperatorKind)Record[Idx++]);
7838 case TemplateName::SubstTemplateTemplateParm: {
7839 TemplateTemplateParmDecl *param
7840 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7841 if (!param) return TemplateName();
7842 TemplateName replacement = ReadTemplateName(F, Record, Idx);
7843 return Context.getSubstTemplateTemplateParm(param, replacement);
7846 case TemplateName::SubstTemplateTemplateParmPack: {
7847 TemplateTemplateParmDecl *Param
7848 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7850 return TemplateName();
7852 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
7853 if (ArgPack.getKind() != TemplateArgument::Pack)
7854 return TemplateName();
7856 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
7860 llvm_unreachable("Unhandled template name kind!");
7863 TemplateArgument ASTReader::ReadTemplateArgument(ModuleFile &F,
7864 const RecordData &Record,
7866 bool Canonicalize) {
7868 // The caller wants a canonical template argument. Sometimes the AST only
7869 // wants template arguments in canonical form (particularly as the template
7870 // argument lists of template specializations) so ensure we preserve that
7871 // canonical form across serialization.
7872 TemplateArgument Arg = ReadTemplateArgument(F, Record, Idx, false);
7873 return Context.getCanonicalTemplateArgument(Arg);
7876 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
7878 case TemplateArgument::Null:
7879 return TemplateArgument();
7880 case TemplateArgument::Type:
7881 return TemplateArgument(readType(F, Record, Idx));
7882 case TemplateArgument::Declaration: {
7883 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
7884 return TemplateArgument(D, readType(F, Record, Idx));
7886 case TemplateArgument::NullPtr:
7887 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
7888 case TemplateArgument::Integral: {
7889 llvm::APSInt Value = ReadAPSInt(Record, Idx);
7890 QualType T = readType(F, Record, Idx);
7891 return TemplateArgument(Context, Value, T);
7893 case TemplateArgument::Template:
7894 return TemplateArgument(ReadTemplateName(F, Record, Idx));
7895 case TemplateArgument::TemplateExpansion: {
7896 TemplateName Name = ReadTemplateName(F, Record, Idx);
7897 Optional<unsigned> NumTemplateExpansions;
7898 if (unsigned NumExpansions = Record[Idx++])
7899 NumTemplateExpansions = NumExpansions - 1;
7900 return TemplateArgument(Name, NumTemplateExpansions);
7902 case TemplateArgument::Expression:
7903 return TemplateArgument(ReadExpr(F));
7904 case TemplateArgument::Pack: {
7905 unsigned NumArgs = Record[Idx++];
7906 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
7907 for (unsigned I = 0; I != NumArgs; ++I)
7908 Args[I] = ReadTemplateArgument(F, Record, Idx);
7909 return TemplateArgument(llvm::makeArrayRef(Args, NumArgs));
7913 llvm_unreachable("Unhandled template argument kind!");
7916 TemplateParameterList *
7917 ASTReader::ReadTemplateParameterList(ModuleFile &F,
7918 const RecordData &Record, unsigned &Idx) {
7919 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
7920 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
7921 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
7923 unsigned NumParams = Record[Idx++];
7924 SmallVector<NamedDecl *, 16> Params;
7925 Params.reserve(NumParams);
7927 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
7930 TemplateParameterList* TemplateParams =
7931 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
7932 Params, RAngleLoc, nullptr);
7933 return TemplateParams;
7938 ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
7939 ModuleFile &F, const RecordData &Record,
7940 unsigned &Idx, bool Canonicalize) {
7941 unsigned NumTemplateArgs = Record[Idx++];
7942 TemplArgs.reserve(NumTemplateArgs);
7943 while (NumTemplateArgs--)
7944 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx, Canonicalize));
7947 /// \brief Read a UnresolvedSet structure.
7948 void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
7949 const RecordData &Record, unsigned &Idx) {
7950 unsigned NumDecls = Record[Idx++];
7951 Set.reserve(Context, NumDecls);
7952 while (NumDecls--) {
7953 DeclID ID = ReadDeclID(F, Record, Idx);
7954 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
7955 Set.addLazyDecl(Context, ID, AS);
7960 ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
7961 const RecordData &Record, unsigned &Idx) {
7962 bool isVirtual = static_cast<bool>(Record[Idx++]);
7963 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
7964 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
7965 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
7966 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
7967 SourceRange Range = ReadSourceRange(F, Record, Idx);
7968 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
7969 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
7971 Result.setInheritConstructors(inheritConstructors);
7975 CXXCtorInitializer **
7976 ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
7978 unsigned NumInitializers = Record[Idx++];
7979 assert(NumInitializers && "wrote ctor initializers but have no inits");
7980 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
7981 for (unsigned i = 0; i != NumInitializers; ++i) {
7982 TypeSourceInfo *TInfo = nullptr;
7983 bool IsBaseVirtual = false;
7984 FieldDecl *Member = nullptr;
7985 IndirectFieldDecl *IndirectMember = nullptr;
7987 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
7989 case CTOR_INITIALIZER_BASE:
7990 TInfo = GetTypeSourceInfo(F, Record, Idx);
7991 IsBaseVirtual = Record[Idx++];
7994 case CTOR_INITIALIZER_DELEGATING:
7995 TInfo = GetTypeSourceInfo(F, Record, Idx);
7998 case CTOR_INITIALIZER_MEMBER:
7999 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
8002 case CTOR_INITIALIZER_INDIRECT_MEMBER:
8003 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
8007 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
8008 Expr *Init = ReadExpr(F);
8009 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
8010 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
8011 bool IsWritten = Record[Idx++];
8012 unsigned SourceOrderOrNumArrayIndices;
8013 SmallVector<VarDecl *, 8> Indices;
8015 SourceOrderOrNumArrayIndices = Record[Idx++];
8017 SourceOrderOrNumArrayIndices = Record[Idx++];
8018 Indices.reserve(SourceOrderOrNumArrayIndices);
8019 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
8020 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
8023 CXXCtorInitializer *BOMInit;
8024 if (Type == CTOR_INITIALIZER_BASE) {
8025 BOMInit = new (Context)
8026 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
8027 RParenLoc, MemberOrEllipsisLoc);
8028 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
8029 BOMInit = new (Context)
8030 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
8031 } else if (IsWritten) {
8033 BOMInit = new (Context) CXXCtorInitializer(
8034 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc);
8036 BOMInit = new (Context)
8037 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
8038 LParenLoc, Init, RParenLoc);
8040 if (IndirectMember) {
8041 assert(Indices.empty() && "Indirect field improperly initialized");
8042 BOMInit = new (Context)
8043 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
8044 LParenLoc, Init, RParenLoc);
8046 BOMInit = CXXCtorInitializer::Create(
8047 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc,
8048 Indices.data(), Indices.size());
8053 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
8054 CtorInitializers[i] = BOMInit;
8057 return CtorInitializers;
8060 NestedNameSpecifier *
8061 ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
8062 const RecordData &Record, unsigned &Idx) {
8063 unsigned N = Record[Idx++];
8064 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
8065 for (unsigned I = 0; I != N; ++I) {
8066 NestedNameSpecifier::SpecifierKind Kind
8067 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8069 case NestedNameSpecifier::Identifier: {
8070 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
8071 NNS = NestedNameSpecifier::Create(Context, Prev, II);
8075 case NestedNameSpecifier::Namespace: {
8076 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8077 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
8081 case NestedNameSpecifier::NamespaceAlias: {
8082 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8083 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
8087 case NestedNameSpecifier::TypeSpec:
8088 case NestedNameSpecifier::TypeSpecWithTemplate: {
8089 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
8093 bool Template = Record[Idx++];
8094 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
8098 case NestedNameSpecifier::Global: {
8099 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
8100 // No associated value, and there can't be a prefix.
8104 case NestedNameSpecifier::Super: {
8105 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8106 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
8115 NestedNameSpecifierLoc
8116 ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
8118 unsigned N = Record[Idx++];
8119 NestedNameSpecifierLocBuilder Builder;
8120 for (unsigned I = 0; I != N; ++I) {
8121 NestedNameSpecifier::SpecifierKind Kind
8122 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8124 case NestedNameSpecifier::Identifier: {
8125 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
8126 SourceRange Range = ReadSourceRange(F, Record, Idx);
8127 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
8131 case NestedNameSpecifier::Namespace: {
8132 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8133 SourceRange Range = ReadSourceRange(F, Record, Idx);
8134 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
8138 case NestedNameSpecifier::NamespaceAlias: {
8139 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8140 SourceRange Range = ReadSourceRange(F, Record, Idx);
8141 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
8145 case NestedNameSpecifier::TypeSpec:
8146 case NestedNameSpecifier::TypeSpecWithTemplate: {
8147 bool Template = Record[Idx++];
8148 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
8150 return NestedNameSpecifierLoc();
8151 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8153 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
8154 Builder.Extend(Context,
8155 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
8156 T->getTypeLoc(), ColonColonLoc);
8160 case NestedNameSpecifier::Global: {
8161 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8162 Builder.MakeGlobal(Context, ColonColonLoc);
8166 case NestedNameSpecifier::Super: {
8167 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8168 SourceRange Range = ReadSourceRange(F, Record, Idx);
8169 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
8175 return Builder.getWithLocInContext(Context);
8179 ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
8181 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
8182 SourceLocation end = ReadSourceLocation(F, Record, Idx);
8183 return SourceRange(beg, end);
8186 /// \brief Read an integral value
8187 llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
8188 unsigned BitWidth = Record[Idx++];
8189 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
8190 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
8195 /// \brief Read a signed integral value
8196 llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
8197 bool isUnsigned = Record[Idx++];
8198 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
8201 /// \brief Read a floating-point value
8202 llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
8203 const llvm::fltSemantics &Sem,
8205 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
8208 // \brief Read a string
8209 std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
8210 unsigned Len = Record[Idx++];
8211 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
8216 std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
8218 std::string Filename = ReadString(Record, Idx);
8219 ResolveImportedPath(F, Filename);
8223 VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
8225 unsigned Major = Record[Idx++];
8226 unsigned Minor = Record[Idx++];
8227 unsigned Subminor = Record[Idx++];
8229 return VersionTuple(Major);
8231 return VersionTuple(Major, Minor - 1);
8232 return VersionTuple(Major, Minor - 1, Subminor - 1);
8235 CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
8236 const RecordData &Record,
8238 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
8239 return CXXTemporary::Create(Context, Decl);
8242 DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
8243 return Diag(CurrentImportLoc, DiagID);
8246 DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
8247 return Diags.Report(Loc, DiagID);
8250 /// \brief Retrieve the identifier table associated with the
8252 IdentifierTable &ASTReader::getIdentifierTable() {
8253 return PP.getIdentifierTable();
8256 /// \brief Record that the given ID maps to the given switch-case
8258 void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
8259 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
8260 "Already have a SwitchCase with this ID");
8261 (*CurrSwitchCaseStmts)[ID] = SC;
8264 /// \brief Retrieve the switch-case statement with the given ID.
8265 SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
8266 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
8267 return (*CurrSwitchCaseStmts)[ID];
8270 void ASTReader::ClearSwitchCaseIDs() {
8271 CurrSwitchCaseStmts->clear();
8274 void ASTReader::ReadComments() {
8275 std::vector<RawComment *> Comments;
8276 for (SmallVectorImpl<std::pair<BitstreamCursor,
8277 serialization::ModuleFile *> >::iterator
8278 I = CommentsCursors.begin(),
8279 E = CommentsCursors.end();
8282 BitstreamCursor &Cursor = I->first;
8283 serialization::ModuleFile &F = *I->second;
8284 SavedStreamPosition SavedPosition(Cursor);
8288 llvm::BitstreamEntry Entry =
8289 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
8291 switch (Entry.Kind) {
8292 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
8293 case llvm::BitstreamEntry::Error:
8294 Error("malformed block record in AST file");
8296 case llvm::BitstreamEntry::EndBlock:
8298 case llvm::BitstreamEntry::Record:
8299 // The interesting case.
8305 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
8306 case COMMENTS_RAW_COMMENT: {
8308 SourceRange SR = ReadSourceRange(F, Record, Idx);
8309 RawComment::CommentKind Kind =
8310 (RawComment::CommentKind) Record[Idx++];
8311 bool IsTrailingComment = Record[Idx++];
8312 bool IsAlmostTrailingComment = Record[Idx++];
8313 Comments.push_back(new (Context) RawComment(
8314 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8315 Context.getLangOpts().CommentOpts.ParseAllComments));
8321 Context.Comments.addDeserializedComments(Comments);
8325 std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
8326 // If we know the owning module, use it.
8327 if (Module *M = D->getImportedOwningModule())
8328 return M->getFullModuleName();
8330 // Otherwise, use the name of the top-level module the decl is within.
8331 if (ModuleFile *M = getOwningModuleFile(D))
8332 return M->ModuleName;
8334 // Not from a module.
8338 void ASTReader::finishPendingActions() {
8339 while (!PendingIdentifierInfos.empty() ||
8340 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
8341 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
8342 !PendingUpdateRecords.empty()) {
8343 // If any identifiers with corresponding top-level declarations have
8344 // been loaded, load those declarations now.
8345 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8347 TopLevelDeclsMap TopLevelDecls;
8349 while (!PendingIdentifierInfos.empty()) {
8350 IdentifierInfo *II = PendingIdentifierInfos.back().first;
8351 SmallVector<uint32_t, 4> DeclIDs =
8352 std::move(PendingIdentifierInfos.back().second);
8353 PendingIdentifierInfos.pop_back();
8355 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
8358 // For each decl chain that we wanted to complete while deserializing, mark
8359 // it as "still needs to be completed".
8360 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8361 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8363 PendingIncompleteDeclChains.clear();
8365 // Load pending declaration chains.
8366 for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
8367 loadPendingDeclChain(PendingDeclChains[I].first, PendingDeclChains[I].second);
8368 PendingDeclChains.clear();
8370 // Make the most recent of the top-level declarations visible.
8371 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8372 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
8373 IdentifierInfo *II = TLD->first;
8374 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
8375 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
8379 // Load any pending macro definitions.
8380 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
8381 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8382 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8383 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8384 // Initialize the macro history from chained-PCHs ahead of module imports.
8385 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
8387 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
8388 if (!Info.M->isModule())
8389 resolvePendingMacro(II, Info);
8391 // Handle module imports.
8392 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
8394 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
8395 if (Info.M->isModule())
8396 resolvePendingMacro(II, Info);
8399 PendingMacroIDs.clear();
8401 // Wire up the DeclContexts for Decls that we delayed setting until
8402 // recursive loading is completed.
8403 while (!PendingDeclContextInfos.empty()) {
8404 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8405 PendingDeclContextInfos.pop_front();
8406 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8407 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8408 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8411 // Perform any pending declaration updates.
8412 while (!PendingUpdateRecords.empty()) {
8413 auto Update = PendingUpdateRecords.pop_back_val();
8414 ReadingKindTracker ReadingKind(Read_Decl, *this);
8415 loadDeclUpdateRecords(Update.first, Update.second);
8419 // At this point, all update records for loaded decls are in place, so any
8420 // fake class definitions should have become real.
8421 assert(PendingFakeDefinitionData.empty() &&
8422 "faked up a class definition but never saw the real one");
8424 // If we deserialized any C++ or Objective-C class definitions, any
8425 // Objective-C protocol definitions, or any redeclarable templates, make sure
8426 // that all redeclarations point to the definitions. Note that this can only
8427 // happen now, after the redeclaration chains have been fully wired.
8428 for (Decl *D : PendingDefinitions) {
8429 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
8430 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
8431 // Make sure that the TagType points at the definition.
8432 const_cast<TagType*>(TagT)->decl = TD;
8435 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
8436 for (auto *R = getMostRecentExistingDecl(RD); R;
8437 R = R->getPreviousDecl()) {
8439 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
8440 "declaration thinks it's the definition but it isn't");
8441 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
8448 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
8449 // Make sure that the ObjCInterfaceType points at the definition.
8450 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8453 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
8454 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
8459 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
8460 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
8461 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
8466 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
8467 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
8468 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
8470 PendingDefinitions.clear();
8472 // Load the bodies of any functions or methods we've encountered. We do
8473 // this now (delayed) so that we can be sure that the declaration chains
8474 // have been fully wired up (hasBody relies on this).
8475 // FIXME: We shouldn't require complete redeclaration chains here.
8476 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8477 PBEnd = PendingBodies.end();
8478 PB != PBEnd; ++PB) {
8479 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8480 // FIXME: Check for =delete/=default?
8481 // FIXME: Complain about ODR violations here?
8482 if (!getContext().getLangOpts().Modules || !FD->hasBody())
8483 FD->setLazyBody(PB->second);
8487 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8488 if (!getContext().getLangOpts().Modules || !MD->hasBody())
8489 MD->setLazyBody(PB->second);
8491 PendingBodies.clear();
8494 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
8495 getContext().deduplicateMergedDefinitonsFor(ND);
8496 PendingMergedDefinitionsToDeduplicate.clear();
8499 void ASTReader::diagnoseOdrViolations() {
8500 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty())
8503 // Trigger the import of the full definition of each class that had any
8504 // odr-merging problems, so we can produce better diagnostics for them.
8505 // These updates may in turn find and diagnose some ODR failures, so take
8506 // ownership of the set first.
8507 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
8508 PendingOdrMergeFailures.clear();
8509 for (auto &Merge : OdrMergeFailures) {
8510 Merge.first->buildLookup();
8511 Merge.first->decls_begin();
8512 Merge.first->bases_begin();
8513 Merge.first->vbases_begin();
8514 for (auto *RD : Merge.second) {
8521 // For each declaration from a merged context, check that the canonical
8522 // definition of that context also contains a declaration of the same
8525 // Caution: this loop does things that might invalidate iterators into
8526 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
8527 while (!PendingOdrMergeChecks.empty()) {
8528 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8530 // FIXME: Skip over implicit declarations for now. This matters for things
8531 // like implicitly-declared special member functions. This isn't entirely
8532 // correct; we can end up with multiple unmerged declarations of the same
8534 if (D->isImplicit())
8537 DeclContext *CanonDef = D->getDeclContext();
8540 const Decl *DCanon = D->getCanonicalDecl();
8542 for (auto RI : D->redecls()) {
8543 if (RI->getLexicalDeclContext() == CanonDef) {
8551 // Quick check failed, time to do the slow thing. Note, we can't just
8552 // look up the name of D in CanonDef here, because the member that is
8553 // in CanonDef might not be found by name lookup (it might have been
8554 // replaced by a more recent declaration in the lookup table), and we
8555 // can't necessarily find it in the redeclaration chain because it might
8556 // be merely mergeable, not redeclarable.
8557 llvm::SmallVector<const NamedDecl*, 4> Candidates;
8558 for (auto *CanonMember : CanonDef->decls()) {
8559 if (CanonMember->getCanonicalDecl() == DCanon) {
8560 // This can happen if the declaration is merely mergeable and not
8561 // actually redeclarable (we looked for redeclarations earlier).
8563 // FIXME: We should be able to detect this more efficiently, without
8564 // pulling in all of the members of CanonDef.
8568 if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
8569 if (ND->getDeclName() == D->getDeclName())
8570 Candidates.push_back(ND);
8574 // The AST doesn't like TagDecls becoming invalid after they've been
8575 // completed. We only really need to mark FieldDecls as invalid here.
8576 if (!isa<TagDecl>(D))
8577 D->setInvalidDecl();
8579 // Ensure we don't accidentally recursively enter deserialization while
8580 // we're producing our diagnostic.
8581 Deserializing RecursionGuard(this);
8583 std::string CanonDefModule =
8584 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
8585 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
8586 << D << getOwningModuleNameForDiagnostic(D)
8587 << CanonDef << CanonDefModule.empty() << CanonDefModule;
8589 if (Candidates.empty())
8590 Diag(cast<Decl>(CanonDef)->getLocation(),
8591 diag::note_module_odr_violation_no_possible_decls) << D;
8593 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
8594 Diag(Candidates[I]->getLocation(),
8595 diag::note_module_odr_violation_possible_decl)
8599 DiagnosedOdrMergeFailures.insert(CanonDef);
8603 if (OdrMergeFailures.empty())
8606 // Ensure we don't accidentally recursively enter deserialization while
8607 // we're producing our diagnostics.
8608 Deserializing RecursionGuard(this);
8610 // Issue any pending ODR-failure diagnostics.
8611 for (auto &Merge : OdrMergeFailures) {
8612 // If we've already pointed out a specific problem with this class, don't
8613 // bother issuing a general "something's different" diagnostic.
8614 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
8617 bool Diagnosed = false;
8618 for (auto *RD : Merge.second) {
8619 // Multiple different declarations got merged together; tell the user
8620 // where they came from.
8621 if (Merge.first != RD) {
8622 // FIXME: Walk the definition, figure out what's different,
8623 // and diagnose that.
8625 std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
8626 Diag(Merge.first->getLocation(),
8627 diag::err_module_odr_violation_different_definitions)
8628 << Merge.first << Module.empty() << Module;
8632 Diag(RD->getLocation(),
8633 diag::note_module_odr_violation_different_definitions)
8634 << getOwningModuleNameForDiagnostic(RD);
8639 // All definitions are updates to the same declaration. This happens if a
8640 // module instantiates the declaration of a class template specialization
8641 // and two or more other modules instantiate its definition.
8643 // FIXME: Indicate which modules had instantiations of this definition.
8644 // FIXME: How can this even happen?
8645 Diag(Merge.first->getLocation(),
8646 diag::err_module_odr_violation_different_instantiations)
8652 void ASTReader::StartedDeserializing() {
8653 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
8654 ReadTimer->startTimer();
8657 void ASTReader::FinishedDeserializing() {
8658 assert(NumCurrentElementsDeserializing &&
8659 "FinishedDeserializing not paired with StartedDeserializing");
8660 if (NumCurrentElementsDeserializing == 1) {
8661 // We decrease NumCurrentElementsDeserializing only after pending actions
8662 // are finished, to avoid recursively re-calling finishPendingActions().
8663 finishPendingActions();
8665 --NumCurrentElementsDeserializing;
8667 if (NumCurrentElementsDeserializing == 0) {
8668 // Propagate exception specification updates along redeclaration chains.
8669 while (!PendingExceptionSpecUpdates.empty()) {
8670 auto Updates = std::move(PendingExceptionSpecUpdates);
8671 PendingExceptionSpecUpdates.clear();
8672 for (auto Update : Updates) {
8673 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
8674 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
8675 auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
8676 if (auto *Listener = Context.getASTMutationListener())
8677 Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
8678 for (auto *Redecl : Update.second->redecls())
8679 Context.adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
8684 ReadTimer->stopTimer();
8686 diagnoseOdrViolations();
8688 // We are not in recursive loading, so it's safe to pass the "interesting"
8689 // decls to the consumer.
8691 PassInterestingDeclsToConsumer();
8695 void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
8696 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
8697 // Remove any fake results before adding any real ones.
8698 auto It = PendingFakeLookupResults.find(II);
8699 if (It != PendingFakeLookupResults.end()) {
8700 for (auto *ND : It->second)
8701 SemaObj->IdResolver.RemoveDecl(ND);
8702 // FIXME: this works around module+PCH performance issue.
8703 // Rather than erase the result from the map, which is O(n), just clear
8704 // the vector of NamedDecls.
8709 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
8710 SemaObj->TUScope->AddDecl(D);
8711 } else if (SemaObj->TUScope) {
8712 // Adding the decl to IdResolver may have failed because it was already in
8713 // (even though it was not added in scope). If it is already in, make sure
8714 // it gets in the scope as well.
8715 if (std::find(SemaObj->IdResolver.begin(Name),
8716 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
8717 SemaObj->TUScope->AddDecl(D);
8721 ASTReader::ASTReader(
8722 Preprocessor &PP, ASTContext &Context,
8723 const PCHContainerReader &PCHContainerRdr,
8724 ArrayRef<IntrusiveRefCntPtr<ModuleFileExtension>> Extensions,
8725 StringRef isysroot, bool DisableValidation,
8726 bool AllowASTWithCompilerErrors,
8727 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
8728 bool UseGlobalIndex,
8729 std::unique_ptr<llvm::Timer> ReadTimer)
8730 : Listener(DisableValidation ?
8731 cast<ASTReaderListener>(new SimpleASTReaderListener(PP)) :
8732 cast<ASTReaderListener>(new PCHValidator(PP, *this))),
8733 DeserializationListener(nullptr),
8734 OwnsDeserializationListener(false), SourceMgr(PP.getSourceManager()),
8735 FileMgr(PP.getFileManager()), PCHContainerRdr(PCHContainerRdr),
8736 Diags(PP.getDiagnostics()), SemaObj(nullptr), PP(PP), Context(Context),
8737 Consumer(nullptr), ModuleMgr(PP.getFileManager(), PCHContainerRdr),
8738 DummyIdResolver(PP),
8739 ReadTimer(std::move(ReadTimer)),
8740 PragmaMSStructState(-1),
8741 PragmaMSPointersToMembersState(-1),
8742 isysroot(isysroot), DisableValidation(DisableValidation),
8743 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
8744 AllowConfigurationMismatch(AllowConfigurationMismatch),
8745 ValidateSystemInputs(ValidateSystemInputs),
8746 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
8747 ProcessingUpdateRecords(false),
8748 CurrSwitchCaseStmts(&SwitchCaseStmts), NumSLocEntriesRead(0),
8749 TotalNumSLocEntries(0), NumStatementsRead(0), TotalNumStatements(0),
8750 NumMacrosRead(0), TotalNumMacros(0), NumIdentifierLookups(0),
8751 NumIdentifierLookupHits(0), NumSelectorsRead(0),
8752 NumMethodPoolEntriesRead(0), NumMethodPoolLookups(0),
8753 NumMethodPoolHits(0), NumMethodPoolTableLookups(0),
8754 NumMethodPoolTableHits(0), TotalNumMethodPoolEntries(0),
8755 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
8756 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
8757 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
8758 PassingDeclsToConsumer(false), ReadingKind(Read_None) {
8759 SourceMgr.setExternalSLocEntrySource(this);
8761 for (const auto &Ext : Extensions) {
8762 auto BlockName = Ext->getExtensionMetadata().BlockName;
8763 auto Known = ModuleFileExtensions.find(BlockName);
8764 if (Known != ModuleFileExtensions.end()) {
8765 Diags.Report(diag::warn_duplicate_module_file_extension)
8770 ModuleFileExtensions.insert({BlockName, Ext});
8774 ASTReader::~ASTReader() {
8775 if (OwnsDeserializationListener)
8776 delete DeserializationListener;
8779 IdentifierResolver &ASTReader::getIdResolver() {
8780 return SemaObj ? SemaObj->IdResolver : DummyIdResolver;