[clang] Handle __declspec() attributes in using
[llvm-project.git] / clang / lib / Serialization / ASTReader.cpp
blobfb723d4e46d6b56fe973dd79eb6ba83d0cf2409b
1 //===- ASTReader.cpp - AST File Reader ------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the ASTReader class, which reads AST files.
11 //===----------------------------------------------------------------------===//
13 #include "ASTCommon.h"
14 #include "ASTReaderInternals.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTMutationListener.h"
18 #include "clang/AST/ASTStructuralEquivalence.h"
19 #include "clang/AST/ASTUnresolvedSet.h"
20 #include "clang/AST/AbstractTypeReader.h"
21 #include "clang/AST/Decl.h"
22 #include "clang/AST/DeclBase.h"
23 #include "clang/AST/DeclCXX.h"
24 #include "clang/AST/DeclFriend.h"
25 #include "clang/AST/DeclGroup.h"
26 #include "clang/AST/DeclObjC.h"
27 #include "clang/AST/DeclTemplate.h"
28 #include "clang/AST/DeclarationName.h"
29 #include "clang/AST/Expr.h"
30 #include "clang/AST/ExprCXX.h"
31 #include "clang/AST/ExternalASTSource.h"
32 #include "clang/AST/NestedNameSpecifier.h"
33 #include "clang/AST/ODRDiagsEmitter.h"
34 #include "clang/AST/ODRHash.h"
35 #include "clang/AST/OpenMPClause.h"
36 #include "clang/AST/RawCommentList.h"
37 #include "clang/AST/TemplateBase.h"
38 #include "clang/AST/TemplateName.h"
39 #include "clang/AST/Type.h"
40 #include "clang/AST/TypeLoc.h"
41 #include "clang/AST/TypeLocVisitor.h"
42 #include "clang/AST/UnresolvedSet.h"
43 #include "clang/Basic/CommentOptions.h"
44 #include "clang/Basic/Diagnostic.h"
45 #include "clang/Basic/DiagnosticError.h"
46 #include "clang/Basic/DiagnosticOptions.h"
47 #include "clang/Basic/DiagnosticSema.h"
48 #include "clang/Basic/ExceptionSpecificationType.h"
49 #include "clang/Basic/FileManager.h"
50 #include "clang/Basic/FileSystemOptions.h"
51 #include "clang/Basic/IdentifierTable.h"
52 #include "clang/Basic/LLVM.h"
53 #include "clang/Basic/LangOptions.h"
54 #include "clang/Basic/Module.h"
55 #include "clang/Basic/ObjCRuntime.h"
56 #include "clang/Basic/OpenMPKinds.h"
57 #include "clang/Basic/OperatorKinds.h"
58 #include "clang/Basic/PragmaKinds.h"
59 #include "clang/Basic/Sanitizers.h"
60 #include "clang/Basic/SourceLocation.h"
61 #include "clang/Basic/SourceManager.h"
62 #include "clang/Basic/SourceManagerInternals.h"
63 #include "clang/Basic/Specifiers.h"
64 #include "clang/Basic/TargetInfo.h"
65 #include "clang/Basic/TargetOptions.h"
66 #include "clang/Basic/TokenKinds.h"
67 #include "clang/Basic/Version.h"
68 #include "clang/Lex/HeaderSearch.h"
69 #include "clang/Lex/HeaderSearchOptions.h"
70 #include "clang/Lex/MacroInfo.h"
71 #include "clang/Lex/ModuleMap.h"
72 #include "clang/Lex/PreprocessingRecord.h"
73 #include "clang/Lex/Preprocessor.h"
74 #include "clang/Lex/PreprocessorOptions.h"
75 #include "clang/Lex/Token.h"
76 #include "clang/Sema/ObjCMethodList.h"
77 #include "clang/Sema/Scope.h"
78 #include "clang/Sema/Sema.h"
79 #include "clang/Sema/Weak.h"
80 #include "clang/Serialization/ASTBitCodes.h"
81 #include "clang/Serialization/ASTDeserializationListener.h"
82 #include "clang/Serialization/ASTRecordReader.h"
83 #include "clang/Serialization/ContinuousRangeMap.h"
84 #include "clang/Serialization/GlobalModuleIndex.h"
85 #include "clang/Serialization/InMemoryModuleCache.h"
86 #include "clang/Serialization/ModuleFile.h"
87 #include "clang/Serialization/ModuleFileExtension.h"
88 #include "clang/Serialization/ModuleManager.h"
89 #include "clang/Serialization/PCHContainerOperations.h"
90 #include "clang/Serialization/SerializationDiagnostic.h"
91 #include "llvm/ADT/APFloat.h"
92 #include "llvm/ADT/APInt.h"
93 #include "llvm/ADT/APSInt.h"
94 #include "llvm/ADT/ArrayRef.h"
95 #include "llvm/ADT/DenseMap.h"
96 #include "llvm/ADT/FloatingPointMode.h"
97 #include "llvm/ADT/FoldingSet.h"
98 #include "llvm/ADT/Hashing.h"
99 #include "llvm/ADT/IntrusiveRefCntPtr.h"
100 #include "llvm/ADT/STLExtras.h"
101 #include "llvm/ADT/ScopeExit.h"
102 #include "llvm/ADT/SmallPtrSet.h"
103 #include "llvm/ADT/SmallString.h"
104 #include "llvm/ADT/SmallVector.h"
105 #include "llvm/ADT/StringExtras.h"
106 #include "llvm/ADT/StringMap.h"
107 #include "llvm/ADT/StringRef.h"
108 #include "llvm/ADT/iterator_range.h"
109 #include "llvm/Bitstream/BitstreamReader.h"
110 #include "llvm/Support/Casting.h"
111 #include "llvm/Support/Compiler.h"
112 #include "llvm/Support/Compression.h"
113 #include "llvm/Support/DJB.h"
114 #include "llvm/Support/Endian.h"
115 #include "llvm/Support/Error.h"
116 #include "llvm/Support/ErrorHandling.h"
117 #include "llvm/Support/FileSystem.h"
118 #include "llvm/Support/LEB128.h"
119 #include "llvm/Support/MemoryBuffer.h"
120 #include "llvm/Support/Path.h"
121 #include "llvm/Support/SaveAndRestore.h"
122 #include "llvm/Support/TimeProfiler.h"
123 #include "llvm/Support/Timer.h"
124 #include "llvm/Support/VersionTuple.h"
125 #include "llvm/Support/raw_ostream.h"
126 #include "llvm/TargetParser/Triple.h"
127 #include <algorithm>
128 #include <cassert>
129 #include <cstddef>
130 #include <cstdint>
131 #include <cstdio>
132 #include <ctime>
133 #include <iterator>
134 #include <limits>
135 #include <map>
136 #include <memory>
137 #include <optional>
138 #include <string>
139 #include <system_error>
140 #include <tuple>
141 #include <utility>
142 #include <vector>
144 using namespace clang;
145 using namespace clang::serialization;
146 using namespace clang::serialization::reader;
147 using llvm::BitstreamCursor;
149 //===----------------------------------------------------------------------===//
150 // ChainedASTReaderListener implementation
151 //===----------------------------------------------------------------------===//
153 bool
154 ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
155 return First->ReadFullVersionInformation(FullVersion) ||
156 Second->ReadFullVersionInformation(FullVersion);
159 void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
160 First->ReadModuleName(ModuleName);
161 Second->ReadModuleName(ModuleName);
164 void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
165 First->ReadModuleMapFile(ModuleMapPath);
166 Second->ReadModuleMapFile(ModuleMapPath);
169 bool
170 ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
171 bool Complain,
172 bool AllowCompatibleDifferences) {
173 return First->ReadLanguageOptions(LangOpts, Complain,
174 AllowCompatibleDifferences) ||
175 Second->ReadLanguageOptions(LangOpts, Complain,
176 AllowCompatibleDifferences);
179 bool ChainedASTReaderListener::ReadTargetOptions(
180 const TargetOptions &TargetOpts, bool Complain,
181 bool AllowCompatibleDifferences) {
182 return First->ReadTargetOptions(TargetOpts, Complain,
183 AllowCompatibleDifferences) ||
184 Second->ReadTargetOptions(TargetOpts, Complain,
185 AllowCompatibleDifferences);
188 bool ChainedASTReaderListener::ReadDiagnosticOptions(
189 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
190 return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
191 Second->ReadDiagnosticOptions(DiagOpts, Complain);
194 bool
195 ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
196 bool Complain) {
197 return First->ReadFileSystemOptions(FSOpts, Complain) ||
198 Second->ReadFileSystemOptions(FSOpts, Complain);
201 bool ChainedASTReaderListener::ReadHeaderSearchOptions(
202 const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath,
203 bool Complain) {
204 return First->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
205 Complain) ||
206 Second->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
207 Complain);
210 bool ChainedASTReaderListener::ReadPreprocessorOptions(
211 const PreprocessorOptions &PPOpts, bool Complain,
212 std::string &SuggestedPredefines) {
213 return First->ReadPreprocessorOptions(PPOpts, Complain,
214 SuggestedPredefines) ||
215 Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
218 void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
219 unsigned Value) {
220 First->ReadCounter(M, Value);
221 Second->ReadCounter(M, Value);
224 bool ChainedASTReaderListener::needsInputFileVisitation() {
225 return First->needsInputFileVisitation() ||
226 Second->needsInputFileVisitation();
229 bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
230 return First->needsSystemInputFileVisitation() ||
231 Second->needsSystemInputFileVisitation();
234 void ChainedASTReaderListener::visitModuleFile(StringRef Filename,
235 ModuleKind Kind) {
236 First->visitModuleFile(Filename, Kind);
237 Second->visitModuleFile(Filename, Kind);
240 bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
241 bool isSystem,
242 bool isOverridden,
243 bool isExplicitModule) {
244 bool Continue = false;
245 if (First->needsInputFileVisitation() &&
246 (!isSystem || First->needsSystemInputFileVisitation()))
247 Continue |= First->visitInputFile(Filename, isSystem, isOverridden,
248 isExplicitModule);
249 if (Second->needsInputFileVisitation() &&
250 (!isSystem || Second->needsSystemInputFileVisitation()))
251 Continue |= Second->visitInputFile(Filename, isSystem, isOverridden,
252 isExplicitModule);
253 return Continue;
256 void ChainedASTReaderListener::readModuleFileExtension(
257 const ModuleFileExtensionMetadata &Metadata) {
258 First->readModuleFileExtension(Metadata);
259 Second->readModuleFileExtension(Metadata);
262 //===----------------------------------------------------------------------===//
263 // PCH validator implementation
264 //===----------------------------------------------------------------------===//
266 ASTReaderListener::~ASTReaderListener() = default;
268 /// Compare the given set of language options against an existing set of
269 /// language options.
271 /// \param Diags If non-NULL, diagnostics will be emitted via this engine.
272 /// \param AllowCompatibleDifferences If true, differences between compatible
273 /// language options will be permitted.
275 /// \returns true if the languagae options mis-match, false otherwise.
276 static bool checkLanguageOptions(const LangOptions &LangOpts,
277 const LangOptions &ExistingLangOpts,
278 DiagnosticsEngine *Diags,
279 bool AllowCompatibleDifferences = true) {
280 #define LANGOPT(Name, Bits, Default, Description) \
281 if (ExistingLangOpts.Name != LangOpts.Name) { \
282 if (Diags) \
283 Diags->Report(diag::err_pch_langopt_mismatch) \
284 << Description << LangOpts.Name << ExistingLangOpts.Name; \
285 return true; \
288 #define VALUE_LANGOPT(Name, Bits, Default, Description) \
289 if (ExistingLangOpts.Name != LangOpts.Name) { \
290 if (Diags) \
291 Diags->Report(diag::err_pch_langopt_value_mismatch) \
292 << Description; \
293 return true; \
296 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
297 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
298 if (Diags) \
299 Diags->Report(diag::err_pch_langopt_value_mismatch) \
300 << Description; \
301 return true; \
304 #define COMPATIBLE_LANGOPT(Name, Bits, Default, Description) \
305 if (!AllowCompatibleDifferences) \
306 LANGOPT(Name, Bits, Default, Description)
308 #define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description) \
309 if (!AllowCompatibleDifferences) \
310 ENUM_LANGOPT(Name, Bits, Default, Description)
312 #define COMPATIBLE_VALUE_LANGOPT(Name, Bits, Default, Description) \
313 if (!AllowCompatibleDifferences) \
314 VALUE_LANGOPT(Name, Bits, Default, Description)
316 #define BENIGN_LANGOPT(Name, Bits, Default, Description)
317 #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
318 #define BENIGN_VALUE_LANGOPT(Name, Bits, Default, Description)
319 #include "clang/Basic/LangOptions.def"
321 if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) {
322 if (Diags)
323 Diags->Report(diag::err_pch_langopt_value_mismatch) << "module features";
324 return true;
327 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
328 if (Diags)
329 Diags->Report(diag::err_pch_langopt_value_mismatch)
330 << "target Objective-C runtime";
331 return true;
334 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
335 LangOpts.CommentOpts.BlockCommandNames) {
336 if (Diags)
337 Diags->Report(diag::err_pch_langopt_value_mismatch)
338 << "block command names";
339 return true;
342 // Sanitizer feature mismatches are treated as compatible differences. If
343 // compatible differences aren't allowed, we still only want to check for
344 // mismatches of non-modular sanitizers (the only ones which can affect AST
345 // generation).
346 if (!AllowCompatibleDifferences) {
347 SanitizerMask ModularSanitizers = getPPTransparentSanitizers();
348 SanitizerSet ExistingSanitizers = ExistingLangOpts.Sanitize;
349 SanitizerSet ImportedSanitizers = LangOpts.Sanitize;
350 ExistingSanitizers.clear(ModularSanitizers);
351 ImportedSanitizers.clear(ModularSanitizers);
352 if (ExistingSanitizers.Mask != ImportedSanitizers.Mask) {
353 const std::string Flag = "-fsanitize=";
354 if (Diags) {
355 #define SANITIZER(NAME, ID) \
357 bool InExistingModule = ExistingSanitizers.has(SanitizerKind::ID); \
358 bool InImportedModule = ImportedSanitizers.has(SanitizerKind::ID); \
359 if (InExistingModule != InImportedModule) \
360 Diags->Report(diag::err_pch_targetopt_feature_mismatch) \
361 << InExistingModule << (Flag + NAME); \
363 #include "clang/Basic/Sanitizers.def"
365 return true;
369 return false;
372 /// Compare the given set of target options against an existing set of
373 /// target options.
375 /// \param Diags If non-NULL, diagnostics will be emitted via this engine.
377 /// \returns true if the target options mis-match, false otherwise.
378 static bool checkTargetOptions(const TargetOptions &TargetOpts,
379 const TargetOptions &ExistingTargetOpts,
380 DiagnosticsEngine *Diags,
381 bool AllowCompatibleDifferences = true) {
382 #define CHECK_TARGET_OPT(Field, Name) \
383 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
384 if (Diags) \
385 Diags->Report(diag::err_pch_targetopt_mismatch) \
386 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
387 return true; \
390 // The triple and ABI must match exactly.
391 CHECK_TARGET_OPT(Triple, "target");
392 CHECK_TARGET_OPT(ABI, "target ABI");
394 // We can tolerate different CPUs in many cases, notably when one CPU
395 // supports a strict superset of another. When allowing compatible
396 // differences skip this check.
397 if (!AllowCompatibleDifferences) {
398 CHECK_TARGET_OPT(CPU, "target CPU");
399 CHECK_TARGET_OPT(TuneCPU, "tune CPU");
402 #undef CHECK_TARGET_OPT
404 // Compare feature sets.
405 SmallVector<StringRef, 4> ExistingFeatures(
406 ExistingTargetOpts.FeaturesAsWritten.begin(),
407 ExistingTargetOpts.FeaturesAsWritten.end());
408 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
409 TargetOpts.FeaturesAsWritten.end());
410 llvm::sort(ExistingFeatures);
411 llvm::sort(ReadFeatures);
413 // We compute the set difference in both directions explicitly so that we can
414 // diagnose the differences differently.
415 SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
416 std::set_difference(
417 ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
418 ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
419 std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
420 ExistingFeatures.begin(), ExistingFeatures.end(),
421 std::back_inserter(UnmatchedReadFeatures));
423 // If we are allowing compatible differences and the read feature set is
424 // a strict subset of the existing feature set, there is nothing to diagnose.
425 if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
426 return false;
428 if (Diags) {
429 for (StringRef Feature : UnmatchedReadFeatures)
430 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
431 << /* is-existing-feature */ false << Feature;
432 for (StringRef Feature : UnmatchedExistingFeatures)
433 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
434 << /* is-existing-feature */ true << Feature;
437 return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
440 bool
441 PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
442 bool Complain,
443 bool AllowCompatibleDifferences) {
444 const LangOptions &ExistingLangOpts = PP.getLangOpts();
445 return checkLanguageOptions(LangOpts, ExistingLangOpts,
446 Complain ? &Reader.Diags : nullptr,
447 AllowCompatibleDifferences);
450 bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
451 bool Complain,
452 bool AllowCompatibleDifferences) {
453 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
454 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
455 Complain ? &Reader.Diags : nullptr,
456 AllowCompatibleDifferences);
459 namespace {
461 using MacroDefinitionsMap =
462 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>;
463 using DeclsMap = llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8>>;
465 } // namespace
467 static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
468 DiagnosticsEngine &Diags,
469 bool Complain) {
470 using Level = DiagnosticsEngine::Level;
472 // Check current mappings for new -Werror mappings, and the stored mappings
473 // for cases that were explicitly mapped to *not* be errors that are now
474 // errors because of options like -Werror.
475 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
477 for (DiagnosticsEngine *MappingSource : MappingSources) {
478 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
479 diag::kind DiagID = DiagIDMappingPair.first;
480 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
481 if (CurLevel < DiagnosticsEngine::Error)
482 continue; // not significant
483 Level StoredLevel =
484 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
485 if (StoredLevel < DiagnosticsEngine::Error) {
486 if (Complain)
487 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
488 Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
489 return true;
494 return false;
497 static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
498 diag::Severity Ext = Diags.getExtensionHandlingBehavior();
499 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
500 return true;
501 return Ext >= diag::Severity::Error;
504 static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
505 DiagnosticsEngine &Diags,
506 bool IsSystem, bool Complain) {
507 // Top-level options
508 if (IsSystem) {
509 if (Diags.getSuppressSystemWarnings())
510 return false;
511 // If -Wsystem-headers was not enabled before, be conservative
512 if (StoredDiags.getSuppressSystemWarnings()) {
513 if (Complain)
514 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
515 return true;
519 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
520 if (Complain)
521 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
522 return true;
525 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
526 !StoredDiags.getEnableAllWarnings()) {
527 if (Complain)
528 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
529 return true;
532 if (isExtHandlingFromDiagsError(Diags) &&
533 !isExtHandlingFromDiagsError(StoredDiags)) {
534 if (Complain)
535 Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
536 return true;
539 return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
542 /// Return the top import module if it is implicit, nullptr otherwise.
543 static Module *getTopImportImplicitModule(ModuleManager &ModuleMgr,
544 Preprocessor &PP) {
545 // If the original import came from a file explicitly generated by the user,
546 // don't check the diagnostic mappings.
547 // FIXME: currently this is approximated by checking whether this is not a
548 // module import of an implicitly-loaded module file.
549 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
550 // the transitive closure of its imports, since unrelated modules cannot be
551 // imported until after this module finishes validation.
552 ModuleFile *TopImport = &*ModuleMgr.rbegin();
553 while (!TopImport->ImportedBy.empty())
554 TopImport = TopImport->ImportedBy[0];
555 if (TopImport->Kind != MK_ImplicitModule)
556 return nullptr;
558 StringRef ModuleName = TopImport->ModuleName;
559 assert(!ModuleName.empty() && "diagnostic options read before module name");
561 Module *M =
562 PP.getHeaderSearchInfo().lookupModule(ModuleName, TopImport->ImportLoc);
563 assert(M && "missing module");
564 return M;
567 bool PCHValidator::ReadDiagnosticOptions(
568 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
569 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
570 IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
571 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
572 new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
573 // This should never fail, because we would have processed these options
574 // before writing them to an ASTFile.
575 ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
577 ModuleManager &ModuleMgr = Reader.getModuleManager();
578 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
580 Module *TopM = getTopImportImplicitModule(ModuleMgr, PP);
581 if (!TopM)
582 return false;
584 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
585 // contains the union of their flags.
586 return checkDiagnosticMappings(*Diags, ExistingDiags, TopM->IsSystem,
587 Complain);
590 /// Collect the macro definitions provided by the given preprocessor
591 /// options.
592 static void
593 collectMacroDefinitions(const PreprocessorOptions &PPOpts,
594 MacroDefinitionsMap &Macros,
595 SmallVectorImpl<StringRef> *MacroNames = nullptr) {
596 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
597 StringRef Macro = PPOpts.Macros[I].first;
598 bool IsUndef = PPOpts.Macros[I].second;
600 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
601 StringRef MacroName = MacroPair.first;
602 StringRef MacroBody = MacroPair.second;
604 // For an #undef'd macro, we only care about the name.
605 if (IsUndef) {
606 if (MacroNames && !Macros.count(MacroName))
607 MacroNames->push_back(MacroName);
609 Macros[MacroName] = std::make_pair("", true);
610 continue;
613 // For a #define'd macro, figure out the actual definition.
614 if (MacroName.size() == Macro.size())
615 MacroBody = "1";
616 else {
617 // Note: GCC drops anything following an end-of-line character.
618 StringRef::size_type End = MacroBody.find_first_of("\n\r");
619 MacroBody = MacroBody.substr(0, End);
622 if (MacroNames && !Macros.count(MacroName))
623 MacroNames->push_back(MacroName);
624 Macros[MacroName] = std::make_pair(MacroBody, false);
628 enum OptionValidation {
629 OptionValidateNone,
630 OptionValidateContradictions,
631 OptionValidateStrictMatches,
634 /// Check the preprocessor options deserialized from the control block
635 /// against the preprocessor options in an existing preprocessor.
637 /// \param Diags If non-null, produce diagnostics for any mismatches incurred.
638 /// \param Validation If set to OptionValidateNone, ignore differences in
639 /// preprocessor options. If set to OptionValidateContradictions,
640 /// require that options passed both in the AST file and on the command
641 /// line (-D or -U) match, but tolerate options missing in one or the
642 /// other. If set to OptionValidateContradictions, require that there
643 /// are no differences in the options between the two.
644 static bool checkPreprocessorOptions(
645 const PreprocessorOptions &PPOpts,
646 const PreprocessorOptions &ExistingPPOpts, DiagnosticsEngine *Diags,
647 FileManager &FileMgr, std::string &SuggestedPredefines,
648 const LangOptions &LangOpts,
649 OptionValidation Validation = OptionValidateContradictions) {
650 // Check macro definitions.
651 MacroDefinitionsMap ASTFileMacros;
652 collectMacroDefinitions(PPOpts, ASTFileMacros);
653 MacroDefinitionsMap ExistingMacros;
654 SmallVector<StringRef, 4> ExistingMacroNames;
655 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
657 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
658 // Dig out the macro definition in the existing preprocessor options.
659 StringRef MacroName = ExistingMacroNames[I];
660 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
662 // Check whether we know anything about this macro name or not.
663 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>::iterator Known =
664 ASTFileMacros.find(MacroName);
665 if (Validation == OptionValidateNone || Known == ASTFileMacros.end()) {
666 if (Validation == OptionValidateStrictMatches) {
667 // If strict matches are requested, don't tolerate any extra defines on
668 // the command line that are missing in the AST file.
669 if (Diags) {
670 Diags->Report(diag::err_pch_macro_def_undef) << MacroName << true;
672 return true;
674 // FIXME: Check whether this identifier was referenced anywhere in the
675 // AST file. If so, we should reject the AST file. Unfortunately, this
676 // information isn't in the control block. What shall we do about it?
678 if (Existing.second) {
679 SuggestedPredefines += "#undef ";
680 SuggestedPredefines += MacroName.str();
681 SuggestedPredefines += '\n';
682 } else {
683 SuggestedPredefines += "#define ";
684 SuggestedPredefines += MacroName.str();
685 SuggestedPredefines += ' ';
686 SuggestedPredefines += Existing.first.str();
687 SuggestedPredefines += '\n';
689 continue;
692 // If the macro was defined in one but undef'd in the other, we have a
693 // conflict.
694 if (Existing.second != Known->second.second) {
695 if (Diags) {
696 Diags->Report(diag::err_pch_macro_def_undef)
697 << MacroName << Known->second.second;
699 return true;
702 // If the macro was #undef'd in both, or if the macro bodies are identical,
703 // it's fine.
704 if (Existing.second || Existing.first == Known->second.first) {
705 ASTFileMacros.erase(Known);
706 continue;
709 // The macro bodies differ; complain.
710 if (Diags) {
711 Diags->Report(diag::err_pch_macro_def_conflict)
712 << MacroName << Known->second.first << Existing.first;
714 return true;
716 if (Validation == OptionValidateStrictMatches) {
717 // If strict matches are requested, don't tolerate any extra defines in
718 // the AST file that are missing on the command line.
719 for (const auto &MacroName : ASTFileMacros.keys()) {
720 if (Diags) {
721 Diags->Report(diag::err_pch_macro_def_undef) << MacroName << false;
723 return true;
727 // Check whether we're using predefines.
728 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines &&
729 Validation != OptionValidateNone) {
730 if (Diags) {
731 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
733 return true;
736 // Detailed record is important since it is used for the module cache hash.
737 if (LangOpts.Modules &&
738 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord &&
739 Validation != OptionValidateNone) {
740 if (Diags) {
741 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
743 return true;
746 // Compute the #include and #include_macros lines we need.
747 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
748 StringRef File = ExistingPPOpts.Includes[I];
750 if (!ExistingPPOpts.ImplicitPCHInclude.empty() &&
751 !ExistingPPOpts.PCHThroughHeader.empty()) {
752 // In case the through header is an include, we must add all the includes
753 // to the predefines so the start point can be determined.
754 SuggestedPredefines += "#include \"";
755 SuggestedPredefines += File;
756 SuggestedPredefines += "\"\n";
757 continue;
760 if (File == ExistingPPOpts.ImplicitPCHInclude)
761 continue;
763 if (llvm::is_contained(PPOpts.Includes, File))
764 continue;
766 SuggestedPredefines += "#include \"";
767 SuggestedPredefines += File;
768 SuggestedPredefines += "\"\n";
771 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
772 StringRef File = ExistingPPOpts.MacroIncludes[I];
773 if (llvm::is_contained(PPOpts.MacroIncludes, File))
774 continue;
776 SuggestedPredefines += "#__include_macros \"";
777 SuggestedPredefines += File;
778 SuggestedPredefines += "\"\n##\n";
781 return false;
784 bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
785 bool Complain,
786 std::string &SuggestedPredefines) {
787 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
789 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
790 Complain? &Reader.Diags : nullptr,
791 PP.getFileManager(),
792 SuggestedPredefines,
793 PP.getLangOpts());
796 bool SimpleASTReaderListener::ReadPreprocessorOptions(
797 const PreprocessorOptions &PPOpts,
798 bool Complain,
799 std::string &SuggestedPredefines) {
800 return checkPreprocessorOptions(PPOpts, PP.getPreprocessorOpts(), nullptr,
801 PP.getFileManager(), SuggestedPredefines,
802 PP.getLangOpts(), OptionValidateNone);
805 /// Check the header search options deserialized from the control block
806 /// against the header search options in an existing preprocessor.
808 /// \param Diags If non-null, produce diagnostics for any mismatches incurred.
809 static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
810 StringRef SpecificModuleCachePath,
811 StringRef ExistingModuleCachePath,
812 DiagnosticsEngine *Diags,
813 const LangOptions &LangOpts,
814 const PreprocessorOptions &PPOpts) {
815 if (LangOpts.Modules) {
816 if (SpecificModuleCachePath != ExistingModuleCachePath &&
817 !PPOpts.AllowPCHWithDifferentModulesCachePath) {
818 if (Diags)
819 Diags->Report(diag::err_pch_modulecache_mismatch)
820 << SpecificModuleCachePath << ExistingModuleCachePath;
821 return true;
825 return false;
828 bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
829 StringRef SpecificModuleCachePath,
830 bool Complain) {
831 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
832 PP.getHeaderSearchInfo().getModuleCachePath(),
833 Complain ? &Reader.Diags : nullptr,
834 PP.getLangOpts(), PP.getPreprocessorOpts());
837 void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
838 PP.setCounterValue(Value);
841 //===----------------------------------------------------------------------===//
842 // AST reader implementation
843 //===----------------------------------------------------------------------===//
845 static uint64_t readULEB(const unsigned char *&P) {
846 unsigned Length = 0;
847 const char *Error = nullptr;
849 uint64_t Val = llvm::decodeULEB128(P, &Length, nullptr, &Error);
850 if (Error)
851 llvm::report_fatal_error(Error);
852 P += Length;
853 return Val;
856 /// Read ULEB-encoded key length and data length.
857 static std::pair<unsigned, unsigned>
858 readULEBKeyDataLength(const unsigned char *&P) {
859 unsigned KeyLen = readULEB(P);
860 if ((unsigned)KeyLen != KeyLen)
861 llvm::report_fatal_error("key too large");
863 unsigned DataLen = readULEB(P);
864 if ((unsigned)DataLen != DataLen)
865 llvm::report_fatal_error("data too large");
867 return std::make_pair(KeyLen, DataLen);
870 void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
871 bool TakeOwnership) {
872 DeserializationListener = Listener;
873 OwnsDeserializationListener = TakeOwnership;
876 unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
877 return serialization::ComputeHash(Sel);
880 std::pair<unsigned, unsigned>
881 ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
882 return readULEBKeyDataLength(d);
885 ASTSelectorLookupTrait::internal_key_type
886 ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
887 using namespace llvm::support;
889 SelectorTable &SelTable = Reader.getContext().Selectors;
890 unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
891 IdentifierInfo *FirstII = Reader.getLocalIdentifier(
892 F, endian::readNext<uint32_t, little, unaligned>(d));
893 if (N == 0)
894 return SelTable.getNullarySelector(FirstII);
895 else if (N == 1)
896 return SelTable.getUnarySelector(FirstII);
898 SmallVector<IdentifierInfo *, 16> Args;
899 Args.push_back(FirstII);
900 for (unsigned I = 1; I != N; ++I)
901 Args.push_back(Reader.getLocalIdentifier(
902 F, endian::readNext<uint32_t, little, unaligned>(d)));
904 return SelTable.getSelector(N, Args.data());
907 ASTSelectorLookupTrait::data_type
908 ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
909 unsigned DataLen) {
910 using namespace llvm::support;
912 data_type Result;
914 Result.ID = Reader.getGlobalSelectorID(
915 F, endian::readNext<uint32_t, little, unaligned>(d));
916 unsigned FullInstanceBits = endian::readNext<uint16_t, little, unaligned>(d);
917 unsigned FullFactoryBits = endian::readNext<uint16_t, little, unaligned>(d);
918 Result.InstanceBits = FullInstanceBits & 0x3;
919 Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
920 Result.FactoryBits = FullFactoryBits & 0x3;
921 Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
922 unsigned NumInstanceMethods = FullInstanceBits >> 3;
923 unsigned NumFactoryMethods = FullFactoryBits >> 3;
925 // Load instance methods
926 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
927 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
928 F, endian::readNext<uint32_t, little, unaligned>(d)))
929 Result.Instance.push_back(Method);
932 // Load factory methods
933 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
934 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
935 F, endian::readNext<uint32_t, little, unaligned>(d)))
936 Result.Factory.push_back(Method);
939 return Result;
942 unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
943 return llvm::djbHash(a);
946 std::pair<unsigned, unsigned>
947 ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
948 return readULEBKeyDataLength(d);
951 ASTIdentifierLookupTraitBase::internal_key_type
952 ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
953 assert(n >= 2 && d[n-1] == '\0');
954 return StringRef((const char*) d, n-1);
957 /// Whether the given identifier is "interesting".
958 static bool isInterestingIdentifier(ASTReader &Reader, IdentifierInfo &II,
959 bool IsModule) {
960 return II.hadMacroDefinition() || II.isPoisoned() ||
961 (!IsModule && II.getObjCOrBuiltinID()) ||
962 II.hasRevertedTokenIDToIdentifier() ||
963 (!(IsModule && Reader.getPreprocessor().getLangOpts().CPlusPlus) &&
964 II.getFETokenInfo());
967 static bool readBit(unsigned &Bits) {
968 bool Value = Bits & 0x1;
969 Bits >>= 1;
970 return Value;
973 IdentID ASTIdentifierLookupTrait::ReadIdentifierID(const unsigned char *d) {
974 using namespace llvm::support;
976 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
977 return Reader.getGlobalIdentifierID(F, RawID >> 1);
980 static void markIdentifierFromAST(ASTReader &Reader, IdentifierInfo &II) {
981 if (!II.isFromAST()) {
982 II.setIsFromAST();
983 bool IsModule = Reader.getPreprocessor().getCurrentModule() != nullptr;
984 if (isInterestingIdentifier(Reader, II, IsModule))
985 II.setChangedSinceDeserialization();
989 IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
990 const unsigned char* d,
991 unsigned DataLen) {
992 using namespace llvm::support;
994 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
995 bool IsInteresting = RawID & 0x01;
997 // Wipe out the "is interesting" bit.
998 RawID = RawID >> 1;
1000 // Build the IdentifierInfo and link the identifier ID with it.
1001 IdentifierInfo *II = KnownII;
1002 if (!II) {
1003 II = &Reader.getIdentifierTable().getOwn(k);
1004 KnownII = II;
1006 markIdentifierFromAST(Reader, *II);
1007 Reader.markIdentifierUpToDate(II);
1009 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
1010 if (!IsInteresting) {
1011 // For uninteresting identifiers, there's nothing else to do. Just notify
1012 // the reader that we've finished loading this identifier.
1013 Reader.SetIdentifierInfo(ID, II);
1014 return II;
1017 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
1018 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
1019 bool CPlusPlusOperatorKeyword = readBit(Bits);
1020 bool HasRevertedTokenIDToIdentifier = readBit(Bits);
1021 bool Poisoned = readBit(Bits);
1022 bool ExtensionToken = readBit(Bits);
1023 bool HadMacroDefinition = readBit(Bits);
1025 assert(Bits == 0 && "Extra bits in the identifier?");
1026 DataLen -= 8;
1028 // Set or check the various bits in the IdentifierInfo structure.
1029 // Token IDs are read-only.
1030 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
1031 II->revertTokenIDToIdentifier();
1032 if (!F.isModule())
1033 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
1034 assert(II->isExtensionToken() == ExtensionToken &&
1035 "Incorrect extension token flag");
1036 (void)ExtensionToken;
1037 if (Poisoned)
1038 II->setIsPoisoned(true);
1039 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
1040 "Incorrect C++ operator keyword flag");
1041 (void)CPlusPlusOperatorKeyword;
1043 // If this identifier is a macro, deserialize the macro
1044 // definition.
1045 if (HadMacroDefinition) {
1046 uint32_t MacroDirectivesOffset =
1047 endian::readNext<uint32_t, little, unaligned>(d);
1048 DataLen -= 4;
1050 Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
1053 Reader.SetIdentifierInfo(ID, II);
1055 // Read all of the declarations visible at global scope with this
1056 // name.
1057 if (DataLen > 0) {
1058 SmallVector<uint32_t, 4> DeclIDs;
1059 for (; DataLen > 0; DataLen -= 4)
1060 DeclIDs.push_back(Reader.getGlobalDeclID(
1061 F, endian::readNext<uint32_t, little, unaligned>(d)));
1062 Reader.SetGloballyVisibleDecls(II, DeclIDs);
1065 return II;
1068 DeclarationNameKey::DeclarationNameKey(DeclarationName Name)
1069 : Kind(Name.getNameKind()) {
1070 switch (Kind) {
1071 case DeclarationName::Identifier:
1072 Data = (uint64_t)Name.getAsIdentifierInfo();
1073 break;
1074 case DeclarationName::ObjCZeroArgSelector:
1075 case DeclarationName::ObjCOneArgSelector:
1076 case DeclarationName::ObjCMultiArgSelector:
1077 Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
1078 break;
1079 case DeclarationName::CXXOperatorName:
1080 Data = Name.getCXXOverloadedOperator();
1081 break;
1082 case DeclarationName::CXXLiteralOperatorName:
1083 Data = (uint64_t)Name.getCXXLiteralIdentifier();
1084 break;
1085 case DeclarationName::CXXDeductionGuideName:
1086 Data = (uint64_t)Name.getCXXDeductionGuideTemplate()
1087 ->getDeclName().getAsIdentifierInfo();
1088 break;
1089 case DeclarationName::CXXConstructorName:
1090 case DeclarationName::CXXDestructorName:
1091 case DeclarationName::CXXConversionFunctionName:
1092 case DeclarationName::CXXUsingDirective:
1093 Data = 0;
1094 break;
1098 unsigned DeclarationNameKey::getHash() const {
1099 llvm::FoldingSetNodeID ID;
1100 ID.AddInteger(Kind);
1102 switch (Kind) {
1103 case DeclarationName::Identifier:
1104 case DeclarationName::CXXLiteralOperatorName:
1105 case DeclarationName::CXXDeductionGuideName:
1106 ID.AddString(((IdentifierInfo*)Data)->getName());
1107 break;
1108 case DeclarationName::ObjCZeroArgSelector:
1109 case DeclarationName::ObjCOneArgSelector:
1110 case DeclarationName::ObjCMultiArgSelector:
1111 ID.AddInteger(serialization::ComputeHash(Selector(Data)));
1112 break;
1113 case DeclarationName::CXXOperatorName:
1114 ID.AddInteger((OverloadedOperatorKind)Data);
1115 break;
1116 case DeclarationName::CXXConstructorName:
1117 case DeclarationName::CXXDestructorName:
1118 case DeclarationName::CXXConversionFunctionName:
1119 case DeclarationName::CXXUsingDirective:
1120 break;
1123 return ID.ComputeHash();
1126 ModuleFile *
1127 ASTDeclContextNameLookupTrait::ReadFileRef(const unsigned char *&d) {
1128 using namespace llvm::support;
1130 uint32_t ModuleFileID = endian::readNext<uint32_t, little, unaligned>(d);
1131 return Reader.getLocalModuleFile(F, ModuleFileID);
1134 std::pair<unsigned, unsigned>
1135 ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char *&d) {
1136 return readULEBKeyDataLength(d);
1139 ASTDeclContextNameLookupTrait::internal_key_type
1140 ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
1141 using namespace llvm::support;
1143 auto Kind = (DeclarationName::NameKind)*d++;
1144 uint64_t Data;
1145 switch (Kind) {
1146 case DeclarationName::Identifier:
1147 case DeclarationName::CXXLiteralOperatorName:
1148 case DeclarationName::CXXDeductionGuideName:
1149 Data = (uint64_t)Reader.getLocalIdentifier(
1150 F, endian::readNext<uint32_t, little, unaligned>(d));
1151 break;
1152 case DeclarationName::ObjCZeroArgSelector:
1153 case DeclarationName::ObjCOneArgSelector:
1154 case DeclarationName::ObjCMultiArgSelector:
1155 Data =
1156 (uint64_t)Reader.getLocalSelector(
1157 F, endian::readNext<uint32_t, little, unaligned>(
1158 d)).getAsOpaquePtr();
1159 break;
1160 case DeclarationName::CXXOperatorName:
1161 Data = *d++; // OverloadedOperatorKind
1162 break;
1163 case DeclarationName::CXXConstructorName:
1164 case DeclarationName::CXXDestructorName:
1165 case DeclarationName::CXXConversionFunctionName:
1166 case DeclarationName::CXXUsingDirective:
1167 Data = 0;
1168 break;
1171 return DeclarationNameKey(Kind, Data);
1174 void ASTDeclContextNameLookupTrait::ReadDataInto(internal_key_type,
1175 const unsigned char *d,
1176 unsigned DataLen,
1177 data_type_builder &Val) {
1178 using namespace llvm::support;
1180 for (unsigned NumDecls = DataLen / 4; NumDecls; --NumDecls) {
1181 uint32_t LocalID = endian::readNext<uint32_t, little, unaligned>(d);
1182 Val.insert(Reader.getGlobalDeclID(F, LocalID));
1186 bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
1187 BitstreamCursor &Cursor,
1188 uint64_t Offset,
1189 DeclContext *DC) {
1190 assert(Offset != 0);
1192 SavedStreamPosition SavedPosition(Cursor);
1193 if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1194 Error(std::move(Err));
1195 return true;
1198 RecordData Record;
1199 StringRef Blob;
1200 Expected<unsigned> MaybeCode = Cursor.ReadCode();
1201 if (!MaybeCode) {
1202 Error(MaybeCode.takeError());
1203 return true;
1205 unsigned Code = MaybeCode.get();
1207 Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
1208 if (!MaybeRecCode) {
1209 Error(MaybeRecCode.takeError());
1210 return true;
1212 unsigned RecCode = MaybeRecCode.get();
1213 if (RecCode != DECL_CONTEXT_LEXICAL) {
1214 Error("Expected lexical block");
1215 return true;
1218 assert(!isa<TranslationUnitDecl>(DC) &&
1219 "expected a TU_UPDATE_LEXICAL record for TU");
1220 // If we are handling a C++ class template instantiation, we can see multiple
1221 // lexical updates for the same record. It's important that we select only one
1222 // of them, so that field numbering works properly. Just pick the first one we
1223 // see.
1224 auto &Lex = LexicalDecls[DC];
1225 if (!Lex.first) {
1226 Lex = std::make_pair(
1227 &M, llvm::ArrayRef(
1228 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
1229 Blob.data()),
1230 Blob.size() / 4));
1232 DC->setHasExternalLexicalStorage(true);
1233 return false;
1236 bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M,
1237 BitstreamCursor &Cursor,
1238 uint64_t Offset,
1239 DeclID ID) {
1240 assert(Offset != 0);
1242 SavedStreamPosition SavedPosition(Cursor);
1243 if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1244 Error(std::move(Err));
1245 return true;
1248 RecordData Record;
1249 StringRef Blob;
1250 Expected<unsigned> MaybeCode = Cursor.ReadCode();
1251 if (!MaybeCode) {
1252 Error(MaybeCode.takeError());
1253 return true;
1255 unsigned Code = MaybeCode.get();
1257 Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
1258 if (!MaybeRecCode) {
1259 Error(MaybeRecCode.takeError());
1260 return true;
1262 unsigned RecCode = MaybeRecCode.get();
1263 if (RecCode != DECL_CONTEXT_VISIBLE) {
1264 Error("Expected visible lookup table block");
1265 return true;
1268 // We can't safely determine the primary context yet, so delay attaching the
1269 // lookup table until we're done with recursive deserialization.
1270 auto *Data = (const unsigned char*)Blob.data();
1271 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&M, Data});
1272 return false;
1275 void ASTReader::Error(StringRef Msg) const {
1276 Error(diag::err_fe_pch_malformed, Msg);
1277 if (PP.getLangOpts().Modules && !Diags.isDiagnosticInFlight() &&
1278 !PP.getHeaderSearchInfo().getModuleCachePath().empty()) {
1279 Diag(diag::note_module_cache_path)
1280 << PP.getHeaderSearchInfo().getModuleCachePath();
1284 void ASTReader::Error(unsigned DiagID, StringRef Arg1, StringRef Arg2,
1285 StringRef Arg3) const {
1286 if (Diags.isDiagnosticInFlight())
1287 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2, Arg3);
1288 else
1289 Diag(DiagID) << Arg1 << Arg2 << Arg3;
1292 void ASTReader::Error(llvm::Error &&Err) const {
1293 llvm::Error RemainingErr =
1294 handleErrors(std::move(Err), [this](const DiagnosticError &E) {
1295 auto Diag = E.getDiagnostic().second;
1297 // Ideally we'd just emit it, but have to handle a possible in-flight
1298 // diagnostic. Note that the location is currently ignored as well.
1299 auto NumArgs = Diag.getStorage()->NumDiagArgs;
1300 assert(NumArgs <= 3 && "Can only have up to 3 arguments");
1301 StringRef Arg1, Arg2, Arg3;
1302 switch (NumArgs) {
1303 case 3:
1304 Arg3 = Diag.getStringArg(2);
1305 [[fallthrough]];
1306 case 2:
1307 Arg2 = Diag.getStringArg(1);
1308 [[fallthrough]];
1309 case 1:
1310 Arg1 = Diag.getStringArg(0);
1312 Error(Diag.getDiagID(), Arg1, Arg2, Arg3);
1314 if (RemainingErr)
1315 Error(toString(std::move(RemainingErr)));
1318 //===----------------------------------------------------------------------===//
1319 // Source Manager Deserialization
1320 //===----------------------------------------------------------------------===//
1322 /// Read the line table in the source manager block.
1323 void ASTReader::ParseLineTable(ModuleFile &F, const RecordData &Record) {
1324 unsigned Idx = 0;
1325 LineTableInfo &LineTable = SourceMgr.getLineTable();
1327 // Parse the file names
1328 std::map<int, int> FileIDs;
1329 FileIDs[-1] = -1; // For unspecified filenames.
1330 for (unsigned I = 0; Record[Idx]; ++I) {
1331 // Extract the file name
1332 auto Filename = ReadPath(F, Record, Idx);
1333 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1335 ++Idx;
1337 // Parse the line entries
1338 std::vector<LineEntry> Entries;
1339 while (Idx < Record.size()) {
1340 FileID FID = ReadFileID(F, Record, Idx);
1342 // Extract the line entries
1343 unsigned NumEntries = Record[Idx++];
1344 assert(NumEntries && "no line entries for file ID");
1345 Entries.clear();
1346 Entries.reserve(NumEntries);
1347 for (unsigned I = 0; I != NumEntries; ++I) {
1348 unsigned FileOffset = Record[Idx++];
1349 unsigned LineNo = Record[Idx++];
1350 int FilenameID = FileIDs[Record[Idx++]];
1351 SrcMgr::CharacteristicKind FileKind
1352 = (SrcMgr::CharacteristicKind)Record[Idx++];
1353 unsigned IncludeOffset = Record[Idx++];
1354 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1355 FileKind, IncludeOffset));
1357 LineTable.AddEntry(FID, Entries);
1361 /// Read a source manager block
1362 llvm::Error ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1363 using namespace SrcMgr;
1365 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
1367 // Set the source-location entry cursor to the current position in
1368 // the stream. This cursor will be used to read the contents of the
1369 // source manager block initially, and then lazily read
1370 // source-location entries as needed.
1371 SLocEntryCursor = F.Stream;
1373 // The stream itself is going to skip over the source manager block.
1374 if (llvm::Error Err = F.Stream.SkipBlock())
1375 return Err;
1377 // Enter the source manager block.
1378 if (llvm::Error Err = SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID))
1379 return Err;
1380 F.SourceManagerBlockStartOffset = SLocEntryCursor.GetCurrentBitNo();
1382 RecordData Record;
1383 while (true) {
1384 Expected<llvm::BitstreamEntry> MaybeE =
1385 SLocEntryCursor.advanceSkippingSubblocks();
1386 if (!MaybeE)
1387 return MaybeE.takeError();
1388 llvm::BitstreamEntry E = MaybeE.get();
1390 switch (E.Kind) {
1391 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1392 case llvm::BitstreamEntry::Error:
1393 return llvm::createStringError(std::errc::illegal_byte_sequence,
1394 "malformed block record in AST file");
1395 case llvm::BitstreamEntry::EndBlock:
1396 return llvm::Error::success();
1397 case llvm::BitstreamEntry::Record:
1398 // The interesting case.
1399 break;
1402 // Read a record.
1403 Record.clear();
1404 StringRef Blob;
1405 Expected<unsigned> MaybeRecord =
1406 SLocEntryCursor.readRecord(E.ID, Record, &Blob);
1407 if (!MaybeRecord)
1408 return MaybeRecord.takeError();
1409 switch (MaybeRecord.get()) {
1410 default: // Default behavior: ignore.
1411 break;
1413 case SM_SLOC_FILE_ENTRY:
1414 case SM_SLOC_BUFFER_ENTRY:
1415 case SM_SLOC_EXPANSION_ENTRY:
1416 // Once we hit one of the source location entries, we're done.
1417 return llvm::Error::success();
1422 bool ASTReader::ReadSLocEntry(int ID) {
1423 if (ID == 0)
1424 return false;
1426 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1427 Error("source location entry ID out-of-range for AST file");
1428 return true;
1431 // Local helper to read the (possibly-compressed) buffer data following the
1432 // entry record.
1433 auto ReadBuffer = [this](
1434 BitstreamCursor &SLocEntryCursor,
1435 StringRef Name) -> std::unique_ptr<llvm::MemoryBuffer> {
1436 RecordData Record;
1437 StringRef Blob;
1438 Expected<unsigned> MaybeCode = SLocEntryCursor.ReadCode();
1439 if (!MaybeCode) {
1440 Error(MaybeCode.takeError());
1441 return nullptr;
1443 unsigned Code = MaybeCode.get();
1445 Expected<unsigned> MaybeRecCode =
1446 SLocEntryCursor.readRecord(Code, Record, &Blob);
1447 if (!MaybeRecCode) {
1448 Error(MaybeRecCode.takeError());
1449 return nullptr;
1451 unsigned RecCode = MaybeRecCode.get();
1453 if (RecCode == SM_SLOC_BUFFER_BLOB_COMPRESSED) {
1454 // Inspect the first byte to differentiate zlib (\x78) and zstd
1455 // (little-endian 0xFD2FB528).
1456 const llvm::compression::Format F =
1457 Blob.size() > 0 && Blob.data()[0] == 0x78
1458 ? llvm::compression::Format::Zlib
1459 : llvm::compression::Format::Zstd;
1460 if (const char *Reason = llvm::compression::getReasonIfUnsupported(F)) {
1461 Error(Reason);
1462 return nullptr;
1464 SmallVector<uint8_t, 0> Decompressed;
1465 if (llvm::Error E = llvm::compression::decompress(
1466 F, llvm::arrayRefFromStringRef(Blob), Decompressed, Record[0])) {
1467 Error("could not decompress embedded file contents: " +
1468 llvm::toString(std::move(E)));
1469 return nullptr;
1471 return llvm::MemoryBuffer::getMemBufferCopy(
1472 llvm::toStringRef(Decompressed), Name);
1473 } else if (RecCode == SM_SLOC_BUFFER_BLOB) {
1474 return llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name, true);
1475 } else {
1476 Error("AST record has invalid code");
1477 return nullptr;
1481 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1482 if (llvm::Error Err = F->SLocEntryCursor.JumpToBit(
1483 F->SLocEntryOffsetsBase +
1484 F->SLocEntryOffsets[ID - F->SLocEntryBaseID])) {
1485 Error(std::move(Err));
1486 return true;
1489 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
1490 SourceLocation::UIntTy BaseOffset = F->SLocEntryBaseOffset;
1492 ++NumSLocEntriesRead;
1493 Expected<llvm::BitstreamEntry> MaybeEntry = SLocEntryCursor.advance();
1494 if (!MaybeEntry) {
1495 Error(MaybeEntry.takeError());
1496 return true;
1498 llvm::BitstreamEntry Entry = MaybeEntry.get();
1500 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1501 Error("incorrectly-formatted source location entry in AST file");
1502 return true;
1505 RecordData Record;
1506 StringRef Blob;
1507 Expected<unsigned> MaybeSLOC =
1508 SLocEntryCursor.readRecord(Entry.ID, Record, &Blob);
1509 if (!MaybeSLOC) {
1510 Error(MaybeSLOC.takeError());
1511 return true;
1513 switch (MaybeSLOC.get()) {
1514 default:
1515 Error("incorrectly-formatted source location entry in AST file");
1516 return true;
1518 case SM_SLOC_FILE_ENTRY: {
1519 // We will detect whether a file changed and return 'Failure' for it, but
1520 // we will also try to fail gracefully by setting up the SLocEntry.
1521 unsigned InputID = Record[4];
1522 InputFile IF = getInputFile(*F, InputID);
1523 OptionalFileEntryRef File = IF.getFile();
1524 bool OverriddenBuffer = IF.isOverridden();
1526 // Note that we only check if a File was returned. If it was out-of-date
1527 // we have complained but we will continue creating a FileID to recover
1528 // gracefully.
1529 if (!File)
1530 return true;
1532 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1533 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1534 // This is the module's main file.
1535 IncludeLoc = getImportLocation(F);
1537 SrcMgr::CharacteristicKind
1538 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1539 FileID FID = SourceMgr.createFileID(*File, IncludeLoc, FileCharacter, ID,
1540 BaseOffset + Record[0]);
1541 SrcMgr::FileInfo &FileInfo =
1542 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1543 FileInfo.NumCreatedFIDs = Record[5];
1544 if (Record[3])
1545 FileInfo.setHasLineDirectives();
1547 unsigned NumFileDecls = Record[7];
1548 if (NumFileDecls && ContextObj) {
1549 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1550 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1551 FileDeclIDs[FID] =
1552 FileDeclsInfo(F, llvm::ArrayRef(FirstDecl, NumFileDecls));
1555 const SrcMgr::ContentCache &ContentCache =
1556 SourceMgr.getOrCreateContentCache(*File, isSystem(FileCharacter));
1557 if (OverriddenBuffer && !ContentCache.BufferOverridden &&
1558 ContentCache.ContentsEntry == ContentCache.OrigEntry &&
1559 !ContentCache.getBufferIfLoaded()) {
1560 auto Buffer = ReadBuffer(SLocEntryCursor, File->getName());
1561 if (!Buffer)
1562 return true;
1563 SourceMgr.overrideFileContents(*File, std::move(Buffer));
1566 break;
1569 case SM_SLOC_BUFFER_ENTRY: {
1570 const char *Name = Blob.data();
1571 unsigned Offset = Record[0];
1572 SrcMgr::CharacteristicKind
1573 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1574 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1575 if (IncludeLoc.isInvalid() && F->isModule()) {
1576 IncludeLoc = getImportLocation(F);
1579 auto Buffer = ReadBuffer(SLocEntryCursor, Name);
1580 if (!Buffer)
1581 return true;
1582 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
1583 BaseOffset + Offset, IncludeLoc);
1584 break;
1587 case SM_SLOC_EXPANSION_ENTRY: {
1588 LocSeq::State Seq;
1589 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1], Seq);
1590 SourceLocation ExpansionBegin = ReadSourceLocation(*F, Record[2], Seq);
1591 SourceLocation ExpansionEnd = ReadSourceLocation(*F, Record[3], Seq);
1592 SourceMgr.createExpansionLoc(SpellingLoc, ExpansionBegin, ExpansionEnd,
1593 Record[5], Record[4], ID,
1594 BaseOffset + Record[0]);
1595 break;
1599 return false;
1602 std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1603 if (ID == 0)
1604 return std::make_pair(SourceLocation(), "");
1606 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1607 Error("source location entry ID out-of-range for AST file");
1608 return std::make_pair(SourceLocation(), "");
1611 // Find which module file this entry lands in.
1612 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
1613 if (!M->isModule())
1614 return std::make_pair(SourceLocation(), "");
1616 // FIXME: Can we map this down to a particular submodule? That would be
1617 // ideal.
1618 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
1621 /// Find the location where the module F is imported.
1622 SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1623 if (F->ImportLoc.isValid())
1624 return F->ImportLoc;
1626 // Otherwise we have a PCH. It's considered to be "imported" at the first
1627 // location of its includer.
1628 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
1629 // Main file is the importer.
1630 assert(SourceMgr.getMainFileID().isValid() && "missing main file");
1631 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
1633 return F->ImportedBy[0]->FirstLoc;
1636 /// Enter a subblock of the specified BlockID with the specified cursor. Read
1637 /// the abbreviations that are at the top of the block and then leave the cursor
1638 /// pointing into the block.
1639 llvm::Error ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor,
1640 unsigned BlockID,
1641 uint64_t *StartOfBlockOffset) {
1642 if (llvm::Error Err = Cursor.EnterSubBlock(BlockID))
1643 return Err;
1645 if (StartOfBlockOffset)
1646 *StartOfBlockOffset = Cursor.GetCurrentBitNo();
1648 while (true) {
1649 uint64_t Offset = Cursor.GetCurrentBitNo();
1650 Expected<unsigned> MaybeCode = Cursor.ReadCode();
1651 if (!MaybeCode)
1652 return MaybeCode.takeError();
1653 unsigned Code = MaybeCode.get();
1655 // We expect all abbrevs to be at the start of the block.
1656 if (Code != llvm::bitc::DEFINE_ABBREV) {
1657 if (llvm::Error Err = Cursor.JumpToBit(Offset))
1658 return Err;
1659 return llvm::Error::success();
1661 if (llvm::Error Err = Cursor.ReadAbbrevRecord())
1662 return Err;
1666 Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
1667 unsigned &Idx) {
1668 Token Tok;
1669 Tok.startToken();
1670 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1671 Tok.setKind((tok::TokenKind)Record[Idx++]);
1672 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1674 if (Tok.isAnnotation()) {
1675 Tok.setAnnotationEndLoc(ReadSourceLocation(F, Record, Idx));
1676 switch (Tok.getKind()) {
1677 case tok::annot_pragma_loop_hint: {
1678 auto *Info = new (PP.getPreprocessorAllocator()) PragmaLoopHintInfo;
1679 Info->PragmaName = ReadToken(F, Record, Idx);
1680 Info->Option = ReadToken(F, Record, Idx);
1681 unsigned NumTokens = Record[Idx++];
1682 SmallVector<Token, 4> Toks;
1683 Toks.reserve(NumTokens);
1684 for (unsigned I = 0; I < NumTokens; ++I)
1685 Toks.push_back(ReadToken(F, Record, Idx));
1686 Info->Toks = llvm::ArrayRef(Toks).copy(PP.getPreprocessorAllocator());
1687 Tok.setAnnotationValue(static_cast<void *>(Info));
1688 break;
1690 case tok::annot_pragma_pack: {
1691 auto *Info = new (PP.getPreprocessorAllocator()) Sema::PragmaPackInfo;
1692 Info->Action = static_cast<Sema::PragmaMsStackAction>(Record[Idx++]);
1693 auto SlotLabel = ReadString(Record, Idx);
1694 Info->SlotLabel =
1695 llvm::StringRef(SlotLabel).copy(PP.getPreprocessorAllocator());
1696 Info->Alignment = ReadToken(F, Record, Idx);
1697 Tok.setAnnotationValue(static_cast<void *>(Info));
1698 break;
1700 // Some annotation tokens do not use the PtrData field.
1701 case tok::annot_pragma_openmp:
1702 case tok::annot_pragma_openmp_end:
1703 case tok::annot_pragma_unused:
1704 break;
1705 default:
1706 llvm_unreachable("missing deserialization code for annotation token");
1708 } else {
1709 Tok.setLength(Record[Idx++]);
1710 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1711 Tok.setIdentifierInfo(II);
1713 return Tok;
1716 MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
1717 BitstreamCursor &Stream = F.MacroCursor;
1719 // Keep track of where we are in the stream, then jump back there
1720 // after reading this macro.
1721 SavedStreamPosition SavedPosition(Stream);
1723 if (llvm::Error Err = Stream.JumpToBit(Offset)) {
1724 // FIXME this drops errors on the floor.
1725 consumeError(std::move(Err));
1726 return nullptr;
1728 RecordData Record;
1729 SmallVector<IdentifierInfo*, 16> MacroParams;
1730 MacroInfo *Macro = nullptr;
1731 llvm::MutableArrayRef<Token> MacroTokens;
1733 while (true) {
1734 // Advance to the next record, but if we get to the end of the block, don't
1735 // pop it (removing all the abbreviations from the cursor) since we want to
1736 // be able to reseek within the block and read entries.
1737 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
1738 Expected<llvm::BitstreamEntry> MaybeEntry =
1739 Stream.advanceSkippingSubblocks(Flags);
1740 if (!MaybeEntry) {
1741 Error(MaybeEntry.takeError());
1742 return Macro;
1744 llvm::BitstreamEntry Entry = MaybeEntry.get();
1746 switch (Entry.Kind) {
1747 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1748 case llvm::BitstreamEntry::Error:
1749 Error("malformed block record in AST file");
1750 return Macro;
1751 case llvm::BitstreamEntry::EndBlock:
1752 return Macro;
1753 case llvm::BitstreamEntry::Record:
1754 // The interesting case.
1755 break;
1758 // Read a record.
1759 Record.clear();
1760 PreprocessorRecordTypes RecType;
1761 if (Expected<unsigned> MaybeRecType = Stream.readRecord(Entry.ID, Record))
1762 RecType = (PreprocessorRecordTypes)MaybeRecType.get();
1763 else {
1764 Error(MaybeRecType.takeError());
1765 return Macro;
1767 switch (RecType) {
1768 case PP_MODULE_MACRO:
1769 case PP_MACRO_DIRECTIVE_HISTORY:
1770 return Macro;
1772 case PP_MACRO_OBJECT_LIKE:
1773 case PP_MACRO_FUNCTION_LIKE: {
1774 // If we already have a macro, that means that we've hit the end
1775 // of the definition of the macro we were looking for. We're
1776 // done.
1777 if (Macro)
1778 return Macro;
1780 unsigned NextIndex = 1; // Skip identifier ID.
1781 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
1782 MacroInfo *MI = PP.AllocateMacroInfo(Loc);
1783 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
1784 MI->setIsUsed(Record[NextIndex++]);
1785 MI->setUsedForHeaderGuard(Record[NextIndex++]);
1786 MacroTokens = MI->allocateTokens(Record[NextIndex++],
1787 PP.getPreprocessorAllocator());
1788 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1789 // Decode function-like macro info.
1790 bool isC99VarArgs = Record[NextIndex++];
1791 bool isGNUVarArgs = Record[NextIndex++];
1792 bool hasCommaPasting = Record[NextIndex++];
1793 MacroParams.clear();
1794 unsigned NumArgs = Record[NextIndex++];
1795 for (unsigned i = 0; i != NumArgs; ++i)
1796 MacroParams.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1798 // Install function-like macro info.
1799 MI->setIsFunctionLike();
1800 if (isC99VarArgs) MI->setIsC99Varargs();
1801 if (isGNUVarArgs) MI->setIsGNUVarargs();
1802 if (hasCommaPasting) MI->setHasCommaPasting();
1803 MI->setParameterList(MacroParams, PP.getPreprocessorAllocator());
1806 // Remember that we saw this macro last so that we add the tokens that
1807 // form its body to it.
1808 Macro = MI;
1810 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1811 Record[NextIndex]) {
1812 // We have a macro definition. Register the association
1813 PreprocessedEntityID
1814 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1815 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
1816 PreprocessingRecord::PPEntityID PPID =
1817 PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
1818 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
1819 PPRec.getPreprocessedEntity(PPID));
1820 if (PPDef)
1821 PPRec.RegisterMacroDefinition(Macro, PPDef);
1824 ++NumMacrosRead;
1825 break;
1828 case PP_TOKEN: {
1829 // If we see a TOKEN before a PP_MACRO_*, then the file is
1830 // erroneous, just pretend we didn't see this.
1831 if (!Macro) break;
1832 if (MacroTokens.empty()) {
1833 Error("unexpected number of macro tokens for a macro in AST file");
1834 return Macro;
1837 unsigned Idx = 0;
1838 MacroTokens[0] = ReadToken(F, Record, Idx);
1839 MacroTokens = MacroTokens.drop_front();
1840 break;
1846 PreprocessedEntityID
1847 ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M,
1848 unsigned LocalID) const {
1849 if (!M.ModuleOffsetMap.empty())
1850 ReadModuleOffsetMap(M);
1852 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1853 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1854 assert(I != M.PreprocessedEntityRemap.end()
1855 && "Invalid index into preprocessed entity index remap");
1857 return LocalID + I->second;
1860 unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1861 return llvm::hash_combine(ikey.Size, ikey.ModTime);
1864 HeaderFileInfoTrait::internal_key_type
1865 HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
1866 internal_key_type ikey = {FE->getSize(),
1867 M.HasTimestamps ? FE->getModificationTime() : 0,
1868 FE->getName(), /*Imported*/ false};
1869 return ikey;
1872 bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
1873 if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime))
1874 return false;
1876 if (llvm::sys::path::is_absolute(a.Filename) && a.Filename == b.Filename)
1877 return true;
1879 // Determine whether the actual files are equivalent.
1880 FileManager &FileMgr = Reader.getFileManager();
1881 auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
1882 if (!Key.Imported) {
1883 if (auto File = FileMgr.getFile(Key.Filename))
1884 return *File;
1885 return nullptr;
1888 std::string Resolved = std::string(Key.Filename);
1889 Reader.ResolveImportedPath(M, Resolved);
1890 if (auto File = FileMgr.getFile(Resolved))
1891 return *File;
1892 return nullptr;
1895 const FileEntry *FEA = GetFile(a);
1896 const FileEntry *FEB = GetFile(b);
1897 return FEA && FEA == FEB;
1900 std::pair<unsigned, unsigned>
1901 HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
1902 return readULEBKeyDataLength(d);
1905 HeaderFileInfoTrait::internal_key_type
1906 HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
1907 using namespace llvm::support;
1909 internal_key_type ikey;
1910 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1911 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
1912 ikey.Filename = (const char *)d;
1913 ikey.Imported = true;
1914 return ikey;
1917 HeaderFileInfoTrait::data_type
1918 HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
1919 unsigned DataLen) {
1920 using namespace llvm::support;
1922 const unsigned char *End = d + DataLen;
1923 HeaderFileInfo HFI;
1924 unsigned Flags = *d++;
1925 // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
1926 HFI.isImport |= (Flags >> 5) & 0x01;
1927 HFI.isPragmaOnce |= (Flags >> 4) & 0x01;
1928 HFI.DirInfo = (Flags >> 1) & 0x07;
1929 HFI.IndexHeaderMapHeader = Flags & 0x01;
1930 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1931 M, endian::readNext<uint32_t, little, unaligned>(d));
1932 if (unsigned FrameworkOffset =
1933 endian::readNext<uint32_t, little, unaligned>(d)) {
1934 // The framework offset is 1 greater than the actual offset,
1935 // since 0 is used as an indicator for "no framework name".
1936 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1937 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1940 assert((End - d) % 4 == 0 &&
1941 "Wrong data length in HeaderFileInfo deserialization");
1942 while (d != End) {
1943 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
1944 auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 7);
1945 LocalSMID >>= 3;
1947 // This header is part of a module. Associate it with the module to enable
1948 // implicit module import.
1949 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1950 Module *Mod = Reader.getSubmodule(GlobalSMID);
1951 FileManager &FileMgr = Reader.getFileManager();
1952 ModuleMap &ModMap =
1953 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1955 std::string Filename = std::string(key.Filename);
1956 if (key.Imported)
1957 Reader.ResolveImportedPath(M, Filename);
1958 // FIXME: NameAsWritten
1959 Module::Header H = {std::string(key.Filename), "",
1960 FileMgr.getOptionalFileRef(Filename)};
1961 ModMap.addHeader(Mod, H, HeaderRole, /*Imported*/true);
1962 HFI.isModuleHeader |= ModuleMap::isModular(HeaderRole);
1965 // This HeaderFileInfo was externally loaded.
1966 HFI.External = true;
1967 HFI.IsValid = true;
1968 return HFI;
1971 void ASTReader::addPendingMacro(IdentifierInfo *II, ModuleFile *M,
1972 uint32_t MacroDirectivesOffset) {
1973 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1974 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
1977 void ASTReader::ReadDefinedMacros() {
1978 // Note that we are loading defined macros.
1979 Deserializing Macros(this);
1981 for (ModuleFile &I : llvm::reverse(ModuleMgr)) {
1982 BitstreamCursor &MacroCursor = I.MacroCursor;
1984 // If there was no preprocessor block, skip this file.
1985 if (MacroCursor.getBitcodeBytes().empty())
1986 continue;
1988 BitstreamCursor Cursor = MacroCursor;
1989 if (llvm::Error Err = Cursor.JumpToBit(I.MacroStartOffset)) {
1990 Error(std::move(Err));
1991 return;
1994 RecordData Record;
1995 while (true) {
1996 Expected<llvm::BitstreamEntry> MaybeE = Cursor.advanceSkippingSubblocks();
1997 if (!MaybeE) {
1998 Error(MaybeE.takeError());
1999 return;
2001 llvm::BitstreamEntry E = MaybeE.get();
2003 switch (E.Kind) {
2004 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
2005 case llvm::BitstreamEntry::Error:
2006 Error("malformed block record in AST file");
2007 return;
2008 case llvm::BitstreamEntry::EndBlock:
2009 goto NextCursor;
2011 case llvm::BitstreamEntry::Record: {
2012 Record.clear();
2013 Expected<unsigned> MaybeRecord = Cursor.readRecord(E.ID, Record);
2014 if (!MaybeRecord) {
2015 Error(MaybeRecord.takeError());
2016 return;
2018 switch (MaybeRecord.get()) {
2019 default: // Default behavior: ignore.
2020 break;
2022 case PP_MACRO_OBJECT_LIKE:
2023 case PP_MACRO_FUNCTION_LIKE: {
2024 IdentifierInfo *II = getLocalIdentifier(I, Record[0]);
2025 if (II->isOutOfDate())
2026 updateOutOfDateIdentifier(*II);
2027 break;
2030 case PP_TOKEN:
2031 // Ignore tokens.
2032 break;
2034 break;
2038 NextCursor: ;
2042 namespace {
2044 /// Visitor class used to look up identifirs in an AST file.
2045 class IdentifierLookupVisitor {
2046 StringRef Name;
2047 unsigned NameHash;
2048 unsigned PriorGeneration;
2049 unsigned &NumIdentifierLookups;
2050 unsigned &NumIdentifierLookupHits;
2051 IdentifierInfo *Found = nullptr;
2053 public:
2054 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
2055 unsigned &NumIdentifierLookups,
2056 unsigned &NumIdentifierLookupHits)
2057 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
2058 PriorGeneration(PriorGeneration),
2059 NumIdentifierLookups(NumIdentifierLookups),
2060 NumIdentifierLookupHits(NumIdentifierLookupHits) {}
2062 bool operator()(ModuleFile &M) {
2063 // If we've already searched this module file, skip it now.
2064 if (M.Generation <= PriorGeneration)
2065 return true;
2067 ASTIdentifierLookupTable *IdTable
2068 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
2069 if (!IdTable)
2070 return false;
2072 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
2073 Found);
2074 ++NumIdentifierLookups;
2075 ASTIdentifierLookupTable::iterator Pos =
2076 IdTable->find_hashed(Name, NameHash, &Trait);
2077 if (Pos == IdTable->end())
2078 return false;
2080 // Dereferencing the iterator has the effect of building the
2081 // IdentifierInfo node and populating it with the various
2082 // declarations it needs.
2083 ++NumIdentifierLookupHits;
2084 Found = *Pos;
2085 return true;
2088 // Retrieve the identifier info found within the module
2089 // files.
2090 IdentifierInfo *getIdentifierInfo() const { return Found; }
2093 } // namespace
2095 void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
2096 // Note that we are loading an identifier.
2097 Deserializing AnIdentifier(this);
2099 unsigned PriorGeneration = 0;
2100 if (getContext().getLangOpts().Modules)
2101 PriorGeneration = IdentifierGeneration[&II];
2103 // If there is a global index, look there first to determine which modules
2104 // provably do not have any results for this identifier.
2105 GlobalModuleIndex::HitSet Hits;
2106 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
2107 if (!loadGlobalIndex()) {
2108 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
2109 HitsPtr = &Hits;
2113 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
2114 NumIdentifierLookups,
2115 NumIdentifierLookupHits);
2116 ModuleMgr.visit(Visitor, HitsPtr);
2117 markIdentifierUpToDate(&II);
2120 void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
2121 if (!II)
2122 return;
2124 II->setOutOfDate(false);
2126 // Update the generation for this identifier.
2127 if (getContext().getLangOpts().Modules)
2128 IdentifierGeneration[II] = getGeneration();
2131 void ASTReader::resolvePendingMacro(IdentifierInfo *II,
2132 const PendingMacroInfo &PMInfo) {
2133 ModuleFile &M = *PMInfo.M;
2135 BitstreamCursor &Cursor = M.MacroCursor;
2136 SavedStreamPosition SavedPosition(Cursor);
2137 if (llvm::Error Err =
2138 Cursor.JumpToBit(M.MacroOffsetsBase + PMInfo.MacroDirectivesOffset)) {
2139 Error(std::move(Err));
2140 return;
2143 struct ModuleMacroRecord {
2144 SubmoduleID SubModID;
2145 MacroInfo *MI;
2146 SmallVector<SubmoduleID, 8> Overrides;
2148 llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
2150 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
2151 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
2152 // macro histroy.
2153 RecordData Record;
2154 while (true) {
2155 Expected<llvm::BitstreamEntry> MaybeEntry =
2156 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
2157 if (!MaybeEntry) {
2158 Error(MaybeEntry.takeError());
2159 return;
2161 llvm::BitstreamEntry Entry = MaybeEntry.get();
2163 if (Entry.Kind != llvm::BitstreamEntry::Record) {
2164 Error("malformed block record in AST file");
2165 return;
2168 Record.clear();
2169 Expected<unsigned> MaybePP = Cursor.readRecord(Entry.ID, Record);
2170 if (!MaybePP) {
2171 Error(MaybePP.takeError());
2172 return;
2174 switch ((PreprocessorRecordTypes)MaybePP.get()) {
2175 case PP_MACRO_DIRECTIVE_HISTORY:
2176 break;
2178 case PP_MODULE_MACRO: {
2179 ModuleMacros.push_back(ModuleMacroRecord());
2180 auto &Info = ModuleMacros.back();
2181 Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
2182 Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
2183 for (int I = 2, N = Record.size(); I != N; ++I)
2184 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
2185 continue;
2188 default:
2189 Error("malformed block record in AST file");
2190 return;
2193 // We found the macro directive history; that's the last record
2194 // for this macro.
2195 break;
2198 // Module macros are listed in reverse dependency order.
2200 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
2201 llvm::SmallVector<ModuleMacro*, 8> Overrides;
2202 for (auto &MMR : ModuleMacros) {
2203 Overrides.clear();
2204 for (unsigned ModID : MMR.Overrides) {
2205 Module *Mod = getSubmodule(ModID);
2206 auto *Macro = PP.getModuleMacro(Mod, II);
2207 assert(Macro && "missing definition for overridden macro");
2208 Overrides.push_back(Macro);
2211 bool Inserted = false;
2212 Module *Owner = getSubmodule(MMR.SubModID);
2213 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
2217 // Don't read the directive history for a module; we don't have anywhere
2218 // to put it.
2219 if (M.isModule())
2220 return;
2222 // Deserialize the macro directives history in reverse source-order.
2223 MacroDirective *Latest = nullptr, *Earliest = nullptr;
2224 unsigned Idx = 0, N = Record.size();
2225 while (Idx < N) {
2226 MacroDirective *MD = nullptr;
2227 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
2228 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
2229 switch (K) {
2230 case MacroDirective::MD_Define: {
2231 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
2232 MD = PP.AllocateDefMacroDirective(MI, Loc);
2233 break;
2235 case MacroDirective::MD_Undefine:
2236 MD = PP.AllocateUndefMacroDirective(Loc);
2237 break;
2238 case MacroDirective::MD_Visibility:
2239 bool isPublic = Record[Idx++];
2240 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
2241 break;
2244 if (!Latest)
2245 Latest = MD;
2246 if (Earliest)
2247 Earliest->setPrevious(MD);
2248 Earliest = MD;
2251 if (Latest)
2252 PP.setLoadedMacroDirective(II, Earliest, Latest);
2255 bool ASTReader::shouldDisableValidationForFile(
2256 const serialization::ModuleFile &M) const {
2257 if (DisableValidationKind == DisableValidationForModuleKind::None)
2258 return false;
2260 // If a PCH is loaded and validation is disabled for PCH then disable
2261 // validation for the PCH and the modules it loads.
2262 ModuleKind K = CurrentDeserializingModuleKind.value_or(M.Kind);
2264 switch (K) {
2265 case MK_MainFile:
2266 case MK_Preamble:
2267 case MK_PCH:
2268 return bool(DisableValidationKind & DisableValidationForModuleKind::PCH);
2269 case MK_ImplicitModule:
2270 case MK_ExplicitModule:
2271 case MK_PrebuiltModule:
2272 return bool(DisableValidationKind & DisableValidationForModuleKind::Module);
2275 return false;
2278 InputFileInfo ASTReader::getInputFileInfo(ModuleFile &F, unsigned ID) {
2279 // If this ID is bogus, just return an empty input file.
2280 if (ID == 0 || ID > F.InputFileInfosLoaded.size())
2281 return InputFileInfo();
2283 // If we've already loaded this input file, return it.
2284 if (!F.InputFileInfosLoaded[ID - 1].Filename.empty())
2285 return F.InputFileInfosLoaded[ID - 1];
2287 // Go find this input file.
2288 BitstreamCursor &Cursor = F.InputFilesCursor;
2289 SavedStreamPosition SavedPosition(Cursor);
2290 if (llvm::Error Err = Cursor.JumpToBit(F.InputFileOffsets[ID - 1])) {
2291 // FIXME this drops errors on the floor.
2292 consumeError(std::move(Err));
2295 Expected<unsigned> MaybeCode = Cursor.ReadCode();
2296 if (!MaybeCode) {
2297 // FIXME this drops errors on the floor.
2298 consumeError(MaybeCode.takeError());
2300 unsigned Code = MaybeCode.get();
2301 RecordData Record;
2302 StringRef Blob;
2304 if (Expected<unsigned> Maybe = Cursor.readRecord(Code, Record, &Blob))
2305 assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE &&
2306 "invalid record type for input file");
2307 else {
2308 // FIXME this drops errors on the floor.
2309 consumeError(Maybe.takeError());
2312 assert(Record[0] == ID && "Bogus stored ID or offset");
2313 InputFileInfo R;
2314 R.StoredSize = static_cast<off_t>(Record[1]);
2315 R.StoredTime = static_cast<time_t>(Record[2]);
2316 R.Overridden = static_cast<bool>(Record[3]);
2317 R.Transient = static_cast<bool>(Record[4]);
2318 R.TopLevelModuleMap = static_cast<bool>(Record[5]);
2319 R.Filename = std::string(Blob);
2320 ResolveImportedPath(F, R.Filename);
2322 Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
2323 if (!MaybeEntry) // FIXME this drops errors on the floor.
2324 consumeError(MaybeEntry.takeError());
2325 llvm::BitstreamEntry Entry = MaybeEntry.get();
2326 assert(Entry.Kind == llvm::BitstreamEntry::Record &&
2327 "expected record type for input file hash");
2329 Record.clear();
2330 if (Expected<unsigned> Maybe = Cursor.readRecord(Entry.ID, Record))
2331 assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE_HASH &&
2332 "invalid record type for input file hash");
2333 else {
2334 // FIXME this drops errors on the floor.
2335 consumeError(Maybe.takeError());
2337 R.ContentHash = (static_cast<uint64_t>(Record[1]) << 32) |
2338 static_cast<uint64_t>(Record[0]);
2340 // Note that we've loaded this input file info.
2341 F.InputFileInfosLoaded[ID - 1] = R;
2342 return R;
2345 static unsigned moduleKindForDiagnostic(ModuleKind Kind);
2346 InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
2347 // If this ID is bogus, just return an empty input file.
2348 if (ID == 0 || ID > F.InputFilesLoaded.size())
2349 return InputFile();
2351 // If we've already loaded this input file, return it.
2352 if (F.InputFilesLoaded[ID-1].getFile())
2353 return F.InputFilesLoaded[ID-1];
2355 if (F.InputFilesLoaded[ID-1].isNotFound())
2356 return InputFile();
2358 // Go find this input file.
2359 BitstreamCursor &Cursor = F.InputFilesCursor;
2360 SavedStreamPosition SavedPosition(Cursor);
2361 if (llvm::Error Err = Cursor.JumpToBit(F.InputFileOffsets[ID - 1])) {
2362 // FIXME this drops errors on the floor.
2363 consumeError(std::move(Err));
2366 InputFileInfo FI = getInputFileInfo(F, ID);
2367 off_t StoredSize = FI.StoredSize;
2368 time_t StoredTime = FI.StoredTime;
2369 bool Overridden = FI.Overridden;
2370 bool Transient = FI.Transient;
2371 StringRef Filename = FI.Filename;
2372 uint64_t StoredContentHash = FI.ContentHash;
2374 OptionalFileEntryRefDegradesToFileEntryPtr File = OptionalFileEntryRef(
2375 expectedToOptional(FileMgr.getFileRef(Filename, /*OpenFile=*/false)));
2377 // For an overridden file, create a virtual file with the stored
2378 // size/timestamp.
2379 if ((Overridden || Transient) && !File)
2380 File = FileMgr.getVirtualFileRef(Filename, StoredSize, StoredTime);
2382 if (!File) {
2383 if (Complain) {
2384 std::string ErrorStr = "could not find file '";
2385 ErrorStr += Filename;
2386 ErrorStr += "' referenced by AST file '";
2387 ErrorStr += F.FileName;
2388 ErrorStr += "'";
2389 Error(ErrorStr);
2391 // Record that we didn't find the file.
2392 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
2393 return InputFile();
2396 // Check if there was a request to override the contents of the file
2397 // that was part of the precompiled header. Overriding such a file
2398 // can lead to problems when lexing using the source locations from the
2399 // PCH.
2400 SourceManager &SM = getSourceManager();
2401 // FIXME: Reject if the overrides are different.
2402 if ((!Overridden && !Transient) && SM.isFileOverridden(File)) {
2403 if (Complain)
2404 Error(diag::err_fe_pch_file_overridden, Filename);
2406 // After emitting the diagnostic, bypass the overriding file to recover
2407 // (this creates a separate FileEntry).
2408 File = SM.bypassFileContentsOverride(*File);
2409 if (!File) {
2410 F.InputFilesLoaded[ID - 1] = InputFile::getNotFound();
2411 return InputFile();
2415 struct Change {
2416 enum ModificationKind {
2417 Size,
2418 ModTime,
2419 Content,
2420 None,
2421 } Kind;
2422 std::optional<int64_t> Old = std::nullopt;
2423 std::optional<int64_t> New = std::nullopt;
2425 auto HasInputFileChanged = [&]() {
2426 if (StoredSize != File->getSize())
2427 return Change{Change::Size, StoredSize, File->getSize()};
2428 if (!shouldDisableValidationForFile(F) && StoredTime &&
2429 StoredTime != File->getModificationTime()) {
2430 Change MTimeChange = {Change::ModTime, StoredTime,
2431 File->getModificationTime()};
2433 // In case the modification time changes but not the content,
2434 // accept the cached file as legit.
2435 if (ValidateASTInputFilesContent &&
2436 StoredContentHash != static_cast<uint64_t>(llvm::hash_code(-1))) {
2437 auto MemBuffOrError = FileMgr.getBufferForFile(File);
2438 if (!MemBuffOrError) {
2439 if (!Complain)
2440 return MTimeChange;
2441 std::string ErrorStr = "could not get buffer for file '";
2442 ErrorStr += File->getName();
2443 ErrorStr += "'";
2444 Error(ErrorStr);
2445 return MTimeChange;
2448 // FIXME: hash_value is not guaranteed to be stable!
2449 auto ContentHash = hash_value(MemBuffOrError.get()->getBuffer());
2450 if (StoredContentHash == static_cast<uint64_t>(ContentHash))
2451 return Change{Change::None};
2453 return Change{Change::Content};
2455 return MTimeChange;
2457 return Change{Change::None};
2460 bool IsOutOfDate = false;
2461 auto FileChange = HasInputFileChanged();
2462 // For an overridden file, there is nothing to validate.
2463 if (!Overridden && FileChange.Kind != Change::None) {
2464 if (Complain && !Diags.isDiagnosticInFlight()) {
2465 // Build a list of the PCH imports that got us here (in reverse).
2466 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2467 while (!ImportStack.back()->ImportedBy.empty())
2468 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
2470 // The top-level PCH is stale.
2471 StringRef TopLevelPCHName(ImportStack.back()->FileName);
2472 Diag(diag::err_fe_ast_file_modified)
2473 << Filename << moduleKindForDiagnostic(ImportStack.back()->Kind)
2474 << TopLevelPCHName << FileChange.Kind
2475 << (FileChange.Old && FileChange.New)
2476 << llvm::itostr(FileChange.Old.value_or(0))
2477 << llvm::itostr(FileChange.New.value_or(0));
2479 // Print the import stack.
2480 if (ImportStack.size() > 1) {
2481 Diag(diag::note_pch_required_by)
2482 << Filename << ImportStack[0]->FileName;
2483 for (unsigned I = 1; I < ImportStack.size(); ++I)
2484 Diag(diag::note_pch_required_by)
2485 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
2488 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
2491 IsOutOfDate = true;
2493 // FIXME: If the file is overridden and we've already opened it,
2494 // issue an error (or split it into a separate FileEntry).
2496 InputFile IF = InputFile(*File, Overridden || Transient, IsOutOfDate);
2498 // Note that we've loaded this input file.
2499 F.InputFilesLoaded[ID-1] = IF;
2500 return IF;
2503 /// If we are loading a relocatable PCH or module file, and the filename
2504 /// is not an absolute path, add the system or module root to the beginning of
2505 /// the file name.
2506 void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2507 // Resolve relative to the base directory, if we have one.
2508 if (!M.BaseDirectory.empty())
2509 return ResolveImportedPath(Filename, M.BaseDirectory);
2512 void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
2513 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2514 return;
2516 SmallString<128> Buffer;
2517 llvm::sys::path::append(Buffer, Prefix, Filename);
2518 Filename.assign(Buffer.begin(), Buffer.end());
2521 static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
2522 switch (ARR) {
2523 case ASTReader::Failure: return true;
2524 case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
2525 case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
2526 case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch);
2527 case ASTReader::ConfigurationMismatch:
2528 return !(Caps & ASTReader::ARR_ConfigurationMismatch);
2529 case ASTReader::HadErrors: return true;
2530 case ASTReader::Success: return false;
2533 llvm_unreachable("unknown ASTReadResult");
2536 ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(
2537 BitstreamCursor &Stream, unsigned ClientLoadCapabilities,
2538 bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener,
2539 std::string &SuggestedPredefines) {
2540 if (llvm::Error Err = Stream.EnterSubBlock(OPTIONS_BLOCK_ID)) {
2541 // FIXME this drops errors on the floor.
2542 consumeError(std::move(Err));
2543 return Failure;
2546 // Read all of the records in the options block.
2547 RecordData Record;
2548 ASTReadResult Result = Success;
2549 while (true) {
2550 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
2551 if (!MaybeEntry) {
2552 // FIXME this drops errors on the floor.
2553 consumeError(MaybeEntry.takeError());
2554 return Failure;
2556 llvm::BitstreamEntry Entry = MaybeEntry.get();
2558 switch (Entry.Kind) {
2559 case llvm::BitstreamEntry::Error:
2560 case llvm::BitstreamEntry::SubBlock:
2561 return Failure;
2563 case llvm::BitstreamEntry::EndBlock:
2564 return Result;
2566 case llvm::BitstreamEntry::Record:
2567 // The interesting case.
2568 break;
2571 // Read and process a record.
2572 Record.clear();
2573 Expected<unsigned> MaybeRecordType = Stream.readRecord(Entry.ID, Record);
2574 if (!MaybeRecordType) {
2575 // FIXME this drops errors on the floor.
2576 consumeError(MaybeRecordType.takeError());
2577 return Failure;
2579 switch ((OptionsRecordTypes)MaybeRecordType.get()) {
2580 case LANGUAGE_OPTIONS: {
2581 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2582 if (ParseLanguageOptions(Record, Complain, Listener,
2583 AllowCompatibleConfigurationMismatch))
2584 Result = ConfigurationMismatch;
2585 break;
2588 case TARGET_OPTIONS: {
2589 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2590 if (ParseTargetOptions(Record, Complain, Listener,
2591 AllowCompatibleConfigurationMismatch))
2592 Result = ConfigurationMismatch;
2593 break;
2596 case FILE_SYSTEM_OPTIONS: {
2597 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2598 if (!AllowCompatibleConfigurationMismatch &&
2599 ParseFileSystemOptions(Record, Complain, Listener))
2600 Result = ConfigurationMismatch;
2601 break;
2604 case HEADER_SEARCH_OPTIONS: {
2605 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2606 if (!AllowCompatibleConfigurationMismatch &&
2607 ParseHeaderSearchOptions(Record, Complain, Listener))
2608 Result = ConfigurationMismatch;
2609 break;
2612 case PREPROCESSOR_OPTIONS:
2613 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2614 if (!AllowCompatibleConfigurationMismatch &&
2615 ParsePreprocessorOptions(Record, Complain, Listener,
2616 SuggestedPredefines))
2617 Result = ConfigurationMismatch;
2618 break;
2623 ASTReader::ASTReadResult
2624 ASTReader::ReadControlBlock(ModuleFile &F,
2625 SmallVectorImpl<ImportedModule> &Loaded,
2626 const ModuleFile *ImportedBy,
2627 unsigned ClientLoadCapabilities) {
2628 BitstreamCursor &Stream = F.Stream;
2630 if (llvm::Error Err = Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2631 Error(std::move(Err));
2632 return Failure;
2635 // Lambda to read the unhashed control block the first time it's called.
2637 // For PCM files, the unhashed control block cannot be read until after the
2638 // MODULE_NAME record. However, PCH files have no MODULE_NAME, and yet still
2639 // need to look ahead before reading the IMPORTS record. For consistency,
2640 // this block is always read somehow (see BitstreamEntry::EndBlock).
2641 bool HasReadUnhashedControlBlock = false;
2642 auto readUnhashedControlBlockOnce = [&]() {
2643 if (!HasReadUnhashedControlBlock) {
2644 HasReadUnhashedControlBlock = true;
2645 if (ASTReadResult Result =
2646 readUnhashedControlBlock(F, ImportedBy, ClientLoadCapabilities))
2647 return Result;
2649 return Success;
2652 bool DisableValidation = shouldDisableValidationForFile(F);
2654 // Read all of the records and blocks in the control block.
2655 RecordData Record;
2656 unsigned NumInputs = 0;
2657 unsigned NumUserInputs = 0;
2658 StringRef BaseDirectoryAsWritten;
2659 while (true) {
2660 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
2661 if (!MaybeEntry) {
2662 Error(MaybeEntry.takeError());
2663 return Failure;
2665 llvm::BitstreamEntry Entry = MaybeEntry.get();
2667 switch (Entry.Kind) {
2668 case llvm::BitstreamEntry::Error:
2669 Error("malformed block record in AST file");
2670 return Failure;
2671 case llvm::BitstreamEntry::EndBlock: {
2672 // Validate the module before returning. This call catches an AST with
2673 // no module name and no imports.
2674 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2675 return Result;
2677 // Validate input files.
2678 const HeaderSearchOptions &HSOpts =
2679 PP.getHeaderSearchInfo().getHeaderSearchOpts();
2681 // All user input files reside at the index range [0, NumUserInputs), and
2682 // system input files reside at [NumUserInputs, NumInputs). For explicitly
2683 // loaded module files, ignore missing inputs.
2684 if (!DisableValidation && F.Kind != MK_ExplicitModule &&
2685 F.Kind != MK_PrebuiltModule) {
2686 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
2688 // If we are reading a module, we will create a verification timestamp,
2689 // so we verify all input files. Otherwise, verify only user input
2690 // files.
2692 unsigned N = ValidateSystemInputs ? NumInputs : NumUserInputs;
2693 if (HSOpts.ModulesValidateOncePerBuildSession &&
2694 F.InputFilesValidationTimestamp > HSOpts.BuildSessionTimestamp &&
2695 F.Kind == MK_ImplicitModule)
2696 N = NumUserInputs;
2698 for (unsigned I = 0; I < N; ++I) {
2699 InputFile IF = getInputFile(F, I+1, Complain);
2700 if (!IF.getFile() || IF.isOutOfDate())
2701 return OutOfDate;
2705 if (Listener)
2706 Listener->visitModuleFile(F.FileName, F.Kind);
2708 if (Listener && Listener->needsInputFileVisitation()) {
2709 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2710 : NumUserInputs;
2711 for (unsigned I = 0; I < N; ++I) {
2712 bool IsSystem = I >= NumUserInputs;
2713 InputFileInfo FI = getInputFileInfo(F, I + 1);
2714 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden,
2715 F.Kind == MK_ExplicitModule ||
2716 F.Kind == MK_PrebuiltModule);
2720 return Success;
2723 case llvm::BitstreamEntry::SubBlock:
2724 switch (Entry.ID) {
2725 case INPUT_FILES_BLOCK_ID:
2726 F.InputFilesCursor = Stream;
2727 if (llvm::Error Err = Stream.SkipBlock()) {
2728 Error(std::move(Err));
2729 return Failure;
2731 if (ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2732 Error("malformed block record in AST file");
2733 return Failure;
2735 continue;
2737 case OPTIONS_BLOCK_ID:
2738 // If we're reading the first module for this group, check its options
2739 // are compatible with ours. For modules it imports, no further checking
2740 // is required, because we checked them when we built it.
2741 if (Listener && !ImportedBy) {
2742 // Should we allow the configuration of the module file to differ from
2743 // the configuration of the current translation unit in a compatible
2744 // way?
2746 // FIXME: Allow this for files explicitly specified with -include-pch.
2747 bool AllowCompatibleConfigurationMismatch =
2748 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
2750 ASTReadResult Result =
2751 ReadOptionsBlock(Stream, ClientLoadCapabilities,
2752 AllowCompatibleConfigurationMismatch, *Listener,
2753 SuggestedPredefines);
2754 if (Result == Failure) {
2755 Error("malformed block record in AST file");
2756 return Result;
2759 if (DisableValidation ||
2760 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
2761 Result = Success;
2763 // If we can't load the module, exit early since we likely
2764 // will rebuild the module anyway. The stream may be in the
2765 // middle of a block.
2766 if (Result != Success)
2767 return Result;
2768 } else if (llvm::Error Err = Stream.SkipBlock()) {
2769 Error(std::move(Err));
2770 return Failure;
2772 continue;
2774 default:
2775 if (llvm::Error Err = Stream.SkipBlock()) {
2776 Error(std::move(Err));
2777 return Failure;
2779 continue;
2782 case llvm::BitstreamEntry::Record:
2783 // The interesting case.
2784 break;
2787 // Read and process a record.
2788 Record.clear();
2789 StringRef Blob;
2790 Expected<unsigned> MaybeRecordType =
2791 Stream.readRecord(Entry.ID, Record, &Blob);
2792 if (!MaybeRecordType) {
2793 Error(MaybeRecordType.takeError());
2794 return Failure;
2796 switch ((ControlRecordTypes)MaybeRecordType.get()) {
2797 case METADATA: {
2798 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2799 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
2800 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2801 : diag::err_pch_version_too_new);
2802 return VersionMismatch;
2805 bool hasErrors = Record[6];
2806 if (hasErrors && !DisableValidation) {
2807 // If requested by the caller and the module hasn't already been read
2808 // or compiled, mark modules on error as out-of-date.
2809 if ((ClientLoadCapabilities & ARR_TreatModuleWithErrorsAsOutOfDate) &&
2810 canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
2811 return OutOfDate;
2813 if (!AllowASTWithCompilerErrors) {
2814 Diag(diag::err_pch_with_compiler_errors);
2815 return HadErrors;
2818 if (hasErrors) {
2819 Diags.ErrorOccurred = true;
2820 Diags.UncompilableErrorOccurred = true;
2821 Diags.UnrecoverableErrorOccurred = true;
2824 F.RelocatablePCH = Record[4];
2825 // Relative paths in a relocatable PCH are relative to our sysroot.
2826 if (F.RelocatablePCH)
2827 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
2829 F.HasTimestamps = Record[5];
2831 const std::string &CurBranch = getClangFullRepositoryVersion();
2832 StringRef ASTBranch = Blob;
2833 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2834 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
2835 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
2836 return VersionMismatch;
2838 break;
2841 case IMPORTS: {
2842 // Validate the AST before processing any imports (otherwise, untangling
2843 // them can be error-prone and expensive). A module will have a name and
2844 // will already have been validated, but this catches the PCH case.
2845 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2846 return Result;
2848 // Load each of the imported PCH files.
2849 unsigned Idx = 0, N = Record.size();
2850 while (Idx < N) {
2851 // Read information about the AST file.
2852 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2853 // The import location will be the local one for now; we will adjust
2854 // all import locations of module imports after the global source
2855 // location info are setup, in ReadAST.
2856 SourceLocation ImportLoc =
2857 ReadUntranslatedSourceLocation(Record[Idx++]);
2858 off_t StoredSize = (off_t)Record[Idx++];
2859 time_t StoredModTime = (time_t)Record[Idx++];
2860 auto FirstSignatureByte = Record.begin() + Idx;
2861 ASTFileSignature StoredSignature = ASTFileSignature::create(
2862 FirstSignatureByte, FirstSignatureByte + ASTFileSignature::size);
2863 Idx += ASTFileSignature::size;
2865 std::string ImportedName = ReadString(Record, Idx);
2866 std::string ImportedFile;
2868 // For prebuilt and explicit modules first consult the file map for
2869 // an override. Note that here we don't search prebuilt module
2870 // directories, only the explicit name to file mappings. Also, we will
2871 // still verify the size/signature making sure it is essentially the
2872 // same file but perhaps in a different location.
2873 if (ImportedKind == MK_PrebuiltModule || ImportedKind == MK_ExplicitModule)
2874 ImportedFile = PP.getHeaderSearchInfo().getPrebuiltModuleFileName(
2875 ImportedName, /*FileMapOnly*/ true);
2877 if (ImportedFile.empty())
2878 // Use BaseDirectoryAsWritten to ensure we use the same path in the
2879 // ModuleCache as when writing.
2880 ImportedFile = ReadPath(BaseDirectoryAsWritten, Record, Idx);
2881 else
2882 SkipPath(Record, Idx);
2884 // If our client can't cope with us being out of date, we can't cope with
2885 // our dependency being missing.
2886 unsigned Capabilities = ClientLoadCapabilities;
2887 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2888 Capabilities &= ~ARR_Missing;
2890 // Load the AST file.
2891 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
2892 Loaded, StoredSize, StoredModTime,
2893 StoredSignature, Capabilities);
2895 // If we diagnosed a problem, produce a backtrace.
2896 bool recompilingFinalized =
2897 Result == OutOfDate && (Capabilities & ARR_OutOfDate) &&
2898 getModuleManager().getModuleCache().isPCMFinal(F.FileName);
2899 if (isDiagnosedResult(Result, Capabilities) || recompilingFinalized)
2900 Diag(diag::note_module_file_imported_by)
2901 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
2902 if (recompilingFinalized)
2903 Diag(diag::note_module_file_conflict);
2905 switch (Result) {
2906 case Failure: return Failure;
2907 // If we have to ignore the dependency, we'll have to ignore this too.
2908 case Missing:
2909 case OutOfDate: return OutOfDate;
2910 case VersionMismatch: return VersionMismatch;
2911 case ConfigurationMismatch: return ConfigurationMismatch;
2912 case HadErrors: return HadErrors;
2913 case Success: break;
2916 break;
2919 case ORIGINAL_FILE:
2920 F.OriginalSourceFileID = FileID::get(Record[0]);
2921 F.ActualOriginalSourceFileName = std::string(Blob);
2922 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
2923 ResolveImportedPath(F, F.OriginalSourceFileName);
2924 break;
2926 case ORIGINAL_FILE_ID:
2927 F.OriginalSourceFileID = FileID::get(Record[0]);
2928 break;
2930 case MODULE_NAME:
2931 F.ModuleName = std::string(Blob);
2932 Diag(diag::remark_module_import)
2933 << F.ModuleName << F.FileName << (ImportedBy ? true : false)
2934 << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());
2935 if (Listener)
2936 Listener->ReadModuleName(F.ModuleName);
2938 // Validate the AST as soon as we have a name so we can exit early on
2939 // failure.
2940 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2941 return Result;
2943 break;
2945 case MODULE_DIRECTORY: {
2946 // Save the BaseDirectory as written in the PCM for computing the module
2947 // filename for the ModuleCache.
2948 BaseDirectoryAsWritten = Blob;
2949 assert(!F.ModuleName.empty() &&
2950 "MODULE_DIRECTORY found before MODULE_NAME");
2951 // If we've already loaded a module map file covering this module, we may
2952 // have a better path for it (relative to the current build).
2953 Module *M = PP.getHeaderSearchInfo().lookupModule(
2954 F.ModuleName, SourceLocation(), /*AllowSearch*/ true,
2955 /*AllowExtraModuleMapSearch*/ true);
2956 if (M && M->Directory) {
2957 // If we're implicitly loading a module, the base directory can't
2958 // change between the build and use.
2959 // Don't emit module relocation error if we have -fno-validate-pch
2960 if (!bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation &
2961 DisableValidationForModuleKind::Module) &&
2962 F.Kind != MK_ExplicitModule && F.Kind != MK_PrebuiltModule) {
2963 auto BuildDir = PP.getFileManager().getDirectory(Blob);
2964 if (!BuildDir || *BuildDir != M->Directory) {
2965 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
2966 Diag(diag::err_imported_module_relocated)
2967 << F.ModuleName << Blob << M->Directory->getName();
2968 return OutOfDate;
2971 F.BaseDirectory = std::string(M->Directory->getName());
2972 } else {
2973 F.BaseDirectory = std::string(Blob);
2975 break;
2978 case MODULE_MAP_FILE:
2979 if (ASTReadResult Result =
2980 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2981 return Result;
2982 break;
2984 case INPUT_FILE_OFFSETS:
2985 NumInputs = Record[0];
2986 NumUserInputs = Record[1];
2987 F.InputFileOffsets =
2988 (const llvm::support::unaligned_uint64_t *)Blob.data();
2989 F.InputFilesLoaded.resize(NumInputs);
2990 F.InputFileInfosLoaded.resize(NumInputs);
2991 F.NumUserInputFiles = NumUserInputs;
2992 break;
2997 void ASTReader::readIncludedFiles(ModuleFile &F, StringRef Blob,
2998 Preprocessor &PP) {
2999 using namespace llvm::support;
3001 const unsigned char *D = (const unsigned char *)Blob.data();
3002 unsigned FileCount = endian::readNext<uint32_t, little, unaligned>(D);
3004 for (unsigned I = 0; I < FileCount; ++I) {
3005 size_t ID = endian::readNext<uint32_t, little, unaligned>(D);
3006 InputFileInfo IFI = getInputFileInfo(F, ID);
3007 if (llvm::ErrorOr<const FileEntry *> File =
3008 PP.getFileManager().getFile(IFI.Filename))
3009 PP.getIncludedFiles().insert(*File);
3013 llvm::Error ASTReader::ReadASTBlock(ModuleFile &F,
3014 unsigned ClientLoadCapabilities) {
3015 BitstreamCursor &Stream = F.Stream;
3017 if (llvm::Error Err = Stream.EnterSubBlock(AST_BLOCK_ID))
3018 return Err;
3019 F.ASTBlockStartOffset = Stream.GetCurrentBitNo();
3021 // Read all of the records and blocks for the AST file.
3022 RecordData Record;
3023 while (true) {
3024 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
3025 if (!MaybeEntry)
3026 return MaybeEntry.takeError();
3027 llvm::BitstreamEntry Entry = MaybeEntry.get();
3029 switch (Entry.Kind) {
3030 case llvm::BitstreamEntry::Error:
3031 return llvm::createStringError(
3032 std::errc::illegal_byte_sequence,
3033 "error at end of module block in AST file");
3034 case llvm::BitstreamEntry::EndBlock:
3035 // Outside of C++, we do not store a lookup map for the translation unit.
3036 // Instead, mark it as needing a lookup map to be built if this module
3037 // contains any declarations lexically within it (which it always does!).
3038 // This usually has no cost, since we very rarely need the lookup map for
3039 // the translation unit outside C++.
3040 if (ASTContext *Ctx = ContextObj) {
3041 DeclContext *DC = Ctx->getTranslationUnitDecl();
3042 if (DC->hasExternalLexicalStorage() && !Ctx->getLangOpts().CPlusPlus)
3043 DC->setMustBuildLookupTable();
3046 return llvm::Error::success();
3047 case llvm::BitstreamEntry::SubBlock:
3048 switch (Entry.ID) {
3049 case DECLTYPES_BLOCK_ID:
3050 // We lazily load the decls block, but we want to set up the
3051 // DeclsCursor cursor to point into it. Clone our current bitcode
3052 // cursor to it, enter the block and read the abbrevs in that block.
3053 // With the main cursor, we just skip over it.
3054 F.DeclsCursor = Stream;
3055 if (llvm::Error Err = Stream.SkipBlock())
3056 return Err;
3057 if (llvm::Error Err = ReadBlockAbbrevs(
3058 F.DeclsCursor, DECLTYPES_BLOCK_ID, &F.DeclsBlockStartOffset))
3059 return Err;
3060 break;
3062 case PREPROCESSOR_BLOCK_ID:
3063 F.MacroCursor = Stream;
3064 if (!PP.getExternalSource())
3065 PP.setExternalSource(this);
3067 if (llvm::Error Err = Stream.SkipBlock())
3068 return Err;
3069 if (llvm::Error Err =
3070 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID))
3071 return Err;
3072 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
3073 break;
3075 case PREPROCESSOR_DETAIL_BLOCK_ID:
3076 F.PreprocessorDetailCursor = Stream;
3078 if (llvm::Error Err = Stream.SkipBlock()) {
3079 return Err;
3081 if (llvm::Error Err = ReadBlockAbbrevs(F.PreprocessorDetailCursor,
3082 PREPROCESSOR_DETAIL_BLOCK_ID))
3083 return Err;
3084 F.PreprocessorDetailStartOffset
3085 = F.PreprocessorDetailCursor.GetCurrentBitNo();
3087 if (!PP.getPreprocessingRecord())
3088 PP.createPreprocessingRecord();
3089 if (!PP.getPreprocessingRecord()->getExternalSource())
3090 PP.getPreprocessingRecord()->SetExternalSource(*this);
3091 break;
3093 case SOURCE_MANAGER_BLOCK_ID:
3094 if (llvm::Error Err = ReadSourceManagerBlock(F))
3095 return Err;
3096 break;
3098 case SUBMODULE_BLOCK_ID:
3099 if (llvm::Error Err = ReadSubmoduleBlock(F, ClientLoadCapabilities))
3100 return Err;
3101 break;
3103 case COMMENTS_BLOCK_ID: {
3104 BitstreamCursor C = Stream;
3106 if (llvm::Error Err = Stream.SkipBlock())
3107 return Err;
3108 if (llvm::Error Err = ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID))
3109 return Err;
3110 CommentsCursors.push_back(std::make_pair(C, &F));
3111 break;
3114 default:
3115 if (llvm::Error Err = Stream.SkipBlock())
3116 return Err;
3117 break;
3119 continue;
3121 case llvm::BitstreamEntry::Record:
3122 // The interesting case.
3123 break;
3126 // Read and process a record.
3127 Record.clear();
3128 StringRef Blob;
3129 Expected<unsigned> MaybeRecordType =
3130 Stream.readRecord(Entry.ID, Record, &Blob);
3131 if (!MaybeRecordType)
3132 return MaybeRecordType.takeError();
3133 ASTRecordTypes RecordType = (ASTRecordTypes)MaybeRecordType.get();
3135 // If we're not loading an AST context, we don't care about most records.
3136 if (!ContextObj) {
3137 switch (RecordType) {
3138 case IDENTIFIER_TABLE:
3139 case IDENTIFIER_OFFSET:
3140 case INTERESTING_IDENTIFIERS:
3141 case STATISTICS:
3142 case PP_ASSUME_NONNULL_LOC:
3143 case PP_CONDITIONAL_STACK:
3144 case PP_COUNTER_VALUE:
3145 case SOURCE_LOCATION_OFFSETS:
3146 case MODULE_OFFSET_MAP:
3147 case SOURCE_MANAGER_LINE_TABLE:
3148 case SOURCE_LOCATION_PRELOADS:
3149 case PPD_ENTITIES_OFFSETS:
3150 case HEADER_SEARCH_TABLE:
3151 case IMPORTED_MODULES:
3152 case MACRO_OFFSET:
3153 break;
3154 default:
3155 continue;
3159 switch (RecordType) {
3160 default: // Default behavior: ignore.
3161 break;
3163 case TYPE_OFFSET: {
3164 if (F.LocalNumTypes != 0)
3165 return llvm::createStringError(
3166 std::errc::illegal_byte_sequence,
3167 "duplicate TYPE_OFFSET record in AST file");
3168 F.TypeOffsets = reinterpret_cast<const UnderalignedInt64 *>(Blob.data());
3169 F.LocalNumTypes = Record[0];
3170 unsigned LocalBaseTypeIndex = Record[1];
3171 F.BaseTypeIndex = getTotalNumTypes();
3173 if (F.LocalNumTypes > 0) {
3174 // Introduce the global -> local mapping for types within this module.
3175 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
3177 // Introduce the local -> global mapping for types within this module.
3178 F.TypeRemap.insertOrReplace(
3179 std::make_pair(LocalBaseTypeIndex,
3180 F.BaseTypeIndex - LocalBaseTypeIndex));
3182 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
3184 break;
3187 case DECL_OFFSET: {
3188 if (F.LocalNumDecls != 0)
3189 return llvm::createStringError(
3190 std::errc::illegal_byte_sequence,
3191 "duplicate DECL_OFFSET record in AST file");
3192 F.DeclOffsets = (const DeclOffset *)Blob.data();
3193 F.LocalNumDecls = Record[0];
3194 unsigned LocalBaseDeclID = Record[1];
3195 F.BaseDeclID = getTotalNumDecls();
3197 if (F.LocalNumDecls > 0) {
3198 // Introduce the global -> local mapping for declarations within this
3199 // module.
3200 GlobalDeclMap.insert(
3201 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
3203 // Introduce the local -> global mapping for declarations within this
3204 // module.
3205 F.DeclRemap.insertOrReplace(
3206 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
3208 // Introduce the global -> local mapping for declarations within this
3209 // module.
3210 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
3212 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
3214 break;
3217 case TU_UPDATE_LEXICAL: {
3218 DeclContext *TU = ContextObj->getTranslationUnitDecl();
3219 LexicalContents Contents(
3220 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
3221 Blob.data()),
3222 static_cast<unsigned int>(Blob.size() / 4));
3223 TULexicalDecls.push_back(std::make_pair(&F, Contents));
3224 TU->setHasExternalLexicalStorage(true);
3225 break;
3228 case UPDATE_VISIBLE: {
3229 unsigned Idx = 0;
3230 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
3231 auto *Data = (const unsigned char*)Blob.data();
3232 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&F, Data});
3233 // If we've already loaded the decl, perform the updates when we finish
3234 // loading this block.
3235 if (Decl *D = GetExistingDecl(ID))
3236 PendingUpdateRecords.push_back(
3237 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3238 break;
3241 case IDENTIFIER_TABLE:
3242 F.IdentifierTableData =
3243 reinterpret_cast<const unsigned char *>(Blob.data());
3244 if (Record[0]) {
3245 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
3246 F.IdentifierTableData + Record[0],
3247 F.IdentifierTableData + sizeof(uint32_t),
3248 F.IdentifierTableData,
3249 ASTIdentifierLookupTrait(*this, F));
3251 PP.getIdentifierTable().setExternalIdentifierLookup(this);
3253 break;
3255 case IDENTIFIER_OFFSET: {
3256 if (F.LocalNumIdentifiers != 0)
3257 return llvm::createStringError(
3258 std::errc::illegal_byte_sequence,
3259 "duplicate IDENTIFIER_OFFSET record in AST file");
3260 F.IdentifierOffsets = (const uint32_t *)Blob.data();
3261 F.LocalNumIdentifiers = Record[0];
3262 unsigned LocalBaseIdentifierID = Record[1];
3263 F.BaseIdentifierID = getTotalNumIdentifiers();
3265 if (F.LocalNumIdentifiers > 0) {
3266 // Introduce the global -> local mapping for identifiers within this
3267 // module.
3268 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
3269 &F));
3271 // Introduce the local -> global mapping for identifiers within this
3272 // module.
3273 F.IdentifierRemap.insertOrReplace(
3274 std::make_pair(LocalBaseIdentifierID,
3275 F.BaseIdentifierID - LocalBaseIdentifierID));
3277 IdentifiersLoaded.resize(IdentifiersLoaded.size()
3278 + F.LocalNumIdentifiers);
3280 break;
3283 case INTERESTING_IDENTIFIERS:
3284 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
3285 break;
3287 case EAGERLY_DESERIALIZED_DECLS:
3288 // FIXME: Skip reading this record if our ASTConsumer doesn't care
3289 // about "interesting" decls (for instance, if we're building a module).
3290 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3291 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
3292 break;
3294 case MODULAR_CODEGEN_DECLS:
3295 // FIXME: Skip reading this record if our ASTConsumer doesn't care about
3296 // them (ie: if we're not codegenerating this module).
3297 if (F.Kind == MK_MainFile ||
3298 getContext().getLangOpts().BuildingPCHWithObjectFile)
3299 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3300 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
3301 break;
3303 case SPECIAL_TYPES:
3304 if (SpecialTypes.empty()) {
3305 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3306 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
3307 break;
3310 if (SpecialTypes.size() != Record.size())
3311 return llvm::createStringError(std::errc::illegal_byte_sequence,
3312 "invalid special-types record");
3314 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
3315 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
3316 if (!SpecialTypes[I])
3317 SpecialTypes[I] = ID;
3318 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
3319 // merge step?
3321 break;
3323 case STATISTICS:
3324 TotalNumStatements += Record[0];
3325 TotalNumMacros += Record[1];
3326 TotalLexicalDeclContexts += Record[2];
3327 TotalVisibleDeclContexts += Record[3];
3328 break;
3330 case UNUSED_FILESCOPED_DECLS:
3331 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3332 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
3333 break;
3335 case DELEGATING_CTORS:
3336 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3337 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
3338 break;
3340 case WEAK_UNDECLARED_IDENTIFIERS:
3341 if (Record.size() % 3 != 0)
3342 return llvm::createStringError(std::errc::illegal_byte_sequence,
3343 "invalid weak identifiers record");
3345 // FIXME: Ignore weak undeclared identifiers from non-original PCH
3346 // files. This isn't the way to do it :)
3347 WeakUndeclaredIdentifiers.clear();
3349 // Translate the weak, undeclared identifiers into global IDs.
3350 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
3351 WeakUndeclaredIdentifiers.push_back(
3352 getGlobalIdentifierID(F, Record[I++]));
3353 WeakUndeclaredIdentifiers.push_back(
3354 getGlobalIdentifierID(F, Record[I++]));
3355 WeakUndeclaredIdentifiers.push_back(
3356 ReadSourceLocation(F, Record, I).getRawEncoding());
3358 break;
3360 case SELECTOR_OFFSETS: {
3361 F.SelectorOffsets = (const uint32_t *)Blob.data();
3362 F.LocalNumSelectors = Record[0];
3363 unsigned LocalBaseSelectorID = Record[1];
3364 F.BaseSelectorID = getTotalNumSelectors();
3366 if (F.LocalNumSelectors > 0) {
3367 // Introduce the global -> local mapping for selectors within this
3368 // module.
3369 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
3371 // Introduce the local -> global mapping for selectors within this
3372 // module.
3373 F.SelectorRemap.insertOrReplace(
3374 std::make_pair(LocalBaseSelectorID,
3375 F.BaseSelectorID - LocalBaseSelectorID));
3377 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
3379 break;
3382 case METHOD_POOL:
3383 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
3384 if (Record[0])
3385 F.SelectorLookupTable
3386 = ASTSelectorLookupTable::Create(
3387 F.SelectorLookupTableData + Record[0],
3388 F.SelectorLookupTableData,
3389 ASTSelectorLookupTrait(*this, F));
3390 TotalNumMethodPoolEntries += Record[1];
3391 break;
3393 case REFERENCED_SELECTOR_POOL:
3394 if (!Record.empty()) {
3395 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
3396 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
3397 Record[Idx++]));
3398 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
3399 getRawEncoding());
3402 break;
3404 case PP_ASSUME_NONNULL_LOC: {
3405 unsigned Idx = 0;
3406 if (!Record.empty())
3407 PP.setPreambleRecordedPragmaAssumeNonNullLoc(
3408 ReadSourceLocation(F, Record, Idx));
3409 break;
3412 case PP_CONDITIONAL_STACK:
3413 if (!Record.empty()) {
3414 unsigned Idx = 0, End = Record.size() - 1;
3415 bool ReachedEOFWhileSkipping = Record[Idx++];
3416 std::optional<Preprocessor::PreambleSkipInfo> SkipInfo;
3417 if (ReachedEOFWhileSkipping) {
3418 SourceLocation HashToken = ReadSourceLocation(F, Record, Idx);
3419 SourceLocation IfTokenLoc = ReadSourceLocation(F, Record, Idx);
3420 bool FoundNonSkipPortion = Record[Idx++];
3421 bool FoundElse = Record[Idx++];
3422 SourceLocation ElseLoc = ReadSourceLocation(F, Record, Idx);
3423 SkipInfo.emplace(HashToken, IfTokenLoc, FoundNonSkipPortion,
3424 FoundElse, ElseLoc);
3426 SmallVector<PPConditionalInfo, 4> ConditionalStack;
3427 while (Idx < End) {
3428 auto Loc = ReadSourceLocation(F, Record, Idx);
3429 bool WasSkipping = Record[Idx++];
3430 bool FoundNonSkip = Record[Idx++];
3431 bool FoundElse = Record[Idx++];
3432 ConditionalStack.push_back(
3433 {Loc, WasSkipping, FoundNonSkip, FoundElse});
3435 PP.setReplayablePreambleConditionalStack(ConditionalStack, SkipInfo);
3437 break;
3439 case PP_COUNTER_VALUE:
3440 if (!Record.empty() && Listener)
3441 Listener->ReadCounter(F, Record[0]);
3442 break;
3444 case FILE_SORTED_DECLS:
3445 F.FileSortedDecls = (const DeclID *)Blob.data();
3446 F.NumFileSortedDecls = Record[0];
3447 break;
3449 case SOURCE_LOCATION_OFFSETS: {
3450 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
3451 F.LocalNumSLocEntries = Record[0];
3452 SourceLocation::UIntTy SLocSpaceSize = Record[1];
3453 F.SLocEntryOffsetsBase = Record[2] + F.SourceManagerBlockStartOffset;
3454 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
3455 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
3456 SLocSpaceSize);
3457 if (!F.SLocEntryBaseID) {
3458 if (!Diags.isDiagnosticInFlight()) {
3459 Diags.Report(SourceLocation(), diag::remark_sloc_usage);
3460 SourceMgr.noteSLocAddressSpaceUsage(Diags);
3462 return llvm::createStringError(std::errc::invalid_argument,
3463 "ran out of source locations");
3465 // Make our entry in the range map. BaseID is negative and growing, so
3466 // we invert it. Because we invert it, though, we need the other end of
3467 // the range.
3468 unsigned RangeStart =
3469 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
3470 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
3471 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
3473 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
3474 assert((F.SLocEntryBaseOffset & SourceLocation::MacroIDBit) == 0);
3475 GlobalSLocOffsetMap.insert(
3476 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
3477 - SLocSpaceSize,&F));
3479 // Initialize the remapping table.
3480 // Invalid stays invalid.
3481 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
3482 // This module. Base was 2 when being compiled.
3483 F.SLocRemap.insertOrReplace(std::make_pair(
3484 2U, static_cast<SourceLocation::IntTy>(F.SLocEntryBaseOffset - 2)));
3486 TotalNumSLocEntries += F.LocalNumSLocEntries;
3487 break;
3490 case MODULE_OFFSET_MAP:
3491 F.ModuleOffsetMap = Blob;
3492 break;
3494 case SOURCE_MANAGER_LINE_TABLE:
3495 ParseLineTable(F, Record);
3496 break;
3498 case SOURCE_LOCATION_PRELOADS: {
3499 // Need to transform from the local view (1-based IDs) to the global view,
3500 // which is based off F.SLocEntryBaseID.
3501 if (!F.PreloadSLocEntries.empty())
3502 return llvm::createStringError(
3503 std::errc::illegal_byte_sequence,
3504 "Multiple SOURCE_LOCATION_PRELOADS records in AST file");
3506 F.PreloadSLocEntries.swap(Record);
3507 break;
3510 case EXT_VECTOR_DECLS:
3511 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3512 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
3513 break;
3515 case VTABLE_USES:
3516 if (Record.size() % 3 != 0)
3517 return llvm::createStringError(std::errc::illegal_byte_sequence,
3518 "Invalid VTABLE_USES record");
3520 // Later tables overwrite earlier ones.
3521 // FIXME: Modules will have some trouble with this. This is clearly not
3522 // the right way to do this.
3523 VTableUses.clear();
3525 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
3526 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
3527 VTableUses.push_back(
3528 ReadSourceLocation(F, Record, Idx).getRawEncoding());
3529 VTableUses.push_back(Record[Idx++]);
3531 break;
3533 case PENDING_IMPLICIT_INSTANTIATIONS:
3534 if (PendingInstantiations.size() % 2 != 0)
3535 return llvm::createStringError(
3536 std::errc::illegal_byte_sequence,
3537 "Invalid existing PendingInstantiations");
3539 if (Record.size() % 2 != 0)
3540 return llvm::createStringError(
3541 std::errc::illegal_byte_sequence,
3542 "Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
3544 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3545 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
3546 PendingInstantiations.push_back(
3547 ReadSourceLocation(F, Record, I).getRawEncoding());
3549 break;
3551 case SEMA_DECL_REFS:
3552 if (Record.size() != 3)
3553 return llvm::createStringError(std::errc::illegal_byte_sequence,
3554 "Invalid SEMA_DECL_REFS block");
3555 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3556 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3557 break;
3559 case PPD_ENTITIES_OFFSETS: {
3560 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3561 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3562 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
3564 unsigned LocalBasePreprocessedEntityID = Record[0];
3566 unsigned StartingID;
3567 if (!PP.getPreprocessingRecord())
3568 PP.createPreprocessingRecord();
3569 if (!PP.getPreprocessingRecord()->getExternalSource())
3570 PP.getPreprocessingRecord()->SetExternalSource(*this);
3571 StartingID
3572 = PP.getPreprocessingRecord()
3573 ->allocateLoadedEntities(F.NumPreprocessedEntities);
3574 F.BasePreprocessedEntityID = StartingID;
3576 if (F.NumPreprocessedEntities > 0) {
3577 // Introduce the global -> local mapping for preprocessed entities in
3578 // this module.
3579 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
3581 // Introduce the local -> global mapping for preprocessed entities in
3582 // this module.
3583 F.PreprocessedEntityRemap.insertOrReplace(
3584 std::make_pair(LocalBasePreprocessedEntityID,
3585 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3588 break;
3591 case PPD_SKIPPED_RANGES: {
3592 F.PreprocessedSkippedRangeOffsets = (const PPSkippedRange*)Blob.data();
3593 assert(Blob.size() % sizeof(PPSkippedRange) == 0);
3594 F.NumPreprocessedSkippedRanges = Blob.size() / sizeof(PPSkippedRange);
3596 if (!PP.getPreprocessingRecord())
3597 PP.createPreprocessingRecord();
3598 if (!PP.getPreprocessingRecord()->getExternalSource())
3599 PP.getPreprocessingRecord()->SetExternalSource(*this);
3600 F.BasePreprocessedSkippedRangeID = PP.getPreprocessingRecord()
3601 ->allocateSkippedRanges(F.NumPreprocessedSkippedRanges);
3603 if (F.NumPreprocessedSkippedRanges > 0)
3604 GlobalSkippedRangeMap.insert(
3605 std::make_pair(F.BasePreprocessedSkippedRangeID, &F));
3606 break;
3609 case DECL_UPDATE_OFFSETS:
3610 if (Record.size() % 2 != 0)
3611 return llvm::createStringError(
3612 std::errc::illegal_byte_sequence,
3613 "invalid DECL_UPDATE_OFFSETS block in AST file");
3614 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3615 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3616 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3618 // If we've already loaded the decl, perform the updates when we finish
3619 // loading this block.
3620 if (Decl *D = GetExistingDecl(ID))
3621 PendingUpdateRecords.push_back(
3622 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3624 break;
3626 case OBJC_CATEGORIES_MAP:
3627 if (F.LocalNumObjCCategoriesInMap != 0)
3628 return llvm::createStringError(
3629 std::errc::illegal_byte_sequence,
3630 "duplicate OBJC_CATEGORIES_MAP record in AST file");
3632 F.LocalNumObjCCategoriesInMap = Record[0];
3633 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
3634 break;
3636 case OBJC_CATEGORIES:
3637 F.ObjCCategories.swap(Record);
3638 break;
3640 case CUDA_SPECIAL_DECL_REFS:
3641 // Later tables overwrite earlier ones.
3642 // FIXME: Modules will have trouble with this.
3643 CUDASpecialDeclRefs.clear();
3644 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3645 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3646 break;
3648 case HEADER_SEARCH_TABLE:
3649 F.HeaderFileInfoTableData = Blob.data();
3650 F.LocalNumHeaderFileInfos = Record[1];
3651 if (Record[0]) {
3652 F.HeaderFileInfoTable
3653 = HeaderFileInfoLookupTable::Create(
3654 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3655 (const unsigned char *)F.HeaderFileInfoTableData,
3656 HeaderFileInfoTrait(*this, F,
3657 &PP.getHeaderSearchInfo(),
3658 Blob.data() + Record[2]));
3660 PP.getHeaderSearchInfo().SetExternalSource(this);
3661 if (!PP.getHeaderSearchInfo().getExternalLookup())
3662 PP.getHeaderSearchInfo().SetExternalLookup(this);
3664 break;
3666 case FP_PRAGMA_OPTIONS:
3667 // Later tables overwrite earlier ones.
3668 FPPragmaOptions.swap(Record);
3669 break;
3671 case OPENCL_EXTENSIONS:
3672 for (unsigned I = 0, E = Record.size(); I != E; ) {
3673 auto Name = ReadString(Record, I);
3674 auto &OptInfo = OpenCLExtensions.OptMap[Name];
3675 OptInfo.Supported = Record[I++] != 0;
3676 OptInfo.Enabled = Record[I++] != 0;
3677 OptInfo.WithPragma = Record[I++] != 0;
3678 OptInfo.Avail = Record[I++];
3679 OptInfo.Core = Record[I++];
3680 OptInfo.Opt = Record[I++];
3682 break;
3684 case TENTATIVE_DEFINITIONS:
3685 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3686 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3687 break;
3689 case KNOWN_NAMESPACES:
3690 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3691 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3692 break;
3694 case UNDEFINED_BUT_USED:
3695 if (UndefinedButUsed.size() % 2 != 0)
3696 return llvm::createStringError(std::errc::illegal_byte_sequence,
3697 "Invalid existing UndefinedButUsed");
3699 if (Record.size() % 2 != 0)
3700 return llvm::createStringError(std::errc::illegal_byte_sequence,
3701 "invalid undefined-but-used record");
3702 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3703 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3704 UndefinedButUsed.push_back(
3705 ReadSourceLocation(F, Record, I).getRawEncoding());
3707 break;
3709 case DELETE_EXPRS_TO_ANALYZE:
3710 for (unsigned I = 0, N = Record.size(); I != N;) {
3711 DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
3712 const uint64_t Count = Record[I++];
3713 DelayedDeleteExprs.push_back(Count);
3714 for (uint64_t C = 0; C < Count; ++C) {
3715 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3716 bool IsArrayForm = Record[I++] == 1;
3717 DelayedDeleteExprs.push_back(IsArrayForm);
3720 break;
3722 case IMPORTED_MODULES:
3723 if (!F.isModule()) {
3724 // If we aren't loading a module (which has its own exports), make
3725 // all of the imported modules visible.
3726 // FIXME: Deal with macros-only imports.
3727 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3728 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3729 SourceLocation Loc = ReadSourceLocation(F, Record, I);
3730 if (GlobalID) {
3731 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
3732 if (DeserializationListener)
3733 DeserializationListener->ModuleImportRead(GlobalID, Loc);
3737 break;
3739 case MACRO_OFFSET: {
3740 if (F.LocalNumMacros != 0)
3741 return llvm::createStringError(
3742 std::errc::illegal_byte_sequence,
3743 "duplicate MACRO_OFFSET record in AST file");
3744 F.MacroOffsets = (const uint32_t *)Blob.data();
3745 F.LocalNumMacros = Record[0];
3746 unsigned LocalBaseMacroID = Record[1];
3747 F.MacroOffsetsBase = Record[2] + F.ASTBlockStartOffset;
3748 F.BaseMacroID = getTotalNumMacros();
3750 if (F.LocalNumMacros > 0) {
3751 // Introduce the global -> local mapping for macros within this module.
3752 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3754 // Introduce the local -> global mapping for macros within this module.
3755 F.MacroRemap.insertOrReplace(
3756 std::make_pair(LocalBaseMacroID,
3757 F.BaseMacroID - LocalBaseMacroID));
3759 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
3761 break;
3764 case PP_INCLUDED_FILES:
3765 readIncludedFiles(F, Blob, PP);
3766 break;
3768 case LATE_PARSED_TEMPLATE:
3769 LateParsedTemplates.emplace_back(
3770 std::piecewise_construct, std::forward_as_tuple(&F),
3771 std::forward_as_tuple(Record.begin(), Record.end()));
3772 break;
3774 case OPTIMIZE_PRAGMA_OPTIONS:
3775 if (Record.size() != 1)
3776 return llvm::createStringError(std::errc::illegal_byte_sequence,
3777 "invalid pragma optimize record");
3778 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3779 break;
3781 case MSSTRUCT_PRAGMA_OPTIONS:
3782 if (Record.size() != 1)
3783 return llvm::createStringError(std::errc::illegal_byte_sequence,
3784 "invalid pragma ms_struct record");
3785 PragmaMSStructState = Record[0];
3786 break;
3788 case POINTERS_TO_MEMBERS_PRAGMA_OPTIONS:
3789 if (Record.size() != 2)
3790 return llvm::createStringError(
3791 std::errc::illegal_byte_sequence,
3792 "invalid pragma pointers to members record");
3793 PragmaMSPointersToMembersState = Record[0];
3794 PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]);
3795 break;
3797 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3798 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3799 UnusedLocalTypedefNameCandidates.push_back(
3800 getGlobalDeclID(F, Record[I]));
3801 break;
3803 case CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH:
3804 if (Record.size() != 1)
3805 return llvm::createStringError(std::errc::illegal_byte_sequence,
3806 "invalid cuda pragma options record");
3807 ForceCUDAHostDeviceDepth = Record[0];
3808 break;
3810 case ALIGN_PACK_PRAGMA_OPTIONS: {
3811 if (Record.size() < 3)
3812 return llvm::createStringError(std::errc::illegal_byte_sequence,
3813 "invalid pragma pack record");
3814 PragmaAlignPackCurrentValue = ReadAlignPackInfo(Record[0]);
3815 PragmaAlignPackCurrentLocation = ReadSourceLocation(F, Record[1]);
3816 unsigned NumStackEntries = Record[2];
3817 unsigned Idx = 3;
3818 // Reset the stack when importing a new module.
3819 PragmaAlignPackStack.clear();
3820 for (unsigned I = 0; I < NumStackEntries; ++I) {
3821 PragmaAlignPackStackEntry Entry;
3822 Entry.Value = ReadAlignPackInfo(Record[Idx++]);
3823 Entry.Location = ReadSourceLocation(F, Record[Idx++]);
3824 Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]);
3825 PragmaAlignPackStrings.push_back(ReadString(Record, Idx));
3826 Entry.SlotLabel = PragmaAlignPackStrings.back();
3827 PragmaAlignPackStack.push_back(Entry);
3829 break;
3832 case FLOAT_CONTROL_PRAGMA_OPTIONS: {
3833 if (Record.size() < 3)
3834 return llvm::createStringError(std::errc::illegal_byte_sequence,
3835 "invalid pragma float control record");
3836 FpPragmaCurrentValue = FPOptionsOverride::getFromOpaqueInt(Record[0]);
3837 FpPragmaCurrentLocation = ReadSourceLocation(F, Record[1]);
3838 unsigned NumStackEntries = Record[2];
3839 unsigned Idx = 3;
3840 // Reset the stack when importing a new module.
3841 FpPragmaStack.clear();
3842 for (unsigned I = 0; I < NumStackEntries; ++I) {
3843 FpPragmaStackEntry Entry;
3844 Entry.Value = FPOptionsOverride::getFromOpaqueInt(Record[Idx++]);
3845 Entry.Location = ReadSourceLocation(F, Record[Idx++]);
3846 Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]);
3847 FpPragmaStrings.push_back(ReadString(Record, Idx));
3848 Entry.SlotLabel = FpPragmaStrings.back();
3849 FpPragmaStack.push_back(Entry);
3851 break;
3854 case DECLS_TO_CHECK_FOR_DEFERRED_DIAGS:
3855 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3856 DeclsToCheckForDeferredDiags.insert(getGlobalDeclID(F, Record[I]));
3857 break;
3862 void ASTReader::ReadModuleOffsetMap(ModuleFile &F) const {
3863 assert(!F.ModuleOffsetMap.empty() && "no module offset map to read");
3865 // Additional remapping information.
3866 const unsigned char *Data = (const unsigned char*)F.ModuleOffsetMap.data();
3867 const unsigned char *DataEnd = Data + F.ModuleOffsetMap.size();
3868 F.ModuleOffsetMap = StringRef();
3870 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
3871 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
3872 F.SLocRemap.insert(std::make_pair(0U, 0));
3873 F.SLocRemap.insert(std::make_pair(2U, 1));
3876 // Continuous range maps we may be updating in our module.
3877 using SLocRemapBuilder =
3878 ContinuousRangeMap<SourceLocation::UIntTy, SourceLocation::IntTy,
3879 2>::Builder;
3880 using RemapBuilder = ContinuousRangeMap<uint32_t, int, 2>::Builder;
3881 SLocRemapBuilder SLocRemap(F.SLocRemap);
3882 RemapBuilder IdentifierRemap(F.IdentifierRemap);
3883 RemapBuilder MacroRemap(F.MacroRemap);
3884 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
3885 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
3886 RemapBuilder SelectorRemap(F.SelectorRemap);
3887 RemapBuilder DeclRemap(F.DeclRemap);
3888 RemapBuilder TypeRemap(F.TypeRemap);
3890 while (Data < DataEnd) {
3891 // FIXME: Looking up dependency modules by filename is horrible. Let's
3892 // start fixing this with prebuilt, explicit and implicit modules and see
3893 // how it goes...
3894 using namespace llvm::support;
3895 ModuleKind Kind = static_cast<ModuleKind>(
3896 endian::readNext<uint8_t, little, unaligned>(Data));
3897 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
3898 StringRef Name = StringRef((const char*)Data, Len);
3899 Data += Len;
3900 ModuleFile *OM = (Kind == MK_PrebuiltModule || Kind == MK_ExplicitModule ||
3901 Kind == MK_ImplicitModule
3902 ? ModuleMgr.lookupByModuleName(Name)
3903 : ModuleMgr.lookupByFileName(Name));
3904 if (!OM) {
3905 std::string Msg =
3906 "SourceLocation remap refers to unknown module, cannot find ";
3907 Msg.append(std::string(Name));
3908 Error(Msg);
3909 return;
3912 SourceLocation::UIntTy SLocOffset =
3913 endian::readNext<uint32_t, little, unaligned>(Data);
3914 uint32_t IdentifierIDOffset =
3915 endian::readNext<uint32_t, little, unaligned>(Data);
3916 uint32_t MacroIDOffset =
3917 endian::readNext<uint32_t, little, unaligned>(Data);
3918 uint32_t PreprocessedEntityIDOffset =
3919 endian::readNext<uint32_t, little, unaligned>(Data);
3920 uint32_t SubmoduleIDOffset =
3921 endian::readNext<uint32_t, little, unaligned>(Data);
3922 uint32_t SelectorIDOffset =
3923 endian::readNext<uint32_t, little, unaligned>(Data);
3924 uint32_t DeclIDOffset =
3925 endian::readNext<uint32_t, little, unaligned>(Data);
3926 uint32_t TypeIndexOffset =
3927 endian::readNext<uint32_t, little, unaligned>(Data);
3929 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
3930 RemapBuilder &Remap) {
3931 constexpr uint32_t None = std::numeric_limits<uint32_t>::max();
3932 if (Offset != None)
3933 Remap.insert(std::make_pair(Offset,
3934 static_cast<int>(BaseOffset - Offset)));
3937 constexpr SourceLocation::UIntTy SLocNone =
3938 std::numeric_limits<SourceLocation::UIntTy>::max();
3939 if (SLocOffset != SLocNone)
3940 SLocRemap.insert(std::make_pair(
3941 SLocOffset, static_cast<SourceLocation::IntTy>(
3942 OM->SLocEntryBaseOffset - SLocOffset)));
3944 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
3945 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
3946 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
3947 PreprocessedEntityRemap);
3948 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
3949 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
3950 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
3951 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
3953 // Global -> local mappings.
3954 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
3958 ASTReader::ASTReadResult
3959 ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3960 const ModuleFile *ImportedBy,
3961 unsigned ClientLoadCapabilities) {
3962 unsigned Idx = 0;
3963 F.ModuleMapPath = ReadPath(F, Record, Idx);
3965 // Try to resolve ModuleName in the current header search context and
3966 // verify that it is found in the same module map file as we saved. If the
3967 // top-level AST file is a main file, skip this check because there is no
3968 // usable header search context.
3969 assert(!F.ModuleName.empty() &&
3970 "MODULE_NAME should come before MODULE_MAP_FILE");
3971 if (F.Kind == MK_ImplicitModule && ModuleMgr.begin()->Kind != MK_MainFile) {
3972 // An implicitly-loaded module file should have its module listed in some
3973 // module map file that we've already loaded.
3974 Module *M =
3975 PP.getHeaderSearchInfo().lookupModule(F.ModuleName, F.ImportLoc);
3976 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3977 OptionalFileEntryRef ModMap =
3978 M ? Map.getModuleMapFileForUniquing(M) : std::nullopt;
3979 // Don't emit module relocation error if we have -fno-validate-pch
3980 if (!bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation &
3981 DisableValidationForModuleKind::Module) &&
3982 !ModMap) {
3983 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities)) {
3984 if (auto ASTFE = M ? M->getASTFile() : std::nullopt) {
3985 // This module was defined by an imported (explicit) module.
3986 Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
3987 << ASTFE->getName();
3988 } else {
3989 // This module was built with a different module map.
3990 Diag(diag::err_imported_module_not_found)
3991 << F.ModuleName << F.FileName
3992 << (ImportedBy ? ImportedBy->FileName : "") << F.ModuleMapPath
3993 << !ImportedBy;
3994 // In case it was imported by a PCH, there's a chance the user is
3995 // just missing to include the search path to the directory containing
3996 // the modulemap.
3997 if (ImportedBy && ImportedBy->Kind == MK_PCH)
3998 Diag(diag::note_imported_by_pch_module_not_found)
3999 << llvm::sys::path::parent_path(F.ModuleMapPath);
4002 return OutOfDate;
4005 assert(M && M->Name == F.ModuleName && "found module with different name");
4007 // Check the primary module map file.
4008 auto StoredModMap = FileMgr.getFile(F.ModuleMapPath);
4009 if (!StoredModMap || *StoredModMap != ModMap) {
4010 assert(ModMap && "found module is missing module map file");
4011 assert((ImportedBy || F.Kind == MK_ImplicitModule) &&
4012 "top-level import should be verified");
4013 bool NotImported = F.Kind == MK_ImplicitModule && !ImportedBy;
4014 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4015 Diag(diag::err_imported_module_modmap_changed)
4016 << F.ModuleName << (NotImported ? F.FileName : ImportedBy->FileName)
4017 << ModMap->getName() << F.ModuleMapPath << NotImported;
4018 return OutOfDate;
4021 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
4022 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
4023 // FIXME: we should use input files rather than storing names.
4024 std::string Filename = ReadPath(F, Record, Idx);
4025 auto SF = FileMgr.getFile(Filename, false, false);
4026 if (!SF) {
4027 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4028 Error("could not find file '" + Filename +"' referenced by AST file");
4029 return OutOfDate;
4031 AdditionalStoredMaps.insert(*SF);
4034 // Check any additional module map files (e.g. module.private.modulemap)
4035 // that are not in the pcm.
4036 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
4037 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
4038 // Remove files that match
4039 // Note: SmallPtrSet::erase is really remove
4040 if (!AdditionalStoredMaps.erase(ModMap)) {
4041 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4042 Diag(diag::err_module_different_modmap)
4043 << F.ModuleName << /*new*/0 << ModMap->getName();
4044 return OutOfDate;
4049 // Check any additional module map files that are in the pcm, but not
4050 // found in header search. Cases that match are already removed.
4051 for (const FileEntry *ModMap : AdditionalStoredMaps) {
4052 if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4053 Diag(diag::err_module_different_modmap)
4054 << F.ModuleName << /*not new*/1 << ModMap->getName();
4055 return OutOfDate;
4059 if (Listener)
4060 Listener->ReadModuleMapFile(F.ModuleMapPath);
4061 return Success;
4064 /// Move the given method to the back of the global list of methods.
4065 static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
4066 // Find the entry for this selector in the method pool.
4067 Sema::GlobalMethodPool::iterator Known
4068 = S.MethodPool.find(Method->getSelector());
4069 if (Known == S.MethodPool.end())
4070 return;
4072 // Retrieve the appropriate method list.
4073 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
4074 : Known->second.second;
4075 bool Found = false;
4076 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
4077 if (!Found) {
4078 if (List->getMethod() == Method) {
4079 Found = true;
4080 } else {
4081 // Keep searching.
4082 continue;
4086 if (List->getNext())
4087 List->setMethod(List->getNext()->getMethod());
4088 else
4089 List->setMethod(Method);
4093 void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
4094 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
4095 for (Decl *D : Names) {
4096 bool wasHidden = !D->isUnconditionallyVisible();
4097 D->setVisibleDespiteOwningModule();
4099 if (wasHidden && SemaObj) {
4100 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
4101 moveMethodToBackOfGlobalList(*SemaObj, Method);
4107 void ASTReader::makeModuleVisible(Module *Mod,
4108 Module::NameVisibilityKind NameVisibility,
4109 SourceLocation ImportLoc) {
4110 llvm::SmallPtrSet<Module *, 4> Visited;
4111 SmallVector<Module *, 4> Stack;
4112 Stack.push_back(Mod);
4113 while (!Stack.empty()) {
4114 Mod = Stack.pop_back_val();
4116 if (NameVisibility <= Mod->NameVisibility) {
4117 // This module already has this level of visibility (or greater), so
4118 // there is nothing more to do.
4119 continue;
4122 if (Mod->isUnimportable()) {
4123 // Modules that aren't importable cannot be made visible.
4124 continue;
4127 // Update the module's name visibility.
4128 Mod->NameVisibility = NameVisibility;
4130 // If we've already deserialized any names from this module,
4131 // mark them as visible.
4132 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
4133 if (Hidden != HiddenNamesMap.end()) {
4134 auto HiddenNames = std::move(*Hidden);
4135 HiddenNamesMap.erase(Hidden);
4136 makeNamesVisible(HiddenNames.second, HiddenNames.first);
4137 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
4138 "making names visible added hidden names");
4141 // Push any exported modules onto the stack to be marked as visible.
4142 SmallVector<Module *, 16> Exports;
4143 Mod->getExportedModules(Exports);
4144 for (SmallVectorImpl<Module *>::iterator
4145 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
4146 Module *Exported = *I;
4147 if (Visited.insert(Exported).second)
4148 Stack.push_back(Exported);
4153 /// We've merged the definition \p MergedDef into the existing definition
4154 /// \p Def. Ensure that \p Def is made visible whenever \p MergedDef is made
4155 /// visible.
4156 void ASTReader::mergeDefinitionVisibility(NamedDecl *Def,
4157 NamedDecl *MergedDef) {
4158 if (!Def->isUnconditionallyVisible()) {
4159 // If MergedDef is visible or becomes visible, make the definition visible.
4160 if (MergedDef->isUnconditionallyVisible())
4161 Def->setVisibleDespiteOwningModule();
4162 else {
4163 getContext().mergeDefinitionIntoModule(
4164 Def, MergedDef->getImportedOwningModule(),
4165 /*NotifyListeners*/ false);
4166 PendingMergedDefinitionsToDeduplicate.insert(Def);
4171 bool ASTReader::loadGlobalIndex() {
4172 if (GlobalIndex)
4173 return false;
4175 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
4176 !PP.getLangOpts().Modules)
4177 return true;
4179 // Try to load the global index.
4180 TriedLoadingGlobalIndex = true;
4181 StringRef ModuleCachePath
4182 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
4183 std::pair<GlobalModuleIndex *, llvm::Error> Result =
4184 GlobalModuleIndex::readIndex(ModuleCachePath);
4185 if (llvm::Error Err = std::move(Result.second)) {
4186 assert(!Result.first);
4187 consumeError(std::move(Err)); // FIXME this drops errors on the floor.
4188 return true;
4191 GlobalIndex.reset(Result.first);
4192 ModuleMgr.setGlobalIndex(GlobalIndex.get());
4193 return false;
4196 bool ASTReader::isGlobalIndexUnavailable() const {
4197 return PP.getLangOpts().Modules && UseGlobalIndex &&
4198 !hasGlobalIndex() && TriedLoadingGlobalIndex;
4201 static void updateModuleTimestamp(ModuleFile &MF) {
4202 // Overwrite the timestamp file contents so that file's mtime changes.
4203 std::string TimestampFilename = MF.getTimestampFilename();
4204 std::error_code EC;
4205 llvm::raw_fd_ostream OS(TimestampFilename, EC,
4206 llvm::sys::fs::OF_TextWithCRLF);
4207 if (EC)
4208 return;
4209 OS << "Timestamp file\n";
4210 OS.close();
4211 OS.clear_error(); // Avoid triggering a fatal error.
4214 /// Given a cursor at the start of an AST file, scan ahead and drop the
4215 /// cursor into the start of the given block ID, returning false on success and
4216 /// true on failure.
4217 static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
4218 while (true) {
4219 Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
4220 if (!MaybeEntry) {
4221 // FIXME this drops errors on the floor.
4222 consumeError(MaybeEntry.takeError());
4223 return true;
4225 llvm::BitstreamEntry Entry = MaybeEntry.get();
4227 switch (Entry.Kind) {
4228 case llvm::BitstreamEntry::Error:
4229 case llvm::BitstreamEntry::EndBlock:
4230 return true;
4232 case llvm::BitstreamEntry::Record:
4233 // Ignore top-level records.
4234 if (Expected<unsigned> Skipped = Cursor.skipRecord(Entry.ID))
4235 break;
4236 else {
4237 // FIXME this drops errors on the floor.
4238 consumeError(Skipped.takeError());
4239 return true;
4242 case llvm::BitstreamEntry::SubBlock:
4243 if (Entry.ID == BlockID) {
4244 if (llvm::Error Err = Cursor.EnterSubBlock(BlockID)) {
4245 // FIXME this drops the error on the floor.
4246 consumeError(std::move(Err));
4247 return true;
4249 // Found it!
4250 return false;
4253 if (llvm::Error Err = Cursor.SkipBlock()) {
4254 // FIXME this drops the error on the floor.
4255 consumeError(std::move(Err));
4256 return true;
4262 ASTReader::ASTReadResult ASTReader::ReadAST(StringRef FileName,
4263 ModuleKind Type,
4264 SourceLocation ImportLoc,
4265 unsigned ClientLoadCapabilities,
4266 SmallVectorImpl<ImportedSubmodule> *Imported) {
4267 llvm::TimeTraceScope scope("ReadAST", FileName);
4269 llvm::SaveAndRestore SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
4270 llvm::SaveAndRestore<std::optional<ModuleKind>> SetCurModuleKindRAII(
4271 CurrentDeserializingModuleKind, Type);
4273 // Defer any pending actions until we get to the end of reading the AST file.
4274 Deserializing AnASTFile(this);
4276 // Bump the generation number.
4277 unsigned PreviousGeneration = 0;
4278 if (ContextObj)
4279 PreviousGeneration = incrementGeneration(*ContextObj);
4281 unsigned NumModules = ModuleMgr.size();
4282 SmallVector<ImportedModule, 4> Loaded;
4283 if (ASTReadResult ReadResult =
4284 ReadASTCore(FileName, Type, ImportLoc,
4285 /*ImportedBy=*/nullptr, Loaded, 0, 0, ASTFileSignature(),
4286 ClientLoadCapabilities)) {
4287 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules);
4289 // If we find that any modules are unusable, the global index is going
4290 // to be out-of-date. Just remove it.
4291 GlobalIndex.reset();
4292 ModuleMgr.setGlobalIndex(nullptr);
4293 return ReadResult;
4296 // Here comes stuff that we only do once the entire chain is loaded. Do *not*
4297 // remove modules from this point. Various fields are updated during reading
4298 // the AST block and removing the modules would result in dangling pointers.
4299 // They are generally only incidentally dereferenced, ie. a binary search
4300 // runs over `GlobalSLocEntryMap`, which could cause an invalid module to
4301 // be dereferenced but it wouldn't actually be used.
4303 // Load the AST blocks of all of the modules that we loaded. We can still
4304 // hit errors parsing the ASTs at this point.
4305 for (ImportedModule &M : Loaded) {
4306 ModuleFile &F = *M.Mod;
4307 llvm::TimeTraceScope Scope2("Read Loaded AST", F.ModuleName);
4309 // Read the AST block.
4310 if (llvm::Error Err = ReadASTBlock(F, ClientLoadCapabilities)) {
4311 Error(std::move(Err));
4312 return Failure;
4315 // The AST block should always have a definition for the main module.
4316 if (F.isModule() && !F.DidReadTopLevelSubmodule) {
4317 Error(diag::err_module_file_missing_top_level_submodule, F.FileName);
4318 return Failure;
4321 // Read the extension blocks.
4322 while (!SkipCursorToBlock(F.Stream, EXTENSION_BLOCK_ID)) {
4323 if (llvm::Error Err = ReadExtensionBlock(F)) {
4324 Error(std::move(Err));
4325 return Failure;
4329 // Once read, set the ModuleFile bit base offset and update the size in
4330 // bits of all files we've seen.
4331 F.GlobalBitOffset = TotalModulesSizeInBits;
4332 TotalModulesSizeInBits += F.SizeInBits;
4333 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
4336 // Preload source locations and interesting indentifiers.
4337 for (ImportedModule &M : Loaded) {
4338 ModuleFile &F = *M.Mod;
4340 // Preload SLocEntries.
4341 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
4342 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
4343 // Load it through the SourceManager and don't call ReadSLocEntry()
4344 // directly because the entry may have already been loaded in which case
4345 // calling ReadSLocEntry() directly would trigger an assertion in
4346 // SourceManager.
4347 SourceMgr.getLoadedSLocEntryByID(Index);
4350 // Map the original source file ID into the ID space of the current
4351 // compilation.
4352 if (F.OriginalSourceFileID.isValid())
4353 F.OriginalSourceFileID = TranslateFileID(F, F.OriginalSourceFileID);
4355 // Preload all the pending interesting identifiers by marking them out of
4356 // date.
4357 for (auto Offset : F.PreloadIdentifierOffsets) {
4358 const unsigned char *Data = F.IdentifierTableData + Offset;
4360 ASTIdentifierLookupTrait Trait(*this, F);
4361 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
4362 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
4363 auto &II = PP.getIdentifierTable().getOwn(Key);
4364 II.setOutOfDate(true);
4366 // Mark this identifier as being from an AST file so that we can track
4367 // whether we need to serialize it.
4368 markIdentifierFromAST(*this, II);
4370 // Associate the ID with the identifier so that the writer can reuse it.
4371 auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
4372 SetIdentifierInfo(ID, &II);
4376 // Setup the import locations and notify the module manager that we've
4377 // committed to these module files.
4378 for (ImportedModule &M : Loaded) {
4379 ModuleFile &F = *M.Mod;
4381 ModuleMgr.moduleFileAccepted(&F);
4383 // Set the import location.
4384 F.DirectImportLoc = ImportLoc;
4385 // FIXME: We assume that locations from PCH / preamble do not need
4386 // any translation.
4387 if (!M.ImportedBy)
4388 F.ImportLoc = M.ImportLoc;
4389 else
4390 F.ImportLoc = TranslateSourceLocation(*M.ImportedBy, M.ImportLoc);
4393 if (!PP.getLangOpts().CPlusPlus ||
4394 (Type != MK_ImplicitModule && Type != MK_ExplicitModule &&
4395 Type != MK_PrebuiltModule)) {
4396 // Mark all of the identifiers in the identifier table as being out of date,
4397 // so that various accessors know to check the loaded modules when the
4398 // identifier is used.
4400 // For C++ modules, we don't need information on many identifiers (just
4401 // those that provide macros or are poisoned), so we mark all of
4402 // the interesting ones via PreloadIdentifierOffsets.
4403 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
4404 IdEnd = PP.getIdentifierTable().end();
4405 Id != IdEnd; ++Id)
4406 Id->second->setOutOfDate(true);
4408 // Mark selectors as out of date.
4409 for (auto Sel : SelectorGeneration)
4410 SelectorOutOfDate[Sel.first] = true;
4412 // Resolve any unresolved module exports.
4413 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
4414 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
4415 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
4416 Module *ResolvedMod = getSubmodule(GlobalID);
4418 switch (Unresolved.Kind) {
4419 case UnresolvedModuleRef::Conflict:
4420 if (ResolvedMod) {
4421 Module::Conflict Conflict;
4422 Conflict.Other = ResolvedMod;
4423 Conflict.Message = Unresolved.String.str();
4424 Unresolved.Mod->Conflicts.push_back(Conflict);
4426 continue;
4428 case UnresolvedModuleRef::Import:
4429 if (ResolvedMod)
4430 Unresolved.Mod->Imports.insert(ResolvedMod);
4431 continue;
4433 case UnresolvedModuleRef::Affecting:
4434 if (ResolvedMod)
4435 Unresolved.Mod->AffectingClangModules.insert(ResolvedMod);
4436 continue;
4438 case UnresolvedModuleRef::Export:
4439 if (ResolvedMod || Unresolved.IsWildcard)
4440 Unresolved.Mod->Exports.push_back(
4441 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
4442 continue;
4445 UnresolvedModuleRefs.clear();
4447 if (Imported)
4448 Imported->append(ImportedModules.begin(),
4449 ImportedModules.end());
4451 // FIXME: How do we load the 'use'd modules? They may not be submodules.
4452 // Might be unnecessary as use declarations are only used to build the
4453 // module itself.
4455 if (ContextObj)
4456 InitializeContext();
4458 if (SemaObj)
4459 UpdateSema();
4461 if (DeserializationListener)
4462 DeserializationListener->ReaderInitialized(this);
4464 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
4465 if (PrimaryModule.OriginalSourceFileID.isValid()) {
4466 // If this AST file is a precompiled preamble, then set the
4467 // preamble file ID of the source manager to the file source file
4468 // from which the preamble was built.
4469 if (Type == MK_Preamble) {
4470 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
4471 } else if (Type == MK_MainFile) {
4472 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
4476 // For any Objective-C class definitions we have already loaded, make sure
4477 // that we load any additional categories.
4478 if (ContextObj) {
4479 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
4480 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
4481 ObjCClassesLoaded[I],
4482 PreviousGeneration);
4486 if (PP.getHeaderSearchInfo()
4487 .getHeaderSearchOpts()
4488 .ModulesValidateOncePerBuildSession) {
4489 // Now we are certain that the module and all modules it depends on are
4490 // up to date. Create or update timestamp files for modules that are
4491 // located in the module cache (not for PCH files that could be anywhere
4492 // in the filesystem).
4493 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
4494 ImportedModule &M = Loaded[I];
4495 if (M.Mod->Kind == MK_ImplicitModule) {
4496 updateModuleTimestamp(*M.Mod);
4501 return Success;
4504 static ASTFileSignature readASTFileSignature(StringRef PCH);
4506 /// Whether \p Stream doesn't start with the AST/PCH file magic number 'CPCH'.
4507 static llvm::Error doesntStartWithASTFileMagic(BitstreamCursor &Stream) {
4508 // FIXME checking magic headers is done in other places such as
4509 // SerializedDiagnosticReader and GlobalModuleIndex, but error handling isn't
4510 // always done the same. Unify it all with a helper.
4511 if (!Stream.canSkipToPos(4))
4512 return llvm::createStringError(std::errc::illegal_byte_sequence,
4513 "file too small to contain AST file magic");
4514 for (unsigned C : {'C', 'P', 'C', 'H'})
4515 if (Expected<llvm::SimpleBitstreamCursor::word_t> Res = Stream.Read(8)) {
4516 if (Res.get() != C)
4517 return llvm::createStringError(
4518 std::errc::illegal_byte_sequence,
4519 "file doesn't start with AST file magic");
4520 } else
4521 return Res.takeError();
4522 return llvm::Error::success();
4525 static unsigned moduleKindForDiagnostic(ModuleKind Kind) {
4526 switch (Kind) {
4527 case MK_PCH:
4528 return 0; // PCH
4529 case MK_ImplicitModule:
4530 case MK_ExplicitModule:
4531 case MK_PrebuiltModule:
4532 return 1; // module
4533 case MK_MainFile:
4534 case MK_Preamble:
4535 return 2; // main source file
4537 llvm_unreachable("unknown module kind");
4540 ASTReader::ASTReadResult
4541 ASTReader::ReadASTCore(StringRef FileName,
4542 ModuleKind Type,
4543 SourceLocation ImportLoc,
4544 ModuleFile *ImportedBy,
4545 SmallVectorImpl<ImportedModule> &Loaded,
4546 off_t ExpectedSize, time_t ExpectedModTime,
4547 ASTFileSignature ExpectedSignature,
4548 unsigned ClientLoadCapabilities) {
4549 ModuleFile *M;
4550 std::string ErrorStr;
4551 ModuleManager::AddModuleResult AddResult
4552 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
4553 getGeneration(), ExpectedSize, ExpectedModTime,
4554 ExpectedSignature, readASTFileSignature,
4555 M, ErrorStr);
4557 switch (AddResult) {
4558 case ModuleManager::AlreadyLoaded:
4559 Diag(diag::remark_module_import)
4560 << M->ModuleName << M->FileName << (ImportedBy ? true : false)
4561 << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());
4562 return Success;
4564 case ModuleManager::NewlyLoaded:
4565 // Load module file below.
4566 break;
4568 case ModuleManager::Missing:
4569 // The module file was missing; if the client can handle that, return
4570 // it.
4571 if (ClientLoadCapabilities & ARR_Missing)
4572 return Missing;
4574 // Otherwise, return an error.
4575 Diag(diag::err_ast_file_not_found)
4576 << moduleKindForDiagnostic(Type) << FileName << !ErrorStr.empty()
4577 << ErrorStr;
4578 return Failure;
4580 case ModuleManager::OutOfDate:
4581 // We couldn't load the module file because it is out-of-date. If the
4582 // client can handle out-of-date, return it.
4583 if (ClientLoadCapabilities & ARR_OutOfDate)
4584 return OutOfDate;
4586 // Otherwise, return an error.
4587 Diag(diag::err_ast_file_out_of_date)
4588 << moduleKindForDiagnostic(Type) << FileName << !ErrorStr.empty()
4589 << ErrorStr;
4590 return Failure;
4593 assert(M && "Missing module file");
4595 bool ShouldFinalizePCM = false;
4596 auto FinalizeOrDropPCM = llvm::make_scope_exit([&]() {
4597 auto &MC = getModuleManager().getModuleCache();
4598 if (ShouldFinalizePCM)
4599 MC.finalizePCM(FileName);
4600 else
4601 MC.tryToDropPCM(FileName);
4603 ModuleFile &F = *M;
4604 BitstreamCursor &Stream = F.Stream;
4605 Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(*F.Buffer));
4606 F.SizeInBits = F.Buffer->getBufferSize() * 8;
4608 // Sniff for the signature.
4609 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
4610 Diag(diag::err_ast_file_invalid)
4611 << moduleKindForDiagnostic(Type) << FileName << std::move(Err);
4612 return Failure;
4615 // This is used for compatibility with older PCH formats.
4616 bool HaveReadControlBlock = false;
4617 while (true) {
4618 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4619 if (!MaybeEntry) {
4620 Error(MaybeEntry.takeError());
4621 return Failure;
4623 llvm::BitstreamEntry Entry = MaybeEntry.get();
4625 switch (Entry.Kind) {
4626 case llvm::BitstreamEntry::Error:
4627 case llvm::BitstreamEntry::Record:
4628 case llvm::BitstreamEntry::EndBlock:
4629 Error("invalid record at top-level of AST file");
4630 return Failure;
4632 case llvm::BitstreamEntry::SubBlock:
4633 break;
4636 switch (Entry.ID) {
4637 case CONTROL_BLOCK_ID:
4638 HaveReadControlBlock = true;
4639 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
4640 case Success:
4641 // Check that we didn't try to load a non-module AST file as a module.
4643 // FIXME: Should we also perform the converse check? Loading a module as
4644 // a PCH file sort of works, but it's a bit wonky.
4645 if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule ||
4646 Type == MK_PrebuiltModule) &&
4647 F.ModuleName.empty()) {
4648 auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
4649 if (Result != OutOfDate ||
4650 (ClientLoadCapabilities & ARR_OutOfDate) == 0)
4651 Diag(diag::err_module_file_not_module) << FileName;
4652 return Result;
4654 break;
4656 case Failure: return Failure;
4657 case Missing: return Missing;
4658 case OutOfDate: return OutOfDate;
4659 case VersionMismatch: return VersionMismatch;
4660 case ConfigurationMismatch: return ConfigurationMismatch;
4661 case HadErrors: return HadErrors;
4663 break;
4665 case AST_BLOCK_ID:
4666 if (!HaveReadControlBlock) {
4667 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
4668 Diag(diag::err_pch_version_too_old);
4669 return VersionMismatch;
4672 // Record that we've loaded this module.
4673 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
4674 ShouldFinalizePCM = true;
4675 return Success;
4677 case UNHASHED_CONTROL_BLOCK_ID:
4678 // This block is handled using look-ahead during ReadControlBlock. We
4679 // shouldn't get here!
4680 Error("malformed block record in AST file");
4681 return Failure;
4683 default:
4684 if (llvm::Error Err = Stream.SkipBlock()) {
4685 Error(std::move(Err));
4686 return Failure;
4688 break;
4692 llvm_unreachable("unexpected break; expected return");
4695 ASTReader::ASTReadResult
4696 ASTReader::readUnhashedControlBlock(ModuleFile &F, bool WasImportedBy,
4697 unsigned ClientLoadCapabilities) {
4698 const HeaderSearchOptions &HSOpts =
4699 PP.getHeaderSearchInfo().getHeaderSearchOpts();
4700 bool AllowCompatibleConfigurationMismatch =
4701 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
4702 bool DisableValidation = shouldDisableValidationForFile(F);
4704 ASTReadResult Result = readUnhashedControlBlockImpl(
4705 &F, F.Data, ClientLoadCapabilities, AllowCompatibleConfigurationMismatch,
4706 Listener.get(),
4707 WasImportedBy ? false : HSOpts.ModulesValidateDiagnosticOptions);
4709 // If F was directly imported by another module, it's implicitly validated by
4710 // the importing module.
4711 if (DisableValidation || WasImportedBy ||
4712 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
4713 return Success;
4715 if (Result == Failure) {
4716 Error("malformed block record in AST file");
4717 return Failure;
4720 if (Result == OutOfDate && F.Kind == MK_ImplicitModule) {
4721 // If this module has already been finalized in the ModuleCache, we're stuck
4722 // with it; we can only load a single version of each module.
4724 // This can happen when a module is imported in two contexts: in one, as a
4725 // user module; in another, as a system module (due to an import from
4726 // another module marked with the [system] flag). It usually indicates a
4727 // bug in the module map: this module should also be marked with [system].
4729 // If -Wno-system-headers (the default), and the first import is as a
4730 // system module, then validation will fail during the as-user import,
4731 // since -Werror flags won't have been validated. However, it's reasonable
4732 // to treat this consistently as a system module.
4734 // If -Wsystem-headers, the PCM on disk was built with
4735 // -Wno-system-headers, and the first import is as a user module, then
4736 // validation will fail during the as-system import since the PCM on disk
4737 // doesn't guarantee that -Werror was respected. However, the -Werror
4738 // flags were checked during the initial as-user import.
4739 if (getModuleManager().getModuleCache().isPCMFinal(F.FileName)) {
4740 Diag(diag::warn_module_system_bit_conflict) << F.FileName;
4741 return Success;
4745 return Result;
4748 ASTReader::ASTReadResult ASTReader::readUnhashedControlBlockImpl(
4749 ModuleFile *F, llvm::StringRef StreamData, unsigned ClientLoadCapabilities,
4750 bool AllowCompatibleConfigurationMismatch, ASTReaderListener *Listener,
4751 bool ValidateDiagnosticOptions) {
4752 // Initialize a stream.
4753 BitstreamCursor Stream(StreamData);
4755 // Sniff for the signature.
4756 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
4757 // FIXME this drops the error on the floor.
4758 consumeError(std::move(Err));
4759 return Failure;
4762 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4763 if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
4764 return Failure;
4766 // Read all of the records in the options block.
4767 RecordData Record;
4768 ASTReadResult Result = Success;
4769 while (true) {
4770 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4771 if (!MaybeEntry) {
4772 // FIXME this drops the error on the floor.
4773 consumeError(MaybeEntry.takeError());
4774 return Failure;
4776 llvm::BitstreamEntry Entry = MaybeEntry.get();
4778 switch (Entry.Kind) {
4779 case llvm::BitstreamEntry::Error:
4780 case llvm::BitstreamEntry::SubBlock:
4781 return Failure;
4783 case llvm::BitstreamEntry::EndBlock:
4784 return Result;
4786 case llvm::BitstreamEntry::Record:
4787 // The interesting case.
4788 break;
4791 // Read and process a record.
4792 Record.clear();
4793 StringRef Blob;
4794 Expected<unsigned> MaybeRecordType =
4795 Stream.readRecord(Entry.ID, Record, &Blob);
4796 if (!MaybeRecordType) {
4797 // FIXME this drops the error.
4798 return Failure;
4800 switch ((UnhashedControlBlockRecordTypes)MaybeRecordType.get()) {
4801 case SIGNATURE:
4802 if (F)
4803 F->Signature = ASTFileSignature::create(Record.begin(), Record.end());
4804 break;
4805 case AST_BLOCK_HASH:
4806 if (F)
4807 F->ASTBlockHash =
4808 ASTFileSignature::create(Record.begin(), Record.end());
4809 break;
4810 case DIAGNOSTIC_OPTIONS: {
4811 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
4812 if (Listener && ValidateDiagnosticOptions &&
4813 !AllowCompatibleConfigurationMismatch &&
4814 ParseDiagnosticOptions(Record, Complain, *Listener))
4815 Result = OutOfDate; // Don't return early. Read the signature.
4816 break;
4818 case HEADER_SEARCH_PATHS: {
4819 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
4820 if (!AllowCompatibleConfigurationMismatch &&
4821 ParseHeaderSearchPaths(Record, Complain, *Listener))
4822 Result = ConfigurationMismatch;
4823 break;
4825 case DIAG_PRAGMA_MAPPINGS:
4826 if (!F)
4827 break;
4828 if (F->PragmaDiagMappings.empty())
4829 F->PragmaDiagMappings.swap(Record);
4830 else
4831 F->PragmaDiagMappings.insert(F->PragmaDiagMappings.end(),
4832 Record.begin(), Record.end());
4833 break;
4834 case HEADER_SEARCH_ENTRY_USAGE:
4835 if (!F)
4836 break;
4837 unsigned Count = Record[0];
4838 const char *Byte = Blob.data();
4839 F->SearchPathUsage = llvm::BitVector(Count, false);
4840 for (unsigned I = 0; I < Count; ++Byte)
4841 for (unsigned Bit = 0; Bit < 8 && I < Count; ++Bit, ++I)
4842 if (*Byte & (1 << Bit))
4843 F->SearchPathUsage[I] = true;
4844 break;
4849 /// Parse a record and blob containing module file extension metadata.
4850 static bool parseModuleFileExtensionMetadata(
4851 const SmallVectorImpl<uint64_t> &Record,
4852 StringRef Blob,
4853 ModuleFileExtensionMetadata &Metadata) {
4854 if (Record.size() < 4) return true;
4856 Metadata.MajorVersion = Record[0];
4857 Metadata.MinorVersion = Record[1];
4859 unsigned BlockNameLen = Record[2];
4860 unsigned UserInfoLen = Record[3];
4862 if (BlockNameLen + UserInfoLen > Blob.size()) return true;
4864 Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
4865 Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,
4866 Blob.data() + BlockNameLen + UserInfoLen);
4867 return false;
4870 llvm::Error ASTReader::ReadExtensionBlock(ModuleFile &F) {
4871 BitstreamCursor &Stream = F.Stream;
4873 RecordData Record;
4874 while (true) {
4875 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4876 if (!MaybeEntry)
4877 return MaybeEntry.takeError();
4878 llvm::BitstreamEntry Entry = MaybeEntry.get();
4880 switch (Entry.Kind) {
4881 case llvm::BitstreamEntry::SubBlock:
4882 if (llvm::Error Err = Stream.SkipBlock())
4883 return Err;
4884 continue;
4885 case llvm::BitstreamEntry::EndBlock:
4886 return llvm::Error::success();
4887 case llvm::BitstreamEntry::Error:
4888 return llvm::createStringError(std::errc::illegal_byte_sequence,
4889 "malformed block record in AST file");
4890 case llvm::BitstreamEntry::Record:
4891 break;
4894 Record.clear();
4895 StringRef Blob;
4896 Expected<unsigned> MaybeRecCode =
4897 Stream.readRecord(Entry.ID, Record, &Blob);
4898 if (!MaybeRecCode)
4899 return MaybeRecCode.takeError();
4900 switch (MaybeRecCode.get()) {
4901 case EXTENSION_METADATA: {
4902 ModuleFileExtensionMetadata Metadata;
4903 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
4904 return llvm::createStringError(
4905 std::errc::illegal_byte_sequence,
4906 "malformed EXTENSION_METADATA in AST file");
4908 // Find a module file extension with this block name.
4909 auto Known = ModuleFileExtensions.find(Metadata.BlockName);
4910 if (Known == ModuleFileExtensions.end()) break;
4912 // Form a reader.
4913 if (auto Reader = Known->second->createExtensionReader(Metadata, *this,
4914 F, Stream)) {
4915 F.ExtensionReaders.push_back(std::move(Reader));
4918 break;
4923 return llvm::Error::success();
4926 void ASTReader::InitializeContext() {
4927 assert(ContextObj && "no context to initialize");
4928 ASTContext &Context = *ContextObj;
4930 // If there's a listener, notify them that we "read" the translation unit.
4931 if (DeserializationListener)
4932 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
4933 Context.getTranslationUnitDecl());
4935 // FIXME: Find a better way to deal with collisions between these
4936 // built-in types. Right now, we just ignore the problem.
4938 // Load the special types.
4939 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
4940 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
4941 if (!Context.CFConstantStringTypeDecl)
4942 Context.setCFConstantStringType(GetType(String));
4945 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
4946 QualType FileType = GetType(File);
4947 if (FileType.isNull()) {
4948 Error("FILE type is NULL");
4949 return;
4952 if (!Context.FILEDecl) {
4953 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
4954 Context.setFILEDecl(Typedef->getDecl());
4955 else {
4956 const TagType *Tag = FileType->getAs<TagType>();
4957 if (!Tag) {
4958 Error("Invalid FILE type in AST file");
4959 return;
4961 Context.setFILEDecl(Tag->getDecl());
4966 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
4967 QualType Jmp_bufType = GetType(Jmp_buf);
4968 if (Jmp_bufType.isNull()) {
4969 Error("jmp_buf type is NULL");
4970 return;
4973 if (!Context.jmp_bufDecl) {
4974 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
4975 Context.setjmp_bufDecl(Typedef->getDecl());
4976 else {
4977 const TagType *Tag = Jmp_bufType->getAs<TagType>();
4978 if (!Tag) {
4979 Error("Invalid jmp_buf type in AST file");
4980 return;
4982 Context.setjmp_bufDecl(Tag->getDecl());
4987 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
4988 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
4989 if (Sigjmp_bufType.isNull()) {
4990 Error("sigjmp_buf type is NULL");
4991 return;
4994 if (!Context.sigjmp_bufDecl) {
4995 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
4996 Context.setsigjmp_bufDecl(Typedef->getDecl());
4997 else {
4998 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
4999 assert(Tag && "Invalid sigjmp_buf type in AST file");
5000 Context.setsigjmp_bufDecl(Tag->getDecl());
5005 if (unsigned ObjCIdRedef
5006 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
5007 if (Context.ObjCIdRedefinitionType.isNull())
5008 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
5011 if (unsigned ObjCClassRedef
5012 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
5013 if (Context.ObjCClassRedefinitionType.isNull())
5014 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
5017 if (unsigned ObjCSelRedef
5018 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
5019 if (Context.ObjCSelRedefinitionType.isNull())
5020 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
5023 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
5024 QualType Ucontext_tType = GetType(Ucontext_t);
5025 if (Ucontext_tType.isNull()) {
5026 Error("ucontext_t type is NULL");
5027 return;
5030 if (!Context.ucontext_tDecl) {
5031 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
5032 Context.setucontext_tDecl(Typedef->getDecl());
5033 else {
5034 const TagType *Tag = Ucontext_tType->getAs<TagType>();
5035 assert(Tag && "Invalid ucontext_t type in AST file");
5036 Context.setucontext_tDecl(Tag->getDecl());
5042 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
5044 // If there were any CUDA special declarations, deserialize them.
5045 if (!CUDASpecialDeclRefs.empty()) {
5046 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
5047 Context.setcudaConfigureCallDecl(
5048 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
5051 // Re-export any modules that were imported by a non-module AST file.
5052 // FIXME: This does not make macro-only imports visible again.
5053 for (auto &Import : ImportedModules) {
5054 if (Module *Imported = getSubmodule(Import.ID)) {
5055 makeModuleVisible(Imported, Module::AllVisible,
5056 /*ImportLoc=*/Import.ImportLoc);
5057 if (Import.ImportLoc.isValid())
5058 PP.makeModuleVisible(Imported, Import.ImportLoc);
5059 // This updates visibility for Preprocessor only. For Sema, which can be
5060 // nullptr here, we do the same later, in UpdateSema().
5065 void ASTReader::finalizeForWriting() {
5066 // Nothing to do for now.
5069 /// Reads and return the signature record from \p PCH's control block, or
5070 /// else returns 0.
5071 static ASTFileSignature readASTFileSignature(StringRef PCH) {
5072 BitstreamCursor Stream(PCH);
5073 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5074 // FIXME this drops the error on the floor.
5075 consumeError(std::move(Err));
5076 return ASTFileSignature();
5079 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
5080 if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
5081 return ASTFileSignature();
5083 // Scan for SIGNATURE inside the diagnostic options block.
5084 ASTReader::RecordData Record;
5085 while (true) {
5086 Expected<llvm::BitstreamEntry> MaybeEntry =
5087 Stream.advanceSkippingSubblocks();
5088 if (!MaybeEntry) {
5089 // FIXME this drops the error on the floor.
5090 consumeError(MaybeEntry.takeError());
5091 return ASTFileSignature();
5093 llvm::BitstreamEntry Entry = MaybeEntry.get();
5095 if (Entry.Kind != llvm::BitstreamEntry::Record)
5096 return ASTFileSignature();
5098 Record.clear();
5099 StringRef Blob;
5100 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);
5101 if (!MaybeRecord) {
5102 // FIXME this drops the error on the floor.
5103 consumeError(MaybeRecord.takeError());
5104 return ASTFileSignature();
5106 if (SIGNATURE == MaybeRecord.get())
5107 return ASTFileSignature::create(Record.begin(),
5108 Record.begin() + ASTFileSignature::size);
5112 /// Retrieve the name of the original source file name
5113 /// directly from the AST file, without actually loading the AST
5114 /// file.
5115 std::string ASTReader::getOriginalSourceFile(
5116 const std::string &ASTFileName, FileManager &FileMgr,
5117 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
5118 // Open the AST file.
5119 auto Buffer = FileMgr.getBufferForFile(ASTFileName, /*IsVolatile=*/false,
5120 /*RequiresNullTerminator=*/false);
5121 if (!Buffer) {
5122 Diags.Report(diag::err_fe_unable_to_read_pch_file)
5123 << ASTFileName << Buffer.getError().message();
5124 return std::string();
5127 // Initialize the stream
5128 BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer));
5130 // Sniff for the signature.
5131 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5132 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName << std::move(Err);
5133 return std::string();
5136 // Scan for the CONTROL_BLOCK_ID block.
5137 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
5138 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
5139 return std::string();
5142 // Scan for ORIGINAL_FILE inside the control block.
5143 RecordData Record;
5144 while (true) {
5145 Expected<llvm::BitstreamEntry> MaybeEntry =
5146 Stream.advanceSkippingSubblocks();
5147 if (!MaybeEntry) {
5148 // FIXME this drops errors on the floor.
5149 consumeError(MaybeEntry.takeError());
5150 return std::string();
5152 llvm::BitstreamEntry Entry = MaybeEntry.get();
5154 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
5155 return std::string();
5157 if (Entry.Kind != llvm::BitstreamEntry::Record) {
5158 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
5159 return std::string();
5162 Record.clear();
5163 StringRef Blob;
5164 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);
5165 if (!MaybeRecord) {
5166 // FIXME this drops the errors on the floor.
5167 consumeError(MaybeRecord.takeError());
5168 return std::string();
5170 if (ORIGINAL_FILE == MaybeRecord.get())
5171 return Blob.str();
5175 namespace {
5177 class SimplePCHValidator : public ASTReaderListener {
5178 const LangOptions &ExistingLangOpts;
5179 const TargetOptions &ExistingTargetOpts;
5180 const PreprocessorOptions &ExistingPPOpts;
5181 std::string ExistingModuleCachePath;
5182 FileManager &FileMgr;
5183 bool StrictOptionMatches;
5185 public:
5186 SimplePCHValidator(const LangOptions &ExistingLangOpts,
5187 const TargetOptions &ExistingTargetOpts,
5188 const PreprocessorOptions &ExistingPPOpts,
5189 StringRef ExistingModuleCachePath, FileManager &FileMgr,
5190 bool StrictOptionMatches)
5191 : ExistingLangOpts(ExistingLangOpts),
5192 ExistingTargetOpts(ExistingTargetOpts),
5193 ExistingPPOpts(ExistingPPOpts),
5194 ExistingModuleCachePath(ExistingModuleCachePath), FileMgr(FileMgr),
5195 StrictOptionMatches(StrictOptionMatches) {}
5197 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
5198 bool AllowCompatibleDifferences) override {
5199 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
5200 AllowCompatibleDifferences);
5203 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
5204 bool AllowCompatibleDifferences) override {
5205 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
5206 AllowCompatibleDifferences);
5209 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
5210 StringRef SpecificModuleCachePath,
5211 bool Complain) override {
5212 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
5213 ExistingModuleCachePath, nullptr,
5214 ExistingLangOpts, ExistingPPOpts);
5217 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
5218 bool Complain,
5219 std::string &SuggestedPredefines) override {
5220 return checkPreprocessorOptions(
5221 PPOpts, ExistingPPOpts, /*Diags=*/nullptr, FileMgr,
5222 SuggestedPredefines, ExistingLangOpts,
5223 StrictOptionMatches ? OptionValidateStrictMatches
5224 : OptionValidateContradictions);
5228 } // namespace
5230 bool ASTReader::readASTFileControlBlock(
5231 StringRef Filename, FileManager &FileMgr,
5232 const InMemoryModuleCache &ModuleCache,
5233 const PCHContainerReader &PCHContainerRdr, bool FindModuleFileExtensions,
5234 ASTReaderListener &Listener, bool ValidateDiagnosticOptions) {
5235 // Open the AST file.
5236 std::unique_ptr<llvm::MemoryBuffer> OwnedBuffer;
5237 llvm::MemoryBuffer *Buffer = ModuleCache.lookupPCM(Filename);
5238 if (!Buffer) {
5239 // FIXME: We should add the pcm to the InMemoryModuleCache if it could be
5240 // read again later, but we do not have the context here to determine if it
5241 // is safe to change the result of InMemoryModuleCache::getPCMState().
5243 // FIXME: This allows use of the VFS; we do not allow use of the
5244 // VFS when actually loading a module.
5245 auto BufferOrErr = FileMgr.getBufferForFile(Filename);
5246 if (!BufferOrErr)
5247 return true;
5248 OwnedBuffer = std::move(*BufferOrErr);
5249 Buffer = OwnedBuffer.get();
5252 // Initialize the stream
5253 StringRef Bytes = PCHContainerRdr.ExtractPCH(*Buffer);
5254 BitstreamCursor Stream(Bytes);
5256 // Sniff for the signature.
5257 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5258 consumeError(std::move(Err)); // FIXME this drops errors on the floor.
5259 return true;
5262 // Scan for the CONTROL_BLOCK_ID block.
5263 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
5264 return true;
5266 bool NeedsInputFiles = Listener.needsInputFileVisitation();
5267 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
5268 bool NeedsImports = Listener.needsImportVisitation();
5269 BitstreamCursor InputFilesCursor;
5271 RecordData Record;
5272 std::string ModuleDir;
5273 bool DoneWithControlBlock = false;
5274 while (!DoneWithControlBlock) {
5275 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5276 if (!MaybeEntry) {
5277 // FIXME this drops the error on the floor.
5278 consumeError(MaybeEntry.takeError());
5279 return true;
5281 llvm::BitstreamEntry Entry = MaybeEntry.get();
5283 switch (Entry.Kind) {
5284 case llvm::BitstreamEntry::SubBlock: {
5285 switch (Entry.ID) {
5286 case OPTIONS_BLOCK_ID: {
5287 std::string IgnoredSuggestedPredefines;
5288 if (ReadOptionsBlock(Stream, ARR_ConfigurationMismatch | ARR_OutOfDate,
5289 /*AllowCompatibleConfigurationMismatch*/ false,
5290 Listener, IgnoredSuggestedPredefines) != Success)
5291 return true;
5292 break;
5295 case INPUT_FILES_BLOCK_ID:
5296 InputFilesCursor = Stream;
5297 if (llvm::Error Err = Stream.SkipBlock()) {
5298 // FIXME this drops the error on the floor.
5299 consumeError(std::move(Err));
5300 return true;
5302 if (NeedsInputFiles &&
5303 ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID))
5304 return true;
5305 break;
5307 default:
5308 if (llvm::Error Err = Stream.SkipBlock()) {
5309 // FIXME this drops the error on the floor.
5310 consumeError(std::move(Err));
5311 return true;
5313 break;
5316 continue;
5319 case llvm::BitstreamEntry::EndBlock:
5320 DoneWithControlBlock = true;
5321 break;
5323 case llvm::BitstreamEntry::Error:
5324 return true;
5326 case llvm::BitstreamEntry::Record:
5327 break;
5330 if (DoneWithControlBlock) break;
5332 Record.clear();
5333 StringRef Blob;
5334 Expected<unsigned> MaybeRecCode =
5335 Stream.readRecord(Entry.ID, Record, &Blob);
5336 if (!MaybeRecCode) {
5337 // FIXME this drops the error.
5338 return Failure;
5340 switch ((ControlRecordTypes)MaybeRecCode.get()) {
5341 case METADATA:
5342 if (Record[0] != VERSION_MAJOR)
5343 return true;
5344 if (Listener.ReadFullVersionInformation(Blob))
5345 return true;
5346 break;
5347 case MODULE_NAME:
5348 Listener.ReadModuleName(Blob);
5349 break;
5350 case MODULE_DIRECTORY:
5351 ModuleDir = std::string(Blob);
5352 break;
5353 case MODULE_MAP_FILE: {
5354 unsigned Idx = 0;
5355 auto Path = ReadString(Record, Idx);
5356 ResolveImportedPath(Path, ModuleDir);
5357 Listener.ReadModuleMapFile(Path);
5358 break;
5360 case INPUT_FILE_OFFSETS: {
5361 if (!NeedsInputFiles)
5362 break;
5364 unsigned NumInputFiles = Record[0];
5365 unsigned NumUserFiles = Record[1];
5366 const llvm::support::unaligned_uint64_t *InputFileOffs =
5367 (const llvm::support::unaligned_uint64_t *)Blob.data();
5368 for (unsigned I = 0; I != NumInputFiles; ++I) {
5369 // Go find this input file.
5370 bool isSystemFile = I >= NumUserFiles;
5372 if (isSystemFile && !NeedsSystemInputFiles)
5373 break; // the rest are system input files
5375 BitstreamCursor &Cursor = InputFilesCursor;
5376 SavedStreamPosition SavedPosition(Cursor);
5377 if (llvm::Error Err = Cursor.JumpToBit(InputFileOffs[I])) {
5378 // FIXME this drops errors on the floor.
5379 consumeError(std::move(Err));
5382 Expected<unsigned> MaybeCode = Cursor.ReadCode();
5383 if (!MaybeCode) {
5384 // FIXME this drops errors on the floor.
5385 consumeError(MaybeCode.takeError());
5387 unsigned Code = MaybeCode.get();
5389 RecordData Record;
5390 StringRef Blob;
5391 bool shouldContinue = false;
5392 Expected<unsigned> MaybeRecordType =
5393 Cursor.readRecord(Code, Record, &Blob);
5394 if (!MaybeRecordType) {
5395 // FIXME this drops errors on the floor.
5396 consumeError(MaybeRecordType.takeError());
5398 switch ((InputFileRecordTypes)MaybeRecordType.get()) {
5399 case INPUT_FILE_HASH:
5400 break;
5401 case INPUT_FILE:
5402 bool Overridden = static_cast<bool>(Record[3]);
5403 std::string Filename = std::string(Blob);
5404 ResolveImportedPath(Filename, ModuleDir);
5405 shouldContinue = Listener.visitInputFile(
5406 Filename, isSystemFile, Overridden, /*IsExplicitModule*/false);
5407 break;
5409 if (!shouldContinue)
5410 break;
5412 break;
5415 case IMPORTS: {
5416 if (!NeedsImports)
5417 break;
5419 unsigned Idx = 0, N = Record.size();
5420 while (Idx < N) {
5421 // Read information about the AST file.
5422 Idx +=
5423 1 + 1 + 1 + 1 +
5424 ASTFileSignature::size; // Kind, ImportLoc, Size, ModTime, Signature
5425 std::string ModuleName = ReadString(Record, Idx);
5426 std::string Filename = ReadString(Record, Idx);
5427 ResolveImportedPath(Filename, ModuleDir);
5428 Listener.visitImport(ModuleName, Filename);
5430 break;
5433 default:
5434 // No other validation to perform.
5435 break;
5439 // Look for module file extension blocks, if requested.
5440 if (FindModuleFileExtensions) {
5441 BitstreamCursor SavedStream = Stream;
5442 while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {
5443 bool DoneWithExtensionBlock = false;
5444 while (!DoneWithExtensionBlock) {
5445 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5446 if (!MaybeEntry) {
5447 // FIXME this drops the error.
5448 return true;
5450 llvm::BitstreamEntry Entry = MaybeEntry.get();
5452 switch (Entry.Kind) {
5453 case llvm::BitstreamEntry::SubBlock:
5454 if (llvm::Error Err = Stream.SkipBlock()) {
5455 // FIXME this drops the error on the floor.
5456 consumeError(std::move(Err));
5457 return true;
5459 continue;
5461 case llvm::BitstreamEntry::EndBlock:
5462 DoneWithExtensionBlock = true;
5463 continue;
5465 case llvm::BitstreamEntry::Error:
5466 return true;
5468 case llvm::BitstreamEntry::Record:
5469 break;
5472 Record.clear();
5473 StringRef Blob;
5474 Expected<unsigned> MaybeRecCode =
5475 Stream.readRecord(Entry.ID, Record, &Blob);
5476 if (!MaybeRecCode) {
5477 // FIXME this drops the error.
5478 return true;
5480 switch (MaybeRecCode.get()) {
5481 case EXTENSION_METADATA: {
5482 ModuleFileExtensionMetadata Metadata;
5483 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
5484 return true;
5486 Listener.readModuleFileExtension(Metadata);
5487 break;
5492 Stream = SavedStream;
5495 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
5496 if (readUnhashedControlBlockImpl(
5497 nullptr, Bytes, ARR_ConfigurationMismatch | ARR_OutOfDate,
5498 /*AllowCompatibleConfigurationMismatch*/ false, &Listener,
5499 ValidateDiagnosticOptions) != Success)
5500 return true;
5502 return false;
5505 bool ASTReader::isAcceptableASTFile(StringRef Filename, FileManager &FileMgr,
5506 const InMemoryModuleCache &ModuleCache,
5507 const PCHContainerReader &PCHContainerRdr,
5508 const LangOptions &LangOpts,
5509 const TargetOptions &TargetOpts,
5510 const PreprocessorOptions &PPOpts,
5511 StringRef ExistingModuleCachePath,
5512 bool RequireStrictOptionMatches) {
5513 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
5514 ExistingModuleCachePath, FileMgr,
5515 RequireStrictOptionMatches);
5516 return !readASTFileControlBlock(Filename, FileMgr, ModuleCache,
5517 PCHContainerRdr,
5518 /*FindModuleFileExtensions=*/false, validator,
5519 /*ValidateDiagnosticOptions=*/true);
5522 llvm::Error ASTReader::ReadSubmoduleBlock(ModuleFile &F,
5523 unsigned ClientLoadCapabilities) {
5524 // Enter the submodule block.
5525 if (llvm::Error Err = F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID))
5526 return Err;
5528 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
5529 bool First = true;
5530 Module *CurrentModule = nullptr;
5531 RecordData Record;
5532 while (true) {
5533 Expected<llvm::BitstreamEntry> MaybeEntry =
5534 F.Stream.advanceSkippingSubblocks();
5535 if (!MaybeEntry)
5536 return MaybeEntry.takeError();
5537 llvm::BitstreamEntry Entry = MaybeEntry.get();
5539 switch (Entry.Kind) {
5540 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
5541 case llvm::BitstreamEntry::Error:
5542 return llvm::createStringError(std::errc::illegal_byte_sequence,
5543 "malformed block record in AST file");
5544 case llvm::BitstreamEntry::EndBlock:
5545 return llvm::Error::success();
5546 case llvm::BitstreamEntry::Record:
5547 // The interesting case.
5548 break;
5551 // Read a record.
5552 StringRef Blob;
5553 Record.clear();
5554 Expected<unsigned> MaybeKind = F.Stream.readRecord(Entry.ID, Record, &Blob);
5555 if (!MaybeKind)
5556 return MaybeKind.takeError();
5557 unsigned Kind = MaybeKind.get();
5559 if ((Kind == SUBMODULE_METADATA) != First)
5560 return llvm::createStringError(
5561 std::errc::illegal_byte_sequence,
5562 "submodule metadata record should be at beginning of block");
5563 First = false;
5565 // Submodule information is only valid if we have a current module.
5566 // FIXME: Should we error on these cases?
5567 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
5568 Kind != SUBMODULE_DEFINITION)
5569 continue;
5571 switch (Kind) {
5572 default: // Default behavior: ignore.
5573 break;
5575 case SUBMODULE_DEFINITION: {
5576 if (Record.size() < 12)
5577 return llvm::createStringError(std::errc::illegal_byte_sequence,
5578 "malformed module definition");
5580 StringRef Name = Blob;
5581 unsigned Idx = 0;
5582 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
5583 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
5584 Module::ModuleKind Kind = (Module::ModuleKind)Record[Idx++];
5585 bool IsFramework = Record[Idx++];
5586 bool IsExplicit = Record[Idx++];
5587 bool IsSystem = Record[Idx++];
5588 bool IsExternC = Record[Idx++];
5589 bool InferSubmodules = Record[Idx++];
5590 bool InferExplicitSubmodules = Record[Idx++];
5591 bool InferExportWildcard = Record[Idx++];
5592 bool ConfigMacrosExhaustive = Record[Idx++];
5593 bool ModuleMapIsPrivate = Record[Idx++];
5595 Module *ParentModule = nullptr;
5596 if (Parent)
5597 ParentModule = getSubmodule(Parent);
5599 // Retrieve this (sub)module from the module map, creating it if
5600 // necessary.
5601 CurrentModule =
5602 ModMap.findOrCreateModule(Name, ParentModule, IsFramework, IsExplicit)
5603 .first;
5605 // FIXME: set the definition loc for CurrentModule, or call
5606 // ModMap.setInferredModuleAllowedBy()
5608 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
5609 if (GlobalIndex >= SubmodulesLoaded.size() ||
5610 SubmodulesLoaded[GlobalIndex])
5611 return llvm::createStringError(std::errc::invalid_argument,
5612 "too many submodules");
5614 if (!ParentModule) {
5615 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
5616 // Don't emit module relocation error if we have -fno-validate-pch
5617 if (!bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation &
5618 DisableValidationForModuleKind::Module) &&
5619 CurFile != F.File) {
5620 auto ConflictError =
5621 PartialDiagnostic(diag::err_module_file_conflict,
5622 ContextObj->DiagAllocator)
5623 << CurrentModule->getTopLevelModuleName() << CurFile->getName()
5624 << F.File->getName();
5625 return DiagnosticError::create(CurrentImportLoc, ConflictError);
5629 F.DidReadTopLevelSubmodule = true;
5630 CurrentModule->setASTFile(F.File);
5631 CurrentModule->PresumedModuleMapFile = F.ModuleMapPath;
5634 CurrentModule->Kind = Kind;
5635 CurrentModule->Signature = F.Signature;
5636 CurrentModule->IsFromModuleFile = true;
5637 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
5638 CurrentModule->IsExternC = IsExternC;
5639 CurrentModule->InferSubmodules = InferSubmodules;
5640 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
5641 CurrentModule->InferExportWildcard = InferExportWildcard;
5642 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
5643 CurrentModule->ModuleMapIsPrivate = ModuleMapIsPrivate;
5644 if (DeserializationListener)
5645 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
5647 SubmodulesLoaded[GlobalIndex] = CurrentModule;
5649 // Clear out data that will be replaced by what is in the module file.
5650 CurrentModule->LinkLibraries.clear();
5651 CurrentModule->ConfigMacros.clear();
5652 CurrentModule->UnresolvedConflicts.clear();
5653 CurrentModule->Conflicts.clear();
5655 // The module is available unless it's missing a requirement; relevant
5656 // requirements will be (re-)added by SUBMODULE_REQUIRES records.
5657 // Missing headers that were present when the module was built do not
5658 // make it unavailable -- if we got this far, this must be an explicitly
5659 // imported module file.
5660 CurrentModule->Requirements.clear();
5661 CurrentModule->MissingHeaders.clear();
5662 CurrentModule->IsUnimportable =
5663 ParentModule && ParentModule->IsUnimportable;
5664 CurrentModule->IsAvailable = !CurrentModule->IsUnimportable;
5665 break;
5668 case SUBMODULE_UMBRELLA_HEADER: {
5669 // FIXME: This doesn't work for framework modules as `Filename` is the
5670 // name as written in the module file and does not include
5671 // `Headers/`, so this path will never exist.
5672 std::string Filename = std::string(Blob);
5673 ResolveImportedPath(F, Filename);
5674 if (auto Umbrella = PP.getFileManager().getOptionalFileRef(Filename)) {
5675 if (!CurrentModule->getUmbrellaHeader()) {
5676 // FIXME: NameAsWritten
5677 ModMap.setUmbrellaHeader(CurrentModule, *Umbrella, Blob, "");
5679 // Note that it's too late at this point to return out of date if the
5680 // name from the PCM doesn't match up with the one in the module map,
5681 // but also quite unlikely since we will have already checked the
5682 // modification time and size of the module map file itself.
5684 break;
5687 case SUBMODULE_HEADER:
5688 case SUBMODULE_EXCLUDED_HEADER:
5689 case SUBMODULE_PRIVATE_HEADER:
5690 // We lazily associate headers with their modules via the HeaderInfo table.
5691 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
5692 // of complete filenames or remove it entirely.
5693 break;
5695 case SUBMODULE_TEXTUAL_HEADER:
5696 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
5697 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
5698 // them here.
5699 break;
5701 case SUBMODULE_TOPHEADER: {
5702 std::string HeaderName(Blob);
5703 ResolveImportedPath(F, HeaderName);
5704 CurrentModule->addTopHeaderFilename(HeaderName);
5705 break;
5708 case SUBMODULE_UMBRELLA_DIR: {
5709 // See comments in SUBMODULE_UMBRELLA_HEADER
5710 std::string Dirname = std::string(Blob);
5711 ResolveImportedPath(F, Dirname);
5712 if (auto Umbrella = PP.getFileManager().getDirectory(Dirname)) {
5713 if (!CurrentModule->getUmbrellaDir()) {
5714 // FIXME: NameAsWritten
5715 ModMap.setUmbrellaDir(CurrentModule, *Umbrella, Blob, "");
5718 break;
5721 case SUBMODULE_METADATA: {
5722 F.BaseSubmoduleID = getTotalNumSubmodules();
5723 F.LocalNumSubmodules = Record[0];
5724 unsigned LocalBaseSubmoduleID = Record[1];
5725 if (F.LocalNumSubmodules > 0) {
5726 // Introduce the global -> local mapping for submodules within this
5727 // module.
5728 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
5730 // Introduce the local -> global mapping for submodules within this
5731 // module.
5732 F.SubmoduleRemap.insertOrReplace(
5733 std::make_pair(LocalBaseSubmoduleID,
5734 F.BaseSubmoduleID - LocalBaseSubmoduleID));
5736 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
5738 break;
5741 case SUBMODULE_IMPORTS:
5742 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
5743 UnresolvedModuleRef Unresolved;
5744 Unresolved.File = &F;
5745 Unresolved.Mod = CurrentModule;
5746 Unresolved.ID = Record[Idx];
5747 Unresolved.Kind = UnresolvedModuleRef::Import;
5748 Unresolved.IsWildcard = false;
5749 UnresolvedModuleRefs.push_back(Unresolved);
5751 break;
5753 case SUBMODULE_AFFECTING_MODULES:
5754 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
5755 UnresolvedModuleRef Unresolved;
5756 Unresolved.File = &F;
5757 Unresolved.Mod = CurrentModule;
5758 Unresolved.ID = Record[Idx];
5759 Unresolved.Kind = UnresolvedModuleRef::Affecting;
5760 Unresolved.IsWildcard = false;
5761 UnresolvedModuleRefs.push_back(Unresolved);
5763 break;
5765 case SUBMODULE_EXPORTS:
5766 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
5767 UnresolvedModuleRef Unresolved;
5768 Unresolved.File = &F;
5769 Unresolved.Mod = CurrentModule;
5770 Unresolved.ID = Record[Idx];
5771 Unresolved.Kind = UnresolvedModuleRef::Export;
5772 Unresolved.IsWildcard = Record[Idx + 1];
5773 UnresolvedModuleRefs.push_back(Unresolved);
5776 // Once we've loaded the set of exports, there's no reason to keep
5777 // the parsed, unresolved exports around.
5778 CurrentModule->UnresolvedExports.clear();
5779 break;
5781 case SUBMODULE_REQUIRES:
5782 CurrentModule->addRequirement(Blob, Record[0], PP.getLangOpts(),
5783 PP.getTargetInfo());
5784 break;
5786 case SUBMODULE_LINK_LIBRARY:
5787 ModMap.resolveLinkAsDependencies(CurrentModule);
5788 CurrentModule->LinkLibraries.push_back(
5789 Module::LinkLibrary(std::string(Blob), Record[0]));
5790 break;
5792 case SUBMODULE_CONFIG_MACRO:
5793 CurrentModule->ConfigMacros.push_back(Blob.str());
5794 break;
5796 case SUBMODULE_CONFLICT: {
5797 UnresolvedModuleRef Unresolved;
5798 Unresolved.File = &F;
5799 Unresolved.Mod = CurrentModule;
5800 Unresolved.ID = Record[0];
5801 Unresolved.Kind = UnresolvedModuleRef::Conflict;
5802 Unresolved.IsWildcard = false;
5803 Unresolved.String = Blob;
5804 UnresolvedModuleRefs.push_back(Unresolved);
5805 break;
5808 case SUBMODULE_INITIALIZERS: {
5809 if (!ContextObj)
5810 break;
5811 SmallVector<uint32_t, 16> Inits;
5812 for (auto &ID : Record)
5813 Inits.push_back(getGlobalDeclID(F, ID));
5814 ContextObj->addLazyModuleInitializers(CurrentModule, Inits);
5815 break;
5818 case SUBMODULE_EXPORT_AS:
5819 CurrentModule->ExportAsModule = Blob.str();
5820 ModMap.addLinkAsDependency(CurrentModule);
5821 break;
5826 /// Parse the record that corresponds to a LangOptions data
5827 /// structure.
5829 /// This routine parses the language options from the AST file and then gives
5830 /// them to the AST listener if one is set.
5832 /// \returns true if the listener deems the file unacceptable, false otherwise.
5833 bool ASTReader::ParseLanguageOptions(const RecordData &Record,
5834 bool Complain,
5835 ASTReaderListener &Listener,
5836 bool AllowCompatibleDifferences) {
5837 LangOptions LangOpts;
5838 unsigned Idx = 0;
5839 #define LANGOPT(Name, Bits, Default, Description) \
5840 LangOpts.Name = Record[Idx++];
5841 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
5842 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
5843 #include "clang/Basic/LangOptions.def"
5844 #define SANITIZER(NAME, ID) \
5845 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
5846 #include "clang/Basic/Sanitizers.def"
5848 for (unsigned N = Record[Idx++]; N; --N)
5849 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
5851 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
5852 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
5853 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
5855 LangOpts.CurrentModule = ReadString(Record, Idx);
5857 // Comment options.
5858 for (unsigned N = Record[Idx++]; N; --N) {
5859 LangOpts.CommentOpts.BlockCommandNames.push_back(
5860 ReadString(Record, Idx));
5862 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
5864 // OpenMP offloading options.
5865 for (unsigned N = Record[Idx++]; N; --N) {
5866 LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx)));
5869 LangOpts.OMPHostIRFile = ReadString(Record, Idx);
5871 return Listener.ReadLanguageOptions(LangOpts, Complain,
5872 AllowCompatibleDifferences);
5875 bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
5876 ASTReaderListener &Listener,
5877 bool AllowCompatibleDifferences) {
5878 unsigned Idx = 0;
5879 TargetOptions TargetOpts;
5880 TargetOpts.Triple = ReadString(Record, Idx);
5881 TargetOpts.CPU = ReadString(Record, Idx);
5882 TargetOpts.TuneCPU = ReadString(Record, Idx);
5883 TargetOpts.ABI = ReadString(Record, Idx);
5884 for (unsigned N = Record[Idx++]; N; --N) {
5885 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
5887 for (unsigned N = Record[Idx++]; N; --N) {
5888 TargetOpts.Features.push_back(ReadString(Record, Idx));
5891 return Listener.ReadTargetOptions(TargetOpts, Complain,
5892 AllowCompatibleDifferences);
5895 bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
5896 ASTReaderListener &Listener) {
5897 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
5898 unsigned Idx = 0;
5899 #define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
5900 #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
5901 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
5902 #include "clang/Basic/DiagnosticOptions.def"
5904 for (unsigned N = Record[Idx++]; N; --N)
5905 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
5906 for (unsigned N = Record[Idx++]; N; --N)
5907 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
5909 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
5912 bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
5913 ASTReaderListener &Listener) {
5914 FileSystemOptions FSOpts;
5915 unsigned Idx = 0;
5916 FSOpts.WorkingDir = ReadString(Record, Idx);
5917 return Listener.ReadFileSystemOptions(FSOpts, Complain);
5920 bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
5921 bool Complain,
5922 ASTReaderListener &Listener) {
5923 HeaderSearchOptions HSOpts;
5924 unsigned Idx = 0;
5925 HSOpts.Sysroot = ReadString(Record, Idx);
5927 HSOpts.ResourceDir = ReadString(Record, Idx);
5928 HSOpts.ModuleCachePath = ReadString(Record, Idx);
5929 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
5930 HSOpts.DisableModuleHash = Record[Idx++];
5931 HSOpts.ImplicitModuleMaps = Record[Idx++];
5932 HSOpts.ModuleMapFileHomeIsCwd = Record[Idx++];
5933 HSOpts.EnablePrebuiltImplicitModules = Record[Idx++];
5934 HSOpts.UseBuiltinIncludes = Record[Idx++];
5935 HSOpts.UseStandardSystemIncludes = Record[Idx++];
5936 HSOpts.UseStandardCXXIncludes = Record[Idx++];
5937 HSOpts.UseLibcxx = Record[Idx++];
5938 std::string SpecificModuleCachePath = ReadString(Record, Idx);
5940 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
5941 Complain);
5944 bool ASTReader::ParseHeaderSearchPaths(const RecordData &Record, bool Complain,
5945 ASTReaderListener &Listener) {
5946 HeaderSearchOptions HSOpts;
5947 unsigned Idx = 0;
5949 // Include entries.
5950 for (unsigned N = Record[Idx++]; N; --N) {
5951 std::string Path = ReadString(Record, Idx);
5952 frontend::IncludeDirGroup Group
5953 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
5954 bool IsFramework = Record[Idx++];
5955 bool IgnoreSysRoot = Record[Idx++];
5956 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
5957 IgnoreSysRoot);
5960 // System header prefixes.
5961 for (unsigned N = Record[Idx++]; N; --N) {
5962 std::string Prefix = ReadString(Record, Idx);
5963 bool IsSystemHeader = Record[Idx++];
5964 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
5967 // VFS overlay files.
5968 for (unsigned N = Record[Idx++]; N; --N) {
5969 std::string VFSOverlayFile = ReadString(Record, Idx);
5970 HSOpts.VFSOverlayFiles.emplace_back(std::move(VFSOverlayFile));
5973 return Listener.ReadHeaderSearchPaths(HSOpts, Complain);
5976 bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
5977 bool Complain,
5978 ASTReaderListener &Listener,
5979 std::string &SuggestedPredefines) {
5980 PreprocessorOptions PPOpts;
5981 unsigned Idx = 0;
5983 // Macro definitions/undefs
5984 for (unsigned N = Record[Idx++]; N; --N) {
5985 std::string Macro = ReadString(Record, Idx);
5986 bool IsUndef = Record[Idx++];
5987 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
5990 // Includes
5991 for (unsigned N = Record[Idx++]; N; --N) {
5992 PPOpts.Includes.push_back(ReadString(Record, Idx));
5995 // Macro Includes
5996 for (unsigned N = Record[Idx++]; N; --N) {
5997 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
6000 PPOpts.UsePredefines = Record[Idx++];
6001 PPOpts.DetailedRecord = Record[Idx++];
6002 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
6003 PPOpts.ObjCXXARCStandardLibrary =
6004 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
6005 SuggestedPredefines.clear();
6006 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
6007 SuggestedPredefines);
6010 std::pair<ModuleFile *, unsigned>
6011 ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
6012 GlobalPreprocessedEntityMapType::iterator
6013 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
6014 assert(I != GlobalPreprocessedEntityMap.end() &&
6015 "Corrupted global preprocessed entity map");
6016 ModuleFile *M = I->second;
6017 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
6018 return std::make_pair(M, LocalIndex);
6021 llvm::iterator_range<PreprocessingRecord::iterator>
6022 ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
6023 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
6024 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
6025 Mod.NumPreprocessedEntities);
6027 return llvm::make_range(PreprocessingRecord::iterator(),
6028 PreprocessingRecord::iterator());
6031 bool ASTReader::canRecoverFromOutOfDate(StringRef ModuleFileName,
6032 unsigned int ClientLoadCapabilities) {
6033 return ClientLoadCapabilities & ARR_OutOfDate &&
6034 !getModuleManager().getModuleCache().isPCMFinal(ModuleFileName);
6037 llvm::iterator_range<ASTReader::ModuleDeclIterator>
6038 ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
6039 return llvm::make_range(
6040 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
6041 ModuleDeclIterator(this, &Mod,
6042 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
6045 SourceRange ASTReader::ReadSkippedRange(unsigned GlobalIndex) {
6046 auto I = GlobalSkippedRangeMap.find(GlobalIndex);
6047 assert(I != GlobalSkippedRangeMap.end() &&
6048 "Corrupted global skipped range map");
6049 ModuleFile *M = I->second;
6050 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedSkippedRangeID;
6051 assert(LocalIndex < M->NumPreprocessedSkippedRanges);
6052 PPSkippedRange RawRange = M->PreprocessedSkippedRangeOffsets[LocalIndex];
6053 SourceRange Range(TranslateSourceLocation(*M, RawRange.getBegin()),
6054 TranslateSourceLocation(*M, RawRange.getEnd()));
6055 assert(Range.isValid());
6056 return Range;
6059 PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
6060 PreprocessedEntityID PPID = Index+1;
6061 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
6062 ModuleFile &M = *PPInfo.first;
6063 unsigned LocalIndex = PPInfo.second;
6064 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
6066 if (!PP.getPreprocessingRecord()) {
6067 Error("no preprocessing record");
6068 return nullptr;
6071 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
6072 if (llvm::Error Err = M.PreprocessorDetailCursor.JumpToBit(
6073 M.MacroOffsetsBase + PPOffs.BitOffset)) {
6074 Error(std::move(Err));
6075 return nullptr;
6078 Expected<llvm::BitstreamEntry> MaybeEntry =
6079 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
6080 if (!MaybeEntry) {
6081 Error(MaybeEntry.takeError());
6082 return nullptr;
6084 llvm::BitstreamEntry Entry = MaybeEntry.get();
6086 if (Entry.Kind != llvm::BitstreamEntry::Record)
6087 return nullptr;
6089 // Read the record.
6090 SourceRange Range(TranslateSourceLocation(M, PPOffs.getBegin()),
6091 TranslateSourceLocation(M, PPOffs.getEnd()));
6092 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
6093 StringRef Blob;
6094 RecordData Record;
6095 Expected<unsigned> MaybeRecType =
6096 M.PreprocessorDetailCursor.readRecord(Entry.ID, Record, &Blob);
6097 if (!MaybeRecType) {
6098 Error(MaybeRecType.takeError());
6099 return nullptr;
6101 switch ((PreprocessorDetailRecordTypes)MaybeRecType.get()) {
6102 case PPD_MACRO_EXPANSION: {
6103 bool isBuiltin = Record[0];
6104 IdentifierInfo *Name = nullptr;
6105 MacroDefinitionRecord *Def = nullptr;
6106 if (isBuiltin)
6107 Name = getLocalIdentifier(M, Record[1]);
6108 else {
6109 PreprocessedEntityID GlobalID =
6110 getGlobalPreprocessedEntityID(M, Record[1]);
6111 Def = cast<MacroDefinitionRecord>(
6112 PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
6115 MacroExpansion *ME;
6116 if (isBuiltin)
6117 ME = new (PPRec) MacroExpansion(Name, Range);
6118 else
6119 ME = new (PPRec) MacroExpansion(Def, Range);
6121 return ME;
6124 case PPD_MACRO_DEFINITION: {
6125 // Decode the identifier info and then check again; if the macro is
6126 // still defined and associated with the identifier,
6127 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
6128 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
6130 if (DeserializationListener)
6131 DeserializationListener->MacroDefinitionRead(PPID, MD);
6133 return MD;
6136 case PPD_INCLUSION_DIRECTIVE: {
6137 const char *FullFileNameStart = Blob.data() + Record[0];
6138 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
6139 OptionalFileEntryRef File;
6140 if (!FullFileName.empty())
6141 File = PP.getFileManager().getOptionalFileRef(FullFileName);
6143 // FIXME: Stable encoding
6144 InclusionDirective::InclusionKind Kind
6145 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
6146 InclusionDirective *ID
6147 = new (PPRec) InclusionDirective(PPRec, Kind,
6148 StringRef(Blob.data(), Record[0]),
6149 Record[1], Record[3],
6150 File,
6151 Range);
6152 return ID;
6156 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
6159 /// Find the next module that contains entities and return the ID
6160 /// of the first entry.
6162 /// \param SLocMapI points at a chunk of a module that contains no
6163 /// preprocessed entities or the entities it contains are not the ones we are
6164 /// looking for.
6165 PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
6166 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
6167 ++SLocMapI;
6168 for (GlobalSLocOffsetMapType::const_iterator
6169 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
6170 ModuleFile &M = *SLocMapI->second;
6171 if (M.NumPreprocessedEntities)
6172 return M.BasePreprocessedEntityID;
6175 return getTotalNumPreprocessedEntities();
6178 namespace {
6180 struct PPEntityComp {
6181 const ASTReader &Reader;
6182 ModuleFile &M;
6184 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) {}
6186 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
6187 SourceLocation LHS = getLoc(L);
6188 SourceLocation RHS = getLoc(R);
6189 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6192 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
6193 SourceLocation LHS = getLoc(L);
6194 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6197 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
6198 SourceLocation RHS = getLoc(R);
6199 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6202 SourceLocation getLoc(const PPEntityOffset &PPE) const {
6203 return Reader.TranslateSourceLocation(M, PPE.getBegin());
6207 } // namespace
6209 PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
6210 bool EndsAfter) const {
6211 if (SourceMgr.isLocalSourceLocation(Loc))
6212 return getTotalNumPreprocessedEntities();
6214 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
6215 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
6216 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
6217 "Corrupted global sloc offset map");
6219 if (SLocMapI->second->NumPreprocessedEntities == 0)
6220 return findNextPreprocessedEntity(SLocMapI);
6222 ModuleFile &M = *SLocMapI->second;
6224 using pp_iterator = const PPEntityOffset *;
6226 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
6227 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
6229 size_t Count = M.NumPreprocessedEntities;
6230 size_t Half;
6231 pp_iterator First = pp_begin;
6232 pp_iterator PPI;
6234 if (EndsAfter) {
6235 PPI = std::upper_bound(pp_begin, pp_end, Loc,
6236 PPEntityComp(*this, M));
6237 } else {
6238 // Do a binary search manually instead of using std::lower_bound because
6239 // The end locations of entities may be unordered (when a macro expansion
6240 // is inside another macro argument), but for this case it is not important
6241 // whether we get the first macro expansion or its containing macro.
6242 while (Count > 0) {
6243 Half = Count / 2;
6244 PPI = First;
6245 std::advance(PPI, Half);
6246 if (SourceMgr.isBeforeInTranslationUnit(
6247 TranslateSourceLocation(M, PPI->getEnd()), Loc)) {
6248 First = PPI;
6249 ++First;
6250 Count = Count - Half - 1;
6251 } else
6252 Count = Half;
6256 if (PPI == pp_end)
6257 return findNextPreprocessedEntity(SLocMapI);
6259 return M.BasePreprocessedEntityID + (PPI - pp_begin);
6262 /// Returns a pair of [Begin, End) indices of preallocated
6263 /// preprocessed entities that \arg Range encompasses.
6264 std::pair<unsigned, unsigned>
6265 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
6266 if (Range.isInvalid())
6267 return std::make_pair(0,0);
6268 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
6270 PreprocessedEntityID BeginID =
6271 findPreprocessedEntity(Range.getBegin(), false);
6272 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
6273 return std::make_pair(BeginID, EndID);
6276 /// Optionally returns true or false if the preallocated preprocessed
6277 /// entity with index \arg Index came from file \arg FID.
6278 std::optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
6279 FileID FID) {
6280 if (FID.isInvalid())
6281 return false;
6283 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
6284 ModuleFile &M = *PPInfo.first;
6285 unsigned LocalIndex = PPInfo.second;
6286 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
6288 SourceLocation Loc = TranslateSourceLocation(M, PPOffs.getBegin());
6289 if (Loc.isInvalid())
6290 return false;
6292 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
6293 return true;
6294 else
6295 return false;
6298 namespace {
6300 /// Visitor used to search for information about a header file.
6301 class HeaderFileInfoVisitor {
6302 const FileEntry *FE;
6303 std::optional<HeaderFileInfo> HFI;
6305 public:
6306 explicit HeaderFileInfoVisitor(const FileEntry *FE) : FE(FE) {}
6308 bool operator()(ModuleFile &M) {
6309 HeaderFileInfoLookupTable *Table
6310 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
6311 if (!Table)
6312 return false;
6314 // Look in the on-disk hash table for an entry for this file name.
6315 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
6316 if (Pos == Table->end())
6317 return false;
6319 HFI = *Pos;
6320 return true;
6323 std::optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
6326 } // namespace
6328 HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
6329 HeaderFileInfoVisitor Visitor(FE);
6330 ModuleMgr.visit(Visitor);
6331 if (std::optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
6332 return *HFI;
6334 return HeaderFileInfo();
6337 void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
6338 using DiagState = DiagnosticsEngine::DiagState;
6339 SmallVector<DiagState *, 32> DiagStates;
6341 for (ModuleFile &F : ModuleMgr) {
6342 unsigned Idx = 0;
6343 auto &Record = F.PragmaDiagMappings;
6344 if (Record.empty())
6345 continue;
6347 DiagStates.clear();
6349 auto ReadDiagState = [&](const DiagState &BasedOn,
6350 bool IncludeNonPragmaStates) {
6351 unsigned BackrefID = Record[Idx++];
6352 if (BackrefID != 0)
6353 return DiagStates[BackrefID - 1];
6355 // A new DiagState was created here.
6356 Diag.DiagStates.push_back(BasedOn);
6357 DiagState *NewState = &Diag.DiagStates.back();
6358 DiagStates.push_back(NewState);
6359 unsigned Size = Record[Idx++];
6360 assert(Idx + Size * 2 <= Record.size() &&
6361 "Invalid data, not enough diag/map pairs");
6362 while (Size--) {
6363 unsigned DiagID = Record[Idx++];
6364 DiagnosticMapping NewMapping =
6365 DiagnosticMapping::deserialize(Record[Idx++]);
6366 if (!NewMapping.isPragma() && !IncludeNonPragmaStates)
6367 continue;
6369 DiagnosticMapping &Mapping = NewState->getOrAddMapping(DiagID);
6371 // If this mapping was specified as a warning but the severity was
6372 // upgraded due to diagnostic settings, simulate the current diagnostic
6373 // settings (and use a warning).
6374 if (NewMapping.wasUpgradedFromWarning() && !Mapping.isErrorOrFatal()) {
6375 NewMapping.setSeverity(diag::Severity::Warning);
6376 NewMapping.setUpgradedFromWarning(false);
6379 Mapping = NewMapping;
6381 return NewState;
6384 // Read the first state.
6385 DiagState *FirstState;
6386 if (F.Kind == MK_ImplicitModule) {
6387 // Implicitly-built modules are reused with different diagnostic
6388 // settings. Use the initial diagnostic state from Diag to simulate this
6389 // compilation's diagnostic settings.
6390 FirstState = Diag.DiagStatesByLoc.FirstDiagState;
6391 DiagStates.push_back(FirstState);
6393 // Skip the initial diagnostic state from the serialized module.
6394 assert(Record[1] == 0 &&
6395 "Invalid data, unexpected backref in initial state");
6396 Idx = 3 + Record[2] * 2;
6397 assert(Idx < Record.size() &&
6398 "Invalid data, not enough state change pairs in initial state");
6399 } else if (F.isModule()) {
6400 // For an explicit module, preserve the flags from the module build
6401 // command line (-w, -Weverything, -Werror, ...) along with any explicit
6402 // -Wblah flags.
6403 unsigned Flags = Record[Idx++];
6404 DiagState Initial;
6405 Initial.SuppressSystemWarnings = Flags & 1; Flags >>= 1;
6406 Initial.ErrorsAsFatal = Flags & 1; Flags >>= 1;
6407 Initial.WarningsAsErrors = Flags & 1; Flags >>= 1;
6408 Initial.EnableAllWarnings = Flags & 1; Flags >>= 1;
6409 Initial.IgnoreAllWarnings = Flags & 1; Flags >>= 1;
6410 Initial.ExtBehavior = (diag::Severity)Flags;
6411 FirstState = ReadDiagState(Initial, true);
6413 assert(F.OriginalSourceFileID.isValid());
6415 // Set up the root buffer of the module to start with the initial
6416 // diagnostic state of the module itself, to cover files that contain no
6417 // explicit transitions (for which we did not serialize anything).
6418 Diag.DiagStatesByLoc.Files[F.OriginalSourceFileID]
6419 .StateTransitions.push_back({FirstState, 0});
6420 } else {
6421 // For prefix ASTs, start with whatever the user configured on the
6422 // command line.
6423 Idx++; // Skip flags.
6424 FirstState = ReadDiagState(*Diag.DiagStatesByLoc.CurDiagState, false);
6427 // Read the state transitions.
6428 unsigned NumLocations = Record[Idx++];
6429 while (NumLocations--) {
6430 assert(Idx < Record.size() &&
6431 "Invalid data, missing pragma diagnostic states");
6432 SourceLocation Loc = ReadSourceLocation(F, Record[Idx++]);
6433 auto IDAndOffset = SourceMgr.getDecomposedLoc(Loc);
6434 assert(IDAndOffset.first.isValid() && "invalid FileID for transition");
6435 assert(IDAndOffset.second == 0 && "not a start location for a FileID");
6436 unsigned Transitions = Record[Idx++];
6438 // Note that we don't need to set up Parent/ParentOffset here, because
6439 // we won't be changing the diagnostic state within imported FileIDs
6440 // (other than perhaps appending to the main source file, which has no
6441 // parent).
6442 auto &F = Diag.DiagStatesByLoc.Files[IDAndOffset.first];
6443 F.StateTransitions.reserve(F.StateTransitions.size() + Transitions);
6444 for (unsigned I = 0; I != Transitions; ++I) {
6445 unsigned Offset = Record[Idx++];
6446 auto *State = ReadDiagState(*FirstState, false);
6447 F.StateTransitions.push_back({State, Offset});
6451 // Read the final state.
6452 assert(Idx < Record.size() &&
6453 "Invalid data, missing final pragma diagnostic state");
6454 SourceLocation CurStateLoc =
6455 ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
6456 auto *CurState = ReadDiagState(*FirstState, false);
6458 if (!F.isModule()) {
6459 Diag.DiagStatesByLoc.CurDiagState = CurState;
6460 Diag.DiagStatesByLoc.CurDiagStateLoc = CurStateLoc;
6462 // Preserve the property that the imaginary root file describes the
6463 // current state.
6464 FileID NullFile;
6465 auto &T = Diag.DiagStatesByLoc.Files[NullFile].StateTransitions;
6466 if (T.empty())
6467 T.push_back({CurState, 0});
6468 else
6469 T[0].State = CurState;
6472 // Don't try to read these mappings again.
6473 Record.clear();
6477 /// Get the correct cursor and offset for loading a type.
6478 ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
6479 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
6480 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
6481 ModuleFile *M = I->second;
6482 return RecordLocation(
6483 M, M->TypeOffsets[Index - M->BaseTypeIndex].getBitOffset() +
6484 M->DeclsBlockStartOffset);
6487 static std::optional<Type::TypeClass> getTypeClassForCode(TypeCode code) {
6488 switch (code) {
6489 #define TYPE_BIT_CODE(CLASS_ID, CODE_ID, CODE_VALUE) \
6490 case TYPE_##CODE_ID: return Type::CLASS_ID;
6491 #include "clang/Serialization/TypeBitCodes.def"
6492 default:
6493 return std::nullopt;
6497 /// Read and return the type with the given index..
6499 /// The index is the type ID, shifted and minus the number of predefs. This
6500 /// routine actually reads the record corresponding to the type at the given
6501 /// location. It is a helper routine for GetType, which deals with reading type
6502 /// IDs.
6503 QualType ASTReader::readTypeRecord(unsigned Index) {
6504 assert(ContextObj && "reading type with no AST context");
6505 ASTContext &Context = *ContextObj;
6506 RecordLocation Loc = TypeCursorForIndex(Index);
6507 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
6509 // Keep track of where we are in the stream, then jump back there
6510 // after reading this type.
6511 SavedStreamPosition SavedPosition(DeclsCursor);
6513 ReadingKindTracker ReadingKind(Read_Type, *this);
6515 // Note that we are loading a type record.
6516 Deserializing AType(this);
6518 if (llvm::Error Err = DeclsCursor.JumpToBit(Loc.Offset)) {
6519 Error(std::move(Err));
6520 return QualType();
6522 Expected<unsigned> RawCode = DeclsCursor.ReadCode();
6523 if (!RawCode) {
6524 Error(RawCode.takeError());
6525 return QualType();
6528 ASTRecordReader Record(*this, *Loc.F);
6529 Expected<unsigned> Code = Record.readRecord(DeclsCursor, RawCode.get());
6530 if (!Code) {
6531 Error(Code.takeError());
6532 return QualType();
6534 if (Code.get() == TYPE_EXT_QUAL) {
6535 QualType baseType = Record.readQualType();
6536 Qualifiers quals = Record.readQualifiers();
6537 return Context.getQualifiedType(baseType, quals);
6540 auto maybeClass = getTypeClassForCode((TypeCode) Code.get());
6541 if (!maybeClass) {
6542 Error("Unexpected code for type");
6543 return QualType();
6546 serialization::AbstractTypeReader<ASTRecordReader> TypeReader(Record);
6547 return TypeReader.read(*maybeClass);
6550 namespace clang {
6552 class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
6553 using LocSeq = SourceLocationSequence;
6555 ASTRecordReader &Reader;
6556 LocSeq *Seq;
6558 SourceLocation readSourceLocation() { return Reader.readSourceLocation(Seq); }
6559 SourceRange readSourceRange() { return Reader.readSourceRange(Seq); }
6561 TypeSourceInfo *GetTypeSourceInfo() {
6562 return Reader.readTypeSourceInfo();
6565 NestedNameSpecifierLoc ReadNestedNameSpecifierLoc() {
6566 return Reader.readNestedNameSpecifierLoc();
6569 Attr *ReadAttr() {
6570 return Reader.readAttr();
6573 public:
6574 TypeLocReader(ASTRecordReader &Reader, LocSeq *Seq)
6575 : Reader(Reader), Seq(Seq) {}
6577 // We want compile-time assurance that we've enumerated all of
6578 // these, so unfortunately we have to declare them first, then
6579 // define them out-of-line.
6580 #define ABSTRACT_TYPELOC(CLASS, PARENT)
6581 #define TYPELOC(CLASS, PARENT) \
6582 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
6583 #include "clang/AST/TypeLocNodes.def"
6585 void VisitFunctionTypeLoc(FunctionTypeLoc);
6586 void VisitArrayTypeLoc(ArrayTypeLoc);
6589 } // namespace clang
6591 void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
6592 // nothing to do
6595 void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
6596 TL.setBuiltinLoc(readSourceLocation());
6597 if (TL.needsExtraLocalData()) {
6598 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Reader.readInt()));
6599 TL.setWrittenSignSpec(static_cast<TypeSpecifierSign>(Reader.readInt()));
6600 TL.setWrittenWidthSpec(static_cast<TypeSpecifierWidth>(Reader.readInt()));
6601 TL.setModeAttr(Reader.readInt());
6605 void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
6606 TL.setNameLoc(readSourceLocation());
6609 void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
6610 TL.setStarLoc(readSourceLocation());
6613 void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
6614 // nothing to do
6617 void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
6618 // nothing to do
6621 void TypeLocReader::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
6622 TL.setExpansionLoc(readSourceLocation());
6625 void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
6626 TL.setCaretLoc(readSourceLocation());
6629 void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
6630 TL.setAmpLoc(readSourceLocation());
6633 void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
6634 TL.setAmpAmpLoc(readSourceLocation());
6637 void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
6638 TL.setStarLoc(readSourceLocation());
6639 TL.setClassTInfo(GetTypeSourceInfo());
6642 void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
6643 TL.setLBracketLoc(readSourceLocation());
6644 TL.setRBracketLoc(readSourceLocation());
6645 if (Reader.readBool())
6646 TL.setSizeExpr(Reader.readExpr());
6647 else
6648 TL.setSizeExpr(nullptr);
6651 void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
6652 VisitArrayTypeLoc(TL);
6655 void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
6656 VisitArrayTypeLoc(TL);
6659 void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
6660 VisitArrayTypeLoc(TL);
6663 void TypeLocReader::VisitDependentSizedArrayTypeLoc(
6664 DependentSizedArrayTypeLoc TL) {
6665 VisitArrayTypeLoc(TL);
6668 void TypeLocReader::VisitDependentAddressSpaceTypeLoc(
6669 DependentAddressSpaceTypeLoc TL) {
6671 TL.setAttrNameLoc(readSourceLocation());
6672 TL.setAttrOperandParensRange(readSourceRange());
6673 TL.setAttrExprOperand(Reader.readExpr());
6676 void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
6677 DependentSizedExtVectorTypeLoc TL) {
6678 TL.setNameLoc(readSourceLocation());
6681 void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
6682 TL.setNameLoc(readSourceLocation());
6685 void TypeLocReader::VisitDependentVectorTypeLoc(
6686 DependentVectorTypeLoc TL) {
6687 TL.setNameLoc(readSourceLocation());
6690 void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
6691 TL.setNameLoc(readSourceLocation());
6694 void TypeLocReader::VisitConstantMatrixTypeLoc(ConstantMatrixTypeLoc TL) {
6695 TL.setAttrNameLoc(readSourceLocation());
6696 TL.setAttrOperandParensRange(readSourceRange());
6697 TL.setAttrRowOperand(Reader.readExpr());
6698 TL.setAttrColumnOperand(Reader.readExpr());
6701 void TypeLocReader::VisitDependentSizedMatrixTypeLoc(
6702 DependentSizedMatrixTypeLoc TL) {
6703 TL.setAttrNameLoc(readSourceLocation());
6704 TL.setAttrOperandParensRange(readSourceRange());
6705 TL.setAttrRowOperand(Reader.readExpr());
6706 TL.setAttrColumnOperand(Reader.readExpr());
6709 void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
6710 TL.setLocalRangeBegin(readSourceLocation());
6711 TL.setLParenLoc(readSourceLocation());
6712 TL.setRParenLoc(readSourceLocation());
6713 TL.setExceptionSpecRange(readSourceRange());
6714 TL.setLocalRangeEnd(readSourceLocation());
6715 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
6716 TL.setParam(i, Reader.readDeclAs<ParmVarDecl>());
6720 void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
6721 VisitFunctionTypeLoc(TL);
6724 void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
6725 VisitFunctionTypeLoc(TL);
6728 void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
6729 TL.setNameLoc(readSourceLocation());
6732 void TypeLocReader::VisitUsingTypeLoc(UsingTypeLoc TL) {
6733 TL.setNameLoc(readSourceLocation());
6736 void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
6737 TL.setNameLoc(readSourceLocation());
6740 void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
6741 TL.setTypeofLoc(readSourceLocation());
6742 TL.setLParenLoc(readSourceLocation());
6743 TL.setRParenLoc(readSourceLocation());
6746 void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
6747 TL.setTypeofLoc(readSourceLocation());
6748 TL.setLParenLoc(readSourceLocation());
6749 TL.setRParenLoc(readSourceLocation());
6750 TL.setUnmodifiedTInfo(GetTypeSourceInfo());
6753 void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
6754 TL.setDecltypeLoc(readSourceLocation());
6755 TL.setRParenLoc(readSourceLocation());
6758 void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
6759 TL.setKWLoc(readSourceLocation());
6760 TL.setLParenLoc(readSourceLocation());
6761 TL.setRParenLoc(readSourceLocation());
6762 TL.setUnderlyingTInfo(GetTypeSourceInfo());
6765 void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
6766 TL.setNameLoc(readSourceLocation());
6767 if (Reader.readBool()) {
6768 TL.setNestedNameSpecifierLoc(ReadNestedNameSpecifierLoc());
6769 TL.setTemplateKWLoc(readSourceLocation());
6770 TL.setConceptNameLoc(readSourceLocation());
6771 TL.setFoundDecl(Reader.readDeclAs<NamedDecl>());
6772 TL.setLAngleLoc(readSourceLocation());
6773 TL.setRAngleLoc(readSourceLocation());
6774 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
6775 TL.setArgLocInfo(
6776 i, Reader.readTemplateArgumentLocInfo(
6777 TL.getTypePtr()->getTypeConstraintArguments()[i].getKind()));
6779 if (Reader.readBool())
6780 TL.setRParenLoc(readSourceLocation());
6783 void TypeLocReader::VisitDeducedTemplateSpecializationTypeLoc(
6784 DeducedTemplateSpecializationTypeLoc TL) {
6785 TL.setTemplateNameLoc(readSourceLocation());
6788 void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
6789 TL.setNameLoc(readSourceLocation());
6792 void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
6793 TL.setNameLoc(readSourceLocation());
6796 void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
6797 TL.setAttr(ReadAttr());
6800 void TypeLocReader::VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) {
6801 // Nothing to do.
6804 void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
6805 TL.setNameLoc(readSourceLocation());
6808 void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
6809 SubstTemplateTypeParmTypeLoc TL) {
6810 TL.setNameLoc(readSourceLocation());
6813 void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
6814 SubstTemplateTypeParmPackTypeLoc TL) {
6815 TL.setNameLoc(readSourceLocation());
6818 void TypeLocReader::VisitTemplateSpecializationTypeLoc(
6819 TemplateSpecializationTypeLoc TL) {
6820 TL.setTemplateKeywordLoc(readSourceLocation());
6821 TL.setTemplateNameLoc(readSourceLocation());
6822 TL.setLAngleLoc(readSourceLocation());
6823 TL.setRAngleLoc(readSourceLocation());
6824 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
6825 TL.setArgLocInfo(i,
6826 Reader.readTemplateArgumentLocInfo(
6827 TL.getTypePtr()->template_arguments()[i].getKind()));
6830 void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
6831 TL.setLParenLoc(readSourceLocation());
6832 TL.setRParenLoc(readSourceLocation());
6835 void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
6836 TL.setElaboratedKeywordLoc(readSourceLocation());
6837 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
6840 void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
6841 TL.setNameLoc(readSourceLocation());
6844 void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
6845 TL.setElaboratedKeywordLoc(readSourceLocation());
6846 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
6847 TL.setNameLoc(readSourceLocation());
6850 void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
6851 DependentTemplateSpecializationTypeLoc TL) {
6852 TL.setElaboratedKeywordLoc(readSourceLocation());
6853 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
6854 TL.setTemplateKeywordLoc(readSourceLocation());
6855 TL.setTemplateNameLoc(readSourceLocation());
6856 TL.setLAngleLoc(readSourceLocation());
6857 TL.setRAngleLoc(readSourceLocation());
6858 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
6859 TL.setArgLocInfo(I,
6860 Reader.readTemplateArgumentLocInfo(
6861 TL.getTypePtr()->template_arguments()[I].getKind()));
6864 void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
6865 TL.setEllipsisLoc(readSourceLocation());
6868 void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
6869 TL.setNameLoc(readSourceLocation());
6870 TL.setNameEndLoc(readSourceLocation());
6873 void TypeLocReader::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
6874 if (TL.getNumProtocols()) {
6875 TL.setProtocolLAngleLoc(readSourceLocation());
6876 TL.setProtocolRAngleLoc(readSourceLocation());
6878 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
6879 TL.setProtocolLoc(i, readSourceLocation());
6882 void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
6883 TL.setHasBaseTypeAsWritten(Reader.readBool());
6884 TL.setTypeArgsLAngleLoc(readSourceLocation());
6885 TL.setTypeArgsRAngleLoc(readSourceLocation());
6886 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
6887 TL.setTypeArgTInfo(i, GetTypeSourceInfo());
6888 TL.setProtocolLAngleLoc(readSourceLocation());
6889 TL.setProtocolRAngleLoc(readSourceLocation());
6890 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
6891 TL.setProtocolLoc(i, readSourceLocation());
6894 void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
6895 TL.setStarLoc(readSourceLocation());
6898 void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
6899 TL.setKWLoc(readSourceLocation());
6900 TL.setLParenLoc(readSourceLocation());
6901 TL.setRParenLoc(readSourceLocation());
6904 void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) {
6905 TL.setKWLoc(readSourceLocation());
6908 void TypeLocReader::VisitBitIntTypeLoc(clang::BitIntTypeLoc TL) {
6909 TL.setNameLoc(readSourceLocation());
6911 void TypeLocReader::VisitDependentBitIntTypeLoc(
6912 clang::DependentBitIntTypeLoc TL) {
6913 TL.setNameLoc(readSourceLocation());
6916 void ASTRecordReader::readTypeLoc(TypeLoc TL, LocSeq *ParentSeq) {
6917 LocSeq::State Seq(ParentSeq);
6918 TypeLocReader TLR(*this, Seq);
6919 for (; !TL.isNull(); TL = TL.getNextTypeLoc())
6920 TLR.Visit(TL);
6923 TypeSourceInfo *ASTRecordReader::readTypeSourceInfo() {
6924 QualType InfoTy = readType();
6925 if (InfoTy.isNull())
6926 return nullptr;
6928 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
6929 readTypeLoc(TInfo->getTypeLoc());
6930 return TInfo;
6933 QualType ASTReader::GetType(TypeID ID) {
6934 assert(ContextObj && "reading type with no AST context");
6935 ASTContext &Context = *ContextObj;
6937 unsigned FastQuals = ID & Qualifiers::FastMask;
6938 unsigned Index = ID >> Qualifiers::FastWidth;
6940 if (Index < NUM_PREDEF_TYPE_IDS) {
6941 QualType T;
6942 switch ((PredefinedTypeIDs)Index) {
6943 case PREDEF_TYPE_NULL_ID:
6944 return QualType();
6945 case PREDEF_TYPE_VOID_ID:
6946 T = Context.VoidTy;
6947 break;
6948 case PREDEF_TYPE_BOOL_ID:
6949 T = Context.BoolTy;
6950 break;
6951 case PREDEF_TYPE_CHAR_U_ID:
6952 case PREDEF_TYPE_CHAR_S_ID:
6953 // FIXME: Check that the signedness of CharTy is correct!
6954 T = Context.CharTy;
6955 break;
6956 case PREDEF_TYPE_UCHAR_ID:
6957 T = Context.UnsignedCharTy;
6958 break;
6959 case PREDEF_TYPE_USHORT_ID:
6960 T = Context.UnsignedShortTy;
6961 break;
6962 case PREDEF_TYPE_UINT_ID:
6963 T = Context.UnsignedIntTy;
6964 break;
6965 case PREDEF_TYPE_ULONG_ID:
6966 T = Context.UnsignedLongTy;
6967 break;
6968 case PREDEF_TYPE_ULONGLONG_ID:
6969 T = Context.UnsignedLongLongTy;
6970 break;
6971 case PREDEF_TYPE_UINT128_ID:
6972 T = Context.UnsignedInt128Ty;
6973 break;
6974 case PREDEF_TYPE_SCHAR_ID:
6975 T = Context.SignedCharTy;
6976 break;
6977 case PREDEF_TYPE_WCHAR_ID:
6978 T = Context.WCharTy;
6979 break;
6980 case PREDEF_TYPE_SHORT_ID:
6981 T = Context.ShortTy;
6982 break;
6983 case PREDEF_TYPE_INT_ID:
6984 T = Context.IntTy;
6985 break;
6986 case PREDEF_TYPE_LONG_ID:
6987 T = Context.LongTy;
6988 break;
6989 case PREDEF_TYPE_LONGLONG_ID:
6990 T = Context.LongLongTy;
6991 break;
6992 case PREDEF_TYPE_INT128_ID:
6993 T = Context.Int128Ty;
6994 break;
6995 case PREDEF_TYPE_BFLOAT16_ID:
6996 T = Context.BFloat16Ty;
6997 break;
6998 case PREDEF_TYPE_HALF_ID:
6999 T = Context.HalfTy;
7000 break;
7001 case PREDEF_TYPE_FLOAT_ID:
7002 T = Context.FloatTy;
7003 break;
7004 case PREDEF_TYPE_DOUBLE_ID:
7005 T = Context.DoubleTy;
7006 break;
7007 case PREDEF_TYPE_LONGDOUBLE_ID:
7008 T = Context.LongDoubleTy;
7009 break;
7010 case PREDEF_TYPE_SHORT_ACCUM_ID:
7011 T = Context.ShortAccumTy;
7012 break;
7013 case PREDEF_TYPE_ACCUM_ID:
7014 T = Context.AccumTy;
7015 break;
7016 case PREDEF_TYPE_LONG_ACCUM_ID:
7017 T = Context.LongAccumTy;
7018 break;
7019 case PREDEF_TYPE_USHORT_ACCUM_ID:
7020 T = Context.UnsignedShortAccumTy;
7021 break;
7022 case PREDEF_TYPE_UACCUM_ID:
7023 T = Context.UnsignedAccumTy;
7024 break;
7025 case PREDEF_TYPE_ULONG_ACCUM_ID:
7026 T = Context.UnsignedLongAccumTy;
7027 break;
7028 case PREDEF_TYPE_SHORT_FRACT_ID:
7029 T = Context.ShortFractTy;
7030 break;
7031 case PREDEF_TYPE_FRACT_ID:
7032 T = Context.FractTy;
7033 break;
7034 case PREDEF_TYPE_LONG_FRACT_ID:
7035 T = Context.LongFractTy;
7036 break;
7037 case PREDEF_TYPE_USHORT_FRACT_ID:
7038 T = Context.UnsignedShortFractTy;
7039 break;
7040 case PREDEF_TYPE_UFRACT_ID:
7041 T = Context.UnsignedFractTy;
7042 break;
7043 case PREDEF_TYPE_ULONG_FRACT_ID:
7044 T = Context.UnsignedLongFractTy;
7045 break;
7046 case PREDEF_TYPE_SAT_SHORT_ACCUM_ID:
7047 T = Context.SatShortAccumTy;
7048 break;
7049 case PREDEF_TYPE_SAT_ACCUM_ID:
7050 T = Context.SatAccumTy;
7051 break;
7052 case PREDEF_TYPE_SAT_LONG_ACCUM_ID:
7053 T = Context.SatLongAccumTy;
7054 break;
7055 case PREDEF_TYPE_SAT_USHORT_ACCUM_ID:
7056 T = Context.SatUnsignedShortAccumTy;
7057 break;
7058 case PREDEF_TYPE_SAT_UACCUM_ID:
7059 T = Context.SatUnsignedAccumTy;
7060 break;
7061 case PREDEF_TYPE_SAT_ULONG_ACCUM_ID:
7062 T = Context.SatUnsignedLongAccumTy;
7063 break;
7064 case PREDEF_TYPE_SAT_SHORT_FRACT_ID:
7065 T = Context.SatShortFractTy;
7066 break;
7067 case PREDEF_TYPE_SAT_FRACT_ID:
7068 T = Context.SatFractTy;
7069 break;
7070 case PREDEF_TYPE_SAT_LONG_FRACT_ID:
7071 T = Context.SatLongFractTy;
7072 break;
7073 case PREDEF_TYPE_SAT_USHORT_FRACT_ID:
7074 T = Context.SatUnsignedShortFractTy;
7075 break;
7076 case PREDEF_TYPE_SAT_UFRACT_ID:
7077 T = Context.SatUnsignedFractTy;
7078 break;
7079 case PREDEF_TYPE_SAT_ULONG_FRACT_ID:
7080 T = Context.SatUnsignedLongFractTy;
7081 break;
7082 case PREDEF_TYPE_FLOAT16_ID:
7083 T = Context.Float16Ty;
7084 break;
7085 case PREDEF_TYPE_FLOAT128_ID:
7086 T = Context.Float128Ty;
7087 break;
7088 case PREDEF_TYPE_IBM128_ID:
7089 T = Context.Ibm128Ty;
7090 break;
7091 case PREDEF_TYPE_OVERLOAD_ID:
7092 T = Context.OverloadTy;
7093 break;
7094 case PREDEF_TYPE_BOUND_MEMBER:
7095 T = Context.BoundMemberTy;
7096 break;
7097 case PREDEF_TYPE_PSEUDO_OBJECT:
7098 T = Context.PseudoObjectTy;
7099 break;
7100 case PREDEF_TYPE_DEPENDENT_ID:
7101 T = Context.DependentTy;
7102 break;
7103 case PREDEF_TYPE_UNKNOWN_ANY:
7104 T = Context.UnknownAnyTy;
7105 break;
7106 case PREDEF_TYPE_NULLPTR_ID:
7107 T = Context.NullPtrTy;
7108 break;
7109 case PREDEF_TYPE_CHAR8_ID:
7110 T = Context.Char8Ty;
7111 break;
7112 case PREDEF_TYPE_CHAR16_ID:
7113 T = Context.Char16Ty;
7114 break;
7115 case PREDEF_TYPE_CHAR32_ID:
7116 T = Context.Char32Ty;
7117 break;
7118 case PREDEF_TYPE_OBJC_ID:
7119 T = Context.ObjCBuiltinIdTy;
7120 break;
7121 case PREDEF_TYPE_OBJC_CLASS:
7122 T = Context.ObjCBuiltinClassTy;
7123 break;
7124 case PREDEF_TYPE_OBJC_SEL:
7125 T = Context.ObjCBuiltinSelTy;
7126 break;
7127 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7128 case PREDEF_TYPE_##Id##_ID: \
7129 T = Context.SingletonId; \
7130 break;
7131 #include "clang/Basic/OpenCLImageTypes.def"
7132 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
7133 case PREDEF_TYPE_##Id##_ID: \
7134 T = Context.Id##Ty; \
7135 break;
7136 #include "clang/Basic/OpenCLExtensionTypes.def"
7137 case PREDEF_TYPE_SAMPLER_ID:
7138 T = Context.OCLSamplerTy;
7139 break;
7140 case PREDEF_TYPE_EVENT_ID:
7141 T = Context.OCLEventTy;
7142 break;
7143 case PREDEF_TYPE_CLK_EVENT_ID:
7144 T = Context.OCLClkEventTy;
7145 break;
7146 case PREDEF_TYPE_QUEUE_ID:
7147 T = Context.OCLQueueTy;
7148 break;
7149 case PREDEF_TYPE_RESERVE_ID_ID:
7150 T = Context.OCLReserveIDTy;
7151 break;
7152 case PREDEF_TYPE_AUTO_DEDUCT:
7153 T = Context.getAutoDeductType();
7154 break;
7155 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
7156 T = Context.getAutoRRefDeductType();
7157 break;
7158 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
7159 T = Context.ARCUnbridgedCastTy;
7160 break;
7161 case PREDEF_TYPE_BUILTIN_FN:
7162 T = Context.BuiltinFnTy;
7163 break;
7164 case PREDEF_TYPE_INCOMPLETE_MATRIX_IDX:
7165 T = Context.IncompleteMatrixIdxTy;
7166 break;
7167 case PREDEF_TYPE_OMP_ARRAY_SECTION:
7168 T = Context.OMPArraySectionTy;
7169 break;
7170 case PREDEF_TYPE_OMP_ARRAY_SHAPING:
7171 T = Context.OMPArraySectionTy;
7172 break;
7173 case PREDEF_TYPE_OMP_ITERATOR:
7174 T = Context.OMPIteratorTy;
7175 break;
7176 #define SVE_TYPE(Name, Id, SingletonId) \
7177 case PREDEF_TYPE_##Id##_ID: \
7178 T = Context.SingletonId; \
7179 break;
7180 #include "clang/Basic/AArch64SVEACLETypes.def"
7181 #define PPC_VECTOR_TYPE(Name, Id, Size) \
7182 case PREDEF_TYPE_##Id##_ID: \
7183 T = Context.Id##Ty; \
7184 break;
7185 #include "clang/Basic/PPCTypes.def"
7186 #define RVV_TYPE(Name, Id, SingletonId) \
7187 case PREDEF_TYPE_##Id##_ID: \
7188 T = Context.SingletonId; \
7189 break;
7190 #include "clang/Basic/RISCVVTypes.def"
7193 assert(!T.isNull() && "Unknown predefined type");
7194 return T.withFastQualifiers(FastQuals);
7197 Index -= NUM_PREDEF_TYPE_IDS;
7198 assert(Index < TypesLoaded.size() && "Type index out-of-range");
7199 if (TypesLoaded[Index].isNull()) {
7200 TypesLoaded[Index] = readTypeRecord(Index);
7201 if (TypesLoaded[Index].isNull())
7202 return QualType();
7204 TypesLoaded[Index]->setFromAST();
7205 if (DeserializationListener)
7206 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
7207 TypesLoaded[Index]);
7210 return TypesLoaded[Index].withFastQualifiers(FastQuals);
7213 QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
7214 return GetType(getGlobalTypeID(F, LocalID));
7217 serialization::TypeID
7218 ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
7219 unsigned FastQuals = LocalID & Qualifiers::FastMask;
7220 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
7222 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
7223 return LocalID;
7225 if (!F.ModuleOffsetMap.empty())
7226 ReadModuleOffsetMap(F);
7228 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7229 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
7230 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
7232 unsigned GlobalIndex = LocalIndex + I->second;
7233 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
7236 TemplateArgumentLocInfo
7237 ASTRecordReader::readTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind) {
7238 switch (Kind) {
7239 case TemplateArgument::Expression:
7240 return readExpr();
7241 case TemplateArgument::Type:
7242 return readTypeSourceInfo();
7243 case TemplateArgument::Template: {
7244 NestedNameSpecifierLoc QualifierLoc =
7245 readNestedNameSpecifierLoc();
7246 SourceLocation TemplateNameLoc = readSourceLocation();
7247 return TemplateArgumentLocInfo(getASTContext(), QualifierLoc,
7248 TemplateNameLoc, SourceLocation());
7250 case TemplateArgument::TemplateExpansion: {
7251 NestedNameSpecifierLoc QualifierLoc = readNestedNameSpecifierLoc();
7252 SourceLocation TemplateNameLoc = readSourceLocation();
7253 SourceLocation EllipsisLoc = readSourceLocation();
7254 return TemplateArgumentLocInfo(getASTContext(), QualifierLoc,
7255 TemplateNameLoc, EllipsisLoc);
7257 case TemplateArgument::Null:
7258 case TemplateArgument::Integral:
7259 case TemplateArgument::Declaration:
7260 case TemplateArgument::NullPtr:
7261 case TemplateArgument::Pack:
7262 // FIXME: Is this right?
7263 return TemplateArgumentLocInfo();
7265 llvm_unreachable("unexpected template argument loc");
7268 TemplateArgumentLoc ASTRecordReader::readTemplateArgumentLoc() {
7269 TemplateArgument Arg = readTemplateArgument();
7271 if (Arg.getKind() == TemplateArgument::Expression) {
7272 if (readBool()) // bool InfoHasSameExpr.
7273 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
7275 return TemplateArgumentLoc(Arg, readTemplateArgumentLocInfo(Arg.getKind()));
7278 const ASTTemplateArgumentListInfo *
7279 ASTRecordReader::readASTTemplateArgumentListInfo() {
7280 SourceLocation LAngleLoc = readSourceLocation();
7281 SourceLocation RAngleLoc = readSourceLocation();
7282 unsigned NumArgsAsWritten = readInt();
7283 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
7284 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
7285 TemplArgsInfo.addArgument(readTemplateArgumentLoc());
7286 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
7289 Decl *ASTReader::GetExternalDecl(uint32_t ID) {
7290 return GetDecl(ID);
7293 void ASTReader::CompleteRedeclChain(const Decl *D) {
7294 if (NumCurrentElementsDeserializing) {
7295 // We arrange to not care about the complete redeclaration chain while we're
7296 // deserializing. Just remember that the AST has marked this one as complete
7297 // but that it's not actually complete yet, so we know we still need to
7298 // complete it later.
7299 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
7300 return;
7303 if (!D->getDeclContext()) {
7304 assert(isa<TranslationUnitDecl>(D) && "Not a TU?");
7305 return;
7308 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
7310 // If this is a named declaration, complete it by looking it up
7311 // within its context.
7313 // FIXME: Merging a function definition should merge
7314 // all mergeable entities within it.
7315 if (isa<TranslationUnitDecl, NamespaceDecl, RecordDecl, EnumDecl>(DC)) {
7316 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
7317 if (!getContext().getLangOpts().CPlusPlus &&
7318 isa<TranslationUnitDecl>(DC)) {
7319 // Outside of C++, we don't have a lookup table for the TU, so update
7320 // the identifier instead. (For C++ modules, we don't store decls
7321 // in the serialized identifier table, so we do the lookup in the TU.)
7322 auto *II = Name.getAsIdentifierInfo();
7323 assert(II && "non-identifier name in C?");
7324 if (II->isOutOfDate())
7325 updateOutOfDateIdentifier(*II);
7326 } else
7327 DC->lookup(Name);
7328 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
7329 // Find all declarations of this kind from the relevant context.
7330 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
7331 auto *DC = cast<DeclContext>(DCDecl);
7332 SmallVector<Decl*, 8> Decls;
7333 FindExternalLexicalDecls(
7334 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
7339 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
7340 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
7341 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
7342 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
7343 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
7344 if (auto *Template = FD->getPrimaryTemplate())
7345 Template->LoadLazySpecializations();
7349 CXXCtorInitializer **
7350 ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
7351 RecordLocation Loc = getLocalBitOffset(Offset);
7352 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
7353 SavedStreamPosition SavedPosition(Cursor);
7354 if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {
7355 Error(std::move(Err));
7356 return nullptr;
7358 ReadingKindTracker ReadingKind(Read_Decl, *this);
7360 Expected<unsigned> MaybeCode = Cursor.ReadCode();
7361 if (!MaybeCode) {
7362 Error(MaybeCode.takeError());
7363 return nullptr;
7365 unsigned Code = MaybeCode.get();
7367 ASTRecordReader Record(*this, *Loc.F);
7368 Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code);
7369 if (!MaybeRecCode) {
7370 Error(MaybeRecCode.takeError());
7371 return nullptr;
7373 if (MaybeRecCode.get() != DECL_CXX_CTOR_INITIALIZERS) {
7374 Error("malformed AST file: missing C++ ctor initializers");
7375 return nullptr;
7378 return Record.readCXXCtorInitializers();
7381 CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
7382 assert(ContextObj && "reading base specifiers with no AST context");
7383 ASTContext &Context = *ContextObj;
7385 RecordLocation Loc = getLocalBitOffset(Offset);
7386 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
7387 SavedStreamPosition SavedPosition(Cursor);
7388 if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {
7389 Error(std::move(Err));
7390 return nullptr;
7392 ReadingKindTracker ReadingKind(Read_Decl, *this);
7394 Expected<unsigned> MaybeCode = Cursor.ReadCode();
7395 if (!MaybeCode) {
7396 Error(MaybeCode.takeError());
7397 return nullptr;
7399 unsigned Code = MaybeCode.get();
7401 ASTRecordReader Record(*this, *Loc.F);
7402 Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code);
7403 if (!MaybeRecCode) {
7404 Error(MaybeCode.takeError());
7405 return nullptr;
7407 unsigned RecCode = MaybeRecCode.get();
7409 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
7410 Error("malformed AST file: missing C++ base specifiers");
7411 return nullptr;
7414 unsigned NumBases = Record.readInt();
7415 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
7416 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
7417 for (unsigned I = 0; I != NumBases; ++I)
7418 Bases[I] = Record.readCXXBaseSpecifier();
7419 return Bases;
7422 serialization::DeclID
7423 ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
7424 if (LocalID < NUM_PREDEF_DECL_IDS)
7425 return LocalID;
7427 if (!F.ModuleOffsetMap.empty())
7428 ReadModuleOffsetMap(F);
7430 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7431 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
7432 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
7434 return LocalID + I->second;
7437 bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
7438 ModuleFile &M) const {
7439 // Predefined decls aren't from any module.
7440 if (ID < NUM_PREDEF_DECL_IDS)
7441 return false;
7443 return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
7444 ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
7447 ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
7448 if (!D->isFromASTFile())
7449 return nullptr;
7450 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
7451 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
7452 return I->second;
7455 SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
7456 if (ID < NUM_PREDEF_DECL_IDS)
7457 return SourceLocation();
7459 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7461 if (Index > DeclsLoaded.size()) {
7462 Error("declaration ID out-of-range for AST file");
7463 return SourceLocation();
7466 if (Decl *D = DeclsLoaded[Index])
7467 return D->getLocation();
7469 SourceLocation Loc;
7470 DeclCursorForID(ID, Loc);
7471 return Loc;
7474 static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
7475 switch (ID) {
7476 case PREDEF_DECL_NULL_ID:
7477 return nullptr;
7479 case PREDEF_DECL_TRANSLATION_UNIT_ID:
7480 return Context.getTranslationUnitDecl();
7482 case PREDEF_DECL_OBJC_ID_ID:
7483 return Context.getObjCIdDecl();
7485 case PREDEF_DECL_OBJC_SEL_ID:
7486 return Context.getObjCSelDecl();
7488 case PREDEF_DECL_OBJC_CLASS_ID:
7489 return Context.getObjCClassDecl();
7491 case PREDEF_DECL_OBJC_PROTOCOL_ID:
7492 return Context.getObjCProtocolDecl();
7494 case PREDEF_DECL_INT_128_ID:
7495 return Context.getInt128Decl();
7497 case PREDEF_DECL_UNSIGNED_INT_128_ID:
7498 return Context.getUInt128Decl();
7500 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
7501 return Context.getObjCInstanceTypeDecl();
7503 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
7504 return Context.getBuiltinVaListDecl();
7506 case PREDEF_DECL_VA_LIST_TAG:
7507 return Context.getVaListTagDecl();
7509 case PREDEF_DECL_BUILTIN_MS_VA_LIST_ID:
7510 return Context.getBuiltinMSVaListDecl();
7512 case PREDEF_DECL_BUILTIN_MS_GUID_ID:
7513 return Context.getMSGuidTagDecl();
7515 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
7516 return Context.getExternCContextDecl();
7518 case PREDEF_DECL_MAKE_INTEGER_SEQ_ID:
7519 return Context.getMakeIntegerSeqDecl();
7521 case PREDEF_DECL_CF_CONSTANT_STRING_ID:
7522 return Context.getCFConstantStringDecl();
7524 case PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID:
7525 return Context.getCFConstantStringTagDecl();
7527 case PREDEF_DECL_TYPE_PACK_ELEMENT_ID:
7528 return Context.getTypePackElementDecl();
7530 llvm_unreachable("PredefinedDeclIDs unknown enum value");
7533 Decl *ASTReader::GetExistingDecl(DeclID ID) {
7534 assert(ContextObj && "reading decl with no AST context");
7535 if (ID < NUM_PREDEF_DECL_IDS) {
7536 Decl *D = getPredefinedDecl(*ContextObj, (PredefinedDeclIDs)ID);
7537 if (D) {
7538 // Track that we have merged the declaration with ID \p ID into the
7539 // pre-existing predefined declaration \p D.
7540 auto &Merged = KeyDecls[D->getCanonicalDecl()];
7541 if (Merged.empty())
7542 Merged.push_back(ID);
7544 return D;
7547 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7549 if (Index >= DeclsLoaded.size()) {
7550 assert(0 && "declaration ID out-of-range for AST file");
7551 Error("declaration ID out-of-range for AST file");
7552 return nullptr;
7555 return DeclsLoaded[Index];
7558 Decl *ASTReader::GetDecl(DeclID ID) {
7559 if (ID < NUM_PREDEF_DECL_IDS)
7560 return GetExistingDecl(ID);
7562 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7564 if (Index >= DeclsLoaded.size()) {
7565 assert(0 && "declaration ID out-of-range for AST file");
7566 Error("declaration ID out-of-range for AST file");
7567 return nullptr;
7570 if (!DeclsLoaded[Index]) {
7571 ReadDeclRecord(ID);
7572 if (DeserializationListener)
7573 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
7576 return DeclsLoaded[Index];
7579 DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
7580 DeclID GlobalID) {
7581 if (GlobalID < NUM_PREDEF_DECL_IDS)
7582 return GlobalID;
7584 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
7585 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
7586 ModuleFile *Owner = I->second;
7588 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
7589 = M.GlobalToLocalDeclIDs.find(Owner);
7590 if (Pos == M.GlobalToLocalDeclIDs.end())
7591 return 0;
7593 return GlobalID - Owner->BaseDeclID + Pos->second;
7596 serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
7597 const RecordData &Record,
7598 unsigned &Idx) {
7599 if (Idx >= Record.size()) {
7600 Error("Corrupted AST file");
7601 return 0;
7604 return getGlobalDeclID(F, Record[Idx++]);
7607 /// Resolve the offset of a statement into a statement.
7609 /// This operation will read a new statement from the external
7610 /// source each time it is called, and is meant to be used via a
7611 /// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
7612 Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
7613 // Switch case IDs are per Decl.
7614 ClearSwitchCaseIDs();
7616 // Offset here is a global offset across the entire chain.
7617 RecordLocation Loc = getLocalBitOffset(Offset);
7618 if (llvm::Error Err = Loc.F->DeclsCursor.JumpToBit(Loc.Offset)) {
7619 Error(std::move(Err));
7620 return nullptr;
7622 assert(NumCurrentElementsDeserializing == 0 &&
7623 "should not be called while already deserializing");
7624 Deserializing D(this);
7625 return ReadStmtFromStream(*Loc.F);
7628 void ASTReader::FindExternalLexicalDecls(
7629 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
7630 SmallVectorImpl<Decl *> &Decls) {
7631 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
7633 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
7634 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
7635 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
7636 auto K = (Decl::Kind)+LexicalDecls[I];
7637 if (!IsKindWeWant(K))
7638 continue;
7640 auto ID = (serialization::DeclID)+LexicalDecls[I + 1];
7642 // Don't add predefined declarations to the lexical context more
7643 // than once.
7644 if (ID < NUM_PREDEF_DECL_IDS) {
7645 if (PredefsVisited[ID])
7646 continue;
7648 PredefsVisited[ID] = true;
7651 if (Decl *D = GetLocalDecl(*M, ID)) {
7652 assert(D->getKind() == K && "wrong kind for lexical decl");
7653 if (!DC->isDeclInLexicalTraversal(D))
7654 Decls.push_back(D);
7659 if (isa<TranslationUnitDecl>(DC)) {
7660 for (auto Lexical : TULexicalDecls)
7661 Visit(Lexical.first, Lexical.second);
7662 } else {
7663 auto I = LexicalDecls.find(DC);
7664 if (I != LexicalDecls.end())
7665 Visit(I->second.first, I->second.second);
7668 ++NumLexicalDeclContextsRead;
7671 namespace {
7673 class DeclIDComp {
7674 ASTReader &Reader;
7675 ModuleFile &Mod;
7677 public:
7678 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
7680 bool operator()(LocalDeclID L, LocalDeclID R) const {
7681 SourceLocation LHS = getLocation(L);
7682 SourceLocation RHS = getLocation(R);
7683 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7686 bool operator()(SourceLocation LHS, LocalDeclID R) const {
7687 SourceLocation RHS = getLocation(R);
7688 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7691 bool operator()(LocalDeclID L, SourceLocation RHS) const {
7692 SourceLocation LHS = getLocation(L);
7693 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7696 SourceLocation getLocation(LocalDeclID ID) const {
7697 return Reader.getSourceManager().getFileLoc(
7698 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
7702 } // namespace
7704 void ASTReader::FindFileRegionDecls(FileID File,
7705 unsigned Offset, unsigned Length,
7706 SmallVectorImpl<Decl *> &Decls) {
7707 SourceManager &SM = getSourceManager();
7709 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
7710 if (I == FileDeclIDs.end())
7711 return;
7713 FileDeclsInfo &DInfo = I->second;
7714 if (DInfo.Decls.empty())
7715 return;
7717 SourceLocation
7718 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
7719 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
7721 DeclIDComp DIDComp(*this, *DInfo.Mod);
7722 ArrayRef<serialization::LocalDeclID>::iterator BeginIt =
7723 llvm::lower_bound(DInfo.Decls, BeginLoc, DIDComp);
7724 if (BeginIt != DInfo.Decls.begin())
7725 --BeginIt;
7727 // If we are pointing at a top-level decl inside an objc container, we need
7728 // to backtrack until we find it otherwise we will fail to report that the
7729 // region overlaps with an objc container.
7730 while (BeginIt != DInfo.Decls.begin() &&
7731 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
7732 ->isTopLevelDeclInObjCContainer())
7733 --BeginIt;
7735 ArrayRef<serialization::LocalDeclID>::iterator EndIt =
7736 llvm::upper_bound(DInfo.Decls, EndLoc, DIDComp);
7737 if (EndIt != DInfo.Decls.end())
7738 ++EndIt;
7740 for (ArrayRef<serialization::LocalDeclID>::iterator
7741 DIt = BeginIt; DIt != EndIt; ++DIt)
7742 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
7745 bool
7746 ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
7747 DeclarationName Name) {
7748 assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
7749 "DeclContext has no visible decls in storage");
7750 if (!Name)
7751 return false;
7753 auto It = Lookups.find(DC);
7754 if (It == Lookups.end())
7755 return false;
7757 Deserializing LookupResults(this);
7759 // Load the list of declarations.
7760 SmallVector<NamedDecl *, 64> Decls;
7761 llvm::SmallPtrSet<NamedDecl *, 8> Found;
7762 for (DeclID ID : It->second.Table.find(Name)) {
7763 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
7764 if (ND->getDeclName() == Name && Found.insert(ND).second)
7765 Decls.push_back(ND);
7768 ++NumVisibleDeclContextsRead;
7769 SetExternalVisibleDeclsForName(DC, Name, Decls);
7770 return !Decls.empty();
7773 void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
7774 if (!DC->hasExternalVisibleStorage())
7775 return;
7777 auto It = Lookups.find(DC);
7778 assert(It != Lookups.end() &&
7779 "have external visible storage but no lookup tables");
7781 DeclsMap Decls;
7783 for (DeclID ID : It->second.Table.findAll()) {
7784 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
7785 Decls[ND->getDeclName()].push_back(ND);
7788 ++NumVisibleDeclContextsRead;
7790 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
7791 SetExternalVisibleDeclsForName(DC, I->first, I->second);
7793 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
7796 const serialization::reader::DeclContextLookupTable *
7797 ASTReader::getLoadedLookupTables(DeclContext *Primary) const {
7798 auto I = Lookups.find(Primary);
7799 return I == Lookups.end() ? nullptr : &I->second;
7802 /// Under non-PCH compilation the consumer receives the objc methods
7803 /// before receiving the implementation, and codegen depends on this.
7804 /// We simulate this by deserializing and passing to consumer the methods of the
7805 /// implementation before passing the deserialized implementation decl.
7806 static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
7807 ASTConsumer *Consumer) {
7808 assert(ImplD && Consumer);
7810 for (auto *I : ImplD->methods())
7811 Consumer->HandleInterestingDecl(DeclGroupRef(I));
7813 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
7816 void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
7817 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
7818 PassObjCImplDeclToConsumer(ImplD, Consumer);
7819 else
7820 Consumer->HandleInterestingDecl(DeclGroupRef(D));
7823 void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
7824 this->Consumer = Consumer;
7826 if (Consumer)
7827 PassInterestingDeclsToConsumer();
7829 if (DeserializationListener)
7830 DeserializationListener->ReaderInitialized(this);
7833 void ASTReader::PrintStats() {
7834 std::fprintf(stderr, "*** AST File Statistics:\n");
7836 unsigned NumTypesLoaded =
7837 TypesLoaded.size() - llvm::count(TypesLoaded, QualType());
7838 unsigned NumDeclsLoaded =
7839 DeclsLoaded.size() - llvm::count(DeclsLoaded, (Decl *)nullptr);
7840 unsigned NumIdentifiersLoaded =
7841 IdentifiersLoaded.size() -
7842 llvm::count(IdentifiersLoaded, (IdentifierInfo *)nullptr);
7843 unsigned NumMacrosLoaded =
7844 MacrosLoaded.size() - llvm::count(MacrosLoaded, (MacroInfo *)nullptr);
7845 unsigned NumSelectorsLoaded =
7846 SelectorsLoaded.size() - llvm::count(SelectorsLoaded, Selector());
7848 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
7849 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
7850 NumSLocEntriesRead, TotalNumSLocEntries,
7851 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
7852 if (!TypesLoaded.empty())
7853 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
7854 NumTypesLoaded, (unsigned)TypesLoaded.size(),
7855 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
7856 if (!DeclsLoaded.empty())
7857 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
7858 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
7859 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
7860 if (!IdentifiersLoaded.empty())
7861 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
7862 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
7863 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
7864 if (!MacrosLoaded.empty())
7865 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
7866 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
7867 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
7868 if (!SelectorsLoaded.empty())
7869 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
7870 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
7871 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
7872 if (TotalNumStatements)
7873 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
7874 NumStatementsRead, TotalNumStatements,
7875 ((float)NumStatementsRead/TotalNumStatements * 100));
7876 if (TotalNumMacros)
7877 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
7878 NumMacrosRead, TotalNumMacros,
7879 ((float)NumMacrosRead/TotalNumMacros * 100));
7880 if (TotalLexicalDeclContexts)
7881 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
7882 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
7883 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
7884 * 100));
7885 if (TotalVisibleDeclContexts)
7886 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
7887 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
7888 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
7889 * 100));
7890 if (TotalNumMethodPoolEntries)
7891 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
7892 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
7893 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
7894 * 100));
7895 if (NumMethodPoolLookups)
7896 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
7897 NumMethodPoolHits, NumMethodPoolLookups,
7898 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
7899 if (NumMethodPoolTableLookups)
7900 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
7901 NumMethodPoolTableHits, NumMethodPoolTableLookups,
7902 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
7903 * 100.0));
7904 if (NumIdentifierLookupHits)
7905 std::fprintf(stderr,
7906 " %u / %u identifier table lookups succeeded (%f%%)\n",
7907 NumIdentifierLookupHits, NumIdentifierLookups,
7908 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
7910 if (GlobalIndex) {
7911 std::fprintf(stderr, "\n");
7912 GlobalIndex->printStats();
7915 std::fprintf(stderr, "\n");
7916 dump();
7917 std::fprintf(stderr, "\n");
7920 template<typename Key, typename ModuleFile, unsigned InitialCapacity>
7921 LLVM_DUMP_METHOD static void
7922 dumpModuleIDMap(StringRef Name,
7923 const ContinuousRangeMap<Key, ModuleFile *,
7924 InitialCapacity> &Map) {
7925 if (Map.begin() == Map.end())
7926 return;
7928 using MapType = ContinuousRangeMap<Key, ModuleFile *, InitialCapacity>;
7930 llvm::errs() << Name << ":\n";
7931 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
7932 I != IEnd; ++I) {
7933 llvm::errs() << " " << I->first << " -> " << I->second->FileName
7934 << "\n";
7938 LLVM_DUMP_METHOD void ASTReader::dump() {
7939 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
7940 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
7941 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
7942 dumpModuleIDMap("Global type map", GlobalTypeMap);
7943 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
7944 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
7945 dumpModuleIDMap("Global macro map", GlobalMacroMap);
7946 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
7947 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
7948 dumpModuleIDMap("Global preprocessed entity map",
7949 GlobalPreprocessedEntityMap);
7951 llvm::errs() << "\n*** PCH/Modules Loaded:";
7952 for (ModuleFile &M : ModuleMgr)
7953 M.dump();
7956 /// Return the amount of memory used by memory buffers, breaking down
7957 /// by heap-backed versus mmap'ed memory.
7958 void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
7959 for (ModuleFile &I : ModuleMgr) {
7960 if (llvm::MemoryBuffer *buf = I.Buffer) {
7961 size_t bytes = buf->getBufferSize();
7962 switch (buf->getBufferKind()) {
7963 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
7964 sizes.malloc_bytes += bytes;
7965 break;
7966 case llvm::MemoryBuffer::MemoryBuffer_MMap:
7967 sizes.mmap_bytes += bytes;
7968 break;
7974 void ASTReader::InitializeSema(Sema &S) {
7975 SemaObj = &S;
7976 S.addExternalSource(this);
7978 // Makes sure any declarations that were deserialized "too early"
7979 // still get added to the identifier's declaration chains.
7980 for (uint64_t ID : PreloadedDeclIDs) {
7981 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
7982 pushExternalDeclIntoScope(D, D->getDeclName());
7984 PreloadedDeclIDs.clear();
7986 // FIXME: What happens if these are changed by a module import?
7987 if (!FPPragmaOptions.empty()) {
7988 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
7989 FPOptionsOverride NewOverrides =
7990 FPOptionsOverride::getFromOpaqueInt(FPPragmaOptions[0]);
7991 SemaObj->CurFPFeatures =
7992 NewOverrides.applyOverrides(SemaObj->getLangOpts());
7995 SemaObj->OpenCLFeatures = OpenCLExtensions;
7997 UpdateSema();
8000 void ASTReader::UpdateSema() {
8001 assert(SemaObj && "no Sema to update");
8003 // Load the offsets of the declarations that Sema references.
8004 // They will be lazily deserialized when needed.
8005 if (!SemaDeclRefs.empty()) {
8006 assert(SemaDeclRefs.size() % 3 == 0);
8007 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 3) {
8008 if (!SemaObj->StdNamespace)
8009 SemaObj->StdNamespace = SemaDeclRefs[I];
8010 if (!SemaObj->StdBadAlloc)
8011 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
8012 if (!SemaObj->StdAlignValT)
8013 SemaObj->StdAlignValT = SemaDeclRefs[I+2];
8015 SemaDeclRefs.clear();
8018 // Update the state of pragmas. Use the same API as if we had encountered the
8019 // pragma in the source.
8020 if(OptimizeOffPragmaLocation.isValid())
8021 SemaObj->ActOnPragmaOptimize(/* On = */ false, OptimizeOffPragmaLocation);
8022 if (PragmaMSStructState != -1)
8023 SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState);
8024 if (PointersToMembersPragmaLocation.isValid()) {
8025 SemaObj->ActOnPragmaMSPointersToMembers(
8026 (LangOptions::PragmaMSPointersToMembersKind)
8027 PragmaMSPointersToMembersState,
8028 PointersToMembersPragmaLocation);
8030 SemaObj->ForceCUDAHostDeviceDepth = ForceCUDAHostDeviceDepth;
8032 if (PragmaAlignPackCurrentValue) {
8033 // The bottom of the stack might have a default value. It must be adjusted
8034 // to the current value to ensure that the packing state is preserved after
8035 // popping entries that were included/imported from a PCH/module.
8036 bool DropFirst = false;
8037 if (!PragmaAlignPackStack.empty() &&
8038 PragmaAlignPackStack.front().Location.isInvalid()) {
8039 assert(PragmaAlignPackStack.front().Value ==
8040 SemaObj->AlignPackStack.DefaultValue &&
8041 "Expected a default alignment value");
8042 SemaObj->AlignPackStack.Stack.emplace_back(
8043 PragmaAlignPackStack.front().SlotLabel,
8044 SemaObj->AlignPackStack.CurrentValue,
8045 SemaObj->AlignPackStack.CurrentPragmaLocation,
8046 PragmaAlignPackStack.front().PushLocation);
8047 DropFirst = true;
8049 for (const auto &Entry :
8050 llvm::ArrayRef(PragmaAlignPackStack).drop_front(DropFirst ? 1 : 0)) {
8051 SemaObj->AlignPackStack.Stack.emplace_back(
8052 Entry.SlotLabel, Entry.Value, Entry.Location, Entry.PushLocation);
8054 if (PragmaAlignPackCurrentLocation.isInvalid()) {
8055 assert(*PragmaAlignPackCurrentValue ==
8056 SemaObj->AlignPackStack.DefaultValue &&
8057 "Expected a default align and pack value");
8058 // Keep the current values.
8059 } else {
8060 SemaObj->AlignPackStack.CurrentValue = *PragmaAlignPackCurrentValue;
8061 SemaObj->AlignPackStack.CurrentPragmaLocation =
8062 PragmaAlignPackCurrentLocation;
8065 if (FpPragmaCurrentValue) {
8066 // The bottom of the stack might have a default value. It must be adjusted
8067 // to the current value to ensure that fp-pragma state is preserved after
8068 // popping entries that were included/imported from a PCH/module.
8069 bool DropFirst = false;
8070 if (!FpPragmaStack.empty() && FpPragmaStack.front().Location.isInvalid()) {
8071 assert(FpPragmaStack.front().Value ==
8072 SemaObj->FpPragmaStack.DefaultValue &&
8073 "Expected a default pragma float_control value");
8074 SemaObj->FpPragmaStack.Stack.emplace_back(
8075 FpPragmaStack.front().SlotLabel, SemaObj->FpPragmaStack.CurrentValue,
8076 SemaObj->FpPragmaStack.CurrentPragmaLocation,
8077 FpPragmaStack.front().PushLocation);
8078 DropFirst = true;
8080 for (const auto &Entry :
8081 llvm::ArrayRef(FpPragmaStack).drop_front(DropFirst ? 1 : 0))
8082 SemaObj->FpPragmaStack.Stack.emplace_back(
8083 Entry.SlotLabel, Entry.Value, Entry.Location, Entry.PushLocation);
8084 if (FpPragmaCurrentLocation.isInvalid()) {
8085 assert(*FpPragmaCurrentValue == SemaObj->FpPragmaStack.DefaultValue &&
8086 "Expected a default pragma float_control value");
8087 // Keep the current values.
8088 } else {
8089 SemaObj->FpPragmaStack.CurrentValue = *FpPragmaCurrentValue;
8090 SemaObj->FpPragmaStack.CurrentPragmaLocation = FpPragmaCurrentLocation;
8094 // For non-modular AST files, restore visiblity of modules.
8095 for (auto &Import : ImportedModules) {
8096 if (Import.ImportLoc.isInvalid())
8097 continue;
8098 if (Module *Imported = getSubmodule(Import.ID)) {
8099 SemaObj->makeModuleVisible(Imported, Import.ImportLoc);
8104 IdentifierInfo *ASTReader::get(StringRef Name) {
8105 // Note that we are loading an identifier.
8106 Deserializing AnIdentifier(this);
8108 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
8109 NumIdentifierLookups,
8110 NumIdentifierLookupHits);
8112 // We don't need to do identifier table lookups in C++ modules (we preload
8113 // all interesting declarations, and don't need to use the scope for name
8114 // lookups). Perform the lookup in PCH files, though, since we don't build
8115 // a complete initial identifier table if we're carrying on from a PCH.
8116 if (PP.getLangOpts().CPlusPlus) {
8117 for (auto *F : ModuleMgr.pch_modules())
8118 if (Visitor(*F))
8119 break;
8120 } else {
8121 // If there is a global index, look there first to determine which modules
8122 // provably do not have any results for this identifier.
8123 GlobalModuleIndex::HitSet Hits;
8124 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
8125 if (!loadGlobalIndex()) {
8126 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
8127 HitsPtr = &Hits;
8131 ModuleMgr.visit(Visitor, HitsPtr);
8134 IdentifierInfo *II = Visitor.getIdentifierInfo();
8135 markIdentifierUpToDate(II);
8136 return II;
8139 namespace clang {
8141 /// An identifier-lookup iterator that enumerates all of the
8142 /// identifiers stored within a set of AST files.
8143 class ASTIdentifierIterator : public IdentifierIterator {
8144 /// The AST reader whose identifiers are being enumerated.
8145 const ASTReader &Reader;
8147 /// The current index into the chain of AST files stored in
8148 /// the AST reader.
8149 unsigned Index;
8151 /// The current position within the identifier lookup table
8152 /// of the current AST file.
8153 ASTIdentifierLookupTable::key_iterator Current;
8155 /// The end position within the identifier lookup table of
8156 /// the current AST file.
8157 ASTIdentifierLookupTable::key_iterator End;
8159 /// Whether to skip any modules in the ASTReader.
8160 bool SkipModules;
8162 public:
8163 explicit ASTIdentifierIterator(const ASTReader &Reader,
8164 bool SkipModules = false);
8166 StringRef Next() override;
8169 } // namespace clang
8171 ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader,
8172 bool SkipModules)
8173 : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) {
8176 StringRef ASTIdentifierIterator::Next() {
8177 while (Current == End) {
8178 // If we have exhausted all of our AST files, we're done.
8179 if (Index == 0)
8180 return StringRef();
8182 --Index;
8183 ModuleFile &F = Reader.ModuleMgr[Index];
8184 if (SkipModules && F.isModule())
8185 continue;
8187 ASTIdentifierLookupTable *IdTable =
8188 (ASTIdentifierLookupTable *)F.IdentifierLookupTable;
8189 Current = IdTable->key_begin();
8190 End = IdTable->key_end();
8193 // We have any identifiers remaining in the current AST file; return
8194 // the next one.
8195 StringRef Result = *Current;
8196 ++Current;
8197 return Result;
8200 namespace {
8202 /// A utility for appending two IdentifierIterators.
8203 class ChainedIdentifierIterator : public IdentifierIterator {
8204 std::unique_ptr<IdentifierIterator> Current;
8205 std::unique_ptr<IdentifierIterator> Queued;
8207 public:
8208 ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First,
8209 std::unique_ptr<IdentifierIterator> Second)
8210 : Current(std::move(First)), Queued(std::move(Second)) {}
8212 StringRef Next() override {
8213 if (!Current)
8214 return StringRef();
8216 StringRef result = Current->Next();
8217 if (!result.empty())
8218 return result;
8220 // Try the queued iterator, which may itself be empty.
8221 Current.reset();
8222 std::swap(Current, Queued);
8223 return Next();
8227 } // namespace
8229 IdentifierIterator *ASTReader::getIdentifiers() {
8230 if (!loadGlobalIndex()) {
8231 std::unique_ptr<IdentifierIterator> ReaderIter(
8232 new ASTIdentifierIterator(*this, /*SkipModules=*/true));
8233 std::unique_ptr<IdentifierIterator> ModulesIter(
8234 GlobalIndex->createIdentifierIterator());
8235 return new ChainedIdentifierIterator(std::move(ReaderIter),
8236 std::move(ModulesIter));
8239 return new ASTIdentifierIterator(*this);
8242 namespace clang {
8243 namespace serialization {
8245 class ReadMethodPoolVisitor {
8246 ASTReader &Reader;
8247 Selector Sel;
8248 unsigned PriorGeneration;
8249 unsigned InstanceBits = 0;
8250 unsigned FactoryBits = 0;
8251 bool InstanceHasMoreThanOneDecl = false;
8252 bool FactoryHasMoreThanOneDecl = false;
8253 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
8254 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
8256 public:
8257 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
8258 unsigned PriorGeneration)
8259 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration) {}
8261 bool operator()(ModuleFile &M) {
8262 if (!M.SelectorLookupTable)
8263 return false;
8265 // If we've already searched this module file, skip it now.
8266 if (M.Generation <= PriorGeneration)
8267 return true;
8269 ++Reader.NumMethodPoolTableLookups;
8270 ASTSelectorLookupTable *PoolTable
8271 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
8272 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
8273 if (Pos == PoolTable->end())
8274 return false;
8276 ++Reader.NumMethodPoolTableHits;
8277 ++Reader.NumSelectorsRead;
8278 // FIXME: Not quite happy with the statistics here. We probably should
8279 // disable this tracking when called via LoadSelector.
8280 // Also, should entries without methods count as misses?
8281 ++Reader.NumMethodPoolEntriesRead;
8282 ASTSelectorLookupTrait::data_type Data = *Pos;
8283 if (Reader.DeserializationListener)
8284 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
8286 // Append methods in the reverse order, so that later we can process them
8287 // in the order they appear in the source code by iterating through
8288 // the vector in the reverse order.
8289 InstanceMethods.append(Data.Instance.rbegin(), Data.Instance.rend());
8290 FactoryMethods.append(Data.Factory.rbegin(), Data.Factory.rend());
8291 InstanceBits = Data.InstanceBits;
8292 FactoryBits = Data.FactoryBits;
8293 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
8294 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
8295 return false;
8298 /// Retrieve the instance methods found by this visitor.
8299 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
8300 return InstanceMethods;
8303 /// Retrieve the instance methods found by this visitor.
8304 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
8305 return FactoryMethods;
8308 unsigned getInstanceBits() const { return InstanceBits; }
8309 unsigned getFactoryBits() const { return FactoryBits; }
8311 bool instanceHasMoreThanOneDecl() const {
8312 return InstanceHasMoreThanOneDecl;
8315 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
8318 } // namespace serialization
8319 } // namespace clang
8321 /// Add the given set of methods to the method list.
8322 static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
8323 ObjCMethodList &List) {
8324 for (ObjCMethodDecl *M : llvm::reverse(Methods))
8325 S.addMethodToGlobalList(&List, M);
8328 void ASTReader::ReadMethodPool(Selector Sel) {
8329 // Get the selector generation and update it to the current generation.
8330 unsigned &Generation = SelectorGeneration[Sel];
8331 unsigned PriorGeneration = Generation;
8332 Generation = getGeneration();
8333 SelectorOutOfDate[Sel] = false;
8335 // Search for methods defined with this selector.
8336 ++NumMethodPoolLookups;
8337 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
8338 ModuleMgr.visit(Visitor);
8340 if (Visitor.getInstanceMethods().empty() &&
8341 Visitor.getFactoryMethods().empty())
8342 return;
8344 ++NumMethodPoolHits;
8346 if (!getSema())
8347 return;
8349 Sema &S = *getSema();
8350 Sema::GlobalMethodPool::iterator Pos =
8351 S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethodPool::Lists()))
8352 .first;
8354 Pos->second.first.setBits(Visitor.getInstanceBits());
8355 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
8356 Pos->second.second.setBits(Visitor.getFactoryBits());
8357 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
8359 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
8360 // when building a module we keep every method individually and may need to
8361 // update hasMoreThanOneDecl as we add the methods.
8362 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
8363 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
8366 void ASTReader::updateOutOfDateSelector(Selector Sel) {
8367 if (SelectorOutOfDate[Sel])
8368 ReadMethodPool(Sel);
8371 void ASTReader::ReadKnownNamespaces(
8372 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
8373 Namespaces.clear();
8375 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
8376 if (NamespaceDecl *Namespace
8377 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
8378 Namespaces.push_back(Namespace);
8382 void ASTReader::ReadUndefinedButUsed(
8383 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {
8384 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
8385 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
8386 SourceLocation Loc =
8387 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
8388 Undefined.insert(std::make_pair(D, Loc));
8392 void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
8393 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
8394 Exprs) {
8395 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
8396 FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
8397 uint64_t Count = DelayedDeleteExprs[Idx++];
8398 for (uint64_t C = 0; C < Count; ++C) {
8399 SourceLocation DeleteLoc =
8400 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
8401 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
8402 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
8407 void ASTReader::ReadTentativeDefinitions(
8408 SmallVectorImpl<VarDecl *> &TentativeDefs) {
8409 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
8410 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
8411 if (Var)
8412 TentativeDefs.push_back(Var);
8414 TentativeDefinitions.clear();
8417 void ASTReader::ReadUnusedFileScopedDecls(
8418 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
8419 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
8420 DeclaratorDecl *D
8421 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
8422 if (D)
8423 Decls.push_back(D);
8425 UnusedFileScopedDecls.clear();
8428 void ASTReader::ReadDelegatingConstructors(
8429 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
8430 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
8431 CXXConstructorDecl *D
8432 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
8433 if (D)
8434 Decls.push_back(D);
8436 DelegatingCtorDecls.clear();
8439 void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
8440 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
8441 TypedefNameDecl *D
8442 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
8443 if (D)
8444 Decls.push_back(D);
8446 ExtVectorDecls.clear();
8449 void ASTReader::ReadUnusedLocalTypedefNameCandidates(
8450 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
8451 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
8452 ++I) {
8453 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
8454 GetDecl(UnusedLocalTypedefNameCandidates[I]));
8455 if (D)
8456 Decls.insert(D);
8458 UnusedLocalTypedefNameCandidates.clear();
8461 void ASTReader::ReadDeclsToCheckForDeferredDiags(
8462 llvm::SmallSetVector<Decl *, 4> &Decls) {
8463 for (auto I : DeclsToCheckForDeferredDiags) {
8464 auto *D = dyn_cast_or_null<Decl>(GetDecl(I));
8465 if (D)
8466 Decls.insert(D);
8468 DeclsToCheckForDeferredDiags.clear();
8471 void ASTReader::ReadReferencedSelectors(
8472 SmallVectorImpl<std::pair<Selector, SourceLocation>> &Sels) {
8473 if (ReferencedSelectorsData.empty())
8474 return;
8476 // If there are @selector references added them to its pool. This is for
8477 // implementation of -Wselector.
8478 unsigned int DataSize = ReferencedSelectorsData.size()-1;
8479 unsigned I = 0;
8480 while (I < DataSize) {
8481 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
8482 SourceLocation SelLoc
8483 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
8484 Sels.push_back(std::make_pair(Sel, SelLoc));
8486 ReferencedSelectorsData.clear();
8489 void ASTReader::ReadWeakUndeclaredIdentifiers(
8490 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo>> &WeakIDs) {
8491 if (WeakUndeclaredIdentifiers.empty())
8492 return;
8494 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
8495 IdentifierInfo *WeakId
8496 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
8497 IdentifierInfo *AliasId
8498 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
8499 SourceLocation Loc =
8500 SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
8501 WeakInfo WI(AliasId, Loc);
8502 WeakIDs.push_back(std::make_pair(WeakId, WI));
8504 WeakUndeclaredIdentifiers.clear();
8507 void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
8508 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
8509 ExternalVTableUse VT;
8510 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
8511 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
8512 VT.DefinitionRequired = VTableUses[Idx++];
8513 VTables.push_back(VT);
8516 VTableUses.clear();
8519 void ASTReader::ReadPendingInstantiations(
8520 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation>> &Pending) {
8521 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
8522 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
8523 SourceLocation Loc
8524 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
8526 Pending.push_back(std::make_pair(D, Loc));
8528 PendingInstantiations.clear();
8531 void ASTReader::ReadLateParsedTemplates(
8532 llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>>
8533 &LPTMap) {
8534 for (auto &LPT : LateParsedTemplates) {
8535 ModuleFile *FMod = LPT.first;
8536 RecordDataImpl &LateParsed = LPT.second;
8537 for (unsigned Idx = 0, N = LateParsed.size(); Idx < N;
8538 /* In loop */) {
8539 FunctionDecl *FD =
8540 cast<FunctionDecl>(GetLocalDecl(*FMod, LateParsed[Idx++]));
8542 auto LT = std::make_unique<LateParsedTemplate>();
8543 LT->D = GetLocalDecl(*FMod, LateParsed[Idx++]);
8545 ModuleFile *F = getOwningModuleFile(LT->D);
8546 assert(F && "No module");
8548 unsigned TokN = LateParsed[Idx++];
8549 LT->Toks.reserve(TokN);
8550 for (unsigned T = 0; T < TokN; ++T)
8551 LT->Toks.push_back(ReadToken(*F, LateParsed, Idx));
8553 LPTMap.insert(std::make_pair(FD, std::move(LT)));
8557 LateParsedTemplates.clear();
8560 void ASTReader::LoadSelector(Selector Sel) {
8561 // It would be complicated to avoid reading the methods anyway. So don't.
8562 ReadMethodPool(Sel);
8565 void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
8566 assert(ID && "Non-zero identifier ID required");
8567 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
8568 IdentifiersLoaded[ID - 1] = II;
8569 if (DeserializationListener)
8570 DeserializationListener->IdentifierRead(ID, II);
8573 /// Set the globally-visible declarations associated with the given
8574 /// identifier.
8576 /// If the AST reader is currently in a state where the given declaration IDs
8577 /// cannot safely be resolved, they are queued until it is safe to resolve
8578 /// them.
8580 /// \param II an IdentifierInfo that refers to one or more globally-visible
8581 /// declarations.
8583 /// \param DeclIDs the set of declaration IDs with the name @p II that are
8584 /// visible at global scope.
8586 /// \param Decls if non-null, this vector will be populated with the set of
8587 /// deserialized declarations. These declarations will not be pushed into
8588 /// scope.
8589 void
8590 ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
8591 const SmallVectorImpl<uint32_t> &DeclIDs,
8592 SmallVectorImpl<Decl *> *Decls) {
8593 if (NumCurrentElementsDeserializing && !Decls) {
8594 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
8595 return;
8598 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
8599 if (!SemaObj) {
8600 // Queue this declaration so that it will be added to the
8601 // translation unit scope and identifier's declaration chain
8602 // once a Sema object is known.
8603 PreloadedDeclIDs.push_back(DeclIDs[I]);
8604 continue;
8607 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
8609 // If we're simply supposed to record the declarations, do so now.
8610 if (Decls) {
8611 Decls->push_back(D);
8612 continue;
8615 // Introduce this declaration into the translation-unit scope
8616 // and add it to the declaration chain for this identifier, so
8617 // that (unqualified) name lookup will find it.
8618 pushExternalDeclIntoScope(D, II);
8622 IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
8623 if (ID == 0)
8624 return nullptr;
8626 if (IdentifiersLoaded.empty()) {
8627 Error("no identifier table in AST file");
8628 return nullptr;
8631 ID -= 1;
8632 if (!IdentifiersLoaded[ID]) {
8633 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
8634 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
8635 ModuleFile *M = I->second;
8636 unsigned Index = ID - M->BaseIdentifierID;
8637 const unsigned char *Data =
8638 M->IdentifierTableData + M->IdentifierOffsets[Index];
8640 ASTIdentifierLookupTrait Trait(*this, *M);
8641 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
8642 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
8643 auto &II = PP.getIdentifierTable().get(Key);
8644 IdentifiersLoaded[ID] = &II;
8645 markIdentifierFromAST(*this, II);
8646 if (DeserializationListener)
8647 DeserializationListener->IdentifierRead(ID + 1, &II);
8650 return IdentifiersLoaded[ID];
8653 IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
8654 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
8657 IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
8658 if (LocalID < NUM_PREDEF_IDENT_IDS)
8659 return LocalID;
8661 if (!M.ModuleOffsetMap.empty())
8662 ReadModuleOffsetMap(M);
8664 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8665 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
8666 assert(I != M.IdentifierRemap.end()
8667 && "Invalid index into identifier index remap");
8669 return LocalID + I->second;
8672 MacroInfo *ASTReader::getMacro(MacroID ID) {
8673 if (ID == 0)
8674 return nullptr;
8676 if (MacrosLoaded.empty()) {
8677 Error("no macro table in AST file");
8678 return nullptr;
8681 ID -= NUM_PREDEF_MACRO_IDS;
8682 if (!MacrosLoaded[ID]) {
8683 GlobalMacroMapType::iterator I
8684 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
8685 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
8686 ModuleFile *M = I->second;
8687 unsigned Index = ID - M->BaseMacroID;
8688 MacrosLoaded[ID] =
8689 ReadMacroRecord(*M, M->MacroOffsetsBase + M->MacroOffsets[Index]);
8691 if (DeserializationListener)
8692 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
8693 MacrosLoaded[ID]);
8696 return MacrosLoaded[ID];
8699 MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
8700 if (LocalID < NUM_PREDEF_MACRO_IDS)
8701 return LocalID;
8703 if (!M.ModuleOffsetMap.empty())
8704 ReadModuleOffsetMap(M);
8706 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8707 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
8708 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
8710 return LocalID + I->second;
8713 serialization::SubmoduleID
8714 ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
8715 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
8716 return LocalID;
8718 if (!M.ModuleOffsetMap.empty())
8719 ReadModuleOffsetMap(M);
8721 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8722 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
8723 assert(I != M.SubmoduleRemap.end()
8724 && "Invalid index into submodule index remap");
8726 return LocalID + I->second;
8729 Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
8730 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
8731 assert(GlobalID == 0 && "Unhandled global submodule ID");
8732 return nullptr;
8735 if (GlobalID > SubmodulesLoaded.size()) {
8736 Error("submodule ID out of range in AST file");
8737 return nullptr;
8740 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
8743 Module *ASTReader::getModule(unsigned ID) {
8744 return getSubmodule(ID);
8747 ModuleFile *ASTReader::getLocalModuleFile(ModuleFile &F, unsigned ID) {
8748 if (ID & 1) {
8749 // It's a module, look it up by submodule ID.
8750 auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(F, ID >> 1));
8751 return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
8752 } else {
8753 // It's a prefix (preamble, PCH, ...). Look it up by index.
8754 unsigned IndexFromEnd = ID >> 1;
8755 assert(IndexFromEnd && "got reference to unknown module file");
8756 return getModuleManager().pch_modules().end()[-IndexFromEnd];
8760 unsigned ASTReader::getModuleFileID(ModuleFile *F) {
8761 if (!F)
8762 return 1;
8764 // For a file representing a module, use the submodule ID of the top-level
8765 // module as the file ID. For any other kind of file, the number of such
8766 // files loaded beforehand will be the same on reload.
8767 // FIXME: Is this true even if we have an explicit module file and a PCH?
8768 if (F->isModule())
8769 return ((F->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
8771 auto PCHModules = getModuleManager().pch_modules();
8772 auto I = llvm::find(PCHModules, F);
8773 assert(I != PCHModules.end() && "emitting reference to unknown file");
8774 return (I - PCHModules.end()) << 1;
8777 std::optional<ASTSourceDescriptor> ASTReader::getSourceDescriptor(unsigned ID) {
8778 if (Module *M = getSubmodule(ID))
8779 return ASTSourceDescriptor(*M);
8781 // If there is only a single PCH, return it instead.
8782 // Chained PCH are not supported.
8783 const auto &PCHChain = ModuleMgr.pch_modules();
8784 if (std::distance(std::begin(PCHChain), std::end(PCHChain))) {
8785 ModuleFile &MF = ModuleMgr.getPrimaryModule();
8786 StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName);
8787 StringRef FileName = llvm::sys::path::filename(MF.FileName);
8788 return ASTSourceDescriptor(ModuleName,
8789 llvm::sys::path::parent_path(MF.FileName),
8790 FileName, MF.Signature);
8792 return std::nullopt;
8795 ExternalASTSource::ExtKind ASTReader::hasExternalDefinitions(const Decl *FD) {
8796 auto I = DefinitionSource.find(FD);
8797 if (I == DefinitionSource.end())
8798 return EK_ReplyHazy;
8799 return I->second ? EK_Never : EK_Always;
8802 Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
8803 return DecodeSelector(getGlobalSelectorID(M, LocalID));
8806 Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
8807 if (ID == 0)
8808 return Selector();
8810 if (ID > SelectorsLoaded.size()) {
8811 Error("selector ID out of range in AST file");
8812 return Selector();
8815 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
8816 // Load this selector from the selector table.
8817 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
8818 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
8819 ModuleFile &M = *I->second;
8820 ASTSelectorLookupTrait Trait(*this, M);
8821 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
8822 SelectorsLoaded[ID - 1] =
8823 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
8824 if (DeserializationListener)
8825 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
8828 return SelectorsLoaded[ID - 1];
8831 Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
8832 return DecodeSelector(ID);
8835 uint32_t ASTReader::GetNumExternalSelectors() {
8836 // ID 0 (the null selector) is considered an external selector.
8837 return getTotalNumSelectors() + 1;
8840 serialization::SelectorID
8841 ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
8842 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
8843 return LocalID;
8845 if (!M.ModuleOffsetMap.empty())
8846 ReadModuleOffsetMap(M);
8848 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8849 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
8850 assert(I != M.SelectorRemap.end()
8851 && "Invalid index into selector index remap");
8853 return LocalID + I->second;
8856 DeclarationNameLoc
8857 ASTRecordReader::readDeclarationNameLoc(DeclarationName Name) {
8858 switch (Name.getNameKind()) {
8859 case DeclarationName::CXXConstructorName:
8860 case DeclarationName::CXXDestructorName:
8861 case DeclarationName::CXXConversionFunctionName:
8862 return DeclarationNameLoc::makeNamedTypeLoc(readTypeSourceInfo());
8864 case DeclarationName::CXXOperatorName:
8865 return DeclarationNameLoc::makeCXXOperatorNameLoc(readSourceRange());
8867 case DeclarationName::CXXLiteralOperatorName:
8868 return DeclarationNameLoc::makeCXXLiteralOperatorNameLoc(
8869 readSourceLocation());
8871 case DeclarationName::Identifier:
8872 case DeclarationName::ObjCZeroArgSelector:
8873 case DeclarationName::ObjCOneArgSelector:
8874 case DeclarationName::ObjCMultiArgSelector:
8875 case DeclarationName::CXXUsingDirective:
8876 case DeclarationName::CXXDeductionGuideName:
8877 break;
8879 return DeclarationNameLoc();
8882 DeclarationNameInfo ASTRecordReader::readDeclarationNameInfo() {
8883 DeclarationNameInfo NameInfo;
8884 NameInfo.setName(readDeclarationName());
8885 NameInfo.setLoc(readSourceLocation());
8886 NameInfo.setInfo(readDeclarationNameLoc(NameInfo.getName()));
8887 return NameInfo;
8890 void ASTRecordReader::readQualifierInfo(QualifierInfo &Info) {
8891 Info.QualifierLoc = readNestedNameSpecifierLoc();
8892 unsigned NumTPLists = readInt();
8893 Info.NumTemplParamLists = NumTPLists;
8894 if (NumTPLists) {
8895 Info.TemplParamLists =
8896 new (getContext()) TemplateParameterList *[NumTPLists];
8897 for (unsigned i = 0; i != NumTPLists; ++i)
8898 Info.TemplParamLists[i] = readTemplateParameterList();
8902 TemplateParameterList *
8903 ASTRecordReader::readTemplateParameterList() {
8904 SourceLocation TemplateLoc = readSourceLocation();
8905 SourceLocation LAngleLoc = readSourceLocation();
8906 SourceLocation RAngleLoc = readSourceLocation();
8908 unsigned NumParams = readInt();
8909 SmallVector<NamedDecl *, 16> Params;
8910 Params.reserve(NumParams);
8911 while (NumParams--)
8912 Params.push_back(readDeclAs<NamedDecl>());
8914 bool HasRequiresClause = readBool();
8915 Expr *RequiresClause = HasRequiresClause ? readExpr() : nullptr;
8917 TemplateParameterList *TemplateParams = TemplateParameterList::Create(
8918 getContext(), TemplateLoc, LAngleLoc, Params, RAngleLoc, RequiresClause);
8919 return TemplateParams;
8922 void ASTRecordReader::readTemplateArgumentList(
8923 SmallVectorImpl<TemplateArgument> &TemplArgs,
8924 bool Canonicalize) {
8925 unsigned NumTemplateArgs = readInt();
8926 TemplArgs.reserve(NumTemplateArgs);
8927 while (NumTemplateArgs--)
8928 TemplArgs.push_back(readTemplateArgument(Canonicalize));
8931 /// Read a UnresolvedSet structure.
8932 void ASTRecordReader::readUnresolvedSet(LazyASTUnresolvedSet &Set) {
8933 unsigned NumDecls = readInt();
8934 Set.reserve(getContext(), NumDecls);
8935 while (NumDecls--) {
8936 DeclID ID = readDeclID();
8937 AccessSpecifier AS = (AccessSpecifier) readInt();
8938 Set.addLazyDecl(getContext(), ID, AS);
8942 CXXBaseSpecifier
8943 ASTRecordReader::readCXXBaseSpecifier() {
8944 bool isVirtual = readBool();
8945 bool isBaseOfClass = readBool();
8946 AccessSpecifier AS = static_cast<AccessSpecifier>(readInt());
8947 bool inheritConstructors = readBool();
8948 TypeSourceInfo *TInfo = readTypeSourceInfo();
8949 SourceRange Range = readSourceRange();
8950 SourceLocation EllipsisLoc = readSourceLocation();
8951 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
8952 EllipsisLoc);
8953 Result.setInheritConstructors(inheritConstructors);
8954 return Result;
8957 CXXCtorInitializer **
8958 ASTRecordReader::readCXXCtorInitializers() {
8959 ASTContext &Context = getContext();
8960 unsigned NumInitializers = readInt();
8961 assert(NumInitializers && "wrote ctor initializers but have no inits");
8962 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
8963 for (unsigned i = 0; i != NumInitializers; ++i) {
8964 TypeSourceInfo *TInfo = nullptr;
8965 bool IsBaseVirtual = false;
8966 FieldDecl *Member = nullptr;
8967 IndirectFieldDecl *IndirectMember = nullptr;
8969 CtorInitializerType Type = (CtorInitializerType) readInt();
8970 switch (Type) {
8971 case CTOR_INITIALIZER_BASE:
8972 TInfo = readTypeSourceInfo();
8973 IsBaseVirtual = readBool();
8974 break;
8976 case CTOR_INITIALIZER_DELEGATING:
8977 TInfo = readTypeSourceInfo();
8978 break;
8980 case CTOR_INITIALIZER_MEMBER:
8981 Member = readDeclAs<FieldDecl>();
8982 break;
8984 case CTOR_INITIALIZER_INDIRECT_MEMBER:
8985 IndirectMember = readDeclAs<IndirectFieldDecl>();
8986 break;
8989 SourceLocation MemberOrEllipsisLoc = readSourceLocation();
8990 Expr *Init = readExpr();
8991 SourceLocation LParenLoc = readSourceLocation();
8992 SourceLocation RParenLoc = readSourceLocation();
8994 CXXCtorInitializer *BOMInit;
8995 if (Type == CTOR_INITIALIZER_BASE)
8996 BOMInit = new (Context)
8997 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
8998 RParenLoc, MemberOrEllipsisLoc);
8999 else if (Type == CTOR_INITIALIZER_DELEGATING)
9000 BOMInit = new (Context)
9001 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
9002 else if (Member)
9003 BOMInit = new (Context)
9004 CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc, LParenLoc,
9005 Init, RParenLoc);
9006 else
9007 BOMInit = new (Context)
9008 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
9009 LParenLoc, Init, RParenLoc);
9011 if (/*IsWritten*/readBool()) {
9012 unsigned SourceOrder = readInt();
9013 BOMInit->setSourceOrder(SourceOrder);
9016 CtorInitializers[i] = BOMInit;
9019 return CtorInitializers;
9022 NestedNameSpecifierLoc
9023 ASTRecordReader::readNestedNameSpecifierLoc() {
9024 ASTContext &Context = getContext();
9025 unsigned N = readInt();
9026 NestedNameSpecifierLocBuilder Builder;
9027 for (unsigned I = 0; I != N; ++I) {
9028 auto Kind = readNestedNameSpecifierKind();
9029 switch (Kind) {
9030 case NestedNameSpecifier::Identifier: {
9031 IdentifierInfo *II = readIdentifier();
9032 SourceRange Range = readSourceRange();
9033 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
9034 break;
9037 case NestedNameSpecifier::Namespace: {
9038 NamespaceDecl *NS = readDeclAs<NamespaceDecl>();
9039 SourceRange Range = readSourceRange();
9040 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
9041 break;
9044 case NestedNameSpecifier::NamespaceAlias: {
9045 NamespaceAliasDecl *Alias = readDeclAs<NamespaceAliasDecl>();
9046 SourceRange Range = readSourceRange();
9047 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
9048 break;
9051 case NestedNameSpecifier::TypeSpec:
9052 case NestedNameSpecifier::TypeSpecWithTemplate: {
9053 bool Template = readBool();
9054 TypeSourceInfo *T = readTypeSourceInfo();
9055 if (!T)
9056 return NestedNameSpecifierLoc();
9057 SourceLocation ColonColonLoc = readSourceLocation();
9059 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
9060 Builder.Extend(Context,
9061 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
9062 T->getTypeLoc(), ColonColonLoc);
9063 break;
9066 case NestedNameSpecifier::Global: {
9067 SourceLocation ColonColonLoc = readSourceLocation();
9068 Builder.MakeGlobal(Context, ColonColonLoc);
9069 break;
9072 case NestedNameSpecifier::Super: {
9073 CXXRecordDecl *RD = readDeclAs<CXXRecordDecl>();
9074 SourceRange Range = readSourceRange();
9075 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
9076 break;
9081 return Builder.getWithLocInContext(Context);
9084 SourceRange ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
9085 unsigned &Idx, LocSeq *Seq) {
9086 SourceLocation beg = ReadSourceLocation(F, Record, Idx, Seq);
9087 SourceLocation end = ReadSourceLocation(F, Record, Idx, Seq);
9088 return SourceRange(beg, end);
9091 /// Read a floating-point value
9092 llvm::APFloat ASTRecordReader::readAPFloat(const llvm::fltSemantics &Sem) {
9093 return llvm::APFloat(Sem, readAPInt());
9096 // Read a string
9097 std::string ASTReader::ReadString(const RecordDataImpl &Record, unsigned &Idx) {
9098 unsigned Len = Record[Idx++];
9099 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
9100 Idx += Len;
9101 return Result;
9104 std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
9105 unsigned &Idx) {
9106 std::string Filename = ReadString(Record, Idx);
9107 ResolveImportedPath(F, Filename);
9108 return Filename;
9111 std::string ASTReader::ReadPath(StringRef BaseDirectory,
9112 const RecordData &Record, unsigned &Idx) {
9113 std::string Filename = ReadString(Record, Idx);
9114 if (!BaseDirectory.empty())
9115 ResolveImportedPath(Filename, BaseDirectory);
9116 return Filename;
9119 VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
9120 unsigned &Idx) {
9121 unsigned Major = Record[Idx++];
9122 unsigned Minor = Record[Idx++];
9123 unsigned Subminor = Record[Idx++];
9124 if (Minor == 0)
9125 return VersionTuple(Major);
9126 if (Subminor == 0)
9127 return VersionTuple(Major, Minor - 1);
9128 return VersionTuple(Major, Minor - 1, Subminor - 1);
9131 CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
9132 const RecordData &Record,
9133 unsigned &Idx) {
9134 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
9135 return CXXTemporary::Create(getContext(), Decl);
9138 DiagnosticBuilder ASTReader::Diag(unsigned DiagID) const {
9139 return Diag(CurrentImportLoc, DiagID);
9142 DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) const {
9143 return Diags.Report(Loc, DiagID);
9146 /// Retrieve the identifier table associated with the
9147 /// preprocessor.
9148 IdentifierTable &ASTReader::getIdentifierTable() {
9149 return PP.getIdentifierTable();
9152 /// Record that the given ID maps to the given switch-case
9153 /// statement.
9154 void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
9155 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
9156 "Already have a SwitchCase with this ID");
9157 (*CurrSwitchCaseStmts)[ID] = SC;
9160 /// Retrieve the switch-case statement with the given ID.
9161 SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
9162 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
9163 return (*CurrSwitchCaseStmts)[ID];
9166 void ASTReader::ClearSwitchCaseIDs() {
9167 CurrSwitchCaseStmts->clear();
9170 void ASTReader::ReadComments() {
9171 ASTContext &Context = getContext();
9172 std::vector<RawComment *> Comments;
9173 for (SmallVectorImpl<std::pair<BitstreamCursor,
9174 serialization::ModuleFile *>>::iterator
9175 I = CommentsCursors.begin(),
9176 E = CommentsCursors.end();
9177 I != E; ++I) {
9178 Comments.clear();
9179 BitstreamCursor &Cursor = I->first;
9180 serialization::ModuleFile &F = *I->second;
9181 SavedStreamPosition SavedPosition(Cursor);
9183 RecordData Record;
9184 while (true) {
9185 Expected<llvm::BitstreamEntry> MaybeEntry =
9186 Cursor.advanceSkippingSubblocks(
9187 BitstreamCursor::AF_DontPopBlockAtEnd);
9188 if (!MaybeEntry) {
9189 Error(MaybeEntry.takeError());
9190 return;
9192 llvm::BitstreamEntry Entry = MaybeEntry.get();
9194 switch (Entry.Kind) {
9195 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
9196 case llvm::BitstreamEntry::Error:
9197 Error("malformed block record in AST file");
9198 return;
9199 case llvm::BitstreamEntry::EndBlock:
9200 goto NextCursor;
9201 case llvm::BitstreamEntry::Record:
9202 // The interesting case.
9203 break;
9206 // Read a record.
9207 Record.clear();
9208 Expected<unsigned> MaybeComment = Cursor.readRecord(Entry.ID, Record);
9209 if (!MaybeComment) {
9210 Error(MaybeComment.takeError());
9211 return;
9213 switch ((CommentRecordTypes)MaybeComment.get()) {
9214 case COMMENTS_RAW_COMMENT: {
9215 unsigned Idx = 0;
9216 SourceRange SR = ReadSourceRange(F, Record, Idx);
9217 RawComment::CommentKind Kind =
9218 (RawComment::CommentKind) Record[Idx++];
9219 bool IsTrailingComment = Record[Idx++];
9220 bool IsAlmostTrailingComment = Record[Idx++];
9221 Comments.push_back(new (Context) RawComment(
9222 SR, Kind, IsTrailingComment, IsAlmostTrailingComment));
9223 break;
9227 NextCursor:
9228 llvm::DenseMap<FileID, std::map<unsigned, RawComment *>>
9229 FileToOffsetToComment;
9230 for (RawComment *C : Comments) {
9231 SourceLocation CommentLoc = C->getBeginLoc();
9232 if (CommentLoc.isValid()) {
9233 std::pair<FileID, unsigned> Loc =
9234 SourceMgr.getDecomposedLoc(CommentLoc);
9235 if (Loc.first.isValid())
9236 Context.Comments.OrderedComments[Loc.first].emplace(Loc.second, C);
9242 void ASTReader::visitInputFiles(serialization::ModuleFile &MF,
9243 bool IncludeSystem, bool Complain,
9244 llvm::function_ref<void(const serialization::InputFile &IF,
9245 bool isSystem)> Visitor) {
9246 unsigned NumUserInputs = MF.NumUserInputFiles;
9247 unsigned NumInputs = MF.InputFilesLoaded.size();
9248 assert(NumUserInputs <= NumInputs);
9249 unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
9250 for (unsigned I = 0; I < N; ++I) {
9251 bool IsSystem = I >= NumUserInputs;
9252 InputFile IF = getInputFile(MF, I+1, Complain);
9253 Visitor(IF, IsSystem);
9257 void ASTReader::visitTopLevelModuleMaps(
9258 serialization::ModuleFile &MF,
9259 llvm::function_ref<void(FileEntryRef FE)> Visitor) {
9260 unsigned NumInputs = MF.InputFilesLoaded.size();
9261 for (unsigned I = 0; I < NumInputs; ++I) {
9262 InputFileInfo IFI = getInputFileInfo(MF, I + 1);
9263 if (IFI.TopLevelModuleMap)
9264 if (auto FE = getInputFile(MF, I + 1).getFile())
9265 Visitor(*FE);
9269 void ASTReader::finishPendingActions() {
9270 while (!PendingIdentifierInfos.empty() || !PendingFunctionTypes.empty() ||
9271 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
9272 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
9273 !PendingUpdateRecords.empty() ||
9274 !PendingObjCExtensionIvarRedeclarations.empty()) {
9275 // If any identifiers with corresponding top-level declarations have
9276 // been loaded, load those declarations now.
9277 using TopLevelDeclsMap =
9278 llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2>>;
9279 TopLevelDeclsMap TopLevelDecls;
9281 while (!PendingIdentifierInfos.empty()) {
9282 IdentifierInfo *II = PendingIdentifierInfos.back().first;
9283 SmallVector<uint32_t, 4> DeclIDs =
9284 std::move(PendingIdentifierInfos.back().second);
9285 PendingIdentifierInfos.pop_back();
9287 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
9290 // Load each function type that we deferred loading because it was a
9291 // deduced type that might refer to a local type declared within itself.
9292 for (unsigned I = 0; I != PendingFunctionTypes.size(); ++I) {
9293 auto *FD = PendingFunctionTypes[I].first;
9294 FD->setType(GetType(PendingFunctionTypes[I].second));
9296 // If we gave a function a deduced return type, remember that we need to
9297 // propagate that along the redeclaration chain.
9298 auto *DT = FD->getReturnType()->getContainedDeducedType();
9299 if (DT && DT->isDeduced())
9300 PendingDeducedTypeUpdates.insert(
9301 {FD->getCanonicalDecl(), FD->getReturnType()});
9303 PendingFunctionTypes.clear();
9305 // For each decl chain that we wanted to complete while deserializing, mark
9306 // it as "still needs to be completed".
9307 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
9308 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
9310 PendingIncompleteDeclChains.clear();
9312 // Load pending declaration chains.
9313 for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
9314 loadPendingDeclChain(PendingDeclChains[I].first,
9315 PendingDeclChains[I].second);
9316 PendingDeclChains.clear();
9318 // Make the most recent of the top-level declarations visible.
9319 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
9320 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
9321 IdentifierInfo *II = TLD->first;
9322 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
9323 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
9327 // Load any pending macro definitions.
9328 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
9329 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
9330 SmallVector<PendingMacroInfo, 2> GlobalIDs;
9331 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
9332 // Initialize the macro history from chained-PCHs ahead of module imports.
9333 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
9334 ++IDIdx) {
9335 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
9336 if (!Info.M->isModule())
9337 resolvePendingMacro(II, Info);
9339 // Handle module imports.
9340 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
9341 ++IDIdx) {
9342 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
9343 if (Info.M->isModule())
9344 resolvePendingMacro(II, Info);
9347 PendingMacroIDs.clear();
9349 // Wire up the DeclContexts for Decls that we delayed setting until
9350 // recursive loading is completed.
9351 while (!PendingDeclContextInfos.empty()) {
9352 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
9353 PendingDeclContextInfos.pop_front();
9354 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
9355 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
9356 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
9359 // Perform any pending declaration updates.
9360 while (!PendingUpdateRecords.empty()) {
9361 auto Update = PendingUpdateRecords.pop_back_val();
9362 ReadingKindTracker ReadingKind(Read_Decl, *this);
9363 loadDeclUpdateRecords(Update);
9366 while (!PendingObjCExtensionIvarRedeclarations.empty()) {
9367 auto ExtensionsPair = PendingObjCExtensionIvarRedeclarations.back().first;
9368 auto DuplicateIvars =
9369 PendingObjCExtensionIvarRedeclarations.back().second;
9370 llvm::DenseSet<std::pair<Decl *, Decl *>> NonEquivalentDecls;
9371 StructuralEquivalenceContext Ctx(
9372 ExtensionsPair.first->getASTContext(),
9373 ExtensionsPair.second->getASTContext(), NonEquivalentDecls,
9374 StructuralEquivalenceKind::Default, /*StrictTypeSpelling =*/false,
9375 /*Complain =*/false,
9376 /*ErrorOnTagTypeMismatch =*/true);
9377 if (Ctx.IsEquivalent(ExtensionsPair.first, ExtensionsPair.second)) {
9378 // Merge redeclared ivars with their predecessors.
9379 for (auto IvarPair : DuplicateIvars) {
9380 ObjCIvarDecl *Ivar = IvarPair.first, *PrevIvar = IvarPair.second;
9381 // Change semantic DeclContext but keep the lexical one.
9382 Ivar->setDeclContextsImpl(PrevIvar->getDeclContext(),
9383 Ivar->getLexicalDeclContext(),
9384 getContext());
9385 getContext().setPrimaryMergedDecl(Ivar, PrevIvar->getCanonicalDecl());
9387 // Invalidate duplicate extension and the cached ivar list.
9388 ExtensionsPair.first->setInvalidDecl();
9389 ExtensionsPair.second->getClassInterface()
9390 ->getDefinition()
9391 ->setIvarList(nullptr);
9392 } else {
9393 for (auto IvarPair : DuplicateIvars) {
9394 Diag(IvarPair.first->getLocation(),
9395 diag::err_duplicate_ivar_declaration)
9396 << IvarPair.first->getIdentifier();
9397 Diag(IvarPair.second->getLocation(), diag::note_previous_definition);
9400 PendingObjCExtensionIvarRedeclarations.pop_back();
9404 // At this point, all update records for loaded decls are in place, so any
9405 // fake class definitions should have become real.
9406 assert(PendingFakeDefinitionData.empty() &&
9407 "faked up a class definition but never saw the real one");
9409 // If we deserialized any C++ or Objective-C class definitions, any
9410 // Objective-C protocol definitions, or any redeclarable templates, make sure
9411 // that all redeclarations point to the definitions. Note that this can only
9412 // happen now, after the redeclaration chains have been fully wired.
9413 for (Decl *D : PendingDefinitions) {
9414 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
9415 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
9416 // Make sure that the TagType points at the definition.
9417 const_cast<TagType*>(TagT)->decl = TD;
9420 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
9421 for (auto *R = getMostRecentExistingDecl(RD); R;
9422 R = R->getPreviousDecl()) {
9423 assert((R == D) ==
9424 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
9425 "declaration thinks it's the definition but it isn't");
9426 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
9430 continue;
9433 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
9434 // Make sure that the ObjCInterfaceType points at the definition.
9435 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
9436 ->Decl = ID;
9438 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
9439 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
9441 continue;
9444 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
9445 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
9446 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
9448 continue;
9451 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
9452 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
9453 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
9455 PendingDefinitions.clear();
9457 // Load the bodies of any functions or methods we've encountered. We do
9458 // this now (delayed) so that we can be sure that the declaration chains
9459 // have been fully wired up (hasBody relies on this).
9460 // FIXME: We shouldn't require complete redeclaration chains here.
9461 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
9462 PBEnd = PendingBodies.end();
9463 PB != PBEnd; ++PB) {
9464 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
9465 // For a function defined inline within a class template, force the
9466 // canonical definition to be the one inside the canonical definition of
9467 // the template. This ensures that we instantiate from a correct view
9468 // of the template.
9470 // Sadly we can't do this more generally: we can't be sure that all
9471 // copies of an arbitrary class definition will have the same members
9472 // defined (eg, some member functions may not be instantiated, and some
9473 // special members may or may not have been implicitly defined).
9474 if (auto *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalParent()))
9475 if (RD->isDependentContext() && !RD->isThisDeclarationADefinition())
9476 continue;
9478 // FIXME: Check for =delete/=default?
9479 // FIXME: Complain about ODR violations here?
9480 const FunctionDecl *Defn = nullptr;
9481 if (!getContext().getLangOpts().Modules || !FD->hasBody(Defn)) {
9482 FD->setLazyBody(PB->second);
9483 } else {
9484 auto *NonConstDefn = const_cast<FunctionDecl*>(Defn);
9485 mergeDefinitionVisibility(NonConstDefn, FD);
9487 if (!FD->isLateTemplateParsed() &&
9488 !NonConstDefn->isLateTemplateParsed() &&
9489 FD->getODRHash() != NonConstDefn->getODRHash()) {
9490 if (!isa<CXXMethodDecl>(FD)) {
9491 PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
9492 } else if (FD->getLexicalParent()->isFileContext() &&
9493 NonConstDefn->getLexicalParent()->isFileContext()) {
9494 // Only diagnose out-of-line method definitions. If they are
9495 // in class definitions, then an error will be generated when
9496 // processing the class bodies.
9497 PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
9501 continue;
9504 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
9505 if (!getContext().getLangOpts().Modules || !MD->hasBody())
9506 MD->setLazyBody(PB->second);
9508 PendingBodies.clear();
9510 // Do some cleanup.
9511 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
9512 getContext().deduplicateMergedDefinitonsFor(ND);
9513 PendingMergedDefinitionsToDeduplicate.clear();
9516 void ASTReader::diagnoseOdrViolations() {
9517 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty() &&
9518 PendingRecordOdrMergeFailures.empty() &&
9519 PendingFunctionOdrMergeFailures.empty() &&
9520 PendingEnumOdrMergeFailures.empty() &&
9521 PendingObjCInterfaceOdrMergeFailures.empty() &&
9522 PendingObjCProtocolOdrMergeFailures.empty())
9523 return;
9525 // Trigger the import of the full definition of each class that had any
9526 // odr-merging problems, so we can produce better diagnostics for them.
9527 // These updates may in turn find and diagnose some ODR failures, so take
9528 // ownership of the set first.
9529 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
9530 PendingOdrMergeFailures.clear();
9531 for (auto &Merge : OdrMergeFailures) {
9532 Merge.first->buildLookup();
9533 Merge.first->decls_begin();
9534 Merge.first->bases_begin();
9535 Merge.first->vbases_begin();
9536 for (auto &RecordPair : Merge.second) {
9537 auto *RD = RecordPair.first;
9538 RD->decls_begin();
9539 RD->bases_begin();
9540 RD->vbases_begin();
9544 // Trigger the import of the full definition of each record in C/ObjC.
9545 auto RecordOdrMergeFailures = std::move(PendingRecordOdrMergeFailures);
9546 PendingRecordOdrMergeFailures.clear();
9547 for (auto &Merge : RecordOdrMergeFailures) {
9548 Merge.first->decls_begin();
9549 for (auto &D : Merge.second)
9550 D->decls_begin();
9553 // Trigger the import of the full interface definition.
9554 auto ObjCInterfaceOdrMergeFailures =
9555 std::move(PendingObjCInterfaceOdrMergeFailures);
9556 PendingObjCInterfaceOdrMergeFailures.clear();
9557 for (auto &Merge : ObjCInterfaceOdrMergeFailures) {
9558 Merge.first->decls_begin();
9559 for (auto &InterfacePair : Merge.second)
9560 InterfacePair.first->decls_begin();
9563 // Trigger the import of functions.
9564 auto FunctionOdrMergeFailures = std::move(PendingFunctionOdrMergeFailures);
9565 PendingFunctionOdrMergeFailures.clear();
9566 for (auto &Merge : FunctionOdrMergeFailures) {
9567 Merge.first->buildLookup();
9568 Merge.first->decls_begin();
9569 Merge.first->getBody();
9570 for (auto &FD : Merge.second) {
9571 FD->buildLookup();
9572 FD->decls_begin();
9573 FD->getBody();
9577 // Trigger the import of enums.
9578 auto EnumOdrMergeFailures = std::move(PendingEnumOdrMergeFailures);
9579 PendingEnumOdrMergeFailures.clear();
9580 for (auto &Merge : EnumOdrMergeFailures) {
9581 Merge.first->decls_begin();
9582 for (auto &Enum : Merge.second) {
9583 Enum->decls_begin();
9587 // Trigger the import of the full protocol definition.
9588 auto ObjCProtocolOdrMergeFailures =
9589 std::move(PendingObjCProtocolOdrMergeFailures);
9590 PendingObjCProtocolOdrMergeFailures.clear();
9591 for (auto &Merge : ObjCProtocolOdrMergeFailures) {
9592 Merge.first->decls_begin();
9593 for (auto &ProtocolPair : Merge.second)
9594 ProtocolPair.first->decls_begin();
9597 // For each declaration from a merged context, check that the canonical
9598 // definition of that context also contains a declaration of the same
9599 // entity.
9601 // Caution: this loop does things that might invalidate iterators into
9602 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
9603 while (!PendingOdrMergeChecks.empty()) {
9604 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
9606 // FIXME: Skip over implicit declarations for now. This matters for things
9607 // like implicitly-declared special member functions. This isn't entirely
9608 // correct; we can end up with multiple unmerged declarations of the same
9609 // implicit entity.
9610 if (D->isImplicit())
9611 continue;
9613 DeclContext *CanonDef = D->getDeclContext();
9615 bool Found = false;
9616 const Decl *DCanon = D->getCanonicalDecl();
9618 for (auto *RI : D->redecls()) {
9619 if (RI->getLexicalDeclContext() == CanonDef) {
9620 Found = true;
9621 break;
9624 if (Found)
9625 continue;
9627 // Quick check failed, time to do the slow thing. Note, we can't just
9628 // look up the name of D in CanonDef here, because the member that is
9629 // in CanonDef might not be found by name lookup (it might have been
9630 // replaced by a more recent declaration in the lookup table), and we
9631 // can't necessarily find it in the redeclaration chain because it might
9632 // be merely mergeable, not redeclarable.
9633 llvm::SmallVector<const NamedDecl*, 4> Candidates;
9634 for (auto *CanonMember : CanonDef->decls()) {
9635 if (CanonMember->getCanonicalDecl() == DCanon) {
9636 // This can happen if the declaration is merely mergeable and not
9637 // actually redeclarable (we looked for redeclarations earlier).
9639 // FIXME: We should be able to detect this more efficiently, without
9640 // pulling in all of the members of CanonDef.
9641 Found = true;
9642 break;
9644 if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
9645 if (ND->getDeclName() == D->getDeclName())
9646 Candidates.push_back(ND);
9649 if (!Found) {
9650 // The AST doesn't like TagDecls becoming invalid after they've been
9651 // completed. We only really need to mark FieldDecls as invalid here.
9652 if (!isa<TagDecl>(D))
9653 D->setInvalidDecl();
9655 // Ensure we don't accidentally recursively enter deserialization while
9656 // we're producing our diagnostic.
9657 Deserializing RecursionGuard(this);
9659 std::string CanonDefModule =
9660 ODRDiagsEmitter::getOwningModuleNameForDiagnostic(
9661 cast<Decl>(CanonDef));
9662 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
9663 << D << ODRDiagsEmitter::getOwningModuleNameForDiagnostic(D)
9664 << CanonDef << CanonDefModule.empty() << CanonDefModule;
9666 if (Candidates.empty())
9667 Diag(cast<Decl>(CanonDef)->getLocation(),
9668 diag::note_module_odr_violation_no_possible_decls) << D;
9669 else {
9670 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
9671 Diag(Candidates[I]->getLocation(),
9672 diag::note_module_odr_violation_possible_decl)
9673 << Candidates[I];
9676 DiagnosedOdrMergeFailures.insert(CanonDef);
9680 if (OdrMergeFailures.empty() && RecordOdrMergeFailures.empty() &&
9681 FunctionOdrMergeFailures.empty() && EnumOdrMergeFailures.empty() &&
9682 ObjCInterfaceOdrMergeFailures.empty() &&
9683 ObjCProtocolOdrMergeFailures.empty())
9684 return;
9686 // Ensure we don't accidentally recursively enter deserialization while
9687 // we're producing our diagnostics.
9688 Deserializing RecursionGuard(this);
9689 ODRDiagsEmitter DiagsEmitter(Diags, getContext(),
9690 getPreprocessor().getLangOpts());
9692 // Issue any pending ODR-failure diagnostics.
9693 for (auto &Merge : OdrMergeFailures) {
9694 // If we've already pointed out a specific problem with this class, don't
9695 // bother issuing a general "something's different" diagnostic.
9696 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
9697 continue;
9699 bool Diagnosed = false;
9700 CXXRecordDecl *FirstRecord = Merge.first;
9701 for (auto &RecordPair : Merge.second) {
9702 if (DiagsEmitter.diagnoseMismatch(FirstRecord, RecordPair.first,
9703 RecordPair.second)) {
9704 Diagnosed = true;
9705 break;
9709 if (!Diagnosed) {
9710 // All definitions are updates to the same declaration. This happens if a
9711 // module instantiates the declaration of a class template specialization
9712 // and two or more other modules instantiate its definition.
9714 // FIXME: Indicate which modules had instantiations of this definition.
9715 // FIXME: How can this even happen?
9716 Diag(Merge.first->getLocation(),
9717 diag::err_module_odr_violation_different_instantiations)
9718 << Merge.first;
9722 // Issue any pending ODR-failure diagnostics for RecordDecl in C/ObjC. Note
9723 // that in C++ this is done as a part of CXXRecordDecl ODR checking.
9724 for (auto &Merge : RecordOdrMergeFailures) {
9725 // If we've already pointed out a specific problem with this class, don't
9726 // bother issuing a general "something's different" diagnostic.
9727 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
9728 continue;
9730 RecordDecl *FirstRecord = Merge.first;
9731 bool Diagnosed = false;
9732 for (auto *SecondRecord : Merge.second) {
9733 if (DiagsEmitter.diagnoseMismatch(FirstRecord, SecondRecord)) {
9734 Diagnosed = true;
9735 break;
9738 (void)Diagnosed;
9739 assert(Diagnosed && "Unable to emit ODR diagnostic.");
9742 // Issue ODR failures diagnostics for functions.
9743 for (auto &Merge : FunctionOdrMergeFailures) {
9744 FunctionDecl *FirstFunction = Merge.first;
9745 bool Diagnosed = false;
9746 for (auto &SecondFunction : Merge.second) {
9747 if (DiagsEmitter.diagnoseMismatch(FirstFunction, SecondFunction)) {
9748 Diagnosed = true;
9749 break;
9752 (void)Diagnosed;
9753 assert(Diagnosed && "Unable to emit ODR diagnostic.");
9756 // Issue ODR failures diagnostics for enums.
9757 for (auto &Merge : EnumOdrMergeFailures) {
9758 // If we've already pointed out a specific problem with this enum, don't
9759 // bother issuing a general "something's different" diagnostic.
9760 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
9761 continue;
9763 EnumDecl *FirstEnum = Merge.first;
9764 bool Diagnosed = false;
9765 for (auto &SecondEnum : Merge.second) {
9766 if (DiagsEmitter.diagnoseMismatch(FirstEnum, SecondEnum)) {
9767 Diagnosed = true;
9768 break;
9771 (void)Diagnosed;
9772 assert(Diagnosed && "Unable to emit ODR diagnostic.");
9775 for (auto &Merge : ObjCInterfaceOdrMergeFailures) {
9776 // If we've already pointed out a specific problem with this interface,
9777 // don't bother issuing a general "something's different" diagnostic.
9778 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
9779 continue;
9781 bool Diagnosed = false;
9782 ObjCInterfaceDecl *FirstID = Merge.first;
9783 for (auto &InterfacePair : Merge.second) {
9784 if (DiagsEmitter.diagnoseMismatch(FirstID, InterfacePair.first,
9785 InterfacePair.second)) {
9786 Diagnosed = true;
9787 break;
9790 (void)Diagnosed;
9791 assert(Diagnosed && "Unable to emit ODR diagnostic.");
9794 for (auto &Merge : ObjCProtocolOdrMergeFailures) {
9795 // If we've already pointed out a specific problem with this protocol,
9796 // don't bother issuing a general "something's different" diagnostic.
9797 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
9798 continue;
9800 ObjCProtocolDecl *FirstProtocol = Merge.first;
9801 bool Diagnosed = false;
9802 for (auto &ProtocolPair : Merge.second) {
9803 if (DiagsEmitter.diagnoseMismatch(FirstProtocol, ProtocolPair.first,
9804 ProtocolPair.second)) {
9805 Diagnosed = true;
9806 break;
9809 (void)Diagnosed;
9810 assert(Diagnosed && "Unable to emit ODR diagnostic.");
9814 void ASTReader::StartedDeserializing() {
9815 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
9816 ReadTimer->startTimer();
9819 void ASTReader::FinishedDeserializing() {
9820 assert(NumCurrentElementsDeserializing &&
9821 "FinishedDeserializing not paired with StartedDeserializing");
9822 if (NumCurrentElementsDeserializing == 1) {
9823 // We decrease NumCurrentElementsDeserializing only after pending actions
9824 // are finished, to avoid recursively re-calling finishPendingActions().
9825 finishPendingActions();
9827 --NumCurrentElementsDeserializing;
9829 if (NumCurrentElementsDeserializing == 0) {
9830 // Propagate exception specification and deduced type updates along
9831 // redeclaration chains.
9833 // We do this now rather than in finishPendingActions because we want to
9834 // be able to walk the complete redeclaration chains of the updated decls.
9835 while (!PendingExceptionSpecUpdates.empty() ||
9836 !PendingDeducedTypeUpdates.empty()) {
9837 auto ESUpdates = std::move(PendingExceptionSpecUpdates);
9838 PendingExceptionSpecUpdates.clear();
9839 for (auto Update : ESUpdates) {
9840 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
9841 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
9842 auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
9843 if (auto *Listener = getContext().getASTMutationListener())
9844 Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
9845 for (auto *Redecl : Update.second->redecls())
9846 getContext().adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
9849 auto DTUpdates = std::move(PendingDeducedTypeUpdates);
9850 PendingDeducedTypeUpdates.clear();
9851 for (auto Update : DTUpdates) {
9852 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
9853 // FIXME: If the return type is already deduced, check that it matches.
9854 getContext().adjustDeducedFunctionResultType(Update.first,
9855 Update.second);
9859 if (ReadTimer)
9860 ReadTimer->stopTimer();
9862 diagnoseOdrViolations();
9864 // We are not in recursive loading, so it's safe to pass the "interesting"
9865 // decls to the consumer.
9866 if (Consumer)
9867 PassInterestingDeclsToConsumer();
9871 void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
9872 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
9873 // Remove any fake results before adding any real ones.
9874 auto It = PendingFakeLookupResults.find(II);
9875 if (It != PendingFakeLookupResults.end()) {
9876 for (auto *ND : It->second)
9877 SemaObj->IdResolver.RemoveDecl(ND);
9878 // FIXME: this works around module+PCH performance issue.
9879 // Rather than erase the result from the map, which is O(n), just clear
9880 // the vector of NamedDecls.
9881 It->second.clear();
9885 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
9886 SemaObj->TUScope->AddDecl(D);
9887 } else if (SemaObj->TUScope) {
9888 // Adding the decl to IdResolver may have failed because it was already in
9889 // (even though it was not added in scope). If it is already in, make sure
9890 // it gets in the scope as well.
9891 if (std::find(SemaObj->IdResolver.begin(Name),
9892 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
9893 SemaObj->TUScope->AddDecl(D);
9897 ASTReader::ASTReader(Preprocessor &PP, InMemoryModuleCache &ModuleCache,
9898 ASTContext *Context,
9899 const PCHContainerReader &PCHContainerRdr,
9900 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
9901 StringRef isysroot,
9902 DisableValidationForModuleKind DisableValidationKind,
9903 bool AllowASTWithCompilerErrors,
9904 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
9905 bool ValidateASTInputFilesContent, bool UseGlobalIndex,
9906 std::unique_ptr<llvm::Timer> ReadTimer)
9907 : Listener(bool(DisableValidationKind &DisableValidationForModuleKind::PCH)
9908 ? cast<ASTReaderListener>(new SimpleASTReaderListener(PP))
9909 : cast<ASTReaderListener>(new PCHValidator(PP, *this))),
9910 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
9911 PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()), PP(PP),
9912 ContextObj(Context), ModuleMgr(PP.getFileManager(), ModuleCache,
9913 PCHContainerRdr, PP.getHeaderSearchInfo()),
9914 DummyIdResolver(PP), ReadTimer(std::move(ReadTimer)), isysroot(isysroot),
9915 DisableValidationKind(DisableValidationKind),
9916 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
9917 AllowConfigurationMismatch(AllowConfigurationMismatch),
9918 ValidateSystemInputs(ValidateSystemInputs),
9919 ValidateASTInputFilesContent(ValidateASTInputFilesContent),
9920 UseGlobalIndex(UseGlobalIndex), CurrSwitchCaseStmts(&SwitchCaseStmts) {
9921 SourceMgr.setExternalSLocEntrySource(this);
9923 for (const auto &Ext : Extensions) {
9924 auto BlockName = Ext->getExtensionMetadata().BlockName;
9925 auto Known = ModuleFileExtensions.find(BlockName);
9926 if (Known != ModuleFileExtensions.end()) {
9927 Diags.Report(diag::warn_duplicate_module_file_extension)
9928 << BlockName;
9929 continue;
9932 ModuleFileExtensions.insert({BlockName, Ext});
9936 ASTReader::~ASTReader() {
9937 if (OwnsDeserializationListener)
9938 delete DeserializationListener;
9941 IdentifierResolver &ASTReader::getIdResolver() {
9942 return SemaObj ? SemaObj->IdResolver : DummyIdResolver;
9945 Expected<unsigned> ASTRecordReader::readRecord(llvm::BitstreamCursor &Cursor,
9946 unsigned AbbrevID) {
9947 Idx = 0;
9948 Record.clear();
9949 return Cursor.readRecord(AbbrevID, Record);
9951 //===----------------------------------------------------------------------===//
9952 //// OMPClauseReader implementation
9953 ////===----------------------------------------------------------------------===//
9955 // This has to be in namespace clang because it's friended by all
9956 // of the OMP clauses.
9957 namespace clang {
9959 class OMPClauseReader : public OMPClauseVisitor<OMPClauseReader> {
9960 ASTRecordReader &Record;
9961 ASTContext &Context;
9963 public:
9964 OMPClauseReader(ASTRecordReader &Record)
9965 : Record(Record), Context(Record.getContext()) {}
9966 #define GEN_CLANG_CLAUSE_CLASS
9967 #define CLAUSE_CLASS(Enum, Str, Class) void Visit##Class(Class *C);
9968 #include "llvm/Frontend/OpenMP/OMP.inc"
9969 OMPClause *readClause();
9970 void VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C);
9971 void VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C);
9974 } // end namespace clang
9976 OMPClause *ASTRecordReader::readOMPClause() {
9977 return OMPClauseReader(*this).readClause();
9980 OMPClause *OMPClauseReader::readClause() {
9981 OMPClause *C = nullptr;
9982 switch (llvm::omp::Clause(Record.readInt())) {
9983 case llvm::omp::OMPC_if:
9984 C = new (Context) OMPIfClause();
9985 break;
9986 case llvm::omp::OMPC_final:
9987 C = new (Context) OMPFinalClause();
9988 break;
9989 case llvm::omp::OMPC_num_threads:
9990 C = new (Context) OMPNumThreadsClause();
9991 break;
9992 case llvm::omp::OMPC_safelen:
9993 C = new (Context) OMPSafelenClause();
9994 break;
9995 case llvm::omp::OMPC_simdlen:
9996 C = new (Context) OMPSimdlenClause();
9997 break;
9998 case llvm::omp::OMPC_sizes: {
9999 unsigned NumSizes = Record.readInt();
10000 C = OMPSizesClause::CreateEmpty(Context, NumSizes);
10001 break;
10003 case llvm::omp::OMPC_full:
10004 C = OMPFullClause::CreateEmpty(Context);
10005 break;
10006 case llvm::omp::OMPC_partial:
10007 C = OMPPartialClause::CreateEmpty(Context);
10008 break;
10009 case llvm::omp::OMPC_allocator:
10010 C = new (Context) OMPAllocatorClause();
10011 break;
10012 case llvm::omp::OMPC_collapse:
10013 C = new (Context) OMPCollapseClause();
10014 break;
10015 case llvm::omp::OMPC_default:
10016 C = new (Context) OMPDefaultClause();
10017 break;
10018 case llvm::omp::OMPC_proc_bind:
10019 C = new (Context) OMPProcBindClause();
10020 break;
10021 case llvm::omp::OMPC_schedule:
10022 C = new (Context) OMPScheduleClause();
10023 break;
10024 case llvm::omp::OMPC_ordered:
10025 C = OMPOrderedClause::CreateEmpty(Context, Record.readInt());
10026 break;
10027 case llvm::omp::OMPC_nowait:
10028 C = new (Context) OMPNowaitClause();
10029 break;
10030 case llvm::omp::OMPC_untied:
10031 C = new (Context) OMPUntiedClause();
10032 break;
10033 case llvm::omp::OMPC_mergeable:
10034 C = new (Context) OMPMergeableClause();
10035 break;
10036 case llvm::omp::OMPC_read:
10037 C = new (Context) OMPReadClause();
10038 break;
10039 case llvm::omp::OMPC_write:
10040 C = new (Context) OMPWriteClause();
10041 break;
10042 case llvm::omp::OMPC_update:
10043 C = OMPUpdateClause::CreateEmpty(Context, Record.readInt());
10044 break;
10045 case llvm::omp::OMPC_capture:
10046 C = new (Context) OMPCaptureClause();
10047 break;
10048 case llvm::omp::OMPC_compare:
10049 C = new (Context) OMPCompareClause();
10050 break;
10051 case llvm::omp::OMPC_seq_cst:
10052 C = new (Context) OMPSeqCstClause();
10053 break;
10054 case llvm::omp::OMPC_acq_rel:
10055 C = new (Context) OMPAcqRelClause();
10056 break;
10057 case llvm::omp::OMPC_acquire:
10058 C = new (Context) OMPAcquireClause();
10059 break;
10060 case llvm::omp::OMPC_release:
10061 C = new (Context) OMPReleaseClause();
10062 break;
10063 case llvm::omp::OMPC_relaxed:
10064 C = new (Context) OMPRelaxedClause();
10065 break;
10066 case llvm::omp::OMPC_threads:
10067 C = new (Context) OMPThreadsClause();
10068 break;
10069 case llvm::omp::OMPC_simd:
10070 C = new (Context) OMPSIMDClause();
10071 break;
10072 case llvm::omp::OMPC_nogroup:
10073 C = new (Context) OMPNogroupClause();
10074 break;
10075 case llvm::omp::OMPC_unified_address:
10076 C = new (Context) OMPUnifiedAddressClause();
10077 break;
10078 case llvm::omp::OMPC_unified_shared_memory:
10079 C = new (Context) OMPUnifiedSharedMemoryClause();
10080 break;
10081 case llvm::omp::OMPC_reverse_offload:
10082 C = new (Context) OMPReverseOffloadClause();
10083 break;
10084 case llvm::omp::OMPC_dynamic_allocators:
10085 C = new (Context) OMPDynamicAllocatorsClause();
10086 break;
10087 case llvm::omp::OMPC_atomic_default_mem_order:
10088 C = new (Context) OMPAtomicDefaultMemOrderClause();
10089 break;
10090 case llvm::omp::OMPC_at:
10091 C = new (Context) OMPAtClause();
10092 break;
10093 case llvm::omp::OMPC_severity:
10094 C = new (Context) OMPSeverityClause();
10095 break;
10096 case llvm::omp::OMPC_message:
10097 C = new (Context) OMPMessageClause();
10098 break;
10099 case llvm::omp::OMPC_private:
10100 C = OMPPrivateClause::CreateEmpty(Context, Record.readInt());
10101 break;
10102 case llvm::omp::OMPC_firstprivate:
10103 C = OMPFirstprivateClause::CreateEmpty(Context, Record.readInt());
10104 break;
10105 case llvm::omp::OMPC_lastprivate:
10106 C = OMPLastprivateClause::CreateEmpty(Context, Record.readInt());
10107 break;
10108 case llvm::omp::OMPC_shared:
10109 C = OMPSharedClause::CreateEmpty(Context, Record.readInt());
10110 break;
10111 case llvm::omp::OMPC_reduction: {
10112 unsigned N = Record.readInt();
10113 auto Modifier = Record.readEnum<OpenMPReductionClauseModifier>();
10114 C = OMPReductionClause::CreateEmpty(Context, N, Modifier);
10115 break;
10117 case llvm::omp::OMPC_task_reduction:
10118 C = OMPTaskReductionClause::CreateEmpty(Context, Record.readInt());
10119 break;
10120 case llvm::omp::OMPC_in_reduction:
10121 C = OMPInReductionClause::CreateEmpty(Context, Record.readInt());
10122 break;
10123 case llvm::omp::OMPC_linear:
10124 C = OMPLinearClause::CreateEmpty(Context, Record.readInt());
10125 break;
10126 case llvm::omp::OMPC_aligned:
10127 C = OMPAlignedClause::CreateEmpty(Context, Record.readInt());
10128 break;
10129 case llvm::omp::OMPC_copyin:
10130 C = OMPCopyinClause::CreateEmpty(Context, Record.readInt());
10131 break;
10132 case llvm::omp::OMPC_copyprivate:
10133 C = OMPCopyprivateClause::CreateEmpty(Context, Record.readInt());
10134 break;
10135 case llvm::omp::OMPC_flush:
10136 C = OMPFlushClause::CreateEmpty(Context, Record.readInt());
10137 break;
10138 case llvm::omp::OMPC_depobj:
10139 C = OMPDepobjClause::CreateEmpty(Context);
10140 break;
10141 case llvm::omp::OMPC_depend: {
10142 unsigned NumVars = Record.readInt();
10143 unsigned NumLoops = Record.readInt();
10144 C = OMPDependClause::CreateEmpty(Context, NumVars, NumLoops);
10145 break;
10147 case llvm::omp::OMPC_device:
10148 C = new (Context) OMPDeviceClause();
10149 break;
10150 case llvm::omp::OMPC_map: {
10151 OMPMappableExprListSizeTy Sizes;
10152 Sizes.NumVars = Record.readInt();
10153 Sizes.NumUniqueDeclarations = Record.readInt();
10154 Sizes.NumComponentLists = Record.readInt();
10155 Sizes.NumComponents = Record.readInt();
10156 C = OMPMapClause::CreateEmpty(Context, Sizes);
10157 break;
10159 case llvm::omp::OMPC_num_teams:
10160 C = new (Context) OMPNumTeamsClause();
10161 break;
10162 case llvm::omp::OMPC_thread_limit:
10163 C = new (Context) OMPThreadLimitClause();
10164 break;
10165 case llvm::omp::OMPC_priority:
10166 C = new (Context) OMPPriorityClause();
10167 break;
10168 case llvm::omp::OMPC_grainsize:
10169 C = new (Context) OMPGrainsizeClause();
10170 break;
10171 case llvm::omp::OMPC_num_tasks:
10172 C = new (Context) OMPNumTasksClause();
10173 break;
10174 case llvm::omp::OMPC_hint:
10175 C = new (Context) OMPHintClause();
10176 break;
10177 case llvm::omp::OMPC_dist_schedule:
10178 C = new (Context) OMPDistScheduleClause();
10179 break;
10180 case llvm::omp::OMPC_defaultmap:
10181 C = new (Context) OMPDefaultmapClause();
10182 break;
10183 case llvm::omp::OMPC_to: {
10184 OMPMappableExprListSizeTy Sizes;
10185 Sizes.NumVars = Record.readInt();
10186 Sizes.NumUniqueDeclarations = Record.readInt();
10187 Sizes.NumComponentLists = Record.readInt();
10188 Sizes.NumComponents = Record.readInt();
10189 C = OMPToClause::CreateEmpty(Context, Sizes);
10190 break;
10192 case llvm::omp::OMPC_from: {
10193 OMPMappableExprListSizeTy Sizes;
10194 Sizes.NumVars = Record.readInt();
10195 Sizes.NumUniqueDeclarations = Record.readInt();
10196 Sizes.NumComponentLists = Record.readInt();
10197 Sizes.NumComponents = Record.readInt();
10198 C = OMPFromClause::CreateEmpty(Context, Sizes);
10199 break;
10201 case llvm::omp::OMPC_use_device_ptr: {
10202 OMPMappableExprListSizeTy Sizes;
10203 Sizes.NumVars = Record.readInt();
10204 Sizes.NumUniqueDeclarations = Record.readInt();
10205 Sizes.NumComponentLists = Record.readInt();
10206 Sizes.NumComponents = Record.readInt();
10207 C = OMPUseDevicePtrClause::CreateEmpty(Context, Sizes);
10208 break;
10210 case llvm::omp::OMPC_use_device_addr: {
10211 OMPMappableExprListSizeTy Sizes;
10212 Sizes.NumVars = Record.readInt();
10213 Sizes.NumUniqueDeclarations = Record.readInt();
10214 Sizes.NumComponentLists = Record.readInt();
10215 Sizes.NumComponents = Record.readInt();
10216 C = OMPUseDeviceAddrClause::CreateEmpty(Context, Sizes);
10217 break;
10219 case llvm::omp::OMPC_is_device_ptr: {
10220 OMPMappableExprListSizeTy Sizes;
10221 Sizes.NumVars = Record.readInt();
10222 Sizes.NumUniqueDeclarations = Record.readInt();
10223 Sizes.NumComponentLists = Record.readInt();
10224 Sizes.NumComponents = Record.readInt();
10225 C = OMPIsDevicePtrClause::CreateEmpty(Context, Sizes);
10226 break;
10228 case llvm::omp::OMPC_has_device_addr: {
10229 OMPMappableExprListSizeTy Sizes;
10230 Sizes.NumVars = Record.readInt();
10231 Sizes.NumUniqueDeclarations = Record.readInt();
10232 Sizes.NumComponentLists = Record.readInt();
10233 Sizes.NumComponents = Record.readInt();
10234 C = OMPHasDeviceAddrClause::CreateEmpty(Context, Sizes);
10235 break;
10237 case llvm::omp::OMPC_allocate:
10238 C = OMPAllocateClause::CreateEmpty(Context, Record.readInt());
10239 break;
10240 case llvm::omp::OMPC_nontemporal:
10241 C = OMPNontemporalClause::CreateEmpty(Context, Record.readInt());
10242 break;
10243 case llvm::omp::OMPC_inclusive:
10244 C = OMPInclusiveClause::CreateEmpty(Context, Record.readInt());
10245 break;
10246 case llvm::omp::OMPC_exclusive:
10247 C = OMPExclusiveClause::CreateEmpty(Context, Record.readInt());
10248 break;
10249 case llvm::omp::OMPC_order:
10250 C = new (Context) OMPOrderClause();
10251 break;
10252 case llvm::omp::OMPC_init:
10253 C = OMPInitClause::CreateEmpty(Context, Record.readInt());
10254 break;
10255 case llvm::omp::OMPC_use:
10256 C = new (Context) OMPUseClause();
10257 break;
10258 case llvm::omp::OMPC_destroy:
10259 C = new (Context) OMPDestroyClause();
10260 break;
10261 case llvm::omp::OMPC_novariants:
10262 C = new (Context) OMPNovariantsClause();
10263 break;
10264 case llvm::omp::OMPC_nocontext:
10265 C = new (Context) OMPNocontextClause();
10266 break;
10267 case llvm::omp::OMPC_detach:
10268 C = new (Context) OMPDetachClause();
10269 break;
10270 case llvm::omp::OMPC_uses_allocators:
10271 C = OMPUsesAllocatorsClause::CreateEmpty(Context, Record.readInt());
10272 break;
10273 case llvm::omp::OMPC_affinity:
10274 C = OMPAffinityClause::CreateEmpty(Context, Record.readInt());
10275 break;
10276 case llvm::omp::OMPC_filter:
10277 C = new (Context) OMPFilterClause();
10278 break;
10279 case llvm::omp::OMPC_bind:
10280 C = OMPBindClause::CreateEmpty(Context);
10281 break;
10282 case llvm::omp::OMPC_align:
10283 C = new (Context) OMPAlignClause();
10284 break;
10285 case llvm::omp::OMPC_ompx_dyn_cgroup_mem:
10286 C = new (Context) OMPXDynCGroupMemClause();
10287 break;
10288 #define OMP_CLAUSE_NO_CLASS(Enum, Str) \
10289 case llvm::omp::Enum: \
10290 break;
10291 #include "llvm/Frontend/OpenMP/OMPKinds.def"
10292 default:
10293 break;
10295 assert(C && "Unknown OMPClause type");
10297 Visit(C);
10298 C->setLocStart(Record.readSourceLocation());
10299 C->setLocEnd(Record.readSourceLocation());
10301 return C;
10304 void OMPClauseReader::VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C) {
10305 C->setPreInitStmt(Record.readSubStmt(),
10306 static_cast<OpenMPDirectiveKind>(Record.readInt()));
10309 void OMPClauseReader::VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C) {
10310 VisitOMPClauseWithPreInit(C);
10311 C->setPostUpdateExpr(Record.readSubExpr());
10314 void OMPClauseReader::VisitOMPIfClause(OMPIfClause *C) {
10315 VisitOMPClauseWithPreInit(C);
10316 C->setNameModifier(static_cast<OpenMPDirectiveKind>(Record.readInt()));
10317 C->setNameModifierLoc(Record.readSourceLocation());
10318 C->setColonLoc(Record.readSourceLocation());
10319 C->setCondition(Record.readSubExpr());
10320 C->setLParenLoc(Record.readSourceLocation());
10323 void OMPClauseReader::VisitOMPFinalClause(OMPFinalClause *C) {
10324 VisitOMPClauseWithPreInit(C);
10325 C->setCondition(Record.readSubExpr());
10326 C->setLParenLoc(Record.readSourceLocation());
10329 void OMPClauseReader::VisitOMPNumThreadsClause(OMPNumThreadsClause *C) {
10330 VisitOMPClauseWithPreInit(C);
10331 C->setNumThreads(Record.readSubExpr());
10332 C->setLParenLoc(Record.readSourceLocation());
10335 void OMPClauseReader::VisitOMPSafelenClause(OMPSafelenClause *C) {
10336 C->setSafelen(Record.readSubExpr());
10337 C->setLParenLoc(Record.readSourceLocation());
10340 void OMPClauseReader::VisitOMPSimdlenClause(OMPSimdlenClause *C) {
10341 C->setSimdlen(Record.readSubExpr());
10342 C->setLParenLoc(Record.readSourceLocation());
10345 void OMPClauseReader::VisitOMPSizesClause(OMPSizesClause *C) {
10346 for (Expr *&E : C->getSizesRefs())
10347 E = Record.readSubExpr();
10348 C->setLParenLoc(Record.readSourceLocation());
10351 void OMPClauseReader::VisitOMPFullClause(OMPFullClause *C) {}
10353 void OMPClauseReader::VisitOMPPartialClause(OMPPartialClause *C) {
10354 C->setFactor(Record.readSubExpr());
10355 C->setLParenLoc(Record.readSourceLocation());
10358 void OMPClauseReader::VisitOMPAllocatorClause(OMPAllocatorClause *C) {
10359 C->setAllocator(Record.readExpr());
10360 C->setLParenLoc(Record.readSourceLocation());
10363 void OMPClauseReader::VisitOMPCollapseClause(OMPCollapseClause *C) {
10364 C->setNumForLoops(Record.readSubExpr());
10365 C->setLParenLoc(Record.readSourceLocation());
10368 void OMPClauseReader::VisitOMPDefaultClause(OMPDefaultClause *C) {
10369 C->setDefaultKind(static_cast<llvm::omp::DefaultKind>(Record.readInt()));
10370 C->setLParenLoc(Record.readSourceLocation());
10371 C->setDefaultKindKwLoc(Record.readSourceLocation());
10374 void OMPClauseReader::VisitOMPProcBindClause(OMPProcBindClause *C) {
10375 C->setProcBindKind(static_cast<llvm::omp::ProcBindKind>(Record.readInt()));
10376 C->setLParenLoc(Record.readSourceLocation());
10377 C->setProcBindKindKwLoc(Record.readSourceLocation());
10380 void OMPClauseReader::VisitOMPScheduleClause(OMPScheduleClause *C) {
10381 VisitOMPClauseWithPreInit(C);
10382 C->setScheduleKind(
10383 static_cast<OpenMPScheduleClauseKind>(Record.readInt()));
10384 C->setFirstScheduleModifier(
10385 static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
10386 C->setSecondScheduleModifier(
10387 static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
10388 C->setChunkSize(Record.readSubExpr());
10389 C->setLParenLoc(Record.readSourceLocation());
10390 C->setFirstScheduleModifierLoc(Record.readSourceLocation());
10391 C->setSecondScheduleModifierLoc(Record.readSourceLocation());
10392 C->setScheduleKindLoc(Record.readSourceLocation());
10393 C->setCommaLoc(Record.readSourceLocation());
10396 void OMPClauseReader::VisitOMPOrderedClause(OMPOrderedClause *C) {
10397 C->setNumForLoops(Record.readSubExpr());
10398 for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
10399 C->setLoopNumIterations(I, Record.readSubExpr());
10400 for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
10401 C->setLoopCounter(I, Record.readSubExpr());
10402 C->setLParenLoc(Record.readSourceLocation());
10405 void OMPClauseReader::VisitOMPDetachClause(OMPDetachClause *C) {
10406 C->setEventHandler(Record.readSubExpr());
10407 C->setLParenLoc(Record.readSourceLocation());
10410 void OMPClauseReader::VisitOMPNowaitClause(OMPNowaitClause *) {}
10412 void OMPClauseReader::VisitOMPUntiedClause(OMPUntiedClause *) {}
10414 void OMPClauseReader::VisitOMPMergeableClause(OMPMergeableClause *) {}
10416 void OMPClauseReader::VisitOMPReadClause(OMPReadClause *) {}
10418 void OMPClauseReader::VisitOMPWriteClause(OMPWriteClause *) {}
10420 void OMPClauseReader::VisitOMPUpdateClause(OMPUpdateClause *C) {
10421 if (C->isExtended()) {
10422 C->setLParenLoc(Record.readSourceLocation());
10423 C->setArgumentLoc(Record.readSourceLocation());
10424 C->setDependencyKind(Record.readEnum<OpenMPDependClauseKind>());
10428 void OMPClauseReader::VisitOMPCaptureClause(OMPCaptureClause *) {}
10430 void OMPClauseReader::VisitOMPCompareClause(OMPCompareClause *) {}
10432 void OMPClauseReader::VisitOMPSeqCstClause(OMPSeqCstClause *) {}
10434 void OMPClauseReader::VisitOMPAcqRelClause(OMPAcqRelClause *) {}
10436 void OMPClauseReader::VisitOMPAcquireClause(OMPAcquireClause *) {}
10438 void OMPClauseReader::VisitOMPReleaseClause(OMPReleaseClause *) {}
10440 void OMPClauseReader::VisitOMPRelaxedClause(OMPRelaxedClause *) {}
10442 void OMPClauseReader::VisitOMPThreadsClause(OMPThreadsClause *) {}
10444 void OMPClauseReader::VisitOMPSIMDClause(OMPSIMDClause *) {}
10446 void OMPClauseReader::VisitOMPNogroupClause(OMPNogroupClause *) {}
10448 void OMPClauseReader::VisitOMPInitClause(OMPInitClause *C) {
10449 unsigned NumVars = C->varlist_size();
10450 SmallVector<Expr *, 16> Vars;
10451 Vars.reserve(NumVars);
10452 for (unsigned I = 0; I != NumVars; ++I)
10453 Vars.push_back(Record.readSubExpr());
10454 C->setVarRefs(Vars);
10455 C->setIsTarget(Record.readBool());
10456 C->setIsTargetSync(Record.readBool());
10457 C->setLParenLoc(Record.readSourceLocation());
10458 C->setVarLoc(Record.readSourceLocation());
10461 void OMPClauseReader::VisitOMPUseClause(OMPUseClause *C) {
10462 C->setInteropVar(Record.readSubExpr());
10463 C->setLParenLoc(Record.readSourceLocation());
10464 C->setVarLoc(Record.readSourceLocation());
10467 void OMPClauseReader::VisitOMPDestroyClause(OMPDestroyClause *C) {
10468 C->setInteropVar(Record.readSubExpr());
10469 C->setLParenLoc(Record.readSourceLocation());
10470 C->setVarLoc(Record.readSourceLocation());
10473 void OMPClauseReader::VisitOMPNovariantsClause(OMPNovariantsClause *C) {
10474 VisitOMPClauseWithPreInit(C);
10475 C->setCondition(Record.readSubExpr());
10476 C->setLParenLoc(Record.readSourceLocation());
10479 void OMPClauseReader::VisitOMPNocontextClause(OMPNocontextClause *C) {
10480 VisitOMPClauseWithPreInit(C);
10481 C->setCondition(Record.readSubExpr());
10482 C->setLParenLoc(Record.readSourceLocation());
10485 void OMPClauseReader::VisitOMPUnifiedAddressClause(OMPUnifiedAddressClause *) {}
10487 void OMPClauseReader::VisitOMPUnifiedSharedMemoryClause(
10488 OMPUnifiedSharedMemoryClause *) {}
10490 void OMPClauseReader::VisitOMPReverseOffloadClause(OMPReverseOffloadClause *) {}
10492 void
10493 OMPClauseReader::VisitOMPDynamicAllocatorsClause(OMPDynamicAllocatorsClause *) {
10496 void OMPClauseReader::VisitOMPAtomicDefaultMemOrderClause(
10497 OMPAtomicDefaultMemOrderClause *C) {
10498 C->setAtomicDefaultMemOrderKind(
10499 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Record.readInt()));
10500 C->setLParenLoc(Record.readSourceLocation());
10501 C->setAtomicDefaultMemOrderKindKwLoc(Record.readSourceLocation());
10504 void OMPClauseReader::VisitOMPAtClause(OMPAtClause *C) {
10505 C->setAtKind(static_cast<OpenMPAtClauseKind>(Record.readInt()));
10506 C->setLParenLoc(Record.readSourceLocation());
10507 C->setAtKindKwLoc(Record.readSourceLocation());
10510 void OMPClauseReader::VisitOMPSeverityClause(OMPSeverityClause *C) {
10511 C->setSeverityKind(static_cast<OpenMPSeverityClauseKind>(Record.readInt()));
10512 C->setLParenLoc(Record.readSourceLocation());
10513 C->setSeverityKindKwLoc(Record.readSourceLocation());
10516 void OMPClauseReader::VisitOMPMessageClause(OMPMessageClause *C) {
10517 C->setMessageString(Record.readSubExpr());
10518 C->setLParenLoc(Record.readSourceLocation());
10521 void OMPClauseReader::VisitOMPPrivateClause(OMPPrivateClause *C) {
10522 C->setLParenLoc(Record.readSourceLocation());
10523 unsigned NumVars = C->varlist_size();
10524 SmallVector<Expr *, 16> Vars;
10525 Vars.reserve(NumVars);
10526 for (unsigned i = 0; i != NumVars; ++i)
10527 Vars.push_back(Record.readSubExpr());
10528 C->setVarRefs(Vars);
10529 Vars.clear();
10530 for (unsigned i = 0; i != NumVars; ++i)
10531 Vars.push_back(Record.readSubExpr());
10532 C->setPrivateCopies(Vars);
10535 void OMPClauseReader::VisitOMPFirstprivateClause(OMPFirstprivateClause *C) {
10536 VisitOMPClauseWithPreInit(C);
10537 C->setLParenLoc(Record.readSourceLocation());
10538 unsigned NumVars = C->varlist_size();
10539 SmallVector<Expr *, 16> Vars;
10540 Vars.reserve(NumVars);
10541 for (unsigned i = 0; i != NumVars; ++i)
10542 Vars.push_back(Record.readSubExpr());
10543 C->setVarRefs(Vars);
10544 Vars.clear();
10545 for (unsigned i = 0; i != NumVars; ++i)
10546 Vars.push_back(Record.readSubExpr());
10547 C->setPrivateCopies(Vars);
10548 Vars.clear();
10549 for (unsigned i = 0; i != NumVars; ++i)
10550 Vars.push_back(Record.readSubExpr());
10551 C->setInits(Vars);
10554 void OMPClauseReader::VisitOMPLastprivateClause(OMPLastprivateClause *C) {
10555 VisitOMPClauseWithPostUpdate(C);
10556 C->setLParenLoc(Record.readSourceLocation());
10557 C->setKind(Record.readEnum<OpenMPLastprivateModifier>());
10558 C->setKindLoc(Record.readSourceLocation());
10559 C->setColonLoc(Record.readSourceLocation());
10560 unsigned NumVars = C->varlist_size();
10561 SmallVector<Expr *, 16> Vars;
10562 Vars.reserve(NumVars);
10563 for (unsigned i = 0; i != NumVars; ++i)
10564 Vars.push_back(Record.readSubExpr());
10565 C->setVarRefs(Vars);
10566 Vars.clear();
10567 for (unsigned i = 0; i != NumVars; ++i)
10568 Vars.push_back(Record.readSubExpr());
10569 C->setPrivateCopies(Vars);
10570 Vars.clear();
10571 for (unsigned i = 0; i != NumVars; ++i)
10572 Vars.push_back(Record.readSubExpr());
10573 C->setSourceExprs(Vars);
10574 Vars.clear();
10575 for (unsigned i = 0; i != NumVars; ++i)
10576 Vars.push_back(Record.readSubExpr());
10577 C->setDestinationExprs(Vars);
10578 Vars.clear();
10579 for (unsigned i = 0; i != NumVars; ++i)
10580 Vars.push_back(Record.readSubExpr());
10581 C->setAssignmentOps(Vars);
10584 void OMPClauseReader::VisitOMPSharedClause(OMPSharedClause *C) {
10585 C->setLParenLoc(Record.readSourceLocation());
10586 unsigned NumVars = C->varlist_size();
10587 SmallVector<Expr *, 16> Vars;
10588 Vars.reserve(NumVars);
10589 for (unsigned i = 0; i != NumVars; ++i)
10590 Vars.push_back(Record.readSubExpr());
10591 C->setVarRefs(Vars);
10594 void OMPClauseReader::VisitOMPReductionClause(OMPReductionClause *C) {
10595 VisitOMPClauseWithPostUpdate(C);
10596 C->setLParenLoc(Record.readSourceLocation());
10597 C->setModifierLoc(Record.readSourceLocation());
10598 C->setColonLoc(Record.readSourceLocation());
10599 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
10600 DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
10601 C->setQualifierLoc(NNSL);
10602 C->setNameInfo(DNI);
10604 unsigned NumVars = C->varlist_size();
10605 SmallVector<Expr *, 16> Vars;
10606 Vars.reserve(NumVars);
10607 for (unsigned i = 0; i != NumVars; ++i)
10608 Vars.push_back(Record.readSubExpr());
10609 C->setVarRefs(Vars);
10610 Vars.clear();
10611 for (unsigned i = 0; i != NumVars; ++i)
10612 Vars.push_back(Record.readSubExpr());
10613 C->setPrivates(Vars);
10614 Vars.clear();
10615 for (unsigned i = 0; i != NumVars; ++i)
10616 Vars.push_back(Record.readSubExpr());
10617 C->setLHSExprs(Vars);
10618 Vars.clear();
10619 for (unsigned i = 0; i != NumVars; ++i)
10620 Vars.push_back(Record.readSubExpr());
10621 C->setRHSExprs(Vars);
10622 Vars.clear();
10623 for (unsigned i = 0; i != NumVars; ++i)
10624 Vars.push_back(Record.readSubExpr());
10625 C->setReductionOps(Vars);
10626 if (C->getModifier() == OMPC_REDUCTION_inscan) {
10627 Vars.clear();
10628 for (unsigned i = 0; i != NumVars; ++i)
10629 Vars.push_back(Record.readSubExpr());
10630 C->setInscanCopyOps(Vars);
10631 Vars.clear();
10632 for (unsigned i = 0; i != NumVars; ++i)
10633 Vars.push_back(Record.readSubExpr());
10634 C->setInscanCopyArrayTemps(Vars);
10635 Vars.clear();
10636 for (unsigned i = 0; i != NumVars; ++i)
10637 Vars.push_back(Record.readSubExpr());
10638 C->setInscanCopyArrayElems(Vars);
10642 void OMPClauseReader::VisitOMPTaskReductionClause(OMPTaskReductionClause *C) {
10643 VisitOMPClauseWithPostUpdate(C);
10644 C->setLParenLoc(Record.readSourceLocation());
10645 C->setColonLoc(Record.readSourceLocation());
10646 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
10647 DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
10648 C->setQualifierLoc(NNSL);
10649 C->setNameInfo(DNI);
10651 unsigned NumVars = C->varlist_size();
10652 SmallVector<Expr *, 16> Vars;
10653 Vars.reserve(NumVars);
10654 for (unsigned I = 0; I != NumVars; ++I)
10655 Vars.push_back(Record.readSubExpr());
10656 C->setVarRefs(Vars);
10657 Vars.clear();
10658 for (unsigned I = 0; I != NumVars; ++I)
10659 Vars.push_back(Record.readSubExpr());
10660 C->setPrivates(Vars);
10661 Vars.clear();
10662 for (unsigned I = 0; I != NumVars; ++I)
10663 Vars.push_back(Record.readSubExpr());
10664 C->setLHSExprs(Vars);
10665 Vars.clear();
10666 for (unsigned I = 0; I != NumVars; ++I)
10667 Vars.push_back(Record.readSubExpr());
10668 C->setRHSExprs(Vars);
10669 Vars.clear();
10670 for (unsigned I = 0; I != NumVars; ++I)
10671 Vars.push_back(Record.readSubExpr());
10672 C->setReductionOps(Vars);
10675 void OMPClauseReader::VisitOMPInReductionClause(OMPInReductionClause *C) {
10676 VisitOMPClauseWithPostUpdate(C);
10677 C->setLParenLoc(Record.readSourceLocation());
10678 C->setColonLoc(Record.readSourceLocation());
10679 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
10680 DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
10681 C->setQualifierLoc(NNSL);
10682 C->setNameInfo(DNI);
10684 unsigned NumVars = C->varlist_size();
10685 SmallVector<Expr *, 16> Vars;
10686 Vars.reserve(NumVars);
10687 for (unsigned I = 0; I != NumVars; ++I)
10688 Vars.push_back(Record.readSubExpr());
10689 C->setVarRefs(Vars);
10690 Vars.clear();
10691 for (unsigned I = 0; I != NumVars; ++I)
10692 Vars.push_back(Record.readSubExpr());
10693 C->setPrivates(Vars);
10694 Vars.clear();
10695 for (unsigned I = 0; I != NumVars; ++I)
10696 Vars.push_back(Record.readSubExpr());
10697 C->setLHSExprs(Vars);
10698 Vars.clear();
10699 for (unsigned I = 0; I != NumVars; ++I)
10700 Vars.push_back(Record.readSubExpr());
10701 C->setRHSExprs(Vars);
10702 Vars.clear();
10703 for (unsigned I = 0; I != NumVars; ++I)
10704 Vars.push_back(Record.readSubExpr());
10705 C->setReductionOps(Vars);
10706 Vars.clear();
10707 for (unsigned I = 0; I != NumVars; ++I)
10708 Vars.push_back(Record.readSubExpr());
10709 C->setTaskgroupDescriptors(Vars);
10712 void OMPClauseReader::VisitOMPLinearClause(OMPLinearClause *C) {
10713 VisitOMPClauseWithPostUpdate(C);
10714 C->setLParenLoc(Record.readSourceLocation());
10715 C->setColonLoc(Record.readSourceLocation());
10716 C->setModifier(static_cast<OpenMPLinearClauseKind>(Record.readInt()));
10717 C->setModifierLoc(Record.readSourceLocation());
10718 unsigned NumVars = C->varlist_size();
10719 SmallVector<Expr *, 16> Vars;
10720 Vars.reserve(NumVars);
10721 for (unsigned i = 0; i != NumVars; ++i)
10722 Vars.push_back(Record.readSubExpr());
10723 C->setVarRefs(Vars);
10724 Vars.clear();
10725 for (unsigned i = 0; i != NumVars; ++i)
10726 Vars.push_back(Record.readSubExpr());
10727 C->setPrivates(Vars);
10728 Vars.clear();
10729 for (unsigned i = 0; i != NumVars; ++i)
10730 Vars.push_back(Record.readSubExpr());
10731 C->setInits(Vars);
10732 Vars.clear();
10733 for (unsigned i = 0; i != NumVars; ++i)
10734 Vars.push_back(Record.readSubExpr());
10735 C->setUpdates(Vars);
10736 Vars.clear();
10737 for (unsigned i = 0; i != NumVars; ++i)
10738 Vars.push_back(Record.readSubExpr());
10739 C->setFinals(Vars);
10740 C->setStep(Record.readSubExpr());
10741 C->setCalcStep(Record.readSubExpr());
10742 Vars.clear();
10743 for (unsigned I = 0; I != NumVars + 1; ++I)
10744 Vars.push_back(Record.readSubExpr());
10745 C->setUsedExprs(Vars);
10748 void OMPClauseReader::VisitOMPAlignedClause(OMPAlignedClause *C) {
10749 C->setLParenLoc(Record.readSourceLocation());
10750 C->setColonLoc(Record.readSourceLocation());
10751 unsigned NumVars = C->varlist_size();
10752 SmallVector<Expr *, 16> Vars;
10753 Vars.reserve(NumVars);
10754 for (unsigned i = 0; i != NumVars; ++i)
10755 Vars.push_back(Record.readSubExpr());
10756 C->setVarRefs(Vars);
10757 C->setAlignment(Record.readSubExpr());
10760 void OMPClauseReader::VisitOMPCopyinClause(OMPCopyinClause *C) {
10761 C->setLParenLoc(Record.readSourceLocation());
10762 unsigned NumVars = C->varlist_size();
10763 SmallVector<Expr *, 16> Exprs;
10764 Exprs.reserve(NumVars);
10765 for (unsigned i = 0; i != NumVars; ++i)
10766 Exprs.push_back(Record.readSubExpr());
10767 C->setVarRefs(Exprs);
10768 Exprs.clear();
10769 for (unsigned i = 0; i != NumVars; ++i)
10770 Exprs.push_back(Record.readSubExpr());
10771 C->setSourceExprs(Exprs);
10772 Exprs.clear();
10773 for (unsigned i = 0; i != NumVars; ++i)
10774 Exprs.push_back(Record.readSubExpr());
10775 C->setDestinationExprs(Exprs);
10776 Exprs.clear();
10777 for (unsigned i = 0; i != NumVars; ++i)
10778 Exprs.push_back(Record.readSubExpr());
10779 C->setAssignmentOps(Exprs);
10782 void OMPClauseReader::VisitOMPCopyprivateClause(OMPCopyprivateClause *C) {
10783 C->setLParenLoc(Record.readSourceLocation());
10784 unsigned NumVars = C->varlist_size();
10785 SmallVector<Expr *, 16> Exprs;
10786 Exprs.reserve(NumVars);
10787 for (unsigned i = 0; i != NumVars; ++i)
10788 Exprs.push_back(Record.readSubExpr());
10789 C->setVarRefs(Exprs);
10790 Exprs.clear();
10791 for (unsigned i = 0; i != NumVars; ++i)
10792 Exprs.push_back(Record.readSubExpr());
10793 C->setSourceExprs(Exprs);
10794 Exprs.clear();
10795 for (unsigned i = 0; i != NumVars; ++i)
10796 Exprs.push_back(Record.readSubExpr());
10797 C->setDestinationExprs(Exprs);
10798 Exprs.clear();
10799 for (unsigned i = 0; i != NumVars; ++i)
10800 Exprs.push_back(Record.readSubExpr());
10801 C->setAssignmentOps(Exprs);
10804 void OMPClauseReader::VisitOMPFlushClause(OMPFlushClause *C) {
10805 C->setLParenLoc(Record.readSourceLocation());
10806 unsigned NumVars = C->varlist_size();
10807 SmallVector<Expr *, 16> Vars;
10808 Vars.reserve(NumVars);
10809 for (unsigned i = 0; i != NumVars; ++i)
10810 Vars.push_back(Record.readSubExpr());
10811 C->setVarRefs(Vars);
10814 void OMPClauseReader::VisitOMPDepobjClause(OMPDepobjClause *C) {
10815 C->setDepobj(Record.readSubExpr());
10816 C->setLParenLoc(Record.readSourceLocation());
10819 void OMPClauseReader::VisitOMPDependClause(OMPDependClause *C) {
10820 C->setLParenLoc(Record.readSourceLocation());
10821 C->setModifier(Record.readSubExpr());
10822 C->setDependencyKind(
10823 static_cast<OpenMPDependClauseKind>(Record.readInt()));
10824 C->setDependencyLoc(Record.readSourceLocation());
10825 C->setColonLoc(Record.readSourceLocation());
10826 C->setOmpAllMemoryLoc(Record.readSourceLocation());
10827 unsigned NumVars = C->varlist_size();
10828 SmallVector<Expr *, 16> Vars;
10829 Vars.reserve(NumVars);
10830 for (unsigned I = 0; I != NumVars; ++I)
10831 Vars.push_back(Record.readSubExpr());
10832 C->setVarRefs(Vars);
10833 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
10834 C->setLoopData(I, Record.readSubExpr());
10837 void OMPClauseReader::VisitOMPDeviceClause(OMPDeviceClause *C) {
10838 VisitOMPClauseWithPreInit(C);
10839 C->setModifier(Record.readEnum<OpenMPDeviceClauseModifier>());
10840 C->setDevice(Record.readSubExpr());
10841 C->setModifierLoc(Record.readSourceLocation());
10842 C->setLParenLoc(Record.readSourceLocation());
10845 void OMPClauseReader::VisitOMPMapClause(OMPMapClause *C) {
10846 C->setLParenLoc(Record.readSourceLocation());
10847 bool HasIteratorModifier = false;
10848 for (unsigned I = 0; I < NumberOfOMPMapClauseModifiers; ++I) {
10849 C->setMapTypeModifier(
10850 I, static_cast<OpenMPMapModifierKind>(Record.readInt()));
10851 C->setMapTypeModifierLoc(I, Record.readSourceLocation());
10852 if (C->getMapTypeModifier(I) == OMPC_MAP_MODIFIER_iterator)
10853 HasIteratorModifier = true;
10855 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
10856 C->setMapperIdInfo(Record.readDeclarationNameInfo());
10857 C->setMapType(
10858 static_cast<OpenMPMapClauseKind>(Record.readInt()));
10859 C->setMapLoc(Record.readSourceLocation());
10860 C->setColonLoc(Record.readSourceLocation());
10861 auto NumVars = C->varlist_size();
10862 auto UniqueDecls = C->getUniqueDeclarationsNum();
10863 auto TotalLists = C->getTotalComponentListNum();
10864 auto TotalComponents = C->getTotalComponentsNum();
10866 SmallVector<Expr *, 16> Vars;
10867 Vars.reserve(NumVars);
10868 for (unsigned i = 0; i != NumVars; ++i)
10869 Vars.push_back(Record.readExpr());
10870 C->setVarRefs(Vars);
10872 SmallVector<Expr *, 16> UDMappers;
10873 UDMappers.reserve(NumVars);
10874 for (unsigned I = 0; I < NumVars; ++I)
10875 UDMappers.push_back(Record.readExpr());
10876 C->setUDMapperRefs(UDMappers);
10878 if (HasIteratorModifier)
10879 C->setIteratorModifier(Record.readExpr());
10881 SmallVector<ValueDecl *, 16> Decls;
10882 Decls.reserve(UniqueDecls);
10883 for (unsigned i = 0; i < UniqueDecls; ++i)
10884 Decls.push_back(Record.readDeclAs<ValueDecl>());
10885 C->setUniqueDecls(Decls);
10887 SmallVector<unsigned, 16> ListsPerDecl;
10888 ListsPerDecl.reserve(UniqueDecls);
10889 for (unsigned i = 0; i < UniqueDecls; ++i)
10890 ListsPerDecl.push_back(Record.readInt());
10891 C->setDeclNumLists(ListsPerDecl);
10893 SmallVector<unsigned, 32> ListSizes;
10894 ListSizes.reserve(TotalLists);
10895 for (unsigned i = 0; i < TotalLists; ++i)
10896 ListSizes.push_back(Record.readInt());
10897 C->setComponentListSizes(ListSizes);
10899 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
10900 Components.reserve(TotalComponents);
10901 for (unsigned i = 0; i < TotalComponents; ++i) {
10902 Expr *AssociatedExprPr = Record.readExpr();
10903 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
10904 Components.emplace_back(AssociatedExprPr, AssociatedDecl,
10905 /*IsNonContiguous=*/false);
10907 C->setComponents(Components, ListSizes);
10910 void OMPClauseReader::VisitOMPAllocateClause(OMPAllocateClause *C) {
10911 C->setLParenLoc(Record.readSourceLocation());
10912 C->setColonLoc(Record.readSourceLocation());
10913 C->setAllocator(Record.readSubExpr());
10914 unsigned NumVars = C->varlist_size();
10915 SmallVector<Expr *, 16> Vars;
10916 Vars.reserve(NumVars);
10917 for (unsigned i = 0; i != NumVars; ++i)
10918 Vars.push_back(Record.readSubExpr());
10919 C->setVarRefs(Vars);
10922 void OMPClauseReader::VisitOMPNumTeamsClause(OMPNumTeamsClause *C) {
10923 VisitOMPClauseWithPreInit(C);
10924 C->setNumTeams(Record.readSubExpr());
10925 C->setLParenLoc(Record.readSourceLocation());
10928 void OMPClauseReader::VisitOMPThreadLimitClause(OMPThreadLimitClause *C) {
10929 VisitOMPClauseWithPreInit(C);
10930 C->setThreadLimit(Record.readSubExpr());
10931 C->setLParenLoc(Record.readSourceLocation());
10934 void OMPClauseReader::VisitOMPPriorityClause(OMPPriorityClause *C) {
10935 VisitOMPClauseWithPreInit(C);
10936 C->setPriority(Record.readSubExpr());
10937 C->setLParenLoc(Record.readSourceLocation());
10940 void OMPClauseReader::VisitOMPGrainsizeClause(OMPGrainsizeClause *C) {
10941 VisitOMPClauseWithPreInit(C);
10942 C->setModifier(Record.readEnum<OpenMPGrainsizeClauseModifier>());
10943 C->setGrainsize(Record.readSubExpr());
10944 C->setModifierLoc(Record.readSourceLocation());
10945 C->setLParenLoc(Record.readSourceLocation());
10948 void OMPClauseReader::VisitOMPNumTasksClause(OMPNumTasksClause *C) {
10949 VisitOMPClauseWithPreInit(C);
10950 C->setModifier(Record.readEnum<OpenMPNumTasksClauseModifier>());
10951 C->setNumTasks(Record.readSubExpr());
10952 C->setModifierLoc(Record.readSourceLocation());
10953 C->setLParenLoc(Record.readSourceLocation());
10956 void OMPClauseReader::VisitOMPHintClause(OMPHintClause *C) {
10957 C->setHint(Record.readSubExpr());
10958 C->setLParenLoc(Record.readSourceLocation());
10961 void OMPClauseReader::VisitOMPDistScheduleClause(OMPDistScheduleClause *C) {
10962 VisitOMPClauseWithPreInit(C);
10963 C->setDistScheduleKind(
10964 static_cast<OpenMPDistScheduleClauseKind>(Record.readInt()));
10965 C->setChunkSize(Record.readSubExpr());
10966 C->setLParenLoc(Record.readSourceLocation());
10967 C->setDistScheduleKindLoc(Record.readSourceLocation());
10968 C->setCommaLoc(Record.readSourceLocation());
10971 void OMPClauseReader::VisitOMPDefaultmapClause(OMPDefaultmapClause *C) {
10972 C->setDefaultmapKind(
10973 static_cast<OpenMPDefaultmapClauseKind>(Record.readInt()));
10974 C->setDefaultmapModifier(
10975 static_cast<OpenMPDefaultmapClauseModifier>(Record.readInt()));
10976 C->setLParenLoc(Record.readSourceLocation());
10977 C->setDefaultmapModifierLoc(Record.readSourceLocation());
10978 C->setDefaultmapKindLoc(Record.readSourceLocation());
10981 void OMPClauseReader::VisitOMPToClause(OMPToClause *C) {
10982 C->setLParenLoc(Record.readSourceLocation());
10983 for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) {
10984 C->setMotionModifier(
10985 I, static_cast<OpenMPMotionModifierKind>(Record.readInt()));
10986 C->setMotionModifierLoc(I, Record.readSourceLocation());
10988 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
10989 C->setMapperIdInfo(Record.readDeclarationNameInfo());
10990 C->setColonLoc(Record.readSourceLocation());
10991 auto NumVars = C->varlist_size();
10992 auto UniqueDecls = C->getUniqueDeclarationsNum();
10993 auto TotalLists = C->getTotalComponentListNum();
10994 auto TotalComponents = C->getTotalComponentsNum();
10996 SmallVector<Expr *, 16> Vars;
10997 Vars.reserve(NumVars);
10998 for (unsigned i = 0; i != NumVars; ++i)
10999 Vars.push_back(Record.readSubExpr());
11000 C->setVarRefs(Vars);
11002 SmallVector<Expr *, 16> UDMappers;
11003 UDMappers.reserve(NumVars);
11004 for (unsigned I = 0; I < NumVars; ++I)
11005 UDMappers.push_back(Record.readSubExpr());
11006 C->setUDMapperRefs(UDMappers);
11008 SmallVector<ValueDecl *, 16> Decls;
11009 Decls.reserve(UniqueDecls);
11010 for (unsigned i = 0; i < UniqueDecls; ++i)
11011 Decls.push_back(Record.readDeclAs<ValueDecl>());
11012 C->setUniqueDecls(Decls);
11014 SmallVector<unsigned, 16> ListsPerDecl;
11015 ListsPerDecl.reserve(UniqueDecls);
11016 for (unsigned i = 0; i < UniqueDecls; ++i)
11017 ListsPerDecl.push_back(Record.readInt());
11018 C->setDeclNumLists(ListsPerDecl);
11020 SmallVector<unsigned, 32> ListSizes;
11021 ListSizes.reserve(TotalLists);
11022 for (unsigned i = 0; i < TotalLists; ++i)
11023 ListSizes.push_back(Record.readInt());
11024 C->setComponentListSizes(ListSizes);
11026 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
11027 Components.reserve(TotalComponents);
11028 for (unsigned i = 0; i < TotalComponents; ++i) {
11029 Expr *AssociatedExprPr = Record.readSubExpr();
11030 bool IsNonContiguous = Record.readBool();
11031 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
11032 Components.emplace_back(AssociatedExprPr, AssociatedDecl, IsNonContiguous);
11034 C->setComponents(Components, ListSizes);
11037 void OMPClauseReader::VisitOMPFromClause(OMPFromClause *C) {
11038 C->setLParenLoc(Record.readSourceLocation());
11039 for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) {
11040 C->setMotionModifier(
11041 I, static_cast<OpenMPMotionModifierKind>(Record.readInt()));
11042 C->setMotionModifierLoc(I, Record.readSourceLocation());
11044 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
11045 C->setMapperIdInfo(Record.readDeclarationNameInfo());
11046 C->setColonLoc(Record.readSourceLocation());
11047 auto NumVars = C->varlist_size();
11048 auto UniqueDecls = C->getUniqueDeclarationsNum();
11049 auto TotalLists = C->getTotalComponentListNum();
11050 auto TotalComponents = C->getTotalComponentsNum();
11052 SmallVector<Expr *, 16> Vars;
11053 Vars.reserve(NumVars);
11054 for (unsigned i = 0; i != NumVars; ++i)
11055 Vars.push_back(Record.readSubExpr());
11056 C->setVarRefs(Vars);
11058 SmallVector<Expr *, 16> UDMappers;
11059 UDMappers.reserve(NumVars);
11060 for (unsigned I = 0; I < NumVars; ++I)
11061 UDMappers.push_back(Record.readSubExpr());
11062 C->setUDMapperRefs(UDMappers);
11064 SmallVector<ValueDecl *, 16> Decls;
11065 Decls.reserve(UniqueDecls);
11066 for (unsigned i = 0; i < UniqueDecls; ++i)
11067 Decls.push_back(Record.readDeclAs<ValueDecl>());
11068 C->setUniqueDecls(Decls);
11070 SmallVector<unsigned, 16> ListsPerDecl;
11071 ListsPerDecl.reserve(UniqueDecls);
11072 for (unsigned i = 0; i < UniqueDecls; ++i)
11073 ListsPerDecl.push_back(Record.readInt());
11074 C->setDeclNumLists(ListsPerDecl);
11076 SmallVector<unsigned, 32> ListSizes;
11077 ListSizes.reserve(TotalLists);
11078 for (unsigned i = 0; i < TotalLists; ++i)
11079 ListSizes.push_back(Record.readInt());
11080 C->setComponentListSizes(ListSizes);
11082 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
11083 Components.reserve(TotalComponents);
11084 for (unsigned i = 0; i < TotalComponents; ++i) {
11085 Expr *AssociatedExprPr = Record.readSubExpr();
11086 bool IsNonContiguous = Record.readBool();
11087 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
11088 Components.emplace_back(AssociatedExprPr, AssociatedDecl, IsNonContiguous);
11090 C->setComponents(Components, ListSizes);
11093 void OMPClauseReader::VisitOMPUseDevicePtrClause(OMPUseDevicePtrClause *C) {
11094 C->setLParenLoc(Record.readSourceLocation());
11095 auto NumVars = C->varlist_size();
11096 auto UniqueDecls = C->getUniqueDeclarationsNum();
11097 auto TotalLists = C->getTotalComponentListNum();
11098 auto TotalComponents = C->getTotalComponentsNum();
11100 SmallVector<Expr *, 16> Vars;
11101 Vars.reserve(NumVars);
11102 for (unsigned i = 0; i != NumVars; ++i)
11103 Vars.push_back(Record.readSubExpr());
11104 C->setVarRefs(Vars);
11105 Vars.clear();
11106 for (unsigned i = 0; i != NumVars; ++i)
11107 Vars.push_back(Record.readSubExpr());
11108 C->setPrivateCopies(Vars);
11109 Vars.clear();
11110 for (unsigned i = 0; i != NumVars; ++i)
11111 Vars.push_back(Record.readSubExpr());
11112 C->setInits(Vars);
11114 SmallVector<ValueDecl *, 16> Decls;
11115 Decls.reserve(UniqueDecls);
11116 for (unsigned i = 0; i < UniqueDecls; ++i)
11117 Decls.push_back(Record.readDeclAs<ValueDecl>());
11118 C->setUniqueDecls(Decls);
11120 SmallVector<unsigned, 16> ListsPerDecl;
11121 ListsPerDecl.reserve(UniqueDecls);
11122 for (unsigned i = 0; i < UniqueDecls; ++i)
11123 ListsPerDecl.push_back(Record.readInt());
11124 C->setDeclNumLists(ListsPerDecl);
11126 SmallVector<unsigned, 32> ListSizes;
11127 ListSizes.reserve(TotalLists);
11128 for (unsigned i = 0; i < TotalLists; ++i)
11129 ListSizes.push_back(Record.readInt());
11130 C->setComponentListSizes(ListSizes);
11132 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
11133 Components.reserve(TotalComponents);
11134 for (unsigned i = 0; i < TotalComponents; ++i) {
11135 auto *AssociatedExprPr = Record.readSubExpr();
11136 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
11137 Components.emplace_back(AssociatedExprPr, AssociatedDecl,
11138 /*IsNonContiguous=*/false);
11140 C->setComponents(Components, ListSizes);
11143 void OMPClauseReader::VisitOMPUseDeviceAddrClause(OMPUseDeviceAddrClause *C) {
11144 C->setLParenLoc(Record.readSourceLocation());
11145 auto NumVars = C->varlist_size();
11146 auto UniqueDecls = C->getUniqueDeclarationsNum();
11147 auto TotalLists = C->getTotalComponentListNum();
11148 auto TotalComponents = C->getTotalComponentsNum();
11150 SmallVector<Expr *, 16> Vars;
11151 Vars.reserve(NumVars);
11152 for (unsigned i = 0; i != NumVars; ++i)
11153 Vars.push_back(Record.readSubExpr());
11154 C->setVarRefs(Vars);
11156 SmallVector<ValueDecl *, 16> Decls;
11157 Decls.reserve(UniqueDecls);
11158 for (unsigned i = 0; i < UniqueDecls; ++i)
11159 Decls.push_back(Record.readDeclAs<ValueDecl>());
11160 C->setUniqueDecls(Decls);
11162 SmallVector<unsigned, 16> ListsPerDecl;
11163 ListsPerDecl.reserve(UniqueDecls);
11164 for (unsigned i = 0; i < UniqueDecls; ++i)
11165 ListsPerDecl.push_back(Record.readInt());
11166 C->setDeclNumLists(ListsPerDecl);
11168 SmallVector<unsigned, 32> ListSizes;
11169 ListSizes.reserve(TotalLists);
11170 for (unsigned i = 0; i < TotalLists; ++i)
11171 ListSizes.push_back(Record.readInt());
11172 C->setComponentListSizes(ListSizes);
11174 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
11175 Components.reserve(TotalComponents);
11176 for (unsigned i = 0; i < TotalComponents; ++i) {
11177 Expr *AssociatedExpr = Record.readSubExpr();
11178 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
11179 Components.emplace_back(AssociatedExpr, AssociatedDecl,
11180 /*IsNonContiguous*/ false);
11182 C->setComponents(Components, ListSizes);
11185 void OMPClauseReader::VisitOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
11186 C->setLParenLoc(Record.readSourceLocation());
11187 auto NumVars = C->varlist_size();
11188 auto UniqueDecls = C->getUniqueDeclarationsNum();
11189 auto TotalLists = C->getTotalComponentListNum();
11190 auto TotalComponents = C->getTotalComponentsNum();
11192 SmallVector<Expr *, 16> Vars;
11193 Vars.reserve(NumVars);
11194 for (unsigned i = 0; i != NumVars; ++i)
11195 Vars.push_back(Record.readSubExpr());
11196 C->setVarRefs(Vars);
11197 Vars.clear();
11199 SmallVector<ValueDecl *, 16> Decls;
11200 Decls.reserve(UniqueDecls);
11201 for (unsigned i = 0; i < UniqueDecls; ++i)
11202 Decls.push_back(Record.readDeclAs<ValueDecl>());
11203 C->setUniqueDecls(Decls);
11205 SmallVector<unsigned, 16> ListsPerDecl;
11206 ListsPerDecl.reserve(UniqueDecls);
11207 for (unsigned i = 0; i < UniqueDecls; ++i)
11208 ListsPerDecl.push_back(Record.readInt());
11209 C->setDeclNumLists(ListsPerDecl);
11211 SmallVector<unsigned, 32> ListSizes;
11212 ListSizes.reserve(TotalLists);
11213 for (unsigned i = 0; i < TotalLists; ++i)
11214 ListSizes.push_back(Record.readInt());
11215 C->setComponentListSizes(ListSizes);
11217 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
11218 Components.reserve(TotalComponents);
11219 for (unsigned i = 0; i < TotalComponents; ++i) {
11220 Expr *AssociatedExpr = Record.readSubExpr();
11221 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
11222 Components.emplace_back(AssociatedExpr, AssociatedDecl,
11223 /*IsNonContiguous=*/false);
11225 C->setComponents(Components, ListSizes);
11228 void OMPClauseReader::VisitOMPHasDeviceAddrClause(OMPHasDeviceAddrClause *C) {
11229 C->setLParenLoc(Record.readSourceLocation());
11230 auto NumVars = C->varlist_size();
11231 auto UniqueDecls = C->getUniqueDeclarationsNum();
11232 auto TotalLists = C->getTotalComponentListNum();
11233 auto TotalComponents = C->getTotalComponentsNum();
11235 SmallVector<Expr *, 16> Vars;
11236 Vars.reserve(NumVars);
11237 for (unsigned I = 0; I != NumVars; ++I)
11238 Vars.push_back(Record.readSubExpr());
11239 C->setVarRefs(Vars);
11240 Vars.clear();
11242 SmallVector<ValueDecl *, 16> Decls;
11243 Decls.reserve(UniqueDecls);
11244 for (unsigned I = 0; I < UniqueDecls; ++I)
11245 Decls.push_back(Record.readDeclAs<ValueDecl>());
11246 C->setUniqueDecls(Decls);
11248 SmallVector<unsigned, 16> ListsPerDecl;
11249 ListsPerDecl.reserve(UniqueDecls);
11250 for (unsigned I = 0; I < UniqueDecls; ++I)
11251 ListsPerDecl.push_back(Record.readInt());
11252 C->setDeclNumLists(ListsPerDecl);
11254 SmallVector<unsigned, 32> ListSizes;
11255 ListSizes.reserve(TotalLists);
11256 for (unsigned i = 0; i < TotalLists; ++i)
11257 ListSizes.push_back(Record.readInt());
11258 C->setComponentListSizes(ListSizes);
11260 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
11261 Components.reserve(TotalComponents);
11262 for (unsigned I = 0; I < TotalComponents; ++I) {
11263 Expr *AssociatedExpr = Record.readSubExpr();
11264 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
11265 Components.emplace_back(AssociatedExpr, AssociatedDecl,
11266 /*IsNonContiguous=*/false);
11268 C->setComponents(Components, ListSizes);
11271 void OMPClauseReader::VisitOMPNontemporalClause(OMPNontemporalClause *C) {
11272 C->setLParenLoc(Record.readSourceLocation());
11273 unsigned NumVars = C->varlist_size();
11274 SmallVector<Expr *, 16> Vars;
11275 Vars.reserve(NumVars);
11276 for (unsigned i = 0; i != NumVars; ++i)
11277 Vars.push_back(Record.readSubExpr());
11278 C->setVarRefs(Vars);
11279 Vars.clear();
11280 Vars.reserve(NumVars);
11281 for (unsigned i = 0; i != NumVars; ++i)
11282 Vars.push_back(Record.readSubExpr());
11283 C->setPrivateRefs(Vars);
11286 void OMPClauseReader::VisitOMPInclusiveClause(OMPInclusiveClause *C) {
11287 C->setLParenLoc(Record.readSourceLocation());
11288 unsigned NumVars = C->varlist_size();
11289 SmallVector<Expr *, 16> Vars;
11290 Vars.reserve(NumVars);
11291 for (unsigned i = 0; i != NumVars; ++i)
11292 Vars.push_back(Record.readSubExpr());
11293 C->setVarRefs(Vars);
11296 void OMPClauseReader::VisitOMPExclusiveClause(OMPExclusiveClause *C) {
11297 C->setLParenLoc(Record.readSourceLocation());
11298 unsigned NumVars = C->varlist_size();
11299 SmallVector<Expr *, 16> Vars;
11300 Vars.reserve(NumVars);
11301 for (unsigned i = 0; i != NumVars; ++i)
11302 Vars.push_back(Record.readSubExpr());
11303 C->setVarRefs(Vars);
11306 void OMPClauseReader::VisitOMPUsesAllocatorsClause(OMPUsesAllocatorsClause *C) {
11307 C->setLParenLoc(Record.readSourceLocation());
11308 unsigned NumOfAllocators = C->getNumberOfAllocators();
11309 SmallVector<OMPUsesAllocatorsClause::Data, 4> Data;
11310 Data.reserve(NumOfAllocators);
11311 for (unsigned I = 0; I != NumOfAllocators; ++I) {
11312 OMPUsesAllocatorsClause::Data &D = Data.emplace_back();
11313 D.Allocator = Record.readSubExpr();
11314 D.AllocatorTraits = Record.readSubExpr();
11315 D.LParenLoc = Record.readSourceLocation();
11316 D.RParenLoc = Record.readSourceLocation();
11318 C->setAllocatorsData(Data);
11321 void OMPClauseReader::VisitOMPAffinityClause(OMPAffinityClause *C) {
11322 C->setLParenLoc(Record.readSourceLocation());
11323 C->setModifier(Record.readSubExpr());
11324 C->setColonLoc(Record.readSourceLocation());
11325 unsigned NumOfLocators = C->varlist_size();
11326 SmallVector<Expr *, 4> Locators;
11327 Locators.reserve(NumOfLocators);
11328 for (unsigned I = 0; I != NumOfLocators; ++I)
11329 Locators.push_back(Record.readSubExpr());
11330 C->setVarRefs(Locators);
11333 void OMPClauseReader::VisitOMPOrderClause(OMPOrderClause *C) {
11334 C->setKind(Record.readEnum<OpenMPOrderClauseKind>());
11335 C->setModifier(Record.readEnum<OpenMPOrderClauseModifier>());
11336 C->setLParenLoc(Record.readSourceLocation());
11337 C->setKindKwLoc(Record.readSourceLocation());
11338 C->setModifierKwLoc(Record.readSourceLocation());
11341 void OMPClauseReader::VisitOMPFilterClause(OMPFilterClause *C) {
11342 VisitOMPClauseWithPreInit(C);
11343 C->setThreadID(Record.readSubExpr());
11344 C->setLParenLoc(Record.readSourceLocation());
11347 void OMPClauseReader::VisitOMPBindClause(OMPBindClause *C) {
11348 C->setBindKind(Record.readEnum<OpenMPBindClauseKind>());
11349 C->setLParenLoc(Record.readSourceLocation());
11350 C->setBindKindLoc(Record.readSourceLocation());
11353 void OMPClauseReader::VisitOMPAlignClause(OMPAlignClause *C) {
11354 C->setAlignment(Record.readExpr());
11355 C->setLParenLoc(Record.readSourceLocation());
11358 void OMPClauseReader::VisitOMPXDynCGroupMemClause(OMPXDynCGroupMemClause *C) {
11359 VisitOMPClauseWithPreInit(C);
11360 C->setSize(Record.readSubExpr());
11361 C->setLParenLoc(Record.readSourceLocation());
11364 OMPTraitInfo *ASTRecordReader::readOMPTraitInfo() {
11365 OMPTraitInfo &TI = getContext().getNewOMPTraitInfo();
11366 TI.Sets.resize(readUInt32());
11367 for (auto &Set : TI.Sets) {
11368 Set.Kind = readEnum<llvm::omp::TraitSet>();
11369 Set.Selectors.resize(readUInt32());
11370 for (auto &Selector : Set.Selectors) {
11371 Selector.Kind = readEnum<llvm::omp::TraitSelector>();
11372 Selector.ScoreOrCondition = nullptr;
11373 if (readBool())
11374 Selector.ScoreOrCondition = readExprRef();
11375 Selector.Properties.resize(readUInt32());
11376 for (auto &Property : Selector.Properties)
11377 Property.Kind = readEnum<llvm::omp::TraitProperty>();
11380 return &TI;
11383 void ASTRecordReader::readOMPChildren(OMPChildren *Data) {
11384 if (!Data)
11385 return;
11386 if (Reader->ReadingKind == ASTReader::Read_Stmt) {
11387 // Skip NumClauses, NumChildren and HasAssociatedStmt fields.
11388 skipInts(3);
11390 SmallVector<OMPClause *, 4> Clauses(Data->getNumClauses());
11391 for (unsigned I = 0, E = Data->getNumClauses(); I < E; ++I)
11392 Clauses[I] = readOMPClause();
11393 Data->setClauses(Clauses);
11394 if (Data->hasAssociatedStmt())
11395 Data->setAssociatedStmt(readStmt());
11396 for (unsigned I = 0, E = Data->getNumChildren(); I < E; ++I)
11397 Data->getChildren()[I] = readStmt();