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