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