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), 1919 *FileMgr.getOptionalFileRef(Filename)}; 1920 ModMap.addHeader(Mod, H, HeaderRole, /*Imported*/true); 1921 HFI.isModuleHeader |= !(HeaderRole & ModuleMap::TextualHeader); 1922 } 1923 1924 // This HeaderFileInfo was externally loaded. 1925 HFI.External = true; 1926 HFI.IsValid = true; 1927 return HFI; 1928 } 1929 1930 void ASTReader::addPendingMacro(IdentifierInfo *II, ModuleFile *M, 1931 uint32_t MacroDirectivesOffset) { 1932 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard"); 1933 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset)); 1934 } 1935 1936 void ASTReader::ReadDefinedMacros() { 1937 // Note that we are loading defined macros. 1938 Deserializing Macros(this); 1939 1940 for (ModuleFile &I : llvm::reverse(ModuleMgr)) { 1941 BitstreamCursor &MacroCursor = I.MacroCursor; 1942 1943 // If there was no preprocessor block, skip this file. 1944 if (MacroCursor.getBitcodeBytes().empty()) 1945 continue; 1946 1947 BitstreamCursor Cursor = MacroCursor; 1948 if (llvm::Error Err = Cursor.JumpToBit(I.MacroStartOffset)) { 1949 Error(std::move(Err)); 1950 return; 1951 } 1952 1953 RecordData Record; 1954 while (true) { 1955 Expected<llvm::BitstreamEntry> MaybeE = Cursor.advanceSkippingSubblocks(); 1956 if (!MaybeE) { 1957 Error(MaybeE.takeError()); 1958 return; 1959 } 1960 llvm::BitstreamEntry E = MaybeE.get(); 1961 1962 switch (E.Kind) { 1963 case llvm::BitstreamEntry::SubBlock: // Handled for us already. 1964 case llvm::BitstreamEntry::Error: 1965 Error("malformed block record in AST file"); 1966 return; 1967 case llvm::BitstreamEntry::EndBlock: 1968 goto NextCursor; 1969 1970 case llvm::BitstreamEntry::Record: { 1971 Record.clear(); 1972 Expected<unsigned> MaybeRecord = Cursor.readRecord(E.ID, Record); 1973 if (!MaybeRecord) { 1974 Error(MaybeRecord.takeError()); 1975 return; 1976 } 1977 switch (MaybeRecord.get()) { 1978 default: // Default behavior: ignore. 1979 break; 1980 1981 case PP_MACRO_OBJECT_LIKE: 1982 case PP_MACRO_FUNCTION_LIKE: { 1983 IdentifierInfo *II = getLocalIdentifier(I, Record[0]); 1984 if (II->isOutOfDate()) 1985 updateOutOfDateIdentifier(*II); 1986 break; 1987 } 1988 1989 case PP_TOKEN: 1990 // Ignore tokens. 1991 break; 1992 } 1993 break; 1994 } 1995 } 1996 } 1997 NextCursor: ; 1998 } 1999 } 2000 2001 namespace { 2002 2003 /// Visitor class used to look up identifirs in an AST file. 2004 class IdentifierLookupVisitor { 2005 StringRef Name; 2006 unsigned NameHash; 2007 unsigned PriorGeneration; 2008 unsigned &NumIdentifierLookups; 2009 unsigned &NumIdentifierLookupHits; 2010 IdentifierInfo *Found = nullptr; 2011 2012 public: 2013 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration, 2014 unsigned &NumIdentifierLookups, 2015 unsigned &NumIdentifierLookupHits) 2016 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)), 2017 PriorGeneration(PriorGeneration), 2018 NumIdentifierLookups(NumIdentifierLookups), 2019 NumIdentifierLookupHits(NumIdentifierLookupHits) {} 2020 2021 bool operator()(ModuleFile &M) { 2022 // If we've already searched this module file, skip it now. 2023 if (M.Generation <= PriorGeneration) 2024 return true; 2025 2026 ASTIdentifierLookupTable *IdTable 2027 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable; 2028 if (!IdTable) 2029 return false; 2030 2031 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M, 2032 Found); 2033 ++NumIdentifierLookups; 2034 ASTIdentifierLookupTable::iterator Pos = 2035 IdTable->find_hashed(Name, NameHash, &Trait); 2036 if (Pos == IdTable->end()) 2037 return false; 2038 2039 // Dereferencing the iterator has the effect of building the 2040 // IdentifierInfo node and populating it with the various 2041 // declarations it needs. 2042 ++NumIdentifierLookupHits; 2043 Found = *Pos; 2044 return true; 2045 } 2046 2047 // Retrieve the identifier info found within the module 2048 // files. 2049 IdentifierInfo *getIdentifierInfo() const { return Found; } 2050 }; 2051 2052 } // namespace 2053 2054 void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) { 2055 // Note that we are loading an identifier. 2056 Deserializing AnIdentifier(this); 2057 2058 unsigned PriorGeneration = 0; 2059 if (getContext().getLangOpts().Modules) 2060 PriorGeneration = IdentifierGeneration[&II]; 2061 2062 // If there is a global index, look there first to determine which modules 2063 // provably do not have any results for this identifier. 2064 GlobalModuleIndex::HitSet Hits; 2065 GlobalModuleIndex::HitSet *HitsPtr = nullptr; 2066 if (!loadGlobalIndex()) { 2067 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) { 2068 HitsPtr = &Hits; 2069 } 2070 } 2071 2072 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration, 2073 NumIdentifierLookups, 2074 NumIdentifierLookupHits); 2075 ModuleMgr.visit(Visitor, HitsPtr); 2076 markIdentifierUpToDate(&II); 2077 } 2078 2079 void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) { 2080 if (!II) 2081 return; 2082 2083 II->setOutOfDate(false); 2084 2085 // Update the generation for this identifier. 2086 if (getContext().getLangOpts().Modules) 2087 IdentifierGeneration[II] = getGeneration(); 2088 } 2089 2090 void ASTReader::resolvePendingMacro(IdentifierInfo *II, 2091 const PendingMacroInfo &PMInfo) { 2092 ModuleFile &M = *PMInfo.M; 2093 2094 BitstreamCursor &Cursor = M.MacroCursor; 2095 SavedStreamPosition SavedPosition(Cursor); 2096 if (llvm::Error Err = 2097 Cursor.JumpToBit(M.MacroOffsetsBase + PMInfo.MacroDirectivesOffset)) { 2098 Error(std::move(Err)); 2099 return; 2100 } 2101 2102 struct ModuleMacroRecord { 2103 SubmoduleID SubModID; 2104 MacroInfo *MI; 2105 SmallVector<SubmoduleID, 8> Overrides; 2106 }; 2107 llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros; 2108 2109 // We expect to see a sequence of PP_MODULE_MACRO records listing exported 2110 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete 2111 // macro histroy. 2112 RecordData Record; 2113 while (true) { 2114 Expected<llvm::BitstreamEntry> MaybeEntry = 2115 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd); 2116 if (!MaybeEntry) { 2117 Error(MaybeEntry.takeError()); 2118 return; 2119 } 2120 llvm::BitstreamEntry Entry = MaybeEntry.get(); 2121 2122 if (Entry.Kind != llvm::BitstreamEntry::Record) { 2123 Error("malformed block record in AST file"); 2124 return; 2125 } 2126 2127 Record.clear(); 2128 Expected<unsigned> MaybePP = Cursor.readRecord(Entry.ID, Record); 2129 if (!MaybePP) { 2130 Error(MaybePP.takeError()); 2131 return; 2132 } 2133 switch ((PreprocessorRecordTypes)MaybePP.get()) { 2134 case PP_MACRO_DIRECTIVE_HISTORY: 2135 break; 2136 2137 case PP_MODULE_MACRO: { 2138 ModuleMacros.push_back(ModuleMacroRecord()); 2139 auto &Info = ModuleMacros.back(); 2140 Info.SubModID = getGlobalSubmoduleID(M, Record[0]); 2141 Info.MI = getMacro(getGlobalMacroID(M, Record[1])); 2142 for (int I = 2, N = Record.size(); I != N; ++I) 2143 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I])); 2144 continue; 2145 } 2146 2147 default: 2148 Error("malformed block record in AST file"); 2149 return; 2150 } 2151 2152 // We found the macro directive history; that's the last record 2153 // for this macro. 2154 break; 2155 } 2156 2157 // Module macros are listed in reverse dependency order. 2158 { 2159 std::reverse(ModuleMacros.begin(), ModuleMacros.end()); 2160 llvm::SmallVector<ModuleMacro*, 8> Overrides; 2161 for (auto &MMR : ModuleMacros) { 2162 Overrides.clear(); 2163 for (unsigned ModID : MMR.Overrides) { 2164 Module *Mod = getSubmodule(ModID); 2165 auto *Macro = PP.getModuleMacro(Mod, II); 2166 assert(Macro && "missing definition for overridden macro"); 2167 Overrides.push_back(Macro); 2168 } 2169 2170 bool Inserted = false; 2171 Module *Owner = getSubmodule(MMR.SubModID); 2172 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted); 2173 } 2174 } 2175 2176 // Don't read the directive history for a module; we don't have anywhere 2177 // to put it. 2178 if (M.isModule()) 2179 return; 2180 2181 // Deserialize the macro directives history in reverse source-order. 2182 MacroDirective *Latest = nullptr, *Earliest = nullptr; 2183 unsigned Idx = 0, N = Record.size(); 2184 while (Idx < N) { 2185 MacroDirective *MD = nullptr; 2186 SourceLocation Loc = ReadSourceLocation(M, Record, Idx); 2187 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++]; 2188 switch (K) { 2189 case MacroDirective::MD_Define: { 2190 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++])); 2191 MD = PP.AllocateDefMacroDirective(MI, Loc); 2192 break; 2193 } 2194 case MacroDirective::MD_Undefine: 2195 MD = PP.AllocateUndefMacroDirective(Loc); 2196 break; 2197 case MacroDirective::MD_Visibility: 2198 bool isPublic = Record[Idx++]; 2199 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic); 2200 break; 2201 } 2202 2203 if (!Latest) 2204 Latest = MD; 2205 if (Earliest) 2206 Earliest->setPrevious(MD); 2207 Earliest = MD; 2208 } 2209 2210 if (Latest) 2211 PP.setLoadedMacroDirective(II, Earliest, Latest); 2212 } 2213 2214 ASTReader::InputFileInfo 2215 ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) { 2216 // Go find this input file. 2217 BitstreamCursor &Cursor = F.InputFilesCursor; 2218 SavedStreamPosition SavedPosition(Cursor); 2219 if (llvm::Error Err = Cursor.JumpToBit(F.InputFileOffsets[ID - 1])) { 2220 // FIXME this drops errors on the floor. 2221 consumeError(std::move(Err)); 2222 } 2223 2224 Expected<unsigned> MaybeCode = Cursor.ReadCode(); 2225 if (!MaybeCode) { 2226 // FIXME this drops errors on the floor. 2227 consumeError(MaybeCode.takeError()); 2228 } 2229 unsigned Code = MaybeCode.get(); 2230 RecordData Record; 2231 StringRef Blob; 2232 2233 if (Expected<unsigned> Maybe = Cursor.readRecord(Code, Record, &Blob)) 2234 assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE && 2235 "invalid record type for input file"); 2236 else { 2237 // FIXME this drops errors on the floor. 2238 consumeError(Maybe.takeError()); 2239 } 2240 2241 assert(Record[0] == ID && "Bogus stored ID or offset"); 2242 InputFileInfo R; 2243 R.StoredSize = static_cast<off_t>(Record[1]); 2244 R.StoredTime = static_cast<time_t>(Record[2]); 2245 R.Overridden = static_cast<bool>(Record[3]); 2246 R.Transient = static_cast<bool>(Record[4]); 2247 R.TopLevelModuleMap = static_cast<bool>(Record[5]); 2248 R.Filename = std::string(Blob); 2249 ResolveImportedPath(F, R.Filename); 2250 2251 Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance(); 2252 if (!MaybeEntry) // FIXME this drops errors on the floor. 2253 consumeError(MaybeEntry.takeError()); 2254 llvm::BitstreamEntry Entry = MaybeEntry.get(); 2255 assert(Entry.Kind == llvm::BitstreamEntry::Record && 2256 "expected record type for input file hash"); 2257 2258 Record.clear(); 2259 if (Expected<unsigned> Maybe = Cursor.readRecord(Entry.ID, Record)) 2260 assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE_HASH && 2261 "invalid record type for input file hash"); 2262 else { 2263 // FIXME this drops errors on the floor. 2264 consumeError(Maybe.takeError()); 2265 } 2266 R.ContentHash = (static_cast<uint64_t>(Record[1]) << 32) | 2267 static_cast<uint64_t>(Record[0]); 2268 return R; 2269 } 2270 2271 static unsigned moduleKindForDiagnostic(ModuleKind Kind); 2272 InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) { 2273 // If this ID is bogus, just return an empty input file. 2274 if (ID == 0 || ID > F.InputFilesLoaded.size()) 2275 return InputFile(); 2276 2277 // If we've already loaded this input file, return it. 2278 if (F.InputFilesLoaded[ID-1].getFile()) 2279 return F.InputFilesLoaded[ID-1]; 2280 2281 if (F.InputFilesLoaded[ID-1].isNotFound()) 2282 return InputFile(); 2283 2284 // Go find this input file. 2285 BitstreamCursor &Cursor = F.InputFilesCursor; 2286 SavedStreamPosition SavedPosition(Cursor); 2287 if (llvm::Error Err = Cursor.JumpToBit(F.InputFileOffsets[ID - 1])) { 2288 // FIXME this drops errors on the floor. 2289 consumeError(std::move(Err)); 2290 } 2291 2292 InputFileInfo FI = readInputFileInfo(F, ID); 2293 off_t StoredSize = FI.StoredSize; 2294 time_t StoredTime = FI.StoredTime; 2295 bool Overridden = FI.Overridden; 2296 bool Transient = FI.Transient; 2297 StringRef Filename = FI.Filename; 2298 uint64_t StoredContentHash = FI.ContentHash; 2299 2300 OptionalFileEntryRefDegradesToFileEntryPtr File = 2301 expectedToOptional(FileMgr.getFileRef(Filename, /*OpenFile=*/false)); 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 && !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 File = expectedToOptional(FileMgr.getFileRef(Resolved)); 2311 } 2312 2313 // For an overridden file, create a virtual file with the stored 2314 // size/timestamp. 2315 if ((Overridden || Transient) && !File) 2316 File = FileMgr.getVirtualFileRef(Filename, StoredSize, StoredTime); 2317 2318 if (!File) { 2319 if (Complain) { 2320 std::string ErrorStr = "could not find file '"; 2321 ErrorStr += Filename; 2322 ErrorStr += "' referenced by AST file '"; 2323 ErrorStr += F.FileName; 2324 ErrorStr += "'"; 2325 Error(ErrorStr); 2326 } 2327 // Record that we didn't find the file. 2328 F.InputFilesLoaded[ID-1] = InputFile::getNotFound(); 2329 return InputFile(); 2330 } 2331 2332 // Check if there was a request to override the contents of the file 2333 // that was part of the precompiled header. Overriding such a file 2334 // can lead to problems when lexing using the source locations from the 2335 // PCH. 2336 SourceManager &SM = getSourceManager(); 2337 // FIXME: Reject if the overrides are different. 2338 if ((!Overridden && !Transient) && SM.isFileOverridden(File)) { 2339 if (Complain) 2340 Error(diag::err_fe_pch_file_overridden, Filename); 2341 2342 // After emitting the diagnostic, bypass the overriding file to recover 2343 // (this creates a separate FileEntry). 2344 File = SM.bypassFileContentsOverride(*File); 2345 if (!File) { 2346 F.InputFilesLoaded[ID - 1] = InputFile::getNotFound(); 2347 return InputFile(); 2348 } 2349 } 2350 2351 enum ModificationType { 2352 Size, 2353 ModTime, 2354 Content, 2355 None, 2356 }; 2357 auto HasInputFileChanged = [&]() { 2358 if (StoredSize != File->getSize()) 2359 return ModificationType::Size; 2360 if (!DisableValidation && StoredTime && 2361 StoredTime != File->getModificationTime()) { 2362 // In case the modification time changes but not the content, 2363 // accept the cached file as legit. 2364 if (ValidateASTInputFilesContent && 2365 StoredContentHash != static_cast<uint64_t>(llvm::hash_code(-1))) { 2366 auto MemBuffOrError = FileMgr.getBufferForFile(File); 2367 if (!MemBuffOrError) { 2368 if (!Complain) 2369 return ModificationType::ModTime; 2370 std::string ErrorStr = "could not get buffer for file '"; 2371 ErrorStr += File->getName(); 2372 ErrorStr += "'"; 2373 Error(ErrorStr); 2374 return ModificationType::ModTime; 2375 } 2376 2377 auto ContentHash = hash_value(MemBuffOrError.get()->getBuffer()); 2378 if (StoredContentHash == static_cast<uint64_t>(ContentHash)) 2379 return ModificationType::None; 2380 return ModificationType::Content; 2381 } 2382 return ModificationType::ModTime; 2383 } 2384 return ModificationType::None; 2385 }; 2386 2387 bool IsOutOfDate = false; 2388 auto FileChange = HasInputFileChanged(); 2389 // For an overridden file, there is nothing to validate. 2390 if (!Overridden && FileChange != ModificationType::None) { 2391 if (Complain && !Diags.isDiagnosticInFlight()) { 2392 // Build a list of the PCH imports that got us here (in reverse). 2393 SmallVector<ModuleFile *, 4> ImportStack(1, &F); 2394 while (!ImportStack.back()->ImportedBy.empty()) 2395 ImportStack.push_back(ImportStack.back()->ImportedBy[0]); 2396 2397 // The top-level PCH is stale. 2398 StringRef TopLevelPCHName(ImportStack.back()->FileName); 2399 Diag(diag::err_fe_ast_file_modified) 2400 << Filename << moduleKindForDiagnostic(ImportStack.back()->Kind) 2401 << TopLevelPCHName << FileChange; 2402 2403 // Print the import stack. 2404 if (ImportStack.size() > 1) { 2405 Diag(diag::note_pch_required_by) 2406 << Filename << ImportStack[0]->FileName; 2407 for (unsigned I = 1; I < ImportStack.size(); ++I) 2408 Diag(diag::note_pch_required_by) 2409 << ImportStack[I-1]->FileName << ImportStack[I]->FileName; 2410 } 2411 2412 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName; 2413 } 2414 2415 IsOutOfDate = true; 2416 } 2417 // FIXME: If the file is overridden and we've already opened it, 2418 // issue an error (or split it into a separate FileEntry). 2419 2420 InputFile IF = InputFile(*File, Overridden || Transient, IsOutOfDate); 2421 2422 // Note that we've loaded this input file. 2423 F.InputFilesLoaded[ID-1] = IF; 2424 return IF; 2425 } 2426 2427 /// If we are loading a relocatable PCH or module file, and the filename 2428 /// is not an absolute path, add the system or module root to the beginning of 2429 /// the file name. 2430 void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) { 2431 // Resolve relative to the base directory, if we have one. 2432 if (!M.BaseDirectory.empty()) 2433 return ResolveImportedPath(Filename, M.BaseDirectory); 2434 } 2435 2436 void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) { 2437 if (Filename.empty() || llvm::sys::path::is_absolute(Filename)) 2438 return; 2439 2440 SmallString<128> Buffer; 2441 llvm::sys::path::append(Buffer, Prefix, Filename); 2442 Filename.assign(Buffer.begin(), Buffer.end()); 2443 } 2444 2445 static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) { 2446 switch (ARR) { 2447 case ASTReader::Failure: return true; 2448 case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing); 2449 case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate); 2450 case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch); 2451 case ASTReader::ConfigurationMismatch: 2452 return !(Caps & ASTReader::ARR_ConfigurationMismatch); 2453 case ASTReader::HadErrors: return true; 2454 case ASTReader::Success: return false; 2455 } 2456 2457 llvm_unreachable("unknown ASTReadResult"); 2458 } 2459 2460 ASTReader::ASTReadResult ASTReader::ReadOptionsBlock( 2461 BitstreamCursor &Stream, unsigned ClientLoadCapabilities, 2462 bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener, 2463 std::string &SuggestedPredefines) { 2464 if (llvm::Error Err = Stream.EnterSubBlock(OPTIONS_BLOCK_ID)) { 2465 // FIXME this drops errors on the floor. 2466 consumeError(std::move(Err)); 2467 return Failure; 2468 } 2469 2470 // Read all of the records in the options block. 2471 RecordData Record; 2472 ASTReadResult Result = Success; 2473 while (true) { 2474 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); 2475 if (!MaybeEntry) { 2476 // FIXME this drops errors on the floor. 2477 consumeError(MaybeEntry.takeError()); 2478 return Failure; 2479 } 2480 llvm::BitstreamEntry Entry = MaybeEntry.get(); 2481 2482 switch (Entry.Kind) { 2483 case llvm::BitstreamEntry::Error: 2484 case llvm::BitstreamEntry::SubBlock: 2485 return Failure; 2486 2487 case llvm::BitstreamEntry::EndBlock: 2488 return Result; 2489 2490 case llvm::BitstreamEntry::Record: 2491 // The interesting case. 2492 break; 2493 } 2494 2495 // Read and process a record. 2496 Record.clear(); 2497 Expected<unsigned> MaybeRecordType = Stream.readRecord(Entry.ID, Record); 2498 if (!MaybeRecordType) { 2499 // FIXME this drops errors on the floor. 2500 consumeError(MaybeRecordType.takeError()); 2501 return Failure; 2502 } 2503 switch ((OptionsRecordTypes)MaybeRecordType.get()) { 2504 case LANGUAGE_OPTIONS: { 2505 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0; 2506 if (ParseLanguageOptions(Record, Complain, Listener, 2507 AllowCompatibleConfigurationMismatch)) 2508 Result = ConfigurationMismatch; 2509 break; 2510 } 2511 2512 case TARGET_OPTIONS: { 2513 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0; 2514 if (ParseTargetOptions(Record, Complain, Listener, 2515 AllowCompatibleConfigurationMismatch)) 2516 Result = ConfigurationMismatch; 2517 break; 2518 } 2519 2520 case FILE_SYSTEM_OPTIONS: { 2521 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0; 2522 if (!AllowCompatibleConfigurationMismatch && 2523 ParseFileSystemOptions(Record, Complain, Listener)) 2524 Result = ConfigurationMismatch; 2525 break; 2526 } 2527 2528 case HEADER_SEARCH_OPTIONS: { 2529 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0; 2530 if (!AllowCompatibleConfigurationMismatch && 2531 ParseHeaderSearchOptions(Record, Complain, Listener)) 2532 Result = ConfigurationMismatch; 2533 break; 2534 } 2535 2536 case PREPROCESSOR_OPTIONS: 2537 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0; 2538 if (!AllowCompatibleConfigurationMismatch && 2539 ParsePreprocessorOptions(Record, Complain, Listener, 2540 SuggestedPredefines)) 2541 Result = ConfigurationMismatch; 2542 break; 2543 } 2544 } 2545 } 2546 2547 ASTReader::ASTReadResult 2548 ASTReader::ReadControlBlock(ModuleFile &F, 2549 SmallVectorImpl<ImportedModule> &Loaded, 2550 const ModuleFile *ImportedBy, 2551 unsigned ClientLoadCapabilities) { 2552 BitstreamCursor &Stream = F.Stream; 2553 2554 if (llvm::Error Err = Stream.EnterSubBlock(CONTROL_BLOCK_ID)) { 2555 Error(std::move(Err)); 2556 return Failure; 2557 } 2558 2559 // Lambda to read the unhashed control block the first time it's called. 2560 // 2561 // For PCM files, the unhashed control block cannot be read until after the 2562 // MODULE_NAME record. However, PCH files have no MODULE_NAME, and yet still 2563 // need to look ahead before reading the IMPORTS record. For consistency, 2564 // this block is always read somehow (see BitstreamEntry::EndBlock). 2565 bool HasReadUnhashedControlBlock = false; 2566 auto readUnhashedControlBlockOnce = [&]() { 2567 if (!HasReadUnhashedControlBlock) { 2568 HasReadUnhashedControlBlock = true; 2569 if (ASTReadResult Result = 2570 readUnhashedControlBlock(F, ImportedBy, ClientLoadCapabilities)) 2571 return Result; 2572 } 2573 return Success; 2574 }; 2575 2576 // Read all of the records and blocks in the control block. 2577 RecordData Record; 2578 unsigned NumInputs = 0; 2579 unsigned NumUserInputs = 0; 2580 StringRef BaseDirectoryAsWritten; 2581 while (true) { 2582 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); 2583 if (!MaybeEntry) { 2584 Error(MaybeEntry.takeError()); 2585 return Failure; 2586 } 2587 llvm::BitstreamEntry Entry = MaybeEntry.get(); 2588 2589 switch (Entry.Kind) { 2590 case llvm::BitstreamEntry::Error: 2591 Error("malformed block record in AST file"); 2592 return Failure; 2593 case llvm::BitstreamEntry::EndBlock: { 2594 // Validate the module before returning. This call catches an AST with 2595 // no module name and no imports. 2596 if (ASTReadResult Result = readUnhashedControlBlockOnce()) 2597 return Result; 2598 2599 // Validate input files. 2600 const HeaderSearchOptions &HSOpts = 2601 PP.getHeaderSearchInfo().getHeaderSearchOpts(); 2602 2603 // All user input files reside at the index range [0, NumUserInputs), and 2604 // system input files reside at [NumUserInputs, NumInputs). For explicitly 2605 // loaded module files, ignore missing inputs. 2606 if (!DisableValidation && F.Kind != MK_ExplicitModule && 2607 F.Kind != MK_PrebuiltModule) { 2608 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0; 2609 2610 // If we are reading a module, we will create a verification timestamp, 2611 // so we verify all input files. Otherwise, verify only user input 2612 // files. 2613 2614 unsigned N = NumUserInputs; 2615 if (ValidateSystemInputs || 2616 (HSOpts.ModulesValidateOncePerBuildSession && 2617 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp && 2618 F.Kind == MK_ImplicitModule)) 2619 N = NumInputs; 2620 2621 for (unsigned I = 0; I < N; ++I) { 2622 InputFile IF = getInputFile(F, I+1, Complain); 2623 if (!IF.getFile() || IF.isOutOfDate()) 2624 return OutOfDate; 2625 } 2626 } 2627 2628 if (Listener) 2629 Listener->visitModuleFile(F.FileName, F.Kind); 2630 2631 if (Listener && Listener->needsInputFileVisitation()) { 2632 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs 2633 : NumUserInputs; 2634 for (unsigned I = 0; I < N; ++I) { 2635 bool IsSystem = I >= NumUserInputs; 2636 InputFileInfo FI = readInputFileInfo(F, I+1); 2637 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden, 2638 F.Kind == MK_ExplicitModule || 2639 F.Kind == MK_PrebuiltModule); 2640 } 2641 } 2642 2643 return Success; 2644 } 2645 2646 case llvm::BitstreamEntry::SubBlock: 2647 switch (Entry.ID) { 2648 case INPUT_FILES_BLOCK_ID: 2649 F.InputFilesCursor = Stream; 2650 if (llvm::Error Err = Stream.SkipBlock()) { 2651 Error(std::move(Err)); 2652 return Failure; 2653 } 2654 if (ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) { 2655 Error("malformed block record in AST file"); 2656 return Failure; 2657 } 2658 continue; 2659 2660 case OPTIONS_BLOCK_ID: 2661 // If we're reading the first module for this group, check its options 2662 // are compatible with ours. For modules it imports, no further checking 2663 // is required, because we checked them when we built it. 2664 if (Listener && !ImportedBy) { 2665 // Should we allow the configuration of the module file to differ from 2666 // the configuration of the current translation unit in a compatible 2667 // way? 2668 // 2669 // FIXME: Allow this for files explicitly specified with -include-pch. 2670 bool AllowCompatibleConfigurationMismatch = 2671 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule; 2672 2673 ASTReadResult Result = 2674 ReadOptionsBlock(Stream, ClientLoadCapabilities, 2675 AllowCompatibleConfigurationMismatch, *Listener, 2676 SuggestedPredefines); 2677 if (Result == Failure) { 2678 Error("malformed block record in AST file"); 2679 return Result; 2680 } 2681 2682 if (DisableValidation || 2683 (AllowConfigurationMismatch && Result == ConfigurationMismatch)) 2684 Result = Success; 2685 2686 // If we can't load the module, exit early since we likely 2687 // will rebuild the module anyway. The stream may be in the 2688 // middle of a block. 2689 if (Result != Success) 2690 return Result; 2691 } else if (llvm::Error Err = Stream.SkipBlock()) { 2692 Error(std::move(Err)); 2693 return Failure; 2694 } 2695 continue; 2696 2697 default: 2698 if (llvm::Error Err = Stream.SkipBlock()) { 2699 Error(std::move(Err)); 2700 return Failure; 2701 } 2702 continue; 2703 } 2704 2705 case llvm::BitstreamEntry::Record: 2706 // The interesting case. 2707 break; 2708 } 2709 2710 // Read and process a record. 2711 Record.clear(); 2712 StringRef Blob; 2713 Expected<unsigned> MaybeRecordType = 2714 Stream.readRecord(Entry.ID, Record, &Blob); 2715 if (!MaybeRecordType) { 2716 Error(MaybeRecordType.takeError()); 2717 return Failure; 2718 } 2719 switch ((ControlRecordTypes)MaybeRecordType.get()) { 2720 case METADATA: { 2721 if (Record[0] != VERSION_MAJOR && !DisableValidation) { 2722 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0) 2723 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old 2724 : diag::err_pch_version_too_new); 2725 return VersionMismatch; 2726 } 2727 2728 bool hasErrors = Record[6]; 2729 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) { 2730 Diag(diag::err_pch_with_compiler_errors); 2731 return HadErrors; 2732 } 2733 if (hasErrors) { 2734 Diags.ErrorOccurred = true; 2735 Diags.UncompilableErrorOccurred = true; 2736 Diags.UnrecoverableErrorOccurred = true; 2737 } 2738 2739 F.RelocatablePCH = Record[4]; 2740 // Relative paths in a relocatable PCH are relative to our sysroot. 2741 if (F.RelocatablePCH) 2742 F.BaseDirectory = isysroot.empty() ? "/" : isysroot; 2743 2744 F.HasTimestamps = Record[5]; 2745 2746 const std::string &CurBranch = getClangFullRepositoryVersion(); 2747 StringRef ASTBranch = Blob; 2748 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) { 2749 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0) 2750 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch; 2751 return VersionMismatch; 2752 } 2753 break; 2754 } 2755 2756 case IMPORTS: { 2757 // Validate the AST before processing any imports (otherwise, untangling 2758 // them can be error-prone and expensive). A module will have a name and 2759 // will already have been validated, but this catches the PCH case. 2760 if (ASTReadResult Result = readUnhashedControlBlockOnce()) 2761 return Result; 2762 2763 // Load each of the imported PCH files. 2764 unsigned Idx = 0, N = Record.size(); 2765 while (Idx < N) { 2766 // Read information about the AST file. 2767 ModuleKind ImportedKind = (ModuleKind)Record[Idx++]; 2768 // The import location will be the local one for now; we will adjust 2769 // all import locations of module imports after the global source 2770 // location info are setup, in ReadAST. 2771 SourceLocation ImportLoc = 2772 ReadUntranslatedSourceLocation(Record[Idx++]); 2773 off_t StoredSize = (off_t)Record[Idx++]; 2774 time_t StoredModTime = (time_t)Record[Idx++]; 2775 auto FirstSignatureByte = Record.begin() + Idx; 2776 ASTFileSignature StoredSignature = ASTFileSignature::create( 2777 FirstSignatureByte, FirstSignatureByte + ASTFileSignature::size); 2778 Idx += ASTFileSignature::size; 2779 2780 std::string ImportedName = ReadString(Record, Idx); 2781 std::string ImportedFile; 2782 2783 // For prebuilt and explicit modules first consult the file map for 2784 // an override. Note that here we don't search prebuilt module 2785 // directories, only the explicit name to file mappings. Also, we will 2786 // still verify the size/signature making sure it is essentially the 2787 // same file but perhaps in a different location. 2788 if (ImportedKind == MK_PrebuiltModule || ImportedKind == MK_ExplicitModule) 2789 ImportedFile = PP.getHeaderSearchInfo().getPrebuiltModuleFileName( 2790 ImportedName, /*FileMapOnly*/ true); 2791 2792 if (ImportedFile.empty()) 2793 // Use BaseDirectoryAsWritten to ensure we use the same path in the 2794 // ModuleCache as when writing. 2795 ImportedFile = ReadPath(BaseDirectoryAsWritten, Record, Idx); 2796 else 2797 SkipPath(Record, Idx); 2798 2799 // If our client can't cope with us being out of date, we can't cope with 2800 // our dependency being missing. 2801 unsigned Capabilities = ClientLoadCapabilities; 2802 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) 2803 Capabilities &= ~ARR_Missing; 2804 2805 // Load the AST file. 2806 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F, 2807 Loaded, StoredSize, StoredModTime, 2808 StoredSignature, Capabilities); 2809 2810 // If we diagnosed a problem, produce a backtrace. 2811 if (isDiagnosedResult(Result, Capabilities)) 2812 Diag(diag::note_module_file_imported_by) 2813 << F.FileName << !F.ModuleName.empty() << F.ModuleName; 2814 2815 switch (Result) { 2816 case Failure: return Failure; 2817 // If we have to ignore the dependency, we'll have to ignore this too. 2818 case Missing: 2819 case OutOfDate: return OutOfDate; 2820 case VersionMismatch: return VersionMismatch; 2821 case ConfigurationMismatch: return ConfigurationMismatch; 2822 case HadErrors: return HadErrors; 2823 case Success: break; 2824 } 2825 } 2826 break; 2827 } 2828 2829 case ORIGINAL_FILE: 2830 F.OriginalSourceFileID = FileID::get(Record[0]); 2831 F.ActualOriginalSourceFileName = std::string(Blob); 2832 F.OriginalSourceFileName = F.ActualOriginalSourceFileName; 2833 ResolveImportedPath(F, F.OriginalSourceFileName); 2834 break; 2835 2836 case ORIGINAL_FILE_ID: 2837 F.OriginalSourceFileID = FileID::get(Record[0]); 2838 break; 2839 2840 case ORIGINAL_PCH_DIR: 2841 F.OriginalDir = std::string(Blob); 2842 break; 2843 2844 case MODULE_NAME: 2845 F.ModuleName = std::string(Blob); 2846 Diag(diag::remark_module_import) 2847 << F.ModuleName << F.FileName << (ImportedBy ? true : false) 2848 << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef()); 2849 if (Listener) 2850 Listener->ReadModuleName(F.ModuleName); 2851 2852 // Validate the AST as soon as we have a name so we can exit early on 2853 // failure. 2854 if (ASTReadResult Result = readUnhashedControlBlockOnce()) 2855 return Result; 2856 2857 break; 2858 2859 case MODULE_DIRECTORY: { 2860 // Save the BaseDirectory as written in the PCM for computing the module 2861 // filename for the ModuleCache. 2862 BaseDirectoryAsWritten = Blob; 2863 assert(!F.ModuleName.empty() && 2864 "MODULE_DIRECTORY found before MODULE_NAME"); 2865 // If we've already loaded a module map file covering this module, we may 2866 // have a better path for it (relative to the current build). 2867 Module *M = PP.getHeaderSearchInfo().lookupModule( 2868 F.ModuleName, /*AllowSearch*/ true, 2869 /*AllowExtraModuleMapSearch*/ true); 2870 if (M && M->Directory) { 2871 // If we're implicitly loading a module, the base directory can't 2872 // change between the build and use. 2873 // Don't emit module relocation error if we have -fno-validate-pch 2874 if (!PP.getPreprocessorOpts().DisablePCHValidation && 2875 F.Kind != MK_ExplicitModule && F.Kind != MK_PrebuiltModule) { 2876 auto BuildDir = PP.getFileManager().getDirectory(Blob); 2877 if (!BuildDir || *BuildDir != M->Directory) { 2878 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) 2879 Diag(diag::err_imported_module_relocated) 2880 << F.ModuleName << Blob << M->Directory->getName(); 2881 return OutOfDate; 2882 } 2883 } 2884 F.BaseDirectory = std::string(M->Directory->getName()); 2885 } else { 2886 F.BaseDirectory = std::string(Blob); 2887 } 2888 break; 2889 } 2890 2891 case MODULE_MAP_FILE: 2892 if (ASTReadResult Result = 2893 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities)) 2894 return Result; 2895 break; 2896 2897 case INPUT_FILE_OFFSETS: 2898 NumInputs = Record[0]; 2899 NumUserInputs = Record[1]; 2900 F.InputFileOffsets = 2901 (const llvm::support::unaligned_uint64_t *)Blob.data(); 2902 F.InputFilesLoaded.resize(NumInputs); 2903 F.NumUserInputFiles = NumUserInputs; 2904 break; 2905 } 2906 } 2907 } 2908 2909 ASTReader::ASTReadResult 2910 ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) { 2911 BitstreamCursor &Stream = F.Stream; 2912 2913 if (llvm::Error Err = Stream.EnterSubBlock(AST_BLOCK_ID)) { 2914 Error(std::move(Err)); 2915 return Failure; 2916 } 2917 F.ASTBlockStartOffset = Stream.GetCurrentBitNo(); 2918 2919 // Read all of the records and blocks for the AST file. 2920 RecordData Record; 2921 while (true) { 2922 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); 2923 if (!MaybeEntry) { 2924 Error(MaybeEntry.takeError()); 2925 return Failure; 2926 } 2927 llvm::BitstreamEntry Entry = MaybeEntry.get(); 2928 2929 switch (Entry.Kind) { 2930 case llvm::BitstreamEntry::Error: 2931 Error("error at end of module block in AST file"); 2932 return Failure; 2933 case llvm::BitstreamEntry::EndBlock: 2934 // Outside of C++, we do not store a lookup map for the translation unit. 2935 // Instead, mark it as needing a lookup map to be built if this module 2936 // contains any declarations lexically within it (which it always does!). 2937 // This usually has no cost, since we very rarely need the lookup map for 2938 // the translation unit outside C++. 2939 if (ASTContext *Ctx = ContextObj) { 2940 DeclContext *DC = Ctx->getTranslationUnitDecl(); 2941 if (DC->hasExternalLexicalStorage() && !Ctx->getLangOpts().CPlusPlus) 2942 DC->setMustBuildLookupTable(); 2943 } 2944 2945 return Success; 2946 case llvm::BitstreamEntry::SubBlock: 2947 switch (Entry.ID) { 2948 case DECLTYPES_BLOCK_ID: 2949 // We lazily load the decls block, but we want to set up the 2950 // DeclsCursor cursor to point into it. Clone our current bitcode 2951 // cursor to it, enter the block and read the abbrevs in that block. 2952 // With the main cursor, we just skip over it. 2953 F.DeclsCursor = Stream; 2954 if (llvm::Error Err = Stream.SkipBlock()) { 2955 Error(std::move(Err)); 2956 return Failure; 2957 } 2958 if (ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID, 2959 &F.DeclsBlockStartOffset)) { 2960 Error("malformed block record in AST file"); 2961 return Failure; 2962 } 2963 break; 2964 2965 case PREPROCESSOR_BLOCK_ID: 2966 F.MacroCursor = Stream; 2967 if (!PP.getExternalSource()) 2968 PP.setExternalSource(this); 2969 2970 if (llvm::Error Err = Stream.SkipBlock()) { 2971 Error(std::move(Err)); 2972 return Failure; 2973 } 2974 if (ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) { 2975 Error("malformed block record in AST file"); 2976 return Failure; 2977 } 2978 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo(); 2979 break; 2980 2981 case PREPROCESSOR_DETAIL_BLOCK_ID: 2982 F.PreprocessorDetailCursor = Stream; 2983 2984 if (llvm::Error Err = Stream.SkipBlock()) { 2985 Error(std::move(Err)); 2986 return Failure; 2987 } 2988 if (ReadBlockAbbrevs(F.PreprocessorDetailCursor, 2989 PREPROCESSOR_DETAIL_BLOCK_ID)) { 2990 Error("malformed preprocessor detail record in AST file"); 2991 return Failure; 2992 } 2993 F.PreprocessorDetailStartOffset 2994 = F.PreprocessorDetailCursor.GetCurrentBitNo(); 2995 2996 if (!PP.getPreprocessingRecord()) 2997 PP.createPreprocessingRecord(); 2998 if (!PP.getPreprocessingRecord()->getExternalSource()) 2999 PP.getPreprocessingRecord()->SetExternalSource(*this); 3000 break; 3001 3002 case SOURCE_MANAGER_BLOCK_ID: 3003 if (ReadSourceManagerBlock(F)) 3004 return Failure; 3005 break; 3006 3007 case SUBMODULE_BLOCK_ID: 3008 if (ASTReadResult Result = 3009 ReadSubmoduleBlock(F, ClientLoadCapabilities)) 3010 return Result; 3011 break; 3012 3013 case COMMENTS_BLOCK_ID: { 3014 BitstreamCursor C = Stream; 3015 3016 if (llvm::Error Err = Stream.SkipBlock()) { 3017 Error(std::move(Err)); 3018 return Failure; 3019 } 3020 if (ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) { 3021 Error("malformed comments block in AST file"); 3022 return Failure; 3023 } 3024 CommentsCursors.push_back(std::make_pair(C, &F)); 3025 break; 3026 } 3027 3028 default: 3029 if (llvm::Error Err = Stream.SkipBlock()) { 3030 Error(std::move(Err)); 3031 return Failure; 3032 } 3033 break; 3034 } 3035 continue; 3036 3037 case llvm::BitstreamEntry::Record: 3038 // The interesting case. 3039 break; 3040 } 3041 3042 // Read and process a record. 3043 Record.clear(); 3044 StringRef Blob; 3045 Expected<unsigned> MaybeRecordType = 3046 Stream.readRecord(Entry.ID, Record, &Blob); 3047 if (!MaybeRecordType) { 3048 Error(MaybeRecordType.takeError()); 3049 return Failure; 3050 } 3051 ASTRecordTypes RecordType = (ASTRecordTypes)MaybeRecordType.get(); 3052 3053 // If we're not loading an AST context, we don't care about most records. 3054 if (!ContextObj) { 3055 switch (RecordType) { 3056 case IDENTIFIER_TABLE: 3057 case IDENTIFIER_OFFSET: 3058 case INTERESTING_IDENTIFIERS: 3059 case STATISTICS: 3060 case PP_CONDITIONAL_STACK: 3061 case PP_COUNTER_VALUE: 3062 case SOURCE_LOCATION_OFFSETS: 3063 case MODULE_OFFSET_MAP: 3064 case SOURCE_MANAGER_LINE_TABLE: 3065 case SOURCE_LOCATION_PRELOADS: 3066 case PPD_ENTITIES_OFFSETS: 3067 case HEADER_SEARCH_TABLE: 3068 case IMPORTED_MODULES: 3069 case MACRO_OFFSET: 3070 break; 3071 default: 3072 continue; 3073 } 3074 } 3075 3076 switch (RecordType) { 3077 default: // Default behavior: ignore. 3078 break; 3079 3080 case TYPE_OFFSET: { 3081 if (F.LocalNumTypes != 0) { 3082 Error("duplicate TYPE_OFFSET record in AST file"); 3083 return Failure; 3084 } 3085 F.TypeOffsets = reinterpret_cast<const UnderalignedInt64 *>(Blob.data()); 3086 F.LocalNumTypes = Record[0]; 3087 unsigned LocalBaseTypeIndex = Record[1]; 3088 F.BaseTypeIndex = getTotalNumTypes(); 3089 3090 if (F.LocalNumTypes > 0) { 3091 // Introduce the global -> local mapping for types within this module. 3092 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F)); 3093 3094 // Introduce the local -> global mapping for types within this module. 3095 F.TypeRemap.insertOrReplace( 3096 std::make_pair(LocalBaseTypeIndex, 3097 F.BaseTypeIndex - LocalBaseTypeIndex)); 3098 3099 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes); 3100 } 3101 break; 3102 } 3103 3104 case DECL_OFFSET: { 3105 if (F.LocalNumDecls != 0) { 3106 Error("duplicate DECL_OFFSET record in AST file"); 3107 return Failure; 3108 } 3109 F.DeclOffsets = (const DeclOffset *)Blob.data(); 3110 F.LocalNumDecls = Record[0]; 3111 unsigned LocalBaseDeclID = Record[1]; 3112 F.BaseDeclID = getTotalNumDecls(); 3113 3114 if (F.LocalNumDecls > 0) { 3115 // Introduce the global -> local mapping for declarations within this 3116 // module. 3117 GlobalDeclMap.insert( 3118 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F)); 3119 3120 // Introduce the local -> global mapping for declarations within this 3121 // module. 3122 F.DeclRemap.insertOrReplace( 3123 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID)); 3124 3125 // Introduce the global -> local mapping for declarations within this 3126 // module. 3127 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID; 3128 3129 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls); 3130 } 3131 break; 3132 } 3133 3134 case TU_UPDATE_LEXICAL: { 3135 DeclContext *TU = ContextObj->getTranslationUnitDecl(); 3136 LexicalContents Contents( 3137 reinterpret_cast<const llvm::support::unaligned_uint32_t *>( 3138 Blob.data()), 3139 static_cast<unsigned int>(Blob.size() / 4)); 3140 TULexicalDecls.push_back(std::make_pair(&F, Contents)); 3141 TU->setHasExternalLexicalStorage(true); 3142 break; 3143 } 3144 3145 case UPDATE_VISIBLE: { 3146 unsigned Idx = 0; 3147 serialization::DeclID ID = ReadDeclID(F, Record, Idx); 3148 auto *Data = (const unsigned char*)Blob.data(); 3149 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&F, Data}); 3150 // If we've already loaded the decl, perform the updates when we finish 3151 // loading this block. 3152 if (Decl *D = GetExistingDecl(ID)) 3153 PendingUpdateRecords.push_back( 3154 PendingUpdateRecord(ID, D, /*JustLoaded=*/false)); 3155 break; 3156 } 3157 3158 case IDENTIFIER_TABLE: 3159 F.IdentifierTableData = Blob.data(); 3160 if (Record[0]) { 3161 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create( 3162 (const unsigned char *)F.IdentifierTableData + Record[0], 3163 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t), 3164 (const unsigned char *)F.IdentifierTableData, 3165 ASTIdentifierLookupTrait(*this, F)); 3166 3167 PP.getIdentifierTable().setExternalIdentifierLookup(this); 3168 } 3169 break; 3170 3171 case IDENTIFIER_OFFSET: { 3172 if (F.LocalNumIdentifiers != 0) { 3173 Error("duplicate IDENTIFIER_OFFSET record in AST file"); 3174 return Failure; 3175 } 3176 F.IdentifierOffsets = (const uint32_t *)Blob.data(); 3177 F.LocalNumIdentifiers = Record[0]; 3178 unsigned LocalBaseIdentifierID = Record[1]; 3179 F.BaseIdentifierID = getTotalNumIdentifiers(); 3180 3181 if (F.LocalNumIdentifiers > 0) { 3182 // Introduce the global -> local mapping for identifiers within this 3183 // module. 3184 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1, 3185 &F)); 3186 3187 // Introduce the local -> global mapping for identifiers within this 3188 // module. 3189 F.IdentifierRemap.insertOrReplace( 3190 std::make_pair(LocalBaseIdentifierID, 3191 F.BaseIdentifierID - LocalBaseIdentifierID)); 3192 3193 IdentifiersLoaded.resize(IdentifiersLoaded.size() 3194 + F.LocalNumIdentifiers); 3195 } 3196 break; 3197 } 3198 3199 case INTERESTING_IDENTIFIERS: 3200 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end()); 3201 break; 3202 3203 case EAGERLY_DESERIALIZED_DECLS: 3204 // FIXME: Skip reading this record if our ASTConsumer doesn't care 3205 // about "interesting" decls (for instance, if we're building a module). 3206 for (unsigned I = 0, N = Record.size(); I != N; ++I) 3207 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I])); 3208 break; 3209 3210 case MODULAR_CODEGEN_DECLS: 3211 // FIXME: Skip reading this record if our ASTConsumer doesn't care about 3212 // them (ie: if we're not codegenerating this module). 3213 if (F.Kind == MK_MainFile || 3214 getContext().getLangOpts().BuildingPCHWithObjectFile) 3215 for (unsigned I = 0, N = Record.size(); I != N; ++I) 3216 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I])); 3217 break; 3218 3219 case SPECIAL_TYPES: 3220 if (SpecialTypes.empty()) { 3221 for (unsigned I = 0, N = Record.size(); I != N; ++I) 3222 SpecialTypes.push_back(getGlobalTypeID(F, Record[I])); 3223 break; 3224 } 3225 3226 if (SpecialTypes.size() != Record.size()) { 3227 Error("invalid special-types record"); 3228 return Failure; 3229 } 3230 3231 for (unsigned I = 0, N = Record.size(); I != N; ++I) { 3232 serialization::TypeID ID = getGlobalTypeID(F, Record[I]); 3233 if (!SpecialTypes[I]) 3234 SpecialTypes[I] = ID; 3235 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate 3236 // merge step? 3237 } 3238 break; 3239 3240 case STATISTICS: 3241 TotalNumStatements += Record[0]; 3242 TotalNumMacros += Record[1]; 3243 TotalLexicalDeclContexts += Record[2]; 3244 TotalVisibleDeclContexts += Record[3]; 3245 break; 3246 3247 case UNUSED_FILESCOPED_DECLS: 3248 for (unsigned I = 0, N = Record.size(); I != N; ++I) 3249 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I])); 3250 break; 3251 3252 case DELEGATING_CTORS: 3253 for (unsigned I = 0, N = Record.size(); I != N; ++I) 3254 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I])); 3255 break; 3256 3257 case WEAK_UNDECLARED_IDENTIFIERS: 3258 if (Record.size() % 4 != 0) { 3259 Error("invalid weak identifiers record"); 3260 return Failure; 3261 } 3262 3263 // FIXME: Ignore weak undeclared identifiers from non-original PCH 3264 // files. This isn't the way to do it :) 3265 WeakUndeclaredIdentifiers.clear(); 3266 3267 // Translate the weak, undeclared identifiers into global IDs. 3268 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) { 3269 WeakUndeclaredIdentifiers.push_back( 3270 getGlobalIdentifierID(F, Record[I++])); 3271 WeakUndeclaredIdentifiers.push_back( 3272 getGlobalIdentifierID(F, Record[I++])); 3273 WeakUndeclaredIdentifiers.push_back( 3274 ReadSourceLocation(F, Record, I).getRawEncoding()); 3275 WeakUndeclaredIdentifiers.push_back(Record[I++]); 3276 } 3277 break; 3278 3279 case SELECTOR_OFFSETS: { 3280 F.SelectorOffsets = (const uint32_t *)Blob.data(); 3281 F.LocalNumSelectors = Record[0]; 3282 unsigned LocalBaseSelectorID = Record[1]; 3283 F.BaseSelectorID = getTotalNumSelectors(); 3284 3285 if (F.LocalNumSelectors > 0) { 3286 // Introduce the global -> local mapping for selectors within this 3287 // module. 3288 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F)); 3289 3290 // Introduce the local -> global mapping for selectors within this 3291 // module. 3292 F.SelectorRemap.insertOrReplace( 3293 std::make_pair(LocalBaseSelectorID, 3294 F.BaseSelectorID - LocalBaseSelectorID)); 3295 3296 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors); 3297 } 3298 break; 3299 } 3300 3301 case METHOD_POOL: 3302 F.SelectorLookupTableData = (const unsigned char *)Blob.data(); 3303 if (Record[0]) 3304 F.SelectorLookupTable 3305 = ASTSelectorLookupTable::Create( 3306 F.SelectorLookupTableData + Record[0], 3307 F.SelectorLookupTableData, 3308 ASTSelectorLookupTrait(*this, F)); 3309 TotalNumMethodPoolEntries += Record[1]; 3310 break; 3311 3312 case REFERENCED_SELECTOR_POOL: 3313 if (!Record.empty()) { 3314 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) { 3315 ReferencedSelectorsData.push_back(getGlobalSelectorID(F, 3316 Record[Idx++])); 3317 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx). 3318 getRawEncoding()); 3319 } 3320 } 3321 break; 3322 3323 case PP_CONDITIONAL_STACK: 3324 if (!Record.empty()) { 3325 unsigned Idx = 0, End = Record.size() - 1; 3326 bool ReachedEOFWhileSkipping = Record[Idx++]; 3327 llvm::Optional<Preprocessor::PreambleSkipInfo> SkipInfo; 3328 if (ReachedEOFWhileSkipping) { 3329 SourceLocation HashToken = ReadSourceLocation(F, Record, Idx); 3330 SourceLocation IfTokenLoc = ReadSourceLocation(F, Record, Idx); 3331 bool FoundNonSkipPortion = Record[Idx++]; 3332 bool FoundElse = Record[Idx++]; 3333 SourceLocation ElseLoc = ReadSourceLocation(F, Record, Idx); 3334 SkipInfo.emplace(HashToken, IfTokenLoc, FoundNonSkipPortion, 3335 FoundElse, ElseLoc); 3336 } 3337 SmallVector<PPConditionalInfo, 4> ConditionalStack; 3338 while (Idx < End) { 3339 auto Loc = ReadSourceLocation(F, Record, Idx); 3340 bool WasSkipping = Record[Idx++]; 3341 bool FoundNonSkip = Record[Idx++]; 3342 bool FoundElse = Record[Idx++]; 3343 ConditionalStack.push_back( 3344 {Loc, WasSkipping, FoundNonSkip, FoundElse}); 3345 } 3346 PP.setReplayablePreambleConditionalStack(ConditionalStack, SkipInfo); 3347 } 3348 break; 3349 3350 case PP_COUNTER_VALUE: 3351 if (!Record.empty() && Listener) 3352 Listener->ReadCounter(F, Record[0]); 3353 break; 3354 3355 case FILE_SORTED_DECLS: 3356 F.FileSortedDecls = (const DeclID *)Blob.data(); 3357 F.NumFileSortedDecls = Record[0]; 3358 break; 3359 3360 case SOURCE_LOCATION_OFFSETS: { 3361 F.SLocEntryOffsets = (const uint32_t *)Blob.data(); 3362 F.LocalNumSLocEntries = Record[0]; 3363 unsigned SLocSpaceSize = Record[1]; 3364 F.SLocEntryOffsetsBase = Record[2] + F.SourceManagerBlockStartOffset; 3365 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) = 3366 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries, 3367 SLocSpaceSize); 3368 if (!F.SLocEntryBaseID) { 3369 Error("ran out of source locations"); 3370 break; 3371 } 3372 // Make our entry in the range map. BaseID is negative and growing, so 3373 // we invert it. Because we invert it, though, we need the other end of 3374 // the range. 3375 unsigned RangeStart = 3376 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1; 3377 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F)); 3378 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset); 3379 3380 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing. 3381 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0); 3382 GlobalSLocOffsetMap.insert( 3383 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset 3384 - SLocSpaceSize,&F)); 3385 3386 // Initialize the remapping table. 3387 // Invalid stays invalid. 3388 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0)); 3389 // This module. Base was 2 when being compiled. 3390 F.SLocRemap.insertOrReplace(std::make_pair(2U, 3391 static_cast<int>(F.SLocEntryBaseOffset - 2))); 3392 3393 TotalNumSLocEntries += F.LocalNumSLocEntries; 3394 break; 3395 } 3396 3397 case MODULE_OFFSET_MAP: 3398 F.ModuleOffsetMap = Blob; 3399 break; 3400 3401 case SOURCE_MANAGER_LINE_TABLE: 3402 if (ParseLineTable(F, Record)) { 3403 Error("malformed SOURCE_MANAGER_LINE_TABLE in AST file"); 3404 return Failure; 3405 } 3406 break; 3407 3408 case SOURCE_LOCATION_PRELOADS: { 3409 // Need to transform from the local view (1-based IDs) to the global view, 3410 // which is based off F.SLocEntryBaseID. 3411 if (!F.PreloadSLocEntries.empty()) { 3412 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file"); 3413 return Failure; 3414 } 3415 3416 F.PreloadSLocEntries.swap(Record); 3417 break; 3418 } 3419 3420 case EXT_VECTOR_DECLS: 3421 for (unsigned I = 0, N = Record.size(); I != N; ++I) 3422 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I])); 3423 break; 3424 3425 case VTABLE_USES: 3426 if (Record.size() % 3 != 0) { 3427 Error("Invalid VTABLE_USES record"); 3428 return Failure; 3429 } 3430 3431 // Later tables overwrite earlier ones. 3432 // FIXME: Modules will have some trouble with this. This is clearly not 3433 // the right way to do this. 3434 VTableUses.clear(); 3435 3436 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) { 3437 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++])); 3438 VTableUses.push_back( 3439 ReadSourceLocation(F, Record, Idx).getRawEncoding()); 3440 VTableUses.push_back(Record[Idx++]); 3441 } 3442 break; 3443 3444 case PENDING_IMPLICIT_INSTANTIATIONS: 3445 if (PendingInstantiations.size() % 2 != 0) { 3446 Error("Invalid existing PendingInstantiations"); 3447 return Failure; 3448 } 3449 3450 if (Record.size() % 2 != 0) { 3451 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block"); 3452 return Failure; 3453 } 3454 3455 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) { 3456 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++])); 3457 PendingInstantiations.push_back( 3458 ReadSourceLocation(F, Record, I).getRawEncoding()); 3459 } 3460 break; 3461 3462 case SEMA_DECL_REFS: 3463 if (Record.size() != 3) { 3464 Error("Invalid SEMA_DECL_REFS block"); 3465 return Failure; 3466 } 3467 for (unsigned I = 0, N = Record.size(); I != N; ++I) 3468 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I])); 3469 break; 3470 3471 case PPD_ENTITIES_OFFSETS: { 3472 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data(); 3473 assert(Blob.size() % sizeof(PPEntityOffset) == 0); 3474 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset); 3475 3476 unsigned LocalBasePreprocessedEntityID = Record[0]; 3477 3478 unsigned StartingID; 3479 if (!PP.getPreprocessingRecord()) 3480 PP.createPreprocessingRecord(); 3481 if (!PP.getPreprocessingRecord()->getExternalSource()) 3482 PP.getPreprocessingRecord()->SetExternalSource(*this); 3483 StartingID 3484 = PP.getPreprocessingRecord() 3485 ->allocateLoadedEntities(F.NumPreprocessedEntities); 3486 F.BasePreprocessedEntityID = StartingID; 3487 3488 if (F.NumPreprocessedEntities > 0) { 3489 // Introduce the global -> local mapping for preprocessed entities in 3490 // this module. 3491 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F)); 3492 3493 // Introduce the local -> global mapping for preprocessed entities in 3494 // this module. 3495 F.PreprocessedEntityRemap.insertOrReplace( 3496 std::make_pair(LocalBasePreprocessedEntityID, 3497 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID)); 3498 } 3499 3500 break; 3501 } 3502 3503 case PPD_SKIPPED_RANGES: { 3504 F.PreprocessedSkippedRangeOffsets = (const PPSkippedRange*)Blob.data(); 3505 assert(Blob.size() % sizeof(PPSkippedRange) == 0); 3506 F.NumPreprocessedSkippedRanges = Blob.size() / sizeof(PPSkippedRange); 3507 3508 if (!PP.getPreprocessingRecord()) 3509 PP.createPreprocessingRecord(); 3510 if (!PP.getPreprocessingRecord()->getExternalSource()) 3511 PP.getPreprocessingRecord()->SetExternalSource(*this); 3512 F.BasePreprocessedSkippedRangeID = PP.getPreprocessingRecord() 3513 ->allocateSkippedRanges(F.NumPreprocessedSkippedRanges); 3514 3515 if (F.NumPreprocessedSkippedRanges > 0) 3516 GlobalSkippedRangeMap.insert( 3517 std::make_pair(F.BasePreprocessedSkippedRangeID, &F)); 3518 break; 3519 } 3520 3521 case DECL_UPDATE_OFFSETS: 3522 if (Record.size() % 2 != 0) { 3523 Error("invalid DECL_UPDATE_OFFSETS block in AST file"); 3524 return Failure; 3525 } 3526 for (unsigned I = 0, N = Record.size(); I != N; I += 2) { 3527 GlobalDeclID ID = getGlobalDeclID(F, Record[I]); 3528 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1])); 3529 3530 // If we've already loaded the decl, perform the updates when we finish 3531 // loading this block. 3532 if (Decl *D = GetExistingDecl(ID)) 3533 PendingUpdateRecords.push_back( 3534 PendingUpdateRecord(ID, D, /*JustLoaded=*/false)); 3535 } 3536 break; 3537 3538 case OBJC_CATEGORIES_MAP: 3539 if (F.LocalNumObjCCategoriesInMap != 0) { 3540 Error("duplicate OBJC_CATEGORIES_MAP record in AST file"); 3541 return Failure; 3542 } 3543 3544 F.LocalNumObjCCategoriesInMap = Record[0]; 3545 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data(); 3546 break; 3547 3548 case OBJC_CATEGORIES: 3549 F.ObjCCategories.swap(Record); 3550 break; 3551 3552 case CUDA_SPECIAL_DECL_REFS: 3553 // Later tables overwrite earlier ones. 3554 // FIXME: Modules will have trouble with this. 3555 CUDASpecialDeclRefs.clear(); 3556 for (unsigned I = 0, N = Record.size(); I != N; ++I) 3557 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I])); 3558 break; 3559 3560 case HEADER_SEARCH_TABLE: 3561 F.HeaderFileInfoTableData = Blob.data(); 3562 F.LocalNumHeaderFileInfos = Record[1]; 3563 if (Record[0]) { 3564 F.HeaderFileInfoTable 3565 = HeaderFileInfoLookupTable::Create( 3566 (const unsigned char *)F.HeaderFileInfoTableData + Record[0], 3567 (const unsigned char *)F.HeaderFileInfoTableData, 3568 HeaderFileInfoTrait(*this, F, 3569 &PP.getHeaderSearchInfo(), 3570 Blob.data() + Record[2])); 3571 3572 PP.getHeaderSearchInfo().SetExternalSource(this); 3573 if (!PP.getHeaderSearchInfo().getExternalLookup()) 3574 PP.getHeaderSearchInfo().SetExternalLookup(this); 3575 } 3576 break; 3577 3578 case FP_PRAGMA_OPTIONS: 3579 // Later tables overwrite earlier ones. 3580 FPPragmaOptions.swap(Record); 3581 break; 3582 3583 case OPENCL_EXTENSIONS: 3584 for (unsigned I = 0, E = Record.size(); I != E; ) { 3585 auto Name = ReadString(Record, I); 3586 auto &Opt = OpenCLExtensions.OptMap[Name]; 3587 Opt.Supported = Record[I++] != 0; 3588 Opt.Enabled = Record[I++] != 0; 3589 Opt.Avail = Record[I++]; 3590 Opt.Core = Record[I++]; 3591 } 3592 break; 3593 3594 case OPENCL_EXTENSION_TYPES: 3595 for (unsigned I = 0, E = Record.size(); I != E;) { 3596 auto TypeID = static_cast<::TypeID>(Record[I++]); 3597 auto *Type = GetType(TypeID).getTypePtr(); 3598 auto NumExt = static_cast<unsigned>(Record[I++]); 3599 for (unsigned II = 0; II != NumExt; ++II) { 3600 auto Ext = ReadString(Record, I); 3601 OpenCLTypeExtMap[Type].insert(Ext); 3602 } 3603 } 3604 break; 3605 3606 case OPENCL_EXTENSION_DECLS: 3607 for (unsigned I = 0, E = Record.size(); I != E;) { 3608 auto DeclID = static_cast<::DeclID>(Record[I++]); 3609 auto *Decl = GetDecl(DeclID); 3610 auto NumExt = static_cast<unsigned>(Record[I++]); 3611 for (unsigned II = 0; II != NumExt; ++II) { 3612 auto Ext = ReadString(Record, I); 3613 OpenCLDeclExtMap[Decl].insert(Ext); 3614 } 3615 } 3616 break; 3617 3618 case TENTATIVE_DEFINITIONS: 3619 for (unsigned I = 0, N = Record.size(); I != N; ++I) 3620 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I])); 3621 break; 3622 3623 case KNOWN_NAMESPACES: 3624 for (unsigned I = 0, N = Record.size(); I != N; ++I) 3625 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I])); 3626 break; 3627 3628 case UNDEFINED_BUT_USED: 3629 if (UndefinedButUsed.size() % 2 != 0) { 3630 Error("Invalid existing UndefinedButUsed"); 3631 return Failure; 3632 } 3633 3634 if (Record.size() % 2 != 0) { 3635 Error("invalid undefined-but-used record"); 3636 return Failure; 3637 } 3638 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) { 3639 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++])); 3640 UndefinedButUsed.push_back( 3641 ReadSourceLocation(F, Record, I).getRawEncoding()); 3642 } 3643 break; 3644 3645 case DELETE_EXPRS_TO_ANALYZE: 3646 for (unsigned I = 0, N = Record.size(); I != N;) { 3647 DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++])); 3648 const uint64_t Count = Record[I++]; 3649 DelayedDeleteExprs.push_back(Count); 3650 for (uint64_t C = 0; C < Count; ++C) { 3651 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding()); 3652 bool IsArrayForm = Record[I++] == 1; 3653 DelayedDeleteExprs.push_back(IsArrayForm); 3654 } 3655 } 3656 break; 3657 3658 case IMPORTED_MODULES: 3659 if (!F.isModule()) { 3660 // If we aren't loading a module (which has its own exports), make 3661 // all of the imported modules visible. 3662 // FIXME: Deal with macros-only imports. 3663 for (unsigned I = 0, N = Record.size(); I != N; /**/) { 3664 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]); 3665 SourceLocation Loc = ReadSourceLocation(F, Record, I); 3666 if (GlobalID) { 3667 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc)); 3668 if (DeserializationListener) 3669 DeserializationListener->ModuleImportRead(GlobalID, Loc); 3670 } 3671 } 3672 } 3673 break; 3674 3675 case MACRO_OFFSET: { 3676 if (F.LocalNumMacros != 0) { 3677 Error("duplicate MACRO_OFFSET record in AST file"); 3678 return Failure; 3679 } 3680 F.MacroOffsets = (const uint32_t *)Blob.data(); 3681 F.LocalNumMacros = Record[0]; 3682 unsigned LocalBaseMacroID = Record[1]; 3683 F.MacroOffsetsBase = Record[2] + F.ASTBlockStartOffset; 3684 F.BaseMacroID = getTotalNumMacros(); 3685 3686 if (F.LocalNumMacros > 0) { 3687 // Introduce the global -> local mapping for macros within this module. 3688 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F)); 3689 3690 // Introduce the local -> global mapping for macros within this module. 3691 F.MacroRemap.insertOrReplace( 3692 std::make_pair(LocalBaseMacroID, 3693 F.BaseMacroID - LocalBaseMacroID)); 3694 3695 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros); 3696 } 3697 break; 3698 } 3699 3700 case LATE_PARSED_TEMPLATE: 3701 LateParsedTemplates.emplace_back( 3702 std::piecewise_construct, std::forward_as_tuple(&F), 3703 std::forward_as_tuple(Record.begin(), Record.end())); 3704 break; 3705 3706 case OPTIMIZE_PRAGMA_OPTIONS: 3707 if (Record.size() != 1) { 3708 Error("invalid pragma optimize record"); 3709 return Failure; 3710 } 3711 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]); 3712 break; 3713 3714 case MSSTRUCT_PRAGMA_OPTIONS: 3715 if (Record.size() != 1) { 3716 Error("invalid pragma ms_struct record"); 3717 return Failure; 3718 } 3719 PragmaMSStructState = Record[0]; 3720 break; 3721 3722 case POINTERS_TO_MEMBERS_PRAGMA_OPTIONS: 3723 if (Record.size() != 2) { 3724 Error("invalid pragma ms_struct record"); 3725 return Failure; 3726 } 3727 PragmaMSPointersToMembersState = Record[0]; 3728 PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]); 3729 break; 3730 3731 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES: 3732 for (unsigned I = 0, N = Record.size(); I != N; ++I) 3733 UnusedLocalTypedefNameCandidates.push_back( 3734 getGlobalDeclID(F, Record[I])); 3735 break; 3736 3737 case CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH: 3738 if (Record.size() != 1) { 3739 Error("invalid cuda pragma options record"); 3740 return Failure; 3741 } 3742 ForceCUDAHostDeviceDepth = Record[0]; 3743 break; 3744 3745 case ALIGN_PACK_PRAGMA_OPTIONS: { 3746 if (Record.size() < 3) { 3747 Error("invalid pragma pack record"); 3748 return Failure; 3749 } 3750 PragmaAlignPackCurrentValue = ReadAlignPackInfo(Record[0]); 3751 PragmaAlignPackCurrentLocation = ReadSourceLocation(F, Record[1]); 3752 unsigned NumStackEntries = Record[2]; 3753 unsigned Idx = 3; 3754 // Reset the stack when importing a new module. 3755 PragmaAlignPackStack.clear(); 3756 for (unsigned I = 0; I < NumStackEntries; ++I) { 3757 PragmaAlignPackStackEntry Entry; 3758 Entry.Value = ReadAlignPackInfo(Record[Idx++]); 3759 Entry.Location = ReadSourceLocation(F, Record[Idx++]); 3760 Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]); 3761 PragmaAlignPackStrings.push_back(ReadString(Record, Idx)); 3762 Entry.SlotLabel = PragmaAlignPackStrings.back(); 3763 PragmaAlignPackStack.push_back(Entry); 3764 } 3765 break; 3766 } 3767 3768 case FLOAT_CONTROL_PRAGMA_OPTIONS: { 3769 if (Record.size() < 3) { 3770 Error("invalid pragma pack record"); 3771 return Failure; 3772 } 3773 FpPragmaCurrentValue = FPOptionsOverride::getFromOpaqueInt(Record[0]); 3774 FpPragmaCurrentLocation = ReadSourceLocation(F, Record[1]); 3775 unsigned NumStackEntries = Record[2]; 3776 unsigned Idx = 3; 3777 // Reset the stack when importing a new module. 3778 FpPragmaStack.clear(); 3779 for (unsigned I = 0; I < NumStackEntries; ++I) { 3780 FpPragmaStackEntry Entry; 3781 Entry.Value = FPOptionsOverride::getFromOpaqueInt(Record[Idx++]); 3782 Entry.Location = ReadSourceLocation(F, Record[Idx++]); 3783 Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]); 3784 FpPragmaStrings.push_back(ReadString(Record, Idx)); 3785 Entry.SlotLabel = FpPragmaStrings.back(); 3786 FpPragmaStack.push_back(Entry); 3787 } 3788 break; 3789 } 3790 3791 case DECLS_TO_CHECK_FOR_DEFERRED_DIAGS: 3792 for (unsigned I = 0, N = Record.size(); I != N; ++I) 3793 DeclsToCheckForDeferredDiags.push_back(getGlobalDeclID(F, Record[I])); 3794 break; 3795 } 3796 } 3797 } 3798 3799 void ASTReader::ReadModuleOffsetMap(ModuleFile &F) const { 3800 assert(!F.ModuleOffsetMap.empty() && "no module offset map to read"); 3801 3802 // Additional remapping information. 3803 const unsigned char *Data = (const unsigned char*)F.ModuleOffsetMap.data(); 3804 const unsigned char *DataEnd = Data + F.ModuleOffsetMap.size(); 3805 F.ModuleOffsetMap = StringRef(); 3806 3807 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders. 3808 if (F.SLocRemap.find(0) == F.SLocRemap.end()) { 3809 F.SLocRemap.insert(std::make_pair(0U, 0)); 3810 F.SLocRemap.insert(std::make_pair(2U, 1)); 3811 } 3812 3813 // Continuous range maps we may be updating in our module. 3814 using RemapBuilder = ContinuousRangeMap<uint32_t, int, 2>::Builder; 3815 RemapBuilder SLocRemap(F.SLocRemap); 3816 RemapBuilder IdentifierRemap(F.IdentifierRemap); 3817 RemapBuilder MacroRemap(F.MacroRemap); 3818 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap); 3819 RemapBuilder SubmoduleRemap(F.SubmoduleRemap); 3820 RemapBuilder SelectorRemap(F.SelectorRemap); 3821 RemapBuilder DeclRemap(F.DeclRemap); 3822 RemapBuilder TypeRemap(F.TypeRemap); 3823 3824 while (Data < DataEnd) { 3825 // FIXME: Looking up dependency modules by filename is horrible. Let's 3826 // start fixing this with prebuilt, explicit and implicit modules and see 3827 // how it goes... 3828 using namespace llvm::support; 3829 ModuleKind Kind = static_cast<ModuleKind>( 3830 endian::readNext<uint8_t, little, unaligned>(Data)); 3831 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data); 3832 StringRef Name = StringRef((const char*)Data, Len); 3833 Data += Len; 3834 ModuleFile *OM = (Kind == MK_PrebuiltModule || Kind == MK_ExplicitModule || 3835 Kind == MK_ImplicitModule 3836 ? ModuleMgr.lookupByModuleName(Name) 3837 : ModuleMgr.lookupByFileName(Name)); 3838 if (!OM) { 3839 std::string Msg = 3840 "SourceLocation remap refers to unknown module, cannot find "; 3841 Msg.append(std::string(Name)); 3842 Error(Msg); 3843 return; 3844 } 3845 3846 uint32_t SLocOffset = 3847 endian::readNext<uint32_t, little, unaligned>(Data); 3848 uint32_t IdentifierIDOffset = 3849 endian::readNext<uint32_t, little, unaligned>(Data); 3850 uint32_t MacroIDOffset = 3851 endian::readNext<uint32_t, little, unaligned>(Data); 3852 uint32_t PreprocessedEntityIDOffset = 3853 endian::readNext<uint32_t, little, unaligned>(Data); 3854 uint32_t SubmoduleIDOffset = 3855 endian::readNext<uint32_t, little, unaligned>(Data); 3856 uint32_t SelectorIDOffset = 3857 endian::readNext<uint32_t, little, unaligned>(Data); 3858 uint32_t DeclIDOffset = 3859 endian::readNext<uint32_t, little, unaligned>(Data); 3860 uint32_t TypeIndexOffset = 3861 endian::readNext<uint32_t, little, unaligned>(Data); 3862 3863 uint32_t None = std::numeric_limits<uint32_t>::max(); 3864 3865 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset, 3866 RemapBuilder &Remap) { 3867 if (Offset != None) 3868 Remap.insert(std::make_pair(Offset, 3869 static_cast<int>(BaseOffset - Offset))); 3870 }; 3871 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap); 3872 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap); 3873 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap); 3874 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID, 3875 PreprocessedEntityRemap); 3876 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap); 3877 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap); 3878 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap); 3879 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap); 3880 3881 // Global -> local mappings. 3882 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset; 3883 } 3884 } 3885 3886 ASTReader::ASTReadResult 3887 ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F, 3888 const ModuleFile *ImportedBy, 3889 unsigned ClientLoadCapabilities) { 3890 unsigned Idx = 0; 3891 F.ModuleMapPath = ReadPath(F, Record, Idx); 3892 3893 // Try to resolve ModuleName in the current header search context and 3894 // verify that it is found in the same module map file as we saved. If the 3895 // top-level AST file is a main file, skip this check because there is no 3896 // usable header search context. 3897 assert(!F.ModuleName.empty() && 3898 "MODULE_NAME should come before MODULE_MAP_FILE"); 3899 if (F.Kind == MK_ImplicitModule && ModuleMgr.begin()->Kind != MK_MainFile) { 3900 // An implicitly-loaded module file should have its module listed in some 3901 // module map file that we've already loaded. 3902 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName); 3903 auto &Map = PP.getHeaderSearchInfo().getModuleMap(); 3904 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr; 3905 // Don't emit module relocation error if we have -fno-validate-pch 3906 if (!PP.getPreprocessorOpts().DisablePCHValidation && !ModMap) { 3907 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) { 3908 if (auto ASTFE = M ? M->getASTFile() : None) { 3909 // This module was defined by an imported (explicit) module. 3910 Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName 3911 << ASTFE->getName(); 3912 } else { 3913 // This module was built with a different module map. 3914 Diag(diag::err_imported_module_not_found) 3915 << F.ModuleName << F.FileName 3916 << (ImportedBy ? ImportedBy->FileName : "") << F.ModuleMapPath 3917 << !ImportedBy; 3918 // In case it was imported by a PCH, there's a chance the user is 3919 // just missing to include the search path to the directory containing 3920 // the modulemap. 3921 if (ImportedBy && ImportedBy->Kind == MK_PCH) 3922 Diag(diag::note_imported_by_pch_module_not_found) 3923 << llvm::sys::path::parent_path(F.ModuleMapPath); 3924 } 3925 } 3926 return OutOfDate; 3927 } 3928 3929 assert(M && M->Name == F.ModuleName && "found module with different name"); 3930 3931 // Check the primary module map file. 3932 auto StoredModMap = FileMgr.getFile(F.ModuleMapPath); 3933 if (!StoredModMap || *StoredModMap != ModMap) { 3934 assert(ModMap && "found module is missing module map file"); 3935 assert((ImportedBy || F.Kind == MK_ImplicitModule) && 3936 "top-level import should be verified"); 3937 bool NotImported = F.Kind == MK_ImplicitModule && !ImportedBy; 3938 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) 3939 Diag(diag::err_imported_module_modmap_changed) 3940 << F.ModuleName << (NotImported ? F.FileName : ImportedBy->FileName) 3941 << ModMap->getName() << F.ModuleMapPath << NotImported; 3942 return OutOfDate; 3943 } 3944 3945 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps; 3946 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) { 3947 // FIXME: we should use input files rather than storing names. 3948 std::string Filename = ReadPath(F, Record, Idx); 3949 auto F = FileMgr.getFile(Filename, false, false); 3950 if (!F) { 3951 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) 3952 Error("could not find file '" + Filename +"' referenced by AST file"); 3953 return OutOfDate; 3954 } 3955 AdditionalStoredMaps.insert(*F); 3956 } 3957 3958 // Check any additional module map files (e.g. module.private.modulemap) 3959 // that are not in the pcm. 3960 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) { 3961 for (const FileEntry *ModMap : *AdditionalModuleMaps) { 3962 // Remove files that match 3963 // Note: SmallPtrSet::erase is really remove 3964 if (!AdditionalStoredMaps.erase(ModMap)) { 3965 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) 3966 Diag(diag::err_module_different_modmap) 3967 << F.ModuleName << /*new*/0 << ModMap->getName(); 3968 return OutOfDate; 3969 } 3970 } 3971 } 3972 3973 // Check any additional module map files that are in the pcm, but not 3974 // found in header search. Cases that match are already removed. 3975 for (const FileEntry *ModMap : AdditionalStoredMaps) { 3976 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) 3977 Diag(diag::err_module_different_modmap) 3978 << F.ModuleName << /*not new*/1 << ModMap->getName(); 3979 return OutOfDate; 3980 } 3981 } 3982 3983 if (Listener) 3984 Listener->ReadModuleMapFile(F.ModuleMapPath); 3985 return Success; 3986 } 3987 3988 /// Move the given method to the back of the global list of methods. 3989 static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) { 3990 // Find the entry for this selector in the method pool. 3991 Sema::GlobalMethodPool::iterator Known 3992 = S.MethodPool.find(Method->getSelector()); 3993 if (Known == S.MethodPool.end()) 3994 return; 3995 3996 // Retrieve the appropriate method list. 3997 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first 3998 : Known->second.second; 3999 bool Found = false; 4000 for (ObjCMethodList *List = &Start; List; List = List->getNext()) { 4001 if (!Found) { 4002 if (List->getMethod() == Method) { 4003 Found = true; 4004 } else { 4005 // Keep searching. 4006 continue; 4007 } 4008 } 4009 4010 if (List->getNext()) 4011 List->setMethod(List->getNext()->getMethod()); 4012 else 4013 List->setMethod(Method); 4014 } 4015 } 4016 4017 void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) { 4018 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?"); 4019 for (Decl *D : Names) { 4020 bool wasHidden = !D->isUnconditionallyVisible(); 4021 D->setVisibleDespiteOwningModule(); 4022 4023 if (wasHidden && SemaObj) { 4024 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) { 4025 moveMethodToBackOfGlobalList(*SemaObj, Method); 4026 } 4027 } 4028 } 4029 } 4030 4031 void ASTReader::makeModuleVisible(Module *Mod, 4032 Module::NameVisibilityKind NameVisibility, 4033 SourceLocation ImportLoc) { 4034 llvm::SmallPtrSet<Module *, 4> Visited; 4035 SmallVector<Module *, 4> Stack; 4036 Stack.push_back(Mod); 4037 while (!Stack.empty()) { 4038 Mod = Stack.pop_back_val(); 4039 4040 if (NameVisibility <= Mod->NameVisibility) { 4041 // This module already has this level of visibility (or greater), so 4042 // there is nothing more to do. 4043 continue; 4044 } 4045 4046 if (Mod->isUnimportable()) { 4047 // Modules that aren't importable cannot be made visible. 4048 continue; 4049 } 4050 4051 // Update the module's name visibility. 4052 Mod->NameVisibility = NameVisibility; 4053 4054 // If we've already deserialized any names from this module, 4055 // mark them as visible. 4056 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod); 4057 if (Hidden != HiddenNamesMap.end()) { 4058 auto HiddenNames = std::move(*Hidden); 4059 HiddenNamesMap.erase(Hidden); 4060 makeNamesVisible(HiddenNames.second, HiddenNames.first); 4061 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() && 4062 "making names visible added hidden names"); 4063 } 4064 4065 // Push any exported modules onto the stack to be marked as visible. 4066 SmallVector<Module *, 16> Exports; 4067 Mod->getExportedModules(Exports); 4068 for (SmallVectorImpl<Module *>::iterator 4069 I = Exports.begin(), E = Exports.end(); I != E; ++I) { 4070 Module *Exported = *I; 4071 if (Visited.insert(Exported).second) 4072 Stack.push_back(Exported); 4073 } 4074 } 4075 } 4076 4077 /// We've merged the definition \p MergedDef into the existing definition 4078 /// \p Def. Ensure that \p Def is made visible whenever \p MergedDef is made 4079 /// visible. 4080 void ASTReader::mergeDefinitionVisibility(NamedDecl *Def, 4081 NamedDecl *MergedDef) { 4082 if (!Def->isUnconditionallyVisible()) { 4083 // If MergedDef is visible or becomes visible, make the definition visible. 4084 if (MergedDef->isUnconditionallyVisible()) 4085 Def->setVisibleDespiteOwningModule(); 4086 else { 4087 getContext().mergeDefinitionIntoModule( 4088 Def, MergedDef->getImportedOwningModule(), 4089 /*NotifyListeners*/ false); 4090 PendingMergedDefinitionsToDeduplicate.insert(Def); 4091 } 4092 } 4093 } 4094 4095 bool ASTReader::loadGlobalIndex() { 4096 if (GlobalIndex) 4097 return false; 4098 4099 if (TriedLoadingGlobalIndex || !UseGlobalIndex || 4100 !PP.getLangOpts().Modules) 4101 return true; 4102 4103 // Try to load the global index. 4104 TriedLoadingGlobalIndex = true; 4105 StringRef ModuleCachePath 4106 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath(); 4107 std::pair<GlobalModuleIndex *, llvm::Error> Result = 4108 GlobalModuleIndex::readIndex(ModuleCachePath); 4109 if (llvm::Error Err = std::move(Result.second)) { 4110 assert(!Result.first); 4111 consumeError(std::move(Err)); // FIXME this drops errors on the floor. 4112 return true; 4113 } 4114 4115 GlobalIndex.reset(Result.first); 4116 ModuleMgr.setGlobalIndex(GlobalIndex.get()); 4117 return false; 4118 } 4119 4120 bool ASTReader::isGlobalIndexUnavailable() const { 4121 return PP.getLangOpts().Modules && UseGlobalIndex && 4122 !hasGlobalIndex() && TriedLoadingGlobalIndex; 4123 } 4124 4125 static void updateModuleTimestamp(ModuleFile &MF) { 4126 // Overwrite the timestamp file contents so that file's mtime changes. 4127 std::string TimestampFilename = MF.getTimestampFilename(); 4128 std::error_code EC; 4129 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::OF_Text); 4130 if (EC) 4131 return; 4132 OS << "Timestamp file\n"; 4133 OS.close(); 4134 OS.clear_error(); // Avoid triggering a fatal error. 4135 } 4136 4137 /// Given a cursor at the start of an AST file, scan ahead and drop the 4138 /// cursor into the start of the given block ID, returning false on success and 4139 /// true on failure. 4140 static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) { 4141 while (true) { 4142 Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance(); 4143 if (!MaybeEntry) { 4144 // FIXME this drops errors on the floor. 4145 consumeError(MaybeEntry.takeError()); 4146 return true; 4147 } 4148 llvm::BitstreamEntry Entry = MaybeEntry.get(); 4149 4150 switch (Entry.Kind) { 4151 case llvm::BitstreamEntry::Error: 4152 case llvm::BitstreamEntry::EndBlock: 4153 return true; 4154 4155 case llvm::BitstreamEntry::Record: 4156 // Ignore top-level records. 4157 if (Expected<unsigned> Skipped = Cursor.skipRecord(Entry.ID)) 4158 break; 4159 else { 4160 // FIXME this drops errors on the floor. 4161 consumeError(Skipped.takeError()); 4162 return true; 4163 } 4164 4165 case llvm::BitstreamEntry::SubBlock: 4166 if (Entry.ID == BlockID) { 4167 if (llvm::Error Err = Cursor.EnterSubBlock(BlockID)) { 4168 // FIXME this drops the error on the floor. 4169 consumeError(std::move(Err)); 4170 return true; 4171 } 4172 // Found it! 4173 return false; 4174 } 4175 4176 if (llvm::Error Err = Cursor.SkipBlock()) { 4177 // FIXME this drops the error on the floor. 4178 consumeError(std::move(Err)); 4179 return true; 4180 } 4181 } 4182 } 4183 } 4184 4185 ASTReader::ASTReadResult ASTReader::ReadAST(StringRef FileName, 4186 ModuleKind Type, 4187 SourceLocation ImportLoc, 4188 unsigned ClientLoadCapabilities, 4189 SmallVectorImpl<ImportedSubmodule> *Imported) { 4190 llvm::SaveAndRestore<SourceLocation> 4191 SetCurImportLocRAII(CurrentImportLoc, ImportLoc); 4192 4193 // Defer any pending actions until we get to the end of reading the AST file. 4194 Deserializing AnASTFile(this); 4195 4196 // Bump the generation number. 4197 unsigned PreviousGeneration = 0; 4198 if (ContextObj) 4199 PreviousGeneration = incrementGeneration(*ContextObj); 4200 4201 unsigned NumModules = ModuleMgr.size(); 4202 auto removeModulesAndReturn = [&](ASTReadResult ReadResult) { 4203 assert(ReadResult && "expected to return error"); 4204 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, 4205 PP.getLangOpts().Modules 4206 ? &PP.getHeaderSearchInfo().getModuleMap() 4207 : nullptr); 4208 4209 // If we find that any modules are unusable, the global index is going 4210 // to be out-of-date. Just remove it. 4211 GlobalIndex.reset(); 4212 ModuleMgr.setGlobalIndex(nullptr); 4213 return ReadResult; 4214 }; 4215 4216 SmallVector<ImportedModule, 4> Loaded; 4217 switch (ASTReadResult ReadResult = 4218 ReadASTCore(FileName, Type, ImportLoc, 4219 /*ImportedBy=*/nullptr, Loaded, 0, 0, 4220 ASTFileSignature(), ClientLoadCapabilities)) { 4221 case Failure: 4222 case Missing: 4223 case OutOfDate: 4224 case VersionMismatch: 4225 case ConfigurationMismatch: 4226 case HadErrors: 4227 return removeModulesAndReturn(ReadResult); 4228 case Success: 4229 break; 4230 } 4231 4232 // Here comes stuff that we only do once the entire chain is loaded. 4233 4234 // Load the AST blocks of all of the modules that we loaded. We can still 4235 // hit errors parsing the ASTs at this point. 4236 for (ImportedModule &M : Loaded) { 4237 ModuleFile &F = *M.Mod; 4238 4239 // Read the AST block. 4240 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities)) 4241 return removeModulesAndReturn(Result); 4242 4243 // The AST block should always have a definition for the main module. 4244 if (F.isModule() && !F.DidReadTopLevelSubmodule) { 4245 Error(diag::err_module_file_missing_top_level_submodule, F.FileName); 4246 return removeModulesAndReturn(Failure); 4247 } 4248 4249 // Read the extension blocks. 4250 while (!SkipCursorToBlock(F.Stream, EXTENSION_BLOCK_ID)) { 4251 if (ASTReadResult Result = ReadExtensionBlock(F)) 4252 return removeModulesAndReturn(Result); 4253 } 4254 4255 // Once read, set the ModuleFile bit base offset and update the size in 4256 // bits of all files we've seen. 4257 F.GlobalBitOffset = TotalModulesSizeInBits; 4258 TotalModulesSizeInBits += F.SizeInBits; 4259 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F)); 4260 } 4261 4262 // Preload source locations and interesting indentifiers. 4263 for (ImportedModule &M : Loaded) { 4264 ModuleFile &F = *M.Mod; 4265 4266 // Preload SLocEntries. 4267 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) { 4268 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID; 4269 // Load it through the SourceManager and don't call ReadSLocEntry() 4270 // directly because the entry may have already been loaded in which case 4271 // calling ReadSLocEntry() directly would trigger an assertion in 4272 // SourceManager. 4273 SourceMgr.getLoadedSLocEntryByID(Index); 4274 } 4275 4276 // Map the original source file ID into the ID space of the current 4277 // compilation. 4278 if (F.OriginalSourceFileID.isValid()) { 4279 F.OriginalSourceFileID = FileID::get( 4280 F.SLocEntryBaseID + F.OriginalSourceFileID.getOpaqueValue() - 1); 4281 } 4282 4283 // Preload all the pending interesting identifiers by marking them out of 4284 // date. 4285 for (auto Offset : F.PreloadIdentifierOffsets) { 4286 const unsigned char *Data = reinterpret_cast<const unsigned char *>( 4287 F.IdentifierTableData + Offset); 4288 4289 ASTIdentifierLookupTrait Trait(*this, F); 4290 auto KeyDataLen = Trait.ReadKeyDataLength(Data); 4291 auto Key = Trait.ReadKey(Data, KeyDataLen.first); 4292 auto &II = PP.getIdentifierTable().getOwn(Key); 4293 II.setOutOfDate(true); 4294 4295 // Mark this identifier as being from an AST file so that we can track 4296 // whether we need to serialize it. 4297 markIdentifierFromAST(*this, II); 4298 4299 // Associate the ID with the identifier so that the writer can reuse it. 4300 auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first); 4301 SetIdentifierInfo(ID, &II); 4302 } 4303 } 4304 4305 // Setup the import locations and notify the module manager that we've 4306 // committed to these module files. 4307 for (ImportedModule &M : Loaded) { 4308 ModuleFile &F = *M.Mod; 4309 4310 ModuleMgr.moduleFileAccepted(&F); 4311 4312 // Set the import location. 4313 F.DirectImportLoc = ImportLoc; 4314 // FIXME: We assume that locations from PCH / preamble do not need 4315 // any translation. 4316 if (!M.ImportedBy) 4317 F.ImportLoc = M.ImportLoc; 4318 else 4319 F.ImportLoc = TranslateSourceLocation(*M.ImportedBy, M.ImportLoc); 4320 } 4321 4322 if (!PP.getLangOpts().CPlusPlus || 4323 (Type != MK_ImplicitModule && Type != MK_ExplicitModule && 4324 Type != MK_PrebuiltModule)) { 4325 // Mark all of the identifiers in the identifier table as being out of date, 4326 // so that various accessors know to check the loaded modules when the 4327 // identifier is used. 4328 // 4329 // For C++ modules, we don't need information on many identifiers (just 4330 // those that provide macros or are poisoned), so we mark all of 4331 // the interesting ones via PreloadIdentifierOffsets. 4332 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(), 4333 IdEnd = PP.getIdentifierTable().end(); 4334 Id != IdEnd; ++Id) 4335 Id->second->setOutOfDate(true); 4336 } 4337 // Mark selectors as out of date. 4338 for (auto Sel : SelectorGeneration) 4339 SelectorOutOfDate[Sel.first] = true; 4340 4341 // Resolve any unresolved module exports. 4342 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) { 4343 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I]; 4344 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID); 4345 Module *ResolvedMod = getSubmodule(GlobalID); 4346 4347 switch (Unresolved.Kind) { 4348 case UnresolvedModuleRef::Conflict: 4349 if (ResolvedMod) { 4350 Module::Conflict Conflict; 4351 Conflict.Other = ResolvedMod; 4352 Conflict.Message = Unresolved.String.str(); 4353 Unresolved.Mod->Conflicts.push_back(Conflict); 4354 } 4355 continue; 4356 4357 case UnresolvedModuleRef::Import: 4358 if (ResolvedMod) 4359 Unresolved.Mod->Imports.insert(ResolvedMod); 4360 continue; 4361 4362 case UnresolvedModuleRef::Export: 4363 if (ResolvedMod || Unresolved.IsWildcard) 4364 Unresolved.Mod->Exports.push_back( 4365 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard)); 4366 continue; 4367 } 4368 } 4369 UnresolvedModuleRefs.clear(); 4370 4371 if (Imported) 4372 Imported->append(ImportedModules.begin(), 4373 ImportedModules.end()); 4374 4375 // FIXME: How do we load the 'use'd modules? They may not be submodules. 4376 // Might be unnecessary as use declarations are only used to build the 4377 // module itself. 4378 4379 if (ContextObj) 4380 InitializeContext(); 4381 4382 if (SemaObj) 4383 UpdateSema(); 4384 4385 if (DeserializationListener) 4386 DeserializationListener->ReaderInitialized(this); 4387 4388 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule(); 4389 if (PrimaryModule.OriginalSourceFileID.isValid()) { 4390 // If this AST file is a precompiled preamble, then set the 4391 // preamble file ID of the source manager to the file source file 4392 // from which the preamble was built. 4393 if (Type == MK_Preamble) { 4394 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID); 4395 } else if (Type == MK_MainFile) { 4396 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID); 4397 } 4398 } 4399 4400 // For any Objective-C class definitions we have already loaded, make sure 4401 // that we load any additional categories. 4402 if (ContextObj) { 4403 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) { 4404 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(), 4405 ObjCClassesLoaded[I], 4406 PreviousGeneration); 4407 } 4408 } 4409 4410 if (PP.getHeaderSearchInfo() 4411 .getHeaderSearchOpts() 4412 .ModulesValidateOncePerBuildSession) { 4413 // Now we are certain that the module and all modules it depends on are 4414 // up to date. Create or update timestamp files for modules that are 4415 // located in the module cache (not for PCH files that could be anywhere 4416 // in the filesystem). 4417 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) { 4418 ImportedModule &M = Loaded[I]; 4419 if (M.Mod->Kind == MK_ImplicitModule) { 4420 updateModuleTimestamp(*M.Mod); 4421 } 4422 } 4423 } 4424 4425 return Success; 4426 } 4427 4428 static ASTFileSignature readASTFileSignature(StringRef PCH); 4429 4430 /// Whether \p Stream doesn't start with the AST/PCH file magic number 'CPCH'. 4431 static llvm::Error doesntStartWithASTFileMagic(BitstreamCursor &Stream) { 4432 // FIXME checking magic headers is done in other places such as 4433 // SerializedDiagnosticReader and GlobalModuleIndex, but error handling isn't 4434 // always done the same. Unify it all with a helper. 4435 if (!Stream.canSkipToPos(4)) 4436 return llvm::createStringError(std::errc::illegal_byte_sequence, 4437 "file too small to contain AST file magic"); 4438 for (unsigned C : {'C', 'P', 'C', 'H'}) 4439 if (Expected<llvm::SimpleBitstreamCursor::word_t> Res = Stream.Read(8)) { 4440 if (Res.get() != C) 4441 return llvm::createStringError( 4442 std::errc::illegal_byte_sequence, 4443 "file doesn't start with AST file magic"); 4444 } else 4445 return Res.takeError(); 4446 return llvm::Error::success(); 4447 } 4448 4449 static unsigned moduleKindForDiagnostic(ModuleKind Kind) { 4450 switch (Kind) { 4451 case MK_PCH: 4452 return 0; // PCH 4453 case MK_ImplicitModule: 4454 case MK_ExplicitModule: 4455 case MK_PrebuiltModule: 4456 return 1; // module 4457 case MK_MainFile: 4458 case MK_Preamble: 4459 return 2; // main source file 4460 } 4461 llvm_unreachable("unknown module kind"); 4462 } 4463 4464 ASTReader::ASTReadResult 4465 ASTReader::ReadASTCore(StringRef FileName, 4466 ModuleKind Type, 4467 SourceLocation ImportLoc, 4468 ModuleFile *ImportedBy, 4469 SmallVectorImpl<ImportedModule> &Loaded, 4470 off_t ExpectedSize, time_t ExpectedModTime, 4471 ASTFileSignature ExpectedSignature, 4472 unsigned ClientLoadCapabilities) { 4473 ModuleFile *M; 4474 std::string ErrorStr; 4475 ModuleManager::AddModuleResult AddResult 4476 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy, 4477 getGeneration(), ExpectedSize, ExpectedModTime, 4478 ExpectedSignature, readASTFileSignature, 4479 M, ErrorStr); 4480 4481 switch (AddResult) { 4482 case ModuleManager::AlreadyLoaded: 4483 Diag(diag::remark_module_import) 4484 << M->ModuleName << M->FileName << (ImportedBy ? true : false) 4485 << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef()); 4486 return Success; 4487 4488 case ModuleManager::NewlyLoaded: 4489 // Load module file below. 4490 break; 4491 4492 case ModuleManager::Missing: 4493 // The module file was missing; if the client can handle that, return 4494 // it. 4495 if (ClientLoadCapabilities & ARR_Missing) 4496 return Missing; 4497 4498 // Otherwise, return an error. 4499 Diag(diag::err_ast_file_not_found) 4500 << moduleKindForDiagnostic(Type) << FileName << !ErrorStr.empty() 4501 << ErrorStr; 4502 return Failure; 4503 4504 case ModuleManager::OutOfDate: 4505 // We couldn't load the module file because it is out-of-date. If the 4506 // client can handle out-of-date, return it. 4507 if (ClientLoadCapabilities & ARR_OutOfDate) 4508 return OutOfDate; 4509 4510 // Otherwise, return an error. 4511 Diag(diag::err_ast_file_out_of_date) 4512 << moduleKindForDiagnostic(Type) << FileName << !ErrorStr.empty() 4513 << ErrorStr; 4514 return Failure; 4515 } 4516 4517 assert(M && "Missing module file"); 4518 4519 bool ShouldFinalizePCM = false; 4520 auto FinalizeOrDropPCM = llvm::make_scope_exit([&]() { 4521 auto &MC = getModuleManager().getModuleCache(); 4522 if (ShouldFinalizePCM) 4523 MC.finalizePCM(FileName); 4524 else 4525 MC.tryToDropPCM(FileName); 4526 }); 4527 ModuleFile &F = *M; 4528 BitstreamCursor &Stream = F.Stream; 4529 Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(*F.Buffer)); 4530 F.SizeInBits = F.Buffer->getBufferSize() * 8; 4531 4532 // Sniff for the signature. 4533 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) { 4534 Diag(diag::err_ast_file_invalid) 4535 << moduleKindForDiagnostic(Type) << FileName << std::move(Err); 4536 return Failure; 4537 } 4538 4539 // This is used for compatibility with older PCH formats. 4540 bool HaveReadControlBlock = false; 4541 while (true) { 4542 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); 4543 if (!MaybeEntry) { 4544 Error(MaybeEntry.takeError()); 4545 return Failure; 4546 } 4547 llvm::BitstreamEntry Entry = MaybeEntry.get(); 4548 4549 switch (Entry.Kind) { 4550 case llvm::BitstreamEntry::Error: 4551 case llvm::BitstreamEntry::Record: 4552 case llvm::BitstreamEntry::EndBlock: 4553 Error("invalid record at top-level of AST file"); 4554 return Failure; 4555 4556 case llvm::BitstreamEntry::SubBlock: 4557 break; 4558 } 4559 4560 switch (Entry.ID) { 4561 case CONTROL_BLOCK_ID: 4562 HaveReadControlBlock = true; 4563 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) { 4564 case Success: 4565 // Check that we didn't try to load a non-module AST file as a module. 4566 // 4567 // FIXME: Should we also perform the converse check? Loading a module as 4568 // a PCH file sort of works, but it's a bit wonky. 4569 if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule || 4570 Type == MK_PrebuiltModule) && 4571 F.ModuleName.empty()) { 4572 auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure; 4573 if (Result != OutOfDate || 4574 (ClientLoadCapabilities & ARR_OutOfDate) == 0) 4575 Diag(diag::err_module_file_not_module) << FileName; 4576 return Result; 4577 } 4578 break; 4579 4580 case Failure: return Failure; 4581 case Missing: return Missing; 4582 case OutOfDate: return OutOfDate; 4583 case VersionMismatch: return VersionMismatch; 4584 case ConfigurationMismatch: return ConfigurationMismatch; 4585 case HadErrors: return HadErrors; 4586 } 4587 break; 4588 4589 case AST_BLOCK_ID: 4590 if (!HaveReadControlBlock) { 4591 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0) 4592 Diag(diag::err_pch_version_too_old); 4593 return VersionMismatch; 4594 } 4595 4596 // Record that we've loaded this module. 4597 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc)); 4598 ShouldFinalizePCM = true; 4599 return Success; 4600 4601 case UNHASHED_CONTROL_BLOCK_ID: 4602 // This block is handled using look-ahead during ReadControlBlock. We 4603 // shouldn't get here! 4604 Error("malformed block record in AST file"); 4605 return Failure; 4606 4607 default: 4608 if (llvm::Error Err = Stream.SkipBlock()) { 4609 Error(std::move(Err)); 4610 return Failure; 4611 } 4612 break; 4613 } 4614 } 4615 4616 llvm_unreachable("unexpected break; expected return"); 4617 } 4618 4619 ASTReader::ASTReadResult 4620 ASTReader::readUnhashedControlBlock(ModuleFile &F, bool WasImportedBy, 4621 unsigned ClientLoadCapabilities) { 4622 const HeaderSearchOptions &HSOpts = 4623 PP.getHeaderSearchInfo().getHeaderSearchOpts(); 4624 bool AllowCompatibleConfigurationMismatch = 4625 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule; 4626 4627 ASTReadResult Result = readUnhashedControlBlockImpl( 4628 &F, F.Data, ClientLoadCapabilities, AllowCompatibleConfigurationMismatch, 4629 Listener.get(), 4630 WasImportedBy ? false : HSOpts.ModulesValidateDiagnosticOptions); 4631 4632 // If F was directly imported by another module, it's implicitly validated by 4633 // the importing module. 4634 if (DisableValidation || WasImportedBy || 4635 (AllowConfigurationMismatch && Result == ConfigurationMismatch)) 4636 return Success; 4637 4638 if (Result == Failure) { 4639 Error("malformed block record in AST file"); 4640 return Failure; 4641 } 4642 4643 if (Result == OutOfDate && F.Kind == MK_ImplicitModule) { 4644 // If this module has already been finalized in the ModuleCache, we're stuck 4645 // with it; we can only load a single version of each module. 4646 // 4647 // This can happen when a module is imported in two contexts: in one, as a 4648 // user module; in another, as a system module (due to an import from 4649 // another module marked with the [system] flag). It usually indicates a 4650 // bug in the module map: this module should also be marked with [system]. 4651 // 4652 // If -Wno-system-headers (the default), and the first import is as a 4653 // system module, then validation will fail during the as-user import, 4654 // since -Werror flags won't have been validated. However, it's reasonable 4655 // to treat this consistently as a system module. 4656 // 4657 // If -Wsystem-headers, the PCM on disk was built with 4658 // -Wno-system-headers, and the first import is as a user module, then 4659 // validation will fail during the as-system import since the PCM on disk 4660 // doesn't guarantee that -Werror was respected. However, the -Werror 4661 // flags were checked during the initial as-user import. 4662 if (getModuleManager().getModuleCache().isPCMFinal(F.FileName)) { 4663 Diag(diag::warn_module_system_bit_conflict) << F.FileName; 4664 return Success; 4665 } 4666 } 4667 4668 return Result; 4669 } 4670 4671 ASTReader::ASTReadResult ASTReader::readUnhashedControlBlockImpl( 4672 ModuleFile *F, llvm::StringRef StreamData, unsigned ClientLoadCapabilities, 4673 bool AllowCompatibleConfigurationMismatch, ASTReaderListener *Listener, 4674 bool ValidateDiagnosticOptions) { 4675 // Initialize a stream. 4676 BitstreamCursor Stream(StreamData); 4677 4678 // Sniff for the signature. 4679 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) { 4680 // FIXME this drops the error on the floor. 4681 consumeError(std::move(Err)); 4682 return Failure; 4683 } 4684 4685 // Scan for the UNHASHED_CONTROL_BLOCK_ID block. 4686 if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID)) 4687 return Failure; 4688 4689 // Read all of the records in the options block. 4690 RecordData Record; 4691 ASTReadResult Result = Success; 4692 while (true) { 4693 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); 4694 if (!MaybeEntry) { 4695 // FIXME this drops the error on the floor. 4696 consumeError(MaybeEntry.takeError()); 4697 return Failure; 4698 } 4699 llvm::BitstreamEntry Entry = MaybeEntry.get(); 4700 4701 switch (Entry.Kind) { 4702 case llvm::BitstreamEntry::Error: 4703 case llvm::BitstreamEntry::SubBlock: 4704 return Failure; 4705 4706 case llvm::BitstreamEntry::EndBlock: 4707 return Result; 4708 4709 case llvm::BitstreamEntry::Record: 4710 // The interesting case. 4711 break; 4712 } 4713 4714 // Read and process a record. 4715 Record.clear(); 4716 Expected<unsigned> MaybeRecordType = Stream.readRecord(Entry.ID, Record); 4717 if (!MaybeRecordType) { 4718 // FIXME this drops the error. 4719 return Failure; 4720 } 4721 switch ((UnhashedControlBlockRecordTypes)MaybeRecordType.get()) { 4722 case SIGNATURE: 4723 if (F) 4724 F->Signature = ASTFileSignature::create(Record.begin(), Record.end()); 4725 break; 4726 case AST_BLOCK_HASH: 4727 if (F) 4728 F->ASTBlockHash = 4729 ASTFileSignature::create(Record.begin(), Record.end()); 4730 break; 4731 case DIAGNOSTIC_OPTIONS: { 4732 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0; 4733 if (Listener && ValidateDiagnosticOptions && 4734 !AllowCompatibleConfigurationMismatch && 4735 ParseDiagnosticOptions(Record, Complain, *Listener)) 4736 Result = OutOfDate; // Don't return early. Read the signature. 4737 break; 4738 } 4739 case DIAG_PRAGMA_MAPPINGS: 4740 if (!F) 4741 break; 4742 if (F->PragmaDiagMappings.empty()) 4743 F->PragmaDiagMappings.swap(Record); 4744 else 4745 F->PragmaDiagMappings.insert(F->PragmaDiagMappings.end(), 4746 Record.begin(), Record.end()); 4747 break; 4748 } 4749 } 4750 } 4751 4752 /// Parse a record and blob containing module file extension metadata. 4753 static bool parseModuleFileExtensionMetadata( 4754 const SmallVectorImpl<uint64_t> &Record, 4755 StringRef Blob, 4756 ModuleFileExtensionMetadata &Metadata) { 4757 if (Record.size() < 4) return true; 4758 4759 Metadata.MajorVersion = Record[0]; 4760 Metadata.MinorVersion = Record[1]; 4761 4762 unsigned BlockNameLen = Record[2]; 4763 unsigned UserInfoLen = Record[3]; 4764 4765 if (BlockNameLen + UserInfoLen > Blob.size()) return true; 4766 4767 Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen); 4768 Metadata.UserInfo = std::string(Blob.data() + BlockNameLen, 4769 Blob.data() + BlockNameLen + UserInfoLen); 4770 return false; 4771 } 4772 4773 ASTReader::ASTReadResult ASTReader::ReadExtensionBlock(ModuleFile &F) { 4774 BitstreamCursor &Stream = F.Stream; 4775 4776 RecordData Record; 4777 while (true) { 4778 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); 4779 if (!MaybeEntry) { 4780 Error(MaybeEntry.takeError()); 4781 return Failure; 4782 } 4783 llvm::BitstreamEntry Entry = MaybeEntry.get(); 4784 4785 switch (Entry.Kind) { 4786 case llvm::BitstreamEntry::SubBlock: 4787 if (llvm::Error Err = Stream.SkipBlock()) { 4788 Error(std::move(Err)); 4789 return Failure; 4790 } 4791 continue; 4792 4793 case llvm::BitstreamEntry::EndBlock: 4794 return Success; 4795 4796 case llvm::BitstreamEntry::Error: 4797 return HadErrors; 4798 4799 case llvm::BitstreamEntry::Record: 4800 break; 4801 } 4802 4803 Record.clear(); 4804 StringRef Blob; 4805 Expected<unsigned> MaybeRecCode = 4806 Stream.readRecord(Entry.ID, Record, &Blob); 4807 if (!MaybeRecCode) { 4808 Error(MaybeRecCode.takeError()); 4809 return Failure; 4810 } 4811 switch (MaybeRecCode.get()) { 4812 case EXTENSION_METADATA: { 4813 ModuleFileExtensionMetadata Metadata; 4814 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata)) { 4815 Error("malformed EXTENSION_METADATA in AST file"); 4816 return Failure; 4817 } 4818 4819 // Find a module file extension with this block name. 4820 auto Known = ModuleFileExtensions.find(Metadata.BlockName); 4821 if (Known == ModuleFileExtensions.end()) break; 4822 4823 // Form a reader. 4824 if (auto Reader = Known->second->createExtensionReader(Metadata, *this, 4825 F, Stream)) { 4826 F.ExtensionReaders.push_back(std::move(Reader)); 4827 } 4828 4829 break; 4830 } 4831 } 4832 } 4833 4834 return Success; 4835 } 4836 4837 void ASTReader::InitializeContext() { 4838 assert(ContextObj && "no context to initialize"); 4839 ASTContext &Context = *ContextObj; 4840 4841 // If there's a listener, notify them that we "read" the translation unit. 4842 if (DeserializationListener) 4843 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID, 4844 Context.getTranslationUnitDecl()); 4845 4846 // FIXME: Find a better way to deal with collisions between these 4847 // built-in types. Right now, we just ignore the problem. 4848 4849 // Load the special types. 4850 if (SpecialTypes.size() >= NumSpecialTypeIDs) { 4851 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) { 4852 if (!Context.CFConstantStringTypeDecl) 4853 Context.setCFConstantStringType(GetType(String)); 4854 } 4855 4856 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) { 4857 QualType FileType = GetType(File); 4858 if (FileType.isNull()) { 4859 Error("FILE type is NULL"); 4860 return; 4861 } 4862 4863 if (!Context.FILEDecl) { 4864 if (const TypedefType *Typedef = FileType->getAs<TypedefType>()) 4865 Context.setFILEDecl(Typedef->getDecl()); 4866 else { 4867 const TagType *Tag = FileType->getAs<TagType>(); 4868 if (!Tag) { 4869 Error("Invalid FILE type in AST file"); 4870 return; 4871 } 4872 Context.setFILEDecl(Tag->getDecl()); 4873 } 4874 } 4875 } 4876 4877 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) { 4878 QualType Jmp_bufType = GetType(Jmp_buf); 4879 if (Jmp_bufType.isNull()) { 4880 Error("jmp_buf type is NULL"); 4881 return; 4882 } 4883 4884 if (!Context.jmp_bufDecl) { 4885 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>()) 4886 Context.setjmp_bufDecl(Typedef->getDecl()); 4887 else { 4888 const TagType *Tag = Jmp_bufType->getAs<TagType>(); 4889 if (!Tag) { 4890 Error("Invalid jmp_buf type in AST file"); 4891 return; 4892 } 4893 Context.setjmp_bufDecl(Tag->getDecl()); 4894 } 4895 } 4896 } 4897 4898 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) { 4899 QualType Sigjmp_bufType = GetType(Sigjmp_buf); 4900 if (Sigjmp_bufType.isNull()) { 4901 Error("sigjmp_buf type is NULL"); 4902 return; 4903 } 4904 4905 if (!Context.sigjmp_bufDecl) { 4906 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>()) 4907 Context.setsigjmp_bufDecl(Typedef->getDecl()); 4908 else { 4909 const TagType *Tag = Sigjmp_bufType->getAs<TagType>(); 4910 assert(Tag && "Invalid sigjmp_buf type in AST file"); 4911 Context.setsigjmp_bufDecl(Tag->getDecl()); 4912 } 4913 } 4914 } 4915 4916 if (unsigned ObjCIdRedef 4917 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) { 4918 if (Context.ObjCIdRedefinitionType.isNull()) 4919 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef); 4920 } 4921 4922 if (unsigned ObjCClassRedef 4923 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) { 4924 if (Context.ObjCClassRedefinitionType.isNull()) 4925 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef); 4926 } 4927 4928 if (unsigned ObjCSelRedef 4929 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) { 4930 if (Context.ObjCSelRedefinitionType.isNull()) 4931 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef); 4932 } 4933 4934 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) { 4935 QualType Ucontext_tType = GetType(Ucontext_t); 4936 if (Ucontext_tType.isNull()) { 4937 Error("ucontext_t type is NULL"); 4938 return; 4939 } 4940 4941 if (!Context.ucontext_tDecl) { 4942 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>()) 4943 Context.setucontext_tDecl(Typedef->getDecl()); 4944 else { 4945 const TagType *Tag = Ucontext_tType->getAs<TagType>(); 4946 assert(Tag && "Invalid ucontext_t type in AST file"); 4947 Context.setucontext_tDecl(Tag->getDecl()); 4948 } 4949 } 4950 } 4951 } 4952 4953 ReadPragmaDiagnosticMappings(Context.getDiagnostics()); 4954 4955 // If there were any CUDA special declarations, deserialize them. 4956 if (!CUDASpecialDeclRefs.empty()) { 4957 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!"); 4958 Context.setcudaConfigureCallDecl( 4959 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0]))); 4960 } 4961 4962 // Re-export any modules that were imported by a non-module AST file. 4963 // FIXME: This does not make macro-only imports visible again. 4964 for (auto &Import : ImportedModules) { 4965 if (Module *Imported = getSubmodule(Import.ID)) { 4966 makeModuleVisible(Imported, Module::AllVisible, 4967 /*ImportLoc=*/Import.ImportLoc); 4968 if (Import.ImportLoc.isValid()) 4969 PP.makeModuleVisible(Imported, Import.ImportLoc); 4970 // This updates visibility for Preprocessor only. For Sema, which can be 4971 // nullptr here, we do the same later, in UpdateSema(). 4972 } 4973 } 4974 } 4975 4976 void ASTReader::finalizeForWriting() { 4977 // Nothing to do for now. 4978 } 4979 4980 /// Reads and return the signature record from \p PCH's control block, or 4981 /// else returns 0. 4982 static ASTFileSignature readASTFileSignature(StringRef PCH) { 4983 BitstreamCursor Stream(PCH); 4984 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) { 4985 // FIXME this drops the error on the floor. 4986 consumeError(std::move(Err)); 4987 return ASTFileSignature(); 4988 } 4989 4990 // Scan for the UNHASHED_CONTROL_BLOCK_ID block. 4991 if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID)) 4992 return ASTFileSignature(); 4993 4994 // Scan for SIGNATURE inside the diagnostic options block. 4995 ASTReader::RecordData Record; 4996 while (true) { 4997 Expected<llvm::BitstreamEntry> MaybeEntry = 4998 Stream.advanceSkippingSubblocks(); 4999 if (!MaybeEntry) { 5000 // FIXME this drops the error on the floor. 5001 consumeError(MaybeEntry.takeError()); 5002 return ASTFileSignature(); 5003 } 5004 llvm::BitstreamEntry Entry = MaybeEntry.get(); 5005 5006 if (Entry.Kind != llvm::BitstreamEntry::Record) 5007 return ASTFileSignature(); 5008 5009 Record.clear(); 5010 StringRef Blob; 5011 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob); 5012 if (!MaybeRecord) { 5013 // FIXME this drops the error on the floor. 5014 consumeError(MaybeRecord.takeError()); 5015 return ASTFileSignature(); 5016 } 5017 if (SIGNATURE == MaybeRecord.get()) 5018 return ASTFileSignature::create(Record.begin(), 5019 Record.begin() + ASTFileSignature::size); 5020 } 5021 } 5022 5023 /// Retrieve the name of the original source file name 5024 /// directly from the AST file, without actually loading the AST 5025 /// file. 5026 std::string ASTReader::getOriginalSourceFile( 5027 const std::string &ASTFileName, FileManager &FileMgr, 5028 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) { 5029 // Open the AST file. 5030 auto Buffer = FileMgr.getBufferForFile(ASTFileName); 5031 if (!Buffer) { 5032 Diags.Report(diag::err_fe_unable_to_read_pch_file) 5033 << ASTFileName << Buffer.getError().message(); 5034 return std::string(); 5035 } 5036 5037 // Initialize the stream 5038 BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer)); 5039 5040 // Sniff for the signature. 5041 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) { 5042 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName << std::move(Err); 5043 return std::string(); 5044 } 5045 5046 // Scan for the CONTROL_BLOCK_ID block. 5047 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) { 5048 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName; 5049 return std::string(); 5050 } 5051 5052 // Scan for ORIGINAL_FILE inside the control block. 5053 RecordData Record; 5054 while (true) { 5055 Expected<llvm::BitstreamEntry> MaybeEntry = 5056 Stream.advanceSkippingSubblocks(); 5057 if (!MaybeEntry) { 5058 // FIXME this drops errors on the floor. 5059 consumeError(MaybeEntry.takeError()); 5060 return std::string(); 5061 } 5062 llvm::BitstreamEntry Entry = MaybeEntry.get(); 5063 5064 if (Entry.Kind == llvm::BitstreamEntry::EndBlock) 5065 return std::string(); 5066 5067 if (Entry.Kind != llvm::BitstreamEntry::Record) { 5068 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName; 5069 return std::string(); 5070 } 5071 5072 Record.clear(); 5073 StringRef Blob; 5074 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob); 5075 if (!MaybeRecord) { 5076 // FIXME this drops the errors on the floor. 5077 consumeError(MaybeRecord.takeError()); 5078 return std::string(); 5079 } 5080 if (ORIGINAL_FILE == MaybeRecord.get()) 5081 return Blob.str(); 5082 } 5083 } 5084 5085 namespace { 5086 5087 class SimplePCHValidator : public ASTReaderListener { 5088 const LangOptions &ExistingLangOpts; 5089 const TargetOptions &ExistingTargetOpts; 5090 const PreprocessorOptions &ExistingPPOpts; 5091 std::string ExistingModuleCachePath; 5092 FileManager &FileMgr; 5093 5094 public: 5095 SimplePCHValidator(const LangOptions &ExistingLangOpts, 5096 const TargetOptions &ExistingTargetOpts, 5097 const PreprocessorOptions &ExistingPPOpts, 5098 StringRef ExistingModuleCachePath, FileManager &FileMgr) 5099 : ExistingLangOpts(ExistingLangOpts), 5100 ExistingTargetOpts(ExistingTargetOpts), 5101 ExistingPPOpts(ExistingPPOpts), 5102 ExistingModuleCachePath(ExistingModuleCachePath), FileMgr(FileMgr) {} 5103 5104 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain, 5105 bool AllowCompatibleDifferences) override { 5106 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr, 5107 AllowCompatibleDifferences); 5108 } 5109 5110 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain, 5111 bool AllowCompatibleDifferences) override { 5112 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr, 5113 AllowCompatibleDifferences); 5114 } 5115 5116 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, 5117 StringRef SpecificModuleCachePath, 5118 bool Complain) override { 5119 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath, 5120 ExistingModuleCachePath, 5121 nullptr, ExistingLangOpts); 5122 } 5123 5124 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, 5125 bool Complain, 5126 std::string &SuggestedPredefines) override { 5127 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr, 5128 SuggestedPredefines, ExistingLangOpts); 5129 } 5130 }; 5131 5132 } // namespace 5133 5134 bool ASTReader::readASTFileControlBlock( 5135 StringRef Filename, FileManager &FileMgr, 5136 const PCHContainerReader &PCHContainerRdr, 5137 bool FindModuleFileExtensions, 5138 ASTReaderListener &Listener, bool ValidateDiagnosticOptions) { 5139 // Open the AST file. 5140 // FIXME: This allows use of the VFS; we do not allow use of the 5141 // VFS when actually loading a module. 5142 auto Buffer = FileMgr.getBufferForFile(Filename); 5143 if (!Buffer) { 5144 return true; 5145 } 5146 5147 // Initialize the stream 5148 StringRef Bytes = PCHContainerRdr.ExtractPCH(**Buffer); 5149 BitstreamCursor Stream(Bytes); 5150 5151 // Sniff for the signature. 5152 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) { 5153 consumeError(std::move(Err)); // FIXME this drops errors on the floor. 5154 return true; 5155 } 5156 5157 // Scan for the CONTROL_BLOCK_ID block. 5158 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) 5159 return true; 5160 5161 bool NeedsInputFiles = Listener.needsInputFileVisitation(); 5162 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation(); 5163 bool NeedsImports = Listener.needsImportVisitation(); 5164 BitstreamCursor InputFilesCursor; 5165 5166 RecordData Record; 5167 std::string ModuleDir; 5168 bool DoneWithControlBlock = false; 5169 while (!DoneWithControlBlock) { 5170 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); 5171 if (!MaybeEntry) { 5172 // FIXME this drops the error on the floor. 5173 consumeError(MaybeEntry.takeError()); 5174 return true; 5175 } 5176 llvm::BitstreamEntry Entry = MaybeEntry.get(); 5177 5178 switch (Entry.Kind) { 5179 case llvm::BitstreamEntry::SubBlock: { 5180 switch (Entry.ID) { 5181 case OPTIONS_BLOCK_ID: { 5182 std::string IgnoredSuggestedPredefines; 5183 if (ReadOptionsBlock(Stream, ARR_ConfigurationMismatch | ARR_OutOfDate, 5184 /*AllowCompatibleConfigurationMismatch*/ false, 5185 Listener, IgnoredSuggestedPredefines) != Success) 5186 return true; 5187 break; 5188 } 5189 5190 case INPUT_FILES_BLOCK_ID: 5191 InputFilesCursor = Stream; 5192 if (llvm::Error Err = Stream.SkipBlock()) { 5193 // FIXME this drops the error on the floor. 5194 consumeError(std::move(Err)); 5195 return true; 5196 } 5197 if (NeedsInputFiles && 5198 ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID)) 5199 return true; 5200 break; 5201 5202 default: 5203 if (llvm::Error Err = Stream.SkipBlock()) { 5204 // FIXME this drops the error on the floor. 5205 consumeError(std::move(Err)); 5206 return true; 5207 } 5208 break; 5209 } 5210 5211 continue; 5212 } 5213 5214 case llvm::BitstreamEntry::EndBlock: 5215 DoneWithControlBlock = true; 5216 break; 5217 5218 case llvm::BitstreamEntry::Error: 5219 return true; 5220 5221 case llvm::BitstreamEntry::Record: 5222 break; 5223 } 5224 5225 if (DoneWithControlBlock) break; 5226 5227 Record.clear(); 5228 StringRef Blob; 5229 Expected<unsigned> MaybeRecCode = 5230 Stream.readRecord(Entry.ID, Record, &Blob); 5231 if (!MaybeRecCode) { 5232 // FIXME this drops the error. 5233 return Failure; 5234 } 5235 switch ((ControlRecordTypes)MaybeRecCode.get()) { 5236 case METADATA: 5237 if (Record[0] != VERSION_MAJOR) 5238 return true; 5239 if (Listener.ReadFullVersionInformation(Blob)) 5240 return true; 5241 break; 5242 case MODULE_NAME: 5243 Listener.ReadModuleName(Blob); 5244 break; 5245 case MODULE_DIRECTORY: 5246 ModuleDir = std::string(Blob); 5247 break; 5248 case MODULE_MAP_FILE: { 5249 unsigned Idx = 0; 5250 auto Path = ReadString(Record, Idx); 5251 ResolveImportedPath(Path, ModuleDir); 5252 Listener.ReadModuleMapFile(Path); 5253 break; 5254 } 5255 case INPUT_FILE_OFFSETS: { 5256 if (!NeedsInputFiles) 5257 break; 5258 5259 unsigned NumInputFiles = Record[0]; 5260 unsigned NumUserFiles = Record[1]; 5261 const llvm::support::unaligned_uint64_t *InputFileOffs = 5262 (const llvm::support::unaligned_uint64_t *)Blob.data(); 5263 for (unsigned I = 0; I != NumInputFiles; ++I) { 5264 // Go find this input file. 5265 bool isSystemFile = I >= NumUserFiles; 5266 5267 if (isSystemFile && !NeedsSystemInputFiles) 5268 break; // the rest are system input files 5269 5270 BitstreamCursor &Cursor = InputFilesCursor; 5271 SavedStreamPosition SavedPosition(Cursor); 5272 if (llvm::Error Err = Cursor.JumpToBit(InputFileOffs[I])) { 5273 // FIXME this drops errors on the floor. 5274 consumeError(std::move(Err)); 5275 } 5276 5277 Expected<unsigned> MaybeCode = Cursor.ReadCode(); 5278 if (!MaybeCode) { 5279 // FIXME this drops errors on the floor. 5280 consumeError(MaybeCode.takeError()); 5281 } 5282 unsigned Code = MaybeCode.get(); 5283 5284 RecordData Record; 5285 StringRef Blob; 5286 bool shouldContinue = false; 5287 Expected<unsigned> MaybeRecordType = 5288 Cursor.readRecord(Code, Record, &Blob); 5289 if (!MaybeRecordType) { 5290 // FIXME this drops errors on the floor. 5291 consumeError(MaybeRecordType.takeError()); 5292 } 5293 switch ((InputFileRecordTypes)MaybeRecordType.get()) { 5294 case INPUT_FILE_HASH: 5295 break; 5296 case INPUT_FILE: 5297 bool Overridden = static_cast<bool>(Record[3]); 5298 std::string Filename = std::string(Blob); 5299 ResolveImportedPath(Filename, ModuleDir); 5300 shouldContinue = Listener.visitInputFile( 5301 Filename, isSystemFile, Overridden, /*IsExplicitModule*/false); 5302 break; 5303 } 5304 if (!shouldContinue) 5305 break; 5306 } 5307 break; 5308 } 5309 5310 case IMPORTS: { 5311 if (!NeedsImports) 5312 break; 5313 5314 unsigned Idx = 0, N = Record.size(); 5315 while (Idx < N) { 5316 // Read information about the AST file. 5317 Idx += 5318 1 + 1 + 1 + 1 + 5319 ASTFileSignature::size; // Kind, ImportLoc, Size, ModTime, Signature 5320 std::string ModuleName = ReadString(Record, Idx); 5321 std::string Filename = ReadString(Record, Idx); 5322 ResolveImportedPath(Filename, ModuleDir); 5323 Listener.visitImport(ModuleName, Filename); 5324 } 5325 break; 5326 } 5327 5328 default: 5329 // No other validation to perform. 5330 break; 5331 } 5332 } 5333 5334 // Look for module file extension blocks, if requested. 5335 if (FindModuleFileExtensions) { 5336 BitstreamCursor SavedStream = Stream; 5337 while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) { 5338 bool DoneWithExtensionBlock = false; 5339 while (!DoneWithExtensionBlock) { 5340 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); 5341 if (!MaybeEntry) { 5342 // FIXME this drops the error. 5343 return true; 5344 } 5345 llvm::BitstreamEntry Entry = MaybeEntry.get(); 5346 5347 switch (Entry.Kind) { 5348 case llvm::BitstreamEntry::SubBlock: 5349 if (llvm::Error Err = Stream.SkipBlock()) { 5350 // FIXME this drops the error on the floor. 5351 consumeError(std::move(Err)); 5352 return true; 5353 } 5354 continue; 5355 5356 case llvm::BitstreamEntry::EndBlock: 5357 DoneWithExtensionBlock = true; 5358 continue; 5359 5360 case llvm::BitstreamEntry::Error: 5361 return true; 5362 5363 case llvm::BitstreamEntry::Record: 5364 break; 5365 } 5366 5367 Record.clear(); 5368 StringRef Blob; 5369 Expected<unsigned> MaybeRecCode = 5370 Stream.readRecord(Entry.ID, Record, &Blob); 5371 if (!MaybeRecCode) { 5372 // FIXME this drops the error. 5373 return true; 5374 } 5375 switch (MaybeRecCode.get()) { 5376 case EXTENSION_METADATA: { 5377 ModuleFileExtensionMetadata Metadata; 5378 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata)) 5379 return true; 5380 5381 Listener.readModuleFileExtension(Metadata); 5382 break; 5383 } 5384 } 5385 } 5386 } 5387 Stream = SavedStream; 5388 } 5389 5390 // Scan for the UNHASHED_CONTROL_BLOCK_ID block. 5391 if (readUnhashedControlBlockImpl( 5392 nullptr, Bytes, ARR_ConfigurationMismatch | ARR_OutOfDate, 5393 /*AllowCompatibleConfigurationMismatch*/ false, &Listener, 5394 ValidateDiagnosticOptions) != Success) 5395 return true; 5396 5397 return false; 5398 } 5399 5400 bool ASTReader::isAcceptableASTFile(StringRef Filename, FileManager &FileMgr, 5401 const PCHContainerReader &PCHContainerRdr, 5402 const LangOptions &LangOpts, 5403 const TargetOptions &TargetOpts, 5404 const PreprocessorOptions &PPOpts, 5405 StringRef ExistingModuleCachePath) { 5406 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts, 5407 ExistingModuleCachePath, FileMgr); 5408 return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr, 5409 /*FindModuleFileExtensions=*/false, 5410 validator, 5411 /*ValidateDiagnosticOptions=*/true); 5412 } 5413 5414 ASTReader::ASTReadResult 5415 ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) { 5416 // Enter the submodule block. 5417 if (llvm::Error Err = F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) { 5418 Error(std::move(Err)); 5419 return Failure; 5420 } 5421 5422 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap(); 5423 bool First = true; 5424 Module *CurrentModule = nullptr; 5425 RecordData Record; 5426 while (true) { 5427 Expected<llvm::BitstreamEntry> MaybeEntry = 5428 F.Stream.advanceSkippingSubblocks(); 5429 if (!MaybeEntry) { 5430 Error(MaybeEntry.takeError()); 5431 return Failure; 5432 } 5433 llvm::BitstreamEntry Entry = MaybeEntry.get(); 5434 5435 switch (Entry.Kind) { 5436 case llvm::BitstreamEntry::SubBlock: // Handled for us already. 5437 case llvm::BitstreamEntry::Error: 5438 Error("malformed block record in AST file"); 5439 return Failure; 5440 case llvm::BitstreamEntry::EndBlock: 5441 return Success; 5442 case llvm::BitstreamEntry::Record: 5443 // The interesting case. 5444 break; 5445 } 5446 5447 // Read a record. 5448 StringRef Blob; 5449 Record.clear(); 5450 Expected<unsigned> MaybeKind = F.Stream.readRecord(Entry.ID, Record, &Blob); 5451 if (!MaybeKind) { 5452 Error(MaybeKind.takeError()); 5453 return Failure; 5454 } 5455 unsigned Kind = MaybeKind.get(); 5456 5457 if ((Kind == SUBMODULE_METADATA) != First) { 5458 Error("submodule metadata record should be at beginning of block"); 5459 return Failure; 5460 } 5461 First = false; 5462 5463 // Submodule information is only valid if we have a current module. 5464 // FIXME: Should we error on these cases? 5465 if (!CurrentModule && Kind != SUBMODULE_METADATA && 5466 Kind != SUBMODULE_DEFINITION) 5467 continue; 5468 5469 switch (Kind) { 5470 default: // Default behavior: ignore. 5471 break; 5472 5473 case SUBMODULE_DEFINITION: { 5474 if (Record.size() < 12) { 5475 Error("malformed module definition"); 5476 return Failure; 5477 } 5478 5479 StringRef Name = Blob; 5480 unsigned Idx = 0; 5481 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]); 5482 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]); 5483 Module::ModuleKind Kind = (Module::ModuleKind)Record[Idx++]; 5484 bool IsFramework = Record[Idx++]; 5485 bool IsExplicit = Record[Idx++]; 5486 bool IsSystem = Record[Idx++]; 5487 bool IsExternC = Record[Idx++]; 5488 bool InferSubmodules = Record[Idx++]; 5489 bool InferExplicitSubmodules = Record[Idx++]; 5490 bool InferExportWildcard = Record[Idx++]; 5491 bool ConfigMacrosExhaustive = Record[Idx++]; 5492 bool ModuleMapIsPrivate = Record[Idx++]; 5493 5494 Module *ParentModule = nullptr; 5495 if (Parent) 5496 ParentModule = getSubmodule(Parent); 5497 5498 // Retrieve this (sub)module from the module map, creating it if 5499 // necessary. 5500 CurrentModule = 5501 ModMap.findOrCreateModule(Name, ParentModule, IsFramework, IsExplicit) 5502 .first; 5503 5504 // FIXME: set the definition loc for CurrentModule, or call 5505 // ModMap.setInferredModuleAllowedBy() 5506 5507 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS; 5508 if (GlobalIndex >= SubmodulesLoaded.size() || 5509 SubmodulesLoaded[GlobalIndex]) { 5510 Error("too many submodules"); 5511 return Failure; 5512 } 5513 5514 if (!ParentModule) { 5515 if (const FileEntry *CurFile = CurrentModule->getASTFile()) { 5516 // Don't emit module relocation error if we have -fno-validate-pch 5517 if (!PP.getPreprocessorOpts().DisablePCHValidation && 5518 CurFile != F.File) { 5519 Error(diag::err_module_file_conflict, 5520 CurrentModule->getTopLevelModuleName(), CurFile->getName(), 5521 F.File->getName()); 5522 return Failure; 5523 } 5524 } 5525 5526 F.DidReadTopLevelSubmodule = true; 5527 CurrentModule->setASTFile(F.File); 5528 CurrentModule->PresumedModuleMapFile = F.ModuleMapPath; 5529 } 5530 5531 CurrentModule->Kind = Kind; 5532 CurrentModule->Signature = F.Signature; 5533 CurrentModule->IsFromModuleFile = true; 5534 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem; 5535 CurrentModule->IsExternC = IsExternC; 5536 CurrentModule->InferSubmodules = InferSubmodules; 5537 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules; 5538 CurrentModule->InferExportWildcard = InferExportWildcard; 5539 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive; 5540 CurrentModule->ModuleMapIsPrivate = ModuleMapIsPrivate; 5541 if (DeserializationListener) 5542 DeserializationListener->ModuleRead(GlobalID, CurrentModule); 5543 5544 SubmodulesLoaded[GlobalIndex] = CurrentModule; 5545 5546 // Clear out data that will be replaced by what is in the module file. 5547 CurrentModule->LinkLibraries.clear(); 5548 CurrentModule->ConfigMacros.clear(); 5549 CurrentModule->UnresolvedConflicts.clear(); 5550 CurrentModule->Conflicts.clear(); 5551 5552 // The module is available unless it's missing a requirement; relevant 5553 // requirements will be (re-)added by SUBMODULE_REQUIRES records. 5554 // Missing headers that were present when the module was built do not 5555 // make it unavailable -- if we got this far, this must be an explicitly 5556 // imported module file. 5557 CurrentModule->Requirements.clear(); 5558 CurrentModule->MissingHeaders.clear(); 5559 CurrentModule->IsUnimportable = 5560 ParentModule && ParentModule->IsUnimportable; 5561 CurrentModule->IsAvailable = !CurrentModule->IsUnimportable; 5562 break; 5563 } 5564 5565 case SUBMODULE_UMBRELLA_HEADER: { 5566 std::string Filename = std::string(Blob); 5567 ResolveImportedPath(F, Filename); 5568 if (auto Umbrella = PP.getFileManager().getOptionalFileRef(Filename)) { 5569 if (!CurrentModule->getUmbrellaHeader()) 5570 ModMap.setUmbrellaHeader(CurrentModule, *Umbrella, Blob); 5571 else if (CurrentModule->getUmbrellaHeader().Entry != *Umbrella) { 5572 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) 5573 Error("mismatched umbrella headers in submodule"); 5574 return OutOfDate; 5575 } 5576 } 5577 break; 5578 } 5579 5580 case SUBMODULE_HEADER: 5581 case SUBMODULE_EXCLUDED_HEADER: 5582 case SUBMODULE_PRIVATE_HEADER: 5583 // We lazily associate headers with their modules via the HeaderInfo table. 5584 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead 5585 // of complete filenames or remove it entirely. 5586 break; 5587 5588 case SUBMODULE_TEXTUAL_HEADER: 5589 case SUBMODULE_PRIVATE_TEXTUAL_HEADER: 5590 // FIXME: Textual headers are not marked in the HeaderInfo table. Load 5591 // them here. 5592 break; 5593 5594 case SUBMODULE_TOPHEADER: 5595 CurrentModule->addTopHeaderFilename(Blob); 5596 break; 5597 5598 case SUBMODULE_UMBRELLA_DIR: { 5599 std::string Dirname = std::string(Blob); 5600 ResolveImportedPath(F, Dirname); 5601 if (auto Umbrella = 5602 PP.getFileManager().getOptionalDirectoryRef(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_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 (PragmaAlignPackCurrentValue) { 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 (!PragmaAlignPackStack.empty() && 7884 PragmaAlignPackStack.front().Location.isInvalid()) { 7885 assert(PragmaAlignPackStack.front().Value == 7886 SemaObj->AlignPackStack.DefaultValue && 7887 "Expected a default alignment value"); 7888 SemaObj->AlignPackStack.Stack.emplace_back( 7889 PragmaAlignPackStack.front().SlotLabel, 7890 SemaObj->AlignPackStack.CurrentValue, 7891 SemaObj->AlignPackStack.CurrentPragmaLocation, 7892 PragmaAlignPackStack.front().PushLocation); 7893 DropFirst = true; 7894 } 7895 for (const auto &Entry : llvm::makeArrayRef(PragmaAlignPackStack) 7896 .drop_front(DropFirst ? 1 : 0)) { 7897 SemaObj->AlignPackStack.Stack.emplace_back( 7898 Entry.SlotLabel, Entry.Value, Entry.Location, Entry.PushLocation); 7899 } 7900 if (PragmaAlignPackCurrentLocation.isInvalid()) { 7901 assert(*PragmaAlignPackCurrentValue == 7902 SemaObj->AlignPackStack.DefaultValue && 7903 "Expected a default align and pack value"); 7904 // Keep the current values. 7905 } else { 7906 SemaObj->AlignPackStack.CurrentValue = *PragmaAlignPackCurrentValue; 7907 SemaObj->AlignPackStack.CurrentPragmaLocation = 7908 PragmaAlignPackCurrentLocation; 7909 } 7910 } 7911 if (FpPragmaCurrentValue) { 7912 // The bottom of the stack might have a default value. It must be adjusted 7913 // to the current value to ensure that fp-pragma state is preserved after 7914 // popping entries that were included/imported from a PCH/module. 7915 bool DropFirst = false; 7916 if (!FpPragmaStack.empty() && FpPragmaStack.front().Location.isInvalid()) { 7917 assert(FpPragmaStack.front().Value == 7918 SemaObj->FpPragmaStack.DefaultValue && 7919 "Expected a default pragma float_control value"); 7920 SemaObj->FpPragmaStack.Stack.emplace_back( 7921 FpPragmaStack.front().SlotLabel, SemaObj->FpPragmaStack.CurrentValue, 7922 SemaObj->FpPragmaStack.CurrentPragmaLocation, 7923 FpPragmaStack.front().PushLocation); 7924 DropFirst = true; 7925 } 7926 for (const auto &Entry : 7927 llvm::makeArrayRef(FpPragmaStack).drop_front(DropFirst ? 1 : 0)) 7928 SemaObj->FpPragmaStack.Stack.emplace_back( 7929 Entry.SlotLabel, Entry.Value, Entry.Location, Entry.PushLocation); 7930 if (FpPragmaCurrentLocation.isInvalid()) { 7931 assert(*FpPragmaCurrentValue == SemaObj->FpPragmaStack.DefaultValue && 7932 "Expected a default pragma float_control value"); 7933 // Keep the current values. 7934 } else { 7935 SemaObj->FpPragmaStack.CurrentValue = *FpPragmaCurrentValue; 7936 SemaObj->FpPragmaStack.CurrentPragmaLocation = FpPragmaCurrentLocation; 7937 } 7938 } 7939 7940 // For non-modular AST files, restore visiblity of modules. 7941 for (auto &Import : ImportedModules) { 7942 if (Import.ImportLoc.isInvalid()) 7943 continue; 7944 if (Module *Imported = getSubmodule(Import.ID)) { 7945 SemaObj->makeModuleVisible(Imported, Import.ImportLoc); 7946 } 7947 } 7948 } 7949 7950 IdentifierInfo *ASTReader::get(StringRef Name) { 7951 // Note that we are loading an identifier. 7952 Deserializing AnIdentifier(this); 7953 7954 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0, 7955 NumIdentifierLookups, 7956 NumIdentifierLookupHits); 7957 7958 // We don't need to do identifier table lookups in C++ modules (we preload 7959 // all interesting declarations, and don't need to use the scope for name 7960 // lookups). Perform the lookup in PCH files, though, since we don't build 7961 // a complete initial identifier table if we're carrying on from a PCH. 7962 if (PP.getLangOpts().CPlusPlus) { 7963 for (auto F : ModuleMgr.pch_modules()) 7964 if (Visitor(*F)) 7965 break; 7966 } else { 7967 // If there is a global index, look there first to determine which modules 7968 // provably do not have any results for this identifier. 7969 GlobalModuleIndex::HitSet Hits; 7970 GlobalModuleIndex::HitSet *HitsPtr = nullptr; 7971 if (!loadGlobalIndex()) { 7972 if (GlobalIndex->lookupIdentifier(Name, Hits)) { 7973 HitsPtr = &Hits; 7974 } 7975 } 7976 7977 ModuleMgr.visit(Visitor, HitsPtr); 7978 } 7979 7980 IdentifierInfo *II = Visitor.getIdentifierInfo(); 7981 markIdentifierUpToDate(II); 7982 return II; 7983 } 7984 7985 namespace clang { 7986 7987 /// An identifier-lookup iterator that enumerates all of the 7988 /// identifiers stored within a set of AST files. 7989 class ASTIdentifierIterator : public IdentifierIterator { 7990 /// The AST reader whose identifiers are being enumerated. 7991 const ASTReader &Reader; 7992 7993 /// The current index into the chain of AST files stored in 7994 /// the AST reader. 7995 unsigned Index; 7996 7997 /// The current position within the identifier lookup table 7998 /// of the current AST file. 7999 ASTIdentifierLookupTable::key_iterator Current; 8000 8001 /// The end position within the identifier lookup table of 8002 /// the current AST file. 8003 ASTIdentifierLookupTable::key_iterator End; 8004 8005 /// Whether to skip any modules in the ASTReader. 8006 bool SkipModules; 8007 8008 public: 8009 explicit ASTIdentifierIterator(const ASTReader &Reader, 8010 bool SkipModules = false); 8011 8012 StringRef Next() override; 8013 }; 8014 8015 } // namespace clang 8016 8017 ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader, 8018 bool SkipModules) 8019 : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) { 8020 } 8021 8022 StringRef ASTIdentifierIterator::Next() { 8023 while (Current == End) { 8024 // If we have exhausted all of our AST files, we're done. 8025 if (Index == 0) 8026 return StringRef(); 8027 8028 --Index; 8029 ModuleFile &F = Reader.ModuleMgr[Index]; 8030 if (SkipModules && F.isModule()) 8031 continue; 8032 8033 ASTIdentifierLookupTable *IdTable = 8034 (ASTIdentifierLookupTable *)F.IdentifierLookupTable; 8035 Current = IdTable->key_begin(); 8036 End = IdTable->key_end(); 8037 } 8038 8039 // We have any identifiers remaining in the current AST file; return 8040 // the next one. 8041 StringRef Result = *Current; 8042 ++Current; 8043 return Result; 8044 } 8045 8046 namespace { 8047 8048 /// A utility for appending two IdentifierIterators. 8049 class ChainedIdentifierIterator : public IdentifierIterator { 8050 std::unique_ptr<IdentifierIterator> Current; 8051 std::unique_ptr<IdentifierIterator> Queued; 8052 8053 public: 8054 ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First, 8055 std::unique_ptr<IdentifierIterator> Second) 8056 : Current(std::move(First)), Queued(std::move(Second)) {} 8057 8058 StringRef Next() override { 8059 if (!Current) 8060 return StringRef(); 8061 8062 StringRef result = Current->Next(); 8063 if (!result.empty()) 8064 return result; 8065 8066 // Try the queued iterator, which may itself be empty. 8067 Current.reset(); 8068 std::swap(Current, Queued); 8069 return Next(); 8070 } 8071 }; 8072 8073 } // namespace 8074 8075 IdentifierIterator *ASTReader::getIdentifiers() { 8076 if (!loadGlobalIndex()) { 8077 std::unique_ptr<IdentifierIterator> ReaderIter( 8078 new ASTIdentifierIterator(*this, /*SkipModules=*/true)); 8079 std::unique_ptr<IdentifierIterator> ModulesIter( 8080 GlobalIndex->createIdentifierIterator()); 8081 return new ChainedIdentifierIterator(std::move(ReaderIter), 8082 std::move(ModulesIter)); 8083 } 8084 8085 return new ASTIdentifierIterator(*this); 8086 } 8087 8088 namespace clang { 8089 namespace serialization { 8090 8091 class ReadMethodPoolVisitor { 8092 ASTReader &Reader; 8093 Selector Sel; 8094 unsigned PriorGeneration; 8095 unsigned InstanceBits = 0; 8096 unsigned FactoryBits = 0; 8097 bool InstanceHasMoreThanOneDecl = false; 8098 bool FactoryHasMoreThanOneDecl = false; 8099 SmallVector<ObjCMethodDecl *, 4> InstanceMethods; 8100 SmallVector<ObjCMethodDecl *, 4> FactoryMethods; 8101 8102 public: 8103 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel, 8104 unsigned PriorGeneration) 8105 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration) {} 8106 8107 bool operator()(ModuleFile &M) { 8108 if (!M.SelectorLookupTable) 8109 return false; 8110 8111 // If we've already searched this module file, skip it now. 8112 if (M.Generation <= PriorGeneration) 8113 return true; 8114 8115 ++Reader.NumMethodPoolTableLookups; 8116 ASTSelectorLookupTable *PoolTable 8117 = (ASTSelectorLookupTable*)M.SelectorLookupTable; 8118 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel); 8119 if (Pos == PoolTable->end()) 8120 return false; 8121 8122 ++Reader.NumMethodPoolTableHits; 8123 ++Reader.NumSelectorsRead; 8124 // FIXME: Not quite happy with the statistics here. We probably should 8125 // disable this tracking when called via LoadSelector. 8126 // Also, should entries without methods count as misses? 8127 ++Reader.NumMethodPoolEntriesRead; 8128 ASTSelectorLookupTrait::data_type Data = *Pos; 8129 if (Reader.DeserializationListener) 8130 Reader.DeserializationListener->SelectorRead(Data.ID, Sel); 8131 8132 InstanceMethods.append(Data.Instance.begin(), Data.Instance.end()); 8133 FactoryMethods.append(Data.Factory.begin(), Data.Factory.end()); 8134 InstanceBits = Data.InstanceBits; 8135 FactoryBits = Data.FactoryBits; 8136 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl; 8137 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl; 8138 return true; 8139 } 8140 8141 /// Retrieve the instance methods found by this visitor. 8142 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const { 8143 return InstanceMethods; 8144 } 8145 8146 /// Retrieve the instance methods found by this visitor. 8147 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const { 8148 return FactoryMethods; 8149 } 8150 8151 unsigned getInstanceBits() const { return InstanceBits; } 8152 unsigned getFactoryBits() const { return FactoryBits; } 8153 8154 bool instanceHasMoreThanOneDecl() const { 8155 return InstanceHasMoreThanOneDecl; 8156 } 8157 8158 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; } 8159 }; 8160 8161 } // namespace serialization 8162 } // namespace clang 8163 8164 /// Add the given set of methods to the method list. 8165 static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods, 8166 ObjCMethodList &List) { 8167 for (unsigned I = 0, N = Methods.size(); I != N; ++I) { 8168 S.addMethodToGlobalList(&List, Methods[I]); 8169 } 8170 } 8171 8172 void ASTReader::ReadMethodPool(Selector Sel) { 8173 // Get the selector generation and update it to the current generation. 8174 unsigned &Generation = SelectorGeneration[Sel]; 8175 unsigned PriorGeneration = Generation; 8176 Generation = getGeneration(); 8177 SelectorOutOfDate[Sel] = false; 8178 8179 // Search for methods defined with this selector. 8180 ++NumMethodPoolLookups; 8181 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration); 8182 ModuleMgr.visit(Visitor); 8183 8184 if (Visitor.getInstanceMethods().empty() && 8185 Visitor.getFactoryMethods().empty()) 8186 return; 8187 8188 ++NumMethodPoolHits; 8189 8190 if (!getSema()) 8191 return; 8192 8193 Sema &S = *getSema(); 8194 Sema::GlobalMethodPool::iterator Pos 8195 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first; 8196 8197 Pos->second.first.setBits(Visitor.getInstanceBits()); 8198 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl()); 8199 Pos->second.second.setBits(Visitor.getFactoryBits()); 8200 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl()); 8201 8202 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since 8203 // when building a module we keep every method individually and may need to 8204 // update hasMoreThanOneDecl as we add the methods. 8205 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first); 8206 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second); 8207 } 8208 8209 void ASTReader::updateOutOfDateSelector(Selector Sel) { 8210 if (SelectorOutOfDate[Sel]) 8211 ReadMethodPool(Sel); 8212 } 8213 8214 void ASTReader::ReadKnownNamespaces( 8215 SmallVectorImpl<NamespaceDecl *> &Namespaces) { 8216 Namespaces.clear(); 8217 8218 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) { 8219 if (NamespaceDecl *Namespace 8220 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I]))) 8221 Namespaces.push_back(Namespace); 8222 } 8223 } 8224 8225 void ASTReader::ReadUndefinedButUsed( 8226 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) { 8227 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) { 8228 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++])); 8229 SourceLocation Loc = 8230 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]); 8231 Undefined.insert(std::make_pair(D, Loc)); 8232 } 8233 } 8234 8235 void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector< 8236 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> & 8237 Exprs) { 8238 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) { 8239 FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++])); 8240 uint64_t Count = DelayedDeleteExprs[Idx++]; 8241 for (uint64_t C = 0; C < Count; ++C) { 8242 SourceLocation DeleteLoc = 8243 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]); 8244 const bool IsArrayForm = DelayedDeleteExprs[Idx++]; 8245 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm)); 8246 } 8247 } 8248 } 8249 8250 void ASTReader::ReadTentativeDefinitions( 8251 SmallVectorImpl<VarDecl *> &TentativeDefs) { 8252 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) { 8253 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I])); 8254 if (Var) 8255 TentativeDefs.push_back(Var); 8256 } 8257 TentativeDefinitions.clear(); 8258 } 8259 8260 void ASTReader::ReadUnusedFileScopedDecls( 8261 SmallVectorImpl<const DeclaratorDecl *> &Decls) { 8262 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) { 8263 DeclaratorDecl *D 8264 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I])); 8265 if (D) 8266 Decls.push_back(D); 8267 } 8268 UnusedFileScopedDecls.clear(); 8269 } 8270 8271 void ASTReader::ReadDelegatingConstructors( 8272 SmallVectorImpl<CXXConstructorDecl *> &Decls) { 8273 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) { 8274 CXXConstructorDecl *D 8275 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I])); 8276 if (D) 8277 Decls.push_back(D); 8278 } 8279 DelegatingCtorDecls.clear(); 8280 } 8281 8282 void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) { 8283 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) { 8284 TypedefNameDecl *D 8285 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I])); 8286 if (D) 8287 Decls.push_back(D); 8288 } 8289 ExtVectorDecls.clear(); 8290 } 8291 8292 void ASTReader::ReadUnusedLocalTypedefNameCandidates( 8293 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) { 8294 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N; 8295 ++I) { 8296 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>( 8297 GetDecl(UnusedLocalTypedefNameCandidates[I])); 8298 if (D) 8299 Decls.insert(D); 8300 } 8301 UnusedLocalTypedefNameCandidates.clear(); 8302 } 8303 8304 void ASTReader::ReadDeclsToCheckForDeferredDiags( 8305 llvm::SmallVector<Decl *, 4> &Decls) { 8306 for (unsigned I = 0, N = DeclsToCheckForDeferredDiags.size(); I != N; 8307 ++I) { 8308 auto *D = dyn_cast_or_null<Decl>( 8309 GetDecl(DeclsToCheckForDeferredDiags[I])); 8310 if (D) 8311 Decls.push_back(D); 8312 } 8313 DeclsToCheckForDeferredDiags.clear(); 8314 } 8315 8316 8317 void ASTReader::ReadReferencedSelectors( 8318 SmallVectorImpl<std::pair<Selector, SourceLocation>> &Sels) { 8319 if (ReferencedSelectorsData.empty()) 8320 return; 8321 8322 // If there are @selector references added them to its pool. This is for 8323 // implementation of -Wselector. 8324 unsigned int DataSize = ReferencedSelectorsData.size()-1; 8325 unsigned I = 0; 8326 while (I < DataSize) { 8327 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]); 8328 SourceLocation SelLoc 8329 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]); 8330 Sels.push_back(std::make_pair(Sel, SelLoc)); 8331 } 8332 ReferencedSelectorsData.clear(); 8333 } 8334 8335 void ASTReader::ReadWeakUndeclaredIdentifiers( 8336 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo>> &WeakIDs) { 8337 if (WeakUndeclaredIdentifiers.empty()) 8338 return; 8339 8340 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) { 8341 IdentifierInfo *WeakId 8342 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]); 8343 IdentifierInfo *AliasId 8344 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]); 8345 SourceLocation Loc 8346 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]); 8347 bool Used = WeakUndeclaredIdentifiers[I++]; 8348 WeakInfo WI(AliasId, Loc); 8349 WI.setUsed(Used); 8350 WeakIDs.push_back(std::make_pair(WeakId, WI)); 8351 } 8352 WeakUndeclaredIdentifiers.clear(); 8353 } 8354 8355 void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) { 8356 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) { 8357 ExternalVTableUse VT; 8358 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++])); 8359 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]); 8360 VT.DefinitionRequired = VTableUses[Idx++]; 8361 VTables.push_back(VT); 8362 } 8363 8364 VTableUses.clear(); 8365 } 8366 8367 void ASTReader::ReadPendingInstantiations( 8368 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation>> &Pending) { 8369 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) { 8370 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++])); 8371 SourceLocation Loc 8372 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]); 8373 8374 Pending.push_back(std::make_pair(D, Loc)); 8375 } 8376 PendingInstantiations.clear(); 8377 } 8378 8379 void ASTReader::ReadLateParsedTemplates( 8380 llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>> 8381 &LPTMap) { 8382 for (auto &LPT : LateParsedTemplates) { 8383 ModuleFile *FMod = LPT.first; 8384 RecordDataImpl &LateParsed = LPT.second; 8385 for (unsigned Idx = 0, N = LateParsed.size(); Idx < N; 8386 /* In loop */) { 8387 FunctionDecl *FD = 8388 cast<FunctionDecl>(GetLocalDecl(*FMod, LateParsed[Idx++])); 8389 8390 auto LT = std::make_unique<LateParsedTemplate>(); 8391 LT->D = GetLocalDecl(*FMod, LateParsed[Idx++]); 8392 8393 ModuleFile *F = getOwningModuleFile(LT->D); 8394 assert(F && "No module"); 8395 8396 unsigned TokN = LateParsed[Idx++]; 8397 LT->Toks.reserve(TokN); 8398 for (unsigned T = 0; T < TokN; ++T) 8399 LT->Toks.push_back(ReadToken(*F, LateParsed, Idx)); 8400 8401 LPTMap.insert(std::make_pair(FD, std::move(LT))); 8402 } 8403 } 8404 } 8405 8406 void ASTReader::LoadSelector(Selector Sel) { 8407 // It would be complicated to avoid reading the methods anyway. So don't. 8408 ReadMethodPool(Sel); 8409 } 8410 8411 void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) { 8412 assert(ID && "Non-zero identifier ID required"); 8413 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range"); 8414 IdentifiersLoaded[ID - 1] = II; 8415 if (DeserializationListener) 8416 DeserializationListener->IdentifierRead(ID, II); 8417 } 8418 8419 /// Set the globally-visible declarations associated with the given 8420 /// identifier. 8421 /// 8422 /// If the AST reader is currently in a state where the given declaration IDs 8423 /// cannot safely be resolved, they are queued until it is safe to resolve 8424 /// them. 8425 /// 8426 /// \param II an IdentifierInfo that refers to one or more globally-visible 8427 /// declarations. 8428 /// 8429 /// \param DeclIDs the set of declaration IDs with the name @p II that are 8430 /// visible at global scope. 8431 /// 8432 /// \param Decls if non-null, this vector will be populated with the set of 8433 /// deserialized declarations. These declarations will not be pushed into 8434 /// scope. 8435 void 8436 ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II, 8437 const SmallVectorImpl<uint32_t> &DeclIDs, 8438 SmallVectorImpl<Decl *> *Decls) { 8439 if (NumCurrentElementsDeserializing && !Decls) { 8440 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end()); 8441 return; 8442 } 8443 8444 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) { 8445 if (!SemaObj) { 8446 // Queue this declaration so that it will be added to the 8447 // translation unit scope and identifier's declaration chain 8448 // once a Sema object is known. 8449 PreloadedDeclIDs.push_back(DeclIDs[I]); 8450 continue; 8451 } 8452 8453 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I])); 8454 8455 // If we're simply supposed to record the declarations, do so now. 8456 if (Decls) { 8457 Decls->push_back(D); 8458 continue; 8459 } 8460 8461 // Introduce this declaration into the translation-unit scope 8462 // and add it to the declaration chain for this identifier, so 8463 // that (unqualified) name lookup will find it. 8464 pushExternalDeclIntoScope(D, II); 8465 } 8466 } 8467 8468 IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) { 8469 if (ID == 0) 8470 return nullptr; 8471 8472 if (IdentifiersLoaded.empty()) { 8473 Error("no identifier table in AST file"); 8474 return nullptr; 8475 } 8476 8477 ID -= 1; 8478 if (!IdentifiersLoaded[ID]) { 8479 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1); 8480 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map"); 8481 ModuleFile *M = I->second; 8482 unsigned Index = ID - M->BaseIdentifierID; 8483 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index]; 8484 8485 // All of the strings in the AST file are preceded by a 16-bit length. 8486 // Extract that 16-bit length to avoid having to execute strlen(). 8487 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as 8488 // unsigned integers. This is important to avoid integer overflow when 8489 // we cast them to 'unsigned'. 8490 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2; 8491 unsigned StrLen = (((unsigned) StrLenPtr[0]) 8492 | (((unsigned) StrLenPtr[1]) << 8)) - 1; 8493 auto &II = PP.getIdentifierTable().get(StringRef(Str, StrLen)); 8494 IdentifiersLoaded[ID] = &II; 8495 markIdentifierFromAST(*this, II); 8496 if (DeserializationListener) 8497 DeserializationListener->IdentifierRead(ID + 1, &II); 8498 } 8499 8500 return IdentifiersLoaded[ID]; 8501 } 8502 8503 IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) { 8504 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID)); 8505 } 8506 8507 IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) { 8508 if (LocalID < NUM_PREDEF_IDENT_IDS) 8509 return LocalID; 8510 8511 if (!M.ModuleOffsetMap.empty()) 8512 ReadModuleOffsetMap(M); 8513 8514 ContinuousRangeMap<uint32_t, int, 2>::iterator I 8515 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS); 8516 assert(I != M.IdentifierRemap.end() 8517 && "Invalid index into identifier index remap"); 8518 8519 return LocalID + I->second; 8520 } 8521 8522 MacroInfo *ASTReader::getMacro(MacroID ID) { 8523 if (ID == 0) 8524 return nullptr; 8525 8526 if (MacrosLoaded.empty()) { 8527 Error("no macro table in AST file"); 8528 return nullptr; 8529 } 8530 8531 ID -= NUM_PREDEF_MACRO_IDS; 8532 if (!MacrosLoaded[ID]) { 8533 GlobalMacroMapType::iterator I 8534 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS); 8535 assert(I != GlobalMacroMap.end() && "Corrupted global macro map"); 8536 ModuleFile *M = I->second; 8537 unsigned Index = ID - M->BaseMacroID; 8538 MacrosLoaded[ID] = 8539 ReadMacroRecord(*M, M->MacroOffsetsBase + M->MacroOffsets[Index]); 8540 8541 if (DeserializationListener) 8542 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS, 8543 MacrosLoaded[ID]); 8544 } 8545 8546 return MacrosLoaded[ID]; 8547 } 8548 8549 MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) { 8550 if (LocalID < NUM_PREDEF_MACRO_IDS) 8551 return LocalID; 8552 8553 if (!M.ModuleOffsetMap.empty()) 8554 ReadModuleOffsetMap(M); 8555 8556 ContinuousRangeMap<uint32_t, int, 2>::iterator I 8557 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS); 8558 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap"); 8559 8560 return LocalID + I->second; 8561 } 8562 8563 serialization::SubmoduleID 8564 ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) { 8565 if (LocalID < NUM_PREDEF_SUBMODULE_IDS) 8566 return LocalID; 8567 8568 if (!M.ModuleOffsetMap.empty()) 8569 ReadModuleOffsetMap(M); 8570 8571 ContinuousRangeMap<uint32_t, int, 2>::iterator I 8572 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS); 8573 assert(I != M.SubmoduleRemap.end() 8574 && "Invalid index into submodule index remap"); 8575 8576 return LocalID + I->second; 8577 } 8578 8579 Module *ASTReader::getSubmodule(SubmoduleID GlobalID) { 8580 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) { 8581 assert(GlobalID == 0 && "Unhandled global submodule ID"); 8582 return nullptr; 8583 } 8584 8585 if (GlobalID > SubmodulesLoaded.size()) { 8586 Error("submodule ID out of range in AST file"); 8587 return nullptr; 8588 } 8589 8590 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS]; 8591 } 8592 8593 Module *ASTReader::getModule(unsigned ID) { 8594 return getSubmodule(ID); 8595 } 8596 8597 ModuleFile *ASTReader::getLocalModuleFile(ModuleFile &F, unsigned ID) { 8598 if (ID & 1) { 8599 // It's a module, look it up by submodule ID. 8600 auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(F, ID >> 1)); 8601 return I == GlobalSubmoduleMap.end() ? nullptr : I->second; 8602 } else { 8603 // It's a prefix (preamble, PCH, ...). Look it up by index. 8604 unsigned IndexFromEnd = ID >> 1; 8605 assert(IndexFromEnd && "got reference to unknown module file"); 8606 return getModuleManager().pch_modules().end()[-IndexFromEnd]; 8607 } 8608 } 8609 8610 unsigned ASTReader::getModuleFileID(ModuleFile *F) { 8611 if (!F) 8612 return 1; 8613 8614 // For a file representing a module, use the submodule ID of the top-level 8615 // module as the file ID. For any other kind of file, the number of such 8616 // files loaded beforehand will be the same on reload. 8617 // FIXME: Is this true even if we have an explicit module file and a PCH? 8618 if (F->isModule()) 8619 return ((F->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1; 8620 8621 auto PCHModules = getModuleManager().pch_modules(); 8622 auto I = llvm::find(PCHModules, F); 8623 assert(I != PCHModules.end() && "emitting reference to unknown file"); 8624 return (I - PCHModules.end()) << 1; 8625 } 8626 8627 llvm::Optional<ASTSourceDescriptor> 8628 ASTReader::getSourceDescriptor(unsigned ID) { 8629 if (Module *M = getSubmodule(ID)) 8630 return ASTSourceDescriptor(*M); 8631 8632 // If there is only a single PCH, return it instead. 8633 // Chained PCH are not supported. 8634 const auto &PCHChain = ModuleMgr.pch_modules(); 8635 if (std::distance(std::begin(PCHChain), std::end(PCHChain))) { 8636 ModuleFile &MF = ModuleMgr.getPrimaryModule(); 8637 StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName); 8638 StringRef FileName = llvm::sys::path::filename(MF.FileName); 8639 return ASTSourceDescriptor(ModuleName, MF.OriginalDir, FileName, 8640 MF.Signature); 8641 } 8642 return None; 8643 } 8644 8645 ExternalASTSource::ExtKind ASTReader::hasExternalDefinitions(const Decl *FD) { 8646 auto I = DefinitionSource.find(FD); 8647 if (I == DefinitionSource.end()) 8648 return EK_ReplyHazy; 8649 return I->second ? EK_Never : EK_Always; 8650 } 8651 8652 Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) { 8653 return DecodeSelector(getGlobalSelectorID(M, LocalID)); 8654 } 8655 8656 Selector ASTReader::DecodeSelector(serialization::SelectorID ID) { 8657 if (ID == 0) 8658 return Selector(); 8659 8660 if (ID > SelectorsLoaded.size()) { 8661 Error("selector ID out of range in AST file"); 8662 return Selector(); 8663 } 8664 8665 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) { 8666 // Load this selector from the selector table. 8667 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID); 8668 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map"); 8669 ModuleFile &M = *I->second; 8670 ASTSelectorLookupTrait Trait(*this, M); 8671 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS; 8672 SelectorsLoaded[ID - 1] = 8673 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0); 8674 if (DeserializationListener) 8675 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]); 8676 } 8677 8678 return SelectorsLoaded[ID - 1]; 8679 } 8680 8681 Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) { 8682 return DecodeSelector(ID); 8683 } 8684 8685 uint32_t ASTReader::GetNumExternalSelectors() { 8686 // ID 0 (the null selector) is considered an external selector. 8687 return getTotalNumSelectors() + 1; 8688 } 8689 8690 serialization::SelectorID 8691 ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const { 8692 if (LocalID < NUM_PREDEF_SELECTOR_IDS) 8693 return LocalID; 8694 8695 if (!M.ModuleOffsetMap.empty()) 8696 ReadModuleOffsetMap(M); 8697 8698 ContinuousRangeMap<uint32_t, int, 2>::iterator I 8699 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS); 8700 assert(I != M.SelectorRemap.end() 8701 && "Invalid index into selector index remap"); 8702 8703 return LocalID + I->second; 8704 } 8705 8706 DeclarationNameLoc 8707 ASTRecordReader::readDeclarationNameLoc(DeclarationName Name) { 8708 DeclarationNameLoc DNLoc; 8709 switch (Name.getNameKind()) { 8710 case DeclarationName::CXXConstructorName: 8711 case DeclarationName::CXXDestructorName: 8712 case DeclarationName::CXXConversionFunctionName: 8713 DNLoc.NamedType.TInfo = readTypeSourceInfo(); 8714 break; 8715 8716 case DeclarationName::CXXOperatorName: 8717 DNLoc.CXXOperatorName.BeginOpNameLoc 8718 = readSourceLocation().getRawEncoding(); 8719 DNLoc.CXXOperatorName.EndOpNameLoc 8720 = readSourceLocation().getRawEncoding(); 8721 break; 8722 8723 case DeclarationName::CXXLiteralOperatorName: 8724 DNLoc.CXXLiteralOperatorName.OpNameLoc 8725 = readSourceLocation().getRawEncoding(); 8726 break; 8727 8728 case DeclarationName::Identifier: 8729 case DeclarationName::ObjCZeroArgSelector: 8730 case DeclarationName::ObjCOneArgSelector: 8731 case DeclarationName::ObjCMultiArgSelector: 8732 case DeclarationName::CXXUsingDirective: 8733 case DeclarationName::CXXDeductionGuideName: 8734 break; 8735 } 8736 return DNLoc; 8737 } 8738 8739 DeclarationNameInfo ASTRecordReader::readDeclarationNameInfo() { 8740 DeclarationNameInfo NameInfo; 8741 NameInfo.setName(readDeclarationName()); 8742 NameInfo.setLoc(readSourceLocation()); 8743 NameInfo.setInfo(readDeclarationNameLoc(NameInfo.getName())); 8744 return NameInfo; 8745 } 8746 8747 void ASTRecordReader::readQualifierInfo(QualifierInfo &Info) { 8748 Info.QualifierLoc = readNestedNameSpecifierLoc(); 8749 unsigned NumTPLists = readInt(); 8750 Info.NumTemplParamLists = NumTPLists; 8751 if (NumTPLists) { 8752 Info.TemplParamLists = 8753 new (getContext()) TemplateParameterList *[NumTPLists]; 8754 for (unsigned i = 0; i != NumTPLists; ++i) 8755 Info.TemplParamLists[i] = readTemplateParameterList(); 8756 } 8757 } 8758 8759 TemplateParameterList * 8760 ASTRecordReader::readTemplateParameterList() { 8761 SourceLocation TemplateLoc = readSourceLocation(); 8762 SourceLocation LAngleLoc = readSourceLocation(); 8763 SourceLocation RAngleLoc = readSourceLocation(); 8764 8765 unsigned NumParams = readInt(); 8766 SmallVector<NamedDecl *, 16> Params; 8767 Params.reserve(NumParams); 8768 while (NumParams--) 8769 Params.push_back(readDeclAs<NamedDecl>()); 8770 8771 bool HasRequiresClause = readBool(); 8772 Expr *RequiresClause = HasRequiresClause ? readExpr() : nullptr; 8773 8774 TemplateParameterList *TemplateParams = TemplateParameterList::Create( 8775 getContext(), TemplateLoc, LAngleLoc, Params, RAngleLoc, RequiresClause); 8776 return TemplateParams; 8777 } 8778 8779 void ASTRecordReader::readTemplateArgumentList( 8780 SmallVectorImpl<TemplateArgument> &TemplArgs, 8781 bool Canonicalize) { 8782 unsigned NumTemplateArgs = readInt(); 8783 TemplArgs.reserve(NumTemplateArgs); 8784 while (NumTemplateArgs--) 8785 TemplArgs.push_back(readTemplateArgument(Canonicalize)); 8786 } 8787 8788 /// Read a UnresolvedSet structure. 8789 void ASTRecordReader::readUnresolvedSet(LazyASTUnresolvedSet &Set) { 8790 unsigned NumDecls = readInt(); 8791 Set.reserve(getContext(), NumDecls); 8792 while (NumDecls--) { 8793 DeclID ID = readDeclID(); 8794 AccessSpecifier AS = (AccessSpecifier) readInt(); 8795 Set.addLazyDecl(getContext(), ID, AS); 8796 } 8797 } 8798 8799 CXXBaseSpecifier 8800 ASTRecordReader::readCXXBaseSpecifier() { 8801 bool isVirtual = readBool(); 8802 bool isBaseOfClass = readBool(); 8803 AccessSpecifier AS = static_cast<AccessSpecifier>(readInt()); 8804 bool inheritConstructors = readBool(); 8805 TypeSourceInfo *TInfo = readTypeSourceInfo(); 8806 SourceRange Range = readSourceRange(); 8807 SourceLocation EllipsisLoc = readSourceLocation(); 8808 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo, 8809 EllipsisLoc); 8810 Result.setInheritConstructors(inheritConstructors); 8811 return Result; 8812 } 8813 8814 CXXCtorInitializer ** 8815 ASTRecordReader::readCXXCtorInitializers() { 8816 ASTContext &Context = getContext(); 8817 unsigned NumInitializers = readInt(); 8818 assert(NumInitializers && "wrote ctor initializers but have no inits"); 8819 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers]; 8820 for (unsigned i = 0; i != NumInitializers; ++i) { 8821 TypeSourceInfo *TInfo = nullptr; 8822 bool IsBaseVirtual = false; 8823 FieldDecl *Member = nullptr; 8824 IndirectFieldDecl *IndirectMember = nullptr; 8825 8826 CtorInitializerType Type = (CtorInitializerType) readInt(); 8827 switch (Type) { 8828 case CTOR_INITIALIZER_BASE: 8829 TInfo = readTypeSourceInfo(); 8830 IsBaseVirtual = readBool(); 8831 break; 8832 8833 case CTOR_INITIALIZER_DELEGATING: 8834 TInfo = readTypeSourceInfo(); 8835 break; 8836 8837 case CTOR_INITIALIZER_MEMBER: 8838 Member = readDeclAs<FieldDecl>(); 8839 break; 8840 8841 case CTOR_INITIALIZER_INDIRECT_MEMBER: 8842 IndirectMember = readDeclAs<IndirectFieldDecl>(); 8843 break; 8844 } 8845 8846 SourceLocation MemberOrEllipsisLoc = readSourceLocation(); 8847 Expr *Init = readExpr(); 8848 SourceLocation LParenLoc = readSourceLocation(); 8849 SourceLocation RParenLoc = readSourceLocation(); 8850 8851 CXXCtorInitializer *BOMInit; 8852 if (Type == CTOR_INITIALIZER_BASE) 8853 BOMInit = new (Context) 8854 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init, 8855 RParenLoc, MemberOrEllipsisLoc); 8856 else if (Type == CTOR_INITIALIZER_DELEGATING) 8857 BOMInit = new (Context) 8858 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc); 8859 else if (Member) 8860 BOMInit = new (Context) 8861 CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc, LParenLoc, 8862 Init, RParenLoc); 8863 else 8864 BOMInit = new (Context) 8865 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc, 8866 LParenLoc, Init, RParenLoc); 8867 8868 if (/*IsWritten*/readBool()) { 8869 unsigned SourceOrder = readInt(); 8870 BOMInit->setSourceOrder(SourceOrder); 8871 } 8872 8873 CtorInitializers[i] = BOMInit; 8874 } 8875 8876 return CtorInitializers; 8877 } 8878 8879 NestedNameSpecifierLoc 8880 ASTRecordReader::readNestedNameSpecifierLoc() { 8881 ASTContext &Context = getContext(); 8882 unsigned N = readInt(); 8883 NestedNameSpecifierLocBuilder Builder; 8884 for (unsigned I = 0; I != N; ++I) { 8885 auto Kind = readNestedNameSpecifierKind(); 8886 switch (Kind) { 8887 case NestedNameSpecifier::Identifier: { 8888 IdentifierInfo *II = readIdentifier(); 8889 SourceRange Range = readSourceRange(); 8890 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd()); 8891 break; 8892 } 8893 8894 case NestedNameSpecifier::Namespace: { 8895 NamespaceDecl *NS = readDeclAs<NamespaceDecl>(); 8896 SourceRange Range = readSourceRange(); 8897 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd()); 8898 break; 8899 } 8900 8901 case NestedNameSpecifier::NamespaceAlias: { 8902 NamespaceAliasDecl *Alias = readDeclAs<NamespaceAliasDecl>(); 8903 SourceRange Range = readSourceRange(); 8904 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd()); 8905 break; 8906 } 8907 8908 case NestedNameSpecifier::TypeSpec: 8909 case NestedNameSpecifier::TypeSpecWithTemplate: { 8910 bool Template = readBool(); 8911 TypeSourceInfo *T = readTypeSourceInfo(); 8912 if (!T) 8913 return NestedNameSpecifierLoc(); 8914 SourceLocation ColonColonLoc = readSourceLocation(); 8915 8916 // FIXME: 'template' keyword location not saved anywhere, so we fake it. 8917 Builder.Extend(Context, 8918 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(), 8919 T->getTypeLoc(), ColonColonLoc); 8920 break; 8921 } 8922 8923 case NestedNameSpecifier::Global: { 8924 SourceLocation ColonColonLoc = readSourceLocation(); 8925 Builder.MakeGlobal(Context, ColonColonLoc); 8926 break; 8927 } 8928 8929 case NestedNameSpecifier::Super: { 8930 CXXRecordDecl *RD = readDeclAs<CXXRecordDecl>(); 8931 SourceRange Range = readSourceRange(); 8932 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd()); 8933 break; 8934 } 8935 } 8936 } 8937 8938 return Builder.getWithLocInContext(Context); 8939 } 8940 8941 SourceRange 8942 ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record, 8943 unsigned &Idx) { 8944 SourceLocation beg = ReadSourceLocation(F, Record, Idx); 8945 SourceLocation end = ReadSourceLocation(F, Record, Idx); 8946 return SourceRange(beg, end); 8947 } 8948 8949 /// Read a floating-point value 8950 llvm::APFloat ASTRecordReader::readAPFloat(const llvm::fltSemantics &Sem) { 8951 return llvm::APFloat(Sem, readAPInt()); 8952 } 8953 8954 // Read a string 8955 std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) { 8956 unsigned Len = Record[Idx++]; 8957 std::string Result(Record.data() + Idx, Record.data() + Idx + Len); 8958 Idx += Len; 8959 return Result; 8960 } 8961 8962 std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record, 8963 unsigned &Idx) { 8964 std::string Filename = ReadString(Record, Idx); 8965 ResolveImportedPath(F, Filename); 8966 return Filename; 8967 } 8968 8969 std::string ASTReader::ReadPath(StringRef BaseDirectory, 8970 const RecordData &Record, unsigned &Idx) { 8971 std::string Filename = ReadString(Record, Idx); 8972 if (!BaseDirectory.empty()) 8973 ResolveImportedPath(Filename, BaseDirectory); 8974 return Filename; 8975 } 8976 8977 VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record, 8978 unsigned &Idx) { 8979 unsigned Major = Record[Idx++]; 8980 unsigned Minor = Record[Idx++]; 8981 unsigned Subminor = Record[Idx++]; 8982 if (Minor == 0) 8983 return VersionTuple(Major); 8984 if (Subminor == 0) 8985 return VersionTuple(Major, Minor - 1); 8986 return VersionTuple(Major, Minor - 1, Subminor - 1); 8987 } 8988 8989 CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F, 8990 const RecordData &Record, 8991 unsigned &Idx) { 8992 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx); 8993 return CXXTemporary::Create(getContext(), Decl); 8994 } 8995 8996 DiagnosticBuilder ASTReader::Diag(unsigned DiagID) const { 8997 return Diag(CurrentImportLoc, DiagID); 8998 } 8999 9000 DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) const { 9001 return Diags.Report(Loc, DiagID); 9002 } 9003 9004 /// Retrieve the identifier table associated with the 9005 /// preprocessor. 9006 IdentifierTable &ASTReader::getIdentifierTable() { 9007 return PP.getIdentifierTable(); 9008 } 9009 9010 /// Record that the given ID maps to the given switch-case 9011 /// statement. 9012 void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) { 9013 assert((*CurrSwitchCaseStmts)[ID] == nullptr && 9014 "Already have a SwitchCase with this ID"); 9015 (*CurrSwitchCaseStmts)[ID] = SC; 9016 } 9017 9018 /// Retrieve the switch-case statement with the given ID. 9019 SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) { 9020 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID"); 9021 return (*CurrSwitchCaseStmts)[ID]; 9022 } 9023 9024 void ASTReader::ClearSwitchCaseIDs() { 9025 CurrSwitchCaseStmts->clear(); 9026 } 9027 9028 void ASTReader::ReadComments() { 9029 ASTContext &Context = getContext(); 9030 std::vector<RawComment *> Comments; 9031 for (SmallVectorImpl<std::pair<BitstreamCursor, 9032 serialization::ModuleFile *>>::iterator 9033 I = CommentsCursors.begin(), 9034 E = CommentsCursors.end(); 9035 I != E; ++I) { 9036 Comments.clear(); 9037 BitstreamCursor &Cursor = I->first; 9038 serialization::ModuleFile &F = *I->second; 9039 SavedStreamPosition SavedPosition(Cursor); 9040 9041 RecordData Record; 9042 while (true) { 9043 Expected<llvm::BitstreamEntry> MaybeEntry = 9044 Cursor.advanceSkippingSubblocks( 9045 BitstreamCursor::AF_DontPopBlockAtEnd); 9046 if (!MaybeEntry) { 9047 Error(MaybeEntry.takeError()); 9048 return; 9049 } 9050 llvm::BitstreamEntry Entry = MaybeEntry.get(); 9051 9052 switch (Entry.Kind) { 9053 case llvm::BitstreamEntry::SubBlock: // Handled for us already. 9054 case llvm::BitstreamEntry::Error: 9055 Error("malformed block record in AST file"); 9056 return; 9057 case llvm::BitstreamEntry::EndBlock: 9058 goto NextCursor; 9059 case llvm::BitstreamEntry::Record: 9060 // The interesting case. 9061 break; 9062 } 9063 9064 // Read a record. 9065 Record.clear(); 9066 Expected<unsigned> MaybeComment = Cursor.readRecord(Entry.ID, Record); 9067 if (!MaybeComment) { 9068 Error(MaybeComment.takeError()); 9069 return; 9070 } 9071 switch ((CommentRecordTypes)MaybeComment.get()) { 9072 case COMMENTS_RAW_COMMENT: { 9073 unsigned Idx = 0; 9074 SourceRange SR = ReadSourceRange(F, Record, Idx); 9075 RawComment::CommentKind Kind = 9076 (RawComment::CommentKind) Record[Idx++]; 9077 bool IsTrailingComment = Record[Idx++]; 9078 bool IsAlmostTrailingComment = Record[Idx++]; 9079 Comments.push_back(new (Context) RawComment( 9080 SR, Kind, IsTrailingComment, IsAlmostTrailingComment)); 9081 break; 9082 } 9083 } 9084 } 9085 NextCursor: 9086 llvm::DenseMap<FileID, std::map<unsigned, RawComment *>> 9087 FileToOffsetToComment; 9088 for (RawComment *C : Comments) { 9089 SourceLocation CommentLoc = C->getBeginLoc(); 9090 if (CommentLoc.isValid()) { 9091 std::pair<FileID, unsigned> Loc = 9092 SourceMgr.getDecomposedLoc(CommentLoc); 9093 if (Loc.first.isValid()) 9094 Context.Comments.OrderedComments[Loc.first].emplace(Loc.second, C); 9095 } 9096 } 9097 } 9098 } 9099 9100 void ASTReader::visitInputFiles(serialization::ModuleFile &MF, 9101 bool IncludeSystem, bool Complain, 9102 llvm::function_ref<void(const serialization::InputFile &IF, 9103 bool isSystem)> Visitor) { 9104 unsigned NumUserInputs = MF.NumUserInputFiles; 9105 unsigned NumInputs = MF.InputFilesLoaded.size(); 9106 assert(NumUserInputs <= NumInputs); 9107 unsigned N = IncludeSystem ? NumInputs : NumUserInputs; 9108 for (unsigned I = 0; I < N; ++I) { 9109 bool IsSystem = I >= NumUserInputs; 9110 InputFile IF = getInputFile(MF, I+1, Complain); 9111 Visitor(IF, IsSystem); 9112 } 9113 } 9114 9115 void ASTReader::visitTopLevelModuleMaps( 9116 serialization::ModuleFile &MF, 9117 llvm::function_ref<void(const FileEntry *FE)> Visitor) { 9118 unsigned NumInputs = MF.InputFilesLoaded.size(); 9119 for (unsigned I = 0; I < NumInputs; ++I) { 9120 InputFileInfo IFI = readInputFileInfo(MF, I + 1); 9121 if (IFI.TopLevelModuleMap) 9122 // FIXME: This unnecessarily re-reads the InputFileInfo. 9123 if (auto FE = getInputFile(MF, I + 1).getFile()) 9124 Visitor(FE); 9125 } 9126 } 9127 9128 std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) { 9129 // If we know the owning module, use it. 9130 if (Module *M = D->getImportedOwningModule()) 9131 return M->getFullModuleName(); 9132 9133 // Otherwise, use the name of the top-level module the decl is within. 9134 if (ModuleFile *M = getOwningModuleFile(D)) 9135 return M->ModuleName; 9136 9137 // Not from a module. 9138 return {}; 9139 } 9140 9141 void ASTReader::finishPendingActions() { 9142 while (!PendingIdentifierInfos.empty() || !PendingFunctionTypes.empty() || 9143 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() || 9144 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() || 9145 !PendingUpdateRecords.empty()) { 9146 // If any identifiers with corresponding top-level declarations have 9147 // been loaded, load those declarations now. 9148 using TopLevelDeclsMap = 9149 llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2>>; 9150 TopLevelDeclsMap TopLevelDecls; 9151 9152 while (!PendingIdentifierInfos.empty()) { 9153 IdentifierInfo *II = PendingIdentifierInfos.back().first; 9154 SmallVector<uint32_t, 4> DeclIDs = 9155 std::move(PendingIdentifierInfos.back().second); 9156 PendingIdentifierInfos.pop_back(); 9157 9158 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]); 9159 } 9160 9161 // Load each function type that we deferred loading because it was a 9162 // deduced type that might refer to a local type declared within itself. 9163 for (unsigned I = 0; I != PendingFunctionTypes.size(); ++I) { 9164 auto *FD = PendingFunctionTypes[I].first; 9165 FD->setType(GetType(PendingFunctionTypes[I].second)); 9166 9167 // If we gave a function a deduced return type, remember that we need to 9168 // propagate that along the redeclaration chain. 9169 auto *DT = FD->getReturnType()->getContainedDeducedType(); 9170 if (DT && DT->isDeduced()) 9171 PendingDeducedTypeUpdates.insert( 9172 {FD->getCanonicalDecl(), FD->getReturnType()}); 9173 } 9174 PendingFunctionTypes.clear(); 9175 9176 // For each decl chain that we wanted to complete while deserializing, mark 9177 // it as "still needs to be completed". 9178 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) { 9179 markIncompleteDeclChain(PendingIncompleteDeclChains[I]); 9180 } 9181 PendingIncompleteDeclChains.clear(); 9182 9183 // Load pending declaration chains. 9184 for (unsigned I = 0; I != PendingDeclChains.size(); ++I) 9185 loadPendingDeclChain(PendingDeclChains[I].first, 9186 PendingDeclChains[I].second); 9187 PendingDeclChains.clear(); 9188 9189 // Make the most recent of the top-level declarations visible. 9190 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(), 9191 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) { 9192 IdentifierInfo *II = TLD->first; 9193 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) { 9194 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II); 9195 } 9196 } 9197 9198 // Load any pending macro definitions. 9199 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) { 9200 IdentifierInfo *II = PendingMacroIDs.begin()[I].first; 9201 SmallVector<PendingMacroInfo, 2> GlobalIDs; 9202 GlobalIDs.swap(PendingMacroIDs.begin()[I].second); 9203 // Initialize the macro history from chained-PCHs ahead of module imports. 9204 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs; 9205 ++IDIdx) { 9206 const PendingMacroInfo &Info = GlobalIDs[IDIdx]; 9207 if (!Info.M->isModule()) 9208 resolvePendingMacro(II, Info); 9209 } 9210 // Handle module imports. 9211 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs; 9212 ++IDIdx) { 9213 const PendingMacroInfo &Info = GlobalIDs[IDIdx]; 9214 if (Info.M->isModule()) 9215 resolvePendingMacro(II, Info); 9216 } 9217 } 9218 PendingMacroIDs.clear(); 9219 9220 // Wire up the DeclContexts for Decls that we delayed setting until 9221 // recursive loading is completed. 9222 while (!PendingDeclContextInfos.empty()) { 9223 PendingDeclContextInfo Info = PendingDeclContextInfos.front(); 9224 PendingDeclContextInfos.pop_front(); 9225 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC)); 9226 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC)); 9227 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext()); 9228 } 9229 9230 // Perform any pending declaration updates. 9231 while (!PendingUpdateRecords.empty()) { 9232 auto Update = PendingUpdateRecords.pop_back_val(); 9233 ReadingKindTracker ReadingKind(Read_Decl, *this); 9234 loadDeclUpdateRecords(Update); 9235 } 9236 } 9237 9238 // At this point, all update records for loaded decls are in place, so any 9239 // fake class definitions should have become real. 9240 assert(PendingFakeDefinitionData.empty() && 9241 "faked up a class definition but never saw the real one"); 9242 9243 // If we deserialized any C++ or Objective-C class definitions, any 9244 // Objective-C protocol definitions, or any redeclarable templates, make sure 9245 // that all redeclarations point to the definitions. Note that this can only 9246 // happen now, after the redeclaration chains have been fully wired. 9247 for (Decl *D : PendingDefinitions) { 9248 if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 9249 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) { 9250 // Make sure that the TagType points at the definition. 9251 const_cast<TagType*>(TagT)->decl = TD; 9252 } 9253 9254 if (auto RD = dyn_cast<CXXRecordDecl>(D)) { 9255 for (auto *R = getMostRecentExistingDecl(RD); R; 9256 R = R->getPreviousDecl()) { 9257 assert((R == D) == 9258 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() && 9259 "declaration thinks it's the definition but it isn't"); 9260 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData; 9261 } 9262 } 9263 9264 continue; 9265 } 9266 9267 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) { 9268 // Make sure that the ObjCInterfaceType points at the definition. 9269 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl)) 9270 ->Decl = ID; 9271 9272 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl()) 9273 cast<ObjCInterfaceDecl>(R)->Data = ID->Data; 9274 9275 continue; 9276 } 9277 9278 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) { 9279 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl()) 9280 cast<ObjCProtocolDecl>(R)->Data = PD->Data; 9281 9282 continue; 9283 } 9284 9285 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl(); 9286 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl()) 9287 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common; 9288 } 9289 PendingDefinitions.clear(); 9290 9291 // Load the bodies of any functions or methods we've encountered. We do 9292 // this now (delayed) so that we can be sure that the declaration chains 9293 // have been fully wired up (hasBody relies on this). 9294 // FIXME: We shouldn't require complete redeclaration chains here. 9295 for (PendingBodiesMap::iterator PB = PendingBodies.begin(), 9296 PBEnd = PendingBodies.end(); 9297 PB != PBEnd; ++PB) { 9298 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) { 9299 // For a function defined inline within a class template, force the 9300 // canonical definition to be the one inside the canonical definition of 9301 // the template. This ensures that we instantiate from a correct view 9302 // of the template. 9303 // 9304 // Sadly we can't do this more generally: we can't be sure that all 9305 // copies of an arbitrary class definition will have the same members 9306 // defined (eg, some member functions may not be instantiated, and some 9307 // special members may or may not have been implicitly defined). 9308 if (auto *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalParent())) 9309 if (RD->isDependentContext() && !RD->isThisDeclarationADefinition()) 9310 continue; 9311 9312 // FIXME: Check for =delete/=default? 9313 // FIXME: Complain about ODR violations here? 9314 const FunctionDecl *Defn = nullptr; 9315 if (!getContext().getLangOpts().Modules || !FD->hasBody(Defn)) { 9316 FD->setLazyBody(PB->second); 9317 } else { 9318 auto *NonConstDefn = const_cast<FunctionDecl*>(Defn); 9319 mergeDefinitionVisibility(NonConstDefn, FD); 9320 9321 if (!FD->isLateTemplateParsed() && 9322 !NonConstDefn->isLateTemplateParsed() && 9323 FD->getODRHash() != NonConstDefn->getODRHash()) { 9324 if (!isa<CXXMethodDecl>(FD)) { 9325 PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn); 9326 } else if (FD->getLexicalParent()->isFileContext() && 9327 NonConstDefn->getLexicalParent()->isFileContext()) { 9328 // Only diagnose out-of-line method definitions. If they are 9329 // in class definitions, then an error will be generated when 9330 // processing the class bodies. 9331 PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn); 9332 } 9333 } 9334 } 9335 continue; 9336 } 9337 9338 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first); 9339 if (!getContext().getLangOpts().Modules || !MD->hasBody()) 9340 MD->setLazyBody(PB->second); 9341 } 9342 PendingBodies.clear(); 9343 9344 // Do some cleanup. 9345 for (auto *ND : PendingMergedDefinitionsToDeduplicate) 9346 getContext().deduplicateMergedDefinitonsFor(ND); 9347 PendingMergedDefinitionsToDeduplicate.clear(); 9348 } 9349 9350 void ASTReader::diagnoseOdrViolations() { 9351 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty() && 9352 PendingFunctionOdrMergeFailures.empty() && 9353 PendingEnumOdrMergeFailures.empty()) 9354 return; 9355 9356 // Trigger the import of the full definition of each class that had any 9357 // odr-merging problems, so we can produce better diagnostics for them. 9358 // These updates may in turn find and diagnose some ODR failures, so take 9359 // ownership of the set first. 9360 auto OdrMergeFailures = std::move(PendingOdrMergeFailures); 9361 PendingOdrMergeFailures.clear(); 9362 for (auto &Merge : OdrMergeFailures) { 9363 Merge.first->buildLookup(); 9364 Merge.first->decls_begin(); 9365 Merge.first->bases_begin(); 9366 Merge.first->vbases_begin(); 9367 for (auto &RecordPair : Merge.second) { 9368 auto *RD = RecordPair.first; 9369 RD->decls_begin(); 9370 RD->bases_begin(); 9371 RD->vbases_begin(); 9372 } 9373 } 9374 9375 // Trigger the import of functions. 9376 auto FunctionOdrMergeFailures = std::move(PendingFunctionOdrMergeFailures); 9377 PendingFunctionOdrMergeFailures.clear(); 9378 for (auto &Merge : FunctionOdrMergeFailures) { 9379 Merge.first->buildLookup(); 9380 Merge.first->decls_begin(); 9381 Merge.first->getBody(); 9382 for (auto &FD : Merge.second) { 9383 FD->buildLookup(); 9384 FD->decls_begin(); 9385 FD->getBody(); 9386 } 9387 } 9388 9389 // Trigger the import of enums. 9390 auto EnumOdrMergeFailures = std::move(PendingEnumOdrMergeFailures); 9391 PendingEnumOdrMergeFailures.clear(); 9392 for (auto &Merge : EnumOdrMergeFailures) { 9393 Merge.first->decls_begin(); 9394 for (auto &Enum : Merge.second) { 9395 Enum->decls_begin(); 9396 } 9397 } 9398 9399 // For each declaration from a merged context, check that the canonical 9400 // definition of that context also contains a declaration of the same 9401 // entity. 9402 // 9403 // Caution: this loop does things that might invalidate iterators into 9404 // PendingOdrMergeChecks. Don't turn this into a range-based for loop! 9405 while (!PendingOdrMergeChecks.empty()) { 9406 NamedDecl *D = PendingOdrMergeChecks.pop_back_val(); 9407 9408 // FIXME: Skip over implicit declarations for now. This matters for things 9409 // like implicitly-declared special member functions. This isn't entirely 9410 // correct; we can end up with multiple unmerged declarations of the same 9411 // implicit entity. 9412 if (D->isImplicit()) 9413 continue; 9414 9415 DeclContext *CanonDef = D->getDeclContext(); 9416 9417 bool Found = false; 9418 const Decl *DCanon = D->getCanonicalDecl(); 9419 9420 for (auto RI : D->redecls()) { 9421 if (RI->getLexicalDeclContext() == CanonDef) { 9422 Found = true; 9423 break; 9424 } 9425 } 9426 if (Found) 9427 continue; 9428 9429 // Quick check failed, time to do the slow thing. Note, we can't just 9430 // look up the name of D in CanonDef here, because the member that is 9431 // in CanonDef might not be found by name lookup (it might have been 9432 // replaced by a more recent declaration in the lookup table), and we 9433 // can't necessarily find it in the redeclaration chain because it might 9434 // be merely mergeable, not redeclarable. 9435 llvm::SmallVector<const NamedDecl*, 4> Candidates; 9436 for (auto *CanonMember : CanonDef->decls()) { 9437 if (CanonMember->getCanonicalDecl() == DCanon) { 9438 // This can happen if the declaration is merely mergeable and not 9439 // actually redeclarable (we looked for redeclarations earlier). 9440 // 9441 // FIXME: We should be able to detect this more efficiently, without 9442 // pulling in all of the members of CanonDef. 9443 Found = true; 9444 break; 9445 } 9446 if (auto *ND = dyn_cast<NamedDecl>(CanonMember)) 9447 if (ND->getDeclName() == D->getDeclName()) 9448 Candidates.push_back(ND); 9449 } 9450 9451 if (!Found) { 9452 // The AST doesn't like TagDecls becoming invalid after they've been 9453 // completed. We only really need to mark FieldDecls as invalid here. 9454 if (!isa<TagDecl>(D)) 9455 D->setInvalidDecl(); 9456 9457 // Ensure we don't accidentally recursively enter deserialization while 9458 // we're producing our diagnostic. 9459 Deserializing RecursionGuard(this); 9460 9461 std::string CanonDefModule = 9462 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef)); 9463 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl) 9464 << D << getOwningModuleNameForDiagnostic(D) 9465 << CanonDef << CanonDefModule.empty() << CanonDefModule; 9466 9467 if (Candidates.empty()) 9468 Diag(cast<Decl>(CanonDef)->getLocation(), 9469 diag::note_module_odr_violation_no_possible_decls) << D; 9470 else { 9471 for (unsigned I = 0, N = Candidates.size(); I != N; ++I) 9472 Diag(Candidates[I]->getLocation(), 9473 diag::note_module_odr_violation_possible_decl) 9474 << Candidates[I]; 9475 } 9476 9477 DiagnosedOdrMergeFailures.insert(CanonDef); 9478 } 9479 } 9480 9481 if (OdrMergeFailures.empty() && FunctionOdrMergeFailures.empty() && 9482 EnumOdrMergeFailures.empty()) 9483 return; 9484 9485 // Ensure we don't accidentally recursively enter deserialization while 9486 // we're producing our diagnostics. 9487 Deserializing RecursionGuard(this); 9488 9489 // Common code for hashing helpers. 9490 ODRHash Hash; 9491 auto ComputeQualTypeODRHash = [&Hash](QualType Ty) { 9492 Hash.clear(); 9493 Hash.AddQualType(Ty); 9494 return Hash.CalculateHash(); 9495 }; 9496 9497 auto ComputeODRHash = [&Hash](const Stmt *S) { 9498 assert(S); 9499 Hash.clear(); 9500 Hash.AddStmt(S); 9501 return Hash.CalculateHash(); 9502 }; 9503 9504 auto ComputeSubDeclODRHash = [&Hash](const Decl *D) { 9505 assert(D); 9506 Hash.clear(); 9507 Hash.AddSubDecl(D); 9508 return Hash.CalculateHash(); 9509 }; 9510 9511 auto ComputeTemplateArgumentODRHash = [&Hash](const TemplateArgument &TA) { 9512 Hash.clear(); 9513 Hash.AddTemplateArgument(TA); 9514 return Hash.CalculateHash(); 9515 }; 9516 9517 auto ComputeTemplateParameterListODRHash = 9518 [&Hash](const TemplateParameterList *TPL) { 9519 assert(TPL); 9520 Hash.clear(); 9521 Hash.AddTemplateParameterList(TPL); 9522 return Hash.CalculateHash(); 9523 }; 9524 9525 // Used with err_module_odr_violation_mismatch_decl and 9526 // note_module_odr_violation_mismatch_decl 9527 // This list should be the same Decl's as in ODRHash::isDeclToBeProcessed 9528 enum ODRMismatchDecl { 9529 EndOfClass, 9530 PublicSpecifer, 9531 PrivateSpecifer, 9532 ProtectedSpecifer, 9533 StaticAssert, 9534 Field, 9535 CXXMethod, 9536 TypeAlias, 9537 TypeDef, 9538 Var, 9539 Friend, 9540 FunctionTemplate, 9541 Other 9542 }; 9543 9544 // Used with err_module_odr_violation_mismatch_decl_diff and 9545 // note_module_odr_violation_mismatch_decl_diff 9546 enum ODRMismatchDeclDifference { 9547 StaticAssertCondition, 9548 StaticAssertMessage, 9549 StaticAssertOnlyMessage, 9550 FieldName, 9551 FieldTypeName, 9552 FieldSingleBitField, 9553 FieldDifferentWidthBitField, 9554 FieldSingleMutable, 9555 FieldSingleInitializer, 9556 FieldDifferentInitializers, 9557 MethodName, 9558 MethodDeleted, 9559 MethodDefaulted, 9560 MethodVirtual, 9561 MethodStatic, 9562 MethodVolatile, 9563 MethodConst, 9564 MethodInline, 9565 MethodNumberParameters, 9566 MethodParameterType, 9567 MethodParameterName, 9568 MethodParameterSingleDefaultArgument, 9569 MethodParameterDifferentDefaultArgument, 9570 MethodNoTemplateArguments, 9571 MethodDifferentNumberTemplateArguments, 9572 MethodDifferentTemplateArgument, 9573 MethodSingleBody, 9574 MethodDifferentBody, 9575 TypedefName, 9576 TypedefType, 9577 VarName, 9578 VarType, 9579 VarSingleInitializer, 9580 VarDifferentInitializer, 9581 VarConstexpr, 9582 FriendTypeFunction, 9583 FriendType, 9584 FriendFunction, 9585 FunctionTemplateDifferentNumberParameters, 9586 FunctionTemplateParameterDifferentKind, 9587 FunctionTemplateParameterName, 9588 FunctionTemplateParameterSingleDefaultArgument, 9589 FunctionTemplateParameterDifferentDefaultArgument, 9590 FunctionTemplateParameterDifferentType, 9591 FunctionTemplatePackParameter, 9592 }; 9593 9594 // These lambdas have the common portions of the ODR diagnostics. This 9595 // has the same return as Diag(), so addition parameters can be passed 9596 // in with operator<< 9597 auto ODRDiagDeclError = [this](NamedDecl *FirstRecord, StringRef FirstModule, 9598 SourceLocation Loc, SourceRange Range, 9599 ODRMismatchDeclDifference DiffType) { 9600 return Diag(Loc, diag::err_module_odr_violation_mismatch_decl_diff) 9601 << FirstRecord << FirstModule.empty() << FirstModule << Range 9602 << DiffType; 9603 }; 9604 auto ODRDiagDeclNote = [this](StringRef SecondModule, SourceLocation Loc, 9605 SourceRange Range, ODRMismatchDeclDifference DiffType) { 9606 return Diag(Loc, diag::note_module_odr_violation_mismatch_decl_diff) 9607 << SecondModule << Range << DiffType; 9608 }; 9609 9610 auto ODRDiagField = [this, &ODRDiagDeclError, &ODRDiagDeclNote, 9611 &ComputeQualTypeODRHash, &ComputeODRHash]( 9612 NamedDecl *FirstRecord, StringRef FirstModule, 9613 StringRef SecondModule, FieldDecl *FirstField, 9614 FieldDecl *SecondField) { 9615 IdentifierInfo *FirstII = FirstField->getIdentifier(); 9616 IdentifierInfo *SecondII = SecondField->getIdentifier(); 9617 if (FirstII->getName() != SecondII->getName()) { 9618 ODRDiagDeclError(FirstRecord, FirstModule, FirstField->getLocation(), 9619 FirstField->getSourceRange(), FieldName) 9620 << FirstII; 9621 ODRDiagDeclNote(SecondModule, SecondField->getLocation(), 9622 SecondField->getSourceRange(), FieldName) 9623 << SecondII; 9624 9625 return true; 9626 } 9627 9628 assert(getContext().hasSameType(FirstField->getType(), 9629 SecondField->getType())); 9630 9631 QualType FirstType = FirstField->getType(); 9632 QualType SecondType = SecondField->getType(); 9633 if (ComputeQualTypeODRHash(FirstType) != 9634 ComputeQualTypeODRHash(SecondType)) { 9635 ODRDiagDeclError(FirstRecord, FirstModule, FirstField->getLocation(), 9636 FirstField->getSourceRange(), FieldTypeName) 9637 << FirstII << FirstType; 9638 ODRDiagDeclNote(SecondModule, SecondField->getLocation(), 9639 SecondField->getSourceRange(), FieldTypeName) 9640 << SecondII << SecondType; 9641 9642 return true; 9643 } 9644 9645 const bool IsFirstBitField = FirstField->isBitField(); 9646 const bool IsSecondBitField = SecondField->isBitField(); 9647 if (IsFirstBitField != IsSecondBitField) { 9648 ODRDiagDeclError(FirstRecord, FirstModule, FirstField->getLocation(), 9649 FirstField->getSourceRange(), FieldSingleBitField) 9650 << FirstII << IsFirstBitField; 9651 ODRDiagDeclNote(SecondModule, SecondField->getLocation(), 9652 SecondField->getSourceRange(), FieldSingleBitField) 9653 << SecondII << IsSecondBitField; 9654 return true; 9655 } 9656 9657 if (IsFirstBitField && IsSecondBitField) { 9658 unsigned FirstBitWidthHash = 9659 ComputeODRHash(FirstField->getBitWidth()); 9660 unsigned SecondBitWidthHash = 9661 ComputeODRHash(SecondField->getBitWidth()); 9662 if (FirstBitWidthHash != SecondBitWidthHash) { 9663 ODRDiagDeclError(FirstRecord, FirstModule, FirstField->getLocation(), 9664 FirstField->getSourceRange(), 9665 FieldDifferentWidthBitField) 9666 << FirstII << FirstField->getBitWidth()->getSourceRange(); 9667 ODRDiagDeclNote(SecondModule, SecondField->getLocation(), 9668 SecondField->getSourceRange(), 9669 FieldDifferentWidthBitField) 9670 << SecondII << SecondField->getBitWidth()->getSourceRange(); 9671 return true; 9672 } 9673 } 9674 9675 if (!PP.getLangOpts().CPlusPlus) 9676 return false; 9677 9678 const bool IsFirstMutable = FirstField->isMutable(); 9679 const bool IsSecondMutable = SecondField->isMutable(); 9680 if (IsFirstMutable != IsSecondMutable) { 9681 ODRDiagDeclError(FirstRecord, FirstModule, FirstField->getLocation(), 9682 FirstField->getSourceRange(), FieldSingleMutable) 9683 << FirstII << IsFirstMutable; 9684 ODRDiagDeclNote(SecondModule, SecondField->getLocation(), 9685 SecondField->getSourceRange(), FieldSingleMutable) 9686 << SecondII << IsSecondMutable; 9687 return true; 9688 } 9689 9690 const Expr *FirstInitializer = FirstField->getInClassInitializer(); 9691 const Expr *SecondInitializer = SecondField->getInClassInitializer(); 9692 if ((!FirstInitializer && SecondInitializer) || 9693 (FirstInitializer && !SecondInitializer)) { 9694 ODRDiagDeclError(FirstRecord, FirstModule, FirstField->getLocation(), 9695 FirstField->getSourceRange(), FieldSingleInitializer) 9696 << FirstII << (FirstInitializer != nullptr); 9697 ODRDiagDeclNote(SecondModule, SecondField->getLocation(), 9698 SecondField->getSourceRange(), FieldSingleInitializer) 9699 << SecondII << (SecondInitializer != nullptr); 9700 return true; 9701 } 9702 9703 if (FirstInitializer && SecondInitializer) { 9704 unsigned FirstInitHash = ComputeODRHash(FirstInitializer); 9705 unsigned SecondInitHash = ComputeODRHash(SecondInitializer); 9706 if (FirstInitHash != SecondInitHash) { 9707 ODRDiagDeclError(FirstRecord, FirstModule, FirstField->getLocation(), 9708 FirstField->getSourceRange(), 9709 FieldDifferentInitializers) 9710 << FirstII << FirstInitializer->getSourceRange(); 9711 ODRDiagDeclNote(SecondModule, SecondField->getLocation(), 9712 SecondField->getSourceRange(), 9713 FieldDifferentInitializers) 9714 << SecondII << SecondInitializer->getSourceRange(); 9715 return true; 9716 } 9717 } 9718 9719 return false; 9720 }; 9721 9722 auto ODRDiagTypeDefOrAlias = 9723 [&ODRDiagDeclError, &ODRDiagDeclNote, &ComputeQualTypeODRHash]( 9724 NamedDecl *FirstRecord, StringRef FirstModule, StringRef SecondModule, 9725 TypedefNameDecl *FirstTD, TypedefNameDecl *SecondTD, 9726 bool IsTypeAlias) { 9727 auto FirstName = FirstTD->getDeclName(); 9728 auto SecondName = SecondTD->getDeclName(); 9729 if (FirstName != SecondName) { 9730 ODRDiagDeclError(FirstRecord, FirstModule, FirstTD->getLocation(), 9731 FirstTD->getSourceRange(), TypedefName) 9732 << IsTypeAlias << FirstName; 9733 ODRDiagDeclNote(SecondModule, SecondTD->getLocation(), 9734 SecondTD->getSourceRange(), TypedefName) 9735 << IsTypeAlias << SecondName; 9736 return true; 9737 } 9738 9739 QualType FirstType = FirstTD->getUnderlyingType(); 9740 QualType SecondType = SecondTD->getUnderlyingType(); 9741 if (ComputeQualTypeODRHash(FirstType) != 9742 ComputeQualTypeODRHash(SecondType)) { 9743 ODRDiagDeclError(FirstRecord, FirstModule, FirstTD->getLocation(), 9744 FirstTD->getSourceRange(), TypedefType) 9745 << IsTypeAlias << FirstName << FirstType; 9746 ODRDiagDeclNote(SecondModule, SecondTD->getLocation(), 9747 SecondTD->getSourceRange(), TypedefType) 9748 << IsTypeAlias << SecondName << SecondType; 9749 return true; 9750 } 9751 9752 return false; 9753 }; 9754 9755 auto ODRDiagVar = [&ODRDiagDeclError, &ODRDiagDeclNote, 9756 &ComputeQualTypeODRHash, &ComputeODRHash, 9757 this](NamedDecl *FirstRecord, StringRef FirstModule, 9758 StringRef SecondModule, VarDecl *FirstVD, 9759 VarDecl *SecondVD) { 9760 auto FirstName = FirstVD->getDeclName(); 9761 auto SecondName = SecondVD->getDeclName(); 9762 if (FirstName != SecondName) { 9763 ODRDiagDeclError(FirstRecord, FirstModule, FirstVD->getLocation(), 9764 FirstVD->getSourceRange(), VarName) 9765 << FirstName; 9766 ODRDiagDeclNote(SecondModule, SecondVD->getLocation(), 9767 SecondVD->getSourceRange(), VarName) 9768 << SecondName; 9769 return true; 9770 } 9771 9772 QualType FirstType = FirstVD->getType(); 9773 QualType SecondType = SecondVD->getType(); 9774 if (ComputeQualTypeODRHash(FirstType) != 9775 ComputeQualTypeODRHash(SecondType)) { 9776 ODRDiagDeclError(FirstRecord, FirstModule, FirstVD->getLocation(), 9777 FirstVD->getSourceRange(), VarType) 9778 << FirstName << FirstType; 9779 ODRDiagDeclNote(SecondModule, SecondVD->getLocation(), 9780 SecondVD->getSourceRange(), VarType) 9781 << SecondName << SecondType; 9782 return true; 9783 } 9784 9785 if (!PP.getLangOpts().CPlusPlus) 9786 return false; 9787 9788 const Expr *FirstInit = FirstVD->getInit(); 9789 const Expr *SecondInit = SecondVD->getInit(); 9790 if ((FirstInit == nullptr) != (SecondInit == nullptr)) { 9791 ODRDiagDeclError(FirstRecord, FirstModule, FirstVD->getLocation(), 9792 FirstVD->getSourceRange(), VarSingleInitializer) 9793 << FirstName << (FirstInit == nullptr) 9794 << (FirstInit ? FirstInit->getSourceRange() : SourceRange()); 9795 ODRDiagDeclNote(SecondModule, SecondVD->getLocation(), 9796 SecondVD->getSourceRange(), VarSingleInitializer) 9797 << SecondName << (SecondInit == nullptr) 9798 << (SecondInit ? SecondInit->getSourceRange() : SourceRange()); 9799 return true; 9800 } 9801 9802 if (FirstInit && SecondInit && 9803 ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) { 9804 ODRDiagDeclError(FirstRecord, FirstModule, FirstVD->getLocation(), 9805 FirstVD->getSourceRange(), VarDifferentInitializer) 9806 << FirstName << FirstInit->getSourceRange(); 9807 ODRDiagDeclNote(SecondModule, SecondVD->getLocation(), 9808 SecondVD->getSourceRange(), VarDifferentInitializer) 9809 << SecondName << SecondInit->getSourceRange(); 9810 return true; 9811 } 9812 9813 const bool FirstIsConstexpr = FirstVD->isConstexpr(); 9814 const bool SecondIsConstexpr = SecondVD->isConstexpr(); 9815 if (FirstIsConstexpr != SecondIsConstexpr) { 9816 ODRDiagDeclError(FirstRecord, FirstModule, FirstVD->getLocation(), 9817 FirstVD->getSourceRange(), VarConstexpr) 9818 << FirstName << FirstIsConstexpr; 9819 ODRDiagDeclNote(SecondModule, SecondVD->getLocation(), 9820 SecondVD->getSourceRange(), VarConstexpr) 9821 << SecondName << SecondIsConstexpr; 9822 return true; 9823 } 9824 return false; 9825 }; 9826 9827 auto DifferenceSelector = [](Decl *D) { 9828 assert(D && "valid Decl required"); 9829 switch (D->getKind()) { 9830 default: 9831 return Other; 9832 case Decl::AccessSpec: 9833 switch (D->getAccess()) { 9834 case AS_public: 9835 return PublicSpecifer; 9836 case AS_private: 9837 return PrivateSpecifer; 9838 case AS_protected: 9839 return ProtectedSpecifer; 9840 case AS_none: 9841 break; 9842 } 9843 llvm_unreachable("Invalid access specifier"); 9844 case Decl::StaticAssert: 9845 return StaticAssert; 9846 case Decl::Field: 9847 return Field; 9848 case Decl::CXXMethod: 9849 case Decl::CXXConstructor: 9850 case Decl::CXXDestructor: 9851 return CXXMethod; 9852 case Decl::TypeAlias: 9853 return TypeAlias; 9854 case Decl::Typedef: 9855 return TypeDef; 9856 case Decl::Var: 9857 return Var; 9858 case Decl::Friend: 9859 return Friend; 9860 case Decl::FunctionTemplate: 9861 return FunctionTemplate; 9862 } 9863 }; 9864 9865 using DeclHashes = llvm::SmallVector<std::pair<Decl *, unsigned>, 4>; 9866 auto PopulateHashes = [&ComputeSubDeclODRHash](DeclHashes &Hashes, 9867 RecordDecl *Record, 9868 const DeclContext *DC) { 9869 for (auto *D : Record->decls()) { 9870 if (!ODRHash::isDeclToBeProcessed(D, DC)) 9871 continue; 9872 Hashes.emplace_back(D, ComputeSubDeclODRHash(D)); 9873 } 9874 }; 9875 9876 struct DiffResult { 9877 Decl *FirstDecl = nullptr, *SecondDecl = nullptr; 9878 ODRMismatchDecl FirstDiffType = Other, SecondDiffType = Other; 9879 }; 9880 9881 // If there is a diagnoseable difference, FirstDiffType and 9882 // SecondDiffType will not be Other and FirstDecl and SecondDecl will be 9883 // filled in if not EndOfClass. 9884 auto FindTypeDiffs = [&DifferenceSelector](DeclHashes &FirstHashes, 9885 DeclHashes &SecondHashes) { 9886 DiffResult DR; 9887 auto FirstIt = FirstHashes.begin(); 9888 auto SecondIt = SecondHashes.begin(); 9889 while (FirstIt != FirstHashes.end() || SecondIt != SecondHashes.end()) { 9890 if (FirstIt != FirstHashes.end() && SecondIt != SecondHashes.end() && 9891 FirstIt->second == SecondIt->second) { 9892 ++FirstIt; 9893 ++SecondIt; 9894 continue; 9895 } 9896 9897 DR.FirstDecl = FirstIt == FirstHashes.end() ? nullptr : FirstIt->first; 9898 DR.SecondDecl = 9899 SecondIt == SecondHashes.end() ? nullptr : SecondIt->first; 9900 9901 DR.FirstDiffType = 9902 DR.FirstDecl ? DifferenceSelector(DR.FirstDecl) : EndOfClass; 9903 DR.SecondDiffType = 9904 DR.SecondDecl ? DifferenceSelector(DR.SecondDecl) : EndOfClass; 9905 return DR; 9906 } 9907 return DR; 9908 }; 9909 9910 // Use this to diagnose that an unexpected Decl was encountered 9911 // or no difference was detected. This causes a generic error 9912 // message to be emitted. 9913 auto DiagnoseODRUnexpected = [this](DiffResult &DR, NamedDecl *FirstRecord, 9914 StringRef FirstModule, 9915 NamedDecl *SecondRecord, 9916 StringRef SecondModule) { 9917 Diag(FirstRecord->getLocation(), 9918 diag::err_module_odr_violation_different_definitions) 9919 << FirstRecord << FirstModule.empty() << FirstModule; 9920 9921 if (DR.FirstDecl) { 9922 Diag(DR.FirstDecl->getLocation(), diag::note_first_module_difference) 9923 << FirstRecord << DR.FirstDecl->getSourceRange(); 9924 } 9925 9926 Diag(SecondRecord->getLocation(), 9927 diag::note_module_odr_violation_different_definitions) 9928 << SecondModule; 9929 9930 if (DR.SecondDecl) { 9931 Diag(DR.SecondDecl->getLocation(), diag::note_second_module_difference) 9932 << DR.SecondDecl->getSourceRange(); 9933 } 9934 }; 9935 9936 auto DiagnoseODRMismatch = 9937 [this](DiffResult &DR, NamedDecl *FirstRecord, StringRef FirstModule, 9938 NamedDecl *SecondRecord, StringRef SecondModule) { 9939 SourceLocation FirstLoc; 9940 SourceRange FirstRange; 9941 auto *FirstTag = dyn_cast<TagDecl>(FirstRecord); 9942 if (DR.FirstDiffType == EndOfClass && FirstTag) { 9943 FirstLoc = FirstTag->getBraceRange().getEnd(); 9944 } else { 9945 FirstLoc = DR.FirstDecl->getLocation(); 9946 FirstRange = DR.FirstDecl->getSourceRange(); 9947 } 9948 Diag(FirstLoc, diag::err_module_odr_violation_mismatch_decl) 9949 << FirstRecord << FirstModule.empty() << FirstModule << FirstRange 9950 << DR.FirstDiffType; 9951 9952 SourceLocation SecondLoc; 9953 SourceRange SecondRange; 9954 auto *SecondTag = dyn_cast<TagDecl>(SecondRecord); 9955 if (DR.SecondDiffType == EndOfClass && SecondTag) { 9956 SecondLoc = SecondTag->getBraceRange().getEnd(); 9957 } else { 9958 SecondLoc = DR.SecondDecl->getLocation(); 9959 SecondRange = DR.SecondDecl->getSourceRange(); 9960 } 9961 Diag(SecondLoc, diag::note_module_odr_violation_mismatch_decl) 9962 << SecondModule << SecondRange << DR.SecondDiffType; 9963 }; 9964 9965 // Issue any pending ODR-failure diagnostics. 9966 for (auto &Merge : OdrMergeFailures) { 9967 // If we've already pointed out a specific problem with this class, don't 9968 // bother issuing a general "something's different" diagnostic. 9969 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second) 9970 continue; 9971 9972 bool Diagnosed = false; 9973 CXXRecordDecl *FirstRecord = Merge.first; 9974 std::string FirstModule = getOwningModuleNameForDiagnostic(FirstRecord); 9975 for (auto &RecordPair : Merge.second) { 9976 CXXRecordDecl *SecondRecord = RecordPair.first; 9977 // Multiple different declarations got merged together; tell the user 9978 // where they came from. 9979 if (FirstRecord == SecondRecord) 9980 continue; 9981 9982 std::string SecondModule = getOwningModuleNameForDiagnostic(SecondRecord); 9983 9984 auto *FirstDD = FirstRecord->DefinitionData; 9985 auto *SecondDD = RecordPair.second; 9986 9987 assert(FirstDD && SecondDD && "Definitions without DefinitionData"); 9988 9989 // Diagnostics from DefinitionData are emitted here. 9990 if (FirstDD != SecondDD) { 9991 enum ODRDefinitionDataDifference { 9992 NumBases, 9993 NumVBases, 9994 BaseType, 9995 BaseVirtual, 9996 BaseAccess, 9997 }; 9998 auto ODRDiagBaseError = [FirstRecord, &FirstModule, 9999 this](SourceLocation Loc, SourceRange Range, 10000 ODRDefinitionDataDifference DiffType) { 10001 return Diag(Loc, diag::err_module_odr_violation_definition_data) 10002 << FirstRecord << FirstModule.empty() << FirstModule << Range 10003 << DiffType; 10004 }; 10005 auto ODRDiagBaseNote = [&SecondModule, 10006 this](SourceLocation Loc, SourceRange Range, 10007 ODRDefinitionDataDifference DiffType) { 10008 return Diag(Loc, diag::note_module_odr_violation_definition_data) 10009 << SecondModule << Range << DiffType; 10010 }; 10011 10012 unsigned FirstNumBases = FirstDD->NumBases; 10013 unsigned FirstNumVBases = FirstDD->NumVBases; 10014 unsigned SecondNumBases = SecondDD->NumBases; 10015 unsigned SecondNumVBases = SecondDD->NumVBases; 10016 10017 auto GetSourceRange = [](struct CXXRecordDecl::DefinitionData *DD) { 10018 unsigned NumBases = DD->NumBases; 10019 if (NumBases == 0) return SourceRange(); 10020 auto bases = DD->bases(); 10021 return SourceRange(bases[0].getBeginLoc(), 10022 bases[NumBases - 1].getEndLoc()); 10023 }; 10024 10025 if (FirstNumBases != SecondNumBases) { 10026 ODRDiagBaseError(FirstRecord->getLocation(), GetSourceRange(FirstDD), 10027 NumBases) 10028 << FirstNumBases; 10029 ODRDiagBaseNote(SecondRecord->getLocation(), GetSourceRange(SecondDD), 10030 NumBases) 10031 << SecondNumBases; 10032 Diagnosed = true; 10033 break; 10034 } 10035 10036 if (FirstNumVBases != SecondNumVBases) { 10037 ODRDiagBaseError(FirstRecord->getLocation(), GetSourceRange(FirstDD), 10038 NumVBases) 10039 << FirstNumVBases; 10040 ODRDiagBaseNote(SecondRecord->getLocation(), GetSourceRange(SecondDD), 10041 NumVBases) 10042 << SecondNumVBases; 10043 Diagnosed = true; 10044 break; 10045 } 10046 10047 auto FirstBases = FirstDD->bases(); 10048 auto SecondBases = SecondDD->bases(); 10049 unsigned i = 0; 10050 for (i = 0; i < FirstNumBases; ++i) { 10051 auto FirstBase = FirstBases[i]; 10052 auto SecondBase = SecondBases[i]; 10053 if (ComputeQualTypeODRHash(FirstBase.getType()) != 10054 ComputeQualTypeODRHash(SecondBase.getType())) { 10055 ODRDiagBaseError(FirstRecord->getLocation(), 10056 FirstBase.getSourceRange(), BaseType) 10057 << (i + 1) << FirstBase.getType(); 10058 ODRDiagBaseNote(SecondRecord->getLocation(), 10059 SecondBase.getSourceRange(), BaseType) 10060 << (i + 1) << SecondBase.getType(); 10061 break; 10062 } 10063 10064 if (FirstBase.isVirtual() != SecondBase.isVirtual()) { 10065 ODRDiagBaseError(FirstRecord->getLocation(), 10066 FirstBase.getSourceRange(), BaseVirtual) 10067 << (i + 1) << FirstBase.isVirtual() << FirstBase.getType(); 10068 ODRDiagBaseNote(SecondRecord->getLocation(), 10069 SecondBase.getSourceRange(), BaseVirtual) 10070 << (i + 1) << SecondBase.isVirtual() << SecondBase.getType(); 10071 break; 10072 } 10073 10074 if (FirstBase.getAccessSpecifierAsWritten() != 10075 SecondBase.getAccessSpecifierAsWritten()) { 10076 ODRDiagBaseError(FirstRecord->getLocation(), 10077 FirstBase.getSourceRange(), BaseAccess) 10078 << (i + 1) << FirstBase.getType() 10079 << (int)FirstBase.getAccessSpecifierAsWritten(); 10080 ODRDiagBaseNote(SecondRecord->getLocation(), 10081 SecondBase.getSourceRange(), BaseAccess) 10082 << (i + 1) << SecondBase.getType() 10083 << (int)SecondBase.getAccessSpecifierAsWritten(); 10084 break; 10085 } 10086 } 10087 10088 if (i != FirstNumBases) { 10089 Diagnosed = true; 10090 break; 10091 } 10092 } 10093 10094 const ClassTemplateDecl *FirstTemplate = 10095 FirstRecord->getDescribedClassTemplate(); 10096 const ClassTemplateDecl *SecondTemplate = 10097 SecondRecord->getDescribedClassTemplate(); 10098 10099 assert(!FirstTemplate == !SecondTemplate && 10100 "Both pointers should be null or non-null"); 10101 10102 enum ODRTemplateDifference { 10103 ParamEmptyName, 10104 ParamName, 10105 ParamSingleDefaultArgument, 10106 ParamDifferentDefaultArgument, 10107 }; 10108 10109 if (FirstTemplate && SecondTemplate) { 10110 DeclHashes FirstTemplateHashes; 10111 DeclHashes SecondTemplateHashes; 10112 10113 auto PopulateTemplateParameterHashs = 10114 [&ComputeSubDeclODRHash](DeclHashes &Hashes, 10115 const ClassTemplateDecl *TD) { 10116 for (auto *D : TD->getTemplateParameters()->asArray()) { 10117 Hashes.emplace_back(D, ComputeSubDeclODRHash(D)); 10118 } 10119 }; 10120 10121 PopulateTemplateParameterHashs(FirstTemplateHashes, FirstTemplate); 10122 PopulateTemplateParameterHashs(SecondTemplateHashes, SecondTemplate); 10123 10124 assert(FirstTemplateHashes.size() == SecondTemplateHashes.size() && 10125 "Number of template parameters should be equal."); 10126 10127 auto FirstIt = FirstTemplateHashes.begin(); 10128 auto FirstEnd = FirstTemplateHashes.end(); 10129 auto SecondIt = SecondTemplateHashes.begin(); 10130 for (; FirstIt != FirstEnd; ++FirstIt, ++SecondIt) { 10131 if (FirstIt->second == SecondIt->second) 10132 continue; 10133 10134 auto ODRDiagTemplateError = [FirstRecord, &FirstModule, this]( 10135 SourceLocation Loc, SourceRange Range, 10136 ODRTemplateDifference DiffType) { 10137 return Diag(Loc, diag::err_module_odr_violation_template_parameter) 10138 << FirstRecord << FirstModule.empty() << FirstModule << Range 10139 << DiffType; 10140 }; 10141 auto ODRDiagTemplateNote = [&SecondModule, this]( 10142 SourceLocation Loc, SourceRange Range, 10143 ODRTemplateDifference DiffType) { 10144 return Diag(Loc, diag::note_module_odr_violation_template_parameter) 10145 << SecondModule << Range << DiffType; 10146 }; 10147 10148 const NamedDecl* FirstDecl = cast<NamedDecl>(FirstIt->first); 10149 const NamedDecl* SecondDecl = cast<NamedDecl>(SecondIt->first); 10150 10151 assert(FirstDecl->getKind() == SecondDecl->getKind() && 10152 "Parameter Decl's should be the same kind."); 10153 10154 DeclarationName FirstName = FirstDecl->getDeclName(); 10155 DeclarationName SecondName = SecondDecl->getDeclName(); 10156 10157 if (FirstName != SecondName) { 10158 const bool FirstNameEmpty = 10159 FirstName.isIdentifier() && !FirstName.getAsIdentifierInfo(); 10160 const bool SecondNameEmpty = 10161 SecondName.isIdentifier() && !SecondName.getAsIdentifierInfo(); 10162 assert((!FirstNameEmpty || !SecondNameEmpty) && 10163 "Both template parameters cannot be unnamed."); 10164 ODRDiagTemplateError(FirstDecl->getLocation(), 10165 FirstDecl->getSourceRange(), 10166 FirstNameEmpty ? ParamEmptyName : ParamName) 10167 << FirstName; 10168 ODRDiagTemplateNote(SecondDecl->getLocation(), 10169 SecondDecl->getSourceRange(), 10170 SecondNameEmpty ? ParamEmptyName : ParamName) 10171 << SecondName; 10172 break; 10173 } 10174 10175 switch (FirstDecl->getKind()) { 10176 default: 10177 llvm_unreachable("Invalid template parameter type."); 10178 case Decl::TemplateTypeParm: { 10179 const auto *FirstParam = cast<TemplateTypeParmDecl>(FirstDecl); 10180 const auto *SecondParam = cast<TemplateTypeParmDecl>(SecondDecl); 10181 const bool HasFirstDefaultArgument = 10182 FirstParam->hasDefaultArgument() && 10183 !FirstParam->defaultArgumentWasInherited(); 10184 const bool HasSecondDefaultArgument = 10185 SecondParam->hasDefaultArgument() && 10186 !SecondParam->defaultArgumentWasInherited(); 10187 10188 if (HasFirstDefaultArgument != HasSecondDefaultArgument) { 10189 ODRDiagTemplateError(FirstDecl->getLocation(), 10190 FirstDecl->getSourceRange(), 10191 ParamSingleDefaultArgument) 10192 << HasFirstDefaultArgument; 10193 ODRDiagTemplateNote(SecondDecl->getLocation(), 10194 SecondDecl->getSourceRange(), 10195 ParamSingleDefaultArgument) 10196 << HasSecondDefaultArgument; 10197 break; 10198 } 10199 10200 assert(HasFirstDefaultArgument && HasSecondDefaultArgument && 10201 "Expecting default arguments."); 10202 10203 ODRDiagTemplateError(FirstDecl->getLocation(), 10204 FirstDecl->getSourceRange(), 10205 ParamDifferentDefaultArgument); 10206 ODRDiagTemplateNote(SecondDecl->getLocation(), 10207 SecondDecl->getSourceRange(), 10208 ParamDifferentDefaultArgument); 10209 10210 break; 10211 } 10212 case Decl::NonTypeTemplateParm: { 10213 const auto *FirstParam = cast<NonTypeTemplateParmDecl>(FirstDecl); 10214 const auto *SecondParam = cast<NonTypeTemplateParmDecl>(SecondDecl); 10215 const bool HasFirstDefaultArgument = 10216 FirstParam->hasDefaultArgument() && 10217 !FirstParam->defaultArgumentWasInherited(); 10218 const bool HasSecondDefaultArgument = 10219 SecondParam->hasDefaultArgument() && 10220 !SecondParam->defaultArgumentWasInherited(); 10221 10222 if (HasFirstDefaultArgument != HasSecondDefaultArgument) { 10223 ODRDiagTemplateError(FirstDecl->getLocation(), 10224 FirstDecl->getSourceRange(), 10225 ParamSingleDefaultArgument) 10226 << HasFirstDefaultArgument; 10227 ODRDiagTemplateNote(SecondDecl->getLocation(), 10228 SecondDecl->getSourceRange(), 10229 ParamSingleDefaultArgument) 10230 << HasSecondDefaultArgument; 10231 break; 10232 } 10233 10234 assert(HasFirstDefaultArgument && HasSecondDefaultArgument && 10235 "Expecting default arguments."); 10236 10237 ODRDiagTemplateError(FirstDecl->getLocation(), 10238 FirstDecl->getSourceRange(), 10239 ParamDifferentDefaultArgument); 10240 ODRDiagTemplateNote(SecondDecl->getLocation(), 10241 SecondDecl->getSourceRange(), 10242 ParamDifferentDefaultArgument); 10243 10244 break; 10245 } 10246 case Decl::TemplateTemplateParm: { 10247 const auto *FirstParam = cast<TemplateTemplateParmDecl>(FirstDecl); 10248 const auto *SecondParam = 10249 cast<TemplateTemplateParmDecl>(SecondDecl); 10250 const bool HasFirstDefaultArgument = 10251 FirstParam->hasDefaultArgument() && 10252 !FirstParam->defaultArgumentWasInherited(); 10253 const bool HasSecondDefaultArgument = 10254 SecondParam->hasDefaultArgument() && 10255 !SecondParam->defaultArgumentWasInherited(); 10256 10257 if (HasFirstDefaultArgument != HasSecondDefaultArgument) { 10258 ODRDiagTemplateError(FirstDecl->getLocation(), 10259 FirstDecl->getSourceRange(), 10260 ParamSingleDefaultArgument) 10261 << HasFirstDefaultArgument; 10262 ODRDiagTemplateNote(SecondDecl->getLocation(), 10263 SecondDecl->getSourceRange(), 10264 ParamSingleDefaultArgument) 10265 << HasSecondDefaultArgument; 10266 break; 10267 } 10268 10269 assert(HasFirstDefaultArgument && HasSecondDefaultArgument && 10270 "Expecting default arguments."); 10271 10272 ODRDiagTemplateError(FirstDecl->getLocation(), 10273 FirstDecl->getSourceRange(), 10274 ParamDifferentDefaultArgument); 10275 ODRDiagTemplateNote(SecondDecl->getLocation(), 10276 SecondDecl->getSourceRange(), 10277 ParamDifferentDefaultArgument); 10278 10279 break; 10280 } 10281 } 10282 10283 break; 10284 } 10285 10286 if (FirstIt != FirstEnd) { 10287 Diagnosed = true; 10288 break; 10289 } 10290 } 10291 10292 DeclHashes FirstHashes; 10293 DeclHashes SecondHashes; 10294 const DeclContext *DC = FirstRecord; 10295 PopulateHashes(FirstHashes, FirstRecord, DC); 10296 PopulateHashes(SecondHashes, SecondRecord, DC); 10297 10298 auto DR = FindTypeDiffs(FirstHashes, SecondHashes); 10299 ODRMismatchDecl FirstDiffType = DR.FirstDiffType; 10300 ODRMismatchDecl SecondDiffType = DR.SecondDiffType; 10301 Decl *FirstDecl = DR.FirstDecl; 10302 Decl *SecondDecl = DR.SecondDecl; 10303 10304 if (FirstDiffType == Other || SecondDiffType == Other) { 10305 DiagnoseODRUnexpected(DR, FirstRecord, FirstModule, SecondRecord, 10306 SecondModule); 10307 Diagnosed = true; 10308 break; 10309 } 10310 10311 if (FirstDiffType != SecondDiffType) { 10312 DiagnoseODRMismatch(DR, FirstRecord, FirstModule, SecondRecord, 10313 SecondModule); 10314 Diagnosed = true; 10315 break; 10316 } 10317 10318 assert(FirstDiffType == SecondDiffType); 10319 10320 switch (FirstDiffType) { 10321 case Other: 10322 case EndOfClass: 10323 case PublicSpecifer: 10324 case PrivateSpecifer: 10325 case ProtectedSpecifer: 10326 llvm_unreachable("Invalid diff type"); 10327 10328 case StaticAssert: { 10329 StaticAssertDecl *FirstSA = cast<StaticAssertDecl>(FirstDecl); 10330 StaticAssertDecl *SecondSA = cast<StaticAssertDecl>(SecondDecl); 10331 10332 Expr *FirstExpr = FirstSA->getAssertExpr(); 10333 Expr *SecondExpr = SecondSA->getAssertExpr(); 10334 unsigned FirstODRHash = ComputeODRHash(FirstExpr); 10335 unsigned SecondODRHash = ComputeODRHash(SecondExpr); 10336 if (FirstODRHash != SecondODRHash) { 10337 ODRDiagDeclError(FirstRecord, FirstModule, FirstExpr->getBeginLoc(), 10338 FirstExpr->getSourceRange(), StaticAssertCondition); 10339 ODRDiagDeclNote(SecondModule, SecondExpr->getBeginLoc(), 10340 SecondExpr->getSourceRange(), StaticAssertCondition); 10341 Diagnosed = true; 10342 break; 10343 } 10344 10345 StringLiteral *FirstStr = FirstSA->getMessage(); 10346 StringLiteral *SecondStr = SecondSA->getMessage(); 10347 assert((FirstStr || SecondStr) && "Both messages cannot be empty"); 10348 if ((FirstStr && !SecondStr) || (!FirstStr && SecondStr)) { 10349 SourceLocation FirstLoc, SecondLoc; 10350 SourceRange FirstRange, SecondRange; 10351 if (FirstStr) { 10352 FirstLoc = FirstStr->getBeginLoc(); 10353 FirstRange = FirstStr->getSourceRange(); 10354 } else { 10355 FirstLoc = FirstSA->getBeginLoc(); 10356 FirstRange = FirstSA->getSourceRange(); 10357 } 10358 if (SecondStr) { 10359 SecondLoc = SecondStr->getBeginLoc(); 10360 SecondRange = SecondStr->getSourceRange(); 10361 } else { 10362 SecondLoc = SecondSA->getBeginLoc(); 10363 SecondRange = SecondSA->getSourceRange(); 10364 } 10365 ODRDiagDeclError(FirstRecord, FirstModule, FirstLoc, FirstRange, 10366 StaticAssertOnlyMessage) 10367 << (FirstStr == nullptr); 10368 ODRDiagDeclNote(SecondModule, SecondLoc, SecondRange, 10369 StaticAssertOnlyMessage) 10370 << (SecondStr == nullptr); 10371 Diagnosed = true; 10372 break; 10373 } 10374 10375 if (FirstStr && SecondStr && 10376 FirstStr->getString() != SecondStr->getString()) { 10377 ODRDiagDeclError(FirstRecord, FirstModule, FirstStr->getBeginLoc(), 10378 FirstStr->getSourceRange(), StaticAssertMessage); 10379 ODRDiagDeclNote(SecondModule, SecondStr->getBeginLoc(), 10380 SecondStr->getSourceRange(), StaticAssertMessage); 10381 Diagnosed = true; 10382 break; 10383 } 10384 break; 10385 } 10386 case Field: { 10387 Diagnosed = ODRDiagField(FirstRecord, FirstModule, SecondModule, 10388 cast<FieldDecl>(FirstDecl), 10389 cast<FieldDecl>(SecondDecl)); 10390 break; 10391 } 10392 case CXXMethod: { 10393 enum { 10394 DiagMethod, 10395 DiagConstructor, 10396 DiagDestructor, 10397 } FirstMethodType, 10398 SecondMethodType; 10399 auto GetMethodTypeForDiagnostics = [](const CXXMethodDecl* D) { 10400 if (isa<CXXConstructorDecl>(D)) return DiagConstructor; 10401 if (isa<CXXDestructorDecl>(D)) return DiagDestructor; 10402 return DiagMethod; 10403 }; 10404 const CXXMethodDecl *FirstMethod = cast<CXXMethodDecl>(FirstDecl); 10405 const CXXMethodDecl *SecondMethod = cast<CXXMethodDecl>(SecondDecl); 10406 FirstMethodType = GetMethodTypeForDiagnostics(FirstMethod); 10407 SecondMethodType = GetMethodTypeForDiagnostics(SecondMethod); 10408 auto FirstName = FirstMethod->getDeclName(); 10409 auto SecondName = SecondMethod->getDeclName(); 10410 if (FirstMethodType != SecondMethodType || FirstName != SecondName) { 10411 ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(), 10412 FirstMethod->getSourceRange(), MethodName) 10413 << FirstMethodType << FirstName; 10414 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(), 10415 SecondMethod->getSourceRange(), MethodName) 10416 << SecondMethodType << SecondName; 10417 10418 Diagnosed = true; 10419 break; 10420 } 10421 10422 const bool FirstDeleted = FirstMethod->isDeletedAsWritten(); 10423 const bool SecondDeleted = SecondMethod->isDeletedAsWritten(); 10424 if (FirstDeleted != SecondDeleted) { 10425 ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(), 10426 FirstMethod->getSourceRange(), MethodDeleted) 10427 << FirstMethodType << FirstName << FirstDeleted; 10428 10429 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(), 10430 SecondMethod->getSourceRange(), MethodDeleted) 10431 << SecondMethodType << SecondName << SecondDeleted; 10432 Diagnosed = true; 10433 break; 10434 } 10435 10436 const bool FirstDefaulted = FirstMethod->isExplicitlyDefaulted(); 10437 const bool SecondDefaulted = SecondMethod->isExplicitlyDefaulted(); 10438 if (FirstDefaulted != SecondDefaulted) { 10439 ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(), 10440 FirstMethod->getSourceRange(), MethodDefaulted) 10441 << FirstMethodType << FirstName << FirstDefaulted; 10442 10443 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(), 10444 SecondMethod->getSourceRange(), MethodDefaulted) 10445 << SecondMethodType << SecondName << SecondDefaulted; 10446 Diagnosed = true; 10447 break; 10448 } 10449 10450 const bool FirstVirtual = FirstMethod->isVirtualAsWritten(); 10451 const bool SecondVirtual = SecondMethod->isVirtualAsWritten(); 10452 const bool FirstPure = FirstMethod->isPure(); 10453 const bool SecondPure = SecondMethod->isPure(); 10454 if ((FirstVirtual || SecondVirtual) && 10455 (FirstVirtual != SecondVirtual || FirstPure != SecondPure)) { 10456 ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(), 10457 FirstMethod->getSourceRange(), MethodVirtual) 10458 << FirstMethodType << FirstName << FirstPure << FirstVirtual; 10459 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(), 10460 SecondMethod->getSourceRange(), MethodVirtual) 10461 << SecondMethodType << SecondName << SecondPure << SecondVirtual; 10462 Diagnosed = true; 10463 break; 10464 } 10465 10466 // CXXMethodDecl::isStatic uses the canonical Decl. With Decl merging, 10467 // FirstDecl is the canonical Decl of SecondDecl, so the storage 10468 // class needs to be checked instead. 10469 const auto FirstStorage = FirstMethod->getStorageClass(); 10470 const auto SecondStorage = SecondMethod->getStorageClass(); 10471 const bool FirstStatic = FirstStorage == SC_Static; 10472 const bool SecondStatic = SecondStorage == SC_Static; 10473 if (FirstStatic != SecondStatic) { 10474 ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(), 10475 FirstMethod->getSourceRange(), MethodStatic) 10476 << FirstMethodType << FirstName << FirstStatic; 10477 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(), 10478 SecondMethod->getSourceRange(), MethodStatic) 10479 << SecondMethodType << SecondName << SecondStatic; 10480 Diagnosed = true; 10481 break; 10482 } 10483 10484 const bool FirstVolatile = FirstMethod->isVolatile(); 10485 const bool SecondVolatile = SecondMethod->isVolatile(); 10486 if (FirstVolatile != SecondVolatile) { 10487 ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(), 10488 FirstMethod->getSourceRange(), MethodVolatile) 10489 << FirstMethodType << FirstName << FirstVolatile; 10490 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(), 10491 SecondMethod->getSourceRange(), MethodVolatile) 10492 << SecondMethodType << SecondName << SecondVolatile; 10493 Diagnosed = true; 10494 break; 10495 } 10496 10497 const bool FirstConst = FirstMethod->isConst(); 10498 const bool SecondConst = SecondMethod->isConst(); 10499 if (FirstConst != SecondConst) { 10500 ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(), 10501 FirstMethod->getSourceRange(), MethodConst) 10502 << FirstMethodType << FirstName << FirstConst; 10503 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(), 10504 SecondMethod->getSourceRange(), MethodConst) 10505 << SecondMethodType << SecondName << SecondConst; 10506 Diagnosed = true; 10507 break; 10508 } 10509 10510 const bool FirstInline = FirstMethod->isInlineSpecified(); 10511 const bool SecondInline = SecondMethod->isInlineSpecified(); 10512 if (FirstInline != SecondInline) { 10513 ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(), 10514 FirstMethod->getSourceRange(), MethodInline) 10515 << FirstMethodType << FirstName << FirstInline; 10516 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(), 10517 SecondMethod->getSourceRange(), MethodInline) 10518 << SecondMethodType << SecondName << SecondInline; 10519 Diagnosed = true; 10520 break; 10521 } 10522 10523 const unsigned FirstNumParameters = FirstMethod->param_size(); 10524 const unsigned SecondNumParameters = SecondMethod->param_size(); 10525 if (FirstNumParameters != SecondNumParameters) { 10526 ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(), 10527 FirstMethod->getSourceRange(), 10528 MethodNumberParameters) 10529 << FirstMethodType << FirstName << FirstNumParameters; 10530 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(), 10531 SecondMethod->getSourceRange(), 10532 MethodNumberParameters) 10533 << SecondMethodType << SecondName << SecondNumParameters; 10534 Diagnosed = true; 10535 break; 10536 } 10537 10538 // Need this status boolean to know when break out of the switch. 10539 bool ParameterMismatch = false; 10540 for (unsigned I = 0; I < FirstNumParameters; ++I) { 10541 const ParmVarDecl *FirstParam = FirstMethod->getParamDecl(I); 10542 const ParmVarDecl *SecondParam = SecondMethod->getParamDecl(I); 10543 10544 QualType FirstParamType = FirstParam->getType(); 10545 QualType SecondParamType = SecondParam->getType(); 10546 if (FirstParamType != SecondParamType && 10547 ComputeQualTypeODRHash(FirstParamType) != 10548 ComputeQualTypeODRHash(SecondParamType)) { 10549 if (const DecayedType *ParamDecayedType = 10550 FirstParamType->getAs<DecayedType>()) { 10551 ODRDiagDeclError( 10552 FirstRecord, FirstModule, FirstMethod->getLocation(), 10553 FirstMethod->getSourceRange(), MethodParameterType) 10554 << FirstMethodType << FirstName << (I + 1) << FirstParamType 10555 << true << ParamDecayedType->getOriginalType(); 10556 } else { 10557 ODRDiagDeclError( 10558 FirstRecord, FirstModule, FirstMethod->getLocation(), 10559 FirstMethod->getSourceRange(), MethodParameterType) 10560 << FirstMethodType << FirstName << (I + 1) << FirstParamType 10561 << false; 10562 } 10563 10564 if (const DecayedType *ParamDecayedType = 10565 SecondParamType->getAs<DecayedType>()) { 10566 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(), 10567 SecondMethod->getSourceRange(), 10568 MethodParameterType) 10569 << SecondMethodType << SecondName << (I + 1) 10570 << SecondParamType << true 10571 << ParamDecayedType->getOriginalType(); 10572 } else { 10573 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(), 10574 SecondMethod->getSourceRange(), 10575 MethodParameterType) 10576 << SecondMethodType << SecondName << (I + 1) 10577 << SecondParamType << false; 10578 } 10579 ParameterMismatch = true; 10580 break; 10581 } 10582 10583 DeclarationName FirstParamName = FirstParam->getDeclName(); 10584 DeclarationName SecondParamName = SecondParam->getDeclName(); 10585 if (FirstParamName != SecondParamName) { 10586 ODRDiagDeclError(FirstRecord, FirstModule, 10587 FirstMethod->getLocation(), 10588 FirstMethod->getSourceRange(), MethodParameterName) 10589 << FirstMethodType << FirstName << (I + 1) << FirstParamName; 10590 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(), 10591 SecondMethod->getSourceRange(), MethodParameterName) 10592 << SecondMethodType << SecondName << (I + 1) << SecondParamName; 10593 ParameterMismatch = true; 10594 break; 10595 } 10596 10597 const Expr *FirstInit = FirstParam->getInit(); 10598 const Expr *SecondInit = SecondParam->getInit(); 10599 if ((FirstInit == nullptr) != (SecondInit == nullptr)) { 10600 ODRDiagDeclError(FirstRecord, FirstModule, 10601 FirstMethod->getLocation(), 10602 FirstMethod->getSourceRange(), 10603 MethodParameterSingleDefaultArgument) 10604 << FirstMethodType << FirstName << (I + 1) 10605 << (FirstInit == nullptr) 10606 << (FirstInit ? FirstInit->getSourceRange() : SourceRange()); 10607 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(), 10608 SecondMethod->getSourceRange(), 10609 MethodParameterSingleDefaultArgument) 10610 << SecondMethodType << SecondName << (I + 1) 10611 << (SecondInit == nullptr) 10612 << (SecondInit ? SecondInit->getSourceRange() : SourceRange()); 10613 ParameterMismatch = true; 10614 break; 10615 } 10616 10617 if (FirstInit && SecondInit && 10618 ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) { 10619 ODRDiagDeclError(FirstRecord, FirstModule, 10620 FirstMethod->getLocation(), 10621 FirstMethod->getSourceRange(), 10622 MethodParameterDifferentDefaultArgument) 10623 << FirstMethodType << FirstName << (I + 1) 10624 << FirstInit->getSourceRange(); 10625 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(), 10626 SecondMethod->getSourceRange(), 10627 MethodParameterDifferentDefaultArgument) 10628 << SecondMethodType << SecondName << (I + 1) 10629 << SecondInit->getSourceRange(); 10630 ParameterMismatch = true; 10631 break; 10632 10633 } 10634 } 10635 10636 if (ParameterMismatch) { 10637 Diagnosed = true; 10638 break; 10639 } 10640 10641 const auto *FirstTemplateArgs = 10642 FirstMethod->getTemplateSpecializationArgs(); 10643 const auto *SecondTemplateArgs = 10644 SecondMethod->getTemplateSpecializationArgs(); 10645 10646 if ((FirstTemplateArgs && !SecondTemplateArgs) || 10647 (!FirstTemplateArgs && SecondTemplateArgs)) { 10648 ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(), 10649 FirstMethod->getSourceRange(), 10650 MethodNoTemplateArguments) 10651 << FirstMethodType << FirstName << (FirstTemplateArgs != nullptr); 10652 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(), 10653 SecondMethod->getSourceRange(), 10654 MethodNoTemplateArguments) 10655 << SecondMethodType << SecondName 10656 << (SecondTemplateArgs != nullptr); 10657 10658 Diagnosed = true; 10659 break; 10660 } 10661 10662 if (FirstTemplateArgs && SecondTemplateArgs) { 10663 // Remove pack expansions from argument list. 10664 auto ExpandTemplateArgumentList = 10665 [](const TemplateArgumentList *TAL) { 10666 llvm::SmallVector<const TemplateArgument *, 8> ExpandedList; 10667 for (const TemplateArgument &TA : TAL->asArray()) { 10668 if (TA.getKind() != TemplateArgument::Pack) { 10669 ExpandedList.push_back(&TA); 10670 continue; 10671 } 10672 for (const TemplateArgument &PackTA : TA.getPackAsArray()) { 10673 ExpandedList.push_back(&PackTA); 10674 } 10675 } 10676 return ExpandedList; 10677 }; 10678 llvm::SmallVector<const TemplateArgument *, 8> FirstExpandedList = 10679 ExpandTemplateArgumentList(FirstTemplateArgs); 10680 llvm::SmallVector<const TemplateArgument *, 8> SecondExpandedList = 10681 ExpandTemplateArgumentList(SecondTemplateArgs); 10682 10683 if (FirstExpandedList.size() != SecondExpandedList.size()) { 10684 ODRDiagDeclError(FirstRecord, FirstModule, 10685 FirstMethod->getLocation(), 10686 FirstMethod->getSourceRange(), 10687 MethodDifferentNumberTemplateArguments) 10688 << FirstMethodType << FirstName 10689 << (unsigned)FirstExpandedList.size(); 10690 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(), 10691 SecondMethod->getSourceRange(), 10692 MethodDifferentNumberTemplateArguments) 10693 << SecondMethodType << SecondName 10694 << (unsigned)SecondExpandedList.size(); 10695 10696 Diagnosed = true; 10697 break; 10698 } 10699 10700 bool TemplateArgumentMismatch = false; 10701 for (unsigned i = 0, e = FirstExpandedList.size(); i != e; ++i) { 10702 const TemplateArgument &FirstTA = *FirstExpandedList[i], 10703 &SecondTA = *SecondExpandedList[i]; 10704 if (ComputeTemplateArgumentODRHash(FirstTA) == 10705 ComputeTemplateArgumentODRHash(SecondTA)) { 10706 continue; 10707 } 10708 10709 ODRDiagDeclError( 10710 FirstRecord, FirstModule, FirstMethod->getLocation(), 10711 FirstMethod->getSourceRange(), MethodDifferentTemplateArgument) 10712 << FirstMethodType << FirstName << FirstTA << i + 1; 10713 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(), 10714 SecondMethod->getSourceRange(), 10715 MethodDifferentTemplateArgument) 10716 << SecondMethodType << SecondName << SecondTA << i + 1; 10717 10718 TemplateArgumentMismatch = true; 10719 break; 10720 } 10721 10722 if (TemplateArgumentMismatch) { 10723 Diagnosed = true; 10724 break; 10725 } 10726 } 10727 10728 // Compute the hash of the method as if it has no body. 10729 auto ComputeCXXMethodODRHash = [&Hash](const CXXMethodDecl *D) { 10730 Hash.clear(); 10731 Hash.AddFunctionDecl(D, true /*SkipBody*/); 10732 return Hash.CalculateHash(); 10733 }; 10734 10735 // Compare the hash generated to the hash stored. A difference means 10736 // that a body was present in the original source. Due to merging, 10737 // the stardard way of detecting a body will not work. 10738 const bool HasFirstBody = 10739 ComputeCXXMethodODRHash(FirstMethod) != FirstMethod->getODRHash(); 10740 const bool HasSecondBody = 10741 ComputeCXXMethodODRHash(SecondMethod) != SecondMethod->getODRHash(); 10742 10743 if (HasFirstBody != HasSecondBody) { 10744 ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(), 10745 FirstMethod->getSourceRange(), MethodSingleBody) 10746 << FirstMethodType << FirstName << HasFirstBody; 10747 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(), 10748 SecondMethod->getSourceRange(), MethodSingleBody) 10749 << SecondMethodType << SecondName << HasSecondBody; 10750 Diagnosed = true; 10751 break; 10752 } 10753 10754 if (HasFirstBody && HasSecondBody) { 10755 ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(), 10756 FirstMethod->getSourceRange(), MethodDifferentBody) 10757 << FirstMethodType << FirstName; 10758 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(), 10759 SecondMethod->getSourceRange(), MethodDifferentBody) 10760 << SecondMethodType << SecondName; 10761 Diagnosed = true; 10762 break; 10763 } 10764 10765 break; 10766 } 10767 case TypeAlias: 10768 case TypeDef: { 10769 Diagnosed = ODRDiagTypeDefOrAlias( 10770 FirstRecord, FirstModule, SecondModule, 10771 cast<TypedefNameDecl>(FirstDecl), cast<TypedefNameDecl>(SecondDecl), 10772 FirstDiffType == TypeAlias); 10773 break; 10774 } 10775 case Var: { 10776 Diagnosed = 10777 ODRDiagVar(FirstRecord, FirstModule, SecondModule, 10778 cast<VarDecl>(FirstDecl), cast<VarDecl>(SecondDecl)); 10779 break; 10780 } 10781 case Friend: { 10782 FriendDecl *FirstFriend = cast<FriendDecl>(FirstDecl); 10783 FriendDecl *SecondFriend = cast<FriendDecl>(SecondDecl); 10784 10785 NamedDecl *FirstND = FirstFriend->getFriendDecl(); 10786 NamedDecl *SecondND = SecondFriend->getFriendDecl(); 10787 10788 TypeSourceInfo *FirstTSI = FirstFriend->getFriendType(); 10789 TypeSourceInfo *SecondTSI = SecondFriend->getFriendType(); 10790 10791 if (FirstND && SecondND) { 10792 ODRDiagDeclError(FirstRecord, FirstModule, 10793 FirstFriend->getFriendLoc(), 10794 FirstFriend->getSourceRange(), FriendFunction) 10795 << FirstND; 10796 ODRDiagDeclNote(SecondModule, SecondFriend->getFriendLoc(), 10797 SecondFriend->getSourceRange(), FriendFunction) 10798 << SecondND; 10799 10800 Diagnosed = true; 10801 break; 10802 } 10803 10804 if (FirstTSI && SecondTSI) { 10805 QualType FirstFriendType = FirstTSI->getType(); 10806 QualType SecondFriendType = SecondTSI->getType(); 10807 assert(ComputeQualTypeODRHash(FirstFriendType) != 10808 ComputeQualTypeODRHash(SecondFriendType)); 10809 ODRDiagDeclError(FirstRecord, FirstModule, 10810 FirstFriend->getFriendLoc(), 10811 FirstFriend->getSourceRange(), FriendType) 10812 << FirstFriendType; 10813 ODRDiagDeclNote(SecondModule, SecondFriend->getFriendLoc(), 10814 SecondFriend->getSourceRange(), FriendType) 10815 << SecondFriendType; 10816 Diagnosed = true; 10817 break; 10818 } 10819 10820 ODRDiagDeclError(FirstRecord, FirstModule, FirstFriend->getFriendLoc(), 10821 FirstFriend->getSourceRange(), FriendTypeFunction) 10822 << (FirstTSI == nullptr); 10823 ODRDiagDeclNote(SecondModule, SecondFriend->getFriendLoc(), 10824 SecondFriend->getSourceRange(), FriendTypeFunction) 10825 << (SecondTSI == nullptr); 10826 10827 Diagnosed = true; 10828 break; 10829 } 10830 case FunctionTemplate: { 10831 FunctionTemplateDecl *FirstTemplate = 10832 cast<FunctionTemplateDecl>(FirstDecl); 10833 FunctionTemplateDecl *SecondTemplate = 10834 cast<FunctionTemplateDecl>(SecondDecl); 10835 10836 TemplateParameterList *FirstTPL = 10837 FirstTemplate->getTemplateParameters(); 10838 TemplateParameterList *SecondTPL = 10839 SecondTemplate->getTemplateParameters(); 10840 10841 if (FirstTPL->size() != SecondTPL->size()) { 10842 ODRDiagDeclError(FirstRecord, FirstModule, 10843 FirstTemplate->getLocation(), 10844 FirstTemplate->getSourceRange(), 10845 FunctionTemplateDifferentNumberParameters) 10846 << FirstTemplate << FirstTPL->size(); 10847 ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(), 10848 SecondTemplate->getSourceRange(), 10849 FunctionTemplateDifferentNumberParameters) 10850 << SecondTemplate << SecondTPL->size(); 10851 10852 Diagnosed = true; 10853 break; 10854 } 10855 10856 bool ParameterMismatch = false; 10857 for (unsigned i = 0, e = FirstTPL->size(); i != e; ++i) { 10858 NamedDecl *FirstParam = FirstTPL->getParam(i); 10859 NamedDecl *SecondParam = SecondTPL->getParam(i); 10860 10861 if (FirstParam->getKind() != SecondParam->getKind()) { 10862 enum { 10863 TemplateTypeParameter, 10864 NonTypeTemplateParameter, 10865 TemplateTemplateParameter, 10866 }; 10867 auto GetParamType = [](NamedDecl *D) { 10868 switch (D->getKind()) { 10869 default: 10870 llvm_unreachable("Unexpected template parameter type"); 10871 case Decl::TemplateTypeParm: 10872 return TemplateTypeParameter; 10873 case Decl::NonTypeTemplateParm: 10874 return NonTypeTemplateParameter; 10875 case Decl::TemplateTemplateParm: 10876 return TemplateTemplateParameter; 10877 } 10878 }; 10879 10880 ODRDiagDeclError(FirstRecord, FirstModule, 10881 FirstTemplate->getLocation(), 10882 FirstTemplate->getSourceRange(), 10883 FunctionTemplateParameterDifferentKind) 10884 << FirstTemplate << (i + 1) << GetParamType(FirstParam); 10885 ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(), 10886 SecondTemplate->getSourceRange(), 10887 FunctionTemplateParameterDifferentKind) 10888 << SecondTemplate << (i + 1) << GetParamType(SecondParam); 10889 10890 ParameterMismatch = true; 10891 break; 10892 } 10893 10894 if (FirstParam->getName() != SecondParam->getName()) { 10895 ODRDiagDeclError( 10896 FirstRecord, FirstModule, FirstTemplate->getLocation(), 10897 FirstTemplate->getSourceRange(), FunctionTemplateParameterName) 10898 << FirstTemplate << (i + 1) << (bool)FirstParam->getIdentifier() 10899 << FirstParam; 10900 ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(), 10901 SecondTemplate->getSourceRange(), 10902 FunctionTemplateParameterName) 10903 << SecondTemplate << (i + 1) 10904 << (bool)SecondParam->getIdentifier() << SecondParam; 10905 ParameterMismatch = true; 10906 break; 10907 } 10908 10909 if (isa<TemplateTypeParmDecl>(FirstParam) && 10910 isa<TemplateTypeParmDecl>(SecondParam)) { 10911 TemplateTypeParmDecl *FirstTTPD = 10912 cast<TemplateTypeParmDecl>(FirstParam); 10913 TemplateTypeParmDecl *SecondTTPD = 10914 cast<TemplateTypeParmDecl>(SecondParam); 10915 bool HasFirstDefaultArgument = 10916 FirstTTPD->hasDefaultArgument() && 10917 !FirstTTPD->defaultArgumentWasInherited(); 10918 bool HasSecondDefaultArgument = 10919 SecondTTPD->hasDefaultArgument() && 10920 !SecondTTPD->defaultArgumentWasInherited(); 10921 if (HasFirstDefaultArgument != HasSecondDefaultArgument) { 10922 ODRDiagDeclError(FirstRecord, FirstModule, 10923 FirstTemplate->getLocation(), 10924 FirstTemplate->getSourceRange(), 10925 FunctionTemplateParameterSingleDefaultArgument) 10926 << FirstTemplate << (i + 1) << HasFirstDefaultArgument; 10927 ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(), 10928 SecondTemplate->getSourceRange(), 10929 FunctionTemplateParameterSingleDefaultArgument) 10930 << SecondTemplate << (i + 1) << HasSecondDefaultArgument; 10931 ParameterMismatch = true; 10932 break; 10933 } 10934 10935 if (HasFirstDefaultArgument && HasSecondDefaultArgument) { 10936 QualType FirstType = FirstTTPD->getDefaultArgument(); 10937 QualType SecondType = SecondTTPD->getDefaultArgument(); 10938 if (ComputeQualTypeODRHash(FirstType) != 10939 ComputeQualTypeODRHash(SecondType)) { 10940 ODRDiagDeclError( 10941 FirstRecord, FirstModule, FirstTemplate->getLocation(), 10942 FirstTemplate->getSourceRange(), 10943 FunctionTemplateParameterDifferentDefaultArgument) 10944 << FirstTemplate << (i + 1) << FirstType; 10945 ODRDiagDeclNote( 10946 SecondModule, SecondTemplate->getLocation(), 10947 SecondTemplate->getSourceRange(), 10948 FunctionTemplateParameterDifferentDefaultArgument) 10949 << SecondTemplate << (i + 1) << SecondType; 10950 ParameterMismatch = true; 10951 break; 10952 } 10953 } 10954 10955 if (FirstTTPD->isParameterPack() != 10956 SecondTTPD->isParameterPack()) { 10957 ODRDiagDeclError(FirstRecord, FirstModule, 10958 FirstTemplate->getLocation(), 10959 FirstTemplate->getSourceRange(), 10960 FunctionTemplatePackParameter) 10961 << FirstTemplate << (i + 1) << FirstTTPD->isParameterPack(); 10962 ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(), 10963 SecondTemplate->getSourceRange(), 10964 FunctionTemplatePackParameter) 10965 << SecondTemplate << (i + 1) << SecondTTPD->isParameterPack(); 10966 ParameterMismatch = true; 10967 break; 10968 } 10969 } 10970 10971 if (isa<TemplateTemplateParmDecl>(FirstParam) && 10972 isa<TemplateTemplateParmDecl>(SecondParam)) { 10973 TemplateTemplateParmDecl *FirstTTPD = 10974 cast<TemplateTemplateParmDecl>(FirstParam); 10975 TemplateTemplateParmDecl *SecondTTPD = 10976 cast<TemplateTemplateParmDecl>(SecondParam); 10977 10978 TemplateParameterList *FirstTPL = 10979 FirstTTPD->getTemplateParameters(); 10980 TemplateParameterList *SecondTPL = 10981 SecondTTPD->getTemplateParameters(); 10982 10983 if (ComputeTemplateParameterListODRHash(FirstTPL) != 10984 ComputeTemplateParameterListODRHash(SecondTPL)) { 10985 ODRDiagDeclError(FirstRecord, FirstModule, 10986 FirstTemplate->getLocation(), 10987 FirstTemplate->getSourceRange(), 10988 FunctionTemplateParameterDifferentType) 10989 << FirstTemplate << (i + 1); 10990 ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(), 10991 SecondTemplate->getSourceRange(), 10992 FunctionTemplateParameterDifferentType) 10993 << SecondTemplate << (i + 1); 10994 ParameterMismatch = true; 10995 break; 10996 } 10997 10998 bool HasFirstDefaultArgument = 10999 FirstTTPD->hasDefaultArgument() && 11000 !FirstTTPD->defaultArgumentWasInherited(); 11001 bool HasSecondDefaultArgument = 11002 SecondTTPD->hasDefaultArgument() && 11003 !SecondTTPD->defaultArgumentWasInherited(); 11004 if (HasFirstDefaultArgument != HasSecondDefaultArgument) { 11005 ODRDiagDeclError(FirstRecord, FirstModule, 11006 FirstTemplate->getLocation(), 11007 FirstTemplate->getSourceRange(), 11008 FunctionTemplateParameterSingleDefaultArgument) 11009 << FirstTemplate << (i + 1) << HasFirstDefaultArgument; 11010 ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(), 11011 SecondTemplate->getSourceRange(), 11012 FunctionTemplateParameterSingleDefaultArgument) 11013 << SecondTemplate << (i + 1) << HasSecondDefaultArgument; 11014 ParameterMismatch = true; 11015 break; 11016 } 11017 11018 if (HasFirstDefaultArgument && HasSecondDefaultArgument) { 11019 TemplateArgument FirstTA = 11020 FirstTTPD->getDefaultArgument().getArgument(); 11021 TemplateArgument SecondTA = 11022 SecondTTPD->getDefaultArgument().getArgument(); 11023 if (ComputeTemplateArgumentODRHash(FirstTA) != 11024 ComputeTemplateArgumentODRHash(SecondTA)) { 11025 ODRDiagDeclError( 11026 FirstRecord, FirstModule, FirstTemplate->getLocation(), 11027 FirstTemplate->getSourceRange(), 11028 FunctionTemplateParameterDifferentDefaultArgument) 11029 << FirstTemplate << (i + 1) << FirstTA; 11030 ODRDiagDeclNote( 11031 SecondModule, SecondTemplate->getLocation(), 11032 SecondTemplate->getSourceRange(), 11033 FunctionTemplateParameterDifferentDefaultArgument) 11034 << SecondTemplate << (i + 1) << SecondTA; 11035 ParameterMismatch = true; 11036 break; 11037 } 11038 } 11039 11040 if (FirstTTPD->isParameterPack() != 11041 SecondTTPD->isParameterPack()) { 11042 ODRDiagDeclError(FirstRecord, FirstModule, 11043 FirstTemplate->getLocation(), 11044 FirstTemplate->getSourceRange(), 11045 FunctionTemplatePackParameter) 11046 << FirstTemplate << (i + 1) << FirstTTPD->isParameterPack(); 11047 ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(), 11048 SecondTemplate->getSourceRange(), 11049 FunctionTemplatePackParameter) 11050 << SecondTemplate << (i + 1) << SecondTTPD->isParameterPack(); 11051 ParameterMismatch = true; 11052 break; 11053 } 11054 } 11055 11056 if (isa<NonTypeTemplateParmDecl>(FirstParam) && 11057 isa<NonTypeTemplateParmDecl>(SecondParam)) { 11058 NonTypeTemplateParmDecl *FirstNTTPD = 11059 cast<NonTypeTemplateParmDecl>(FirstParam); 11060 NonTypeTemplateParmDecl *SecondNTTPD = 11061 cast<NonTypeTemplateParmDecl>(SecondParam); 11062 11063 QualType FirstType = FirstNTTPD->getType(); 11064 QualType SecondType = SecondNTTPD->getType(); 11065 if (ComputeQualTypeODRHash(FirstType) != 11066 ComputeQualTypeODRHash(SecondType)) { 11067 ODRDiagDeclError(FirstRecord, FirstModule, 11068 FirstTemplate->getLocation(), 11069 FirstTemplate->getSourceRange(), 11070 FunctionTemplateParameterDifferentType) 11071 << FirstTemplate << (i + 1); 11072 ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(), 11073 SecondTemplate->getSourceRange(), 11074 FunctionTemplateParameterDifferentType) 11075 << SecondTemplate << (i + 1); 11076 ParameterMismatch = true; 11077 break; 11078 } 11079 11080 bool HasFirstDefaultArgument = 11081 FirstNTTPD->hasDefaultArgument() && 11082 !FirstNTTPD->defaultArgumentWasInherited(); 11083 bool HasSecondDefaultArgument = 11084 SecondNTTPD->hasDefaultArgument() && 11085 !SecondNTTPD->defaultArgumentWasInherited(); 11086 if (HasFirstDefaultArgument != HasSecondDefaultArgument) { 11087 ODRDiagDeclError(FirstRecord, FirstModule, 11088 FirstTemplate->getLocation(), 11089 FirstTemplate->getSourceRange(), 11090 FunctionTemplateParameterSingleDefaultArgument) 11091 << FirstTemplate << (i + 1) << HasFirstDefaultArgument; 11092 ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(), 11093 SecondTemplate->getSourceRange(), 11094 FunctionTemplateParameterSingleDefaultArgument) 11095 << SecondTemplate << (i + 1) << HasSecondDefaultArgument; 11096 ParameterMismatch = true; 11097 break; 11098 } 11099 11100 if (HasFirstDefaultArgument && HasSecondDefaultArgument) { 11101 Expr *FirstDefaultArgument = FirstNTTPD->getDefaultArgument(); 11102 Expr *SecondDefaultArgument = SecondNTTPD->getDefaultArgument(); 11103 if (ComputeODRHash(FirstDefaultArgument) != 11104 ComputeODRHash(SecondDefaultArgument)) { 11105 ODRDiagDeclError( 11106 FirstRecord, FirstModule, FirstTemplate->getLocation(), 11107 FirstTemplate->getSourceRange(), 11108 FunctionTemplateParameterDifferentDefaultArgument) 11109 << FirstTemplate << (i + 1) << FirstDefaultArgument; 11110 ODRDiagDeclNote( 11111 SecondModule, SecondTemplate->getLocation(), 11112 SecondTemplate->getSourceRange(), 11113 FunctionTemplateParameterDifferentDefaultArgument) 11114 << SecondTemplate << (i + 1) << SecondDefaultArgument; 11115 ParameterMismatch = true; 11116 break; 11117 } 11118 } 11119 11120 if (FirstNTTPD->isParameterPack() != 11121 SecondNTTPD->isParameterPack()) { 11122 ODRDiagDeclError(FirstRecord, FirstModule, 11123 FirstTemplate->getLocation(), 11124 FirstTemplate->getSourceRange(), 11125 FunctionTemplatePackParameter) 11126 << FirstTemplate << (i + 1) << FirstNTTPD->isParameterPack(); 11127 ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(), 11128 SecondTemplate->getSourceRange(), 11129 FunctionTemplatePackParameter) 11130 << SecondTemplate << (i + 1) 11131 << SecondNTTPD->isParameterPack(); 11132 ParameterMismatch = true; 11133 break; 11134 } 11135 } 11136 } 11137 11138 if (ParameterMismatch) { 11139 Diagnosed = true; 11140 break; 11141 } 11142 11143 break; 11144 } 11145 } 11146 11147 if (Diagnosed) 11148 continue; 11149 11150 Diag(FirstDecl->getLocation(), 11151 diag::err_module_odr_violation_mismatch_decl_unknown) 11152 << FirstRecord << FirstModule.empty() << FirstModule << FirstDiffType 11153 << FirstDecl->getSourceRange(); 11154 Diag(SecondDecl->getLocation(), 11155 diag::note_module_odr_violation_mismatch_decl_unknown) 11156 << SecondModule << FirstDiffType << SecondDecl->getSourceRange(); 11157 Diagnosed = true; 11158 } 11159 11160 if (!Diagnosed) { 11161 // All definitions are updates to the same declaration. This happens if a 11162 // module instantiates the declaration of a class template specialization 11163 // and two or more other modules instantiate its definition. 11164 // 11165 // FIXME: Indicate which modules had instantiations of this definition. 11166 // FIXME: How can this even happen? 11167 Diag(Merge.first->getLocation(), 11168 diag::err_module_odr_violation_different_instantiations) 11169 << Merge.first; 11170 } 11171 } 11172 11173 // Issue ODR failures diagnostics for functions. 11174 for (auto &Merge : FunctionOdrMergeFailures) { 11175 enum ODRFunctionDifference { 11176 ReturnType, 11177 ParameterName, 11178 ParameterType, 11179 ParameterSingleDefaultArgument, 11180 ParameterDifferentDefaultArgument, 11181 FunctionBody, 11182 }; 11183 11184 FunctionDecl *FirstFunction = Merge.first; 11185 std::string FirstModule = getOwningModuleNameForDiagnostic(FirstFunction); 11186 11187 bool Diagnosed = false; 11188 for (auto &SecondFunction : Merge.second) { 11189 11190 if (FirstFunction == SecondFunction) 11191 continue; 11192 11193 std::string SecondModule = 11194 getOwningModuleNameForDiagnostic(SecondFunction); 11195 11196 auto ODRDiagError = [FirstFunction, &FirstModule, 11197 this](SourceLocation Loc, SourceRange Range, 11198 ODRFunctionDifference DiffType) { 11199 return Diag(Loc, diag::err_module_odr_violation_function) 11200 << FirstFunction << FirstModule.empty() << FirstModule << Range 11201 << DiffType; 11202 }; 11203 auto ODRDiagNote = [&SecondModule, this](SourceLocation Loc, 11204 SourceRange Range, 11205 ODRFunctionDifference DiffType) { 11206 return Diag(Loc, diag::note_module_odr_violation_function) 11207 << SecondModule << Range << DiffType; 11208 }; 11209 11210 if (ComputeQualTypeODRHash(FirstFunction->getReturnType()) != 11211 ComputeQualTypeODRHash(SecondFunction->getReturnType())) { 11212 ODRDiagError(FirstFunction->getReturnTypeSourceRange().getBegin(), 11213 FirstFunction->getReturnTypeSourceRange(), ReturnType) 11214 << FirstFunction->getReturnType(); 11215 ODRDiagNote(SecondFunction->getReturnTypeSourceRange().getBegin(), 11216 SecondFunction->getReturnTypeSourceRange(), ReturnType) 11217 << SecondFunction->getReturnType(); 11218 Diagnosed = true; 11219 break; 11220 } 11221 11222 assert(FirstFunction->param_size() == SecondFunction->param_size() && 11223 "Merged functions with different number of parameters"); 11224 11225 auto ParamSize = FirstFunction->param_size(); 11226 bool ParameterMismatch = false; 11227 for (unsigned I = 0; I < ParamSize; ++I) { 11228 auto *FirstParam = FirstFunction->getParamDecl(I); 11229 auto *SecondParam = SecondFunction->getParamDecl(I); 11230 11231 assert(getContext().hasSameType(FirstParam->getType(), 11232 SecondParam->getType()) && 11233 "Merged function has different parameter types."); 11234 11235 if (FirstParam->getDeclName() != SecondParam->getDeclName()) { 11236 ODRDiagError(FirstParam->getLocation(), FirstParam->getSourceRange(), 11237 ParameterName) 11238 << I + 1 << FirstParam->getDeclName(); 11239 ODRDiagNote(SecondParam->getLocation(), SecondParam->getSourceRange(), 11240 ParameterName) 11241 << I + 1 << SecondParam->getDeclName(); 11242 ParameterMismatch = true; 11243 break; 11244 }; 11245 11246 QualType FirstParamType = FirstParam->getType(); 11247 QualType SecondParamType = SecondParam->getType(); 11248 if (FirstParamType != SecondParamType && 11249 ComputeQualTypeODRHash(FirstParamType) != 11250 ComputeQualTypeODRHash(SecondParamType)) { 11251 if (const DecayedType *ParamDecayedType = 11252 FirstParamType->getAs<DecayedType>()) { 11253 ODRDiagError(FirstParam->getLocation(), 11254 FirstParam->getSourceRange(), ParameterType) 11255 << (I + 1) << FirstParamType << true 11256 << ParamDecayedType->getOriginalType(); 11257 } else { 11258 ODRDiagError(FirstParam->getLocation(), 11259 FirstParam->getSourceRange(), ParameterType) 11260 << (I + 1) << FirstParamType << false; 11261 } 11262 11263 if (const DecayedType *ParamDecayedType = 11264 SecondParamType->getAs<DecayedType>()) { 11265 ODRDiagNote(SecondParam->getLocation(), 11266 SecondParam->getSourceRange(), ParameterType) 11267 << (I + 1) << SecondParamType << true 11268 << ParamDecayedType->getOriginalType(); 11269 } else { 11270 ODRDiagNote(SecondParam->getLocation(), 11271 SecondParam->getSourceRange(), ParameterType) 11272 << (I + 1) << SecondParamType << false; 11273 } 11274 ParameterMismatch = true; 11275 break; 11276 } 11277 11278 const Expr *FirstInit = FirstParam->getInit(); 11279 const Expr *SecondInit = SecondParam->getInit(); 11280 if ((FirstInit == nullptr) != (SecondInit == nullptr)) { 11281 ODRDiagError(FirstParam->getLocation(), FirstParam->getSourceRange(), 11282 ParameterSingleDefaultArgument) 11283 << (I + 1) << (FirstInit == nullptr) 11284 << (FirstInit ? FirstInit->getSourceRange() : SourceRange()); 11285 ODRDiagNote(SecondParam->getLocation(), SecondParam->getSourceRange(), 11286 ParameterSingleDefaultArgument) 11287 << (I + 1) << (SecondInit == nullptr) 11288 << (SecondInit ? SecondInit->getSourceRange() : SourceRange()); 11289 ParameterMismatch = true; 11290 break; 11291 } 11292 11293 if (FirstInit && SecondInit && 11294 ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) { 11295 ODRDiagError(FirstParam->getLocation(), FirstParam->getSourceRange(), 11296 ParameterDifferentDefaultArgument) 11297 << (I + 1) << FirstInit->getSourceRange(); 11298 ODRDiagNote(SecondParam->getLocation(), SecondParam->getSourceRange(), 11299 ParameterDifferentDefaultArgument) 11300 << (I + 1) << SecondInit->getSourceRange(); 11301 ParameterMismatch = true; 11302 break; 11303 } 11304 11305 assert(ComputeSubDeclODRHash(FirstParam) == 11306 ComputeSubDeclODRHash(SecondParam) && 11307 "Undiagnosed parameter difference."); 11308 } 11309 11310 if (ParameterMismatch) { 11311 Diagnosed = true; 11312 break; 11313 } 11314 11315 // If no error has been generated before now, assume the problem is in 11316 // the body and generate a message. 11317 ODRDiagError(FirstFunction->getLocation(), 11318 FirstFunction->getSourceRange(), FunctionBody); 11319 ODRDiagNote(SecondFunction->getLocation(), 11320 SecondFunction->getSourceRange(), FunctionBody); 11321 Diagnosed = true; 11322 break; 11323 } 11324 (void)Diagnosed; 11325 assert(Diagnosed && "Unable to emit ODR diagnostic."); 11326 } 11327 11328 // Issue ODR failures diagnostics for enums. 11329 for (auto &Merge : EnumOdrMergeFailures) { 11330 enum ODREnumDifference { 11331 SingleScopedEnum, 11332 EnumTagKeywordMismatch, 11333 SingleSpecifiedType, 11334 DifferentSpecifiedTypes, 11335 DifferentNumberEnumConstants, 11336 EnumConstantName, 11337 EnumConstantSingleInitilizer, 11338 EnumConstantDifferentInitilizer, 11339 }; 11340 11341 // If we've already pointed out a specific problem with this enum, don't 11342 // bother issuing a general "something's different" diagnostic. 11343 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second) 11344 continue; 11345 11346 EnumDecl *FirstEnum = Merge.first; 11347 std::string FirstModule = getOwningModuleNameForDiagnostic(FirstEnum); 11348 11349 using DeclHashes = 11350 llvm::SmallVector<std::pair<EnumConstantDecl *, unsigned>, 4>; 11351 auto PopulateHashes = [&ComputeSubDeclODRHash, FirstEnum]( 11352 DeclHashes &Hashes, EnumDecl *Enum) { 11353 for (auto *D : Enum->decls()) { 11354 // Due to decl merging, the first EnumDecl is the parent of 11355 // Decls in both records. 11356 if (!ODRHash::isDeclToBeProcessed(D, FirstEnum)) 11357 continue; 11358 assert(isa<EnumConstantDecl>(D) && "Unexpected Decl kind"); 11359 Hashes.emplace_back(cast<EnumConstantDecl>(D), 11360 ComputeSubDeclODRHash(D)); 11361 } 11362 }; 11363 DeclHashes FirstHashes; 11364 PopulateHashes(FirstHashes, FirstEnum); 11365 bool Diagnosed = false; 11366 for (auto &SecondEnum : Merge.second) { 11367 11368 if (FirstEnum == SecondEnum) 11369 continue; 11370 11371 std::string SecondModule = 11372 getOwningModuleNameForDiagnostic(SecondEnum); 11373 11374 auto ODRDiagError = [FirstEnum, &FirstModule, 11375 this](SourceLocation Loc, SourceRange Range, 11376 ODREnumDifference DiffType) { 11377 return Diag(Loc, diag::err_module_odr_violation_enum) 11378 << FirstEnum << FirstModule.empty() << FirstModule << Range 11379 << DiffType; 11380 }; 11381 auto ODRDiagNote = [&SecondModule, this](SourceLocation Loc, 11382 SourceRange Range, 11383 ODREnumDifference DiffType) { 11384 return Diag(Loc, diag::note_module_odr_violation_enum) 11385 << SecondModule << Range << DiffType; 11386 }; 11387 11388 if (FirstEnum->isScoped() != SecondEnum->isScoped()) { 11389 ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(), 11390 SingleScopedEnum) 11391 << FirstEnum->isScoped(); 11392 ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(), 11393 SingleScopedEnum) 11394 << SecondEnum->isScoped(); 11395 Diagnosed = true; 11396 continue; 11397 } 11398 11399 if (FirstEnum->isScoped() && SecondEnum->isScoped()) { 11400 if (FirstEnum->isScopedUsingClassTag() != 11401 SecondEnum->isScopedUsingClassTag()) { 11402 ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(), 11403 EnumTagKeywordMismatch) 11404 << FirstEnum->isScopedUsingClassTag(); 11405 ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(), 11406 EnumTagKeywordMismatch) 11407 << SecondEnum->isScopedUsingClassTag(); 11408 Diagnosed = true; 11409 continue; 11410 } 11411 } 11412 11413 QualType FirstUnderlyingType = 11414 FirstEnum->getIntegerTypeSourceInfo() 11415 ? FirstEnum->getIntegerTypeSourceInfo()->getType() 11416 : QualType(); 11417 QualType SecondUnderlyingType = 11418 SecondEnum->getIntegerTypeSourceInfo() 11419 ? SecondEnum->getIntegerTypeSourceInfo()->getType() 11420 : QualType(); 11421 if (FirstUnderlyingType.isNull() != SecondUnderlyingType.isNull()) { 11422 ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(), 11423 SingleSpecifiedType) 11424 << !FirstUnderlyingType.isNull(); 11425 ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(), 11426 SingleSpecifiedType) 11427 << !SecondUnderlyingType.isNull(); 11428 Diagnosed = true; 11429 continue; 11430 } 11431 11432 if (!FirstUnderlyingType.isNull() && !SecondUnderlyingType.isNull()) { 11433 if (ComputeQualTypeODRHash(FirstUnderlyingType) != 11434 ComputeQualTypeODRHash(SecondUnderlyingType)) { 11435 ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(), 11436 DifferentSpecifiedTypes) 11437 << FirstUnderlyingType; 11438 ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(), 11439 DifferentSpecifiedTypes) 11440 << SecondUnderlyingType; 11441 Diagnosed = true; 11442 continue; 11443 } 11444 } 11445 11446 DeclHashes SecondHashes; 11447 PopulateHashes(SecondHashes, SecondEnum); 11448 11449 if (FirstHashes.size() != SecondHashes.size()) { 11450 ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(), 11451 DifferentNumberEnumConstants) 11452 << (int)FirstHashes.size(); 11453 ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(), 11454 DifferentNumberEnumConstants) 11455 << (int)SecondHashes.size(); 11456 Diagnosed = true; 11457 continue; 11458 } 11459 11460 for (unsigned I = 0; I < FirstHashes.size(); ++I) { 11461 if (FirstHashes[I].second == SecondHashes[I].second) 11462 continue; 11463 const EnumConstantDecl *FirstEnumConstant = FirstHashes[I].first; 11464 const EnumConstantDecl *SecondEnumConstant = SecondHashes[I].first; 11465 11466 if (FirstEnumConstant->getDeclName() != 11467 SecondEnumConstant->getDeclName()) { 11468 11469 ODRDiagError(FirstEnumConstant->getLocation(), 11470 FirstEnumConstant->getSourceRange(), EnumConstantName) 11471 << I + 1 << FirstEnumConstant; 11472 ODRDiagNote(SecondEnumConstant->getLocation(), 11473 SecondEnumConstant->getSourceRange(), EnumConstantName) 11474 << I + 1 << SecondEnumConstant; 11475 Diagnosed = true; 11476 break; 11477 } 11478 11479 const Expr *FirstInit = FirstEnumConstant->getInitExpr(); 11480 const Expr *SecondInit = SecondEnumConstant->getInitExpr(); 11481 if (!FirstInit && !SecondInit) 11482 continue; 11483 11484 if (!FirstInit || !SecondInit) { 11485 ODRDiagError(FirstEnumConstant->getLocation(), 11486 FirstEnumConstant->getSourceRange(), 11487 EnumConstantSingleInitilizer) 11488 << I + 1 << FirstEnumConstant << (FirstInit != nullptr); 11489 ODRDiagNote(SecondEnumConstant->getLocation(), 11490 SecondEnumConstant->getSourceRange(), 11491 EnumConstantSingleInitilizer) 11492 << I + 1 << SecondEnumConstant << (SecondInit != nullptr); 11493 Diagnosed = true; 11494 break; 11495 } 11496 11497 if (ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) { 11498 ODRDiagError(FirstEnumConstant->getLocation(), 11499 FirstEnumConstant->getSourceRange(), 11500 EnumConstantDifferentInitilizer) 11501 << I + 1 << FirstEnumConstant; 11502 ODRDiagNote(SecondEnumConstant->getLocation(), 11503 SecondEnumConstant->getSourceRange(), 11504 EnumConstantDifferentInitilizer) 11505 << I + 1 << SecondEnumConstant; 11506 Diagnosed = true; 11507 break; 11508 } 11509 } 11510 } 11511 11512 (void)Diagnosed; 11513 assert(Diagnosed && "Unable to emit ODR diagnostic."); 11514 } 11515 } 11516 11517 void ASTReader::StartedDeserializing() { 11518 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get()) 11519 ReadTimer->startTimer(); 11520 } 11521 11522 void ASTReader::FinishedDeserializing() { 11523 assert(NumCurrentElementsDeserializing && 11524 "FinishedDeserializing not paired with StartedDeserializing"); 11525 if (NumCurrentElementsDeserializing == 1) { 11526 // We decrease NumCurrentElementsDeserializing only after pending actions 11527 // are finished, to avoid recursively re-calling finishPendingActions(). 11528 finishPendingActions(); 11529 } 11530 --NumCurrentElementsDeserializing; 11531 11532 if (NumCurrentElementsDeserializing == 0) { 11533 // Propagate exception specification and deduced type updates along 11534 // redeclaration chains. 11535 // 11536 // We do this now rather than in finishPendingActions because we want to 11537 // be able to walk the complete redeclaration chains of the updated decls. 11538 while (!PendingExceptionSpecUpdates.empty() || 11539 !PendingDeducedTypeUpdates.empty()) { 11540 auto ESUpdates = std::move(PendingExceptionSpecUpdates); 11541 PendingExceptionSpecUpdates.clear(); 11542 for (auto Update : ESUpdates) { 11543 ProcessingUpdatesRAIIObj ProcessingUpdates(*this); 11544 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>(); 11545 auto ESI = FPT->getExtProtoInfo().ExceptionSpec; 11546 if (auto *Listener = getContext().getASTMutationListener()) 11547 Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second)); 11548 for (auto *Redecl : Update.second->redecls()) 11549 getContext().adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI); 11550 } 11551 11552 auto DTUpdates = std::move(PendingDeducedTypeUpdates); 11553 PendingDeducedTypeUpdates.clear(); 11554 for (auto Update : DTUpdates) { 11555 ProcessingUpdatesRAIIObj ProcessingUpdates(*this); 11556 // FIXME: If the return type is already deduced, check that it matches. 11557 getContext().adjustDeducedFunctionResultType(Update.first, 11558 Update.second); 11559 } 11560 } 11561 11562 if (ReadTimer) 11563 ReadTimer->stopTimer(); 11564 11565 diagnoseOdrViolations(); 11566 11567 // We are not in recursive loading, so it's safe to pass the "interesting" 11568 // decls to the consumer. 11569 if (Consumer) 11570 PassInterestingDeclsToConsumer(); 11571 } 11572 } 11573 11574 void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) { 11575 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) { 11576 // Remove any fake results before adding any real ones. 11577 auto It = PendingFakeLookupResults.find(II); 11578 if (It != PendingFakeLookupResults.end()) { 11579 for (auto *ND : It->second) 11580 SemaObj->IdResolver.RemoveDecl(ND); 11581 // FIXME: this works around module+PCH performance issue. 11582 // Rather than erase the result from the map, which is O(n), just clear 11583 // the vector of NamedDecls. 11584 It->second.clear(); 11585 } 11586 } 11587 11588 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) { 11589 SemaObj->TUScope->AddDecl(D); 11590 } else if (SemaObj->TUScope) { 11591 // Adding the decl to IdResolver may have failed because it was already in 11592 // (even though it was not added in scope). If it is already in, make sure 11593 // it gets in the scope as well. 11594 if (std::find(SemaObj->IdResolver.begin(Name), 11595 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end()) 11596 SemaObj->TUScope->AddDecl(D); 11597 } 11598 } 11599 11600 ASTReader::ASTReader(Preprocessor &PP, InMemoryModuleCache &ModuleCache, 11601 ASTContext *Context, 11602 const PCHContainerReader &PCHContainerRdr, 11603 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions, 11604 StringRef isysroot, bool DisableValidation, 11605 bool AllowASTWithCompilerErrors, 11606 bool AllowConfigurationMismatch, bool ValidateSystemInputs, 11607 bool ValidateASTInputFilesContent, bool UseGlobalIndex, 11608 std::unique_ptr<llvm::Timer> ReadTimer) 11609 : Listener(DisableValidation 11610 ? cast<ASTReaderListener>(new SimpleASTReaderListener(PP)) 11611 : cast<ASTReaderListener>(new PCHValidator(PP, *this))), 11612 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()), 11613 PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()), PP(PP), 11614 ContextObj(Context), ModuleMgr(PP.getFileManager(), ModuleCache, 11615 PCHContainerRdr, PP.getHeaderSearchInfo()), 11616 DummyIdResolver(PP), ReadTimer(std::move(ReadTimer)), isysroot(isysroot), 11617 DisableValidation(DisableValidation), 11618 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors), 11619 AllowConfigurationMismatch(AllowConfigurationMismatch), 11620 ValidateSystemInputs(ValidateSystemInputs), 11621 ValidateASTInputFilesContent(ValidateASTInputFilesContent), 11622 UseGlobalIndex(UseGlobalIndex), CurrSwitchCaseStmts(&SwitchCaseStmts) { 11623 SourceMgr.setExternalSLocEntrySource(this); 11624 11625 for (const auto &Ext : Extensions) { 11626 auto BlockName = Ext->getExtensionMetadata().BlockName; 11627 auto Known = ModuleFileExtensions.find(BlockName); 11628 if (Known != ModuleFileExtensions.end()) { 11629 Diags.Report(diag::warn_duplicate_module_file_extension) 11630 << BlockName; 11631 continue; 11632 } 11633 11634 ModuleFileExtensions.insert({BlockName, Ext}); 11635 } 11636 } 11637 11638 ASTReader::~ASTReader() { 11639 if (OwnsDeserializationListener) 11640 delete DeserializationListener; 11641 } 11642 11643 IdentifierResolver &ASTReader::getIdResolver() { 11644 return SemaObj ? SemaObj->IdResolver : DummyIdResolver; 11645 } 11646 11647 Expected<unsigned> ASTRecordReader::readRecord(llvm::BitstreamCursor &Cursor, 11648 unsigned AbbrevID) { 11649 Idx = 0; 11650 Record.clear(); 11651 return Cursor.readRecord(AbbrevID, Record); 11652 } 11653 //===----------------------------------------------------------------------===// 11654 //// OMPClauseReader implementation 11655 ////===----------------------------------------------------------------------===// 11656 11657 // This has to be in namespace clang because it's friended by all 11658 // of the OMP clauses. 11659 namespace clang { 11660 11661 class OMPClauseReader : public OMPClauseVisitor<OMPClauseReader> { 11662 ASTRecordReader &Record; 11663 ASTContext &Context; 11664 11665 public: 11666 OMPClauseReader(ASTRecordReader &Record) 11667 : Record(Record), Context(Record.getContext()) {} 11668 #define GEN_CLANG_CLAUSE_CLASS 11669 #define CLAUSE_CLASS(Enum, Str, Class) void Visit##Class(Class *C); 11670 #include "llvm/Frontend/OpenMP/OMP.inc" 11671 OMPClause *readClause(); 11672 void VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C); 11673 void VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C); 11674 }; 11675 11676 } // end namespace clang 11677 11678 OMPClause *ASTRecordReader::readOMPClause() { 11679 return OMPClauseReader(*this).readClause(); 11680 } 11681 11682 OMPClause *OMPClauseReader::readClause() { 11683 OMPClause *C = nullptr; 11684 switch (llvm::omp::Clause(Record.readInt())) { 11685 case llvm::omp::OMPC_if: 11686 C = new (Context) OMPIfClause(); 11687 break; 11688 case llvm::omp::OMPC_final: 11689 C = new (Context) OMPFinalClause(); 11690 break; 11691 case llvm::omp::OMPC_num_threads: 11692 C = new (Context) OMPNumThreadsClause(); 11693 break; 11694 case llvm::omp::OMPC_safelen: 11695 C = new (Context) OMPSafelenClause(); 11696 break; 11697 case llvm::omp::OMPC_simdlen: 11698 C = new (Context) OMPSimdlenClause(); 11699 break; 11700 case llvm::omp::OMPC_allocator: 11701 C = new (Context) OMPAllocatorClause(); 11702 break; 11703 case llvm::omp::OMPC_collapse: 11704 C = new (Context) OMPCollapseClause(); 11705 break; 11706 case llvm::omp::OMPC_default: 11707 C = new (Context) OMPDefaultClause(); 11708 break; 11709 case llvm::omp::OMPC_proc_bind: 11710 C = new (Context) OMPProcBindClause(); 11711 break; 11712 case llvm::omp::OMPC_schedule: 11713 C = new (Context) OMPScheduleClause(); 11714 break; 11715 case llvm::omp::OMPC_ordered: 11716 C = OMPOrderedClause::CreateEmpty(Context, Record.readInt()); 11717 break; 11718 case llvm::omp::OMPC_nowait: 11719 C = new (Context) OMPNowaitClause(); 11720 break; 11721 case llvm::omp::OMPC_untied: 11722 C = new (Context) OMPUntiedClause(); 11723 break; 11724 case llvm::omp::OMPC_mergeable: 11725 C = new (Context) OMPMergeableClause(); 11726 break; 11727 case llvm::omp::OMPC_read: 11728 C = new (Context) OMPReadClause(); 11729 break; 11730 case llvm::omp::OMPC_write: 11731 C = new (Context) OMPWriteClause(); 11732 break; 11733 case llvm::omp::OMPC_update: 11734 C = OMPUpdateClause::CreateEmpty(Context, Record.readInt()); 11735 break; 11736 case llvm::omp::OMPC_capture: 11737 C = new (Context) OMPCaptureClause(); 11738 break; 11739 case llvm::omp::OMPC_seq_cst: 11740 C = new (Context) OMPSeqCstClause(); 11741 break; 11742 case llvm::omp::OMPC_acq_rel: 11743 C = new (Context) OMPAcqRelClause(); 11744 break; 11745 case llvm::omp::OMPC_acquire: 11746 C = new (Context) OMPAcquireClause(); 11747 break; 11748 case llvm::omp::OMPC_release: 11749 C = new (Context) OMPReleaseClause(); 11750 break; 11751 case llvm::omp::OMPC_relaxed: 11752 C = new (Context) OMPRelaxedClause(); 11753 break; 11754 case llvm::omp::OMPC_threads: 11755 C = new (Context) OMPThreadsClause(); 11756 break; 11757 case llvm::omp::OMPC_simd: 11758 C = new (Context) OMPSIMDClause(); 11759 break; 11760 case llvm::omp::OMPC_nogroup: 11761 C = new (Context) OMPNogroupClause(); 11762 break; 11763 case llvm::omp::OMPC_unified_address: 11764 C = new (Context) OMPUnifiedAddressClause(); 11765 break; 11766 case llvm::omp::OMPC_unified_shared_memory: 11767 C = new (Context) OMPUnifiedSharedMemoryClause(); 11768 break; 11769 case llvm::omp::OMPC_reverse_offload: 11770 C = new (Context) OMPReverseOffloadClause(); 11771 break; 11772 case llvm::omp::OMPC_dynamic_allocators: 11773 C = new (Context) OMPDynamicAllocatorsClause(); 11774 break; 11775 case llvm::omp::OMPC_atomic_default_mem_order: 11776 C = new (Context) OMPAtomicDefaultMemOrderClause(); 11777 break; 11778 case llvm::omp::OMPC_private: 11779 C = OMPPrivateClause::CreateEmpty(Context, Record.readInt()); 11780 break; 11781 case llvm::omp::OMPC_firstprivate: 11782 C = OMPFirstprivateClause::CreateEmpty(Context, Record.readInt()); 11783 break; 11784 case llvm::omp::OMPC_lastprivate: 11785 C = OMPLastprivateClause::CreateEmpty(Context, Record.readInt()); 11786 break; 11787 case llvm::omp::OMPC_shared: 11788 C = OMPSharedClause::CreateEmpty(Context, Record.readInt()); 11789 break; 11790 case llvm::omp::OMPC_reduction: { 11791 unsigned N = Record.readInt(); 11792 auto Modifier = Record.readEnum<OpenMPReductionClauseModifier>(); 11793 C = OMPReductionClause::CreateEmpty(Context, N, Modifier); 11794 break; 11795 } 11796 case llvm::omp::OMPC_task_reduction: 11797 C = OMPTaskReductionClause::CreateEmpty(Context, Record.readInt()); 11798 break; 11799 case llvm::omp::OMPC_in_reduction: 11800 C = OMPInReductionClause::CreateEmpty(Context, Record.readInt()); 11801 break; 11802 case llvm::omp::OMPC_linear: 11803 C = OMPLinearClause::CreateEmpty(Context, Record.readInt()); 11804 break; 11805 case llvm::omp::OMPC_aligned: 11806 C = OMPAlignedClause::CreateEmpty(Context, Record.readInt()); 11807 break; 11808 case llvm::omp::OMPC_copyin: 11809 C = OMPCopyinClause::CreateEmpty(Context, Record.readInt()); 11810 break; 11811 case llvm::omp::OMPC_copyprivate: 11812 C = OMPCopyprivateClause::CreateEmpty(Context, Record.readInt()); 11813 break; 11814 case llvm::omp::OMPC_flush: 11815 C = OMPFlushClause::CreateEmpty(Context, Record.readInt()); 11816 break; 11817 case llvm::omp::OMPC_depobj: 11818 C = OMPDepobjClause::CreateEmpty(Context); 11819 break; 11820 case llvm::omp::OMPC_depend: { 11821 unsigned NumVars = Record.readInt(); 11822 unsigned NumLoops = Record.readInt(); 11823 C = OMPDependClause::CreateEmpty(Context, NumVars, NumLoops); 11824 break; 11825 } 11826 case llvm::omp::OMPC_device: 11827 C = new (Context) OMPDeviceClause(); 11828 break; 11829 case llvm::omp::OMPC_map: { 11830 OMPMappableExprListSizeTy Sizes; 11831 Sizes.NumVars = Record.readInt(); 11832 Sizes.NumUniqueDeclarations = Record.readInt(); 11833 Sizes.NumComponentLists = Record.readInt(); 11834 Sizes.NumComponents = Record.readInt(); 11835 C = OMPMapClause::CreateEmpty(Context, Sizes); 11836 break; 11837 } 11838 case llvm::omp::OMPC_num_teams: 11839 C = new (Context) OMPNumTeamsClause(); 11840 break; 11841 case llvm::omp::OMPC_thread_limit: 11842 C = new (Context) OMPThreadLimitClause(); 11843 break; 11844 case llvm::omp::OMPC_priority: 11845 C = new (Context) OMPPriorityClause(); 11846 break; 11847 case llvm::omp::OMPC_grainsize: 11848 C = new (Context) OMPGrainsizeClause(); 11849 break; 11850 case llvm::omp::OMPC_num_tasks: 11851 C = new (Context) OMPNumTasksClause(); 11852 break; 11853 case llvm::omp::OMPC_hint: 11854 C = new (Context) OMPHintClause(); 11855 break; 11856 case llvm::omp::OMPC_dist_schedule: 11857 C = new (Context) OMPDistScheduleClause(); 11858 break; 11859 case llvm::omp::OMPC_defaultmap: 11860 C = new (Context) OMPDefaultmapClause(); 11861 break; 11862 case llvm::omp::OMPC_to: { 11863 OMPMappableExprListSizeTy Sizes; 11864 Sizes.NumVars = Record.readInt(); 11865 Sizes.NumUniqueDeclarations = Record.readInt(); 11866 Sizes.NumComponentLists = Record.readInt(); 11867 Sizes.NumComponents = Record.readInt(); 11868 C = OMPToClause::CreateEmpty(Context, Sizes); 11869 break; 11870 } 11871 case llvm::omp::OMPC_from: { 11872 OMPMappableExprListSizeTy Sizes; 11873 Sizes.NumVars = Record.readInt(); 11874 Sizes.NumUniqueDeclarations = Record.readInt(); 11875 Sizes.NumComponentLists = Record.readInt(); 11876 Sizes.NumComponents = Record.readInt(); 11877 C = OMPFromClause::CreateEmpty(Context, Sizes); 11878 break; 11879 } 11880 case llvm::omp::OMPC_use_device_ptr: { 11881 OMPMappableExprListSizeTy Sizes; 11882 Sizes.NumVars = Record.readInt(); 11883 Sizes.NumUniqueDeclarations = Record.readInt(); 11884 Sizes.NumComponentLists = Record.readInt(); 11885 Sizes.NumComponents = Record.readInt(); 11886 C = OMPUseDevicePtrClause::CreateEmpty(Context, Sizes); 11887 break; 11888 } 11889 case llvm::omp::OMPC_use_device_addr: { 11890 OMPMappableExprListSizeTy Sizes; 11891 Sizes.NumVars = Record.readInt(); 11892 Sizes.NumUniqueDeclarations = Record.readInt(); 11893 Sizes.NumComponentLists = Record.readInt(); 11894 Sizes.NumComponents = Record.readInt(); 11895 C = OMPUseDeviceAddrClause::CreateEmpty(Context, Sizes); 11896 break; 11897 } 11898 case llvm::omp::OMPC_is_device_ptr: { 11899 OMPMappableExprListSizeTy Sizes; 11900 Sizes.NumVars = Record.readInt(); 11901 Sizes.NumUniqueDeclarations = Record.readInt(); 11902 Sizes.NumComponentLists = Record.readInt(); 11903 Sizes.NumComponents = Record.readInt(); 11904 C = OMPIsDevicePtrClause::CreateEmpty(Context, Sizes); 11905 break; 11906 } 11907 case llvm::omp::OMPC_allocate: 11908 C = OMPAllocateClause::CreateEmpty(Context, Record.readInt()); 11909 break; 11910 case llvm::omp::OMPC_nontemporal: 11911 C = OMPNontemporalClause::CreateEmpty(Context, Record.readInt()); 11912 break; 11913 case llvm::omp::OMPC_inclusive: 11914 C = OMPInclusiveClause::CreateEmpty(Context, Record.readInt()); 11915 break; 11916 case llvm::omp::OMPC_exclusive: 11917 C = OMPExclusiveClause::CreateEmpty(Context, Record.readInt()); 11918 break; 11919 case llvm::omp::OMPC_order: 11920 C = new (Context) OMPOrderClause(); 11921 break; 11922 case llvm::omp::OMPC_destroy: 11923 C = new (Context) OMPDestroyClause(); 11924 break; 11925 case llvm::omp::OMPC_detach: 11926 C = new (Context) OMPDetachClause(); 11927 break; 11928 case llvm::omp::OMPC_uses_allocators: 11929 C = OMPUsesAllocatorsClause::CreateEmpty(Context, Record.readInt()); 11930 break; 11931 case llvm::omp::OMPC_affinity: 11932 C = OMPAffinityClause::CreateEmpty(Context, Record.readInt()); 11933 break; 11934 #define OMP_CLAUSE_NO_CLASS(Enum, Str) \ 11935 case llvm::omp::Enum: \ 11936 break; 11937 #include "llvm/Frontend/OpenMP/OMPKinds.def" 11938 default: 11939 break; 11940 } 11941 assert(C && "Unknown OMPClause type"); 11942 11943 Visit(C); 11944 C->setLocStart(Record.readSourceLocation()); 11945 C->setLocEnd(Record.readSourceLocation()); 11946 11947 return C; 11948 } 11949 11950 void OMPClauseReader::VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C) { 11951 C->setPreInitStmt(Record.readSubStmt(), 11952 static_cast<OpenMPDirectiveKind>(Record.readInt())); 11953 } 11954 11955 void OMPClauseReader::VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C) { 11956 VisitOMPClauseWithPreInit(C); 11957 C->setPostUpdateExpr(Record.readSubExpr()); 11958 } 11959 11960 void OMPClauseReader::VisitOMPIfClause(OMPIfClause *C) { 11961 VisitOMPClauseWithPreInit(C); 11962 C->setNameModifier(static_cast<OpenMPDirectiveKind>(Record.readInt())); 11963 C->setNameModifierLoc(Record.readSourceLocation()); 11964 C->setColonLoc(Record.readSourceLocation()); 11965 C->setCondition(Record.readSubExpr()); 11966 C->setLParenLoc(Record.readSourceLocation()); 11967 } 11968 11969 void OMPClauseReader::VisitOMPFinalClause(OMPFinalClause *C) { 11970 VisitOMPClauseWithPreInit(C); 11971 C->setCondition(Record.readSubExpr()); 11972 C->setLParenLoc(Record.readSourceLocation()); 11973 } 11974 11975 void OMPClauseReader::VisitOMPNumThreadsClause(OMPNumThreadsClause *C) { 11976 VisitOMPClauseWithPreInit(C); 11977 C->setNumThreads(Record.readSubExpr()); 11978 C->setLParenLoc(Record.readSourceLocation()); 11979 } 11980 11981 void OMPClauseReader::VisitOMPSafelenClause(OMPSafelenClause *C) { 11982 C->setSafelen(Record.readSubExpr()); 11983 C->setLParenLoc(Record.readSourceLocation()); 11984 } 11985 11986 void OMPClauseReader::VisitOMPSimdlenClause(OMPSimdlenClause *C) { 11987 C->setSimdlen(Record.readSubExpr()); 11988 C->setLParenLoc(Record.readSourceLocation()); 11989 } 11990 11991 void OMPClauseReader::VisitOMPAllocatorClause(OMPAllocatorClause *C) { 11992 C->setAllocator(Record.readExpr()); 11993 C->setLParenLoc(Record.readSourceLocation()); 11994 } 11995 11996 void OMPClauseReader::VisitOMPCollapseClause(OMPCollapseClause *C) { 11997 C->setNumForLoops(Record.readSubExpr()); 11998 C->setLParenLoc(Record.readSourceLocation()); 11999 } 12000 12001 void OMPClauseReader::VisitOMPDefaultClause(OMPDefaultClause *C) { 12002 C->setDefaultKind(static_cast<llvm::omp::DefaultKind>(Record.readInt())); 12003 C->setLParenLoc(Record.readSourceLocation()); 12004 C->setDefaultKindKwLoc(Record.readSourceLocation()); 12005 } 12006 12007 void OMPClauseReader::VisitOMPProcBindClause(OMPProcBindClause *C) { 12008 C->setProcBindKind(static_cast<llvm::omp::ProcBindKind>(Record.readInt())); 12009 C->setLParenLoc(Record.readSourceLocation()); 12010 C->setProcBindKindKwLoc(Record.readSourceLocation()); 12011 } 12012 12013 void OMPClauseReader::VisitOMPScheduleClause(OMPScheduleClause *C) { 12014 VisitOMPClauseWithPreInit(C); 12015 C->setScheduleKind( 12016 static_cast<OpenMPScheduleClauseKind>(Record.readInt())); 12017 C->setFirstScheduleModifier( 12018 static_cast<OpenMPScheduleClauseModifier>(Record.readInt())); 12019 C->setSecondScheduleModifier( 12020 static_cast<OpenMPScheduleClauseModifier>(Record.readInt())); 12021 C->setChunkSize(Record.readSubExpr()); 12022 C->setLParenLoc(Record.readSourceLocation()); 12023 C->setFirstScheduleModifierLoc(Record.readSourceLocation()); 12024 C->setSecondScheduleModifierLoc(Record.readSourceLocation()); 12025 C->setScheduleKindLoc(Record.readSourceLocation()); 12026 C->setCommaLoc(Record.readSourceLocation()); 12027 } 12028 12029 void OMPClauseReader::VisitOMPOrderedClause(OMPOrderedClause *C) { 12030 C->setNumForLoops(Record.readSubExpr()); 12031 for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I) 12032 C->setLoopNumIterations(I, Record.readSubExpr()); 12033 for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I) 12034 C->setLoopCounter(I, Record.readSubExpr()); 12035 C->setLParenLoc(Record.readSourceLocation()); 12036 } 12037 12038 void OMPClauseReader::VisitOMPDetachClause(OMPDetachClause *C) { 12039 C->setEventHandler(Record.readSubExpr()); 12040 C->setLParenLoc(Record.readSourceLocation()); 12041 } 12042 12043 void OMPClauseReader::VisitOMPNowaitClause(OMPNowaitClause *) {} 12044 12045 void OMPClauseReader::VisitOMPUntiedClause(OMPUntiedClause *) {} 12046 12047 void OMPClauseReader::VisitOMPMergeableClause(OMPMergeableClause *) {} 12048 12049 void OMPClauseReader::VisitOMPReadClause(OMPReadClause *) {} 12050 12051 void OMPClauseReader::VisitOMPWriteClause(OMPWriteClause *) {} 12052 12053 void OMPClauseReader::VisitOMPUpdateClause(OMPUpdateClause *C) { 12054 if (C->isExtended()) { 12055 C->setLParenLoc(Record.readSourceLocation()); 12056 C->setArgumentLoc(Record.readSourceLocation()); 12057 C->setDependencyKind(Record.readEnum<OpenMPDependClauseKind>()); 12058 } 12059 } 12060 12061 void OMPClauseReader::VisitOMPCaptureClause(OMPCaptureClause *) {} 12062 12063 void OMPClauseReader::VisitOMPSeqCstClause(OMPSeqCstClause *) {} 12064 12065 void OMPClauseReader::VisitOMPAcqRelClause(OMPAcqRelClause *) {} 12066 12067 void OMPClauseReader::VisitOMPAcquireClause(OMPAcquireClause *) {} 12068 12069 void OMPClauseReader::VisitOMPReleaseClause(OMPReleaseClause *) {} 12070 12071 void OMPClauseReader::VisitOMPRelaxedClause(OMPRelaxedClause *) {} 12072 12073 void OMPClauseReader::VisitOMPThreadsClause(OMPThreadsClause *) {} 12074 12075 void OMPClauseReader::VisitOMPSIMDClause(OMPSIMDClause *) {} 12076 12077 void OMPClauseReader::VisitOMPNogroupClause(OMPNogroupClause *) {} 12078 12079 void OMPClauseReader::VisitOMPDestroyClause(OMPDestroyClause *) {} 12080 12081 void OMPClauseReader::VisitOMPUnifiedAddressClause(OMPUnifiedAddressClause *) {} 12082 12083 void OMPClauseReader::VisitOMPUnifiedSharedMemoryClause( 12084 OMPUnifiedSharedMemoryClause *) {} 12085 12086 void OMPClauseReader::VisitOMPReverseOffloadClause(OMPReverseOffloadClause *) {} 12087 12088 void 12089 OMPClauseReader::VisitOMPDynamicAllocatorsClause(OMPDynamicAllocatorsClause *) { 12090 } 12091 12092 void OMPClauseReader::VisitOMPAtomicDefaultMemOrderClause( 12093 OMPAtomicDefaultMemOrderClause *C) { 12094 C->setAtomicDefaultMemOrderKind( 12095 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Record.readInt())); 12096 C->setLParenLoc(Record.readSourceLocation()); 12097 C->setAtomicDefaultMemOrderKindKwLoc(Record.readSourceLocation()); 12098 } 12099 12100 void OMPClauseReader::VisitOMPPrivateClause(OMPPrivateClause *C) { 12101 C->setLParenLoc(Record.readSourceLocation()); 12102 unsigned NumVars = C->varlist_size(); 12103 SmallVector<Expr *, 16> Vars; 12104 Vars.reserve(NumVars); 12105 for (unsigned i = 0; i != NumVars; ++i) 12106 Vars.push_back(Record.readSubExpr()); 12107 C->setVarRefs(Vars); 12108 Vars.clear(); 12109 for (unsigned i = 0; i != NumVars; ++i) 12110 Vars.push_back(Record.readSubExpr()); 12111 C->setPrivateCopies(Vars); 12112 } 12113 12114 void OMPClauseReader::VisitOMPFirstprivateClause(OMPFirstprivateClause *C) { 12115 VisitOMPClauseWithPreInit(C); 12116 C->setLParenLoc(Record.readSourceLocation()); 12117 unsigned NumVars = C->varlist_size(); 12118 SmallVector<Expr *, 16> Vars; 12119 Vars.reserve(NumVars); 12120 for (unsigned i = 0; i != NumVars; ++i) 12121 Vars.push_back(Record.readSubExpr()); 12122 C->setVarRefs(Vars); 12123 Vars.clear(); 12124 for (unsigned i = 0; i != NumVars; ++i) 12125 Vars.push_back(Record.readSubExpr()); 12126 C->setPrivateCopies(Vars); 12127 Vars.clear(); 12128 for (unsigned i = 0; i != NumVars; ++i) 12129 Vars.push_back(Record.readSubExpr()); 12130 C->setInits(Vars); 12131 } 12132 12133 void OMPClauseReader::VisitOMPLastprivateClause(OMPLastprivateClause *C) { 12134 VisitOMPClauseWithPostUpdate(C); 12135 C->setLParenLoc(Record.readSourceLocation()); 12136 C->setKind(Record.readEnum<OpenMPLastprivateModifier>()); 12137 C->setKindLoc(Record.readSourceLocation()); 12138 C->setColonLoc(Record.readSourceLocation()); 12139 unsigned NumVars = C->varlist_size(); 12140 SmallVector<Expr *, 16> Vars; 12141 Vars.reserve(NumVars); 12142 for (unsigned i = 0; i != NumVars; ++i) 12143 Vars.push_back(Record.readSubExpr()); 12144 C->setVarRefs(Vars); 12145 Vars.clear(); 12146 for (unsigned i = 0; i != NumVars; ++i) 12147 Vars.push_back(Record.readSubExpr()); 12148 C->setPrivateCopies(Vars); 12149 Vars.clear(); 12150 for (unsigned i = 0; i != NumVars; ++i) 12151 Vars.push_back(Record.readSubExpr()); 12152 C->setSourceExprs(Vars); 12153 Vars.clear(); 12154 for (unsigned i = 0; i != NumVars; ++i) 12155 Vars.push_back(Record.readSubExpr()); 12156 C->setDestinationExprs(Vars); 12157 Vars.clear(); 12158 for (unsigned i = 0; i != NumVars; ++i) 12159 Vars.push_back(Record.readSubExpr()); 12160 C->setAssignmentOps(Vars); 12161 } 12162 12163 void OMPClauseReader::VisitOMPSharedClause(OMPSharedClause *C) { 12164 C->setLParenLoc(Record.readSourceLocation()); 12165 unsigned NumVars = C->varlist_size(); 12166 SmallVector<Expr *, 16> Vars; 12167 Vars.reserve(NumVars); 12168 for (unsigned i = 0; i != NumVars; ++i) 12169 Vars.push_back(Record.readSubExpr()); 12170 C->setVarRefs(Vars); 12171 } 12172 12173 void OMPClauseReader::VisitOMPReductionClause(OMPReductionClause *C) { 12174 VisitOMPClauseWithPostUpdate(C); 12175 C->setLParenLoc(Record.readSourceLocation()); 12176 C->setModifierLoc(Record.readSourceLocation()); 12177 C->setColonLoc(Record.readSourceLocation()); 12178 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc(); 12179 DeclarationNameInfo DNI = Record.readDeclarationNameInfo(); 12180 C->setQualifierLoc(NNSL); 12181 C->setNameInfo(DNI); 12182 12183 unsigned NumVars = C->varlist_size(); 12184 SmallVector<Expr *, 16> Vars; 12185 Vars.reserve(NumVars); 12186 for (unsigned i = 0; i != NumVars; ++i) 12187 Vars.push_back(Record.readSubExpr()); 12188 C->setVarRefs(Vars); 12189 Vars.clear(); 12190 for (unsigned i = 0; i != NumVars; ++i) 12191 Vars.push_back(Record.readSubExpr()); 12192 C->setPrivates(Vars); 12193 Vars.clear(); 12194 for (unsigned i = 0; i != NumVars; ++i) 12195 Vars.push_back(Record.readSubExpr()); 12196 C->setLHSExprs(Vars); 12197 Vars.clear(); 12198 for (unsigned i = 0; i != NumVars; ++i) 12199 Vars.push_back(Record.readSubExpr()); 12200 C->setRHSExprs(Vars); 12201 Vars.clear(); 12202 for (unsigned i = 0; i != NumVars; ++i) 12203 Vars.push_back(Record.readSubExpr()); 12204 C->setReductionOps(Vars); 12205 if (C->getModifier() == OMPC_REDUCTION_inscan) { 12206 Vars.clear(); 12207 for (unsigned i = 0; i != NumVars; ++i) 12208 Vars.push_back(Record.readSubExpr()); 12209 C->setInscanCopyOps(Vars); 12210 Vars.clear(); 12211 for (unsigned i = 0; i != NumVars; ++i) 12212 Vars.push_back(Record.readSubExpr()); 12213 C->setInscanCopyArrayTemps(Vars); 12214 Vars.clear(); 12215 for (unsigned i = 0; i != NumVars; ++i) 12216 Vars.push_back(Record.readSubExpr()); 12217 C->setInscanCopyArrayElems(Vars); 12218 } 12219 } 12220 12221 void OMPClauseReader::VisitOMPTaskReductionClause(OMPTaskReductionClause *C) { 12222 VisitOMPClauseWithPostUpdate(C); 12223 C->setLParenLoc(Record.readSourceLocation()); 12224 C->setColonLoc(Record.readSourceLocation()); 12225 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc(); 12226 DeclarationNameInfo DNI = Record.readDeclarationNameInfo(); 12227 C->setQualifierLoc(NNSL); 12228 C->setNameInfo(DNI); 12229 12230 unsigned NumVars = C->varlist_size(); 12231 SmallVector<Expr *, 16> Vars; 12232 Vars.reserve(NumVars); 12233 for (unsigned I = 0; I != NumVars; ++I) 12234 Vars.push_back(Record.readSubExpr()); 12235 C->setVarRefs(Vars); 12236 Vars.clear(); 12237 for (unsigned I = 0; I != NumVars; ++I) 12238 Vars.push_back(Record.readSubExpr()); 12239 C->setPrivates(Vars); 12240 Vars.clear(); 12241 for (unsigned I = 0; I != NumVars; ++I) 12242 Vars.push_back(Record.readSubExpr()); 12243 C->setLHSExprs(Vars); 12244 Vars.clear(); 12245 for (unsigned I = 0; I != NumVars; ++I) 12246 Vars.push_back(Record.readSubExpr()); 12247 C->setRHSExprs(Vars); 12248 Vars.clear(); 12249 for (unsigned I = 0; I != NumVars; ++I) 12250 Vars.push_back(Record.readSubExpr()); 12251 C->setReductionOps(Vars); 12252 } 12253 12254 void OMPClauseReader::VisitOMPInReductionClause(OMPInReductionClause *C) { 12255 VisitOMPClauseWithPostUpdate(C); 12256 C->setLParenLoc(Record.readSourceLocation()); 12257 C->setColonLoc(Record.readSourceLocation()); 12258 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc(); 12259 DeclarationNameInfo DNI = Record.readDeclarationNameInfo(); 12260 C->setQualifierLoc(NNSL); 12261 C->setNameInfo(DNI); 12262 12263 unsigned NumVars = C->varlist_size(); 12264 SmallVector<Expr *, 16> Vars; 12265 Vars.reserve(NumVars); 12266 for (unsigned I = 0; I != NumVars; ++I) 12267 Vars.push_back(Record.readSubExpr()); 12268 C->setVarRefs(Vars); 12269 Vars.clear(); 12270 for (unsigned I = 0; I != NumVars; ++I) 12271 Vars.push_back(Record.readSubExpr()); 12272 C->setPrivates(Vars); 12273 Vars.clear(); 12274 for (unsigned I = 0; I != NumVars; ++I) 12275 Vars.push_back(Record.readSubExpr()); 12276 C->setLHSExprs(Vars); 12277 Vars.clear(); 12278 for (unsigned I = 0; I != NumVars; ++I) 12279 Vars.push_back(Record.readSubExpr()); 12280 C->setRHSExprs(Vars); 12281 Vars.clear(); 12282 for (unsigned I = 0; I != NumVars; ++I) 12283 Vars.push_back(Record.readSubExpr()); 12284 C->setReductionOps(Vars); 12285 Vars.clear(); 12286 for (unsigned I = 0; I != NumVars; ++I) 12287 Vars.push_back(Record.readSubExpr()); 12288 C->setTaskgroupDescriptors(Vars); 12289 } 12290 12291 void OMPClauseReader::VisitOMPLinearClause(OMPLinearClause *C) { 12292 VisitOMPClauseWithPostUpdate(C); 12293 C->setLParenLoc(Record.readSourceLocation()); 12294 C->setColonLoc(Record.readSourceLocation()); 12295 C->setModifier(static_cast<OpenMPLinearClauseKind>(Record.readInt())); 12296 C->setModifierLoc(Record.readSourceLocation()); 12297 unsigned NumVars = C->varlist_size(); 12298 SmallVector<Expr *, 16> Vars; 12299 Vars.reserve(NumVars); 12300 for (unsigned i = 0; i != NumVars; ++i) 12301 Vars.push_back(Record.readSubExpr()); 12302 C->setVarRefs(Vars); 12303 Vars.clear(); 12304 for (unsigned i = 0; i != NumVars; ++i) 12305 Vars.push_back(Record.readSubExpr()); 12306 C->setPrivates(Vars); 12307 Vars.clear(); 12308 for (unsigned i = 0; i != NumVars; ++i) 12309 Vars.push_back(Record.readSubExpr()); 12310 C->setInits(Vars); 12311 Vars.clear(); 12312 for (unsigned i = 0; i != NumVars; ++i) 12313 Vars.push_back(Record.readSubExpr()); 12314 C->setUpdates(Vars); 12315 Vars.clear(); 12316 for (unsigned i = 0; i != NumVars; ++i) 12317 Vars.push_back(Record.readSubExpr()); 12318 C->setFinals(Vars); 12319 C->setStep(Record.readSubExpr()); 12320 C->setCalcStep(Record.readSubExpr()); 12321 Vars.clear(); 12322 for (unsigned I = 0; I != NumVars + 1; ++I) 12323 Vars.push_back(Record.readSubExpr()); 12324 C->setUsedExprs(Vars); 12325 } 12326 12327 void OMPClauseReader::VisitOMPAlignedClause(OMPAlignedClause *C) { 12328 C->setLParenLoc(Record.readSourceLocation()); 12329 C->setColonLoc(Record.readSourceLocation()); 12330 unsigned NumVars = C->varlist_size(); 12331 SmallVector<Expr *, 16> Vars; 12332 Vars.reserve(NumVars); 12333 for (unsigned i = 0; i != NumVars; ++i) 12334 Vars.push_back(Record.readSubExpr()); 12335 C->setVarRefs(Vars); 12336 C->setAlignment(Record.readSubExpr()); 12337 } 12338 12339 void OMPClauseReader::VisitOMPCopyinClause(OMPCopyinClause *C) { 12340 C->setLParenLoc(Record.readSourceLocation()); 12341 unsigned NumVars = C->varlist_size(); 12342 SmallVector<Expr *, 16> Exprs; 12343 Exprs.reserve(NumVars); 12344 for (unsigned i = 0; i != NumVars; ++i) 12345 Exprs.push_back(Record.readSubExpr()); 12346 C->setVarRefs(Exprs); 12347 Exprs.clear(); 12348 for (unsigned i = 0; i != NumVars; ++i) 12349 Exprs.push_back(Record.readSubExpr()); 12350 C->setSourceExprs(Exprs); 12351 Exprs.clear(); 12352 for (unsigned i = 0; i != NumVars; ++i) 12353 Exprs.push_back(Record.readSubExpr()); 12354 C->setDestinationExprs(Exprs); 12355 Exprs.clear(); 12356 for (unsigned i = 0; i != NumVars; ++i) 12357 Exprs.push_back(Record.readSubExpr()); 12358 C->setAssignmentOps(Exprs); 12359 } 12360 12361 void OMPClauseReader::VisitOMPCopyprivateClause(OMPCopyprivateClause *C) { 12362 C->setLParenLoc(Record.readSourceLocation()); 12363 unsigned NumVars = C->varlist_size(); 12364 SmallVector<Expr *, 16> Exprs; 12365 Exprs.reserve(NumVars); 12366 for (unsigned i = 0; i != NumVars; ++i) 12367 Exprs.push_back(Record.readSubExpr()); 12368 C->setVarRefs(Exprs); 12369 Exprs.clear(); 12370 for (unsigned i = 0; i != NumVars; ++i) 12371 Exprs.push_back(Record.readSubExpr()); 12372 C->setSourceExprs(Exprs); 12373 Exprs.clear(); 12374 for (unsigned i = 0; i != NumVars; ++i) 12375 Exprs.push_back(Record.readSubExpr()); 12376 C->setDestinationExprs(Exprs); 12377 Exprs.clear(); 12378 for (unsigned i = 0; i != NumVars; ++i) 12379 Exprs.push_back(Record.readSubExpr()); 12380 C->setAssignmentOps(Exprs); 12381 } 12382 12383 void OMPClauseReader::VisitOMPFlushClause(OMPFlushClause *C) { 12384 C->setLParenLoc(Record.readSourceLocation()); 12385 unsigned NumVars = C->varlist_size(); 12386 SmallVector<Expr *, 16> Vars; 12387 Vars.reserve(NumVars); 12388 for (unsigned i = 0; i != NumVars; ++i) 12389 Vars.push_back(Record.readSubExpr()); 12390 C->setVarRefs(Vars); 12391 } 12392 12393 void OMPClauseReader::VisitOMPDepobjClause(OMPDepobjClause *C) { 12394 C->setDepobj(Record.readSubExpr()); 12395 C->setLParenLoc(Record.readSourceLocation()); 12396 } 12397 12398 void OMPClauseReader::VisitOMPDependClause(OMPDependClause *C) { 12399 C->setLParenLoc(Record.readSourceLocation()); 12400 C->setModifier(Record.readSubExpr()); 12401 C->setDependencyKind( 12402 static_cast<OpenMPDependClauseKind>(Record.readInt())); 12403 C->setDependencyLoc(Record.readSourceLocation()); 12404 C->setColonLoc(Record.readSourceLocation()); 12405 unsigned NumVars = C->varlist_size(); 12406 SmallVector<Expr *, 16> Vars; 12407 Vars.reserve(NumVars); 12408 for (unsigned I = 0; I != NumVars; ++I) 12409 Vars.push_back(Record.readSubExpr()); 12410 C->setVarRefs(Vars); 12411 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I) 12412 C->setLoopData(I, Record.readSubExpr()); 12413 } 12414 12415 void OMPClauseReader::VisitOMPDeviceClause(OMPDeviceClause *C) { 12416 VisitOMPClauseWithPreInit(C); 12417 C->setModifier(Record.readEnum<OpenMPDeviceClauseModifier>()); 12418 C->setDevice(Record.readSubExpr()); 12419 C->setModifierLoc(Record.readSourceLocation()); 12420 C->setLParenLoc(Record.readSourceLocation()); 12421 } 12422 12423 void OMPClauseReader::VisitOMPMapClause(OMPMapClause *C) { 12424 C->setLParenLoc(Record.readSourceLocation()); 12425 for (unsigned I = 0; I < NumberOfOMPMapClauseModifiers; ++I) { 12426 C->setMapTypeModifier( 12427 I, static_cast<OpenMPMapModifierKind>(Record.readInt())); 12428 C->setMapTypeModifierLoc(I, Record.readSourceLocation()); 12429 } 12430 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc()); 12431 C->setMapperIdInfo(Record.readDeclarationNameInfo()); 12432 C->setMapType( 12433 static_cast<OpenMPMapClauseKind>(Record.readInt())); 12434 C->setMapLoc(Record.readSourceLocation()); 12435 C->setColonLoc(Record.readSourceLocation()); 12436 auto NumVars = C->varlist_size(); 12437 auto UniqueDecls = C->getUniqueDeclarationsNum(); 12438 auto TotalLists = C->getTotalComponentListNum(); 12439 auto TotalComponents = C->getTotalComponentsNum(); 12440 12441 SmallVector<Expr *, 16> Vars; 12442 Vars.reserve(NumVars); 12443 for (unsigned i = 0; i != NumVars; ++i) 12444 Vars.push_back(Record.readExpr()); 12445 C->setVarRefs(Vars); 12446 12447 SmallVector<Expr *, 16> UDMappers; 12448 UDMappers.reserve(NumVars); 12449 for (unsigned I = 0; I < NumVars; ++I) 12450 UDMappers.push_back(Record.readExpr()); 12451 C->setUDMapperRefs(UDMappers); 12452 12453 SmallVector<ValueDecl *, 16> Decls; 12454 Decls.reserve(UniqueDecls); 12455 for (unsigned i = 0; i < UniqueDecls; ++i) 12456 Decls.push_back(Record.readDeclAs<ValueDecl>()); 12457 C->setUniqueDecls(Decls); 12458 12459 SmallVector<unsigned, 16> ListsPerDecl; 12460 ListsPerDecl.reserve(UniqueDecls); 12461 for (unsigned i = 0; i < UniqueDecls; ++i) 12462 ListsPerDecl.push_back(Record.readInt()); 12463 C->setDeclNumLists(ListsPerDecl); 12464 12465 SmallVector<unsigned, 32> ListSizes; 12466 ListSizes.reserve(TotalLists); 12467 for (unsigned i = 0; i < TotalLists; ++i) 12468 ListSizes.push_back(Record.readInt()); 12469 C->setComponentListSizes(ListSizes); 12470 12471 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components; 12472 Components.reserve(TotalComponents); 12473 for (unsigned i = 0; i < TotalComponents; ++i) { 12474 Expr *AssociatedExprPr = Record.readExpr(); 12475 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>(); 12476 Components.emplace_back(AssociatedExprPr, AssociatedDecl, 12477 /*IsNonContiguous=*/false); 12478 } 12479 C->setComponents(Components, ListSizes); 12480 } 12481 12482 void OMPClauseReader::VisitOMPAllocateClause(OMPAllocateClause *C) { 12483 C->setLParenLoc(Record.readSourceLocation()); 12484 C->setColonLoc(Record.readSourceLocation()); 12485 C->setAllocator(Record.readSubExpr()); 12486 unsigned NumVars = C->varlist_size(); 12487 SmallVector<Expr *, 16> Vars; 12488 Vars.reserve(NumVars); 12489 for (unsigned i = 0; i != NumVars; ++i) 12490 Vars.push_back(Record.readSubExpr()); 12491 C->setVarRefs(Vars); 12492 } 12493 12494 void OMPClauseReader::VisitOMPNumTeamsClause(OMPNumTeamsClause *C) { 12495 VisitOMPClauseWithPreInit(C); 12496 C->setNumTeams(Record.readSubExpr()); 12497 C->setLParenLoc(Record.readSourceLocation()); 12498 } 12499 12500 void OMPClauseReader::VisitOMPThreadLimitClause(OMPThreadLimitClause *C) { 12501 VisitOMPClauseWithPreInit(C); 12502 C->setThreadLimit(Record.readSubExpr()); 12503 C->setLParenLoc(Record.readSourceLocation()); 12504 } 12505 12506 void OMPClauseReader::VisitOMPPriorityClause(OMPPriorityClause *C) { 12507 VisitOMPClauseWithPreInit(C); 12508 C->setPriority(Record.readSubExpr()); 12509 C->setLParenLoc(Record.readSourceLocation()); 12510 } 12511 12512 void OMPClauseReader::VisitOMPGrainsizeClause(OMPGrainsizeClause *C) { 12513 VisitOMPClauseWithPreInit(C); 12514 C->setGrainsize(Record.readSubExpr()); 12515 C->setLParenLoc(Record.readSourceLocation()); 12516 } 12517 12518 void OMPClauseReader::VisitOMPNumTasksClause(OMPNumTasksClause *C) { 12519 VisitOMPClauseWithPreInit(C); 12520 C->setNumTasks(Record.readSubExpr()); 12521 C->setLParenLoc(Record.readSourceLocation()); 12522 } 12523 12524 void OMPClauseReader::VisitOMPHintClause(OMPHintClause *C) { 12525 C->setHint(Record.readSubExpr()); 12526 C->setLParenLoc(Record.readSourceLocation()); 12527 } 12528 12529 void OMPClauseReader::VisitOMPDistScheduleClause(OMPDistScheduleClause *C) { 12530 VisitOMPClauseWithPreInit(C); 12531 C->setDistScheduleKind( 12532 static_cast<OpenMPDistScheduleClauseKind>(Record.readInt())); 12533 C->setChunkSize(Record.readSubExpr()); 12534 C->setLParenLoc(Record.readSourceLocation()); 12535 C->setDistScheduleKindLoc(Record.readSourceLocation()); 12536 C->setCommaLoc(Record.readSourceLocation()); 12537 } 12538 12539 void OMPClauseReader::VisitOMPDefaultmapClause(OMPDefaultmapClause *C) { 12540 C->setDefaultmapKind( 12541 static_cast<OpenMPDefaultmapClauseKind>(Record.readInt())); 12542 C->setDefaultmapModifier( 12543 static_cast<OpenMPDefaultmapClauseModifier>(Record.readInt())); 12544 C->setLParenLoc(Record.readSourceLocation()); 12545 C->setDefaultmapModifierLoc(Record.readSourceLocation()); 12546 C->setDefaultmapKindLoc(Record.readSourceLocation()); 12547 } 12548 12549 void OMPClauseReader::VisitOMPToClause(OMPToClause *C) { 12550 C->setLParenLoc(Record.readSourceLocation()); 12551 for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) { 12552 C->setMotionModifier( 12553 I, static_cast<OpenMPMotionModifierKind>(Record.readInt())); 12554 C->setMotionModifierLoc(I, Record.readSourceLocation()); 12555 } 12556 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc()); 12557 C->setMapperIdInfo(Record.readDeclarationNameInfo()); 12558 C->setColonLoc(Record.readSourceLocation()); 12559 auto NumVars = C->varlist_size(); 12560 auto UniqueDecls = C->getUniqueDeclarationsNum(); 12561 auto TotalLists = C->getTotalComponentListNum(); 12562 auto TotalComponents = C->getTotalComponentsNum(); 12563 12564 SmallVector<Expr *, 16> Vars; 12565 Vars.reserve(NumVars); 12566 for (unsigned i = 0; i != NumVars; ++i) 12567 Vars.push_back(Record.readSubExpr()); 12568 C->setVarRefs(Vars); 12569 12570 SmallVector<Expr *, 16> UDMappers; 12571 UDMappers.reserve(NumVars); 12572 for (unsigned I = 0; I < NumVars; ++I) 12573 UDMappers.push_back(Record.readSubExpr()); 12574 C->setUDMapperRefs(UDMappers); 12575 12576 SmallVector<ValueDecl *, 16> Decls; 12577 Decls.reserve(UniqueDecls); 12578 for (unsigned i = 0; i < UniqueDecls; ++i) 12579 Decls.push_back(Record.readDeclAs<ValueDecl>()); 12580 C->setUniqueDecls(Decls); 12581 12582 SmallVector<unsigned, 16> ListsPerDecl; 12583 ListsPerDecl.reserve(UniqueDecls); 12584 for (unsigned i = 0; i < UniqueDecls; ++i) 12585 ListsPerDecl.push_back(Record.readInt()); 12586 C->setDeclNumLists(ListsPerDecl); 12587 12588 SmallVector<unsigned, 32> ListSizes; 12589 ListSizes.reserve(TotalLists); 12590 for (unsigned i = 0; i < TotalLists; ++i) 12591 ListSizes.push_back(Record.readInt()); 12592 C->setComponentListSizes(ListSizes); 12593 12594 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components; 12595 Components.reserve(TotalComponents); 12596 for (unsigned i = 0; i < TotalComponents; ++i) { 12597 Expr *AssociatedExprPr = Record.readSubExpr(); 12598 bool IsNonContiguous = Record.readBool(); 12599 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>(); 12600 Components.emplace_back(AssociatedExprPr, AssociatedDecl, IsNonContiguous); 12601 } 12602 C->setComponents(Components, ListSizes); 12603 } 12604 12605 void OMPClauseReader::VisitOMPFromClause(OMPFromClause *C) { 12606 C->setLParenLoc(Record.readSourceLocation()); 12607 for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) { 12608 C->setMotionModifier( 12609 I, static_cast<OpenMPMotionModifierKind>(Record.readInt())); 12610 C->setMotionModifierLoc(I, Record.readSourceLocation()); 12611 } 12612 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc()); 12613 C->setMapperIdInfo(Record.readDeclarationNameInfo()); 12614 C->setColonLoc(Record.readSourceLocation()); 12615 auto NumVars = C->varlist_size(); 12616 auto UniqueDecls = C->getUniqueDeclarationsNum(); 12617 auto TotalLists = C->getTotalComponentListNum(); 12618 auto TotalComponents = C->getTotalComponentsNum(); 12619 12620 SmallVector<Expr *, 16> Vars; 12621 Vars.reserve(NumVars); 12622 for (unsigned i = 0; i != NumVars; ++i) 12623 Vars.push_back(Record.readSubExpr()); 12624 C->setVarRefs(Vars); 12625 12626 SmallVector<Expr *, 16> UDMappers; 12627 UDMappers.reserve(NumVars); 12628 for (unsigned I = 0; I < NumVars; ++I) 12629 UDMappers.push_back(Record.readSubExpr()); 12630 C->setUDMapperRefs(UDMappers); 12631 12632 SmallVector<ValueDecl *, 16> Decls; 12633 Decls.reserve(UniqueDecls); 12634 for (unsigned i = 0; i < UniqueDecls; ++i) 12635 Decls.push_back(Record.readDeclAs<ValueDecl>()); 12636 C->setUniqueDecls(Decls); 12637 12638 SmallVector<unsigned, 16> ListsPerDecl; 12639 ListsPerDecl.reserve(UniqueDecls); 12640 for (unsigned i = 0; i < UniqueDecls; ++i) 12641 ListsPerDecl.push_back(Record.readInt()); 12642 C->setDeclNumLists(ListsPerDecl); 12643 12644 SmallVector<unsigned, 32> ListSizes; 12645 ListSizes.reserve(TotalLists); 12646 for (unsigned i = 0; i < TotalLists; ++i) 12647 ListSizes.push_back(Record.readInt()); 12648 C->setComponentListSizes(ListSizes); 12649 12650 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components; 12651 Components.reserve(TotalComponents); 12652 for (unsigned i = 0; i < TotalComponents; ++i) { 12653 Expr *AssociatedExprPr = Record.readSubExpr(); 12654 bool IsNonContiguous = Record.readBool(); 12655 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>(); 12656 Components.emplace_back(AssociatedExprPr, AssociatedDecl, IsNonContiguous); 12657 } 12658 C->setComponents(Components, ListSizes); 12659 } 12660 12661 void OMPClauseReader::VisitOMPUseDevicePtrClause(OMPUseDevicePtrClause *C) { 12662 C->setLParenLoc(Record.readSourceLocation()); 12663 auto NumVars = C->varlist_size(); 12664 auto UniqueDecls = C->getUniqueDeclarationsNum(); 12665 auto TotalLists = C->getTotalComponentListNum(); 12666 auto TotalComponents = C->getTotalComponentsNum(); 12667 12668 SmallVector<Expr *, 16> Vars; 12669 Vars.reserve(NumVars); 12670 for (unsigned i = 0; i != NumVars; ++i) 12671 Vars.push_back(Record.readSubExpr()); 12672 C->setVarRefs(Vars); 12673 Vars.clear(); 12674 for (unsigned i = 0; i != NumVars; ++i) 12675 Vars.push_back(Record.readSubExpr()); 12676 C->setPrivateCopies(Vars); 12677 Vars.clear(); 12678 for (unsigned i = 0; i != NumVars; ++i) 12679 Vars.push_back(Record.readSubExpr()); 12680 C->setInits(Vars); 12681 12682 SmallVector<ValueDecl *, 16> Decls; 12683 Decls.reserve(UniqueDecls); 12684 for (unsigned i = 0; i < UniqueDecls; ++i) 12685 Decls.push_back(Record.readDeclAs<ValueDecl>()); 12686 C->setUniqueDecls(Decls); 12687 12688 SmallVector<unsigned, 16> ListsPerDecl; 12689 ListsPerDecl.reserve(UniqueDecls); 12690 for (unsigned i = 0; i < UniqueDecls; ++i) 12691 ListsPerDecl.push_back(Record.readInt()); 12692 C->setDeclNumLists(ListsPerDecl); 12693 12694 SmallVector<unsigned, 32> ListSizes; 12695 ListSizes.reserve(TotalLists); 12696 for (unsigned i = 0; i < TotalLists; ++i) 12697 ListSizes.push_back(Record.readInt()); 12698 C->setComponentListSizes(ListSizes); 12699 12700 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components; 12701 Components.reserve(TotalComponents); 12702 for (unsigned i = 0; i < TotalComponents; ++i) { 12703 auto *AssociatedExprPr = Record.readSubExpr(); 12704 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>(); 12705 Components.emplace_back(AssociatedExprPr, AssociatedDecl, 12706 /*IsNonContiguous=*/false); 12707 } 12708 C->setComponents(Components, ListSizes); 12709 } 12710 12711 void OMPClauseReader::VisitOMPUseDeviceAddrClause(OMPUseDeviceAddrClause *C) { 12712 C->setLParenLoc(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<ValueDecl *, 16> Decls; 12725 Decls.reserve(UniqueDecls); 12726 for (unsigned i = 0; i < UniqueDecls; ++i) 12727 Decls.push_back(Record.readDeclAs<ValueDecl>()); 12728 C->setUniqueDecls(Decls); 12729 12730 SmallVector<unsigned, 16> ListsPerDecl; 12731 ListsPerDecl.reserve(UniqueDecls); 12732 for (unsigned i = 0; i < UniqueDecls; ++i) 12733 ListsPerDecl.push_back(Record.readInt()); 12734 C->setDeclNumLists(ListsPerDecl); 12735 12736 SmallVector<unsigned, 32> ListSizes; 12737 ListSizes.reserve(TotalLists); 12738 for (unsigned i = 0; i < TotalLists; ++i) 12739 ListSizes.push_back(Record.readInt()); 12740 C->setComponentListSizes(ListSizes); 12741 12742 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components; 12743 Components.reserve(TotalComponents); 12744 for (unsigned i = 0; i < TotalComponents; ++i) { 12745 Expr *AssociatedExpr = Record.readSubExpr(); 12746 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>(); 12747 Components.emplace_back(AssociatedExpr, AssociatedDecl, 12748 /*IsNonContiguous*/ false); 12749 } 12750 C->setComponents(Components, ListSizes); 12751 } 12752 12753 void OMPClauseReader::VisitOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) { 12754 C->setLParenLoc(Record.readSourceLocation()); 12755 auto NumVars = C->varlist_size(); 12756 auto UniqueDecls = C->getUniqueDeclarationsNum(); 12757 auto TotalLists = C->getTotalComponentListNum(); 12758 auto TotalComponents = C->getTotalComponentsNum(); 12759 12760 SmallVector<Expr *, 16> Vars; 12761 Vars.reserve(NumVars); 12762 for (unsigned i = 0; i != NumVars; ++i) 12763 Vars.push_back(Record.readSubExpr()); 12764 C->setVarRefs(Vars); 12765 Vars.clear(); 12766 12767 SmallVector<ValueDecl *, 16> Decls; 12768 Decls.reserve(UniqueDecls); 12769 for (unsigned i = 0; i < UniqueDecls; ++i) 12770 Decls.push_back(Record.readDeclAs<ValueDecl>()); 12771 C->setUniqueDecls(Decls); 12772 12773 SmallVector<unsigned, 16> ListsPerDecl; 12774 ListsPerDecl.reserve(UniqueDecls); 12775 for (unsigned i = 0; i < UniqueDecls; ++i) 12776 ListsPerDecl.push_back(Record.readInt()); 12777 C->setDeclNumLists(ListsPerDecl); 12778 12779 SmallVector<unsigned, 32> ListSizes; 12780 ListSizes.reserve(TotalLists); 12781 for (unsigned i = 0; i < TotalLists; ++i) 12782 ListSizes.push_back(Record.readInt()); 12783 C->setComponentListSizes(ListSizes); 12784 12785 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components; 12786 Components.reserve(TotalComponents); 12787 for (unsigned i = 0; i < TotalComponents; ++i) { 12788 Expr *AssociatedExpr = Record.readSubExpr(); 12789 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>(); 12790 Components.emplace_back(AssociatedExpr, AssociatedDecl, 12791 /*IsNonContiguous=*/false); 12792 } 12793 C->setComponents(Components, ListSizes); 12794 } 12795 12796 void OMPClauseReader::VisitOMPNontemporalClause(OMPNontemporalClause *C) { 12797 C->setLParenLoc(Record.readSourceLocation()); 12798 unsigned NumVars = C->varlist_size(); 12799 SmallVector<Expr *, 16> Vars; 12800 Vars.reserve(NumVars); 12801 for (unsigned i = 0; i != NumVars; ++i) 12802 Vars.push_back(Record.readSubExpr()); 12803 C->setVarRefs(Vars); 12804 Vars.clear(); 12805 Vars.reserve(NumVars); 12806 for (unsigned i = 0; i != NumVars; ++i) 12807 Vars.push_back(Record.readSubExpr()); 12808 C->setPrivateRefs(Vars); 12809 } 12810 12811 void OMPClauseReader::VisitOMPInclusiveClause(OMPInclusiveClause *C) { 12812 C->setLParenLoc(Record.readSourceLocation()); 12813 unsigned NumVars = C->varlist_size(); 12814 SmallVector<Expr *, 16> Vars; 12815 Vars.reserve(NumVars); 12816 for (unsigned i = 0; i != NumVars; ++i) 12817 Vars.push_back(Record.readSubExpr()); 12818 C->setVarRefs(Vars); 12819 } 12820 12821 void OMPClauseReader::VisitOMPExclusiveClause(OMPExclusiveClause *C) { 12822 C->setLParenLoc(Record.readSourceLocation()); 12823 unsigned NumVars = C->varlist_size(); 12824 SmallVector<Expr *, 16> Vars; 12825 Vars.reserve(NumVars); 12826 for (unsigned i = 0; i != NumVars; ++i) 12827 Vars.push_back(Record.readSubExpr()); 12828 C->setVarRefs(Vars); 12829 } 12830 12831 void OMPClauseReader::VisitOMPUsesAllocatorsClause(OMPUsesAllocatorsClause *C) { 12832 C->setLParenLoc(Record.readSourceLocation()); 12833 unsigned NumOfAllocators = C->getNumberOfAllocators(); 12834 SmallVector<OMPUsesAllocatorsClause::Data, 4> Data; 12835 Data.reserve(NumOfAllocators); 12836 for (unsigned I = 0; I != NumOfAllocators; ++I) { 12837 OMPUsesAllocatorsClause::Data &D = Data.emplace_back(); 12838 D.Allocator = Record.readSubExpr(); 12839 D.AllocatorTraits = Record.readSubExpr(); 12840 D.LParenLoc = Record.readSourceLocation(); 12841 D.RParenLoc = Record.readSourceLocation(); 12842 } 12843 C->setAllocatorsData(Data); 12844 } 12845 12846 void OMPClauseReader::VisitOMPAffinityClause(OMPAffinityClause *C) { 12847 C->setLParenLoc(Record.readSourceLocation()); 12848 C->setModifier(Record.readSubExpr()); 12849 C->setColonLoc(Record.readSourceLocation()); 12850 unsigned NumOfLocators = C->varlist_size(); 12851 SmallVector<Expr *, 4> Locators; 12852 Locators.reserve(NumOfLocators); 12853 for (unsigned I = 0; I != NumOfLocators; ++I) 12854 Locators.push_back(Record.readSubExpr()); 12855 C->setVarRefs(Locators); 12856 } 12857 12858 void OMPClauseReader::VisitOMPOrderClause(OMPOrderClause *C) { 12859 C->setKind(Record.readEnum<OpenMPOrderClauseKind>()); 12860 C->setLParenLoc(Record.readSourceLocation()); 12861 C->setKindKwLoc(Record.readSourceLocation()); 12862 } 12863 12864 OMPTraitInfo *ASTRecordReader::readOMPTraitInfo() { 12865 OMPTraitInfo &TI = getContext().getNewOMPTraitInfo(); 12866 TI.Sets.resize(readUInt32()); 12867 for (auto &Set : TI.Sets) { 12868 Set.Kind = readEnum<llvm::omp::TraitSet>(); 12869 Set.Selectors.resize(readUInt32()); 12870 for (auto &Selector : Set.Selectors) { 12871 Selector.Kind = readEnum<llvm::omp::TraitSelector>(); 12872 Selector.ScoreOrCondition = nullptr; 12873 if (readBool()) 12874 Selector.ScoreOrCondition = readExprRef(); 12875 Selector.Properties.resize(readUInt32()); 12876 for (auto &Property : Selector.Properties) 12877 Property.Kind = readEnum<llvm::omp::TraitProperty>(); 12878 } 12879 } 12880 return &TI; 12881 } 12882 12883 void ASTRecordReader::readOMPChildren(OMPChildren *Data) { 12884 if (!Data) 12885 return; 12886 if (Reader->ReadingKind == ASTReader::Read_Stmt) { 12887 // Skip NumClauses, NumChildren and HasAssociatedStmt fields. 12888 skipInts(3); 12889 } 12890 SmallVector<OMPClause *, 4> Clauses(Data->getNumClauses()); 12891 for (unsigned I = 0, E = Data->getNumClauses(); I < E; ++I) 12892 Clauses[I] = readOMPClause(); 12893 Data->setClauses(Clauses); 12894 if (Data->hasAssociatedStmt()) 12895 Data->setAssociatedStmt(readStmt()); 12896 for (unsigned I = 0, E = Data->getNumChildren(); I < E; ++I) 12897 Data->getChildren()[I] = readStmt(); 12898 } 12899