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