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