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. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "clang/Basic/OpenMPKinds.h" 14 #include "clang/Serialization/ASTRecordReader.h" 15 #include "ASTCommon.h" 16 #include "ASTReaderInternals.h" 17 #include "clang/AST/AbstractTypeReader.h" 18 #include "clang/AST/ASTConsumer.h" 19 #include "clang/AST/ASTContext.h" 20 #include "clang/AST/ASTMutationListener.h" 21 #include "clang/AST/ASTUnresolvedSet.h" 22 #include "clang/AST/Decl.h" 23 #include "clang/AST/DeclBase.h" 24 #include "clang/AST/DeclCXX.h" 25 #include "clang/AST/DeclFriend.h" 26 #include "clang/AST/DeclGroup.h" 27 #include "clang/AST/DeclObjC.h" 28 #include "clang/AST/DeclTemplate.h" 29 #include "clang/AST/DeclarationName.h" 30 #include "clang/AST/Expr.h" 31 #include "clang/AST/ExprCXX.h" 32 #include "clang/AST/ExternalASTSource.h" 33 #include "clang/AST/NestedNameSpecifier.h" 34 #include "clang/AST/OpenMPClause.h" 35 #include "clang/AST/ODRHash.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/DiagnosticOptions.h" 46 #include "clang/Basic/ExceptionSpecificationType.h" 47 #include "clang/Basic/FileManager.h" 48 #include "clang/Basic/FileSystemOptions.h" 49 #include "clang/Basic/IdentifierTable.h" 50 #include "clang/Basic/LLVM.h" 51 #include "clang/Basic/LangOptions.h" 52 #include "clang/Basic/Module.h" 53 #include "clang/Basic/ObjCRuntime.h" 54 #include "clang/Basic/OperatorKinds.h" 55 #include "clang/Basic/PragmaKinds.h" 56 #include "clang/Basic/Sanitizers.h" 57 #include "clang/Basic/SourceLocation.h" 58 #include "clang/Basic/SourceManager.h" 59 #include "clang/Basic/SourceManagerInternals.h" 60 #include "clang/Basic/Specifiers.h" 61 #include "clang/Basic/TargetInfo.h" 62 #include "clang/Basic/TargetOptions.h" 63 #include "clang/Basic/TokenKinds.h" 64 #include "clang/Basic/Version.h" 65 #include "clang/Lex/HeaderSearch.h" 66 #include "clang/Lex/HeaderSearchOptions.h" 67 #include "clang/Lex/MacroInfo.h" 68 #include "clang/Lex/ModuleMap.h" 69 #include "clang/Lex/PreprocessingRecord.h" 70 #include "clang/Lex/Preprocessor.h" 71 #include "clang/Lex/PreprocessorOptions.h" 72 #include "clang/Lex/Token.h" 73 #include "clang/Sema/ObjCMethodList.h" 74 #include "clang/Sema/Scope.h" 75 #include "clang/Sema/Sema.h" 76 #include "clang/Sema/Weak.h" 77 #include "clang/Serialization/ASTBitCodes.h" 78 #include "clang/Serialization/ASTDeserializationListener.h" 79 #include "clang/Serialization/ContinuousRangeMap.h" 80 #include "clang/Serialization/GlobalModuleIndex.h" 81 #include "clang/Serialization/InMemoryModuleCache.h" 82 #include "clang/Serialization/ModuleFile.h" 83 #include "clang/Serialization/ModuleFileExtension.h" 84 #include "clang/Serialization/ModuleManager.h" 85 #include "clang/Serialization/PCHContainerOperations.h" 86 #include "clang/Serialization/SerializationDiagnostic.h" 87 #include "llvm/ADT/APFloat.h" 88 #include "llvm/ADT/APInt.h" 89 #include "llvm/ADT/APSInt.h" 90 #include "llvm/ADT/ArrayRef.h" 91 #include "llvm/ADT/DenseMap.h" 92 #include "llvm/ADT/FloatingPointMode.h" 93 #include "llvm/ADT/FoldingSet.h" 94 #include "llvm/ADT/Hashing.h" 95 #include "llvm/ADT/IntrusiveRefCntPtr.h" 96 #include "llvm/ADT/None.h" 97 #include "llvm/ADT/Optional.h" 98 #include "llvm/ADT/STLExtras.h" 99 #include "llvm/ADT/ScopeExit.h" 100 #include "llvm/ADT/SmallPtrSet.h" 101 #include "llvm/ADT/SmallString.h" 102 #include "llvm/ADT/SmallVector.h" 103 #include "llvm/ADT/StringExtras.h" 104 #include "llvm/ADT/StringMap.h" 105 #include "llvm/ADT/StringRef.h" 106 #include "llvm/ADT/Triple.h" 107 #include "llvm/ADT/iterator_range.h" 108 #include "llvm/Bitstream/BitstreamReader.h" 109 #include "llvm/Support/Casting.h" 110 #include "llvm/Support/Compiler.h" 111 #include "llvm/Support/Compression.h" 112 #include "llvm/Support/DJB.h" 113 #include "llvm/Support/Endian.h" 114 #include "llvm/Support/Error.h" 115 #include "llvm/Support/ErrorHandling.h" 116 #include "llvm/Support/FileSystem.h" 117 #include "llvm/Support/MemoryBuffer.h" 118 #include "llvm/Support/Path.h" 119 #include "llvm/Support/SaveAndRestore.h" 120 #include "llvm/Support/Timer.h" 121 #include "llvm/Support/VersionTuple.h" 122 #include "llvm/Support/raw_ostream.h" 123 #include <algorithm> 124 #include <cassert> 125 #include <cstddef> 126 #include <cstdint> 127 #include <cstdio> 128 #include <ctime> 129 #include <iterator> 130 #include <limits> 131 #include <map> 132 #include <memory> 133 #include <string> 134 #include <system_error> 135 #include <tuple> 136 #include <utility> 137 #include <vector> 138 139 using namespace clang; 140 using namespace clang::serialization; 141 using namespace clang::serialization::reader; 142 using llvm::BitstreamCursor; 143 using llvm::RoundingMode; 144 145 //===----------------------------------------------------------------------===// 146 // ChainedASTReaderListener implementation 147 //===----------------------------------------------------------------------===// 148 149 bool 150 ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) { 151 return First->ReadFullVersionInformation(FullVersion) || 152 Second->ReadFullVersionInformation(FullVersion); 153 } 154 155 void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) { 156 First->ReadModuleName(ModuleName); 157 Second->ReadModuleName(ModuleName); 158 } 159 160 void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) { 161 First->ReadModuleMapFile(ModuleMapPath); 162 Second->ReadModuleMapFile(ModuleMapPath); 163 } 164 165 bool 166 ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts, 167 bool Complain, 168 bool AllowCompatibleDifferences) { 169 return First->ReadLanguageOptions(LangOpts, Complain, 170 AllowCompatibleDifferences) || 171 Second->ReadLanguageOptions(LangOpts, Complain, 172 AllowCompatibleDifferences); 173 } 174 175 bool ChainedASTReaderListener::ReadTargetOptions( 176 const TargetOptions &TargetOpts, bool Complain, 177 bool AllowCompatibleDifferences) { 178 return First->ReadTargetOptions(TargetOpts, Complain, 179 AllowCompatibleDifferences) || 180 Second->ReadTargetOptions(TargetOpts, Complain, 181 AllowCompatibleDifferences); 182 } 183 184 bool ChainedASTReaderListener::ReadDiagnosticOptions( 185 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) { 186 return First->ReadDiagnosticOptions(DiagOpts, Complain) || 187 Second->ReadDiagnosticOptions(DiagOpts, Complain); 188 } 189 190 bool 191 ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts, 192 bool Complain) { 193 return First->ReadFileSystemOptions(FSOpts, Complain) || 194 Second->ReadFileSystemOptions(FSOpts, Complain); 195 } 196 197 bool ChainedASTReaderListener::ReadHeaderSearchOptions( 198 const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath, 199 bool Complain) { 200 return First->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath, 201 Complain) || 202 Second->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath, 203 Complain); 204 } 205 206 bool ChainedASTReaderListener::ReadPreprocessorOptions( 207 const PreprocessorOptions &PPOpts, bool Complain, 208 std::string &SuggestedPredefines) { 209 return First->ReadPreprocessorOptions(PPOpts, Complain, 210 SuggestedPredefines) || 211 Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines); 212 } 213 214 void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M, 215 unsigned Value) { 216 First->ReadCounter(M, Value); 217 Second->ReadCounter(M, Value); 218 } 219 220 bool ChainedASTReaderListener::needsInputFileVisitation() { 221 return First->needsInputFileVisitation() || 222 Second->needsInputFileVisitation(); 223 } 224 225 bool ChainedASTReaderListener::needsSystemInputFileVisitation() { 226 return First->needsSystemInputFileVisitation() || 227 Second->needsSystemInputFileVisitation(); 228 } 229 230 void ChainedASTReaderListener::visitModuleFile(StringRef Filename, 231 ModuleKind Kind) { 232 First->visitModuleFile(Filename, Kind); 233 Second->visitModuleFile(Filename, Kind); 234 } 235 236 bool ChainedASTReaderListener::visitInputFile(StringRef Filename, 237 bool isSystem, 238 bool isOverridden, 239 bool isExplicitModule) { 240 bool Continue = false; 241 if (First->needsInputFileVisitation() && 242 (!isSystem || First->needsSystemInputFileVisitation())) 243 Continue |= First->visitInputFile(Filename, isSystem, isOverridden, 244 isExplicitModule); 245 if (Second->needsInputFileVisitation() && 246 (!isSystem || Second->needsSystemInputFileVisitation())) 247 Continue |= Second->visitInputFile(Filename, isSystem, isOverridden, 248 isExplicitModule); 249 return Continue; 250 } 251 252 void ChainedASTReaderListener::readModuleFileExtension( 253 const ModuleFileExtensionMetadata &Metadata) { 254 First->readModuleFileExtension(Metadata); 255 Second->readModuleFileExtension(Metadata); 256 } 257 258 //===----------------------------------------------------------------------===// 259 // PCH validator implementation 260 //===----------------------------------------------------------------------===// 261 262 ASTReaderListener::~ASTReaderListener() = default; 263 264 /// Compare the given set of language options against an existing set of 265 /// language options. 266 /// 267 /// \param Diags If non-NULL, diagnostics will be emitted via this engine. 268 /// \param AllowCompatibleDifferences If true, differences between compatible 269 /// language options will be permitted. 270 /// 271 /// \returns true if the languagae options mis-match, false otherwise. 272 static bool checkLanguageOptions(const LangOptions &LangOpts, 273 const LangOptions &ExistingLangOpts, 274 DiagnosticsEngine *Diags, 275 bool AllowCompatibleDifferences = true) { 276 #define LANGOPT(Name, Bits, Default, Description) \ 277 if (ExistingLangOpts.Name != LangOpts.Name) { \ 278 if (Diags) \ 279 Diags->Report(diag::err_pch_langopt_mismatch) \ 280 << Description << LangOpts.Name << ExistingLangOpts.Name; \ 281 return true; \ 282 } 283 284 #define VALUE_LANGOPT(Name, Bits, Default, Description) \ 285 if (ExistingLangOpts.Name != LangOpts.Name) { \ 286 if (Diags) \ 287 Diags->Report(diag::err_pch_langopt_value_mismatch) \ 288 << Description; \ 289 return true; \ 290 } 291 292 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \ 293 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \ 294 if (Diags) \ 295 Diags->Report(diag::err_pch_langopt_value_mismatch) \ 296 << Description; \ 297 return true; \ 298 } 299 300 #define COMPATIBLE_LANGOPT(Name, Bits, Default, Description) \ 301 if (!AllowCompatibleDifferences) \ 302 LANGOPT(Name, Bits, Default, Description) 303 304 #define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description) \ 305 if (!AllowCompatibleDifferences) \ 306 ENUM_LANGOPT(Name, Bits, Default, Description) 307 308 #define COMPATIBLE_VALUE_LANGOPT(Name, Bits, Default, Description) \ 309 if (!AllowCompatibleDifferences) \ 310 VALUE_LANGOPT(Name, Bits, Default, Description) 311 312 #define BENIGN_LANGOPT(Name, Bits, Default, Description) 313 #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description) 314 #define BENIGN_VALUE_LANGOPT(Name, Type, Bits, Default, Description) 315 #include "clang/Basic/LangOptions.def" 316 317 if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) { 318 if (Diags) 319 Diags->Report(diag::err_pch_langopt_value_mismatch) << "module features"; 320 return true; 321 } 322 323 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) { 324 if (Diags) 325 Diags->Report(diag::err_pch_langopt_value_mismatch) 326 << "target Objective-C runtime"; 327 return true; 328 } 329 330 if (ExistingLangOpts.CommentOpts.BlockCommandNames != 331 LangOpts.CommentOpts.BlockCommandNames) { 332 if (Diags) 333 Diags->Report(diag::err_pch_langopt_value_mismatch) 334 << "block command names"; 335 return true; 336 } 337 338 // Sanitizer feature mismatches are treated as compatible differences. If 339 // compatible differences aren't allowed, we still only want to check for 340 // mismatches of non-modular sanitizers (the only ones which can affect AST 341 // generation). 342 if (!AllowCompatibleDifferences) { 343 SanitizerMask ModularSanitizers = getPPTransparentSanitizers(); 344 SanitizerSet ExistingSanitizers = ExistingLangOpts.Sanitize; 345 SanitizerSet ImportedSanitizers = LangOpts.Sanitize; 346 ExistingSanitizers.clear(ModularSanitizers); 347 ImportedSanitizers.clear(ModularSanitizers); 348 if (ExistingSanitizers.Mask != ImportedSanitizers.Mask) { 349 const std::string Flag = "-fsanitize="; 350 if (Diags) { 351 #define SANITIZER(NAME, ID) \ 352 { \ 353 bool InExistingModule = ExistingSanitizers.has(SanitizerKind::ID); \ 354 bool InImportedModule = ImportedSanitizers.has(SanitizerKind::ID); \ 355 if (InExistingModule != InImportedModule) \ 356 Diags->Report(diag::err_pch_targetopt_feature_mismatch) \ 357 << InExistingModule << (Flag + NAME); \ 358 } 359 #include "clang/Basic/Sanitizers.def" 360 } 361 return true; 362 } 363 } 364 365 return false; 366 } 367 368 /// Compare the given set of target options against an existing set of 369 /// target options. 370 /// 371 /// \param Diags If non-NULL, diagnostics will be emitted via this engine. 372 /// 373 /// \returns true if the target options mis-match, false otherwise. 374 static bool checkTargetOptions(const TargetOptions &TargetOpts, 375 const TargetOptions &ExistingTargetOpts, 376 DiagnosticsEngine *Diags, 377 bool AllowCompatibleDifferences = true) { 378 #define CHECK_TARGET_OPT(Field, Name) \ 379 if (TargetOpts.Field != ExistingTargetOpts.Field) { \ 380 if (Diags) \ 381 Diags->Report(diag::err_pch_targetopt_mismatch) \ 382 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \ 383 return true; \ 384 } 385 386 // The triple and ABI must match exactly. 387 CHECK_TARGET_OPT(Triple, "target"); 388 CHECK_TARGET_OPT(ABI, "target ABI"); 389 390 // We can tolerate different CPUs in many cases, notably when one CPU 391 // supports a strict superset of another. When allowing compatible 392 // differences skip this check. 393 if (!AllowCompatibleDifferences) { 394 CHECK_TARGET_OPT(CPU, "target CPU"); 395 CHECK_TARGET_OPT(TuneCPU, "tune CPU"); 396 } 397 398 #undef CHECK_TARGET_OPT 399 400 // Compare feature sets. 401 SmallVector<StringRef, 4> ExistingFeatures( 402 ExistingTargetOpts.FeaturesAsWritten.begin(), 403 ExistingTargetOpts.FeaturesAsWritten.end()); 404 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(), 405 TargetOpts.FeaturesAsWritten.end()); 406 llvm::sort(ExistingFeatures); 407 llvm::sort(ReadFeatures); 408 409 // We compute the set difference in both directions explicitly so that we can 410 // diagnose the differences differently. 411 SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures; 412 std::set_difference( 413 ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(), 414 ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures)); 415 std::set_difference(ReadFeatures.begin(), ReadFeatures.end(), 416 ExistingFeatures.begin(), ExistingFeatures.end(), 417 std::back_inserter(UnmatchedReadFeatures)); 418 419 // If we are allowing compatible differences and the read feature set is 420 // a strict subset of the existing feature set, there is nothing to diagnose. 421 if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty()) 422 return false; 423 424 if (Diags) { 425 for (StringRef Feature : UnmatchedReadFeatures) 426 Diags->Report(diag::err_pch_targetopt_feature_mismatch) 427 << /* is-existing-feature */ false << Feature; 428 for (StringRef Feature : UnmatchedExistingFeatures) 429 Diags->Report(diag::err_pch_targetopt_feature_mismatch) 430 << /* is-existing-feature */ true << Feature; 431 } 432 433 return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty(); 434 } 435 436 bool 437 PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts, 438 bool Complain, 439 bool AllowCompatibleDifferences) { 440 const LangOptions &ExistingLangOpts = PP.getLangOpts(); 441 return checkLanguageOptions(LangOpts, ExistingLangOpts, 442 Complain ? &Reader.Diags : nullptr, 443 AllowCompatibleDifferences); 444 } 445 446 bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts, 447 bool Complain, 448 bool AllowCompatibleDifferences) { 449 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts(); 450 return checkTargetOptions(TargetOpts, ExistingTargetOpts, 451 Complain ? &Reader.Diags : nullptr, 452 AllowCompatibleDifferences); 453 } 454 455 namespace { 456 457 using MacroDefinitionsMap = 458 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>; 459 using DeclsMap = llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8>>; 460 461 } // namespace 462 463 static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags, 464 DiagnosticsEngine &Diags, 465 bool Complain) { 466 using Level = DiagnosticsEngine::Level; 467 468 // Check current mappings for new -Werror mappings, and the stored mappings 469 // for cases that were explicitly mapped to *not* be errors that are now 470 // errors because of options like -Werror. 471 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags }; 472 473 for (DiagnosticsEngine *MappingSource : MappingSources) { 474 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) { 475 diag::kind DiagID = DiagIDMappingPair.first; 476 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation()); 477 if (CurLevel < DiagnosticsEngine::Error) 478 continue; // not significant 479 Level StoredLevel = 480 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation()); 481 if (StoredLevel < DiagnosticsEngine::Error) { 482 if (Complain) 483 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" + 484 Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str(); 485 return true; 486 } 487 } 488 } 489 490 return false; 491 } 492 493 static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) { 494 diag::Severity Ext = Diags.getExtensionHandlingBehavior(); 495 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors()) 496 return true; 497 return Ext >= diag::Severity::Error; 498 } 499 500 static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags, 501 DiagnosticsEngine &Diags, 502 bool IsSystem, bool Complain) { 503 // Top-level options 504 if (IsSystem) { 505 if (Diags.getSuppressSystemWarnings()) 506 return false; 507 // If -Wsystem-headers was not enabled before, be conservative 508 if (StoredDiags.getSuppressSystemWarnings()) { 509 if (Complain) 510 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers"; 511 return true; 512 } 513 } 514 515 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) { 516 if (Complain) 517 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror"; 518 return true; 519 } 520 521 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() && 522 !StoredDiags.getEnableAllWarnings()) { 523 if (Complain) 524 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror"; 525 return true; 526 } 527 528 if (isExtHandlingFromDiagsError(Diags) && 529 !isExtHandlingFromDiagsError(StoredDiags)) { 530 if (Complain) 531 Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors"; 532 return true; 533 } 534 535 return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain); 536 } 537 538 /// Return the top import module if it is implicit, nullptr otherwise. 539 static Module *getTopImportImplicitModule(ModuleManager &ModuleMgr, 540 Preprocessor &PP) { 541 // If the original import came from a file explicitly generated by the user, 542 // don't check the diagnostic mappings. 543 // FIXME: currently this is approximated by checking whether this is not a 544 // module import of an implicitly-loaded module file. 545 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in 546 // the transitive closure of its imports, since unrelated modules cannot be 547 // imported until after this module finishes validation. 548 ModuleFile *TopImport = &*ModuleMgr.rbegin(); 549 while (!TopImport->ImportedBy.empty()) 550 TopImport = TopImport->ImportedBy[0]; 551 if (TopImport->Kind != MK_ImplicitModule) 552 return nullptr; 553 554 StringRef ModuleName = TopImport->ModuleName; 555 assert(!ModuleName.empty() && "diagnostic options read before module name"); 556 557 Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName); 558 assert(M && "missing module"); 559 return M; 560 } 561 562 bool PCHValidator::ReadDiagnosticOptions( 563 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) { 564 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics(); 565 IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs()); 566 IntrusiveRefCntPtr<DiagnosticsEngine> Diags( 567 new DiagnosticsEngine(DiagIDs, DiagOpts.get())); 568 // This should never fail, because we would have processed these options 569 // before writing them to an ASTFile. 570 ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false); 571 572 ModuleManager &ModuleMgr = Reader.getModuleManager(); 573 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then"); 574 575 Module *TopM = getTopImportImplicitModule(ModuleMgr, PP); 576 if (!TopM) 577 return false; 578 579 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that 580 // contains the union of their flags. 581 return checkDiagnosticMappings(*Diags, ExistingDiags, TopM->IsSystem, 582 Complain); 583 } 584 585 /// Collect the macro definitions provided by the given preprocessor 586 /// options. 587 static void 588 collectMacroDefinitions(const PreprocessorOptions &PPOpts, 589 MacroDefinitionsMap &Macros, 590 SmallVectorImpl<StringRef> *MacroNames = nullptr) { 591 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) { 592 StringRef Macro = PPOpts.Macros[I].first; 593 bool IsUndef = PPOpts.Macros[I].second; 594 595 std::pair<StringRef, StringRef> MacroPair = Macro.split('='); 596 StringRef MacroName = MacroPair.first; 597 StringRef MacroBody = MacroPair.second; 598 599 // For an #undef'd macro, we only care about the name. 600 if (IsUndef) { 601 if (MacroNames && !Macros.count(MacroName)) 602 MacroNames->push_back(MacroName); 603 604 Macros[MacroName] = std::make_pair("", true); 605 continue; 606 } 607 608 // For a #define'd macro, figure out the actual definition. 609 if (MacroName.size() == Macro.size()) 610 MacroBody = "1"; 611 else { 612 // Note: GCC drops anything following an end-of-line character. 613 StringRef::size_type End = MacroBody.find_first_of("\n\r"); 614 MacroBody = MacroBody.substr(0, End); 615 } 616 617 if (MacroNames && !Macros.count(MacroName)) 618 MacroNames->push_back(MacroName); 619 Macros[MacroName] = std::make_pair(MacroBody, false); 620 } 621 } 622 623 /// Check the preprocessor options deserialized from the control block 624 /// against the preprocessor options in an existing preprocessor. 625 /// 626 /// \param Diags If non-null, produce diagnostics for any mismatches incurred. 627 /// \param Validate If true, validate preprocessor options. If false, allow 628 /// macros defined by \p ExistingPPOpts to override those defined by 629 /// \p PPOpts in SuggestedPredefines. 630 static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts, 631 const PreprocessorOptions &ExistingPPOpts, 632 DiagnosticsEngine *Diags, 633 FileManager &FileMgr, 634 std::string &SuggestedPredefines, 635 const LangOptions &LangOpts, 636 bool Validate = true) { 637 // Check macro definitions. 638 MacroDefinitionsMap ASTFileMacros; 639 collectMacroDefinitions(PPOpts, ASTFileMacros); 640 MacroDefinitionsMap ExistingMacros; 641 SmallVector<StringRef, 4> ExistingMacroNames; 642 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames); 643 644 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) { 645 // Dig out the macro definition in the existing preprocessor options. 646 StringRef MacroName = ExistingMacroNames[I]; 647 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName]; 648 649 // Check whether we know anything about this macro name or not. 650 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>::iterator Known = 651 ASTFileMacros.find(MacroName); 652 if (!Validate || Known == ASTFileMacros.end()) { 653 // FIXME: Check whether this identifier was referenced anywhere in the 654 // AST file. If so, we should reject the AST file. Unfortunately, this 655 // information isn't in the control block. What shall we do about it? 656 657 if (Existing.second) { 658 SuggestedPredefines += "#undef "; 659 SuggestedPredefines += MacroName.str(); 660 SuggestedPredefines += '\n'; 661 } else { 662 SuggestedPredefines += "#define "; 663 SuggestedPredefines += MacroName.str(); 664 SuggestedPredefines += ' '; 665 SuggestedPredefines += Existing.first.str(); 666 SuggestedPredefines += '\n'; 667 } 668 continue; 669 } 670 671 // If the macro was defined in one but undef'd in the other, we have a 672 // conflict. 673 if (Existing.second != Known->second.second) { 674 if (Diags) { 675 Diags->Report(diag::err_pch_macro_def_undef) 676 << MacroName << Known->second.second; 677 } 678 return true; 679 } 680 681 // If the macro was #undef'd in both, or if the macro bodies are identical, 682 // it's fine. 683 if (Existing.second || Existing.first == Known->second.first) 684 continue; 685 686 // The macro bodies differ; complain. 687 if (Diags) { 688 Diags->Report(diag::err_pch_macro_def_conflict) 689 << MacroName << Known->second.first << Existing.first; 690 } 691 return true; 692 } 693 694 // Check whether we're using predefines. 695 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines && Validate) { 696 if (Diags) { 697 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines; 698 } 699 return true; 700 } 701 702 // Detailed record is important since it is used for the module cache hash. 703 if (LangOpts.Modules && 704 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord && Validate) { 705 if (Diags) { 706 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord; 707 } 708 return true; 709 } 710 711 // Compute the #include and #include_macros lines we need. 712 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) { 713 StringRef File = ExistingPPOpts.Includes[I]; 714 715 if (!ExistingPPOpts.ImplicitPCHInclude.empty() && 716 !ExistingPPOpts.PCHThroughHeader.empty()) { 717 // In case the through header is an include, we must add all the includes 718 // to the predefines so the start point can be determined. 719 SuggestedPredefines += "#include \""; 720 SuggestedPredefines += File; 721 SuggestedPredefines += "\"\n"; 722 continue; 723 } 724 725 if (File == ExistingPPOpts.ImplicitPCHInclude) 726 continue; 727 728 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File) 729 != PPOpts.Includes.end()) 730 continue; 731 732 SuggestedPredefines += "#include \""; 733 SuggestedPredefines += File; 734 SuggestedPredefines += "\"\n"; 735 } 736 737 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) { 738 StringRef File = ExistingPPOpts.MacroIncludes[I]; 739 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(), 740 File) 741 != PPOpts.MacroIncludes.end()) 742 continue; 743 744 SuggestedPredefines += "#__include_macros \""; 745 SuggestedPredefines += File; 746 SuggestedPredefines += "\"\n##\n"; 747 } 748 749 return false; 750 } 751 752 bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, 753 bool Complain, 754 std::string &SuggestedPredefines) { 755 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts(); 756 757 return checkPreprocessorOptions(PPOpts, ExistingPPOpts, 758 Complain? &Reader.Diags : nullptr, 759 PP.getFileManager(), 760 SuggestedPredefines, 761 PP.getLangOpts()); 762 } 763 764 bool SimpleASTReaderListener::ReadPreprocessorOptions( 765 const PreprocessorOptions &PPOpts, 766 bool Complain, 767 std::string &SuggestedPredefines) { 768 return checkPreprocessorOptions(PPOpts, 769 PP.getPreprocessorOpts(), 770 nullptr, 771 PP.getFileManager(), 772 SuggestedPredefines, 773 PP.getLangOpts(), 774 false); 775 } 776 777 /// Check the header search options deserialized from the control block 778 /// against the header search options in an existing preprocessor. 779 /// 780 /// \param Diags If non-null, produce diagnostics for any mismatches incurred. 781 static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts, 782 StringRef SpecificModuleCachePath, 783 StringRef ExistingModuleCachePath, 784 DiagnosticsEngine *Diags, 785 const LangOptions &LangOpts) { 786 if (LangOpts.Modules) { 787 if (SpecificModuleCachePath != ExistingModuleCachePath) { 788 if (Diags) 789 Diags->Report(diag::err_pch_modulecache_mismatch) 790 << SpecificModuleCachePath << ExistingModuleCachePath; 791 return true; 792 } 793 } 794 795 return false; 796 } 797 798 bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, 799 StringRef SpecificModuleCachePath, 800 bool Complain) { 801 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath, 802 PP.getHeaderSearchInfo().getModuleCachePath(), 803 Complain ? &Reader.Diags : nullptr, 804 PP.getLangOpts()); 805 } 806 807 void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) { 808 PP.setCounterValue(Value); 809 } 810 811 //===----------------------------------------------------------------------===// 812 // AST reader implementation 813 //===----------------------------------------------------------------------===// 814 815 void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener, 816 bool TakeOwnership) { 817 DeserializationListener = Listener; 818 OwnsDeserializationListener = TakeOwnership; 819 } 820 821 unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) { 822 return serialization::ComputeHash(Sel); 823 } 824 825 std::pair<unsigned, unsigned> 826 ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) { 827 using namespace llvm::support; 828 829 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d); 830 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d); 831 return std::make_pair(KeyLen, DataLen); 832 } 833 834 ASTSelectorLookupTrait::internal_key_type 835 ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) { 836 using namespace llvm::support; 837 838 SelectorTable &SelTable = Reader.getContext().Selectors; 839 unsigned N = endian::readNext<uint16_t, little, unaligned>(d); 840 IdentifierInfo *FirstII = Reader.getLocalIdentifier( 841 F, endian::readNext<uint32_t, little, unaligned>(d)); 842 if (N == 0) 843 return SelTable.getNullarySelector(FirstII); 844 else if (N == 1) 845 return SelTable.getUnarySelector(FirstII); 846 847 SmallVector<IdentifierInfo *, 16> Args; 848 Args.push_back(FirstII); 849 for (unsigned I = 1; I != N; ++I) 850 Args.push_back(Reader.getLocalIdentifier( 851 F, endian::readNext<uint32_t, little, unaligned>(d))); 852 853 return SelTable.getSelector(N, Args.data()); 854 } 855 856 ASTSelectorLookupTrait::data_type 857 ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d, 858 unsigned DataLen) { 859 using namespace llvm::support; 860 861 data_type Result; 862 863 Result.ID = Reader.getGlobalSelectorID( 864 F, endian::readNext<uint32_t, little, unaligned>(d)); 865 unsigned FullInstanceBits = endian::readNext<uint16_t, little, unaligned>(d); 866 unsigned FullFactoryBits = endian::readNext<uint16_t, little, unaligned>(d); 867 Result.InstanceBits = FullInstanceBits & 0x3; 868 Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1; 869 Result.FactoryBits = FullFactoryBits & 0x3; 870 Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1; 871 unsigned NumInstanceMethods = FullInstanceBits >> 3; 872 unsigned NumFactoryMethods = FullFactoryBits >> 3; 873 874 // Load instance methods 875 for (unsigned I = 0; I != NumInstanceMethods; ++I) { 876 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>( 877 F, endian::readNext<uint32_t, little, unaligned>(d))) 878 Result.Instance.push_back(Method); 879 } 880 881 // Load factory methods 882 for (unsigned I = 0; I != NumFactoryMethods; ++I) { 883 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>( 884 F, endian::readNext<uint32_t, little, unaligned>(d))) 885 Result.Factory.push_back(Method); 886 } 887 888 return Result; 889 } 890 891 unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) { 892 return llvm::djbHash(a); 893 } 894 895 std::pair<unsigned, unsigned> 896 ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) { 897 using namespace llvm::support; 898 899 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d); 900 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d); 901 return std::make_pair(KeyLen, DataLen); 902 } 903 904 ASTIdentifierLookupTraitBase::internal_key_type 905 ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) { 906 assert(n >= 2 && d[n-1] == '\0'); 907 return StringRef((const char*) d, n-1); 908 } 909 910 /// Whether the given identifier is "interesting". 911 static bool isInterestingIdentifier(ASTReader &Reader, IdentifierInfo &II, 912 bool IsModule) { 913 return II.hadMacroDefinition() || II.isPoisoned() || 914 (!IsModule && II.getObjCOrBuiltinID()) || 915 II.hasRevertedTokenIDToIdentifier() || 916 (!(IsModule && Reader.getPreprocessor().getLangOpts().CPlusPlus) && 917 II.getFETokenInfo()); 918 } 919 920 static bool readBit(unsigned &Bits) { 921 bool Value = Bits & 0x1; 922 Bits >>= 1; 923 return Value; 924 } 925 926 IdentID ASTIdentifierLookupTrait::ReadIdentifierID(const unsigned char *d) { 927 using namespace llvm::support; 928 929 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d); 930 return Reader.getGlobalIdentifierID(F, RawID >> 1); 931 } 932 933 static void markIdentifierFromAST(ASTReader &Reader, IdentifierInfo &II) { 934 if (!II.isFromAST()) { 935 II.setIsFromAST(); 936 bool IsModule = Reader.getPreprocessor().getCurrentModule() != nullptr; 937 if (isInterestingIdentifier(Reader, II, IsModule)) 938 II.setChangedSinceDeserialization(); 939 } 940 } 941 942 IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k, 943 const unsigned char* d, 944 unsigned DataLen) { 945 using namespace llvm::support; 946 947 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d); 948 bool IsInteresting = RawID & 0x01; 949 950 // Wipe out the "is interesting" bit. 951 RawID = RawID >> 1; 952 953 // Build the IdentifierInfo and link the identifier ID with it. 954 IdentifierInfo *II = KnownII; 955 if (!II) { 956 II = &Reader.getIdentifierTable().getOwn(k); 957 KnownII = II; 958 } 959 markIdentifierFromAST(Reader, *II); 960 Reader.markIdentifierUpToDate(II); 961 962 IdentID ID = Reader.getGlobalIdentifierID(F, RawID); 963 if (!IsInteresting) { 964 // For uninteresting identifiers, there's nothing else to do. Just notify 965 // the reader that we've finished loading this identifier. 966 Reader.SetIdentifierInfo(ID, II); 967 return II; 968 } 969 970 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d); 971 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d); 972 bool CPlusPlusOperatorKeyword = readBit(Bits); 973 bool HasRevertedTokenIDToIdentifier = readBit(Bits); 974 bool Poisoned = readBit(Bits); 975 bool ExtensionToken = readBit(Bits); 976 bool HadMacroDefinition = readBit(Bits); 977 978 assert(Bits == 0 && "Extra bits in the identifier?"); 979 DataLen -= 8; 980 981 // Set or check the various bits in the IdentifierInfo structure. 982 // Token IDs are read-only. 983 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier) 984 II->revertTokenIDToIdentifier(); 985 if (!F.isModule()) 986 II->setObjCOrBuiltinID(ObjCOrBuiltinID); 987 assert(II->isExtensionToken() == ExtensionToken && 988 "Incorrect extension token flag"); 989 (void)ExtensionToken; 990 if (Poisoned) 991 II->setIsPoisoned(true); 992 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword && 993 "Incorrect C++ operator keyword flag"); 994 (void)CPlusPlusOperatorKeyword; 995 996 // If this identifier is a macro, deserialize the macro 997 // definition. 998 if (HadMacroDefinition) { 999 uint32_t MacroDirectivesOffset = 1000 endian::readNext<uint32_t, little, unaligned>(d); 1001 DataLen -= 4; 1002 1003 Reader.addPendingMacro(II, &F, MacroDirectivesOffset); 1004 } 1005 1006 Reader.SetIdentifierInfo(ID, II); 1007 1008 // Read all of the declarations visible at global scope with this 1009 // name. 1010 if (DataLen > 0) { 1011 SmallVector<uint32_t, 4> DeclIDs; 1012 for (; DataLen > 0; DataLen -= 4) 1013 DeclIDs.push_back(Reader.getGlobalDeclID( 1014 F, endian::readNext<uint32_t, little, unaligned>(d))); 1015 Reader.SetGloballyVisibleDecls(II, DeclIDs); 1016 } 1017 1018 return II; 1019 } 1020 1021 DeclarationNameKey::DeclarationNameKey(DeclarationName Name) 1022 : Kind(Name.getNameKind()) { 1023 switch (Kind) { 1024 case DeclarationName::Identifier: 1025 Data = (uint64_t)Name.getAsIdentifierInfo(); 1026 break; 1027 case DeclarationName::ObjCZeroArgSelector: 1028 case DeclarationName::ObjCOneArgSelector: 1029 case DeclarationName::ObjCMultiArgSelector: 1030 Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr(); 1031 break; 1032 case DeclarationName::CXXOperatorName: 1033 Data = Name.getCXXOverloadedOperator(); 1034 break; 1035 case DeclarationName::CXXLiteralOperatorName: 1036 Data = (uint64_t)Name.getCXXLiteralIdentifier(); 1037 break; 1038 case DeclarationName::CXXDeductionGuideName: 1039 Data = (uint64_t)Name.getCXXDeductionGuideTemplate() 1040 ->getDeclName().getAsIdentifierInfo(); 1041 break; 1042 case DeclarationName::CXXConstructorName: 1043 case DeclarationName::CXXDestructorName: 1044 case DeclarationName::CXXConversionFunctionName: 1045 case DeclarationName::CXXUsingDirective: 1046 Data = 0; 1047 break; 1048 } 1049 } 1050 1051 unsigned DeclarationNameKey::getHash() const { 1052 llvm::FoldingSetNodeID ID; 1053 ID.AddInteger(Kind); 1054 1055 switch (Kind) { 1056 case DeclarationName::Identifier: 1057 case DeclarationName::CXXLiteralOperatorName: 1058 case DeclarationName::CXXDeductionGuideName: 1059 ID.AddString(((IdentifierInfo*)Data)->getName()); 1060 break; 1061 case DeclarationName::ObjCZeroArgSelector: 1062 case DeclarationName::ObjCOneArgSelector: 1063 case DeclarationName::ObjCMultiArgSelector: 1064 ID.AddInteger(serialization::ComputeHash(Selector(Data))); 1065 break; 1066 case DeclarationName::CXXOperatorName: 1067 ID.AddInteger((OverloadedOperatorKind)Data); 1068 break; 1069 case DeclarationName::CXXConstructorName: 1070 case DeclarationName::CXXDestructorName: 1071 case DeclarationName::CXXConversionFunctionName: 1072 case DeclarationName::CXXUsingDirective: 1073 break; 1074 } 1075 1076 return ID.ComputeHash(); 1077 } 1078 1079 ModuleFile * 1080 ASTDeclContextNameLookupTrait::ReadFileRef(const unsigned char *&d) { 1081 using namespace llvm::support; 1082 1083 uint32_t ModuleFileID = endian::readNext<uint32_t, little, unaligned>(d); 1084 return Reader.getLocalModuleFile(F, ModuleFileID); 1085 } 1086 1087 std::pair<unsigned, unsigned> 1088 ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char *&d) { 1089 using namespace llvm::support; 1090 1091 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d); 1092 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d); 1093 return std::make_pair(KeyLen, DataLen); 1094 } 1095 1096 ASTDeclContextNameLookupTrait::internal_key_type 1097 ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) { 1098 using namespace llvm::support; 1099 1100 auto Kind = (DeclarationName::NameKind)*d++; 1101 uint64_t Data; 1102 switch (Kind) { 1103 case DeclarationName::Identifier: 1104 case DeclarationName::CXXLiteralOperatorName: 1105 case DeclarationName::CXXDeductionGuideName: 1106 Data = (uint64_t)Reader.getLocalIdentifier( 1107 F, endian::readNext<uint32_t, little, unaligned>(d)); 1108 break; 1109 case DeclarationName::ObjCZeroArgSelector: 1110 case DeclarationName::ObjCOneArgSelector: 1111 case DeclarationName::ObjCMultiArgSelector: 1112 Data = 1113 (uint64_t)Reader.getLocalSelector( 1114 F, endian::readNext<uint32_t, little, unaligned>( 1115 d)).getAsOpaquePtr(); 1116 break; 1117 case DeclarationName::CXXOperatorName: 1118 Data = *d++; // OverloadedOperatorKind 1119 break; 1120 case DeclarationName::CXXConstructorName: 1121 case DeclarationName::CXXDestructorName: 1122 case DeclarationName::CXXConversionFunctionName: 1123 case DeclarationName::CXXUsingDirective: 1124 Data = 0; 1125 break; 1126 } 1127 1128 return DeclarationNameKey(Kind, Data); 1129 } 1130 1131 void ASTDeclContextNameLookupTrait::ReadDataInto(internal_key_type, 1132 const unsigned char *d, 1133 unsigned DataLen, 1134 data_type_builder &Val) { 1135 using namespace llvm::support; 1136 1137 for (unsigned NumDecls = DataLen / 4; NumDecls; --NumDecls) { 1138 uint32_t LocalID = endian::readNext<uint32_t, little, unaligned>(d); 1139 Val.insert(Reader.getGlobalDeclID(F, LocalID)); 1140 } 1141 } 1142 1143 bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M, 1144 BitstreamCursor &Cursor, 1145 uint64_t Offset, 1146 DeclContext *DC) { 1147 assert(Offset != 0); 1148 1149 SavedStreamPosition SavedPosition(Cursor); 1150 if (llvm::Error Err = Cursor.JumpToBit(Offset)) { 1151 Error(std::move(Err)); 1152 return true; 1153 } 1154 1155 RecordData Record; 1156 StringRef Blob; 1157 Expected<unsigned> MaybeCode = Cursor.ReadCode(); 1158 if (!MaybeCode) { 1159 Error(MaybeCode.takeError()); 1160 return true; 1161 } 1162 unsigned Code = MaybeCode.get(); 1163 1164 Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob); 1165 if (!MaybeRecCode) { 1166 Error(MaybeRecCode.takeError()); 1167 return true; 1168 } 1169 unsigned RecCode = MaybeRecCode.get(); 1170 if (RecCode != DECL_CONTEXT_LEXICAL) { 1171 Error("Expected lexical block"); 1172 return true; 1173 } 1174 1175 assert(!isa<TranslationUnitDecl>(DC) && 1176 "expected a TU_UPDATE_LEXICAL record for TU"); 1177 // If we are handling a C++ class template instantiation, we can see multiple 1178 // lexical updates for the same record. It's important that we select only one 1179 // of them, so that field numbering works properly. Just pick the first one we 1180 // see. 1181 auto &Lex = LexicalDecls[DC]; 1182 if (!Lex.first) { 1183 Lex = std::make_pair( 1184 &M, llvm::makeArrayRef( 1185 reinterpret_cast<const llvm::support::unaligned_uint32_t *>( 1186 Blob.data()), 1187 Blob.size() / 4)); 1188 } 1189 DC->setHasExternalLexicalStorage(true); 1190 return false; 1191 } 1192 1193 bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M, 1194 BitstreamCursor &Cursor, 1195 uint64_t Offset, 1196 DeclID ID) { 1197 assert(Offset != 0); 1198 1199 SavedStreamPosition SavedPosition(Cursor); 1200 if (llvm::Error Err = Cursor.JumpToBit(Offset)) { 1201 Error(std::move(Err)); 1202 return true; 1203 } 1204 1205 RecordData Record; 1206 StringRef Blob; 1207 Expected<unsigned> MaybeCode = Cursor.ReadCode(); 1208 if (!MaybeCode) { 1209 Error(MaybeCode.takeError()); 1210 return true; 1211 } 1212 unsigned Code = MaybeCode.get(); 1213 1214 Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob); 1215 if (!MaybeRecCode) { 1216 Error(MaybeRecCode.takeError()); 1217 return true; 1218 } 1219 unsigned RecCode = MaybeRecCode.get(); 1220 if (RecCode != DECL_CONTEXT_VISIBLE) { 1221 Error("Expected visible lookup table block"); 1222 return true; 1223 } 1224 1225 // We can't safely determine the primary context yet, so delay attaching the 1226 // lookup table until we're done with recursive deserialization. 1227 auto *Data = (const unsigned char*)Blob.data(); 1228 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&M, Data}); 1229 return false; 1230 } 1231 1232 void ASTReader::Error(StringRef Msg) const { 1233 Error(diag::err_fe_pch_malformed, Msg); 1234 if (PP.getLangOpts().Modules && !Diags.isDiagnosticInFlight() && 1235 !PP.getHeaderSearchInfo().getModuleCachePath().empty()) { 1236 Diag(diag::note_module_cache_path) 1237 << PP.getHeaderSearchInfo().getModuleCachePath(); 1238 } 1239 } 1240 1241 void ASTReader::Error(unsigned DiagID, StringRef Arg1, StringRef Arg2, 1242 StringRef Arg3) const { 1243 if (Diags.isDiagnosticInFlight()) 1244 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2, Arg3); 1245 else 1246 Diag(DiagID) << Arg1 << Arg2 << Arg3; 1247 } 1248 1249 void ASTReader::Error(llvm::Error &&Err) const { 1250 Error(toString(std::move(Err))); 1251 } 1252 1253 //===----------------------------------------------------------------------===// 1254 // Source Manager Deserialization 1255 //===----------------------------------------------------------------------===// 1256 1257 /// Read the line table in the source manager block. 1258 /// \returns true if there was an error. 1259 bool ASTReader::ParseLineTable(ModuleFile &F, 1260 const RecordData &Record) { 1261 unsigned Idx = 0; 1262 LineTableInfo &LineTable = SourceMgr.getLineTable(); 1263 1264 // Parse the file names 1265 std::map<int, int> FileIDs; 1266 FileIDs[-1] = -1; // For unspecified filenames. 1267 for (unsigned I = 0; Record[Idx]; ++I) { 1268 // Extract the file name 1269 auto Filename = ReadPath(F, Record, Idx); 1270 FileIDs[I] = LineTable.getLineTableFilenameID(Filename); 1271 } 1272 ++Idx; 1273 1274 // Parse the line entries 1275 std::vector<LineEntry> Entries; 1276 while (Idx < Record.size()) { 1277 int FID = Record[Idx++]; 1278 assert(FID >= 0 && "Serialized line entries for non-local file."); 1279 // Remap FileID from 1-based old view. 1280 FID += F.SLocEntryBaseID - 1; 1281 1282 // Extract the line entries 1283 unsigned NumEntries = Record[Idx++]; 1284 assert(NumEntries && "no line entries for file ID"); 1285 Entries.clear(); 1286 Entries.reserve(NumEntries); 1287 for (unsigned I = 0; I != NumEntries; ++I) { 1288 unsigned FileOffset = Record[Idx++]; 1289 unsigned LineNo = Record[Idx++]; 1290 int FilenameID = FileIDs[Record[Idx++]]; 1291 SrcMgr::CharacteristicKind FileKind 1292 = (SrcMgr::CharacteristicKind)Record[Idx++]; 1293 unsigned IncludeOffset = Record[Idx++]; 1294 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID, 1295 FileKind, IncludeOffset)); 1296 } 1297 LineTable.AddEntry(FileID::get(FID), Entries); 1298 } 1299 1300 return false; 1301 } 1302 1303 /// Read a source manager block 1304 bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) { 1305 using namespace SrcMgr; 1306 1307 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor; 1308 1309 // Set the source-location entry cursor to the current position in 1310 // the stream. This cursor will be used to read the contents of the 1311 // source manager block initially, and then lazily read 1312 // source-location entries as needed. 1313 SLocEntryCursor = F.Stream; 1314 1315 // The stream itself is going to skip over the source manager block. 1316 if (llvm::Error Err = F.Stream.SkipBlock()) { 1317 Error(std::move(Err)); 1318 return true; 1319 } 1320 1321 // Enter the source manager block. 1322 if (llvm::Error Err = 1323 SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) { 1324 Error(std::move(Err)); 1325 return true; 1326 } 1327 F.SourceManagerBlockStartOffset = SLocEntryCursor.GetCurrentBitNo(); 1328 1329 RecordData Record; 1330 while (true) { 1331 Expected<llvm::BitstreamEntry> MaybeE = 1332 SLocEntryCursor.advanceSkippingSubblocks(); 1333 if (!MaybeE) { 1334 Error(MaybeE.takeError()); 1335 return true; 1336 } 1337 llvm::BitstreamEntry E = MaybeE.get(); 1338 1339 switch (E.Kind) { 1340 case llvm::BitstreamEntry::SubBlock: // Handled for us already. 1341 case llvm::BitstreamEntry::Error: 1342 Error("malformed block record in AST file"); 1343 return true; 1344 case llvm::BitstreamEntry::EndBlock: 1345 return false; 1346 case llvm::BitstreamEntry::Record: 1347 // The interesting case. 1348 break; 1349 } 1350 1351 // Read a record. 1352 Record.clear(); 1353 StringRef Blob; 1354 Expected<unsigned> MaybeRecord = 1355 SLocEntryCursor.readRecord(E.ID, Record, &Blob); 1356 if (!MaybeRecord) { 1357 Error(MaybeRecord.takeError()); 1358 return true; 1359 } 1360 switch (MaybeRecord.get()) { 1361 default: // Default behavior: ignore. 1362 break; 1363 1364 case SM_SLOC_FILE_ENTRY: 1365 case SM_SLOC_BUFFER_ENTRY: 1366 case SM_SLOC_EXPANSION_ENTRY: 1367 // Once we hit one of the source location entries, we're done. 1368 return false; 1369 } 1370 } 1371 } 1372 1373 /// If a header file is not found at the path that we expect it to be 1374 /// and the PCH file was moved from its original location, try to resolve the 1375 /// file by assuming that header+PCH were moved together and the header is in 1376 /// the same place relative to the PCH. 1377 static std::string 1378 resolveFileRelativeToOriginalDir(const std::string &Filename, 1379 const std::string &OriginalDir, 1380 const std::string &CurrDir) { 1381 assert(OriginalDir != CurrDir && 1382 "No point trying to resolve the file if the PCH dir didn't change"); 1383 1384 using namespace llvm::sys; 1385 1386 SmallString<128> filePath(Filename); 1387 fs::make_absolute(filePath); 1388 assert(path::is_absolute(OriginalDir)); 1389 SmallString<128> currPCHPath(CurrDir); 1390 1391 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)), 1392 fileDirE = path::end(path::parent_path(filePath)); 1393 path::const_iterator origDirI = path::begin(OriginalDir), 1394 origDirE = path::end(OriginalDir); 1395 // Skip the common path components from filePath and OriginalDir. 1396 while (fileDirI != fileDirE && origDirI != origDirE && 1397 *fileDirI == *origDirI) { 1398 ++fileDirI; 1399 ++origDirI; 1400 } 1401 for (; origDirI != origDirE; ++origDirI) 1402 path::append(currPCHPath, ".."); 1403 path::append(currPCHPath, fileDirI, fileDirE); 1404 path::append(currPCHPath, path::filename(Filename)); 1405 return std::string(currPCHPath.str()); 1406 } 1407 1408 bool ASTReader::ReadSLocEntry(int ID) { 1409 if (ID == 0) 1410 return false; 1411 1412 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) { 1413 Error("source location entry ID out-of-range for AST file"); 1414 return true; 1415 } 1416 1417 // Local helper to read the (possibly-compressed) buffer data following the 1418 // entry record. 1419 auto ReadBuffer = [this]( 1420 BitstreamCursor &SLocEntryCursor, 1421 StringRef Name) -> std::unique_ptr<llvm::MemoryBuffer> { 1422 RecordData Record; 1423 StringRef Blob; 1424 Expected<unsigned> MaybeCode = SLocEntryCursor.ReadCode(); 1425 if (!MaybeCode) { 1426 Error(MaybeCode.takeError()); 1427 return nullptr; 1428 } 1429 unsigned Code = MaybeCode.get(); 1430 1431 Expected<unsigned> MaybeRecCode = 1432 SLocEntryCursor.readRecord(Code, Record, &Blob); 1433 if (!MaybeRecCode) { 1434 Error(MaybeRecCode.takeError()); 1435 return nullptr; 1436 } 1437 unsigned RecCode = MaybeRecCode.get(); 1438 1439 if (RecCode == SM_SLOC_BUFFER_BLOB_COMPRESSED) { 1440 if (!llvm::zlib::isAvailable()) { 1441 Error("zlib is not available"); 1442 return nullptr; 1443 } 1444 SmallString<0> Uncompressed; 1445 if (llvm::Error E = 1446 llvm::zlib::uncompress(Blob, Uncompressed, Record[0])) { 1447 Error("could not decompress embedded file contents: " + 1448 llvm::toString(std::move(E))); 1449 return nullptr; 1450 } 1451 return llvm::MemoryBuffer::getMemBufferCopy(Uncompressed, Name); 1452 } else if (RecCode == SM_SLOC_BUFFER_BLOB) { 1453 return llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name, true); 1454 } else { 1455 Error("AST record has invalid code"); 1456 return nullptr; 1457 } 1458 }; 1459 1460 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second; 1461 if (llvm::Error Err = F->SLocEntryCursor.JumpToBit( 1462 F->SLocEntryOffsetsBase + 1463 F->SLocEntryOffsets[ID - F->SLocEntryBaseID])) { 1464 Error(std::move(Err)); 1465 return true; 1466 } 1467 1468 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor; 1469 unsigned BaseOffset = F->SLocEntryBaseOffset; 1470 1471 ++NumSLocEntriesRead; 1472 Expected<llvm::BitstreamEntry> MaybeEntry = SLocEntryCursor.advance(); 1473 if (!MaybeEntry) { 1474 Error(MaybeEntry.takeError()); 1475 return true; 1476 } 1477 llvm::BitstreamEntry Entry = MaybeEntry.get(); 1478 1479 if (Entry.Kind != llvm::BitstreamEntry::Record) { 1480 Error("incorrectly-formatted source location entry in AST file"); 1481 return true; 1482 } 1483 1484 RecordData Record; 1485 StringRef Blob; 1486 Expected<unsigned> MaybeSLOC = 1487 SLocEntryCursor.readRecord(Entry.ID, Record, &Blob); 1488 if (!MaybeSLOC) { 1489 Error(MaybeSLOC.takeError()); 1490 return true; 1491 } 1492 switch (MaybeSLOC.get()) { 1493 default: 1494 Error("incorrectly-formatted source location entry in AST file"); 1495 return true; 1496 1497 case SM_SLOC_FILE_ENTRY: { 1498 // We will detect whether a file changed and return 'Failure' for it, but 1499 // we will also try to fail gracefully by setting up the SLocEntry. 1500 unsigned InputID = Record[4]; 1501 InputFile IF = getInputFile(*F, InputID); 1502 const FileEntry *File = IF.getFile(); 1503 bool OverriddenBuffer = IF.isOverridden(); 1504 1505 // Note that we only check if a File was returned. If it was out-of-date 1506 // we have complained but we will continue creating a FileID to recover 1507 // gracefully. 1508 if (!File) 1509 return true; 1510 1511 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]); 1512 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) { 1513 // This is the module's main file. 1514 IncludeLoc = getImportLocation(F); 1515 } 1516 SrcMgr::CharacteristicKind 1517 FileCharacter = (SrcMgr::CharacteristicKind)Record[2]; 1518 // FIXME: The FileID should be created from the FileEntryRef. 1519 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter, 1520 ID, BaseOffset + Record[0]); 1521 SrcMgr::FileInfo &FileInfo = 1522 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile()); 1523 FileInfo.NumCreatedFIDs = Record[5]; 1524 if (Record[3]) 1525 FileInfo.setHasLineDirectives(); 1526 1527 unsigned NumFileDecls = Record[7]; 1528 if (NumFileDecls && ContextObj) { 1529 const DeclID *FirstDecl = F->FileSortedDecls + Record[6]; 1530 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?"); 1531 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl, 1532 NumFileDecls)); 1533 } 1534 1535 const SrcMgr::ContentCache &ContentCache = 1536 SourceMgr.getOrCreateContentCache(File, isSystem(FileCharacter)); 1537 if (OverriddenBuffer && !ContentCache.BufferOverridden && 1538 ContentCache.ContentsEntry == ContentCache.OrigEntry && 1539 !ContentCache.getBufferIfLoaded()) { 1540 auto Buffer = ReadBuffer(SLocEntryCursor, File->getName()); 1541 if (!Buffer) 1542 return true; 1543 SourceMgr.overrideFileContents(File, std::move(Buffer)); 1544 } 1545 1546 break; 1547 } 1548 1549 case SM_SLOC_BUFFER_ENTRY: { 1550 const char *Name = Blob.data(); 1551 unsigned Offset = Record[0]; 1552 SrcMgr::CharacteristicKind 1553 FileCharacter = (SrcMgr::CharacteristicKind)Record[2]; 1554 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]); 1555 if (IncludeLoc.isInvalid() && F->isModule()) { 1556 IncludeLoc = getImportLocation(F); 1557 } 1558 1559 auto Buffer = ReadBuffer(SLocEntryCursor, Name); 1560 if (!Buffer) 1561 return true; 1562 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID, 1563 BaseOffset + Offset, IncludeLoc); 1564 break; 1565 } 1566 1567 case SM_SLOC_EXPANSION_ENTRY: { 1568 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]); 1569 SourceMgr.createExpansionLoc(SpellingLoc, 1570 ReadSourceLocation(*F, Record[2]), 1571 ReadSourceLocation(*F, Record[3]), 1572 Record[5], 1573 Record[4], 1574 ID, 1575 BaseOffset + Record[0]); 1576 break; 1577 } 1578 } 1579 1580 return false; 1581 } 1582 1583 std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) { 1584 if (ID == 0) 1585 return std::make_pair(SourceLocation(), ""); 1586 1587 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) { 1588 Error("source location entry ID out-of-range for AST file"); 1589 return std::make_pair(SourceLocation(), ""); 1590 } 1591 1592 // Find which module file this entry lands in. 1593 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second; 1594 if (!M->isModule()) 1595 return std::make_pair(SourceLocation(), ""); 1596 1597 // FIXME: Can we map this down to a particular submodule? That would be 1598 // ideal. 1599 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName)); 1600 } 1601 1602 /// Find the location where the module F is imported. 1603 SourceLocation ASTReader::getImportLocation(ModuleFile *F) { 1604 if (F->ImportLoc.isValid()) 1605 return F->ImportLoc; 1606 1607 // Otherwise we have a PCH. It's considered to be "imported" at the first 1608 // location of its includer. 1609 if (F->ImportedBy.empty() || !F->ImportedBy[0]) { 1610 // Main file is the importer. 1611 assert(SourceMgr.getMainFileID().isValid() && "missing main file"); 1612 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID()); 1613 } 1614 return F->ImportedBy[0]->FirstLoc; 1615 } 1616 1617 /// Enter a subblock of the specified BlockID with the specified cursor. Read 1618 /// the abbreviations that are at the top of the block and then leave the cursor 1619 /// pointing into the block. 1620 bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID, 1621 uint64_t *StartOfBlockOffset) { 1622 if (llvm::Error Err = Cursor.EnterSubBlock(BlockID)) { 1623 // FIXME this drops errors on the floor. 1624 consumeError(std::move(Err)); 1625 return true; 1626 } 1627 1628 if (StartOfBlockOffset) 1629 *StartOfBlockOffset = Cursor.GetCurrentBitNo(); 1630 1631 while (true) { 1632 uint64_t Offset = Cursor.GetCurrentBitNo(); 1633 Expected<unsigned> MaybeCode = Cursor.ReadCode(); 1634 if (!MaybeCode) { 1635 // FIXME this drops errors on the floor. 1636 consumeError(MaybeCode.takeError()); 1637 return true; 1638 } 1639 unsigned Code = MaybeCode.get(); 1640 1641 // We expect all abbrevs to be at the start of the block. 1642 if (Code != llvm::bitc::DEFINE_ABBREV) { 1643 if (llvm::Error Err = Cursor.JumpToBit(Offset)) { 1644 // FIXME this drops errors on the floor. 1645 consumeError(std::move(Err)); 1646 return true; 1647 } 1648 return false; 1649 } 1650 if (llvm::Error Err = Cursor.ReadAbbrevRecord()) { 1651 // FIXME this drops errors on the floor. 1652 consumeError(std::move(Err)); 1653 return true; 1654 } 1655 } 1656 } 1657 1658 Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record, 1659 unsigned &Idx) { 1660 Token Tok; 1661 Tok.startToken(); 1662 Tok.setLocation(ReadSourceLocation(F, Record, Idx)); 1663 Tok.setLength(Record[Idx++]); 1664 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++])) 1665 Tok.setIdentifierInfo(II); 1666 Tok.setKind((tok::TokenKind)Record[Idx++]); 1667 Tok.setFlag((Token::TokenFlags)Record[Idx++]); 1668 return Tok; 1669 } 1670 1671 MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) { 1672 BitstreamCursor &Stream = F.MacroCursor; 1673 1674 // Keep track of where we are in the stream, then jump back there 1675 // after reading this macro. 1676 SavedStreamPosition SavedPosition(Stream); 1677 1678 if (llvm::Error Err = Stream.JumpToBit(Offset)) { 1679 // FIXME this drops errors on the floor. 1680 consumeError(std::move(Err)); 1681 return nullptr; 1682 } 1683 RecordData Record; 1684 SmallVector<IdentifierInfo*, 16> MacroParams; 1685 MacroInfo *Macro = nullptr; 1686 1687 while (true) { 1688 // Advance to the next record, but if we get to the end of the block, don't 1689 // pop it (removing all the abbreviations from the cursor) since we want to 1690 // be able to reseek within the block and read entries. 1691 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd; 1692 Expected<llvm::BitstreamEntry> MaybeEntry = 1693 Stream.advanceSkippingSubblocks(Flags); 1694 if (!MaybeEntry) { 1695 Error(MaybeEntry.takeError()); 1696 return Macro; 1697 } 1698 llvm::BitstreamEntry Entry = MaybeEntry.get(); 1699 1700 switch (Entry.Kind) { 1701 case llvm::BitstreamEntry::SubBlock: // Handled for us already. 1702 case llvm::BitstreamEntry::Error: 1703 Error("malformed block record in AST file"); 1704 return Macro; 1705 case llvm::BitstreamEntry::EndBlock: 1706 return Macro; 1707 case llvm::BitstreamEntry::Record: 1708 // The interesting case. 1709 break; 1710 } 1711 1712 // Read a record. 1713 Record.clear(); 1714 PreprocessorRecordTypes RecType; 1715 if (Expected<unsigned> MaybeRecType = Stream.readRecord(Entry.ID, Record)) 1716 RecType = (PreprocessorRecordTypes)MaybeRecType.get(); 1717 else { 1718 Error(MaybeRecType.takeError()); 1719 return Macro; 1720 } 1721 switch (RecType) { 1722 case PP_MODULE_MACRO: 1723 case PP_MACRO_DIRECTIVE_HISTORY: 1724 return Macro; 1725 1726 case PP_MACRO_OBJECT_LIKE: 1727 case PP_MACRO_FUNCTION_LIKE: { 1728 // If we already have a macro, that means that we've hit the end 1729 // of the definition of the macro we were looking for. We're 1730 // done. 1731 if (Macro) 1732 return Macro; 1733 1734 unsigned NextIndex = 1; // Skip identifier ID. 1735 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex); 1736 MacroInfo *MI = PP.AllocateMacroInfo(Loc); 1737 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex)); 1738 MI->setIsUsed(Record[NextIndex++]); 1739 MI->setUsedForHeaderGuard(Record[NextIndex++]); 1740 1741 if (RecType == PP_MACRO_FUNCTION_LIKE) { 1742 // Decode function-like macro info. 1743 bool isC99VarArgs = Record[NextIndex++]; 1744 bool isGNUVarArgs = Record[NextIndex++]; 1745 bool hasCommaPasting = Record[NextIndex++]; 1746 MacroParams.clear(); 1747 unsigned NumArgs = Record[NextIndex++]; 1748 for (unsigned i = 0; i != NumArgs; ++i) 1749 MacroParams.push_back(getLocalIdentifier(F, Record[NextIndex++])); 1750 1751 // Install function-like macro info. 1752 MI->setIsFunctionLike(); 1753 if (isC99VarArgs) MI->setIsC99Varargs(); 1754 if (isGNUVarArgs) MI->setIsGNUVarargs(); 1755 if (hasCommaPasting) MI->setHasCommaPasting(); 1756 MI->setParameterList(MacroParams, PP.getPreprocessorAllocator()); 1757 } 1758 1759 // Remember that we saw this macro last so that we add the tokens that 1760 // form its body to it. 1761 Macro = MI; 1762 1763 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() && 1764 Record[NextIndex]) { 1765 // We have a macro definition. Register the association 1766 PreprocessedEntityID 1767 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]); 1768 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord(); 1769 PreprocessingRecord::PPEntityID PPID = 1770 PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true); 1771 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>( 1772 PPRec.getPreprocessedEntity(PPID)); 1773 if (PPDef) 1774 PPRec.RegisterMacroDefinition(Macro, PPDef); 1775 } 1776 1777 ++NumMacrosRead; 1778 break; 1779 } 1780 1781 case PP_TOKEN: { 1782 // If we see a TOKEN before a PP_MACRO_*, then the file is 1783 // erroneous, just pretend we didn't see this. 1784 if (!Macro) break; 1785 1786 unsigned Idx = 0; 1787 Token Tok = ReadToken(F, Record, Idx); 1788 Macro->AddTokenToBody(Tok); 1789 break; 1790 } 1791 } 1792 } 1793 } 1794 1795 PreprocessedEntityID 1796 ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, 1797 unsigned LocalID) const { 1798 if (!M.ModuleOffsetMap.empty()) 1799 ReadModuleOffsetMap(M); 1800 1801 ContinuousRangeMap<uint32_t, int, 2>::const_iterator 1802 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS); 1803 assert(I != M.PreprocessedEntityRemap.end() 1804 && "Invalid index into preprocessed entity index remap"); 1805 1806 return LocalID + I->second; 1807 } 1808 1809 unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) { 1810 return llvm::hash_combine(ikey.Size, ikey.ModTime); 1811 } 1812 1813 HeaderFileInfoTrait::internal_key_type 1814 HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) { 1815 internal_key_type ikey = {FE->getSize(), 1816 M.HasTimestamps ? FE->getModificationTime() : 0, 1817 FE->getName(), /*Imported*/ false}; 1818 return ikey; 1819 } 1820 1821 bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) { 1822 if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime)) 1823 return false; 1824 1825 if (llvm::sys::path::is_absolute(a.Filename) && a.Filename == b.Filename) 1826 return true; 1827 1828 // Determine whether the actual files are equivalent. 1829 FileManager &FileMgr = Reader.getFileManager(); 1830 auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* { 1831 if (!Key.Imported) { 1832 if (auto File = FileMgr.getFile(Key.Filename)) 1833 return *File; 1834 return nullptr; 1835 } 1836 1837 std::string Resolved = std::string(Key.Filename); 1838 Reader.ResolveImportedPath(M, Resolved); 1839 if (auto File = FileMgr.getFile(Resolved)) 1840 return *File; 1841 return nullptr; 1842 }; 1843 1844 const FileEntry *FEA = GetFile(a); 1845 const FileEntry *FEB = GetFile(b); 1846 return FEA && FEA == FEB; 1847 } 1848 1849 std::pair<unsigned, unsigned> 1850 HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) { 1851 using namespace llvm::support; 1852 1853 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d); 1854 unsigned DataLen = (unsigned) *d++; 1855 return std::make_pair(KeyLen, DataLen); 1856 } 1857 1858 HeaderFileInfoTrait::internal_key_type 1859 HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) { 1860 using namespace llvm::support; 1861 1862 internal_key_type ikey; 1863 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d)); 1864 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d)); 1865 ikey.Filename = (const char *)d; 1866 ikey.Imported = true; 1867 return ikey; 1868 } 1869 1870 HeaderFileInfoTrait::data_type 1871 HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d, 1872 unsigned DataLen) { 1873 using namespace llvm::support; 1874 1875 const unsigned char *End = d + DataLen; 1876 HeaderFileInfo HFI; 1877 unsigned Flags = *d++; 1878 // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp. 1879 HFI.isImport |= (Flags >> 5) & 0x01; 1880 HFI.isPragmaOnce |= (Flags >> 4) & 0x01; 1881 HFI.DirInfo = (Flags >> 1) & 0x07; 1882 HFI.IndexHeaderMapHeader = Flags & 0x01; 1883 // FIXME: Find a better way to handle this. Maybe just store a 1884 // "has been included" flag? 1885 HFI.NumIncludes = std::max(endian::readNext<uint16_t, little, unaligned>(d), 1886 HFI.NumIncludes); 1887 HFI.ControllingMacroID = Reader.getGlobalIdentifierID( 1888 M, endian::readNext<uint32_t, little, unaligned>(d)); 1889 if (unsigned FrameworkOffset = 1890 endian::readNext<uint32_t, little, unaligned>(d)) { 1891 // The framework offset is 1 greater than the actual offset, 1892 // since 0 is used as an indicator for "no framework name". 1893 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1); 1894 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName); 1895 } 1896 1897 assert((End - d) % 4 == 0 && 1898 "Wrong data length in HeaderFileInfo deserialization"); 1899 while (d != End) { 1900 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d); 1901 auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 3); 1902 LocalSMID >>= 2; 1903 1904 // This header is part of a module. Associate it with the module to enable 1905 // implicit module import. 1906 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID); 1907 Module *Mod = Reader.getSubmodule(GlobalSMID); 1908 FileManager &FileMgr = Reader.getFileManager(); 1909 ModuleMap &ModMap = 1910 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap(); 1911 1912 std::string Filename = std::string(key.Filename); 1913 if (key.Imported) 1914 Reader.ResolveImportedPath(M, Filename); 1915 // FIXME: This is not always the right filename-as-written, but we're not 1916 // going to use this information to rebuild the module, so it doesn't make 1917 // a lot of difference. 1918 Module::Header H = {std::string(key.Filename), *FileMgr.getFile(Filename)}; 1919 ModMap.addHeader(Mod, H, HeaderRole, /*Imported*/true); 1920 HFI.isModuleHeader |= !(HeaderRole & ModuleMap::TextualHeader); 1921 } 1922 1923 // This HeaderFileInfo was externally loaded. 1924 HFI.External = true; 1925 HFI.IsValid = true; 1926 return HFI; 1927 } 1928 1929 void ASTReader::addPendingMacro(IdentifierInfo *II, ModuleFile *M, 1930 uint32_t MacroDirectivesOffset) { 1931 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard"); 1932 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset)); 1933 } 1934 1935 void ASTReader::ReadDefinedMacros() { 1936 // Note that we are loading defined macros. 1937 Deserializing Macros(this); 1938 1939 for (ModuleFile &I : llvm::reverse(ModuleMgr)) { 1940 BitstreamCursor &MacroCursor = I.MacroCursor; 1941 1942 // If there was no preprocessor block, skip this file. 1943 if (MacroCursor.getBitcodeBytes().empty()) 1944 continue; 1945 1946 BitstreamCursor Cursor = MacroCursor; 1947 if (llvm::Error Err = Cursor.JumpToBit(I.MacroStartOffset)) { 1948 Error(std::move(Err)); 1949 return; 1950 } 1951 1952 RecordData Record; 1953 while (true) { 1954 Expected<llvm::BitstreamEntry> MaybeE = Cursor.advanceSkippingSubblocks(); 1955 if (!MaybeE) { 1956 Error(MaybeE.takeError()); 1957 return; 1958 } 1959 llvm::BitstreamEntry E = MaybeE.get(); 1960 1961 switch (E.Kind) { 1962 case llvm::BitstreamEntry::SubBlock: // Handled for us already. 1963 case llvm::BitstreamEntry::Error: 1964 Error("malformed block record in AST file"); 1965 return; 1966 case llvm::BitstreamEntry::EndBlock: 1967 goto NextCursor; 1968 1969 case llvm::BitstreamEntry::Record: { 1970 Record.clear(); 1971 Expected<unsigned> MaybeRecord = Cursor.readRecord(E.ID, Record); 1972 if (!MaybeRecord) { 1973 Error(MaybeRecord.takeError()); 1974 return; 1975 } 1976 switch (MaybeRecord.get()) { 1977 default: // Default behavior: ignore. 1978 break; 1979 1980 case PP_MACRO_OBJECT_LIKE: 1981 case PP_MACRO_FUNCTION_LIKE: { 1982 IdentifierInfo *II = getLocalIdentifier(I, Record[0]); 1983 if (II->isOutOfDate()) 1984 updateOutOfDateIdentifier(*II); 1985 break; 1986 } 1987 1988 case PP_TOKEN: 1989 // Ignore tokens. 1990 break; 1991 } 1992 break; 1993 } 1994 } 1995 } 1996 NextCursor: ; 1997 } 1998 } 1999 2000 namespace { 2001 2002 /// Visitor class used to look up identifirs in an AST file. 2003 class IdentifierLookupVisitor { 2004 StringRef Name; 2005 unsigned NameHash; 2006 unsigned PriorGeneration; 2007 unsigned &NumIdentifierLookups; 2008 unsigned &NumIdentifierLookupHits; 2009 IdentifierInfo *Found = nullptr; 2010 2011 public: 2012 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration, 2013 unsigned &NumIdentifierLookups, 2014 unsigned &NumIdentifierLookupHits) 2015 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)), 2016 PriorGeneration(PriorGeneration), 2017 NumIdentifierLookups(NumIdentifierLookups), 2018 NumIdentifierLookupHits(NumIdentifierLookupHits) {} 2019 2020 bool operator()(ModuleFile &M) { 2021 // If we've already searched this module file, skip it now. 2022 if (M.Generation <= PriorGeneration) 2023 return true; 2024 2025 ASTIdentifierLookupTable *IdTable 2026 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable; 2027 if (!IdTable) 2028 return false; 2029 2030 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M, 2031 Found); 2032 ++NumIdentifierLookups; 2033 ASTIdentifierLookupTable::iterator Pos = 2034 IdTable->find_hashed(Name, NameHash, &Trait); 2035 if (Pos == IdTable->end()) 2036 return false; 2037 2038 // Dereferencing the iterator has the effect of building the 2039 // IdentifierInfo node and populating it with the various 2040 // declarations it needs. 2041 ++NumIdentifierLookupHits; 2042 Found = *Pos; 2043 return true; 2044 } 2045 2046 // Retrieve the identifier info found within the module 2047 // files. 2048 IdentifierInfo *getIdentifierInfo() const { return Found; } 2049 }; 2050 2051 } // namespace 2052 2053 void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) { 2054 // Note that we are loading an identifier. 2055 Deserializing AnIdentifier(this); 2056 2057 unsigned PriorGeneration = 0; 2058 if (getContext().getLangOpts().Modules) 2059 PriorGeneration = IdentifierGeneration[&II]; 2060 2061 // If there is a global index, look there first to determine which modules 2062 // provably do not have any results for this identifier. 2063 GlobalModuleIndex::HitSet Hits; 2064 GlobalModuleIndex::HitSet *HitsPtr = nullptr; 2065 if (!loadGlobalIndex()) { 2066 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) { 2067 HitsPtr = &Hits; 2068 } 2069 } 2070 2071 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration, 2072 NumIdentifierLookups, 2073 NumIdentifierLookupHits); 2074 ModuleMgr.visit(Visitor, HitsPtr); 2075 markIdentifierUpToDate(&II); 2076 } 2077 2078 void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) { 2079 if (!II) 2080 return; 2081 2082 II->setOutOfDate(false); 2083 2084 // Update the generation for this identifier. 2085 if (getContext().getLangOpts().Modules) 2086 IdentifierGeneration[II] = getGeneration(); 2087 } 2088 2089 void ASTReader::resolvePendingMacro(IdentifierInfo *II, 2090 const PendingMacroInfo &PMInfo) { 2091 ModuleFile &M = *PMInfo.M; 2092 2093 BitstreamCursor &Cursor = M.MacroCursor; 2094 SavedStreamPosition SavedPosition(Cursor); 2095 if (llvm::Error Err = 2096 Cursor.JumpToBit(M.MacroOffsetsBase + PMInfo.MacroDirectivesOffset)) { 2097 Error(std::move(Err)); 2098 return; 2099 } 2100 2101 struct ModuleMacroRecord { 2102 SubmoduleID SubModID; 2103 MacroInfo *MI; 2104 SmallVector<SubmoduleID, 8> Overrides; 2105 }; 2106 llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros; 2107 2108 // We expect to see a sequence of PP_MODULE_MACRO records listing exported 2109 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete 2110 // macro histroy. 2111 RecordData Record; 2112 while (true) { 2113 Expected<llvm::BitstreamEntry> MaybeEntry = 2114 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd); 2115 if (!MaybeEntry) { 2116 Error(MaybeEntry.takeError()); 2117 return; 2118 } 2119 llvm::BitstreamEntry Entry = MaybeEntry.get(); 2120 2121 if (Entry.Kind != llvm::BitstreamEntry::Record) { 2122 Error("malformed block record in AST file"); 2123 return; 2124 } 2125 2126 Record.clear(); 2127 Expected<unsigned> MaybePP = Cursor.readRecord(Entry.ID, Record); 2128 if (!MaybePP) { 2129 Error(MaybePP.takeError()); 2130 return; 2131 } 2132 switch ((PreprocessorRecordTypes)MaybePP.get()) { 2133 case PP_MACRO_DIRECTIVE_HISTORY: 2134 break; 2135 2136 case PP_MODULE_MACRO: { 2137 ModuleMacros.push_back(ModuleMacroRecord()); 2138 auto &Info = ModuleMacros.back(); 2139 Info.SubModID = getGlobalSubmoduleID(M, Record[0]); 2140 Info.MI = getMacro(getGlobalMacroID(M, Record[1])); 2141 for (int I = 2, N = Record.size(); I != N; ++I) 2142 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I])); 2143 continue; 2144 } 2145 2146 default: 2147 Error("malformed block record in AST file"); 2148 return; 2149 } 2150 2151 // We found the macro directive history; that's the last record 2152 // for this macro. 2153 break; 2154 } 2155 2156 // Module macros are listed in reverse dependency order. 2157 { 2158 std::reverse(ModuleMacros.begin(), ModuleMacros.end()); 2159 llvm::SmallVector<ModuleMacro*, 8> Overrides; 2160 for (auto &MMR : ModuleMacros) { 2161 Overrides.clear(); 2162 for (unsigned ModID : MMR.Overrides) { 2163 Module *Mod = getSubmodule(ModID); 2164 auto *Macro = PP.getModuleMacro(Mod, II); 2165 assert(Macro && "missing definition for overridden macro"); 2166 Overrides.push_back(Macro); 2167 } 2168 2169 bool Inserted = false; 2170 Module *Owner = getSubmodule(MMR.SubModID); 2171 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted); 2172 } 2173 } 2174 2175 // Don't read the directive history for a module; we don't have anywhere 2176 // to put it. 2177 if (M.isModule()) 2178 return; 2179 2180 // Deserialize the macro directives history in reverse source-order. 2181 MacroDirective *Latest = nullptr, *Earliest = nullptr; 2182 unsigned Idx = 0, N = Record.size(); 2183 while (Idx < N) { 2184 MacroDirective *MD = nullptr; 2185 SourceLocation Loc = ReadSourceLocation(M, Record, Idx); 2186 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++]; 2187 switch (K) { 2188 case MacroDirective::MD_Define: { 2189 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++])); 2190 MD = PP.AllocateDefMacroDirective(MI, Loc); 2191 break; 2192 } 2193 case MacroDirective::MD_Undefine: 2194 MD = PP.AllocateUndefMacroDirective(Loc); 2195 break; 2196 case MacroDirective::MD_Visibility: 2197 bool isPublic = Record[Idx++]; 2198 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic); 2199 break; 2200 } 2201 2202 if (!Latest) 2203 Latest = MD; 2204 if (Earliest) 2205 Earliest->setPrevious(MD); 2206 Earliest = MD; 2207 } 2208 2209 if (Latest) 2210 PP.setLoadedMacroDirective(II, Earliest, Latest); 2211 } 2212 2213 ASTReader::InputFileInfo 2214 ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) { 2215 // Go find this input file. 2216 BitstreamCursor &Cursor = F.InputFilesCursor; 2217 SavedStreamPosition SavedPosition(Cursor); 2218 if (llvm::Error Err = Cursor.JumpToBit(F.InputFileOffsets[ID - 1])) { 2219 // FIXME this drops errors on the floor. 2220 consumeError(std::move(Err)); 2221 } 2222 2223 Expected<unsigned> MaybeCode = Cursor.ReadCode(); 2224 if (!MaybeCode) { 2225 // FIXME this drops errors on the floor. 2226 consumeError(MaybeCode.takeError()); 2227 } 2228 unsigned Code = MaybeCode.get(); 2229 RecordData Record; 2230 StringRef Blob; 2231 2232 if (Expected<unsigned> Maybe = Cursor.readRecord(Code, Record, &Blob)) 2233 assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE && 2234 "invalid record type for input file"); 2235 else { 2236 // FIXME this drops errors on the floor. 2237 consumeError(Maybe.takeError()); 2238 } 2239 2240 assert(Record[0] == ID && "Bogus stored ID or offset"); 2241 InputFileInfo R; 2242 R.StoredSize = static_cast<off_t>(Record[1]); 2243 R.StoredTime = static_cast<time_t>(Record[2]); 2244 R.Overridden = static_cast<bool>(Record[3]); 2245 R.Transient = static_cast<bool>(Record[4]); 2246 R.TopLevelModuleMap = static_cast<bool>(Record[5]); 2247 R.Filename = std::string(Blob); 2248 ResolveImportedPath(F, R.Filename); 2249 2250 Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance(); 2251 if (!MaybeEntry) // FIXME this drops errors on the floor. 2252 consumeError(MaybeEntry.takeError()); 2253 llvm::BitstreamEntry Entry = MaybeEntry.get(); 2254 assert(Entry.Kind == llvm::BitstreamEntry::Record && 2255 "expected record type for input file hash"); 2256 2257 Record.clear(); 2258 if (Expected<unsigned> Maybe = Cursor.readRecord(Entry.ID, Record)) 2259 assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE_HASH && 2260 "invalid record type for input file hash"); 2261 else { 2262 // FIXME this drops errors on the floor. 2263 consumeError(Maybe.takeError()); 2264 } 2265 R.ContentHash = (static_cast<uint64_t>(Record[1]) << 32) | 2266 static_cast<uint64_t>(Record[0]); 2267 return R; 2268 } 2269 2270 static unsigned moduleKindForDiagnostic(ModuleKind Kind); 2271 InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) { 2272 // If this ID is bogus, just return an empty input file. 2273 if (ID == 0 || ID > F.InputFilesLoaded.size()) 2274 return InputFile(); 2275 2276 // If we've already loaded this input file, return it. 2277 if (F.InputFilesLoaded[ID-1].getFile()) 2278 return F.InputFilesLoaded[ID-1]; 2279 2280 if (F.InputFilesLoaded[ID-1].isNotFound()) 2281 return InputFile(); 2282 2283 // Go find this input file. 2284 BitstreamCursor &Cursor = F.InputFilesCursor; 2285 SavedStreamPosition SavedPosition(Cursor); 2286 if (llvm::Error Err = Cursor.JumpToBit(F.InputFileOffsets[ID - 1])) { 2287 // FIXME this drops errors on the floor. 2288 consumeError(std::move(Err)); 2289 } 2290 2291 InputFileInfo FI = readInputFileInfo(F, ID); 2292 off_t StoredSize = FI.StoredSize; 2293 time_t StoredTime = FI.StoredTime; 2294 bool Overridden = FI.Overridden; 2295 bool Transient = FI.Transient; 2296 StringRef Filename = FI.Filename; 2297 uint64_t StoredContentHash = FI.ContentHash; 2298 2299 const FileEntry *File = nullptr; 2300 if (auto FE = FileMgr.getFile(Filename, /*OpenFile=*/false)) 2301 File = *FE; 2302 2303 // If we didn't find the file, resolve it relative to the 2304 // original directory from which this AST file was created. 2305 if (File == nullptr && !F.OriginalDir.empty() && !F.BaseDirectory.empty() && 2306 F.OriginalDir != F.BaseDirectory) { 2307 std::string Resolved = resolveFileRelativeToOriginalDir( 2308 std::string(Filename), F.OriginalDir, F.BaseDirectory); 2309 if (!Resolved.empty()) 2310 if (auto FE = FileMgr.getFile(Resolved)) 2311 File = *FE; 2312 } 2313 2314 // For an overridden file, create a virtual file with the stored 2315 // size/timestamp. 2316 if ((Overridden || Transient) && File == nullptr) 2317 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime); 2318 2319 if (File == nullptr) { 2320 if (Complain) { 2321 std::string ErrorStr = "could not find file '"; 2322 ErrorStr += Filename; 2323 ErrorStr += "' referenced by AST file '"; 2324 ErrorStr += F.FileName; 2325 ErrorStr += "'"; 2326 Error(ErrorStr); 2327 } 2328 // Record that we didn't find the file. 2329 F.InputFilesLoaded[ID-1] = InputFile::getNotFound(); 2330 return InputFile(); 2331 } 2332 2333 // Check if there was a request to override the contents of the file 2334 // that was part of the precompiled header. Overriding such a file 2335 // can lead to problems when lexing using the source locations from the 2336 // PCH. 2337 SourceManager &SM = getSourceManager(); 2338 // FIXME: Reject if the overrides are different. 2339 if ((!Overridden && !Transient) && SM.isFileOverridden(File)) { 2340 if (Complain) 2341 Error(diag::err_fe_pch_file_overridden, Filename); 2342 2343 // After emitting the diagnostic, bypass the overriding file to recover 2344 // (this creates a separate FileEntry). 2345 File = SM.bypassFileContentsOverride(*File); 2346 if (!File) { 2347 F.InputFilesLoaded[ID - 1] = InputFile::getNotFound(); 2348 return InputFile(); 2349 } 2350 } 2351 2352 enum ModificationType { 2353 Size, 2354 ModTime, 2355 Content, 2356 None, 2357 }; 2358 auto HasInputFileChanged = [&]() { 2359 if (StoredSize != File->getSize()) 2360 return ModificationType::Size; 2361 if (!DisableValidation && StoredTime && 2362 StoredTime != File->getModificationTime()) { 2363 // In case the modification time changes but not the content, 2364 // accept the cached file as legit. 2365 if (ValidateASTInputFilesContent && 2366 StoredContentHash != static_cast<uint64_t>(llvm::hash_code(-1))) { 2367 auto MemBuffOrError = FileMgr.getBufferForFile(File); 2368 if (!MemBuffOrError) { 2369 if (!Complain) 2370 return ModificationType::ModTime; 2371 std::string ErrorStr = "could not get buffer for file '"; 2372 ErrorStr += File->getName(); 2373 ErrorStr += "'"; 2374 Error(ErrorStr); 2375 return ModificationType::ModTime; 2376 } 2377 2378 auto ContentHash = hash_value(MemBuffOrError.get()->getBuffer()); 2379 if (StoredContentHash == static_cast<uint64_t>(ContentHash)) 2380 return ModificationType::None; 2381 return ModificationType::Content; 2382 } 2383 return ModificationType::ModTime; 2384 } 2385 return ModificationType::None; 2386 }; 2387 2388 bool IsOutOfDate = false; 2389 auto FileChange = HasInputFileChanged(); 2390 // For an overridden file, there is nothing to validate. 2391 if (!Overridden && FileChange != ModificationType::None) { 2392 if (Complain && !Diags.isDiagnosticInFlight()) { 2393 // Build a list of the PCH imports that got us here (in reverse). 2394 SmallVector<ModuleFile *, 4> ImportStack(1, &F); 2395 while (!ImportStack.back()->ImportedBy.empty()) 2396 ImportStack.push_back(ImportStack.back()->ImportedBy[0]); 2397 2398 // The top-level PCH is stale. 2399 StringRef TopLevelPCHName(ImportStack.back()->FileName); 2400 Diag(diag::err_fe_ast_file_modified) 2401 << Filename << moduleKindForDiagnostic(ImportStack.back()->Kind) 2402 << TopLevelPCHName << FileChange; 2403 2404 // Print the import stack. 2405 if (ImportStack.size() > 1) { 2406 Diag(diag::note_pch_required_by) 2407 << Filename << ImportStack[0]->FileName; 2408 for (unsigned I = 1; I < ImportStack.size(); ++I) 2409 Diag(diag::note_pch_required_by) 2410 << ImportStack[I-1]->FileName << ImportStack[I]->FileName; 2411 } 2412 2413 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName; 2414 } 2415 2416 IsOutOfDate = true; 2417 } 2418 // FIXME: If the file is overridden and we've already opened it, 2419 // issue an error (or split it into a separate FileEntry). 2420 2421 InputFile IF = InputFile(File, Overridden || Transient, IsOutOfDate); 2422 2423 // Note that we've loaded this input file. 2424 F.InputFilesLoaded[ID-1] = IF; 2425 return IF; 2426 } 2427 2428 /// If we are loading a relocatable PCH or module file, and the filename 2429 /// is not an absolute path, add the system or module root to the beginning of 2430 /// the file name. 2431 void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) { 2432 // Resolve relative to the base directory, if we have one. 2433 if (!M.BaseDirectory.empty()) 2434 return ResolveImportedPath(Filename, M.BaseDirectory); 2435 } 2436 2437 void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) { 2438 if (Filename.empty() || llvm::sys::path::is_absolute(Filename)) 2439 return; 2440 2441 SmallString<128> Buffer; 2442 llvm::sys::path::append(Buffer, Prefix, Filename); 2443 Filename.assign(Buffer.begin(), Buffer.end()); 2444 } 2445 2446 static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) { 2447 switch (ARR) { 2448 case ASTReader::Failure: return true; 2449 case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing); 2450 case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate); 2451 case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch); 2452 case ASTReader::ConfigurationMismatch: 2453 return !(Caps & ASTReader::ARR_ConfigurationMismatch); 2454 case ASTReader::HadErrors: return true; 2455 case ASTReader::Success: return false; 2456 } 2457 2458 llvm_unreachable("unknown ASTReadResult"); 2459 } 2460 2461 ASTReader::ASTReadResult ASTReader::ReadOptionsBlock( 2462 BitstreamCursor &Stream, unsigned ClientLoadCapabilities, 2463 bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener, 2464 std::string &SuggestedPredefines) { 2465 if (llvm::Error Err = Stream.EnterSubBlock(OPTIONS_BLOCK_ID)) { 2466 // FIXME this drops errors on the floor. 2467 consumeError(std::move(Err)); 2468 return Failure; 2469 } 2470 2471 // Read all of the records in the options block. 2472 RecordData Record; 2473 ASTReadResult Result = Success; 2474 while (true) { 2475 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); 2476 if (!MaybeEntry) { 2477 // FIXME this drops errors on the floor. 2478 consumeError(MaybeEntry.takeError()); 2479 return Failure; 2480 } 2481 llvm::BitstreamEntry Entry = MaybeEntry.get(); 2482 2483 switch (Entry.Kind) { 2484 case llvm::BitstreamEntry::Error: 2485 case llvm::BitstreamEntry::SubBlock: 2486 return Failure; 2487 2488 case llvm::BitstreamEntry::EndBlock: 2489 return Result; 2490 2491 case llvm::BitstreamEntry::Record: 2492 // The interesting case. 2493 break; 2494 } 2495 2496 // Read and process a record. 2497 Record.clear(); 2498 Expected<unsigned> MaybeRecordType = Stream.readRecord(Entry.ID, Record); 2499 if (!MaybeRecordType) { 2500 // FIXME this drops errors on the floor. 2501 consumeError(MaybeRecordType.takeError()); 2502 return Failure; 2503 } 2504 switch ((OptionsRecordTypes)MaybeRecordType.get()) { 2505 case LANGUAGE_OPTIONS: { 2506 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0; 2507 if (ParseLanguageOptions(Record, Complain, Listener, 2508 AllowCompatibleConfigurationMismatch)) 2509 Result = ConfigurationMismatch; 2510 break; 2511 } 2512 2513 case TARGET_OPTIONS: { 2514 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0; 2515 if (ParseTargetOptions(Record, Complain, Listener, 2516 AllowCompatibleConfigurationMismatch)) 2517 Result = ConfigurationMismatch; 2518 break; 2519 } 2520 2521 case FILE_SYSTEM_OPTIONS: { 2522 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0; 2523 if (!AllowCompatibleConfigurationMismatch && 2524 ParseFileSystemOptions(Record, Complain, Listener)) 2525 Result = ConfigurationMismatch; 2526 break; 2527 } 2528 2529 case HEADER_SEARCH_OPTIONS: { 2530 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0; 2531 if (!AllowCompatibleConfigurationMismatch && 2532 ParseHeaderSearchOptions(Record, Complain, Listener)) 2533 Result = ConfigurationMismatch; 2534 break; 2535 } 2536 2537 case PREPROCESSOR_OPTIONS: 2538 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0; 2539 if (!AllowCompatibleConfigurationMismatch && 2540 ParsePreprocessorOptions(Record, Complain, Listener, 2541 SuggestedPredefines)) 2542 Result = ConfigurationMismatch; 2543 break; 2544 } 2545 } 2546 } 2547 2548 ASTReader::ASTReadResult 2549 ASTReader::ReadControlBlock(ModuleFile &F, 2550 SmallVectorImpl<ImportedModule> &Loaded, 2551 const ModuleFile *ImportedBy, 2552 unsigned ClientLoadCapabilities) { 2553 BitstreamCursor &Stream = F.Stream; 2554 2555 if (llvm::Error Err = Stream.EnterSubBlock(CONTROL_BLOCK_ID)) { 2556 Error(std::move(Err)); 2557 return Failure; 2558 } 2559 2560 // Lambda to read the unhashed control block the first time it's called. 2561 // 2562 // For PCM files, the unhashed control block cannot be read until after the 2563 // MODULE_NAME record. However, PCH files have no MODULE_NAME, and yet still 2564 // need to look ahead before reading the IMPORTS record. For consistency, 2565 // this block is always read somehow (see BitstreamEntry::EndBlock). 2566 bool HasReadUnhashedControlBlock = false; 2567 auto readUnhashedControlBlockOnce = [&]() { 2568 if (!HasReadUnhashedControlBlock) { 2569 HasReadUnhashedControlBlock = true; 2570 if (ASTReadResult Result = 2571 readUnhashedControlBlock(F, ImportedBy, ClientLoadCapabilities)) 2572 return Result; 2573 } 2574 return Success; 2575 }; 2576 2577 // Read all of the records and blocks in the control block. 2578 RecordData Record; 2579 unsigned NumInputs = 0; 2580 unsigned NumUserInputs = 0; 2581 StringRef BaseDirectoryAsWritten; 2582 while (true) { 2583 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); 2584 if (!MaybeEntry) { 2585 Error(MaybeEntry.takeError()); 2586 return Failure; 2587 } 2588 llvm::BitstreamEntry Entry = MaybeEntry.get(); 2589 2590 switch (Entry.Kind) { 2591 case llvm::BitstreamEntry::Error: 2592 Error("malformed block record in AST file"); 2593 return Failure; 2594 case llvm::BitstreamEntry::EndBlock: { 2595 // Validate the module before returning. This call catches an AST with 2596 // no module name and no imports. 2597 if (ASTReadResult Result = readUnhashedControlBlockOnce()) 2598 return Result; 2599 2600 // Validate input files. 2601 const HeaderSearchOptions &HSOpts = 2602 PP.getHeaderSearchInfo().getHeaderSearchOpts(); 2603 2604 // All user input files reside at the index range [0, NumUserInputs), and 2605 // system input files reside at [NumUserInputs, NumInputs). For explicitly 2606 // loaded module files, ignore missing inputs. 2607 if (!DisableValidation && F.Kind != MK_ExplicitModule && 2608 F.Kind != MK_PrebuiltModule) { 2609 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0; 2610 2611 // If we are reading a module, we will create a verification timestamp, 2612 // so we verify all input files. Otherwise, verify only user input 2613 // files. 2614 2615 unsigned N = NumUserInputs; 2616 if (ValidateSystemInputs || 2617 (HSOpts.ModulesValidateOncePerBuildSession && 2618 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp && 2619 F.Kind == MK_ImplicitModule)) 2620 N = NumInputs; 2621 2622 for (unsigned I = 0; I < N; ++I) { 2623 InputFile IF = getInputFile(F, I+1, Complain); 2624 if (!IF.getFile() || IF.isOutOfDate()) 2625 return OutOfDate; 2626 } 2627 } 2628 2629 if (Listener) 2630 Listener->visitModuleFile(F.FileName, F.Kind); 2631 2632 if (Listener && Listener->needsInputFileVisitation()) { 2633 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs 2634 : NumUserInputs; 2635 for (unsigned I = 0; I < N; ++I) { 2636 bool IsSystem = I >= NumUserInputs; 2637 InputFileInfo FI = readInputFileInfo(F, I+1); 2638 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden, 2639 F.Kind == MK_ExplicitModule || 2640 F.Kind == MK_PrebuiltModule); 2641 } 2642 } 2643 2644 return Success; 2645 } 2646 2647 case llvm::BitstreamEntry::SubBlock: 2648 switch (Entry.ID) { 2649 case INPUT_FILES_BLOCK_ID: 2650 F.InputFilesCursor = Stream; 2651 if (llvm::Error Err = Stream.SkipBlock()) { 2652 Error(std::move(Err)); 2653 return Failure; 2654 } 2655 if (ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) { 2656 Error("malformed block record in AST file"); 2657 return Failure; 2658 } 2659 continue; 2660 2661 case OPTIONS_BLOCK_ID: 2662 // If we're reading the first module for this group, check its options 2663 // are compatible with ours. For modules it imports, no further checking 2664 // is required, because we checked them when we built it. 2665 if (Listener && !ImportedBy) { 2666 // Should we allow the configuration of the module file to differ from 2667 // the configuration of the current translation unit in a compatible 2668 // way? 2669 // 2670 // FIXME: Allow this for files explicitly specified with -include-pch. 2671 bool AllowCompatibleConfigurationMismatch = 2672 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule; 2673 2674 ASTReadResult Result = 2675 ReadOptionsBlock(Stream, ClientLoadCapabilities, 2676 AllowCompatibleConfigurationMismatch, *Listener, 2677 SuggestedPredefines); 2678 if (Result == Failure) { 2679 Error("malformed block record in AST file"); 2680 return Result; 2681 } 2682 2683 if (DisableValidation || 2684 (AllowConfigurationMismatch && Result == ConfigurationMismatch)) 2685 Result = Success; 2686 2687 // If we can't load the module, exit early since we likely 2688 // will rebuild the module anyway. The stream may be in the 2689 // middle of a block. 2690 if (Result != Success) 2691 return Result; 2692 } else if (llvm::Error Err = Stream.SkipBlock()) { 2693 Error(std::move(Err)); 2694 return Failure; 2695 } 2696 continue; 2697 2698 default: 2699 if (llvm::Error Err = Stream.SkipBlock()) { 2700 Error(std::move(Err)); 2701 return Failure; 2702 } 2703 continue; 2704 } 2705 2706 case llvm::BitstreamEntry::Record: 2707 // The interesting case. 2708 break; 2709 } 2710 2711 // Read and process a record. 2712 Record.clear(); 2713 StringRef Blob; 2714 Expected<unsigned> MaybeRecordType = 2715 Stream.readRecord(Entry.ID, Record, &Blob); 2716 if (!MaybeRecordType) { 2717 Error(MaybeRecordType.takeError()); 2718 return Failure; 2719 } 2720 switch ((ControlRecordTypes)MaybeRecordType.get()) { 2721 case METADATA: { 2722 if (Record[0] != VERSION_MAJOR && !DisableValidation) { 2723 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0) 2724 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old 2725 : diag::err_pch_version_too_new); 2726 return VersionMismatch; 2727 } 2728 2729 bool hasErrors = Record[6]; 2730 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) { 2731 Diag(diag::err_pch_with_compiler_errors); 2732 return HadErrors; 2733 } 2734 if (hasErrors) { 2735 Diags.ErrorOccurred = true; 2736 Diags.UncompilableErrorOccurred = true; 2737 Diags.UnrecoverableErrorOccurred = true; 2738 } 2739 2740 F.RelocatablePCH = Record[4]; 2741 // Relative paths in a relocatable PCH are relative to our sysroot. 2742 if (F.RelocatablePCH) 2743 F.BaseDirectory = isysroot.empty() ? "/" : isysroot; 2744 2745 F.HasTimestamps = Record[5]; 2746 2747 const std::string &CurBranch = getClangFullRepositoryVersion(); 2748 StringRef ASTBranch = Blob; 2749 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) { 2750 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0) 2751 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch; 2752 return VersionMismatch; 2753 } 2754 break; 2755 } 2756 2757 case IMPORTS: { 2758 // Validate the AST before processing any imports (otherwise, untangling 2759 // them can be error-prone and expensive). A module will have a name and 2760 // will already have been validated, but this catches the PCH case. 2761 if (ASTReadResult Result = readUnhashedControlBlockOnce()) 2762 return Result; 2763 2764 // Load each of the imported PCH files. 2765 unsigned Idx = 0, N = Record.size(); 2766 while (Idx < N) { 2767 // Read information about the AST file. 2768 ModuleKind ImportedKind = (ModuleKind)Record[Idx++]; 2769 // The import location will be the local one for now; we will adjust 2770 // all import locations of module imports after the global source 2771 // location info are setup, in ReadAST. 2772 SourceLocation ImportLoc = 2773 ReadUntranslatedSourceLocation(Record[Idx++]); 2774 off_t StoredSize = (off_t)Record[Idx++]; 2775 time_t StoredModTime = (time_t)Record[Idx++]; 2776 auto FirstSignatureByte = Record.begin() + Idx; 2777 ASTFileSignature StoredSignature = ASTFileSignature::create( 2778 FirstSignatureByte, FirstSignatureByte + ASTFileSignature::size); 2779 Idx += ASTFileSignature::size; 2780 2781 std::string ImportedName = ReadString(Record, Idx); 2782 std::string ImportedFile; 2783 2784 // For prebuilt and explicit modules first consult the file map for 2785 // an override. Note that here we don't search prebuilt module 2786 // directories, only the explicit name to file mappings. Also, we will 2787 // still verify the size/signature making sure it is essentially the 2788 // same file but perhaps in a different location. 2789 if (ImportedKind == MK_PrebuiltModule || ImportedKind == MK_ExplicitModule) 2790 ImportedFile = PP.getHeaderSearchInfo().getPrebuiltModuleFileName( 2791 ImportedName, /*FileMapOnly*/ true); 2792 2793 if (ImportedFile.empty()) 2794 // Use BaseDirectoryAsWritten to ensure we use the same path in the 2795 // ModuleCache as when writing. 2796 ImportedFile = ReadPath(BaseDirectoryAsWritten, Record, Idx); 2797 else 2798 SkipPath(Record, Idx); 2799 2800 // If our client can't cope with us being out of date, we can't cope with 2801 // our dependency being missing. 2802 unsigned Capabilities = ClientLoadCapabilities; 2803 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) 2804 Capabilities &= ~ARR_Missing; 2805 2806 // Load the AST file. 2807 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F, 2808 Loaded, StoredSize, StoredModTime, 2809 StoredSignature, Capabilities); 2810 2811 // If we diagnosed a problem, produce a backtrace. 2812 if (isDiagnosedResult(Result, Capabilities)) 2813 Diag(diag::note_module_file_imported_by) 2814 << F.FileName << !F.ModuleName.empty() << F.ModuleName; 2815 2816 switch (Result) { 2817 case Failure: return Failure; 2818 // If we have to ignore the dependency, we'll have to ignore this too. 2819 case Missing: 2820 case OutOfDate: return OutOfDate; 2821 case VersionMismatch: return VersionMismatch; 2822 case ConfigurationMismatch: return ConfigurationMismatch; 2823 case HadErrors: return HadErrors; 2824 case Success: break; 2825 } 2826 } 2827 break; 2828 } 2829 2830 case ORIGINAL_FILE: 2831 F.OriginalSourceFileID = FileID::get(Record[0]); 2832 F.ActualOriginalSourceFileName = std::string(Blob); 2833 F.OriginalSourceFileName = F.ActualOriginalSourceFileName; 2834 ResolveImportedPath(F, F.OriginalSourceFileName); 2835 break; 2836 2837 case ORIGINAL_FILE_ID: 2838 F.OriginalSourceFileID = FileID::get(Record[0]); 2839 break; 2840 2841 case ORIGINAL_PCH_DIR: 2842 F.OriginalDir = std::string(Blob); 2843 break; 2844 2845 case MODULE_NAME: 2846 F.ModuleName = std::string(Blob); 2847 Diag(diag::remark_module_import) 2848 << F.ModuleName << F.FileName << (ImportedBy ? true : false) 2849 << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef()); 2850 if (Listener) 2851 Listener->ReadModuleName(F.ModuleName); 2852 2853 // Validate the AST as soon as we have a name so we can exit early on 2854 // failure. 2855 if (ASTReadResult Result = readUnhashedControlBlockOnce()) 2856 return Result; 2857 2858 break; 2859 2860 case MODULE_DIRECTORY: { 2861 // Save the BaseDirectory as written in the PCM for computing the module 2862 // filename for the ModuleCache. 2863 BaseDirectoryAsWritten = Blob; 2864 assert(!F.ModuleName.empty() && 2865 "MODULE_DIRECTORY found before MODULE_NAME"); 2866 // If we've already loaded a module map file covering this module, we may 2867 // have a better path for it (relative to the current build). 2868 Module *M = PP.getHeaderSearchInfo().lookupModule( 2869 F.ModuleName, /*AllowSearch*/ true, 2870 /*AllowExtraModuleMapSearch*/ true); 2871 if (M && M->Directory) { 2872 // If we're implicitly loading a module, the base directory can't 2873 // change between the build and use. 2874 // Don't emit module relocation error if we have -fno-validate-pch 2875 if (!PP.getPreprocessorOpts().DisablePCHValidation && 2876 F.Kind != MK_ExplicitModule && F.Kind != MK_PrebuiltModule) { 2877 auto BuildDir = PP.getFileManager().getDirectory(Blob); 2878 if (!BuildDir || *BuildDir != M->Directory) { 2879 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) 2880 Diag(diag::err_imported_module_relocated) 2881 << F.ModuleName << Blob << M->Directory->getName(); 2882 return OutOfDate; 2883 } 2884 } 2885 F.BaseDirectory = std::string(M->Directory->getName()); 2886 } else { 2887 F.BaseDirectory = std::string(Blob); 2888 } 2889 break; 2890 } 2891 2892 case MODULE_MAP_FILE: 2893 if (ASTReadResult Result = 2894 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities)) 2895 return Result; 2896 break; 2897 2898 case INPUT_FILE_OFFSETS: 2899 NumInputs = Record[0]; 2900 NumUserInputs = Record[1]; 2901 F.InputFileOffsets = 2902 (const llvm::support::unaligned_uint64_t *)Blob.data(); 2903 F.InputFilesLoaded.resize(NumInputs); 2904 F.NumUserInputFiles = NumUserInputs; 2905 break; 2906 } 2907 } 2908 } 2909 2910 ASTReader::ASTReadResult 2911 ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) { 2912 BitstreamCursor &Stream = F.Stream; 2913 2914 if (llvm::Error Err = Stream.EnterSubBlock(AST_BLOCK_ID)) { 2915 Error(std::move(Err)); 2916 return Failure; 2917 } 2918 F.ASTBlockStartOffset = Stream.GetCurrentBitNo(); 2919 2920 // Read all of the records and blocks for the AST file. 2921 RecordData Record; 2922 while (true) { 2923 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); 2924 if (!MaybeEntry) { 2925 Error(MaybeEntry.takeError()); 2926 return Failure; 2927 } 2928 llvm::BitstreamEntry Entry = MaybeEntry.get(); 2929 2930 switch (Entry.Kind) { 2931 case llvm::BitstreamEntry::Error: 2932 Error("error at end of module block in AST file"); 2933 return Failure; 2934 case llvm::BitstreamEntry::EndBlock: 2935 // Outside of C++, we do not store a lookup map for the translation unit. 2936 // Instead, mark it as needing a lookup map to be built if this module 2937 // contains any declarations lexically within it (which it always does!). 2938 // This usually has no cost, since we very rarely need the lookup map for 2939 // the translation unit outside C++. 2940 if (ASTContext *Ctx = ContextObj) { 2941 DeclContext *DC = Ctx->getTranslationUnitDecl(); 2942 if (DC->hasExternalLexicalStorage() && !Ctx->getLangOpts().CPlusPlus) 2943 DC->setMustBuildLookupTable(); 2944 } 2945 2946 return Success; 2947 case llvm::BitstreamEntry::SubBlock: 2948 switch (Entry.ID) { 2949 case DECLTYPES_BLOCK_ID: 2950 // We lazily load the decls block, but we want to set up the 2951 // DeclsCursor cursor to point into it. Clone our current bitcode 2952 // cursor to it, enter the block and read the abbrevs in that block. 2953 // With the main cursor, we just skip over it. 2954 F.DeclsCursor = Stream; 2955 if (llvm::Error Err = Stream.SkipBlock()) { 2956 Error(std::move(Err)); 2957 return Failure; 2958 } 2959 if (ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID, 2960 &F.DeclsBlockStartOffset)) { 2961 Error("malformed block record in AST file"); 2962 return Failure; 2963 } 2964 break; 2965 2966 case PREPROCESSOR_BLOCK_ID: 2967 F.MacroCursor = Stream; 2968 if (!PP.getExternalSource()) 2969 PP.setExternalSource(this); 2970 2971 if (llvm::Error Err = Stream.SkipBlock()) { 2972 Error(std::move(Err)); 2973 return Failure; 2974 } 2975 if (ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) { 2976 Error("malformed block record in AST file"); 2977 return Failure; 2978 } 2979 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo(); 2980 break; 2981 2982 case PREPROCESSOR_DETAIL_BLOCK_ID: 2983 F.PreprocessorDetailCursor = Stream; 2984 2985 if (llvm::Error Err = Stream.SkipBlock()) { 2986 Error(std::move(Err)); 2987 return Failure; 2988 } 2989 if (ReadBlockAbbrevs(F.PreprocessorDetailCursor, 2990 PREPROCESSOR_DETAIL_BLOCK_ID)) { 2991 Error("malformed preprocessor detail record in AST file"); 2992 return Failure; 2993 } 2994 F.PreprocessorDetailStartOffset 2995 = F.PreprocessorDetailCursor.GetCurrentBitNo(); 2996 2997 if (!PP.getPreprocessingRecord()) 2998 PP.createPreprocessingRecord(); 2999 if (!PP.getPreprocessingRecord()->getExternalSource()) 3000 PP.getPreprocessingRecord()->SetExternalSource(*this); 3001 break; 3002 3003 case SOURCE_MANAGER_BLOCK_ID: 3004 if (ReadSourceManagerBlock(F)) 3005 return Failure; 3006 break; 3007 3008 case SUBMODULE_BLOCK_ID: 3009 if (ASTReadResult Result = 3010 ReadSubmoduleBlock(F, ClientLoadCapabilities)) 3011 return Result; 3012 break; 3013 3014 case COMMENTS_BLOCK_ID: { 3015 BitstreamCursor C = Stream; 3016 3017 if (llvm::Error Err = Stream.SkipBlock()) { 3018 Error(std::move(Err)); 3019 return Failure; 3020 } 3021 if (ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) { 3022 Error("malformed comments block in AST file"); 3023 return Failure; 3024 } 3025 CommentsCursors.push_back(std::make_pair(C, &F)); 3026 break; 3027 } 3028 3029 default: 3030 if (llvm::Error Err = Stream.SkipBlock()) { 3031 Error(std::move(Err)); 3032 return Failure; 3033 } 3034 break; 3035 } 3036 continue; 3037 3038 case llvm::BitstreamEntry::Record: 3039 // The interesting case. 3040 break; 3041 } 3042 3043 // Read and process a record. 3044 Record.clear(); 3045 StringRef Blob; 3046 Expected<unsigned> MaybeRecordType = 3047 Stream.readRecord(Entry.ID, Record, &Blob); 3048 if (!MaybeRecordType) { 3049 Error(MaybeRecordType.takeError()); 3050 return Failure; 3051 } 3052 ASTRecordTypes RecordType = (ASTRecordTypes)MaybeRecordType.get(); 3053 3054 // If we're not loading an AST context, we don't care about most records. 3055 if (!ContextObj) { 3056 switch (RecordType) { 3057 case IDENTIFIER_TABLE: 3058 case IDENTIFIER_OFFSET: 3059 case INTERESTING_IDENTIFIERS: 3060 case STATISTICS: 3061 case PP_CONDITIONAL_STACK: 3062 case PP_COUNTER_VALUE: 3063 case SOURCE_LOCATION_OFFSETS: 3064 case MODULE_OFFSET_MAP: 3065 case SOURCE_MANAGER_LINE_TABLE: 3066 case SOURCE_LOCATION_PRELOADS: 3067 case PPD_ENTITIES_OFFSETS: 3068 case HEADER_SEARCH_TABLE: 3069 case IMPORTED_MODULES: 3070 case MACRO_OFFSET: 3071 break; 3072 default: 3073 continue; 3074 } 3075 } 3076 3077 switch (RecordType) { 3078 default: // Default behavior: ignore. 3079 break; 3080 3081 case TYPE_OFFSET: { 3082 if (F.LocalNumTypes != 0) { 3083 Error("duplicate TYPE_OFFSET record in AST file"); 3084 return Failure; 3085 } 3086 F.TypeOffsets = reinterpret_cast<const UnderalignedInt64 *>(Blob.data()); 3087 F.LocalNumTypes = Record[0]; 3088 unsigned LocalBaseTypeIndex = Record[1]; 3089 F.BaseTypeIndex = getTotalNumTypes(); 3090 3091 if (F.LocalNumTypes > 0) { 3092 // Introduce the global -> local mapping for types within this module. 3093 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F)); 3094 3095 // Introduce the local -> global mapping for types within this module. 3096 F.TypeRemap.insertOrReplace( 3097 std::make_pair(LocalBaseTypeIndex, 3098 F.BaseTypeIndex - LocalBaseTypeIndex)); 3099 3100 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes); 3101 } 3102 break; 3103 } 3104 3105 case DECL_OFFSET: { 3106 if (F.LocalNumDecls != 0) { 3107 Error("duplicate DECL_OFFSET record in AST file"); 3108 return Failure; 3109 } 3110 F.DeclOffsets = (const DeclOffset *)Blob.data(); 3111 F.LocalNumDecls = Record[0]; 3112 unsigned LocalBaseDeclID = Record[1]; 3113 F.BaseDeclID = getTotalNumDecls(); 3114 3115 if (F.LocalNumDecls > 0) { 3116 // Introduce the global -> local mapping for declarations within this 3117 // module. 3118 GlobalDeclMap.insert( 3119 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F)); 3120 3121 // Introduce the local -> global mapping for declarations within this 3122 // module. 3123 F.DeclRemap.insertOrReplace( 3124 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID)); 3125 3126 // Introduce the global -> local mapping for declarations within this 3127 // module. 3128 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID; 3129 3130 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls); 3131 } 3132 break; 3133 } 3134 3135 case TU_UPDATE_LEXICAL: { 3136 DeclContext *TU = ContextObj->getTranslationUnitDecl(); 3137 LexicalContents Contents( 3138 reinterpret_cast<const llvm::support::unaligned_uint32_t *>( 3139 Blob.data()), 3140 static_cast<unsigned int>(Blob.size() / 4)); 3141 TULexicalDecls.push_back(std::make_pair(&F, Contents)); 3142 TU->setHasExternalLexicalStorage(true); 3143 break; 3144 } 3145 3146 case UPDATE_VISIBLE: { 3147 unsigned Idx = 0; 3148 serialization::DeclID ID = ReadDeclID(F, Record, Idx); 3149 auto *Data = (const unsigned char*)Blob.data(); 3150 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&F, Data}); 3151 // If we've already loaded the decl, perform the updates when we finish 3152 // loading this block. 3153 if (Decl *D = GetExistingDecl(ID)) 3154 PendingUpdateRecords.push_back( 3155 PendingUpdateRecord(ID, D, /*JustLoaded=*/false)); 3156 break; 3157 } 3158 3159 case IDENTIFIER_TABLE: 3160 F.IdentifierTableData = Blob.data(); 3161 if (Record[0]) { 3162 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create( 3163 (const unsigned char *)F.IdentifierTableData + Record[0], 3164 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t), 3165 (const unsigned char *)F.IdentifierTableData, 3166 ASTIdentifierLookupTrait(*this, F)); 3167 3168 PP.getIdentifierTable().setExternalIdentifierLookup(this); 3169 } 3170 break; 3171 3172 case IDENTIFIER_OFFSET: { 3173 if (F.LocalNumIdentifiers != 0) { 3174 Error("duplicate IDENTIFIER_OFFSET record in AST file"); 3175 return Failure; 3176 } 3177 F.IdentifierOffsets = (const uint32_t *)Blob.data(); 3178 F.LocalNumIdentifiers = Record[0]; 3179 unsigned LocalBaseIdentifierID = Record[1]; 3180 F.BaseIdentifierID = getTotalNumIdentifiers(); 3181 3182 if (F.LocalNumIdentifiers > 0) { 3183 // Introduce the global -> local mapping for identifiers within this 3184 // module. 3185 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1, 3186 &F)); 3187 3188 // Introduce the local -> global mapping for identifiers within this 3189 // module. 3190 F.IdentifierRemap.insertOrReplace( 3191 std::make_pair(LocalBaseIdentifierID, 3192 F.BaseIdentifierID - LocalBaseIdentifierID)); 3193 3194 IdentifiersLoaded.resize(IdentifiersLoaded.size() 3195 + F.LocalNumIdentifiers); 3196 } 3197 break; 3198 } 3199 3200 case INTERESTING_IDENTIFIERS: 3201 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end()); 3202 break; 3203 3204 case EAGERLY_DESERIALIZED_DECLS: 3205 // FIXME: Skip reading this record if our ASTConsumer doesn't care 3206 // about "interesting" decls (for instance, if we're building a module). 3207 for (unsigned I = 0, N = Record.size(); I != N; ++I) 3208 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I])); 3209 break; 3210 3211 case MODULAR_CODEGEN_DECLS: 3212 // FIXME: Skip reading this record if our ASTConsumer doesn't care about 3213 // them (ie: if we're not codegenerating this module). 3214 if (F.Kind == MK_MainFile || 3215 getContext().getLangOpts().BuildingPCHWithObjectFile) 3216 for (unsigned I = 0, N = Record.size(); I != N; ++I) 3217 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I])); 3218 break; 3219 3220 case SPECIAL_TYPES: 3221 if (SpecialTypes.empty()) { 3222 for (unsigned I = 0, N = Record.size(); I != N; ++I) 3223 SpecialTypes.push_back(getGlobalTypeID(F, Record[I])); 3224 break; 3225 } 3226 3227 if (SpecialTypes.size() != Record.size()) { 3228 Error("invalid special-types record"); 3229 return Failure; 3230 } 3231 3232 for (unsigned I = 0, N = Record.size(); I != N; ++I) { 3233 serialization::TypeID ID = getGlobalTypeID(F, Record[I]); 3234 if (!SpecialTypes[I]) 3235 SpecialTypes[I] = ID; 3236 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate 3237 // merge step? 3238 } 3239 break; 3240 3241 case STATISTICS: 3242 TotalNumStatements += Record[0]; 3243 TotalNumMacros += Record[1]; 3244 TotalLexicalDeclContexts += Record[2]; 3245 TotalVisibleDeclContexts += Record[3]; 3246 break; 3247 3248 case UNUSED_FILESCOPED_DECLS: 3249 for (unsigned I = 0, N = Record.size(); I != N; ++I) 3250 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I])); 3251 break; 3252 3253 case DELEGATING_CTORS: 3254 for (unsigned I = 0, N = Record.size(); I != N; ++I) 3255 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I])); 3256 break; 3257 3258 case WEAK_UNDECLARED_IDENTIFIERS: 3259 if (Record.size() % 4 != 0) { 3260 Error("invalid weak identifiers record"); 3261 return Failure; 3262 } 3263 3264 // FIXME: Ignore weak undeclared identifiers from non-original PCH 3265 // files. This isn't the way to do it :) 3266 WeakUndeclaredIdentifiers.clear(); 3267 3268 // Translate the weak, undeclared identifiers into global IDs. 3269 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) { 3270 WeakUndeclaredIdentifiers.push_back( 3271 getGlobalIdentifierID(F, Record[I++])); 3272 WeakUndeclaredIdentifiers.push_back( 3273 getGlobalIdentifierID(F, Record[I++])); 3274 WeakUndeclaredIdentifiers.push_back( 3275 ReadSourceLocation(F, Record, I).getRawEncoding()); 3276 WeakUndeclaredIdentifiers.push_back(Record[I++]); 3277 } 3278 break; 3279 3280 case SELECTOR_OFFSETS: { 3281 F.SelectorOffsets = (const uint32_t *)Blob.data(); 3282 F.LocalNumSelectors = Record[0]; 3283 unsigned LocalBaseSelectorID = Record[1]; 3284 F.BaseSelectorID = getTotalNumSelectors(); 3285 3286 if (F.LocalNumSelectors > 0) { 3287 // Introduce the global -> local mapping for selectors within this 3288 // module. 3289 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F)); 3290 3291 // Introduce the local -> global mapping for selectors within this 3292 // module. 3293 F.SelectorRemap.insertOrReplace( 3294 std::make_pair(LocalBaseSelectorID, 3295 F.BaseSelectorID - LocalBaseSelectorID)); 3296 3297 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors); 3298 } 3299 break; 3300 } 3301 3302 case METHOD_POOL: 3303 F.SelectorLookupTableData = (const unsigned char *)Blob.data(); 3304 if (Record[0]) 3305 F.SelectorLookupTable 3306 = ASTSelectorLookupTable::Create( 3307 F.SelectorLookupTableData + Record[0], 3308 F.SelectorLookupTableData, 3309 ASTSelectorLookupTrait(*this, F)); 3310 TotalNumMethodPoolEntries += Record[1]; 3311 break; 3312 3313 case REFERENCED_SELECTOR_POOL: 3314 if (!Record.empty()) { 3315 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) { 3316 ReferencedSelectorsData.push_back(getGlobalSelectorID(F, 3317 Record[Idx++])); 3318 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx). 3319 getRawEncoding()); 3320 } 3321 } 3322 break; 3323 3324 case PP_CONDITIONAL_STACK: 3325 if (!Record.empty()) { 3326 unsigned Idx = 0, End = Record.size() - 1; 3327 bool ReachedEOFWhileSkipping = Record[Idx++]; 3328 llvm::Optional<Preprocessor::PreambleSkipInfo> SkipInfo; 3329 if (ReachedEOFWhileSkipping) { 3330 SourceLocation HashToken = ReadSourceLocation(F, Record, Idx); 3331 SourceLocation IfTokenLoc = ReadSourceLocation(F, Record, Idx); 3332 bool FoundNonSkipPortion = Record[Idx++]; 3333 bool FoundElse = Record[Idx++]; 3334 SourceLocation ElseLoc = ReadSourceLocation(F, Record, Idx); 3335 SkipInfo.emplace(HashToken, IfTokenLoc, FoundNonSkipPortion, 3336 FoundElse, ElseLoc); 3337 } 3338 SmallVector<PPConditionalInfo, 4> ConditionalStack; 3339 while (Idx < End) { 3340 auto Loc = ReadSourceLocation(F, Record, Idx); 3341 bool WasSkipping = Record[Idx++]; 3342 bool FoundNonSkip = Record[Idx++]; 3343 bool FoundElse = Record[Idx++]; 3344 ConditionalStack.push_back( 3345 {Loc, WasSkipping, FoundNonSkip, FoundElse}); 3346 } 3347 PP.setReplayablePreambleConditionalStack(ConditionalStack, SkipInfo); 3348 } 3349 break; 3350 3351 case PP_COUNTER_VALUE: 3352 if (!Record.empty() && Listener) 3353 Listener->ReadCounter(F, Record[0]); 3354 break; 3355 3356 case FILE_SORTED_DECLS: 3357 F.FileSortedDecls = (const DeclID *)Blob.data(); 3358 F.NumFileSortedDecls = Record[0]; 3359 break; 3360 3361 case SOURCE_LOCATION_OFFSETS: { 3362 F.SLocEntryOffsets = (const uint32_t *)Blob.data(); 3363 F.LocalNumSLocEntries = Record[0]; 3364 unsigned SLocSpaceSize = Record[1]; 3365 F.SLocEntryOffsetsBase = Record[2] + F.SourceManagerBlockStartOffset; 3366 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) = 3367 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries, 3368 SLocSpaceSize); 3369 if (!F.SLocEntryBaseID) { 3370 Error("ran out of source locations"); 3371 break; 3372 } 3373 // Make our entry in the range map. BaseID is negative and growing, so 3374 // we invert it. Because we invert it, though, we need the other end of 3375 // the range. 3376 unsigned RangeStart = 3377 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1; 3378 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F)); 3379 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset); 3380 3381 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing. 3382 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0); 3383 GlobalSLocOffsetMap.insert( 3384 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset 3385 - SLocSpaceSize,&F)); 3386 3387 // Initialize the remapping table. 3388 // Invalid stays invalid. 3389 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0)); 3390 // This module. Base was 2 when being compiled. 3391 F.SLocRemap.insertOrReplace(std::make_pair(2U, 3392 static_cast<int>(F.SLocEntryBaseOffset - 2))); 3393 3394 TotalNumSLocEntries += F.LocalNumSLocEntries; 3395 break; 3396 } 3397 3398 case MODULE_OFFSET_MAP: 3399 F.ModuleOffsetMap = Blob; 3400 break; 3401 3402 case SOURCE_MANAGER_LINE_TABLE: 3403 if (ParseLineTable(F, Record)) { 3404 Error("malformed SOURCE_MANAGER_LINE_TABLE in AST file"); 3405 return Failure; 3406 } 3407 break; 3408 3409 case SOURCE_LOCATION_PRELOADS: { 3410 // Need to transform from the local view (1-based IDs) to the global view, 3411 // which is based off F.SLocEntryBaseID. 3412 if (!F.PreloadSLocEntries.empty()) { 3413 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file"); 3414 return Failure; 3415 } 3416 3417 F.PreloadSLocEntries.swap(Record); 3418 break; 3419 } 3420 3421 case EXT_VECTOR_DECLS: 3422 for (unsigned I = 0, N = Record.size(); I != N; ++I) 3423 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I])); 3424 break; 3425 3426 case VTABLE_USES: 3427 if (Record.size() % 3 != 0) { 3428 Error("Invalid VTABLE_USES record"); 3429 return Failure; 3430 } 3431 3432 // Later tables overwrite earlier ones. 3433 // FIXME: Modules will have some trouble with this. This is clearly not 3434 // the right way to do this. 3435 VTableUses.clear(); 3436 3437 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) { 3438 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++])); 3439 VTableUses.push_back( 3440 ReadSourceLocation(F, Record, Idx).getRawEncoding()); 3441 VTableUses.push_back(Record[Idx++]); 3442 } 3443 break; 3444 3445 case PENDING_IMPLICIT_INSTANTIATIONS: 3446 if (PendingInstantiations.size() % 2 != 0) { 3447 Error("Invalid existing PendingInstantiations"); 3448 return Failure; 3449 } 3450 3451 if (Record.size() % 2 != 0) { 3452 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block"); 3453 return Failure; 3454 } 3455 3456 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) { 3457 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++])); 3458 PendingInstantiations.push_back( 3459 ReadSourceLocation(F, Record, I).getRawEncoding()); 3460 } 3461 break; 3462 3463 case SEMA_DECL_REFS: 3464 if (Record.size() != 3) { 3465 Error("Invalid SEMA_DECL_REFS block"); 3466 return Failure; 3467 } 3468 for (unsigned I = 0, N = Record.size(); I != N; ++I) 3469 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I])); 3470 break; 3471 3472 case PPD_ENTITIES_OFFSETS: { 3473 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data(); 3474 assert(Blob.size() % sizeof(PPEntityOffset) == 0); 3475 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset); 3476 3477 unsigned LocalBasePreprocessedEntityID = Record[0]; 3478 3479 unsigned StartingID; 3480 if (!PP.getPreprocessingRecord()) 3481 PP.createPreprocessingRecord(); 3482 if (!PP.getPreprocessingRecord()->getExternalSource()) 3483 PP.getPreprocessingRecord()->SetExternalSource(*this); 3484 StartingID 3485 = PP.getPreprocessingRecord() 3486 ->allocateLoadedEntities(F.NumPreprocessedEntities); 3487 F.BasePreprocessedEntityID = StartingID; 3488 3489 if (F.NumPreprocessedEntities > 0) { 3490 // Introduce the global -> local mapping for preprocessed entities in 3491 // this module. 3492 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F)); 3493 3494 // Introduce the local -> global mapping for preprocessed entities in 3495 // this module. 3496 F.PreprocessedEntityRemap.insertOrReplace( 3497 std::make_pair(LocalBasePreprocessedEntityID, 3498 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID)); 3499 } 3500 3501 break; 3502 } 3503 3504 case PPD_SKIPPED_RANGES: { 3505 F.PreprocessedSkippedRangeOffsets = (const PPSkippedRange*)Blob.data(); 3506 assert(Blob.size() % sizeof(PPSkippedRange) == 0); 3507 F.NumPreprocessedSkippedRanges = Blob.size() / sizeof(PPSkippedRange); 3508 3509 if (!PP.getPreprocessingRecord()) 3510 PP.createPreprocessingRecord(); 3511 if (!PP.getPreprocessingRecord()->getExternalSource()) 3512 PP.getPreprocessingRecord()->SetExternalSource(*this); 3513 F.BasePreprocessedSkippedRangeID = PP.getPreprocessingRecord() 3514 ->allocateSkippedRanges(F.NumPreprocessedSkippedRanges); 3515 3516 if (F.NumPreprocessedSkippedRanges > 0) 3517 GlobalSkippedRangeMap.insert( 3518 std::make_pair(F.BasePreprocessedSkippedRangeID, &F)); 3519 break; 3520 } 3521 3522 case DECL_UPDATE_OFFSETS: 3523 if (Record.size() % 2 != 0) { 3524 Error("invalid DECL_UPDATE_OFFSETS block in AST file"); 3525 return Failure; 3526 } 3527 for (unsigned I = 0, N = Record.size(); I != N; I += 2) { 3528 GlobalDeclID ID = getGlobalDeclID(F, Record[I]); 3529 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1])); 3530 3531 // If we've already loaded the decl, perform the updates when we finish 3532 // loading this block. 3533 if (Decl *D = GetExistingDecl(ID)) 3534 PendingUpdateRecords.push_back( 3535 PendingUpdateRecord(ID, D, /*JustLoaded=*/false)); 3536 } 3537 break; 3538 3539 case OBJC_CATEGORIES_MAP: 3540 if (F.LocalNumObjCCategoriesInMap != 0) { 3541 Error("duplicate OBJC_CATEGORIES_MAP record in AST file"); 3542 return Failure; 3543 } 3544 3545 F.LocalNumObjCCategoriesInMap = Record[0]; 3546 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data(); 3547 break; 3548 3549 case OBJC_CATEGORIES: 3550 F.ObjCCategories.swap(Record); 3551 break; 3552 3553 case CUDA_SPECIAL_DECL_REFS: 3554 // Later tables overwrite earlier ones. 3555 // FIXME: Modules will have trouble with this. 3556 CUDASpecialDeclRefs.clear(); 3557 for (unsigned I = 0, N = Record.size(); I != N; ++I) 3558 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I])); 3559 break; 3560 3561 case HEADER_SEARCH_TABLE: 3562 F.HeaderFileInfoTableData = Blob.data(); 3563 F.LocalNumHeaderFileInfos = Record[1]; 3564 if (Record[0]) { 3565 F.HeaderFileInfoTable 3566 = HeaderFileInfoLookupTable::Create( 3567 (const unsigned char *)F.HeaderFileInfoTableData + Record[0], 3568 (const unsigned char *)F.HeaderFileInfoTableData, 3569 HeaderFileInfoTrait(*this, F, 3570 &PP.getHeaderSearchInfo(), 3571 Blob.data() + Record[2])); 3572 3573 PP.getHeaderSearchInfo().SetExternalSource(this); 3574 if (!PP.getHeaderSearchInfo().getExternalLookup()) 3575 PP.getHeaderSearchInfo().SetExternalLookup(this); 3576 } 3577 break; 3578 3579 case FP_PRAGMA_OPTIONS: 3580 // Later tables overwrite earlier ones. 3581 FPPragmaOptions.swap(Record); 3582 break; 3583 3584 case OPENCL_EXTENSIONS: 3585 for (unsigned I = 0, E = Record.size(); I != E; ) { 3586 auto Name = ReadString(Record, I); 3587 auto &Opt = OpenCLExtensions.OptMap[Name]; 3588 Opt.Supported = Record[I++] != 0; 3589 Opt.Enabled = Record[I++] != 0; 3590 Opt.Avail = Record[I++]; 3591 Opt.Core = Record[I++]; 3592 } 3593 break; 3594 3595 case OPENCL_EXTENSION_TYPES: 3596 for (unsigned I = 0, E = Record.size(); I != E;) { 3597 auto TypeID = static_cast<::TypeID>(Record[I++]); 3598 auto *Type = GetType(TypeID).getTypePtr(); 3599 auto NumExt = static_cast<unsigned>(Record[I++]); 3600 for (unsigned II = 0; II != NumExt; ++II) { 3601 auto Ext = ReadString(Record, I); 3602 OpenCLTypeExtMap[Type].insert(Ext); 3603 } 3604 } 3605 break; 3606 3607 case OPENCL_EXTENSION_DECLS: 3608 for (unsigned I = 0, E = Record.size(); I != E;) { 3609 auto DeclID = static_cast<::DeclID>(Record[I++]); 3610 auto *Decl = GetDecl(DeclID); 3611 auto NumExt = static_cast<unsigned>(Record[I++]); 3612 for (unsigned II = 0; II != NumExt; ++II) { 3613 auto Ext = ReadString(Record, I); 3614 OpenCLDeclExtMap[Decl].insert(Ext); 3615 } 3616 } 3617 break; 3618 3619 case TENTATIVE_DEFINITIONS: 3620 for (unsigned I = 0, N = Record.size(); I != N; ++I) 3621 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I])); 3622 break; 3623 3624 case KNOWN_NAMESPACES: 3625 for (unsigned I = 0, N = Record.size(); I != N; ++I) 3626 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I])); 3627 break; 3628 3629 case UNDEFINED_BUT_USED: 3630 if (UndefinedButUsed.size() % 2 != 0) { 3631 Error("Invalid existing UndefinedButUsed"); 3632 return Failure; 3633 } 3634 3635 if (Record.size() % 2 != 0) { 3636 Error("invalid undefined-but-used record"); 3637 return Failure; 3638 } 3639 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) { 3640 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++])); 3641 UndefinedButUsed.push_back( 3642 ReadSourceLocation(F, Record, I).getRawEncoding()); 3643 } 3644 break; 3645 3646 case DELETE_EXPRS_TO_ANALYZE: 3647 for (unsigned I = 0, N = Record.size(); I != N;) { 3648 DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++])); 3649 const uint64_t Count = Record[I++]; 3650 DelayedDeleteExprs.push_back(Count); 3651 for (uint64_t C = 0; C < Count; ++C) { 3652 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding()); 3653 bool IsArrayForm = Record[I++] == 1; 3654 DelayedDeleteExprs.push_back(IsArrayForm); 3655 } 3656 } 3657 break; 3658 3659 case IMPORTED_MODULES: 3660 if (!F.isModule()) { 3661 // If we aren't loading a module (which has its own exports), make 3662 // all of the imported modules visible. 3663 // FIXME: Deal with macros-only imports. 3664 for (unsigned I = 0, N = Record.size(); I != N; /**/) { 3665 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]); 3666 SourceLocation Loc = ReadSourceLocation(F, Record, I); 3667 if (GlobalID) { 3668 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc)); 3669 if (DeserializationListener) 3670 DeserializationListener->ModuleImportRead(GlobalID, Loc); 3671 } 3672 } 3673 } 3674 break; 3675 3676 case MACRO_OFFSET: { 3677 if (F.LocalNumMacros != 0) { 3678 Error("duplicate MACRO_OFFSET record in AST file"); 3679 return Failure; 3680 } 3681 F.MacroOffsets = (const uint32_t *)Blob.data(); 3682 F.LocalNumMacros = Record[0]; 3683 unsigned LocalBaseMacroID = Record[1]; 3684 F.MacroOffsetsBase = Record[2] + F.ASTBlockStartOffset; 3685 F.BaseMacroID = getTotalNumMacros(); 3686 3687 if (F.LocalNumMacros > 0) { 3688 // Introduce the global -> local mapping for macros within this module. 3689 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F)); 3690 3691 // Introduce the local -> global mapping for macros within this module. 3692 F.MacroRemap.insertOrReplace( 3693 std::make_pair(LocalBaseMacroID, 3694 F.BaseMacroID - LocalBaseMacroID)); 3695 3696 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros); 3697 } 3698 break; 3699 } 3700 3701 case LATE_PARSED_TEMPLATE: 3702 LateParsedTemplates.emplace_back( 3703 std::piecewise_construct, std::forward_as_tuple(&F), 3704 std::forward_as_tuple(Record.begin(), Record.end())); 3705 break; 3706 3707 case OPTIMIZE_PRAGMA_OPTIONS: 3708 if (Record.size() != 1) { 3709 Error("invalid pragma optimize record"); 3710 return Failure; 3711 } 3712 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]); 3713 break; 3714 3715 case MSSTRUCT_PRAGMA_OPTIONS: 3716 if (Record.size() != 1) { 3717 Error("invalid pragma ms_struct record"); 3718 return Failure; 3719 } 3720 PragmaMSStructState = Record[0]; 3721 break; 3722 3723 case POINTERS_TO_MEMBERS_PRAGMA_OPTIONS: 3724 if (Record.size() != 2) { 3725 Error("invalid pragma ms_struct record"); 3726 return Failure; 3727 } 3728 PragmaMSPointersToMembersState = Record[0]; 3729 PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]); 3730 break; 3731 3732 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES: 3733 for (unsigned I = 0, N = Record.size(); I != N; ++I) 3734 UnusedLocalTypedefNameCandidates.push_back( 3735 getGlobalDeclID(F, Record[I])); 3736 break; 3737 3738 case CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH: 3739 if (Record.size() != 1) { 3740 Error("invalid cuda pragma options record"); 3741 return Failure; 3742 } 3743 ForceCUDAHostDeviceDepth = Record[0]; 3744 break; 3745 3746 case PACK_PRAGMA_OPTIONS: { 3747 if (Record.size() < 3) { 3748 Error("invalid pragma pack record"); 3749 return Failure; 3750 } 3751 PragmaPackCurrentValue = Record[0]; 3752 PragmaPackCurrentLocation = ReadSourceLocation(F, Record[1]); 3753 unsigned NumStackEntries = Record[2]; 3754 unsigned Idx = 3; 3755 // Reset the stack when importing a new module. 3756 PragmaPackStack.clear(); 3757 for (unsigned I = 0; I < NumStackEntries; ++I) { 3758 PragmaPackStackEntry Entry; 3759 Entry.Value = Record[Idx++]; 3760 Entry.Location = ReadSourceLocation(F, Record[Idx++]); 3761 Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]); 3762 PragmaPackStrings.push_back(ReadString(Record, Idx)); 3763 Entry.SlotLabel = PragmaPackStrings.back(); 3764 PragmaPackStack.push_back(Entry); 3765 } 3766 break; 3767 } 3768 3769 case FLOAT_CONTROL_PRAGMA_OPTIONS: { 3770 if (Record.size() < 3) { 3771 Error("invalid pragma pack record"); 3772 return Failure; 3773 } 3774 FpPragmaCurrentValue = FPOptionsOverride::getFromOpaqueInt(Record[0]); 3775 FpPragmaCurrentLocation = ReadSourceLocation(F, Record[1]); 3776 unsigned NumStackEntries = Record[2]; 3777 unsigned Idx = 3; 3778 // Reset the stack when importing a new module. 3779 FpPragmaStack.clear(); 3780 for (unsigned I = 0; I < NumStackEntries; ++I) { 3781 FpPragmaStackEntry Entry; 3782 Entry.Value = FPOptionsOverride::getFromOpaqueInt(Record[Idx++]); 3783 Entry.Location = ReadSourceLocation(F, Record[Idx++]); 3784 Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]); 3785 FpPragmaStrings.push_back(ReadString(Record, Idx)); 3786 Entry.SlotLabel = FpPragmaStrings.back(); 3787 FpPragmaStack.push_back(Entry); 3788 } 3789 break; 3790 } 3791 3792 case DECLS_TO_CHECK_FOR_DEFERRED_DIAGS: 3793 for (unsigned I = 0, N = Record.size(); I != N; ++I) 3794 DeclsToCheckForDeferredDiags.push_back(getGlobalDeclID(F, Record[I])); 3795 break; 3796 } 3797 } 3798 } 3799 3800 void ASTReader::ReadModuleOffsetMap(ModuleFile &F) const { 3801 assert(!F.ModuleOffsetMap.empty() && "no module offset map to read"); 3802 3803 // Additional remapping information. 3804 const unsigned char *Data = (const unsigned char*)F.ModuleOffsetMap.data(); 3805 const unsigned char *DataEnd = Data + F.ModuleOffsetMap.size(); 3806 F.ModuleOffsetMap = StringRef(); 3807 3808 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders. 3809 if (F.SLocRemap.find(0) == F.SLocRemap.end()) { 3810 F.SLocRemap.insert(std::make_pair(0U, 0)); 3811 F.SLocRemap.insert(std::make_pair(2U, 1)); 3812 } 3813 3814 // Continuous range maps we may be updating in our module. 3815 using RemapBuilder = ContinuousRangeMap<uint32_t, int, 2>::Builder; 3816 RemapBuilder SLocRemap(F.SLocRemap); 3817 RemapBuilder IdentifierRemap(F.IdentifierRemap); 3818 RemapBuilder MacroRemap(F.MacroRemap); 3819 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap); 3820 RemapBuilder SubmoduleRemap(F.SubmoduleRemap); 3821 RemapBuilder SelectorRemap(F.SelectorRemap); 3822 RemapBuilder DeclRemap(F.DeclRemap); 3823 RemapBuilder TypeRemap(F.TypeRemap); 3824 3825 while (Data < DataEnd) { 3826 // FIXME: Looking up dependency modules by filename is horrible. Let's 3827 // start fixing this with prebuilt, explicit and implicit modules and see 3828 // how it goes... 3829 using namespace llvm::support; 3830 ModuleKind Kind = static_cast<ModuleKind>( 3831 endian::readNext<uint8_t, little, unaligned>(Data)); 3832 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data); 3833 StringRef Name = StringRef((const char*)Data, Len); 3834 Data += Len; 3835 ModuleFile *OM = (Kind == MK_PrebuiltModule || Kind == MK_ExplicitModule || 3836 Kind == MK_ImplicitModule 3837 ? ModuleMgr.lookupByModuleName(Name) 3838 : ModuleMgr.lookupByFileName(Name)); 3839 if (!OM) { 3840 std::string Msg = 3841 "SourceLocation remap refers to unknown module, cannot find "; 3842 Msg.append(std::string(Name)); 3843 Error(Msg); 3844 return; 3845 } 3846 3847 uint32_t SLocOffset = 3848 endian::readNext<uint32_t, little, unaligned>(Data); 3849 uint32_t IdentifierIDOffset = 3850 endian::readNext<uint32_t, little, unaligned>(Data); 3851 uint32_t MacroIDOffset = 3852 endian::readNext<uint32_t, little, unaligned>(Data); 3853 uint32_t PreprocessedEntityIDOffset = 3854 endian::readNext<uint32_t, little, unaligned>(Data); 3855 uint32_t SubmoduleIDOffset = 3856 endian::readNext<uint32_t, little, unaligned>(Data); 3857 uint32_t SelectorIDOffset = 3858 endian::readNext<uint32_t, little, unaligned>(Data); 3859 uint32_t DeclIDOffset = 3860 endian::readNext<uint32_t, little, unaligned>(Data); 3861 uint32_t TypeIndexOffset = 3862 endian::readNext<uint32_t, little, unaligned>(Data); 3863 3864 uint32_t None = std::numeric_limits<uint32_t>::max(); 3865 3866 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset, 3867 RemapBuilder &Remap) { 3868 if (Offset != None) 3869 Remap.insert(std::make_pair(Offset, 3870 static_cast<int>(BaseOffset - Offset))); 3871 }; 3872 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap); 3873 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap); 3874 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap); 3875 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID, 3876 PreprocessedEntityRemap); 3877 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap); 3878 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap); 3879 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap); 3880 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap); 3881 3882 // Global -> local mappings. 3883 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset; 3884 } 3885 } 3886 3887 ASTReader::ASTReadResult 3888 ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F, 3889 const ModuleFile *ImportedBy, 3890 unsigned ClientLoadCapabilities) { 3891 unsigned Idx = 0; 3892 F.ModuleMapPath = ReadPath(F, Record, Idx); 3893 3894 // Try to resolve ModuleName in the current header search context and 3895 // verify that it is found in the same module map file as we saved. If the 3896 // top-level AST file is a main file, skip this check because there is no 3897 // usable header search context. 3898 assert(!F.ModuleName.empty() && 3899 "MODULE_NAME should come before MODULE_MAP_FILE"); 3900 if (F.Kind == MK_ImplicitModule && ModuleMgr.begin()->Kind != MK_MainFile) { 3901 // An implicitly-loaded module file should have its module listed in some 3902 // module map file that we've already loaded. 3903 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName); 3904 auto &Map = PP.getHeaderSearchInfo().getModuleMap(); 3905 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr; 3906 // Don't emit module relocation error if we have -fno-validate-pch 3907 if (!PP.getPreprocessorOpts().DisablePCHValidation && !ModMap) { 3908 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) { 3909 if (auto ASTFE = M ? M->getASTFile() : None) { 3910 // This module was defined by an imported (explicit) module. 3911 Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName 3912 << ASTFE->getName(); 3913 } else { 3914 // This module was built with a different module map. 3915 Diag(diag::err_imported_module_not_found) 3916 << F.ModuleName << F.FileName 3917 << (ImportedBy ? ImportedBy->FileName : "") << F.ModuleMapPath 3918 << !ImportedBy; 3919 // In case it was imported by a PCH, there's a chance the user is 3920 // just missing to include the search path to the directory containing 3921 // the modulemap. 3922 if (ImportedBy && ImportedBy->Kind == MK_PCH) 3923 Diag(diag::note_imported_by_pch_module_not_found) 3924 << llvm::sys::path::parent_path(F.ModuleMapPath); 3925 } 3926 } 3927 return OutOfDate; 3928 } 3929 3930 assert(M && M->Name == F.ModuleName && "found module with different name"); 3931 3932 // Check the primary module map file. 3933 auto StoredModMap = FileMgr.getFile(F.ModuleMapPath); 3934 if (!StoredModMap || *StoredModMap != ModMap) { 3935 assert(ModMap && "found module is missing module map file"); 3936 assert((ImportedBy || F.Kind == MK_ImplicitModule) && 3937 "top-level import should be verified"); 3938 bool NotImported = F.Kind == MK_ImplicitModule && !ImportedBy; 3939 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) 3940 Diag(diag::err_imported_module_modmap_changed) 3941 << F.ModuleName << (NotImported ? F.FileName : ImportedBy->FileName) 3942 << ModMap->getName() << F.ModuleMapPath << NotImported; 3943 return OutOfDate; 3944 } 3945 3946 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps; 3947 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) { 3948 // FIXME: we should use input files rather than storing names. 3949 std::string Filename = ReadPath(F, Record, Idx); 3950 auto F = FileMgr.getFile(Filename, false, false); 3951 if (!F) { 3952 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) 3953 Error("could not find file '" + Filename +"' referenced by AST file"); 3954 return OutOfDate; 3955 } 3956 AdditionalStoredMaps.insert(*F); 3957 } 3958 3959 // Check any additional module map files (e.g. module.private.modulemap) 3960 // that are not in the pcm. 3961 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) { 3962 for (const FileEntry *ModMap : *AdditionalModuleMaps) { 3963 // Remove files that match 3964 // Note: SmallPtrSet::erase is really remove 3965 if (!AdditionalStoredMaps.erase(ModMap)) { 3966 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) 3967 Diag(diag::err_module_different_modmap) 3968 << F.ModuleName << /*new*/0 << ModMap->getName(); 3969 return OutOfDate; 3970 } 3971 } 3972 } 3973 3974 // Check any additional module map files that are in the pcm, but not 3975 // found in header search. Cases that match are already removed. 3976 for (const FileEntry *ModMap : AdditionalStoredMaps) { 3977 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) 3978 Diag(diag::err_module_different_modmap) 3979 << F.ModuleName << /*not new*/1 << ModMap->getName(); 3980 return OutOfDate; 3981 } 3982 } 3983 3984 if (Listener) 3985 Listener->ReadModuleMapFile(F.ModuleMapPath); 3986 return Success; 3987 } 3988 3989 /// Move the given method to the back of the global list of methods. 3990 static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) { 3991 // Find the entry for this selector in the method pool. 3992 Sema::GlobalMethodPool::iterator Known 3993 = S.MethodPool.find(Method->getSelector()); 3994 if (Known == S.MethodPool.end()) 3995 return; 3996 3997 // Retrieve the appropriate method list. 3998 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first 3999 : Known->second.second; 4000 bool Found = false; 4001 for (ObjCMethodList *List = &Start; List; List = List->getNext()) { 4002 if (!Found) { 4003 if (List->getMethod() == Method) { 4004 Found = true; 4005 } else { 4006 // Keep searching. 4007 continue; 4008 } 4009 } 4010 4011 if (List->getNext()) 4012 List->setMethod(List->getNext()->getMethod()); 4013 else 4014 List->setMethod(Method); 4015 } 4016 } 4017 4018 void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) { 4019 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?"); 4020 for (Decl *D : Names) { 4021 bool wasHidden = !D->isUnconditionallyVisible(); 4022 D->setVisibleDespiteOwningModule(); 4023 4024 if (wasHidden && SemaObj) { 4025 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) { 4026 moveMethodToBackOfGlobalList(*SemaObj, Method); 4027 } 4028 } 4029 } 4030 } 4031 4032 void ASTReader::makeModuleVisible(Module *Mod, 4033 Module::NameVisibilityKind NameVisibility, 4034 SourceLocation ImportLoc) { 4035 llvm::SmallPtrSet<Module *, 4> Visited; 4036 SmallVector<Module *, 4> Stack; 4037 Stack.push_back(Mod); 4038 while (!Stack.empty()) { 4039 Mod = Stack.pop_back_val(); 4040 4041 if (NameVisibility <= Mod->NameVisibility) { 4042 // This module already has this level of visibility (or greater), so 4043 // there is nothing more to do. 4044 continue; 4045 } 4046 4047 if (Mod->isUnimportable()) { 4048 // Modules that aren't importable cannot be made visible. 4049 continue; 4050 } 4051 4052 // Update the module's name visibility. 4053 Mod->NameVisibility = NameVisibility; 4054 4055 // If we've already deserialized any names from this module, 4056 // mark them as visible. 4057 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod); 4058 if (Hidden != HiddenNamesMap.end()) { 4059 auto HiddenNames = std::move(*Hidden); 4060 HiddenNamesMap.erase(Hidden); 4061 makeNamesVisible(HiddenNames.second, HiddenNames.first); 4062 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() && 4063 "making names visible added hidden names"); 4064 } 4065 4066 // Push any exported modules onto the stack to be marked as visible. 4067 SmallVector<Module *, 16> Exports; 4068 Mod->getExportedModules(Exports); 4069 for (SmallVectorImpl<Module *>::iterator 4070 I = Exports.begin(), E = Exports.end(); I != E; ++I) { 4071 Module *Exported = *I; 4072 if (Visited.insert(Exported).second) 4073 Stack.push_back(Exported); 4074 } 4075 } 4076 } 4077 4078 /// We've merged the definition \p MergedDef into the existing definition 4079 /// \p Def. Ensure that \p Def is made visible whenever \p MergedDef is made 4080 /// visible. 4081 void ASTReader::mergeDefinitionVisibility(NamedDecl *Def, 4082 NamedDecl *MergedDef) { 4083 if (!Def->isUnconditionallyVisible()) { 4084 // If MergedDef is visible or becomes visible, make the definition visible. 4085 if (MergedDef->isUnconditionallyVisible()) 4086 Def->setVisibleDespiteOwningModule(); 4087 else { 4088 getContext().mergeDefinitionIntoModule( 4089 Def, MergedDef->getImportedOwningModule(), 4090 /*NotifyListeners*/ false); 4091 PendingMergedDefinitionsToDeduplicate.insert(Def); 4092 } 4093 } 4094 } 4095 4096 bool ASTReader::loadGlobalIndex() { 4097 if (GlobalIndex) 4098 return false; 4099 4100 if (TriedLoadingGlobalIndex || !UseGlobalIndex || 4101 !PP.getLangOpts().Modules) 4102 return true; 4103 4104 // Try to load the global index. 4105 TriedLoadingGlobalIndex = true; 4106 StringRef ModuleCachePath 4107 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath(); 4108 std::pair<GlobalModuleIndex *, llvm::Error> Result = 4109 GlobalModuleIndex::readIndex(ModuleCachePath); 4110 if (llvm::Error Err = std::move(Result.second)) { 4111 assert(!Result.first); 4112 consumeError(std::move(Err)); // FIXME this drops errors on the floor. 4113 return true; 4114 } 4115 4116 GlobalIndex.reset(Result.first); 4117 ModuleMgr.setGlobalIndex(GlobalIndex.get()); 4118 return false; 4119 } 4120 4121 bool ASTReader::isGlobalIndexUnavailable() const { 4122 return PP.getLangOpts().Modules && UseGlobalIndex && 4123 !hasGlobalIndex() && TriedLoadingGlobalIndex; 4124 } 4125 4126 static void updateModuleTimestamp(ModuleFile &MF) { 4127 // Overwrite the timestamp file contents so that file's mtime changes. 4128 std::string TimestampFilename = MF.getTimestampFilename(); 4129 std::error_code EC; 4130 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::OF_Text); 4131 if (EC) 4132 return; 4133 OS << "Timestamp file\n"; 4134 OS.close(); 4135 OS.clear_error(); // Avoid triggering a fatal error. 4136 } 4137 4138 /// Given a cursor at the start of an AST file, scan ahead and drop the 4139 /// cursor into the start of the given block ID, returning false on success and 4140 /// true on failure. 4141 static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) { 4142 while (true) { 4143 Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance(); 4144 if (!MaybeEntry) { 4145 // FIXME this drops errors on the floor. 4146 consumeError(MaybeEntry.takeError()); 4147 return true; 4148 } 4149 llvm::BitstreamEntry Entry = MaybeEntry.get(); 4150 4151 switch (Entry.Kind) { 4152 case llvm::BitstreamEntry::Error: 4153 case llvm::BitstreamEntry::EndBlock: 4154 return true; 4155 4156 case llvm::BitstreamEntry::Record: 4157 // Ignore top-level records. 4158 if (Expected<unsigned> Skipped = Cursor.skipRecord(Entry.ID)) 4159 break; 4160 else { 4161 // FIXME this drops errors on the floor. 4162 consumeError(Skipped.takeError()); 4163 return true; 4164 } 4165 4166 case llvm::BitstreamEntry::SubBlock: 4167 if (Entry.ID == BlockID) { 4168 if (llvm::Error Err = Cursor.EnterSubBlock(BlockID)) { 4169 // FIXME this drops the error on the floor. 4170 consumeError(std::move(Err)); 4171 return true; 4172 } 4173 // Found it! 4174 return false; 4175 } 4176 4177 if (llvm::Error Err = Cursor.SkipBlock()) { 4178 // FIXME this drops the error on the floor. 4179 consumeError(std::move(Err)); 4180 return true; 4181 } 4182 } 4183 } 4184 } 4185 4186 ASTReader::ASTReadResult ASTReader::ReadAST(StringRef FileName, 4187 ModuleKind Type, 4188 SourceLocation ImportLoc, 4189 unsigned ClientLoadCapabilities, 4190 SmallVectorImpl<ImportedSubmodule> *Imported) { 4191 llvm::SaveAndRestore<SourceLocation> 4192 SetCurImportLocRAII(CurrentImportLoc, ImportLoc); 4193 4194 // Defer any pending actions until we get to the end of reading the AST file. 4195 Deserializing AnASTFile(this); 4196 4197 // Bump the generation number. 4198 unsigned PreviousGeneration = 0; 4199 if (ContextObj) 4200 PreviousGeneration = incrementGeneration(*ContextObj); 4201 4202 unsigned NumModules = ModuleMgr.size(); 4203 auto removeModulesAndReturn = [&](ASTReadResult ReadResult) { 4204 assert(ReadResult && "expected to return error"); 4205 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, 4206 PP.getLangOpts().Modules 4207 ? &PP.getHeaderSearchInfo().getModuleMap() 4208 : nullptr); 4209 4210 // If we find that any modules are unusable, the global index is going 4211 // to be out-of-date. Just remove it. 4212 GlobalIndex.reset(); 4213 ModuleMgr.setGlobalIndex(nullptr); 4214 return ReadResult; 4215 }; 4216 4217 SmallVector<ImportedModule, 4> Loaded; 4218 switch (ASTReadResult ReadResult = 4219 ReadASTCore(FileName, Type, ImportLoc, 4220 /*ImportedBy=*/nullptr, Loaded, 0, 0, 4221 ASTFileSignature(), ClientLoadCapabilities)) { 4222 case Failure: 4223 case Missing: 4224 case OutOfDate: 4225 case VersionMismatch: 4226 case ConfigurationMismatch: 4227 case HadErrors: 4228 return removeModulesAndReturn(ReadResult); 4229 case Success: 4230 break; 4231 } 4232 4233 // Here comes stuff that we only do once the entire chain is loaded. 4234 4235 // Load the AST blocks of all of the modules that we loaded. We can still 4236 // hit errors parsing the ASTs at this point. 4237 for (ImportedModule &M : Loaded) { 4238 ModuleFile &F = *M.Mod; 4239 4240 // Read the AST block. 4241 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities)) 4242 return removeModulesAndReturn(Result); 4243 4244 // The AST block should always have a definition for the main module. 4245 if (F.isModule() && !F.DidReadTopLevelSubmodule) { 4246 Error(diag::err_module_file_missing_top_level_submodule, F.FileName); 4247 return removeModulesAndReturn(Failure); 4248 } 4249 4250 // Read the extension blocks. 4251 while (!SkipCursorToBlock(F.Stream, EXTENSION_BLOCK_ID)) { 4252 if (ASTReadResult Result = ReadExtensionBlock(F)) 4253 return removeModulesAndReturn(Result); 4254 } 4255 4256 // Once read, set the ModuleFile bit base offset and update the size in 4257 // bits of all files we've seen. 4258 F.GlobalBitOffset = TotalModulesSizeInBits; 4259 TotalModulesSizeInBits += F.SizeInBits; 4260 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F)); 4261 } 4262 4263 // Preload source locations and interesting indentifiers. 4264 for (ImportedModule &M : Loaded) { 4265 ModuleFile &F = *M.Mod; 4266 4267 // Preload SLocEntries. 4268 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) { 4269 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID; 4270 // Load it through the SourceManager and don't call ReadSLocEntry() 4271 // directly because the entry may have already been loaded in which case 4272 // calling ReadSLocEntry() directly would trigger an assertion in 4273 // SourceManager. 4274 SourceMgr.getLoadedSLocEntryByID(Index); 4275 } 4276 4277 // Map the original source file ID into the ID space of the current 4278 // compilation. 4279 if (F.OriginalSourceFileID.isValid()) { 4280 F.OriginalSourceFileID = FileID::get( 4281 F.SLocEntryBaseID + F.OriginalSourceFileID.getOpaqueValue() - 1); 4282 } 4283 4284 // Preload all the pending interesting identifiers by marking them out of 4285 // date. 4286 for (auto Offset : F.PreloadIdentifierOffsets) { 4287 const unsigned char *Data = reinterpret_cast<const unsigned char *>( 4288 F.IdentifierTableData + Offset); 4289 4290 ASTIdentifierLookupTrait Trait(*this, F); 4291 auto KeyDataLen = Trait.ReadKeyDataLength(Data); 4292 auto Key = Trait.ReadKey(Data, KeyDataLen.first); 4293 auto &II = PP.getIdentifierTable().getOwn(Key); 4294 II.setOutOfDate(true); 4295 4296 // Mark this identifier as being from an AST file so that we can track 4297 // whether we need to serialize it. 4298 markIdentifierFromAST(*this, II); 4299 4300 // Associate the ID with the identifier so that the writer can reuse it. 4301 auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first); 4302 SetIdentifierInfo(ID, &II); 4303 } 4304 } 4305 4306 // Setup the import locations and notify the module manager that we've 4307 // committed to these module files. 4308 for (ImportedModule &M : Loaded) { 4309 ModuleFile &F = *M.Mod; 4310 4311 ModuleMgr.moduleFileAccepted(&F); 4312 4313 // Set the import location. 4314 F.DirectImportLoc = ImportLoc; 4315 // FIXME: We assume that locations from PCH / preamble do not need 4316 // any translation. 4317 if (!M.ImportedBy) 4318 F.ImportLoc = M.ImportLoc; 4319 else 4320 F.ImportLoc = TranslateSourceLocation(*M.ImportedBy, M.ImportLoc); 4321 } 4322 4323 if (!PP.getLangOpts().CPlusPlus || 4324 (Type != MK_ImplicitModule && Type != MK_ExplicitModule && 4325 Type != MK_PrebuiltModule)) { 4326 // Mark all of the identifiers in the identifier table as being out of date, 4327 // so that various accessors know to check the loaded modules when the 4328 // identifier is used. 4329 // 4330 // For C++ modules, we don't need information on many identifiers (just 4331 // those that provide macros or are poisoned), so we mark all of 4332 // the interesting ones via PreloadIdentifierOffsets. 4333 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(), 4334 IdEnd = PP.getIdentifierTable().end(); 4335 Id != IdEnd; ++Id) 4336 Id->second->setOutOfDate(true); 4337 } 4338 // Mark selectors as out of date. 4339 for (auto Sel : SelectorGeneration) 4340 SelectorOutOfDate[Sel.first] = true; 4341 4342 // Resolve any unresolved module exports. 4343 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) { 4344 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I]; 4345 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID); 4346 Module *ResolvedMod = getSubmodule(GlobalID); 4347 4348 switch (Unresolved.Kind) { 4349 case UnresolvedModuleRef::Conflict: 4350 if (ResolvedMod) { 4351 Module::Conflict Conflict; 4352 Conflict.Other = ResolvedMod; 4353 Conflict.Message = Unresolved.String.str(); 4354 Unresolved.Mod->Conflicts.push_back(Conflict); 4355 } 4356 continue; 4357 4358 case UnresolvedModuleRef::Import: 4359 if (ResolvedMod) 4360 Unresolved.Mod->Imports.insert(ResolvedMod); 4361 continue; 4362 4363 case UnresolvedModuleRef::Export: 4364 if (ResolvedMod || Unresolved.IsWildcard) 4365 Unresolved.Mod->Exports.push_back( 4366 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard)); 4367 continue; 4368 } 4369 } 4370 UnresolvedModuleRefs.clear(); 4371 4372 if (Imported) 4373 Imported->append(ImportedModules.begin(), 4374 ImportedModules.end()); 4375 4376 // FIXME: How do we load the 'use'd modules? They may not be submodules. 4377 // Might be unnecessary as use declarations are only used to build the 4378 // module itself. 4379 4380 if (ContextObj) 4381 InitializeContext(); 4382 4383 if (SemaObj) 4384 UpdateSema(); 4385 4386 if (DeserializationListener) 4387 DeserializationListener->ReaderInitialized(this); 4388 4389 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule(); 4390 if (PrimaryModule.OriginalSourceFileID.isValid()) { 4391 // If this AST file is a precompiled preamble, then set the 4392 // preamble file ID of the source manager to the file source file 4393 // from which the preamble was built. 4394 if (Type == MK_Preamble) { 4395 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID); 4396 } else if (Type == MK_MainFile) { 4397 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID); 4398 } 4399 } 4400 4401 // For any Objective-C class definitions we have already loaded, make sure 4402 // that we load any additional categories. 4403 if (ContextObj) { 4404 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) { 4405 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(), 4406 ObjCClassesLoaded[I], 4407 PreviousGeneration); 4408 } 4409 } 4410 4411 if (PP.getHeaderSearchInfo() 4412 .getHeaderSearchOpts() 4413 .ModulesValidateOncePerBuildSession) { 4414 // Now we are certain that the module and all modules it depends on are 4415 // up to date. Create or update timestamp files for modules that are 4416 // located in the module cache (not for PCH files that could be anywhere 4417 // in the filesystem). 4418 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) { 4419 ImportedModule &M = Loaded[I]; 4420 if (M.Mod->Kind == MK_ImplicitModule) { 4421 updateModuleTimestamp(*M.Mod); 4422 } 4423 } 4424 } 4425 4426 return Success; 4427 } 4428 4429 static ASTFileSignature readASTFileSignature(StringRef PCH); 4430 4431 /// Whether \p Stream doesn't start with the AST/PCH file magic number 'CPCH'. 4432 static llvm::Error doesntStartWithASTFileMagic(BitstreamCursor &Stream) { 4433 // FIXME checking magic headers is done in other places such as 4434 // SerializedDiagnosticReader and GlobalModuleIndex, but error handling isn't 4435 // always done the same. Unify it all with a helper. 4436 if (!Stream.canSkipToPos(4)) 4437 return llvm::createStringError(std::errc::illegal_byte_sequence, 4438 "file too small to contain AST file magic"); 4439 for (unsigned C : {'C', 'P', 'C', 'H'}) 4440 if (Expected<llvm::SimpleBitstreamCursor::word_t> Res = Stream.Read(8)) { 4441 if (Res.get() != C) 4442 return llvm::createStringError( 4443 std::errc::illegal_byte_sequence, 4444 "file doesn't start with AST file magic"); 4445 } else 4446 return Res.takeError(); 4447 return llvm::Error::success(); 4448 } 4449 4450 static unsigned moduleKindForDiagnostic(ModuleKind Kind) { 4451 switch (Kind) { 4452 case MK_PCH: 4453 return 0; // PCH 4454 case MK_ImplicitModule: 4455 case MK_ExplicitModule: 4456 case MK_PrebuiltModule: 4457 return 1; // module 4458 case MK_MainFile: 4459 case MK_Preamble: 4460 return 2; // main source file 4461 } 4462 llvm_unreachable("unknown module kind"); 4463 } 4464 4465 ASTReader::ASTReadResult 4466 ASTReader::ReadASTCore(StringRef FileName, 4467 ModuleKind Type, 4468 SourceLocation ImportLoc, 4469 ModuleFile *ImportedBy, 4470 SmallVectorImpl<ImportedModule> &Loaded, 4471 off_t ExpectedSize, time_t ExpectedModTime, 4472 ASTFileSignature ExpectedSignature, 4473 unsigned ClientLoadCapabilities) { 4474 ModuleFile *M; 4475 std::string ErrorStr; 4476 ModuleManager::AddModuleResult AddResult 4477 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy, 4478 getGeneration(), ExpectedSize, ExpectedModTime, 4479 ExpectedSignature, readASTFileSignature, 4480 M, ErrorStr); 4481 4482 switch (AddResult) { 4483 case ModuleManager::AlreadyLoaded: 4484 Diag(diag::remark_module_import) 4485 << M->ModuleName << M->FileName << (ImportedBy ? true : false) 4486 << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef()); 4487 return Success; 4488 4489 case ModuleManager::NewlyLoaded: 4490 // Load module file below. 4491 break; 4492 4493 case ModuleManager::Missing: 4494 // The module file was missing; if the client can handle that, return 4495 // it. 4496 if (ClientLoadCapabilities & ARR_Missing) 4497 return Missing; 4498 4499 // Otherwise, return an error. 4500 Diag(diag::err_ast_file_not_found) 4501 << moduleKindForDiagnostic(Type) << FileName << !ErrorStr.empty() 4502 << ErrorStr; 4503 return Failure; 4504 4505 case ModuleManager::OutOfDate: 4506 // We couldn't load the module file because it is out-of-date. If the 4507 // client can handle out-of-date, return it. 4508 if (ClientLoadCapabilities & ARR_OutOfDate) 4509 return OutOfDate; 4510 4511 // Otherwise, return an error. 4512 Diag(diag::err_ast_file_out_of_date) 4513 << moduleKindForDiagnostic(Type) << FileName << !ErrorStr.empty() 4514 << ErrorStr; 4515 return Failure; 4516 } 4517 4518 assert(M && "Missing module file"); 4519 4520 bool ShouldFinalizePCM = false; 4521 auto FinalizeOrDropPCM = llvm::make_scope_exit([&]() { 4522 auto &MC = getModuleManager().getModuleCache(); 4523 if (ShouldFinalizePCM) 4524 MC.finalizePCM(FileName); 4525 else 4526 MC.tryToDropPCM(FileName); 4527 }); 4528 ModuleFile &F = *M; 4529 BitstreamCursor &Stream = F.Stream; 4530 Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(*F.Buffer)); 4531 F.SizeInBits = F.Buffer->getBufferSize() * 8; 4532 4533 // Sniff for the signature. 4534 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) { 4535 Diag(diag::err_ast_file_invalid) 4536 << moduleKindForDiagnostic(Type) << FileName << std::move(Err); 4537 return Failure; 4538 } 4539 4540 // This is used for compatibility with older PCH formats. 4541 bool HaveReadControlBlock = false; 4542 while (true) { 4543 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); 4544 if (!MaybeEntry) { 4545 Error(MaybeEntry.takeError()); 4546 return Failure; 4547 } 4548 llvm::BitstreamEntry Entry = MaybeEntry.get(); 4549 4550 switch (Entry.Kind) { 4551 case llvm::BitstreamEntry::Error: 4552 case llvm::BitstreamEntry::Record: 4553 case llvm::BitstreamEntry::EndBlock: 4554 Error("invalid record at top-level of AST file"); 4555 return Failure; 4556 4557 case llvm::BitstreamEntry::SubBlock: 4558 break; 4559 } 4560 4561 switch (Entry.ID) { 4562 case CONTROL_BLOCK_ID: 4563 HaveReadControlBlock = true; 4564 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) { 4565 case Success: 4566 // Check that we didn't try to load a non-module AST file as a module. 4567 // 4568 // FIXME: Should we also perform the converse check? Loading a module as 4569 // a PCH file sort of works, but it's a bit wonky. 4570 if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule || 4571 Type == MK_PrebuiltModule) && 4572 F.ModuleName.empty()) { 4573 auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure; 4574 if (Result != OutOfDate || 4575 (ClientLoadCapabilities & ARR_OutOfDate) == 0) 4576 Diag(diag::err_module_file_not_module) << FileName; 4577 return Result; 4578 } 4579 break; 4580 4581 case Failure: return Failure; 4582 case Missing: return Missing; 4583 case OutOfDate: return OutOfDate; 4584 case VersionMismatch: return VersionMismatch; 4585 case ConfigurationMismatch: return ConfigurationMismatch; 4586 case HadErrors: return HadErrors; 4587 } 4588 break; 4589 4590 case AST_BLOCK_ID: 4591 if (!HaveReadControlBlock) { 4592 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0) 4593 Diag(diag::err_pch_version_too_old); 4594 return VersionMismatch; 4595 } 4596 4597 // Record that we've loaded this module. 4598 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc)); 4599 ShouldFinalizePCM = true; 4600 return Success; 4601 4602 case UNHASHED_CONTROL_BLOCK_ID: 4603 // This block is handled using look-ahead during ReadControlBlock. We 4604 // shouldn't get here! 4605 Error("malformed block record in AST file"); 4606 return Failure; 4607 4608 default: 4609 if (llvm::Error Err = Stream.SkipBlock()) { 4610 Error(std::move(Err)); 4611 return Failure; 4612 } 4613 break; 4614 } 4615 } 4616 4617 llvm_unreachable("unexpected break; expected return"); 4618 } 4619 4620 ASTReader::ASTReadResult 4621 ASTReader::readUnhashedControlBlock(ModuleFile &F, bool WasImportedBy, 4622 unsigned ClientLoadCapabilities) { 4623 const HeaderSearchOptions &HSOpts = 4624 PP.getHeaderSearchInfo().getHeaderSearchOpts(); 4625 bool AllowCompatibleConfigurationMismatch = 4626 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule; 4627 4628 ASTReadResult Result = readUnhashedControlBlockImpl( 4629 &F, F.Data, ClientLoadCapabilities, AllowCompatibleConfigurationMismatch, 4630 Listener.get(), 4631 WasImportedBy ? false : HSOpts.ModulesValidateDiagnosticOptions); 4632 4633 // If F was directly imported by another module, it's implicitly validated by 4634 // the importing module. 4635 if (DisableValidation || WasImportedBy || 4636 (AllowConfigurationMismatch && Result == ConfigurationMismatch)) 4637 return Success; 4638 4639 if (Result == Failure) { 4640 Error("malformed block record in AST file"); 4641 return Failure; 4642 } 4643 4644 if (Result == OutOfDate && F.Kind == MK_ImplicitModule) { 4645 // If this module has already been finalized in the ModuleCache, we're stuck 4646 // with it; we can only load a single version of each module. 4647 // 4648 // This can happen when a module is imported in two contexts: in one, as a 4649 // user module; in another, as a system module (due to an import from 4650 // another module marked with the [system] flag). It usually indicates a 4651 // bug in the module map: this module should also be marked with [system]. 4652 // 4653 // If -Wno-system-headers (the default), and the first import is as a 4654 // system module, then validation will fail during the as-user import, 4655 // since -Werror flags won't have been validated. However, it's reasonable 4656 // to treat this consistently as a system module. 4657 // 4658 // If -Wsystem-headers, the PCM on disk was built with 4659 // -Wno-system-headers, and the first import is as a user module, then 4660 // validation will fail during the as-system import since the PCM on disk 4661 // doesn't guarantee that -Werror was respected. However, the -Werror 4662 // flags were checked during the initial as-user import. 4663 if (getModuleManager().getModuleCache().isPCMFinal(F.FileName)) { 4664 Diag(diag::warn_module_system_bit_conflict) << F.FileName; 4665 return Success; 4666 } 4667 } 4668 4669 return Result; 4670 } 4671 4672 ASTReader::ASTReadResult ASTReader::readUnhashedControlBlockImpl( 4673 ModuleFile *F, llvm::StringRef StreamData, unsigned ClientLoadCapabilities, 4674 bool AllowCompatibleConfigurationMismatch, ASTReaderListener *Listener, 4675 bool ValidateDiagnosticOptions) { 4676 // Initialize a stream. 4677 BitstreamCursor Stream(StreamData); 4678 4679 // Sniff for the signature. 4680 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) { 4681 // FIXME this drops the error on the floor. 4682 consumeError(std::move(Err)); 4683 return Failure; 4684 } 4685 4686 // Scan for the UNHASHED_CONTROL_BLOCK_ID block. 4687 if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID)) 4688 return Failure; 4689 4690 // Read all of the records in the options block. 4691 RecordData Record; 4692 ASTReadResult Result = Success; 4693 while (true) { 4694 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); 4695 if (!MaybeEntry) { 4696 // FIXME this drops the error on the floor. 4697 consumeError(MaybeEntry.takeError()); 4698 return Failure; 4699 } 4700 llvm::BitstreamEntry Entry = MaybeEntry.get(); 4701 4702 switch (Entry.Kind) { 4703 case llvm::BitstreamEntry::Error: 4704 case llvm::BitstreamEntry::SubBlock: 4705 return Failure; 4706 4707 case llvm::BitstreamEntry::EndBlock: 4708 return Result; 4709 4710 case llvm::BitstreamEntry::Record: 4711 // The interesting case. 4712 break; 4713 } 4714 4715 // Read and process a record. 4716 Record.clear(); 4717 Expected<unsigned> MaybeRecordType = Stream.readRecord(Entry.ID, Record); 4718 if (!MaybeRecordType) { 4719 // FIXME this drops the error. 4720 return Failure; 4721 } 4722 switch ((UnhashedControlBlockRecordTypes)MaybeRecordType.get()) { 4723 case SIGNATURE: 4724 if (F) 4725 F->Signature = ASTFileSignature::create(Record.begin(), Record.end()); 4726 break; 4727 case AST_BLOCK_HASH: 4728 if (F) 4729 F->ASTBlockHash = 4730 ASTFileSignature::create(Record.begin(), Record.end()); 4731 break; 4732 case DIAGNOSTIC_OPTIONS: { 4733 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0; 4734 if (Listener && ValidateDiagnosticOptions && 4735 !AllowCompatibleConfigurationMismatch && 4736 ParseDiagnosticOptions(Record, Complain, *Listener)) 4737 Result = OutOfDate; // Don't return early. Read the signature. 4738 break; 4739 } 4740 case DIAG_PRAGMA_MAPPINGS: 4741 if (!F) 4742 break; 4743 if (F->PragmaDiagMappings.empty()) 4744 F->PragmaDiagMappings.swap(Record); 4745 else 4746 F->PragmaDiagMappings.insert(F->PragmaDiagMappings.end(), 4747 Record.begin(), Record.end()); 4748 break; 4749 } 4750 } 4751 } 4752 4753 /// Parse a record and blob containing module file extension metadata. 4754 static bool parseModuleFileExtensionMetadata( 4755 const SmallVectorImpl<uint64_t> &Record, 4756 StringRef Blob, 4757 ModuleFileExtensionMetadata &Metadata) { 4758 if (Record.size() < 4) return true; 4759 4760 Metadata.MajorVersion = Record[0]; 4761 Metadata.MinorVersion = Record[1]; 4762 4763 unsigned BlockNameLen = Record[2]; 4764 unsigned UserInfoLen = Record[3]; 4765 4766 if (BlockNameLen + UserInfoLen > Blob.size()) return true; 4767 4768 Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen); 4769 Metadata.UserInfo = std::string(Blob.data() + BlockNameLen, 4770 Blob.data() + BlockNameLen + UserInfoLen); 4771 return false; 4772 } 4773 4774 ASTReader::ASTReadResult ASTReader::ReadExtensionBlock(ModuleFile &F) { 4775 BitstreamCursor &Stream = F.Stream; 4776 4777 RecordData Record; 4778 while (true) { 4779 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); 4780 if (!MaybeEntry) { 4781 Error(MaybeEntry.takeError()); 4782 return Failure; 4783 } 4784 llvm::BitstreamEntry Entry = MaybeEntry.get(); 4785 4786 switch (Entry.Kind) { 4787 case llvm::BitstreamEntry::SubBlock: 4788 if (llvm::Error Err = Stream.SkipBlock()) { 4789 Error(std::move(Err)); 4790 return Failure; 4791 } 4792 continue; 4793 4794 case llvm::BitstreamEntry::EndBlock: 4795 return Success; 4796 4797 case llvm::BitstreamEntry::Error: 4798 return HadErrors; 4799 4800 case llvm::BitstreamEntry::Record: 4801 break; 4802 } 4803 4804 Record.clear(); 4805 StringRef Blob; 4806 Expected<unsigned> MaybeRecCode = 4807 Stream.readRecord(Entry.ID, Record, &Blob); 4808 if (!MaybeRecCode) { 4809 Error(MaybeRecCode.takeError()); 4810 return Failure; 4811 } 4812 switch (MaybeRecCode.get()) { 4813 case EXTENSION_METADATA: { 4814 ModuleFileExtensionMetadata Metadata; 4815 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata)) { 4816 Error("malformed EXTENSION_METADATA in AST file"); 4817 return Failure; 4818 } 4819 4820 // Find a module file extension with this block name. 4821 auto Known = ModuleFileExtensions.find(Metadata.BlockName); 4822 if (Known == ModuleFileExtensions.end()) break; 4823 4824 // Form a reader. 4825 if (auto Reader = Known->second->createExtensionReader(Metadata, *this, 4826 F, Stream)) { 4827 F.ExtensionReaders.push_back(std::move(Reader)); 4828 } 4829 4830 break; 4831 } 4832 } 4833 } 4834 4835 return Success; 4836 } 4837 4838 void ASTReader::InitializeContext() { 4839 assert(ContextObj && "no context to initialize"); 4840 ASTContext &Context = *ContextObj; 4841 4842 // If there's a listener, notify them that we "read" the translation unit. 4843 if (DeserializationListener) 4844 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID, 4845 Context.getTranslationUnitDecl()); 4846 4847 // FIXME: Find a better way to deal with collisions between these 4848 // built-in types. Right now, we just ignore the problem. 4849 4850 // Load the special types. 4851 if (SpecialTypes.size() >= NumSpecialTypeIDs) { 4852 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) { 4853 if (!Context.CFConstantStringTypeDecl) 4854 Context.setCFConstantStringType(GetType(String)); 4855 } 4856 4857 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) { 4858 QualType FileType = GetType(File); 4859 if (FileType.isNull()) { 4860 Error("FILE type is NULL"); 4861 return; 4862 } 4863 4864 if (!Context.FILEDecl) { 4865 if (const TypedefType *Typedef = FileType->getAs<TypedefType>()) 4866 Context.setFILEDecl(Typedef->getDecl()); 4867 else { 4868 const TagType *Tag = FileType->getAs<TagType>(); 4869 if (!Tag) { 4870 Error("Invalid FILE type in AST file"); 4871 return; 4872 } 4873 Context.setFILEDecl(Tag->getDecl()); 4874 } 4875 } 4876 } 4877 4878 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) { 4879 QualType Jmp_bufType = GetType(Jmp_buf); 4880 if (Jmp_bufType.isNull()) { 4881 Error("jmp_buf type is NULL"); 4882 return; 4883 } 4884 4885 if (!Context.jmp_bufDecl) { 4886 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>()) 4887 Context.setjmp_bufDecl(Typedef->getDecl()); 4888 else { 4889 const TagType *Tag = Jmp_bufType->getAs<TagType>(); 4890 if (!Tag) { 4891 Error("Invalid jmp_buf type in AST file"); 4892 return; 4893 } 4894 Context.setjmp_bufDecl(Tag->getDecl()); 4895 } 4896 } 4897 } 4898 4899 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) { 4900 QualType Sigjmp_bufType = GetType(Sigjmp_buf); 4901 if (Sigjmp_bufType.isNull()) { 4902 Error("sigjmp_buf type is NULL"); 4903 return; 4904 } 4905 4906 if (!Context.sigjmp_bufDecl) { 4907 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>()) 4908 Context.setsigjmp_bufDecl(Typedef->getDecl()); 4909 else { 4910 const TagType *Tag = Sigjmp_bufType->getAs<TagType>(); 4911 assert(Tag && "Invalid sigjmp_buf type in AST file"); 4912 Context.setsigjmp_bufDecl(Tag->getDecl()); 4913 } 4914 } 4915 } 4916 4917 if (unsigned ObjCIdRedef 4918 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) { 4919 if (Context.ObjCIdRedefinitionType.isNull()) 4920 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef); 4921 } 4922 4923 if (unsigned ObjCClassRedef 4924 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) { 4925 if (Context.ObjCClassRedefinitionType.isNull()) 4926 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef); 4927 } 4928 4929 if (unsigned ObjCSelRedef 4930 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) { 4931 if (Context.ObjCSelRedefinitionType.isNull()) 4932 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef); 4933 } 4934 4935 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) { 4936 QualType Ucontext_tType = GetType(Ucontext_t); 4937 if (Ucontext_tType.isNull()) { 4938 Error("ucontext_t type is NULL"); 4939 return; 4940 } 4941 4942 if (!Context.ucontext_tDecl) { 4943 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>()) 4944 Context.setucontext_tDecl(Typedef->getDecl()); 4945 else { 4946 const TagType *Tag = Ucontext_tType->getAs<TagType>(); 4947 assert(Tag && "Invalid ucontext_t type in AST file"); 4948 Context.setucontext_tDecl(Tag->getDecl()); 4949 } 4950 } 4951 } 4952 } 4953 4954 ReadPragmaDiagnosticMappings(Context.getDiagnostics()); 4955 4956 // If there were any CUDA special declarations, deserialize them. 4957 if (!CUDASpecialDeclRefs.empty()) { 4958 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!"); 4959 Context.setcudaConfigureCallDecl( 4960 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0]))); 4961 } 4962 4963 // Re-export any modules that were imported by a non-module AST file. 4964 // FIXME: This does not make macro-only imports visible again. 4965 for (auto &Import : ImportedModules) { 4966 if (Module *Imported = getSubmodule(Import.ID)) { 4967 makeModuleVisible(Imported, Module::AllVisible, 4968 /*ImportLoc=*/Import.ImportLoc); 4969 if (Import.ImportLoc.isValid()) 4970 PP.makeModuleVisible(Imported, Import.ImportLoc); 4971 // This updates visibility for Preprocessor only. For Sema, which can be 4972 // nullptr here, we do the same later, in UpdateSema(). 4973 } 4974 } 4975 } 4976 4977 void ASTReader::finalizeForWriting() { 4978 // Nothing to do for now. 4979 } 4980 4981 /// Reads and return the signature record from \p PCH's control block, or 4982 /// else returns 0. 4983 static ASTFileSignature readASTFileSignature(StringRef PCH) { 4984 BitstreamCursor Stream(PCH); 4985 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) { 4986 // FIXME this drops the error on the floor. 4987 consumeError(std::move(Err)); 4988 return ASTFileSignature(); 4989 } 4990 4991 // Scan for the UNHASHED_CONTROL_BLOCK_ID block. 4992 if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID)) 4993 return ASTFileSignature(); 4994 4995 // Scan for SIGNATURE inside the diagnostic options block. 4996 ASTReader::RecordData Record; 4997 while (true) { 4998 Expected<llvm::BitstreamEntry> MaybeEntry = 4999 Stream.advanceSkippingSubblocks(); 5000 if (!MaybeEntry) { 5001 // FIXME this drops the error on the floor. 5002 consumeError(MaybeEntry.takeError()); 5003 return ASTFileSignature(); 5004 } 5005 llvm::BitstreamEntry Entry = MaybeEntry.get(); 5006 5007 if (Entry.Kind != llvm::BitstreamEntry::Record) 5008 return ASTFileSignature(); 5009 5010 Record.clear(); 5011 StringRef Blob; 5012 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob); 5013 if (!MaybeRecord) { 5014 // FIXME this drops the error on the floor. 5015 consumeError(MaybeRecord.takeError()); 5016 return ASTFileSignature(); 5017 } 5018 if (SIGNATURE == MaybeRecord.get()) 5019 return ASTFileSignature::create(Record.begin(), 5020 Record.begin() + ASTFileSignature::size); 5021 } 5022 } 5023 5024 /// Retrieve the name of the original source file name 5025 /// directly from the AST file, without actually loading the AST 5026 /// file. 5027 std::string ASTReader::getOriginalSourceFile( 5028 const std::string &ASTFileName, FileManager &FileMgr, 5029 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) { 5030 // Open the AST file. 5031 auto Buffer = FileMgr.getBufferForFile(ASTFileName); 5032 if (!Buffer) { 5033 Diags.Report(diag::err_fe_unable_to_read_pch_file) 5034 << ASTFileName << Buffer.getError().message(); 5035 return std::string(); 5036 } 5037 5038 // Initialize the stream 5039 BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer)); 5040 5041 // Sniff for the signature. 5042 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) { 5043 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName << std::move(Err); 5044 return std::string(); 5045 } 5046 5047 // Scan for the CONTROL_BLOCK_ID block. 5048 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) { 5049 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName; 5050 return std::string(); 5051 } 5052 5053 // Scan for ORIGINAL_FILE inside the control block. 5054 RecordData Record; 5055 while (true) { 5056 Expected<llvm::BitstreamEntry> MaybeEntry = 5057 Stream.advanceSkippingSubblocks(); 5058 if (!MaybeEntry) { 5059 // FIXME this drops errors on the floor. 5060 consumeError(MaybeEntry.takeError()); 5061 return std::string(); 5062 } 5063 llvm::BitstreamEntry Entry = MaybeEntry.get(); 5064 5065 if (Entry.Kind == llvm::BitstreamEntry::EndBlock) 5066 return std::string(); 5067 5068 if (Entry.Kind != llvm::BitstreamEntry::Record) { 5069 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName; 5070 return std::string(); 5071 } 5072 5073 Record.clear(); 5074 StringRef Blob; 5075 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob); 5076 if (!MaybeRecord) { 5077 // FIXME this drops the errors on the floor. 5078 consumeError(MaybeRecord.takeError()); 5079 return std::string(); 5080 } 5081 if (ORIGINAL_FILE == MaybeRecord.get()) 5082 return Blob.str(); 5083 } 5084 } 5085 5086 namespace { 5087 5088 class SimplePCHValidator : public ASTReaderListener { 5089 const LangOptions &ExistingLangOpts; 5090 const TargetOptions &ExistingTargetOpts; 5091 const PreprocessorOptions &ExistingPPOpts; 5092 std::string ExistingModuleCachePath; 5093 FileManager &FileMgr; 5094 5095 public: 5096 SimplePCHValidator(const LangOptions &ExistingLangOpts, 5097 const TargetOptions &ExistingTargetOpts, 5098 const PreprocessorOptions &ExistingPPOpts, 5099 StringRef ExistingModuleCachePath, FileManager &FileMgr) 5100 : ExistingLangOpts(ExistingLangOpts), 5101 ExistingTargetOpts(ExistingTargetOpts), 5102 ExistingPPOpts(ExistingPPOpts), 5103 ExistingModuleCachePath(ExistingModuleCachePath), FileMgr(FileMgr) {} 5104 5105 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain, 5106 bool AllowCompatibleDifferences) override { 5107 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr, 5108 AllowCompatibleDifferences); 5109 } 5110 5111 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain, 5112 bool AllowCompatibleDifferences) override { 5113 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr, 5114 AllowCompatibleDifferences); 5115 } 5116 5117 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, 5118 StringRef SpecificModuleCachePath, 5119 bool Complain) override { 5120 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath, 5121 ExistingModuleCachePath, 5122 nullptr, ExistingLangOpts); 5123 } 5124 5125 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, 5126 bool Complain, 5127 std::string &SuggestedPredefines) override { 5128 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr, 5129 SuggestedPredefines, ExistingLangOpts); 5130 } 5131 }; 5132 5133 } // namespace 5134 5135 bool ASTReader::readASTFileControlBlock( 5136 StringRef Filename, FileManager &FileMgr, 5137 const PCHContainerReader &PCHContainerRdr, 5138 bool FindModuleFileExtensions, 5139 ASTReaderListener &Listener, bool ValidateDiagnosticOptions) { 5140 // Open the AST file. 5141 // FIXME: This allows use of the VFS; we do not allow use of the 5142 // VFS when actually loading a module. 5143 auto Buffer = FileMgr.getBufferForFile(Filename); 5144 if (!Buffer) { 5145 return true; 5146 } 5147 5148 // Initialize the stream 5149 StringRef Bytes = PCHContainerRdr.ExtractPCH(**Buffer); 5150 BitstreamCursor Stream(Bytes); 5151 5152 // Sniff for the signature. 5153 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) { 5154 consumeError(std::move(Err)); // FIXME this drops errors on the floor. 5155 return true; 5156 } 5157 5158 // Scan for the CONTROL_BLOCK_ID block. 5159 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) 5160 return true; 5161 5162 bool NeedsInputFiles = Listener.needsInputFileVisitation(); 5163 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation(); 5164 bool NeedsImports = Listener.needsImportVisitation(); 5165 BitstreamCursor InputFilesCursor; 5166 5167 RecordData Record; 5168 std::string ModuleDir; 5169 bool DoneWithControlBlock = false; 5170 while (!DoneWithControlBlock) { 5171 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); 5172 if (!MaybeEntry) { 5173 // FIXME this drops the error on the floor. 5174 consumeError(MaybeEntry.takeError()); 5175 return true; 5176 } 5177 llvm::BitstreamEntry Entry = MaybeEntry.get(); 5178 5179 switch (Entry.Kind) { 5180 case llvm::BitstreamEntry::SubBlock: { 5181 switch (Entry.ID) { 5182 case OPTIONS_BLOCK_ID: { 5183 std::string IgnoredSuggestedPredefines; 5184 if (ReadOptionsBlock(Stream, ARR_ConfigurationMismatch | ARR_OutOfDate, 5185 /*AllowCompatibleConfigurationMismatch*/ false, 5186 Listener, IgnoredSuggestedPredefines) != Success) 5187 return true; 5188 break; 5189 } 5190 5191 case INPUT_FILES_BLOCK_ID: 5192 InputFilesCursor = Stream; 5193 if (llvm::Error Err = Stream.SkipBlock()) { 5194 // FIXME this drops the error on the floor. 5195 consumeError(std::move(Err)); 5196 return true; 5197 } 5198 if (NeedsInputFiles && 5199 ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID)) 5200 return true; 5201 break; 5202 5203 default: 5204 if (llvm::Error Err = Stream.SkipBlock()) { 5205 // FIXME this drops the error on the floor. 5206 consumeError(std::move(Err)); 5207 return true; 5208 } 5209 break; 5210 } 5211 5212 continue; 5213 } 5214 5215 case llvm::BitstreamEntry::EndBlock: 5216 DoneWithControlBlock = true; 5217 break; 5218 5219 case llvm::BitstreamEntry::Error: 5220 return true; 5221 5222 case llvm::BitstreamEntry::Record: 5223 break; 5224 } 5225 5226 if (DoneWithControlBlock) break; 5227 5228 Record.clear(); 5229 StringRef Blob; 5230 Expected<unsigned> MaybeRecCode = 5231 Stream.readRecord(Entry.ID, Record, &Blob); 5232 if (!MaybeRecCode) { 5233 // FIXME this drops the error. 5234 return Failure; 5235 } 5236 switch ((ControlRecordTypes)MaybeRecCode.get()) { 5237 case METADATA: 5238 if (Record[0] != VERSION_MAJOR) 5239 return true; 5240 if (Listener.ReadFullVersionInformation(Blob)) 5241 return true; 5242 break; 5243 case MODULE_NAME: 5244 Listener.ReadModuleName(Blob); 5245 break; 5246 case MODULE_DIRECTORY: 5247 ModuleDir = std::string(Blob); 5248 break; 5249 case MODULE_MAP_FILE: { 5250 unsigned Idx = 0; 5251 auto Path = ReadString(Record, Idx); 5252 ResolveImportedPath(Path, ModuleDir); 5253 Listener.ReadModuleMapFile(Path); 5254 break; 5255 } 5256 case INPUT_FILE_OFFSETS: { 5257 if (!NeedsInputFiles) 5258 break; 5259 5260 unsigned NumInputFiles = Record[0]; 5261 unsigned NumUserFiles = Record[1]; 5262 const llvm::support::unaligned_uint64_t *InputFileOffs = 5263 (const llvm::support::unaligned_uint64_t *)Blob.data(); 5264 for (unsigned I = 0; I != NumInputFiles; ++I) { 5265 // Go find this input file. 5266 bool isSystemFile = I >= NumUserFiles; 5267 5268 if (isSystemFile && !NeedsSystemInputFiles) 5269 break; // the rest are system input files 5270 5271 BitstreamCursor &Cursor = InputFilesCursor; 5272 SavedStreamPosition SavedPosition(Cursor); 5273 if (llvm::Error Err = Cursor.JumpToBit(InputFileOffs[I])) { 5274 // FIXME this drops errors on the floor. 5275 consumeError(std::move(Err)); 5276 } 5277 5278 Expected<unsigned> MaybeCode = Cursor.ReadCode(); 5279 if (!MaybeCode) { 5280 // FIXME this drops errors on the floor. 5281 consumeError(MaybeCode.takeError()); 5282 } 5283 unsigned Code = MaybeCode.get(); 5284 5285 RecordData Record; 5286 StringRef Blob; 5287 bool shouldContinue = false; 5288 Expected<unsigned> MaybeRecordType = 5289 Cursor.readRecord(Code, Record, &Blob); 5290 if (!MaybeRecordType) { 5291 // FIXME this drops errors on the floor. 5292 consumeError(MaybeRecordType.takeError()); 5293 } 5294 switch ((InputFileRecordTypes)MaybeRecordType.get()) { 5295 case INPUT_FILE_HASH: 5296 break; 5297 case INPUT_FILE: 5298 bool Overridden = static_cast<bool>(Record[3]); 5299 std::string Filename = std::string(Blob); 5300 ResolveImportedPath(Filename, ModuleDir); 5301 shouldContinue = Listener.visitInputFile( 5302 Filename, isSystemFile, Overridden, /*IsExplicitModule*/false); 5303 break; 5304 } 5305 if (!shouldContinue) 5306 break; 5307 } 5308 break; 5309 } 5310 5311 case IMPORTS: { 5312 if (!NeedsImports) 5313 break; 5314 5315 unsigned Idx = 0, N = Record.size(); 5316 while (Idx < N) { 5317 // Read information about the AST file. 5318 Idx += 5319 1 + 1 + 1 + 1 + 5320 ASTFileSignature::size; // Kind, ImportLoc, Size, ModTime, Signature 5321 std::string ModuleName = ReadString(Record, Idx); 5322 std::string Filename = ReadString(Record, Idx); 5323 ResolveImportedPath(Filename, ModuleDir); 5324 Listener.visitImport(ModuleName, Filename); 5325 } 5326 break; 5327 } 5328 5329 default: 5330 // No other validation to perform. 5331 break; 5332 } 5333 } 5334 5335 // Look for module file extension blocks, if requested. 5336 if (FindModuleFileExtensions) { 5337 BitstreamCursor SavedStream = Stream; 5338 while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) { 5339 bool DoneWithExtensionBlock = false; 5340 while (!DoneWithExtensionBlock) { 5341 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); 5342 if (!MaybeEntry) { 5343 // FIXME this drops the error. 5344 return true; 5345 } 5346 llvm::BitstreamEntry Entry = MaybeEntry.get(); 5347 5348 switch (Entry.Kind) { 5349 case llvm::BitstreamEntry::SubBlock: 5350 if (llvm::Error Err = Stream.SkipBlock()) { 5351 // FIXME this drops the error on the floor. 5352 consumeError(std::move(Err)); 5353 return true; 5354 } 5355 continue; 5356 5357 case llvm::BitstreamEntry::EndBlock: 5358 DoneWithExtensionBlock = true; 5359 continue; 5360 5361 case llvm::BitstreamEntry::Error: 5362 return true; 5363 5364 case llvm::BitstreamEntry::Record: 5365 break; 5366 } 5367 5368 Record.clear(); 5369 StringRef Blob; 5370 Expected<unsigned> MaybeRecCode = 5371 Stream.readRecord(Entry.ID, Record, &Blob); 5372 if (!MaybeRecCode) { 5373 // FIXME this drops the error. 5374 return true; 5375 } 5376 switch (MaybeRecCode.get()) { 5377 case EXTENSION_METADATA: { 5378 ModuleFileExtensionMetadata Metadata; 5379 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata)) 5380 return true; 5381 5382 Listener.readModuleFileExtension(Metadata); 5383 break; 5384 } 5385 } 5386 } 5387 } 5388 Stream = SavedStream; 5389 } 5390 5391 // Scan for the UNHASHED_CONTROL_BLOCK_ID block. 5392 if (readUnhashedControlBlockImpl( 5393 nullptr, Bytes, ARR_ConfigurationMismatch | ARR_OutOfDate, 5394 /*AllowCompatibleConfigurationMismatch*/ false, &Listener, 5395 ValidateDiagnosticOptions) != Success) 5396 return true; 5397 5398 return false; 5399 } 5400 5401 bool ASTReader::isAcceptableASTFile(StringRef Filename, FileManager &FileMgr, 5402 const PCHContainerReader &PCHContainerRdr, 5403 const LangOptions &LangOpts, 5404 const TargetOptions &TargetOpts, 5405 const PreprocessorOptions &PPOpts, 5406 StringRef ExistingModuleCachePath) { 5407 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts, 5408 ExistingModuleCachePath, FileMgr); 5409 return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr, 5410 /*FindModuleFileExtensions=*/false, 5411 validator, 5412 /*ValidateDiagnosticOptions=*/true); 5413 } 5414 5415 ASTReader::ASTReadResult 5416 ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) { 5417 // Enter the submodule block. 5418 if (llvm::Error Err = F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) { 5419 Error(std::move(Err)); 5420 return Failure; 5421 } 5422 5423 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap(); 5424 bool First = true; 5425 Module *CurrentModule = nullptr; 5426 RecordData Record; 5427 while (true) { 5428 Expected<llvm::BitstreamEntry> MaybeEntry = 5429 F.Stream.advanceSkippingSubblocks(); 5430 if (!MaybeEntry) { 5431 Error(MaybeEntry.takeError()); 5432 return Failure; 5433 } 5434 llvm::BitstreamEntry Entry = MaybeEntry.get(); 5435 5436 switch (Entry.Kind) { 5437 case llvm::BitstreamEntry::SubBlock: // Handled for us already. 5438 case llvm::BitstreamEntry::Error: 5439 Error("malformed block record in AST file"); 5440 return Failure; 5441 case llvm::BitstreamEntry::EndBlock: 5442 return Success; 5443 case llvm::BitstreamEntry::Record: 5444 // The interesting case. 5445 break; 5446 } 5447 5448 // Read a record. 5449 StringRef Blob; 5450 Record.clear(); 5451 Expected<unsigned> MaybeKind = F.Stream.readRecord(Entry.ID, Record, &Blob); 5452 if (!MaybeKind) { 5453 Error(MaybeKind.takeError()); 5454 return Failure; 5455 } 5456 unsigned Kind = MaybeKind.get(); 5457 5458 if ((Kind == SUBMODULE_METADATA) != First) { 5459 Error("submodule metadata record should be at beginning of block"); 5460 return Failure; 5461 } 5462 First = false; 5463 5464 // Submodule information is only valid if we have a current module. 5465 // FIXME: Should we error on these cases? 5466 if (!CurrentModule && Kind != SUBMODULE_METADATA && 5467 Kind != SUBMODULE_DEFINITION) 5468 continue; 5469 5470 switch (Kind) { 5471 default: // Default behavior: ignore. 5472 break; 5473 5474 case SUBMODULE_DEFINITION: { 5475 if (Record.size() < 12) { 5476 Error("malformed module definition"); 5477 return Failure; 5478 } 5479 5480 StringRef Name = Blob; 5481 unsigned Idx = 0; 5482 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]); 5483 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]); 5484 Module::ModuleKind Kind = (Module::ModuleKind)Record[Idx++]; 5485 bool IsFramework = Record[Idx++]; 5486 bool IsExplicit = Record[Idx++]; 5487 bool IsSystem = Record[Idx++]; 5488 bool IsExternC = Record[Idx++]; 5489 bool InferSubmodules = Record[Idx++]; 5490 bool InferExplicitSubmodules = Record[Idx++]; 5491 bool InferExportWildcard = Record[Idx++]; 5492 bool ConfigMacrosExhaustive = Record[Idx++]; 5493 bool ModuleMapIsPrivate = Record[Idx++]; 5494 5495 Module *ParentModule = nullptr; 5496 if (Parent) 5497 ParentModule = getSubmodule(Parent); 5498 5499 // Retrieve this (sub)module from the module map, creating it if 5500 // necessary. 5501 CurrentModule = 5502 ModMap.findOrCreateModule(Name, ParentModule, IsFramework, IsExplicit) 5503 .first; 5504 5505 // FIXME: set the definition loc for CurrentModule, or call 5506 // ModMap.setInferredModuleAllowedBy() 5507 5508 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS; 5509 if (GlobalIndex >= SubmodulesLoaded.size() || 5510 SubmodulesLoaded[GlobalIndex]) { 5511 Error("too many submodules"); 5512 return Failure; 5513 } 5514 5515 if (!ParentModule) { 5516 if (const FileEntry *CurFile = CurrentModule->getASTFile()) { 5517 // Don't emit module relocation error if we have -fno-validate-pch 5518 if (!PP.getPreprocessorOpts().DisablePCHValidation && 5519 CurFile != F.File) { 5520 Error(diag::err_module_file_conflict, 5521 CurrentModule->getTopLevelModuleName(), CurFile->getName(), 5522 F.File->getName()); 5523 return Failure; 5524 } 5525 } 5526 5527 F.DidReadTopLevelSubmodule = true; 5528 CurrentModule->setASTFile(F.File); 5529 CurrentModule->PresumedModuleMapFile = F.ModuleMapPath; 5530 } 5531 5532 CurrentModule->Kind = Kind; 5533 CurrentModule->Signature = F.Signature; 5534 CurrentModule->IsFromModuleFile = true; 5535 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem; 5536 CurrentModule->IsExternC = IsExternC; 5537 CurrentModule->InferSubmodules = InferSubmodules; 5538 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules; 5539 CurrentModule->InferExportWildcard = InferExportWildcard; 5540 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive; 5541 CurrentModule->ModuleMapIsPrivate = ModuleMapIsPrivate; 5542 if (DeserializationListener) 5543 DeserializationListener->ModuleRead(GlobalID, CurrentModule); 5544 5545 SubmodulesLoaded[GlobalIndex] = CurrentModule; 5546 5547 // Clear out data that will be replaced by what is in the module file. 5548 CurrentModule->LinkLibraries.clear(); 5549 CurrentModule->ConfigMacros.clear(); 5550 CurrentModule->UnresolvedConflicts.clear(); 5551 CurrentModule->Conflicts.clear(); 5552 5553 // The module is available unless it's missing a requirement; relevant 5554 // requirements will be (re-)added by SUBMODULE_REQUIRES records. 5555 // Missing headers that were present when the module was built do not 5556 // make it unavailable -- if we got this far, this must be an explicitly 5557 // imported module file. 5558 CurrentModule->Requirements.clear(); 5559 CurrentModule->MissingHeaders.clear(); 5560 CurrentModule->IsUnimportable = 5561 ParentModule && ParentModule->IsUnimportable; 5562 CurrentModule->IsAvailable = !CurrentModule->IsUnimportable; 5563 break; 5564 } 5565 5566 case SUBMODULE_UMBRELLA_HEADER: { 5567 std::string Filename = std::string(Blob); 5568 ResolveImportedPath(F, Filename); 5569 if (auto Umbrella = PP.getFileManager().getFile(Filename)) { 5570 if (!CurrentModule->getUmbrellaHeader()) 5571 ModMap.setUmbrellaHeader(CurrentModule, *Umbrella, Blob); 5572 else if (CurrentModule->getUmbrellaHeader().Entry != *Umbrella) { 5573 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) 5574 Error("mismatched umbrella headers in submodule"); 5575 return OutOfDate; 5576 } 5577 } 5578 break; 5579 } 5580 5581 case SUBMODULE_HEADER: 5582 case SUBMODULE_EXCLUDED_HEADER: 5583 case SUBMODULE_PRIVATE_HEADER: 5584 // We lazily associate headers with their modules via the HeaderInfo table. 5585 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead 5586 // of complete filenames or remove it entirely. 5587 break; 5588 5589 case SUBMODULE_TEXTUAL_HEADER: 5590 case SUBMODULE_PRIVATE_TEXTUAL_HEADER: 5591 // FIXME: Textual headers are not marked in the HeaderInfo table. Load 5592 // them here. 5593 break; 5594 5595 case SUBMODULE_TOPHEADER: 5596 CurrentModule->addTopHeaderFilename(Blob); 5597 break; 5598 5599 case SUBMODULE_UMBRELLA_DIR: { 5600 std::string Dirname = std::string(Blob); 5601 ResolveImportedPath(F, Dirname); 5602 if (auto Umbrella = PP.getFileManager().getDirectory(Dirname)) { 5603 if (!CurrentModule->getUmbrellaDir()) 5604 ModMap.setUmbrellaDir(CurrentModule, *Umbrella, Blob); 5605 else if (CurrentModule->getUmbrellaDir().Entry != *Umbrella) { 5606 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) 5607 Error("mismatched umbrella directories in submodule"); 5608 return OutOfDate; 5609 } 5610 } 5611 break; 5612 } 5613 5614 case SUBMODULE_METADATA: { 5615 F.BaseSubmoduleID = getTotalNumSubmodules(); 5616 F.LocalNumSubmodules = Record[0]; 5617 unsigned LocalBaseSubmoduleID = Record[1]; 5618 if (F.LocalNumSubmodules > 0) { 5619 // Introduce the global -> local mapping for submodules within this 5620 // module. 5621 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F)); 5622 5623 // Introduce the local -> global mapping for submodules within this 5624 // module. 5625 F.SubmoduleRemap.insertOrReplace( 5626 std::make_pair(LocalBaseSubmoduleID, 5627 F.BaseSubmoduleID - LocalBaseSubmoduleID)); 5628 5629 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules); 5630 } 5631 break; 5632 } 5633 5634 case SUBMODULE_IMPORTS: 5635 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) { 5636 UnresolvedModuleRef Unresolved; 5637 Unresolved.File = &F; 5638 Unresolved.Mod = CurrentModule; 5639 Unresolved.ID = Record[Idx]; 5640 Unresolved.Kind = UnresolvedModuleRef::Import; 5641 Unresolved.IsWildcard = false; 5642 UnresolvedModuleRefs.push_back(Unresolved); 5643 } 5644 break; 5645 5646 case SUBMODULE_EXPORTS: 5647 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) { 5648 UnresolvedModuleRef Unresolved; 5649 Unresolved.File = &F; 5650 Unresolved.Mod = CurrentModule; 5651 Unresolved.ID = Record[Idx]; 5652 Unresolved.Kind = UnresolvedModuleRef::Export; 5653 Unresolved.IsWildcard = Record[Idx + 1]; 5654 UnresolvedModuleRefs.push_back(Unresolved); 5655 } 5656 5657 // Once we've loaded the set of exports, there's no reason to keep 5658 // the parsed, unresolved exports around. 5659 CurrentModule->UnresolvedExports.clear(); 5660 break; 5661 5662 case SUBMODULE_REQUIRES: 5663 CurrentModule->addRequirement(Blob, Record[0], PP.getLangOpts(), 5664 PP.getTargetInfo()); 5665 break; 5666 5667 case SUBMODULE_LINK_LIBRARY: 5668 ModMap.resolveLinkAsDependencies(CurrentModule); 5669 CurrentModule->LinkLibraries.push_back( 5670 Module::LinkLibrary(std::string(Blob), Record[0])); 5671 break; 5672 5673 case SUBMODULE_CONFIG_MACRO: 5674 CurrentModule->ConfigMacros.push_back(Blob.str()); 5675 break; 5676 5677 case SUBMODULE_CONFLICT: { 5678 UnresolvedModuleRef Unresolved; 5679 Unresolved.File = &F; 5680 Unresolved.Mod = CurrentModule; 5681 Unresolved.ID = Record[0]; 5682 Unresolved.Kind = UnresolvedModuleRef::Conflict; 5683 Unresolved.IsWildcard = false; 5684 Unresolved.String = Blob; 5685 UnresolvedModuleRefs.push_back(Unresolved); 5686 break; 5687 } 5688 5689 case SUBMODULE_INITIALIZERS: { 5690 if (!ContextObj) 5691 break; 5692 SmallVector<uint32_t, 16> Inits; 5693 for (auto &ID : Record) 5694 Inits.push_back(getGlobalDeclID(F, ID)); 5695 ContextObj->addLazyModuleInitializers(CurrentModule, Inits); 5696 break; 5697 } 5698 5699 case SUBMODULE_EXPORT_AS: 5700 CurrentModule->ExportAsModule = Blob.str(); 5701 ModMap.addLinkAsDependency(CurrentModule); 5702 break; 5703 } 5704 } 5705 } 5706 5707 /// Parse the record that corresponds to a LangOptions data 5708 /// structure. 5709 /// 5710 /// This routine parses the language options from the AST file and then gives 5711 /// them to the AST listener if one is set. 5712 /// 5713 /// \returns true if the listener deems the file unacceptable, false otherwise. 5714 bool ASTReader::ParseLanguageOptions(const RecordData &Record, 5715 bool Complain, 5716 ASTReaderListener &Listener, 5717 bool AllowCompatibleDifferences) { 5718 LangOptions LangOpts; 5719 unsigned Idx = 0; 5720 #define LANGOPT(Name, Bits, Default, Description) \ 5721 LangOpts.Name = Record[Idx++]; 5722 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \ 5723 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++])); 5724 #include "clang/Basic/LangOptions.def" 5725 #define SANITIZER(NAME, ID) \ 5726 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]); 5727 #include "clang/Basic/Sanitizers.def" 5728 5729 for (unsigned N = Record[Idx++]; N; --N) 5730 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx)); 5731 5732 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++]; 5733 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx); 5734 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion); 5735 5736 LangOpts.CurrentModule = ReadString(Record, Idx); 5737 5738 // Comment options. 5739 for (unsigned N = Record[Idx++]; N; --N) { 5740 LangOpts.CommentOpts.BlockCommandNames.push_back( 5741 ReadString(Record, Idx)); 5742 } 5743 LangOpts.CommentOpts.ParseAllComments = Record[Idx++]; 5744 5745 // OpenMP offloading options. 5746 for (unsigned N = Record[Idx++]; N; --N) { 5747 LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx))); 5748 } 5749 5750 LangOpts.OMPHostIRFile = ReadString(Record, Idx); 5751 5752 return Listener.ReadLanguageOptions(LangOpts, Complain, 5753 AllowCompatibleDifferences); 5754 } 5755 5756 bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain, 5757 ASTReaderListener &Listener, 5758 bool AllowCompatibleDifferences) { 5759 unsigned Idx = 0; 5760 TargetOptions TargetOpts; 5761 TargetOpts.Triple = ReadString(Record, Idx); 5762 TargetOpts.CPU = ReadString(Record, Idx); 5763 TargetOpts.TuneCPU = ReadString(Record, Idx); 5764 TargetOpts.ABI = ReadString(Record, Idx); 5765 for (unsigned N = Record[Idx++]; N; --N) { 5766 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx)); 5767 } 5768 for (unsigned N = Record[Idx++]; N; --N) { 5769 TargetOpts.Features.push_back(ReadString(Record, Idx)); 5770 } 5771 5772 return Listener.ReadTargetOptions(TargetOpts, Complain, 5773 AllowCompatibleDifferences); 5774 } 5775 5776 bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain, 5777 ASTReaderListener &Listener) { 5778 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions); 5779 unsigned Idx = 0; 5780 #define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++]; 5781 #define ENUM_DIAGOPT(Name, Type, Bits, Default) \ 5782 DiagOpts->set##Name(static_cast<Type>(Record[Idx++])); 5783 #include "clang/Basic/DiagnosticOptions.def" 5784 5785 for (unsigned N = Record[Idx++]; N; --N) 5786 DiagOpts->Warnings.push_back(ReadString(Record, Idx)); 5787 for (unsigned N = Record[Idx++]; N; --N) 5788 DiagOpts->Remarks.push_back(ReadString(Record, Idx)); 5789 5790 return Listener.ReadDiagnosticOptions(DiagOpts, Complain); 5791 } 5792 5793 bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain, 5794 ASTReaderListener &Listener) { 5795 FileSystemOptions FSOpts; 5796 unsigned Idx = 0; 5797 FSOpts.WorkingDir = ReadString(Record, Idx); 5798 return Listener.ReadFileSystemOptions(FSOpts, Complain); 5799 } 5800 5801 bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record, 5802 bool Complain, 5803 ASTReaderListener &Listener) { 5804 HeaderSearchOptions HSOpts; 5805 unsigned Idx = 0; 5806 HSOpts.Sysroot = ReadString(Record, Idx); 5807 5808 // Include entries. 5809 for (unsigned N = Record[Idx++]; N; --N) { 5810 std::string Path = ReadString(Record, Idx); 5811 frontend::IncludeDirGroup Group 5812 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]); 5813 bool IsFramework = Record[Idx++]; 5814 bool IgnoreSysRoot = Record[Idx++]; 5815 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework, 5816 IgnoreSysRoot); 5817 } 5818 5819 // System header prefixes. 5820 for (unsigned N = Record[Idx++]; N; --N) { 5821 std::string Prefix = ReadString(Record, Idx); 5822 bool IsSystemHeader = Record[Idx++]; 5823 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader); 5824 } 5825 5826 HSOpts.ResourceDir = ReadString(Record, Idx); 5827 HSOpts.ModuleCachePath = ReadString(Record, Idx); 5828 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx); 5829 HSOpts.DisableModuleHash = Record[Idx++]; 5830 HSOpts.ImplicitModuleMaps = Record[Idx++]; 5831 HSOpts.ModuleMapFileHomeIsCwd = Record[Idx++]; 5832 HSOpts.EnablePrebuiltImplicitModules = Record[Idx++]; 5833 HSOpts.UseBuiltinIncludes = Record[Idx++]; 5834 HSOpts.UseStandardSystemIncludes = Record[Idx++]; 5835 HSOpts.UseStandardCXXIncludes = Record[Idx++]; 5836 HSOpts.UseLibcxx = Record[Idx++]; 5837 std::string SpecificModuleCachePath = ReadString(Record, Idx); 5838 5839 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath, 5840 Complain); 5841 } 5842 5843 bool ASTReader::ParsePreprocessorOptions(const RecordData &Record, 5844 bool Complain, 5845 ASTReaderListener &Listener, 5846 std::string &SuggestedPredefines) { 5847 PreprocessorOptions PPOpts; 5848 unsigned Idx = 0; 5849 5850 // Macro definitions/undefs 5851 for (unsigned N = Record[Idx++]; N; --N) { 5852 std::string Macro = ReadString(Record, Idx); 5853 bool IsUndef = Record[Idx++]; 5854 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef)); 5855 } 5856 5857 // Includes 5858 for (unsigned N = Record[Idx++]; N; --N) { 5859 PPOpts.Includes.push_back(ReadString(Record, Idx)); 5860 } 5861 5862 // Macro Includes 5863 for (unsigned N = Record[Idx++]; N; --N) { 5864 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx)); 5865 } 5866 5867 PPOpts.UsePredefines = Record[Idx++]; 5868 PPOpts.DetailedRecord = Record[Idx++]; 5869 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx); 5870 PPOpts.ObjCXXARCStandardLibrary = 5871 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]); 5872 SuggestedPredefines.clear(); 5873 return Listener.ReadPreprocessorOptions(PPOpts, Complain, 5874 SuggestedPredefines); 5875 } 5876 5877 std::pair<ModuleFile *, unsigned> 5878 ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) { 5879 GlobalPreprocessedEntityMapType::iterator 5880 I = GlobalPreprocessedEntityMap.find(GlobalIndex); 5881 assert(I != GlobalPreprocessedEntityMap.end() && 5882 "Corrupted global preprocessed entity map"); 5883 ModuleFile *M = I->second; 5884 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID; 5885 return std::make_pair(M, LocalIndex); 5886 } 5887 5888 llvm::iterator_range<PreprocessingRecord::iterator> 5889 ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const { 5890 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord()) 5891 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID, 5892 Mod.NumPreprocessedEntities); 5893 5894 return llvm::make_range(PreprocessingRecord::iterator(), 5895 PreprocessingRecord::iterator()); 5896 } 5897 5898 llvm::iterator_range<ASTReader::ModuleDeclIterator> 5899 ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) { 5900 return llvm::make_range( 5901 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls), 5902 ModuleDeclIterator(this, &Mod, 5903 Mod.FileSortedDecls + Mod.NumFileSortedDecls)); 5904 } 5905 5906 SourceRange ASTReader::ReadSkippedRange(unsigned GlobalIndex) { 5907 auto I = GlobalSkippedRangeMap.find(GlobalIndex); 5908 assert(I != GlobalSkippedRangeMap.end() && 5909 "Corrupted global skipped range map"); 5910 ModuleFile *M = I->second; 5911 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedSkippedRangeID; 5912 assert(LocalIndex < M->NumPreprocessedSkippedRanges); 5913 PPSkippedRange RawRange = M->PreprocessedSkippedRangeOffsets[LocalIndex]; 5914 SourceRange Range(TranslateSourceLocation(*M, RawRange.getBegin()), 5915 TranslateSourceLocation(*M, RawRange.getEnd())); 5916 assert(Range.isValid()); 5917 return Range; 5918 } 5919 5920 PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) { 5921 PreprocessedEntityID PPID = Index+1; 5922 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index); 5923 ModuleFile &M = *PPInfo.first; 5924 unsigned LocalIndex = PPInfo.second; 5925 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex]; 5926 5927 if (!PP.getPreprocessingRecord()) { 5928 Error("no preprocessing record"); 5929 return nullptr; 5930 } 5931 5932 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor); 5933 if (llvm::Error Err = M.PreprocessorDetailCursor.JumpToBit( 5934 M.MacroOffsetsBase + PPOffs.BitOffset)) { 5935 Error(std::move(Err)); 5936 return nullptr; 5937 } 5938 5939 Expected<llvm::BitstreamEntry> MaybeEntry = 5940 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd); 5941 if (!MaybeEntry) { 5942 Error(MaybeEntry.takeError()); 5943 return nullptr; 5944 } 5945 llvm::BitstreamEntry Entry = MaybeEntry.get(); 5946 5947 if (Entry.Kind != llvm::BitstreamEntry::Record) 5948 return nullptr; 5949 5950 // Read the record. 5951 SourceRange Range(TranslateSourceLocation(M, PPOffs.getBegin()), 5952 TranslateSourceLocation(M, PPOffs.getEnd())); 5953 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord(); 5954 StringRef Blob; 5955 RecordData Record; 5956 Expected<unsigned> MaybeRecType = 5957 M.PreprocessorDetailCursor.readRecord(Entry.ID, Record, &Blob); 5958 if (!MaybeRecType) { 5959 Error(MaybeRecType.takeError()); 5960 return nullptr; 5961 } 5962 switch ((PreprocessorDetailRecordTypes)MaybeRecType.get()) { 5963 case PPD_MACRO_EXPANSION: { 5964 bool isBuiltin = Record[0]; 5965 IdentifierInfo *Name = nullptr; 5966 MacroDefinitionRecord *Def = nullptr; 5967 if (isBuiltin) 5968 Name = getLocalIdentifier(M, Record[1]); 5969 else { 5970 PreprocessedEntityID GlobalID = 5971 getGlobalPreprocessedEntityID(M, Record[1]); 5972 Def = cast<MacroDefinitionRecord>( 5973 PPRec.getLoadedPreprocessedEntity(GlobalID - 1)); 5974 } 5975 5976 MacroExpansion *ME; 5977 if (isBuiltin) 5978 ME = new (PPRec) MacroExpansion(Name, Range); 5979 else 5980 ME = new (PPRec) MacroExpansion(Def, Range); 5981 5982 return ME; 5983 } 5984 5985 case PPD_MACRO_DEFINITION: { 5986 // Decode the identifier info and then check again; if the macro is 5987 // still defined and associated with the identifier, 5988 IdentifierInfo *II = getLocalIdentifier(M, Record[0]); 5989 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range); 5990 5991 if (DeserializationListener) 5992 DeserializationListener->MacroDefinitionRead(PPID, MD); 5993 5994 return MD; 5995 } 5996 5997 case PPD_INCLUSION_DIRECTIVE: { 5998 const char *FullFileNameStart = Blob.data() + Record[0]; 5999 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]); 6000 const FileEntry *File = nullptr; 6001 if (!FullFileName.empty()) 6002 if (auto FE = PP.getFileManager().getFile(FullFileName)) 6003 File = *FE; 6004 6005 // FIXME: Stable encoding 6006 InclusionDirective::InclusionKind Kind 6007 = static_cast<InclusionDirective::InclusionKind>(Record[2]); 6008 InclusionDirective *ID 6009 = new (PPRec) InclusionDirective(PPRec, Kind, 6010 StringRef(Blob.data(), Record[0]), 6011 Record[1], Record[3], 6012 File, 6013 Range); 6014 return ID; 6015 } 6016 } 6017 6018 llvm_unreachable("Invalid PreprocessorDetailRecordTypes"); 6019 } 6020 6021 /// Find the next module that contains entities and return the ID 6022 /// of the first entry. 6023 /// 6024 /// \param SLocMapI points at a chunk of a module that contains no 6025 /// preprocessed entities or the entities it contains are not the ones we are 6026 /// looking for. 6027 PreprocessedEntityID ASTReader::findNextPreprocessedEntity( 6028 GlobalSLocOffsetMapType::const_iterator SLocMapI) const { 6029 ++SLocMapI; 6030 for (GlobalSLocOffsetMapType::const_iterator 6031 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) { 6032 ModuleFile &M = *SLocMapI->second; 6033 if (M.NumPreprocessedEntities) 6034 return M.BasePreprocessedEntityID; 6035 } 6036 6037 return getTotalNumPreprocessedEntities(); 6038 } 6039 6040 namespace { 6041 6042 struct PPEntityComp { 6043 const ASTReader &Reader; 6044 ModuleFile &M; 6045 6046 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) {} 6047 6048 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const { 6049 SourceLocation LHS = getLoc(L); 6050 SourceLocation RHS = getLoc(R); 6051 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS); 6052 } 6053 6054 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const { 6055 SourceLocation LHS = getLoc(L); 6056 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS); 6057 } 6058 6059 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const { 6060 SourceLocation RHS = getLoc(R); 6061 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS); 6062 } 6063 6064 SourceLocation getLoc(const PPEntityOffset &PPE) const { 6065 return Reader.TranslateSourceLocation(M, PPE.getBegin()); 6066 } 6067 }; 6068 6069 } // namespace 6070 6071 PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc, 6072 bool EndsAfter) const { 6073 if (SourceMgr.isLocalSourceLocation(Loc)) 6074 return getTotalNumPreprocessedEntities(); 6075 6076 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find( 6077 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1); 6078 assert(SLocMapI != GlobalSLocOffsetMap.end() && 6079 "Corrupted global sloc offset map"); 6080 6081 if (SLocMapI->second->NumPreprocessedEntities == 0) 6082 return findNextPreprocessedEntity(SLocMapI); 6083 6084 ModuleFile &M = *SLocMapI->second; 6085 6086 using pp_iterator = const PPEntityOffset *; 6087 6088 pp_iterator pp_begin = M.PreprocessedEntityOffsets; 6089 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities; 6090 6091 size_t Count = M.NumPreprocessedEntities; 6092 size_t Half; 6093 pp_iterator First = pp_begin; 6094 pp_iterator PPI; 6095 6096 if (EndsAfter) { 6097 PPI = std::upper_bound(pp_begin, pp_end, Loc, 6098 PPEntityComp(*this, M)); 6099 } else { 6100 // Do a binary search manually instead of using std::lower_bound because 6101 // The end locations of entities may be unordered (when a macro expansion 6102 // is inside another macro argument), but for this case it is not important 6103 // whether we get the first macro expansion or its containing macro. 6104 while (Count > 0) { 6105 Half = Count / 2; 6106 PPI = First; 6107 std::advance(PPI, Half); 6108 if (SourceMgr.isBeforeInTranslationUnit( 6109 TranslateSourceLocation(M, PPI->getEnd()), Loc)) { 6110 First = PPI; 6111 ++First; 6112 Count = Count - Half - 1; 6113 } else 6114 Count = Half; 6115 } 6116 } 6117 6118 if (PPI == pp_end) 6119 return findNextPreprocessedEntity(SLocMapI); 6120 6121 return M.BasePreprocessedEntityID + (PPI - pp_begin); 6122 } 6123 6124 /// Returns a pair of [Begin, End) indices of preallocated 6125 /// preprocessed entities that \arg Range encompasses. 6126 std::pair<unsigned, unsigned> 6127 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) { 6128 if (Range.isInvalid()) 6129 return std::make_pair(0,0); 6130 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin())); 6131 6132 PreprocessedEntityID BeginID = 6133 findPreprocessedEntity(Range.getBegin(), false); 6134 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true); 6135 return std::make_pair(BeginID, EndID); 6136 } 6137 6138 /// Optionally returns true or false if the preallocated preprocessed 6139 /// entity with index \arg Index came from file \arg FID. 6140 Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index, 6141 FileID FID) { 6142 if (FID.isInvalid()) 6143 return false; 6144 6145 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index); 6146 ModuleFile &M = *PPInfo.first; 6147 unsigned LocalIndex = PPInfo.second; 6148 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex]; 6149 6150 SourceLocation Loc = TranslateSourceLocation(M, PPOffs.getBegin()); 6151 if (Loc.isInvalid()) 6152 return false; 6153 6154 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID)) 6155 return true; 6156 else 6157 return false; 6158 } 6159 6160 namespace { 6161 6162 /// Visitor used to search for information about a header file. 6163 class HeaderFileInfoVisitor { 6164 const FileEntry *FE; 6165 Optional<HeaderFileInfo> HFI; 6166 6167 public: 6168 explicit HeaderFileInfoVisitor(const FileEntry *FE) : FE(FE) {} 6169 6170 bool operator()(ModuleFile &M) { 6171 HeaderFileInfoLookupTable *Table 6172 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable); 6173 if (!Table) 6174 return false; 6175 6176 // Look in the on-disk hash table for an entry for this file name. 6177 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE); 6178 if (Pos == Table->end()) 6179 return false; 6180 6181 HFI = *Pos; 6182 return true; 6183 } 6184 6185 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; } 6186 }; 6187 6188 } // namespace 6189 6190 HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) { 6191 HeaderFileInfoVisitor Visitor(FE); 6192 ModuleMgr.visit(Visitor); 6193 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo()) 6194 return *HFI; 6195 6196 return HeaderFileInfo(); 6197 } 6198 6199 void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) { 6200 using DiagState = DiagnosticsEngine::DiagState; 6201 SmallVector<DiagState *, 32> DiagStates; 6202 6203 for (ModuleFile &F : ModuleMgr) { 6204 unsigned Idx = 0; 6205 auto &Record = F.PragmaDiagMappings; 6206 if (Record.empty()) 6207 continue; 6208 6209 DiagStates.clear(); 6210 6211 auto ReadDiagState = 6212 [&](const DiagState &BasedOn, SourceLocation Loc, 6213 bool IncludeNonPragmaStates) -> DiagnosticsEngine::DiagState * { 6214 unsigned BackrefID = Record[Idx++]; 6215 if (BackrefID != 0) 6216 return DiagStates[BackrefID - 1]; 6217 6218 // A new DiagState was created here. 6219 Diag.DiagStates.push_back(BasedOn); 6220 DiagState *NewState = &Diag.DiagStates.back(); 6221 DiagStates.push_back(NewState); 6222 unsigned Size = Record[Idx++]; 6223 assert(Idx + Size * 2 <= Record.size() && 6224 "Invalid data, not enough diag/map pairs"); 6225 while (Size--) { 6226 unsigned DiagID = Record[Idx++]; 6227 DiagnosticMapping NewMapping = 6228 DiagnosticMapping::deserialize(Record[Idx++]); 6229 if (!NewMapping.isPragma() && !IncludeNonPragmaStates) 6230 continue; 6231 6232 DiagnosticMapping &Mapping = NewState->getOrAddMapping(DiagID); 6233 6234 // If this mapping was specified as a warning but the severity was 6235 // upgraded due to diagnostic settings, simulate the current diagnostic 6236 // settings (and use a warning). 6237 if (NewMapping.wasUpgradedFromWarning() && !Mapping.isErrorOrFatal()) { 6238 NewMapping.setSeverity(diag::Severity::Warning); 6239 NewMapping.setUpgradedFromWarning(false); 6240 } 6241 6242 Mapping = NewMapping; 6243 } 6244 return NewState; 6245 }; 6246 6247 // Read the first state. 6248 DiagState *FirstState; 6249 if (F.Kind == MK_ImplicitModule) { 6250 // Implicitly-built modules are reused with different diagnostic 6251 // settings. Use the initial diagnostic state from Diag to simulate this 6252 // compilation's diagnostic settings. 6253 FirstState = Diag.DiagStatesByLoc.FirstDiagState; 6254 DiagStates.push_back(FirstState); 6255 6256 // Skip the initial diagnostic state from the serialized module. 6257 assert(Record[1] == 0 && 6258 "Invalid data, unexpected backref in initial state"); 6259 Idx = 3 + Record[2] * 2; 6260 assert(Idx < Record.size() && 6261 "Invalid data, not enough state change pairs in initial state"); 6262 } else if (F.isModule()) { 6263 // For an explicit module, preserve the flags from the module build 6264 // command line (-w, -Weverything, -Werror, ...) along with any explicit 6265 // -Wblah flags. 6266 unsigned Flags = Record[Idx++]; 6267 DiagState Initial; 6268 Initial.SuppressSystemWarnings = Flags & 1; Flags >>= 1; 6269 Initial.ErrorsAsFatal = Flags & 1; Flags >>= 1; 6270 Initial.WarningsAsErrors = Flags & 1; Flags >>= 1; 6271 Initial.EnableAllWarnings = Flags & 1; Flags >>= 1; 6272 Initial.IgnoreAllWarnings = Flags & 1; Flags >>= 1; 6273 Initial.ExtBehavior = (diag::Severity)Flags; 6274 FirstState = ReadDiagState(Initial, SourceLocation(), true); 6275 6276 assert(F.OriginalSourceFileID.isValid()); 6277 6278 // Set up the root buffer of the module to start with the initial 6279 // diagnostic state of the module itself, to cover files that contain no 6280 // explicit transitions (for which we did not serialize anything). 6281 Diag.DiagStatesByLoc.Files[F.OriginalSourceFileID] 6282 .StateTransitions.push_back({FirstState, 0}); 6283 } else { 6284 // For prefix ASTs, start with whatever the user configured on the 6285 // command line. 6286 Idx++; // Skip flags. 6287 FirstState = ReadDiagState(*Diag.DiagStatesByLoc.CurDiagState, 6288 SourceLocation(), false); 6289 } 6290 6291 // Read the state transitions. 6292 unsigned NumLocations = Record[Idx++]; 6293 while (NumLocations--) { 6294 assert(Idx < Record.size() && 6295 "Invalid data, missing pragma diagnostic states"); 6296 SourceLocation Loc = ReadSourceLocation(F, Record[Idx++]); 6297 auto IDAndOffset = SourceMgr.getDecomposedLoc(Loc); 6298 assert(IDAndOffset.first.isValid() && "invalid FileID for transition"); 6299 assert(IDAndOffset.second == 0 && "not a start location for a FileID"); 6300 unsigned Transitions = Record[Idx++]; 6301 6302 // Note that we don't need to set up Parent/ParentOffset here, because 6303 // we won't be changing the diagnostic state within imported FileIDs 6304 // (other than perhaps appending to the main source file, which has no 6305 // parent). 6306 auto &F = Diag.DiagStatesByLoc.Files[IDAndOffset.first]; 6307 F.StateTransitions.reserve(F.StateTransitions.size() + Transitions); 6308 for (unsigned I = 0; I != Transitions; ++I) { 6309 unsigned Offset = Record[Idx++]; 6310 auto *State = 6311 ReadDiagState(*FirstState, Loc.getLocWithOffset(Offset), false); 6312 F.StateTransitions.push_back({State, Offset}); 6313 } 6314 } 6315 6316 // Read the final state. 6317 assert(Idx < Record.size() && 6318 "Invalid data, missing final pragma diagnostic state"); 6319 SourceLocation CurStateLoc = 6320 ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]); 6321 auto *CurState = ReadDiagState(*FirstState, CurStateLoc, false); 6322 6323 if (!F.isModule()) { 6324 Diag.DiagStatesByLoc.CurDiagState = CurState; 6325 Diag.DiagStatesByLoc.CurDiagStateLoc = CurStateLoc; 6326 6327 // Preserve the property that the imaginary root file describes the 6328 // current state. 6329 FileID NullFile; 6330 auto &T = Diag.DiagStatesByLoc.Files[NullFile].StateTransitions; 6331 if (T.empty()) 6332 T.push_back({CurState, 0}); 6333 else 6334 T[0].State = CurState; 6335 } 6336 6337 // Don't try to read these mappings again. 6338 Record.clear(); 6339 } 6340 } 6341 6342 /// Get the correct cursor and offset for loading a type. 6343 ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) { 6344 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index); 6345 assert(I != GlobalTypeMap.end() && "Corrupted global type map"); 6346 ModuleFile *M = I->second; 6347 return RecordLocation( 6348 M, M->TypeOffsets[Index - M->BaseTypeIndex].getBitOffset() + 6349 M->DeclsBlockStartOffset); 6350 } 6351 6352 static llvm::Optional<Type::TypeClass> getTypeClassForCode(TypeCode code) { 6353 switch (code) { 6354 #define TYPE_BIT_CODE(CLASS_ID, CODE_ID, CODE_VALUE) \ 6355 case TYPE_##CODE_ID: return Type::CLASS_ID; 6356 #include "clang/Serialization/TypeBitCodes.def" 6357 default: return llvm::None; 6358 } 6359 } 6360 6361 /// Read and return the type with the given index.. 6362 /// 6363 /// The index is the type ID, shifted and minus the number of predefs. This 6364 /// routine actually reads the record corresponding to the type at the given 6365 /// location. It is a helper routine for GetType, which deals with reading type 6366 /// IDs. 6367 QualType ASTReader::readTypeRecord(unsigned Index) { 6368 assert(ContextObj && "reading type with no AST context"); 6369 ASTContext &Context = *ContextObj; 6370 RecordLocation Loc = TypeCursorForIndex(Index); 6371 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor; 6372 6373 // Keep track of where we are in the stream, then jump back there 6374 // after reading this type. 6375 SavedStreamPosition SavedPosition(DeclsCursor); 6376 6377 ReadingKindTracker ReadingKind(Read_Type, *this); 6378 6379 // Note that we are loading a type record. 6380 Deserializing AType(this); 6381 6382 if (llvm::Error Err = DeclsCursor.JumpToBit(Loc.Offset)) { 6383 Error(std::move(Err)); 6384 return QualType(); 6385 } 6386 Expected<unsigned> RawCode = DeclsCursor.ReadCode(); 6387 if (!RawCode) { 6388 Error(RawCode.takeError()); 6389 return QualType(); 6390 } 6391 6392 ASTRecordReader Record(*this, *Loc.F); 6393 Expected<unsigned> Code = Record.readRecord(DeclsCursor, RawCode.get()); 6394 if (!Code) { 6395 Error(Code.takeError()); 6396 return QualType(); 6397 } 6398 if (Code.get() == TYPE_EXT_QUAL) { 6399 QualType baseType = Record.readQualType(); 6400 Qualifiers quals = Record.readQualifiers(); 6401 return Context.getQualifiedType(baseType, quals); 6402 } 6403 6404 auto maybeClass = getTypeClassForCode((TypeCode) Code.get()); 6405 if (!maybeClass) { 6406 Error("Unexpected code for type"); 6407 return QualType(); 6408 } 6409 6410 serialization::AbstractTypeReader<ASTRecordReader> TypeReader(Record); 6411 return TypeReader.read(*maybeClass); 6412 } 6413 6414 namespace clang { 6415 6416 class TypeLocReader : public TypeLocVisitor<TypeLocReader> { 6417 ASTRecordReader &Reader; 6418 6419 SourceLocation readSourceLocation() { 6420 return Reader.readSourceLocation(); 6421 } 6422 6423 TypeSourceInfo *GetTypeSourceInfo() { 6424 return Reader.readTypeSourceInfo(); 6425 } 6426 6427 NestedNameSpecifierLoc ReadNestedNameSpecifierLoc() { 6428 return Reader.readNestedNameSpecifierLoc(); 6429 } 6430 6431 Attr *ReadAttr() { 6432 return Reader.readAttr(); 6433 } 6434 6435 public: 6436 TypeLocReader(ASTRecordReader &Reader) : Reader(Reader) {} 6437 6438 // We want compile-time assurance that we've enumerated all of 6439 // these, so unfortunately we have to declare them first, then 6440 // define them out-of-line. 6441 #define ABSTRACT_TYPELOC(CLASS, PARENT) 6442 #define TYPELOC(CLASS, PARENT) \ 6443 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc); 6444 #include "clang/AST/TypeLocNodes.def" 6445 6446 void VisitFunctionTypeLoc(FunctionTypeLoc); 6447 void VisitArrayTypeLoc(ArrayTypeLoc); 6448 }; 6449 6450 } // namespace clang 6451 6452 void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { 6453 // nothing to do 6454 } 6455 6456 void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) { 6457 TL.setBuiltinLoc(readSourceLocation()); 6458 if (TL.needsExtraLocalData()) { 6459 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Reader.readInt())); 6460 TL.setWrittenSignSpec(static_cast<TypeSpecifierSign>(Reader.readInt())); 6461 TL.setWrittenWidthSpec(static_cast<TypeSpecifierWidth>(Reader.readInt())); 6462 TL.setModeAttr(Reader.readInt()); 6463 } 6464 } 6465 6466 void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) { 6467 TL.setNameLoc(readSourceLocation()); 6468 } 6469 6470 void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) { 6471 TL.setStarLoc(readSourceLocation()); 6472 } 6473 6474 void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) { 6475 // nothing to do 6476 } 6477 6478 void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) { 6479 // nothing to do 6480 } 6481 6482 void TypeLocReader::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) { 6483 TL.setExpansionLoc(readSourceLocation()); 6484 } 6485 6486 void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) { 6487 TL.setCaretLoc(readSourceLocation()); 6488 } 6489 6490 void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) { 6491 TL.setAmpLoc(readSourceLocation()); 6492 } 6493 6494 void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) { 6495 TL.setAmpAmpLoc(readSourceLocation()); 6496 } 6497 6498 void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) { 6499 TL.setStarLoc(readSourceLocation()); 6500 TL.setClassTInfo(GetTypeSourceInfo()); 6501 } 6502 6503 void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) { 6504 TL.setLBracketLoc(readSourceLocation()); 6505 TL.setRBracketLoc(readSourceLocation()); 6506 if (Reader.readBool()) 6507 TL.setSizeExpr(Reader.readExpr()); 6508 else 6509 TL.setSizeExpr(nullptr); 6510 } 6511 6512 void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) { 6513 VisitArrayTypeLoc(TL); 6514 } 6515 6516 void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) { 6517 VisitArrayTypeLoc(TL); 6518 } 6519 6520 void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) { 6521 VisitArrayTypeLoc(TL); 6522 } 6523 6524 void TypeLocReader::VisitDependentSizedArrayTypeLoc( 6525 DependentSizedArrayTypeLoc TL) { 6526 VisitArrayTypeLoc(TL); 6527 } 6528 6529 void TypeLocReader::VisitDependentAddressSpaceTypeLoc( 6530 DependentAddressSpaceTypeLoc TL) { 6531 6532 TL.setAttrNameLoc(readSourceLocation()); 6533 TL.setAttrOperandParensRange(Reader.readSourceRange()); 6534 TL.setAttrExprOperand(Reader.readExpr()); 6535 } 6536 6537 void TypeLocReader::VisitDependentSizedExtVectorTypeLoc( 6538 DependentSizedExtVectorTypeLoc TL) { 6539 TL.setNameLoc(readSourceLocation()); 6540 } 6541 6542 void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) { 6543 TL.setNameLoc(readSourceLocation()); 6544 } 6545 6546 void TypeLocReader::VisitDependentVectorTypeLoc( 6547 DependentVectorTypeLoc TL) { 6548 TL.setNameLoc(readSourceLocation()); 6549 } 6550 6551 void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) { 6552 TL.setNameLoc(readSourceLocation()); 6553 } 6554 6555 void TypeLocReader::VisitConstantMatrixTypeLoc(ConstantMatrixTypeLoc TL) { 6556 TL.setAttrNameLoc(readSourceLocation()); 6557 TL.setAttrOperandParensRange(Reader.readSourceRange()); 6558 TL.setAttrRowOperand(Reader.readExpr()); 6559 TL.setAttrColumnOperand(Reader.readExpr()); 6560 } 6561 6562 void TypeLocReader::VisitDependentSizedMatrixTypeLoc( 6563 DependentSizedMatrixTypeLoc TL) { 6564 TL.setAttrNameLoc(readSourceLocation()); 6565 TL.setAttrOperandParensRange(Reader.readSourceRange()); 6566 TL.setAttrRowOperand(Reader.readExpr()); 6567 TL.setAttrColumnOperand(Reader.readExpr()); 6568 } 6569 6570 void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) { 6571 TL.setLocalRangeBegin(readSourceLocation()); 6572 TL.setLParenLoc(readSourceLocation()); 6573 TL.setRParenLoc(readSourceLocation()); 6574 TL.setExceptionSpecRange(Reader.readSourceRange()); 6575 TL.setLocalRangeEnd(readSourceLocation()); 6576 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) { 6577 TL.setParam(i, Reader.readDeclAs<ParmVarDecl>()); 6578 } 6579 } 6580 6581 void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) { 6582 VisitFunctionTypeLoc(TL); 6583 } 6584 6585 void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) { 6586 VisitFunctionTypeLoc(TL); 6587 } 6588 6589 void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) { 6590 TL.setNameLoc(readSourceLocation()); 6591 } 6592 6593 void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) { 6594 TL.setNameLoc(readSourceLocation()); 6595 } 6596 6597 void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) { 6598 TL.setTypeofLoc(readSourceLocation()); 6599 TL.setLParenLoc(readSourceLocation()); 6600 TL.setRParenLoc(readSourceLocation()); 6601 } 6602 6603 void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) { 6604 TL.setTypeofLoc(readSourceLocation()); 6605 TL.setLParenLoc(readSourceLocation()); 6606 TL.setRParenLoc(readSourceLocation()); 6607 TL.setUnderlyingTInfo(GetTypeSourceInfo()); 6608 } 6609 6610 void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) { 6611 TL.setNameLoc(readSourceLocation()); 6612 } 6613 6614 void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) { 6615 TL.setKWLoc(readSourceLocation()); 6616 TL.setLParenLoc(readSourceLocation()); 6617 TL.setRParenLoc(readSourceLocation()); 6618 TL.setUnderlyingTInfo(GetTypeSourceInfo()); 6619 } 6620 6621 void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) { 6622 TL.setNameLoc(readSourceLocation()); 6623 if (Reader.readBool()) { 6624 TL.setNestedNameSpecifierLoc(ReadNestedNameSpecifierLoc()); 6625 TL.setTemplateKWLoc(readSourceLocation()); 6626 TL.setConceptNameLoc(readSourceLocation()); 6627 TL.setFoundDecl(Reader.readDeclAs<NamedDecl>()); 6628 TL.setLAngleLoc(readSourceLocation()); 6629 TL.setRAngleLoc(readSourceLocation()); 6630 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) 6631 TL.setArgLocInfo(i, Reader.readTemplateArgumentLocInfo( 6632 TL.getTypePtr()->getArg(i).getKind())); 6633 } 6634 } 6635 6636 void TypeLocReader::VisitDeducedTemplateSpecializationTypeLoc( 6637 DeducedTemplateSpecializationTypeLoc TL) { 6638 TL.setTemplateNameLoc(readSourceLocation()); 6639 } 6640 6641 void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) { 6642 TL.setNameLoc(readSourceLocation()); 6643 } 6644 6645 void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) { 6646 TL.setNameLoc(readSourceLocation()); 6647 } 6648 6649 void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) { 6650 TL.setAttr(ReadAttr()); 6651 } 6652 6653 void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) { 6654 TL.setNameLoc(readSourceLocation()); 6655 } 6656 6657 void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc( 6658 SubstTemplateTypeParmTypeLoc TL) { 6659 TL.setNameLoc(readSourceLocation()); 6660 } 6661 6662 void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc( 6663 SubstTemplateTypeParmPackTypeLoc TL) { 6664 TL.setNameLoc(readSourceLocation()); 6665 } 6666 6667 void TypeLocReader::VisitTemplateSpecializationTypeLoc( 6668 TemplateSpecializationTypeLoc TL) { 6669 TL.setTemplateKeywordLoc(readSourceLocation()); 6670 TL.setTemplateNameLoc(readSourceLocation()); 6671 TL.setLAngleLoc(readSourceLocation()); 6672 TL.setRAngleLoc(readSourceLocation()); 6673 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) 6674 TL.setArgLocInfo( 6675 i, 6676 Reader.readTemplateArgumentLocInfo( 6677 TL.getTypePtr()->getArg(i).getKind())); 6678 } 6679 6680 void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) { 6681 TL.setLParenLoc(readSourceLocation()); 6682 TL.setRParenLoc(readSourceLocation()); 6683 } 6684 6685 void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) { 6686 TL.setElaboratedKeywordLoc(readSourceLocation()); 6687 TL.setQualifierLoc(ReadNestedNameSpecifierLoc()); 6688 } 6689 6690 void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) { 6691 TL.setNameLoc(readSourceLocation()); 6692 } 6693 6694 void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) { 6695 TL.setElaboratedKeywordLoc(readSourceLocation()); 6696 TL.setQualifierLoc(ReadNestedNameSpecifierLoc()); 6697 TL.setNameLoc(readSourceLocation()); 6698 } 6699 6700 void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc( 6701 DependentTemplateSpecializationTypeLoc TL) { 6702 TL.setElaboratedKeywordLoc(readSourceLocation()); 6703 TL.setQualifierLoc(ReadNestedNameSpecifierLoc()); 6704 TL.setTemplateKeywordLoc(readSourceLocation()); 6705 TL.setTemplateNameLoc(readSourceLocation()); 6706 TL.setLAngleLoc(readSourceLocation()); 6707 TL.setRAngleLoc(readSourceLocation()); 6708 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) 6709 TL.setArgLocInfo( 6710 I, 6711 Reader.readTemplateArgumentLocInfo( 6712 TL.getTypePtr()->getArg(I).getKind())); 6713 } 6714 6715 void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) { 6716 TL.setEllipsisLoc(readSourceLocation()); 6717 } 6718 6719 void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) { 6720 TL.setNameLoc(readSourceLocation()); 6721 } 6722 6723 void TypeLocReader::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) { 6724 if (TL.getNumProtocols()) { 6725 TL.setProtocolLAngleLoc(readSourceLocation()); 6726 TL.setProtocolRAngleLoc(readSourceLocation()); 6727 } 6728 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i) 6729 TL.setProtocolLoc(i, readSourceLocation()); 6730 } 6731 6732 void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) { 6733 TL.setHasBaseTypeAsWritten(Reader.readBool()); 6734 TL.setTypeArgsLAngleLoc(readSourceLocation()); 6735 TL.setTypeArgsRAngleLoc(readSourceLocation()); 6736 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i) 6737 TL.setTypeArgTInfo(i, GetTypeSourceInfo()); 6738 TL.setProtocolLAngleLoc(readSourceLocation()); 6739 TL.setProtocolRAngleLoc(readSourceLocation()); 6740 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i) 6741 TL.setProtocolLoc(i, readSourceLocation()); 6742 } 6743 6744 void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { 6745 TL.setStarLoc(readSourceLocation()); 6746 } 6747 6748 void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) { 6749 TL.setKWLoc(readSourceLocation()); 6750 TL.setLParenLoc(readSourceLocation()); 6751 TL.setRParenLoc(readSourceLocation()); 6752 } 6753 6754 void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) { 6755 TL.setKWLoc(readSourceLocation()); 6756 } 6757 6758 void TypeLocReader::VisitExtIntTypeLoc(clang::ExtIntTypeLoc TL) { 6759 TL.setNameLoc(readSourceLocation()); 6760 } 6761 void TypeLocReader::VisitDependentExtIntTypeLoc( 6762 clang::DependentExtIntTypeLoc TL) { 6763 TL.setNameLoc(readSourceLocation()); 6764 } 6765 6766 6767 void ASTRecordReader::readTypeLoc(TypeLoc TL) { 6768 TypeLocReader TLR(*this); 6769 for (; !TL.isNull(); TL = TL.getNextTypeLoc()) 6770 TLR.Visit(TL); 6771 } 6772 6773 TypeSourceInfo *ASTRecordReader::readTypeSourceInfo() { 6774 QualType InfoTy = readType(); 6775 if (InfoTy.isNull()) 6776 return nullptr; 6777 6778 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy); 6779 readTypeLoc(TInfo->getTypeLoc()); 6780 return TInfo; 6781 } 6782 6783 QualType ASTReader::GetType(TypeID ID) { 6784 assert(ContextObj && "reading type with no AST context"); 6785 ASTContext &Context = *ContextObj; 6786 6787 unsigned FastQuals = ID & Qualifiers::FastMask; 6788 unsigned Index = ID >> Qualifiers::FastWidth; 6789 6790 if (Index < NUM_PREDEF_TYPE_IDS) { 6791 QualType T; 6792 switch ((PredefinedTypeIDs)Index) { 6793 case PREDEF_TYPE_NULL_ID: 6794 return QualType(); 6795 case PREDEF_TYPE_VOID_ID: 6796 T = Context.VoidTy; 6797 break; 6798 case PREDEF_TYPE_BOOL_ID: 6799 T = Context.BoolTy; 6800 break; 6801 case PREDEF_TYPE_CHAR_U_ID: 6802 case PREDEF_TYPE_CHAR_S_ID: 6803 // FIXME: Check that the signedness of CharTy is correct! 6804 T = Context.CharTy; 6805 break; 6806 case PREDEF_TYPE_UCHAR_ID: 6807 T = Context.UnsignedCharTy; 6808 break; 6809 case PREDEF_TYPE_USHORT_ID: 6810 T = Context.UnsignedShortTy; 6811 break; 6812 case PREDEF_TYPE_UINT_ID: 6813 T = Context.UnsignedIntTy; 6814 break; 6815 case PREDEF_TYPE_ULONG_ID: 6816 T = Context.UnsignedLongTy; 6817 break; 6818 case PREDEF_TYPE_ULONGLONG_ID: 6819 T = Context.UnsignedLongLongTy; 6820 break; 6821 case PREDEF_TYPE_UINT128_ID: 6822 T = Context.UnsignedInt128Ty; 6823 break; 6824 case PREDEF_TYPE_SCHAR_ID: 6825 T = Context.SignedCharTy; 6826 break; 6827 case PREDEF_TYPE_WCHAR_ID: 6828 T = Context.WCharTy; 6829 break; 6830 case PREDEF_TYPE_SHORT_ID: 6831 T = Context.ShortTy; 6832 break; 6833 case PREDEF_TYPE_INT_ID: 6834 T = Context.IntTy; 6835 break; 6836 case PREDEF_TYPE_LONG_ID: 6837 T = Context.LongTy; 6838 break; 6839 case PREDEF_TYPE_LONGLONG_ID: 6840 T = Context.LongLongTy; 6841 break; 6842 case PREDEF_TYPE_INT128_ID: 6843 T = Context.Int128Ty; 6844 break; 6845 case PREDEF_TYPE_BFLOAT16_ID: 6846 T = Context.BFloat16Ty; 6847 break; 6848 case PREDEF_TYPE_HALF_ID: 6849 T = Context.HalfTy; 6850 break; 6851 case PREDEF_TYPE_FLOAT_ID: 6852 T = Context.FloatTy; 6853 break; 6854 case PREDEF_TYPE_DOUBLE_ID: 6855 T = Context.DoubleTy; 6856 break; 6857 case PREDEF_TYPE_LONGDOUBLE_ID: 6858 T = Context.LongDoubleTy; 6859 break; 6860 case PREDEF_TYPE_SHORT_ACCUM_ID: 6861 T = Context.ShortAccumTy; 6862 break; 6863 case PREDEF_TYPE_ACCUM_ID: 6864 T = Context.AccumTy; 6865 break; 6866 case PREDEF_TYPE_LONG_ACCUM_ID: 6867 T = Context.LongAccumTy; 6868 break; 6869 case PREDEF_TYPE_USHORT_ACCUM_ID: 6870 T = Context.UnsignedShortAccumTy; 6871 break; 6872 case PREDEF_TYPE_UACCUM_ID: 6873 T = Context.UnsignedAccumTy; 6874 break; 6875 case PREDEF_TYPE_ULONG_ACCUM_ID: 6876 T = Context.UnsignedLongAccumTy; 6877 break; 6878 case PREDEF_TYPE_SHORT_FRACT_ID: 6879 T = Context.ShortFractTy; 6880 break; 6881 case PREDEF_TYPE_FRACT_ID: 6882 T = Context.FractTy; 6883 break; 6884 case PREDEF_TYPE_LONG_FRACT_ID: 6885 T = Context.LongFractTy; 6886 break; 6887 case PREDEF_TYPE_USHORT_FRACT_ID: 6888 T = Context.UnsignedShortFractTy; 6889 break; 6890 case PREDEF_TYPE_UFRACT_ID: 6891 T = Context.UnsignedFractTy; 6892 break; 6893 case PREDEF_TYPE_ULONG_FRACT_ID: 6894 T = Context.UnsignedLongFractTy; 6895 break; 6896 case PREDEF_TYPE_SAT_SHORT_ACCUM_ID: 6897 T = Context.SatShortAccumTy; 6898 break; 6899 case PREDEF_TYPE_SAT_ACCUM_ID: 6900 T = Context.SatAccumTy; 6901 break; 6902 case PREDEF_TYPE_SAT_LONG_ACCUM_ID: 6903 T = Context.SatLongAccumTy; 6904 break; 6905 case PREDEF_TYPE_SAT_USHORT_ACCUM_ID: 6906 T = Context.SatUnsignedShortAccumTy; 6907 break; 6908 case PREDEF_TYPE_SAT_UACCUM_ID: 6909 T = Context.SatUnsignedAccumTy; 6910 break; 6911 case PREDEF_TYPE_SAT_ULONG_ACCUM_ID: 6912 T = Context.SatUnsignedLongAccumTy; 6913 break; 6914 case PREDEF_TYPE_SAT_SHORT_FRACT_ID: 6915 T = Context.SatShortFractTy; 6916 break; 6917 case PREDEF_TYPE_SAT_FRACT_ID: 6918 T = Context.SatFractTy; 6919 break; 6920 case PREDEF_TYPE_SAT_LONG_FRACT_ID: 6921 T = Context.SatLongFractTy; 6922 break; 6923 case PREDEF_TYPE_SAT_USHORT_FRACT_ID: 6924 T = Context.SatUnsignedShortFractTy; 6925 break; 6926 case PREDEF_TYPE_SAT_UFRACT_ID: 6927 T = Context.SatUnsignedFractTy; 6928 break; 6929 case PREDEF_TYPE_SAT_ULONG_FRACT_ID: 6930 T = Context.SatUnsignedLongFractTy; 6931 break; 6932 case PREDEF_TYPE_FLOAT16_ID: 6933 T = Context.Float16Ty; 6934 break; 6935 case PREDEF_TYPE_FLOAT128_ID: 6936 T = Context.Float128Ty; 6937 break; 6938 case PREDEF_TYPE_OVERLOAD_ID: 6939 T = Context.OverloadTy; 6940 break; 6941 case PREDEF_TYPE_BOUND_MEMBER: 6942 T = Context.BoundMemberTy; 6943 break; 6944 case PREDEF_TYPE_PSEUDO_OBJECT: 6945 T = Context.PseudoObjectTy; 6946 break; 6947 case PREDEF_TYPE_DEPENDENT_ID: 6948 T = Context.DependentTy; 6949 break; 6950 case PREDEF_TYPE_UNKNOWN_ANY: 6951 T = Context.UnknownAnyTy; 6952 break; 6953 case PREDEF_TYPE_NULLPTR_ID: 6954 T = Context.NullPtrTy; 6955 break; 6956 case PREDEF_TYPE_CHAR8_ID: 6957 T = Context.Char8Ty; 6958 break; 6959 case PREDEF_TYPE_CHAR16_ID: 6960 T = Context.Char16Ty; 6961 break; 6962 case PREDEF_TYPE_CHAR32_ID: 6963 T = Context.Char32Ty; 6964 break; 6965 case PREDEF_TYPE_OBJC_ID: 6966 T = Context.ObjCBuiltinIdTy; 6967 break; 6968 case PREDEF_TYPE_OBJC_CLASS: 6969 T = Context.ObjCBuiltinClassTy; 6970 break; 6971 case PREDEF_TYPE_OBJC_SEL: 6972 T = Context.ObjCBuiltinSelTy; 6973 break; 6974 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 6975 case PREDEF_TYPE_##Id##_ID: \ 6976 T = Context.SingletonId; \ 6977 break; 6978 #include "clang/Basic/OpenCLImageTypes.def" 6979 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 6980 case PREDEF_TYPE_##Id##_ID: \ 6981 T = Context.Id##Ty; \ 6982 break; 6983 #include "clang/Basic/OpenCLExtensionTypes.def" 6984 case PREDEF_TYPE_SAMPLER_ID: 6985 T = Context.OCLSamplerTy; 6986 break; 6987 case PREDEF_TYPE_EVENT_ID: 6988 T = Context.OCLEventTy; 6989 break; 6990 case PREDEF_TYPE_CLK_EVENT_ID: 6991 T = Context.OCLClkEventTy; 6992 break; 6993 case PREDEF_TYPE_QUEUE_ID: 6994 T = Context.OCLQueueTy; 6995 break; 6996 case PREDEF_TYPE_RESERVE_ID_ID: 6997 T = Context.OCLReserveIDTy; 6998 break; 6999 case PREDEF_TYPE_AUTO_DEDUCT: 7000 T = Context.getAutoDeductType(); 7001 break; 7002 case PREDEF_TYPE_AUTO_RREF_DEDUCT: 7003 T = Context.getAutoRRefDeductType(); 7004 break; 7005 case PREDEF_TYPE_ARC_UNBRIDGED_CAST: 7006 T = Context.ARCUnbridgedCastTy; 7007 break; 7008 case PREDEF_TYPE_BUILTIN_FN: 7009 T = Context.BuiltinFnTy; 7010 break; 7011 case PREDEF_TYPE_INCOMPLETE_MATRIX_IDX: 7012 T = Context.IncompleteMatrixIdxTy; 7013 break; 7014 case PREDEF_TYPE_OMP_ARRAY_SECTION: 7015 T = Context.OMPArraySectionTy; 7016 break; 7017 case PREDEF_TYPE_OMP_ARRAY_SHAPING: 7018 T = Context.OMPArraySectionTy; 7019 break; 7020 case PREDEF_TYPE_OMP_ITERATOR: 7021 T = Context.OMPIteratorTy; 7022 break; 7023 #define SVE_TYPE(Name, Id, SingletonId) \ 7024 case PREDEF_TYPE_##Id##_ID: \ 7025 T = Context.SingletonId; \ 7026 break; 7027 #include "clang/Basic/AArch64SVEACLETypes.def" 7028 #define PPC_MMA_VECTOR_TYPE(Name, Id, Size) \ 7029 case PREDEF_TYPE_##Id##_ID: \ 7030 T = Context.Id##Ty; \ 7031 break; 7032 #include "clang/Basic/PPCTypes.def" 7033 } 7034 7035 assert(!T.isNull() && "Unknown predefined type"); 7036 return T.withFastQualifiers(FastQuals); 7037 } 7038 7039 Index -= NUM_PREDEF_TYPE_IDS; 7040 assert(Index < TypesLoaded.size() && "Type index out-of-range"); 7041 if (TypesLoaded[Index].isNull()) { 7042 TypesLoaded[Index] = readTypeRecord(Index); 7043 if (TypesLoaded[Index].isNull()) 7044 return QualType(); 7045 7046 TypesLoaded[Index]->setFromAST(); 7047 if (DeserializationListener) 7048 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID), 7049 TypesLoaded[Index]); 7050 } 7051 7052 return TypesLoaded[Index].withFastQualifiers(FastQuals); 7053 } 7054 7055 QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) { 7056 return GetType(getGlobalTypeID(F, LocalID)); 7057 } 7058 7059 serialization::TypeID 7060 ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const { 7061 unsigned FastQuals = LocalID & Qualifiers::FastMask; 7062 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth; 7063 7064 if (LocalIndex < NUM_PREDEF_TYPE_IDS) 7065 return LocalID; 7066 7067 if (!F.ModuleOffsetMap.empty()) 7068 ReadModuleOffsetMap(F); 7069 7070 ContinuousRangeMap<uint32_t, int, 2>::iterator I 7071 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS); 7072 assert(I != F.TypeRemap.end() && "Invalid index into type index remap"); 7073 7074 unsigned GlobalIndex = LocalIndex + I->second; 7075 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals; 7076 } 7077 7078 TemplateArgumentLocInfo 7079 ASTRecordReader::readTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind) { 7080 switch (Kind) { 7081 case TemplateArgument::Expression: 7082 return readExpr(); 7083 case TemplateArgument::Type: 7084 return readTypeSourceInfo(); 7085 case TemplateArgument::Template: { 7086 NestedNameSpecifierLoc QualifierLoc = 7087 readNestedNameSpecifierLoc(); 7088 SourceLocation TemplateNameLoc = readSourceLocation(); 7089 return TemplateArgumentLocInfo(getASTContext(), QualifierLoc, 7090 TemplateNameLoc, SourceLocation()); 7091 } 7092 case TemplateArgument::TemplateExpansion: { 7093 NestedNameSpecifierLoc QualifierLoc = readNestedNameSpecifierLoc(); 7094 SourceLocation TemplateNameLoc = readSourceLocation(); 7095 SourceLocation EllipsisLoc = readSourceLocation(); 7096 return TemplateArgumentLocInfo(getASTContext(), QualifierLoc, 7097 TemplateNameLoc, EllipsisLoc); 7098 } 7099 case TemplateArgument::Null: 7100 case TemplateArgument::Integral: 7101 case TemplateArgument::Declaration: 7102 case TemplateArgument::NullPtr: 7103 case TemplateArgument::Pack: 7104 // FIXME: Is this right? 7105 return TemplateArgumentLocInfo(); 7106 } 7107 llvm_unreachable("unexpected template argument loc"); 7108 } 7109 7110 TemplateArgumentLoc ASTRecordReader::readTemplateArgumentLoc() { 7111 TemplateArgument Arg = readTemplateArgument(); 7112 7113 if (Arg.getKind() == TemplateArgument::Expression) { 7114 if (readBool()) // bool InfoHasSameExpr. 7115 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr())); 7116 } 7117 return TemplateArgumentLoc(Arg, readTemplateArgumentLocInfo(Arg.getKind())); 7118 } 7119 7120 const ASTTemplateArgumentListInfo * 7121 ASTRecordReader::readASTTemplateArgumentListInfo() { 7122 SourceLocation LAngleLoc = readSourceLocation(); 7123 SourceLocation RAngleLoc = readSourceLocation(); 7124 unsigned NumArgsAsWritten = readInt(); 7125 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc); 7126 for (unsigned i = 0; i != NumArgsAsWritten; ++i) 7127 TemplArgsInfo.addArgument(readTemplateArgumentLoc()); 7128 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo); 7129 } 7130 7131 Decl *ASTReader::GetExternalDecl(uint32_t ID) { 7132 return GetDecl(ID); 7133 } 7134 7135 void ASTReader::CompleteRedeclChain(const Decl *D) { 7136 if (NumCurrentElementsDeserializing) { 7137 // We arrange to not care about the complete redeclaration chain while we're 7138 // deserializing. Just remember that the AST has marked this one as complete 7139 // but that it's not actually complete yet, so we know we still need to 7140 // complete it later. 7141 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D)); 7142 return; 7143 } 7144 7145 const DeclContext *DC = D->getDeclContext()->getRedeclContext(); 7146 7147 // If this is a named declaration, complete it by looking it up 7148 // within its context. 7149 // 7150 // FIXME: Merging a function definition should merge 7151 // all mergeable entities within it. 7152 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) || 7153 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) { 7154 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) { 7155 if (!getContext().getLangOpts().CPlusPlus && 7156 isa<TranslationUnitDecl>(DC)) { 7157 // Outside of C++, we don't have a lookup table for the TU, so update 7158 // the identifier instead. (For C++ modules, we don't store decls 7159 // in the serialized identifier table, so we do the lookup in the TU.) 7160 auto *II = Name.getAsIdentifierInfo(); 7161 assert(II && "non-identifier name in C?"); 7162 if (II->isOutOfDate()) 7163 updateOutOfDateIdentifier(*II); 7164 } else 7165 DC->lookup(Name); 7166 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) { 7167 // Find all declarations of this kind from the relevant context. 7168 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) { 7169 auto *DC = cast<DeclContext>(DCDecl); 7170 SmallVector<Decl*, 8> Decls; 7171 FindExternalLexicalDecls( 7172 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls); 7173 } 7174 } 7175 } 7176 7177 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) 7178 CTSD->getSpecializedTemplate()->LoadLazySpecializations(); 7179 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D)) 7180 VTSD->getSpecializedTemplate()->LoadLazySpecializations(); 7181 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 7182 if (auto *Template = FD->getPrimaryTemplate()) 7183 Template->LoadLazySpecializations(); 7184 } 7185 } 7186 7187 CXXCtorInitializer ** 7188 ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) { 7189 RecordLocation Loc = getLocalBitOffset(Offset); 7190 BitstreamCursor &Cursor = Loc.F->DeclsCursor; 7191 SavedStreamPosition SavedPosition(Cursor); 7192 if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) { 7193 Error(std::move(Err)); 7194 return nullptr; 7195 } 7196 ReadingKindTracker ReadingKind(Read_Decl, *this); 7197 7198 Expected<unsigned> MaybeCode = Cursor.ReadCode(); 7199 if (!MaybeCode) { 7200 Error(MaybeCode.takeError()); 7201 return nullptr; 7202 } 7203 unsigned Code = MaybeCode.get(); 7204 7205 ASTRecordReader Record(*this, *Loc.F); 7206 Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code); 7207 if (!MaybeRecCode) { 7208 Error(MaybeRecCode.takeError()); 7209 return nullptr; 7210 } 7211 if (MaybeRecCode.get() != DECL_CXX_CTOR_INITIALIZERS) { 7212 Error("malformed AST file: missing C++ ctor initializers"); 7213 return nullptr; 7214 } 7215 7216 return Record.readCXXCtorInitializers(); 7217 } 7218 7219 CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) { 7220 assert(ContextObj && "reading base specifiers with no AST context"); 7221 ASTContext &Context = *ContextObj; 7222 7223 RecordLocation Loc = getLocalBitOffset(Offset); 7224 BitstreamCursor &Cursor = Loc.F->DeclsCursor; 7225 SavedStreamPosition SavedPosition(Cursor); 7226 if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) { 7227 Error(std::move(Err)); 7228 return nullptr; 7229 } 7230 ReadingKindTracker ReadingKind(Read_Decl, *this); 7231 7232 Expected<unsigned> MaybeCode = Cursor.ReadCode(); 7233 if (!MaybeCode) { 7234 Error(MaybeCode.takeError()); 7235 return nullptr; 7236 } 7237 unsigned Code = MaybeCode.get(); 7238 7239 ASTRecordReader Record(*this, *Loc.F); 7240 Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code); 7241 if (!MaybeRecCode) { 7242 Error(MaybeCode.takeError()); 7243 return nullptr; 7244 } 7245 unsigned RecCode = MaybeRecCode.get(); 7246 7247 if (RecCode != DECL_CXX_BASE_SPECIFIERS) { 7248 Error("malformed AST file: missing C++ base specifiers"); 7249 return nullptr; 7250 } 7251 7252 unsigned NumBases = Record.readInt(); 7253 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases); 7254 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases]; 7255 for (unsigned I = 0; I != NumBases; ++I) 7256 Bases[I] = Record.readCXXBaseSpecifier(); 7257 return Bases; 7258 } 7259 7260 serialization::DeclID 7261 ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const { 7262 if (LocalID < NUM_PREDEF_DECL_IDS) 7263 return LocalID; 7264 7265 if (!F.ModuleOffsetMap.empty()) 7266 ReadModuleOffsetMap(F); 7267 7268 ContinuousRangeMap<uint32_t, int, 2>::iterator I 7269 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS); 7270 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap"); 7271 7272 return LocalID + I->second; 7273 } 7274 7275 bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID, 7276 ModuleFile &M) const { 7277 // Predefined decls aren't from any module. 7278 if (ID < NUM_PREDEF_DECL_IDS) 7279 return false; 7280 7281 return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID && 7282 ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls; 7283 } 7284 7285 ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) { 7286 if (!D->isFromASTFile()) 7287 return nullptr; 7288 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID()); 7289 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map"); 7290 return I->second; 7291 } 7292 7293 SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) { 7294 if (ID < NUM_PREDEF_DECL_IDS) 7295 return SourceLocation(); 7296 7297 unsigned Index = ID - NUM_PREDEF_DECL_IDS; 7298 7299 if (Index > DeclsLoaded.size()) { 7300 Error("declaration ID out-of-range for AST file"); 7301 return SourceLocation(); 7302 } 7303 7304 if (Decl *D = DeclsLoaded[Index]) 7305 return D->getLocation(); 7306 7307 SourceLocation Loc; 7308 DeclCursorForID(ID, Loc); 7309 return Loc; 7310 } 7311 7312 static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) { 7313 switch (ID) { 7314 case PREDEF_DECL_NULL_ID: 7315 return nullptr; 7316 7317 case PREDEF_DECL_TRANSLATION_UNIT_ID: 7318 return Context.getTranslationUnitDecl(); 7319 7320 case PREDEF_DECL_OBJC_ID_ID: 7321 return Context.getObjCIdDecl(); 7322 7323 case PREDEF_DECL_OBJC_SEL_ID: 7324 return Context.getObjCSelDecl(); 7325 7326 case PREDEF_DECL_OBJC_CLASS_ID: 7327 return Context.getObjCClassDecl(); 7328 7329 case PREDEF_DECL_OBJC_PROTOCOL_ID: 7330 return Context.getObjCProtocolDecl(); 7331 7332 case PREDEF_DECL_INT_128_ID: 7333 return Context.getInt128Decl(); 7334 7335 case PREDEF_DECL_UNSIGNED_INT_128_ID: 7336 return Context.getUInt128Decl(); 7337 7338 case PREDEF_DECL_OBJC_INSTANCETYPE_ID: 7339 return Context.getObjCInstanceTypeDecl(); 7340 7341 case PREDEF_DECL_BUILTIN_VA_LIST_ID: 7342 return Context.getBuiltinVaListDecl(); 7343 7344 case PREDEF_DECL_VA_LIST_TAG: 7345 return Context.getVaListTagDecl(); 7346 7347 case PREDEF_DECL_BUILTIN_MS_VA_LIST_ID: 7348 return Context.getBuiltinMSVaListDecl(); 7349 7350 case PREDEF_DECL_BUILTIN_MS_GUID_ID: 7351 return Context.getMSGuidTagDecl(); 7352 7353 case PREDEF_DECL_EXTERN_C_CONTEXT_ID: 7354 return Context.getExternCContextDecl(); 7355 7356 case PREDEF_DECL_MAKE_INTEGER_SEQ_ID: 7357 return Context.getMakeIntegerSeqDecl(); 7358 7359 case PREDEF_DECL_CF_CONSTANT_STRING_ID: 7360 return Context.getCFConstantStringDecl(); 7361 7362 case PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID: 7363 return Context.getCFConstantStringTagDecl(); 7364 7365 case PREDEF_DECL_TYPE_PACK_ELEMENT_ID: 7366 return Context.getTypePackElementDecl(); 7367 } 7368 llvm_unreachable("PredefinedDeclIDs unknown enum value"); 7369 } 7370 7371 Decl *ASTReader::GetExistingDecl(DeclID ID) { 7372 assert(ContextObj && "reading decl with no AST context"); 7373 if (ID < NUM_PREDEF_DECL_IDS) { 7374 Decl *D = getPredefinedDecl(*ContextObj, (PredefinedDeclIDs)ID); 7375 if (D) { 7376 // Track that we have merged the declaration with ID \p ID into the 7377 // pre-existing predefined declaration \p D. 7378 auto &Merged = KeyDecls[D->getCanonicalDecl()]; 7379 if (Merged.empty()) 7380 Merged.push_back(ID); 7381 } 7382 return D; 7383 } 7384 7385 unsigned Index = ID - NUM_PREDEF_DECL_IDS; 7386 7387 if (Index >= DeclsLoaded.size()) { 7388 assert(0 && "declaration ID out-of-range for AST file"); 7389 Error("declaration ID out-of-range for AST file"); 7390 return nullptr; 7391 } 7392 7393 return DeclsLoaded[Index]; 7394 } 7395 7396 Decl *ASTReader::GetDecl(DeclID ID) { 7397 if (ID < NUM_PREDEF_DECL_IDS) 7398 return GetExistingDecl(ID); 7399 7400 unsigned Index = ID - NUM_PREDEF_DECL_IDS; 7401 7402 if (Index >= DeclsLoaded.size()) { 7403 assert(0 && "declaration ID out-of-range for AST file"); 7404 Error("declaration ID out-of-range for AST file"); 7405 return nullptr; 7406 } 7407 7408 if (!DeclsLoaded[Index]) { 7409 ReadDeclRecord(ID); 7410 if (DeserializationListener) 7411 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]); 7412 } 7413 7414 return DeclsLoaded[Index]; 7415 } 7416 7417 DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M, 7418 DeclID GlobalID) { 7419 if (GlobalID < NUM_PREDEF_DECL_IDS) 7420 return GlobalID; 7421 7422 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID); 7423 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map"); 7424 ModuleFile *Owner = I->second; 7425 7426 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos 7427 = M.GlobalToLocalDeclIDs.find(Owner); 7428 if (Pos == M.GlobalToLocalDeclIDs.end()) 7429 return 0; 7430 7431 return GlobalID - Owner->BaseDeclID + Pos->second; 7432 } 7433 7434 serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F, 7435 const RecordData &Record, 7436 unsigned &Idx) { 7437 if (Idx >= Record.size()) { 7438 Error("Corrupted AST file"); 7439 return 0; 7440 } 7441 7442 return getGlobalDeclID(F, Record[Idx++]); 7443 } 7444 7445 /// Resolve the offset of a statement into a statement. 7446 /// 7447 /// This operation will read a new statement from the external 7448 /// source each time it is called, and is meant to be used via a 7449 /// LazyOffsetPtr (which is used by Decls for the body of functions, etc). 7450 Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) { 7451 // Switch case IDs are per Decl. 7452 ClearSwitchCaseIDs(); 7453 7454 // Offset here is a global offset across the entire chain. 7455 RecordLocation Loc = getLocalBitOffset(Offset); 7456 if (llvm::Error Err = Loc.F->DeclsCursor.JumpToBit(Loc.Offset)) { 7457 Error(std::move(Err)); 7458 return nullptr; 7459 } 7460 assert(NumCurrentElementsDeserializing == 0 && 7461 "should not be called while already deserializing"); 7462 Deserializing D(this); 7463 return ReadStmtFromStream(*Loc.F); 7464 } 7465 7466 void ASTReader::FindExternalLexicalDecls( 7467 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant, 7468 SmallVectorImpl<Decl *> &Decls) { 7469 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {}; 7470 7471 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) { 7472 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries"); 7473 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) { 7474 auto K = (Decl::Kind)+LexicalDecls[I]; 7475 if (!IsKindWeWant(K)) 7476 continue; 7477 7478 auto ID = (serialization::DeclID)+LexicalDecls[I + 1]; 7479 7480 // Don't add predefined declarations to the lexical context more 7481 // than once. 7482 if (ID < NUM_PREDEF_DECL_IDS) { 7483 if (PredefsVisited[ID]) 7484 continue; 7485 7486 PredefsVisited[ID] = true; 7487 } 7488 7489 if (Decl *D = GetLocalDecl(*M, ID)) { 7490 assert(D->getKind() == K && "wrong kind for lexical decl"); 7491 if (!DC->isDeclInLexicalTraversal(D)) 7492 Decls.push_back(D); 7493 } 7494 } 7495 }; 7496 7497 if (isa<TranslationUnitDecl>(DC)) { 7498 for (auto Lexical : TULexicalDecls) 7499 Visit(Lexical.first, Lexical.second); 7500 } else { 7501 auto I = LexicalDecls.find(DC); 7502 if (I != LexicalDecls.end()) 7503 Visit(I->second.first, I->second.second); 7504 } 7505 7506 ++NumLexicalDeclContextsRead; 7507 } 7508 7509 namespace { 7510 7511 class DeclIDComp { 7512 ASTReader &Reader; 7513 ModuleFile &Mod; 7514 7515 public: 7516 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {} 7517 7518 bool operator()(LocalDeclID L, LocalDeclID R) const { 7519 SourceLocation LHS = getLocation(L); 7520 SourceLocation RHS = getLocation(R); 7521 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS); 7522 } 7523 7524 bool operator()(SourceLocation LHS, LocalDeclID R) const { 7525 SourceLocation RHS = getLocation(R); 7526 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS); 7527 } 7528 7529 bool operator()(LocalDeclID L, SourceLocation RHS) const { 7530 SourceLocation LHS = getLocation(L); 7531 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS); 7532 } 7533 7534 SourceLocation getLocation(LocalDeclID ID) const { 7535 return Reader.getSourceManager().getFileLoc( 7536 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID))); 7537 } 7538 }; 7539 7540 } // namespace 7541 7542 void ASTReader::FindFileRegionDecls(FileID File, 7543 unsigned Offset, unsigned Length, 7544 SmallVectorImpl<Decl *> &Decls) { 7545 SourceManager &SM = getSourceManager(); 7546 7547 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File); 7548 if (I == FileDeclIDs.end()) 7549 return; 7550 7551 FileDeclsInfo &DInfo = I->second; 7552 if (DInfo.Decls.empty()) 7553 return; 7554 7555 SourceLocation 7556 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset); 7557 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length); 7558 7559 DeclIDComp DIDComp(*this, *DInfo.Mod); 7560 ArrayRef<serialization::LocalDeclID>::iterator BeginIt = 7561 llvm::lower_bound(DInfo.Decls, BeginLoc, DIDComp); 7562 if (BeginIt != DInfo.Decls.begin()) 7563 --BeginIt; 7564 7565 // If we are pointing at a top-level decl inside an objc container, we need 7566 // to backtrack until we find it otherwise we will fail to report that the 7567 // region overlaps with an objc container. 7568 while (BeginIt != DInfo.Decls.begin() && 7569 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt)) 7570 ->isTopLevelDeclInObjCContainer()) 7571 --BeginIt; 7572 7573 ArrayRef<serialization::LocalDeclID>::iterator EndIt = 7574 llvm::upper_bound(DInfo.Decls, EndLoc, DIDComp); 7575 if (EndIt != DInfo.Decls.end()) 7576 ++EndIt; 7577 7578 for (ArrayRef<serialization::LocalDeclID>::iterator 7579 DIt = BeginIt; DIt != EndIt; ++DIt) 7580 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt))); 7581 } 7582 7583 bool 7584 ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC, 7585 DeclarationName Name) { 7586 assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() && 7587 "DeclContext has no visible decls in storage"); 7588 if (!Name) 7589 return false; 7590 7591 auto It = Lookups.find(DC); 7592 if (It == Lookups.end()) 7593 return false; 7594 7595 Deserializing LookupResults(this); 7596 7597 // Load the list of declarations. 7598 SmallVector<NamedDecl *, 64> Decls; 7599 for (DeclID ID : It->second.Table.find(Name)) { 7600 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID)); 7601 if (ND->getDeclName() == Name) 7602 Decls.push_back(ND); 7603 } 7604 7605 ++NumVisibleDeclContextsRead; 7606 SetExternalVisibleDeclsForName(DC, Name, Decls); 7607 return !Decls.empty(); 7608 } 7609 7610 void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) { 7611 if (!DC->hasExternalVisibleStorage()) 7612 return; 7613 7614 auto It = Lookups.find(DC); 7615 assert(It != Lookups.end() && 7616 "have external visible storage but no lookup tables"); 7617 7618 DeclsMap Decls; 7619 7620 for (DeclID ID : It->second.Table.findAll()) { 7621 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID)); 7622 Decls[ND->getDeclName()].push_back(ND); 7623 } 7624 7625 ++NumVisibleDeclContextsRead; 7626 7627 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) { 7628 SetExternalVisibleDeclsForName(DC, I->first, I->second); 7629 } 7630 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false); 7631 } 7632 7633 const serialization::reader::DeclContextLookupTable * 7634 ASTReader::getLoadedLookupTables(DeclContext *Primary) const { 7635 auto I = Lookups.find(Primary); 7636 return I == Lookups.end() ? nullptr : &I->second; 7637 } 7638 7639 /// Under non-PCH compilation the consumer receives the objc methods 7640 /// before receiving the implementation, and codegen depends on this. 7641 /// We simulate this by deserializing and passing to consumer the methods of the 7642 /// implementation before passing the deserialized implementation decl. 7643 static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD, 7644 ASTConsumer *Consumer) { 7645 assert(ImplD && Consumer); 7646 7647 for (auto *I : ImplD->methods()) 7648 Consumer->HandleInterestingDecl(DeclGroupRef(I)); 7649 7650 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD)); 7651 } 7652 7653 void ASTReader::PassInterestingDeclToConsumer(Decl *D) { 7654 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D)) 7655 PassObjCImplDeclToConsumer(ImplD, Consumer); 7656 else 7657 Consumer->HandleInterestingDecl(DeclGroupRef(D)); 7658 } 7659 7660 void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) { 7661 this->Consumer = Consumer; 7662 7663 if (Consumer) 7664 PassInterestingDeclsToConsumer(); 7665 7666 if (DeserializationListener) 7667 DeserializationListener->ReaderInitialized(this); 7668 } 7669 7670 void ASTReader::PrintStats() { 7671 std::fprintf(stderr, "*** AST File Statistics:\n"); 7672 7673 unsigned NumTypesLoaded 7674 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(), 7675 QualType()); 7676 unsigned NumDeclsLoaded 7677 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(), 7678 (Decl *)nullptr); 7679 unsigned NumIdentifiersLoaded 7680 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(), 7681 IdentifiersLoaded.end(), 7682 (IdentifierInfo *)nullptr); 7683 unsigned NumMacrosLoaded 7684 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(), 7685 MacrosLoaded.end(), 7686 (MacroInfo *)nullptr); 7687 unsigned NumSelectorsLoaded 7688 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(), 7689 SelectorsLoaded.end(), 7690 Selector()); 7691 7692 if (unsigned TotalNumSLocEntries = getTotalNumSLocs()) 7693 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n", 7694 NumSLocEntriesRead, TotalNumSLocEntries, 7695 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100)); 7696 if (!TypesLoaded.empty()) 7697 std::fprintf(stderr, " %u/%u types read (%f%%)\n", 7698 NumTypesLoaded, (unsigned)TypesLoaded.size(), 7699 ((float)NumTypesLoaded/TypesLoaded.size() * 100)); 7700 if (!DeclsLoaded.empty()) 7701 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n", 7702 NumDeclsLoaded, (unsigned)DeclsLoaded.size(), 7703 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100)); 7704 if (!IdentifiersLoaded.empty()) 7705 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n", 7706 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(), 7707 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100)); 7708 if (!MacrosLoaded.empty()) 7709 std::fprintf(stderr, " %u/%u macros read (%f%%)\n", 7710 NumMacrosLoaded, (unsigned)MacrosLoaded.size(), 7711 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100)); 7712 if (!SelectorsLoaded.empty()) 7713 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n", 7714 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(), 7715 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100)); 7716 if (TotalNumStatements) 7717 std::fprintf(stderr, " %u/%u statements read (%f%%)\n", 7718 NumStatementsRead, TotalNumStatements, 7719 ((float)NumStatementsRead/TotalNumStatements * 100)); 7720 if (TotalNumMacros) 7721 std::fprintf(stderr, " %u/%u macros read (%f%%)\n", 7722 NumMacrosRead, TotalNumMacros, 7723 ((float)NumMacrosRead/TotalNumMacros * 100)); 7724 if (TotalLexicalDeclContexts) 7725 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n", 7726 NumLexicalDeclContextsRead, TotalLexicalDeclContexts, 7727 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts 7728 * 100)); 7729 if (TotalVisibleDeclContexts) 7730 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n", 7731 NumVisibleDeclContextsRead, TotalVisibleDeclContexts, 7732 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts 7733 * 100)); 7734 if (TotalNumMethodPoolEntries) 7735 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n", 7736 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries, 7737 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries 7738 * 100)); 7739 if (NumMethodPoolLookups) 7740 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n", 7741 NumMethodPoolHits, NumMethodPoolLookups, 7742 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0)); 7743 if (NumMethodPoolTableLookups) 7744 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n", 7745 NumMethodPoolTableHits, NumMethodPoolTableLookups, 7746 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups 7747 * 100.0)); 7748 if (NumIdentifierLookupHits) 7749 std::fprintf(stderr, 7750 " %u / %u identifier table lookups succeeded (%f%%)\n", 7751 NumIdentifierLookupHits, NumIdentifierLookups, 7752 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups); 7753 7754 if (GlobalIndex) { 7755 std::fprintf(stderr, "\n"); 7756 GlobalIndex->printStats(); 7757 } 7758 7759 std::fprintf(stderr, "\n"); 7760 dump(); 7761 std::fprintf(stderr, "\n"); 7762 } 7763 7764 template<typename Key, typename ModuleFile, unsigned InitialCapacity> 7765 LLVM_DUMP_METHOD static void 7766 dumpModuleIDMap(StringRef Name, 7767 const ContinuousRangeMap<Key, ModuleFile *, 7768 InitialCapacity> &Map) { 7769 if (Map.begin() == Map.end()) 7770 return; 7771 7772 using MapType = ContinuousRangeMap<Key, ModuleFile *, InitialCapacity>; 7773 7774 llvm::errs() << Name << ":\n"; 7775 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end(); 7776 I != IEnd; ++I) { 7777 llvm::errs() << " " << I->first << " -> " << I->second->FileName 7778 << "\n"; 7779 } 7780 } 7781 7782 LLVM_DUMP_METHOD void ASTReader::dump() { 7783 llvm::errs() << "*** PCH/ModuleFile Remappings:\n"; 7784 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap); 7785 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap); 7786 dumpModuleIDMap("Global type map", GlobalTypeMap); 7787 dumpModuleIDMap("Global declaration map", GlobalDeclMap); 7788 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap); 7789 dumpModuleIDMap("Global macro map", GlobalMacroMap); 7790 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap); 7791 dumpModuleIDMap("Global selector map", GlobalSelectorMap); 7792 dumpModuleIDMap("Global preprocessed entity map", 7793 GlobalPreprocessedEntityMap); 7794 7795 llvm::errs() << "\n*** PCH/Modules Loaded:"; 7796 for (ModuleFile &M : ModuleMgr) 7797 M.dump(); 7798 } 7799 7800 /// Return the amount of memory used by memory buffers, breaking down 7801 /// by heap-backed versus mmap'ed memory. 7802 void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const { 7803 for (ModuleFile &I : ModuleMgr) { 7804 if (llvm::MemoryBuffer *buf = I.Buffer) { 7805 size_t bytes = buf->getBufferSize(); 7806 switch (buf->getBufferKind()) { 7807 case llvm::MemoryBuffer::MemoryBuffer_Malloc: 7808 sizes.malloc_bytes += bytes; 7809 break; 7810 case llvm::MemoryBuffer::MemoryBuffer_MMap: 7811 sizes.mmap_bytes += bytes; 7812 break; 7813 } 7814 } 7815 } 7816 } 7817 7818 void ASTReader::InitializeSema(Sema &S) { 7819 SemaObj = &S; 7820 S.addExternalSource(this); 7821 7822 // Makes sure any declarations that were deserialized "too early" 7823 // still get added to the identifier's declaration chains. 7824 for (uint64_t ID : PreloadedDeclIDs) { 7825 NamedDecl *D = cast<NamedDecl>(GetDecl(ID)); 7826 pushExternalDeclIntoScope(D, D->getDeclName()); 7827 } 7828 PreloadedDeclIDs.clear(); 7829 7830 // FIXME: What happens if these are changed by a module import? 7831 if (!FPPragmaOptions.empty()) { 7832 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS"); 7833 FPOptionsOverride NewOverrides = 7834 FPOptionsOverride::getFromOpaqueInt(FPPragmaOptions[0]); 7835 SemaObj->CurFPFeatures = 7836 NewOverrides.applyOverrides(SemaObj->getLangOpts()); 7837 } 7838 7839 SemaObj->OpenCLFeatures.copy(OpenCLExtensions); 7840 SemaObj->OpenCLTypeExtMap = OpenCLTypeExtMap; 7841 SemaObj->OpenCLDeclExtMap = OpenCLDeclExtMap; 7842 7843 UpdateSema(); 7844 } 7845 7846 void ASTReader::UpdateSema() { 7847 assert(SemaObj && "no Sema to update"); 7848 7849 // Load the offsets of the declarations that Sema references. 7850 // They will be lazily deserialized when needed. 7851 if (!SemaDeclRefs.empty()) { 7852 assert(SemaDeclRefs.size() % 3 == 0); 7853 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 3) { 7854 if (!SemaObj->StdNamespace) 7855 SemaObj->StdNamespace = SemaDeclRefs[I]; 7856 if (!SemaObj->StdBadAlloc) 7857 SemaObj->StdBadAlloc = SemaDeclRefs[I+1]; 7858 if (!SemaObj->StdAlignValT) 7859 SemaObj->StdAlignValT = SemaDeclRefs[I+2]; 7860 } 7861 SemaDeclRefs.clear(); 7862 } 7863 7864 // Update the state of pragmas. Use the same API as if we had encountered the 7865 // pragma in the source. 7866 if(OptimizeOffPragmaLocation.isValid()) 7867 SemaObj->ActOnPragmaOptimize(/* On = */ false, OptimizeOffPragmaLocation); 7868 if (PragmaMSStructState != -1) 7869 SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState); 7870 if (PointersToMembersPragmaLocation.isValid()) { 7871 SemaObj->ActOnPragmaMSPointersToMembers( 7872 (LangOptions::PragmaMSPointersToMembersKind) 7873 PragmaMSPointersToMembersState, 7874 PointersToMembersPragmaLocation); 7875 } 7876 SemaObj->ForceCUDAHostDeviceDepth = ForceCUDAHostDeviceDepth; 7877 7878 if (PragmaPackCurrentValue) { 7879 // The bottom of the stack might have a default value. It must be adjusted 7880 // to the current value to ensure that the packing state is preserved after 7881 // popping entries that were included/imported from a PCH/module. 7882 bool DropFirst = false; 7883 if (!PragmaPackStack.empty() && 7884 PragmaPackStack.front().Location.isInvalid()) { 7885 assert(PragmaPackStack.front().Value == SemaObj->PackStack.DefaultValue && 7886 "Expected a default alignment value"); 7887 SemaObj->PackStack.Stack.emplace_back( 7888 PragmaPackStack.front().SlotLabel, SemaObj->PackStack.CurrentValue, 7889 SemaObj->PackStack.CurrentPragmaLocation, 7890 PragmaPackStack.front().PushLocation); 7891 DropFirst = true; 7892 } 7893 for (const auto &Entry : 7894 llvm::makeArrayRef(PragmaPackStack).drop_front(DropFirst ? 1 : 0)) 7895 SemaObj->PackStack.Stack.emplace_back(Entry.SlotLabel, Entry.Value, 7896 Entry.Location, Entry.PushLocation); 7897 if (PragmaPackCurrentLocation.isInvalid()) { 7898 assert(*PragmaPackCurrentValue == SemaObj->PackStack.DefaultValue && 7899 "Expected a default alignment value"); 7900 // Keep the current values. 7901 } else { 7902 SemaObj->PackStack.CurrentValue = *PragmaPackCurrentValue; 7903 SemaObj->PackStack.CurrentPragmaLocation = PragmaPackCurrentLocation; 7904 } 7905 } 7906 if (FpPragmaCurrentValue) { 7907 // The bottom of the stack might have a default value. It must be adjusted 7908 // to the current value to ensure that fp-pragma state is preserved after 7909 // popping entries that were included/imported from a PCH/module. 7910 bool DropFirst = false; 7911 if (!FpPragmaStack.empty() && FpPragmaStack.front().Location.isInvalid()) { 7912 assert(FpPragmaStack.front().Value == 7913 SemaObj->FpPragmaStack.DefaultValue && 7914 "Expected a default pragma float_control value"); 7915 SemaObj->FpPragmaStack.Stack.emplace_back( 7916 FpPragmaStack.front().SlotLabel, SemaObj->FpPragmaStack.CurrentValue, 7917 SemaObj->FpPragmaStack.CurrentPragmaLocation, 7918 FpPragmaStack.front().PushLocation); 7919 DropFirst = true; 7920 } 7921 for (const auto &Entry : 7922 llvm::makeArrayRef(FpPragmaStack).drop_front(DropFirst ? 1 : 0)) 7923 SemaObj->FpPragmaStack.Stack.emplace_back( 7924 Entry.SlotLabel, Entry.Value, Entry.Location, Entry.PushLocation); 7925 if (FpPragmaCurrentLocation.isInvalid()) { 7926 assert(*FpPragmaCurrentValue == SemaObj->FpPragmaStack.DefaultValue && 7927 "Expected a default pragma float_control value"); 7928 // Keep the current values. 7929 } else { 7930 SemaObj->FpPragmaStack.CurrentValue = *FpPragmaCurrentValue; 7931 SemaObj->FpPragmaStack.CurrentPragmaLocation = FpPragmaCurrentLocation; 7932 } 7933 } 7934 7935 // For non-modular AST files, restore visiblity of modules. 7936 for (auto &Import : ImportedModules) { 7937 if (Import.ImportLoc.isInvalid()) 7938 continue; 7939 if (Module *Imported = getSubmodule(Import.ID)) { 7940 SemaObj->makeModuleVisible(Imported, Import.ImportLoc); 7941 } 7942 } 7943 } 7944 7945 IdentifierInfo *ASTReader::get(StringRef Name) { 7946 // Note that we are loading an identifier. 7947 Deserializing AnIdentifier(this); 7948 7949 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0, 7950 NumIdentifierLookups, 7951 NumIdentifierLookupHits); 7952 7953 // We don't need to do identifier table lookups in C++ modules (we preload 7954 // all interesting declarations, and don't need to use the scope for name 7955 // lookups). Perform the lookup in PCH files, though, since we don't build 7956 // a complete initial identifier table if we're carrying on from a PCH. 7957 if (PP.getLangOpts().CPlusPlus) { 7958 for (auto F : ModuleMgr.pch_modules()) 7959 if (Visitor(*F)) 7960 break; 7961 } else { 7962 // If there is a global index, look there first to determine which modules 7963 // provably do not have any results for this identifier. 7964 GlobalModuleIndex::HitSet Hits; 7965 GlobalModuleIndex::HitSet *HitsPtr = nullptr; 7966 if (!loadGlobalIndex()) { 7967 if (GlobalIndex->lookupIdentifier(Name, Hits)) { 7968 HitsPtr = &Hits; 7969 } 7970 } 7971 7972 ModuleMgr.visit(Visitor, HitsPtr); 7973 } 7974 7975 IdentifierInfo *II = Visitor.getIdentifierInfo(); 7976 markIdentifierUpToDate(II); 7977 return II; 7978 } 7979 7980 namespace clang { 7981 7982 /// An identifier-lookup iterator that enumerates all of the 7983 /// identifiers stored within a set of AST files. 7984 class ASTIdentifierIterator : public IdentifierIterator { 7985 /// The AST reader whose identifiers are being enumerated. 7986 const ASTReader &Reader; 7987 7988 /// The current index into the chain of AST files stored in 7989 /// the AST reader. 7990 unsigned Index; 7991 7992 /// The current position within the identifier lookup table 7993 /// of the current AST file. 7994 ASTIdentifierLookupTable::key_iterator Current; 7995 7996 /// The end position within the identifier lookup table of 7997 /// the current AST file. 7998 ASTIdentifierLookupTable::key_iterator End; 7999 8000 /// Whether to skip any modules in the ASTReader. 8001 bool SkipModules; 8002 8003 public: 8004 explicit ASTIdentifierIterator(const ASTReader &Reader, 8005 bool SkipModules = false); 8006 8007 StringRef Next() override; 8008 }; 8009 8010 } // namespace clang 8011 8012 ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader, 8013 bool SkipModules) 8014 : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) { 8015 } 8016 8017 StringRef ASTIdentifierIterator::Next() { 8018 while (Current == End) { 8019 // If we have exhausted all of our AST files, we're done. 8020 if (Index == 0) 8021 return StringRef(); 8022 8023 --Index; 8024 ModuleFile &F = Reader.ModuleMgr[Index]; 8025 if (SkipModules && F.isModule()) 8026 continue; 8027 8028 ASTIdentifierLookupTable *IdTable = 8029 (ASTIdentifierLookupTable *)F.IdentifierLookupTable; 8030 Current = IdTable->key_begin(); 8031 End = IdTable->key_end(); 8032 } 8033 8034 // We have any identifiers remaining in the current AST file; return 8035 // the next one. 8036 StringRef Result = *Current; 8037 ++Current; 8038 return Result; 8039 } 8040 8041 namespace { 8042 8043 /// A utility for appending two IdentifierIterators. 8044 class ChainedIdentifierIterator : public IdentifierIterator { 8045 std::unique_ptr<IdentifierIterator> Current; 8046 std::unique_ptr<IdentifierIterator> Queued; 8047 8048 public: 8049 ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First, 8050 std::unique_ptr<IdentifierIterator> Second) 8051 : Current(std::move(First)), Queued(std::move(Second)) {} 8052 8053 StringRef Next() override { 8054 if (!Current) 8055 return StringRef(); 8056 8057 StringRef result = Current->Next(); 8058 if (!result.empty()) 8059 return result; 8060 8061 // Try the queued iterator, which may itself be empty. 8062 Current.reset(); 8063 std::swap(Current, Queued); 8064 return Next(); 8065 } 8066 }; 8067 8068 } // namespace 8069 8070 IdentifierIterator *ASTReader::getIdentifiers() { 8071 if (!loadGlobalIndex()) { 8072 std::unique_ptr<IdentifierIterator> ReaderIter( 8073 new ASTIdentifierIterator(*this, /*SkipModules=*/true)); 8074 std::unique_ptr<IdentifierIterator> ModulesIter( 8075 GlobalIndex->createIdentifierIterator()); 8076 return new ChainedIdentifierIterator(std::move(ReaderIter), 8077 std::move(ModulesIter)); 8078 } 8079 8080 return new ASTIdentifierIterator(*this); 8081 } 8082 8083 namespace clang { 8084 namespace serialization { 8085 8086 class ReadMethodPoolVisitor { 8087 ASTReader &Reader; 8088 Selector Sel; 8089 unsigned PriorGeneration; 8090 unsigned InstanceBits = 0; 8091 unsigned FactoryBits = 0; 8092 bool InstanceHasMoreThanOneDecl = false; 8093 bool FactoryHasMoreThanOneDecl = false; 8094 SmallVector<ObjCMethodDecl *, 4> InstanceMethods; 8095 SmallVector<ObjCMethodDecl *, 4> FactoryMethods; 8096 8097 public: 8098 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel, 8099 unsigned PriorGeneration) 8100 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration) {} 8101 8102 bool operator()(ModuleFile &M) { 8103 if (!M.SelectorLookupTable) 8104 return false; 8105 8106 // If we've already searched this module file, skip it now. 8107 if (M.Generation <= PriorGeneration) 8108 return true; 8109 8110 ++Reader.NumMethodPoolTableLookups; 8111 ASTSelectorLookupTable *PoolTable 8112 = (ASTSelectorLookupTable*)M.SelectorLookupTable; 8113 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel); 8114 if (Pos == PoolTable->end()) 8115 return false; 8116 8117 ++Reader.NumMethodPoolTableHits; 8118 ++Reader.NumSelectorsRead; 8119 // FIXME: Not quite happy with the statistics here. We probably should 8120 // disable this tracking when called via LoadSelector. 8121 // Also, should entries without methods count as misses? 8122 ++Reader.NumMethodPoolEntriesRead; 8123 ASTSelectorLookupTrait::data_type Data = *Pos; 8124 if (Reader.DeserializationListener) 8125 Reader.DeserializationListener->SelectorRead(Data.ID, Sel); 8126 8127 InstanceMethods.append(Data.Instance.begin(), Data.Instance.end()); 8128 FactoryMethods.append(Data.Factory.begin(), Data.Factory.end()); 8129 InstanceBits = Data.InstanceBits; 8130 FactoryBits = Data.FactoryBits; 8131 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl; 8132 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl; 8133 return true; 8134 } 8135 8136 /// Retrieve the instance methods found by this visitor. 8137 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const { 8138 return InstanceMethods; 8139 } 8140 8141 /// Retrieve the instance methods found by this visitor. 8142 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const { 8143 return FactoryMethods; 8144 } 8145 8146 unsigned getInstanceBits() const { return InstanceBits; } 8147 unsigned getFactoryBits() const { return FactoryBits; } 8148 8149 bool instanceHasMoreThanOneDecl() const { 8150 return InstanceHasMoreThanOneDecl; 8151 } 8152 8153 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; } 8154 }; 8155 8156 } // namespace serialization 8157 } // namespace clang 8158 8159 /// Add the given set of methods to the method list. 8160 static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods, 8161 ObjCMethodList &List) { 8162 for (unsigned I = 0, N = Methods.size(); I != N; ++I) { 8163 S.addMethodToGlobalList(&List, Methods[I]); 8164 } 8165 } 8166 8167 void ASTReader::ReadMethodPool(Selector Sel) { 8168 // Get the selector generation and update it to the current generation. 8169 unsigned &Generation = SelectorGeneration[Sel]; 8170 unsigned PriorGeneration = Generation; 8171 Generation = getGeneration(); 8172 SelectorOutOfDate[Sel] = false; 8173 8174 // Search for methods defined with this selector. 8175 ++NumMethodPoolLookups; 8176 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration); 8177 ModuleMgr.visit(Visitor); 8178 8179 if (Visitor.getInstanceMethods().empty() && 8180 Visitor.getFactoryMethods().empty()) 8181 return; 8182 8183 ++NumMethodPoolHits; 8184 8185 if (!getSema()) 8186 return; 8187 8188 Sema &S = *getSema(); 8189 Sema::GlobalMethodPool::iterator Pos 8190 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first; 8191 8192 Pos->second.first.setBits(Visitor.getInstanceBits()); 8193 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl()); 8194 Pos->second.second.setBits(Visitor.getFactoryBits()); 8195 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl()); 8196 8197 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since 8198 // when building a module we keep every method individually and may need to 8199 // update hasMoreThanOneDecl as we add the methods. 8200 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first); 8201 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second); 8202 } 8203 8204 void ASTReader::updateOutOfDateSelector(Selector Sel) { 8205 if (SelectorOutOfDate[Sel]) 8206 ReadMethodPool(Sel); 8207 } 8208 8209 void ASTReader::ReadKnownNamespaces( 8210 SmallVectorImpl<NamespaceDecl *> &Namespaces) { 8211 Namespaces.clear(); 8212 8213 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) { 8214 if (NamespaceDecl *Namespace 8215 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I]))) 8216 Namespaces.push_back(Namespace); 8217 } 8218 } 8219 8220 void ASTReader::ReadUndefinedButUsed( 8221 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) { 8222 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) { 8223 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++])); 8224 SourceLocation Loc = 8225 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]); 8226 Undefined.insert(std::make_pair(D, Loc)); 8227 } 8228 } 8229 8230 void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector< 8231 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> & 8232 Exprs) { 8233 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) { 8234 FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++])); 8235 uint64_t Count = DelayedDeleteExprs[Idx++]; 8236 for (uint64_t C = 0; C < Count; ++C) { 8237 SourceLocation DeleteLoc = 8238 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]); 8239 const bool IsArrayForm = DelayedDeleteExprs[Idx++]; 8240 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm)); 8241 } 8242 } 8243 } 8244 8245 void ASTReader::ReadTentativeDefinitions( 8246 SmallVectorImpl<VarDecl *> &TentativeDefs) { 8247 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) { 8248 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I])); 8249 if (Var) 8250 TentativeDefs.push_back(Var); 8251 } 8252 TentativeDefinitions.clear(); 8253 } 8254 8255 void ASTReader::ReadUnusedFileScopedDecls( 8256 SmallVectorImpl<const DeclaratorDecl *> &Decls) { 8257 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) { 8258 DeclaratorDecl *D 8259 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I])); 8260 if (D) 8261 Decls.push_back(D); 8262 } 8263 UnusedFileScopedDecls.clear(); 8264 } 8265 8266 void ASTReader::ReadDelegatingConstructors( 8267 SmallVectorImpl<CXXConstructorDecl *> &Decls) { 8268 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) { 8269 CXXConstructorDecl *D 8270 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I])); 8271 if (D) 8272 Decls.push_back(D); 8273 } 8274 DelegatingCtorDecls.clear(); 8275 } 8276 8277 void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) { 8278 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) { 8279 TypedefNameDecl *D 8280 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I])); 8281 if (D) 8282 Decls.push_back(D); 8283 } 8284 ExtVectorDecls.clear(); 8285 } 8286 8287 void ASTReader::ReadUnusedLocalTypedefNameCandidates( 8288 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) { 8289 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N; 8290 ++I) { 8291 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>( 8292 GetDecl(UnusedLocalTypedefNameCandidates[I])); 8293 if (D) 8294 Decls.insert(D); 8295 } 8296 UnusedLocalTypedefNameCandidates.clear(); 8297 } 8298 8299 void ASTReader::ReadDeclsToCheckForDeferredDiags( 8300 llvm::SmallVector<Decl *, 4> &Decls) { 8301 for (unsigned I = 0, N = DeclsToCheckForDeferredDiags.size(); I != N; 8302 ++I) { 8303 auto *D = dyn_cast_or_null<Decl>( 8304 GetDecl(DeclsToCheckForDeferredDiags[I])); 8305 if (D) 8306 Decls.push_back(D); 8307 } 8308 DeclsToCheckForDeferredDiags.clear(); 8309 } 8310 8311 8312 void ASTReader::ReadReferencedSelectors( 8313 SmallVectorImpl<std::pair<Selector, SourceLocation>> &Sels) { 8314 if (ReferencedSelectorsData.empty()) 8315 return; 8316 8317 // If there are @selector references added them to its pool. This is for 8318 // implementation of -Wselector. 8319 unsigned int DataSize = ReferencedSelectorsData.size()-1; 8320 unsigned I = 0; 8321 while (I < DataSize) { 8322 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]); 8323 SourceLocation SelLoc 8324 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]); 8325 Sels.push_back(std::make_pair(Sel, SelLoc)); 8326 } 8327 ReferencedSelectorsData.clear(); 8328 } 8329 8330 void ASTReader::ReadWeakUndeclaredIdentifiers( 8331 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo>> &WeakIDs) { 8332 if (WeakUndeclaredIdentifiers.empty()) 8333 return; 8334 8335 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) { 8336 IdentifierInfo *WeakId 8337 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]); 8338 IdentifierInfo *AliasId 8339 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]); 8340 SourceLocation Loc 8341 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]); 8342 bool Used = WeakUndeclaredIdentifiers[I++]; 8343 WeakInfo WI(AliasId, Loc); 8344 WI.setUsed(Used); 8345 WeakIDs.push_back(std::make_pair(WeakId, WI)); 8346 } 8347 WeakUndeclaredIdentifiers.clear(); 8348 } 8349 8350 void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) { 8351 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) { 8352 ExternalVTableUse VT; 8353 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++])); 8354 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]); 8355 VT.DefinitionRequired = VTableUses[Idx++]; 8356 VTables.push_back(VT); 8357 } 8358 8359 VTableUses.clear(); 8360 } 8361 8362 void ASTReader::ReadPendingInstantiations( 8363 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation>> &Pending) { 8364 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) { 8365 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++])); 8366 SourceLocation Loc 8367 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]); 8368 8369 Pending.push_back(std::make_pair(D, Loc)); 8370 } 8371 PendingInstantiations.clear(); 8372 } 8373 8374 void ASTReader::ReadLateParsedTemplates( 8375 llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>> 8376 &LPTMap) { 8377 for (auto &LPT : LateParsedTemplates) { 8378 ModuleFile *FMod = LPT.first; 8379 RecordDataImpl &LateParsed = LPT.second; 8380 for (unsigned Idx = 0, N = LateParsed.size(); Idx < N; 8381 /* In loop */) { 8382 FunctionDecl *FD = 8383 cast<FunctionDecl>(GetLocalDecl(*FMod, LateParsed[Idx++])); 8384 8385 auto LT = std::make_unique<LateParsedTemplate>(); 8386 LT->D = GetLocalDecl(*FMod, LateParsed[Idx++]); 8387 8388 ModuleFile *F = getOwningModuleFile(LT->D); 8389 assert(F && "No module"); 8390 8391 unsigned TokN = LateParsed[Idx++]; 8392 LT->Toks.reserve(TokN); 8393 for (unsigned T = 0; T < TokN; ++T) 8394 LT->Toks.push_back(ReadToken(*F, LateParsed, Idx)); 8395 8396 LPTMap.insert(std::make_pair(FD, std::move(LT))); 8397 } 8398 } 8399 } 8400 8401 void ASTReader::LoadSelector(Selector Sel) { 8402 // It would be complicated to avoid reading the methods anyway. So don't. 8403 ReadMethodPool(Sel); 8404 } 8405 8406 void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) { 8407 assert(ID && "Non-zero identifier ID required"); 8408 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range"); 8409 IdentifiersLoaded[ID - 1] = II; 8410 if (DeserializationListener) 8411 DeserializationListener->IdentifierRead(ID, II); 8412 } 8413 8414 /// Set the globally-visible declarations associated with the given 8415 /// identifier. 8416 /// 8417 /// If the AST reader is currently in a state where the given declaration IDs 8418 /// cannot safely be resolved, they are queued until it is safe to resolve 8419 /// them. 8420 /// 8421 /// \param II an IdentifierInfo that refers to one or more globally-visible 8422 /// declarations. 8423 /// 8424 /// \param DeclIDs the set of declaration IDs with the name @p II that are 8425 /// visible at global scope. 8426 /// 8427 /// \param Decls if non-null, this vector will be populated with the set of 8428 /// deserialized declarations. These declarations will not be pushed into 8429 /// scope. 8430 void 8431 ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II, 8432 const SmallVectorImpl<uint32_t> &DeclIDs, 8433 SmallVectorImpl<Decl *> *Decls) { 8434 if (NumCurrentElementsDeserializing && !Decls) { 8435 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end()); 8436 return; 8437 } 8438 8439 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) { 8440 if (!SemaObj) { 8441 // Queue this declaration so that it will be added to the 8442 // translation unit scope and identifier's declaration chain 8443 // once a Sema object is known. 8444 PreloadedDeclIDs.push_back(DeclIDs[I]); 8445 continue; 8446 } 8447 8448 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I])); 8449 8450 // If we're simply supposed to record the declarations, do so now. 8451 if (Decls) { 8452 Decls->push_back(D); 8453 continue; 8454 } 8455 8456 // Introduce this declaration into the translation-unit scope 8457 // and add it to the declaration chain for this identifier, so 8458 // that (unqualified) name lookup will find it. 8459 pushExternalDeclIntoScope(D, II); 8460 } 8461 } 8462 8463 IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) { 8464 if (ID == 0) 8465 return nullptr; 8466 8467 if (IdentifiersLoaded.empty()) { 8468 Error("no identifier table in AST file"); 8469 return nullptr; 8470 } 8471 8472 ID -= 1; 8473 if (!IdentifiersLoaded[ID]) { 8474 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1); 8475 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map"); 8476 ModuleFile *M = I->second; 8477 unsigned Index = ID - M->BaseIdentifierID; 8478 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index]; 8479 8480 // All of the strings in the AST file are preceded by a 16-bit length. 8481 // Extract that 16-bit length to avoid having to execute strlen(). 8482 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as 8483 // unsigned integers. This is important to avoid integer overflow when 8484 // we cast them to 'unsigned'. 8485 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2; 8486 unsigned StrLen = (((unsigned) StrLenPtr[0]) 8487 | (((unsigned) StrLenPtr[1]) << 8)) - 1; 8488 auto &II = PP.getIdentifierTable().get(StringRef(Str, StrLen)); 8489 IdentifiersLoaded[ID] = &II; 8490 markIdentifierFromAST(*this, II); 8491 if (DeserializationListener) 8492 DeserializationListener->IdentifierRead(ID + 1, &II); 8493 } 8494 8495 return IdentifiersLoaded[ID]; 8496 } 8497 8498 IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) { 8499 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID)); 8500 } 8501 8502 IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) { 8503 if (LocalID < NUM_PREDEF_IDENT_IDS) 8504 return LocalID; 8505 8506 if (!M.ModuleOffsetMap.empty()) 8507 ReadModuleOffsetMap(M); 8508 8509 ContinuousRangeMap<uint32_t, int, 2>::iterator I 8510 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS); 8511 assert(I != M.IdentifierRemap.end() 8512 && "Invalid index into identifier index remap"); 8513 8514 return LocalID + I->second; 8515 } 8516 8517 MacroInfo *ASTReader::getMacro(MacroID ID) { 8518 if (ID == 0) 8519 return nullptr; 8520 8521 if (MacrosLoaded.empty()) { 8522 Error("no macro table in AST file"); 8523 return nullptr; 8524 } 8525 8526 ID -= NUM_PREDEF_MACRO_IDS; 8527 if (!MacrosLoaded[ID]) { 8528 GlobalMacroMapType::iterator I 8529 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS); 8530 assert(I != GlobalMacroMap.end() && "Corrupted global macro map"); 8531 ModuleFile *M = I->second; 8532 unsigned Index = ID - M->BaseMacroID; 8533 MacrosLoaded[ID] = 8534 ReadMacroRecord(*M, M->MacroOffsetsBase + M->MacroOffsets[Index]); 8535 8536 if (DeserializationListener) 8537 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS, 8538 MacrosLoaded[ID]); 8539 } 8540 8541 return MacrosLoaded[ID]; 8542 } 8543 8544 MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) { 8545 if (LocalID < NUM_PREDEF_MACRO_IDS) 8546 return LocalID; 8547 8548 if (!M.ModuleOffsetMap.empty()) 8549 ReadModuleOffsetMap(M); 8550 8551 ContinuousRangeMap<uint32_t, int, 2>::iterator I 8552 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS); 8553 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap"); 8554 8555 return LocalID + I->second; 8556 } 8557 8558 serialization::SubmoduleID 8559 ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) { 8560 if (LocalID < NUM_PREDEF_SUBMODULE_IDS) 8561 return LocalID; 8562 8563 if (!M.ModuleOffsetMap.empty()) 8564 ReadModuleOffsetMap(M); 8565 8566 ContinuousRangeMap<uint32_t, int, 2>::iterator I 8567 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS); 8568 assert(I != M.SubmoduleRemap.end() 8569 && "Invalid index into submodule index remap"); 8570 8571 return LocalID + I->second; 8572 } 8573 8574 Module *ASTReader::getSubmodule(SubmoduleID GlobalID) { 8575 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) { 8576 assert(GlobalID == 0 && "Unhandled global submodule ID"); 8577 return nullptr; 8578 } 8579 8580 if (GlobalID > SubmodulesLoaded.size()) { 8581 Error("submodule ID out of range in AST file"); 8582 return nullptr; 8583 } 8584 8585 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS]; 8586 } 8587 8588 Module *ASTReader::getModule(unsigned ID) { 8589 return getSubmodule(ID); 8590 } 8591 8592 ModuleFile *ASTReader::getLocalModuleFile(ModuleFile &F, unsigned ID) { 8593 if (ID & 1) { 8594 // It's a module, look it up by submodule ID. 8595 auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(F, ID >> 1)); 8596 return I == GlobalSubmoduleMap.end() ? nullptr : I->second; 8597 } else { 8598 // It's a prefix (preamble, PCH, ...). Look it up by index. 8599 unsigned IndexFromEnd = ID >> 1; 8600 assert(IndexFromEnd && "got reference to unknown module file"); 8601 return getModuleManager().pch_modules().end()[-IndexFromEnd]; 8602 } 8603 } 8604 8605 unsigned ASTReader::getModuleFileID(ModuleFile *F) { 8606 if (!F) 8607 return 1; 8608 8609 // For a file representing a module, use the submodule ID of the top-level 8610 // module as the file ID. For any other kind of file, the number of such 8611 // files loaded beforehand will be the same on reload. 8612 // FIXME: Is this true even if we have an explicit module file and a PCH? 8613 if (F->isModule()) 8614 return ((F->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1; 8615 8616 auto PCHModules = getModuleManager().pch_modules(); 8617 auto I = llvm::find(PCHModules, F); 8618 assert(I != PCHModules.end() && "emitting reference to unknown file"); 8619 return (I - PCHModules.end()) << 1; 8620 } 8621 8622 llvm::Optional<ASTSourceDescriptor> 8623 ASTReader::getSourceDescriptor(unsigned ID) { 8624 if (Module *M = getSubmodule(ID)) 8625 return ASTSourceDescriptor(*M); 8626 8627 // If there is only a single PCH, return it instead. 8628 // Chained PCH are not supported. 8629 const auto &PCHChain = ModuleMgr.pch_modules(); 8630 if (std::distance(std::begin(PCHChain), std::end(PCHChain))) { 8631 ModuleFile &MF = ModuleMgr.getPrimaryModule(); 8632 StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName); 8633 StringRef FileName = llvm::sys::path::filename(MF.FileName); 8634 return ASTSourceDescriptor(ModuleName, MF.OriginalDir, FileName, 8635 MF.Signature); 8636 } 8637 return None; 8638 } 8639 8640 ExternalASTSource::ExtKind ASTReader::hasExternalDefinitions(const Decl *FD) { 8641 auto I = DefinitionSource.find(FD); 8642 if (I == DefinitionSource.end()) 8643 return EK_ReplyHazy; 8644 return I->second ? EK_Never : EK_Always; 8645 } 8646 8647 Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) { 8648 return DecodeSelector(getGlobalSelectorID(M, LocalID)); 8649 } 8650 8651 Selector ASTReader::DecodeSelector(serialization::SelectorID ID) { 8652 if (ID == 0) 8653 return Selector(); 8654 8655 if (ID > SelectorsLoaded.size()) { 8656 Error("selector ID out of range in AST file"); 8657 return Selector(); 8658 } 8659 8660 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) { 8661 // Load this selector from the selector table. 8662 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID); 8663 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map"); 8664 ModuleFile &M = *I->second; 8665 ASTSelectorLookupTrait Trait(*this, M); 8666 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS; 8667 SelectorsLoaded[ID - 1] = 8668 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0); 8669 if (DeserializationListener) 8670 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]); 8671 } 8672 8673 return SelectorsLoaded[ID - 1]; 8674 } 8675 8676 Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) { 8677 return DecodeSelector(ID); 8678 } 8679 8680 uint32_t ASTReader::GetNumExternalSelectors() { 8681 // ID 0 (the null selector) is considered an external selector. 8682 return getTotalNumSelectors() + 1; 8683 } 8684 8685 serialization::SelectorID 8686 ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const { 8687 if (LocalID < NUM_PREDEF_SELECTOR_IDS) 8688 return LocalID; 8689 8690 if (!M.ModuleOffsetMap.empty()) 8691 ReadModuleOffsetMap(M); 8692 8693 ContinuousRangeMap<uint32_t, int, 2>::iterator I 8694 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS); 8695 assert(I != M.SelectorRemap.end() 8696 && "Invalid index into selector index remap"); 8697 8698 return LocalID + I->second; 8699 } 8700 8701 DeclarationNameLoc 8702 ASTRecordReader::readDeclarationNameLoc(DeclarationName Name) { 8703 DeclarationNameLoc DNLoc; 8704 switch (Name.getNameKind()) { 8705 case DeclarationName::CXXConstructorName: 8706 case DeclarationName::CXXDestructorName: 8707 case DeclarationName::CXXConversionFunctionName: 8708 DNLoc.NamedType.TInfo = readTypeSourceInfo(); 8709 break; 8710 8711 case DeclarationName::CXXOperatorName: 8712 DNLoc.CXXOperatorName.BeginOpNameLoc 8713 = readSourceLocation().getRawEncoding(); 8714 DNLoc.CXXOperatorName.EndOpNameLoc 8715 = readSourceLocation().getRawEncoding(); 8716 break; 8717 8718 case DeclarationName::CXXLiteralOperatorName: 8719 DNLoc.CXXLiteralOperatorName.OpNameLoc 8720 = readSourceLocation().getRawEncoding(); 8721 break; 8722 8723 case DeclarationName::Identifier: 8724 case DeclarationName::ObjCZeroArgSelector: 8725 case DeclarationName::ObjCOneArgSelector: 8726 case DeclarationName::ObjCMultiArgSelector: 8727 case DeclarationName::CXXUsingDirective: 8728 case DeclarationName::CXXDeductionGuideName: 8729 break; 8730 } 8731 return DNLoc; 8732 } 8733 8734 DeclarationNameInfo ASTRecordReader::readDeclarationNameInfo() { 8735 DeclarationNameInfo NameInfo; 8736 NameInfo.setName(readDeclarationName()); 8737 NameInfo.setLoc(readSourceLocation()); 8738 NameInfo.setInfo(readDeclarationNameLoc(NameInfo.getName())); 8739 return NameInfo; 8740 } 8741 8742 void ASTRecordReader::readQualifierInfo(QualifierInfo &Info) { 8743 Info.QualifierLoc = readNestedNameSpecifierLoc(); 8744 unsigned NumTPLists = readInt(); 8745 Info.NumTemplParamLists = NumTPLists; 8746 if (NumTPLists) { 8747 Info.TemplParamLists = 8748 new (getContext()) TemplateParameterList *[NumTPLists]; 8749 for (unsigned i = 0; i != NumTPLists; ++i) 8750 Info.TemplParamLists[i] = readTemplateParameterList(); 8751 } 8752 } 8753 8754 TemplateParameterList * 8755 ASTRecordReader::readTemplateParameterList() { 8756 SourceLocation TemplateLoc = readSourceLocation(); 8757 SourceLocation LAngleLoc = readSourceLocation(); 8758 SourceLocation RAngleLoc = readSourceLocation(); 8759 8760 unsigned NumParams = readInt(); 8761 SmallVector<NamedDecl *, 16> Params; 8762 Params.reserve(NumParams); 8763 while (NumParams--) 8764 Params.push_back(readDeclAs<NamedDecl>()); 8765 8766 bool HasRequiresClause = readBool(); 8767 Expr *RequiresClause = HasRequiresClause ? readExpr() : nullptr; 8768 8769 TemplateParameterList *TemplateParams = TemplateParameterList::Create( 8770 getContext(), TemplateLoc, LAngleLoc, Params, RAngleLoc, RequiresClause); 8771 return TemplateParams; 8772 } 8773 8774 void ASTRecordReader::readTemplateArgumentList( 8775 SmallVectorImpl<TemplateArgument> &TemplArgs, 8776 bool Canonicalize) { 8777 unsigned NumTemplateArgs = readInt(); 8778 TemplArgs.reserve(NumTemplateArgs); 8779 while (NumTemplateArgs--) 8780 TemplArgs.push_back(readTemplateArgument(Canonicalize)); 8781 } 8782 8783 /// Read a UnresolvedSet structure. 8784 void ASTRecordReader::readUnresolvedSet(LazyASTUnresolvedSet &Set) { 8785 unsigned NumDecls = readInt(); 8786 Set.reserve(getContext(), NumDecls); 8787 while (NumDecls--) { 8788 DeclID ID = readDeclID(); 8789 AccessSpecifier AS = (AccessSpecifier) readInt(); 8790 Set.addLazyDecl(getContext(), ID, AS); 8791 } 8792 } 8793 8794 CXXBaseSpecifier 8795 ASTRecordReader::readCXXBaseSpecifier() { 8796 bool isVirtual = readBool(); 8797 bool isBaseOfClass = readBool(); 8798 AccessSpecifier AS = static_cast<AccessSpecifier>(readInt()); 8799 bool inheritConstructors = readBool(); 8800 TypeSourceInfo *TInfo = readTypeSourceInfo(); 8801 SourceRange Range = readSourceRange(); 8802 SourceLocation EllipsisLoc = readSourceLocation(); 8803 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo, 8804 EllipsisLoc); 8805 Result.setInheritConstructors(inheritConstructors); 8806 return Result; 8807 } 8808 8809 CXXCtorInitializer ** 8810 ASTRecordReader::readCXXCtorInitializers() { 8811 ASTContext &Context = getContext(); 8812 unsigned NumInitializers = readInt(); 8813 assert(NumInitializers && "wrote ctor initializers but have no inits"); 8814 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers]; 8815 for (unsigned i = 0; i != NumInitializers; ++i) { 8816 TypeSourceInfo *TInfo = nullptr; 8817 bool IsBaseVirtual = false; 8818 FieldDecl *Member = nullptr; 8819 IndirectFieldDecl *IndirectMember = nullptr; 8820 8821 CtorInitializerType Type = (CtorInitializerType) readInt(); 8822 switch (Type) { 8823 case CTOR_INITIALIZER_BASE: 8824 TInfo = readTypeSourceInfo(); 8825 IsBaseVirtual = readBool(); 8826 break; 8827 8828 case CTOR_INITIALIZER_DELEGATING: 8829 TInfo = readTypeSourceInfo(); 8830 break; 8831 8832 case CTOR_INITIALIZER_MEMBER: 8833 Member = readDeclAs<FieldDecl>(); 8834 break; 8835 8836 case CTOR_INITIALIZER_INDIRECT_MEMBER: 8837 IndirectMember = readDeclAs<IndirectFieldDecl>(); 8838 break; 8839 } 8840 8841 SourceLocation MemberOrEllipsisLoc = readSourceLocation(); 8842 Expr *Init = readExpr(); 8843 SourceLocation LParenLoc = readSourceLocation(); 8844 SourceLocation RParenLoc = readSourceLocation(); 8845 8846 CXXCtorInitializer *BOMInit; 8847 if (Type == CTOR_INITIALIZER_BASE) 8848 BOMInit = new (Context) 8849 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init, 8850 RParenLoc, MemberOrEllipsisLoc); 8851 else if (Type == CTOR_INITIALIZER_DELEGATING) 8852 BOMInit = new (Context) 8853 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc); 8854 else if (Member) 8855 BOMInit = new (Context) 8856 CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc, LParenLoc, 8857 Init, RParenLoc); 8858 else 8859 BOMInit = new (Context) 8860 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc, 8861 LParenLoc, Init, RParenLoc); 8862 8863 if (/*IsWritten*/readBool()) { 8864 unsigned SourceOrder = readInt(); 8865 BOMInit->setSourceOrder(SourceOrder); 8866 } 8867 8868 CtorInitializers[i] = BOMInit; 8869 } 8870 8871 return CtorInitializers; 8872 } 8873 8874 NestedNameSpecifierLoc 8875 ASTRecordReader::readNestedNameSpecifierLoc() { 8876 ASTContext &Context = getContext(); 8877 unsigned N = readInt(); 8878 NestedNameSpecifierLocBuilder Builder; 8879 for (unsigned I = 0; I != N; ++I) { 8880 auto Kind = readNestedNameSpecifierKind(); 8881 switch (Kind) { 8882 case NestedNameSpecifier::Identifier: { 8883 IdentifierInfo *II = readIdentifier(); 8884 SourceRange Range = readSourceRange(); 8885 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd()); 8886 break; 8887 } 8888 8889 case NestedNameSpecifier::Namespace: { 8890 NamespaceDecl *NS = readDeclAs<NamespaceDecl>(); 8891 SourceRange Range = readSourceRange(); 8892 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd()); 8893 break; 8894 } 8895 8896 case NestedNameSpecifier::NamespaceAlias: { 8897 NamespaceAliasDecl *Alias = readDeclAs<NamespaceAliasDecl>(); 8898 SourceRange Range = readSourceRange(); 8899 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd()); 8900 break; 8901 } 8902 8903 case NestedNameSpecifier::TypeSpec: 8904 case NestedNameSpecifier::TypeSpecWithTemplate: { 8905 bool Template = readBool(); 8906 TypeSourceInfo *T = readTypeSourceInfo(); 8907 if (!T) 8908 return NestedNameSpecifierLoc(); 8909 SourceLocation ColonColonLoc = readSourceLocation(); 8910 8911 // FIXME: 'template' keyword location not saved anywhere, so we fake it. 8912 Builder.Extend(Context, 8913 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(), 8914 T->getTypeLoc(), ColonColonLoc); 8915 break; 8916 } 8917 8918 case NestedNameSpecifier::Global: { 8919 SourceLocation ColonColonLoc = readSourceLocation(); 8920 Builder.MakeGlobal(Context, ColonColonLoc); 8921 break; 8922 } 8923 8924 case NestedNameSpecifier::Super: { 8925 CXXRecordDecl *RD = readDeclAs<CXXRecordDecl>(); 8926 SourceRange Range = readSourceRange(); 8927 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd()); 8928 break; 8929 } 8930 } 8931 } 8932 8933 return Builder.getWithLocInContext(Context); 8934 } 8935 8936 SourceRange 8937 ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record, 8938 unsigned &Idx) { 8939 SourceLocation beg = ReadSourceLocation(F, Record, Idx); 8940 SourceLocation end = ReadSourceLocation(F, Record, Idx); 8941 return SourceRange(beg, end); 8942 } 8943 8944 static llvm::FixedPointSemantics 8945 ReadFixedPointSemantics(const SmallVectorImpl<uint64_t> &Record, 8946 unsigned &Idx) { 8947 unsigned Width = Record[Idx++]; 8948 unsigned Scale = Record[Idx++]; 8949 uint64_t Tmp = Record[Idx++]; 8950 bool IsSigned = Tmp & 0x1; 8951 bool IsSaturated = Tmp & 0x2; 8952 bool HasUnsignedPadding = Tmp & 0x4; 8953 return llvm::FixedPointSemantics(Width, Scale, IsSigned, IsSaturated, 8954 HasUnsignedPadding); 8955 } 8956 8957 APValue ASTRecordReader::readAPValue() { 8958 auto Kind = static_cast<APValue::ValueKind>(asImpl().readUInt32()); 8959 switch (Kind) { 8960 case APValue::None: 8961 return APValue(); 8962 case APValue::Indeterminate: 8963 return APValue::IndeterminateValue(); 8964 case APValue::Int: 8965 return APValue(asImpl().readAPSInt()); 8966 case APValue::Float: { 8967 const llvm::fltSemantics &FloatSema = llvm::APFloatBase::EnumToSemantics( 8968 static_cast<llvm::APFloatBase::Semantics>(asImpl().readUInt32())); 8969 return APValue(asImpl().readAPFloat(FloatSema)); 8970 } 8971 case APValue::FixedPoint: { 8972 llvm::FixedPointSemantics FPSema = ReadFixedPointSemantics(Record, Idx); 8973 return APValue(llvm::APFixedPoint(readAPInt(), FPSema)); 8974 } 8975 case APValue::ComplexInt: { 8976 llvm::APSInt First = asImpl().readAPSInt(); 8977 return APValue(std::move(First), asImpl().readAPSInt()); 8978 } 8979 case APValue::ComplexFloat: { 8980 const llvm::fltSemantics &FloatSema = llvm::APFloatBase::EnumToSemantics( 8981 static_cast<llvm::APFloatBase::Semantics>(asImpl().readUInt32())); 8982 llvm::APFloat First = readAPFloat(FloatSema); 8983 return APValue(std::move(First), asImpl().readAPFloat(FloatSema)); 8984 } 8985 case APValue::Vector: { 8986 APValue Result; 8987 Result.MakeVector(); 8988 unsigned Length = asImpl().readUInt32(); 8989 (void)Result.setVectorUninit(Length); 8990 for (unsigned LoopIdx = 0; LoopIdx < Length; LoopIdx++) 8991 Result.getVectorElt(LoopIdx) = asImpl().readAPValue(); 8992 return Result; 8993 } 8994 case APValue::Array: { 8995 APValue Result; 8996 unsigned InitLength = asImpl().readUInt32(); 8997 unsigned TotalLength = asImpl().readUInt32(); 8998 Result.MakeArray(InitLength, TotalLength); 8999 for (unsigned LoopIdx = 0; LoopIdx < InitLength; LoopIdx++) 9000 Result.getArrayInitializedElt(LoopIdx) = asImpl().readAPValue(); 9001 if (Result.hasArrayFiller()) 9002 Result.getArrayFiller() = asImpl().readAPValue(); 9003 return Result; 9004 } 9005 case APValue::Struct: { 9006 APValue Result; 9007 unsigned BasesLength = asImpl().readUInt32(); 9008 unsigned FieldsLength = asImpl().readUInt32(); 9009 Result.MakeStruct(BasesLength, FieldsLength); 9010 for (unsigned LoopIdx = 0; LoopIdx < BasesLength; LoopIdx++) 9011 Result.getStructBase(LoopIdx) = asImpl().readAPValue(); 9012 for (unsigned LoopIdx = 0; LoopIdx < FieldsLength; LoopIdx++) 9013 Result.getStructField(LoopIdx) = asImpl().readAPValue(); 9014 return Result; 9015 } 9016 case APValue::Union: { 9017 auto *FDecl = asImpl().readDeclAs<FieldDecl>(); 9018 APValue Value = asImpl().readAPValue(); 9019 return APValue(FDecl, std::move(Value)); 9020 } 9021 case APValue::AddrLabelDiff: { 9022 auto *LHS = cast<AddrLabelExpr>(asImpl().readExpr()); 9023 auto *RHS = cast<AddrLabelExpr>(asImpl().readExpr()); 9024 return APValue(LHS, RHS); 9025 } 9026 case APValue::MemberPointer: { 9027 APValue Result; 9028 bool IsDerived = asImpl().readUInt32(); 9029 auto *Member = asImpl().readDeclAs<ValueDecl>(); 9030 unsigned PathSize = asImpl().readUInt32(); 9031 const CXXRecordDecl **PathArray = 9032 Result.setMemberPointerUninit(Member, IsDerived, PathSize).data(); 9033 for (unsigned LoopIdx = 0; LoopIdx < PathSize; LoopIdx++) 9034 PathArray[LoopIdx] = 9035 asImpl().readDeclAs<const CXXRecordDecl>()->getCanonicalDecl(); 9036 return Result; 9037 } 9038 case APValue::LValue: { 9039 uint64_t Bits = asImpl().readUInt32(); 9040 bool HasLValuePath = Bits & 0x1; 9041 bool IsLValueOnePastTheEnd = Bits & 0x2; 9042 bool IsExpr = Bits & 0x4; 9043 bool IsTypeInfo = Bits & 0x8; 9044 bool IsNullPtr = Bits & 0x10; 9045 bool HasBase = Bits & 0x20; 9046 APValue::LValueBase Base; 9047 QualType ElemTy; 9048 assert((!IsExpr || !IsTypeInfo) && "LValueBase cannot be both"); 9049 if (HasBase) { 9050 if (!IsTypeInfo) { 9051 unsigned CallIndex = asImpl().readUInt32(); 9052 unsigned Version = asImpl().readUInt32(); 9053 if (IsExpr) { 9054 Base = APValue::LValueBase(asImpl().readExpr(), CallIndex, Version); 9055 ElemTy = Base.get<const Expr *>()->getType(); 9056 } else { 9057 Base = APValue::LValueBase(asImpl().readDeclAs<const ValueDecl>(), 9058 CallIndex, Version); 9059 ElemTy = Base.get<const ValueDecl *>()->getType(); 9060 } 9061 } else { 9062 QualType TypeInfo = asImpl().readType(); 9063 QualType Type = asImpl().readType(); 9064 Base = APValue::LValueBase::getTypeInfo( 9065 TypeInfoLValue(TypeInfo.getTypePtr()), Type); 9066 Base.getTypeInfoType(); 9067 } 9068 } 9069 CharUnits Offset = CharUnits::fromQuantity(asImpl().readUInt32()); 9070 unsigned PathLength = asImpl().readUInt32(); 9071 APValue Result; 9072 Result.MakeLValue(); 9073 if (HasLValuePath) { 9074 APValue::LValuePathEntry *Path = 9075 Result 9076 .setLValueUninit(Base, Offset, PathLength, IsLValueOnePastTheEnd, 9077 IsNullPtr) 9078 .data(); 9079 for (unsigned LoopIdx = 0; LoopIdx < PathLength; LoopIdx++) { 9080 if (ElemTy->getAs<RecordType>()) { 9081 unsigned Int = asImpl().readUInt32(); 9082 Decl *D = asImpl().readDeclAs<Decl>(); 9083 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) 9084 ElemTy = getASTContext().getRecordType(RD); 9085 else 9086 ElemTy = cast<ValueDecl>(D)->getType(); 9087 Path[LoopIdx] = 9088 APValue::LValuePathEntry(APValue::BaseOrMemberType(D, Int)); 9089 } else { 9090 ElemTy = getASTContext().getAsArrayType(ElemTy)->getElementType(); 9091 Path[LoopIdx] = 9092 APValue::LValuePathEntry::ArrayIndex(asImpl().readUInt32()); 9093 } 9094 } 9095 } else 9096 Result.setLValue(Base, Offset, APValue::NoLValuePath{}, IsNullPtr); 9097 return Result; 9098 } 9099 } 9100 llvm_unreachable("Invalid APValue::ValueKind"); 9101 } 9102 9103 /// Read a floating-point value 9104 llvm::APFloat ASTRecordReader::readAPFloat(const llvm::fltSemantics &Sem) { 9105 return llvm::APFloat(Sem, readAPInt()); 9106 } 9107 9108 // Read a string 9109 std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) { 9110 unsigned Len = Record[Idx++]; 9111 std::string Result(Record.data() + Idx, Record.data() + Idx + Len); 9112 Idx += Len; 9113 return Result; 9114 } 9115 9116 std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record, 9117 unsigned &Idx) { 9118 std::string Filename = ReadString(Record, Idx); 9119 ResolveImportedPath(F, Filename); 9120 return Filename; 9121 } 9122 9123 std::string ASTReader::ReadPath(StringRef BaseDirectory, 9124 const RecordData &Record, unsigned &Idx) { 9125 std::string Filename = ReadString(Record, Idx); 9126 if (!BaseDirectory.empty()) 9127 ResolveImportedPath(Filename, BaseDirectory); 9128 return Filename; 9129 } 9130 9131 VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record, 9132 unsigned &Idx) { 9133 unsigned Major = Record[Idx++]; 9134 unsigned Minor = Record[Idx++]; 9135 unsigned Subminor = Record[Idx++]; 9136 if (Minor == 0) 9137 return VersionTuple(Major); 9138 if (Subminor == 0) 9139 return VersionTuple(Major, Minor - 1); 9140 return VersionTuple(Major, Minor - 1, Subminor - 1); 9141 } 9142 9143 CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F, 9144 const RecordData &Record, 9145 unsigned &Idx) { 9146 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx); 9147 return CXXTemporary::Create(getContext(), Decl); 9148 } 9149 9150 DiagnosticBuilder ASTReader::Diag(unsigned DiagID) const { 9151 return Diag(CurrentImportLoc, DiagID); 9152 } 9153 9154 DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) const { 9155 return Diags.Report(Loc, DiagID); 9156 } 9157 9158 /// Retrieve the identifier table associated with the 9159 /// preprocessor. 9160 IdentifierTable &ASTReader::getIdentifierTable() { 9161 return PP.getIdentifierTable(); 9162 } 9163 9164 /// Record that the given ID maps to the given switch-case 9165 /// statement. 9166 void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) { 9167 assert((*CurrSwitchCaseStmts)[ID] == nullptr && 9168 "Already have a SwitchCase with this ID"); 9169 (*CurrSwitchCaseStmts)[ID] = SC; 9170 } 9171 9172 /// Retrieve the switch-case statement with the given ID. 9173 SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) { 9174 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID"); 9175 return (*CurrSwitchCaseStmts)[ID]; 9176 } 9177 9178 void ASTReader::ClearSwitchCaseIDs() { 9179 CurrSwitchCaseStmts->clear(); 9180 } 9181 9182 void ASTReader::ReadComments() { 9183 ASTContext &Context = getContext(); 9184 std::vector<RawComment *> Comments; 9185 for (SmallVectorImpl<std::pair<BitstreamCursor, 9186 serialization::ModuleFile *>>::iterator 9187 I = CommentsCursors.begin(), 9188 E = CommentsCursors.end(); 9189 I != E; ++I) { 9190 Comments.clear(); 9191 BitstreamCursor &Cursor = I->first; 9192 serialization::ModuleFile &F = *I->second; 9193 SavedStreamPosition SavedPosition(Cursor); 9194 9195 RecordData Record; 9196 while (true) { 9197 Expected<llvm::BitstreamEntry> MaybeEntry = 9198 Cursor.advanceSkippingSubblocks( 9199 BitstreamCursor::AF_DontPopBlockAtEnd); 9200 if (!MaybeEntry) { 9201 Error(MaybeEntry.takeError()); 9202 return; 9203 } 9204 llvm::BitstreamEntry Entry = MaybeEntry.get(); 9205 9206 switch (Entry.Kind) { 9207 case llvm::BitstreamEntry::SubBlock: // Handled for us already. 9208 case llvm::BitstreamEntry::Error: 9209 Error("malformed block record in AST file"); 9210 return; 9211 case llvm::BitstreamEntry::EndBlock: 9212 goto NextCursor; 9213 case llvm::BitstreamEntry::Record: 9214 // The interesting case. 9215 break; 9216 } 9217 9218 // Read a record. 9219 Record.clear(); 9220 Expected<unsigned> MaybeComment = Cursor.readRecord(Entry.ID, Record); 9221 if (!MaybeComment) { 9222 Error(MaybeComment.takeError()); 9223 return; 9224 } 9225 switch ((CommentRecordTypes)MaybeComment.get()) { 9226 case COMMENTS_RAW_COMMENT: { 9227 unsigned Idx = 0; 9228 SourceRange SR = ReadSourceRange(F, Record, Idx); 9229 RawComment::CommentKind Kind = 9230 (RawComment::CommentKind) Record[Idx++]; 9231 bool IsTrailingComment = Record[Idx++]; 9232 bool IsAlmostTrailingComment = Record[Idx++]; 9233 Comments.push_back(new (Context) RawComment( 9234 SR, Kind, IsTrailingComment, IsAlmostTrailingComment)); 9235 break; 9236 } 9237 } 9238 } 9239 NextCursor: 9240 llvm::DenseMap<FileID, std::map<unsigned, RawComment *>> 9241 FileToOffsetToComment; 9242 for (RawComment *C : Comments) { 9243 SourceLocation CommentLoc = C->getBeginLoc(); 9244 if (CommentLoc.isValid()) { 9245 std::pair<FileID, unsigned> Loc = 9246 SourceMgr.getDecomposedLoc(CommentLoc); 9247 if (Loc.first.isValid()) 9248 Context.Comments.OrderedComments[Loc.first].emplace(Loc.second, C); 9249 } 9250 } 9251 } 9252 } 9253 9254 void ASTReader::visitInputFiles(serialization::ModuleFile &MF, 9255 bool IncludeSystem, bool Complain, 9256 llvm::function_ref<void(const serialization::InputFile &IF, 9257 bool isSystem)> Visitor) { 9258 unsigned NumUserInputs = MF.NumUserInputFiles; 9259 unsigned NumInputs = MF.InputFilesLoaded.size(); 9260 assert(NumUserInputs <= NumInputs); 9261 unsigned N = IncludeSystem ? NumInputs : NumUserInputs; 9262 for (unsigned I = 0; I < N; ++I) { 9263 bool IsSystem = I >= NumUserInputs; 9264 InputFile IF = getInputFile(MF, I+1, Complain); 9265 Visitor(IF, IsSystem); 9266 } 9267 } 9268 9269 void ASTReader::visitTopLevelModuleMaps( 9270 serialization::ModuleFile &MF, 9271 llvm::function_ref<void(const FileEntry *FE)> Visitor) { 9272 unsigned NumInputs = MF.InputFilesLoaded.size(); 9273 for (unsigned I = 0; I < NumInputs; ++I) { 9274 InputFileInfo IFI = readInputFileInfo(MF, I + 1); 9275 if (IFI.TopLevelModuleMap) 9276 // FIXME: This unnecessarily re-reads the InputFileInfo. 9277 if (auto *FE = getInputFile(MF, I + 1).getFile()) 9278 Visitor(FE); 9279 } 9280 } 9281 9282 std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) { 9283 // If we know the owning module, use it. 9284 if (Module *M = D->getImportedOwningModule()) 9285 return M->getFullModuleName(); 9286 9287 // Otherwise, use the name of the top-level module the decl is within. 9288 if (ModuleFile *M = getOwningModuleFile(D)) 9289 return M->ModuleName; 9290 9291 // Not from a module. 9292 return {}; 9293 } 9294 9295 void ASTReader::finishPendingActions() { 9296 while (!PendingIdentifierInfos.empty() || !PendingFunctionTypes.empty() || 9297 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() || 9298 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() || 9299 !PendingUpdateRecords.empty()) { 9300 // If any identifiers with corresponding top-level declarations have 9301 // been loaded, load those declarations now. 9302 using TopLevelDeclsMap = 9303 llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2>>; 9304 TopLevelDeclsMap TopLevelDecls; 9305 9306 while (!PendingIdentifierInfos.empty()) { 9307 IdentifierInfo *II = PendingIdentifierInfos.back().first; 9308 SmallVector<uint32_t, 4> DeclIDs = 9309 std::move(PendingIdentifierInfos.back().second); 9310 PendingIdentifierInfos.pop_back(); 9311 9312 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]); 9313 } 9314 9315 // Load each function type that we deferred loading because it was a 9316 // deduced type that might refer to a local type declared within itself. 9317 for (unsigned I = 0; I != PendingFunctionTypes.size(); ++I) { 9318 auto *FD = PendingFunctionTypes[I].first; 9319 FD->setType(GetType(PendingFunctionTypes[I].second)); 9320 9321 // If we gave a function a deduced return type, remember that we need to 9322 // propagate that along the redeclaration chain. 9323 auto *DT = FD->getReturnType()->getContainedDeducedType(); 9324 if (DT && DT->isDeduced()) 9325 PendingDeducedTypeUpdates.insert( 9326 {FD->getCanonicalDecl(), FD->getReturnType()}); 9327 } 9328 PendingFunctionTypes.clear(); 9329 9330 // For each decl chain that we wanted to complete while deserializing, mark 9331 // it as "still needs to be completed". 9332 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) { 9333 markIncompleteDeclChain(PendingIncompleteDeclChains[I]); 9334 } 9335 PendingIncompleteDeclChains.clear(); 9336 9337 // Load pending declaration chains. 9338 for (unsigned I = 0; I != PendingDeclChains.size(); ++I) 9339 loadPendingDeclChain(PendingDeclChains[I].first, 9340 PendingDeclChains[I].second); 9341 PendingDeclChains.clear(); 9342 9343 // Make the most recent of the top-level declarations visible. 9344 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(), 9345 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) { 9346 IdentifierInfo *II = TLD->first; 9347 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) { 9348 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II); 9349 } 9350 } 9351 9352 // Load any pending macro definitions. 9353 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) { 9354 IdentifierInfo *II = PendingMacroIDs.begin()[I].first; 9355 SmallVector<PendingMacroInfo, 2> GlobalIDs; 9356 GlobalIDs.swap(PendingMacroIDs.begin()[I].second); 9357 // Initialize the macro history from chained-PCHs ahead of module imports. 9358 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs; 9359 ++IDIdx) { 9360 const PendingMacroInfo &Info = GlobalIDs[IDIdx]; 9361 if (!Info.M->isModule()) 9362 resolvePendingMacro(II, Info); 9363 } 9364 // Handle module imports. 9365 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs; 9366 ++IDIdx) { 9367 const PendingMacroInfo &Info = GlobalIDs[IDIdx]; 9368 if (Info.M->isModule()) 9369 resolvePendingMacro(II, Info); 9370 } 9371 } 9372 PendingMacroIDs.clear(); 9373 9374 // Wire up the DeclContexts for Decls that we delayed setting until 9375 // recursive loading is completed. 9376 while (!PendingDeclContextInfos.empty()) { 9377 PendingDeclContextInfo Info = PendingDeclContextInfos.front(); 9378 PendingDeclContextInfos.pop_front(); 9379 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC)); 9380 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC)); 9381 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext()); 9382 } 9383 9384 // Perform any pending declaration updates. 9385 while (!PendingUpdateRecords.empty()) { 9386 auto Update = PendingUpdateRecords.pop_back_val(); 9387 ReadingKindTracker ReadingKind(Read_Decl, *this); 9388 loadDeclUpdateRecords(Update); 9389 } 9390 } 9391 9392 // At this point, all update records for loaded decls are in place, so any 9393 // fake class definitions should have become real. 9394 assert(PendingFakeDefinitionData.empty() && 9395 "faked up a class definition but never saw the real one"); 9396 9397 // If we deserialized any C++ or Objective-C class definitions, any 9398 // Objective-C protocol definitions, or any redeclarable templates, make sure 9399 // that all redeclarations point to the definitions. Note that this can only 9400 // happen now, after the redeclaration chains have been fully wired. 9401 for (Decl *D : PendingDefinitions) { 9402 if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 9403 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) { 9404 // Make sure that the TagType points at the definition. 9405 const_cast<TagType*>(TagT)->decl = TD; 9406 } 9407 9408 if (auto RD = dyn_cast<CXXRecordDecl>(D)) { 9409 for (auto *R = getMostRecentExistingDecl(RD); R; 9410 R = R->getPreviousDecl()) { 9411 assert((R == D) == 9412 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() && 9413 "declaration thinks it's the definition but it isn't"); 9414 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData; 9415 } 9416 } 9417 9418 continue; 9419 } 9420 9421 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) { 9422 // Make sure that the ObjCInterfaceType points at the definition. 9423 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl)) 9424 ->Decl = ID; 9425 9426 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl()) 9427 cast<ObjCInterfaceDecl>(R)->Data = ID->Data; 9428 9429 continue; 9430 } 9431 9432 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) { 9433 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl()) 9434 cast<ObjCProtocolDecl>(R)->Data = PD->Data; 9435 9436 continue; 9437 } 9438 9439 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl(); 9440 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl()) 9441 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common; 9442 } 9443 PendingDefinitions.clear(); 9444 9445 // Load the bodies of any functions or methods we've encountered. We do 9446 // this now (delayed) so that we can be sure that the declaration chains 9447 // have been fully wired up (hasBody relies on this). 9448 // FIXME: We shouldn't require complete redeclaration chains here. 9449 for (PendingBodiesMap::iterator PB = PendingBodies.begin(), 9450 PBEnd = PendingBodies.end(); 9451 PB != PBEnd; ++PB) { 9452 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) { 9453 // For a function defined inline within a class template, force the 9454 // canonical definition to be the one inside the canonical definition of 9455 // the template. This ensures that we instantiate from a correct view 9456 // of the template. 9457 // 9458 // Sadly we can't do this more generally: we can't be sure that all 9459 // copies of an arbitrary class definition will have the same members 9460 // defined (eg, some member functions may not be instantiated, and some 9461 // special members may or may not have been implicitly defined). 9462 if (auto *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalParent())) 9463 if (RD->isDependentContext() && !RD->isThisDeclarationADefinition()) 9464 continue; 9465 9466 // FIXME: Check for =delete/=default? 9467 // FIXME: Complain about ODR violations here? 9468 const FunctionDecl *Defn = nullptr; 9469 if (!getContext().getLangOpts().Modules || !FD->hasBody(Defn)) { 9470 FD->setLazyBody(PB->second); 9471 } else { 9472 auto *NonConstDefn = const_cast<FunctionDecl*>(Defn); 9473 mergeDefinitionVisibility(NonConstDefn, FD); 9474 9475 if (!FD->isLateTemplateParsed() && 9476 !NonConstDefn->isLateTemplateParsed() && 9477 FD->getODRHash() != NonConstDefn->getODRHash()) { 9478 if (!isa<CXXMethodDecl>(FD)) { 9479 PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn); 9480 } else if (FD->getLexicalParent()->isFileContext() && 9481 NonConstDefn->getLexicalParent()->isFileContext()) { 9482 // Only diagnose out-of-line method definitions. If they are 9483 // in class definitions, then an error will be generated when 9484 // processing the class bodies. 9485 PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn); 9486 } 9487 } 9488 } 9489 continue; 9490 } 9491 9492 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first); 9493 if (!getContext().getLangOpts().Modules || !MD->hasBody()) 9494 MD->setLazyBody(PB->second); 9495 } 9496 PendingBodies.clear(); 9497 9498 // Do some cleanup. 9499 for (auto *ND : PendingMergedDefinitionsToDeduplicate) 9500 getContext().deduplicateMergedDefinitonsFor(ND); 9501 PendingMergedDefinitionsToDeduplicate.clear(); 9502 } 9503 9504 void ASTReader::diagnoseOdrViolations() { 9505 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty() && 9506 PendingFunctionOdrMergeFailures.empty() && 9507 PendingEnumOdrMergeFailures.empty()) 9508 return; 9509 9510 // Trigger the import of the full definition of each class that had any 9511 // odr-merging problems, so we can produce better diagnostics for them. 9512 // These updates may in turn find and diagnose some ODR failures, so take 9513 // ownership of the set first. 9514 auto OdrMergeFailures = std::move(PendingOdrMergeFailures); 9515 PendingOdrMergeFailures.clear(); 9516 for (auto &Merge : OdrMergeFailures) { 9517 Merge.first->buildLookup(); 9518 Merge.first->decls_begin(); 9519 Merge.first->bases_begin(); 9520 Merge.first->vbases_begin(); 9521 for (auto &RecordPair : Merge.second) { 9522 auto *RD = RecordPair.first; 9523 RD->decls_begin(); 9524 RD->bases_begin(); 9525 RD->vbases_begin(); 9526 } 9527 } 9528 9529 // Trigger the import of functions. 9530 auto FunctionOdrMergeFailures = std::move(PendingFunctionOdrMergeFailures); 9531 PendingFunctionOdrMergeFailures.clear(); 9532 for (auto &Merge : FunctionOdrMergeFailures) { 9533 Merge.first->buildLookup(); 9534 Merge.first->decls_begin(); 9535 Merge.first->getBody(); 9536 for (auto &FD : Merge.second) { 9537 FD->buildLookup(); 9538 FD->decls_begin(); 9539 FD->getBody(); 9540 } 9541 } 9542 9543 // Trigger the import of enums. 9544 auto EnumOdrMergeFailures = std::move(PendingEnumOdrMergeFailures); 9545 PendingEnumOdrMergeFailures.clear(); 9546 for (auto &Merge : EnumOdrMergeFailures) { 9547 Merge.first->decls_begin(); 9548 for (auto &Enum : Merge.second) { 9549 Enum->decls_begin(); 9550 } 9551 } 9552 9553 // For each declaration from a merged context, check that the canonical 9554 // definition of that context also contains a declaration of the same 9555 // entity. 9556 // 9557 // Caution: this loop does things that might invalidate iterators into 9558 // PendingOdrMergeChecks. Don't turn this into a range-based for loop! 9559 while (!PendingOdrMergeChecks.empty()) { 9560 NamedDecl *D = PendingOdrMergeChecks.pop_back_val(); 9561 9562 // FIXME: Skip over implicit declarations for now. This matters for things 9563 // like implicitly-declared special member functions. This isn't entirely 9564 // correct; we can end up with multiple unmerged declarations of the same 9565 // implicit entity. 9566 if (D->isImplicit()) 9567 continue; 9568 9569 DeclContext *CanonDef = D->getDeclContext(); 9570 9571 bool Found = false; 9572 const Decl *DCanon = D->getCanonicalDecl(); 9573 9574 for (auto RI : D->redecls()) { 9575 if (RI->getLexicalDeclContext() == CanonDef) { 9576 Found = true; 9577 break; 9578 } 9579 } 9580 if (Found) 9581 continue; 9582 9583 // Quick check failed, time to do the slow thing. Note, we can't just 9584 // look up the name of D in CanonDef here, because the member that is 9585 // in CanonDef might not be found by name lookup (it might have been 9586 // replaced by a more recent declaration in the lookup table), and we 9587 // can't necessarily find it in the redeclaration chain because it might 9588 // be merely mergeable, not redeclarable. 9589 llvm::SmallVector<const NamedDecl*, 4> Candidates; 9590 for (auto *CanonMember : CanonDef->decls()) { 9591 if (CanonMember->getCanonicalDecl() == DCanon) { 9592 // This can happen if the declaration is merely mergeable and not 9593 // actually redeclarable (we looked for redeclarations earlier). 9594 // 9595 // FIXME: We should be able to detect this more efficiently, without 9596 // pulling in all of the members of CanonDef. 9597 Found = true; 9598 break; 9599 } 9600 if (auto *ND = dyn_cast<NamedDecl>(CanonMember)) 9601 if (ND->getDeclName() == D->getDeclName()) 9602 Candidates.push_back(ND); 9603 } 9604 9605 if (!Found) { 9606 // The AST doesn't like TagDecls becoming invalid after they've been 9607 // completed. We only really need to mark FieldDecls as invalid here. 9608 if (!isa<TagDecl>(D)) 9609 D->setInvalidDecl(); 9610 9611 // Ensure we don't accidentally recursively enter deserialization while 9612 // we're producing our diagnostic. 9613 Deserializing RecursionGuard(this); 9614 9615 std::string CanonDefModule = 9616 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef)); 9617 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl) 9618 << D << getOwningModuleNameForDiagnostic(D) 9619 << CanonDef << CanonDefModule.empty() << CanonDefModule; 9620 9621 if (Candidates.empty()) 9622 Diag(cast<Decl>(CanonDef)->getLocation(), 9623 diag::note_module_odr_violation_no_possible_decls) << D; 9624 else { 9625 for (unsigned I = 0, N = Candidates.size(); I != N; ++I) 9626 Diag(Candidates[I]->getLocation(), 9627 diag::note_module_odr_violation_possible_decl) 9628 << Candidates[I]; 9629 } 9630 9631 DiagnosedOdrMergeFailures.insert(CanonDef); 9632 } 9633 } 9634 9635 if (OdrMergeFailures.empty() && FunctionOdrMergeFailures.empty() && 9636 EnumOdrMergeFailures.empty()) 9637 return; 9638 9639 // Ensure we don't accidentally recursively enter deserialization while 9640 // we're producing our diagnostics. 9641 Deserializing RecursionGuard(this); 9642 9643 // Common code for hashing helpers. 9644 ODRHash Hash; 9645 auto ComputeQualTypeODRHash = [&Hash](QualType Ty) { 9646 Hash.clear(); 9647 Hash.AddQualType(Ty); 9648 return Hash.CalculateHash(); 9649 }; 9650 9651 auto ComputeODRHash = [&Hash](const Stmt *S) { 9652 assert(S); 9653 Hash.clear(); 9654 Hash.AddStmt(S); 9655 return Hash.CalculateHash(); 9656 }; 9657 9658 auto ComputeSubDeclODRHash = [&Hash](const Decl *D) { 9659 assert(D); 9660 Hash.clear(); 9661 Hash.AddSubDecl(D); 9662 return Hash.CalculateHash(); 9663 }; 9664 9665 auto ComputeTemplateArgumentODRHash = [&Hash](const TemplateArgument &TA) { 9666 Hash.clear(); 9667 Hash.AddTemplateArgument(TA); 9668 return Hash.CalculateHash(); 9669 }; 9670 9671 auto ComputeTemplateParameterListODRHash = 9672 [&Hash](const TemplateParameterList *TPL) { 9673 assert(TPL); 9674 Hash.clear(); 9675 Hash.AddTemplateParameterList(TPL); 9676 return Hash.CalculateHash(); 9677 }; 9678 9679 // Used with err_module_odr_violation_mismatch_decl and 9680 // note_module_odr_violation_mismatch_decl 9681 // This list should be the same Decl's as in ODRHash::isDeclToBeProcessed 9682 enum ODRMismatchDecl { 9683 EndOfClass, 9684 PublicSpecifer, 9685 PrivateSpecifer, 9686 ProtectedSpecifer, 9687 StaticAssert, 9688 Field, 9689 CXXMethod, 9690 TypeAlias, 9691 TypeDef, 9692 Var, 9693 Friend, 9694 FunctionTemplate, 9695 Other 9696 }; 9697 9698 // Used with err_module_odr_violation_mismatch_decl_diff and 9699 // note_module_odr_violation_mismatch_decl_diff 9700 enum ODRMismatchDeclDifference { 9701 StaticAssertCondition, 9702 StaticAssertMessage, 9703 StaticAssertOnlyMessage, 9704 FieldName, 9705 FieldTypeName, 9706 FieldSingleBitField, 9707 FieldDifferentWidthBitField, 9708 FieldSingleMutable, 9709 FieldSingleInitializer, 9710 FieldDifferentInitializers, 9711 MethodName, 9712 MethodDeleted, 9713 MethodDefaulted, 9714 MethodVirtual, 9715 MethodStatic, 9716 MethodVolatile, 9717 MethodConst, 9718 MethodInline, 9719 MethodNumberParameters, 9720 MethodParameterType, 9721 MethodParameterName, 9722 MethodParameterSingleDefaultArgument, 9723 MethodParameterDifferentDefaultArgument, 9724 MethodNoTemplateArguments, 9725 MethodDifferentNumberTemplateArguments, 9726 MethodDifferentTemplateArgument, 9727 MethodSingleBody, 9728 MethodDifferentBody, 9729 TypedefName, 9730 TypedefType, 9731 VarName, 9732 VarType, 9733 VarSingleInitializer, 9734 VarDifferentInitializer, 9735 VarConstexpr, 9736 FriendTypeFunction, 9737 FriendType, 9738 FriendFunction, 9739 FunctionTemplateDifferentNumberParameters, 9740 FunctionTemplateParameterDifferentKind, 9741 FunctionTemplateParameterName, 9742 FunctionTemplateParameterSingleDefaultArgument, 9743 FunctionTemplateParameterDifferentDefaultArgument, 9744 FunctionTemplateParameterDifferentType, 9745 FunctionTemplatePackParameter, 9746 }; 9747 9748 // These lambdas have the common portions of the ODR diagnostics. This 9749 // has the same return as Diag(), so addition parameters can be passed 9750 // in with operator<< 9751 auto ODRDiagDeclError = [this](NamedDecl *FirstRecord, StringRef FirstModule, 9752 SourceLocation Loc, SourceRange Range, 9753 ODRMismatchDeclDifference DiffType) { 9754 return Diag(Loc, diag::err_module_odr_violation_mismatch_decl_diff) 9755 << FirstRecord << FirstModule.empty() << FirstModule << Range 9756 << DiffType; 9757 }; 9758 auto ODRDiagDeclNote = [this](StringRef SecondModule, SourceLocation Loc, 9759 SourceRange Range, ODRMismatchDeclDifference DiffType) { 9760 return Diag(Loc, diag::note_module_odr_violation_mismatch_decl_diff) 9761 << SecondModule << Range << DiffType; 9762 }; 9763 9764 auto ODRDiagField = [this, &ODRDiagDeclError, &ODRDiagDeclNote, 9765 &ComputeQualTypeODRHash, &ComputeODRHash]( 9766 NamedDecl *FirstRecord, StringRef FirstModule, 9767 StringRef SecondModule, FieldDecl *FirstField, 9768 FieldDecl *SecondField) { 9769 IdentifierInfo *FirstII = FirstField->getIdentifier(); 9770 IdentifierInfo *SecondII = SecondField->getIdentifier(); 9771 if (FirstII->getName() != SecondII->getName()) { 9772 ODRDiagDeclError(FirstRecord, FirstModule, FirstField->getLocation(), 9773 FirstField->getSourceRange(), FieldName) 9774 << FirstII; 9775 ODRDiagDeclNote(SecondModule, SecondField->getLocation(), 9776 SecondField->getSourceRange(), FieldName) 9777 << SecondII; 9778 9779 return true; 9780 } 9781 9782 assert(getContext().hasSameType(FirstField->getType(), 9783 SecondField->getType())); 9784 9785 QualType FirstType = FirstField->getType(); 9786 QualType SecondType = SecondField->getType(); 9787 if (ComputeQualTypeODRHash(FirstType) != 9788 ComputeQualTypeODRHash(SecondType)) { 9789 ODRDiagDeclError(FirstRecord, FirstModule, FirstField->getLocation(), 9790 FirstField->getSourceRange(), FieldTypeName) 9791 << FirstII << FirstType; 9792 ODRDiagDeclNote(SecondModule, SecondField->getLocation(), 9793 SecondField->getSourceRange(), FieldTypeName) 9794 << SecondII << SecondType; 9795 9796 return true; 9797 } 9798 9799 const bool IsFirstBitField = FirstField->isBitField(); 9800 const bool IsSecondBitField = SecondField->isBitField(); 9801 if (IsFirstBitField != IsSecondBitField) { 9802 ODRDiagDeclError(FirstRecord, FirstModule, FirstField->getLocation(), 9803 FirstField->getSourceRange(), FieldSingleBitField) 9804 << FirstII << IsFirstBitField; 9805 ODRDiagDeclNote(SecondModule, SecondField->getLocation(), 9806 SecondField->getSourceRange(), FieldSingleBitField) 9807 << SecondII << IsSecondBitField; 9808 return true; 9809 } 9810 9811 if (IsFirstBitField && IsSecondBitField) { 9812 unsigned FirstBitWidthHash = 9813 ComputeODRHash(FirstField->getBitWidth()); 9814 unsigned SecondBitWidthHash = 9815 ComputeODRHash(SecondField->getBitWidth()); 9816 if (FirstBitWidthHash != SecondBitWidthHash) { 9817 ODRDiagDeclError(FirstRecord, FirstModule, FirstField->getLocation(), 9818 FirstField->getSourceRange(), 9819 FieldDifferentWidthBitField) 9820 << FirstII << FirstField->getBitWidth()->getSourceRange(); 9821 ODRDiagDeclNote(SecondModule, SecondField->getLocation(), 9822 SecondField->getSourceRange(), 9823 FieldDifferentWidthBitField) 9824 << SecondII << SecondField->getBitWidth()->getSourceRange(); 9825 return true; 9826 } 9827 } 9828 9829 if (!PP.getLangOpts().CPlusPlus) 9830 return false; 9831 9832 const bool IsFirstMutable = FirstField->isMutable(); 9833 const bool IsSecondMutable = SecondField->isMutable(); 9834 if (IsFirstMutable != IsSecondMutable) { 9835 ODRDiagDeclError(FirstRecord, FirstModule, FirstField->getLocation(), 9836 FirstField->getSourceRange(), FieldSingleMutable) 9837 << FirstII << IsFirstMutable; 9838 ODRDiagDeclNote(SecondModule, SecondField->getLocation(), 9839 SecondField->getSourceRange(), FieldSingleMutable) 9840 << SecondII << IsSecondMutable; 9841 return true; 9842 } 9843 9844 const Expr *FirstInitializer = FirstField->getInClassInitializer(); 9845 const Expr *SecondInitializer = SecondField->getInClassInitializer(); 9846 if ((!FirstInitializer && SecondInitializer) || 9847 (FirstInitializer && !SecondInitializer)) { 9848 ODRDiagDeclError(FirstRecord, FirstModule, FirstField->getLocation(), 9849 FirstField->getSourceRange(), FieldSingleInitializer) 9850 << FirstII << (FirstInitializer != nullptr); 9851 ODRDiagDeclNote(SecondModule, SecondField->getLocation(), 9852 SecondField->getSourceRange(), FieldSingleInitializer) 9853 << SecondII << (SecondInitializer != nullptr); 9854 return true; 9855 } 9856 9857 if (FirstInitializer && SecondInitializer) { 9858 unsigned FirstInitHash = ComputeODRHash(FirstInitializer); 9859 unsigned SecondInitHash = ComputeODRHash(SecondInitializer); 9860 if (FirstInitHash != SecondInitHash) { 9861 ODRDiagDeclError(FirstRecord, FirstModule, FirstField->getLocation(), 9862 FirstField->getSourceRange(), 9863 FieldDifferentInitializers) 9864 << FirstII << FirstInitializer->getSourceRange(); 9865 ODRDiagDeclNote(SecondModule, SecondField->getLocation(), 9866 SecondField->getSourceRange(), 9867 FieldDifferentInitializers) 9868 << SecondII << SecondInitializer->getSourceRange(); 9869 return true; 9870 } 9871 } 9872 9873 return false; 9874 }; 9875 9876 auto ODRDiagTypeDefOrAlias = 9877 [&ODRDiagDeclError, &ODRDiagDeclNote, &ComputeQualTypeODRHash]( 9878 NamedDecl *FirstRecord, StringRef FirstModule, StringRef SecondModule, 9879 TypedefNameDecl *FirstTD, TypedefNameDecl *SecondTD, 9880 bool IsTypeAlias) { 9881 auto FirstName = FirstTD->getDeclName(); 9882 auto SecondName = SecondTD->getDeclName(); 9883 if (FirstName != SecondName) { 9884 ODRDiagDeclError(FirstRecord, FirstModule, FirstTD->getLocation(), 9885 FirstTD->getSourceRange(), TypedefName) 9886 << IsTypeAlias << FirstName; 9887 ODRDiagDeclNote(SecondModule, SecondTD->getLocation(), 9888 SecondTD->getSourceRange(), TypedefName) 9889 << IsTypeAlias << SecondName; 9890 return true; 9891 } 9892 9893 QualType FirstType = FirstTD->getUnderlyingType(); 9894 QualType SecondType = SecondTD->getUnderlyingType(); 9895 if (ComputeQualTypeODRHash(FirstType) != 9896 ComputeQualTypeODRHash(SecondType)) { 9897 ODRDiagDeclError(FirstRecord, FirstModule, FirstTD->getLocation(), 9898 FirstTD->getSourceRange(), TypedefType) 9899 << IsTypeAlias << FirstName << FirstType; 9900 ODRDiagDeclNote(SecondModule, SecondTD->getLocation(), 9901 SecondTD->getSourceRange(), TypedefType) 9902 << IsTypeAlias << SecondName << SecondType; 9903 return true; 9904 } 9905 9906 return false; 9907 }; 9908 9909 auto ODRDiagVar = [&ODRDiagDeclError, &ODRDiagDeclNote, 9910 &ComputeQualTypeODRHash, &ComputeODRHash, 9911 this](NamedDecl *FirstRecord, StringRef FirstModule, 9912 StringRef SecondModule, VarDecl *FirstVD, 9913 VarDecl *SecondVD) { 9914 auto FirstName = FirstVD->getDeclName(); 9915 auto SecondName = SecondVD->getDeclName(); 9916 if (FirstName != SecondName) { 9917 ODRDiagDeclError(FirstRecord, FirstModule, FirstVD->getLocation(), 9918 FirstVD->getSourceRange(), VarName) 9919 << FirstName; 9920 ODRDiagDeclNote(SecondModule, SecondVD->getLocation(), 9921 SecondVD->getSourceRange(), VarName) 9922 << SecondName; 9923 return true; 9924 } 9925 9926 QualType FirstType = FirstVD->getType(); 9927 QualType SecondType = SecondVD->getType(); 9928 if (ComputeQualTypeODRHash(FirstType) != 9929 ComputeQualTypeODRHash(SecondType)) { 9930 ODRDiagDeclError(FirstRecord, FirstModule, FirstVD->getLocation(), 9931 FirstVD->getSourceRange(), VarType) 9932 << FirstName << FirstType; 9933 ODRDiagDeclNote(SecondModule, SecondVD->getLocation(), 9934 SecondVD->getSourceRange(), VarType) 9935 << SecondName << SecondType; 9936 return true; 9937 } 9938 9939 if (!PP.getLangOpts().CPlusPlus) 9940 return false; 9941 9942 const Expr *FirstInit = FirstVD->getInit(); 9943 const Expr *SecondInit = SecondVD->getInit(); 9944 if ((FirstInit == nullptr) != (SecondInit == nullptr)) { 9945 ODRDiagDeclError(FirstRecord, FirstModule, FirstVD->getLocation(), 9946 FirstVD->getSourceRange(), VarSingleInitializer) 9947 << FirstName << (FirstInit == nullptr) 9948 << (FirstInit ? FirstInit->getSourceRange() : SourceRange()); 9949 ODRDiagDeclNote(SecondModule, SecondVD->getLocation(), 9950 SecondVD->getSourceRange(), VarSingleInitializer) 9951 << SecondName << (SecondInit == nullptr) 9952 << (SecondInit ? SecondInit->getSourceRange() : SourceRange()); 9953 return true; 9954 } 9955 9956 if (FirstInit && SecondInit && 9957 ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) { 9958 ODRDiagDeclError(FirstRecord, FirstModule, FirstVD->getLocation(), 9959 FirstVD->getSourceRange(), VarDifferentInitializer) 9960 << FirstName << FirstInit->getSourceRange(); 9961 ODRDiagDeclNote(SecondModule, SecondVD->getLocation(), 9962 SecondVD->getSourceRange(), VarDifferentInitializer) 9963 << SecondName << SecondInit->getSourceRange(); 9964 return true; 9965 } 9966 9967 const bool FirstIsConstexpr = FirstVD->isConstexpr(); 9968 const bool SecondIsConstexpr = SecondVD->isConstexpr(); 9969 if (FirstIsConstexpr != SecondIsConstexpr) { 9970 ODRDiagDeclError(FirstRecord, FirstModule, FirstVD->getLocation(), 9971 FirstVD->getSourceRange(), VarConstexpr) 9972 << FirstName << FirstIsConstexpr; 9973 ODRDiagDeclNote(SecondModule, SecondVD->getLocation(), 9974 SecondVD->getSourceRange(), VarConstexpr) 9975 << SecondName << SecondIsConstexpr; 9976 return true; 9977 } 9978 return false; 9979 }; 9980 9981 auto DifferenceSelector = [](Decl *D) { 9982 assert(D && "valid Decl required"); 9983 switch (D->getKind()) { 9984 default: 9985 return Other; 9986 case Decl::AccessSpec: 9987 switch (D->getAccess()) { 9988 case AS_public: 9989 return PublicSpecifer; 9990 case AS_private: 9991 return PrivateSpecifer; 9992 case AS_protected: 9993 return ProtectedSpecifer; 9994 case AS_none: 9995 break; 9996 } 9997 llvm_unreachable("Invalid access specifier"); 9998 case Decl::StaticAssert: 9999 return StaticAssert; 10000 case Decl::Field: 10001 return Field; 10002 case Decl::CXXMethod: 10003 case Decl::CXXConstructor: 10004 case Decl::CXXDestructor: 10005 return CXXMethod; 10006 case Decl::TypeAlias: 10007 return TypeAlias; 10008 case Decl::Typedef: 10009 return TypeDef; 10010 case Decl::Var: 10011 return Var; 10012 case Decl::Friend: 10013 return Friend; 10014 case Decl::FunctionTemplate: 10015 return FunctionTemplate; 10016 } 10017 }; 10018 10019 using DeclHashes = llvm::SmallVector<std::pair<Decl *, unsigned>, 4>; 10020 auto PopulateHashes = [&ComputeSubDeclODRHash](DeclHashes &Hashes, 10021 RecordDecl *Record, 10022 const DeclContext *DC) { 10023 for (auto *D : Record->decls()) { 10024 if (!ODRHash::isDeclToBeProcessed(D, DC)) 10025 continue; 10026 Hashes.emplace_back(D, ComputeSubDeclODRHash(D)); 10027 } 10028 }; 10029 10030 struct DiffResult { 10031 Decl *FirstDecl = nullptr, *SecondDecl = nullptr; 10032 ODRMismatchDecl FirstDiffType = Other, SecondDiffType = Other; 10033 }; 10034 10035 // If there is a diagnoseable difference, FirstDiffType and 10036 // SecondDiffType will not be Other and FirstDecl and SecondDecl will be 10037 // filled in if not EndOfClass. 10038 auto FindTypeDiffs = [&DifferenceSelector](DeclHashes &FirstHashes, 10039 DeclHashes &SecondHashes) { 10040 DiffResult DR; 10041 auto FirstIt = FirstHashes.begin(); 10042 auto SecondIt = SecondHashes.begin(); 10043 while (FirstIt != FirstHashes.end() || SecondIt != SecondHashes.end()) { 10044 if (FirstIt != FirstHashes.end() && SecondIt != SecondHashes.end() && 10045 FirstIt->second == SecondIt->second) { 10046 ++FirstIt; 10047 ++SecondIt; 10048 continue; 10049 } 10050 10051 DR.FirstDecl = FirstIt == FirstHashes.end() ? nullptr : FirstIt->first; 10052 DR.SecondDecl = 10053 SecondIt == SecondHashes.end() ? nullptr : SecondIt->first; 10054 10055 DR.FirstDiffType = 10056 DR.FirstDecl ? DifferenceSelector(DR.FirstDecl) : EndOfClass; 10057 DR.SecondDiffType = 10058 DR.SecondDecl ? DifferenceSelector(DR.SecondDecl) : EndOfClass; 10059 return DR; 10060 } 10061 return DR; 10062 }; 10063 10064 // Use this to diagnose that an unexpected Decl was encountered 10065 // or no difference was detected. This causes a generic error 10066 // message to be emitted. 10067 auto DiagnoseODRUnexpected = [this](DiffResult &DR, NamedDecl *FirstRecord, 10068 StringRef FirstModule, 10069 NamedDecl *SecondRecord, 10070 StringRef SecondModule) { 10071 Diag(FirstRecord->getLocation(), 10072 diag::err_module_odr_violation_different_definitions) 10073 << FirstRecord << FirstModule.empty() << FirstModule; 10074 10075 if (DR.FirstDecl) { 10076 Diag(DR.FirstDecl->getLocation(), diag::note_first_module_difference) 10077 << FirstRecord << DR.FirstDecl->getSourceRange(); 10078 } 10079 10080 Diag(SecondRecord->getLocation(), 10081 diag::note_module_odr_violation_different_definitions) 10082 << SecondModule; 10083 10084 if (DR.SecondDecl) { 10085 Diag(DR.SecondDecl->getLocation(), diag::note_second_module_difference) 10086 << DR.SecondDecl->getSourceRange(); 10087 } 10088 }; 10089 10090 auto DiagnoseODRMismatch = 10091 [this](DiffResult &DR, NamedDecl *FirstRecord, StringRef FirstModule, 10092 NamedDecl *SecondRecord, StringRef SecondModule) { 10093 SourceLocation FirstLoc; 10094 SourceRange FirstRange; 10095 auto *FirstTag = dyn_cast<TagDecl>(FirstRecord); 10096 if (DR.FirstDiffType == EndOfClass && FirstTag) { 10097 FirstLoc = FirstTag->getBraceRange().getEnd(); 10098 } else { 10099 FirstLoc = DR.FirstDecl->getLocation(); 10100 FirstRange = DR.FirstDecl->getSourceRange(); 10101 } 10102 Diag(FirstLoc, diag::err_module_odr_violation_mismatch_decl) 10103 << FirstRecord << FirstModule.empty() << FirstModule << FirstRange 10104 << DR.FirstDiffType; 10105 10106 SourceLocation SecondLoc; 10107 SourceRange SecondRange; 10108 auto *SecondTag = dyn_cast<TagDecl>(SecondRecord); 10109 if (DR.SecondDiffType == EndOfClass && SecondTag) { 10110 SecondLoc = SecondTag->getBraceRange().getEnd(); 10111 } else { 10112 SecondLoc = DR.SecondDecl->getLocation(); 10113 SecondRange = DR.SecondDecl->getSourceRange(); 10114 } 10115 Diag(SecondLoc, diag::note_module_odr_violation_mismatch_decl) 10116 << SecondModule << SecondRange << DR.SecondDiffType; 10117 }; 10118 10119 // Issue any pending ODR-failure diagnostics. 10120 for (auto &Merge : OdrMergeFailures) { 10121 // If we've already pointed out a specific problem with this class, don't 10122 // bother issuing a general "something's different" diagnostic. 10123 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second) 10124 continue; 10125 10126 bool Diagnosed = false; 10127 CXXRecordDecl *FirstRecord = Merge.first; 10128 std::string FirstModule = getOwningModuleNameForDiagnostic(FirstRecord); 10129 for (auto &RecordPair : Merge.second) { 10130 CXXRecordDecl *SecondRecord = RecordPair.first; 10131 // Multiple different declarations got merged together; tell the user 10132 // where they came from. 10133 if (FirstRecord == SecondRecord) 10134 continue; 10135 10136 std::string SecondModule = getOwningModuleNameForDiagnostic(SecondRecord); 10137 10138 auto *FirstDD = FirstRecord->DefinitionData; 10139 auto *SecondDD = RecordPair.second; 10140 10141 assert(FirstDD && SecondDD && "Definitions without DefinitionData"); 10142 10143 // Diagnostics from DefinitionData are emitted here. 10144 if (FirstDD != SecondDD) { 10145 enum ODRDefinitionDataDifference { 10146 NumBases, 10147 NumVBases, 10148 BaseType, 10149 BaseVirtual, 10150 BaseAccess, 10151 }; 10152 auto ODRDiagBaseError = [FirstRecord, &FirstModule, 10153 this](SourceLocation Loc, SourceRange Range, 10154 ODRDefinitionDataDifference DiffType) { 10155 return Diag(Loc, diag::err_module_odr_violation_definition_data) 10156 << FirstRecord << FirstModule.empty() << FirstModule << Range 10157 << DiffType; 10158 }; 10159 auto ODRDiagBaseNote = [&SecondModule, 10160 this](SourceLocation Loc, SourceRange Range, 10161 ODRDefinitionDataDifference DiffType) { 10162 return Diag(Loc, diag::note_module_odr_violation_definition_data) 10163 << SecondModule << Range << DiffType; 10164 }; 10165 10166 unsigned FirstNumBases = FirstDD->NumBases; 10167 unsigned FirstNumVBases = FirstDD->NumVBases; 10168 unsigned SecondNumBases = SecondDD->NumBases; 10169 unsigned SecondNumVBases = SecondDD->NumVBases; 10170 10171 auto GetSourceRange = [](struct CXXRecordDecl::DefinitionData *DD) { 10172 unsigned NumBases = DD->NumBases; 10173 if (NumBases == 0) return SourceRange(); 10174 auto bases = DD->bases(); 10175 return SourceRange(bases[0].getBeginLoc(), 10176 bases[NumBases - 1].getEndLoc()); 10177 }; 10178 10179 if (FirstNumBases != SecondNumBases) { 10180 ODRDiagBaseError(FirstRecord->getLocation(), GetSourceRange(FirstDD), 10181 NumBases) 10182 << FirstNumBases; 10183 ODRDiagBaseNote(SecondRecord->getLocation(), GetSourceRange(SecondDD), 10184 NumBases) 10185 << SecondNumBases; 10186 Diagnosed = true; 10187 break; 10188 } 10189 10190 if (FirstNumVBases != SecondNumVBases) { 10191 ODRDiagBaseError(FirstRecord->getLocation(), GetSourceRange(FirstDD), 10192 NumVBases) 10193 << FirstNumVBases; 10194 ODRDiagBaseNote(SecondRecord->getLocation(), GetSourceRange(SecondDD), 10195 NumVBases) 10196 << SecondNumVBases; 10197 Diagnosed = true; 10198 break; 10199 } 10200 10201 auto FirstBases = FirstDD->bases(); 10202 auto SecondBases = SecondDD->bases(); 10203 unsigned i = 0; 10204 for (i = 0; i < FirstNumBases; ++i) { 10205 auto FirstBase = FirstBases[i]; 10206 auto SecondBase = SecondBases[i]; 10207 if (ComputeQualTypeODRHash(FirstBase.getType()) != 10208 ComputeQualTypeODRHash(SecondBase.getType())) { 10209 ODRDiagBaseError(FirstRecord->getLocation(), 10210 FirstBase.getSourceRange(), BaseType) 10211 << (i + 1) << FirstBase.getType(); 10212 ODRDiagBaseNote(SecondRecord->getLocation(), 10213 SecondBase.getSourceRange(), BaseType) 10214 << (i + 1) << SecondBase.getType(); 10215 break; 10216 } 10217 10218 if (FirstBase.isVirtual() != SecondBase.isVirtual()) { 10219 ODRDiagBaseError(FirstRecord->getLocation(), 10220 FirstBase.getSourceRange(), BaseVirtual) 10221 << (i + 1) << FirstBase.isVirtual() << FirstBase.getType(); 10222 ODRDiagBaseNote(SecondRecord->getLocation(), 10223 SecondBase.getSourceRange(), BaseVirtual) 10224 << (i + 1) << SecondBase.isVirtual() << SecondBase.getType(); 10225 break; 10226 } 10227 10228 if (FirstBase.getAccessSpecifierAsWritten() != 10229 SecondBase.getAccessSpecifierAsWritten()) { 10230 ODRDiagBaseError(FirstRecord->getLocation(), 10231 FirstBase.getSourceRange(), BaseAccess) 10232 << (i + 1) << FirstBase.getType() 10233 << (int)FirstBase.getAccessSpecifierAsWritten(); 10234 ODRDiagBaseNote(SecondRecord->getLocation(), 10235 SecondBase.getSourceRange(), BaseAccess) 10236 << (i + 1) << SecondBase.getType() 10237 << (int)SecondBase.getAccessSpecifierAsWritten(); 10238 break; 10239 } 10240 } 10241 10242 if (i != FirstNumBases) { 10243 Diagnosed = true; 10244 break; 10245 } 10246 } 10247 10248 const ClassTemplateDecl *FirstTemplate = 10249 FirstRecord->getDescribedClassTemplate(); 10250 const ClassTemplateDecl *SecondTemplate = 10251 SecondRecord->getDescribedClassTemplate(); 10252 10253 assert(!FirstTemplate == !SecondTemplate && 10254 "Both pointers should be null or non-null"); 10255 10256 enum ODRTemplateDifference { 10257 ParamEmptyName, 10258 ParamName, 10259 ParamSingleDefaultArgument, 10260 ParamDifferentDefaultArgument, 10261 }; 10262 10263 if (FirstTemplate && SecondTemplate) { 10264 DeclHashes FirstTemplateHashes; 10265 DeclHashes SecondTemplateHashes; 10266 10267 auto PopulateTemplateParameterHashs = 10268 [&ComputeSubDeclODRHash](DeclHashes &Hashes, 10269 const ClassTemplateDecl *TD) { 10270 for (auto *D : TD->getTemplateParameters()->asArray()) { 10271 Hashes.emplace_back(D, ComputeSubDeclODRHash(D)); 10272 } 10273 }; 10274 10275 PopulateTemplateParameterHashs(FirstTemplateHashes, FirstTemplate); 10276 PopulateTemplateParameterHashs(SecondTemplateHashes, SecondTemplate); 10277 10278 assert(FirstTemplateHashes.size() == SecondTemplateHashes.size() && 10279 "Number of template parameters should be equal."); 10280 10281 auto FirstIt = FirstTemplateHashes.begin(); 10282 auto FirstEnd = FirstTemplateHashes.end(); 10283 auto SecondIt = SecondTemplateHashes.begin(); 10284 for (; FirstIt != FirstEnd; ++FirstIt, ++SecondIt) { 10285 if (FirstIt->second == SecondIt->second) 10286 continue; 10287 10288 auto ODRDiagTemplateError = [FirstRecord, &FirstModule, this]( 10289 SourceLocation Loc, SourceRange Range, 10290 ODRTemplateDifference DiffType) { 10291 return Diag(Loc, diag::err_module_odr_violation_template_parameter) 10292 << FirstRecord << FirstModule.empty() << FirstModule << Range 10293 << DiffType; 10294 }; 10295 auto ODRDiagTemplateNote = [&SecondModule, this]( 10296 SourceLocation Loc, SourceRange Range, 10297 ODRTemplateDifference DiffType) { 10298 return Diag(Loc, diag::note_module_odr_violation_template_parameter) 10299 << SecondModule << Range << DiffType; 10300 }; 10301 10302 const NamedDecl* FirstDecl = cast<NamedDecl>(FirstIt->first); 10303 const NamedDecl* SecondDecl = cast<NamedDecl>(SecondIt->first); 10304 10305 assert(FirstDecl->getKind() == SecondDecl->getKind() && 10306 "Parameter Decl's should be the same kind."); 10307 10308 DeclarationName FirstName = FirstDecl->getDeclName(); 10309 DeclarationName SecondName = SecondDecl->getDeclName(); 10310 10311 if (FirstName != SecondName) { 10312 const bool FirstNameEmpty = 10313 FirstName.isIdentifier() && !FirstName.getAsIdentifierInfo(); 10314 const bool SecondNameEmpty = 10315 SecondName.isIdentifier() && !SecondName.getAsIdentifierInfo(); 10316 assert((!FirstNameEmpty || !SecondNameEmpty) && 10317 "Both template parameters cannot be unnamed."); 10318 ODRDiagTemplateError(FirstDecl->getLocation(), 10319 FirstDecl->getSourceRange(), 10320 FirstNameEmpty ? ParamEmptyName : ParamName) 10321 << FirstName; 10322 ODRDiagTemplateNote(SecondDecl->getLocation(), 10323 SecondDecl->getSourceRange(), 10324 SecondNameEmpty ? ParamEmptyName : ParamName) 10325 << SecondName; 10326 break; 10327 } 10328 10329 switch (FirstDecl->getKind()) { 10330 default: 10331 llvm_unreachable("Invalid template parameter type."); 10332 case Decl::TemplateTypeParm: { 10333 const auto *FirstParam = cast<TemplateTypeParmDecl>(FirstDecl); 10334 const auto *SecondParam = cast<TemplateTypeParmDecl>(SecondDecl); 10335 const bool HasFirstDefaultArgument = 10336 FirstParam->hasDefaultArgument() && 10337 !FirstParam->defaultArgumentWasInherited(); 10338 const bool HasSecondDefaultArgument = 10339 SecondParam->hasDefaultArgument() && 10340 !SecondParam->defaultArgumentWasInherited(); 10341 10342 if (HasFirstDefaultArgument != HasSecondDefaultArgument) { 10343 ODRDiagTemplateError(FirstDecl->getLocation(), 10344 FirstDecl->getSourceRange(), 10345 ParamSingleDefaultArgument) 10346 << HasFirstDefaultArgument; 10347 ODRDiagTemplateNote(SecondDecl->getLocation(), 10348 SecondDecl->getSourceRange(), 10349 ParamSingleDefaultArgument) 10350 << HasSecondDefaultArgument; 10351 break; 10352 } 10353 10354 assert(HasFirstDefaultArgument && HasSecondDefaultArgument && 10355 "Expecting default arguments."); 10356 10357 ODRDiagTemplateError(FirstDecl->getLocation(), 10358 FirstDecl->getSourceRange(), 10359 ParamDifferentDefaultArgument); 10360 ODRDiagTemplateNote(SecondDecl->getLocation(), 10361 SecondDecl->getSourceRange(), 10362 ParamDifferentDefaultArgument); 10363 10364 break; 10365 } 10366 case Decl::NonTypeTemplateParm: { 10367 const auto *FirstParam = cast<NonTypeTemplateParmDecl>(FirstDecl); 10368 const auto *SecondParam = cast<NonTypeTemplateParmDecl>(SecondDecl); 10369 const bool HasFirstDefaultArgument = 10370 FirstParam->hasDefaultArgument() && 10371 !FirstParam->defaultArgumentWasInherited(); 10372 const bool HasSecondDefaultArgument = 10373 SecondParam->hasDefaultArgument() && 10374 !SecondParam->defaultArgumentWasInherited(); 10375 10376 if (HasFirstDefaultArgument != HasSecondDefaultArgument) { 10377 ODRDiagTemplateError(FirstDecl->getLocation(), 10378 FirstDecl->getSourceRange(), 10379 ParamSingleDefaultArgument) 10380 << HasFirstDefaultArgument; 10381 ODRDiagTemplateNote(SecondDecl->getLocation(), 10382 SecondDecl->getSourceRange(), 10383 ParamSingleDefaultArgument) 10384 << HasSecondDefaultArgument; 10385 break; 10386 } 10387 10388 assert(HasFirstDefaultArgument && HasSecondDefaultArgument && 10389 "Expecting default arguments."); 10390 10391 ODRDiagTemplateError(FirstDecl->getLocation(), 10392 FirstDecl->getSourceRange(), 10393 ParamDifferentDefaultArgument); 10394 ODRDiagTemplateNote(SecondDecl->getLocation(), 10395 SecondDecl->getSourceRange(), 10396 ParamDifferentDefaultArgument); 10397 10398 break; 10399 } 10400 case Decl::TemplateTemplateParm: { 10401 const auto *FirstParam = cast<TemplateTemplateParmDecl>(FirstDecl); 10402 const auto *SecondParam = 10403 cast<TemplateTemplateParmDecl>(SecondDecl); 10404 const bool HasFirstDefaultArgument = 10405 FirstParam->hasDefaultArgument() && 10406 !FirstParam->defaultArgumentWasInherited(); 10407 const bool HasSecondDefaultArgument = 10408 SecondParam->hasDefaultArgument() && 10409 !SecondParam->defaultArgumentWasInherited(); 10410 10411 if (HasFirstDefaultArgument != HasSecondDefaultArgument) { 10412 ODRDiagTemplateError(FirstDecl->getLocation(), 10413 FirstDecl->getSourceRange(), 10414 ParamSingleDefaultArgument) 10415 << HasFirstDefaultArgument; 10416 ODRDiagTemplateNote(SecondDecl->getLocation(), 10417 SecondDecl->getSourceRange(), 10418 ParamSingleDefaultArgument) 10419 << HasSecondDefaultArgument; 10420 break; 10421 } 10422 10423 assert(HasFirstDefaultArgument && HasSecondDefaultArgument && 10424 "Expecting default arguments."); 10425 10426 ODRDiagTemplateError(FirstDecl->getLocation(), 10427 FirstDecl->getSourceRange(), 10428 ParamDifferentDefaultArgument); 10429 ODRDiagTemplateNote(SecondDecl->getLocation(), 10430 SecondDecl->getSourceRange(), 10431 ParamDifferentDefaultArgument); 10432 10433 break; 10434 } 10435 } 10436 10437 break; 10438 } 10439 10440 if (FirstIt != FirstEnd) { 10441 Diagnosed = true; 10442 break; 10443 } 10444 } 10445 10446 DeclHashes FirstHashes; 10447 DeclHashes SecondHashes; 10448 const DeclContext *DC = FirstRecord; 10449 PopulateHashes(FirstHashes, FirstRecord, DC); 10450 PopulateHashes(SecondHashes, SecondRecord, DC); 10451 10452 auto DR = FindTypeDiffs(FirstHashes, SecondHashes); 10453 ODRMismatchDecl FirstDiffType = DR.FirstDiffType; 10454 ODRMismatchDecl SecondDiffType = DR.SecondDiffType; 10455 Decl *FirstDecl = DR.FirstDecl; 10456 Decl *SecondDecl = DR.SecondDecl; 10457 10458 if (FirstDiffType == Other || SecondDiffType == Other) { 10459 DiagnoseODRUnexpected(DR, FirstRecord, FirstModule, SecondRecord, 10460 SecondModule); 10461 Diagnosed = true; 10462 break; 10463 } 10464 10465 if (FirstDiffType != SecondDiffType) { 10466 DiagnoseODRMismatch(DR, FirstRecord, FirstModule, SecondRecord, 10467 SecondModule); 10468 Diagnosed = true; 10469 break; 10470 } 10471 10472 assert(FirstDiffType == SecondDiffType); 10473 10474 switch (FirstDiffType) { 10475 case Other: 10476 case EndOfClass: 10477 case PublicSpecifer: 10478 case PrivateSpecifer: 10479 case ProtectedSpecifer: 10480 llvm_unreachable("Invalid diff type"); 10481 10482 case StaticAssert: { 10483 StaticAssertDecl *FirstSA = cast<StaticAssertDecl>(FirstDecl); 10484 StaticAssertDecl *SecondSA = cast<StaticAssertDecl>(SecondDecl); 10485 10486 Expr *FirstExpr = FirstSA->getAssertExpr(); 10487 Expr *SecondExpr = SecondSA->getAssertExpr(); 10488 unsigned FirstODRHash = ComputeODRHash(FirstExpr); 10489 unsigned SecondODRHash = ComputeODRHash(SecondExpr); 10490 if (FirstODRHash != SecondODRHash) { 10491 ODRDiagDeclError(FirstRecord, FirstModule, FirstExpr->getBeginLoc(), 10492 FirstExpr->getSourceRange(), StaticAssertCondition); 10493 ODRDiagDeclNote(SecondModule, SecondExpr->getBeginLoc(), 10494 SecondExpr->getSourceRange(), StaticAssertCondition); 10495 Diagnosed = true; 10496 break; 10497 } 10498 10499 StringLiteral *FirstStr = FirstSA->getMessage(); 10500 StringLiteral *SecondStr = SecondSA->getMessage(); 10501 assert((FirstStr || SecondStr) && "Both messages cannot be empty"); 10502 if ((FirstStr && !SecondStr) || (!FirstStr && SecondStr)) { 10503 SourceLocation FirstLoc, SecondLoc; 10504 SourceRange FirstRange, SecondRange; 10505 if (FirstStr) { 10506 FirstLoc = FirstStr->getBeginLoc(); 10507 FirstRange = FirstStr->getSourceRange(); 10508 } else { 10509 FirstLoc = FirstSA->getBeginLoc(); 10510 FirstRange = FirstSA->getSourceRange(); 10511 } 10512 if (SecondStr) { 10513 SecondLoc = SecondStr->getBeginLoc(); 10514 SecondRange = SecondStr->getSourceRange(); 10515 } else { 10516 SecondLoc = SecondSA->getBeginLoc(); 10517 SecondRange = SecondSA->getSourceRange(); 10518 } 10519 ODRDiagDeclError(FirstRecord, FirstModule, FirstLoc, FirstRange, 10520 StaticAssertOnlyMessage) 10521 << (FirstStr == nullptr); 10522 ODRDiagDeclNote(SecondModule, SecondLoc, SecondRange, 10523 StaticAssertOnlyMessage) 10524 << (SecondStr == nullptr); 10525 Diagnosed = true; 10526 break; 10527 } 10528 10529 if (FirstStr && SecondStr && 10530 FirstStr->getString() != SecondStr->getString()) { 10531 ODRDiagDeclError(FirstRecord, FirstModule, FirstStr->getBeginLoc(), 10532 FirstStr->getSourceRange(), StaticAssertMessage); 10533 ODRDiagDeclNote(SecondModule, SecondStr->getBeginLoc(), 10534 SecondStr->getSourceRange(), StaticAssertMessage); 10535 Diagnosed = true; 10536 break; 10537 } 10538 break; 10539 } 10540 case Field: { 10541 Diagnosed = ODRDiagField(FirstRecord, FirstModule, SecondModule, 10542 cast<FieldDecl>(FirstDecl), 10543 cast<FieldDecl>(SecondDecl)); 10544 break; 10545 } 10546 case CXXMethod: { 10547 enum { 10548 DiagMethod, 10549 DiagConstructor, 10550 DiagDestructor, 10551 } FirstMethodType, 10552 SecondMethodType; 10553 auto GetMethodTypeForDiagnostics = [](const CXXMethodDecl* D) { 10554 if (isa<CXXConstructorDecl>(D)) return DiagConstructor; 10555 if (isa<CXXDestructorDecl>(D)) return DiagDestructor; 10556 return DiagMethod; 10557 }; 10558 const CXXMethodDecl *FirstMethod = cast<CXXMethodDecl>(FirstDecl); 10559 const CXXMethodDecl *SecondMethod = cast<CXXMethodDecl>(SecondDecl); 10560 FirstMethodType = GetMethodTypeForDiagnostics(FirstMethod); 10561 SecondMethodType = GetMethodTypeForDiagnostics(SecondMethod); 10562 auto FirstName = FirstMethod->getDeclName(); 10563 auto SecondName = SecondMethod->getDeclName(); 10564 if (FirstMethodType != SecondMethodType || FirstName != SecondName) { 10565 ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(), 10566 FirstMethod->getSourceRange(), MethodName) 10567 << FirstMethodType << FirstName; 10568 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(), 10569 SecondMethod->getSourceRange(), MethodName) 10570 << SecondMethodType << SecondName; 10571 10572 Diagnosed = true; 10573 break; 10574 } 10575 10576 const bool FirstDeleted = FirstMethod->isDeletedAsWritten(); 10577 const bool SecondDeleted = SecondMethod->isDeletedAsWritten(); 10578 if (FirstDeleted != SecondDeleted) { 10579 ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(), 10580 FirstMethod->getSourceRange(), MethodDeleted) 10581 << FirstMethodType << FirstName << FirstDeleted; 10582 10583 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(), 10584 SecondMethod->getSourceRange(), MethodDeleted) 10585 << SecondMethodType << SecondName << SecondDeleted; 10586 Diagnosed = true; 10587 break; 10588 } 10589 10590 const bool FirstDefaulted = FirstMethod->isExplicitlyDefaulted(); 10591 const bool SecondDefaulted = SecondMethod->isExplicitlyDefaulted(); 10592 if (FirstDefaulted != SecondDefaulted) { 10593 ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(), 10594 FirstMethod->getSourceRange(), MethodDefaulted) 10595 << FirstMethodType << FirstName << FirstDefaulted; 10596 10597 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(), 10598 SecondMethod->getSourceRange(), MethodDefaulted) 10599 << SecondMethodType << SecondName << SecondDefaulted; 10600 Diagnosed = true; 10601 break; 10602 } 10603 10604 const bool FirstVirtual = FirstMethod->isVirtualAsWritten(); 10605 const bool SecondVirtual = SecondMethod->isVirtualAsWritten(); 10606 const bool FirstPure = FirstMethod->isPure(); 10607 const bool SecondPure = SecondMethod->isPure(); 10608 if ((FirstVirtual || SecondVirtual) && 10609 (FirstVirtual != SecondVirtual || FirstPure != SecondPure)) { 10610 ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(), 10611 FirstMethod->getSourceRange(), MethodVirtual) 10612 << FirstMethodType << FirstName << FirstPure << FirstVirtual; 10613 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(), 10614 SecondMethod->getSourceRange(), MethodVirtual) 10615 << SecondMethodType << SecondName << SecondPure << SecondVirtual; 10616 Diagnosed = true; 10617 break; 10618 } 10619 10620 // CXXMethodDecl::isStatic uses the canonical Decl. With Decl merging, 10621 // FirstDecl is the canonical Decl of SecondDecl, so the storage 10622 // class needs to be checked instead. 10623 const auto FirstStorage = FirstMethod->getStorageClass(); 10624 const auto SecondStorage = SecondMethod->getStorageClass(); 10625 const bool FirstStatic = FirstStorage == SC_Static; 10626 const bool SecondStatic = SecondStorage == SC_Static; 10627 if (FirstStatic != SecondStatic) { 10628 ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(), 10629 FirstMethod->getSourceRange(), MethodStatic) 10630 << FirstMethodType << FirstName << FirstStatic; 10631 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(), 10632 SecondMethod->getSourceRange(), MethodStatic) 10633 << SecondMethodType << SecondName << SecondStatic; 10634 Diagnosed = true; 10635 break; 10636 } 10637 10638 const bool FirstVolatile = FirstMethod->isVolatile(); 10639 const bool SecondVolatile = SecondMethod->isVolatile(); 10640 if (FirstVolatile != SecondVolatile) { 10641 ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(), 10642 FirstMethod->getSourceRange(), MethodVolatile) 10643 << FirstMethodType << FirstName << FirstVolatile; 10644 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(), 10645 SecondMethod->getSourceRange(), MethodVolatile) 10646 << SecondMethodType << SecondName << SecondVolatile; 10647 Diagnosed = true; 10648 break; 10649 } 10650 10651 const bool FirstConst = FirstMethod->isConst(); 10652 const bool SecondConst = SecondMethod->isConst(); 10653 if (FirstConst != SecondConst) { 10654 ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(), 10655 FirstMethod->getSourceRange(), MethodConst) 10656 << FirstMethodType << FirstName << FirstConst; 10657 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(), 10658 SecondMethod->getSourceRange(), MethodConst) 10659 << SecondMethodType << SecondName << SecondConst; 10660 Diagnosed = true; 10661 break; 10662 } 10663 10664 const bool FirstInline = FirstMethod->isInlineSpecified(); 10665 const bool SecondInline = SecondMethod->isInlineSpecified(); 10666 if (FirstInline != SecondInline) { 10667 ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(), 10668 FirstMethod->getSourceRange(), MethodInline) 10669 << FirstMethodType << FirstName << FirstInline; 10670 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(), 10671 SecondMethod->getSourceRange(), MethodInline) 10672 << SecondMethodType << SecondName << SecondInline; 10673 Diagnosed = true; 10674 break; 10675 } 10676 10677 const unsigned FirstNumParameters = FirstMethod->param_size(); 10678 const unsigned SecondNumParameters = SecondMethod->param_size(); 10679 if (FirstNumParameters != SecondNumParameters) { 10680 ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(), 10681 FirstMethod->getSourceRange(), 10682 MethodNumberParameters) 10683 << FirstMethodType << FirstName << FirstNumParameters; 10684 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(), 10685 SecondMethod->getSourceRange(), 10686 MethodNumberParameters) 10687 << SecondMethodType << SecondName << SecondNumParameters; 10688 Diagnosed = true; 10689 break; 10690 } 10691 10692 // Need this status boolean to know when break out of the switch. 10693 bool ParameterMismatch = false; 10694 for (unsigned I = 0; I < FirstNumParameters; ++I) { 10695 const ParmVarDecl *FirstParam = FirstMethod->getParamDecl(I); 10696 const ParmVarDecl *SecondParam = SecondMethod->getParamDecl(I); 10697 10698 QualType FirstParamType = FirstParam->getType(); 10699 QualType SecondParamType = SecondParam->getType(); 10700 if (FirstParamType != SecondParamType && 10701 ComputeQualTypeODRHash(FirstParamType) != 10702 ComputeQualTypeODRHash(SecondParamType)) { 10703 if (const DecayedType *ParamDecayedType = 10704 FirstParamType->getAs<DecayedType>()) { 10705 ODRDiagDeclError( 10706 FirstRecord, FirstModule, FirstMethod->getLocation(), 10707 FirstMethod->getSourceRange(), MethodParameterType) 10708 << FirstMethodType << FirstName << (I + 1) << FirstParamType 10709 << true << ParamDecayedType->getOriginalType(); 10710 } else { 10711 ODRDiagDeclError( 10712 FirstRecord, FirstModule, FirstMethod->getLocation(), 10713 FirstMethod->getSourceRange(), MethodParameterType) 10714 << FirstMethodType << FirstName << (I + 1) << FirstParamType 10715 << false; 10716 } 10717 10718 if (const DecayedType *ParamDecayedType = 10719 SecondParamType->getAs<DecayedType>()) { 10720 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(), 10721 SecondMethod->getSourceRange(), 10722 MethodParameterType) 10723 << SecondMethodType << SecondName << (I + 1) 10724 << SecondParamType << true 10725 << ParamDecayedType->getOriginalType(); 10726 } else { 10727 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(), 10728 SecondMethod->getSourceRange(), 10729 MethodParameterType) 10730 << SecondMethodType << SecondName << (I + 1) 10731 << SecondParamType << false; 10732 } 10733 ParameterMismatch = true; 10734 break; 10735 } 10736 10737 DeclarationName FirstParamName = FirstParam->getDeclName(); 10738 DeclarationName SecondParamName = SecondParam->getDeclName(); 10739 if (FirstParamName != SecondParamName) { 10740 ODRDiagDeclError(FirstRecord, FirstModule, 10741 FirstMethod->getLocation(), 10742 FirstMethod->getSourceRange(), MethodParameterName) 10743 << FirstMethodType << FirstName << (I + 1) << FirstParamName; 10744 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(), 10745 SecondMethod->getSourceRange(), MethodParameterName) 10746 << SecondMethodType << SecondName << (I + 1) << SecondParamName; 10747 ParameterMismatch = true; 10748 break; 10749 } 10750 10751 const Expr *FirstInit = FirstParam->getInit(); 10752 const Expr *SecondInit = SecondParam->getInit(); 10753 if ((FirstInit == nullptr) != (SecondInit == nullptr)) { 10754 ODRDiagDeclError(FirstRecord, FirstModule, 10755 FirstMethod->getLocation(), 10756 FirstMethod->getSourceRange(), 10757 MethodParameterSingleDefaultArgument) 10758 << FirstMethodType << FirstName << (I + 1) 10759 << (FirstInit == nullptr) 10760 << (FirstInit ? FirstInit->getSourceRange() : SourceRange()); 10761 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(), 10762 SecondMethod->getSourceRange(), 10763 MethodParameterSingleDefaultArgument) 10764 << SecondMethodType << SecondName << (I + 1) 10765 << (SecondInit == nullptr) 10766 << (SecondInit ? SecondInit->getSourceRange() : SourceRange()); 10767 ParameterMismatch = true; 10768 break; 10769 } 10770 10771 if (FirstInit && SecondInit && 10772 ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) { 10773 ODRDiagDeclError(FirstRecord, FirstModule, 10774 FirstMethod->getLocation(), 10775 FirstMethod->getSourceRange(), 10776 MethodParameterDifferentDefaultArgument) 10777 << FirstMethodType << FirstName << (I + 1) 10778 << FirstInit->getSourceRange(); 10779 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(), 10780 SecondMethod->getSourceRange(), 10781 MethodParameterDifferentDefaultArgument) 10782 << SecondMethodType << SecondName << (I + 1) 10783 << SecondInit->getSourceRange(); 10784 ParameterMismatch = true; 10785 break; 10786 10787 } 10788 } 10789 10790 if (ParameterMismatch) { 10791 Diagnosed = true; 10792 break; 10793 } 10794 10795 const auto *FirstTemplateArgs = 10796 FirstMethod->getTemplateSpecializationArgs(); 10797 const auto *SecondTemplateArgs = 10798 SecondMethod->getTemplateSpecializationArgs(); 10799 10800 if ((FirstTemplateArgs && !SecondTemplateArgs) || 10801 (!FirstTemplateArgs && SecondTemplateArgs)) { 10802 ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(), 10803 FirstMethod->getSourceRange(), 10804 MethodNoTemplateArguments) 10805 << FirstMethodType << FirstName << (FirstTemplateArgs != nullptr); 10806 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(), 10807 SecondMethod->getSourceRange(), 10808 MethodNoTemplateArguments) 10809 << SecondMethodType << SecondName 10810 << (SecondTemplateArgs != nullptr); 10811 10812 Diagnosed = true; 10813 break; 10814 } 10815 10816 if (FirstTemplateArgs && SecondTemplateArgs) { 10817 // Remove pack expansions from argument list. 10818 auto ExpandTemplateArgumentList = 10819 [](const TemplateArgumentList *TAL) { 10820 llvm::SmallVector<const TemplateArgument *, 8> ExpandedList; 10821 for (const TemplateArgument &TA : TAL->asArray()) { 10822 if (TA.getKind() != TemplateArgument::Pack) { 10823 ExpandedList.push_back(&TA); 10824 continue; 10825 } 10826 for (const TemplateArgument &PackTA : TA.getPackAsArray()) { 10827 ExpandedList.push_back(&PackTA); 10828 } 10829 } 10830 return ExpandedList; 10831 }; 10832 llvm::SmallVector<const TemplateArgument *, 8> FirstExpandedList = 10833 ExpandTemplateArgumentList(FirstTemplateArgs); 10834 llvm::SmallVector<const TemplateArgument *, 8> SecondExpandedList = 10835 ExpandTemplateArgumentList(SecondTemplateArgs); 10836 10837 if (FirstExpandedList.size() != SecondExpandedList.size()) { 10838 ODRDiagDeclError(FirstRecord, FirstModule, 10839 FirstMethod->getLocation(), 10840 FirstMethod->getSourceRange(), 10841 MethodDifferentNumberTemplateArguments) 10842 << FirstMethodType << FirstName 10843 << (unsigned)FirstExpandedList.size(); 10844 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(), 10845 SecondMethod->getSourceRange(), 10846 MethodDifferentNumberTemplateArguments) 10847 << SecondMethodType << SecondName 10848 << (unsigned)SecondExpandedList.size(); 10849 10850 Diagnosed = true; 10851 break; 10852 } 10853 10854 bool TemplateArgumentMismatch = false; 10855 for (unsigned i = 0, e = FirstExpandedList.size(); i != e; ++i) { 10856 const TemplateArgument &FirstTA = *FirstExpandedList[i], 10857 &SecondTA = *SecondExpandedList[i]; 10858 if (ComputeTemplateArgumentODRHash(FirstTA) == 10859 ComputeTemplateArgumentODRHash(SecondTA)) { 10860 continue; 10861 } 10862 10863 ODRDiagDeclError( 10864 FirstRecord, FirstModule, FirstMethod->getLocation(), 10865 FirstMethod->getSourceRange(), MethodDifferentTemplateArgument) 10866 << FirstMethodType << FirstName << FirstTA << i + 1; 10867 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(), 10868 SecondMethod->getSourceRange(), 10869 MethodDifferentTemplateArgument) 10870 << SecondMethodType << SecondName << SecondTA << i + 1; 10871 10872 TemplateArgumentMismatch = true; 10873 break; 10874 } 10875 10876 if (TemplateArgumentMismatch) { 10877 Diagnosed = true; 10878 break; 10879 } 10880 } 10881 10882 // Compute the hash of the method as if it has no body. 10883 auto ComputeCXXMethodODRHash = [&Hash](const CXXMethodDecl *D) { 10884 Hash.clear(); 10885 Hash.AddFunctionDecl(D, true /*SkipBody*/); 10886 return Hash.CalculateHash(); 10887 }; 10888 10889 // Compare the hash generated to the hash stored. A difference means 10890 // that a body was present in the original source. Due to merging, 10891 // the stardard way of detecting a body will not work. 10892 const bool HasFirstBody = 10893 ComputeCXXMethodODRHash(FirstMethod) != FirstMethod->getODRHash(); 10894 const bool HasSecondBody = 10895 ComputeCXXMethodODRHash(SecondMethod) != SecondMethod->getODRHash(); 10896 10897 if (HasFirstBody != HasSecondBody) { 10898 ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(), 10899 FirstMethod->getSourceRange(), MethodSingleBody) 10900 << FirstMethodType << FirstName << HasFirstBody; 10901 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(), 10902 SecondMethod->getSourceRange(), MethodSingleBody) 10903 << SecondMethodType << SecondName << HasSecondBody; 10904 Diagnosed = true; 10905 break; 10906 } 10907 10908 if (HasFirstBody && HasSecondBody) { 10909 ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(), 10910 FirstMethod->getSourceRange(), MethodDifferentBody) 10911 << FirstMethodType << FirstName; 10912 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(), 10913 SecondMethod->getSourceRange(), MethodDifferentBody) 10914 << SecondMethodType << SecondName; 10915 Diagnosed = true; 10916 break; 10917 } 10918 10919 break; 10920 } 10921 case TypeAlias: 10922 case TypeDef: { 10923 Diagnosed = ODRDiagTypeDefOrAlias( 10924 FirstRecord, FirstModule, SecondModule, 10925 cast<TypedefNameDecl>(FirstDecl), cast<TypedefNameDecl>(SecondDecl), 10926 FirstDiffType == TypeAlias); 10927 break; 10928 } 10929 case Var: { 10930 Diagnosed = 10931 ODRDiagVar(FirstRecord, FirstModule, SecondModule, 10932 cast<VarDecl>(FirstDecl), cast<VarDecl>(SecondDecl)); 10933 break; 10934 } 10935 case Friend: { 10936 FriendDecl *FirstFriend = cast<FriendDecl>(FirstDecl); 10937 FriendDecl *SecondFriend = cast<FriendDecl>(SecondDecl); 10938 10939 NamedDecl *FirstND = FirstFriend->getFriendDecl(); 10940 NamedDecl *SecondND = SecondFriend->getFriendDecl(); 10941 10942 TypeSourceInfo *FirstTSI = FirstFriend->getFriendType(); 10943 TypeSourceInfo *SecondTSI = SecondFriend->getFriendType(); 10944 10945 if (FirstND && SecondND) { 10946 ODRDiagDeclError(FirstRecord, FirstModule, 10947 FirstFriend->getFriendLoc(), 10948 FirstFriend->getSourceRange(), FriendFunction) 10949 << FirstND; 10950 ODRDiagDeclNote(SecondModule, SecondFriend->getFriendLoc(), 10951 SecondFriend->getSourceRange(), FriendFunction) 10952 << SecondND; 10953 10954 Diagnosed = true; 10955 break; 10956 } 10957 10958 if (FirstTSI && SecondTSI) { 10959 QualType FirstFriendType = FirstTSI->getType(); 10960 QualType SecondFriendType = SecondTSI->getType(); 10961 assert(ComputeQualTypeODRHash(FirstFriendType) != 10962 ComputeQualTypeODRHash(SecondFriendType)); 10963 ODRDiagDeclError(FirstRecord, FirstModule, 10964 FirstFriend->getFriendLoc(), 10965 FirstFriend->getSourceRange(), FriendType) 10966 << FirstFriendType; 10967 ODRDiagDeclNote(SecondModule, SecondFriend->getFriendLoc(), 10968 SecondFriend->getSourceRange(), FriendType) 10969 << SecondFriendType; 10970 Diagnosed = true; 10971 break; 10972 } 10973 10974 ODRDiagDeclError(FirstRecord, FirstModule, FirstFriend->getFriendLoc(), 10975 FirstFriend->getSourceRange(), FriendTypeFunction) 10976 << (FirstTSI == nullptr); 10977 ODRDiagDeclNote(SecondModule, SecondFriend->getFriendLoc(), 10978 SecondFriend->getSourceRange(), FriendTypeFunction) 10979 << (SecondTSI == nullptr); 10980 10981 Diagnosed = true; 10982 break; 10983 } 10984 case FunctionTemplate: { 10985 FunctionTemplateDecl *FirstTemplate = 10986 cast<FunctionTemplateDecl>(FirstDecl); 10987 FunctionTemplateDecl *SecondTemplate = 10988 cast<FunctionTemplateDecl>(SecondDecl); 10989 10990 TemplateParameterList *FirstTPL = 10991 FirstTemplate->getTemplateParameters(); 10992 TemplateParameterList *SecondTPL = 10993 SecondTemplate->getTemplateParameters(); 10994 10995 if (FirstTPL->size() != SecondTPL->size()) { 10996 ODRDiagDeclError(FirstRecord, FirstModule, 10997 FirstTemplate->getLocation(), 10998 FirstTemplate->getSourceRange(), 10999 FunctionTemplateDifferentNumberParameters) 11000 << FirstTemplate << FirstTPL->size(); 11001 ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(), 11002 SecondTemplate->getSourceRange(), 11003 FunctionTemplateDifferentNumberParameters) 11004 << SecondTemplate << SecondTPL->size(); 11005 11006 Diagnosed = true; 11007 break; 11008 } 11009 11010 bool ParameterMismatch = false; 11011 for (unsigned i = 0, e = FirstTPL->size(); i != e; ++i) { 11012 NamedDecl *FirstParam = FirstTPL->getParam(i); 11013 NamedDecl *SecondParam = SecondTPL->getParam(i); 11014 11015 if (FirstParam->getKind() != SecondParam->getKind()) { 11016 enum { 11017 TemplateTypeParameter, 11018 NonTypeTemplateParameter, 11019 TemplateTemplateParameter, 11020 }; 11021 auto GetParamType = [](NamedDecl *D) { 11022 switch (D->getKind()) { 11023 default: 11024 llvm_unreachable("Unexpected template parameter type"); 11025 case Decl::TemplateTypeParm: 11026 return TemplateTypeParameter; 11027 case Decl::NonTypeTemplateParm: 11028 return NonTypeTemplateParameter; 11029 case Decl::TemplateTemplateParm: 11030 return TemplateTemplateParameter; 11031 } 11032 }; 11033 11034 ODRDiagDeclError(FirstRecord, FirstModule, 11035 FirstTemplate->getLocation(), 11036 FirstTemplate->getSourceRange(), 11037 FunctionTemplateParameterDifferentKind) 11038 << FirstTemplate << (i + 1) << GetParamType(FirstParam); 11039 ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(), 11040 SecondTemplate->getSourceRange(), 11041 FunctionTemplateParameterDifferentKind) 11042 << SecondTemplate << (i + 1) << GetParamType(SecondParam); 11043 11044 ParameterMismatch = true; 11045 break; 11046 } 11047 11048 if (FirstParam->getName() != SecondParam->getName()) { 11049 ODRDiagDeclError( 11050 FirstRecord, FirstModule, FirstTemplate->getLocation(), 11051 FirstTemplate->getSourceRange(), FunctionTemplateParameterName) 11052 << FirstTemplate << (i + 1) << (bool)FirstParam->getIdentifier() 11053 << FirstParam; 11054 ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(), 11055 SecondTemplate->getSourceRange(), 11056 FunctionTemplateParameterName) 11057 << SecondTemplate << (i + 1) 11058 << (bool)SecondParam->getIdentifier() << SecondParam; 11059 ParameterMismatch = true; 11060 break; 11061 } 11062 11063 if (isa<TemplateTypeParmDecl>(FirstParam) && 11064 isa<TemplateTypeParmDecl>(SecondParam)) { 11065 TemplateTypeParmDecl *FirstTTPD = 11066 cast<TemplateTypeParmDecl>(FirstParam); 11067 TemplateTypeParmDecl *SecondTTPD = 11068 cast<TemplateTypeParmDecl>(SecondParam); 11069 bool HasFirstDefaultArgument = 11070 FirstTTPD->hasDefaultArgument() && 11071 !FirstTTPD->defaultArgumentWasInherited(); 11072 bool HasSecondDefaultArgument = 11073 SecondTTPD->hasDefaultArgument() && 11074 !SecondTTPD->defaultArgumentWasInherited(); 11075 if (HasFirstDefaultArgument != HasSecondDefaultArgument) { 11076 ODRDiagDeclError(FirstRecord, FirstModule, 11077 FirstTemplate->getLocation(), 11078 FirstTemplate->getSourceRange(), 11079 FunctionTemplateParameterSingleDefaultArgument) 11080 << FirstTemplate << (i + 1) << HasFirstDefaultArgument; 11081 ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(), 11082 SecondTemplate->getSourceRange(), 11083 FunctionTemplateParameterSingleDefaultArgument) 11084 << SecondTemplate << (i + 1) << HasSecondDefaultArgument; 11085 ParameterMismatch = true; 11086 break; 11087 } 11088 11089 if (HasFirstDefaultArgument && HasSecondDefaultArgument) { 11090 QualType FirstType = FirstTTPD->getDefaultArgument(); 11091 QualType SecondType = SecondTTPD->getDefaultArgument(); 11092 if (ComputeQualTypeODRHash(FirstType) != 11093 ComputeQualTypeODRHash(SecondType)) { 11094 ODRDiagDeclError( 11095 FirstRecord, FirstModule, FirstTemplate->getLocation(), 11096 FirstTemplate->getSourceRange(), 11097 FunctionTemplateParameterDifferentDefaultArgument) 11098 << FirstTemplate << (i + 1) << FirstType; 11099 ODRDiagDeclNote( 11100 SecondModule, SecondTemplate->getLocation(), 11101 SecondTemplate->getSourceRange(), 11102 FunctionTemplateParameterDifferentDefaultArgument) 11103 << SecondTemplate << (i + 1) << SecondType; 11104 ParameterMismatch = true; 11105 break; 11106 } 11107 } 11108 11109 if (FirstTTPD->isParameterPack() != 11110 SecondTTPD->isParameterPack()) { 11111 ODRDiagDeclError(FirstRecord, FirstModule, 11112 FirstTemplate->getLocation(), 11113 FirstTemplate->getSourceRange(), 11114 FunctionTemplatePackParameter) 11115 << FirstTemplate << (i + 1) << FirstTTPD->isParameterPack(); 11116 ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(), 11117 SecondTemplate->getSourceRange(), 11118 FunctionTemplatePackParameter) 11119 << SecondTemplate << (i + 1) << SecondTTPD->isParameterPack(); 11120 ParameterMismatch = true; 11121 break; 11122 } 11123 } 11124 11125 if (isa<TemplateTemplateParmDecl>(FirstParam) && 11126 isa<TemplateTemplateParmDecl>(SecondParam)) { 11127 TemplateTemplateParmDecl *FirstTTPD = 11128 cast<TemplateTemplateParmDecl>(FirstParam); 11129 TemplateTemplateParmDecl *SecondTTPD = 11130 cast<TemplateTemplateParmDecl>(SecondParam); 11131 11132 TemplateParameterList *FirstTPL = 11133 FirstTTPD->getTemplateParameters(); 11134 TemplateParameterList *SecondTPL = 11135 SecondTTPD->getTemplateParameters(); 11136 11137 if (ComputeTemplateParameterListODRHash(FirstTPL) != 11138 ComputeTemplateParameterListODRHash(SecondTPL)) { 11139 ODRDiagDeclError(FirstRecord, FirstModule, 11140 FirstTemplate->getLocation(), 11141 FirstTemplate->getSourceRange(), 11142 FunctionTemplateParameterDifferentType) 11143 << FirstTemplate << (i + 1); 11144 ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(), 11145 SecondTemplate->getSourceRange(), 11146 FunctionTemplateParameterDifferentType) 11147 << SecondTemplate << (i + 1); 11148 ParameterMismatch = true; 11149 break; 11150 } 11151 11152 bool HasFirstDefaultArgument = 11153 FirstTTPD->hasDefaultArgument() && 11154 !FirstTTPD->defaultArgumentWasInherited(); 11155 bool HasSecondDefaultArgument = 11156 SecondTTPD->hasDefaultArgument() && 11157 !SecondTTPD->defaultArgumentWasInherited(); 11158 if (HasFirstDefaultArgument != HasSecondDefaultArgument) { 11159 ODRDiagDeclError(FirstRecord, FirstModule, 11160 FirstTemplate->getLocation(), 11161 FirstTemplate->getSourceRange(), 11162 FunctionTemplateParameterSingleDefaultArgument) 11163 << FirstTemplate << (i + 1) << HasFirstDefaultArgument; 11164 ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(), 11165 SecondTemplate->getSourceRange(), 11166 FunctionTemplateParameterSingleDefaultArgument) 11167 << SecondTemplate << (i + 1) << HasSecondDefaultArgument; 11168 ParameterMismatch = true; 11169 break; 11170 } 11171 11172 if (HasFirstDefaultArgument && HasSecondDefaultArgument) { 11173 TemplateArgument FirstTA = 11174 FirstTTPD->getDefaultArgument().getArgument(); 11175 TemplateArgument SecondTA = 11176 SecondTTPD->getDefaultArgument().getArgument(); 11177 if (ComputeTemplateArgumentODRHash(FirstTA) != 11178 ComputeTemplateArgumentODRHash(SecondTA)) { 11179 ODRDiagDeclError( 11180 FirstRecord, FirstModule, FirstTemplate->getLocation(), 11181 FirstTemplate->getSourceRange(), 11182 FunctionTemplateParameterDifferentDefaultArgument) 11183 << FirstTemplate << (i + 1) << FirstTA; 11184 ODRDiagDeclNote( 11185 SecondModule, SecondTemplate->getLocation(), 11186 SecondTemplate->getSourceRange(), 11187 FunctionTemplateParameterDifferentDefaultArgument) 11188 << SecondTemplate << (i + 1) << SecondTA; 11189 ParameterMismatch = true; 11190 break; 11191 } 11192 } 11193 11194 if (FirstTTPD->isParameterPack() != 11195 SecondTTPD->isParameterPack()) { 11196 ODRDiagDeclError(FirstRecord, FirstModule, 11197 FirstTemplate->getLocation(), 11198 FirstTemplate->getSourceRange(), 11199 FunctionTemplatePackParameter) 11200 << FirstTemplate << (i + 1) << FirstTTPD->isParameterPack(); 11201 ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(), 11202 SecondTemplate->getSourceRange(), 11203 FunctionTemplatePackParameter) 11204 << SecondTemplate << (i + 1) << SecondTTPD->isParameterPack(); 11205 ParameterMismatch = true; 11206 break; 11207 } 11208 } 11209 11210 if (isa<NonTypeTemplateParmDecl>(FirstParam) && 11211 isa<NonTypeTemplateParmDecl>(SecondParam)) { 11212 NonTypeTemplateParmDecl *FirstNTTPD = 11213 cast<NonTypeTemplateParmDecl>(FirstParam); 11214 NonTypeTemplateParmDecl *SecondNTTPD = 11215 cast<NonTypeTemplateParmDecl>(SecondParam); 11216 11217 QualType FirstType = FirstNTTPD->getType(); 11218 QualType SecondType = SecondNTTPD->getType(); 11219 if (ComputeQualTypeODRHash(FirstType) != 11220 ComputeQualTypeODRHash(SecondType)) { 11221 ODRDiagDeclError(FirstRecord, FirstModule, 11222 FirstTemplate->getLocation(), 11223 FirstTemplate->getSourceRange(), 11224 FunctionTemplateParameterDifferentType) 11225 << FirstTemplate << (i + 1); 11226 ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(), 11227 SecondTemplate->getSourceRange(), 11228 FunctionTemplateParameterDifferentType) 11229 << SecondTemplate << (i + 1); 11230 ParameterMismatch = true; 11231 break; 11232 } 11233 11234 bool HasFirstDefaultArgument = 11235 FirstNTTPD->hasDefaultArgument() && 11236 !FirstNTTPD->defaultArgumentWasInherited(); 11237 bool HasSecondDefaultArgument = 11238 SecondNTTPD->hasDefaultArgument() && 11239 !SecondNTTPD->defaultArgumentWasInherited(); 11240 if (HasFirstDefaultArgument != HasSecondDefaultArgument) { 11241 ODRDiagDeclError(FirstRecord, FirstModule, 11242 FirstTemplate->getLocation(), 11243 FirstTemplate->getSourceRange(), 11244 FunctionTemplateParameterSingleDefaultArgument) 11245 << FirstTemplate << (i + 1) << HasFirstDefaultArgument; 11246 ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(), 11247 SecondTemplate->getSourceRange(), 11248 FunctionTemplateParameterSingleDefaultArgument) 11249 << SecondTemplate << (i + 1) << HasSecondDefaultArgument; 11250 ParameterMismatch = true; 11251 break; 11252 } 11253 11254 if (HasFirstDefaultArgument && HasSecondDefaultArgument) { 11255 Expr *FirstDefaultArgument = FirstNTTPD->getDefaultArgument(); 11256 Expr *SecondDefaultArgument = SecondNTTPD->getDefaultArgument(); 11257 if (ComputeODRHash(FirstDefaultArgument) != 11258 ComputeODRHash(SecondDefaultArgument)) { 11259 ODRDiagDeclError( 11260 FirstRecord, FirstModule, FirstTemplate->getLocation(), 11261 FirstTemplate->getSourceRange(), 11262 FunctionTemplateParameterDifferentDefaultArgument) 11263 << FirstTemplate << (i + 1) << FirstDefaultArgument; 11264 ODRDiagDeclNote( 11265 SecondModule, SecondTemplate->getLocation(), 11266 SecondTemplate->getSourceRange(), 11267 FunctionTemplateParameterDifferentDefaultArgument) 11268 << SecondTemplate << (i + 1) << SecondDefaultArgument; 11269 ParameterMismatch = true; 11270 break; 11271 } 11272 } 11273 11274 if (FirstNTTPD->isParameterPack() != 11275 SecondNTTPD->isParameterPack()) { 11276 ODRDiagDeclError(FirstRecord, FirstModule, 11277 FirstTemplate->getLocation(), 11278 FirstTemplate->getSourceRange(), 11279 FunctionTemplatePackParameter) 11280 << FirstTemplate << (i + 1) << FirstNTTPD->isParameterPack(); 11281 ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(), 11282 SecondTemplate->getSourceRange(), 11283 FunctionTemplatePackParameter) 11284 << SecondTemplate << (i + 1) 11285 << SecondNTTPD->isParameterPack(); 11286 ParameterMismatch = true; 11287 break; 11288 } 11289 } 11290 } 11291 11292 if (ParameterMismatch) { 11293 Diagnosed = true; 11294 break; 11295 } 11296 11297 break; 11298 } 11299 } 11300 11301 if (Diagnosed) 11302 continue; 11303 11304 Diag(FirstDecl->getLocation(), 11305 diag::err_module_odr_violation_mismatch_decl_unknown) 11306 << FirstRecord << FirstModule.empty() << FirstModule << FirstDiffType 11307 << FirstDecl->getSourceRange(); 11308 Diag(SecondDecl->getLocation(), 11309 diag::note_module_odr_violation_mismatch_decl_unknown) 11310 << SecondModule << FirstDiffType << SecondDecl->getSourceRange(); 11311 Diagnosed = true; 11312 } 11313 11314 if (!Diagnosed) { 11315 // All definitions are updates to the same declaration. This happens if a 11316 // module instantiates the declaration of a class template specialization 11317 // and two or more other modules instantiate its definition. 11318 // 11319 // FIXME: Indicate which modules had instantiations of this definition. 11320 // FIXME: How can this even happen? 11321 Diag(Merge.first->getLocation(), 11322 diag::err_module_odr_violation_different_instantiations) 11323 << Merge.first; 11324 } 11325 } 11326 11327 // Issue ODR failures diagnostics for functions. 11328 for (auto &Merge : FunctionOdrMergeFailures) { 11329 enum ODRFunctionDifference { 11330 ReturnType, 11331 ParameterName, 11332 ParameterType, 11333 ParameterSingleDefaultArgument, 11334 ParameterDifferentDefaultArgument, 11335 FunctionBody, 11336 }; 11337 11338 FunctionDecl *FirstFunction = Merge.first; 11339 std::string FirstModule = getOwningModuleNameForDiagnostic(FirstFunction); 11340 11341 bool Diagnosed = false; 11342 for (auto &SecondFunction : Merge.second) { 11343 11344 if (FirstFunction == SecondFunction) 11345 continue; 11346 11347 std::string SecondModule = 11348 getOwningModuleNameForDiagnostic(SecondFunction); 11349 11350 auto ODRDiagError = [FirstFunction, &FirstModule, 11351 this](SourceLocation Loc, SourceRange Range, 11352 ODRFunctionDifference DiffType) { 11353 return Diag(Loc, diag::err_module_odr_violation_function) 11354 << FirstFunction << FirstModule.empty() << FirstModule << Range 11355 << DiffType; 11356 }; 11357 auto ODRDiagNote = [&SecondModule, this](SourceLocation Loc, 11358 SourceRange Range, 11359 ODRFunctionDifference DiffType) { 11360 return Diag(Loc, diag::note_module_odr_violation_function) 11361 << SecondModule << Range << DiffType; 11362 }; 11363 11364 if (ComputeQualTypeODRHash(FirstFunction->getReturnType()) != 11365 ComputeQualTypeODRHash(SecondFunction->getReturnType())) { 11366 ODRDiagError(FirstFunction->getReturnTypeSourceRange().getBegin(), 11367 FirstFunction->getReturnTypeSourceRange(), ReturnType) 11368 << FirstFunction->getReturnType(); 11369 ODRDiagNote(SecondFunction->getReturnTypeSourceRange().getBegin(), 11370 SecondFunction->getReturnTypeSourceRange(), ReturnType) 11371 << SecondFunction->getReturnType(); 11372 Diagnosed = true; 11373 break; 11374 } 11375 11376 assert(FirstFunction->param_size() == SecondFunction->param_size() && 11377 "Merged functions with different number of parameters"); 11378 11379 auto ParamSize = FirstFunction->param_size(); 11380 bool ParameterMismatch = false; 11381 for (unsigned I = 0; I < ParamSize; ++I) { 11382 auto *FirstParam = FirstFunction->getParamDecl(I); 11383 auto *SecondParam = SecondFunction->getParamDecl(I); 11384 11385 assert(getContext().hasSameType(FirstParam->getType(), 11386 SecondParam->getType()) && 11387 "Merged function has different parameter types."); 11388 11389 if (FirstParam->getDeclName() != SecondParam->getDeclName()) { 11390 ODRDiagError(FirstParam->getLocation(), FirstParam->getSourceRange(), 11391 ParameterName) 11392 << I + 1 << FirstParam->getDeclName(); 11393 ODRDiagNote(SecondParam->getLocation(), SecondParam->getSourceRange(), 11394 ParameterName) 11395 << I + 1 << SecondParam->getDeclName(); 11396 ParameterMismatch = true; 11397 break; 11398 }; 11399 11400 QualType FirstParamType = FirstParam->getType(); 11401 QualType SecondParamType = SecondParam->getType(); 11402 if (FirstParamType != SecondParamType && 11403 ComputeQualTypeODRHash(FirstParamType) != 11404 ComputeQualTypeODRHash(SecondParamType)) { 11405 if (const DecayedType *ParamDecayedType = 11406 FirstParamType->getAs<DecayedType>()) { 11407 ODRDiagError(FirstParam->getLocation(), 11408 FirstParam->getSourceRange(), ParameterType) 11409 << (I + 1) << FirstParamType << true 11410 << ParamDecayedType->getOriginalType(); 11411 } else { 11412 ODRDiagError(FirstParam->getLocation(), 11413 FirstParam->getSourceRange(), ParameterType) 11414 << (I + 1) << FirstParamType << false; 11415 } 11416 11417 if (const DecayedType *ParamDecayedType = 11418 SecondParamType->getAs<DecayedType>()) { 11419 ODRDiagNote(SecondParam->getLocation(), 11420 SecondParam->getSourceRange(), ParameterType) 11421 << (I + 1) << SecondParamType << true 11422 << ParamDecayedType->getOriginalType(); 11423 } else { 11424 ODRDiagNote(SecondParam->getLocation(), 11425 SecondParam->getSourceRange(), ParameterType) 11426 << (I + 1) << SecondParamType << false; 11427 } 11428 ParameterMismatch = true; 11429 break; 11430 } 11431 11432 const Expr *FirstInit = FirstParam->getInit(); 11433 const Expr *SecondInit = SecondParam->getInit(); 11434 if ((FirstInit == nullptr) != (SecondInit == nullptr)) { 11435 ODRDiagError(FirstParam->getLocation(), FirstParam->getSourceRange(), 11436 ParameterSingleDefaultArgument) 11437 << (I + 1) << (FirstInit == nullptr) 11438 << (FirstInit ? FirstInit->getSourceRange() : SourceRange()); 11439 ODRDiagNote(SecondParam->getLocation(), SecondParam->getSourceRange(), 11440 ParameterSingleDefaultArgument) 11441 << (I + 1) << (SecondInit == nullptr) 11442 << (SecondInit ? SecondInit->getSourceRange() : SourceRange()); 11443 ParameterMismatch = true; 11444 break; 11445 } 11446 11447 if (FirstInit && SecondInit && 11448 ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) { 11449 ODRDiagError(FirstParam->getLocation(), FirstParam->getSourceRange(), 11450 ParameterDifferentDefaultArgument) 11451 << (I + 1) << FirstInit->getSourceRange(); 11452 ODRDiagNote(SecondParam->getLocation(), SecondParam->getSourceRange(), 11453 ParameterDifferentDefaultArgument) 11454 << (I + 1) << SecondInit->getSourceRange(); 11455 ParameterMismatch = true; 11456 break; 11457 } 11458 11459 assert(ComputeSubDeclODRHash(FirstParam) == 11460 ComputeSubDeclODRHash(SecondParam) && 11461 "Undiagnosed parameter difference."); 11462 } 11463 11464 if (ParameterMismatch) { 11465 Diagnosed = true; 11466 break; 11467 } 11468 11469 // If no error has been generated before now, assume the problem is in 11470 // the body and generate a message. 11471 ODRDiagError(FirstFunction->getLocation(), 11472 FirstFunction->getSourceRange(), FunctionBody); 11473 ODRDiagNote(SecondFunction->getLocation(), 11474 SecondFunction->getSourceRange(), FunctionBody); 11475 Diagnosed = true; 11476 break; 11477 } 11478 (void)Diagnosed; 11479 assert(Diagnosed && "Unable to emit ODR diagnostic."); 11480 } 11481 11482 // Issue ODR failures diagnostics for enums. 11483 for (auto &Merge : EnumOdrMergeFailures) { 11484 enum ODREnumDifference { 11485 SingleScopedEnum, 11486 EnumTagKeywordMismatch, 11487 SingleSpecifiedType, 11488 DifferentSpecifiedTypes, 11489 DifferentNumberEnumConstants, 11490 EnumConstantName, 11491 EnumConstantSingleInitilizer, 11492 EnumConstantDifferentInitilizer, 11493 }; 11494 11495 // If we've already pointed out a specific problem with this enum, don't 11496 // bother issuing a general "something's different" diagnostic. 11497 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second) 11498 continue; 11499 11500 EnumDecl *FirstEnum = Merge.first; 11501 std::string FirstModule = getOwningModuleNameForDiagnostic(FirstEnum); 11502 11503 using DeclHashes = 11504 llvm::SmallVector<std::pair<EnumConstantDecl *, unsigned>, 4>; 11505 auto PopulateHashes = [&ComputeSubDeclODRHash, FirstEnum]( 11506 DeclHashes &Hashes, EnumDecl *Enum) { 11507 for (auto *D : Enum->decls()) { 11508 // Due to decl merging, the first EnumDecl is the parent of 11509 // Decls in both records. 11510 if (!ODRHash::isDeclToBeProcessed(D, FirstEnum)) 11511 continue; 11512 assert(isa<EnumConstantDecl>(D) && "Unexpected Decl kind"); 11513 Hashes.emplace_back(cast<EnumConstantDecl>(D), 11514 ComputeSubDeclODRHash(D)); 11515 } 11516 }; 11517 DeclHashes FirstHashes; 11518 PopulateHashes(FirstHashes, FirstEnum); 11519 bool Diagnosed = false; 11520 for (auto &SecondEnum : Merge.second) { 11521 11522 if (FirstEnum == SecondEnum) 11523 continue; 11524 11525 std::string SecondModule = 11526 getOwningModuleNameForDiagnostic(SecondEnum); 11527 11528 auto ODRDiagError = [FirstEnum, &FirstModule, 11529 this](SourceLocation Loc, SourceRange Range, 11530 ODREnumDifference DiffType) { 11531 return Diag(Loc, diag::err_module_odr_violation_enum) 11532 << FirstEnum << FirstModule.empty() << FirstModule << Range 11533 << DiffType; 11534 }; 11535 auto ODRDiagNote = [&SecondModule, this](SourceLocation Loc, 11536 SourceRange Range, 11537 ODREnumDifference DiffType) { 11538 return Diag(Loc, diag::note_module_odr_violation_enum) 11539 << SecondModule << Range << DiffType; 11540 }; 11541 11542 if (FirstEnum->isScoped() != SecondEnum->isScoped()) { 11543 ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(), 11544 SingleScopedEnum) 11545 << FirstEnum->isScoped(); 11546 ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(), 11547 SingleScopedEnum) 11548 << SecondEnum->isScoped(); 11549 Diagnosed = true; 11550 continue; 11551 } 11552 11553 if (FirstEnum->isScoped() && SecondEnum->isScoped()) { 11554 if (FirstEnum->isScopedUsingClassTag() != 11555 SecondEnum->isScopedUsingClassTag()) { 11556 ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(), 11557 EnumTagKeywordMismatch) 11558 << FirstEnum->isScopedUsingClassTag(); 11559 ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(), 11560 EnumTagKeywordMismatch) 11561 << SecondEnum->isScopedUsingClassTag(); 11562 Diagnosed = true; 11563 continue; 11564 } 11565 } 11566 11567 QualType FirstUnderlyingType = 11568 FirstEnum->getIntegerTypeSourceInfo() 11569 ? FirstEnum->getIntegerTypeSourceInfo()->getType() 11570 : QualType(); 11571 QualType SecondUnderlyingType = 11572 SecondEnum->getIntegerTypeSourceInfo() 11573 ? SecondEnum->getIntegerTypeSourceInfo()->getType() 11574 : QualType(); 11575 if (FirstUnderlyingType.isNull() != SecondUnderlyingType.isNull()) { 11576 ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(), 11577 SingleSpecifiedType) 11578 << !FirstUnderlyingType.isNull(); 11579 ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(), 11580 SingleSpecifiedType) 11581 << !SecondUnderlyingType.isNull(); 11582 Diagnosed = true; 11583 continue; 11584 } 11585 11586 if (!FirstUnderlyingType.isNull() && !SecondUnderlyingType.isNull()) { 11587 if (ComputeQualTypeODRHash(FirstUnderlyingType) != 11588 ComputeQualTypeODRHash(SecondUnderlyingType)) { 11589 ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(), 11590 DifferentSpecifiedTypes) 11591 << FirstUnderlyingType; 11592 ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(), 11593 DifferentSpecifiedTypes) 11594 << SecondUnderlyingType; 11595 Diagnosed = true; 11596 continue; 11597 } 11598 } 11599 11600 DeclHashes SecondHashes; 11601 PopulateHashes(SecondHashes, SecondEnum); 11602 11603 if (FirstHashes.size() != SecondHashes.size()) { 11604 ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(), 11605 DifferentNumberEnumConstants) 11606 << (int)FirstHashes.size(); 11607 ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(), 11608 DifferentNumberEnumConstants) 11609 << (int)SecondHashes.size(); 11610 Diagnosed = true; 11611 continue; 11612 } 11613 11614 for (unsigned I = 0; I < FirstHashes.size(); ++I) { 11615 if (FirstHashes[I].second == SecondHashes[I].second) 11616 continue; 11617 const EnumConstantDecl *FirstEnumConstant = FirstHashes[I].first; 11618 const EnumConstantDecl *SecondEnumConstant = SecondHashes[I].first; 11619 11620 if (FirstEnumConstant->getDeclName() != 11621 SecondEnumConstant->getDeclName()) { 11622 11623 ODRDiagError(FirstEnumConstant->getLocation(), 11624 FirstEnumConstant->getSourceRange(), EnumConstantName) 11625 << I + 1 << FirstEnumConstant; 11626 ODRDiagNote(SecondEnumConstant->getLocation(), 11627 SecondEnumConstant->getSourceRange(), EnumConstantName) 11628 << I + 1 << SecondEnumConstant; 11629 Diagnosed = true; 11630 break; 11631 } 11632 11633 const Expr *FirstInit = FirstEnumConstant->getInitExpr(); 11634 const Expr *SecondInit = SecondEnumConstant->getInitExpr(); 11635 if (!FirstInit && !SecondInit) 11636 continue; 11637 11638 if (!FirstInit || !SecondInit) { 11639 ODRDiagError(FirstEnumConstant->getLocation(), 11640 FirstEnumConstant->getSourceRange(), 11641 EnumConstantSingleInitilizer) 11642 << I + 1 << FirstEnumConstant << (FirstInit != nullptr); 11643 ODRDiagNote(SecondEnumConstant->getLocation(), 11644 SecondEnumConstant->getSourceRange(), 11645 EnumConstantSingleInitilizer) 11646 << I + 1 << SecondEnumConstant << (SecondInit != nullptr); 11647 Diagnosed = true; 11648 break; 11649 } 11650 11651 if (ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) { 11652 ODRDiagError(FirstEnumConstant->getLocation(), 11653 FirstEnumConstant->getSourceRange(), 11654 EnumConstantDifferentInitilizer) 11655 << I + 1 << FirstEnumConstant; 11656 ODRDiagNote(SecondEnumConstant->getLocation(), 11657 SecondEnumConstant->getSourceRange(), 11658 EnumConstantDifferentInitilizer) 11659 << I + 1 << SecondEnumConstant; 11660 Diagnosed = true; 11661 break; 11662 } 11663 } 11664 } 11665 11666 (void)Diagnosed; 11667 assert(Diagnosed && "Unable to emit ODR diagnostic."); 11668 } 11669 } 11670 11671 void ASTReader::StartedDeserializing() { 11672 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get()) 11673 ReadTimer->startTimer(); 11674 } 11675 11676 void ASTReader::FinishedDeserializing() { 11677 assert(NumCurrentElementsDeserializing && 11678 "FinishedDeserializing not paired with StartedDeserializing"); 11679 if (NumCurrentElementsDeserializing == 1) { 11680 // We decrease NumCurrentElementsDeserializing only after pending actions 11681 // are finished, to avoid recursively re-calling finishPendingActions(). 11682 finishPendingActions(); 11683 } 11684 --NumCurrentElementsDeserializing; 11685 11686 if (NumCurrentElementsDeserializing == 0) { 11687 // Propagate exception specification and deduced type updates along 11688 // redeclaration chains. 11689 // 11690 // We do this now rather than in finishPendingActions because we want to 11691 // be able to walk the complete redeclaration chains of the updated decls. 11692 while (!PendingExceptionSpecUpdates.empty() || 11693 !PendingDeducedTypeUpdates.empty()) { 11694 auto ESUpdates = std::move(PendingExceptionSpecUpdates); 11695 PendingExceptionSpecUpdates.clear(); 11696 for (auto Update : ESUpdates) { 11697 ProcessingUpdatesRAIIObj ProcessingUpdates(*this); 11698 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>(); 11699 auto ESI = FPT->getExtProtoInfo().ExceptionSpec; 11700 if (auto *Listener = getContext().getASTMutationListener()) 11701 Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second)); 11702 for (auto *Redecl : Update.second->redecls()) 11703 getContext().adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI); 11704 } 11705 11706 auto DTUpdates = std::move(PendingDeducedTypeUpdates); 11707 PendingDeducedTypeUpdates.clear(); 11708 for (auto Update : DTUpdates) { 11709 ProcessingUpdatesRAIIObj ProcessingUpdates(*this); 11710 // FIXME: If the return type is already deduced, check that it matches. 11711 getContext().adjustDeducedFunctionResultType(Update.first, 11712 Update.second); 11713 } 11714 } 11715 11716 if (ReadTimer) 11717 ReadTimer->stopTimer(); 11718 11719 diagnoseOdrViolations(); 11720 11721 // We are not in recursive loading, so it's safe to pass the "interesting" 11722 // decls to the consumer. 11723 if (Consumer) 11724 PassInterestingDeclsToConsumer(); 11725 } 11726 } 11727 11728 void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) { 11729 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) { 11730 // Remove any fake results before adding any real ones. 11731 auto It = PendingFakeLookupResults.find(II); 11732 if (It != PendingFakeLookupResults.end()) { 11733 for (auto *ND : It->second) 11734 SemaObj->IdResolver.RemoveDecl(ND); 11735 // FIXME: this works around module+PCH performance issue. 11736 // Rather than erase the result from the map, which is O(n), just clear 11737 // the vector of NamedDecls. 11738 It->second.clear(); 11739 } 11740 } 11741 11742 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) { 11743 SemaObj->TUScope->AddDecl(D); 11744 } else if (SemaObj->TUScope) { 11745 // Adding the decl to IdResolver may have failed because it was already in 11746 // (even though it was not added in scope). If it is already in, make sure 11747 // it gets in the scope as well. 11748 if (std::find(SemaObj->IdResolver.begin(Name), 11749 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end()) 11750 SemaObj->TUScope->AddDecl(D); 11751 } 11752 } 11753 11754 ASTReader::ASTReader(Preprocessor &PP, InMemoryModuleCache &ModuleCache, 11755 ASTContext *Context, 11756 const PCHContainerReader &PCHContainerRdr, 11757 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions, 11758 StringRef isysroot, bool DisableValidation, 11759 bool AllowASTWithCompilerErrors, 11760 bool AllowConfigurationMismatch, bool ValidateSystemInputs, 11761 bool ValidateASTInputFilesContent, bool UseGlobalIndex, 11762 std::unique_ptr<llvm::Timer> ReadTimer) 11763 : Listener(DisableValidation 11764 ? cast<ASTReaderListener>(new SimpleASTReaderListener(PP)) 11765 : cast<ASTReaderListener>(new PCHValidator(PP, *this))), 11766 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()), 11767 PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()), PP(PP), 11768 ContextObj(Context), ModuleMgr(PP.getFileManager(), ModuleCache, 11769 PCHContainerRdr, PP.getHeaderSearchInfo()), 11770 DummyIdResolver(PP), ReadTimer(std::move(ReadTimer)), isysroot(isysroot), 11771 DisableValidation(DisableValidation), 11772 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors), 11773 AllowConfigurationMismatch(AllowConfigurationMismatch), 11774 ValidateSystemInputs(ValidateSystemInputs), 11775 ValidateASTInputFilesContent(ValidateASTInputFilesContent), 11776 UseGlobalIndex(UseGlobalIndex), CurrSwitchCaseStmts(&SwitchCaseStmts) { 11777 SourceMgr.setExternalSLocEntrySource(this); 11778 11779 for (const auto &Ext : Extensions) { 11780 auto BlockName = Ext->getExtensionMetadata().BlockName; 11781 auto Known = ModuleFileExtensions.find(BlockName); 11782 if (Known != ModuleFileExtensions.end()) { 11783 Diags.Report(diag::warn_duplicate_module_file_extension) 11784 << BlockName; 11785 continue; 11786 } 11787 11788 ModuleFileExtensions.insert({BlockName, Ext}); 11789 } 11790 } 11791 11792 ASTReader::~ASTReader() { 11793 if (OwnsDeserializationListener) 11794 delete DeserializationListener; 11795 } 11796 11797 IdentifierResolver &ASTReader::getIdResolver() { 11798 return SemaObj ? SemaObj->IdResolver : DummyIdResolver; 11799 } 11800 11801 Expected<unsigned> ASTRecordReader::readRecord(llvm::BitstreamCursor &Cursor, 11802 unsigned AbbrevID) { 11803 Idx = 0; 11804 Record.clear(); 11805 return Cursor.readRecord(AbbrevID, Record); 11806 } 11807 //===----------------------------------------------------------------------===// 11808 //// OMPClauseReader implementation 11809 ////===----------------------------------------------------------------------===// 11810 11811 // This has to be in namespace clang because it's friended by all 11812 // of the OMP clauses. 11813 namespace clang { 11814 11815 class OMPClauseReader : public OMPClauseVisitor<OMPClauseReader> { 11816 ASTRecordReader &Record; 11817 ASTContext &Context; 11818 11819 public: 11820 OMPClauseReader(ASTRecordReader &Record) 11821 : Record(Record), Context(Record.getContext()) {} 11822 11823 #define OMP_CLAUSE_CLASS(Enum, Str, Class) void Visit##Class(Class *C); 11824 #include "llvm/Frontend/OpenMP/OMPKinds.def" 11825 OMPClause *readClause(); 11826 void VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C); 11827 void VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C); 11828 }; 11829 11830 } // end namespace clang 11831 11832 OMPClause *ASTRecordReader::readOMPClause() { 11833 return OMPClauseReader(*this).readClause(); 11834 } 11835 11836 OMPClause *OMPClauseReader::readClause() { 11837 OMPClause *C = nullptr; 11838 switch (llvm::omp::Clause(Record.readInt())) { 11839 case llvm::omp::OMPC_if: 11840 C = new (Context) OMPIfClause(); 11841 break; 11842 case llvm::omp::OMPC_final: 11843 C = new (Context) OMPFinalClause(); 11844 break; 11845 case llvm::omp::OMPC_num_threads: 11846 C = new (Context) OMPNumThreadsClause(); 11847 break; 11848 case llvm::omp::OMPC_safelen: 11849 C = new (Context) OMPSafelenClause(); 11850 break; 11851 case llvm::omp::OMPC_simdlen: 11852 C = new (Context) OMPSimdlenClause(); 11853 break; 11854 case llvm::omp::OMPC_allocator: 11855 C = new (Context) OMPAllocatorClause(); 11856 break; 11857 case llvm::omp::OMPC_collapse: 11858 C = new (Context) OMPCollapseClause(); 11859 break; 11860 case llvm::omp::OMPC_default: 11861 C = new (Context) OMPDefaultClause(); 11862 break; 11863 case llvm::omp::OMPC_proc_bind: 11864 C = new (Context) OMPProcBindClause(); 11865 break; 11866 case llvm::omp::OMPC_schedule: 11867 C = new (Context) OMPScheduleClause(); 11868 break; 11869 case llvm::omp::OMPC_ordered: 11870 C = OMPOrderedClause::CreateEmpty(Context, Record.readInt()); 11871 break; 11872 case llvm::omp::OMPC_nowait: 11873 C = new (Context) OMPNowaitClause(); 11874 break; 11875 case llvm::omp::OMPC_untied: 11876 C = new (Context) OMPUntiedClause(); 11877 break; 11878 case llvm::omp::OMPC_mergeable: 11879 C = new (Context) OMPMergeableClause(); 11880 break; 11881 case llvm::omp::OMPC_read: 11882 C = new (Context) OMPReadClause(); 11883 break; 11884 case llvm::omp::OMPC_write: 11885 C = new (Context) OMPWriteClause(); 11886 break; 11887 case llvm::omp::OMPC_update: 11888 C = OMPUpdateClause::CreateEmpty(Context, Record.readInt()); 11889 break; 11890 case llvm::omp::OMPC_capture: 11891 C = new (Context) OMPCaptureClause(); 11892 break; 11893 case llvm::omp::OMPC_seq_cst: 11894 C = new (Context) OMPSeqCstClause(); 11895 break; 11896 case llvm::omp::OMPC_acq_rel: 11897 C = new (Context) OMPAcqRelClause(); 11898 break; 11899 case llvm::omp::OMPC_acquire: 11900 C = new (Context) OMPAcquireClause(); 11901 break; 11902 case llvm::omp::OMPC_release: 11903 C = new (Context) OMPReleaseClause(); 11904 break; 11905 case llvm::omp::OMPC_relaxed: 11906 C = new (Context) OMPRelaxedClause(); 11907 break; 11908 case llvm::omp::OMPC_threads: 11909 C = new (Context) OMPThreadsClause(); 11910 break; 11911 case llvm::omp::OMPC_simd: 11912 C = new (Context) OMPSIMDClause(); 11913 break; 11914 case llvm::omp::OMPC_nogroup: 11915 C = new (Context) OMPNogroupClause(); 11916 break; 11917 case llvm::omp::OMPC_unified_address: 11918 C = new (Context) OMPUnifiedAddressClause(); 11919 break; 11920 case llvm::omp::OMPC_unified_shared_memory: 11921 C = new (Context) OMPUnifiedSharedMemoryClause(); 11922 break; 11923 case llvm::omp::OMPC_reverse_offload: 11924 C = new (Context) OMPReverseOffloadClause(); 11925 break; 11926 case llvm::omp::OMPC_dynamic_allocators: 11927 C = new (Context) OMPDynamicAllocatorsClause(); 11928 break; 11929 case llvm::omp::OMPC_atomic_default_mem_order: 11930 C = new (Context) OMPAtomicDefaultMemOrderClause(); 11931 break; 11932 case llvm::omp::OMPC_private: 11933 C = OMPPrivateClause::CreateEmpty(Context, Record.readInt()); 11934 break; 11935 case llvm::omp::OMPC_firstprivate: 11936 C = OMPFirstprivateClause::CreateEmpty(Context, Record.readInt()); 11937 break; 11938 case llvm::omp::OMPC_lastprivate: 11939 C = OMPLastprivateClause::CreateEmpty(Context, Record.readInt()); 11940 break; 11941 case llvm::omp::OMPC_shared: 11942 C = OMPSharedClause::CreateEmpty(Context, Record.readInt()); 11943 break; 11944 case llvm::omp::OMPC_reduction: { 11945 unsigned N = Record.readInt(); 11946 auto Modifier = Record.readEnum<OpenMPReductionClauseModifier>(); 11947 C = OMPReductionClause::CreateEmpty(Context, N, Modifier); 11948 break; 11949 } 11950 case llvm::omp::OMPC_task_reduction: 11951 C = OMPTaskReductionClause::CreateEmpty(Context, Record.readInt()); 11952 break; 11953 case llvm::omp::OMPC_in_reduction: 11954 C = OMPInReductionClause::CreateEmpty(Context, Record.readInt()); 11955 break; 11956 case llvm::omp::OMPC_linear: 11957 C = OMPLinearClause::CreateEmpty(Context, Record.readInt()); 11958 break; 11959 case llvm::omp::OMPC_aligned: 11960 C = OMPAlignedClause::CreateEmpty(Context, Record.readInt()); 11961 break; 11962 case llvm::omp::OMPC_copyin: 11963 C = OMPCopyinClause::CreateEmpty(Context, Record.readInt()); 11964 break; 11965 case llvm::omp::OMPC_copyprivate: 11966 C = OMPCopyprivateClause::CreateEmpty(Context, Record.readInt()); 11967 break; 11968 case llvm::omp::OMPC_flush: 11969 C = OMPFlushClause::CreateEmpty(Context, Record.readInt()); 11970 break; 11971 case llvm::omp::OMPC_depobj: 11972 C = OMPDepobjClause::CreateEmpty(Context); 11973 break; 11974 case llvm::omp::OMPC_depend: { 11975 unsigned NumVars = Record.readInt(); 11976 unsigned NumLoops = Record.readInt(); 11977 C = OMPDependClause::CreateEmpty(Context, NumVars, NumLoops); 11978 break; 11979 } 11980 case llvm::omp::OMPC_device: 11981 C = new (Context) OMPDeviceClause(); 11982 break; 11983 case llvm::omp::OMPC_map: { 11984 OMPMappableExprListSizeTy Sizes; 11985 Sizes.NumVars = Record.readInt(); 11986 Sizes.NumUniqueDeclarations = Record.readInt(); 11987 Sizes.NumComponentLists = Record.readInt(); 11988 Sizes.NumComponents = Record.readInt(); 11989 C = OMPMapClause::CreateEmpty(Context, Sizes); 11990 break; 11991 } 11992 case llvm::omp::OMPC_num_teams: 11993 C = new (Context) OMPNumTeamsClause(); 11994 break; 11995 case llvm::omp::OMPC_thread_limit: 11996 C = new (Context) OMPThreadLimitClause(); 11997 break; 11998 case llvm::omp::OMPC_priority: 11999 C = new (Context) OMPPriorityClause(); 12000 break; 12001 case llvm::omp::OMPC_grainsize: 12002 C = new (Context) OMPGrainsizeClause(); 12003 break; 12004 case llvm::omp::OMPC_num_tasks: 12005 C = new (Context) OMPNumTasksClause(); 12006 break; 12007 case llvm::omp::OMPC_hint: 12008 C = new (Context) OMPHintClause(); 12009 break; 12010 case llvm::omp::OMPC_dist_schedule: 12011 C = new (Context) OMPDistScheduleClause(); 12012 break; 12013 case llvm::omp::OMPC_defaultmap: 12014 C = new (Context) OMPDefaultmapClause(); 12015 break; 12016 case llvm::omp::OMPC_to: { 12017 OMPMappableExprListSizeTy Sizes; 12018 Sizes.NumVars = Record.readInt(); 12019 Sizes.NumUniqueDeclarations = Record.readInt(); 12020 Sizes.NumComponentLists = Record.readInt(); 12021 Sizes.NumComponents = Record.readInt(); 12022 C = OMPToClause::CreateEmpty(Context, Sizes); 12023 break; 12024 } 12025 case llvm::omp::OMPC_from: { 12026 OMPMappableExprListSizeTy Sizes; 12027 Sizes.NumVars = Record.readInt(); 12028 Sizes.NumUniqueDeclarations = Record.readInt(); 12029 Sizes.NumComponentLists = Record.readInt(); 12030 Sizes.NumComponents = Record.readInt(); 12031 C = OMPFromClause::CreateEmpty(Context, Sizes); 12032 break; 12033 } 12034 case llvm::omp::OMPC_use_device_ptr: { 12035 OMPMappableExprListSizeTy Sizes; 12036 Sizes.NumVars = Record.readInt(); 12037 Sizes.NumUniqueDeclarations = Record.readInt(); 12038 Sizes.NumComponentLists = Record.readInt(); 12039 Sizes.NumComponents = Record.readInt(); 12040 C = OMPUseDevicePtrClause::CreateEmpty(Context, Sizes); 12041 break; 12042 } 12043 case llvm::omp::OMPC_use_device_addr: { 12044 OMPMappableExprListSizeTy Sizes; 12045 Sizes.NumVars = Record.readInt(); 12046 Sizes.NumUniqueDeclarations = Record.readInt(); 12047 Sizes.NumComponentLists = Record.readInt(); 12048 Sizes.NumComponents = Record.readInt(); 12049 C = OMPUseDeviceAddrClause::CreateEmpty(Context, Sizes); 12050 break; 12051 } 12052 case llvm::omp::OMPC_is_device_ptr: { 12053 OMPMappableExprListSizeTy Sizes; 12054 Sizes.NumVars = Record.readInt(); 12055 Sizes.NumUniqueDeclarations = Record.readInt(); 12056 Sizes.NumComponentLists = Record.readInt(); 12057 Sizes.NumComponents = Record.readInt(); 12058 C = OMPIsDevicePtrClause::CreateEmpty(Context, Sizes); 12059 break; 12060 } 12061 case llvm::omp::OMPC_allocate: 12062 C = OMPAllocateClause::CreateEmpty(Context, Record.readInt()); 12063 break; 12064 case llvm::omp::OMPC_nontemporal: 12065 C = OMPNontemporalClause::CreateEmpty(Context, Record.readInt()); 12066 break; 12067 case llvm::omp::OMPC_inclusive: 12068 C = OMPInclusiveClause::CreateEmpty(Context, Record.readInt()); 12069 break; 12070 case llvm::omp::OMPC_exclusive: 12071 C = OMPExclusiveClause::CreateEmpty(Context, Record.readInt()); 12072 break; 12073 case llvm::omp::OMPC_order: 12074 C = new (Context) OMPOrderClause(); 12075 break; 12076 case llvm::omp::OMPC_destroy: 12077 C = new (Context) OMPDestroyClause(); 12078 break; 12079 case llvm::omp::OMPC_detach: 12080 C = new (Context) OMPDetachClause(); 12081 break; 12082 case llvm::omp::OMPC_uses_allocators: 12083 C = OMPUsesAllocatorsClause::CreateEmpty(Context, Record.readInt()); 12084 break; 12085 case llvm::omp::OMPC_affinity: 12086 C = OMPAffinityClause::CreateEmpty(Context, Record.readInt()); 12087 break; 12088 #define OMP_CLAUSE_NO_CLASS(Enum, Str) \ 12089 case llvm::omp::Enum: \ 12090 break; 12091 #include "llvm/Frontend/OpenMP/OMPKinds.def" 12092 default: 12093 break; 12094 } 12095 assert(C && "Unknown OMPClause type"); 12096 12097 Visit(C); 12098 C->setLocStart(Record.readSourceLocation()); 12099 C->setLocEnd(Record.readSourceLocation()); 12100 12101 return C; 12102 } 12103 12104 void OMPClauseReader::VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C) { 12105 C->setPreInitStmt(Record.readSubStmt(), 12106 static_cast<OpenMPDirectiveKind>(Record.readInt())); 12107 } 12108 12109 void OMPClauseReader::VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C) { 12110 VisitOMPClauseWithPreInit(C); 12111 C->setPostUpdateExpr(Record.readSubExpr()); 12112 } 12113 12114 void OMPClauseReader::VisitOMPIfClause(OMPIfClause *C) { 12115 VisitOMPClauseWithPreInit(C); 12116 C->setNameModifier(static_cast<OpenMPDirectiveKind>(Record.readInt())); 12117 C->setNameModifierLoc(Record.readSourceLocation()); 12118 C->setColonLoc(Record.readSourceLocation()); 12119 C->setCondition(Record.readSubExpr()); 12120 C->setLParenLoc(Record.readSourceLocation()); 12121 } 12122 12123 void OMPClauseReader::VisitOMPFinalClause(OMPFinalClause *C) { 12124 VisitOMPClauseWithPreInit(C); 12125 C->setCondition(Record.readSubExpr()); 12126 C->setLParenLoc(Record.readSourceLocation()); 12127 } 12128 12129 void OMPClauseReader::VisitOMPNumThreadsClause(OMPNumThreadsClause *C) { 12130 VisitOMPClauseWithPreInit(C); 12131 C->setNumThreads(Record.readSubExpr()); 12132 C->setLParenLoc(Record.readSourceLocation()); 12133 } 12134 12135 void OMPClauseReader::VisitOMPSafelenClause(OMPSafelenClause *C) { 12136 C->setSafelen(Record.readSubExpr()); 12137 C->setLParenLoc(Record.readSourceLocation()); 12138 } 12139 12140 void OMPClauseReader::VisitOMPSimdlenClause(OMPSimdlenClause *C) { 12141 C->setSimdlen(Record.readSubExpr()); 12142 C->setLParenLoc(Record.readSourceLocation()); 12143 } 12144 12145 void OMPClauseReader::VisitOMPAllocatorClause(OMPAllocatorClause *C) { 12146 C->setAllocator(Record.readExpr()); 12147 C->setLParenLoc(Record.readSourceLocation()); 12148 } 12149 12150 void OMPClauseReader::VisitOMPCollapseClause(OMPCollapseClause *C) { 12151 C->setNumForLoops(Record.readSubExpr()); 12152 C->setLParenLoc(Record.readSourceLocation()); 12153 } 12154 12155 void OMPClauseReader::VisitOMPDefaultClause(OMPDefaultClause *C) { 12156 C->setDefaultKind(static_cast<llvm::omp::DefaultKind>(Record.readInt())); 12157 C->setLParenLoc(Record.readSourceLocation()); 12158 C->setDefaultKindKwLoc(Record.readSourceLocation()); 12159 } 12160 12161 void OMPClauseReader::VisitOMPProcBindClause(OMPProcBindClause *C) { 12162 C->setProcBindKind(static_cast<llvm::omp::ProcBindKind>(Record.readInt())); 12163 C->setLParenLoc(Record.readSourceLocation()); 12164 C->setProcBindKindKwLoc(Record.readSourceLocation()); 12165 } 12166 12167 void OMPClauseReader::VisitOMPScheduleClause(OMPScheduleClause *C) { 12168 VisitOMPClauseWithPreInit(C); 12169 C->setScheduleKind( 12170 static_cast<OpenMPScheduleClauseKind>(Record.readInt())); 12171 C->setFirstScheduleModifier( 12172 static_cast<OpenMPScheduleClauseModifier>(Record.readInt())); 12173 C->setSecondScheduleModifier( 12174 static_cast<OpenMPScheduleClauseModifier>(Record.readInt())); 12175 C->setChunkSize(Record.readSubExpr()); 12176 C->setLParenLoc(Record.readSourceLocation()); 12177 C->setFirstScheduleModifierLoc(Record.readSourceLocation()); 12178 C->setSecondScheduleModifierLoc(Record.readSourceLocation()); 12179 C->setScheduleKindLoc(Record.readSourceLocation()); 12180 C->setCommaLoc(Record.readSourceLocation()); 12181 } 12182 12183 void OMPClauseReader::VisitOMPOrderedClause(OMPOrderedClause *C) { 12184 C->setNumForLoops(Record.readSubExpr()); 12185 for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I) 12186 C->setLoopNumIterations(I, Record.readSubExpr()); 12187 for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I) 12188 C->setLoopCounter(I, Record.readSubExpr()); 12189 C->setLParenLoc(Record.readSourceLocation()); 12190 } 12191 12192 void OMPClauseReader::VisitOMPDetachClause(OMPDetachClause *C) { 12193 C->setEventHandler(Record.readSubExpr()); 12194 C->setLParenLoc(Record.readSourceLocation()); 12195 } 12196 12197 void OMPClauseReader::VisitOMPNowaitClause(OMPNowaitClause *) {} 12198 12199 void OMPClauseReader::VisitOMPUntiedClause(OMPUntiedClause *) {} 12200 12201 void OMPClauseReader::VisitOMPMergeableClause(OMPMergeableClause *) {} 12202 12203 void OMPClauseReader::VisitOMPReadClause(OMPReadClause *) {} 12204 12205 void OMPClauseReader::VisitOMPWriteClause(OMPWriteClause *) {} 12206 12207 void OMPClauseReader::VisitOMPUpdateClause(OMPUpdateClause *C) { 12208 if (C->isExtended()) { 12209 C->setLParenLoc(Record.readSourceLocation()); 12210 C->setArgumentLoc(Record.readSourceLocation()); 12211 C->setDependencyKind(Record.readEnum<OpenMPDependClauseKind>()); 12212 } 12213 } 12214 12215 void OMPClauseReader::VisitOMPCaptureClause(OMPCaptureClause *) {} 12216 12217 void OMPClauseReader::VisitOMPSeqCstClause(OMPSeqCstClause *) {} 12218 12219 void OMPClauseReader::VisitOMPAcqRelClause(OMPAcqRelClause *) {} 12220 12221 void OMPClauseReader::VisitOMPAcquireClause(OMPAcquireClause *) {} 12222 12223 void OMPClauseReader::VisitOMPReleaseClause(OMPReleaseClause *) {} 12224 12225 void OMPClauseReader::VisitOMPRelaxedClause(OMPRelaxedClause *) {} 12226 12227 void OMPClauseReader::VisitOMPThreadsClause(OMPThreadsClause *) {} 12228 12229 void OMPClauseReader::VisitOMPSIMDClause(OMPSIMDClause *) {} 12230 12231 void OMPClauseReader::VisitOMPNogroupClause(OMPNogroupClause *) {} 12232 12233 void OMPClauseReader::VisitOMPDestroyClause(OMPDestroyClause *) {} 12234 12235 void OMPClauseReader::VisitOMPUnifiedAddressClause(OMPUnifiedAddressClause *) {} 12236 12237 void OMPClauseReader::VisitOMPUnifiedSharedMemoryClause( 12238 OMPUnifiedSharedMemoryClause *) {} 12239 12240 void OMPClauseReader::VisitOMPReverseOffloadClause(OMPReverseOffloadClause *) {} 12241 12242 void 12243 OMPClauseReader::VisitOMPDynamicAllocatorsClause(OMPDynamicAllocatorsClause *) { 12244 } 12245 12246 void OMPClauseReader::VisitOMPAtomicDefaultMemOrderClause( 12247 OMPAtomicDefaultMemOrderClause *C) { 12248 C->setAtomicDefaultMemOrderKind( 12249 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Record.readInt())); 12250 C->setLParenLoc(Record.readSourceLocation()); 12251 C->setAtomicDefaultMemOrderKindKwLoc(Record.readSourceLocation()); 12252 } 12253 12254 void OMPClauseReader::VisitOMPPrivateClause(OMPPrivateClause *C) { 12255 C->setLParenLoc(Record.readSourceLocation()); 12256 unsigned NumVars = C->varlist_size(); 12257 SmallVector<Expr *, 16> Vars; 12258 Vars.reserve(NumVars); 12259 for (unsigned i = 0; i != NumVars; ++i) 12260 Vars.push_back(Record.readSubExpr()); 12261 C->setVarRefs(Vars); 12262 Vars.clear(); 12263 for (unsigned i = 0; i != NumVars; ++i) 12264 Vars.push_back(Record.readSubExpr()); 12265 C->setPrivateCopies(Vars); 12266 } 12267 12268 void OMPClauseReader::VisitOMPFirstprivateClause(OMPFirstprivateClause *C) { 12269 VisitOMPClauseWithPreInit(C); 12270 C->setLParenLoc(Record.readSourceLocation()); 12271 unsigned NumVars = C->varlist_size(); 12272 SmallVector<Expr *, 16> Vars; 12273 Vars.reserve(NumVars); 12274 for (unsigned i = 0; i != NumVars; ++i) 12275 Vars.push_back(Record.readSubExpr()); 12276 C->setVarRefs(Vars); 12277 Vars.clear(); 12278 for (unsigned i = 0; i != NumVars; ++i) 12279 Vars.push_back(Record.readSubExpr()); 12280 C->setPrivateCopies(Vars); 12281 Vars.clear(); 12282 for (unsigned i = 0; i != NumVars; ++i) 12283 Vars.push_back(Record.readSubExpr()); 12284 C->setInits(Vars); 12285 } 12286 12287 void OMPClauseReader::VisitOMPLastprivateClause(OMPLastprivateClause *C) { 12288 VisitOMPClauseWithPostUpdate(C); 12289 C->setLParenLoc(Record.readSourceLocation()); 12290 C->setKind(Record.readEnum<OpenMPLastprivateModifier>()); 12291 C->setKindLoc(Record.readSourceLocation()); 12292 C->setColonLoc(Record.readSourceLocation()); 12293 unsigned NumVars = C->varlist_size(); 12294 SmallVector<Expr *, 16> Vars; 12295 Vars.reserve(NumVars); 12296 for (unsigned i = 0; i != NumVars; ++i) 12297 Vars.push_back(Record.readSubExpr()); 12298 C->setVarRefs(Vars); 12299 Vars.clear(); 12300 for (unsigned i = 0; i != NumVars; ++i) 12301 Vars.push_back(Record.readSubExpr()); 12302 C->setPrivateCopies(Vars); 12303 Vars.clear(); 12304 for (unsigned i = 0; i != NumVars; ++i) 12305 Vars.push_back(Record.readSubExpr()); 12306 C->setSourceExprs(Vars); 12307 Vars.clear(); 12308 for (unsigned i = 0; i != NumVars; ++i) 12309 Vars.push_back(Record.readSubExpr()); 12310 C->setDestinationExprs(Vars); 12311 Vars.clear(); 12312 for (unsigned i = 0; i != NumVars; ++i) 12313 Vars.push_back(Record.readSubExpr()); 12314 C->setAssignmentOps(Vars); 12315 } 12316 12317 void OMPClauseReader::VisitOMPSharedClause(OMPSharedClause *C) { 12318 C->setLParenLoc(Record.readSourceLocation()); 12319 unsigned NumVars = C->varlist_size(); 12320 SmallVector<Expr *, 16> Vars; 12321 Vars.reserve(NumVars); 12322 for (unsigned i = 0; i != NumVars; ++i) 12323 Vars.push_back(Record.readSubExpr()); 12324 C->setVarRefs(Vars); 12325 } 12326 12327 void OMPClauseReader::VisitOMPReductionClause(OMPReductionClause *C) { 12328 VisitOMPClauseWithPostUpdate(C); 12329 C->setLParenLoc(Record.readSourceLocation()); 12330 C->setModifierLoc(Record.readSourceLocation()); 12331 C->setColonLoc(Record.readSourceLocation()); 12332 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc(); 12333 DeclarationNameInfo DNI = Record.readDeclarationNameInfo(); 12334 C->setQualifierLoc(NNSL); 12335 C->setNameInfo(DNI); 12336 12337 unsigned NumVars = C->varlist_size(); 12338 SmallVector<Expr *, 16> Vars; 12339 Vars.reserve(NumVars); 12340 for (unsigned i = 0; i != NumVars; ++i) 12341 Vars.push_back(Record.readSubExpr()); 12342 C->setVarRefs(Vars); 12343 Vars.clear(); 12344 for (unsigned i = 0; i != NumVars; ++i) 12345 Vars.push_back(Record.readSubExpr()); 12346 C->setPrivates(Vars); 12347 Vars.clear(); 12348 for (unsigned i = 0; i != NumVars; ++i) 12349 Vars.push_back(Record.readSubExpr()); 12350 C->setLHSExprs(Vars); 12351 Vars.clear(); 12352 for (unsigned i = 0; i != NumVars; ++i) 12353 Vars.push_back(Record.readSubExpr()); 12354 C->setRHSExprs(Vars); 12355 Vars.clear(); 12356 for (unsigned i = 0; i != NumVars; ++i) 12357 Vars.push_back(Record.readSubExpr()); 12358 C->setReductionOps(Vars); 12359 if (C->getModifier() == OMPC_REDUCTION_inscan) { 12360 Vars.clear(); 12361 for (unsigned i = 0; i != NumVars; ++i) 12362 Vars.push_back(Record.readSubExpr()); 12363 C->setInscanCopyOps(Vars); 12364 Vars.clear(); 12365 for (unsigned i = 0; i != NumVars; ++i) 12366 Vars.push_back(Record.readSubExpr()); 12367 C->setInscanCopyArrayTemps(Vars); 12368 Vars.clear(); 12369 for (unsigned i = 0; i != NumVars; ++i) 12370 Vars.push_back(Record.readSubExpr()); 12371 C->setInscanCopyArrayElems(Vars); 12372 } 12373 } 12374 12375 void OMPClauseReader::VisitOMPTaskReductionClause(OMPTaskReductionClause *C) { 12376 VisitOMPClauseWithPostUpdate(C); 12377 C->setLParenLoc(Record.readSourceLocation()); 12378 C->setColonLoc(Record.readSourceLocation()); 12379 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc(); 12380 DeclarationNameInfo DNI = Record.readDeclarationNameInfo(); 12381 C->setQualifierLoc(NNSL); 12382 C->setNameInfo(DNI); 12383 12384 unsigned NumVars = C->varlist_size(); 12385 SmallVector<Expr *, 16> Vars; 12386 Vars.reserve(NumVars); 12387 for (unsigned I = 0; I != NumVars; ++I) 12388 Vars.push_back(Record.readSubExpr()); 12389 C->setVarRefs(Vars); 12390 Vars.clear(); 12391 for (unsigned I = 0; I != NumVars; ++I) 12392 Vars.push_back(Record.readSubExpr()); 12393 C->setPrivates(Vars); 12394 Vars.clear(); 12395 for (unsigned I = 0; I != NumVars; ++I) 12396 Vars.push_back(Record.readSubExpr()); 12397 C->setLHSExprs(Vars); 12398 Vars.clear(); 12399 for (unsigned I = 0; I != NumVars; ++I) 12400 Vars.push_back(Record.readSubExpr()); 12401 C->setRHSExprs(Vars); 12402 Vars.clear(); 12403 for (unsigned I = 0; I != NumVars; ++I) 12404 Vars.push_back(Record.readSubExpr()); 12405 C->setReductionOps(Vars); 12406 } 12407 12408 void OMPClauseReader::VisitOMPInReductionClause(OMPInReductionClause *C) { 12409 VisitOMPClauseWithPostUpdate(C); 12410 C->setLParenLoc(Record.readSourceLocation()); 12411 C->setColonLoc(Record.readSourceLocation()); 12412 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc(); 12413 DeclarationNameInfo DNI = Record.readDeclarationNameInfo(); 12414 C->setQualifierLoc(NNSL); 12415 C->setNameInfo(DNI); 12416 12417 unsigned NumVars = C->varlist_size(); 12418 SmallVector<Expr *, 16> Vars; 12419 Vars.reserve(NumVars); 12420 for (unsigned I = 0; I != NumVars; ++I) 12421 Vars.push_back(Record.readSubExpr()); 12422 C->setVarRefs(Vars); 12423 Vars.clear(); 12424 for (unsigned I = 0; I != NumVars; ++I) 12425 Vars.push_back(Record.readSubExpr()); 12426 C->setPrivates(Vars); 12427 Vars.clear(); 12428 for (unsigned I = 0; I != NumVars; ++I) 12429 Vars.push_back(Record.readSubExpr()); 12430 C->setLHSExprs(Vars); 12431 Vars.clear(); 12432 for (unsigned I = 0; I != NumVars; ++I) 12433 Vars.push_back(Record.readSubExpr()); 12434 C->setRHSExprs(Vars); 12435 Vars.clear(); 12436 for (unsigned I = 0; I != NumVars; ++I) 12437 Vars.push_back(Record.readSubExpr()); 12438 C->setReductionOps(Vars); 12439 Vars.clear(); 12440 for (unsigned I = 0; I != NumVars; ++I) 12441 Vars.push_back(Record.readSubExpr()); 12442 C->setTaskgroupDescriptors(Vars); 12443 } 12444 12445 void OMPClauseReader::VisitOMPLinearClause(OMPLinearClause *C) { 12446 VisitOMPClauseWithPostUpdate(C); 12447 C->setLParenLoc(Record.readSourceLocation()); 12448 C->setColonLoc(Record.readSourceLocation()); 12449 C->setModifier(static_cast<OpenMPLinearClauseKind>(Record.readInt())); 12450 C->setModifierLoc(Record.readSourceLocation()); 12451 unsigned NumVars = C->varlist_size(); 12452 SmallVector<Expr *, 16> Vars; 12453 Vars.reserve(NumVars); 12454 for (unsigned i = 0; i != NumVars; ++i) 12455 Vars.push_back(Record.readSubExpr()); 12456 C->setVarRefs(Vars); 12457 Vars.clear(); 12458 for (unsigned i = 0; i != NumVars; ++i) 12459 Vars.push_back(Record.readSubExpr()); 12460 C->setPrivates(Vars); 12461 Vars.clear(); 12462 for (unsigned i = 0; i != NumVars; ++i) 12463 Vars.push_back(Record.readSubExpr()); 12464 C->setInits(Vars); 12465 Vars.clear(); 12466 for (unsigned i = 0; i != NumVars; ++i) 12467 Vars.push_back(Record.readSubExpr()); 12468 C->setUpdates(Vars); 12469 Vars.clear(); 12470 for (unsigned i = 0; i != NumVars; ++i) 12471 Vars.push_back(Record.readSubExpr()); 12472 C->setFinals(Vars); 12473 C->setStep(Record.readSubExpr()); 12474 C->setCalcStep(Record.readSubExpr()); 12475 Vars.clear(); 12476 for (unsigned I = 0; I != NumVars + 1; ++I) 12477 Vars.push_back(Record.readSubExpr()); 12478 C->setUsedExprs(Vars); 12479 } 12480 12481 void OMPClauseReader::VisitOMPAlignedClause(OMPAlignedClause *C) { 12482 C->setLParenLoc(Record.readSourceLocation()); 12483 C->setColonLoc(Record.readSourceLocation()); 12484 unsigned NumVars = C->varlist_size(); 12485 SmallVector<Expr *, 16> Vars; 12486 Vars.reserve(NumVars); 12487 for (unsigned i = 0; i != NumVars; ++i) 12488 Vars.push_back(Record.readSubExpr()); 12489 C->setVarRefs(Vars); 12490 C->setAlignment(Record.readSubExpr()); 12491 } 12492 12493 void OMPClauseReader::VisitOMPCopyinClause(OMPCopyinClause *C) { 12494 C->setLParenLoc(Record.readSourceLocation()); 12495 unsigned NumVars = C->varlist_size(); 12496 SmallVector<Expr *, 16> Exprs; 12497 Exprs.reserve(NumVars); 12498 for (unsigned i = 0; i != NumVars; ++i) 12499 Exprs.push_back(Record.readSubExpr()); 12500 C->setVarRefs(Exprs); 12501 Exprs.clear(); 12502 for (unsigned i = 0; i != NumVars; ++i) 12503 Exprs.push_back(Record.readSubExpr()); 12504 C->setSourceExprs(Exprs); 12505 Exprs.clear(); 12506 for (unsigned i = 0; i != NumVars; ++i) 12507 Exprs.push_back(Record.readSubExpr()); 12508 C->setDestinationExprs(Exprs); 12509 Exprs.clear(); 12510 for (unsigned i = 0; i != NumVars; ++i) 12511 Exprs.push_back(Record.readSubExpr()); 12512 C->setAssignmentOps(Exprs); 12513 } 12514 12515 void OMPClauseReader::VisitOMPCopyprivateClause(OMPCopyprivateClause *C) { 12516 C->setLParenLoc(Record.readSourceLocation()); 12517 unsigned NumVars = C->varlist_size(); 12518 SmallVector<Expr *, 16> Exprs; 12519 Exprs.reserve(NumVars); 12520 for (unsigned i = 0; i != NumVars; ++i) 12521 Exprs.push_back(Record.readSubExpr()); 12522 C->setVarRefs(Exprs); 12523 Exprs.clear(); 12524 for (unsigned i = 0; i != NumVars; ++i) 12525 Exprs.push_back(Record.readSubExpr()); 12526 C->setSourceExprs(Exprs); 12527 Exprs.clear(); 12528 for (unsigned i = 0; i != NumVars; ++i) 12529 Exprs.push_back(Record.readSubExpr()); 12530 C->setDestinationExprs(Exprs); 12531 Exprs.clear(); 12532 for (unsigned i = 0; i != NumVars; ++i) 12533 Exprs.push_back(Record.readSubExpr()); 12534 C->setAssignmentOps(Exprs); 12535 } 12536 12537 void OMPClauseReader::VisitOMPFlushClause(OMPFlushClause *C) { 12538 C->setLParenLoc(Record.readSourceLocation()); 12539 unsigned NumVars = C->varlist_size(); 12540 SmallVector<Expr *, 16> Vars; 12541 Vars.reserve(NumVars); 12542 for (unsigned i = 0; i != NumVars; ++i) 12543 Vars.push_back(Record.readSubExpr()); 12544 C->setVarRefs(Vars); 12545 } 12546 12547 void OMPClauseReader::VisitOMPDepobjClause(OMPDepobjClause *C) { 12548 C->setDepobj(Record.readSubExpr()); 12549 C->setLParenLoc(Record.readSourceLocation()); 12550 } 12551 12552 void OMPClauseReader::VisitOMPDependClause(OMPDependClause *C) { 12553 C->setLParenLoc(Record.readSourceLocation()); 12554 C->setModifier(Record.readSubExpr()); 12555 C->setDependencyKind( 12556 static_cast<OpenMPDependClauseKind>(Record.readInt())); 12557 C->setDependencyLoc(Record.readSourceLocation()); 12558 C->setColonLoc(Record.readSourceLocation()); 12559 unsigned NumVars = C->varlist_size(); 12560 SmallVector<Expr *, 16> Vars; 12561 Vars.reserve(NumVars); 12562 for (unsigned I = 0; I != NumVars; ++I) 12563 Vars.push_back(Record.readSubExpr()); 12564 C->setVarRefs(Vars); 12565 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I) 12566 C->setLoopData(I, Record.readSubExpr()); 12567 } 12568 12569 void OMPClauseReader::VisitOMPDeviceClause(OMPDeviceClause *C) { 12570 VisitOMPClauseWithPreInit(C); 12571 C->setModifier(Record.readEnum<OpenMPDeviceClauseModifier>()); 12572 C->setDevice(Record.readSubExpr()); 12573 C->setModifierLoc(Record.readSourceLocation()); 12574 C->setLParenLoc(Record.readSourceLocation()); 12575 } 12576 12577 void OMPClauseReader::VisitOMPMapClause(OMPMapClause *C) { 12578 C->setLParenLoc(Record.readSourceLocation()); 12579 for (unsigned I = 0; I < NumberOfOMPMapClauseModifiers; ++I) { 12580 C->setMapTypeModifier( 12581 I, static_cast<OpenMPMapModifierKind>(Record.readInt())); 12582 C->setMapTypeModifierLoc(I, Record.readSourceLocation()); 12583 } 12584 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc()); 12585 C->setMapperIdInfo(Record.readDeclarationNameInfo()); 12586 C->setMapType( 12587 static_cast<OpenMPMapClauseKind>(Record.readInt())); 12588 C->setMapLoc(Record.readSourceLocation()); 12589 C->setColonLoc(Record.readSourceLocation()); 12590 auto NumVars = C->varlist_size(); 12591 auto UniqueDecls = C->getUniqueDeclarationsNum(); 12592 auto TotalLists = C->getTotalComponentListNum(); 12593 auto TotalComponents = C->getTotalComponentsNum(); 12594 12595 SmallVector<Expr *, 16> Vars; 12596 Vars.reserve(NumVars); 12597 for (unsigned i = 0; i != NumVars; ++i) 12598 Vars.push_back(Record.readExpr()); 12599 C->setVarRefs(Vars); 12600 12601 SmallVector<Expr *, 16> UDMappers; 12602 UDMappers.reserve(NumVars); 12603 for (unsigned I = 0; I < NumVars; ++I) 12604 UDMappers.push_back(Record.readExpr()); 12605 C->setUDMapperRefs(UDMappers); 12606 12607 SmallVector<ValueDecl *, 16> Decls; 12608 Decls.reserve(UniqueDecls); 12609 for (unsigned i = 0; i < UniqueDecls; ++i) 12610 Decls.push_back(Record.readDeclAs<ValueDecl>()); 12611 C->setUniqueDecls(Decls); 12612 12613 SmallVector<unsigned, 16> ListsPerDecl; 12614 ListsPerDecl.reserve(UniqueDecls); 12615 for (unsigned i = 0; i < UniqueDecls; ++i) 12616 ListsPerDecl.push_back(Record.readInt()); 12617 C->setDeclNumLists(ListsPerDecl); 12618 12619 SmallVector<unsigned, 32> ListSizes; 12620 ListSizes.reserve(TotalLists); 12621 for (unsigned i = 0; i < TotalLists; ++i) 12622 ListSizes.push_back(Record.readInt()); 12623 C->setComponentListSizes(ListSizes); 12624 12625 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components; 12626 Components.reserve(TotalComponents); 12627 for (unsigned i = 0; i < TotalComponents; ++i) { 12628 Expr *AssociatedExprPr = Record.readExpr(); 12629 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>(); 12630 Components.emplace_back(AssociatedExprPr, AssociatedDecl, 12631 /*IsNonContiguous=*/false); 12632 } 12633 C->setComponents(Components, ListSizes); 12634 } 12635 12636 void OMPClauseReader::VisitOMPAllocateClause(OMPAllocateClause *C) { 12637 C->setLParenLoc(Record.readSourceLocation()); 12638 C->setColonLoc(Record.readSourceLocation()); 12639 C->setAllocator(Record.readSubExpr()); 12640 unsigned NumVars = C->varlist_size(); 12641 SmallVector<Expr *, 16> Vars; 12642 Vars.reserve(NumVars); 12643 for (unsigned i = 0; i != NumVars; ++i) 12644 Vars.push_back(Record.readSubExpr()); 12645 C->setVarRefs(Vars); 12646 } 12647 12648 void OMPClauseReader::VisitOMPNumTeamsClause(OMPNumTeamsClause *C) { 12649 VisitOMPClauseWithPreInit(C); 12650 C->setNumTeams(Record.readSubExpr()); 12651 C->setLParenLoc(Record.readSourceLocation()); 12652 } 12653 12654 void OMPClauseReader::VisitOMPThreadLimitClause(OMPThreadLimitClause *C) { 12655 VisitOMPClauseWithPreInit(C); 12656 C->setThreadLimit(Record.readSubExpr()); 12657 C->setLParenLoc(Record.readSourceLocation()); 12658 } 12659 12660 void OMPClauseReader::VisitOMPPriorityClause(OMPPriorityClause *C) { 12661 VisitOMPClauseWithPreInit(C); 12662 C->setPriority(Record.readSubExpr()); 12663 C->setLParenLoc(Record.readSourceLocation()); 12664 } 12665 12666 void OMPClauseReader::VisitOMPGrainsizeClause(OMPGrainsizeClause *C) { 12667 VisitOMPClauseWithPreInit(C); 12668 C->setGrainsize(Record.readSubExpr()); 12669 C->setLParenLoc(Record.readSourceLocation()); 12670 } 12671 12672 void OMPClauseReader::VisitOMPNumTasksClause(OMPNumTasksClause *C) { 12673 VisitOMPClauseWithPreInit(C); 12674 C->setNumTasks(Record.readSubExpr()); 12675 C->setLParenLoc(Record.readSourceLocation()); 12676 } 12677 12678 void OMPClauseReader::VisitOMPHintClause(OMPHintClause *C) { 12679 C->setHint(Record.readSubExpr()); 12680 C->setLParenLoc(Record.readSourceLocation()); 12681 } 12682 12683 void OMPClauseReader::VisitOMPDistScheduleClause(OMPDistScheduleClause *C) { 12684 VisitOMPClauseWithPreInit(C); 12685 C->setDistScheduleKind( 12686 static_cast<OpenMPDistScheduleClauseKind>(Record.readInt())); 12687 C->setChunkSize(Record.readSubExpr()); 12688 C->setLParenLoc(Record.readSourceLocation()); 12689 C->setDistScheduleKindLoc(Record.readSourceLocation()); 12690 C->setCommaLoc(Record.readSourceLocation()); 12691 } 12692 12693 void OMPClauseReader::VisitOMPDefaultmapClause(OMPDefaultmapClause *C) { 12694 C->setDefaultmapKind( 12695 static_cast<OpenMPDefaultmapClauseKind>(Record.readInt())); 12696 C->setDefaultmapModifier( 12697 static_cast<OpenMPDefaultmapClauseModifier>(Record.readInt())); 12698 C->setLParenLoc(Record.readSourceLocation()); 12699 C->setDefaultmapModifierLoc(Record.readSourceLocation()); 12700 C->setDefaultmapKindLoc(Record.readSourceLocation()); 12701 } 12702 12703 void OMPClauseReader::VisitOMPToClause(OMPToClause *C) { 12704 C->setLParenLoc(Record.readSourceLocation()); 12705 for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) { 12706 C->setMotionModifier( 12707 I, static_cast<OpenMPMotionModifierKind>(Record.readInt())); 12708 C->setMotionModifierLoc(I, Record.readSourceLocation()); 12709 } 12710 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc()); 12711 C->setMapperIdInfo(Record.readDeclarationNameInfo()); 12712 C->setColonLoc(Record.readSourceLocation()); 12713 auto NumVars = C->varlist_size(); 12714 auto UniqueDecls = C->getUniqueDeclarationsNum(); 12715 auto TotalLists = C->getTotalComponentListNum(); 12716 auto TotalComponents = C->getTotalComponentsNum(); 12717 12718 SmallVector<Expr *, 16> Vars; 12719 Vars.reserve(NumVars); 12720 for (unsigned i = 0; i != NumVars; ++i) 12721 Vars.push_back(Record.readSubExpr()); 12722 C->setVarRefs(Vars); 12723 12724 SmallVector<Expr *, 16> UDMappers; 12725 UDMappers.reserve(NumVars); 12726 for (unsigned I = 0; I < NumVars; ++I) 12727 UDMappers.push_back(Record.readSubExpr()); 12728 C->setUDMapperRefs(UDMappers); 12729 12730 SmallVector<ValueDecl *, 16> Decls; 12731 Decls.reserve(UniqueDecls); 12732 for (unsigned i = 0; i < UniqueDecls; ++i) 12733 Decls.push_back(Record.readDeclAs<ValueDecl>()); 12734 C->setUniqueDecls(Decls); 12735 12736 SmallVector<unsigned, 16> ListsPerDecl; 12737 ListsPerDecl.reserve(UniqueDecls); 12738 for (unsigned i = 0; i < UniqueDecls; ++i) 12739 ListsPerDecl.push_back(Record.readInt()); 12740 C->setDeclNumLists(ListsPerDecl); 12741 12742 SmallVector<unsigned, 32> ListSizes; 12743 ListSizes.reserve(TotalLists); 12744 for (unsigned i = 0; i < TotalLists; ++i) 12745 ListSizes.push_back(Record.readInt()); 12746 C->setComponentListSizes(ListSizes); 12747 12748 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components; 12749 Components.reserve(TotalComponents); 12750 for (unsigned i = 0; i < TotalComponents; ++i) { 12751 Expr *AssociatedExprPr = Record.readSubExpr(); 12752 bool IsNonContiguous = Record.readBool(); 12753 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>(); 12754 Components.emplace_back(AssociatedExprPr, AssociatedDecl, IsNonContiguous); 12755 } 12756 C->setComponents(Components, ListSizes); 12757 } 12758 12759 void OMPClauseReader::VisitOMPFromClause(OMPFromClause *C) { 12760 C->setLParenLoc(Record.readSourceLocation()); 12761 for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) { 12762 C->setMotionModifier( 12763 I, static_cast<OpenMPMotionModifierKind>(Record.readInt())); 12764 C->setMotionModifierLoc(I, Record.readSourceLocation()); 12765 } 12766 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc()); 12767 C->setMapperIdInfo(Record.readDeclarationNameInfo()); 12768 C->setColonLoc(Record.readSourceLocation()); 12769 auto NumVars = C->varlist_size(); 12770 auto UniqueDecls = C->getUniqueDeclarationsNum(); 12771 auto TotalLists = C->getTotalComponentListNum(); 12772 auto TotalComponents = C->getTotalComponentsNum(); 12773 12774 SmallVector<Expr *, 16> Vars; 12775 Vars.reserve(NumVars); 12776 for (unsigned i = 0; i != NumVars; ++i) 12777 Vars.push_back(Record.readSubExpr()); 12778 C->setVarRefs(Vars); 12779 12780 SmallVector<Expr *, 16> UDMappers; 12781 UDMappers.reserve(NumVars); 12782 for (unsigned I = 0; I < NumVars; ++I) 12783 UDMappers.push_back(Record.readSubExpr()); 12784 C->setUDMapperRefs(UDMappers); 12785 12786 SmallVector<ValueDecl *, 16> Decls; 12787 Decls.reserve(UniqueDecls); 12788 for (unsigned i = 0; i < UniqueDecls; ++i) 12789 Decls.push_back(Record.readDeclAs<ValueDecl>()); 12790 C->setUniqueDecls(Decls); 12791 12792 SmallVector<unsigned, 16> ListsPerDecl; 12793 ListsPerDecl.reserve(UniqueDecls); 12794 for (unsigned i = 0; i < UniqueDecls; ++i) 12795 ListsPerDecl.push_back(Record.readInt()); 12796 C->setDeclNumLists(ListsPerDecl); 12797 12798 SmallVector<unsigned, 32> ListSizes; 12799 ListSizes.reserve(TotalLists); 12800 for (unsigned i = 0; i < TotalLists; ++i) 12801 ListSizes.push_back(Record.readInt()); 12802 C->setComponentListSizes(ListSizes); 12803 12804 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components; 12805 Components.reserve(TotalComponents); 12806 for (unsigned i = 0; i < TotalComponents; ++i) { 12807 Expr *AssociatedExprPr = Record.readSubExpr(); 12808 bool IsNonContiguous = Record.readBool(); 12809 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>(); 12810 Components.emplace_back(AssociatedExprPr, AssociatedDecl, IsNonContiguous); 12811 } 12812 C->setComponents(Components, ListSizes); 12813 } 12814 12815 void OMPClauseReader::VisitOMPUseDevicePtrClause(OMPUseDevicePtrClause *C) { 12816 C->setLParenLoc(Record.readSourceLocation()); 12817 auto NumVars = C->varlist_size(); 12818 auto UniqueDecls = C->getUniqueDeclarationsNum(); 12819 auto TotalLists = C->getTotalComponentListNum(); 12820 auto TotalComponents = C->getTotalComponentsNum(); 12821 12822 SmallVector<Expr *, 16> Vars; 12823 Vars.reserve(NumVars); 12824 for (unsigned i = 0; i != NumVars; ++i) 12825 Vars.push_back(Record.readSubExpr()); 12826 C->setVarRefs(Vars); 12827 Vars.clear(); 12828 for (unsigned i = 0; i != NumVars; ++i) 12829 Vars.push_back(Record.readSubExpr()); 12830 C->setPrivateCopies(Vars); 12831 Vars.clear(); 12832 for (unsigned i = 0; i != NumVars; ++i) 12833 Vars.push_back(Record.readSubExpr()); 12834 C->setInits(Vars); 12835 12836 SmallVector<ValueDecl *, 16> Decls; 12837 Decls.reserve(UniqueDecls); 12838 for (unsigned i = 0; i < UniqueDecls; ++i) 12839 Decls.push_back(Record.readDeclAs<ValueDecl>()); 12840 C->setUniqueDecls(Decls); 12841 12842 SmallVector<unsigned, 16> ListsPerDecl; 12843 ListsPerDecl.reserve(UniqueDecls); 12844 for (unsigned i = 0; i < UniqueDecls; ++i) 12845 ListsPerDecl.push_back(Record.readInt()); 12846 C->setDeclNumLists(ListsPerDecl); 12847 12848 SmallVector<unsigned, 32> ListSizes; 12849 ListSizes.reserve(TotalLists); 12850 for (unsigned i = 0; i < TotalLists; ++i) 12851 ListSizes.push_back(Record.readInt()); 12852 C->setComponentListSizes(ListSizes); 12853 12854 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components; 12855 Components.reserve(TotalComponents); 12856 for (unsigned i = 0; i < TotalComponents; ++i) { 12857 auto *AssociatedExprPr = Record.readSubExpr(); 12858 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>(); 12859 Components.emplace_back(AssociatedExprPr, AssociatedDecl, 12860 /*IsNonContiguous=*/false); 12861 } 12862 C->setComponents(Components, ListSizes); 12863 } 12864 12865 void OMPClauseReader::VisitOMPUseDeviceAddrClause(OMPUseDeviceAddrClause *C) { 12866 C->setLParenLoc(Record.readSourceLocation()); 12867 auto NumVars = C->varlist_size(); 12868 auto UniqueDecls = C->getUniqueDeclarationsNum(); 12869 auto TotalLists = C->getTotalComponentListNum(); 12870 auto TotalComponents = C->getTotalComponentsNum(); 12871 12872 SmallVector<Expr *, 16> Vars; 12873 Vars.reserve(NumVars); 12874 for (unsigned i = 0; i != NumVars; ++i) 12875 Vars.push_back(Record.readSubExpr()); 12876 C->setVarRefs(Vars); 12877 12878 SmallVector<ValueDecl *, 16> Decls; 12879 Decls.reserve(UniqueDecls); 12880 for (unsigned i = 0; i < UniqueDecls; ++i) 12881 Decls.push_back(Record.readDeclAs<ValueDecl>()); 12882 C->setUniqueDecls(Decls); 12883 12884 SmallVector<unsigned, 16> ListsPerDecl; 12885 ListsPerDecl.reserve(UniqueDecls); 12886 for (unsigned i = 0; i < UniqueDecls; ++i) 12887 ListsPerDecl.push_back(Record.readInt()); 12888 C->setDeclNumLists(ListsPerDecl); 12889 12890 SmallVector<unsigned, 32> ListSizes; 12891 ListSizes.reserve(TotalLists); 12892 for (unsigned i = 0; i < TotalLists; ++i) 12893 ListSizes.push_back(Record.readInt()); 12894 C->setComponentListSizes(ListSizes); 12895 12896 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components; 12897 Components.reserve(TotalComponents); 12898 for (unsigned i = 0; i < TotalComponents; ++i) { 12899 Expr *AssociatedExpr = Record.readSubExpr(); 12900 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>(); 12901 Components.emplace_back(AssociatedExpr, AssociatedDecl, 12902 /*IsNonContiguous*/ false); 12903 } 12904 C->setComponents(Components, ListSizes); 12905 } 12906 12907 void OMPClauseReader::VisitOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) { 12908 C->setLParenLoc(Record.readSourceLocation()); 12909 auto NumVars = C->varlist_size(); 12910 auto UniqueDecls = C->getUniqueDeclarationsNum(); 12911 auto TotalLists = C->getTotalComponentListNum(); 12912 auto TotalComponents = C->getTotalComponentsNum(); 12913 12914 SmallVector<Expr *, 16> Vars; 12915 Vars.reserve(NumVars); 12916 for (unsigned i = 0; i != NumVars; ++i) 12917 Vars.push_back(Record.readSubExpr()); 12918 C->setVarRefs(Vars); 12919 Vars.clear(); 12920 12921 SmallVector<ValueDecl *, 16> Decls; 12922 Decls.reserve(UniqueDecls); 12923 for (unsigned i = 0; i < UniqueDecls; ++i) 12924 Decls.push_back(Record.readDeclAs<ValueDecl>()); 12925 C->setUniqueDecls(Decls); 12926 12927 SmallVector<unsigned, 16> ListsPerDecl; 12928 ListsPerDecl.reserve(UniqueDecls); 12929 for (unsigned i = 0; i < UniqueDecls; ++i) 12930 ListsPerDecl.push_back(Record.readInt()); 12931 C->setDeclNumLists(ListsPerDecl); 12932 12933 SmallVector<unsigned, 32> ListSizes; 12934 ListSizes.reserve(TotalLists); 12935 for (unsigned i = 0; i < TotalLists; ++i) 12936 ListSizes.push_back(Record.readInt()); 12937 C->setComponentListSizes(ListSizes); 12938 12939 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components; 12940 Components.reserve(TotalComponents); 12941 for (unsigned i = 0; i < TotalComponents; ++i) { 12942 Expr *AssociatedExpr = Record.readSubExpr(); 12943 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>(); 12944 Components.emplace_back(AssociatedExpr, AssociatedDecl, 12945 /*IsNonContiguous=*/false); 12946 } 12947 C->setComponents(Components, ListSizes); 12948 } 12949 12950 void OMPClauseReader::VisitOMPNontemporalClause(OMPNontemporalClause *C) { 12951 C->setLParenLoc(Record.readSourceLocation()); 12952 unsigned NumVars = C->varlist_size(); 12953 SmallVector<Expr *, 16> Vars; 12954 Vars.reserve(NumVars); 12955 for (unsigned i = 0; i != NumVars; ++i) 12956 Vars.push_back(Record.readSubExpr()); 12957 C->setVarRefs(Vars); 12958 Vars.clear(); 12959 Vars.reserve(NumVars); 12960 for (unsigned i = 0; i != NumVars; ++i) 12961 Vars.push_back(Record.readSubExpr()); 12962 C->setPrivateRefs(Vars); 12963 } 12964 12965 void OMPClauseReader::VisitOMPInclusiveClause(OMPInclusiveClause *C) { 12966 C->setLParenLoc(Record.readSourceLocation()); 12967 unsigned NumVars = C->varlist_size(); 12968 SmallVector<Expr *, 16> Vars; 12969 Vars.reserve(NumVars); 12970 for (unsigned i = 0; i != NumVars; ++i) 12971 Vars.push_back(Record.readSubExpr()); 12972 C->setVarRefs(Vars); 12973 } 12974 12975 void OMPClauseReader::VisitOMPExclusiveClause(OMPExclusiveClause *C) { 12976 C->setLParenLoc(Record.readSourceLocation()); 12977 unsigned NumVars = C->varlist_size(); 12978 SmallVector<Expr *, 16> Vars; 12979 Vars.reserve(NumVars); 12980 for (unsigned i = 0; i != NumVars; ++i) 12981 Vars.push_back(Record.readSubExpr()); 12982 C->setVarRefs(Vars); 12983 } 12984 12985 void OMPClauseReader::VisitOMPUsesAllocatorsClause(OMPUsesAllocatorsClause *C) { 12986 C->setLParenLoc(Record.readSourceLocation()); 12987 unsigned NumOfAllocators = C->getNumberOfAllocators(); 12988 SmallVector<OMPUsesAllocatorsClause::Data, 4> Data; 12989 Data.reserve(NumOfAllocators); 12990 for (unsigned I = 0; I != NumOfAllocators; ++I) { 12991 OMPUsesAllocatorsClause::Data &D = Data.emplace_back(); 12992 D.Allocator = Record.readSubExpr(); 12993 D.AllocatorTraits = Record.readSubExpr(); 12994 D.LParenLoc = Record.readSourceLocation(); 12995 D.RParenLoc = Record.readSourceLocation(); 12996 } 12997 C->setAllocatorsData(Data); 12998 } 12999 13000 void OMPClauseReader::VisitOMPAffinityClause(OMPAffinityClause *C) { 13001 C->setLParenLoc(Record.readSourceLocation()); 13002 C->setModifier(Record.readSubExpr()); 13003 C->setColonLoc(Record.readSourceLocation()); 13004 unsigned NumOfLocators = C->varlist_size(); 13005 SmallVector<Expr *, 4> Locators; 13006 Locators.reserve(NumOfLocators); 13007 for (unsigned I = 0; I != NumOfLocators; ++I) 13008 Locators.push_back(Record.readSubExpr()); 13009 C->setVarRefs(Locators); 13010 } 13011 13012 void OMPClauseReader::VisitOMPOrderClause(OMPOrderClause *C) { 13013 C->setKind(Record.readEnum<OpenMPOrderClauseKind>()); 13014 C->setLParenLoc(Record.readSourceLocation()); 13015 C->setKindKwLoc(Record.readSourceLocation()); 13016 } 13017 13018 OMPTraitInfo *ASTRecordReader::readOMPTraitInfo() { 13019 OMPTraitInfo &TI = getContext().getNewOMPTraitInfo(); 13020 TI.Sets.resize(readUInt32()); 13021 for (auto &Set : TI.Sets) { 13022 Set.Kind = readEnum<llvm::omp::TraitSet>(); 13023 Set.Selectors.resize(readUInt32()); 13024 for (auto &Selector : Set.Selectors) { 13025 Selector.Kind = readEnum<llvm::omp::TraitSelector>(); 13026 Selector.ScoreOrCondition = nullptr; 13027 if (readBool()) 13028 Selector.ScoreOrCondition = readExprRef(); 13029 Selector.Properties.resize(readUInt32()); 13030 for (auto &Property : Selector.Properties) 13031 Property.Kind = readEnum<llvm::omp::TraitProperty>(); 13032 } 13033 } 13034 return &TI; 13035 } 13036 13037 void ASTRecordReader::readOMPChildren(OMPChildren *Data) { 13038 if (!Data) 13039 return; 13040 if (Reader->ReadingKind == ASTReader::Read_Stmt) { 13041 // Skip NumClauses, NumChildren and HasAssociatedStmt fields. 13042 skipInts(3); 13043 } 13044 SmallVector<OMPClause *, 4> Clauses(Data->getNumClauses()); 13045 for (unsigned I = 0, E = Data->getNumClauses(); I < E; ++I) 13046 Clauses[I] = readOMPClause(); 13047 Data->setClauses(Clauses); 13048 if (Data->hasAssociatedStmt()) 13049 Data->setAssociatedStmt(readStmt()); 13050 for (unsigned I = 0, E = Data->getNumChildren(); I < E; ++I) 13051 Data->getChildren()[I] = readStmt(); 13052 } 13053