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