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