1 //===-- ASTReader.cpp - AST File Reader -----------------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file defines the ASTReader class, which reads AST files. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/Serialization/ASTReader.h" 15 #include "ASTCommon.h" 16 #include "ASTReaderInternals.h" 17 #include "clang/AST/ASTConsumer.h" 18 #include "clang/AST/ASTContext.h" 19 #include "clang/AST/ASTMutationListener.h" 20 #include "clang/AST/ASTUnresolvedSet.h" 21 #include "clang/AST/Decl.h" 22 #include "clang/AST/DeclCXX.h" 23 #include "clang/AST/DeclGroup.h" 24 #include "clang/AST/DeclObjC.h" 25 #include "clang/AST/DeclTemplate.h" 26 #include "clang/AST/Expr.h" 27 #include "clang/AST/ExprCXX.h" 28 #include "clang/AST/NestedNameSpecifier.h" 29 #include "clang/AST/ODRHash.h" 30 #include "clang/AST/RawCommentList.h" 31 #include "clang/AST/Type.h" 32 #include "clang/AST/TypeLocVisitor.h" 33 #include "clang/AST/UnresolvedSet.h" 34 #include "clang/Basic/CommentOptions.h" 35 #include "clang/Basic/DiagnosticOptions.h" 36 #include "clang/Basic/ExceptionSpecificationType.h" 37 #include "clang/Basic/FileManager.h" 38 #include "clang/Basic/FileSystemOptions.h" 39 #include "clang/Basic/LangOptions.h" 40 #include "clang/Basic/MemoryBufferCache.h" 41 #include "clang/Basic/ObjCRuntime.h" 42 #include "clang/Basic/OperatorKinds.h" 43 #include "clang/Basic/Sanitizers.h" 44 #include "clang/Basic/SourceManager.h" 45 #include "clang/Basic/SourceManagerInternals.h" 46 #include "clang/Basic/Specifiers.h" 47 #include "clang/Basic/TargetInfo.h" 48 #include "clang/Basic/TargetOptions.h" 49 #include "clang/Basic/TokenKinds.h" 50 #include "clang/Basic/Version.h" 51 #include "clang/Basic/VersionTuple.h" 52 #include "clang/Frontend/PCHContainerOperations.h" 53 #include "clang/Lex/HeaderSearch.h" 54 #include "clang/Lex/HeaderSearchOptions.h" 55 #include "clang/Lex/MacroInfo.h" 56 #include "clang/Lex/ModuleMap.h" 57 #include "clang/Lex/PreprocessingRecord.h" 58 #include "clang/Lex/Preprocessor.h" 59 #include "clang/Lex/PreprocessorOptions.h" 60 #include "clang/Sema/Scope.h" 61 #include "clang/Sema/Sema.h" 62 #include "clang/Sema/Weak.h" 63 #include "clang/Serialization/ASTDeserializationListener.h" 64 #include "clang/Serialization/GlobalModuleIndex.h" 65 #include "clang/Serialization/ModuleManager.h" 66 #include "clang/Serialization/SerializationDiagnostic.h" 67 #include "llvm/ADT/APFloat.h" 68 #include "llvm/ADT/APInt.h" 69 #include "llvm/ADT/APSInt.h" 70 #include "llvm/ADT/Hashing.h" 71 #include "llvm/ADT/SmallString.h" 72 #include "llvm/ADT/StringExtras.h" 73 #include "llvm/ADT/Triple.h" 74 #include "llvm/Bitcode/BitstreamReader.h" 75 #include "llvm/Support/Compression.h" 76 #include "llvm/Support/Compiler.h" 77 #include "llvm/Support/Error.h" 78 #include "llvm/Support/ErrorHandling.h" 79 #include "llvm/Support/FileSystem.h" 80 #include "llvm/Support/MemoryBuffer.h" 81 #include "llvm/Support/Path.h" 82 #include "llvm/Support/SaveAndRestore.h" 83 #include "llvm/Support/raw_ostream.h" 84 #include <algorithm> 85 #include <cassert> 86 #include <cstdint> 87 #include <cstdio> 88 #include <cstring> 89 #include <ctime> 90 #include <iterator> 91 #include <limits> 92 #include <map> 93 #include <memory> 94 #include <new> 95 #include <string> 96 #include <system_error> 97 #include <tuple> 98 #include <utility> 99 #include <vector> 100 101 using namespace clang; 102 using namespace clang::serialization; 103 using namespace clang::serialization::reader; 104 using llvm::BitstreamCursor; 105 106 //===----------------------------------------------------------------------===// 107 // ChainedASTReaderListener implementation 108 //===----------------------------------------------------------------------===// 109 110 bool 111 ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) { 112 return First->ReadFullVersionInformation(FullVersion) || 113 Second->ReadFullVersionInformation(FullVersion); 114 } 115 116 void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) { 117 First->ReadModuleName(ModuleName); 118 Second->ReadModuleName(ModuleName); 119 } 120 121 void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) { 122 First->ReadModuleMapFile(ModuleMapPath); 123 Second->ReadModuleMapFile(ModuleMapPath); 124 } 125 126 bool 127 ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts, 128 bool Complain, 129 bool AllowCompatibleDifferences) { 130 return First->ReadLanguageOptions(LangOpts, Complain, 131 AllowCompatibleDifferences) || 132 Second->ReadLanguageOptions(LangOpts, Complain, 133 AllowCompatibleDifferences); 134 } 135 136 bool ChainedASTReaderListener::ReadTargetOptions( 137 const TargetOptions &TargetOpts, bool Complain, 138 bool AllowCompatibleDifferences) { 139 return First->ReadTargetOptions(TargetOpts, Complain, 140 AllowCompatibleDifferences) || 141 Second->ReadTargetOptions(TargetOpts, Complain, 142 AllowCompatibleDifferences); 143 } 144 145 bool ChainedASTReaderListener::ReadDiagnosticOptions( 146 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) { 147 return First->ReadDiagnosticOptions(DiagOpts, Complain) || 148 Second->ReadDiagnosticOptions(DiagOpts, Complain); 149 } 150 151 bool 152 ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts, 153 bool Complain) { 154 return First->ReadFileSystemOptions(FSOpts, Complain) || 155 Second->ReadFileSystemOptions(FSOpts, Complain); 156 } 157 158 bool ChainedASTReaderListener::ReadHeaderSearchOptions( 159 const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath, 160 bool Complain) { 161 return First->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath, 162 Complain) || 163 Second->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath, 164 Complain); 165 } 166 167 bool ChainedASTReaderListener::ReadPreprocessorOptions( 168 const PreprocessorOptions &PPOpts, bool Complain, 169 std::string &SuggestedPredefines) { 170 return First->ReadPreprocessorOptions(PPOpts, Complain, 171 SuggestedPredefines) || 172 Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines); 173 } 174 void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M, 175 unsigned Value) { 176 First->ReadCounter(M, Value); 177 Second->ReadCounter(M, Value); 178 } 179 bool ChainedASTReaderListener::needsInputFileVisitation() { 180 return First->needsInputFileVisitation() || 181 Second->needsInputFileVisitation(); 182 } 183 bool ChainedASTReaderListener::needsSystemInputFileVisitation() { 184 return First->needsSystemInputFileVisitation() || 185 Second->needsSystemInputFileVisitation(); 186 } 187 void ChainedASTReaderListener::visitModuleFile(StringRef Filename, 188 ModuleKind Kind) { 189 First->visitModuleFile(Filename, Kind); 190 Second->visitModuleFile(Filename, Kind); 191 } 192 193 bool ChainedASTReaderListener::visitInputFile(StringRef Filename, 194 bool isSystem, 195 bool isOverridden, 196 bool isExplicitModule) { 197 bool Continue = false; 198 if (First->needsInputFileVisitation() && 199 (!isSystem || First->needsSystemInputFileVisitation())) 200 Continue |= First->visitInputFile(Filename, isSystem, isOverridden, 201 isExplicitModule); 202 if (Second->needsInputFileVisitation() && 203 (!isSystem || Second->needsSystemInputFileVisitation())) 204 Continue |= Second->visitInputFile(Filename, isSystem, isOverridden, 205 isExplicitModule); 206 return Continue; 207 } 208 209 void ChainedASTReaderListener::readModuleFileExtension( 210 const ModuleFileExtensionMetadata &Metadata) { 211 First->readModuleFileExtension(Metadata); 212 Second->readModuleFileExtension(Metadata); 213 } 214 215 //===----------------------------------------------------------------------===// 216 // PCH validator implementation 217 //===----------------------------------------------------------------------===// 218 219 ASTReaderListener::~ASTReaderListener() {} 220 221 /// \brief Compare the given set of language options against an existing set of 222 /// language options. 223 /// 224 /// \param Diags If non-NULL, diagnostics will be emitted via this engine. 225 /// \param AllowCompatibleDifferences If true, differences between compatible 226 /// language options will be permitted. 227 /// 228 /// \returns true if the languagae options mis-match, false otherwise. 229 static bool checkLanguageOptions(const LangOptions &LangOpts, 230 const LangOptions &ExistingLangOpts, 231 DiagnosticsEngine *Diags, 232 bool AllowCompatibleDifferences = true) { 233 #define LANGOPT(Name, Bits, Default, Description) \ 234 if (ExistingLangOpts.Name != LangOpts.Name) { \ 235 if (Diags) \ 236 Diags->Report(diag::err_pch_langopt_mismatch) \ 237 << Description << LangOpts.Name << ExistingLangOpts.Name; \ 238 return true; \ 239 } 240 241 #define VALUE_LANGOPT(Name, Bits, Default, Description) \ 242 if (ExistingLangOpts.Name != LangOpts.Name) { \ 243 if (Diags) \ 244 Diags->Report(diag::err_pch_langopt_value_mismatch) \ 245 << Description; \ 246 return true; \ 247 } 248 249 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \ 250 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \ 251 if (Diags) \ 252 Diags->Report(diag::err_pch_langopt_value_mismatch) \ 253 << Description; \ 254 return true; \ 255 } 256 257 #define COMPATIBLE_LANGOPT(Name, Bits, Default, Description) \ 258 if (!AllowCompatibleDifferences) \ 259 LANGOPT(Name, Bits, Default, Description) 260 261 #define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description) \ 262 if (!AllowCompatibleDifferences) \ 263 ENUM_LANGOPT(Name, Bits, Default, Description) 264 265 #define COMPATIBLE_VALUE_LANGOPT(Name, Bits, Default, Description) \ 266 if (!AllowCompatibleDifferences) \ 267 VALUE_LANGOPT(Name, Bits, Default, Description) 268 269 #define BENIGN_LANGOPT(Name, Bits, Default, Description) 270 #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description) 271 #define BENIGN_VALUE_LANGOPT(Name, Type, Bits, Default, Description) 272 #include "clang/Basic/LangOptions.def" 273 274 if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) { 275 if (Diags) 276 Diags->Report(diag::err_pch_langopt_value_mismatch) << "module features"; 277 return true; 278 } 279 280 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) { 281 if (Diags) 282 Diags->Report(diag::err_pch_langopt_value_mismatch) 283 << "target Objective-C runtime"; 284 return true; 285 } 286 287 if (ExistingLangOpts.CommentOpts.BlockCommandNames != 288 LangOpts.CommentOpts.BlockCommandNames) { 289 if (Diags) 290 Diags->Report(diag::err_pch_langopt_value_mismatch) 291 << "block command names"; 292 return true; 293 } 294 295 return false; 296 } 297 298 /// \brief Compare the given set of target options against an existing set of 299 /// target options. 300 /// 301 /// \param Diags If non-NULL, diagnostics will be emitted via this engine. 302 /// 303 /// \returns true if the target options mis-match, false otherwise. 304 static bool checkTargetOptions(const TargetOptions &TargetOpts, 305 const TargetOptions &ExistingTargetOpts, 306 DiagnosticsEngine *Diags, 307 bool AllowCompatibleDifferences = true) { 308 #define CHECK_TARGET_OPT(Field, Name) \ 309 if (TargetOpts.Field != ExistingTargetOpts.Field) { \ 310 if (Diags) \ 311 Diags->Report(diag::err_pch_targetopt_mismatch) \ 312 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \ 313 return true; \ 314 } 315 316 // The triple and ABI must match exactly. 317 CHECK_TARGET_OPT(Triple, "target"); 318 CHECK_TARGET_OPT(ABI, "target ABI"); 319 320 // We can tolerate different CPUs in many cases, notably when one CPU 321 // supports a strict superset of another. When allowing compatible 322 // differences skip this check. 323 if (!AllowCompatibleDifferences) 324 CHECK_TARGET_OPT(CPU, "target CPU"); 325 326 #undef CHECK_TARGET_OPT 327 328 // Compare feature sets. 329 SmallVector<StringRef, 4> ExistingFeatures( 330 ExistingTargetOpts.FeaturesAsWritten.begin(), 331 ExistingTargetOpts.FeaturesAsWritten.end()); 332 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(), 333 TargetOpts.FeaturesAsWritten.end()); 334 std::sort(ExistingFeatures.begin(), ExistingFeatures.end()); 335 std::sort(ReadFeatures.begin(), ReadFeatures.end()); 336 337 // We compute the set difference in both directions explicitly so that we can 338 // diagnose the differences differently. 339 SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures; 340 std::set_difference( 341 ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(), 342 ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures)); 343 std::set_difference(ReadFeatures.begin(), ReadFeatures.end(), 344 ExistingFeatures.begin(), ExistingFeatures.end(), 345 std::back_inserter(UnmatchedReadFeatures)); 346 347 // If we are allowing compatible differences and the read feature set is 348 // a strict subset of the existing feature set, there is nothing to diagnose. 349 if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty()) 350 return false; 351 352 if (Diags) { 353 for (StringRef Feature : UnmatchedReadFeatures) 354 Diags->Report(diag::err_pch_targetopt_feature_mismatch) 355 << /* is-existing-feature */ false << Feature; 356 for (StringRef Feature : UnmatchedExistingFeatures) 357 Diags->Report(diag::err_pch_targetopt_feature_mismatch) 358 << /* is-existing-feature */ true << Feature; 359 } 360 361 return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty(); 362 } 363 364 bool 365 PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts, 366 bool Complain, 367 bool AllowCompatibleDifferences) { 368 const LangOptions &ExistingLangOpts = PP.getLangOpts(); 369 return checkLanguageOptions(LangOpts, ExistingLangOpts, 370 Complain ? &Reader.Diags : nullptr, 371 AllowCompatibleDifferences); 372 } 373 374 bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts, 375 bool Complain, 376 bool AllowCompatibleDifferences) { 377 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts(); 378 return checkTargetOptions(TargetOpts, ExistingTargetOpts, 379 Complain ? &Reader.Diags : nullptr, 380 AllowCompatibleDifferences); 381 } 382 383 namespace { 384 385 typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> > 386 MacroDefinitionsMap; 387 typedef llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> > 388 DeclsMap; 389 390 } // end anonymous namespace 391 392 static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags, 393 DiagnosticsEngine &Diags, 394 bool Complain) { 395 typedef DiagnosticsEngine::Level Level; 396 397 // Check current mappings for new -Werror mappings, and the stored mappings 398 // for cases that were explicitly mapped to *not* be errors that are now 399 // errors because of options like -Werror. 400 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags }; 401 402 for (DiagnosticsEngine *MappingSource : MappingSources) { 403 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) { 404 diag::kind DiagID = DiagIDMappingPair.first; 405 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation()); 406 if (CurLevel < DiagnosticsEngine::Error) 407 continue; // not significant 408 Level StoredLevel = 409 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation()); 410 if (StoredLevel < DiagnosticsEngine::Error) { 411 if (Complain) 412 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" + 413 Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str(); 414 return true; 415 } 416 } 417 } 418 419 return false; 420 } 421 422 static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) { 423 diag::Severity Ext = Diags.getExtensionHandlingBehavior(); 424 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors()) 425 return true; 426 return Ext >= diag::Severity::Error; 427 } 428 429 static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags, 430 DiagnosticsEngine &Diags, 431 bool IsSystem, bool Complain) { 432 // Top-level options 433 if (IsSystem) { 434 if (Diags.getSuppressSystemWarnings()) 435 return false; 436 // If -Wsystem-headers was not enabled before, be conservative 437 if (StoredDiags.getSuppressSystemWarnings()) { 438 if (Complain) 439 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers"; 440 return true; 441 } 442 } 443 444 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) { 445 if (Complain) 446 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror"; 447 return true; 448 } 449 450 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() && 451 !StoredDiags.getEnableAllWarnings()) { 452 if (Complain) 453 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror"; 454 return true; 455 } 456 457 if (isExtHandlingFromDiagsError(Diags) && 458 !isExtHandlingFromDiagsError(StoredDiags)) { 459 if (Complain) 460 Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors"; 461 return true; 462 } 463 464 return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain); 465 } 466 467 /// Return the top import module if it is implicit, nullptr otherwise. 468 static Module *getTopImportImplicitModule(ModuleManager &ModuleMgr, 469 Preprocessor &PP) { 470 // If the original import came from a file explicitly generated by the user, 471 // don't check the diagnostic mappings. 472 // FIXME: currently this is approximated by checking whether this is not a 473 // module import of an implicitly-loaded module file. 474 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in 475 // the transitive closure of its imports, since unrelated modules cannot be 476 // imported until after this module finishes validation. 477 ModuleFile *TopImport = &*ModuleMgr.rbegin(); 478 while (!TopImport->ImportedBy.empty()) 479 TopImport = TopImport->ImportedBy[0]; 480 if (TopImport->Kind != MK_ImplicitModule) 481 return nullptr; 482 483 StringRef ModuleName = TopImport->ModuleName; 484 assert(!ModuleName.empty() && "diagnostic options read before module name"); 485 486 Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName); 487 assert(M && "missing module"); 488 return M; 489 } 490 491 bool PCHValidator::ReadDiagnosticOptions( 492 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) { 493 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics(); 494 IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs()); 495 IntrusiveRefCntPtr<DiagnosticsEngine> Diags( 496 new DiagnosticsEngine(DiagIDs, DiagOpts.get())); 497 // This should never fail, because we would have processed these options 498 // before writing them to an ASTFile. 499 ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false); 500 501 ModuleManager &ModuleMgr = Reader.getModuleManager(); 502 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then"); 503 504 Module *TopM = getTopImportImplicitModule(ModuleMgr, PP); 505 if (!TopM) 506 return false; 507 508 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that 509 // contains the union of their flags. 510 return checkDiagnosticMappings(*Diags, ExistingDiags, TopM->IsSystem, 511 Complain); 512 } 513 514 /// \brief Collect the macro definitions provided by the given preprocessor 515 /// options. 516 static void 517 collectMacroDefinitions(const PreprocessorOptions &PPOpts, 518 MacroDefinitionsMap &Macros, 519 SmallVectorImpl<StringRef> *MacroNames = nullptr) { 520 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) { 521 StringRef Macro = PPOpts.Macros[I].first; 522 bool IsUndef = PPOpts.Macros[I].second; 523 524 std::pair<StringRef, StringRef> MacroPair = Macro.split('='); 525 StringRef MacroName = MacroPair.first; 526 StringRef MacroBody = MacroPair.second; 527 528 // For an #undef'd macro, we only care about the name. 529 if (IsUndef) { 530 if (MacroNames && !Macros.count(MacroName)) 531 MacroNames->push_back(MacroName); 532 533 Macros[MacroName] = std::make_pair("", true); 534 continue; 535 } 536 537 // For a #define'd macro, figure out the actual definition. 538 if (MacroName.size() == Macro.size()) 539 MacroBody = "1"; 540 else { 541 // Note: GCC drops anything following an end-of-line character. 542 StringRef::size_type End = MacroBody.find_first_of("\n\r"); 543 MacroBody = MacroBody.substr(0, End); 544 } 545 546 if (MacroNames && !Macros.count(MacroName)) 547 MacroNames->push_back(MacroName); 548 Macros[MacroName] = std::make_pair(MacroBody, false); 549 } 550 } 551 552 /// \brief Check the preprocessor options deserialized from the control block 553 /// against the preprocessor options in an existing preprocessor. 554 /// 555 /// \param Diags If non-null, produce diagnostics for any mismatches incurred. 556 /// \param Validate If true, validate preprocessor options. If false, allow 557 /// macros defined by \p ExistingPPOpts to override those defined by 558 /// \p PPOpts in SuggestedPredefines. 559 static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts, 560 const PreprocessorOptions &ExistingPPOpts, 561 DiagnosticsEngine *Diags, 562 FileManager &FileMgr, 563 std::string &SuggestedPredefines, 564 const LangOptions &LangOpts, 565 bool Validate = true) { 566 // Check macro definitions. 567 MacroDefinitionsMap ASTFileMacros; 568 collectMacroDefinitions(PPOpts, ASTFileMacros); 569 MacroDefinitionsMap ExistingMacros; 570 SmallVector<StringRef, 4> ExistingMacroNames; 571 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames); 572 573 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) { 574 // Dig out the macro definition in the existing preprocessor options. 575 StringRef MacroName = ExistingMacroNames[I]; 576 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName]; 577 578 // Check whether we know anything about this macro name or not. 579 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known 580 = ASTFileMacros.find(MacroName); 581 if (!Validate || Known == ASTFileMacros.end()) { 582 // FIXME: Check whether this identifier was referenced anywhere in the 583 // AST file. If so, we should reject the AST file. Unfortunately, this 584 // information isn't in the control block. What shall we do about it? 585 586 if (Existing.second) { 587 SuggestedPredefines += "#undef "; 588 SuggestedPredefines += MacroName.str(); 589 SuggestedPredefines += '\n'; 590 } else { 591 SuggestedPredefines += "#define "; 592 SuggestedPredefines += MacroName.str(); 593 SuggestedPredefines += ' '; 594 SuggestedPredefines += Existing.first.str(); 595 SuggestedPredefines += '\n'; 596 } 597 continue; 598 } 599 600 // If the macro was defined in one but undef'd in the other, we have a 601 // conflict. 602 if (Existing.second != Known->second.second) { 603 if (Diags) { 604 Diags->Report(diag::err_pch_macro_def_undef) 605 << MacroName << Known->second.second; 606 } 607 return true; 608 } 609 610 // If the macro was #undef'd in both, or if the macro bodies are identical, 611 // it's fine. 612 if (Existing.second || Existing.first == Known->second.first) 613 continue; 614 615 // The macro bodies differ; complain. 616 if (Diags) { 617 Diags->Report(diag::err_pch_macro_def_conflict) 618 << MacroName << Known->second.first << Existing.first; 619 } 620 return true; 621 } 622 623 // Check whether we're using predefines. 624 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines && Validate) { 625 if (Diags) { 626 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines; 627 } 628 return true; 629 } 630 631 // Detailed record is important since it is used for the module cache hash. 632 if (LangOpts.Modules && 633 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord && Validate) { 634 if (Diags) { 635 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord; 636 } 637 return true; 638 } 639 640 // Compute the #include and #include_macros lines we need. 641 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) { 642 StringRef File = ExistingPPOpts.Includes[I]; 643 if (File == ExistingPPOpts.ImplicitPCHInclude) 644 continue; 645 646 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File) 647 != PPOpts.Includes.end()) 648 continue; 649 650 SuggestedPredefines += "#include \""; 651 SuggestedPredefines += File; 652 SuggestedPredefines += "\"\n"; 653 } 654 655 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) { 656 StringRef File = ExistingPPOpts.MacroIncludes[I]; 657 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(), 658 File) 659 != PPOpts.MacroIncludes.end()) 660 continue; 661 662 SuggestedPredefines += "#__include_macros \""; 663 SuggestedPredefines += File; 664 SuggestedPredefines += "\"\n##\n"; 665 } 666 667 return false; 668 } 669 670 bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, 671 bool Complain, 672 std::string &SuggestedPredefines) { 673 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts(); 674 675 return checkPreprocessorOptions(PPOpts, ExistingPPOpts, 676 Complain? &Reader.Diags : nullptr, 677 PP.getFileManager(), 678 SuggestedPredefines, 679 PP.getLangOpts()); 680 } 681 682 bool SimpleASTReaderListener::ReadPreprocessorOptions( 683 const PreprocessorOptions &PPOpts, 684 bool Complain, 685 std::string &SuggestedPredefines) { 686 return checkPreprocessorOptions(PPOpts, 687 PP.getPreprocessorOpts(), 688 nullptr, 689 PP.getFileManager(), 690 SuggestedPredefines, 691 PP.getLangOpts(), 692 false); 693 } 694 695 /// Check the header search options deserialized from the control block 696 /// against the header search options in an existing preprocessor. 697 /// 698 /// \param Diags If non-null, produce diagnostics for any mismatches incurred. 699 static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts, 700 StringRef SpecificModuleCachePath, 701 StringRef ExistingModuleCachePath, 702 DiagnosticsEngine *Diags, 703 const LangOptions &LangOpts) { 704 if (LangOpts.Modules) { 705 if (SpecificModuleCachePath != ExistingModuleCachePath) { 706 if (Diags) 707 Diags->Report(diag::err_pch_modulecache_mismatch) 708 << SpecificModuleCachePath << ExistingModuleCachePath; 709 return true; 710 } 711 } 712 713 return false; 714 } 715 716 bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, 717 StringRef SpecificModuleCachePath, 718 bool Complain) { 719 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath, 720 PP.getHeaderSearchInfo().getModuleCachePath(), 721 Complain ? &Reader.Diags : nullptr, 722 PP.getLangOpts()); 723 } 724 725 void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) { 726 PP.setCounterValue(Value); 727 } 728 729 //===----------------------------------------------------------------------===// 730 // AST reader implementation 731 //===----------------------------------------------------------------------===// 732 733 void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener, 734 bool TakeOwnership) { 735 DeserializationListener = Listener; 736 OwnsDeserializationListener = TakeOwnership; 737 } 738 739 unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) { 740 return serialization::ComputeHash(Sel); 741 } 742 743 std::pair<unsigned, unsigned> 744 ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) { 745 using namespace llvm::support; 746 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d); 747 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d); 748 return std::make_pair(KeyLen, DataLen); 749 } 750 751 ASTSelectorLookupTrait::internal_key_type 752 ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) { 753 using namespace llvm::support; 754 SelectorTable &SelTable = Reader.getContext().Selectors; 755 unsigned N = endian::readNext<uint16_t, little, unaligned>(d); 756 IdentifierInfo *FirstII = Reader.getLocalIdentifier( 757 F, endian::readNext<uint32_t, little, unaligned>(d)); 758 if (N == 0) 759 return SelTable.getNullarySelector(FirstII); 760 else if (N == 1) 761 return SelTable.getUnarySelector(FirstII); 762 763 SmallVector<IdentifierInfo *, 16> Args; 764 Args.push_back(FirstII); 765 for (unsigned I = 1; I != N; ++I) 766 Args.push_back(Reader.getLocalIdentifier( 767 F, endian::readNext<uint32_t, little, unaligned>(d))); 768 769 return SelTable.getSelector(N, Args.data()); 770 } 771 772 ASTSelectorLookupTrait::data_type 773 ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d, 774 unsigned DataLen) { 775 using namespace llvm::support; 776 777 data_type Result; 778 779 Result.ID = Reader.getGlobalSelectorID( 780 F, endian::readNext<uint32_t, little, unaligned>(d)); 781 unsigned FullInstanceBits = endian::readNext<uint16_t, little, unaligned>(d); 782 unsigned FullFactoryBits = endian::readNext<uint16_t, little, unaligned>(d); 783 Result.InstanceBits = FullInstanceBits & 0x3; 784 Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1; 785 Result.FactoryBits = FullFactoryBits & 0x3; 786 Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1; 787 unsigned NumInstanceMethods = FullInstanceBits >> 3; 788 unsigned NumFactoryMethods = FullFactoryBits >> 3; 789 790 // Load instance methods 791 for (unsigned I = 0; I != NumInstanceMethods; ++I) { 792 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>( 793 F, endian::readNext<uint32_t, little, unaligned>(d))) 794 Result.Instance.push_back(Method); 795 } 796 797 // Load factory methods 798 for (unsigned I = 0; I != NumFactoryMethods; ++I) { 799 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>( 800 F, endian::readNext<uint32_t, little, unaligned>(d))) 801 Result.Factory.push_back(Method); 802 } 803 804 return Result; 805 } 806 807 unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) { 808 return llvm::HashString(a); 809 } 810 811 std::pair<unsigned, unsigned> 812 ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) { 813 using namespace llvm::support; 814 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d); 815 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d); 816 return std::make_pair(KeyLen, DataLen); 817 } 818 819 ASTIdentifierLookupTraitBase::internal_key_type 820 ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) { 821 assert(n >= 2 && d[n-1] == '\0'); 822 return StringRef((const char*) d, n-1); 823 } 824 825 /// \brief Whether the given identifier is "interesting". 826 static bool isInterestingIdentifier(ASTReader &Reader, IdentifierInfo &II, 827 bool IsModule) { 828 return II.hadMacroDefinition() || 829 II.isPoisoned() || 830 (IsModule ? II.hasRevertedBuiltin() : II.getObjCOrBuiltinID()) || 831 II.hasRevertedTokenIDToIdentifier() || 832 (!(IsModule && Reader.getContext().getLangOpts().CPlusPlus) && 833 II.getFETokenInfo<void>()); 834 } 835 836 static bool readBit(unsigned &Bits) { 837 bool Value = Bits & 0x1; 838 Bits >>= 1; 839 return Value; 840 } 841 842 IdentID ASTIdentifierLookupTrait::ReadIdentifierID(const unsigned char *d) { 843 using namespace llvm::support; 844 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d); 845 return Reader.getGlobalIdentifierID(F, RawID >> 1); 846 } 847 848 static void markIdentifierFromAST(ASTReader &Reader, IdentifierInfo &II) { 849 if (!II.isFromAST()) { 850 II.setIsFromAST(); 851 bool IsModule = Reader.getPreprocessor().getCurrentModule() != nullptr; 852 if (isInterestingIdentifier(Reader, II, IsModule)) 853 II.setChangedSinceDeserialization(); 854 } 855 } 856 857 IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k, 858 const unsigned char* d, 859 unsigned DataLen) { 860 using namespace llvm::support; 861 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d); 862 bool IsInteresting = RawID & 0x01; 863 864 // Wipe out the "is interesting" bit. 865 RawID = RawID >> 1; 866 867 // Build the IdentifierInfo and link the identifier ID with it. 868 IdentifierInfo *II = KnownII; 869 if (!II) { 870 II = &Reader.getIdentifierTable().getOwn(k); 871 KnownII = II; 872 } 873 markIdentifierFromAST(Reader, *II); 874 Reader.markIdentifierUpToDate(II); 875 876 IdentID ID = Reader.getGlobalIdentifierID(F, RawID); 877 if (!IsInteresting) { 878 // For uninteresting identifiers, there's nothing else to do. Just notify 879 // the reader that we've finished loading this identifier. 880 Reader.SetIdentifierInfo(ID, II); 881 return II; 882 } 883 884 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d); 885 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d); 886 bool CPlusPlusOperatorKeyword = readBit(Bits); 887 bool HasRevertedTokenIDToIdentifier = readBit(Bits); 888 bool HasRevertedBuiltin = readBit(Bits); 889 bool Poisoned = readBit(Bits); 890 bool ExtensionToken = readBit(Bits); 891 bool HadMacroDefinition = readBit(Bits); 892 893 assert(Bits == 0 && "Extra bits in the identifier?"); 894 DataLen -= 8; 895 896 // Set or check the various bits in the IdentifierInfo structure. 897 // Token IDs are read-only. 898 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier) 899 II->revertTokenIDToIdentifier(); 900 if (!F.isModule()) 901 II->setObjCOrBuiltinID(ObjCOrBuiltinID); 902 else if (HasRevertedBuiltin && II->getBuiltinID()) { 903 II->revertBuiltin(); 904 assert((II->hasRevertedBuiltin() || 905 II->getObjCOrBuiltinID() == ObjCOrBuiltinID) && 906 "Incorrect ObjC keyword or builtin ID"); 907 } 908 assert(II->isExtensionToken() == ExtensionToken && 909 "Incorrect extension token flag"); 910 (void)ExtensionToken; 911 if (Poisoned) 912 II->setIsPoisoned(true); 913 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword && 914 "Incorrect C++ operator keyword flag"); 915 (void)CPlusPlusOperatorKeyword; 916 917 // If this identifier is a macro, deserialize the macro 918 // definition. 919 if (HadMacroDefinition) { 920 uint32_t MacroDirectivesOffset = 921 endian::readNext<uint32_t, little, unaligned>(d); 922 DataLen -= 4; 923 924 Reader.addPendingMacro(II, &F, MacroDirectivesOffset); 925 } 926 927 Reader.SetIdentifierInfo(ID, II); 928 929 // Read all of the declarations visible at global scope with this 930 // name. 931 if (DataLen > 0) { 932 SmallVector<uint32_t, 4> DeclIDs; 933 for (; DataLen > 0; DataLen -= 4) 934 DeclIDs.push_back(Reader.getGlobalDeclID( 935 F, endian::readNext<uint32_t, little, unaligned>(d))); 936 Reader.SetGloballyVisibleDecls(II, DeclIDs); 937 } 938 939 return II; 940 } 941 942 DeclarationNameKey::DeclarationNameKey(DeclarationName Name) 943 : Kind(Name.getNameKind()) { 944 switch (Kind) { 945 case DeclarationName::Identifier: 946 Data = (uint64_t)Name.getAsIdentifierInfo(); 947 break; 948 case DeclarationName::ObjCZeroArgSelector: 949 case DeclarationName::ObjCOneArgSelector: 950 case DeclarationName::ObjCMultiArgSelector: 951 Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr(); 952 break; 953 case DeclarationName::CXXOperatorName: 954 Data = Name.getCXXOverloadedOperator(); 955 break; 956 case DeclarationName::CXXLiteralOperatorName: 957 Data = (uint64_t)Name.getCXXLiteralIdentifier(); 958 break; 959 case DeclarationName::CXXDeductionGuideName: 960 Data = (uint64_t)Name.getCXXDeductionGuideTemplate() 961 ->getDeclName().getAsIdentifierInfo(); 962 break; 963 case DeclarationName::CXXConstructorName: 964 case DeclarationName::CXXDestructorName: 965 case DeclarationName::CXXConversionFunctionName: 966 case DeclarationName::CXXUsingDirective: 967 Data = 0; 968 break; 969 } 970 } 971 972 unsigned DeclarationNameKey::getHash() const { 973 llvm::FoldingSetNodeID ID; 974 ID.AddInteger(Kind); 975 976 switch (Kind) { 977 case DeclarationName::Identifier: 978 case DeclarationName::CXXLiteralOperatorName: 979 case DeclarationName::CXXDeductionGuideName: 980 ID.AddString(((IdentifierInfo*)Data)->getName()); 981 break; 982 case DeclarationName::ObjCZeroArgSelector: 983 case DeclarationName::ObjCOneArgSelector: 984 case DeclarationName::ObjCMultiArgSelector: 985 ID.AddInteger(serialization::ComputeHash(Selector(Data))); 986 break; 987 case DeclarationName::CXXOperatorName: 988 ID.AddInteger((OverloadedOperatorKind)Data); 989 break; 990 case DeclarationName::CXXConstructorName: 991 case DeclarationName::CXXDestructorName: 992 case DeclarationName::CXXConversionFunctionName: 993 case DeclarationName::CXXUsingDirective: 994 break; 995 } 996 997 return ID.ComputeHash(); 998 } 999 1000 ModuleFile * 1001 ASTDeclContextNameLookupTrait::ReadFileRef(const unsigned char *&d) { 1002 using namespace llvm::support; 1003 uint32_t ModuleFileID = endian::readNext<uint32_t, little, unaligned>(d); 1004 return Reader.getLocalModuleFile(F, ModuleFileID); 1005 } 1006 1007 std::pair<unsigned, unsigned> 1008 ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char *&d) { 1009 using namespace llvm::support; 1010 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d); 1011 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d); 1012 return std::make_pair(KeyLen, DataLen); 1013 } 1014 1015 ASTDeclContextNameLookupTrait::internal_key_type 1016 ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) { 1017 using namespace llvm::support; 1018 1019 auto Kind = (DeclarationName::NameKind)*d++; 1020 uint64_t Data; 1021 switch (Kind) { 1022 case DeclarationName::Identifier: 1023 case DeclarationName::CXXLiteralOperatorName: 1024 case DeclarationName::CXXDeductionGuideName: 1025 Data = (uint64_t)Reader.getLocalIdentifier( 1026 F, endian::readNext<uint32_t, little, unaligned>(d)); 1027 break; 1028 case DeclarationName::ObjCZeroArgSelector: 1029 case DeclarationName::ObjCOneArgSelector: 1030 case DeclarationName::ObjCMultiArgSelector: 1031 Data = 1032 (uint64_t)Reader.getLocalSelector( 1033 F, endian::readNext<uint32_t, little, unaligned>( 1034 d)).getAsOpaquePtr(); 1035 break; 1036 case DeclarationName::CXXOperatorName: 1037 Data = *d++; // OverloadedOperatorKind 1038 break; 1039 case DeclarationName::CXXConstructorName: 1040 case DeclarationName::CXXDestructorName: 1041 case DeclarationName::CXXConversionFunctionName: 1042 case DeclarationName::CXXUsingDirective: 1043 Data = 0; 1044 break; 1045 } 1046 1047 return DeclarationNameKey(Kind, Data); 1048 } 1049 1050 void ASTDeclContextNameLookupTrait::ReadDataInto(internal_key_type, 1051 const unsigned char *d, 1052 unsigned DataLen, 1053 data_type_builder &Val) { 1054 using namespace llvm::support; 1055 for (unsigned NumDecls = DataLen / 4; NumDecls; --NumDecls) { 1056 uint32_t LocalID = endian::readNext<uint32_t, little, unaligned>(d); 1057 Val.insert(Reader.getGlobalDeclID(F, LocalID)); 1058 } 1059 } 1060 1061 bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M, 1062 BitstreamCursor &Cursor, 1063 uint64_t Offset, 1064 DeclContext *DC) { 1065 assert(Offset != 0); 1066 1067 SavedStreamPosition SavedPosition(Cursor); 1068 Cursor.JumpToBit(Offset); 1069 1070 RecordData Record; 1071 StringRef Blob; 1072 unsigned Code = Cursor.ReadCode(); 1073 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob); 1074 if (RecCode != DECL_CONTEXT_LEXICAL) { 1075 Error("Expected lexical block"); 1076 return true; 1077 } 1078 1079 assert(!isa<TranslationUnitDecl>(DC) && 1080 "expected a TU_UPDATE_LEXICAL record for TU"); 1081 // If we are handling a C++ class template instantiation, we can see multiple 1082 // lexical updates for the same record. It's important that we select only one 1083 // of them, so that field numbering works properly. Just pick the first one we 1084 // see. 1085 auto &Lex = LexicalDecls[DC]; 1086 if (!Lex.first) { 1087 Lex = std::make_pair( 1088 &M, llvm::makeArrayRef( 1089 reinterpret_cast<const llvm::support::unaligned_uint32_t *>( 1090 Blob.data()), 1091 Blob.size() / 4)); 1092 } 1093 DC->setHasExternalLexicalStorage(true); 1094 return false; 1095 } 1096 1097 bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M, 1098 BitstreamCursor &Cursor, 1099 uint64_t Offset, 1100 DeclID ID) { 1101 assert(Offset != 0); 1102 1103 SavedStreamPosition SavedPosition(Cursor); 1104 Cursor.JumpToBit(Offset); 1105 1106 RecordData Record; 1107 StringRef Blob; 1108 unsigned Code = Cursor.ReadCode(); 1109 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob); 1110 if (RecCode != DECL_CONTEXT_VISIBLE) { 1111 Error("Expected visible lookup table block"); 1112 return true; 1113 } 1114 1115 // We can't safely determine the primary context yet, so delay attaching the 1116 // lookup table until we're done with recursive deserialization. 1117 auto *Data = (const unsigned char*)Blob.data(); 1118 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&M, Data}); 1119 return false; 1120 } 1121 1122 void ASTReader::Error(StringRef Msg) const { 1123 Error(diag::err_fe_pch_malformed, Msg); 1124 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight() && 1125 !PP.getHeaderSearchInfo().getModuleCachePath().empty()) { 1126 Diag(diag::note_module_cache_path) 1127 << PP.getHeaderSearchInfo().getModuleCachePath(); 1128 } 1129 } 1130 1131 void ASTReader::Error(unsigned DiagID, 1132 StringRef Arg1, StringRef Arg2) const { 1133 if (Diags.isDiagnosticInFlight()) 1134 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2); 1135 else 1136 Diag(DiagID) << Arg1 << Arg2; 1137 } 1138 1139 //===----------------------------------------------------------------------===// 1140 // Source Manager Deserialization 1141 //===----------------------------------------------------------------------===// 1142 1143 /// \brief Read the line table in the source manager block. 1144 /// \returns true if there was an error. 1145 bool ASTReader::ParseLineTable(ModuleFile &F, 1146 const RecordData &Record) { 1147 unsigned Idx = 0; 1148 LineTableInfo &LineTable = SourceMgr.getLineTable(); 1149 1150 // Parse the file names 1151 std::map<int, int> FileIDs; 1152 for (unsigned I = 0; Record[Idx]; ++I) { 1153 // Extract the file name 1154 auto Filename = ReadPath(F, Record, Idx); 1155 FileIDs[I] = LineTable.getLineTableFilenameID(Filename); 1156 } 1157 ++Idx; 1158 1159 // Parse the line entries 1160 std::vector<LineEntry> Entries; 1161 while (Idx < Record.size()) { 1162 int FID = Record[Idx++]; 1163 assert(FID >= 0 && "Serialized line entries for non-local file."); 1164 // Remap FileID from 1-based old view. 1165 FID += F.SLocEntryBaseID - 1; 1166 1167 // Extract the line entries 1168 unsigned NumEntries = Record[Idx++]; 1169 assert(NumEntries && "no line entries for file ID"); 1170 Entries.clear(); 1171 Entries.reserve(NumEntries); 1172 for (unsigned I = 0; I != NumEntries; ++I) { 1173 unsigned FileOffset = Record[Idx++]; 1174 unsigned LineNo = Record[Idx++]; 1175 int FilenameID = FileIDs[Record[Idx++]]; 1176 SrcMgr::CharacteristicKind FileKind 1177 = (SrcMgr::CharacteristicKind)Record[Idx++]; 1178 unsigned IncludeOffset = Record[Idx++]; 1179 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID, 1180 FileKind, IncludeOffset)); 1181 } 1182 LineTable.AddEntry(FileID::get(FID), Entries); 1183 } 1184 1185 return false; 1186 } 1187 1188 /// \brief Read a source manager block 1189 bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) { 1190 using namespace SrcMgr; 1191 1192 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor; 1193 1194 // Set the source-location entry cursor to the current position in 1195 // the stream. This cursor will be used to read the contents of the 1196 // source manager block initially, and then lazily read 1197 // source-location entries as needed. 1198 SLocEntryCursor = F.Stream; 1199 1200 // The stream itself is going to skip over the source manager block. 1201 if (F.Stream.SkipBlock()) { 1202 Error("malformed block record in AST file"); 1203 return true; 1204 } 1205 1206 // Enter the source manager block. 1207 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) { 1208 Error("malformed source manager block record in AST file"); 1209 return true; 1210 } 1211 1212 RecordData Record; 1213 while (true) { 1214 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks(); 1215 1216 switch (E.Kind) { 1217 case llvm::BitstreamEntry::SubBlock: // Handled for us already. 1218 case llvm::BitstreamEntry::Error: 1219 Error("malformed block record in AST file"); 1220 return true; 1221 case llvm::BitstreamEntry::EndBlock: 1222 return false; 1223 case llvm::BitstreamEntry::Record: 1224 // The interesting case. 1225 break; 1226 } 1227 1228 // Read a record. 1229 Record.clear(); 1230 StringRef Blob; 1231 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) { 1232 default: // Default behavior: ignore. 1233 break; 1234 1235 case SM_SLOC_FILE_ENTRY: 1236 case SM_SLOC_BUFFER_ENTRY: 1237 case SM_SLOC_EXPANSION_ENTRY: 1238 // Once we hit one of the source location entries, we're done. 1239 return false; 1240 } 1241 } 1242 } 1243 1244 /// \brief If a header file is not found at the path that we expect it to be 1245 /// and the PCH file was moved from its original location, try to resolve the 1246 /// file by assuming that header+PCH were moved together and the header is in 1247 /// the same place relative to the PCH. 1248 static std::string 1249 resolveFileRelativeToOriginalDir(const std::string &Filename, 1250 const std::string &OriginalDir, 1251 const std::string &CurrDir) { 1252 assert(OriginalDir != CurrDir && 1253 "No point trying to resolve the file if the PCH dir didn't change"); 1254 using namespace llvm::sys; 1255 SmallString<128> filePath(Filename); 1256 fs::make_absolute(filePath); 1257 assert(path::is_absolute(OriginalDir)); 1258 SmallString<128> currPCHPath(CurrDir); 1259 1260 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)), 1261 fileDirE = path::end(path::parent_path(filePath)); 1262 path::const_iterator origDirI = path::begin(OriginalDir), 1263 origDirE = path::end(OriginalDir); 1264 // Skip the common path components from filePath and OriginalDir. 1265 while (fileDirI != fileDirE && origDirI != origDirE && 1266 *fileDirI == *origDirI) { 1267 ++fileDirI; 1268 ++origDirI; 1269 } 1270 for (; origDirI != origDirE; ++origDirI) 1271 path::append(currPCHPath, ".."); 1272 path::append(currPCHPath, fileDirI, fileDirE); 1273 path::append(currPCHPath, path::filename(Filename)); 1274 return currPCHPath.str(); 1275 } 1276 1277 bool ASTReader::ReadSLocEntry(int ID) { 1278 if (ID == 0) 1279 return false; 1280 1281 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) { 1282 Error("source location entry ID out-of-range for AST file"); 1283 return true; 1284 } 1285 1286 // Local helper to read the (possibly-compressed) buffer data following the 1287 // entry record. 1288 auto ReadBuffer = [this]( 1289 BitstreamCursor &SLocEntryCursor, 1290 StringRef Name) -> std::unique_ptr<llvm::MemoryBuffer> { 1291 RecordData Record; 1292 StringRef Blob; 1293 unsigned Code = SLocEntryCursor.ReadCode(); 1294 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob); 1295 1296 if (RecCode == SM_SLOC_BUFFER_BLOB_COMPRESSED) { 1297 if (!llvm::zlib::isAvailable()) { 1298 Error("zlib is not available"); 1299 return nullptr; 1300 } 1301 SmallString<0> Uncompressed; 1302 if (llvm::Error E = 1303 llvm::zlib::uncompress(Blob, Uncompressed, Record[0])) { 1304 Error("could not decompress embedded file contents: " + 1305 llvm::toString(std::move(E))); 1306 return nullptr; 1307 } 1308 return llvm::MemoryBuffer::getMemBufferCopy(Uncompressed, Name); 1309 } else if (RecCode == SM_SLOC_BUFFER_BLOB) { 1310 return llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name, true); 1311 } else { 1312 Error("AST record has invalid code"); 1313 return nullptr; 1314 } 1315 }; 1316 1317 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second; 1318 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]); 1319 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor; 1320 unsigned BaseOffset = F->SLocEntryBaseOffset; 1321 1322 ++NumSLocEntriesRead; 1323 llvm::BitstreamEntry Entry = SLocEntryCursor.advance(); 1324 if (Entry.Kind != llvm::BitstreamEntry::Record) { 1325 Error("incorrectly-formatted source location entry in AST file"); 1326 return true; 1327 } 1328 1329 RecordData Record; 1330 StringRef Blob; 1331 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) { 1332 default: 1333 Error("incorrectly-formatted source location entry in AST file"); 1334 return true; 1335 1336 case SM_SLOC_FILE_ENTRY: { 1337 // We will detect whether a file changed and return 'Failure' for it, but 1338 // we will also try to fail gracefully by setting up the SLocEntry. 1339 unsigned InputID = Record[4]; 1340 InputFile IF = getInputFile(*F, InputID); 1341 const FileEntry *File = IF.getFile(); 1342 bool OverriddenBuffer = IF.isOverridden(); 1343 1344 // Note that we only check if a File was returned. If it was out-of-date 1345 // we have complained but we will continue creating a FileID to recover 1346 // gracefully. 1347 if (!File) 1348 return true; 1349 1350 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]); 1351 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) { 1352 // This is the module's main file. 1353 IncludeLoc = getImportLocation(F); 1354 } 1355 SrcMgr::CharacteristicKind 1356 FileCharacter = (SrcMgr::CharacteristicKind)Record[2]; 1357 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter, 1358 ID, BaseOffset + Record[0]); 1359 SrcMgr::FileInfo &FileInfo = 1360 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile()); 1361 FileInfo.NumCreatedFIDs = Record[5]; 1362 if (Record[3]) 1363 FileInfo.setHasLineDirectives(); 1364 1365 const DeclID *FirstDecl = F->FileSortedDecls + Record[6]; 1366 unsigned NumFileDecls = Record[7]; 1367 if (NumFileDecls) { 1368 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?"); 1369 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl, 1370 NumFileDecls)); 1371 } 1372 1373 const SrcMgr::ContentCache *ContentCache 1374 = SourceMgr.getOrCreateContentCache(File, 1375 /*isSystemFile=*/FileCharacter != SrcMgr::C_User); 1376 if (OverriddenBuffer && !ContentCache->BufferOverridden && 1377 ContentCache->ContentsEntry == ContentCache->OrigEntry && 1378 !ContentCache->getRawBuffer()) { 1379 auto Buffer = ReadBuffer(SLocEntryCursor, File->getName()); 1380 if (!Buffer) 1381 return true; 1382 SourceMgr.overrideFileContents(File, std::move(Buffer)); 1383 } 1384 1385 break; 1386 } 1387 1388 case SM_SLOC_BUFFER_ENTRY: { 1389 const char *Name = Blob.data(); 1390 unsigned Offset = Record[0]; 1391 SrcMgr::CharacteristicKind 1392 FileCharacter = (SrcMgr::CharacteristicKind)Record[2]; 1393 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]); 1394 if (IncludeLoc.isInvalid() && F->isModule()) { 1395 IncludeLoc = getImportLocation(F); 1396 } 1397 1398 auto Buffer = ReadBuffer(SLocEntryCursor, Name); 1399 if (!Buffer) 1400 return true; 1401 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID, 1402 BaseOffset + Offset, IncludeLoc); 1403 break; 1404 } 1405 1406 case SM_SLOC_EXPANSION_ENTRY: { 1407 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]); 1408 SourceMgr.createExpansionLoc(SpellingLoc, 1409 ReadSourceLocation(*F, Record[2]), 1410 ReadSourceLocation(*F, Record[3]), 1411 Record[4], 1412 ID, 1413 BaseOffset + Record[0]); 1414 break; 1415 } 1416 } 1417 1418 return false; 1419 } 1420 1421 std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) { 1422 if (ID == 0) 1423 return std::make_pair(SourceLocation(), ""); 1424 1425 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) { 1426 Error("source location entry ID out-of-range for AST file"); 1427 return std::make_pair(SourceLocation(), ""); 1428 } 1429 1430 // Find which module file this entry lands in. 1431 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second; 1432 if (!M->isModule()) 1433 return std::make_pair(SourceLocation(), ""); 1434 1435 // FIXME: Can we map this down to a particular submodule? That would be 1436 // ideal. 1437 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName)); 1438 } 1439 1440 /// \brief Find the location where the module F is imported. 1441 SourceLocation ASTReader::getImportLocation(ModuleFile *F) { 1442 if (F->ImportLoc.isValid()) 1443 return F->ImportLoc; 1444 1445 // Otherwise we have a PCH. It's considered to be "imported" at the first 1446 // location of its includer. 1447 if (F->ImportedBy.empty() || !F->ImportedBy[0]) { 1448 // Main file is the importer. 1449 assert(SourceMgr.getMainFileID().isValid() && "missing main file"); 1450 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID()); 1451 } 1452 return F->ImportedBy[0]->FirstLoc; 1453 } 1454 1455 /// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the 1456 /// specified cursor. Read the abbreviations that are at the top of the block 1457 /// and then leave the cursor pointing into the block. 1458 bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) { 1459 if (Cursor.EnterSubBlock(BlockID)) 1460 return true; 1461 1462 while (true) { 1463 uint64_t Offset = Cursor.GetCurrentBitNo(); 1464 unsigned Code = Cursor.ReadCode(); 1465 1466 // We expect all abbrevs to be at the start of the block. 1467 if (Code != llvm::bitc::DEFINE_ABBREV) { 1468 Cursor.JumpToBit(Offset); 1469 return false; 1470 } 1471 Cursor.ReadAbbrevRecord(); 1472 } 1473 } 1474 1475 Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record, 1476 unsigned &Idx) { 1477 Token Tok; 1478 Tok.startToken(); 1479 Tok.setLocation(ReadSourceLocation(F, Record, Idx)); 1480 Tok.setLength(Record[Idx++]); 1481 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++])) 1482 Tok.setIdentifierInfo(II); 1483 Tok.setKind((tok::TokenKind)Record[Idx++]); 1484 Tok.setFlag((Token::TokenFlags)Record[Idx++]); 1485 return Tok; 1486 } 1487 1488 MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) { 1489 BitstreamCursor &Stream = F.MacroCursor; 1490 1491 // Keep track of where we are in the stream, then jump back there 1492 // after reading this macro. 1493 SavedStreamPosition SavedPosition(Stream); 1494 1495 Stream.JumpToBit(Offset); 1496 RecordData Record; 1497 SmallVector<IdentifierInfo*, 16> MacroArgs; 1498 MacroInfo *Macro = nullptr; 1499 1500 while (true) { 1501 // Advance to the next record, but if we get to the end of the block, don't 1502 // pop it (removing all the abbreviations from the cursor) since we want to 1503 // be able to reseek within the block and read entries. 1504 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd; 1505 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags); 1506 1507 switch (Entry.Kind) { 1508 case llvm::BitstreamEntry::SubBlock: // Handled for us already. 1509 case llvm::BitstreamEntry::Error: 1510 Error("malformed block record in AST file"); 1511 return Macro; 1512 case llvm::BitstreamEntry::EndBlock: 1513 return Macro; 1514 case llvm::BitstreamEntry::Record: 1515 // The interesting case. 1516 break; 1517 } 1518 1519 // Read a record. 1520 Record.clear(); 1521 PreprocessorRecordTypes RecType = 1522 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record); 1523 switch (RecType) { 1524 case PP_MODULE_MACRO: 1525 case PP_MACRO_DIRECTIVE_HISTORY: 1526 return Macro; 1527 1528 case PP_MACRO_OBJECT_LIKE: 1529 case PP_MACRO_FUNCTION_LIKE: { 1530 // If we already have a macro, that means that we've hit the end 1531 // of the definition of the macro we were looking for. We're 1532 // done. 1533 if (Macro) 1534 return Macro; 1535 1536 unsigned NextIndex = 1; // Skip identifier ID. 1537 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]); 1538 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex); 1539 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID); 1540 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex)); 1541 MI->setIsUsed(Record[NextIndex++]); 1542 MI->setUsedForHeaderGuard(Record[NextIndex++]); 1543 1544 if (RecType == PP_MACRO_FUNCTION_LIKE) { 1545 // Decode function-like macro info. 1546 bool isC99VarArgs = Record[NextIndex++]; 1547 bool isGNUVarArgs = Record[NextIndex++]; 1548 bool hasCommaPasting = Record[NextIndex++]; 1549 MacroArgs.clear(); 1550 unsigned NumArgs = Record[NextIndex++]; 1551 for (unsigned i = 0; i != NumArgs; ++i) 1552 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++])); 1553 1554 // Install function-like macro info. 1555 MI->setIsFunctionLike(); 1556 if (isC99VarArgs) MI->setIsC99Varargs(); 1557 if (isGNUVarArgs) MI->setIsGNUVarargs(); 1558 if (hasCommaPasting) MI->setHasCommaPasting(); 1559 MI->setArgumentList(MacroArgs, PP.getPreprocessorAllocator()); 1560 } 1561 1562 // Remember that we saw this macro last so that we add the tokens that 1563 // form its body to it. 1564 Macro = MI; 1565 1566 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() && 1567 Record[NextIndex]) { 1568 // We have a macro definition. Register the association 1569 PreprocessedEntityID 1570 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]); 1571 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord(); 1572 PreprocessingRecord::PPEntityID PPID = 1573 PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true); 1574 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>( 1575 PPRec.getPreprocessedEntity(PPID)); 1576 if (PPDef) 1577 PPRec.RegisterMacroDefinition(Macro, PPDef); 1578 } 1579 1580 ++NumMacrosRead; 1581 break; 1582 } 1583 1584 case PP_TOKEN: { 1585 // If we see a TOKEN before a PP_MACRO_*, then the file is 1586 // erroneous, just pretend we didn't see this. 1587 if (!Macro) break; 1588 1589 unsigned Idx = 0; 1590 Token Tok = ReadToken(F, Record, Idx); 1591 Macro->AddTokenToBody(Tok); 1592 break; 1593 } 1594 } 1595 } 1596 } 1597 1598 PreprocessedEntityID 1599 ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, 1600 unsigned LocalID) const { 1601 if (!M.ModuleOffsetMap.empty()) 1602 ReadModuleOffsetMap(M); 1603 1604 ContinuousRangeMap<uint32_t, int, 2>::const_iterator 1605 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS); 1606 assert(I != M.PreprocessedEntityRemap.end() 1607 && "Invalid index into preprocessed entity index remap"); 1608 1609 return LocalID + I->second; 1610 } 1611 1612 unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) { 1613 return llvm::hash_combine(ikey.Size, ikey.ModTime); 1614 } 1615 1616 HeaderFileInfoTrait::internal_key_type 1617 HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) { 1618 internal_key_type ikey = {FE->getSize(), 1619 M.HasTimestamps ? FE->getModificationTime() : 0, 1620 FE->getName(), /*Imported*/ false}; 1621 return ikey; 1622 } 1623 1624 bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) { 1625 if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime)) 1626 return false; 1627 1628 if (llvm::sys::path::is_absolute(a.Filename) && a.Filename == b.Filename) 1629 return true; 1630 1631 // Determine whether the actual files are equivalent. 1632 FileManager &FileMgr = Reader.getFileManager(); 1633 auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* { 1634 if (!Key.Imported) 1635 return FileMgr.getFile(Key.Filename); 1636 1637 std::string Resolved = Key.Filename; 1638 Reader.ResolveImportedPath(M, Resolved); 1639 return FileMgr.getFile(Resolved); 1640 }; 1641 1642 const FileEntry *FEA = GetFile(a); 1643 const FileEntry *FEB = GetFile(b); 1644 return FEA && FEA == FEB; 1645 } 1646 1647 std::pair<unsigned, unsigned> 1648 HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) { 1649 using namespace llvm::support; 1650 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d); 1651 unsigned DataLen = (unsigned) *d++; 1652 return std::make_pair(KeyLen, DataLen); 1653 } 1654 1655 HeaderFileInfoTrait::internal_key_type 1656 HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) { 1657 using namespace llvm::support; 1658 internal_key_type ikey; 1659 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d)); 1660 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d)); 1661 ikey.Filename = (const char *)d; 1662 ikey.Imported = true; 1663 return ikey; 1664 } 1665 1666 HeaderFileInfoTrait::data_type 1667 HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d, 1668 unsigned DataLen) { 1669 const unsigned char *End = d + DataLen; 1670 using namespace llvm::support; 1671 HeaderFileInfo HFI; 1672 unsigned Flags = *d++; 1673 // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp. 1674 HFI.isImport |= (Flags >> 4) & 0x01; 1675 HFI.isPragmaOnce |= (Flags >> 3) & 0x01; 1676 HFI.DirInfo = (Flags >> 1) & 0x03; 1677 HFI.IndexHeaderMapHeader = Flags & 0x01; 1678 // FIXME: Find a better way to handle this. Maybe just store a 1679 // "has been included" flag? 1680 HFI.NumIncludes = std::max(endian::readNext<uint16_t, little, unaligned>(d), 1681 HFI.NumIncludes); 1682 HFI.ControllingMacroID = Reader.getGlobalIdentifierID( 1683 M, endian::readNext<uint32_t, little, unaligned>(d)); 1684 if (unsigned FrameworkOffset = 1685 endian::readNext<uint32_t, little, unaligned>(d)) { 1686 // The framework offset is 1 greater than the actual offset, 1687 // since 0 is used as an indicator for "no framework name". 1688 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1); 1689 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName); 1690 } 1691 1692 assert((End - d) % 4 == 0 && 1693 "Wrong data length in HeaderFileInfo deserialization"); 1694 while (d != End) { 1695 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d); 1696 auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 3); 1697 LocalSMID >>= 2; 1698 1699 // This header is part of a module. Associate it with the module to enable 1700 // implicit module import. 1701 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID); 1702 Module *Mod = Reader.getSubmodule(GlobalSMID); 1703 FileManager &FileMgr = Reader.getFileManager(); 1704 ModuleMap &ModMap = 1705 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap(); 1706 1707 std::string Filename = key.Filename; 1708 if (key.Imported) 1709 Reader.ResolveImportedPath(M, Filename); 1710 // FIXME: This is not always the right filename-as-written, but we're not 1711 // going to use this information to rebuild the module, so it doesn't make 1712 // a lot of difference. 1713 Module::Header H = { key.Filename, FileMgr.getFile(Filename) }; 1714 ModMap.addHeader(Mod, H, HeaderRole, /*Imported*/true); 1715 HFI.isModuleHeader |= !(HeaderRole & ModuleMap::TextualHeader); 1716 } 1717 1718 // This HeaderFileInfo was externally loaded. 1719 HFI.External = true; 1720 HFI.IsValid = true; 1721 return HFI; 1722 } 1723 1724 void ASTReader::addPendingMacro(IdentifierInfo *II, 1725 ModuleFile *M, 1726 uint64_t MacroDirectivesOffset) { 1727 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard"); 1728 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset)); 1729 } 1730 1731 void ASTReader::ReadDefinedMacros() { 1732 // Note that we are loading defined macros. 1733 Deserializing Macros(this); 1734 1735 for (ModuleFile &I : llvm::reverse(ModuleMgr)) { 1736 BitstreamCursor &MacroCursor = I.MacroCursor; 1737 1738 // If there was no preprocessor block, skip this file. 1739 if (MacroCursor.getBitcodeBytes().empty()) 1740 continue; 1741 1742 BitstreamCursor Cursor = MacroCursor; 1743 Cursor.JumpToBit(I.MacroStartOffset); 1744 1745 RecordData Record; 1746 while (true) { 1747 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks(); 1748 1749 switch (E.Kind) { 1750 case llvm::BitstreamEntry::SubBlock: // Handled for us already. 1751 case llvm::BitstreamEntry::Error: 1752 Error("malformed block record in AST file"); 1753 return; 1754 case llvm::BitstreamEntry::EndBlock: 1755 goto NextCursor; 1756 1757 case llvm::BitstreamEntry::Record: 1758 Record.clear(); 1759 switch (Cursor.readRecord(E.ID, Record)) { 1760 default: // Default behavior: ignore. 1761 break; 1762 1763 case PP_MACRO_OBJECT_LIKE: 1764 case PP_MACRO_FUNCTION_LIKE: { 1765 IdentifierInfo *II = getLocalIdentifier(I, Record[0]); 1766 if (II->isOutOfDate()) 1767 updateOutOfDateIdentifier(*II); 1768 break; 1769 } 1770 1771 case PP_TOKEN: 1772 // Ignore tokens. 1773 break; 1774 } 1775 break; 1776 } 1777 } 1778 NextCursor: ; 1779 } 1780 } 1781 1782 namespace { 1783 1784 /// \brief Visitor class used to look up identifirs in an AST file. 1785 class IdentifierLookupVisitor { 1786 StringRef Name; 1787 unsigned NameHash; 1788 unsigned PriorGeneration; 1789 unsigned &NumIdentifierLookups; 1790 unsigned &NumIdentifierLookupHits; 1791 IdentifierInfo *Found; 1792 1793 public: 1794 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration, 1795 unsigned &NumIdentifierLookups, 1796 unsigned &NumIdentifierLookupHits) 1797 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)), 1798 PriorGeneration(PriorGeneration), 1799 NumIdentifierLookups(NumIdentifierLookups), 1800 NumIdentifierLookupHits(NumIdentifierLookupHits), 1801 Found() 1802 { 1803 } 1804 1805 bool operator()(ModuleFile &M) { 1806 // If we've already searched this module file, skip it now. 1807 if (M.Generation <= PriorGeneration) 1808 return true; 1809 1810 ASTIdentifierLookupTable *IdTable 1811 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable; 1812 if (!IdTable) 1813 return false; 1814 1815 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M, 1816 Found); 1817 ++NumIdentifierLookups; 1818 ASTIdentifierLookupTable::iterator Pos = 1819 IdTable->find_hashed(Name, NameHash, &Trait); 1820 if (Pos == IdTable->end()) 1821 return false; 1822 1823 // Dereferencing the iterator has the effect of building the 1824 // IdentifierInfo node and populating it with the various 1825 // declarations it needs. 1826 ++NumIdentifierLookupHits; 1827 Found = *Pos; 1828 return true; 1829 } 1830 1831 // \brief Retrieve the identifier info found within the module 1832 // files. 1833 IdentifierInfo *getIdentifierInfo() const { return Found; } 1834 }; 1835 1836 } // end anonymous namespace 1837 1838 void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) { 1839 // Note that we are loading an identifier. 1840 Deserializing AnIdentifier(this); 1841 1842 unsigned PriorGeneration = 0; 1843 if (getContext().getLangOpts().Modules) 1844 PriorGeneration = IdentifierGeneration[&II]; 1845 1846 // If there is a global index, look there first to determine which modules 1847 // provably do not have any results for this identifier. 1848 GlobalModuleIndex::HitSet Hits; 1849 GlobalModuleIndex::HitSet *HitsPtr = nullptr; 1850 if (!loadGlobalIndex()) { 1851 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) { 1852 HitsPtr = &Hits; 1853 } 1854 } 1855 1856 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration, 1857 NumIdentifierLookups, 1858 NumIdentifierLookupHits); 1859 ModuleMgr.visit(Visitor, HitsPtr); 1860 markIdentifierUpToDate(&II); 1861 } 1862 1863 void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) { 1864 if (!II) 1865 return; 1866 1867 II->setOutOfDate(false); 1868 1869 // Update the generation for this identifier. 1870 if (getContext().getLangOpts().Modules) 1871 IdentifierGeneration[II] = getGeneration(); 1872 } 1873 1874 void ASTReader::resolvePendingMacro(IdentifierInfo *II, 1875 const PendingMacroInfo &PMInfo) { 1876 ModuleFile &M = *PMInfo.M; 1877 1878 BitstreamCursor &Cursor = M.MacroCursor; 1879 SavedStreamPosition SavedPosition(Cursor); 1880 Cursor.JumpToBit(PMInfo.MacroDirectivesOffset); 1881 1882 struct ModuleMacroRecord { 1883 SubmoduleID SubModID; 1884 MacroInfo *MI; 1885 SmallVector<SubmoduleID, 8> Overrides; 1886 }; 1887 llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros; 1888 1889 // We expect to see a sequence of PP_MODULE_MACRO records listing exported 1890 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete 1891 // macro histroy. 1892 RecordData Record; 1893 while (true) { 1894 llvm::BitstreamEntry Entry = 1895 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd); 1896 if (Entry.Kind != llvm::BitstreamEntry::Record) { 1897 Error("malformed block record in AST file"); 1898 return; 1899 } 1900 1901 Record.clear(); 1902 switch ((PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record)) { 1903 case PP_MACRO_DIRECTIVE_HISTORY: 1904 break; 1905 1906 case PP_MODULE_MACRO: { 1907 ModuleMacros.push_back(ModuleMacroRecord()); 1908 auto &Info = ModuleMacros.back(); 1909 Info.SubModID = getGlobalSubmoduleID(M, Record[0]); 1910 Info.MI = getMacro(getGlobalMacroID(M, Record[1])); 1911 for (int I = 2, N = Record.size(); I != N; ++I) 1912 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I])); 1913 continue; 1914 } 1915 1916 default: 1917 Error("malformed block record in AST file"); 1918 return; 1919 } 1920 1921 // We found the macro directive history; that's the last record 1922 // for this macro. 1923 break; 1924 } 1925 1926 // Module macros are listed in reverse dependency order. 1927 { 1928 std::reverse(ModuleMacros.begin(), ModuleMacros.end()); 1929 llvm::SmallVector<ModuleMacro*, 8> Overrides; 1930 for (auto &MMR : ModuleMacros) { 1931 Overrides.clear(); 1932 for (unsigned ModID : MMR.Overrides) { 1933 Module *Mod = getSubmodule(ModID); 1934 auto *Macro = PP.getModuleMacro(Mod, II); 1935 assert(Macro && "missing definition for overridden macro"); 1936 Overrides.push_back(Macro); 1937 } 1938 1939 bool Inserted = false; 1940 Module *Owner = getSubmodule(MMR.SubModID); 1941 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted); 1942 } 1943 } 1944 1945 // Don't read the directive history for a module; we don't have anywhere 1946 // to put it. 1947 if (M.isModule()) 1948 return; 1949 1950 // Deserialize the macro directives history in reverse source-order. 1951 MacroDirective *Latest = nullptr, *Earliest = nullptr; 1952 unsigned Idx = 0, N = Record.size(); 1953 while (Idx < N) { 1954 MacroDirective *MD = nullptr; 1955 SourceLocation Loc = ReadSourceLocation(M, Record, Idx); 1956 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++]; 1957 switch (K) { 1958 case MacroDirective::MD_Define: { 1959 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++])); 1960 MD = PP.AllocateDefMacroDirective(MI, Loc); 1961 break; 1962 } 1963 case MacroDirective::MD_Undefine: { 1964 MD = PP.AllocateUndefMacroDirective(Loc); 1965 break; 1966 } 1967 case MacroDirective::MD_Visibility: 1968 bool isPublic = Record[Idx++]; 1969 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic); 1970 break; 1971 } 1972 1973 if (!Latest) 1974 Latest = MD; 1975 if (Earliest) 1976 Earliest->setPrevious(MD); 1977 Earliest = MD; 1978 } 1979 1980 if (Latest) 1981 PP.setLoadedMacroDirective(II, Earliest, Latest); 1982 } 1983 1984 ASTReader::InputFileInfo 1985 ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) { 1986 // Go find this input file. 1987 BitstreamCursor &Cursor = F.InputFilesCursor; 1988 SavedStreamPosition SavedPosition(Cursor); 1989 Cursor.JumpToBit(F.InputFileOffsets[ID-1]); 1990 1991 unsigned Code = Cursor.ReadCode(); 1992 RecordData Record; 1993 StringRef Blob; 1994 1995 unsigned Result = Cursor.readRecord(Code, Record, &Blob); 1996 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE && 1997 "invalid record type for input file"); 1998 (void)Result; 1999 2000 assert(Record[0] == ID && "Bogus stored ID or offset"); 2001 InputFileInfo R; 2002 R.StoredSize = static_cast<off_t>(Record[1]); 2003 R.StoredTime = static_cast<time_t>(Record[2]); 2004 R.Overridden = static_cast<bool>(Record[3]); 2005 R.Transient = static_cast<bool>(Record[4]); 2006 R.Filename = Blob; 2007 ResolveImportedPath(F, R.Filename); 2008 return R; 2009 } 2010 2011 static unsigned moduleKindForDiagnostic(ModuleKind Kind); 2012 InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) { 2013 // If this ID is bogus, just return an empty input file. 2014 if (ID == 0 || ID > F.InputFilesLoaded.size()) 2015 return InputFile(); 2016 2017 // If we've already loaded this input file, return it. 2018 if (F.InputFilesLoaded[ID-1].getFile()) 2019 return F.InputFilesLoaded[ID-1]; 2020 2021 if (F.InputFilesLoaded[ID-1].isNotFound()) 2022 return InputFile(); 2023 2024 // Go find this input file. 2025 BitstreamCursor &Cursor = F.InputFilesCursor; 2026 SavedStreamPosition SavedPosition(Cursor); 2027 Cursor.JumpToBit(F.InputFileOffsets[ID-1]); 2028 2029 InputFileInfo FI = readInputFileInfo(F, ID); 2030 off_t StoredSize = FI.StoredSize; 2031 time_t StoredTime = FI.StoredTime; 2032 bool Overridden = FI.Overridden; 2033 bool Transient = FI.Transient; 2034 StringRef Filename = FI.Filename; 2035 2036 const FileEntry *File = FileMgr.getFile(Filename, /*OpenFile=*/false); 2037 2038 // If we didn't find the file, resolve it relative to the 2039 // original directory from which this AST file was created. 2040 if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() && 2041 F.OriginalDir != CurrentDir) { 2042 std::string Resolved = resolveFileRelativeToOriginalDir(Filename, 2043 F.OriginalDir, 2044 CurrentDir); 2045 if (!Resolved.empty()) 2046 File = FileMgr.getFile(Resolved); 2047 } 2048 2049 // For an overridden file, create a virtual file with the stored 2050 // size/timestamp. 2051 if ((Overridden || Transient) && File == nullptr) 2052 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime); 2053 2054 if (File == nullptr) { 2055 if (Complain) { 2056 std::string ErrorStr = "could not find file '"; 2057 ErrorStr += Filename; 2058 ErrorStr += "' referenced by AST file '"; 2059 ErrorStr += F.FileName; 2060 ErrorStr += "'"; 2061 Error(ErrorStr); 2062 } 2063 // Record that we didn't find the file. 2064 F.InputFilesLoaded[ID-1] = InputFile::getNotFound(); 2065 return InputFile(); 2066 } 2067 2068 // Check if there was a request to override the contents of the file 2069 // that was part of the precompiled header. Overridding such a file 2070 // can lead to problems when lexing using the source locations from the 2071 // PCH. 2072 SourceManager &SM = getSourceManager(); 2073 // FIXME: Reject if the overrides are different. 2074 if ((!Overridden && !Transient) && SM.isFileOverridden(File)) { 2075 if (Complain) 2076 Error(diag::err_fe_pch_file_overridden, Filename); 2077 // After emitting the diagnostic, recover by disabling the override so 2078 // that the original file will be used. 2079 // 2080 // FIXME: This recovery is just as broken as the original state; there may 2081 // be another precompiled module that's using the overridden contents, or 2082 // we might be half way through parsing it. Instead, we should treat the 2083 // overridden contents as belonging to a separate FileEntry. 2084 SM.disableFileContentsOverride(File); 2085 // The FileEntry is a virtual file entry with the size of the contents 2086 // that would override the original contents. Set it to the original's 2087 // size/time. 2088 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File), 2089 StoredSize, StoredTime); 2090 } 2091 2092 bool IsOutOfDate = false; 2093 2094 // For an overridden file, there is nothing to validate. 2095 if (!Overridden && // 2096 (StoredSize != File->getSize() || 2097 (StoredTime && StoredTime != File->getModificationTime() && 2098 !DisableValidation) 2099 )) { 2100 if (Complain) { 2101 // Build a list of the PCH imports that got us here (in reverse). 2102 SmallVector<ModuleFile *, 4> ImportStack(1, &F); 2103 while (ImportStack.back()->ImportedBy.size() > 0) 2104 ImportStack.push_back(ImportStack.back()->ImportedBy[0]); 2105 2106 // The top-level PCH is stale. 2107 StringRef TopLevelPCHName(ImportStack.back()->FileName); 2108 unsigned DiagnosticKind = moduleKindForDiagnostic(ImportStack.back()->Kind); 2109 if (DiagnosticKind == 0) 2110 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName); 2111 else if (DiagnosticKind == 1) 2112 Error(diag::err_fe_module_file_modified, Filename, TopLevelPCHName); 2113 else 2114 Error(diag::err_fe_ast_file_modified, Filename, TopLevelPCHName); 2115 2116 // Print the import stack. 2117 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) { 2118 Diag(diag::note_pch_required_by) 2119 << Filename << ImportStack[0]->FileName; 2120 for (unsigned I = 1; I < ImportStack.size(); ++I) 2121 Diag(diag::note_pch_required_by) 2122 << ImportStack[I-1]->FileName << ImportStack[I]->FileName; 2123 } 2124 2125 if (!Diags.isDiagnosticInFlight()) 2126 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName; 2127 } 2128 2129 IsOutOfDate = true; 2130 } 2131 // FIXME: If the file is overridden and we've already opened it, 2132 // issue an error (or split it into a separate FileEntry). 2133 2134 InputFile IF = InputFile(File, Overridden || Transient, IsOutOfDate); 2135 2136 // Note that we've loaded this input file. 2137 F.InputFilesLoaded[ID-1] = IF; 2138 return IF; 2139 } 2140 2141 /// \brief If we are loading a relocatable PCH or module file, and the filename 2142 /// is not an absolute path, add the system or module root to the beginning of 2143 /// the file name. 2144 void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) { 2145 // Resolve relative to the base directory, if we have one. 2146 if (!M.BaseDirectory.empty()) 2147 return ResolveImportedPath(Filename, M.BaseDirectory); 2148 } 2149 2150 void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) { 2151 if (Filename.empty() || llvm::sys::path::is_absolute(Filename)) 2152 return; 2153 2154 SmallString<128> Buffer; 2155 llvm::sys::path::append(Buffer, Prefix, Filename); 2156 Filename.assign(Buffer.begin(), Buffer.end()); 2157 } 2158 2159 static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) { 2160 switch (ARR) { 2161 case ASTReader::Failure: return true; 2162 case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing); 2163 case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate); 2164 case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch); 2165 case ASTReader::ConfigurationMismatch: 2166 return !(Caps & ASTReader::ARR_ConfigurationMismatch); 2167 case ASTReader::HadErrors: return true; 2168 case ASTReader::Success: return false; 2169 } 2170 2171 llvm_unreachable("unknown ASTReadResult"); 2172 } 2173 2174 ASTReader::ASTReadResult ASTReader::ReadOptionsBlock( 2175 BitstreamCursor &Stream, unsigned ClientLoadCapabilities, 2176 bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener, 2177 std::string &SuggestedPredefines) { 2178 if (Stream.EnterSubBlock(OPTIONS_BLOCK_ID)) 2179 return Failure; 2180 2181 // Read all of the records in the options block. 2182 RecordData Record; 2183 ASTReadResult Result = Success; 2184 while (true) { 2185 llvm::BitstreamEntry Entry = Stream.advance(); 2186 2187 switch (Entry.Kind) { 2188 case llvm::BitstreamEntry::Error: 2189 case llvm::BitstreamEntry::SubBlock: 2190 return Failure; 2191 2192 case llvm::BitstreamEntry::EndBlock: 2193 return Result; 2194 2195 case llvm::BitstreamEntry::Record: 2196 // The interesting case. 2197 break; 2198 } 2199 2200 // Read and process a record. 2201 Record.clear(); 2202 switch ((OptionsRecordTypes)Stream.readRecord(Entry.ID, Record)) { 2203 case LANGUAGE_OPTIONS: { 2204 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0; 2205 if (ParseLanguageOptions(Record, Complain, Listener, 2206 AllowCompatibleConfigurationMismatch)) 2207 Result = ConfigurationMismatch; 2208 break; 2209 } 2210 2211 case TARGET_OPTIONS: { 2212 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0; 2213 if (ParseTargetOptions(Record, Complain, Listener, 2214 AllowCompatibleConfigurationMismatch)) 2215 Result = ConfigurationMismatch; 2216 break; 2217 } 2218 2219 case FILE_SYSTEM_OPTIONS: { 2220 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0; 2221 if (!AllowCompatibleConfigurationMismatch && 2222 ParseFileSystemOptions(Record, Complain, Listener)) 2223 Result = ConfigurationMismatch; 2224 break; 2225 } 2226 2227 case HEADER_SEARCH_OPTIONS: { 2228 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0; 2229 if (!AllowCompatibleConfigurationMismatch && 2230 ParseHeaderSearchOptions(Record, Complain, Listener)) 2231 Result = ConfigurationMismatch; 2232 break; 2233 } 2234 2235 case PREPROCESSOR_OPTIONS: 2236 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0; 2237 if (!AllowCompatibleConfigurationMismatch && 2238 ParsePreprocessorOptions(Record, Complain, Listener, 2239 SuggestedPredefines)) 2240 Result = ConfigurationMismatch; 2241 break; 2242 } 2243 } 2244 } 2245 2246 ASTReader::ASTReadResult 2247 ASTReader::ReadControlBlock(ModuleFile &F, 2248 SmallVectorImpl<ImportedModule> &Loaded, 2249 const ModuleFile *ImportedBy, 2250 unsigned ClientLoadCapabilities) { 2251 BitstreamCursor &Stream = F.Stream; 2252 ASTReadResult Result = Success; 2253 2254 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) { 2255 Error("malformed block record in AST file"); 2256 return Failure; 2257 } 2258 2259 // Lambda to read the unhashed control block the first time it's called. 2260 // 2261 // For PCM files, the unhashed control block cannot be read until after the 2262 // MODULE_NAME record. However, PCH files have no MODULE_NAME, and yet still 2263 // need to look ahead before reading the IMPORTS record. For consistency, 2264 // this block is always read somehow (see BitstreamEntry::EndBlock). 2265 bool HasReadUnhashedControlBlock = false; 2266 auto readUnhashedControlBlockOnce = [&]() { 2267 if (!HasReadUnhashedControlBlock) { 2268 HasReadUnhashedControlBlock = true; 2269 if (ASTReadResult Result = 2270 readUnhashedControlBlock(F, ImportedBy, ClientLoadCapabilities)) 2271 return Result; 2272 } 2273 return Success; 2274 }; 2275 2276 // Read all of the records and blocks in the control block. 2277 RecordData Record; 2278 unsigned NumInputs = 0; 2279 unsigned NumUserInputs = 0; 2280 while (true) { 2281 llvm::BitstreamEntry Entry = Stream.advance(); 2282 2283 switch (Entry.Kind) { 2284 case llvm::BitstreamEntry::Error: 2285 Error("malformed block record in AST file"); 2286 return Failure; 2287 case llvm::BitstreamEntry::EndBlock: { 2288 // Validate the module before returning. This call catches an AST with 2289 // no module name and no imports. 2290 if (ASTReadResult Result = readUnhashedControlBlockOnce()) 2291 return Result; 2292 2293 // Validate input files. 2294 const HeaderSearchOptions &HSOpts = 2295 PP.getHeaderSearchInfo().getHeaderSearchOpts(); 2296 2297 // All user input files reside at the index range [0, NumUserInputs), and 2298 // system input files reside at [NumUserInputs, NumInputs). For explicitly 2299 // loaded module files, ignore missing inputs. 2300 if (!DisableValidation && F.Kind != MK_ExplicitModule && 2301 F.Kind != MK_PrebuiltModule) { 2302 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0; 2303 2304 // If we are reading a module, we will create a verification timestamp, 2305 // so we verify all input files. Otherwise, verify only user input 2306 // files. 2307 2308 unsigned N = NumUserInputs; 2309 if (ValidateSystemInputs || 2310 (HSOpts.ModulesValidateOncePerBuildSession && 2311 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp && 2312 F.Kind == MK_ImplicitModule)) 2313 N = NumInputs; 2314 2315 for (unsigned I = 0; I < N; ++I) { 2316 InputFile IF = getInputFile(F, I+1, Complain); 2317 if (!IF.getFile() || IF.isOutOfDate()) 2318 return OutOfDate; 2319 } 2320 } 2321 2322 if (Listener) 2323 Listener->visitModuleFile(F.FileName, F.Kind); 2324 2325 if (Listener && Listener->needsInputFileVisitation()) { 2326 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs 2327 : NumUserInputs; 2328 for (unsigned I = 0; I < N; ++I) { 2329 bool IsSystem = I >= NumUserInputs; 2330 InputFileInfo FI = readInputFileInfo(F, I+1); 2331 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden, 2332 F.Kind == MK_ExplicitModule || 2333 F.Kind == MK_PrebuiltModule); 2334 } 2335 } 2336 2337 return Result; 2338 } 2339 2340 case llvm::BitstreamEntry::SubBlock: 2341 switch (Entry.ID) { 2342 case INPUT_FILES_BLOCK_ID: 2343 F.InputFilesCursor = Stream; 2344 if (Stream.SkipBlock() || // Skip with the main cursor 2345 // Read the abbreviations 2346 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) { 2347 Error("malformed block record in AST file"); 2348 return Failure; 2349 } 2350 continue; 2351 2352 case OPTIONS_BLOCK_ID: 2353 // If we're reading the first module for this group, check its options 2354 // are compatible with ours. For modules it imports, no further checking 2355 // is required, because we checked them when we built it. 2356 if (Listener && !ImportedBy) { 2357 // Should we allow the configuration of the module file to differ from 2358 // the configuration of the current translation unit in a compatible 2359 // way? 2360 // 2361 // FIXME: Allow this for files explicitly specified with -include-pch. 2362 bool AllowCompatibleConfigurationMismatch = 2363 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule; 2364 2365 Result = ReadOptionsBlock(Stream, ClientLoadCapabilities, 2366 AllowCompatibleConfigurationMismatch, 2367 *Listener, SuggestedPredefines); 2368 if (Result == Failure) { 2369 Error("malformed block record in AST file"); 2370 return Result; 2371 } 2372 2373 if (DisableValidation || 2374 (AllowConfigurationMismatch && Result == ConfigurationMismatch)) 2375 Result = Success; 2376 2377 // If we can't load the module, exit early since we likely 2378 // will rebuild the module anyway. The stream may be in the 2379 // middle of a block. 2380 if (Result != Success) 2381 return Result; 2382 } else if (Stream.SkipBlock()) { 2383 Error("malformed block record in AST file"); 2384 return Failure; 2385 } 2386 continue; 2387 2388 default: 2389 if (Stream.SkipBlock()) { 2390 Error("malformed block record in AST file"); 2391 return Failure; 2392 } 2393 continue; 2394 } 2395 2396 case llvm::BitstreamEntry::Record: 2397 // The interesting case. 2398 break; 2399 } 2400 2401 // Read and process a record. 2402 Record.clear(); 2403 StringRef Blob; 2404 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) { 2405 case METADATA: { 2406 if (Record[0] != VERSION_MAJOR && !DisableValidation) { 2407 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0) 2408 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old 2409 : diag::err_pch_version_too_new); 2410 return VersionMismatch; 2411 } 2412 2413 bool hasErrors = Record[6]; 2414 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) { 2415 Diag(diag::err_pch_with_compiler_errors); 2416 return HadErrors; 2417 } 2418 if (hasErrors) { 2419 Diags.ErrorOccurred = true; 2420 Diags.UncompilableErrorOccurred = true; 2421 Diags.UnrecoverableErrorOccurred = true; 2422 } 2423 2424 F.RelocatablePCH = Record[4]; 2425 // Relative paths in a relocatable PCH are relative to our sysroot. 2426 if (F.RelocatablePCH) 2427 F.BaseDirectory = isysroot.empty() ? "/" : isysroot; 2428 2429 F.HasTimestamps = Record[5]; 2430 2431 const std::string &CurBranch = getClangFullRepositoryVersion(); 2432 StringRef ASTBranch = Blob; 2433 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) { 2434 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0) 2435 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch; 2436 return VersionMismatch; 2437 } 2438 break; 2439 } 2440 2441 case IMPORTS: { 2442 // Validate the AST before processing any imports (otherwise, untangling 2443 // them can be error-prone and expensive). A module will have a name and 2444 // will already have been validated, but this catches the PCH case. 2445 if (ASTReadResult Result = readUnhashedControlBlockOnce()) 2446 return Result; 2447 2448 // Load each of the imported PCH files. 2449 unsigned Idx = 0, N = Record.size(); 2450 while (Idx < N) { 2451 // Read information about the AST file. 2452 ModuleKind ImportedKind = (ModuleKind)Record[Idx++]; 2453 // The import location will be the local one for now; we will adjust 2454 // all import locations of module imports after the global source 2455 // location info are setup, in ReadAST. 2456 SourceLocation ImportLoc = 2457 ReadUntranslatedSourceLocation(Record[Idx++]); 2458 off_t StoredSize = (off_t)Record[Idx++]; 2459 time_t StoredModTime = (time_t)Record[Idx++]; 2460 ASTFileSignature StoredSignature = { 2461 {{(uint32_t)Record[Idx++], (uint32_t)Record[Idx++], 2462 (uint32_t)Record[Idx++], (uint32_t)Record[Idx++], 2463 (uint32_t)Record[Idx++]}}}; 2464 auto ImportedFile = ReadPath(F, Record, Idx); 2465 2466 // If our client can't cope with us being out of date, we can't cope with 2467 // our dependency being missing. 2468 unsigned Capabilities = ClientLoadCapabilities; 2469 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) 2470 Capabilities &= ~ARR_Missing; 2471 2472 // Load the AST file. 2473 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F, 2474 Loaded, StoredSize, StoredModTime, 2475 StoredSignature, Capabilities); 2476 2477 // If we diagnosed a problem, produce a backtrace. 2478 if (isDiagnosedResult(Result, Capabilities)) 2479 Diag(diag::note_module_file_imported_by) 2480 << F.FileName << !F.ModuleName.empty() << F.ModuleName; 2481 2482 switch (Result) { 2483 case Failure: return Failure; 2484 // If we have to ignore the dependency, we'll have to ignore this too. 2485 case Missing: 2486 case OutOfDate: return OutOfDate; 2487 case VersionMismatch: return VersionMismatch; 2488 case ConfigurationMismatch: return ConfigurationMismatch; 2489 case HadErrors: return HadErrors; 2490 case Success: break; 2491 } 2492 } 2493 break; 2494 } 2495 2496 case ORIGINAL_FILE: 2497 F.OriginalSourceFileID = FileID::get(Record[0]); 2498 F.ActualOriginalSourceFileName = Blob; 2499 F.OriginalSourceFileName = F.ActualOriginalSourceFileName; 2500 ResolveImportedPath(F, F.OriginalSourceFileName); 2501 break; 2502 2503 case ORIGINAL_FILE_ID: 2504 F.OriginalSourceFileID = FileID::get(Record[0]); 2505 break; 2506 2507 case ORIGINAL_PCH_DIR: 2508 F.OriginalDir = Blob; 2509 break; 2510 2511 case MODULE_NAME: 2512 F.ModuleName = Blob; 2513 if (Listener) 2514 Listener->ReadModuleName(F.ModuleName); 2515 2516 // Validate the AST as soon as we have a name so we can exit early on 2517 // failure. 2518 if (ASTReadResult Result = readUnhashedControlBlockOnce()) 2519 return Result; 2520 2521 break; 2522 2523 case MODULE_DIRECTORY: { 2524 assert(!F.ModuleName.empty() && 2525 "MODULE_DIRECTORY found before MODULE_NAME"); 2526 // If we've already loaded a module map file covering this module, we may 2527 // have a better path for it (relative to the current build). 2528 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName); 2529 if (M && M->Directory) { 2530 // If we're implicitly loading a module, the base directory can't 2531 // change between the build and use. 2532 if (F.Kind != MK_ExplicitModule && F.Kind != MK_PrebuiltModule) { 2533 const DirectoryEntry *BuildDir = 2534 PP.getFileManager().getDirectory(Blob); 2535 if (!BuildDir || BuildDir != M->Directory) { 2536 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) 2537 Diag(diag::err_imported_module_relocated) 2538 << F.ModuleName << Blob << M->Directory->getName(); 2539 return OutOfDate; 2540 } 2541 } 2542 F.BaseDirectory = M->Directory->getName(); 2543 } else { 2544 F.BaseDirectory = Blob; 2545 } 2546 break; 2547 } 2548 2549 case MODULE_MAP_FILE: 2550 if (ASTReadResult Result = 2551 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities)) 2552 return Result; 2553 break; 2554 2555 case INPUT_FILE_OFFSETS: 2556 NumInputs = Record[0]; 2557 NumUserInputs = Record[1]; 2558 F.InputFileOffsets = 2559 (const llvm::support::unaligned_uint64_t *)Blob.data(); 2560 F.InputFilesLoaded.resize(NumInputs); 2561 F.NumUserInputFiles = NumUserInputs; 2562 break; 2563 } 2564 } 2565 } 2566 2567 ASTReader::ASTReadResult 2568 ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) { 2569 BitstreamCursor &Stream = F.Stream; 2570 2571 if (Stream.EnterSubBlock(AST_BLOCK_ID)) { 2572 Error("malformed block record in AST file"); 2573 return Failure; 2574 } 2575 2576 // Read all of the records and blocks for the AST file. 2577 RecordData Record; 2578 while (true) { 2579 llvm::BitstreamEntry Entry = Stream.advance(); 2580 2581 switch (Entry.Kind) { 2582 case llvm::BitstreamEntry::Error: 2583 Error("error at end of module block in AST file"); 2584 return Failure; 2585 case llvm::BitstreamEntry::EndBlock: { 2586 // Outside of C++, we do not store a lookup map for the translation unit. 2587 // Instead, mark it as needing a lookup map to be built if this module 2588 // contains any declarations lexically within it (which it always does!). 2589 // This usually has no cost, since we very rarely need the lookup map for 2590 // the translation unit outside C++. 2591 DeclContext *DC = Context.getTranslationUnitDecl(); 2592 if (DC->hasExternalLexicalStorage() && 2593 !getContext().getLangOpts().CPlusPlus) 2594 DC->setMustBuildLookupTable(); 2595 2596 return Success; 2597 } 2598 case llvm::BitstreamEntry::SubBlock: 2599 switch (Entry.ID) { 2600 case DECLTYPES_BLOCK_ID: 2601 // We lazily load the decls block, but we want to set up the 2602 // DeclsCursor cursor to point into it. Clone our current bitcode 2603 // cursor to it, enter the block and read the abbrevs in that block. 2604 // With the main cursor, we just skip over it. 2605 F.DeclsCursor = Stream; 2606 if (Stream.SkipBlock() || // Skip with the main cursor. 2607 // Read the abbrevs. 2608 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) { 2609 Error("malformed block record in AST file"); 2610 return Failure; 2611 } 2612 break; 2613 2614 case PREPROCESSOR_BLOCK_ID: 2615 F.MacroCursor = Stream; 2616 if (!PP.getExternalSource()) 2617 PP.setExternalSource(this); 2618 2619 if (Stream.SkipBlock() || 2620 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) { 2621 Error("malformed block record in AST file"); 2622 return Failure; 2623 } 2624 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo(); 2625 break; 2626 2627 case PREPROCESSOR_DETAIL_BLOCK_ID: 2628 F.PreprocessorDetailCursor = Stream; 2629 if (Stream.SkipBlock() || 2630 ReadBlockAbbrevs(F.PreprocessorDetailCursor, 2631 PREPROCESSOR_DETAIL_BLOCK_ID)) { 2632 Error("malformed preprocessor detail record in AST file"); 2633 return Failure; 2634 } 2635 F.PreprocessorDetailStartOffset 2636 = F.PreprocessorDetailCursor.GetCurrentBitNo(); 2637 2638 if (!PP.getPreprocessingRecord()) 2639 PP.createPreprocessingRecord(); 2640 if (!PP.getPreprocessingRecord()->getExternalSource()) 2641 PP.getPreprocessingRecord()->SetExternalSource(*this); 2642 break; 2643 2644 case SOURCE_MANAGER_BLOCK_ID: 2645 if (ReadSourceManagerBlock(F)) 2646 return Failure; 2647 break; 2648 2649 case SUBMODULE_BLOCK_ID: 2650 if (ASTReadResult Result = 2651 ReadSubmoduleBlock(F, ClientLoadCapabilities)) 2652 return Result; 2653 break; 2654 2655 case COMMENTS_BLOCK_ID: { 2656 BitstreamCursor C = Stream; 2657 if (Stream.SkipBlock() || 2658 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) { 2659 Error("malformed comments block in AST file"); 2660 return Failure; 2661 } 2662 CommentsCursors.push_back(std::make_pair(C, &F)); 2663 break; 2664 } 2665 2666 default: 2667 if (Stream.SkipBlock()) { 2668 Error("malformed block record in AST file"); 2669 return Failure; 2670 } 2671 break; 2672 } 2673 continue; 2674 2675 case llvm::BitstreamEntry::Record: 2676 // The interesting case. 2677 break; 2678 } 2679 2680 // Read and process a record. 2681 Record.clear(); 2682 StringRef Blob; 2683 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) { 2684 default: // Default behavior: ignore. 2685 break; 2686 2687 case TYPE_OFFSET: { 2688 if (F.LocalNumTypes != 0) { 2689 Error("duplicate TYPE_OFFSET record in AST file"); 2690 return Failure; 2691 } 2692 F.TypeOffsets = (const uint32_t *)Blob.data(); 2693 F.LocalNumTypes = Record[0]; 2694 unsigned LocalBaseTypeIndex = Record[1]; 2695 F.BaseTypeIndex = getTotalNumTypes(); 2696 2697 if (F.LocalNumTypes > 0) { 2698 // Introduce the global -> local mapping for types within this module. 2699 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F)); 2700 2701 // Introduce the local -> global mapping for types within this module. 2702 F.TypeRemap.insertOrReplace( 2703 std::make_pair(LocalBaseTypeIndex, 2704 F.BaseTypeIndex - LocalBaseTypeIndex)); 2705 2706 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes); 2707 } 2708 break; 2709 } 2710 2711 case DECL_OFFSET: { 2712 if (F.LocalNumDecls != 0) { 2713 Error("duplicate DECL_OFFSET record in AST file"); 2714 return Failure; 2715 } 2716 F.DeclOffsets = (const DeclOffset *)Blob.data(); 2717 F.LocalNumDecls = Record[0]; 2718 unsigned LocalBaseDeclID = Record[1]; 2719 F.BaseDeclID = getTotalNumDecls(); 2720 2721 if (F.LocalNumDecls > 0) { 2722 // Introduce the global -> local mapping for declarations within this 2723 // module. 2724 GlobalDeclMap.insert( 2725 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F)); 2726 2727 // Introduce the local -> global mapping for declarations within this 2728 // module. 2729 F.DeclRemap.insertOrReplace( 2730 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID)); 2731 2732 // Introduce the global -> local mapping for declarations within this 2733 // module. 2734 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID; 2735 2736 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls); 2737 } 2738 break; 2739 } 2740 2741 case TU_UPDATE_LEXICAL: { 2742 DeclContext *TU = Context.getTranslationUnitDecl(); 2743 LexicalContents Contents( 2744 reinterpret_cast<const llvm::support::unaligned_uint32_t *>( 2745 Blob.data()), 2746 static_cast<unsigned int>(Blob.size() / 4)); 2747 TULexicalDecls.push_back(std::make_pair(&F, Contents)); 2748 TU->setHasExternalLexicalStorage(true); 2749 break; 2750 } 2751 2752 case UPDATE_VISIBLE: { 2753 unsigned Idx = 0; 2754 serialization::DeclID ID = ReadDeclID(F, Record, Idx); 2755 auto *Data = (const unsigned char*)Blob.data(); 2756 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&F, Data}); 2757 // If we've already loaded the decl, perform the updates when we finish 2758 // loading this block. 2759 if (Decl *D = GetExistingDecl(ID)) 2760 PendingUpdateRecords.push_back(std::make_pair(ID, D)); 2761 break; 2762 } 2763 2764 case IDENTIFIER_TABLE: 2765 F.IdentifierTableData = Blob.data(); 2766 if (Record[0]) { 2767 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create( 2768 (const unsigned char *)F.IdentifierTableData + Record[0], 2769 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t), 2770 (const unsigned char *)F.IdentifierTableData, 2771 ASTIdentifierLookupTrait(*this, F)); 2772 2773 PP.getIdentifierTable().setExternalIdentifierLookup(this); 2774 } 2775 break; 2776 2777 case IDENTIFIER_OFFSET: { 2778 if (F.LocalNumIdentifiers != 0) { 2779 Error("duplicate IDENTIFIER_OFFSET record in AST file"); 2780 return Failure; 2781 } 2782 F.IdentifierOffsets = (const uint32_t *)Blob.data(); 2783 F.LocalNumIdentifiers = Record[0]; 2784 unsigned LocalBaseIdentifierID = Record[1]; 2785 F.BaseIdentifierID = getTotalNumIdentifiers(); 2786 2787 if (F.LocalNumIdentifiers > 0) { 2788 // Introduce the global -> local mapping for identifiers within this 2789 // module. 2790 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1, 2791 &F)); 2792 2793 // Introduce the local -> global mapping for identifiers within this 2794 // module. 2795 F.IdentifierRemap.insertOrReplace( 2796 std::make_pair(LocalBaseIdentifierID, 2797 F.BaseIdentifierID - LocalBaseIdentifierID)); 2798 2799 IdentifiersLoaded.resize(IdentifiersLoaded.size() 2800 + F.LocalNumIdentifiers); 2801 } 2802 break; 2803 } 2804 2805 case INTERESTING_IDENTIFIERS: 2806 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end()); 2807 break; 2808 2809 case EAGERLY_DESERIALIZED_DECLS: 2810 // FIXME: Skip reading this record if our ASTConsumer doesn't care 2811 // about "interesting" decls (for instance, if we're building a module). 2812 for (unsigned I = 0, N = Record.size(); I != N; ++I) 2813 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I])); 2814 break; 2815 2816 case MODULAR_CODEGEN_DECLS: 2817 // FIXME: Skip reading this record if our ASTConsumer doesn't care about 2818 // them (ie: if we're not codegenerating this module). 2819 if (F.Kind == MK_MainFile) 2820 for (unsigned I = 0, N = Record.size(); I != N; ++I) 2821 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I])); 2822 break; 2823 2824 case SPECIAL_TYPES: 2825 if (SpecialTypes.empty()) { 2826 for (unsigned I = 0, N = Record.size(); I != N; ++I) 2827 SpecialTypes.push_back(getGlobalTypeID(F, Record[I])); 2828 break; 2829 } 2830 2831 if (SpecialTypes.size() != Record.size()) { 2832 Error("invalid special-types record"); 2833 return Failure; 2834 } 2835 2836 for (unsigned I = 0, N = Record.size(); I != N; ++I) { 2837 serialization::TypeID ID = getGlobalTypeID(F, Record[I]); 2838 if (!SpecialTypes[I]) 2839 SpecialTypes[I] = ID; 2840 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate 2841 // merge step? 2842 } 2843 break; 2844 2845 case STATISTICS: 2846 TotalNumStatements += Record[0]; 2847 TotalNumMacros += Record[1]; 2848 TotalLexicalDeclContexts += Record[2]; 2849 TotalVisibleDeclContexts += Record[3]; 2850 break; 2851 2852 case UNUSED_FILESCOPED_DECLS: 2853 for (unsigned I = 0, N = Record.size(); I != N; ++I) 2854 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I])); 2855 break; 2856 2857 case DELEGATING_CTORS: 2858 for (unsigned I = 0, N = Record.size(); I != N; ++I) 2859 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I])); 2860 break; 2861 2862 case WEAK_UNDECLARED_IDENTIFIERS: 2863 if (Record.size() % 4 != 0) { 2864 Error("invalid weak identifiers record"); 2865 return Failure; 2866 } 2867 2868 // FIXME: Ignore weak undeclared identifiers from non-original PCH 2869 // files. This isn't the way to do it :) 2870 WeakUndeclaredIdentifiers.clear(); 2871 2872 // Translate the weak, undeclared identifiers into global IDs. 2873 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) { 2874 WeakUndeclaredIdentifiers.push_back( 2875 getGlobalIdentifierID(F, Record[I++])); 2876 WeakUndeclaredIdentifiers.push_back( 2877 getGlobalIdentifierID(F, Record[I++])); 2878 WeakUndeclaredIdentifiers.push_back( 2879 ReadSourceLocation(F, Record, I).getRawEncoding()); 2880 WeakUndeclaredIdentifiers.push_back(Record[I++]); 2881 } 2882 break; 2883 2884 case SELECTOR_OFFSETS: { 2885 F.SelectorOffsets = (const uint32_t *)Blob.data(); 2886 F.LocalNumSelectors = Record[0]; 2887 unsigned LocalBaseSelectorID = Record[1]; 2888 F.BaseSelectorID = getTotalNumSelectors(); 2889 2890 if (F.LocalNumSelectors > 0) { 2891 // Introduce the global -> local mapping for selectors within this 2892 // module. 2893 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F)); 2894 2895 // Introduce the local -> global mapping for selectors within this 2896 // module. 2897 F.SelectorRemap.insertOrReplace( 2898 std::make_pair(LocalBaseSelectorID, 2899 F.BaseSelectorID - LocalBaseSelectorID)); 2900 2901 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors); 2902 } 2903 break; 2904 } 2905 2906 case METHOD_POOL: 2907 F.SelectorLookupTableData = (const unsigned char *)Blob.data(); 2908 if (Record[0]) 2909 F.SelectorLookupTable 2910 = ASTSelectorLookupTable::Create( 2911 F.SelectorLookupTableData + Record[0], 2912 F.SelectorLookupTableData, 2913 ASTSelectorLookupTrait(*this, F)); 2914 TotalNumMethodPoolEntries += Record[1]; 2915 break; 2916 2917 case REFERENCED_SELECTOR_POOL: 2918 if (!Record.empty()) { 2919 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) { 2920 ReferencedSelectorsData.push_back(getGlobalSelectorID(F, 2921 Record[Idx++])); 2922 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx). 2923 getRawEncoding()); 2924 } 2925 } 2926 break; 2927 2928 case PP_COUNTER_VALUE: 2929 if (!Record.empty() && Listener) 2930 Listener->ReadCounter(F, Record[0]); 2931 break; 2932 2933 case FILE_SORTED_DECLS: 2934 F.FileSortedDecls = (const DeclID *)Blob.data(); 2935 F.NumFileSortedDecls = Record[0]; 2936 break; 2937 2938 case SOURCE_LOCATION_OFFSETS: { 2939 F.SLocEntryOffsets = (const uint32_t *)Blob.data(); 2940 F.LocalNumSLocEntries = Record[0]; 2941 unsigned SLocSpaceSize = Record[1]; 2942 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) = 2943 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries, 2944 SLocSpaceSize); 2945 if (!F.SLocEntryBaseID) { 2946 Error("ran out of source locations"); 2947 break; 2948 } 2949 // Make our entry in the range map. BaseID is negative and growing, so 2950 // we invert it. Because we invert it, though, we need the other end of 2951 // the range. 2952 unsigned RangeStart = 2953 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1; 2954 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F)); 2955 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset); 2956 2957 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing. 2958 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0); 2959 GlobalSLocOffsetMap.insert( 2960 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset 2961 - SLocSpaceSize,&F)); 2962 2963 // Initialize the remapping table. 2964 // Invalid stays invalid. 2965 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0)); 2966 // This module. Base was 2 when being compiled. 2967 F.SLocRemap.insertOrReplace(std::make_pair(2U, 2968 static_cast<int>(F.SLocEntryBaseOffset - 2))); 2969 2970 TotalNumSLocEntries += F.LocalNumSLocEntries; 2971 break; 2972 } 2973 2974 case MODULE_OFFSET_MAP: 2975 F.ModuleOffsetMap = Blob; 2976 break; 2977 2978 case SOURCE_MANAGER_LINE_TABLE: 2979 if (ParseLineTable(F, Record)) 2980 return Failure; 2981 break; 2982 2983 case SOURCE_LOCATION_PRELOADS: { 2984 // Need to transform from the local view (1-based IDs) to the global view, 2985 // which is based off F.SLocEntryBaseID. 2986 if (!F.PreloadSLocEntries.empty()) { 2987 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file"); 2988 return Failure; 2989 } 2990 2991 F.PreloadSLocEntries.swap(Record); 2992 break; 2993 } 2994 2995 case EXT_VECTOR_DECLS: 2996 for (unsigned I = 0, N = Record.size(); I != N; ++I) 2997 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I])); 2998 break; 2999 3000 case VTABLE_USES: 3001 if (Record.size() % 3 != 0) { 3002 Error("Invalid VTABLE_USES record"); 3003 return Failure; 3004 } 3005 3006 // Later tables overwrite earlier ones. 3007 // FIXME: Modules will have some trouble with this. This is clearly not 3008 // the right way to do this. 3009 VTableUses.clear(); 3010 3011 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) { 3012 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++])); 3013 VTableUses.push_back( 3014 ReadSourceLocation(F, Record, Idx).getRawEncoding()); 3015 VTableUses.push_back(Record[Idx++]); 3016 } 3017 break; 3018 3019 case PENDING_IMPLICIT_INSTANTIATIONS: 3020 if (PendingInstantiations.size() % 2 != 0) { 3021 Error("Invalid existing PendingInstantiations"); 3022 return Failure; 3023 } 3024 3025 if (Record.size() % 2 != 0) { 3026 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block"); 3027 return Failure; 3028 } 3029 3030 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) { 3031 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++])); 3032 PendingInstantiations.push_back( 3033 ReadSourceLocation(F, Record, I).getRawEncoding()); 3034 } 3035 break; 3036 3037 case SEMA_DECL_REFS: 3038 if (Record.size() != 3) { 3039 Error("Invalid SEMA_DECL_REFS block"); 3040 return Failure; 3041 } 3042 for (unsigned I = 0, N = Record.size(); I != N; ++I) 3043 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I])); 3044 break; 3045 3046 case PPD_ENTITIES_OFFSETS: { 3047 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data(); 3048 assert(Blob.size() % sizeof(PPEntityOffset) == 0); 3049 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset); 3050 3051 unsigned LocalBasePreprocessedEntityID = Record[0]; 3052 3053 unsigned StartingID; 3054 if (!PP.getPreprocessingRecord()) 3055 PP.createPreprocessingRecord(); 3056 if (!PP.getPreprocessingRecord()->getExternalSource()) 3057 PP.getPreprocessingRecord()->SetExternalSource(*this); 3058 StartingID 3059 = PP.getPreprocessingRecord() 3060 ->allocateLoadedEntities(F.NumPreprocessedEntities); 3061 F.BasePreprocessedEntityID = StartingID; 3062 3063 if (F.NumPreprocessedEntities > 0) { 3064 // Introduce the global -> local mapping for preprocessed entities in 3065 // this module. 3066 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F)); 3067 3068 // Introduce the local -> global mapping for preprocessed entities in 3069 // this module. 3070 F.PreprocessedEntityRemap.insertOrReplace( 3071 std::make_pair(LocalBasePreprocessedEntityID, 3072 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID)); 3073 } 3074 3075 break; 3076 } 3077 3078 case DECL_UPDATE_OFFSETS: { 3079 if (Record.size() % 2 != 0) { 3080 Error("invalid DECL_UPDATE_OFFSETS block in AST file"); 3081 return Failure; 3082 } 3083 for (unsigned I = 0, N = Record.size(); I != N; I += 2) { 3084 GlobalDeclID ID = getGlobalDeclID(F, Record[I]); 3085 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1])); 3086 3087 // If we've already loaded the decl, perform the updates when we finish 3088 // loading this block. 3089 if (Decl *D = GetExistingDecl(ID)) 3090 PendingUpdateRecords.push_back(std::make_pair(ID, D)); 3091 } 3092 break; 3093 } 3094 3095 case OBJC_CATEGORIES_MAP: { 3096 if (F.LocalNumObjCCategoriesInMap != 0) { 3097 Error("duplicate OBJC_CATEGORIES_MAP record in AST file"); 3098 return Failure; 3099 } 3100 3101 F.LocalNumObjCCategoriesInMap = Record[0]; 3102 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data(); 3103 break; 3104 } 3105 3106 case OBJC_CATEGORIES: 3107 F.ObjCCategories.swap(Record); 3108 break; 3109 3110 case CUDA_SPECIAL_DECL_REFS: 3111 // Later tables overwrite earlier ones. 3112 // FIXME: Modules will have trouble with this. 3113 CUDASpecialDeclRefs.clear(); 3114 for (unsigned I = 0, N = Record.size(); I != N; ++I) 3115 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I])); 3116 break; 3117 3118 case HEADER_SEARCH_TABLE: { 3119 F.HeaderFileInfoTableData = Blob.data(); 3120 F.LocalNumHeaderFileInfos = Record[1]; 3121 if (Record[0]) { 3122 F.HeaderFileInfoTable 3123 = HeaderFileInfoLookupTable::Create( 3124 (const unsigned char *)F.HeaderFileInfoTableData + Record[0], 3125 (const unsigned char *)F.HeaderFileInfoTableData, 3126 HeaderFileInfoTrait(*this, F, 3127 &PP.getHeaderSearchInfo(), 3128 Blob.data() + Record[2])); 3129 3130 PP.getHeaderSearchInfo().SetExternalSource(this); 3131 if (!PP.getHeaderSearchInfo().getExternalLookup()) 3132 PP.getHeaderSearchInfo().SetExternalLookup(this); 3133 } 3134 break; 3135 } 3136 3137 case FP_PRAGMA_OPTIONS: 3138 // Later tables overwrite earlier ones. 3139 FPPragmaOptions.swap(Record); 3140 break; 3141 3142 case OPENCL_EXTENSIONS: 3143 for (unsigned I = 0, E = Record.size(); I != E; ) { 3144 auto Name = ReadString(Record, I); 3145 auto &Opt = OpenCLExtensions.OptMap[Name]; 3146 Opt.Supported = Record[I++] != 0; 3147 Opt.Enabled = Record[I++] != 0; 3148 Opt.Avail = Record[I++]; 3149 Opt.Core = Record[I++]; 3150 } 3151 break; 3152 3153 case OPENCL_EXTENSION_TYPES: 3154 for (unsigned I = 0, E = Record.size(); I != E;) { 3155 auto TypeID = static_cast<::TypeID>(Record[I++]); 3156 auto *Type = GetType(TypeID).getTypePtr(); 3157 auto NumExt = static_cast<unsigned>(Record[I++]); 3158 for (unsigned II = 0; II != NumExt; ++II) { 3159 auto Ext = ReadString(Record, I); 3160 OpenCLTypeExtMap[Type].insert(Ext); 3161 } 3162 } 3163 break; 3164 3165 case OPENCL_EXTENSION_DECLS: 3166 for (unsigned I = 0, E = Record.size(); I != E;) { 3167 auto DeclID = static_cast<::DeclID>(Record[I++]); 3168 auto *Decl = GetDecl(DeclID); 3169 auto NumExt = static_cast<unsigned>(Record[I++]); 3170 for (unsigned II = 0; II != NumExt; ++II) { 3171 auto Ext = ReadString(Record, I); 3172 OpenCLDeclExtMap[Decl].insert(Ext); 3173 } 3174 } 3175 break; 3176 3177 case TENTATIVE_DEFINITIONS: 3178 for (unsigned I = 0, N = Record.size(); I != N; ++I) 3179 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I])); 3180 break; 3181 3182 case KNOWN_NAMESPACES: 3183 for (unsigned I = 0, N = Record.size(); I != N; ++I) 3184 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I])); 3185 break; 3186 3187 case UNDEFINED_BUT_USED: 3188 if (UndefinedButUsed.size() % 2 != 0) { 3189 Error("Invalid existing UndefinedButUsed"); 3190 return Failure; 3191 } 3192 3193 if (Record.size() % 2 != 0) { 3194 Error("invalid undefined-but-used record"); 3195 return Failure; 3196 } 3197 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) { 3198 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++])); 3199 UndefinedButUsed.push_back( 3200 ReadSourceLocation(F, Record, I).getRawEncoding()); 3201 } 3202 break; 3203 case DELETE_EXPRS_TO_ANALYZE: 3204 for (unsigned I = 0, N = Record.size(); I != N;) { 3205 DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++])); 3206 const uint64_t Count = Record[I++]; 3207 DelayedDeleteExprs.push_back(Count); 3208 for (uint64_t C = 0; C < Count; ++C) { 3209 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding()); 3210 bool IsArrayForm = Record[I++] == 1; 3211 DelayedDeleteExprs.push_back(IsArrayForm); 3212 } 3213 } 3214 break; 3215 3216 case IMPORTED_MODULES: { 3217 if (!F.isModule()) { 3218 // If we aren't loading a module (which has its own exports), make 3219 // all of the imported modules visible. 3220 // FIXME: Deal with macros-only imports. 3221 for (unsigned I = 0, N = Record.size(); I != N; /**/) { 3222 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]); 3223 SourceLocation Loc = ReadSourceLocation(F, Record, I); 3224 if (GlobalID) { 3225 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc)); 3226 if (DeserializationListener) 3227 DeserializationListener->ModuleImportRead(GlobalID, Loc); 3228 } 3229 } 3230 } 3231 break; 3232 } 3233 3234 case MACRO_OFFSET: { 3235 if (F.LocalNumMacros != 0) { 3236 Error("duplicate MACRO_OFFSET record in AST file"); 3237 return Failure; 3238 } 3239 F.MacroOffsets = (const uint32_t *)Blob.data(); 3240 F.LocalNumMacros = Record[0]; 3241 unsigned LocalBaseMacroID = Record[1]; 3242 F.BaseMacroID = getTotalNumMacros(); 3243 3244 if (F.LocalNumMacros > 0) { 3245 // Introduce the global -> local mapping for macros within this module. 3246 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F)); 3247 3248 // Introduce the local -> global mapping for macros within this module. 3249 F.MacroRemap.insertOrReplace( 3250 std::make_pair(LocalBaseMacroID, 3251 F.BaseMacroID - LocalBaseMacroID)); 3252 3253 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros); 3254 } 3255 break; 3256 } 3257 3258 case LATE_PARSED_TEMPLATE: { 3259 LateParsedTemplates.append(Record.begin(), Record.end()); 3260 break; 3261 } 3262 3263 case OPTIMIZE_PRAGMA_OPTIONS: 3264 if (Record.size() != 1) { 3265 Error("invalid pragma optimize record"); 3266 return Failure; 3267 } 3268 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]); 3269 break; 3270 3271 case MSSTRUCT_PRAGMA_OPTIONS: 3272 if (Record.size() != 1) { 3273 Error("invalid pragma ms_struct record"); 3274 return Failure; 3275 } 3276 PragmaMSStructState = Record[0]; 3277 break; 3278 3279 case POINTERS_TO_MEMBERS_PRAGMA_OPTIONS: 3280 if (Record.size() != 2) { 3281 Error("invalid pragma ms_struct record"); 3282 return Failure; 3283 } 3284 PragmaMSPointersToMembersState = Record[0]; 3285 PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]); 3286 break; 3287 3288 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES: 3289 for (unsigned I = 0, N = Record.size(); I != N; ++I) 3290 UnusedLocalTypedefNameCandidates.push_back( 3291 getGlobalDeclID(F, Record[I])); 3292 break; 3293 3294 case CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH: 3295 if (Record.size() != 1) { 3296 Error("invalid cuda pragma options record"); 3297 return Failure; 3298 } 3299 ForceCUDAHostDeviceDepth = Record[0]; 3300 break; 3301 } 3302 } 3303 } 3304 3305 void ASTReader::ReadModuleOffsetMap(ModuleFile &F) const { 3306 assert(!F.ModuleOffsetMap.empty() && "no module offset map to read"); 3307 3308 // Additional remapping information. 3309 const unsigned char *Data = (const unsigned char*)F.ModuleOffsetMap.data(); 3310 const unsigned char *DataEnd = Data + F.ModuleOffsetMap.size(); 3311 F.ModuleOffsetMap = StringRef(); 3312 3313 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders. 3314 if (F.SLocRemap.find(0) == F.SLocRemap.end()) { 3315 F.SLocRemap.insert(std::make_pair(0U, 0)); 3316 F.SLocRemap.insert(std::make_pair(2U, 1)); 3317 } 3318 3319 // Continuous range maps we may be updating in our module. 3320 typedef ContinuousRangeMap<uint32_t, int, 2>::Builder 3321 RemapBuilder; 3322 RemapBuilder SLocRemap(F.SLocRemap); 3323 RemapBuilder IdentifierRemap(F.IdentifierRemap); 3324 RemapBuilder MacroRemap(F.MacroRemap); 3325 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap); 3326 RemapBuilder SubmoduleRemap(F.SubmoduleRemap); 3327 RemapBuilder SelectorRemap(F.SelectorRemap); 3328 RemapBuilder DeclRemap(F.DeclRemap); 3329 RemapBuilder TypeRemap(F.TypeRemap); 3330 3331 while (Data < DataEnd) { 3332 // FIXME: Looking up dependency modules by filename is horrible. 3333 using namespace llvm::support; 3334 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data); 3335 StringRef Name = StringRef((const char*)Data, Len); 3336 Data += Len; 3337 ModuleFile *OM = ModuleMgr.lookup(Name); 3338 if (!OM) { 3339 std::string Msg = 3340 "SourceLocation remap refers to unknown module, cannot find "; 3341 Msg.append(Name); 3342 Error(Msg); 3343 return; 3344 } 3345 3346 uint32_t SLocOffset = 3347 endian::readNext<uint32_t, little, unaligned>(Data); 3348 uint32_t IdentifierIDOffset = 3349 endian::readNext<uint32_t, little, unaligned>(Data); 3350 uint32_t MacroIDOffset = 3351 endian::readNext<uint32_t, little, unaligned>(Data); 3352 uint32_t PreprocessedEntityIDOffset = 3353 endian::readNext<uint32_t, little, unaligned>(Data); 3354 uint32_t SubmoduleIDOffset = 3355 endian::readNext<uint32_t, little, unaligned>(Data); 3356 uint32_t SelectorIDOffset = 3357 endian::readNext<uint32_t, little, unaligned>(Data); 3358 uint32_t DeclIDOffset = 3359 endian::readNext<uint32_t, little, unaligned>(Data); 3360 uint32_t TypeIndexOffset = 3361 endian::readNext<uint32_t, little, unaligned>(Data); 3362 3363 uint32_t None = std::numeric_limits<uint32_t>::max(); 3364 3365 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset, 3366 RemapBuilder &Remap) { 3367 if (Offset != None) 3368 Remap.insert(std::make_pair(Offset, 3369 static_cast<int>(BaseOffset - Offset))); 3370 }; 3371 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap); 3372 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap); 3373 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap); 3374 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID, 3375 PreprocessedEntityRemap); 3376 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap); 3377 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap); 3378 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap); 3379 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap); 3380 3381 // Global -> local mappings. 3382 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset; 3383 } 3384 } 3385 3386 ASTReader::ASTReadResult 3387 ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F, 3388 const ModuleFile *ImportedBy, 3389 unsigned ClientLoadCapabilities) { 3390 unsigned Idx = 0; 3391 F.ModuleMapPath = ReadPath(F, Record, Idx); 3392 3393 if (F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule) { 3394 // For an explicitly-loaded module, we don't care whether the original 3395 // module map file exists or matches. 3396 return Success; 3397 } 3398 3399 // Try to resolve ModuleName in the current header search context and 3400 // verify that it is found in the same module map file as we saved. If the 3401 // top-level AST file is a main file, skip this check because there is no 3402 // usable header search context. 3403 assert(!F.ModuleName.empty() && 3404 "MODULE_NAME should come before MODULE_MAP_FILE"); 3405 if (F.Kind == MK_ImplicitModule && ModuleMgr.begin()->Kind != MK_MainFile) { 3406 // An implicitly-loaded module file should have its module listed in some 3407 // module map file that we've already loaded. 3408 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName); 3409 auto &Map = PP.getHeaderSearchInfo().getModuleMap(); 3410 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr; 3411 if (!ModMap) { 3412 assert(ImportedBy && "top-level import should be verified"); 3413 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) { 3414 if (auto *ASTFE = M ? M->getASTFile() : nullptr) 3415 // This module was defined by an imported (explicit) module. 3416 Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName 3417 << ASTFE->getName(); 3418 else 3419 // This module was built with a different module map. 3420 Diag(diag::err_imported_module_not_found) 3421 << F.ModuleName << F.FileName << ImportedBy->FileName 3422 << F.ModuleMapPath; 3423 } 3424 return OutOfDate; 3425 } 3426 3427 assert(M->Name == F.ModuleName && "found module with different name"); 3428 3429 // Check the primary module map file. 3430 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath); 3431 if (StoredModMap == nullptr || StoredModMap != ModMap) { 3432 assert(ModMap && "found module is missing module map file"); 3433 assert(ImportedBy && "top-level import should be verified"); 3434 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) 3435 Diag(diag::err_imported_module_modmap_changed) 3436 << F.ModuleName << ImportedBy->FileName 3437 << ModMap->getName() << F.ModuleMapPath; 3438 return OutOfDate; 3439 } 3440 3441 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps; 3442 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) { 3443 // FIXME: we should use input files rather than storing names. 3444 std::string Filename = ReadPath(F, Record, Idx); 3445 const FileEntry *F = 3446 FileMgr.getFile(Filename, false, false); 3447 if (F == nullptr) { 3448 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) 3449 Error("could not find file '" + Filename +"' referenced by AST file"); 3450 return OutOfDate; 3451 } 3452 AdditionalStoredMaps.insert(F); 3453 } 3454 3455 // Check any additional module map files (e.g. module.private.modulemap) 3456 // that are not in the pcm. 3457 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) { 3458 for (const FileEntry *ModMap : *AdditionalModuleMaps) { 3459 // Remove files that match 3460 // Note: SmallPtrSet::erase is really remove 3461 if (!AdditionalStoredMaps.erase(ModMap)) { 3462 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) 3463 Diag(diag::err_module_different_modmap) 3464 << F.ModuleName << /*new*/0 << ModMap->getName(); 3465 return OutOfDate; 3466 } 3467 } 3468 } 3469 3470 // Check any additional module map files that are in the pcm, but not 3471 // found in header search. Cases that match are already removed. 3472 for (const FileEntry *ModMap : AdditionalStoredMaps) { 3473 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) 3474 Diag(diag::err_module_different_modmap) 3475 << F.ModuleName << /*not new*/1 << ModMap->getName(); 3476 return OutOfDate; 3477 } 3478 } 3479 3480 if (Listener) 3481 Listener->ReadModuleMapFile(F.ModuleMapPath); 3482 return Success; 3483 } 3484 3485 3486 /// \brief Move the given method to the back of the global list of methods. 3487 static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) { 3488 // Find the entry for this selector in the method pool. 3489 Sema::GlobalMethodPool::iterator Known 3490 = S.MethodPool.find(Method->getSelector()); 3491 if (Known == S.MethodPool.end()) 3492 return; 3493 3494 // Retrieve the appropriate method list. 3495 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first 3496 : Known->second.second; 3497 bool Found = false; 3498 for (ObjCMethodList *List = &Start; List; List = List->getNext()) { 3499 if (!Found) { 3500 if (List->getMethod() == Method) { 3501 Found = true; 3502 } else { 3503 // Keep searching. 3504 continue; 3505 } 3506 } 3507 3508 if (List->getNext()) 3509 List->setMethod(List->getNext()->getMethod()); 3510 else 3511 List->setMethod(Method); 3512 } 3513 } 3514 3515 void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) { 3516 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?"); 3517 for (Decl *D : Names) { 3518 bool wasHidden = D->Hidden; 3519 D->Hidden = false; 3520 3521 if (wasHidden && SemaObj) { 3522 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) { 3523 moveMethodToBackOfGlobalList(*SemaObj, Method); 3524 } 3525 } 3526 } 3527 } 3528 3529 void ASTReader::makeModuleVisible(Module *Mod, 3530 Module::NameVisibilityKind NameVisibility, 3531 SourceLocation ImportLoc) { 3532 llvm::SmallPtrSet<Module *, 4> Visited; 3533 SmallVector<Module *, 4> Stack; 3534 Stack.push_back(Mod); 3535 while (!Stack.empty()) { 3536 Mod = Stack.pop_back_val(); 3537 3538 if (NameVisibility <= Mod->NameVisibility) { 3539 // This module already has this level of visibility (or greater), so 3540 // there is nothing more to do. 3541 continue; 3542 } 3543 3544 if (!Mod->isAvailable()) { 3545 // Modules that aren't available cannot be made visible. 3546 continue; 3547 } 3548 3549 // Update the module's name visibility. 3550 Mod->NameVisibility = NameVisibility; 3551 3552 // If we've already deserialized any names from this module, 3553 // mark them as visible. 3554 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod); 3555 if (Hidden != HiddenNamesMap.end()) { 3556 auto HiddenNames = std::move(*Hidden); 3557 HiddenNamesMap.erase(Hidden); 3558 makeNamesVisible(HiddenNames.second, HiddenNames.first); 3559 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() && 3560 "making names visible added hidden names"); 3561 } 3562 3563 // Push any exported modules onto the stack to be marked as visible. 3564 SmallVector<Module *, 16> Exports; 3565 Mod->getExportedModules(Exports); 3566 for (SmallVectorImpl<Module *>::iterator 3567 I = Exports.begin(), E = Exports.end(); I != E; ++I) { 3568 Module *Exported = *I; 3569 if (Visited.insert(Exported).second) 3570 Stack.push_back(Exported); 3571 } 3572 } 3573 } 3574 3575 /// We've merged the definition \p MergedDef into the existing definition 3576 /// \p Def. Ensure that \p Def is made visible whenever \p MergedDef is made 3577 /// visible. 3578 void ASTReader::mergeDefinitionVisibility(NamedDecl *Def, 3579 NamedDecl *MergedDef) { 3580 // FIXME: This doesn't correctly handle the case where MergedDef is visible 3581 // in modules other than its owning module. We should instead give the 3582 // ASTContext a list of merged definitions for Def. 3583 if (Def->isHidden()) { 3584 // If MergedDef is visible or becomes visible, make the definition visible. 3585 if (!MergedDef->isHidden()) 3586 Def->Hidden = false; 3587 else if (getContext().getLangOpts().ModulesLocalVisibility) { 3588 getContext().mergeDefinitionIntoModule( 3589 Def, MergedDef->getImportedOwningModule(), 3590 /*NotifyListeners*/ false); 3591 PendingMergedDefinitionsToDeduplicate.insert(Def); 3592 } else { 3593 auto SubmoduleID = MergedDef->getOwningModuleID(); 3594 assert(SubmoduleID && "hidden definition in no module"); 3595 HiddenNamesMap[getSubmodule(SubmoduleID)].push_back(Def); 3596 } 3597 } 3598 } 3599 3600 bool ASTReader::loadGlobalIndex() { 3601 if (GlobalIndex) 3602 return false; 3603 3604 if (TriedLoadingGlobalIndex || !UseGlobalIndex || 3605 !Context.getLangOpts().Modules) 3606 return true; 3607 3608 // Try to load the global index. 3609 TriedLoadingGlobalIndex = true; 3610 StringRef ModuleCachePath 3611 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath(); 3612 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result 3613 = GlobalModuleIndex::readIndex(ModuleCachePath); 3614 if (!Result.first) 3615 return true; 3616 3617 GlobalIndex.reset(Result.first); 3618 ModuleMgr.setGlobalIndex(GlobalIndex.get()); 3619 return false; 3620 } 3621 3622 bool ASTReader::isGlobalIndexUnavailable() const { 3623 return Context.getLangOpts().Modules && UseGlobalIndex && 3624 !hasGlobalIndex() && TriedLoadingGlobalIndex; 3625 } 3626 3627 static void updateModuleTimestamp(ModuleFile &MF) { 3628 // Overwrite the timestamp file contents so that file's mtime changes. 3629 std::string TimestampFilename = MF.getTimestampFilename(); 3630 std::error_code EC; 3631 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text); 3632 if (EC) 3633 return; 3634 OS << "Timestamp file\n"; 3635 } 3636 3637 /// \brief Given a cursor at the start of an AST file, scan ahead and drop the 3638 /// cursor into the start of the given block ID, returning false on success and 3639 /// true on failure. 3640 static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) { 3641 while (true) { 3642 llvm::BitstreamEntry Entry = Cursor.advance(); 3643 switch (Entry.Kind) { 3644 case llvm::BitstreamEntry::Error: 3645 case llvm::BitstreamEntry::EndBlock: 3646 return true; 3647 3648 case llvm::BitstreamEntry::Record: 3649 // Ignore top-level records. 3650 Cursor.skipRecord(Entry.ID); 3651 break; 3652 3653 case llvm::BitstreamEntry::SubBlock: 3654 if (Entry.ID == BlockID) { 3655 if (Cursor.EnterSubBlock(BlockID)) 3656 return true; 3657 // Found it! 3658 return false; 3659 } 3660 3661 if (Cursor.SkipBlock()) 3662 return true; 3663 } 3664 } 3665 } 3666 3667 ASTReader::ASTReadResult ASTReader::ReadAST(StringRef FileName, 3668 ModuleKind Type, 3669 SourceLocation ImportLoc, 3670 unsigned ClientLoadCapabilities, 3671 SmallVectorImpl<ImportedSubmodule> *Imported) { 3672 llvm::SaveAndRestore<SourceLocation> 3673 SetCurImportLocRAII(CurrentImportLoc, ImportLoc); 3674 3675 // Defer any pending actions until we get to the end of reading the AST file. 3676 Deserializing AnASTFile(this); 3677 3678 // Bump the generation number. 3679 unsigned PreviousGeneration = incrementGeneration(Context); 3680 3681 unsigned NumModules = ModuleMgr.size(); 3682 SmallVector<ImportedModule, 4> Loaded; 3683 switch (ASTReadResult ReadResult = 3684 ReadASTCore(FileName, Type, ImportLoc, 3685 /*ImportedBy=*/nullptr, Loaded, 0, 0, 3686 ASTFileSignature(), ClientLoadCapabilities)) { 3687 case Failure: 3688 case Missing: 3689 case OutOfDate: 3690 case VersionMismatch: 3691 case ConfigurationMismatch: 3692 case HadErrors: { 3693 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet; 3694 for (const ImportedModule &IM : Loaded) 3695 LoadedSet.insert(IM.Mod); 3696 3697 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, LoadedSet, 3698 Context.getLangOpts().Modules 3699 ? &PP.getHeaderSearchInfo().getModuleMap() 3700 : nullptr); 3701 3702 // If we find that any modules are unusable, the global index is going 3703 // to be out-of-date. Just remove it. 3704 GlobalIndex.reset(); 3705 ModuleMgr.setGlobalIndex(nullptr); 3706 return ReadResult; 3707 } 3708 case Success: 3709 break; 3710 } 3711 3712 // Here comes stuff that we only do once the entire chain is loaded. 3713 3714 // Load the AST blocks of all of the modules that we loaded. 3715 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(), 3716 MEnd = Loaded.end(); 3717 M != MEnd; ++M) { 3718 ModuleFile &F = *M->Mod; 3719 3720 // Read the AST block. 3721 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities)) 3722 return Result; 3723 3724 // Read the extension blocks. 3725 while (!SkipCursorToBlock(F.Stream, EXTENSION_BLOCK_ID)) { 3726 if (ASTReadResult Result = ReadExtensionBlock(F)) 3727 return Result; 3728 } 3729 3730 // Once read, set the ModuleFile bit base offset and update the size in 3731 // bits of all files we've seen. 3732 F.GlobalBitOffset = TotalModulesSizeInBits; 3733 TotalModulesSizeInBits += F.SizeInBits; 3734 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F)); 3735 3736 // Preload SLocEntries. 3737 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) { 3738 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID; 3739 // Load it through the SourceManager and don't call ReadSLocEntry() 3740 // directly because the entry may have already been loaded in which case 3741 // calling ReadSLocEntry() directly would trigger an assertion in 3742 // SourceManager. 3743 SourceMgr.getLoadedSLocEntryByID(Index); 3744 } 3745 3746 // Preload all the pending interesting identifiers by marking them out of 3747 // date. 3748 for (auto Offset : F.PreloadIdentifierOffsets) { 3749 const unsigned char *Data = reinterpret_cast<const unsigned char *>( 3750 F.IdentifierTableData + Offset); 3751 3752 ASTIdentifierLookupTrait Trait(*this, F); 3753 auto KeyDataLen = Trait.ReadKeyDataLength(Data); 3754 auto Key = Trait.ReadKey(Data, KeyDataLen.first); 3755 auto &II = PP.getIdentifierTable().getOwn(Key); 3756 II.setOutOfDate(true); 3757 3758 // Mark this identifier as being from an AST file so that we can track 3759 // whether we need to serialize it. 3760 markIdentifierFromAST(*this, II); 3761 3762 // Associate the ID with the identifier so that the writer can reuse it. 3763 auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first); 3764 SetIdentifierInfo(ID, &II); 3765 } 3766 } 3767 3768 // Setup the import locations and notify the module manager that we've 3769 // committed to these module files. 3770 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(), 3771 MEnd = Loaded.end(); 3772 M != MEnd; ++M) { 3773 ModuleFile &F = *M->Mod; 3774 3775 ModuleMgr.moduleFileAccepted(&F); 3776 3777 // Set the import location. 3778 F.DirectImportLoc = ImportLoc; 3779 // FIXME: We assume that locations from PCH / preamble do not need 3780 // any translation. 3781 if (!M->ImportedBy) 3782 F.ImportLoc = M->ImportLoc; 3783 else 3784 F.ImportLoc = TranslateSourceLocation(*M->ImportedBy, M->ImportLoc); 3785 } 3786 3787 if (!Context.getLangOpts().CPlusPlus || 3788 (Type != MK_ImplicitModule && Type != MK_ExplicitModule && 3789 Type != MK_PrebuiltModule)) { 3790 // Mark all of the identifiers in the identifier table as being out of date, 3791 // so that various accessors know to check the loaded modules when the 3792 // identifier is used. 3793 // 3794 // For C++ modules, we don't need information on many identifiers (just 3795 // those that provide macros or are poisoned), so we mark all of 3796 // the interesting ones via PreloadIdentifierOffsets. 3797 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(), 3798 IdEnd = PP.getIdentifierTable().end(); 3799 Id != IdEnd; ++Id) 3800 Id->second->setOutOfDate(true); 3801 } 3802 // Mark selectors as out of date. 3803 for (auto Sel : SelectorGeneration) 3804 SelectorOutOfDate[Sel.first] = true; 3805 3806 // Resolve any unresolved module exports. 3807 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) { 3808 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I]; 3809 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID); 3810 Module *ResolvedMod = getSubmodule(GlobalID); 3811 3812 switch (Unresolved.Kind) { 3813 case UnresolvedModuleRef::Conflict: 3814 if (ResolvedMod) { 3815 Module::Conflict Conflict; 3816 Conflict.Other = ResolvedMod; 3817 Conflict.Message = Unresolved.String.str(); 3818 Unresolved.Mod->Conflicts.push_back(Conflict); 3819 } 3820 continue; 3821 3822 case UnresolvedModuleRef::Import: 3823 if (ResolvedMod) 3824 Unresolved.Mod->Imports.insert(ResolvedMod); 3825 continue; 3826 3827 case UnresolvedModuleRef::Export: 3828 if (ResolvedMod || Unresolved.IsWildcard) 3829 Unresolved.Mod->Exports.push_back( 3830 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard)); 3831 continue; 3832 } 3833 } 3834 UnresolvedModuleRefs.clear(); 3835 3836 if (Imported) 3837 Imported->append(ImportedModules.begin(), 3838 ImportedModules.end()); 3839 3840 // FIXME: How do we load the 'use'd modules? They may not be submodules. 3841 // Might be unnecessary as use declarations are only used to build the 3842 // module itself. 3843 3844 InitializeContext(); 3845 3846 if (SemaObj) 3847 UpdateSema(); 3848 3849 if (DeserializationListener) 3850 DeserializationListener->ReaderInitialized(this); 3851 3852 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule(); 3853 if (PrimaryModule.OriginalSourceFileID.isValid()) { 3854 PrimaryModule.OriginalSourceFileID 3855 = FileID::get(PrimaryModule.SLocEntryBaseID 3856 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1); 3857 3858 // If this AST file is a precompiled preamble, then set the 3859 // preamble file ID of the source manager to the file source file 3860 // from which the preamble was built. 3861 if (Type == MK_Preamble) { 3862 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID); 3863 } else if (Type == MK_MainFile) { 3864 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID); 3865 } 3866 } 3867 3868 // For any Objective-C class definitions we have already loaded, make sure 3869 // that we load any additional categories. 3870 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) { 3871 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(), 3872 ObjCClassesLoaded[I], 3873 PreviousGeneration); 3874 } 3875 3876 if (PP.getHeaderSearchInfo() 3877 .getHeaderSearchOpts() 3878 .ModulesValidateOncePerBuildSession) { 3879 // Now we are certain that the module and all modules it depends on are 3880 // up to date. Create or update timestamp files for modules that are 3881 // located in the module cache (not for PCH files that could be anywhere 3882 // in the filesystem). 3883 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) { 3884 ImportedModule &M = Loaded[I]; 3885 if (M.Mod->Kind == MK_ImplicitModule) { 3886 updateModuleTimestamp(*M.Mod); 3887 } 3888 } 3889 } 3890 3891 return Success; 3892 } 3893 3894 static ASTFileSignature readASTFileSignature(StringRef PCH); 3895 3896 /// \brief Whether \p Stream starts with the AST/PCH file magic number 'CPCH'. 3897 static bool startsWithASTFileMagic(BitstreamCursor &Stream) { 3898 return Stream.canSkipToPos(4) && 3899 Stream.Read(8) == 'C' && 3900 Stream.Read(8) == 'P' && 3901 Stream.Read(8) == 'C' && 3902 Stream.Read(8) == 'H'; 3903 } 3904 3905 static unsigned moduleKindForDiagnostic(ModuleKind Kind) { 3906 switch (Kind) { 3907 case MK_PCH: 3908 return 0; // PCH 3909 case MK_ImplicitModule: 3910 case MK_ExplicitModule: 3911 case MK_PrebuiltModule: 3912 return 1; // module 3913 case MK_MainFile: 3914 case MK_Preamble: 3915 return 2; // main source file 3916 } 3917 llvm_unreachable("unknown module kind"); 3918 } 3919 3920 ASTReader::ASTReadResult 3921 ASTReader::ReadASTCore(StringRef FileName, 3922 ModuleKind Type, 3923 SourceLocation ImportLoc, 3924 ModuleFile *ImportedBy, 3925 SmallVectorImpl<ImportedModule> &Loaded, 3926 off_t ExpectedSize, time_t ExpectedModTime, 3927 ASTFileSignature ExpectedSignature, 3928 unsigned ClientLoadCapabilities) { 3929 ModuleFile *M; 3930 std::string ErrorStr; 3931 ModuleManager::AddModuleResult AddResult 3932 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy, 3933 getGeneration(), ExpectedSize, ExpectedModTime, 3934 ExpectedSignature, readASTFileSignature, 3935 M, ErrorStr); 3936 3937 switch (AddResult) { 3938 case ModuleManager::AlreadyLoaded: 3939 return Success; 3940 3941 case ModuleManager::NewlyLoaded: 3942 // Load module file below. 3943 break; 3944 3945 case ModuleManager::Missing: 3946 // The module file was missing; if the client can handle that, return 3947 // it. 3948 if (ClientLoadCapabilities & ARR_Missing) 3949 return Missing; 3950 3951 // Otherwise, return an error. 3952 Diag(diag::err_module_file_not_found) << moduleKindForDiagnostic(Type) 3953 << FileName << !ErrorStr.empty() 3954 << ErrorStr; 3955 return Failure; 3956 3957 case ModuleManager::OutOfDate: 3958 // We couldn't load the module file because it is out-of-date. If the 3959 // client can handle out-of-date, return it. 3960 if (ClientLoadCapabilities & ARR_OutOfDate) 3961 return OutOfDate; 3962 3963 // Otherwise, return an error. 3964 Diag(diag::err_module_file_out_of_date) << moduleKindForDiagnostic(Type) 3965 << FileName << !ErrorStr.empty() 3966 << ErrorStr; 3967 return Failure; 3968 } 3969 3970 assert(M && "Missing module file"); 3971 3972 // FIXME: This seems rather a hack. Should CurrentDir be part of the 3973 // module? 3974 if (FileName != "-") { 3975 CurrentDir = llvm::sys::path::parent_path(FileName); 3976 if (CurrentDir.empty()) CurrentDir = "."; 3977 } 3978 3979 ModuleFile &F = *M; 3980 BitstreamCursor &Stream = F.Stream; 3981 Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(*F.Buffer)); 3982 F.SizeInBits = F.Buffer->getBufferSize() * 8; 3983 3984 // Sniff for the signature. 3985 if (!startsWithASTFileMagic(Stream)) { 3986 Diag(diag::err_module_file_invalid) << moduleKindForDiagnostic(Type) 3987 << FileName; 3988 return Failure; 3989 } 3990 3991 // This is used for compatibility with older PCH formats. 3992 bool HaveReadControlBlock = false; 3993 while (true) { 3994 llvm::BitstreamEntry Entry = Stream.advance(); 3995 3996 switch (Entry.Kind) { 3997 case llvm::BitstreamEntry::Error: 3998 case llvm::BitstreamEntry::Record: 3999 case llvm::BitstreamEntry::EndBlock: 4000 Error("invalid record at top-level of AST file"); 4001 return Failure; 4002 4003 case llvm::BitstreamEntry::SubBlock: 4004 break; 4005 } 4006 4007 switch (Entry.ID) { 4008 case CONTROL_BLOCK_ID: 4009 HaveReadControlBlock = true; 4010 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) { 4011 case Success: 4012 // Check that we didn't try to load a non-module AST file as a module. 4013 // 4014 // FIXME: Should we also perform the converse check? Loading a module as 4015 // a PCH file sort of works, but it's a bit wonky. 4016 if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule || 4017 Type == MK_PrebuiltModule) && 4018 F.ModuleName.empty()) { 4019 auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure; 4020 if (Result != OutOfDate || 4021 (ClientLoadCapabilities & ARR_OutOfDate) == 0) 4022 Diag(diag::err_module_file_not_module) << FileName; 4023 return Result; 4024 } 4025 break; 4026 4027 case Failure: return Failure; 4028 case Missing: return Missing; 4029 case OutOfDate: return OutOfDate; 4030 case VersionMismatch: return VersionMismatch; 4031 case ConfigurationMismatch: return ConfigurationMismatch; 4032 case HadErrors: return HadErrors; 4033 } 4034 break; 4035 4036 case AST_BLOCK_ID: 4037 if (!HaveReadControlBlock) { 4038 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0) 4039 Diag(diag::err_pch_version_too_old); 4040 return VersionMismatch; 4041 } 4042 4043 // Record that we've loaded this module. 4044 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc)); 4045 return Success; 4046 4047 case UNHASHED_CONTROL_BLOCK_ID: 4048 // This block is handled using look-ahead during ReadControlBlock. We 4049 // shouldn't get here! 4050 Error("malformed block record in AST file"); 4051 return Failure; 4052 4053 default: 4054 if (Stream.SkipBlock()) { 4055 Error("malformed block record in AST file"); 4056 return Failure; 4057 } 4058 break; 4059 } 4060 } 4061 4062 return Success; 4063 } 4064 4065 ASTReader::ASTReadResult 4066 ASTReader::readUnhashedControlBlock(ModuleFile &F, bool WasImportedBy, 4067 unsigned ClientLoadCapabilities) { 4068 const HeaderSearchOptions &HSOpts = 4069 PP.getHeaderSearchInfo().getHeaderSearchOpts(); 4070 bool AllowCompatibleConfigurationMismatch = 4071 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule; 4072 4073 ASTReadResult Result = readUnhashedControlBlockImpl( 4074 &F, F.Data, ClientLoadCapabilities, AllowCompatibleConfigurationMismatch, 4075 Listener.get(), 4076 WasImportedBy ? false : HSOpts.ModulesValidateDiagnosticOptions); 4077 4078 // If F was directly imported by another module, it's implicitly validated by 4079 // the importing module. 4080 if (DisableValidation || WasImportedBy || 4081 (AllowConfigurationMismatch && Result == ConfigurationMismatch)) 4082 return Success; 4083 4084 if (Result == Failure) { 4085 Error("malformed block record in AST file"); 4086 return Failure; 4087 } 4088 4089 if (Result == OutOfDate && F.Kind == MK_ImplicitModule) { 4090 // If this module has already been finalized in the PCMCache, we're stuck 4091 // with it; we can only load a single version of each module. 4092 // 4093 // This can happen when a module is imported in two contexts: in one, as a 4094 // user module; in another, as a system module (due to an import from 4095 // another module marked with the [system] flag). It usually indicates a 4096 // bug in the module map: this module should also be marked with [system]. 4097 // 4098 // If -Wno-system-headers (the default), and the first import is as a 4099 // system module, then validation will fail during the as-user import, 4100 // since -Werror flags won't have been validated. However, it's reasonable 4101 // to treat this consistently as a system module. 4102 // 4103 // If -Wsystem-headers, the PCM on disk was built with 4104 // -Wno-system-headers, and the first import is as a user module, then 4105 // validation will fail during the as-system import since the PCM on disk 4106 // doesn't guarantee that -Werror was respected. However, the -Werror 4107 // flags were checked during the initial as-user import. 4108 if (PCMCache.isBufferFinal(F.FileName)) { 4109 Diag(diag::warn_module_system_bit_conflict) << F.FileName; 4110 return Success; 4111 } 4112 } 4113 4114 return Result; 4115 } 4116 4117 ASTReader::ASTReadResult ASTReader::readUnhashedControlBlockImpl( 4118 ModuleFile *F, llvm::StringRef StreamData, unsigned ClientLoadCapabilities, 4119 bool AllowCompatibleConfigurationMismatch, ASTReaderListener *Listener, 4120 bool ValidateDiagnosticOptions) { 4121 // Initialize a stream. 4122 BitstreamCursor Stream(StreamData); 4123 4124 // Sniff for the signature. 4125 if (!startsWithASTFileMagic(Stream)) 4126 return Failure; 4127 4128 // Scan for the UNHASHED_CONTROL_BLOCK_ID block. 4129 if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID)) 4130 return Failure; 4131 4132 // Read all of the records in the options block. 4133 RecordData Record; 4134 ASTReadResult Result = Success; 4135 while (1) { 4136 llvm::BitstreamEntry Entry = Stream.advance(); 4137 4138 switch (Entry.Kind) { 4139 case llvm::BitstreamEntry::Error: 4140 case llvm::BitstreamEntry::SubBlock: 4141 return Failure; 4142 4143 case llvm::BitstreamEntry::EndBlock: 4144 return Result; 4145 4146 case llvm::BitstreamEntry::Record: 4147 // The interesting case. 4148 break; 4149 } 4150 4151 // Read and process a record. 4152 Record.clear(); 4153 switch ( 4154 (UnhashedControlBlockRecordTypes)Stream.readRecord(Entry.ID, Record)) { 4155 case SIGNATURE: { 4156 if (F) 4157 std::copy(Record.begin(), Record.end(), F->Signature.data()); 4158 break; 4159 } 4160 case DIAGNOSTIC_OPTIONS: { 4161 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0; 4162 if (Listener && ValidateDiagnosticOptions && 4163 !AllowCompatibleConfigurationMismatch && 4164 ParseDiagnosticOptions(Record, Complain, *Listener)) 4165 Result = OutOfDate; // Don't return early. Read the signature. 4166 break; 4167 } 4168 case DIAG_PRAGMA_MAPPINGS: 4169 if (!F) 4170 break; 4171 if (F->PragmaDiagMappings.empty()) 4172 F->PragmaDiagMappings.swap(Record); 4173 else 4174 F->PragmaDiagMappings.insert(F->PragmaDiagMappings.end(), 4175 Record.begin(), Record.end()); 4176 break; 4177 } 4178 } 4179 } 4180 4181 /// Parse a record and blob containing module file extension metadata. 4182 static bool parseModuleFileExtensionMetadata( 4183 const SmallVectorImpl<uint64_t> &Record, 4184 StringRef Blob, 4185 ModuleFileExtensionMetadata &Metadata) { 4186 if (Record.size() < 4) return true; 4187 4188 Metadata.MajorVersion = Record[0]; 4189 Metadata.MinorVersion = Record[1]; 4190 4191 unsigned BlockNameLen = Record[2]; 4192 unsigned UserInfoLen = Record[3]; 4193 4194 if (BlockNameLen + UserInfoLen > Blob.size()) return true; 4195 4196 Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen); 4197 Metadata.UserInfo = std::string(Blob.data() + BlockNameLen, 4198 Blob.data() + BlockNameLen + UserInfoLen); 4199 return false; 4200 } 4201 4202 ASTReader::ASTReadResult ASTReader::ReadExtensionBlock(ModuleFile &F) { 4203 BitstreamCursor &Stream = F.Stream; 4204 4205 RecordData Record; 4206 while (true) { 4207 llvm::BitstreamEntry Entry = Stream.advance(); 4208 switch (Entry.Kind) { 4209 case llvm::BitstreamEntry::SubBlock: 4210 if (Stream.SkipBlock()) 4211 return Failure; 4212 4213 continue; 4214 4215 case llvm::BitstreamEntry::EndBlock: 4216 return Success; 4217 4218 case llvm::BitstreamEntry::Error: 4219 return HadErrors; 4220 4221 case llvm::BitstreamEntry::Record: 4222 break; 4223 } 4224 4225 Record.clear(); 4226 StringRef Blob; 4227 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob); 4228 switch (RecCode) { 4229 case EXTENSION_METADATA: { 4230 ModuleFileExtensionMetadata Metadata; 4231 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata)) 4232 return Failure; 4233 4234 // Find a module file extension with this block name. 4235 auto Known = ModuleFileExtensions.find(Metadata.BlockName); 4236 if (Known == ModuleFileExtensions.end()) break; 4237 4238 // Form a reader. 4239 if (auto Reader = Known->second->createExtensionReader(Metadata, *this, 4240 F, Stream)) { 4241 F.ExtensionReaders.push_back(std::move(Reader)); 4242 } 4243 4244 break; 4245 } 4246 } 4247 } 4248 4249 return Success; 4250 } 4251 4252 void ASTReader::InitializeContext() { 4253 // If there's a listener, notify them that we "read" the translation unit. 4254 if (DeserializationListener) 4255 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID, 4256 Context.getTranslationUnitDecl()); 4257 4258 // FIXME: Find a better way to deal with collisions between these 4259 // built-in types. Right now, we just ignore the problem. 4260 4261 // Load the special types. 4262 if (SpecialTypes.size() >= NumSpecialTypeIDs) { 4263 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) { 4264 if (!Context.CFConstantStringTypeDecl) 4265 Context.setCFConstantStringType(GetType(String)); 4266 } 4267 4268 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) { 4269 QualType FileType = GetType(File); 4270 if (FileType.isNull()) { 4271 Error("FILE type is NULL"); 4272 return; 4273 } 4274 4275 if (!Context.FILEDecl) { 4276 if (const TypedefType *Typedef = FileType->getAs<TypedefType>()) 4277 Context.setFILEDecl(Typedef->getDecl()); 4278 else { 4279 const TagType *Tag = FileType->getAs<TagType>(); 4280 if (!Tag) { 4281 Error("Invalid FILE type in AST file"); 4282 return; 4283 } 4284 Context.setFILEDecl(Tag->getDecl()); 4285 } 4286 } 4287 } 4288 4289 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) { 4290 QualType Jmp_bufType = GetType(Jmp_buf); 4291 if (Jmp_bufType.isNull()) { 4292 Error("jmp_buf type is NULL"); 4293 return; 4294 } 4295 4296 if (!Context.jmp_bufDecl) { 4297 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>()) 4298 Context.setjmp_bufDecl(Typedef->getDecl()); 4299 else { 4300 const TagType *Tag = Jmp_bufType->getAs<TagType>(); 4301 if (!Tag) { 4302 Error("Invalid jmp_buf type in AST file"); 4303 return; 4304 } 4305 Context.setjmp_bufDecl(Tag->getDecl()); 4306 } 4307 } 4308 } 4309 4310 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) { 4311 QualType Sigjmp_bufType = GetType(Sigjmp_buf); 4312 if (Sigjmp_bufType.isNull()) { 4313 Error("sigjmp_buf type is NULL"); 4314 return; 4315 } 4316 4317 if (!Context.sigjmp_bufDecl) { 4318 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>()) 4319 Context.setsigjmp_bufDecl(Typedef->getDecl()); 4320 else { 4321 const TagType *Tag = Sigjmp_bufType->getAs<TagType>(); 4322 assert(Tag && "Invalid sigjmp_buf type in AST file"); 4323 Context.setsigjmp_bufDecl(Tag->getDecl()); 4324 } 4325 } 4326 } 4327 4328 if (unsigned ObjCIdRedef 4329 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) { 4330 if (Context.ObjCIdRedefinitionType.isNull()) 4331 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef); 4332 } 4333 4334 if (unsigned ObjCClassRedef 4335 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) { 4336 if (Context.ObjCClassRedefinitionType.isNull()) 4337 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef); 4338 } 4339 4340 if (unsigned ObjCSelRedef 4341 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) { 4342 if (Context.ObjCSelRedefinitionType.isNull()) 4343 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef); 4344 } 4345 4346 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) { 4347 QualType Ucontext_tType = GetType(Ucontext_t); 4348 if (Ucontext_tType.isNull()) { 4349 Error("ucontext_t type is NULL"); 4350 return; 4351 } 4352 4353 if (!Context.ucontext_tDecl) { 4354 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>()) 4355 Context.setucontext_tDecl(Typedef->getDecl()); 4356 else { 4357 const TagType *Tag = Ucontext_tType->getAs<TagType>(); 4358 assert(Tag && "Invalid ucontext_t type in AST file"); 4359 Context.setucontext_tDecl(Tag->getDecl()); 4360 } 4361 } 4362 } 4363 } 4364 4365 ReadPragmaDiagnosticMappings(Context.getDiagnostics()); 4366 4367 // If there were any CUDA special declarations, deserialize them. 4368 if (!CUDASpecialDeclRefs.empty()) { 4369 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!"); 4370 Context.setcudaConfigureCallDecl( 4371 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0]))); 4372 } 4373 4374 // Re-export any modules that were imported by a non-module AST file. 4375 // FIXME: This does not make macro-only imports visible again. 4376 for (auto &Import : ImportedModules) { 4377 if (Module *Imported = getSubmodule(Import.ID)) { 4378 makeModuleVisible(Imported, Module::AllVisible, 4379 /*ImportLoc=*/Import.ImportLoc); 4380 if (Import.ImportLoc.isValid()) 4381 PP.makeModuleVisible(Imported, Import.ImportLoc); 4382 // FIXME: should we tell Sema to make the module visible too? 4383 } 4384 } 4385 ImportedModules.clear(); 4386 } 4387 4388 void ASTReader::finalizeForWriting() { 4389 // Nothing to do for now. 4390 } 4391 4392 /// \brief Reads and return the signature record from \p PCH's control block, or 4393 /// else returns 0. 4394 static ASTFileSignature readASTFileSignature(StringRef PCH) { 4395 BitstreamCursor Stream(PCH); 4396 if (!startsWithASTFileMagic(Stream)) 4397 return ASTFileSignature(); 4398 4399 // Scan for the UNHASHED_CONTROL_BLOCK_ID block. 4400 if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID)) 4401 return ASTFileSignature(); 4402 4403 // Scan for SIGNATURE inside the diagnostic options block. 4404 ASTReader::RecordData Record; 4405 while (true) { 4406 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 4407 if (Entry.Kind != llvm::BitstreamEntry::Record) 4408 return ASTFileSignature(); 4409 4410 Record.clear(); 4411 StringRef Blob; 4412 if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob)) 4413 return {{{(uint32_t)Record[0], (uint32_t)Record[1], (uint32_t)Record[2], 4414 (uint32_t)Record[3], (uint32_t)Record[4]}}}; 4415 } 4416 } 4417 4418 /// \brief Retrieve the name of the original source file name 4419 /// directly from the AST file, without actually loading the AST 4420 /// file. 4421 std::string ASTReader::getOriginalSourceFile( 4422 const std::string &ASTFileName, FileManager &FileMgr, 4423 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) { 4424 // Open the AST file. 4425 auto Buffer = FileMgr.getBufferForFile(ASTFileName); 4426 if (!Buffer) { 4427 Diags.Report(diag::err_fe_unable_to_read_pch_file) 4428 << ASTFileName << Buffer.getError().message(); 4429 return std::string(); 4430 } 4431 4432 // Initialize the stream 4433 BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer)); 4434 4435 // Sniff for the signature. 4436 if (!startsWithASTFileMagic(Stream)) { 4437 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName; 4438 return std::string(); 4439 } 4440 4441 // Scan for the CONTROL_BLOCK_ID block. 4442 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) { 4443 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName; 4444 return std::string(); 4445 } 4446 4447 // Scan for ORIGINAL_FILE inside the control block. 4448 RecordData Record; 4449 while (true) { 4450 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 4451 if (Entry.Kind == llvm::BitstreamEntry::EndBlock) 4452 return std::string(); 4453 4454 if (Entry.Kind != llvm::BitstreamEntry::Record) { 4455 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName; 4456 return std::string(); 4457 } 4458 4459 Record.clear(); 4460 StringRef Blob; 4461 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE) 4462 return Blob.str(); 4463 } 4464 } 4465 4466 namespace { 4467 4468 class SimplePCHValidator : public ASTReaderListener { 4469 const LangOptions &ExistingLangOpts; 4470 const TargetOptions &ExistingTargetOpts; 4471 const PreprocessorOptions &ExistingPPOpts; 4472 std::string ExistingModuleCachePath; 4473 FileManager &FileMgr; 4474 4475 public: 4476 SimplePCHValidator(const LangOptions &ExistingLangOpts, 4477 const TargetOptions &ExistingTargetOpts, 4478 const PreprocessorOptions &ExistingPPOpts, 4479 StringRef ExistingModuleCachePath, 4480 FileManager &FileMgr) 4481 : ExistingLangOpts(ExistingLangOpts), 4482 ExistingTargetOpts(ExistingTargetOpts), 4483 ExistingPPOpts(ExistingPPOpts), 4484 ExistingModuleCachePath(ExistingModuleCachePath), 4485 FileMgr(FileMgr) 4486 { 4487 } 4488 4489 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain, 4490 bool AllowCompatibleDifferences) override { 4491 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr, 4492 AllowCompatibleDifferences); 4493 } 4494 4495 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain, 4496 bool AllowCompatibleDifferences) override { 4497 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr, 4498 AllowCompatibleDifferences); 4499 } 4500 4501 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, 4502 StringRef SpecificModuleCachePath, 4503 bool Complain) override { 4504 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath, 4505 ExistingModuleCachePath, 4506 nullptr, ExistingLangOpts); 4507 } 4508 4509 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, 4510 bool Complain, 4511 std::string &SuggestedPredefines) override { 4512 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr, 4513 SuggestedPredefines, ExistingLangOpts); 4514 } 4515 }; 4516 4517 } // end anonymous namespace 4518 4519 bool ASTReader::readASTFileControlBlock( 4520 StringRef Filename, FileManager &FileMgr, 4521 const PCHContainerReader &PCHContainerRdr, 4522 bool FindModuleFileExtensions, 4523 ASTReaderListener &Listener, bool ValidateDiagnosticOptions) { 4524 // Open the AST file. 4525 // FIXME: This allows use of the VFS; we do not allow use of the 4526 // VFS when actually loading a module. 4527 auto Buffer = FileMgr.getBufferForFile(Filename); 4528 if (!Buffer) { 4529 return true; 4530 } 4531 4532 // Initialize the stream 4533 StringRef Bytes = PCHContainerRdr.ExtractPCH(**Buffer); 4534 BitstreamCursor Stream(Bytes); 4535 4536 // Sniff for the signature. 4537 if (!startsWithASTFileMagic(Stream)) 4538 return true; 4539 4540 // Scan for the CONTROL_BLOCK_ID block. 4541 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) 4542 return true; 4543 4544 bool NeedsInputFiles = Listener.needsInputFileVisitation(); 4545 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation(); 4546 bool NeedsImports = Listener.needsImportVisitation(); 4547 BitstreamCursor InputFilesCursor; 4548 4549 RecordData Record; 4550 std::string ModuleDir; 4551 bool DoneWithControlBlock = false; 4552 while (!DoneWithControlBlock) { 4553 llvm::BitstreamEntry Entry = Stream.advance(); 4554 4555 switch (Entry.Kind) { 4556 case llvm::BitstreamEntry::SubBlock: { 4557 switch (Entry.ID) { 4558 case OPTIONS_BLOCK_ID: { 4559 std::string IgnoredSuggestedPredefines; 4560 if (ReadOptionsBlock(Stream, ARR_ConfigurationMismatch | ARR_OutOfDate, 4561 /*AllowCompatibleConfigurationMismatch*/ false, 4562 Listener, IgnoredSuggestedPredefines) != Success) 4563 return true; 4564 break; 4565 } 4566 4567 case INPUT_FILES_BLOCK_ID: 4568 InputFilesCursor = Stream; 4569 if (Stream.SkipBlock() || 4570 (NeedsInputFiles && 4571 ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID))) 4572 return true; 4573 break; 4574 4575 default: 4576 if (Stream.SkipBlock()) 4577 return true; 4578 break; 4579 } 4580 4581 continue; 4582 } 4583 4584 case llvm::BitstreamEntry::EndBlock: 4585 DoneWithControlBlock = true; 4586 break; 4587 4588 case llvm::BitstreamEntry::Error: 4589 return true; 4590 4591 case llvm::BitstreamEntry::Record: 4592 break; 4593 } 4594 4595 if (DoneWithControlBlock) break; 4596 4597 Record.clear(); 4598 StringRef Blob; 4599 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob); 4600 switch ((ControlRecordTypes)RecCode) { 4601 case METADATA: { 4602 if (Record[0] != VERSION_MAJOR) 4603 return true; 4604 4605 if (Listener.ReadFullVersionInformation(Blob)) 4606 return true; 4607 4608 break; 4609 } 4610 case MODULE_NAME: 4611 Listener.ReadModuleName(Blob); 4612 break; 4613 case MODULE_DIRECTORY: 4614 ModuleDir = Blob; 4615 break; 4616 case MODULE_MAP_FILE: { 4617 unsigned Idx = 0; 4618 auto Path = ReadString(Record, Idx); 4619 ResolveImportedPath(Path, ModuleDir); 4620 Listener.ReadModuleMapFile(Path); 4621 break; 4622 } 4623 case INPUT_FILE_OFFSETS: { 4624 if (!NeedsInputFiles) 4625 break; 4626 4627 unsigned NumInputFiles = Record[0]; 4628 unsigned NumUserFiles = Record[1]; 4629 const uint64_t *InputFileOffs = (const uint64_t *)Blob.data(); 4630 for (unsigned I = 0; I != NumInputFiles; ++I) { 4631 // Go find this input file. 4632 bool isSystemFile = I >= NumUserFiles; 4633 4634 if (isSystemFile && !NeedsSystemInputFiles) 4635 break; // the rest are system input files 4636 4637 BitstreamCursor &Cursor = InputFilesCursor; 4638 SavedStreamPosition SavedPosition(Cursor); 4639 Cursor.JumpToBit(InputFileOffs[I]); 4640 4641 unsigned Code = Cursor.ReadCode(); 4642 RecordData Record; 4643 StringRef Blob; 4644 bool shouldContinue = false; 4645 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) { 4646 case INPUT_FILE: 4647 bool Overridden = static_cast<bool>(Record[3]); 4648 std::string Filename = Blob; 4649 ResolveImportedPath(Filename, ModuleDir); 4650 shouldContinue = Listener.visitInputFile( 4651 Filename, isSystemFile, Overridden, /*IsExplicitModule*/false); 4652 break; 4653 } 4654 if (!shouldContinue) 4655 break; 4656 } 4657 break; 4658 } 4659 4660 case IMPORTS: { 4661 if (!NeedsImports) 4662 break; 4663 4664 unsigned Idx = 0, N = Record.size(); 4665 while (Idx < N) { 4666 // Read information about the AST file. 4667 Idx += 5; // ImportLoc, Size, ModTime, Signature 4668 std::string Filename = ReadString(Record, Idx); 4669 ResolveImportedPath(Filename, ModuleDir); 4670 Listener.visitImport(Filename); 4671 } 4672 break; 4673 } 4674 4675 default: 4676 // No other validation to perform. 4677 break; 4678 } 4679 } 4680 4681 // Look for module file extension blocks, if requested. 4682 if (FindModuleFileExtensions) { 4683 BitstreamCursor SavedStream = Stream; 4684 while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) { 4685 bool DoneWithExtensionBlock = false; 4686 while (!DoneWithExtensionBlock) { 4687 llvm::BitstreamEntry Entry = Stream.advance(); 4688 4689 switch (Entry.Kind) { 4690 case llvm::BitstreamEntry::SubBlock: 4691 if (Stream.SkipBlock()) 4692 return true; 4693 4694 continue; 4695 4696 case llvm::BitstreamEntry::EndBlock: 4697 DoneWithExtensionBlock = true; 4698 continue; 4699 4700 case llvm::BitstreamEntry::Error: 4701 return true; 4702 4703 case llvm::BitstreamEntry::Record: 4704 break; 4705 } 4706 4707 Record.clear(); 4708 StringRef Blob; 4709 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob); 4710 switch (RecCode) { 4711 case EXTENSION_METADATA: { 4712 ModuleFileExtensionMetadata Metadata; 4713 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata)) 4714 return true; 4715 4716 Listener.readModuleFileExtension(Metadata); 4717 break; 4718 } 4719 } 4720 } 4721 } 4722 Stream = SavedStream; 4723 } 4724 4725 // Scan for the UNHASHED_CONTROL_BLOCK_ID block. 4726 if (readUnhashedControlBlockImpl( 4727 nullptr, Bytes, ARR_ConfigurationMismatch | ARR_OutOfDate, 4728 /*AllowCompatibleConfigurationMismatch*/ false, &Listener, 4729 ValidateDiagnosticOptions) != Success) 4730 return true; 4731 4732 return false; 4733 } 4734 4735 bool ASTReader::isAcceptableASTFile( 4736 StringRef Filename, FileManager &FileMgr, 4737 const PCHContainerReader &PCHContainerRdr, const LangOptions &LangOpts, 4738 const TargetOptions &TargetOpts, const PreprocessorOptions &PPOpts, 4739 std::string ExistingModuleCachePath) { 4740 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts, 4741 ExistingModuleCachePath, FileMgr); 4742 return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr, 4743 /*FindModuleFileExtensions=*/false, 4744 validator, 4745 /*ValidateDiagnosticOptions=*/true); 4746 } 4747 4748 ASTReader::ASTReadResult 4749 ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) { 4750 // Enter the submodule block. 4751 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) { 4752 Error("malformed submodule block record in AST file"); 4753 return Failure; 4754 } 4755 4756 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap(); 4757 bool First = true; 4758 Module *CurrentModule = nullptr; 4759 RecordData Record; 4760 while (true) { 4761 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks(); 4762 4763 switch (Entry.Kind) { 4764 case llvm::BitstreamEntry::SubBlock: // Handled for us already. 4765 case llvm::BitstreamEntry::Error: 4766 Error("malformed block record in AST file"); 4767 return Failure; 4768 case llvm::BitstreamEntry::EndBlock: 4769 return Success; 4770 case llvm::BitstreamEntry::Record: 4771 // The interesting case. 4772 break; 4773 } 4774 4775 // Read a record. 4776 StringRef Blob; 4777 Record.clear(); 4778 auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob); 4779 4780 if ((Kind == SUBMODULE_METADATA) != First) { 4781 Error("submodule metadata record should be at beginning of block"); 4782 return Failure; 4783 } 4784 First = false; 4785 4786 // Submodule information is only valid if we have a current module. 4787 // FIXME: Should we error on these cases? 4788 if (!CurrentModule && Kind != SUBMODULE_METADATA && 4789 Kind != SUBMODULE_DEFINITION) 4790 continue; 4791 4792 switch (Kind) { 4793 default: // Default behavior: ignore. 4794 break; 4795 4796 case SUBMODULE_DEFINITION: { 4797 if (Record.size() < 8) { 4798 Error("malformed module definition"); 4799 return Failure; 4800 } 4801 4802 StringRef Name = Blob; 4803 unsigned Idx = 0; 4804 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]); 4805 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]); 4806 bool IsFramework = Record[Idx++]; 4807 bool IsExplicit = Record[Idx++]; 4808 bool IsSystem = Record[Idx++]; 4809 bool IsExternC = Record[Idx++]; 4810 bool InferSubmodules = Record[Idx++]; 4811 bool InferExplicitSubmodules = Record[Idx++]; 4812 bool InferExportWildcard = Record[Idx++]; 4813 bool ConfigMacrosExhaustive = Record[Idx++]; 4814 bool WithCodegen = Record[Idx++]; 4815 4816 Module *ParentModule = nullptr; 4817 if (Parent) 4818 ParentModule = getSubmodule(Parent); 4819 4820 // Retrieve this (sub)module from the module map, creating it if 4821 // necessary. 4822 CurrentModule = 4823 ModMap.findOrCreateModule(Name, ParentModule, IsFramework, IsExplicit) 4824 .first; 4825 4826 // FIXME: set the definition loc for CurrentModule, or call 4827 // ModMap.setInferredModuleAllowedBy() 4828 4829 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS; 4830 if (GlobalIndex >= SubmodulesLoaded.size() || 4831 SubmodulesLoaded[GlobalIndex]) { 4832 Error("too many submodules"); 4833 return Failure; 4834 } 4835 4836 if (!ParentModule) { 4837 if (const FileEntry *CurFile = CurrentModule->getASTFile()) { 4838 if (CurFile != F.File) { 4839 if (!Diags.isDiagnosticInFlight()) { 4840 Diag(diag::err_module_file_conflict) 4841 << CurrentModule->getTopLevelModuleName() 4842 << CurFile->getName() 4843 << F.File->getName(); 4844 } 4845 return Failure; 4846 } 4847 } 4848 4849 CurrentModule->setASTFile(F.File); 4850 } 4851 4852 CurrentModule->Signature = F.Signature; 4853 CurrentModule->IsFromModuleFile = true; 4854 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem; 4855 CurrentModule->IsExternC = IsExternC; 4856 CurrentModule->InferSubmodules = InferSubmodules; 4857 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules; 4858 CurrentModule->InferExportWildcard = InferExportWildcard; 4859 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive; 4860 CurrentModule->WithCodegen = WithCodegen; 4861 if (DeserializationListener) 4862 DeserializationListener->ModuleRead(GlobalID, CurrentModule); 4863 4864 SubmodulesLoaded[GlobalIndex] = CurrentModule; 4865 4866 // Clear out data that will be replaced by what is in the module file. 4867 CurrentModule->LinkLibraries.clear(); 4868 CurrentModule->ConfigMacros.clear(); 4869 CurrentModule->UnresolvedConflicts.clear(); 4870 CurrentModule->Conflicts.clear(); 4871 4872 // The module is available unless it's missing a requirement; relevant 4873 // requirements will be (re-)added by SUBMODULE_REQUIRES records. 4874 // Missing headers that were present when the module was built do not 4875 // make it unavailable -- if we got this far, this must be an explicitly 4876 // imported module file. 4877 CurrentModule->Requirements.clear(); 4878 CurrentModule->MissingHeaders.clear(); 4879 CurrentModule->IsMissingRequirement = 4880 ParentModule && ParentModule->IsMissingRequirement; 4881 CurrentModule->IsAvailable = !CurrentModule->IsMissingRequirement; 4882 break; 4883 } 4884 4885 case SUBMODULE_UMBRELLA_HEADER: { 4886 std::string Filename = Blob; 4887 ResolveImportedPath(F, Filename); 4888 if (auto *Umbrella = PP.getFileManager().getFile(Filename)) { 4889 if (!CurrentModule->getUmbrellaHeader()) 4890 ModMap.setUmbrellaHeader(CurrentModule, Umbrella, Blob); 4891 else if (CurrentModule->getUmbrellaHeader().Entry != Umbrella) { 4892 // This can be a spurious difference caused by changing the VFS to 4893 // point to a different copy of the file, and it is too late to 4894 // to rebuild safely. 4895 // FIXME: If we wrote the virtual paths instead of the 'real' paths, 4896 // after input file validation only real problems would remain and we 4897 // could just error. For now, assume it's okay. 4898 break; 4899 } 4900 } 4901 break; 4902 } 4903 4904 case SUBMODULE_HEADER: 4905 case SUBMODULE_EXCLUDED_HEADER: 4906 case SUBMODULE_PRIVATE_HEADER: 4907 // We lazily associate headers with their modules via the HeaderInfo table. 4908 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead 4909 // of complete filenames or remove it entirely. 4910 break; 4911 4912 case SUBMODULE_TEXTUAL_HEADER: 4913 case SUBMODULE_PRIVATE_TEXTUAL_HEADER: 4914 // FIXME: Textual headers are not marked in the HeaderInfo table. Load 4915 // them here. 4916 break; 4917 4918 case SUBMODULE_TOPHEADER: { 4919 CurrentModule->addTopHeaderFilename(Blob); 4920 break; 4921 } 4922 4923 case SUBMODULE_UMBRELLA_DIR: { 4924 std::string Dirname = Blob; 4925 ResolveImportedPath(F, Dirname); 4926 if (auto *Umbrella = PP.getFileManager().getDirectory(Dirname)) { 4927 if (!CurrentModule->getUmbrellaDir()) 4928 ModMap.setUmbrellaDir(CurrentModule, Umbrella, Blob); 4929 else if (CurrentModule->getUmbrellaDir().Entry != Umbrella) { 4930 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) 4931 Error("mismatched umbrella directories in submodule"); 4932 return OutOfDate; 4933 } 4934 } 4935 break; 4936 } 4937 4938 case SUBMODULE_METADATA: { 4939 F.BaseSubmoduleID = getTotalNumSubmodules(); 4940 F.LocalNumSubmodules = Record[0]; 4941 unsigned LocalBaseSubmoduleID = Record[1]; 4942 if (F.LocalNumSubmodules > 0) { 4943 // Introduce the global -> local mapping for submodules within this 4944 // module. 4945 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F)); 4946 4947 // Introduce the local -> global mapping for submodules within this 4948 // module. 4949 F.SubmoduleRemap.insertOrReplace( 4950 std::make_pair(LocalBaseSubmoduleID, 4951 F.BaseSubmoduleID - LocalBaseSubmoduleID)); 4952 4953 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules); 4954 } 4955 break; 4956 } 4957 4958 case SUBMODULE_IMPORTS: { 4959 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) { 4960 UnresolvedModuleRef Unresolved; 4961 Unresolved.File = &F; 4962 Unresolved.Mod = CurrentModule; 4963 Unresolved.ID = Record[Idx]; 4964 Unresolved.Kind = UnresolvedModuleRef::Import; 4965 Unresolved.IsWildcard = false; 4966 UnresolvedModuleRefs.push_back(Unresolved); 4967 } 4968 break; 4969 } 4970 4971 case SUBMODULE_EXPORTS: { 4972 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) { 4973 UnresolvedModuleRef Unresolved; 4974 Unresolved.File = &F; 4975 Unresolved.Mod = CurrentModule; 4976 Unresolved.ID = Record[Idx]; 4977 Unresolved.Kind = UnresolvedModuleRef::Export; 4978 Unresolved.IsWildcard = Record[Idx + 1]; 4979 UnresolvedModuleRefs.push_back(Unresolved); 4980 } 4981 4982 // Once we've loaded the set of exports, there's no reason to keep 4983 // the parsed, unresolved exports around. 4984 CurrentModule->UnresolvedExports.clear(); 4985 break; 4986 } 4987 case SUBMODULE_REQUIRES: { 4988 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(), 4989 Context.getTargetInfo()); 4990 break; 4991 } 4992 4993 case SUBMODULE_LINK_LIBRARY: 4994 CurrentModule->LinkLibraries.push_back( 4995 Module::LinkLibrary(Blob, Record[0])); 4996 break; 4997 4998 case SUBMODULE_CONFIG_MACRO: 4999 CurrentModule->ConfigMacros.push_back(Blob.str()); 5000 break; 5001 5002 case SUBMODULE_CONFLICT: { 5003 UnresolvedModuleRef Unresolved; 5004 Unresolved.File = &F; 5005 Unresolved.Mod = CurrentModule; 5006 Unresolved.ID = Record[0]; 5007 Unresolved.Kind = UnresolvedModuleRef::Conflict; 5008 Unresolved.IsWildcard = false; 5009 Unresolved.String = Blob; 5010 UnresolvedModuleRefs.push_back(Unresolved); 5011 break; 5012 } 5013 5014 case SUBMODULE_INITIALIZERS: 5015 SmallVector<uint32_t, 16> Inits; 5016 for (auto &ID : Record) 5017 Inits.push_back(getGlobalDeclID(F, ID)); 5018 Context.addLazyModuleInitializers(CurrentModule, Inits); 5019 break; 5020 } 5021 } 5022 } 5023 5024 /// \brief Parse the record that corresponds to a LangOptions data 5025 /// structure. 5026 /// 5027 /// This routine parses the language options from the AST file and then gives 5028 /// them to the AST listener if one is set. 5029 /// 5030 /// \returns true if the listener deems the file unacceptable, false otherwise. 5031 bool ASTReader::ParseLanguageOptions(const RecordData &Record, 5032 bool Complain, 5033 ASTReaderListener &Listener, 5034 bool AllowCompatibleDifferences) { 5035 LangOptions LangOpts; 5036 unsigned Idx = 0; 5037 #define LANGOPT(Name, Bits, Default, Description) \ 5038 LangOpts.Name = Record[Idx++]; 5039 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \ 5040 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++])); 5041 #include "clang/Basic/LangOptions.def" 5042 #define SANITIZER(NAME, ID) \ 5043 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]); 5044 #include "clang/Basic/Sanitizers.def" 5045 5046 for (unsigned N = Record[Idx++]; N; --N) 5047 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx)); 5048 5049 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++]; 5050 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx); 5051 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion); 5052 5053 LangOpts.CurrentModule = ReadString(Record, Idx); 5054 5055 // Comment options. 5056 for (unsigned N = Record[Idx++]; N; --N) { 5057 LangOpts.CommentOpts.BlockCommandNames.push_back( 5058 ReadString(Record, Idx)); 5059 } 5060 LangOpts.CommentOpts.ParseAllComments = Record[Idx++]; 5061 5062 // OpenMP offloading options. 5063 for (unsigned N = Record[Idx++]; N; --N) { 5064 LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx))); 5065 } 5066 5067 LangOpts.OMPHostIRFile = ReadString(Record, Idx); 5068 5069 return Listener.ReadLanguageOptions(LangOpts, Complain, 5070 AllowCompatibleDifferences); 5071 } 5072 5073 bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain, 5074 ASTReaderListener &Listener, 5075 bool AllowCompatibleDifferences) { 5076 unsigned Idx = 0; 5077 TargetOptions TargetOpts; 5078 TargetOpts.Triple = ReadString(Record, Idx); 5079 TargetOpts.CPU = ReadString(Record, Idx); 5080 TargetOpts.ABI = ReadString(Record, Idx); 5081 for (unsigned N = Record[Idx++]; N; --N) { 5082 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx)); 5083 } 5084 for (unsigned N = Record[Idx++]; N; --N) { 5085 TargetOpts.Features.push_back(ReadString(Record, Idx)); 5086 } 5087 5088 return Listener.ReadTargetOptions(TargetOpts, Complain, 5089 AllowCompatibleDifferences); 5090 } 5091 5092 bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain, 5093 ASTReaderListener &Listener) { 5094 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions); 5095 unsigned Idx = 0; 5096 #define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++]; 5097 #define ENUM_DIAGOPT(Name, Type, Bits, Default) \ 5098 DiagOpts->set##Name(static_cast<Type>(Record[Idx++])); 5099 #include "clang/Basic/DiagnosticOptions.def" 5100 5101 for (unsigned N = Record[Idx++]; N; --N) 5102 DiagOpts->Warnings.push_back(ReadString(Record, Idx)); 5103 for (unsigned N = Record[Idx++]; N; --N) 5104 DiagOpts->Remarks.push_back(ReadString(Record, Idx)); 5105 5106 return Listener.ReadDiagnosticOptions(DiagOpts, Complain); 5107 } 5108 5109 bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain, 5110 ASTReaderListener &Listener) { 5111 FileSystemOptions FSOpts; 5112 unsigned Idx = 0; 5113 FSOpts.WorkingDir = ReadString(Record, Idx); 5114 return Listener.ReadFileSystemOptions(FSOpts, Complain); 5115 } 5116 5117 bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record, 5118 bool Complain, 5119 ASTReaderListener &Listener) { 5120 HeaderSearchOptions HSOpts; 5121 unsigned Idx = 0; 5122 HSOpts.Sysroot = ReadString(Record, Idx); 5123 5124 // Include entries. 5125 for (unsigned N = Record[Idx++]; N; --N) { 5126 std::string Path = ReadString(Record, Idx); 5127 frontend::IncludeDirGroup Group 5128 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]); 5129 bool IsFramework = Record[Idx++]; 5130 bool IgnoreSysRoot = Record[Idx++]; 5131 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework, 5132 IgnoreSysRoot); 5133 } 5134 5135 // System header prefixes. 5136 for (unsigned N = Record[Idx++]; N; --N) { 5137 std::string Prefix = ReadString(Record, Idx); 5138 bool IsSystemHeader = Record[Idx++]; 5139 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader); 5140 } 5141 5142 HSOpts.ResourceDir = ReadString(Record, Idx); 5143 HSOpts.ModuleCachePath = ReadString(Record, Idx); 5144 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx); 5145 HSOpts.DisableModuleHash = Record[Idx++]; 5146 HSOpts.UseBuiltinIncludes = Record[Idx++]; 5147 HSOpts.UseStandardSystemIncludes = Record[Idx++]; 5148 HSOpts.UseStandardCXXIncludes = Record[Idx++]; 5149 HSOpts.UseLibcxx = Record[Idx++]; 5150 std::string SpecificModuleCachePath = ReadString(Record, Idx); 5151 5152 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath, 5153 Complain); 5154 } 5155 5156 bool ASTReader::ParsePreprocessorOptions(const RecordData &Record, 5157 bool Complain, 5158 ASTReaderListener &Listener, 5159 std::string &SuggestedPredefines) { 5160 PreprocessorOptions PPOpts; 5161 unsigned Idx = 0; 5162 5163 // Macro definitions/undefs 5164 for (unsigned N = Record[Idx++]; N; --N) { 5165 std::string Macro = ReadString(Record, Idx); 5166 bool IsUndef = Record[Idx++]; 5167 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef)); 5168 } 5169 5170 // Includes 5171 for (unsigned N = Record[Idx++]; N; --N) { 5172 PPOpts.Includes.push_back(ReadString(Record, Idx)); 5173 } 5174 5175 // Macro Includes 5176 for (unsigned N = Record[Idx++]; N; --N) { 5177 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx)); 5178 } 5179 5180 PPOpts.UsePredefines = Record[Idx++]; 5181 PPOpts.DetailedRecord = Record[Idx++]; 5182 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx); 5183 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx); 5184 PPOpts.ObjCXXARCStandardLibrary = 5185 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]); 5186 SuggestedPredefines.clear(); 5187 return Listener.ReadPreprocessorOptions(PPOpts, Complain, 5188 SuggestedPredefines); 5189 } 5190 5191 std::pair<ModuleFile *, unsigned> 5192 ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) { 5193 GlobalPreprocessedEntityMapType::iterator 5194 I = GlobalPreprocessedEntityMap.find(GlobalIndex); 5195 assert(I != GlobalPreprocessedEntityMap.end() && 5196 "Corrupted global preprocessed entity map"); 5197 ModuleFile *M = I->second; 5198 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID; 5199 return std::make_pair(M, LocalIndex); 5200 } 5201 5202 llvm::iterator_range<PreprocessingRecord::iterator> 5203 ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const { 5204 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord()) 5205 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID, 5206 Mod.NumPreprocessedEntities); 5207 5208 return llvm::make_range(PreprocessingRecord::iterator(), 5209 PreprocessingRecord::iterator()); 5210 } 5211 5212 llvm::iterator_range<ASTReader::ModuleDeclIterator> 5213 ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) { 5214 return llvm::make_range( 5215 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls), 5216 ModuleDeclIterator(this, &Mod, 5217 Mod.FileSortedDecls + Mod.NumFileSortedDecls)); 5218 } 5219 5220 PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) { 5221 PreprocessedEntityID PPID = Index+1; 5222 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index); 5223 ModuleFile &M = *PPInfo.first; 5224 unsigned LocalIndex = PPInfo.second; 5225 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex]; 5226 5227 if (!PP.getPreprocessingRecord()) { 5228 Error("no preprocessing record"); 5229 return nullptr; 5230 } 5231 5232 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor); 5233 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset); 5234 5235 llvm::BitstreamEntry Entry = 5236 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd); 5237 if (Entry.Kind != llvm::BitstreamEntry::Record) 5238 return nullptr; 5239 5240 // Read the record. 5241 SourceRange Range(TranslateSourceLocation(M, PPOffs.getBegin()), 5242 TranslateSourceLocation(M, PPOffs.getEnd())); 5243 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord(); 5244 StringRef Blob; 5245 RecordData Record; 5246 PreprocessorDetailRecordTypes RecType = 5247 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord( 5248 Entry.ID, Record, &Blob); 5249 switch (RecType) { 5250 case PPD_MACRO_EXPANSION: { 5251 bool isBuiltin = Record[0]; 5252 IdentifierInfo *Name = nullptr; 5253 MacroDefinitionRecord *Def = nullptr; 5254 if (isBuiltin) 5255 Name = getLocalIdentifier(M, Record[1]); 5256 else { 5257 PreprocessedEntityID GlobalID = 5258 getGlobalPreprocessedEntityID(M, Record[1]); 5259 Def = cast<MacroDefinitionRecord>( 5260 PPRec.getLoadedPreprocessedEntity(GlobalID - 1)); 5261 } 5262 5263 MacroExpansion *ME; 5264 if (isBuiltin) 5265 ME = new (PPRec) MacroExpansion(Name, Range); 5266 else 5267 ME = new (PPRec) MacroExpansion(Def, Range); 5268 5269 return ME; 5270 } 5271 5272 case PPD_MACRO_DEFINITION: { 5273 // Decode the identifier info and then check again; if the macro is 5274 // still defined and associated with the identifier, 5275 IdentifierInfo *II = getLocalIdentifier(M, Record[0]); 5276 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range); 5277 5278 if (DeserializationListener) 5279 DeserializationListener->MacroDefinitionRead(PPID, MD); 5280 5281 return MD; 5282 } 5283 5284 case PPD_INCLUSION_DIRECTIVE: { 5285 const char *FullFileNameStart = Blob.data() + Record[0]; 5286 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]); 5287 const FileEntry *File = nullptr; 5288 if (!FullFileName.empty()) 5289 File = PP.getFileManager().getFile(FullFileName); 5290 5291 // FIXME: Stable encoding 5292 InclusionDirective::InclusionKind Kind 5293 = static_cast<InclusionDirective::InclusionKind>(Record[2]); 5294 InclusionDirective *ID 5295 = new (PPRec) InclusionDirective(PPRec, Kind, 5296 StringRef(Blob.data(), Record[0]), 5297 Record[1], Record[3], 5298 File, 5299 Range); 5300 return ID; 5301 } 5302 } 5303 5304 llvm_unreachable("Invalid PreprocessorDetailRecordTypes"); 5305 } 5306 5307 /// \brief \arg SLocMapI points at a chunk of a module that contains no 5308 /// preprocessed entities or the entities it contains are not the ones we are 5309 /// looking for. Find the next module that contains entities and return the ID 5310 /// of the first entry. 5311 PreprocessedEntityID ASTReader::findNextPreprocessedEntity( 5312 GlobalSLocOffsetMapType::const_iterator SLocMapI) const { 5313 ++SLocMapI; 5314 for (GlobalSLocOffsetMapType::const_iterator 5315 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) { 5316 ModuleFile &M = *SLocMapI->second; 5317 if (M.NumPreprocessedEntities) 5318 return M.BasePreprocessedEntityID; 5319 } 5320 5321 return getTotalNumPreprocessedEntities(); 5322 } 5323 5324 namespace { 5325 5326 struct PPEntityComp { 5327 const ASTReader &Reader; 5328 ModuleFile &M; 5329 5330 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { } 5331 5332 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const { 5333 SourceLocation LHS = getLoc(L); 5334 SourceLocation RHS = getLoc(R); 5335 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS); 5336 } 5337 5338 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const { 5339 SourceLocation LHS = getLoc(L); 5340 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS); 5341 } 5342 5343 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const { 5344 SourceLocation RHS = getLoc(R); 5345 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS); 5346 } 5347 5348 SourceLocation getLoc(const PPEntityOffset &PPE) const { 5349 return Reader.TranslateSourceLocation(M, PPE.getBegin()); 5350 } 5351 }; 5352 5353 } // end anonymous namespace 5354 5355 PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc, 5356 bool EndsAfter) const { 5357 if (SourceMgr.isLocalSourceLocation(Loc)) 5358 return getTotalNumPreprocessedEntities(); 5359 5360 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find( 5361 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1); 5362 assert(SLocMapI != GlobalSLocOffsetMap.end() && 5363 "Corrupted global sloc offset map"); 5364 5365 if (SLocMapI->second->NumPreprocessedEntities == 0) 5366 return findNextPreprocessedEntity(SLocMapI); 5367 5368 ModuleFile &M = *SLocMapI->second; 5369 typedef const PPEntityOffset *pp_iterator; 5370 pp_iterator pp_begin = M.PreprocessedEntityOffsets; 5371 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities; 5372 5373 size_t Count = M.NumPreprocessedEntities; 5374 size_t Half; 5375 pp_iterator First = pp_begin; 5376 pp_iterator PPI; 5377 5378 if (EndsAfter) { 5379 PPI = std::upper_bound(pp_begin, pp_end, Loc, 5380 PPEntityComp(*this, M)); 5381 } else { 5382 // Do a binary search manually instead of using std::lower_bound because 5383 // The end locations of entities may be unordered (when a macro expansion 5384 // is inside another macro argument), but for this case it is not important 5385 // whether we get the first macro expansion or its containing macro. 5386 while (Count > 0) { 5387 Half = Count / 2; 5388 PPI = First; 5389 std::advance(PPI, Half); 5390 if (SourceMgr.isBeforeInTranslationUnit( 5391 TranslateSourceLocation(M, PPI->getEnd()), Loc)) { 5392 First = PPI; 5393 ++First; 5394 Count = Count - Half - 1; 5395 } else 5396 Count = Half; 5397 } 5398 } 5399 5400 if (PPI == pp_end) 5401 return findNextPreprocessedEntity(SLocMapI); 5402 5403 return M.BasePreprocessedEntityID + (PPI - pp_begin); 5404 } 5405 5406 /// \brief Returns a pair of [Begin, End) indices of preallocated 5407 /// preprocessed entities that \arg Range encompasses. 5408 std::pair<unsigned, unsigned> 5409 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) { 5410 if (Range.isInvalid()) 5411 return std::make_pair(0,0); 5412 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin())); 5413 5414 PreprocessedEntityID BeginID = 5415 findPreprocessedEntity(Range.getBegin(), false); 5416 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true); 5417 return std::make_pair(BeginID, EndID); 5418 } 5419 5420 /// \brief Optionally returns true or false if the preallocated preprocessed 5421 /// entity with index \arg Index came from file \arg FID. 5422 Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index, 5423 FileID FID) { 5424 if (FID.isInvalid()) 5425 return false; 5426 5427 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index); 5428 ModuleFile &M = *PPInfo.first; 5429 unsigned LocalIndex = PPInfo.second; 5430 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex]; 5431 5432 SourceLocation Loc = TranslateSourceLocation(M, PPOffs.getBegin()); 5433 if (Loc.isInvalid()) 5434 return false; 5435 5436 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID)) 5437 return true; 5438 else 5439 return false; 5440 } 5441 5442 namespace { 5443 5444 /// \brief Visitor used to search for information about a header file. 5445 class HeaderFileInfoVisitor { 5446 const FileEntry *FE; 5447 5448 Optional<HeaderFileInfo> HFI; 5449 5450 public: 5451 explicit HeaderFileInfoVisitor(const FileEntry *FE) 5452 : FE(FE) { } 5453 5454 bool operator()(ModuleFile &M) { 5455 HeaderFileInfoLookupTable *Table 5456 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable); 5457 if (!Table) 5458 return false; 5459 5460 // Look in the on-disk hash table for an entry for this file name. 5461 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE); 5462 if (Pos == Table->end()) 5463 return false; 5464 5465 HFI = *Pos; 5466 return true; 5467 } 5468 5469 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; } 5470 }; 5471 5472 } // end anonymous namespace 5473 5474 HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) { 5475 HeaderFileInfoVisitor Visitor(FE); 5476 ModuleMgr.visit(Visitor); 5477 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo()) 5478 return *HFI; 5479 5480 return HeaderFileInfo(); 5481 } 5482 5483 void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) { 5484 using DiagState = DiagnosticsEngine::DiagState; 5485 SmallVector<DiagState *, 32> DiagStates; 5486 5487 for (ModuleFile &F : ModuleMgr) { 5488 unsigned Idx = 0; 5489 auto &Record = F.PragmaDiagMappings; 5490 if (Record.empty()) 5491 continue; 5492 5493 DiagStates.clear(); 5494 5495 auto ReadDiagState = 5496 [&](const DiagState &BasedOn, SourceLocation Loc, 5497 bool IncludeNonPragmaStates) -> DiagnosticsEngine::DiagState * { 5498 unsigned BackrefID = Record[Idx++]; 5499 if (BackrefID != 0) 5500 return DiagStates[BackrefID - 1]; 5501 5502 // A new DiagState was created here. 5503 Diag.DiagStates.push_back(BasedOn); 5504 DiagState *NewState = &Diag.DiagStates.back(); 5505 DiagStates.push_back(NewState); 5506 unsigned Size = Record[Idx++]; 5507 assert(Idx + Size * 2 <= Record.size() && 5508 "Invalid data, not enough diag/map pairs"); 5509 while (Size--) { 5510 unsigned DiagID = Record[Idx++]; 5511 diag::Severity Map = (diag::Severity)Record[Idx++]; 5512 DiagnosticMapping Mapping = Diag.makeUserMapping(Map, Loc); 5513 if (Mapping.isPragma() || IncludeNonPragmaStates) 5514 NewState->setMapping(DiagID, Mapping); 5515 } 5516 return NewState; 5517 }; 5518 5519 auto *FirstState = ReadDiagState( 5520 F.isModule() ? DiagState() : *Diag.DiagStatesByLoc.CurDiagState, 5521 SourceLocation(), F.isModule()); 5522 SourceLocation CurStateLoc = 5523 ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]); 5524 auto *CurState = ReadDiagState(*FirstState, CurStateLoc, false); 5525 5526 if (!F.isModule()) { 5527 Diag.DiagStatesByLoc.CurDiagState = CurState; 5528 Diag.DiagStatesByLoc.CurDiagStateLoc = CurStateLoc; 5529 5530 // Preserve the property that the imaginary root file describes the 5531 // current state. 5532 auto &T = Diag.DiagStatesByLoc.Files[FileID()].StateTransitions; 5533 if (T.empty()) 5534 T.push_back({CurState, 0}); 5535 else 5536 T[0].State = CurState; 5537 } 5538 5539 while (Idx < Record.size()) { 5540 SourceLocation Loc = ReadSourceLocation(F, Record[Idx++]); 5541 auto IDAndOffset = SourceMgr.getDecomposedLoc(Loc); 5542 assert(IDAndOffset.second == 0 && "not a start location for a FileID"); 5543 unsigned Transitions = Record[Idx++]; 5544 5545 // Note that we don't need to set up Parent/ParentOffset here, because 5546 // we won't be changing the diagnostic state within imported FileIDs 5547 // (other than perhaps appending to the main source file, which has no 5548 // parent). 5549 auto &F = Diag.DiagStatesByLoc.Files[IDAndOffset.first]; 5550 F.StateTransitions.reserve(F.StateTransitions.size() + Transitions); 5551 for (unsigned I = 0; I != Transitions; ++I) { 5552 unsigned Offset = Record[Idx++]; 5553 auto *State = 5554 ReadDiagState(*FirstState, Loc.getLocWithOffset(Offset), false); 5555 F.StateTransitions.push_back({State, Offset}); 5556 } 5557 } 5558 5559 // Don't try to read these mappings again. 5560 Record.clear(); 5561 } 5562 } 5563 5564 /// \brief Get the correct cursor and offset for loading a type. 5565 ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) { 5566 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index); 5567 assert(I != GlobalTypeMap.end() && "Corrupted global type map"); 5568 ModuleFile *M = I->second; 5569 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]); 5570 } 5571 5572 /// \brief Read and return the type with the given index.. 5573 /// 5574 /// The index is the type ID, shifted and minus the number of predefs. This 5575 /// routine actually reads the record corresponding to the type at the given 5576 /// location. It is a helper routine for GetType, which deals with reading type 5577 /// IDs. 5578 QualType ASTReader::readTypeRecord(unsigned Index) { 5579 RecordLocation Loc = TypeCursorForIndex(Index); 5580 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor; 5581 5582 // Keep track of where we are in the stream, then jump back there 5583 // after reading this type. 5584 SavedStreamPosition SavedPosition(DeclsCursor); 5585 5586 ReadingKindTracker ReadingKind(Read_Type, *this); 5587 5588 // Note that we are loading a type record. 5589 Deserializing AType(this); 5590 5591 unsigned Idx = 0; 5592 DeclsCursor.JumpToBit(Loc.Offset); 5593 RecordData Record; 5594 unsigned Code = DeclsCursor.ReadCode(); 5595 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) { 5596 case TYPE_EXT_QUAL: { 5597 if (Record.size() != 2) { 5598 Error("Incorrect encoding of extended qualifier type"); 5599 return QualType(); 5600 } 5601 QualType Base = readType(*Loc.F, Record, Idx); 5602 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]); 5603 return Context.getQualifiedType(Base, Quals); 5604 } 5605 5606 case TYPE_COMPLEX: { 5607 if (Record.size() != 1) { 5608 Error("Incorrect encoding of complex type"); 5609 return QualType(); 5610 } 5611 QualType ElemType = readType(*Loc.F, Record, Idx); 5612 return Context.getComplexType(ElemType); 5613 } 5614 5615 case TYPE_POINTER: { 5616 if (Record.size() != 1) { 5617 Error("Incorrect encoding of pointer type"); 5618 return QualType(); 5619 } 5620 QualType PointeeType = readType(*Loc.F, Record, Idx); 5621 return Context.getPointerType(PointeeType); 5622 } 5623 5624 case TYPE_DECAYED: { 5625 if (Record.size() != 1) { 5626 Error("Incorrect encoding of decayed type"); 5627 return QualType(); 5628 } 5629 QualType OriginalType = readType(*Loc.F, Record, Idx); 5630 QualType DT = Context.getAdjustedParameterType(OriginalType); 5631 if (!isa<DecayedType>(DT)) 5632 Error("Decayed type does not decay"); 5633 return DT; 5634 } 5635 5636 case TYPE_ADJUSTED: { 5637 if (Record.size() != 2) { 5638 Error("Incorrect encoding of adjusted type"); 5639 return QualType(); 5640 } 5641 QualType OriginalTy = readType(*Loc.F, Record, Idx); 5642 QualType AdjustedTy = readType(*Loc.F, Record, Idx); 5643 return Context.getAdjustedType(OriginalTy, AdjustedTy); 5644 } 5645 5646 case TYPE_BLOCK_POINTER: { 5647 if (Record.size() != 1) { 5648 Error("Incorrect encoding of block pointer type"); 5649 return QualType(); 5650 } 5651 QualType PointeeType = readType(*Loc.F, Record, Idx); 5652 return Context.getBlockPointerType(PointeeType); 5653 } 5654 5655 case TYPE_LVALUE_REFERENCE: { 5656 if (Record.size() != 2) { 5657 Error("Incorrect encoding of lvalue reference type"); 5658 return QualType(); 5659 } 5660 QualType PointeeType = readType(*Loc.F, Record, Idx); 5661 return Context.getLValueReferenceType(PointeeType, Record[1]); 5662 } 5663 5664 case TYPE_RVALUE_REFERENCE: { 5665 if (Record.size() != 1) { 5666 Error("Incorrect encoding of rvalue reference type"); 5667 return QualType(); 5668 } 5669 QualType PointeeType = readType(*Loc.F, Record, Idx); 5670 return Context.getRValueReferenceType(PointeeType); 5671 } 5672 5673 case TYPE_MEMBER_POINTER: { 5674 if (Record.size() != 2) { 5675 Error("Incorrect encoding of member pointer type"); 5676 return QualType(); 5677 } 5678 QualType PointeeType = readType(*Loc.F, Record, Idx); 5679 QualType ClassType = readType(*Loc.F, Record, Idx); 5680 if (PointeeType.isNull() || ClassType.isNull()) 5681 return QualType(); 5682 5683 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr()); 5684 } 5685 5686 case TYPE_CONSTANT_ARRAY: { 5687 QualType ElementType = readType(*Loc.F, Record, Idx); 5688 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1]; 5689 unsigned IndexTypeQuals = Record[2]; 5690 unsigned Idx = 3; 5691 llvm::APInt Size = ReadAPInt(Record, Idx); 5692 return Context.getConstantArrayType(ElementType, Size, 5693 ASM, IndexTypeQuals); 5694 } 5695 5696 case TYPE_INCOMPLETE_ARRAY: { 5697 QualType ElementType = readType(*Loc.F, Record, Idx); 5698 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1]; 5699 unsigned IndexTypeQuals = Record[2]; 5700 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals); 5701 } 5702 5703 case TYPE_VARIABLE_ARRAY: { 5704 QualType ElementType = readType(*Loc.F, Record, Idx); 5705 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1]; 5706 unsigned IndexTypeQuals = Record[2]; 5707 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]); 5708 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]); 5709 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F), 5710 ASM, IndexTypeQuals, 5711 SourceRange(LBLoc, RBLoc)); 5712 } 5713 5714 case TYPE_VECTOR: { 5715 if (Record.size() != 3) { 5716 Error("incorrect encoding of vector type in AST file"); 5717 return QualType(); 5718 } 5719 5720 QualType ElementType = readType(*Loc.F, Record, Idx); 5721 unsigned NumElements = Record[1]; 5722 unsigned VecKind = Record[2]; 5723 return Context.getVectorType(ElementType, NumElements, 5724 (VectorType::VectorKind)VecKind); 5725 } 5726 5727 case TYPE_EXT_VECTOR: { 5728 if (Record.size() != 3) { 5729 Error("incorrect encoding of extended vector type in AST file"); 5730 return QualType(); 5731 } 5732 5733 QualType ElementType = readType(*Loc.F, Record, Idx); 5734 unsigned NumElements = Record[1]; 5735 return Context.getExtVectorType(ElementType, NumElements); 5736 } 5737 5738 case TYPE_FUNCTION_NO_PROTO: { 5739 if (Record.size() != 6) { 5740 Error("incorrect encoding of no-proto function type"); 5741 return QualType(); 5742 } 5743 QualType ResultType = readType(*Loc.F, Record, Idx); 5744 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3], 5745 (CallingConv)Record[4], Record[5]); 5746 return Context.getFunctionNoProtoType(ResultType, Info); 5747 } 5748 5749 case TYPE_FUNCTION_PROTO: { 5750 QualType ResultType = readType(*Loc.F, Record, Idx); 5751 5752 FunctionProtoType::ExtProtoInfo EPI; 5753 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1], 5754 /*hasregparm*/ Record[2], 5755 /*regparm*/ Record[3], 5756 static_cast<CallingConv>(Record[4]), 5757 /*produces*/ Record[5]); 5758 5759 unsigned Idx = 6; 5760 5761 EPI.Variadic = Record[Idx++]; 5762 EPI.HasTrailingReturn = Record[Idx++]; 5763 EPI.TypeQuals = Record[Idx++]; 5764 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]); 5765 SmallVector<QualType, 8> ExceptionStorage; 5766 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx); 5767 5768 unsigned NumParams = Record[Idx++]; 5769 SmallVector<QualType, 16> ParamTypes; 5770 for (unsigned I = 0; I != NumParams; ++I) 5771 ParamTypes.push_back(readType(*Loc.F, Record, Idx)); 5772 5773 SmallVector<FunctionProtoType::ExtParameterInfo, 4> ExtParameterInfos; 5774 if (Idx != Record.size()) { 5775 for (unsigned I = 0; I != NumParams; ++I) 5776 ExtParameterInfos.push_back( 5777 FunctionProtoType::ExtParameterInfo 5778 ::getFromOpaqueValue(Record[Idx++])); 5779 EPI.ExtParameterInfos = ExtParameterInfos.data(); 5780 } 5781 5782 assert(Idx == Record.size()); 5783 5784 return Context.getFunctionType(ResultType, ParamTypes, EPI); 5785 } 5786 5787 case TYPE_UNRESOLVED_USING: { 5788 unsigned Idx = 0; 5789 return Context.getTypeDeclType( 5790 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx)); 5791 } 5792 5793 case TYPE_TYPEDEF: { 5794 if (Record.size() != 2) { 5795 Error("incorrect encoding of typedef type"); 5796 return QualType(); 5797 } 5798 unsigned Idx = 0; 5799 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx); 5800 QualType Canonical = readType(*Loc.F, Record, Idx); 5801 if (!Canonical.isNull()) 5802 Canonical = Context.getCanonicalType(Canonical); 5803 return Context.getTypedefType(Decl, Canonical); 5804 } 5805 5806 case TYPE_TYPEOF_EXPR: 5807 return Context.getTypeOfExprType(ReadExpr(*Loc.F)); 5808 5809 case TYPE_TYPEOF: { 5810 if (Record.size() != 1) { 5811 Error("incorrect encoding of typeof(type) in AST file"); 5812 return QualType(); 5813 } 5814 QualType UnderlyingType = readType(*Loc.F, Record, Idx); 5815 return Context.getTypeOfType(UnderlyingType); 5816 } 5817 5818 case TYPE_DECLTYPE: { 5819 QualType UnderlyingType = readType(*Loc.F, Record, Idx); 5820 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType); 5821 } 5822 5823 case TYPE_UNARY_TRANSFORM: { 5824 QualType BaseType = readType(*Loc.F, Record, Idx); 5825 QualType UnderlyingType = readType(*Loc.F, Record, Idx); 5826 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2]; 5827 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind); 5828 } 5829 5830 case TYPE_AUTO: { 5831 QualType Deduced = readType(*Loc.F, Record, Idx); 5832 AutoTypeKeyword Keyword = (AutoTypeKeyword)Record[Idx++]; 5833 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false; 5834 return Context.getAutoType(Deduced, Keyword, IsDependent); 5835 } 5836 5837 case TYPE_DEDUCED_TEMPLATE_SPECIALIZATION: { 5838 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx); 5839 QualType Deduced = readType(*Loc.F, Record, Idx); 5840 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false; 5841 return Context.getDeducedTemplateSpecializationType(Name, Deduced, 5842 IsDependent); 5843 } 5844 5845 case TYPE_RECORD: { 5846 if (Record.size() != 2) { 5847 Error("incorrect encoding of record type"); 5848 return QualType(); 5849 } 5850 unsigned Idx = 0; 5851 bool IsDependent = Record[Idx++]; 5852 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx); 5853 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl()); 5854 QualType T = Context.getRecordType(RD); 5855 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent); 5856 return T; 5857 } 5858 5859 case TYPE_ENUM: { 5860 if (Record.size() != 2) { 5861 Error("incorrect encoding of enum type"); 5862 return QualType(); 5863 } 5864 unsigned Idx = 0; 5865 bool IsDependent = Record[Idx++]; 5866 QualType T 5867 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx)); 5868 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent); 5869 return T; 5870 } 5871 5872 case TYPE_ATTRIBUTED: { 5873 if (Record.size() != 3) { 5874 Error("incorrect encoding of attributed type"); 5875 return QualType(); 5876 } 5877 QualType modifiedType = readType(*Loc.F, Record, Idx); 5878 QualType equivalentType = readType(*Loc.F, Record, Idx); 5879 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]); 5880 return Context.getAttributedType(kind, modifiedType, equivalentType); 5881 } 5882 5883 case TYPE_PAREN: { 5884 if (Record.size() != 1) { 5885 Error("incorrect encoding of paren type"); 5886 return QualType(); 5887 } 5888 QualType InnerType = readType(*Loc.F, Record, Idx); 5889 return Context.getParenType(InnerType); 5890 } 5891 5892 case TYPE_PACK_EXPANSION: { 5893 if (Record.size() != 2) { 5894 Error("incorrect encoding of pack expansion type"); 5895 return QualType(); 5896 } 5897 QualType Pattern = readType(*Loc.F, Record, Idx); 5898 if (Pattern.isNull()) 5899 return QualType(); 5900 Optional<unsigned> NumExpansions; 5901 if (Record[1]) 5902 NumExpansions = Record[1] - 1; 5903 return Context.getPackExpansionType(Pattern, NumExpansions); 5904 } 5905 5906 case TYPE_ELABORATED: { 5907 unsigned Idx = 0; 5908 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++]; 5909 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx); 5910 QualType NamedType = readType(*Loc.F, Record, Idx); 5911 return Context.getElaboratedType(Keyword, NNS, NamedType); 5912 } 5913 5914 case TYPE_OBJC_INTERFACE: { 5915 unsigned Idx = 0; 5916 ObjCInterfaceDecl *ItfD 5917 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx); 5918 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl()); 5919 } 5920 5921 case TYPE_OBJC_TYPE_PARAM: { 5922 unsigned Idx = 0; 5923 ObjCTypeParamDecl *Decl 5924 = ReadDeclAs<ObjCTypeParamDecl>(*Loc.F, Record, Idx); 5925 unsigned NumProtos = Record[Idx++]; 5926 SmallVector<ObjCProtocolDecl*, 4> Protos; 5927 for (unsigned I = 0; I != NumProtos; ++I) 5928 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx)); 5929 return Context.getObjCTypeParamType(Decl, Protos); 5930 } 5931 case TYPE_OBJC_OBJECT: { 5932 unsigned Idx = 0; 5933 QualType Base = readType(*Loc.F, Record, Idx); 5934 unsigned NumTypeArgs = Record[Idx++]; 5935 SmallVector<QualType, 4> TypeArgs; 5936 for (unsigned I = 0; I != NumTypeArgs; ++I) 5937 TypeArgs.push_back(readType(*Loc.F, Record, Idx)); 5938 unsigned NumProtos = Record[Idx++]; 5939 SmallVector<ObjCProtocolDecl*, 4> Protos; 5940 for (unsigned I = 0; I != NumProtos; ++I) 5941 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx)); 5942 bool IsKindOf = Record[Idx++]; 5943 return Context.getObjCObjectType(Base, TypeArgs, Protos, IsKindOf); 5944 } 5945 5946 case TYPE_OBJC_OBJECT_POINTER: { 5947 unsigned Idx = 0; 5948 QualType Pointee = readType(*Loc.F, Record, Idx); 5949 return Context.getObjCObjectPointerType(Pointee); 5950 } 5951 5952 case TYPE_SUBST_TEMPLATE_TYPE_PARM: { 5953 unsigned Idx = 0; 5954 QualType Parm = readType(*Loc.F, Record, Idx); 5955 QualType Replacement = readType(*Loc.F, Record, Idx); 5956 return Context.getSubstTemplateTypeParmType( 5957 cast<TemplateTypeParmType>(Parm), 5958 Context.getCanonicalType(Replacement)); 5959 } 5960 5961 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: { 5962 unsigned Idx = 0; 5963 QualType Parm = readType(*Loc.F, Record, Idx); 5964 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx); 5965 return Context.getSubstTemplateTypeParmPackType( 5966 cast<TemplateTypeParmType>(Parm), 5967 ArgPack); 5968 } 5969 5970 case TYPE_INJECTED_CLASS_NAME: { 5971 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx); 5972 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable 5973 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable 5974 // for AST reading, too much interdependencies. 5975 const Type *T = nullptr; 5976 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) { 5977 if (const Type *Existing = DI->getTypeForDecl()) { 5978 T = Existing; 5979 break; 5980 } 5981 } 5982 if (!T) { 5983 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST); 5984 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) 5985 DI->setTypeForDecl(T); 5986 } 5987 return QualType(T, 0); 5988 } 5989 5990 case TYPE_TEMPLATE_TYPE_PARM: { 5991 unsigned Idx = 0; 5992 unsigned Depth = Record[Idx++]; 5993 unsigned Index = Record[Idx++]; 5994 bool Pack = Record[Idx++]; 5995 TemplateTypeParmDecl *D 5996 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx); 5997 return Context.getTemplateTypeParmType(Depth, Index, Pack, D); 5998 } 5999 6000 case TYPE_DEPENDENT_NAME: { 6001 unsigned Idx = 0; 6002 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++]; 6003 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx); 6004 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx); 6005 QualType Canon = readType(*Loc.F, Record, Idx); 6006 if (!Canon.isNull()) 6007 Canon = Context.getCanonicalType(Canon); 6008 return Context.getDependentNameType(Keyword, NNS, Name, Canon); 6009 } 6010 6011 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: { 6012 unsigned Idx = 0; 6013 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++]; 6014 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx); 6015 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx); 6016 unsigned NumArgs = Record[Idx++]; 6017 SmallVector<TemplateArgument, 8> Args; 6018 Args.reserve(NumArgs); 6019 while (NumArgs--) 6020 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx)); 6021 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name, 6022 Args); 6023 } 6024 6025 case TYPE_DEPENDENT_SIZED_ARRAY: { 6026 unsigned Idx = 0; 6027 6028 // ArrayType 6029 QualType ElementType = readType(*Loc.F, Record, Idx); 6030 ArrayType::ArraySizeModifier ASM 6031 = (ArrayType::ArraySizeModifier)Record[Idx++]; 6032 unsigned IndexTypeQuals = Record[Idx++]; 6033 6034 // DependentSizedArrayType 6035 Expr *NumElts = ReadExpr(*Loc.F); 6036 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx); 6037 6038 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM, 6039 IndexTypeQuals, Brackets); 6040 } 6041 6042 case TYPE_TEMPLATE_SPECIALIZATION: { 6043 unsigned Idx = 0; 6044 bool IsDependent = Record[Idx++]; 6045 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx); 6046 SmallVector<TemplateArgument, 8> Args; 6047 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx); 6048 QualType Underlying = readType(*Loc.F, Record, Idx); 6049 QualType T; 6050 if (Underlying.isNull()) 6051 T = Context.getCanonicalTemplateSpecializationType(Name, Args); 6052 else 6053 T = Context.getTemplateSpecializationType(Name, Args, Underlying); 6054 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent); 6055 return T; 6056 } 6057 6058 case TYPE_ATOMIC: { 6059 if (Record.size() != 1) { 6060 Error("Incorrect encoding of atomic type"); 6061 return QualType(); 6062 } 6063 QualType ValueType = readType(*Loc.F, Record, Idx); 6064 return Context.getAtomicType(ValueType); 6065 } 6066 6067 case TYPE_PIPE: { 6068 if (Record.size() != 2) { 6069 Error("Incorrect encoding of pipe type"); 6070 return QualType(); 6071 } 6072 6073 // Reading the pipe element type. 6074 QualType ElementType = readType(*Loc.F, Record, Idx); 6075 unsigned ReadOnly = Record[1]; 6076 return Context.getPipeType(ElementType, ReadOnly); 6077 } 6078 6079 } 6080 llvm_unreachable("Invalid TypeCode!"); 6081 } 6082 6083 void ASTReader::readExceptionSpec(ModuleFile &ModuleFile, 6084 SmallVectorImpl<QualType> &Exceptions, 6085 FunctionProtoType::ExceptionSpecInfo &ESI, 6086 const RecordData &Record, unsigned &Idx) { 6087 ExceptionSpecificationType EST = 6088 static_cast<ExceptionSpecificationType>(Record[Idx++]); 6089 ESI.Type = EST; 6090 if (EST == EST_Dynamic) { 6091 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I) 6092 Exceptions.push_back(readType(ModuleFile, Record, Idx)); 6093 ESI.Exceptions = Exceptions; 6094 } else if (EST == EST_ComputedNoexcept) { 6095 ESI.NoexceptExpr = ReadExpr(ModuleFile); 6096 } else if (EST == EST_Uninstantiated) { 6097 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx); 6098 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx); 6099 } else if (EST == EST_Unevaluated) { 6100 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx); 6101 } 6102 } 6103 6104 class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> { 6105 ModuleFile *F; 6106 ASTReader *Reader; 6107 const ASTReader::RecordData &Record; 6108 unsigned &Idx; 6109 6110 SourceLocation ReadSourceLocation() { 6111 return Reader->ReadSourceLocation(*F, Record, Idx); 6112 } 6113 6114 TypeSourceInfo *GetTypeSourceInfo() { 6115 return Reader->GetTypeSourceInfo(*F, Record, Idx); 6116 } 6117 6118 NestedNameSpecifierLoc ReadNestedNameSpecifierLoc() { 6119 return Reader->ReadNestedNameSpecifierLoc(*F, Record, Idx); 6120 } 6121 6122 public: 6123 TypeLocReader(ModuleFile &F, ASTReader &Reader, 6124 const ASTReader::RecordData &Record, unsigned &Idx) 6125 : F(&F), Reader(&Reader), Record(Record), Idx(Idx) {} 6126 6127 // We want compile-time assurance that we've enumerated all of 6128 // these, so unfortunately we have to declare them first, then 6129 // define them out-of-line. 6130 #define ABSTRACT_TYPELOC(CLASS, PARENT) 6131 #define TYPELOC(CLASS, PARENT) \ 6132 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc); 6133 #include "clang/AST/TypeLocNodes.def" 6134 6135 void VisitFunctionTypeLoc(FunctionTypeLoc); 6136 void VisitArrayTypeLoc(ArrayTypeLoc); 6137 }; 6138 6139 void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { 6140 // nothing to do 6141 } 6142 6143 void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) { 6144 TL.setBuiltinLoc(ReadSourceLocation()); 6145 if (TL.needsExtraLocalData()) { 6146 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++])); 6147 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++])); 6148 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++])); 6149 TL.setModeAttr(Record[Idx++]); 6150 } 6151 } 6152 6153 void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) { 6154 TL.setNameLoc(ReadSourceLocation()); 6155 } 6156 6157 void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) { 6158 TL.setStarLoc(ReadSourceLocation()); 6159 } 6160 6161 void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) { 6162 // nothing to do 6163 } 6164 6165 void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) { 6166 // nothing to do 6167 } 6168 6169 void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) { 6170 TL.setCaretLoc(ReadSourceLocation()); 6171 } 6172 6173 void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) { 6174 TL.setAmpLoc(ReadSourceLocation()); 6175 } 6176 6177 void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) { 6178 TL.setAmpAmpLoc(ReadSourceLocation()); 6179 } 6180 6181 void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) { 6182 TL.setStarLoc(ReadSourceLocation()); 6183 TL.setClassTInfo(GetTypeSourceInfo()); 6184 } 6185 6186 void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) { 6187 TL.setLBracketLoc(ReadSourceLocation()); 6188 TL.setRBracketLoc(ReadSourceLocation()); 6189 if (Record[Idx++]) 6190 TL.setSizeExpr(Reader->ReadExpr(*F)); 6191 else 6192 TL.setSizeExpr(nullptr); 6193 } 6194 6195 void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) { 6196 VisitArrayTypeLoc(TL); 6197 } 6198 6199 void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) { 6200 VisitArrayTypeLoc(TL); 6201 } 6202 6203 void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) { 6204 VisitArrayTypeLoc(TL); 6205 } 6206 6207 void TypeLocReader::VisitDependentSizedArrayTypeLoc( 6208 DependentSizedArrayTypeLoc TL) { 6209 VisitArrayTypeLoc(TL); 6210 } 6211 6212 void TypeLocReader::VisitDependentSizedExtVectorTypeLoc( 6213 DependentSizedExtVectorTypeLoc TL) { 6214 TL.setNameLoc(ReadSourceLocation()); 6215 } 6216 6217 void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) { 6218 TL.setNameLoc(ReadSourceLocation()); 6219 } 6220 6221 void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) { 6222 TL.setNameLoc(ReadSourceLocation()); 6223 } 6224 6225 void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) { 6226 TL.setLocalRangeBegin(ReadSourceLocation()); 6227 TL.setLParenLoc(ReadSourceLocation()); 6228 TL.setRParenLoc(ReadSourceLocation()); 6229 TL.setExceptionSpecRange(SourceRange(Reader->ReadSourceLocation(*F, Record, Idx), 6230 Reader->ReadSourceLocation(*F, Record, Idx))); 6231 TL.setLocalRangeEnd(ReadSourceLocation()); 6232 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) { 6233 TL.setParam(i, Reader->ReadDeclAs<ParmVarDecl>(*F, Record, Idx)); 6234 } 6235 } 6236 6237 void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) { 6238 VisitFunctionTypeLoc(TL); 6239 } 6240 6241 void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) { 6242 VisitFunctionTypeLoc(TL); 6243 } 6244 void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) { 6245 TL.setNameLoc(ReadSourceLocation()); 6246 } 6247 void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) { 6248 TL.setNameLoc(ReadSourceLocation()); 6249 } 6250 void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) { 6251 TL.setTypeofLoc(ReadSourceLocation()); 6252 TL.setLParenLoc(ReadSourceLocation()); 6253 TL.setRParenLoc(ReadSourceLocation()); 6254 } 6255 void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) { 6256 TL.setTypeofLoc(ReadSourceLocation()); 6257 TL.setLParenLoc(ReadSourceLocation()); 6258 TL.setRParenLoc(ReadSourceLocation()); 6259 TL.setUnderlyingTInfo(GetTypeSourceInfo()); 6260 } 6261 void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) { 6262 TL.setNameLoc(ReadSourceLocation()); 6263 } 6264 6265 void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) { 6266 TL.setKWLoc(ReadSourceLocation()); 6267 TL.setLParenLoc(ReadSourceLocation()); 6268 TL.setRParenLoc(ReadSourceLocation()); 6269 TL.setUnderlyingTInfo(GetTypeSourceInfo()); 6270 } 6271 6272 void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) { 6273 TL.setNameLoc(ReadSourceLocation()); 6274 } 6275 6276 void TypeLocReader::VisitDeducedTemplateSpecializationTypeLoc( 6277 DeducedTemplateSpecializationTypeLoc TL) { 6278 TL.setTemplateNameLoc(ReadSourceLocation()); 6279 } 6280 6281 void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) { 6282 TL.setNameLoc(ReadSourceLocation()); 6283 } 6284 6285 void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) { 6286 TL.setNameLoc(ReadSourceLocation()); 6287 } 6288 6289 void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) { 6290 TL.setAttrNameLoc(ReadSourceLocation()); 6291 if (TL.hasAttrOperand()) { 6292 SourceRange range; 6293 range.setBegin(ReadSourceLocation()); 6294 range.setEnd(ReadSourceLocation()); 6295 TL.setAttrOperandParensRange(range); 6296 } 6297 if (TL.hasAttrExprOperand()) { 6298 if (Record[Idx++]) 6299 TL.setAttrExprOperand(Reader->ReadExpr(*F)); 6300 else 6301 TL.setAttrExprOperand(nullptr); 6302 } else if (TL.hasAttrEnumOperand()) 6303 TL.setAttrEnumOperandLoc(ReadSourceLocation()); 6304 } 6305 6306 void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) { 6307 TL.setNameLoc(ReadSourceLocation()); 6308 } 6309 6310 void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc( 6311 SubstTemplateTypeParmTypeLoc TL) { 6312 TL.setNameLoc(ReadSourceLocation()); 6313 } 6314 void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc( 6315 SubstTemplateTypeParmPackTypeLoc TL) { 6316 TL.setNameLoc(ReadSourceLocation()); 6317 } 6318 void TypeLocReader::VisitTemplateSpecializationTypeLoc( 6319 TemplateSpecializationTypeLoc TL) { 6320 TL.setTemplateKeywordLoc(ReadSourceLocation()); 6321 TL.setTemplateNameLoc(ReadSourceLocation()); 6322 TL.setLAngleLoc(ReadSourceLocation()); 6323 TL.setRAngleLoc(ReadSourceLocation()); 6324 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) 6325 TL.setArgLocInfo( 6326 i, 6327 Reader->GetTemplateArgumentLocInfo( 6328 *F, TL.getTypePtr()->getArg(i).getKind(), Record, Idx)); 6329 } 6330 void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) { 6331 TL.setLParenLoc(ReadSourceLocation()); 6332 TL.setRParenLoc(ReadSourceLocation()); 6333 } 6334 6335 void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) { 6336 TL.setElaboratedKeywordLoc(ReadSourceLocation()); 6337 TL.setQualifierLoc(ReadNestedNameSpecifierLoc()); 6338 } 6339 6340 void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) { 6341 TL.setNameLoc(ReadSourceLocation()); 6342 } 6343 6344 void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) { 6345 TL.setElaboratedKeywordLoc(ReadSourceLocation()); 6346 TL.setQualifierLoc(ReadNestedNameSpecifierLoc()); 6347 TL.setNameLoc(ReadSourceLocation()); 6348 } 6349 6350 void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc( 6351 DependentTemplateSpecializationTypeLoc TL) { 6352 TL.setElaboratedKeywordLoc(ReadSourceLocation()); 6353 TL.setQualifierLoc(ReadNestedNameSpecifierLoc()); 6354 TL.setTemplateKeywordLoc(ReadSourceLocation()); 6355 TL.setTemplateNameLoc(ReadSourceLocation()); 6356 TL.setLAngleLoc(ReadSourceLocation()); 6357 TL.setRAngleLoc(ReadSourceLocation()); 6358 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) 6359 TL.setArgLocInfo( 6360 I, 6361 Reader->GetTemplateArgumentLocInfo( 6362 *F, TL.getTypePtr()->getArg(I).getKind(), Record, Idx)); 6363 } 6364 6365 void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) { 6366 TL.setEllipsisLoc(ReadSourceLocation()); 6367 } 6368 6369 void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) { 6370 TL.setNameLoc(ReadSourceLocation()); 6371 } 6372 6373 void TypeLocReader::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) { 6374 if (TL.getNumProtocols()) { 6375 TL.setProtocolLAngleLoc(ReadSourceLocation()); 6376 TL.setProtocolRAngleLoc(ReadSourceLocation()); 6377 } 6378 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i) 6379 TL.setProtocolLoc(i, ReadSourceLocation()); 6380 } 6381 6382 void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) { 6383 TL.setHasBaseTypeAsWritten(Record[Idx++]); 6384 TL.setTypeArgsLAngleLoc(ReadSourceLocation()); 6385 TL.setTypeArgsRAngleLoc(ReadSourceLocation()); 6386 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i) 6387 TL.setTypeArgTInfo(i, GetTypeSourceInfo()); 6388 TL.setProtocolLAngleLoc(ReadSourceLocation()); 6389 TL.setProtocolRAngleLoc(ReadSourceLocation()); 6390 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i) 6391 TL.setProtocolLoc(i, ReadSourceLocation()); 6392 } 6393 6394 void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { 6395 TL.setStarLoc(ReadSourceLocation()); 6396 } 6397 6398 void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) { 6399 TL.setKWLoc(ReadSourceLocation()); 6400 TL.setLParenLoc(ReadSourceLocation()); 6401 TL.setRParenLoc(ReadSourceLocation()); 6402 } 6403 6404 void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) { 6405 TL.setKWLoc(ReadSourceLocation()); 6406 } 6407 6408 TypeSourceInfo * 6409 ASTReader::GetTypeSourceInfo(ModuleFile &F, const ASTReader::RecordData &Record, 6410 unsigned &Idx) { 6411 QualType InfoTy = readType(F, Record, Idx); 6412 if (InfoTy.isNull()) 6413 return nullptr; 6414 6415 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy); 6416 TypeLocReader TLR(F, *this, Record, Idx); 6417 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc()) 6418 TLR.Visit(TL); 6419 return TInfo; 6420 } 6421 6422 QualType ASTReader::GetType(TypeID ID) { 6423 unsigned FastQuals = ID & Qualifiers::FastMask; 6424 unsigned Index = ID >> Qualifiers::FastWidth; 6425 6426 if (Index < NUM_PREDEF_TYPE_IDS) { 6427 QualType T; 6428 switch ((PredefinedTypeIDs)Index) { 6429 case PREDEF_TYPE_NULL_ID: 6430 return QualType(); 6431 case PREDEF_TYPE_VOID_ID: 6432 T = Context.VoidTy; 6433 break; 6434 case PREDEF_TYPE_BOOL_ID: 6435 T = Context.BoolTy; 6436 break; 6437 6438 case PREDEF_TYPE_CHAR_U_ID: 6439 case PREDEF_TYPE_CHAR_S_ID: 6440 // FIXME: Check that the signedness of CharTy is correct! 6441 T = Context.CharTy; 6442 break; 6443 6444 case PREDEF_TYPE_UCHAR_ID: 6445 T = Context.UnsignedCharTy; 6446 break; 6447 case PREDEF_TYPE_USHORT_ID: 6448 T = Context.UnsignedShortTy; 6449 break; 6450 case PREDEF_TYPE_UINT_ID: 6451 T = Context.UnsignedIntTy; 6452 break; 6453 case PREDEF_TYPE_ULONG_ID: 6454 T = Context.UnsignedLongTy; 6455 break; 6456 case PREDEF_TYPE_ULONGLONG_ID: 6457 T = Context.UnsignedLongLongTy; 6458 break; 6459 case PREDEF_TYPE_UINT128_ID: 6460 T = Context.UnsignedInt128Ty; 6461 break; 6462 case PREDEF_TYPE_SCHAR_ID: 6463 T = Context.SignedCharTy; 6464 break; 6465 case PREDEF_TYPE_WCHAR_ID: 6466 T = Context.WCharTy; 6467 break; 6468 case PREDEF_TYPE_SHORT_ID: 6469 T = Context.ShortTy; 6470 break; 6471 case PREDEF_TYPE_INT_ID: 6472 T = Context.IntTy; 6473 break; 6474 case PREDEF_TYPE_LONG_ID: 6475 T = Context.LongTy; 6476 break; 6477 case PREDEF_TYPE_LONGLONG_ID: 6478 T = Context.LongLongTy; 6479 break; 6480 case PREDEF_TYPE_INT128_ID: 6481 T = Context.Int128Ty; 6482 break; 6483 case PREDEF_TYPE_HALF_ID: 6484 T = Context.HalfTy; 6485 break; 6486 case PREDEF_TYPE_FLOAT_ID: 6487 T = Context.FloatTy; 6488 break; 6489 case PREDEF_TYPE_DOUBLE_ID: 6490 T = Context.DoubleTy; 6491 break; 6492 case PREDEF_TYPE_LONGDOUBLE_ID: 6493 T = Context.LongDoubleTy; 6494 break; 6495 case PREDEF_TYPE_FLOAT128_ID: 6496 T = Context.Float128Ty; 6497 break; 6498 case PREDEF_TYPE_OVERLOAD_ID: 6499 T = Context.OverloadTy; 6500 break; 6501 case PREDEF_TYPE_BOUND_MEMBER: 6502 T = Context.BoundMemberTy; 6503 break; 6504 case PREDEF_TYPE_PSEUDO_OBJECT: 6505 T = Context.PseudoObjectTy; 6506 break; 6507 case PREDEF_TYPE_DEPENDENT_ID: 6508 T = Context.DependentTy; 6509 break; 6510 case PREDEF_TYPE_UNKNOWN_ANY: 6511 T = Context.UnknownAnyTy; 6512 break; 6513 case PREDEF_TYPE_NULLPTR_ID: 6514 T = Context.NullPtrTy; 6515 break; 6516 case PREDEF_TYPE_CHAR16_ID: 6517 T = Context.Char16Ty; 6518 break; 6519 case PREDEF_TYPE_CHAR32_ID: 6520 T = Context.Char32Ty; 6521 break; 6522 case PREDEF_TYPE_OBJC_ID: 6523 T = Context.ObjCBuiltinIdTy; 6524 break; 6525 case PREDEF_TYPE_OBJC_CLASS: 6526 T = Context.ObjCBuiltinClassTy; 6527 break; 6528 case PREDEF_TYPE_OBJC_SEL: 6529 T = Context.ObjCBuiltinSelTy; 6530 break; 6531 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 6532 case PREDEF_TYPE_##Id##_ID: \ 6533 T = Context.SingletonId; \ 6534 break; 6535 #include "clang/Basic/OpenCLImageTypes.def" 6536 case PREDEF_TYPE_SAMPLER_ID: 6537 T = Context.OCLSamplerTy; 6538 break; 6539 case PREDEF_TYPE_EVENT_ID: 6540 T = Context.OCLEventTy; 6541 break; 6542 case PREDEF_TYPE_CLK_EVENT_ID: 6543 T = Context.OCLClkEventTy; 6544 break; 6545 case PREDEF_TYPE_QUEUE_ID: 6546 T = Context.OCLQueueTy; 6547 break; 6548 case PREDEF_TYPE_RESERVE_ID_ID: 6549 T = Context.OCLReserveIDTy; 6550 break; 6551 case PREDEF_TYPE_AUTO_DEDUCT: 6552 T = Context.getAutoDeductType(); 6553 break; 6554 6555 case PREDEF_TYPE_AUTO_RREF_DEDUCT: 6556 T = Context.getAutoRRefDeductType(); 6557 break; 6558 6559 case PREDEF_TYPE_ARC_UNBRIDGED_CAST: 6560 T = Context.ARCUnbridgedCastTy; 6561 break; 6562 6563 case PREDEF_TYPE_BUILTIN_FN: 6564 T = Context.BuiltinFnTy; 6565 break; 6566 6567 case PREDEF_TYPE_OMP_ARRAY_SECTION: 6568 T = Context.OMPArraySectionTy; 6569 break; 6570 } 6571 6572 assert(!T.isNull() && "Unknown predefined type"); 6573 return T.withFastQualifiers(FastQuals); 6574 } 6575 6576 Index -= NUM_PREDEF_TYPE_IDS; 6577 assert(Index < TypesLoaded.size() && "Type index out-of-range"); 6578 if (TypesLoaded[Index].isNull()) { 6579 TypesLoaded[Index] = readTypeRecord(Index); 6580 if (TypesLoaded[Index].isNull()) 6581 return QualType(); 6582 6583 TypesLoaded[Index]->setFromAST(); 6584 if (DeserializationListener) 6585 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID), 6586 TypesLoaded[Index]); 6587 } 6588 6589 return TypesLoaded[Index].withFastQualifiers(FastQuals); 6590 } 6591 6592 QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) { 6593 return GetType(getGlobalTypeID(F, LocalID)); 6594 } 6595 6596 serialization::TypeID 6597 ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const { 6598 unsigned FastQuals = LocalID & Qualifiers::FastMask; 6599 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth; 6600 6601 if (LocalIndex < NUM_PREDEF_TYPE_IDS) 6602 return LocalID; 6603 6604 if (!F.ModuleOffsetMap.empty()) 6605 ReadModuleOffsetMap(F); 6606 6607 ContinuousRangeMap<uint32_t, int, 2>::iterator I 6608 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS); 6609 assert(I != F.TypeRemap.end() && "Invalid index into type index remap"); 6610 6611 unsigned GlobalIndex = LocalIndex + I->second; 6612 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals; 6613 } 6614 6615 TemplateArgumentLocInfo 6616 ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F, 6617 TemplateArgument::ArgKind Kind, 6618 const RecordData &Record, 6619 unsigned &Index) { 6620 switch (Kind) { 6621 case TemplateArgument::Expression: 6622 return ReadExpr(F); 6623 case TemplateArgument::Type: 6624 return GetTypeSourceInfo(F, Record, Index); 6625 case TemplateArgument::Template: { 6626 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, 6627 Index); 6628 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index); 6629 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc, 6630 SourceLocation()); 6631 } 6632 case TemplateArgument::TemplateExpansion: { 6633 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, 6634 Index); 6635 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index); 6636 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index); 6637 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc, 6638 EllipsisLoc); 6639 } 6640 case TemplateArgument::Null: 6641 case TemplateArgument::Integral: 6642 case TemplateArgument::Declaration: 6643 case TemplateArgument::NullPtr: 6644 case TemplateArgument::Pack: 6645 // FIXME: Is this right? 6646 return TemplateArgumentLocInfo(); 6647 } 6648 llvm_unreachable("unexpected template argument loc"); 6649 } 6650 6651 TemplateArgumentLoc 6652 ASTReader::ReadTemplateArgumentLoc(ModuleFile &F, 6653 const RecordData &Record, unsigned &Index) { 6654 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index); 6655 6656 if (Arg.getKind() == TemplateArgument::Expression) { 6657 if (Record[Index++]) // bool InfoHasSameExpr. 6658 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr())); 6659 } 6660 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(), 6661 Record, Index)); 6662 } 6663 6664 const ASTTemplateArgumentListInfo* 6665 ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F, 6666 const RecordData &Record, 6667 unsigned &Index) { 6668 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index); 6669 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index); 6670 unsigned NumArgsAsWritten = Record[Index++]; 6671 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc); 6672 for (unsigned i = 0; i != NumArgsAsWritten; ++i) 6673 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index)); 6674 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo); 6675 } 6676 6677 Decl *ASTReader::GetExternalDecl(uint32_t ID) { 6678 return GetDecl(ID); 6679 } 6680 6681 void ASTReader::CompleteRedeclChain(const Decl *D) { 6682 if (NumCurrentElementsDeserializing) { 6683 // We arrange to not care about the complete redeclaration chain while we're 6684 // deserializing. Just remember that the AST has marked this one as complete 6685 // but that it's not actually complete yet, so we know we still need to 6686 // complete it later. 6687 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D)); 6688 return; 6689 } 6690 6691 const DeclContext *DC = D->getDeclContext()->getRedeclContext(); 6692 6693 // If this is a named declaration, complete it by looking it up 6694 // within its context. 6695 // 6696 // FIXME: Merging a function definition should merge 6697 // all mergeable entities within it. 6698 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) || 6699 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) { 6700 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) { 6701 if (!getContext().getLangOpts().CPlusPlus && 6702 isa<TranslationUnitDecl>(DC)) { 6703 // Outside of C++, we don't have a lookup table for the TU, so update 6704 // the identifier instead. (For C++ modules, we don't store decls 6705 // in the serialized identifier table, so we do the lookup in the TU.) 6706 auto *II = Name.getAsIdentifierInfo(); 6707 assert(II && "non-identifier name in C?"); 6708 if (II->isOutOfDate()) 6709 updateOutOfDateIdentifier(*II); 6710 } else 6711 DC->lookup(Name); 6712 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) { 6713 // Find all declarations of this kind from the relevant context. 6714 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) { 6715 auto *DC = cast<DeclContext>(DCDecl); 6716 SmallVector<Decl*, 8> Decls; 6717 FindExternalLexicalDecls( 6718 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls); 6719 } 6720 } 6721 } 6722 6723 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) 6724 CTSD->getSpecializedTemplate()->LoadLazySpecializations(); 6725 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D)) 6726 VTSD->getSpecializedTemplate()->LoadLazySpecializations(); 6727 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 6728 if (auto *Template = FD->getPrimaryTemplate()) 6729 Template->LoadLazySpecializations(); 6730 } 6731 } 6732 6733 CXXCtorInitializer ** 6734 ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) { 6735 RecordLocation Loc = getLocalBitOffset(Offset); 6736 BitstreamCursor &Cursor = Loc.F->DeclsCursor; 6737 SavedStreamPosition SavedPosition(Cursor); 6738 Cursor.JumpToBit(Loc.Offset); 6739 ReadingKindTracker ReadingKind(Read_Decl, *this); 6740 6741 RecordData Record; 6742 unsigned Code = Cursor.ReadCode(); 6743 unsigned RecCode = Cursor.readRecord(Code, Record); 6744 if (RecCode != DECL_CXX_CTOR_INITIALIZERS) { 6745 Error("malformed AST file: missing C++ ctor initializers"); 6746 return nullptr; 6747 } 6748 6749 unsigned Idx = 0; 6750 return ReadCXXCtorInitializers(*Loc.F, Record, Idx); 6751 } 6752 6753 CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) { 6754 RecordLocation Loc = getLocalBitOffset(Offset); 6755 BitstreamCursor &Cursor = Loc.F->DeclsCursor; 6756 SavedStreamPosition SavedPosition(Cursor); 6757 Cursor.JumpToBit(Loc.Offset); 6758 ReadingKindTracker ReadingKind(Read_Decl, *this); 6759 RecordData Record; 6760 unsigned Code = Cursor.ReadCode(); 6761 unsigned RecCode = Cursor.readRecord(Code, Record); 6762 if (RecCode != DECL_CXX_BASE_SPECIFIERS) { 6763 Error("malformed AST file: missing C++ base specifiers"); 6764 return nullptr; 6765 } 6766 6767 unsigned Idx = 0; 6768 unsigned NumBases = Record[Idx++]; 6769 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases); 6770 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases]; 6771 for (unsigned I = 0; I != NumBases; ++I) 6772 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx); 6773 return Bases; 6774 } 6775 6776 serialization::DeclID 6777 ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const { 6778 if (LocalID < NUM_PREDEF_DECL_IDS) 6779 return LocalID; 6780 6781 if (!F.ModuleOffsetMap.empty()) 6782 ReadModuleOffsetMap(F); 6783 6784 ContinuousRangeMap<uint32_t, int, 2>::iterator I 6785 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS); 6786 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap"); 6787 6788 return LocalID + I->second; 6789 } 6790 6791 bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID, 6792 ModuleFile &M) const { 6793 // Predefined decls aren't from any module. 6794 if (ID < NUM_PREDEF_DECL_IDS) 6795 return false; 6796 6797 return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID && 6798 ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls; 6799 } 6800 6801 ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) { 6802 if (!D->isFromASTFile()) 6803 return nullptr; 6804 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID()); 6805 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map"); 6806 return I->second; 6807 } 6808 6809 SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) { 6810 if (ID < NUM_PREDEF_DECL_IDS) 6811 return SourceLocation(); 6812 6813 unsigned Index = ID - NUM_PREDEF_DECL_IDS; 6814 6815 if (Index > DeclsLoaded.size()) { 6816 Error("declaration ID out-of-range for AST file"); 6817 return SourceLocation(); 6818 } 6819 6820 if (Decl *D = DeclsLoaded[Index]) 6821 return D->getLocation(); 6822 6823 SourceLocation Loc; 6824 DeclCursorForID(ID, Loc); 6825 return Loc; 6826 } 6827 6828 static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) { 6829 switch (ID) { 6830 case PREDEF_DECL_NULL_ID: 6831 return nullptr; 6832 6833 case PREDEF_DECL_TRANSLATION_UNIT_ID: 6834 return Context.getTranslationUnitDecl(); 6835 6836 case PREDEF_DECL_OBJC_ID_ID: 6837 return Context.getObjCIdDecl(); 6838 6839 case PREDEF_DECL_OBJC_SEL_ID: 6840 return Context.getObjCSelDecl(); 6841 6842 case PREDEF_DECL_OBJC_CLASS_ID: 6843 return Context.getObjCClassDecl(); 6844 6845 case PREDEF_DECL_OBJC_PROTOCOL_ID: 6846 return Context.getObjCProtocolDecl(); 6847 6848 case PREDEF_DECL_INT_128_ID: 6849 return Context.getInt128Decl(); 6850 6851 case PREDEF_DECL_UNSIGNED_INT_128_ID: 6852 return Context.getUInt128Decl(); 6853 6854 case PREDEF_DECL_OBJC_INSTANCETYPE_ID: 6855 return Context.getObjCInstanceTypeDecl(); 6856 6857 case PREDEF_DECL_BUILTIN_VA_LIST_ID: 6858 return Context.getBuiltinVaListDecl(); 6859 6860 case PREDEF_DECL_VA_LIST_TAG: 6861 return Context.getVaListTagDecl(); 6862 6863 case PREDEF_DECL_BUILTIN_MS_VA_LIST_ID: 6864 return Context.getBuiltinMSVaListDecl(); 6865 6866 case PREDEF_DECL_EXTERN_C_CONTEXT_ID: 6867 return Context.getExternCContextDecl(); 6868 6869 case PREDEF_DECL_MAKE_INTEGER_SEQ_ID: 6870 return Context.getMakeIntegerSeqDecl(); 6871 6872 case PREDEF_DECL_CF_CONSTANT_STRING_ID: 6873 return Context.getCFConstantStringDecl(); 6874 6875 case PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID: 6876 return Context.getCFConstantStringTagDecl(); 6877 6878 case PREDEF_DECL_TYPE_PACK_ELEMENT_ID: 6879 return Context.getTypePackElementDecl(); 6880 } 6881 llvm_unreachable("PredefinedDeclIDs unknown enum value"); 6882 } 6883 6884 Decl *ASTReader::GetExistingDecl(DeclID ID) { 6885 if (ID < NUM_PREDEF_DECL_IDS) { 6886 Decl *D = getPredefinedDecl(Context, (PredefinedDeclIDs)ID); 6887 if (D) { 6888 // Track that we have merged the declaration with ID \p ID into the 6889 // pre-existing predefined declaration \p D. 6890 auto &Merged = KeyDecls[D->getCanonicalDecl()]; 6891 if (Merged.empty()) 6892 Merged.push_back(ID); 6893 } 6894 return D; 6895 } 6896 6897 unsigned Index = ID - NUM_PREDEF_DECL_IDS; 6898 6899 if (Index >= DeclsLoaded.size()) { 6900 assert(0 && "declaration ID out-of-range for AST file"); 6901 Error("declaration ID out-of-range for AST file"); 6902 return nullptr; 6903 } 6904 6905 return DeclsLoaded[Index]; 6906 } 6907 6908 Decl *ASTReader::GetDecl(DeclID ID) { 6909 if (ID < NUM_PREDEF_DECL_IDS) 6910 return GetExistingDecl(ID); 6911 6912 unsigned Index = ID - NUM_PREDEF_DECL_IDS; 6913 6914 if (Index >= DeclsLoaded.size()) { 6915 assert(0 && "declaration ID out-of-range for AST file"); 6916 Error("declaration ID out-of-range for AST file"); 6917 return nullptr; 6918 } 6919 6920 if (!DeclsLoaded[Index]) { 6921 ReadDeclRecord(ID); 6922 if (DeserializationListener) 6923 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]); 6924 } 6925 6926 return DeclsLoaded[Index]; 6927 } 6928 6929 DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M, 6930 DeclID GlobalID) { 6931 if (GlobalID < NUM_PREDEF_DECL_IDS) 6932 return GlobalID; 6933 6934 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID); 6935 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map"); 6936 ModuleFile *Owner = I->second; 6937 6938 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos 6939 = M.GlobalToLocalDeclIDs.find(Owner); 6940 if (Pos == M.GlobalToLocalDeclIDs.end()) 6941 return 0; 6942 6943 return GlobalID - Owner->BaseDeclID + Pos->second; 6944 } 6945 6946 serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F, 6947 const RecordData &Record, 6948 unsigned &Idx) { 6949 if (Idx >= Record.size()) { 6950 Error("Corrupted AST file"); 6951 return 0; 6952 } 6953 6954 return getGlobalDeclID(F, Record[Idx++]); 6955 } 6956 6957 /// \brief Resolve the offset of a statement into a statement. 6958 /// 6959 /// This operation will read a new statement from the external 6960 /// source each time it is called, and is meant to be used via a 6961 /// LazyOffsetPtr (which is used by Decls for the body of functions, etc). 6962 Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) { 6963 // Switch case IDs are per Decl. 6964 ClearSwitchCaseIDs(); 6965 6966 // Offset here is a global offset across the entire chain. 6967 RecordLocation Loc = getLocalBitOffset(Offset); 6968 Loc.F->DeclsCursor.JumpToBit(Loc.Offset); 6969 assert(NumCurrentElementsDeserializing == 0 && 6970 "should not be called while already deserializing"); 6971 Deserializing D(this); 6972 return ReadStmtFromStream(*Loc.F); 6973 } 6974 6975 void ASTReader::FindExternalLexicalDecls( 6976 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant, 6977 SmallVectorImpl<Decl *> &Decls) { 6978 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {}; 6979 6980 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) { 6981 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries"); 6982 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) { 6983 auto K = (Decl::Kind)+LexicalDecls[I]; 6984 if (!IsKindWeWant(K)) 6985 continue; 6986 6987 auto ID = (serialization::DeclID)+LexicalDecls[I + 1]; 6988 6989 // Don't add predefined declarations to the lexical context more 6990 // than once. 6991 if (ID < NUM_PREDEF_DECL_IDS) { 6992 if (PredefsVisited[ID]) 6993 continue; 6994 6995 PredefsVisited[ID] = true; 6996 } 6997 6998 if (Decl *D = GetLocalDecl(*M, ID)) { 6999 assert(D->getKind() == K && "wrong kind for lexical decl"); 7000 if (!DC->isDeclInLexicalTraversal(D)) 7001 Decls.push_back(D); 7002 } 7003 } 7004 }; 7005 7006 if (isa<TranslationUnitDecl>(DC)) { 7007 for (auto Lexical : TULexicalDecls) 7008 Visit(Lexical.first, Lexical.second); 7009 } else { 7010 auto I = LexicalDecls.find(DC); 7011 if (I != LexicalDecls.end()) 7012 Visit(I->second.first, I->second.second); 7013 } 7014 7015 ++NumLexicalDeclContextsRead; 7016 } 7017 7018 namespace { 7019 7020 class DeclIDComp { 7021 ASTReader &Reader; 7022 ModuleFile &Mod; 7023 7024 public: 7025 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {} 7026 7027 bool operator()(LocalDeclID L, LocalDeclID R) const { 7028 SourceLocation LHS = getLocation(L); 7029 SourceLocation RHS = getLocation(R); 7030 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS); 7031 } 7032 7033 bool operator()(SourceLocation LHS, LocalDeclID R) const { 7034 SourceLocation RHS = getLocation(R); 7035 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS); 7036 } 7037 7038 bool operator()(LocalDeclID L, SourceLocation RHS) const { 7039 SourceLocation LHS = getLocation(L); 7040 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS); 7041 } 7042 7043 SourceLocation getLocation(LocalDeclID ID) const { 7044 return Reader.getSourceManager().getFileLoc( 7045 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID))); 7046 } 7047 }; 7048 7049 } // end anonymous namespace 7050 7051 void ASTReader::FindFileRegionDecls(FileID File, 7052 unsigned Offset, unsigned Length, 7053 SmallVectorImpl<Decl *> &Decls) { 7054 SourceManager &SM = getSourceManager(); 7055 7056 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File); 7057 if (I == FileDeclIDs.end()) 7058 return; 7059 7060 FileDeclsInfo &DInfo = I->second; 7061 if (DInfo.Decls.empty()) 7062 return; 7063 7064 SourceLocation 7065 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset); 7066 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length); 7067 7068 DeclIDComp DIDComp(*this, *DInfo.Mod); 7069 ArrayRef<serialization::LocalDeclID>::iterator 7070 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(), 7071 BeginLoc, DIDComp); 7072 if (BeginIt != DInfo.Decls.begin()) 7073 --BeginIt; 7074 7075 // If we are pointing at a top-level decl inside an objc container, we need 7076 // to backtrack until we find it otherwise we will fail to report that the 7077 // region overlaps with an objc container. 7078 while (BeginIt != DInfo.Decls.begin() && 7079 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt)) 7080 ->isTopLevelDeclInObjCContainer()) 7081 --BeginIt; 7082 7083 ArrayRef<serialization::LocalDeclID>::iterator 7084 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(), 7085 EndLoc, DIDComp); 7086 if (EndIt != DInfo.Decls.end()) 7087 ++EndIt; 7088 7089 for (ArrayRef<serialization::LocalDeclID>::iterator 7090 DIt = BeginIt; DIt != EndIt; ++DIt) 7091 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt))); 7092 } 7093 7094 bool 7095 ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC, 7096 DeclarationName Name) { 7097 assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() && 7098 "DeclContext has no visible decls in storage"); 7099 if (!Name) 7100 return false; 7101 7102 auto It = Lookups.find(DC); 7103 if (It == Lookups.end()) 7104 return false; 7105 7106 Deserializing LookupResults(this); 7107 7108 // Load the list of declarations. 7109 SmallVector<NamedDecl *, 64> Decls; 7110 for (DeclID ID : It->second.Table.find(Name)) { 7111 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID)); 7112 if (ND->getDeclName() == Name) 7113 Decls.push_back(ND); 7114 } 7115 7116 ++NumVisibleDeclContextsRead; 7117 SetExternalVisibleDeclsForName(DC, Name, Decls); 7118 return !Decls.empty(); 7119 } 7120 7121 void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) { 7122 if (!DC->hasExternalVisibleStorage()) 7123 return; 7124 7125 auto It = Lookups.find(DC); 7126 assert(It != Lookups.end() && 7127 "have external visible storage but no lookup tables"); 7128 7129 DeclsMap Decls; 7130 7131 for (DeclID ID : It->second.Table.findAll()) { 7132 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID)); 7133 Decls[ND->getDeclName()].push_back(ND); 7134 } 7135 7136 ++NumVisibleDeclContextsRead; 7137 7138 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) { 7139 SetExternalVisibleDeclsForName(DC, I->first, I->second); 7140 } 7141 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false); 7142 } 7143 7144 const serialization::reader::DeclContextLookupTable * 7145 ASTReader::getLoadedLookupTables(DeclContext *Primary) const { 7146 auto I = Lookups.find(Primary); 7147 return I == Lookups.end() ? nullptr : &I->second; 7148 } 7149 7150 /// \brief Under non-PCH compilation the consumer receives the objc methods 7151 /// before receiving the implementation, and codegen depends on this. 7152 /// We simulate this by deserializing and passing to consumer the methods of the 7153 /// implementation before passing the deserialized implementation decl. 7154 static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD, 7155 ASTConsumer *Consumer) { 7156 assert(ImplD && Consumer); 7157 7158 for (auto *I : ImplD->methods()) 7159 Consumer->HandleInterestingDecl(DeclGroupRef(I)); 7160 7161 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD)); 7162 } 7163 7164 void ASTReader::PassInterestingDeclsToConsumer() { 7165 assert(Consumer); 7166 7167 if (PassingDeclsToConsumer) 7168 return; 7169 7170 // Guard variable to avoid recursively redoing the process of passing 7171 // decls to consumer. 7172 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer, 7173 true); 7174 7175 // Ensure that we've loaded all potentially-interesting declarations 7176 // that need to be eagerly loaded. 7177 for (auto ID : EagerlyDeserializedDecls) 7178 GetDecl(ID); 7179 EagerlyDeserializedDecls.clear(); 7180 7181 while (!InterestingDecls.empty()) { 7182 Decl *D = InterestingDecls.front(); 7183 InterestingDecls.pop_front(); 7184 7185 PassInterestingDeclToConsumer(D); 7186 } 7187 } 7188 7189 void ASTReader::PassInterestingDeclToConsumer(Decl *D) { 7190 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D)) 7191 PassObjCImplDeclToConsumer(ImplD, Consumer); 7192 else 7193 Consumer->HandleInterestingDecl(DeclGroupRef(D)); 7194 } 7195 7196 void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) { 7197 this->Consumer = Consumer; 7198 7199 if (Consumer) 7200 PassInterestingDeclsToConsumer(); 7201 7202 if (DeserializationListener) 7203 DeserializationListener->ReaderInitialized(this); 7204 } 7205 7206 void ASTReader::PrintStats() { 7207 std::fprintf(stderr, "*** AST File Statistics:\n"); 7208 7209 unsigned NumTypesLoaded 7210 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(), 7211 QualType()); 7212 unsigned NumDeclsLoaded 7213 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(), 7214 (Decl *)nullptr); 7215 unsigned NumIdentifiersLoaded 7216 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(), 7217 IdentifiersLoaded.end(), 7218 (IdentifierInfo *)nullptr); 7219 unsigned NumMacrosLoaded 7220 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(), 7221 MacrosLoaded.end(), 7222 (MacroInfo *)nullptr); 7223 unsigned NumSelectorsLoaded 7224 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(), 7225 SelectorsLoaded.end(), 7226 Selector()); 7227 7228 if (unsigned TotalNumSLocEntries = getTotalNumSLocs()) 7229 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n", 7230 NumSLocEntriesRead, TotalNumSLocEntries, 7231 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100)); 7232 if (!TypesLoaded.empty()) 7233 std::fprintf(stderr, " %u/%u types read (%f%%)\n", 7234 NumTypesLoaded, (unsigned)TypesLoaded.size(), 7235 ((float)NumTypesLoaded/TypesLoaded.size() * 100)); 7236 if (!DeclsLoaded.empty()) 7237 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n", 7238 NumDeclsLoaded, (unsigned)DeclsLoaded.size(), 7239 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100)); 7240 if (!IdentifiersLoaded.empty()) 7241 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n", 7242 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(), 7243 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100)); 7244 if (!MacrosLoaded.empty()) 7245 std::fprintf(stderr, " %u/%u macros read (%f%%)\n", 7246 NumMacrosLoaded, (unsigned)MacrosLoaded.size(), 7247 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100)); 7248 if (!SelectorsLoaded.empty()) 7249 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n", 7250 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(), 7251 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100)); 7252 if (TotalNumStatements) 7253 std::fprintf(stderr, " %u/%u statements read (%f%%)\n", 7254 NumStatementsRead, TotalNumStatements, 7255 ((float)NumStatementsRead/TotalNumStatements * 100)); 7256 if (TotalNumMacros) 7257 std::fprintf(stderr, " %u/%u macros read (%f%%)\n", 7258 NumMacrosRead, TotalNumMacros, 7259 ((float)NumMacrosRead/TotalNumMacros * 100)); 7260 if (TotalLexicalDeclContexts) 7261 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n", 7262 NumLexicalDeclContextsRead, TotalLexicalDeclContexts, 7263 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts 7264 * 100)); 7265 if (TotalVisibleDeclContexts) 7266 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n", 7267 NumVisibleDeclContextsRead, TotalVisibleDeclContexts, 7268 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts 7269 * 100)); 7270 if (TotalNumMethodPoolEntries) { 7271 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n", 7272 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries, 7273 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries 7274 * 100)); 7275 } 7276 if (NumMethodPoolLookups) { 7277 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n", 7278 NumMethodPoolHits, NumMethodPoolLookups, 7279 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0)); 7280 } 7281 if (NumMethodPoolTableLookups) { 7282 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n", 7283 NumMethodPoolTableHits, NumMethodPoolTableLookups, 7284 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups 7285 * 100.0)); 7286 } 7287 7288 if (NumIdentifierLookupHits) { 7289 std::fprintf(stderr, 7290 " %u / %u identifier table lookups succeeded (%f%%)\n", 7291 NumIdentifierLookupHits, NumIdentifierLookups, 7292 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups); 7293 } 7294 7295 if (GlobalIndex) { 7296 std::fprintf(stderr, "\n"); 7297 GlobalIndex->printStats(); 7298 } 7299 7300 std::fprintf(stderr, "\n"); 7301 dump(); 7302 std::fprintf(stderr, "\n"); 7303 } 7304 7305 template<typename Key, typename ModuleFile, unsigned InitialCapacity> 7306 LLVM_DUMP_METHOD static void 7307 dumpModuleIDMap(StringRef Name, 7308 const ContinuousRangeMap<Key, ModuleFile *, 7309 InitialCapacity> &Map) { 7310 if (Map.begin() == Map.end()) 7311 return; 7312 7313 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType; 7314 llvm::errs() << Name << ":\n"; 7315 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end(); 7316 I != IEnd; ++I) { 7317 llvm::errs() << " " << I->first << " -> " << I->second->FileName 7318 << "\n"; 7319 } 7320 } 7321 7322 LLVM_DUMP_METHOD void ASTReader::dump() { 7323 llvm::errs() << "*** PCH/ModuleFile Remappings:\n"; 7324 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap); 7325 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap); 7326 dumpModuleIDMap("Global type map", GlobalTypeMap); 7327 dumpModuleIDMap("Global declaration map", GlobalDeclMap); 7328 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap); 7329 dumpModuleIDMap("Global macro map", GlobalMacroMap); 7330 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap); 7331 dumpModuleIDMap("Global selector map", GlobalSelectorMap); 7332 dumpModuleIDMap("Global preprocessed entity map", 7333 GlobalPreprocessedEntityMap); 7334 7335 llvm::errs() << "\n*** PCH/Modules Loaded:"; 7336 for (ModuleFile &M : ModuleMgr) 7337 M.dump(); 7338 } 7339 7340 /// Return the amount of memory used by memory buffers, breaking down 7341 /// by heap-backed versus mmap'ed memory. 7342 void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const { 7343 for (ModuleFile &I : ModuleMgr) { 7344 if (llvm::MemoryBuffer *buf = I.Buffer) { 7345 size_t bytes = buf->getBufferSize(); 7346 switch (buf->getBufferKind()) { 7347 case llvm::MemoryBuffer::MemoryBuffer_Malloc: 7348 sizes.malloc_bytes += bytes; 7349 break; 7350 case llvm::MemoryBuffer::MemoryBuffer_MMap: 7351 sizes.mmap_bytes += bytes; 7352 break; 7353 } 7354 } 7355 } 7356 } 7357 7358 void ASTReader::InitializeSema(Sema &S) { 7359 SemaObj = &S; 7360 S.addExternalSource(this); 7361 7362 // Makes sure any declarations that were deserialized "too early" 7363 // still get added to the identifier's declaration chains. 7364 for (uint64_t ID : PreloadedDeclIDs) { 7365 NamedDecl *D = cast<NamedDecl>(GetDecl(ID)); 7366 pushExternalDeclIntoScope(D, D->getDeclName()); 7367 } 7368 PreloadedDeclIDs.clear(); 7369 7370 // FIXME: What happens if these are changed by a module import? 7371 if (!FPPragmaOptions.empty()) { 7372 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS"); 7373 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0]; 7374 } 7375 7376 SemaObj->OpenCLFeatures.copy(OpenCLExtensions); 7377 SemaObj->OpenCLTypeExtMap = OpenCLTypeExtMap; 7378 SemaObj->OpenCLDeclExtMap = OpenCLDeclExtMap; 7379 7380 UpdateSema(); 7381 } 7382 7383 void ASTReader::UpdateSema() { 7384 assert(SemaObj && "no Sema to update"); 7385 7386 // Load the offsets of the declarations that Sema references. 7387 // They will be lazily deserialized when needed. 7388 if (!SemaDeclRefs.empty()) { 7389 assert(SemaDeclRefs.size() % 3 == 0); 7390 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 3) { 7391 if (!SemaObj->StdNamespace) 7392 SemaObj->StdNamespace = SemaDeclRefs[I]; 7393 if (!SemaObj->StdBadAlloc) 7394 SemaObj->StdBadAlloc = SemaDeclRefs[I+1]; 7395 if (!SemaObj->StdAlignValT) 7396 SemaObj->StdAlignValT = SemaDeclRefs[I+2]; 7397 } 7398 SemaDeclRefs.clear(); 7399 } 7400 7401 // Update the state of pragmas. Use the same API as if we had encountered the 7402 // pragma in the source. 7403 if(OptimizeOffPragmaLocation.isValid()) 7404 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation); 7405 if (PragmaMSStructState != -1) 7406 SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState); 7407 if (PointersToMembersPragmaLocation.isValid()) { 7408 SemaObj->ActOnPragmaMSPointersToMembers( 7409 (LangOptions::PragmaMSPointersToMembersKind) 7410 PragmaMSPointersToMembersState, 7411 PointersToMembersPragmaLocation); 7412 } 7413 SemaObj->ForceCUDAHostDeviceDepth = ForceCUDAHostDeviceDepth; 7414 } 7415 7416 IdentifierInfo *ASTReader::get(StringRef Name) { 7417 // Note that we are loading an identifier. 7418 Deserializing AnIdentifier(this); 7419 7420 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0, 7421 NumIdentifierLookups, 7422 NumIdentifierLookupHits); 7423 7424 // We don't need to do identifier table lookups in C++ modules (we preload 7425 // all interesting declarations, and don't need to use the scope for name 7426 // lookups). Perform the lookup in PCH files, though, since we don't build 7427 // a complete initial identifier table if we're carrying on from a PCH. 7428 if (Context.getLangOpts().CPlusPlus) { 7429 for (auto F : ModuleMgr.pch_modules()) 7430 if (Visitor(*F)) 7431 break; 7432 } else { 7433 // If there is a global index, look there first to determine which modules 7434 // provably do not have any results for this identifier. 7435 GlobalModuleIndex::HitSet Hits; 7436 GlobalModuleIndex::HitSet *HitsPtr = nullptr; 7437 if (!loadGlobalIndex()) { 7438 if (GlobalIndex->lookupIdentifier(Name, Hits)) { 7439 HitsPtr = &Hits; 7440 } 7441 } 7442 7443 ModuleMgr.visit(Visitor, HitsPtr); 7444 } 7445 7446 IdentifierInfo *II = Visitor.getIdentifierInfo(); 7447 markIdentifierUpToDate(II); 7448 return II; 7449 } 7450 7451 namespace clang { 7452 7453 /// \brief An identifier-lookup iterator that enumerates all of the 7454 /// identifiers stored within a set of AST files. 7455 class ASTIdentifierIterator : public IdentifierIterator { 7456 /// \brief The AST reader whose identifiers are being enumerated. 7457 const ASTReader &Reader; 7458 7459 /// \brief The current index into the chain of AST files stored in 7460 /// the AST reader. 7461 unsigned Index; 7462 7463 /// \brief The current position within the identifier lookup table 7464 /// of the current AST file. 7465 ASTIdentifierLookupTable::key_iterator Current; 7466 7467 /// \brief The end position within the identifier lookup table of 7468 /// the current AST file. 7469 ASTIdentifierLookupTable::key_iterator End; 7470 7471 /// \brief Whether to skip any modules in the ASTReader. 7472 bool SkipModules; 7473 7474 public: 7475 explicit ASTIdentifierIterator(const ASTReader &Reader, 7476 bool SkipModules = false); 7477 7478 StringRef Next() override; 7479 }; 7480 7481 } // end namespace clang 7482 7483 ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader, 7484 bool SkipModules) 7485 : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) { 7486 } 7487 7488 StringRef ASTIdentifierIterator::Next() { 7489 while (Current == End) { 7490 // If we have exhausted all of our AST files, we're done. 7491 if (Index == 0) 7492 return StringRef(); 7493 7494 --Index; 7495 ModuleFile &F = Reader.ModuleMgr[Index]; 7496 if (SkipModules && F.isModule()) 7497 continue; 7498 7499 ASTIdentifierLookupTable *IdTable = 7500 (ASTIdentifierLookupTable *)F.IdentifierLookupTable; 7501 Current = IdTable->key_begin(); 7502 End = IdTable->key_end(); 7503 } 7504 7505 // We have any identifiers remaining in the current AST file; return 7506 // the next one. 7507 StringRef Result = *Current; 7508 ++Current; 7509 return Result; 7510 } 7511 7512 namespace { 7513 7514 /// A utility for appending two IdentifierIterators. 7515 class ChainedIdentifierIterator : public IdentifierIterator { 7516 std::unique_ptr<IdentifierIterator> Current; 7517 std::unique_ptr<IdentifierIterator> Queued; 7518 7519 public: 7520 ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First, 7521 std::unique_ptr<IdentifierIterator> Second) 7522 : Current(std::move(First)), Queued(std::move(Second)) {} 7523 7524 StringRef Next() override { 7525 if (!Current) 7526 return StringRef(); 7527 7528 StringRef result = Current->Next(); 7529 if (!result.empty()) 7530 return result; 7531 7532 // Try the queued iterator, which may itself be empty. 7533 Current.reset(); 7534 std::swap(Current, Queued); 7535 return Next(); 7536 } 7537 }; 7538 7539 } // end anonymous namespace. 7540 7541 IdentifierIterator *ASTReader::getIdentifiers() { 7542 if (!loadGlobalIndex()) { 7543 std::unique_ptr<IdentifierIterator> ReaderIter( 7544 new ASTIdentifierIterator(*this, /*SkipModules=*/true)); 7545 std::unique_ptr<IdentifierIterator> ModulesIter( 7546 GlobalIndex->createIdentifierIterator()); 7547 return new ChainedIdentifierIterator(std::move(ReaderIter), 7548 std::move(ModulesIter)); 7549 } 7550 7551 return new ASTIdentifierIterator(*this); 7552 } 7553 7554 namespace clang { 7555 namespace serialization { 7556 7557 class ReadMethodPoolVisitor { 7558 ASTReader &Reader; 7559 Selector Sel; 7560 unsigned PriorGeneration; 7561 unsigned InstanceBits; 7562 unsigned FactoryBits; 7563 bool InstanceHasMoreThanOneDecl; 7564 bool FactoryHasMoreThanOneDecl; 7565 SmallVector<ObjCMethodDecl *, 4> InstanceMethods; 7566 SmallVector<ObjCMethodDecl *, 4> FactoryMethods; 7567 7568 public: 7569 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel, 7570 unsigned PriorGeneration) 7571 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration), 7572 InstanceBits(0), FactoryBits(0), InstanceHasMoreThanOneDecl(false), 7573 FactoryHasMoreThanOneDecl(false) {} 7574 7575 bool operator()(ModuleFile &M) { 7576 if (!M.SelectorLookupTable) 7577 return false; 7578 7579 // If we've already searched this module file, skip it now. 7580 if (M.Generation <= PriorGeneration) 7581 return true; 7582 7583 ++Reader.NumMethodPoolTableLookups; 7584 ASTSelectorLookupTable *PoolTable 7585 = (ASTSelectorLookupTable*)M.SelectorLookupTable; 7586 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel); 7587 if (Pos == PoolTable->end()) 7588 return false; 7589 7590 ++Reader.NumMethodPoolTableHits; 7591 ++Reader.NumSelectorsRead; 7592 // FIXME: Not quite happy with the statistics here. We probably should 7593 // disable this tracking when called via LoadSelector. 7594 // Also, should entries without methods count as misses? 7595 ++Reader.NumMethodPoolEntriesRead; 7596 ASTSelectorLookupTrait::data_type Data = *Pos; 7597 if (Reader.DeserializationListener) 7598 Reader.DeserializationListener->SelectorRead(Data.ID, Sel); 7599 7600 InstanceMethods.append(Data.Instance.begin(), Data.Instance.end()); 7601 FactoryMethods.append(Data.Factory.begin(), Data.Factory.end()); 7602 InstanceBits = Data.InstanceBits; 7603 FactoryBits = Data.FactoryBits; 7604 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl; 7605 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl; 7606 return true; 7607 } 7608 7609 /// \brief Retrieve the instance methods found by this visitor. 7610 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const { 7611 return InstanceMethods; 7612 } 7613 7614 /// \brief Retrieve the instance methods found by this visitor. 7615 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const { 7616 return FactoryMethods; 7617 } 7618 7619 unsigned getInstanceBits() const { return InstanceBits; } 7620 unsigned getFactoryBits() const { return FactoryBits; } 7621 bool instanceHasMoreThanOneDecl() const { 7622 return InstanceHasMoreThanOneDecl; 7623 } 7624 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; } 7625 }; 7626 7627 } // end namespace serialization 7628 } // end namespace clang 7629 7630 /// \brief Add the given set of methods to the method list. 7631 static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods, 7632 ObjCMethodList &List) { 7633 for (unsigned I = 0, N = Methods.size(); I != N; ++I) { 7634 S.addMethodToGlobalList(&List, Methods[I]); 7635 } 7636 } 7637 7638 void ASTReader::ReadMethodPool(Selector Sel) { 7639 // Get the selector generation and update it to the current generation. 7640 unsigned &Generation = SelectorGeneration[Sel]; 7641 unsigned PriorGeneration = Generation; 7642 Generation = getGeneration(); 7643 SelectorOutOfDate[Sel] = false; 7644 7645 // Search for methods defined with this selector. 7646 ++NumMethodPoolLookups; 7647 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration); 7648 ModuleMgr.visit(Visitor); 7649 7650 if (Visitor.getInstanceMethods().empty() && 7651 Visitor.getFactoryMethods().empty()) 7652 return; 7653 7654 ++NumMethodPoolHits; 7655 7656 if (!getSema()) 7657 return; 7658 7659 Sema &S = *getSema(); 7660 Sema::GlobalMethodPool::iterator Pos 7661 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first; 7662 7663 Pos->second.first.setBits(Visitor.getInstanceBits()); 7664 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl()); 7665 Pos->second.second.setBits(Visitor.getFactoryBits()); 7666 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl()); 7667 7668 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since 7669 // when building a module we keep every method individually and may need to 7670 // update hasMoreThanOneDecl as we add the methods. 7671 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first); 7672 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second); 7673 } 7674 7675 void ASTReader::updateOutOfDateSelector(Selector Sel) { 7676 if (SelectorOutOfDate[Sel]) 7677 ReadMethodPool(Sel); 7678 } 7679 7680 void ASTReader::ReadKnownNamespaces( 7681 SmallVectorImpl<NamespaceDecl *> &Namespaces) { 7682 Namespaces.clear(); 7683 7684 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) { 7685 if (NamespaceDecl *Namespace 7686 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I]))) 7687 Namespaces.push_back(Namespace); 7688 } 7689 } 7690 7691 void ASTReader::ReadUndefinedButUsed( 7692 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) { 7693 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) { 7694 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++])); 7695 SourceLocation Loc = 7696 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]); 7697 Undefined.insert(std::make_pair(D, Loc)); 7698 } 7699 } 7700 7701 void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector< 7702 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> & 7703 Exprs) { 7704 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) { 7705 FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++])); 7706 uint64_t Count = DelayedDeleteExprs[Idx++]; 7707 for (uint64_t C = 0; C < Count; ++C) { 7708 SourceLocation DeleteLoc = 7709 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]); 7710 const bool IsArrayForm = DelayedDeleteExprs[Idx++]; 7711 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm)); 7712 } 7713 } 7714 } 7715 7716 void ASTReader::ReadTentativeDefinitions( 7717 SmallVectorImpl<VarDecl *> &TentativeDefs) { 7718 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) { 7719 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I])); 7720 if (Var) 7721 TentativeDefs.push_back(Var); 7722 } 7723 TentativeDefinitions.clear(); 7724 } 7725 7726 void ASTReader::ReadUnusedFileScopedDecls( 7727 SmallVectorImpl<const DeclaratorDecl *> &Decls) { 7728 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) { 7729 DeclaratorDecl *D 7730 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I])); 7731 if (D) 7732 Decls.push_back(D); 7733 } 7734 UnusedFileScopedDecls.clear(); 7735 } 7736 7737 void ASTReader::ReadDelegatingConstructors( 7738 SmallVectorImpl<CXXConstructorDecl *> &Decls) { 7739 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) { 7740 CXXConstructorDecl *D 7741 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I])); 7742 if (D) 7743 Decls.push_back(D); 7744 } 7745 DelegatingCtorDecls.clear(); 7746 } 7747 7748 void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) { 7749 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) { 7750 TypedefNameDecl *D 7751 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I])); 7752 if (D) 7753 Decls.push_back(D); 7754 } 7755 ExtVectorDecls.clear(); 7756 } 7757 7758 void ASTReader::ReadUnusedLocalTypedefNameCandidates( 7759 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) { 7760 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N; 7761 ++I) { 7762 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>( 7763 GetDecl(UnusedLocalTypedefNameCandidates[I])); 7764 if (D) 7765 Decls.insert(D); 7766 } 7767 UnusedLocalTypedefNameCandidates.clear(); 7768 } 7769 7770 void ASTReader::ReadReferencedSelectors( 7771 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) { 7772 if (ReferencedSelectorsData.empty()) 7773 return; 7774 7775 // If there are @selector references added them to its pool. This is for 7776 // implementation of -Wselector. 7777 unsigned int DataSize = ReferencedSelectorsData.size()-1; 7778 unsigned I = 0; 7779 while (I < DataSize) { 7780 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]); 7781 SourceLocation SelLoc 7782 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]); 7783 Sels.push_back(std::make_pair(Sel, SelLoc)); 7784 } 7785 ReferencedSelectorsData.clear(); 7786 } 7787 7788 void ASTReader::ReadWeakUndeclaredIdentifiers( 7789 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) { 7790 if (WeakUndeclaredIdentifiers.empty()) 7791 return; 7792 7793 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) { 7794 IdentifierInfo *WeakId 7795 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]); 7796 IdentifierInfo *AliasId 7797 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]); 7798 SourceLocation Loc 7799 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]); 7800 bool Used = WeakUndeclaredIdentifiers[I++]; 7801 WeakInfo WI(AliasId, Loc); 7802 WI.setUsed(Used); 7803 WeakIDs.push_back(std::make_pair(WeakId, WI)); 7804 } 7805 WeakUndeclaredIdentifiers.clear(); 7806 } 7807 7808 void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) { 7809 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) { 7810 ExternalVTableUse VT; 7811 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++])); 7812 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]); 7813 VT.DefinitionRequired = VTableUses[Idx++]; 7814 VTables.push_back(VT); 7815 } 7816 7817 VTableUses.clear(); 7818 } 7819 7820 void ASTReader::ReadPendingInstantiations( 7821 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) { 7822 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) { 7823 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++])); 7824 SourceLocation Loc 7825 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]); 7826 7827 Pending.push_back(std::make_pair(D, Loc)); 7828 } 7829 PendingInstantiations.clear(); 7830 } 7831 7832 void ASTReader::ReadLateParsedTemplates( 7833 llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>> 7834 &LPTMap) { 7835 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N; 7836 /* In loop */) { 7837 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++])); 7838 7839 auto LT = llvm::make_unique<LateParsedTemplate>(); 7840 LT->D = GetDecl(LateParsedTemplates[Idx++]); 7841 7842 ModuleFile *F = getOwningModuleFile(LT->D); 7843 assert(F && "No module"); 7844 7845 unsigned TokN = LateParsedTemplates[Idx++]; 7846 LT->Toks.reserve(TokN); 7847 for (unsigned T = 0; T < TokN; ++T) 7848 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx)); 7849 7850 LPTMap.insert(std::make_pair(FD, std::move(LT))); 7851 } 7852 7853 LateParsedTemplates.clear(); 7854 } 7855 7856 void ASTReader::LoadSelector(Selector Sel) { 7857 // It would be complicated to avoid reading the methods anyway. So don't. 7858 ReadMethodPool(Sel); 7859 } 7860 7861 void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) { 7862 assert(ID && "Non-zero identifier ID required"); 7863 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range"); 7864 IdentifiersLoaded[ID - 1] = II; 7865 if (DeserializationListener) 7866 DeserializationListener->IdentifierRead(ID, II); 7867 } 7868 7869 /// \brief Set the globally-visible declarations associated with the given 7870 /// identifier. 7871 /// 7872 /// If the AST reader is currently in a state where the given declaration IDs 7873 /// cannot safely be resolved, they are queued until it is safe to resolve 7874 /// them. 7875 /// 7876 /// \param II an IdentifierInfo that refers to one or more globally-visible 7877 /// declarations. 7878 /// 7879 /// \param DeclIDs the set of declaration IDs with the name @p II that are 7880 /// visible at global scope. 7881 /// 7882 /// \param Decls if non-null, this vector will be populated with the set of 7883 /// deserialized declarations. These declarations will not be pushed into 7884 /// scope. 7885 void 7886 ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II, 7887 const SmallVectorImpl<uint32_t> &DeclIDs, 7888 SmallVectorImpl<Decl *> *Decls) { 7889 if (NumCurrentElementsDeserializing && !Decls) { 7890 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end()); 7891 return; 7892 } 7893 7894 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) { 7895 if (!SemaObj) { 7896 // Queue this declaration so that it will be added to the 7897 // translation unit scope and identifier's declaration chain 7898 // once a Sema object is known. 7899 PreloadedDeclIDs.push_back(DeclIDs[I]); 7900 continue; 7901 } 7902 7903 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I])); 7904 7905 // If we're simply supposed to record the declarations, do so now. 7906 if (Decls) { 7907 Decls->push_back(D); 7908 continue; 7909 } 7910 7911 // Introduce this declaration into the translation-unit scope 7912 // and add it to the declaration chain for this identifier, so 7913 // that (unqualified) name lookup will find it. 7914 pushExternalDeclIntoScope(D, II); 7915 } 7916 } 7917 7918 IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) { 7919 if (ID == 0) 7920 return nullptr; 7921 7922 if (IdentifiersLoaded.empty()) { 7923 Error("no identifier table in AST file"); 7924 return nullptr; 7925 } 7926 7927 ID -= 1; 7928 if (!IdentifiersLoaded[ID]) { 7929 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1); 7930 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map"); 7931 ModuleFile *M = I->second; 7932 unsigned Index = ID - M->BaseIdentifierID; 7933 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index]; 7934 7935 // All of the strings in the AST file are preceded by a 16-bit length. 7936 // Extract that 16-bit length to avoid having to execute strlen(). 7937 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as 7938 // unsigned integers. This is important to avoid integer overflow when 7939 // we cast them to 'unsigned'. 7940 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2; 7941 unsigned StrLen = (((unsigned) StrLenPtr[0]) 7942 | (((unsigned) StrLenPtr[1]) << 8)) - 1; 7943 auto &II = PP.getIdentifierTable().get(StringRef(Str, StrLen)); 7944 IdentifiersLoaded[ID] = &II; 7945 markIdentifierFromAST(*this, II); 7946 if (DeserializationListener) 7947 DeserializationListener->IdentifierRead(ID + 1, &II); 7948 } 7949 7950 return IdentifiersLoaded[ID]; 7951 } 7952 7953 IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) { 7954 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID)); 7955 } 7956 7957 IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) { 7958 if (LocalID < NUM_PREDEF_IDENT_IDS) 7959 return LocalID; 7960 7961 if (!M.ModuleOffsetMap.empty()) 7962 ReadModuleOffsetMap(M); 7963 7964 ContinuousRangeMap<uint32_t, int, 2>::iterator I 7965 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS); 7966 assert(I != M.IdentifierRemap.end() 7967 && "Invalid index into identifier index remap"); 7968 7969 return LocalID + I->second; 7970 } 7971 7972 MacroInfo *ASTReader::getMacro(MacroID ID) { 7973 if (ID == 0) 7974 return nullptr; 7975 7976 if (MacrosLoaded.empty()) { 7977 Error("no macro table in AST file"); 7978 return nullptr; 7979 } 7980 7981 ID -= NUM_PREDEF_MACRO_IDS; 7982 if (!MacrosLoaded[ID]) { 7983 GlobalMacroMapType::iterator I 7984 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS); 7985 assert(I != GlobalMacroMap.end() && "Corrupted global macro map"); 7986 ModuleFile *M = I->second; 7987 unsigned Index = ID - M->BaseMacroID; 7988 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]); 7989 7990 if (DeserializationListener) 7991 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS, 7992 MacrosLoaded[ID]); 7993 } 7994 7995 return MacrosLoaded[ID]; 7996 } 7997 7998 MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) { 7999 if (LocalID < NUM_PREDEF_MACRO_IDS) 8000 return LocalID; 8001 8002 if (!M.ModuleOffsetMap.empty()) 8003 ReadModuleOffsetMap(M); 8004 8005 ContinuousRangeMap<uint32_t, int, 2>::iterator I 8006 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS); 8007 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap"); 8008 8009 return LocalID + I->second; 8010 } 8011 8012 serialization::SubmoduleID 8013 ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) { 8014 if (LocalID < NUM_PREDEF_SUBMODULE_IDS) 8015 return LocalID; 8016 8017 if (!M.ModuleOffsetMap.empty()) 8018 ReadModuleOffsetMap(M); 8019 8020 ContinuousRangeMap<uint32_t, int, 2>::iterator I 8021 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS); 8022 assert(I != M.SubmoduleRemap.end() 8023 && "Invalid index into submodule index remap"); 8024 8025 return LocalID + I->second; 8026 } 8027 8028 Module *ASTReader::getSubmodule(SubmoduleID GlobalID) { 8029 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) { 8030 assert(GlobalID == 0 && "Unhandled global submodule ID"); 8031 return nullptr; 8032 } 8033 8034 if (GlobalID > SubmodulesLoaded.size()) { 8035 Error("submodule ID out of range in AST file"); 8036 return nullptr; 8037 } 8038 8039 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS]; 8040 } 8041 8042 Module *ASTReader::getModule(unsigned ID) { 8043 return getSubmodule(ID); 8044 } 8045 8046 ModuleFile *ASTReader::getLocalModuleFile(ModuleFile &F, unsigned ID) { 8047 if (ID & 1) { 8048 // It's a module, look it up by submodule ID. 8049 auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(F, ID >> 1)); 8050 return I == GlobalSubmoduleMap.end() ? nullptr : I->second; 8051 } else { 8052 // It's a prefix (preamble, PCH, ...). Look it up by index. 8053 unsigned IndexFromEnd = ID >> 1; 8054 assert(IndexFromEnd && "got reference to unknown module file"); 8055 return getModuleManager().pch_modules().end()[-IndexFromEnd]; 8056 } 8057 } 8058 8059 unsigned ASTReader::getModuleFileID(ModuleFile *F) { 8060 if (!F) 8061 return 1; 8062 8063 // For a file representing a module, use the submodule ID of the top-level 8064 // module as the file ID. For any other kind of file, the number of such 8065 // files loaded beforehand will be the same on reload. 8066 // FIXME: Is this true even if we have an explicit module file and a PCH? 8067 if (F->isModule()) 8068 return ((F->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1; 8069 8070 auto PCHModules = getModuleManager().pch_modules(); 8071 auto I = std::find(PCHModules.begin(), PCHModules.end(), F); 8072 assert(I != PCHModules.end() && "emitting reference to unknown file"); 8073 return (I - PCHModules.end()) << 1; 8074 } 8075 8076 llvm::Optional<ExternalASTSource::ASTSourceDescriptor> 8077 ASTReader::getSourceDescriptor(unsigned ID) { 8078 if (const Module *M = getSubmodule(ID)) 8079 return ExternalASTSource::ASTSourceDescriptor(*M); 8080 8081 // If there is only a single PCH, return it instead. 8082 // Chained PCH are not suported. 8083 const auto &PCHChain = ModuleMgr.pch_modules(); 8084 if (std::distance(std::begin(PCHChain), std::end(PCHChain))) { 8085 ModuleFile &MF = ModuleMgr.getPrimaryModule(); 8086 StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName); 8087 StringRef FileName = llvm::sys::path::filename(MF.FileName); 8088 return ASTReader::ASTSourceDescriptor(ModuleName, MF.OriginalDir, FileName, 8089 MF.Signature); 8090 } 8091 return None; 8092 } 8093 8094 ExternalASTSource::ExtKind ASTReader::hasExternalDefinitions(unsigned ID) { 8095 const Module *M = getSubmodule(ID); 8096 if (!M || !M->WithCodegen) 8097 return EK_ReplyHazy; 8098 8099 ModuleFile *MF = ModuleMgr.lookup(M->getASTFile()); 8100 assert(MF); // ? 8101 if (MF->Kind == ModuleKind::MK_MainFile) 8102 return EK_Never; 8103 return EK_Always; 8104 } 8105 8106 Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) { 8107 return DecodeSelector(getGlobalSelectorID(M, LocalID)); 8108 } 8109 8110 Selector ASTReader::DecodeSelector(serialization::SelectorID ID) { 8111 if (ID == 0) 8112 return Selector(); 8113 8114 if (ID > SelectorsLoaded.size()) { 8115 Error("selector ID out of range in AST file"); 8116 return Selector(); 8117 } 8118 8119 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) { 8120 // Load this selector from the selector table. 8121 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID); 8122 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map"); 8123 ModuleFile &M = *I->second; 8124 ASTSelectorLookupTrait Trait(*this, M); 8125 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS; 8126 SelectorsLoaded[ID - 1] = 8127 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0); 8128 if (DeserializationListener) 8129 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]); 8130 } 8131 8132 return SelectorsLoaded[ID - 1]; 8133 } 8134 8135 Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) { 8136 return DecodeSelector(ID); 8137 } 8138 8139 uint32_t ASTReader::GetNumExternalSelectors() { 8140 // ID 0 (the null selector) is considered an external selector. 8141 return getTotalNumSelectors() + 1; 8142 } 8143 8144 serialization::SelectorID 8145 ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const { 8146 if (LocalID < NUM_PREDEF_SELECTOR_IDS) 8147 return LocalID; 8148 8149 if (!M.ModuleOffsetMap.empty()) 8150 ReadModuleOffsetMap(M); 8151 8152 ContinuousRangeMap<uint32_t, int, 2>::iterator I 8153 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS); 8154 assert(I != M.SelectorRemap.end() 8155 && "Invalid index into selector index remap"); 8156 8157 return LocalID + I->second; 8158 } 8159 8160 DeclarationName 8161 ASTReader::ReadDeclarationName(ModuleFile &F, 8162 const RecordData &Record, unsigned &Idx) { 8163 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++]; 8164 switch (Kind) { 8165 case DeclarationName::Identifier: 8166 return DeclarationName(GetIdentifierInfo(F, Record, Idx)); 8167 8168 case DeclarationName::ObjCZeroArgSelector: 8169 case DeclarationName::ObjCOneArgSelector: 8170 case DeclarationName::ObjCMultiArgSelector: 8171 return DeclarationName(ReadSelector(F, Record, Idx)); 8172 8173 case DeclarationName::CXXConstructorName: 8174 return Context.DeclarationNames.getCXXConstructorName( 8175 Context.getCanonicalType(readType(F, Record, Idx))); 8176 8177 case DeclarationName::CXXDestructorName: 8178 return Context.DeclarationNames.getCXXDestructorName( 8179 Context.getCanonicalType(readType(F, Record, Idx))); 8180 8181 case DeclarationName::CXXDeductionGuideName: 8182 return Context.DeclarationNames.getCXXDeductionGuideName( 8183 ReadDeclAs<TemplateDecl>(F, Record, Idx)); 8184 8185 case DeclarationName::CXXConversionFunctionName: 8186 return Context.DeclarationNames.getCXXConversionFunctionName( 8187 Context.getCanonicalType(readType(F, Record, Idx))); 8188 8189 case DeclarationName::CXXOperatorName: 8190 return Context.DeclarationNames.getCXXOperatorName( 8191 (OverloadedOperatorKind)Record[Idx++]); 8192 8193 case DeclarationName::CXXLiteralOperatorName: 8194 return Context.DeclarationNames.getCXXLiteralOperatorName( 8195 GetIdentifierInfo(F, Record, Idx)); 8196 8197 case DeclarationName::CXXUsingDirective: 8198 return DeclarationName::getUsingDirectiveName(); 8199 } 8200 8201 llvm_unreachable("Invalid NameKind!"); 8202 } 8203 8204 void ASTReader::ReadDeclarationNameLoc(ModuleFile &F, 8205 DeclarationNameLoc &DNLoc, 8206 DeclarationName Name, 8207 const RecordData &Record, unsigned &Idx) { 8208 switch (Name.getNameKind()) { 8209 case DeclarationName::CXXConstructorName: 8210 case DeclarationName::CXXDestructorName: 8211 case DeclarationName::CXXConversionFunctionName: 8212 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx); 8213 break; 8214 8215 case DeclarationName::CXXOperatorName: 8216 DNLoc.CXXOperatorName.BeginOpNameLoc 8217 = ReadSourceLocation(F, Record, Idx).getRawEncoding(); 8218 DNLoc.CXXOperatorName.EndOpNameLoc 8219 = ReadSourceLocation(F, Record, Idx).getRawEncoding(); 8220 break; 8221 8222 case DeclarationName::CXXLiteralOperatorName: 8223 DNLoc.CXXLiteralOperatorName.OpNameLoc 8224 = ReadSourceLocation(F, Record, Idx).getRawEncoding(); 8225 break; 8226 8227 case DeclarationName::Identifier: 8228 case DeclarationName::ObjCZeroArgSelector: 8229 case DeclarationName::ObjCOneArgSelector: 8230 case DeclarationName::ObjCMultiArgSelector: 8231 case DeclarationName::CXXUsingDirective: 8232 case DeclarationName::CXXDeductionGuideName: 8233 break; 8234 } 8235 } 8236 8237 void ASTReader::ReadDeclarationNameInfo(ModuleFile &F, 8238 DeclarationNameInfo &NameInfo, 8239 const RecordData &Record, unsigned &Idx) { 8240 NameInfo.setName(ReadDeclarationName(F, Record, Idx)); 8241 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx)); 8242 DeclarationNameLoc DNLoc; 8243 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx); 8244 NameInfo.setInfo(DNLoc); 8245 } 8246 8247 void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info, 8248 const RecordData &Record, unsigned &Idx) { 8249 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx); 8250 unsigned NumTPLists = Record[Idx++]; 8251 Info.NumTemplParamLists = NumTPLists; 8252 if (NumTPLists) { 8253 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists]; 8254 for (unsigned i = 0; i != NumTPLists; ++i) 8255 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx); 8256 } 8257 } 8258 8259 TemplateName 8260 ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record, 8261 unsigned &Idx) { 8262 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++]; 8263 switch (Kind) { 8264 case TemplateName::Template: 8265 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx)); 8266 8267 case TemplateName::OverloadedTemplate: { 8268 unsigned size = Record[Idx++]; 8269 UnresolvedSet<8> Decls; 8270 while (size--) 8271 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx)); 8272 8273 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end()); 8274 } 8275 8276 case TemplateName::QualifiedTemplate: { 8277 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx); 8278 bool hasTemplKeyword = Record[Idx++]; 8279 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx); 8280 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template); 8281 } 8282 8283 case TemplateName::DependentTemplate: { 8284 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx); 8285 if (Record[Idx++]) // isIdentifier 8286 return Context.getDependentTemplateName(NNS, 8287 GetIdentifierInfo(F, Record, 8288 Idx)); 8289 return Context.getDependentTemplateName(NNS, 8290 (OverloadedOperatorKind)Record[Idx++]); 8291 } 8292 8293 case TemplateName::SubstTemplateTemplateParm: { 8294 TemplateTemplateParmDecl *param 8295 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx); 8296 if (!param) return TemplateName(); 8297 TemplateName replacement = ReadTemplateName(F, Record, Idx); 8298 return Context.getSubstTemplateTemplateParm(param, replacement); 8299 } 8300 8301 case TemplateName::SubstTemplateTemplateParmPack: { 8302 TemplateTemplateParmDecl *Param 8303 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx); 8304 if (!Param) 8305 return TemplateName(); 8306 8307 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx); 8308 if (ArgPack.getKind() != TemplateArgument::Pack) 8309 return TemplateName(); 8310 8311 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack); 8312 } 8313 } 8314 8315 llvm_unreachable("Unhandled template name kind!"); 8316 } 8317 8318 TemplateArgument ASTReader::ReadTemplateArgument(ModuleFile &F, 8319 const RecordData &Record, 8320 unsigned &Idx, 8321 bool Canonicalize) { 8322 if (Canonicalize) { 8323 // The caller wants a canonical template argument. Sometimes the AST only 8324 // wants template arguments in canonical form (particularly as the template 8325 // argument lists of template specializations) so ensure we preserve that 8326 // canonical form across serialization. 8327 TemplateArgument Arg = ReadTemplateArgument(F, Record, Idx, false); 8328 return Context.getCanonicalTemplateArgument(Arg); 8329 } 8330 8331 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++]; 8332 switch (Kind) { 8333 case TemplateArgument::Null: 8334 return TemplateArgument(); 8335 case TemplateArgument::Type: 8336 return TemplateArgument(readType(F, Record, Idx)); 8337 case TemplateArgument::Declaration: { 8338 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx); 8339 return TemplateArgument(D, readType(F, Record, Idx)); 8340 } 8341 case TemplateArgument::NullPtr: 8342 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true); 8343 case TemplateArgument::Integral: { 8344 llvm::APSInt Value = ReadAPSInt(Record, Idx); 8345 QualType T = readType(F, Record, Idx); 8346 return TemplateArgument(Context, Value, T); 8347 } 8348 case TemplateArgument::Template: 8349 return TemplateArgument(ReadTemplateName(F, Record, Idx)); 8350 case TemplateArgument::TemplateExpansion: { 8351 TemplateName Name = ReadTemplateName(F, Record, Idx); 8352 Optional<unsigned> NumTemplateExpansions; 8353 if (unsigned NumExpansions = Record[Idx++]) 8354 NumTemplateExpansions = NumExpansions - 1; 8355 return TemplateArgument(Name, NumTemplateExpansions); 8356 } 8357 case TemplateArgument::Expression: 8358 return TemplateArgument(ReadExpr(F)); 8359 case TemplateArgument::Pack: { 8360 unsigned NumArgs = Record[Idx++]; 8361 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs]; 8362 for (unsigned I = 0; I != NumArgs; ++I) 8363 Args[I] = ReadTemplateArgument(F, Record, Idx); 8364 return TemplateArgument(llvm::makeArrayRef(Args, NumArgs)); 8365 } 8366 } 8367 8368 llvm_unreachable("Unhandled template argument kind!"); 8369 } 8370 8371 TemplateParameterList * 8372 ASTReader::ReadTemplateParameterList(ModuleFile &F, 8373 const RecordData &Record, unsigned &Idx) { 8374 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx); 8375 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx); 8376 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx); 8377 8378 unsigned NumParams = Record[Idx++]; 8379 SmallVector<NamedDecl *, 16> Params; 8380 Params.reserve(NumParams); 8381 while (NumParams--) 8382 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx)); 8383 8384 // TODO: Concepts 8385 TemplateParameterList* TemplateParams = 8386 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc, 8387 Params, RAngleLoc, nullptr); 8388 return TemplateParams; 8389 } 8390 8391 void 8392 ASTReader:: 8393 ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs, 8394 ModuleFile &F, const RecordData &Record, 8395 unsigned &Idx, bool Canonicalize) { 8396 unsigned NumTemplateArgs = Record[Idx++]; 8397 TemplArgs.reserve(NumTemplateArgs); 8398 while (NumTemplateArgs--) 8399 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx, Canonicalize)); 8400 } 8401 8402 /// \brief Read a UnresolvedSet structure. 8403 void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set, 8404 const RecordData &Record, unsigned &Idx) { 8405 unsigned NumDecls = Record[Idx++]; 8406 Set.reserve(Context, NumDecls); 8407 while (NumDecls--) { 8408 DeclID ID = ReadDeclID(F, Record, Idx); 8409 AccessSpecifier AS = (AccessSpecifier)Record[Idx++]; 8410 Set.addLazyDecl(Context, ID, AS); 8411 } 8412 } 8413 8414 CXXBaseSpecifier 8415 ASTReader::ReadCXXBaseSpecifier(ModuleFile &F, 8416 const RecordData &Record, unsigned &Idx) { 8417 bool isVirtual = static_cast<bool>(Record[Idx++]); 8418 bool isBaseOfClass = static_cast<bool>(Record[Idx++]); 8419 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]); 8420 bool inheritConstructors = static_cast<bool>(Record[Idx++]); 8421 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx); 8422 SourceRange Range = ReadSourceRange(F, Record, Idx); 8423 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx); 8424 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo, 8425 EllipsisLoc); 8426 Result.setInheritConstructors(inheritConstructors); 8427 return Result; 8428 } 8429 8430 CXXCtorInitializer ** 8431 ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record, 8432 unsigned &Idx) { 8433 unsigned NumInitializers = Record[Idx++]; 8434 assert(NumInitializers && "wrote ctor initializers but have no inits"); 8435 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers]; 8436 for (unsigned i = 0; i != NumInitializers; ++i) { 8437 TypeSourceInfo *TInfo = nullptr; 8438 bool IsBaseVirtual = false; 8439 FieldDecl *Member = nullptr; 8440 IndirectFieldDecl *IndirectMember = nullptr; 8441 8442 CtorInitializerType Type = (CtorInitializerType)Record[Idx++]; 8443 switch (Type) { 8444 case CTOR_INITIALIZER_BASE: 8445 TInfo = GetTypeSourceInfo(F, Record, Idx); 8446 IsBaseVirtual = Record[Idx++]; 8447 break; 8448 8449 case CTOR_INITIALIZER_DELEGATING: 8450 TInfo = GetTypeSourceInfo(F, Record, Idx); 8451 break; 8452 8453 case CTOR_INITIALIZER_MEMBER: 8454 Member = ReadDeclAs<FieldDecl>(F, Record, Idx); 8455 break; 8456 8457 case CTOR_INITIALIZER_INDIRECT_MEMBER: 8458 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx); 8459 break; 8460 } 8461 8462 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx); 8463 Expr *Init = ReadExpr(F); 8464 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx); 8465 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx); 8466 8467 CXXCtorInitializer *BOMInit; 8468 if (Type == CTOR_INITIALIZER_BASE) 8469 BOMInit = new (Context) 8470 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init, 8471 RParenLoc, MemberOrEllipsisLoc); 8472 else if (Type == CTOR_INITIALIZER_DELEGATING) 8473 BOMInit = new (Context) 8474 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc); 8475 else if (Member) 8476 BOMInit = new (Context) 8477 CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc, LParenLoc, 8478 Init, RParenLoc); 8479 else 8480 BOMInit = new (Context) 8481 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc, 8482 LParenLoc, Init, RParenLoc); 8483 8484 if (/*IsWritten*/Record[Idx++]) { 8485 unsigned SourceOrder = Record[Idx++]; 8486 BOMInit->setSourceOrder(SourceOrder); 8487 } 8488 8489 CtorInitializers[i] = BOMInit; 8490 } 8491 8492 return CtorInitializers; 8493 } 8494 8495 NestedNameSpecifier * 8496 ASTReader::ReadNestedNameSpecifier(ModuleFile &F, 8497 const RecordData &Record, unsigned &Idx) { 8498 unsigned N = Record[Idx++]; 8499 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr; 8500 for (unsigned I = 0; I != N; ++I) { 8501 NestedNameSpecifier::SpecifierKind Kind 8502 = (NestedNameSpecifier::SpecifierKind)Record[Idx++]; 8503 switch (Kind) { 8504 case NestedNameSpecifier::Identifier: { 8505 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx); 8506 NNS = NestedNameSpecifier::Create(Context, Prev, II); 8507 break; 8508 } 8509 8510 case NestedNameSpecifier::Namespace: { 8511 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx); 8512 NNS = NestedNameSpecifier::Create(Context, Prev, NS); 8513 break; 8514 } 8515 8516 case NestedNameSpecifier::NamespaceAlias: { 8517 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx); 8518 NNS = NestedNameSpecifier::Create(Context, Prev, Alias); 8519 break; 8520 } 8521 8522 case NestedNameSpecifier::TypeSpec: 8523 case NestedNameSpecifier::TypeSpecWithTemplate: { 8524 const Type *T = readType(F, Record, Idx).getTypePtrOrNull(); 8525 if (!T) 8526 return nullptr; 8527 8528 bool Template = Record[Idx++]; 8529 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T); 8530 break; 8531 } 8532 8533 case NestedNameSpecifier::Global: { 8534 NNS = NestedNameSpecifier::GlobalSpecifier(Context); 8535 // No associated value, and there can't be a prefix. 8536 break; 8537 } 8538 8539 case NestedNameSpecifier::Super: { 8540 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx); 8541 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD); 8542 break; 8543 } 8544 } 8545 Prev = NNS; 8546 } 8547 return NNS; 8548 } 8549 8550 NestedNameSpecifierLoc 8551 ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record, 8552 unsigned &Idx) { 8553 unsigned N = Record[Idx++]; 8554 NestedNameSpecifierLocBuilder Builder; 8555 for (unsigned I = 0; I != N; ++I) { 8556 NestedNameSpecifier::SpecifierKind Kind 8557 = (NestedNameSpecifier::SpecifierKind)Record[Idx++]; 8558 switch (Kind) { 8559 case NestedNameSpecifier::Identifier: { 8560 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx); 8561 SourceRange Range = ReadSourceRange(F, Record, Idx); 8562 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd()); 8563 break; 8564 } 8565 8566 case NestedNameSpecifier::Namespace: { 8567 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx); 8568 SourceRange Range = ReadSourceRange(F, Record, Idx); 8569 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd()); 8570 break; 8571 } 8572 8573 case NestedNameSpecifier::NamespaceAlias: { 8574 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx); 8575 SourceRange Range = ReadSourceRange(F, Record, Idx); 8576 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd()); 8577 break; 8578 } 8579 8580 case NestedNameSpecifier::TypeSpec: 8581 case NestedNameSpecifier::TypeSpecWithTemplate: { 8582 bool Template = Record[Idx++]; 8583 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx); 8584 if (!T) 8585 return NestedNameSpecifierLoc(); 8586 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx); 8587 8588 // FIXME: 'template' keyword location not saved anywhere, so we fake it. 8589 Builder.Extend(Context, 8590 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(), 8591 T->getTypeLoc(), ColonColonLoc); 8592 break; 8593 } 8594 8595 case NestedNameSpecifier::Global: { 8596 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx); 8597 Builder.MakeGlobal(Context, ColonColonLoc); 8598 break; 8599 } 8600 8601 case NestedNameSpecifier::Super: { 8602 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx); 8603 SourceRange Range = ReadSourceRange(F, Record, Idx); 8604 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd()); 8605 break; 8606 } 8607 } 8608 } 8609 8610 return Builder.getWithLocInContext(Context); 8611 } 8612 8613 SourceRange 8614 ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record, 8615 unsigned &Idx) { 8616 SourceLocation beg = ReadSourceLocation(F, Record, Idx); 8617 SourceLocation end = ReadSourceLocation(F, Record, Idx); 8618 return SourceRange(beg, end); 8619 } 8620 8621 /// \brief Read an integral value 8622 llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) { 8623 unsigned BitWidth = Record[Idx++]; 8624 unsigned NumWords = llvm::APInt::getNumWords(BitWidth); 8625 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]); 8626 Idx += NumWords; 8627 return Result; 8628 } 8629 8630 /// \brief Read a signed integral value 8631 llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) { 8632 bool isUnsigned = Record[Idx++]; 8633 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned); 8634 } 8635 8636 /// \brief Read a floating-point value 8637 llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record, 8638 const llvm::fltSemantics &Sem, 8639 unsigned &Idx) { 8640 return llvm::APFloat(Sem, ReadAPInt(Record, Idx)); 8641 } 8642 8643 // \brief Read a string 8644 std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) { 8645 unsigned Len = Record[Idx++]; 8646 std::string Result(Record.data() + Idx, Record.data() + Idx + Len); 8647 Idx += Len; 8648 return Result; 8649 } 8650 8651 std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record, 8652 unsigned &Idx) { 8653 std::string Filename = ReadString(Record, Idx); 8654 ResolveImportedPath(F, Filename); 8655 return Filename; 8656 } 8657 8658 VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record, 8659 unsigned &Idx) { 8660 unsigned Major = Record[Idx++]; 8661 unsigned Minor = Record[Idx++]; 8662 unsigned Subminor = Record[Idx++]; 8663 if (Minor == 0) 8664 return VersionTuple(Major); 8665 if (Subminor == 0) 8666 return VersionTuple(Major, Minor - 1); 8667 return VersionTuple(Major, Minor - 1, Subminor - 1); 8668 } 8669 8670 CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F, 8671 const RecordData &Record, 8672 unsigned &Idx) { 8673 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx); 8674 return CXXTemporary::Create(Context, Decl); 8675 } 8676 8677 DiagnosticBuilder ASTReader::Diag(unsigned DiagID) const { 8678 return Diag(CurrentImportLoc, DiagID); 8679 } 8680 8681 DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) const { 8682 return Diags.Report(Loc, DiagID); 8683 } 8684 8685 /// \brief Retrieve the identifier table associated with the 8686 /// preprocessor. 8687 IdentifierTable &ASTReader::getIdentifierTable() { 8688 return PP.getIdentifierTable(); 8689 } 8690 8691 /// \brief Record that the given ID maps to the given switch-case 8692 /// statement. 8693 void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) { 8694 assert((*CurrSwitchCaseStmts)[ID] == nullptr && 8695 "Already have a SwitchCase with this ID"); 8696 (*CurrSwitchCaseStmts)[ID] = SC; 8697 } 8698 8699 /// \brief Retrieve the switch-case statement with the given ID. 8700 SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) { 8701 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID"); 8702 return (*CurrSwitchCaseStmts)[ID]; 8703 } 8704 8705 void ASTReader::ClearSwitchCaseIDs() { 8706 CurrSwitchCaseStmts->clear(); 8707 } 8708 8709 void ASTReader::ReadComments() { 8710 std::vector<RawComment *> Comments; 8711 for (SmallVectorImpl<std::pair<BitstreamCursor, 8712 serialization::ModuleFile *> >::iterator 8713 I = CommentsCursors.begin(), 8714 E = CommentsCursors.end(); 8715 I != E; ++I) { 8716 Comments.clear(); 8717 BitstreamCursor &Cursor = I->first; 8718 serialization::ModuleFile &F = *I->second; 8719 SavedStreamPosition SavedPosition(Cursor); 8720 8721 RecordData Record; 8722 while (true) { 8723 llvm::BitstreamEntry Entry = 8724 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd); 8725 8726 switch (Entry.Kind) { 8727 case llvm::BitstreamEntry::SubBlock: // Handled for us already. 8728 case llvm::BitstreamEntry::Error: 8729 Error("malformed block record in AST file"); 8730 return; 8731 case llvm::BitstreamEntry::EndBlock: 8732 goto NextCursor; 8733 case llvm::BitstreamEntry::Record: 8734 // The interesting case. 8735 break; 8736 } 8737 8738 // Read a record. 8739 Record.clear(); 8740 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) { 8741 case COMMENTS_RAW_COMMENT: { 8742 unsigned Idx = 0; 8743 SourceRange SR = ReadSourceRange(F, Record, Idx); 8744 RawComment::CommentKind Kind = 8745 (RawComment::CommentKind) Record[Idx++]; 8746 bool IsTrailingComment = Record[Idx++]; 8747 bool IsAlmostTrailingComment = Record[Idx++]; 8748 Comments.push_back(new (Context) RawComment( 8749 SR, Kind, IsTrailingComment, IsAlmostTrailingComment, 8750 Context.getLangOpts().CommentOpts.ParseAllComments)); 8751 break; 8752 } 8753 } 8754 } 8755 NextCursor: 8756 // De-serialized SourceLocations get negative FileIDs for other modules, 8757 // potentially invalidating the original order. Sort it again. 8758 std::sort(Comments.begin(), Comments.end(), 8759 BeforeThanCompare<RawComment>(SourceMgr)); 8760 Context.Comments.addDeserializedComments(Comments); 8761 } 8762 } 8763 8764 void ASTReader::visitInputFiles(serialization::ModuleFile &MF, 8765 bool IncludeSystem, bool Complain, 8766 llvm::function_ref<void(const serialization::InputFile &IF, 8767 bool isSystem)> Visitor) { 8768 unsigned NumUserInputs = MF.NumUserInputFiles; 8769 unsigned NumInputs = MF.InputFilesLoaded.size(); 8770 assert(NumUserInputs <= NumInputs); 8771 unsigned N = IncludeSystem ? NumInputs : NumUserInputs; 8772 for (unsigned I = 0; I < N; ++I) { 8773 bool IsSystem = I >= NumUserInputs; 8774 InputFile IF = getInputFile(MF, I+1, Complain); 8775 Visitor(IF, IsSystem); 8776 } 8777 } 8778 8779 std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) { 8780 // If we know the owning module, use it. 8781 if (Module *M = D->getImportedOwningModule()) 8782 return M->getFullModuleName(); 8783 8784 // Otherwise, use the name of the top-level module the decl is within. 8785 if (ModuleFile *M = getOwningModuleFile(D)) 8786 return M->ModuleName; 8787 8788 // Not from a module. 8789 return ""; 8790 } 8791 8792 void ASTReader::finishPendingActions() { 8793 while (!PendingIdentifierInfos.empty() || 8794 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() || 8795 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() || 8796 !PendingUpdateRecords.empty()) { 8797 // If any identifiers with corresponding top-level declarations have 8798 // been loaded, load those declarations now. 8799 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> > 8800 TopLevelDeclsMap; 8801 TopLevelDeclsMap TopLevelDecls; 8802 8803 while (!PendingIdentifierInfos.empty()) { 8804 IdentifierInfo *II = PendingIdentifierInfos.back().first; 8805 SmallVector<uint32_t, 4> DeclIDs = 8806 std::move(PendingIdentifierInfos.back().second); 8807 PendingIdentifierInfos.pop_back(); 8808 8809 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]); 8810 } 8811 8812 // For each decl chain that we wanted to complete while deserializing, mark 8813 // it as "still needs to be completed". 8814 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) { 8815 markIncompleteDeclChain(PendingIncompleteDeclChains[I]); 8816 } 8817 PendingIncompleteDeclChains.clear(); 8818 8819 // Load pending declaration chains. 8820 for (unsigned I = 0; I != PendingDeclChains.size(); ++I) 8821 loadPendingDeclChain(PendingDeclChains[I].first, PendingDeclChains[I].second); 8822 PendingDeclChains.clear(); 8823 8824 // Make the most recent of the top-level declarations visible. 8825 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(), 8826 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) { 8827 IdentifierInfo *II = TLD->first; 8828 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) { 8829 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II); 8830 } 8831 } 8832 8833 // Load any pending macro definitions. 8834 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) { 8835 IdentifierInfo *II = PendingMacroIDs.begin()[I].first; 8836 SmallVector<PendingMacroInfo, 2> GlobalIDs; 8837 GlobalIDs.swap(PendingMacroIDs.begin()[I].second); 8838 // Initialize the macro history from chained-PCHs ahead of module imports. 8839 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs; 8840 ++IDIdx) { 8841 const PendingMacroInfo &Info = GlobalIDs[IDIdx]; 8842 if (!Info.M->isModule()) 8843 resolvePendingMacro(II, Info); 8844 } 8845 // Handle module imports. 8846 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs; 8847 ++IDIdx) { 8848 const PendingMacroInfo &Info = GlobalIDs[IDIdx]; 8849 if (Info.M->isModule()) 8850 resolvePendingMacro(II, Info); 8851 } 8852 } 8853 PendingMacroIDs.clear(); 8854 8855 // Wire up the DeclContexts for Decls that we delayed setting until 8856 // recursive loading is completed. 8857 while (!PendingDeclContextInfos.empty()) { 8858 PendingDeclContextInfo Info = PendingDeclContextInfos.front(); 8859 PendingDeclContextInfos.pop_front(); 8860 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC)); 8861 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC)); 8862 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext()); 8863 } 8864 8865 // Perform any pending declaration updates. 8866 while (!PendingUpdateRecords.empty()) { 8867 auto Update = PendingUpdateRecords.pop_back_val(); 8868 ReadingKindTracker ReadingKind(Read_Decl, *this); 8869 loadDeclUpdateRecords(Update.first, Update.second); 8870 } 8871 } 8872 8873 // At this point, all update records for loaded decls are in place, so any 8874 // fake class definitions should have become real. 8875 assert(PendingFakeDefinitionData.empty() && 8876 "faked up a class definition but never saw the real one"); 8877 8878 // If we deserialized any C++ or Objective-C class definitions, any 8879 // Objective-C protocol definitions, or any redeclarable templates, make sure 8880 // that all redeclarations point to the definitions. Note that this can only 8881 // happen now, after the redeclaration chains have been fully wired. 8882 for (Decl *D : PendingDefinitions) { 8883 if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 8884 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) { 8885 // Make sure that the TagType points at the definition. 8886 const_cast<TagType*>(TagT)->decl = TD; 8887 } 8888 8889 if (auto RD = dyn_cast<CXXRecordDecl>(D)) { 8890 for (auto *R = getMostRecentExistingDecl(RD); R; 8891 R = R->getPreviousDecl()) { 8892 assert((R == D) == 8893 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() && 8894 "declaration thinks it's the definition but it isn't"); 8895 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData; 8896 } 8897 } 8898 8899 continue; 8900 } 8901 8902 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) { 8903 // Make sure that the ObjCInterfaceType points at the definition. 8904 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl)) 8905 ->Decl = ID; 8906 8907 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl()) 8908 cast<ObjCInterfaceDecl>(R)->Data = ID->Data; 8909 8910 continue; 8911 } 8912 8913 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) { 8914 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl()) 8915 cast<ObjCProtocolDecl>(R)->Data = PD->Data; 8916 8917 continue; 8918 } 8919 8920 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl(); 8921 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl()) 8922 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common; 8923 } 8924 PendingDefinitions.clear(); 8925 8926 // Load the bodies of any functions or methods we've encountered. We do 8927 // this now (delayed) so that we can be sure that the declaration chains 8928 // have been fully wired up (hasBody relies on this). 8929 // FIXME: We shouldn't require complete redeclaration chains here. 8930 for (PendingBodiesMap::iterator PB = PendingBodies.begin(), 8931 PBEnd = PendingBodies.end(); 8932 PB != PBEnd; ++PB) { 8933 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) { 8934 // FIXME: Check for =delete/=default? 8935 // FIXME: Complain about ODR violations here? 8936 const FunctionDecl *Defn = nullptr; 8937 if (!getContext().getLangOpts().Modules || !FD->hasBody(Defn)) 8938 FD->setLazyBody(PB->second); 8939 else 8940 mergeDefinitionVisibility(const_cast<FunctionDecl*>(Defn), FD); 8941 continue; 8942 } 8943 8944 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first); 8945 if (!getContext().getLangOpts().Modules || !MD->hasBody()) 8946 MD->setLazyBody(PB->second); 8947 } 8948 PendingBodies.clear(); 8949 8950 // Do some cleanup. 8951 for (auto *ND : PendingMergedDefinitionsToDeduplicate) 8952 getContext().deduplicateMergedDefinitonsFor(ND); 8953 PendingMergedDefinitionsToDeduplicate.clear(); 8954 } 8955 8956 void ASTReader::diagnoseOdrViolations() { 8957 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty()) 8958 return; 8959 8960 // Trigger the import of the full definition of each class that had any 8961 // odr-merging problems, so we can produce better diagnostics for them. 8962 // These updates may in turn find and diagnose some ODR failures, so take 8963 // ownership of the set first. 8964 auto OdrMergeFailures = std::move(PendingOdrMergeFailures); 8965 PendingOdrMergeFailures.clear(); 8966 for (auto &Merge : OdrMergeFailures) { 8967 Merge.first->buildLookup(); 8968 Merge.first->decls_begin(); 8969 Merge.first->bases_begin(); 8970 Merge.first->vbases_begin(); 8971 for (auto *RD : Merge.second) { 8972 RD->decls_begin(); 8973 RD->bases_begin(); 8974 RD->vbases_begin(); 8975 } 8976 } 8977 8978 // For each declaration from a merged context, check that the canonical 8979 // definition of that context also contains a declaration of the same 8980 // entity. 8981 // 8982 // Caution: this loop does things that might invalidate iterators into 8983 // PendingOdrMergeChecks. Don't turn this into a range-based for loop! 8984 while (!PendingOdrMergeChecks.empty()) { 8985 NamedDecl *D = PendingOdrMergeChecks.pop_back_val(); 8986 8987 // FIXME: Skip over implicit declarations for now. This matters for things 8988 // like implicitly-declared special member functions. This isn't entirely 8989 // correct; we can end up with multiple unmerged declarations of the same 8990 // implicit entity. 8991 if (D->isImplicit()) 8992 continue; 8993 8994 DeclContext *CanonDef = D->getDeclContext(); 8995 8996 bool Found = false; 8997 const Decl *DCanon = D->getCanonicalDecl(); 8998 8999 for (auto RI : D->redecls()) { 9000 if (RI->getLexicalDeclContext() == CanonDef) { 9001 Found = true; 9002 break; 9003 } 9004 } 9005 if (Found) 9006 continue; 9007 9008 // Quick check failed, time to do the slow thing. Note, we can't just 9009 // look up the name of D in CanonDef here, because the member that is 9010 // in CanonDef might not be found by name lookup (it might have been 9011 // replaced by a more recent declaration in the lookup table), and we 9012 // can't necessarily find it in the redeclaration chain because it might 9013 // be merely mergeable, not redeclarable. 9014 llvm::SmallVector<const NamedDecl*, 4> Candidates; 9015 for (auto *CanonMember : CanonDef->decls()) { 9016 if (CanonMember->getCanonicalDecl() == DCanon) { 9017 // This can happen if the declaration is merely mergeable and not 9018 // actually redeclarable (we looked for redeclarations earlier). 9019 // 9020 // FIXME: We should be able to detect this more efficiently, without 9021 // pulling in all of the members of CanonDef. 9022 Found = true; 9023 break; 9024 } 9025 if (auto *ND = dyn_cast<NamedDecl>(CanonMember)) 9026 if (ND->getDeclName() == D->getDeclName()) 9027 Candidates.push_back(ND); 9028 } 9029 9030 if (!Found) { 9031 // The AST doesn't like TagDecls becoming invalid after they've been 9032 // completed. We only really need to mark FieldDecls as invalid here. 9033 if (!isa<TagDecl>(D)) 9034 D->setInvalidDecl(); 9035 9036 // Ensure we don't accidentally recursively enter deserialization while 9037 // we're producing our diagnostic. 9038 Deserializing RecursionGuard(this); 9039 9040 std::string CanonDefModule = 9041 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef)); 9042 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl) 9043 << D << getOwningModuleNameForDiagnostic(D) 9044 << CanonDef << CanonDefModule.empty() << CanonDefModule; 9045 9046 if (Candidates.empty()) 9047 Diag(cast<Decl>(CanonDef)->getLocation(), 9048 diag::note_module_odr_violation_no_possible_decls) << D; 9049 else { 9050 for (unsigned I = 0, N = Candidates.size(); I != N; ++I) 9051 Diag(Candidates[I]->getLocation(), 9052 diag::note_module_odr_violation_possible_decl) 9053 << Candidates[I]; 9054 } 9055 9056 DiagnosedOdrMergeFailures.insert(CanonDef); 9057 } 9058 } 9059 9060 if (OdrMergeFailures.empty()) 9061 return; 9062 9063 // Ensure we don't accidentally recursively enter deserialization while 9064 // we're producing our diagnostics. 9065 Deserializing RecursionGuard(this); 9066 9067 // Issue any pending ODR-failure diagnostics. 9068 for (auto &Merge : OdrMergeFailures) { 9069 // If we've already pointed out a specific problem with this class, don't 9070 // bother issuing a general "something's different" diagnostic. 9071 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second) 9072 continue; 9073 9074 bool Diagnosed = false; 9075 CXXRecordDecl *FirstRecord = Merge.first; 9076 std::string FirstModule = getOwningModuleNameForDiagnostic(FirstRecord); 9077 for (CXXRecordDecl *SecondRecord : Merge.second) { 9078 // Multiple different declarations got merged together; tell the user 9079 // where they came from. 9080 if (FirstRecord == SecondRecord) 9081 continue; 9082 9083 std::string SecondModule = getOwningModuleNameForDiagnostic(SecondRecord); 9084 using DeclHashes = llvm::SmallVector<std::pair<Decl *, unsigned>, 4>; 9085 DeclHashes FirstHashes; 9086 DeclHashes SecondHashes; 9087 ODRHash Hash; 9088 9089 auto PopulateHashes = [&Hash, FirstRecord](DeclHashes &Hashes, 9090 CXXRecordDecl *Record) { 9091 for (auto *D : Record->decls()) { 9092 // Due to decl merging, the first CXXRecordDecl is the parent of 9093 // Decls in both records. 9094 if (!ODRHash::isWhitelistedDecl(D, FirstRecord)) 9095 continue; 9096 Hash.clear(); 9097 Hash.AddSubDecl(D); 9098 Hashes.emplace_back(D, Hash.CalculateHash()); 9099 } 9100 }; 9101 PopulateHashes(FirstHashes, FirstRecord); 9102 PopulateHashes(SecondHashes, SecondRecord); 9103 9104 // Used with err_module_odr_violation_mismatch_decl and 9105 // note_module_odr_violation_mismatch_decl 9106 enum { 9107 EndOfClass, 9108 PublicSpecifer, 9109 PrivateSpecifer, 9110 ProtectedSpecifer, 9111 StaticAssert, 9112 Field, 9113 CXXMethod, 9114 Other 9115 } FirstDiffType = Other, 9116 SecondDiffType = Other; 9117 9118 auto DifferenceSelector = [](Decl *D) { 9119 assert(D && "valid Decl required"); 9120 switch (D->getKind()) { 9121 default: 9122 return Other; 9123 case Decl::AccessSpec: 9124 switch (D->getAccess()) { 9125 case AS_public: 9126 return PublicSpecifer; 9127 case AS_private: 9128 return PrivateSpecifer; 9129 case AS_protected: 9130 return ProtectedSpecifer; 9131 case AS_none: 9132 break; 9133 } 9134 llvm_unreachable("Invalid access specifier"); 9135 case Decl::StaticAssert: 9136 return StaticAssert; 9137 case Decl::Field: 9138 return Field; 9139 case Decl::CXXMethod: 9140 return CXXMethod; 9141 } 9142 }; 9143 9144 Decl *FirstDecl = nullptr; 9145 Decl *SecondDecl = nullptr; 9146 auto FirstIt = FirstHashes.begin(); 9147 auto SecondIt = SecondHashes.begin(); 9148 9149 // If there is a diagnoseable difference, FirstDiffType and 9150 // SecondDiffType will not be Other and FirstDecl and SecondDecl will be 9151 // filled in if not EndOfClass. 9152 while (FirstIt != FirstHashes.end() || SecondIt != SecondHashes.end()) { 9153 if (FirstIt != FirstHashes.end() && SecondIt != SecondHashes.end() && 9154 FirstIt->second == SecondIt->second) { 9155 ++FirstIt; 9156 ++SecondIt; 9157 continue; 9158 } 9159 9160 FirstDecl = FirstIt == FirstHashes.end() ? nullptr : FirstIt->first; 9161 SecondDecl = SecondIt == SecondHashes.end() ? nullptr : SecondIt->first; 9162 9163 FirstDiffType = FirstDecl ? DifferenceSelector(FirstDecl) : EndOfClass; 9164 SecondDiffType = 9165 SecondDecl ? DifferenceSelector(SecondDecl) : EndOfClass; 9166 9167 break; 9168 } 9169 9170 if (FirstDiffType == Other || SecondDiffType == Other) { 9171 // Reaching this point means an unexpected Decl was encountered 9172 // or no difference was detected. This causes a generic error 9173 // message to be emitted. 9174 Diag(FirstRecord->getLocation(), 9175 diag::err_module_odr_violation_different_definitions) 9176 << FirstRecord << FirstModule.empty() << FirstModule; 9177 9178 Diag(SecondRecord->getLocation(), 9179 diag::note_module_odr_violation_different_definitions) 9180 << SecondModule; 9181 Diagnosed = true; 9182 break; 9183 } 9184 9185 if (FirstDiffType != SecondDiffType) { 9186 SourceLocation FirstLoc; 9187 SourceRange FirstRange; 9188 if (FirstDiffType == EndOfClass) { 9189 FirstLoc = FirstRecord->getBraceRange().getEnd(); 9190 } else { 9191 FirstLoc = FirstIt->first->getLocation(); 9192 FirstRange = FirstIt->first->getSourceRange(); 9193 } 9194 Diag(FirstLoc, diag::err_module_odr_violation_mismatch_decl) 9195 << FirstRecord << FirstModule.empty() << FirstModule << FirstRange 9196 << FirstDiffType; 9197 9198 SourceLocation SecondLoc; 9199 SourceRange SecondRange; 9200 if (SecondDiffType == EndOfClass) { 9201 SecondLoc = SecondRecord->getBraceRange().getEnd(); 9202 } else { 9203 SecondLoc = SecondDecl->getLocation(); 9204 SecondRange = SecondDecl->getSourceRange(); 9205 } 9206 Diag(SecondLoc, diag::note_module_odr_violation_mismatch_decl) 9207 << SecondModule << SecondRange << SecondDiffType; 9208 Diagnosed = true; 9209 break; 9210 } 9211 9212 assert(FirstDiffType == SecondDiffType); 9213 9214 // Used with err_module_odr_violation_mismatch_decl_diff and 9215 // note_module_odr_violation_mismatch_decl_diff 9216 enum ODRDeclDifference{ 9217 StaticAssertCondition, 9218 StaticAssertMessage, 9219 StaticAssertOnlyMessage, 9220 FieldName, 9221 FieldTypeName, 9222 FieldSingleBitField, 9223 FieldDifferentWidthBitField, 9224 FieldSingleMutable, 9225 FieldSingleInitializer, 9226 FieldDifferentInitializers, 9227 MethodName, 9228 MethodDeleted, 9229 MethodVirtual, 9230 MethodStatic, 9231 MethodVolatile, 9232 MethodConst, 9233 MethodInline, 9234 }; 9235 9236 // These lambdas have the common portions of the ODR diagnostics. This 9237 // has the same return as Diag(), so addition parameters can be passed 9238 // in with operator<< 9239 auto ODRDiagError = [FirstRecord, &FirstModule, this]( 9240 SourceLocation Loc, SourceRange Range, ODRDeclDifference DiffType) { 9241 return Diag(Loc, diag::err_module_odr_violation_mismatch_decl_diff) 9242 << FirstRecord << FirstModule.empty() << FirstModule << Range 9243 << DiffType; 9244 }; 9245 auto ODRDiagNote = [&SecondModule, this]( 9246 SourceLocation Loc, SourceRange Range, ODRDeclDifference DiffType) { 9247 return Diag(Loc, diag::note_module_odr_violation_mismatch_decl_diff) 9248 << SecondModule << Range << DiffType; 9249 }; 9250 9251 auto ComputeODRHash = [&Hash](const Stmt* S) { 9252 assert(S); 9253 Hash.clear(); 9254 Hash.AddStmt(S); 9255 return Hash.CalculateHash(); 9256 }; 9257 9258 auto ComputeDeclNameODRHash = [&Hash](const DeclarationName Name) { 9259 Hash.clear(); 9260 Hash.AddDeclarationName(Name); 9261 return Hash.CalculateHash(); 9262 }; 9263 9264 switch (FirstDiffType) { 9265 case Other: 9266 case EndOfClass: 9267 case PublicSpecifer: 9268 case PrivateSpecifer: 9269 case ProtectedSpecifer: 9270 llvm_unreachable("Invalid diff type"); 9271 9272 case StaticAssert: { 9273 StaticAssertDecl *FirstSA = cast<StaticAssertDecl>(FirstDecl); 9274 StaticAssertDecl *SecondSA = cast<StaticAssertDecl>(SecondDecl); 9275 9276 Expr *FirstExpr = FirstSA->getAssertExpr(); 9277 Expr *SecondExpr = SecondSA->getAssertExpr(); 9278 unsigned FirstODRHash = ComputeODRHash(FirstExpr); 9279 unsigned SecondODRHash = ComputeODRHash(SecondExpr); 9280 if (FirstODRHash != SecondODRHash) { 9281 ODRDiagError(FirstExpr->getLocStart(), FirstExpr->getSourceRange(), 9282 StaticAssertCondition); 9283 ODRDiagNote(SecondExpr->getLocStart(), 9284 SecondExpr->getSourceRange(), StaticAssertCondition); 9285 Diagnosed = true; 9286 break; 9287 } 9288 9289 StringLiteral *FirstStr = FirstSA->getMessage(); 9290 StringLiteral *SecondStr = SecondSA->getMessage(); 9291 assert((FirstStr || SecondStr) && "Both messages cannot be empty"); 9292 if ((FirstStr && !SecondStr) || (!FirstStr && SecondStr)) { 9293 SourceLocation FirstLoc, SecondLoc; 9294 SourceRange FirstRange, SecondRange; 9295 if (FirstStr) { 9296 FirstLoc = FirstStr->getLocStart(); 9297 FirstRange = FirstStr->getSourceRange(); 9298 } else { 9299 FirstLoc = FirstSA->getLocStart(); 9300 FirstRange = FirstSA->getSourceRange(); 9301 } 9302 if (SecondStr) { 9303 SecondLoc = SecondStr->getLocStart(); 9304 SecondRange = SecondStr->getSourceRange(); 9305 } else { 9306 SecondLoc = SecondSA->getLocStart(); 9307 SecondRange = SecondSA->getSourceRange(); 9308 } 9309 ODRDiagError(FirstLoc, FirstRange, StaticAssertOnlyMessage) 9310 << (FirstStr == nullptr); 9311 ODRDiagNote(SecondLoc, SecondRange, StaticAssertOnlyMessage) 9312 << (SecondStr == nullptr); 9313 Diagnosed = true; 9314 break; 9315 } 9316 9317 if (FirstStr && SecondStr && 9318 FirstStr->getString() != SecondStr->getString()) { 9319 ODRDiagError(FirstStr->getLocStart(), FirstStr->getSourceRange(), 9320 StaticAssertMessage); 9321 ODRDiagNote(SecondStr->getLocStart(), SecondStr->getSourceRange(), 9322 StaticAssertMessage); 9323 Diagnosed = true; 9324 break; 9325 } 9326 break; 9327 } 9328 case Field: { 9329 FieldDecl *FirstField = cast<FieldDecl>(FirstDecl); 9330 FieldDecl *SecondField = cast<FieldDecl>(SecondDecl); 9331 IdentifierInfo *FirstII = FirstField->getIdentifier(); 9332 IdentifierInfo *SecondII = SecondField->getIdentifier(); 9333 if (FirstII->getName() != SecondII->getName()) { 9334 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(), 9335 FieldName) 9336 << FirstII; 9337 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(), 9338 FieldName) 9339 << SecondII; 9340 9341 Diagnosed = true; 9342 break; 9343 } 9344 9345 assert( 9346 Context.hasSameType(FirstField->getType(), SecondField->getType())); 9347 9348 QualType FirstType = FirstField->getType(); 9349 QualType SecondType = SecondField->getType(); 9350 const TypedefType *FirstTypedef = dyn_cast<TypedefType>(FirstType); 9351 const TypedefType *SecondTypedef = dyn_cast<TypedefType>(SecondType); 9352 9353 if ((FirstTypedef && !SecondTypedef) || 9354 (!FirstTypedef && SecondTypedef)) { 9355 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(), 9356 FieldTypeName) 9357 << FirstII << FirstType; 9358 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(), 9359 FieldTypeName) 9360 << SecondII << SecondType; 9361 9362 Diagnosed = true; 9363 break; 9364 } 9365 9366 if (FirstTypedef && SecondTypedef) { 9367 unsigned FirstHash = ComputeDeclNameODRHash( 9368 FirstTypedef->getDecl()->getDeclName()); 9369 unsigned SecondHash = ComputeDeclNameODRHash( 9370 SecondTypedef->getDecl()->getDeclName()); 9371 if (FirstHash != SecondHash) { 9372 ODRDiagError(FirstField->getLocation(), 9373 FirstField->getSourceRange(), FieldTypeName) 9374 << FirstII << FirstType; 9375 ODRDiagNote(SecondField->getLocation(), 9376 SecondField->getSourceRange(), FieldTypeName) 9377 << SecondII << SecondType; 9378 9379 Diagnosed = true; 9380 break; 9381 } 9382 } 9383 9384 const bool IsFirstBitField = FirstField->isBitField(); 9385 const bool IsSecondBitField = SecondField->isBitField(); 9386 if (IsFirstBitField != IsSecondBitField) { 9387 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(), 9388 FieldSingleBitField) 9389 << FirstII << IsFirstBitField; 9390 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(), 9391 FieldSingleBitField) 9392 << SecondII << IsSecondBitField; 9393 Diagnosed = true; 9394 break; 9395 } 9396 9397 if (IsFirstBitField && IsSecondBitField) { 9398 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(), 9399 FieldDifferentWidthBitField) 9400 << FirstII << FirstField->getBitWidth()->getSourceRange(); 9401 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(), 9402 FieldDifferentWidthBitField) 9403 << SecondII << SecondField->getBitWidth()->getSourceRange(); 9404 Diagnosed = true; 9405 break; 9406 } 9407 9408 const bool IsFirstMutable = FirstField->isMutable(); 9409 const bool IsSecondMutable = SecondField->isMutable(); 9410 if (IsFirstMutable != IsSecondMutable) { 9411 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(), 9412 FieldSingleMutable) 9413 << FirstII << IsFirstMutable; 9414 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(), 9415 FieldSingleMutable) 9416 << SecondII << IsSecondMutable; 9417 Diagnosed = true; 9418 break; 9419 } 9420 9421 const Expr *FirstInitializer = FirstField->getInClassInitializer(); 9422 const Expr *SecondInitializer = SecondField->getInClassInitializer(); 9423 if ((!FirstInitializer && SecondInitializer) || 9424 (FirstInitializer && !SecondInitializer)) { 9425 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(), 9426 FieldSingleInitializer) 9427 << FirstII << (FirstInitializer != nullptr); 9428 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(), 9429 FieldSingleInitializer) 9430 << SecondII << (SecondInitializer != nullptr); 9431 Diagnosed = true; 9432 break; 9433 } 9434 9435 if (FirstInitializer && SecondInitializer) { 9436 unsigned FirstInitHash = ComputeODRHash(FirstInitializer); 9437 unsigned SecondInitHash = ComputeODRHash(SecondInitializer); 9438 if (FirstInitHash != SecondInitHash) { 9439 ODRDiagError(FirstField->getLocation(), 9440 FirstField->getSourceRange(), 9441 FieldDifferentInitializers) 9442 << FirstII << FirstInitializer->getSourceRange(); 9443 ODRDiagNote(SecondField->getLocation(), 9444 SecondField->getSourceRange(), 9445 FieldDifferentInitializers) 9446 << SecondII << SecondInitializer->getSourceRange(); 9447 Diagnosed = true; 9448 break; 9449 } 9450 } 9451 9452 break; 9453 } 9454 case CXXMethod: { 9455 const CXXMethodDecl *FirstMethod = cast<CXXMethodDecl>(FirstDecl); 9456 const CXXMethodDecl *SecondMethod = cast<CXXMethodDecl>(SecondDecl); 9457 auto FirstName = FirstMethod->getDeclName(); 9458 auto SecondName = SecondMethod->getDeclName(); 9459 if (FirstName != SecondName) { 9460 ODRDiagError(FirstMethod->getLocation(), 9461 FirstMethod->getSourceRange(), MethodName) 9462 << FirstName; 9463 ODRDiagNote(SecondMethod->getLocation(), 9464 SecondMethod->getSourceRange(), MethodName) 9465 << SecondName; 9466 9467 Diagnosed = true; 9468 break; 9469 } 9470 9471 const bool FirstDeleted = FirstMethod->isDeleted(); 9472 const bool SecondDeleted = SecondMethod->isDeleted(); 9473 if (FirstDeleted != SecondDeleted) { 9474 ODRDiagError(FirstMethod->getLocation(), 9475 FirstMethod->getSourceRange(), MethodDeleted) 9476 << FirstName << FirstDeleted; 9477 9478 ODRDiagNote(SecondMethod->getLocation(), 9479 SecondMethod->getSourceRange(), MethodDeleted) 9480 << SecondName << SecondDeleted; 9481 Diagnosed = true; 9482 break; 9483 } 9484 9485 const bool FirstVirtual = FirstMethod->isVirtualAsWritten(); 9486 const bool SecondVirtual = SecondMethod->isVirtualAsWritten(); 9487 const bool FirstPure = FirstMethod->isPure(); 9488 const bool SecondPure = SecondMethod->isPure(); 9489 if ((FirstVirtual || SecondVirtual) && 9490 (FirstVirtual != SecondVirtual || FirstPure != SecondPure)) { 9491 ODRDiagError(FirstMethod->getLocation(), 9492 FirstMethod->getSourceRange(), MethodVirtual) 9493 << FirstName << FirstPure << FirstVirtual; 9494 ODRDiagNote(SecondMethod->getLocation(), 9495 SecondMethod->getSourceRange(), MethodVirtual) 9496 << SecondName << SecondPure << SecondVirtual; 9497 Diagnosed = true; 9498 break; 9499 } 9500 9501 // CXXMethodDecl::isStatic uses the canonical Decl. With Decl merging, 9502 // FirstDecl is the canonical Decl of SecondDecl, so the storage 9503 // class needs to be checked instead. 9504 const auto FirstStorage = FirstMethod->getStorageClass(); 9505 const auto SecondStorage = SecondMethod->getStorageClass(); 9506 const bool FirstStatic = FirstStorage == SC_Static; 9507 const bool SecondStatic = SecondStorage == SC_Static; 9508 if (FirstStatic != SecondStatic) { 9509 ODRDiagError(FirstMethod->getLocation(), 9510 FirstMethod->getSourceRange(), MethodStatic) 9511 << FirstName << FirstStatic; 9512 ODRDiagNote(SecondMethod->getLocation(), 9513 SecondMethod->getSourceRange(), MethodStatic) 9514 << SecondName << SecondStatic; 9515 Diagnosed = true; 9516 break; 9517 } 9518 9519 const bool FirstVolatile = FirstMethod->isVolatile(); 9520 const bool SecondVolatile = SecondMethod->isVolatile(); 9521 if (FirstVolatile != SecondVolatile) { 9522 ODRDiagError(FirstMethod->getLocation(), 9523 FirstMethod->getSourceRange(), MethodVolatile) 9524 << FirstName << FirstVolatile; 9525 ODRDiagNote(SecondMethod->getLocation(), 9526 SecondMethod->getSourceRange(), MethodVolatile) 9527 << SecondName << SecondVolatile; 9528 Diagnosed = true; 9529 break; 9530 } 9531 9532 const bool FirstConst = FirstMethod->isConst(); 9533 const bool SecondConst = SecondMethod->isConst(); 9534 if (FirstConst != SecondConst) { 9535 ODRDiagError(FirstMethod->getLocation(), 9536 FirstMethod->getSourceRange(), MethodConst) 9537 << FirstName << FirstConst; 9538 ODRDiagNote(SecondMethod->getLocation(), 9539 SecondMethod->getSourceRange(), MethodConst) 9540 << SecondName << SecondConst; 9541 Diagnosed = true; 9542 break; 9543 } 9544 9545 const bool FirstInline = FirstMethod->isInlineSpecified(); 9546 const bool SecondInline = SecondMethod->isInlineSpecified(); 9547 if (FirstInline != SecondInline) { 9548 ODRDiagError(FirstMethod->getLocation(), 9549 FirstMethod->getSourceRange(), MethodInline) 9550 << FirstName << FirstInline; 9551 ODRDiagNote(SecondMethod->getLocation(), 9552 SecondMethod->getSourceRange(), MethodInline) 9553 << SecondName << SecondInline; 9554 Diagnosed = true; 9555 break; 9556 } 9557 9558 break; 9559 } 9560 } 9561 9562 if (Diagnosed == true) 9563 continue; 9564 9565 Diag(FirstRecord->getLocation(), 9566 diag::err_module_odr_violation_different_definitions) 9567 << FirstRecord << FirstModule.empty() << FirstModule; 9568 9569 Diag(SecondRecord->getLocation(), 9570 diag::note_module_odr_violation_different_definitions) 9571 << SecondModule; 9572 Diagnosed = true; 9573 } 9574 9575 if (!Diagnosed) { 9576 // All definitions are updates to the same declaration. This happens if a 9577 // module instantiates the declaration of a class template specialization 9578 // and two or more other modules instantiate its definition. 9579 // 9580 // FIXME: Indicate which modules had instantiations of this definition. 9581 // FIXME: How can this even happen? 9582 Diag(Merge.first->getLocation(), 9583 diag::err_module_odr_violation_different_instantiations) 9584 << Merge.first; 9585 } 9586 } 9587 } 9588 9589 void ASTReader::StartedDeserializing() { 9590 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get()) 9591 ReadTimer->startTimer(); 9592 } 9593 9594 void ASTReader::FinishedDeserializing() { 9595 assert(NumCurrentElementsDeserializing && 9596 "FinishedDeserializing not paired with StartedDeserializing"); 9597 if (NumCurrentElementsDeserializing == 1) { 9598 // We decrease NumCurrentElementsDeserializing only after pending actions 9599 // are finished, to avoid recursively re-calling finishPendingActions(). 9600 finishPendingActions(); 9601 } 9602 --NumCurrentElementsDeserializing; 9603 9604 if (NumCurrentElementsDeserializing == 0) { 9605 // Propagate exception specification updates along redeclaration chains. 9606 while (!PendingExceptionSpecUpdates.empty()) { 9607 auto Updates = std::move(PendingExceptionSpecUpdates); 9608 PendingExceptionSpecUpdates.clear(); 9609 for (auto Update : Updates) { 9610 ProcessingUpdatesRAIIObj ProcessingUpdates(*this); 9611 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>(); 9612 auto ESI = FPT->getExtProtoInfo().ExceptionSpec; 9613 if (auto *Listener = Context.getASTMutationListener()) 9614 Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second)); 9615 for (auto *Redecl : Update.second->redecls()) 9616 Context.adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI); 9617 } 9618 } 9619 9620 if (ReadTimer) 9621 ReadTimer->stopTimer(); 9622 9623 diagnoseOdrViolations(); 9624 9625 // We are not in recursive loading, so it's safe to pass the "interesting" 9626 // decls to the consumer. 9627 if (Consumer) 9628 PassInterestingDeclsToConsumer(); 9629 } 9630 } 9631 9632 void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) { 9633 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) { 9634 // Remove any fake results before adding any real ones. 9635 auto It = PendingFakeLookupResults.find(II); 9636 if (It != PendingFakeLookupResults.end()) { 9637 for (auto *ND : It->second) 9638 SemaObj->IdResolver.RemoveDecl(ND); 9639 // FIXME: this works around module+PCH performance issue. 9640 // Rather than erase the result from the map, which is O(n), just clear 9641 // the vector of NamedDecls. 9642 It->second.clear(); 9643 } 9644 } 9645 9646 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) { 9647 SemaObj->TUScope->AddDecl(D); 9648 } else if (SemaObj->TUScope) { 9649 // Adding the decl to IdResolver may have failed because it was already in 9650 // (even though it was not added in scope). If it is already in, make sure 9651 // it gets in the scope as well. 9652 if (std::find(SemaObj->IdResolver.begin(Name), 9653 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end()) 9654 SemaObj->TUScope->AddDecl(D); 9655 } 9656 } 9657 9658 ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context, 9659 const PCHContainerReader &PCHContainerRdr, 9660 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions, 9661 StringRef isysroot, bool DisableValidation, 9662 bool AllowASTWithCompilerErrors, 9663 bool AllowConfigurationMismatch, bool ValidateSystemInputs, 9664 bool UseGlobalIndex, 9665 std::unique_ptr<llvm::Timer> ReadTimer) 9666 : Listener(DisableValidation 9667 ? cast<ASTReaderListener>(new SimpleASTReaderListener(PP)) 9668 : cast<ASTReaderListener>(new PCHValidator(PP, *this))), 9669 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()), 9670 PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()), PP(PP), 9671 Context(Context), 9672 ModuleMgr(PP.getFileManager(), PP.getPCMCache(), PCHContainerRdr), 9673 PCMCache(PP.getPCMCache()), DummyIdResolver(PP), 9674 ReadTimer(std::move(ReadTimer)), isysroot(isysroot), 9675 DisableValidation(DisableValidation), 9676 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors), 9677 AllowConfigurationMismatch(AllowConfigurationMismatch), 9678 ValidateSystemInputs(ValidateSystemInputs), 9679 UseGlobalIndex(UseGlobalIndex), CurrSwitchCaseStmts(&SwitchCaseStmts) { 9680 SourceMgr.setExternalSLocEntrySource(this); 9681 9682 for (const auto &Ext : Extensions) { 9683 auto BlockName = Ext->getExtensionMetadata().BlockName; 9684 auto Known = ModuleFileExtensions.find(BlockName); 9685 if (Known != ModuleFileExtensions.end()) { 9686 Diags.Report(diag::warn_duplicate_module_file_extension) 9687 << BlockName; 9688 continue; 9689 } 9690 9691 ModuleFileExtensions.insert({BlockName, Ext}); 9692 } 9693 } 9694 9695 ASTReader::~ASTReader() { 9696 if (OwnsDeserializationListener) 9697 delete DeserializationListener; 9698 } 9699 9700 IdentifierResolver &ASTReader::getIdResolver() { 9701 return SemaObj ? SemaObj->IdResolver : DummyIdResolver; 9702 } 9703 9704 unsigned ASTRecordReader::readRecord(llvm::BitstreamCursor &Cursor, 9705 unsigned AbbrevID) { 9706 Idx = 0; 9707 Record.clear(); 9708 return Cursor.readRecord(AbbrevID, Record); 9709 } 9710