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