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