1 //===--- ASTReaderDecl.cpp - Decl Deserialization ---------------*- C++ -*-===// 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 implements the ASTReader::ReadDeclRecord method, which is the 11 // entrypoint for loading a decl. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "ASTCommon.h" 16 #include "ASTReaderInternals.h" 17 #include "clang/AST/ASTContext.h" 18 #include "clang/AST/DeclCXX.h" 19 #include "clang/AST/DeclGroup.h" 20 #include "clang/AST/DeclTemplate.h" 21 #include "clang/AST/DeclVisitor.h" 22 #include "clang/AST/Expr.h" 23 #include "clang/Sema/IdentifierResolver.h" 24 #include "clang/Sema/SemaDiagnostic.h" 25 #include "clang/Serialization/ASTReader.h" 26 #include "llvm/Support/SaveAndRestore.h" 27 28 using namespace clang; 29 using namespace clang::serialization; 30 31 //===----------------------------------------------------------------------===// 32 // Declaration deserialization 33 //===----------------------------------------------------------------------===// 34 35 namespace clang { 36 class ASTDeclReader : public DeclVisitor<ASTDeclReader, void> { 37 ASTReader &Reader; 38 ASTRecordReader &Record; 39 ASTReader::RecordLocation Loc; 40 const DeclID ThisDeclID; 41 const SourceLocation ThisDeclLoc; 42 typedef ASTReader::RecordData RecordData; 43 TypeID TypeIDForTypeDecl; 44 unsigned AnonymousDeclNumber; 45 GlobalDeclID NamedDeclForTagDecl; 46 IdentifierInfo *TypedefNameForLinkage; 47 48 bool HasPendingBody; 49 50 ///\brief A flag to carry the information for a decl from the entity is 51 /// used. We use it to delay the marking of the canonical decl as used until 52 /// the entire declaration is deserialized and merged. 53 bool IsDeclMarkedUsed; 54 55 uint64_t GetCurrentCursorOffset(); 56 57 uint64_t ReadLocalOffset() { 58 uint64_t LocalOffset = Record.readInt(); 59 assert(LocalOffset < Loc.Offset && "offset point after current record"); 60 return LocalOffset ? Loc.Offset - LocalOffset : 0; 61 } 62 63 uint64_t ReadGlobalOffset() { 64 uint64_t Local = ReadLocalOffset(); 65 return Local ? Record.getGlobalBitOffset(Local) : 0; 66 } 67 68 SourceLocation ReadSourceLocation() { 69 return Record.readSourceLocation(); 70 } 71 72 SourceRange ReadSourceRange() { 73 return Record.readSourceRange(); 74 } 75 76 TypeSourceInfo *GetTypeSourceInfo() { 77 return Record.getTypeSourceInfo(); 78 } 79 80 serialization::DeclID ReadDeclID() { 81 return Record.readDeclID(); 82 } 83 84 std::string ReadString() { 85 return Record.readString(); 86 } 87 88 void ReadDeclIDList(SmallVectorImpl<DeclID> &IDs) { 89 for (unsigned I = 0, Size = Record.readInt(); I != Size; ++I) 90 IDs.push_back(ReadDeclID()); 91 } 92 93 Decl *ReadDecl() { 94 return Record.readDecl(); 95 } 96 97 template<typename T> 98 T *ReadDeclAs() { 99 return Record.readDeclAs<T>(); 100 } 101 102 void ReadQualifierInfo(QualifierInfo &Info) { 103 Record.readQualifierInfo(Info); 104 } 105 106 void ReadDeclarationNameLoc(DeclarationNameLoc &DNLoc, DeclarationName Name) { 107 Record.readDeclarationNameLoc(DNLoc, Name); 108 } 109 110 serialization::SubmoduleID readSubmoduleID() { 111 if (Record.getIdx() == Record.size()) 112 return 0; 113 114 return Record.getGlobalSubmoduleID(Record.readInt()); 115 } 116 117 Module *readModule() { 118 return Record.getSubmodule(readSubmoduleID()); 119 } 120 121 void ReadCXXRecordDefinition(CXXRecordDecl *D, bool Update); 122 void ReadCXXDefinitionData(struct CXXRecordDecl::DefinitionData &Data); 123 void MergeDefinitionData(CXXRecordDecl *D, 124 struct CXXRecordDecl::DefinitionData &&NewDD); 125 void ReadObjCDefinitionData(struct ObjCInterfaceDecl::DefinitionData &Data); 126 void MergeDefinitionData(ObjCInterfaceDecl *D, 127 struct ObjCInterfaceDecl::DefinitionData &&NewDD); 128 129 static NamedDecl *getAnonymousDeclForMerging(ASTReader &Reader, 130 DeclContext *DC, 131 unsigned Index); 132 static void setAnonymousDeclForMerging(ASTReader &Reader, DeclContext *DC, 133 unsigned Index, NamedDecl *D); 134 135 /// Results from loading a RedeclarableDecl. 136 class RedeclarableResult { 137 Decl *MergeWith; 138 GlobalDeclID FirstID; 139 bool IsKeyDecl; 140 141 public: 142 RedeclarableResult(Decl *MergeWith, GlobalDeclID FirstID, bool IsKeyDecl) 143 : MergeWith(MergeWith), FirstID(FirstID), IsKeyDecl(IsKeyDecl) {} 144 145 /// \brief Retrieve the first ID. 146 GlobalDeclID getFirstID() const { return FirstID; } 147 148 /// \brief Is this declaration a key declaration? 149 bool isKeyDecl() const { return IsKeyDecl; } 150 151 /// \brief Get a known declaration that this should be merged with, if 152 /// any. 153 Decl *getKnownMergeTarget() const { return MergeWith; } 154 }; 155 156 /// \brief Class used to capture the result of searching for an existing 157 /// declaration of a specific kind and name, along with the ability 158 /// to update the place where this result was found (the declaration 159 /// chain hanging off an identifier or the DeclContext we searched in) 160 /// if requested. 161 class FindExistingResult { 162 ASTReader &Reader; 163 NamedDecl *New; 164 NamedDecl *Existing; 165 bool AddResult; 166 167 unsigned AnonymousDeclNumber; 168 IdentifierInfo *TypedefNameForLinkage; 169 170 void operator=(FindExistingResult &&) = delete; 171 172 public: 173 FindExistingResult(ASTReader &Reader) 174 : Reader(Reader), New(nullptr), Existing(nullptr), AddResult(false), 175 AnonymousDeclNumber(0), TypedefNameForLinkage(nullptr) {} 176 177 FindExistingResult(ASTReader &Reader, NamedDecl *New, NamedDecl *Existing, 178 unsigned AnonymousDeclNumber, 179 IdentifierInfo *TypedefNameForLinkage) 180 : Reader(Reader), New(New), Existing(Existing), AddResult(true), 181 AnonymousDeclNumber(AnonymousDeclNumber), 182 TypedefNameForLinkage(TypedefNameForLinkage) {} 183 184 FindExistingResult(FindExistingResult &&Other) 185 : Reader(Other.Reader), New(Other.New), Existing(Other.Existing), 186 AddResult(Other.AddResult), 187 AnonymousDeclNumber(Other.AnonymousDeclNumber), 188 TypedefNameForLinkage(Other.TypedefNameForLinkage) { 189 Other.AddResult = false; 190 } 191 192 ~FindExistingResult(); 193 194 /// \brief Suppress the addition of this result into the known set of 195 /// names. 196 void suppress() { AddResult = false; } 197 198 operator NamedDecl*() const { return Existing; } 199 200 template<typename T> 201 operator T*() const { return dyn_cast_or_null<T>(Existing); } 202 }; 203 204 static DeclContext *getPrimaryContextForMerging(ASTReader &Reader, 205 DeclContext *DC); 206 FindExistingResult findExisting(NamedDecl *D); 207 208 public: 209 ASTDeclReader(ASTReader &Reader, ASTRecordReader &Record, 210 ASTReader::RecordLocation Loc, 211 DeclID thisDeclID, SourceLocation ThisDeclLoc) 212 : Reader(Reader), Record(Record), Loc(Loc), 213 ThisDeclID(thisDeclID), ThisDeclLoc(ThisDeclLoc), 214 TypeIDForTypeDecl(0), NamedDeclForTagDecl(0), 215 TypedefNameForLinkage(nullptr), HasPendingBody(false), 216 IsDeclMarkedUsed(false) {} 217 218 template <typename DeclT> 219 static Decl *getMostRecentDeclImpl(Redeclarable<DeclT> *D); 220 static Decl *getMostRecentDeclImpl(...); 221 static Decl *getMostRecentDecl(Decl *D); 222 223 template <typename DeclT> 224 static void attachPreviousDeclImpl(ASTReader &Reader, 225 Redeclarable<DeclT> *D, Decl *Previous, 226 Decl *Canon); 227 static void attachPreviousDeclImpl(ASTReader &Reader, ...); 228 static void attachPreviousDecl(ASTReader &Reader, Decl *D, Decl *Previous, 229 Decl *Canon); 230 231 template <typename DeclT> 232 static void attachLatestDeclImpl(Redeclarable<DeclT> *D, Decl *Latest); 233 static void attachLatestDeclImpl(...); 234 static void attachLatestDecl(Decl *D, Decl *latest); 235 236 template <typename DeclT> 237 static void markIncompleteDeclChainImpl(Redeclarable<DeclT> *D); 238 static void markIncompleteDeclChainImpl(...); 239 240 /// \brief Determine whether this declaration has a pending body. 241 bool hasPendingBody() const { return HasPendingBody; } 242 243 void Visit(Decl *D); 244 245 void UpdateDecl(Decl *D); 246 247 static void setNextObjCCategory(ObjCCategoryDecl *Cat, 248 ObjCCategoryDecl *Next) { 249 Cat->NextClassCategory = Next; 250 } 251 252 void VisitDecl(Decl *D); 253 void VisitPragmaCommentDecl(PragmaCommentDecl *D); 254 void VisitPragmaDetectMismatchDecl(PragmaDetectMismatchDecl *D); 255 void VisitTranslationUnitDecl(TranslationUnitDecl *TU); 256 void VisitNamedDecl(NamedDecl *ND); 257 void VisitLabelDecl(LabelDecl *LD); 258 void VisitNamespaceDecl(NamespaceDecl *D); 259 void VisitUsingDirectiveDecl(UsingDirectiveDecl *D); 260 void VisitNamespaceAliasDecl(NamespaceAliasDecl *D); 261 void VisitTypeDecl(TypeDecl *TD); 262 RedeclarableResult VisitTypedefNameDecl(TypedefNameDecl *TD); 263 void VisitTypedefDecl(TypedefDecl *TD); 264 void VisitTypeAliasDecl(TypeAliasDecl *TD); 265 void VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D); 266 RedeclarableResult VisitTagDecl(TagDecl *TD); 267 void VisitEnumDecl(EnumDecl *ED); 268 RedeclarableResult VisitRecordDeclImpl(RecordDecl *RD); 269 void VisitRecordDecl(RecordDecl *RD) { VisitRecordDeclImpl(RD); } 270 RedeclarableResult VisitCXXRecordDeclImpl(CXXRecordDecl *D); 271 void VisitCXXRecordDecl(CXXRecordDecl *D) { VisitCXXRecordDeclImpl(D); } 272 RedeclarableResult VisitClassTemplateSpecializationDeclImpl( 273 ClassTemplateSpecializationDecl *D); 274 void VisitClassTemplateSpecializationDecl( 275 ClassTemplateSpecializationDecl *D) { 276 VisitClassTemplateSpecializationDeclImpl(D); 277 } 278 void VisitClassTemplatePartialSpecializationDecl( 279 ClassTemplatePartialSpecializationDecl *D); 280 void VisitClassScopeFunctionSpecializationDecl( 281 ClassScopeFunctionSpecializationDecl *D); 282 RedeclarableResult 283 VisitVarTemplateSpecializationDeclImpl(VarTemplateSpecializationDecl *D); 284 void VisitVarTemplateSpecializationDecl(VarTemplateSpecializationDecl *D) { 285 VisitVarTemplateSpecializationDeclImpl(D); 286 } 287 void VisitVarTemplatePartialSpecializationDecl( 288 VarTemplatePartialSpecializationDecl *D); 289 void VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D); 290 void VisitValueDecl(ValueDecl *VD); 291 void VisitEnumConstantDecl(EnumConstantDecl *ECD); 292 void VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D); 293 void VisitDeclaratorDecl(DeclaratorDecl *DD); 294 void VisitFunctionDecl(FunctionDecl *FD); 295 void VisitCXXMethodDecl(CXXMethodDecl *D); 296 void VisitCXXConstructorDecl(CXXConstructorDecl *D); 297 void VisitCXXDestructorDecl(CXXDestructorDecl *D); 298 void VisitCXXConversionDecl(CXXConversionDecl *D); 299 void VisitFieldDecl(FieldDecl *FD); 300 void VisitMSPropertyDecl(MSPropertyDecl *FD); 301 void VisitIndirectFieldDecl(IndirectFieldDecl *FD); 302 RedeclarableResult VisitVarDeclImpl(VarDecl *D); 303 void VisitVarDecl(VarDecl *VD) { VisitVarDeclImpl(VD); } 304 void VisitImplicitParamDecl(ImplicitParamDecl *PD); 305 void VisitParmVarDecl(ParmVarDecl *PD); 306 void VisitDecompositionDecl(DecompositionDecl *DD); 307 void VisitBindingDecl(BindingDecl *BD); 308 void VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D); 309 DeclID VisitTemplateDecl(TemplateDecl *D); 310 RedeclarableResult VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D); 311 void VisitClassTemplateDecl(ClassTemplateDecl *D); 312 void VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D); 313 void VisitVarTemplateDecl(VarTemplateDecl *D); 314 void VisitFunctionTemplateDecl(FunctionTemplateDecl *D); 315 void VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D); 316 void VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D); 317 void VisitUsingDecl(UsingDecl *D); 318 void VisitUsingPackDecl(UsingPackDecl *D); 319 void VisitUsingShadowDecl(UsingShadowDecl *D); 320 void VisitConstructorUsingShadowDecl(ConstructorUsingShadowDecl *D); 321 void VisitLinkageSpecDecl(LinkageSpecDecl *D); 322 void VisitExportDecl(ExportDecl *D); 323 void VisitFileScopeAsmDecl(FileScopeAsmDecl *AD); 324 void VisitImportDecl(ImportDecl *D); 325 void VisitAccessSpecDecl(AccessSpecDecl *D); 326 void VisitFriendDecl(FriendDecl *D); 327 void VisitFriendTemplateDecl(FriendTemplateDecl *D); 328 void VisitStaticAssertDecl(StaticAssertDecl *D); 329 void VisitBlockDecl(BlockDecl *BD); 330 void VisitCapturedDecl(CapturedDecl *CD); 331 void VisitEmptyDecl(EmptyDecl *D); 332 333 std::pair<uint64_t, uint64_t> VisitDeclContext(DeclContext *DC); 334 335 template<typename T> 336 RedeclarableResult VisitRedeclarable(Redeclarable<T> *D); 337 338 template<typename T> 339 void mergeRedeclarable(Redeclarable<T> *D, RedeclarableResult &Redecl, 340 DeclID TemplatePatternID = 0); 341 342 template<typename T> 343 void mergeRedeclarable(Redeclarable<T> *D, T *Existing, 344 RedeclarableResult &Redecl, 345 DeclID TemplatePatternID = 0); 346 347 template<typename T> 348 void mergeMergeable(Mergeable<T> *D); 349 350 void mergeTemplatePattern(RedeclarableTemplateDecl *D, 351 RedeclarableTemplateDecl *Existing, 352 DeclID DsID, bool IsKeyDecl); 353 354 ObjCTypeParamList *ReadObjCTypeParamList(); 355 356 // FIXME: Reorder according to DeclNodes.td? 357 void VisitObjCMethodDecl(ObjCMethodDecl *D); 358 void VisitObjCTypeParamDecl(ObjCTypeParamDecl *D); 359 void VisitObjCContainerDecl(ObjCContainerDecl *D); 360 void VisitObjCInterfaceDecl(ObjCInterfaceDecl *D); 361 void VisitObjCIvarDecl(ObjCIvarDecl *D); 362 void VisitObjCProtocolDecl(ObjCProtocolDecl *D); 363 void VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D); 364 void VisitObjCCategoryDecl(ObjCCategoryDecl *D); 365 void VisitObjCImplDecl(ObjCImplDecl *D); 366 void VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D); 367 void VisitObjCImplementationDecl(ObjCImplementationDecl *D); 368 void VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *D); 369 void VisitObjCPropertyDecl(ObjCPropertyDecl *D); 370 void VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D); 371 void VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D); 372 void VisitOMPDeclareReductionDecl(OMPDeclareReductionDecl *D); 373 void VisitOMPCapturedExprDecl(OMPCapturedExprDecl *D); 374 }; 375 } // end namespace clang 376 377 namespace { 378 /// Iterator over the redeclarations of a declaration that have already 379 /// been merged into the same redeclaration chain. 380 template<typename DeclT> 381 class MergedRedeclIterator { 382 DeclT *Start, *Canonical, *Current; 383 public: 384 MergedRedeclIterator() : Current(nullptr) {} 385 MergedRedeclIterator(DeclT *Start) 386 : Start(Start), Canonical(nullptr), Current(Start) {} 387 388 DeclT *operator*() { return Current; } 389 390 MergedRedeclIterator &operator++() { 391 if (Current->isFirstDecl()) { 392 Canonical = Current; 393 Current = Current->getMostRecentDecl(); 394 } else 395 Current = Current->getPreviousDecl(); 396 397 // If we started in the merged portion, we'll reach our start position 398 // eventually. Otherwise, we'll never reach it, but the second declaration 399 // we reached was the canonical declaration, so stop when we see that one 400 // again. 401 if (Current == Start || Current == Canonical) 402 Current = nullptr; 403 return *this; 404 } 405 406 friend bool operator!=(const MergedRedeclIterator &A, 407 const MergedRedeclIterator &B) { 408 return A.Current != B.Current; 409 } 410 }; 411 } // end anonymous namespace 412 413 template <typename DeclT> 414 static llvm::iterator_range<MergedRedeclIterator<DeclT>> 415 merged_redecls(DeclT *D) { 416 return llvm::make_range(MergedRedeclIterator<DeclT>(D), 417 MergedRedeclIterator<DeclT>()); 418 } 419 420 uint64_t ASTDeclReader::GetCurrentCursorOffset() { 421 return Loc.F->DeclsCursor.GetCurrentBitNo() + Loc.F->GlobalBitOffset; 422 } 423 424 void ASTDeclReader::Visit(Decl *D) { 425 DeclVisitor<ASTDeclReader, void>::Visit(D); 426 427 // At this point we have deserialized and merged the decl and it is safe to 428 // update its canonical decl to signal that the entire entity is used. 429 D->getCanonicalDecl()->Used |= IsDeclMarkedUsed; 430 IsDeclMarkedUsed = false; 431 432 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 433 if (DD->DeclInfo) { 434 DeclaratorDecl::ExtInfo *Info = 435 DD->DeclInfo.get<DeclaratorDecl::ExtInfo *>(); 436 Info->TInfo = GetTypeSourceInfo(); 437 } 438 else { 439 DD->DeclInfo = GetTypeSourceInfo(); 440 } 441 } 442 443 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) { 444 // We have a fully initialized TypeDecl. Read its type now. 445 TD->setTypeForDecl(Reader.GetType(TypeIDForTypeDecl).getTypePtrOrNull()); 446 447 // If this is a tag declaration with a typedef name for linkage, it's safe 448 // to load that typedef now. 449 if (NamedDeclForTagDecl) 450 cast<TagDecl>(D)->TypedefNameDeclOrQualifier = 451 cast<TypedefNameDecl>(Reader.GetDecl(NamedDeclForTagDecl)); 452 } else if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) { 453 // if we have a fully initialized TypeDecl, we can safely read its type now. 454 ID->TypeForDecl = Reader.GetType(TypeIDForTypeDecl).getTypePtrOrNull(); 455 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 456 // FunctionDecl's body was written last after all other Stmts/Exprs. 457 // We only read it if FD doesn't already have a body (e.g., from another 458 // module). 459 // FIXME: Can we diagnose ODR violations somehow? 460 if (Record.readInt()) { 461 if (auto *CD = dyn_cast<CXXConstructorDecl>(FD)) { 462 CD->NumCtorInitializers = Record.readInt(); 463 if (CD->NumCtorInitializers) 464 CD->CtorInitializers = ReadGlobalOffset(); 465 } 466 Reader.PendingBodies[FD] = GetCurrentCursorOffset(); 467 HasPendingBody = true; 468 } 469 } 470 } 471 472 void ASTDeclReader::VisitDecl(Decl *D) { 473 if (D->isTemplateParameter() || D->isTemplateParameterPack() || 474 isa<ParmVarDecl>(D)) { 475 // We don't want to deserialize the DeclContext of a template 476 // parameter or of a parameter of a function template immediately. These 477 // entities might be used in the formulation of its DeclContext (for 478 // example, a function parameter can be used in decltype() in trailing 479 // return type of the function). Use the translation unit DeclContext as a 480 // placeholder. 481 GlobalDeclID SemaDCIDForTemplateParmDecl = ReadDeclID(); 482 GlobalDeclID LexicalDCIDForTemplateParmDecl = ReadDeclID(); 483 if (!LexicalDCIDForTemplateParmDecl) 484 LexicalDCIDForTemplateParmDecl = SemaDCIDForTemplateParmDecl; 485 Reader.addPendingDeclContextInfo(D, 486 SemaDCIDForTemplateParmDecl, 487 LexicalDCIDForTemplateParmDecl); 488 D->setDeclContext(Reader.getContext().getTranslationUnitDecl()); 489 } else { 490 DeclContext *SemaDC = ReadDeclAs<DeclContext>(); 491 DeclContext *LexicalDC = ReadDeclAs<DeclContext>(); 492 if (!LexicalDC) 493 LexicalDC = SemaDC; 494 DeclContext *MergedSemaDC = Reader.MergedDeclContexts.lookup(SemaDC); 495 // Avoid calling setLexicalDeclContext() directly because it uses 496 // Decl::getASTContext() internally which is unsafe during derialization. 497 D->setDeclContextsImpl(MergedSemaDC ? MergedSemaDC : SemaDC, LexicalDC, 498 Reader.getContext()); 499 } 500 D->setLocation(ThisDeclLoc); 501 D->setInvalidDecl(Record.readInt()); 502 if (Record.readInt()) { // hasAttrs 503 AttrVec Attrs; 504 Record.readAttributes(Attrs); 505 // Avoid calling setAttrs() directly because it uses Decl::getASTContext() 506 // internally which is unsafe during derialization. 507 D->setAttrsImpl(Attrs, Reader.getContext()); 508 } 509 D->setImplicit(Record.readInt()); 510 D->Used = Record.readInt(); 511 IsDeclMarkedUsed |= D->Used; 512 D->setReferenced(Record.readInt()); 513 D->setTopLevelDeclInObjCContainer(Record.readInt()); 514 D->setAccess((AccessSpecifier)Record.readInt()); 515 D->FromASTFile = true; 516 D->setModulePrivate(Record.readInt()); 517 D->Hidden = D->isModulePrivate(); 518 519 // Determine whether this declaration is part of a (sub)module. If so, it 520 // may not yet be visible. 521 if (unsigned SubmoduleID = readSubmoduleID()) { 522 // Store the owning submodule ID in the declaration. 523 D->setOwningModuleID(SubmoduleID); 524 525 if (D->Hidden) { 526 // Module-private declarations are never visible, so there is no work to do. 527 } else if (Reader.getContext().getLangOpts().ModulesLocalVisibility) { 528 // If local visibility is being tracked, this declaration will become 529 // hidden and visible as the owning module does. Inform Sema that this 530 // declaration might not be visible. 531 D->Hidden = true; 532 } else if (Module *Owner = Reader.getSubmodule(SubmoduleID)) { 533 if (Owner->NameVisibility != Module::AllVisible) { 534 // The owning module is not visible. Mark this declaration as hidden. 535 D->Hidden = true; 536 537 // Note that this declaration was hidden because its owning module is 538 // not yet visible. 539 Reader.HiddenNamesMap[Owner].push_back(D); 540 } 541 } 542 } 543 } 544 545 void ASTDeclReader::VisitPragmaCommentDecl(PragmaCommentDecl *D) { 546 VisitDecl(D); 547 D->setLocation(ReadSourceLocation()); 548 D->CommentKind = (PragmaMSCommentKind)Record.readInt(); 549 std::string Arg = ReadString(); 550 memcpy(D->getTrailingObjects<char>(), Arg.data(), Arg.size()); 551 D->getTrailingObjects<char>()[Arg.size()] = '\0'; 552 } 553 554 void ASTDeclReader::VisitPragmaDetectMismatchDecl(PragmaDetectMismatchDecl *D) { 555 VisitDecl(D); 556 D->setLocation(ReadSourceLocation()); 557 std::string Name = ReadString(); 558 memcpy(D->getTrailingObjects<char>(), Name.data(), Name.size()); 559 D->getTrailingObjects<char>()[Name.size()] = '\0'; 560 561 D->ValueStart = Name.size() + 1; 562 std::string Value = ReadString(); 563 memcpy(D->getTrailingObjects<char>() + D->ValueStart, Value.data(), 564 Value.size()); 565 D->getTrailingObjects<char>()[D->ValueStart + Value.size()] = '\0'; 566 } 567 568 void ASTDeclReader::VisitTranslationUnitDecl(TranslationUnitDecl *TU) { 569 llvm_unreachable("Translation units are not serialized"); 570 } 571 572 void ASTDeclReader::VisitNamedDecl(NamedDecl *ND) { 573 VisitDecl(ND); 574 ND->setDeclName(Record.readDeclarationName()); 575 AnonymousDeclNumber = Record.readInt(); 576 } 577 578 void ASTDeclReader::VisitTypeDecl(TypeDecl *TD) { 579 VisitNamedDecl(TD); 580 TD->setLocStart(ReadSourceLocation()); 581 // Delay type reading until after we have fully initialized the decl. 582 TypeIDForTypeDecl = Record.getGlobalTypeID(Record.readInt()); 583 } 584 585 ASTDeclReader::RedeclarableResult 586 ASTDeclReader::VisitTypedefNameDecl(TypedefNameDecl *TD) { 587 RedeclarableResult Redecl = VisitRedeclarable(TD); 588 VisitTypeDecl(TD); 589 TypeSourceInfo *TInfo = GetTypeSourceInfo(); 590 if (Record.readInt()) { // isModed 591 QualType modedT = Record.readType(); 592 TD->setModedTypeSourceInfo(TInfo, modedT); 593 } else 594 TD->setTypeSourceInfo(TInfo); 595 return Redecl; 596 } 597 598 void ASTDeclReader::VisitTypedefDecl(TypedefDecl *TD) { 599 RedeclarableResult Redecl = VisitTypedefNameDecl(TD); 600 mergeRedeclarable(TD, Redecl); 601 } 602 603 void ASTDeclReader::VisitTypeAliasDecl(TypeAliasDecl *TD) { 604 RedeclarableResult Redecl = VisitTypedefNameDecl(TD); 605 if (auto *Template = ReadDeclAs<TypeAliasTemplateDecl>()) 606 // Merged when we merge the template. 607 TD->setDescribedAliasTemplate(Template); 608 else 609 mergeRedeclarable(TD, Redecl); 610 } 611 612 ASTDeclReader::RedeclarableResult ASTDeclReader::VisitTagDecl(TagDecl *TD) { 613 RedeclarableResult Redecl = VisitRedeclarable(TD); 614 VisitTypeDecl(TD); 615 616 TD->IdentifierNamespace = Record.readInt(); 617 TD->setTagKind((TagDecl::TagKind)Record.readInt()); 618 if (!isa<CXXRecordDecl>(TD)) 619 TD->setCompleteDefinition(Record.readInt()); 620 TD->setEmbeddedInDeclarator(Record.readInt()); 621 TD->setFreeStanding(Record.readInt()); 622 TD->setCompleteDefinitionRequired(Record.readInt()); 623 TD->setBraceRange(ReadSourceRange()); 624 625 switch (Record.readInt()) { 626 case 0: 627 break; 628 case 1: { // ExtInfo 629 TagDecl::ExtInfo *Info = new (Reader.getContext()) TagDecl::ExtInfo(); 630 ReadQualifierInfo(*Info); 631 TD->TypedefNameDeclOrQualifier = Info; 632 break; 633 } 634 case 2: // TypedefNameForAnonDecl 635 NamedDeclForTagDecl = ReadDeclID(); 636 TypedefNameForLinkage = Record.getIdentifierInfo(); 637 break; 638 default: 639 llvm_unreachable("unexpected tag info kind"); 640 } 641 642 if (!isa<CXXRecordDecl>(TD)) 643 mergeRedeclarable(TD, Redecl); 644 return Redecl; 645 } 646 647 void ASTDeclReader::VisitEnumDecl(EnumDecl *ED) { 648 VisitTagDecl(ED); 649 if (TypeSourceInfo *TI = GetTypeSourceInfo()) 650 ED->setIntegerTypeSourceInfo(TI); 651 else 652 ED->setIntegerType(Record.readType()); 653 ED->setPromotionType(Record.readType()); 654 ED->setNumPositiveBits(Record.readInt()); 655 ED->setNumNegativeBits(Record.readInt()); 656 ED->IsScoped = Record.readInt(); 657 ED->IsScopedUsingClassTag = Record.readInt(); 658 ED->IsFixed = Record.readInt(); 659 660 // If this is a definition subject to the ODR, and we already have a 661 // definition, merge this one into it. 662 if (ED->IsCompleteDefinition && 663 Reader.getContext().getLangOpts().Modules && 664 Reader.getContext().getLangOpts().CPlusPlus) { 665 EnumDecl *&OldDef = Reader.EnumDefinitions[ED->getCanonicalDecl()]; 666 if (!OldDef) { 667 // This is the first time we've seen an imported definition. Look for a 668 // local definition before deciding that we are the first definition. 669 for (auto *D : merged_redecls(ED->getCanonicalDecl())) { 670 if (!D->isFromASTFile() && D->isCompleteDefinition()) { 671 OldDef = D; 672 break; 673 } 674 } 675 } 676 if (OldDef) { 677 Reader.MergedDeclContexts.insert(std::make_pair(ED, OldDef)); 678 ED->IsCompleteDefinition = false; 679 Reader.mergeDefinitionVisibility(OldDef, ED); 680 } else { 681 OldDef = ED; 682 } 683 } 684 685 if (EnumDecl *InstED = ReadDeclAs<EnumDecl>()) { 686 TemplateSpecializationKind TSK = 687 (TemplateSpecializationKind)Record.readInt(); 688 SourceLocation POI = ReadSourceLocation(); 689 ED->setInstantiationOfMemberEnum(Reader.getContext(), InstED, TSK); 690 ED->getMemberSpecializationInfo()->setPointOfInstantiation(POI); 691 } 692 } 693 694 ASTDeclReader::RedeclarableResult 695 ASTDeclReader::VisitRecordDeclImpl(RecordDecl *RD) { 696 RedeclarableResult Redecl = VisitTagDecl(RD); 697 RD->setHasFlexibleArrayMember(Record.readInt()); 698 RD->setAnonymousStructOrUnion(Record.readInt()); 699 RD->setHasObjectMember(Record.readInt()); 700 RD->setHasVolatileMember(Record.readInt()); 701 return Redecl; 702 } 703 704 void ASTDeclReader::VisitValueDecl(ValueDecl *VD) { 705 VisitNamedDecl(VD); 706 VD->setType(Record.readType()); 707 } 708 709 void ASTDeclReader::VisitEnumConstantDecl(EnumConstantDecl *ECD) { 710 VisitValueDecl(ECD); 711 if (Record.readInt()) 712 ECD->setInitExpr(Record.readExpr()); 713 ECD->setInitVal(Record.readAPSInt()); 714 mergeMergeable(ECD); 715 } 716 717 void ASTDeclReader::VisitDeclaratorDecl(DeclaratorDecl *DD) { 718 VisitValueDecl(DD); 719 DD->setInnerLocStart(ReadSourceLocation()); 720 if (Record.readInt()) { // hasExtInfo 721 DeclaratorDecl::ExtInfo *Info 722 = new (Reader.getContext()) DeclaratorDecl::ExtInfo(); 723 ReadQualifierInfo(*Info); 724 DD->DeclInfo = Info; 725 } 726 } 727 728 void ASTDeclReader::VisitFunctionDecl(FunctionDecl *FD) { 729 RedeclarableResult Redecl = VisitRedeclarable(FD); 730 VisitDeclaratorDecl(FD); 731 732 ReadDeclarationNameLoc(FD->DNLoc, FD->getDeclName()); 733 FD->IdentifierNamespace = Record.readInt(); 734 735 // FunctionDecl's body is handled last at ASTDeclReader::Visit, 736 // after everything else is read. 737 738 FD->SClass = (StorageClass)Record.readInt(); 739 FD->IsInline = Record.readInt(); 740 FD->IsInlineSpecified = Record.readInt(); 741 FD->IsVirtualAsWritten = Record.readInt(); 742 FD->IsPure = Record.readInt(); 743 FD->HasInheritedPrototype = Record.readInt(); 744 FD->HasWrittenPrototype = Record.readInt(); 745 FD->IsDeleted = Record.readInt(); 746 FD->IsTrivial = Record.readInt(); 747 FD->IsDefaulted = Record.readInt(); 748 FD->IsExplicitlyDefaulted = Record.readInt(); 749 FD->HasImplicitReturnZero = Record.readInt(); 750 FD->IsConstexpr = Record.readInt(); 751 FD->UsesSEHTry = Record.readInt(); 752 FD->HasSkippedBody = Record.readInt(); 753 FD->IsLateTemplateParsed = Record.readInt(); 754 FD->setCachedLinkage(Linkage(Record.readInt())); 755 FD->EndRangeLoc = ReadSourceLocation(); 756 757 switch ((FunctionDecl::TemplatedKind)Record.readInt()) { 758 case FunctionDecl::TK_NonTemplate: 759 mergeRedeclarable(FD, Redecl); 760 break; 761 case FunctionDecl::TK_FunctionTemplate: 762 // Merged when we merge the template. 763 FD->setDescribedFunctionTemplate(ReadDeclAs<FunctionTemplateDecl>()); 764 break; 765 case FunctionDecl::TK_MemberSpecialization: { 766 FunctionDecl *InstFD = ReadDeclAs<FunctionDecl>(); 767 TemplateSpecializationKind TSK = 768 (TemplateSpecializationKind)Record.readInt(); 769 SourceLocation POI = ReadSourceLocation(); 770 FD->setInstantiationOfMemberFunction(Reader.getContext(), InstFD, TSK); 771 FD->getMemberSpecializationInfo()->setPointOfInstantiation(POI); 772 mergeRedeclarable(FD, Redecl); 773 break; 774 } 775 case FunctionDecl::TK_FunctionTemplateSpecialization: { 776 FunctionTemplateDecl *Template = ReadDeclAs<FunctionTemplateDecl>(); 777 TemplateSpecializationKind TSK = 778 (TemplateSpecializationKind)Record.readInt(); 779 780 // Template arguments. 781 SmallVector<TemplateArgument, 8> TemplArgs; 782 Record.readTemplateArgumentList(TemplArgs, /*Canonicalize*/ true); 783 784 // Template args as written. 785 SmallVector<TemplateArgumentLoc, 8> TemplArgLocs; 786 SourceLocation LAngleLoc, RAngleLoc; 787 bool HasTemplateArgumentsAsWritten = Record.readInt(); 788 if (HasTemplateArgumentsAsWritten) { 789 unsigned NumTemplateArgLocs = Record.readInt(); 790 TemplArgLocs.reserve(NumTemplateArgLocs); 791 for (unsigned i=0; i != NumTemplateArgLocs; ++i) 792 TemplArgLocs.push_back(Record.readTemplateArgumentLoc()); 793 794 LAngleLoc = ReadSourceLocation(); 795 RAngleLoc = ReadSourceLocation(); 796 } 797 798 SourceLocation POI = ReadSourceLocation(); 799 800 ASTContext &C = Reader.getContext(); 801 TemplateArgumentList *TemplArgList 802 = TemplateArgumentList::CreateCopy(C, TemplArgs); 803 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc); 804 for (unsigned i=0, e = TemplArgLocs.size(); i != e; ++i) 805 TemplArgsInfo.addArgument(TemplArgLocs[i]); 806 FunctionTemplateSpecializationInfo *FTInfo 807 = FunctionTemplateSpecializationInfo::Create(C, FD, Template, TSK, 808 TemplArgList, 809 HasTemplateArgumentsAsWritten ? &TemplArgsInfo 810 : nullptr, 811 POI); 812 FD->TemplateOrSpecialization = FTInfo; 813 814 if (FD->isCanonicalDecl()) { // if canonical add to template's set. 815 // The template that contains the specializations set. It's not safe to 816 // use getCanonicalDecl on Template since it may still be initializing. 817 FunctionTemplateDecl *CanonTemplate = ReadDeclAs<FunctionTemplateDecl>(); 818 // Get the InsertPos by FindNodeOrInsertPos() instead of calling 819 // InsertNode(FTInfo) directly to avoid the getASTContext() call in 820 // FunctionTemplateSpecializationInfo's Profile(). 821 // We avoid getASTContext because a decl in the parent hierarchy may 822 // be initializing. 823 llvm::FoldingSetNodeID ID; 824 FunctionTemplateSpecializationInfo::Profile(ID, TemplArgs, C); 825 void *InsertPos = nullptr; 826 FunctionTemplateDecl::Common *CommonPtr = CanonTemplate->getCommonPtr(); 827 FunctionTemplateSpecializationInfo *ExistingInfo = 828 CommonPtr->Specializations.FindNodeOrInsertPos(ID, InsertPos); 829 if (InsertPos) 830 CommonPtr->Specializations.InsertNode(FTInfo, InsertPos); 831 else { 832 assert(Reader.getContext().getLangOpts().Modules && 833 "already deserialized this template specialization"); 834 mergeRedeclarable(FD, ExistingInfo->Function, Redecl); 835 } 836 } 837 break; 838 } 839 case FunctionDecl::TK_DependentFunctionTemplateSpecialization: { 840 // Templates. 841 UnresolvedSet<8> TemplDecls; 842 unsigned NumTemplates = Record.readInt(); 843 while (NumTemplates--) 844 TemplDecls.addDecl(ReadDeclAs<NamedDecl>()); 845 846 // Templates args. 847 TemplateArgumentListInfo TemplArgs; 848 unsigned NumArgs = Record.readInt(); 849 while (NumArgs--) 850 TemplArgs.addArgument(Record.readTemplateArgumentLoc()); 851 TemplArgs.setLAngleLoc(ReadSourceLocation()); 852 TemplArgs.setRAngleLoc(ReadSourceLocation()); 853 854 FD->setDependentTemplateSpecialization(Reader.getContext(), 855 TemplDecls, TemplArgs); 856 // These are not merged; we don't need to merge redeclarations of dependent 857 // template friends. 858 break; 859 } 860 } 861 862 // Read in the parameters. 863 unsigned NumParams = Record.readInt(); 864 SmallVector<ParmVarDecl *, 16> Params; 865 Params.reserve(NumParams); 866 for (unsigned I = 0; I != NumParams; ++I) 867 Params.push_back(ReadDeclAs<ParmVarDecl>()); 868 FD->setParams(Reader.getContext(), Params); 869 } 870 871 void ASTDeclReader::VisitObjCMethodDecl(ObjCMethodDecl *MD) { 872 VisitNamedDecl(MD); 873 if (Record.readInt()) { 874 // Load the body on-demand. Most clients won't care, because method 875 // definitions rarely show up in headers. 876 Reader.PendingBodies[MD] = GetCurrentCursorOffset(); 877 HasPendingBody = true; 878 MD->setSelfDecl(ReadDeclAs<ImplicitParamDecl>()); 879 MD->setCmdDecl(ReadDeclAs<ImplicitParamDecl>()); 880 } 881 MD->setInstanceMethod(Record.readInt()); 882 MD->setVariadic(Record.readInt()); 883 MD->setPropertyAccessor(Record.readInt()); 884 MD->setDefined(Record.readInt()); 885 MD->IsOverriding = Record.readInt(); 886 MD->HasSkippedBody = Record.readInt(); 887 888 MD->IsRedeclaration = Record.readInt(); 889 MD->HasRedeclaration = Record.readInt(); 890 if (MD->HasRedeclaration) 891 Reader.getContext().setObjCMethodRedeclaration(MD, 892 ReadDeclAs<ObjCMethodDecl>()); 893 894 MD->setDeclImplementation((ObjCMethodDecl::ImplementationControl)Record.readInt()); 895 MD->setObjCDeclQualifier((Decl::ObjCDeclQualifier)Record.readInt()); 896 MD->SetRelatedResultType(Record.readInt()); 897 MD->setReturnType(Record.readType()); 898 MD->setReturnTypeSourceInfo(GetTypeSourceInfo()); 899 MD->DeclEndLoc = ReadSourceLocation(); 900 unsigned NumParams = Record.readInt(); 901 SmallVector<ParmVarDecl *, 16> Params; 902 Params.reserve(NumParams); 903 for (unsigned I = 0; I != NumParams; ++I) 904 Params.push_back(ReadDeclAs<ParmVarDecl>()); 905 906 MD->SelLocsKind = Record.readInt(); 907 unsigned NumStoredSelLocs = Record.readInt(); 908 SmallVector<SourceLocation, 16> SelLocs; 909 SelLocs.reserve(NumStoredSelLocs); 910 for (unsigned i = 0; i != NumStoredSelLocs; ++i) 911 SelLocs.push_back(ReadSourceLocation()); 912 913 MD->setParamsAndSelLocs(Reader.getContext(), Params, SelLocs); 914 } 915 916 void ASTDeclReader::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) { 917 VisitTypedefNameDecl(D); 918 919 D->Variance = Record.readInt(); 920 D->Index = Record.readInt(); 921 D->VarianceLoc = ReadSourceLocation(); 922 D->ColonLoc = ReadSourceLocation(); 923 } 924 925 void ASTDeclReader::VisitObjCContainerDecl(ObjCContainerDecl *CD) { 926 VisitNamedDecl(CD); 927 CD->setAtStartLoc(ReadSourceLocation()); 928 CD->setAtEndRange(ReadSourceRange()); 929 } 930 931 ObjCTypeParamList *ASTDeclReader::ReadObjCTypeParamList() { 932 unsigned numParams = Record.readInt(); 933 if (numParams == 0) 934 return nullptr; 935 936 SmallVector<ObjCTypeParamDecl *, 4> typeParams; 937 typeParams.reserve(numParams); 938 for (unsigned i = 0; i != numParams; ++i) { 939 auto typeParam = ReadDeclAs<ObjCTypeParamDecl>(); 940 if (!typeParam) 941 return nullptr; 942 943 typeParams.push_back(typeParam); 944 } 945 946 SourceLocation lAngleLoc = ReadSourceLocation(); 947 SourceLocation rAngleLoc = ReadSourceLocation(); 948 949 return ObjCTypeParamList::create(Reader.getContext(), lAngleLoc, 950 typeParams, rAngleLoc); 951 } 952 953 void ASTDeclReader::ReadObjCDefinitionData( 954 struct ObjCInterfaceDecl::DefinitionData &Data) { 955 // Read the superclass. 956 Data.SuperClassTInfo = GetTypeSourceInfo(); 957 958 Data.EndLoc = ReadSourceLocation(); 959 Data.HasDesignatedInitializers = Record.readInt(); 960 961 // Read the directly referenced protocols and their SourceLocations. 962 unsigned NumProtocols = Record.readInt(); 963 SmallVector<ObjCProtocolDecl *, 16> Protocols; 964 Protocols.reserve(NumProtocols); 965 for (unsigned I = 0; I != NumProtocols; ++I) 966 Protocols.push_back(ReadDeclAs<ObjCProtocolDecl>()); 967 SmallVector<SourceLocation, 16> ProtoLocs; 968 ProtoLocs.reserve(NumProtocols); 969 for (unsigned I = 0; I != NumProtocols; ++I) 970 ProtoLocs.push_back(ReadSourceLocation()); 971 Data.ReferencedProtocols.set(Protocols.data(), NumProtocols, ProtoLocs.data(), 972 Reader.getContext()); 973 974 // Read the transitive closure of protocols referenced by this class. 975 NumProtocols = Record.readInt(); 976 Protocols.clear(); 977 Protocols.reserve(NumProtocols); 978 for (unsigned I = 0; I != NumProtocols; ++I) 979 Protocols.push_back(ReadDeclAs<ObjCProtocolDecl>()); 980 Data.AllReferencedProtocols.set(Protocols.data(), NumProtocols, 981 Reader.getContext()); 982 } 983 984 void ASTDeclReader::MergeDefinitionData(ObjCInterfaceDecl *D, 985 struct ObjCInterfaceDecl::DefinitionData &&NewDD) { 986 // FIXME: odr checking? 987 } 988 989 void ASTDeclReader::VisitObjCInterfaceDecl(ObjCInterfaceDecl *ID) { 990 RedeclarableResult Redecl = VisitRedeclarable(ID); 991 VisitObjCContainerDecl(ID); 992 TypeIDForTypeDecl = Record.getGlobalTypeID(Record.readInt()); 993 mergeRedeclarable(ID, Redecl); 994 995 ID->TypeParamList = ReadObjCTypeParamList(); 996 if (Record.readInt()) { 997 // Read the definition. 998 ID->allocateDefinitionData(); 999 1000 ReadObjCDefinitionData(ID->data()); 1001 ObjCInterfaceDecl *Canon = ID->getCanonicalDecl(); 1002 if (Canon->Data.getPointer()) { 1003 // If we already have a definition, keep the definition invariant and 1004 // merge the data. 1005 MergeDefinitionData(Canon, std::move(ID->data())); 1006 ID->Data = Canon->Data; 1007 } else { 1008 // Set the definition data of the canonical declaration, so other 1009 // redeclarations will see it. 1010 ID->getCanonicalDecl()->Data = ID->Data; 1011 1012 // We will rebuild this list lazily. 1013 ID->setIvarList(nullptr); 1014 } 1015 1016 // Note that we have deserialized a definition. 1017 Reader.PendingDefinitions.insert(ID); 1018 1019 // Note that we've loaded this Objective-C class. 1020 Reader.ObjCClassesLoaded.push_back(ID); 1021 } else { 1022 ID->Data = ID->getCanonicalDecl()->Data; 1023 } 1024 } 1025 1026 void ASTDeclReader::VisitObjCIvarDecl(ObjCIvarDecl *IVD) { 1027 VisitFieldDecl(IVD); 1028 IVD->setAccessControl((ObjCIvarDecl::AccessControl)Record.readInt()); 1029 // This field will be built lazily. 1030 IVD->setNextIvar(nullptr); 1031 bool synth = Record.readInt(); 1032 IVD->setSynthesize(synth); 1033 } 1034 1035 void ASTDeclReader::VisitObjCProtocolDecl(ObjCProtocolDecl *PD) { 1036 RedeclarableResult Redecl = VisitRedeclarable(PD); 1037 VisitObjCContainerDecl(PD); 1038 mergeRedeclarable(PD, Redecl); 1039 1040 if (Record.readInt()) { 1041 // Read the definition. 1042 PD->allocateDefinitionData(); 1043 1044 // Set the definition data of the canonical declaration, so other 1045 // redeclarations will see it. 1046 PD->getCanonicalDecl()->Data = PD->Data; 1047 1048 unsigned NumProtoRefs = Record.readInt(); 1049 SmallVector<ObjCProtocolDecl *, 16> ProtoRefs; 1050 ProtoRefs.reserve(NumProtoRefs); 1051 for (unsigned I = 0; I != NumProtoRefs; ++I) 1052 ProtoRefs.push_back(ReadDeclAs<ObjCProtocolDecl>()); 1053 SmallVector<SourceLocation, 16> ProtoLocs; 1054 ProtoLocs.reserve(NumProtoRefs); 1055 for (unsigned I = 0; I != NumProtoRefs; ++I) 1056 ProtoLocs.push_back(ReadSourceLocation()); 1057 PD->setProtocolList(ProtoRefs.data(), NumProtoRefs, ProtoLocs.data(), 1058 Reader.getContext()); 1059 1060 // Note that we have deserialized a definition. 1061 Reader.PendingDefinitions.insert(PD); 1062 } else { 1063 PD->Data = PD->getCanonicalDecl()->Data; 1064 } 1065 } 1066 1067 void ASTDeclReader::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *FD) { 1068 VisitFieldDecl(FD); 1069 } 1070 1071 void ASTDeclReader::VisitObjCCategoryDecl(ObjCCategoryDecl *CD) { 1072 VisitObjCContainerDecl(CD); 1073 CD->setCategoryNameLoc(ReadSourceLocation()); 1074 CD->setIvarLBraceLoc(ReadSourceLocation()); 1075 CD->setIvarRBraceLoc(ReadSourceLocation()); 1076 1077 // Note that this category has been deserialized. We do this before 1078 // deserializing the interface declaration, so that it will consider this 1079 /// category. 1080 Reader.CategoriesDeserialized.insert(CD); 1081 1082 CD->ClassInterface = ReadDeclAs<ObjCInterfaceDecl>(); 1083 CD->TypeParamList = ReadObjCTypeParamList(); 1084 unsigned NumProtoRefs = Record.readInt(); 1085 SmallVector<ObjCProtocolDecl *, 16> ProtoRefs; 1086 ProtoRefs.reserve(NumProtoRefs); 1087 for (unsigned I = 0; I != NumProtoRefs; ++I) 1088 ProtoRefs.push_back(ReadDeclAs<ObjCProtocolDecl>()); 1089 SmallVector<SourceLocation, 16> ProtoLocs; 1090 ProtoLocs.reserve(NumProtoRefs); 1091 for (unsigned I = 0; I != NumProtoRefs; ++I) 1092 ProtoLocs.push_back(ReadSourceLocation()); 1093 CD->setProtocolList(ProtoRefs.data(), NumProtoRefs, ProtoLocs.data(), 1094 Reader.getContext()); 1095 } 1096 1097 void ASTDeclReader::VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *CAD) { 1098 VisitNamedDecl(CAD); 1099 CAD->setClassInterface(ReadDeclAs<ObjCInterfaceDecl>()); 1100 } 1101 1102 void ASTDeclReader::VisitObjCPropertyDecl(ObjCPropertyDecl *D) { 1103 VisitNamedDecl(D); 1104 D->setAtLoc(ReadSourceLocation()); 1105 D->setLParenLoc(ReadSourceLocation()); 1106 QualType T = Record.readType(); 1107 TypeSourceInfo *TSI = GetTypeSourceInfo(); 1108 D->setType(T, TSI); 1109 D->setPropertyAttributes( 1110 (ObjCPropertyDecl::PropertyAttributeKind)Record.readInt()); 1111 D->setPropertyAttributesAsWritten( 1112 (ObjCPropertyDecl::PropertyAttributeKind)Record.readInt()); 1113 D->setPropertyImplementation( 1114 (ObjCPropertyDecl::PropertyControl)Record.readInt()); 1115 D->setGetterName(Record.readDeclarationName().getObjCSelector()); 1116 D->setSetterName(Record.readDeclarationName().getObjCSelector()); 1117 D->setGetterMethodDecl(ReadDeclAs<ObjCMethodDecl>()); 1118 D->setSetterMethodDecl(ReadDeclAs<ObjCMethodDecl>()); 1119 D->setPropertyIvarDecl(ReadDeclAs<ObjCIvarDecl>()); 1120 } 1121 1122 void ASTDeclReader::VisitObjCImplDecl(ObjCImplDecl *D) { 1123 VisitObjCContainerDecl(D); 1124 D->setClassInterface(ReadDeclAs<ObjCInterfaceDecl>()); 1125 } 1126 1127 void ASTDeclReader::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) { 1128 VisitObjCImplDecl(D); 1129 D->setIdentifier(Record.getIdentifierInfo()); 1130 D->CategoryNameLoc = ReadSourceLocation(); 1131 } 1132 1133 void ASTDeclReader::VisitObjCImplementationDecl(ObjCImplementationDecl *D) { 1134 VisitObjCImplDecl(D); 1135 D->setSuperClass(ReadDeclAs<ObjCInterfaceDecl>()); 1136 D->SuperLoc = ReadSourceLocation(); 1137 D->setIvarLBraceLoc(ReadSourceLocation()); 1138 D->setIvarRBraceLoc(ReadSourceLocation()); 1139 D->setHasNonZeroConstructors(Record.readInt()); 1140 D->setHasDestructors(Record.readInt()); 1141 D->NumIvarInitializers = Record.readInt(); 1142 if (D->NumIvarInitializers) 1143 D->IvarInitializers = ReadGlobalOffset(); 1144 } 1145 1146 void ASTDeclReader::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) { 1147 VisitDecl(D); 1148 D->setAtLoc(ReadSourceLocation()); 1149 D->setPropertyDecl(ReadDeclAs<ObjCPropertyDecl>()); 1150 D->PropertyIvarDecl = ReadDeclAs<ObjCIvarDecl>(); 1151 D->IvarLoc = ReadSourceLocation(); 1152 D->setGetterCXXConstructor(Record.readExpr()); 1153 D->setSetterCXXAssignment(Record.readExpr()); 1154 } 1155 1156 void ASTDeclReader::VisitFieldDecl(FieldDecl *FD) { 1157 VisitDeclaratorDecl(FD); 1158 FD->Mutable = Record.readInt(); 1159 if (int BitWidthOrInitializer = Record.readInt()) { 1160 FD->InitStorage.setInt( 1161 static_cast<FieldDecl::InitStorageKind>(BitWidthOrInitializer - 1)); 1162 if (FD->InitStorage.getInt() == FieldDecl::ISK_CapturedVLAType) { 1163 // Read captured variable length array. 1164 FD->InitStorage.setPointer(Record.readType().getAsOpaquePtr()); 1165 } else { 1166 FD->InitStorage.setPointer(Record.readExpr()); 1167 } 1168 } 1169 if (!FD->getDeclName()) { 1170 if (FieldDecl *Tmpl = ReadDeclAs<FieldDecl>()) 1171 Reader.getContext().setInstantiatedFromUnnamedFieldDecl(FD, Tmpl); 1172 } 1173 mergeMergeable(FD); 1174 } 1175 1176 void ASTDeclReader::VisitMSPropertyDecl(MSPropertyDecl *PD) { 1177 VisitDeclaratorDecl(PD); 1178 PD->GetterId = Record.getIdentifierInfo(); 1179 PD->SetterId = Record.getIdentifierInfo(); 1180 } 1181 1182 void ASTDeclReader::VisitIndirectFieldDecl(IndirectFieldDecl *FD) { 1183 VisitValueDecl(FD); 1184 1185 FD->ChainingSize = Record.readInt(); 1186 assert(FD->ChainingSize >= 2 && "Anonymous chaining must be >= 2"); 1187 FD->Chaining = new (Reader.getContext())NamedDecl*[FD->ChainingSize]; 1188 1189 for (unsigned I = 0; I != FD->ChainingSize; ++I) 1190 FD->Chaining[I] = ReadDeclAs<NamedDecl>(); 1191 1192 mergeMergeable(FD); 1193 } 1194 1195 ASTDeclReader::RedeclarableResult ASTDeclReader::VisitVarDeclImpl(VarDecl *VD) { 1196 RedeclarableResult Redecl = VisitRedeclarable(VD); 1197 VisitDeclaratorDecl(VD); 1198 1199 VD->VarDeclBits.SClass = (StorageClass)Record.readInt(); 1200 VD->VarDeclBits.TSCSpec = Record.readInt(); 1201 VD->VarDeclBits.InitStyle = Record.readInt(); 1202 if (!isa<ParmVarDecl>(VD)) { 1203 VD->NonParmVarDeclBits.IsThisDeclarationADemotedDefinition = 1204 Record.readInt(); 1205 VD->NonParmVarDeclBits.ExceptionVar = Record.readInt(); 1206 VD->NonParmVarDeclBits.NRVOVariable = Record.readInt(); 1207 VD->NonParmVarDeclBits.CXXForRangeDecl = Record.readInt(); 1208 VD->NonParmVarDeclBits.ARCPseudoStrong = Record.readInt(); 1209 VD->NonParmVarDeclBits.IsInline = Record.readInt(); 1210 VD->NonParmVarDeclBits.IsInlineSpecified = Record.readInt(); 1211 VD->NonParmVarDeclBits.IsConstexpr = Record.readInt(); 1212 VD->NonParmVarDeclBits.IsInitCapture = Record.readInt(); 1213 VD->NonParmVarDeclBits.PreviousDeclInSameBlockScope = Record.readInt(); 1214 } 1215 Linkage VarLinkage = Linkage(Record.readInt()); 1216 VD->setCachedLinkage(VarLinkage); 1217 1218 // Reconstruct the one piece of the IdentifierNamespace that we need. 1219 if (VD->getStorageClass() == SC_Extern && VarLinkage != NoLinkage && 1220 VD->getLexicalDeclContext()->isFunctionOrMethod()) 1221 VD->setLocalExternDecl(); 1222 1223 if (uint64_t Val = Record.readInt()) { 1224 VD->setInit(Record.readExpr()); 1225 if (Val > 1) { // IsInitKnownICE = 1, IsInitNotICE = 2, IsInitICE = 3 1226 EvaluatedStmt *Eval = VD->ensureEvaluatedStmt(); 1227 Eval->CheckedICE = true; 1228 Eval->IsICE = Val == 3; 1229 } 1230 } 1231 1232 enum VarKind { 1233 VarNotTemplate = 0, VarTemplate, StaticDataMemberSpecialization 1234 }; 1235 switch ((VarKind)Record.readInt()) { 1236 case VarNotTemplate: 1237 // Only true variables (not parameters or implicit parameters) can be 1238 // merged; the other kinds are not really redeclarable at all. 1239 if (!isa<ParmVarDecl>(VD) && !isa<ImplicitParamDecl>(VD) && 1240 !isa<VarTemplateSpecializationDecl>(VD)) 1241 mergeRedeclarable(VD, Redecl); 1242 break; 1243 case VarTemplate: 1244 // Merged when we merge the template. 1245 VD->setDescribedVarTemplate(ReadDeclAs<VarTemplateDecl>()); 1246 break; 1247 case StaticDataMemberSpecialization: { // HasMemberSpecializationInfo. 1248 VarDecl *Tmpl = ReadDeclAs<VarDecl>(); 1249 TemplateSpecializationKind TSK = 1250 (TemplateSpecializationKind)Record.readInt(); 1251 SourceLocation POI = ReadSourceLocation(); 1252 Reader.getContext().setInstantiatedFromStaticDataMember(VD, Tmpl, TSK,POI); 1253 mergeRedeclarable(VD, Redecl); 1254 break; 1255 } 1256 } 1257 1258 return Redecl; 1259 } 1260 1261 void ASTDeclReader::VisitImplicitParamDecl(ImplicitParamDecl *PD) { 1262 VisitVarDecl(PD); 1263 } 1264 1265 void ASTDeclReader::VisitParmVarDecl(ParmVarDecl *PD) { 1266 VisitVarDecl(PD); 1267 unsigned isObjCMethodParam = Record.readInt(); 1268 unsigned scopeDepth = Record.readInt(); 1269 unsigned scopeIndex = Record.readInt(); 1270 unsigned declQualifier = Record.readInt(); 1271 if (isObjCMethodParam) { 1272 assert(scopeDepth == 0); 1273 PD->setObjCMethodScopeInfo(scopeIndex); 1274 PD->ParmVarDeclBits.ScopeDepthOrObjCQuals = declQualifier; 1275 } else { 1276 PD->setScopeInfo(scopeDepth, scopeIndex); 1277 } 1278 PD->ParmVarDeclBits.IsKNRPromoted = Record.readInt(); 1279 PD->ParmVarDeclBits.HasInheritedDefaultArg = Record.readInt(); 1280 if (Record.readInt()) // hasUninstantiatedDefaultArg. 1281 PD->setUninstantiatedDefaultArg(Record.readExpr()); 1282 1283 // FIXME: If this is a redeclaration of a function from another module, handle 1284 // inheritance of default arguments. 1285 } 1286 1287 void ASTDeclReader::VisitDecompositionDecl(DecompositionDecl *DD) { 1288 VisitVarDecl(DD); 1289 BindingDecl **BDs = DD->getTrailingObjects<BindingDecl*>(); 1290 for (unsigned I = 0; I != DD->NumBindings; ++I) 1291 BDs[I] = ReadDeclAs<BindingDecl>(); 1292 } 1293 1294 void ASTDeclReader::VisitBindingDecl(BindingDecl *BD) { 1295 VisitValueDecl(BD); 1296 BD->Binding = Record.readExpr(); 1297 } 1298 1299 void ASTDeclReader::VisitFileScopeAsmDecl(FileScopeAsmDecl *AD) { 1300 VisitDecl(AD); 1301 AD->setAsmString(cast<StringLiteral>(Record.readExpr())); 1302 AD->setRParenLoc(ReadSourceLocation()); 1303 } 1304 1305 void ASTDeclReader::VisitBlockDecl(BlockDecl *BD) { 1306 VisitDecl(BD); 1307 BD->setBody(cast_or_null<CompoundStmt>(Record.readStmt())); 1308 BD->setSignatureAsWritten(GetTypeSourceInfo()); 1309 unsigned NumParams = Record.readInt(); 1310 SmallVector<ParmVarDecl *, 16> Params; 1311 Params.reserve(NumParams); 1312 for (unsigned I = 0; I != NumParams; ++I) 1313 Params.push_back(ReadDeclAs<ParmVarDecl>()); 1314 BD->setParams(Params); 1315 1316 BD->setIsVariadic(Record.readInt()); 1317 BD->setBlockMissingReturnType(Record.readInt()); 1318 BD->setIsConversionFromLambda(Record.readInt()); 1319 1320 bool capturesCXXThis = Record.readInt(); 1321 unsigned numCaptures = Record.readInt(); 1322 SmallVector<BlockDecl::Capture, 16> captures; 1323 captures.reserve(numCaptures); 1324 for (unsigned i = 0; i != numCaptures; ++i) { 1325 VarDecl *decl = ReadDeclAs<VarDecl>(); 1326 unsigned flags = Record.readInt(); 1327 bool byRef = (flags & 1); 1328 bool nested = (flags & 2); 1329 Expr *copyExpr = ((flags & 4) ? Record.readExpr() : nullptr); 1330 1331 captures.push_back(BlockDecl::Capture(decl, byRef, nested, copyExpr)); 1332 } 1333 BD->setCaptures(Reader.getContext(), captures, capturesCXXThis); 1334 } 1335 1336 void ASTDeclReader::VisitCapturedDecl(CapturedDecl *CD) { 1337 VisitDecl(CD); 1338 unsigned ContextParamPos = Record.readInt(); 1339 CD->setNothrow(Record.readInt() != 0); 1340 // Body is set by VisitCapturedStmt. 1341 for (unsigned I = 0; I < CD->NumParams; ++I) { 1342 if (I != ContextParamPos) 1343 CD->setParam(I, ReadDeclAs<ImplicitParamDecl>()); 1344 else 1345 CD->setContextParam(I, ReadDeclAs<ImplicitParamDecl>()); 1346 } 1347 } 1348 1349 void ASTDeclReader::VisitLinkageSpecDecl(LinkageSpecDecl *D) { 1350 VisitDecl(D); 1351 D->setLanguage((LinkageSpecDecl::LanguageIDs)Record.readInt()); 1352 D->setExternLoc(ReadSourceLocation()); 1353 D->setRBraceLoc(ReadSourceLocation()); 1354 } 1355 1356 void ASTDeclReader::VisitExportDecl(ExportDecl *D) { 1357 VisitDecl(D); 1358 D->RBraceLoc = ReadSourceLocation(); 1359 } 1360 1361 void ASTDeclReader::VisitLabelDecl(LabelDecl *D) { 1362 VisitNamedDecl(D); 1363 D->setLocStart(ReadSourceLocation()); 1364 } 1365 1366 void ASTDeclReader::VisitNamespaceDecl(NamespaceDecl *D) { 1367 RedeclarableResult Redecl = VisitRedeclarable(D); 1368 VisitNamedDecl(D); 1369 D->setInline(Record.readInt()); 1370 D->LocStart = ReadSourceLocation(); 1371 D->RBraceLoc = ReadSourceLocation(); 1372 1373 // Defer loading the anonymous namespace until we've finished merging 1374 // this namespace; loading it might load a later declaration of the 1375 // same namespace, and we have an invariant that older declarations 1376 // get merged before newer ones try to merge. 1377 GlobalDeclID AnonNamespace = 0; 1378 if (Redecl.getFirstID() == ThisDeclID) { 1379 AnonNamespace = ReadDeclID(); 1380 } else { 1381 // Link this namespace back to the first declaration, which has already 1382 // been deserialized. 1383 D->AnonOrFirstNamespaceAndInline.setPointer(D->getFirstDecl()); 1384 } 1385 1386 mergeRedeclarable(D, Redecl); 1387 1388 if (AnonNamespace) { 1389 // Each module has its own anonymous namespace, which is disjoint from 1390 // any other module's anonymous namespaces, so don't attach the anonymous 1391 // namespace at all. 1392 NamespaceDecl *Anon = cast<NamespaceDecl>(Reader.GetDecl(AnonNamespace)); 1393 if (!Record.isModule()) 1394 D->setAnonymousNamespace(Anon); 1395 } 1396 } 1397 1398 void ASTDeclReader::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) { 1399 RedeclarableResult Redecl = VisitRedeclarable(D); 1400 VisitNamedDecl(D); 1401 D->NamespaceLoc = ReadSourceLocation(); 1402 D->IdentLoc = ReadSourceLocation(); 1403 D->QualifierLoc = Record.readNestedNameSpecifierLoc(); 1404 D->Namespace = ReadDeclAs<NamedDecl>(); 1405 mergeRedeclarable(D, Redecl); 1406 } 1407 1408 void ASTDeclReader::VisitUsingDecl(UsingDecl *D) { 1409 VisitNamedDecl(D); 1410 D->setUsingLoc(ReadSourceLocation()); 1411 D->QualifierLoc = Record.readNestedNameSpecifierLoc(); 1412 ReadDeclarationNameLoc(D->DNLoc, D->getDeclName()); 1413 D->FirstUsingShadow.setPointer(ReadDeclAs<UsingShadowDecl>()); 1414 D->setTypename(Record.readInt()); 1415 if (NamedDecl *Pattern = ReadDeclAs<NamedDecl>()) 1416 Reader.getContext().setInstantiatedFromUsingDecl(D, Pattern); 1417 mergeMergeable(D); 1418 } 1419 1420 void ASTDeclReader::VisitUsingPackDecl(UsingPackDecl *D) { 1421 VisitNamedDecl(D); 1422 D->InstantiatedFrom = ReadDeclAs<NamedDecl>(); 1423 NamedDecl **Expansions = D->getTrailingObjects<NamedDecl*>(); 1424 for (unsigned I = 0; I != D->NumExpansions; ++I) 1425 Expansions[I] = ReadDeclAs<NamedDecl>(); 1426 mergeMergeable(D); 1427 } 1428 1429 void ASTDeclReader::VisitUsingShadowDecl(UsingShadowDecl *D) { 1430 RedeclarableResult Redecl = VisitRedeclarable(D); 1431 VisitNamedDecl(D); 1432 D->setTargetDecl(ReadDeclAs<NamedDecl>()); 1433 D->UsingOrNextShadow = ReadDeclAs<NamedDecl>(); 1434 UsingShadowDecl *Pattern = ReadDeclAs<UsingShadowDecl>(); 1435 if (Pattern) 1436 Reader.getContext().setInstantiatedFromUsingShadowDecl(D, Pattern); 1437 mergeRedeclarable(D, Redecl); 1438 } 1439 1440 void ASTDeclReader::VisitConstructorUsingShadowDecl( 1441 ConstructorUsingShadowDecl *D) { 1442 VisitUsingShadowDecl(D); 1443 D->NominatedBaseClassShadowDecl = ReadDeclAs<ConstructorUsingShadowDecl>(); 1444 D->ConstructedBaseClassShadowDecl = ReadDeclAs<ConstructorUsingShadowDecl>(); 1445 D->IsVirtual = Record.readInt(); 1446 } 1447 1448 void ASTDeclReader::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) { 1449 VisitNamedDecl(D); 1450 D->UsingLoc = ReadSourceLocation(); 1451 D->NamespaceLoc = ReadSourceLocation(); 1452 D->QualifierLoc = Record.readNestedNameSpecifierLoc(); 1453 D->NominatedNamespace = ReadDeclAs<NamedDecl>(); 1454 D->CommonAncestor = ReadDeclAs<DeclContext>(); 1455 } 1456 1457 void ASTDeclReader::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) { 1458 VisitValueDecl(D); 1459 D->setUsingLoc(ReadSourceLocation()); 1460 D->QualifierLoc = Record.readNestedNameSpecifierLoc(); 1461 ReadDeclarationNameLoc(D->DNLoc, D->getDeclName()); 1462 D->EllipsisLoc = ReadSourceLocation(); 1463 mergeMergeable(D); 1464 } 1465 1466 void ASTDeclReader::VisitUnresolvedUsingTypenameDecl( 1467 UnresolvedUsingTypenameDecl *D) { 1468 VisitTypeDecl(D); 1469 D->TypenameLocation = ReadSourceLocation(); 1470 D->QualifierLoc = Record.readNestedNameSpecifierLoc(); 1471 D->EllipsisLoc = ReadSourceLocation(); 1472 mergeMergeable(D); 1473 } 1474 1475 void ASTDeclReader::ReadCXXDefinitionData( 1476 struct CXXRecordDecl::DefinitionData &Data) { 1477 // Note: the caller has deserialized the IsLambda bit already. 1478 Data.UserDeclaredConstructor = Record.readInt(); 1479 Data.UserDeclaredSpecialMembers = Record.readInt(); 1480 Data.Aggregate = Record.readInt(); 1481 Data.PlainOldData = Record.readInt(); 1482 Data.Empty = Record.readInt(); 1483 Data.Polymorphic = Record.readInt(); 1484 Data.Abstract = Record.readInt(); 1485 Data.IsStandardLayout = Record.readInt(); 1486 Data.HasNoNonEmptyBases = Record.readInt(); 1487 Data.HasPrivateFields = Record.readInt(); 1488 Data.HasProtectedFields = Record.readInt(); 1489 Data.HasPublicFields = Record.readInt(); 1490 Data.HasMutableFields = Record.readInt(); 1491 Data.HasVariantMembers = Record.readInt(); 1492 Data.HasOnlyCMembers = Record.readInt(); 1493 Data.HasInClassInitializer = Record.readInt(); 1494 Data.HasUninitializedReferenceMember = Record.readInt(); 1495 Data.HasUninitializedFields = Record.readInt(); 1496 Data.HasInheritedConstructor = Record.readInt(); 1497 Data.HasInheritedAssignment = Record.readInt(); 1498 Data.NeedOverloadResolutionForMoveConstructor = Record.readInt(); 1499 Data.NeedOverloadResolutionForMoveAssignment = Record.readInt(); 1500 Data.NeedOverloadResolutionForDestructor = Record.readInt(); 1501 Data.DefaultedMoveConstructorIsDeleted = Record.readInt(); 1502 Data.DefaultedMoveAssignmentIsDeleted = Record.readInt(); 1503 Data.DefaultedDestructorIsDeleted = Record.readInt(); 1504 Data.HasTrivialSpecialMembers = Record.readInt(); 1505 Data.DeclaredNonTrivialSpecialMembers = Record.readInt(); 1506 Data.HasIrrelevantDestructor = Record.readInt(); 1507 Data.HasConstexprNonCopyMoveConstructor = Record.readInt(); 1508 Data.HasDefaultedDefaultConstructor = Record.readInt(); 1509 Data.DefaultedDefaultConstructorIsConstexpr = Record.readInt(); 1510 Data.HasConstexprDefaultConstructor = Record.readInt(); 1511 Data.HasNonLiteralTypeFieldsOrBases = Record.readInt(); 1512 Data.ComputedVisibleConversions = Record.readInt(); 1513 Data.UserProvidedDefaultConstructor = Record.readInt(); 1514 Data.DeclaredSpecialMembers = Record.readInt(); 1515 Data.ImplicitCopyConstructorHasConstParam = Record.readInt(); 1516 Data.ImplicitCopyAssignmentHasConstParam = Record.readInt(); 1517 Data.HasDeclaredCopyConstructorWithConstParam = Record.readInt(); 1518 Data.HasDeclaredCopyAssignmentWithConstParam = Record.readInt(); 1519 1520 Data.NumBases = Record.readInt(); 1521 if (Data.NumBases) 1522 Data.Bases = ReadGlobalOffset(); 1523 Data.NumVBases = Record.readInt(); 1524 if (Data.NumVBases) 1525 Data.VBases = ReadGlobalOffset(); 1526 1527 Record.readUnresolvedSet(Data.Conversions); 1528 Record.readUnresolvedSet(Data.VisibleConversions); 1529 assert(Data.Definition && "Data.Definition should be already set!"); 1530 Data.FirstFriend = ReadDeclID(); 1531 1532 if (Data.IsLambda) { 1533 typedef LambdaCapture Capture; 1534 CXXRecordDecl::LambdaDefinitionData &Lambda 1535 = static_cast<CXXRecordDecl::LambdaDefinitionData &>(Data); 1536 Lambda.Dependent = Record.readInt(); 1537 Lambda.IsGenericLambda = Record.readInt(); 1538 Lambda.CaptureDefault = Record.readInt(); 1539 Lambda.NumCaptures = Record.readInt(); 1540 Lambda.NumExplicitCaptures = Record.readInt(); 1541 Lambda.ManglingNumber = Record.readInt(); 1542 Lambda.ContextDecl = ReadDeclID(); 1543 Lambda.Captures 1544 = (Capture*)Reader.Context.Allocate(sizeof(Capture)*Lambda.NumCaptures); 1545 Capture *ToCapture = Lambda.Captures; 1546 Lambda.MethodTyInfo = GetTypeSourceInfo(); 1547 for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) { 1548 SourceLocation Loc = ReadSourceLocation(); 1549 bool IsImplicit = Record.readInt(); 1550 LambdaCaptureKind Kind = static_cast<LambdaCaptureKind>(Record.readInt()); 1551 switch (Kind) { 1552 case LCK_StarThis: 1553 case LCK_This: 1554 case LCK_VLAType: 1555 *ToCapture++ = Capture(Loc, IsImplicit, Kind, nullptr,SourceLocation()); 1556 break; 1557 case LCK_ByCopy: 1558 case LCK_ByRef: 1559 VarDecl *Var = ReadDeclAs<VarDecl>(); 1560 SourceLocation EllipsisLoc = ReadSourceLocation(); 1561 *ToCapture++ = Capture(Loc, IsImplicit, Kind, Var, EllipsisLoc); 1562 break; 1563 } 1564 } 1565 } 1566 } 1567 1568 void ASTDeclReader::MergeDefinitionData( 1569 CXXRecordDecl *D, struct CXXRecordDecl::DefinitionData &&MergeDD) { 1570 assert(D->DefinitionData && 1571 "merging class definition into non-definition"); 1572 auto &DD = *D->DefinitionData; 1573 1574 if (DD.Definition != MergeDD.Definition) { 1575 // Track that we merged the definitions. 1576 Reader.MergedDeclContexts.insert(std::make_pair(MergeDD.Definition, 1577 DD.Definition)); 1578 Reader.PendingDefinitions.erase(MergeDD.Definition); 1579 MergeDD.Definition->IsCompleteDefinition = false; 1580 Reader.mergeDefinitionVisibility(DD.Definition, MergeDD.Definition); 1581 assert(Reader.Lookups.find(MergeDD.Definition) == Reader.Lookups.end() && 1582 "already loaded pending lookups for merged definition"); 1583 } 1584 1585 auto PFDI = Reader.PendingFakeDefinitionData.find(&DD); 1586 if (PFDI != Reader.PendingFakeDefinitionData.end() && 1587 PFDI->second == ASTReader::PendingFakeDefinitionKind::Fake) { 1588 // We faked up this definition data because we found a class for which we'd 1589 // not yet loaded the definition. Replace it with the real thing now. 1590 assert(!DD.IsLambda && !MergeDD.IsLambda && "faked up lambda definition?"); 1591 PFDI->second = ASTReader::PendingFakeDefinitionKind::FakeLoaded; 1592 1593 // Don't change which declaration is the definition; that is required 1594 // to be invariant once we select it. 1595 auto *Def = DD.Definition; 1596 DD = std::move(MergeDD); 1597 DD.Definition = Def; 1598 return; 1599 } 1600 1601 // FIXME: Move this out into a .def file? 1602 bool DetectedOdrViolation = false; 1603 #define OR_FIELD(Field) DD.Field |= MergeDD.Field; 1604 #define MATCH_FIELD(Field) \ 1605 DetectedOdrViolation |= DD.Field != MergeDD.Field; \ 1606 OR_FIELD(Field) 1607 MATCH_FIELD(UserDeclaredConstructor) 1608 MATCH_FIELD(UserDeclaredSpecialMembers) 1609 MATCH_FIELD(Aggregate) 1610 MATCH_FIELD(PlainOldData) 1611 MATCH_FIELD(Empty) 1612 MATCH_FIELD(Polymorphic) 1613 MATCH_FIELD(Abstract) 1614 MATCH_FIELD(IsStandardLayout) 1615 MATCH_FIELD(HasNoNonEmptyBases) 1616 MATCH_FIELD(HasPrivateFields) 1617 MATCH_FIELD(HasProtectedFields) 1618 MATCH_FIELD(HasPublicFields) 1619 MATCH_FIELD(HasMutableFields) 1620 MATCH_FIELD(HasVariantMembers) 1621 MATCH_FIELD(HasOnlyCMembers) 1622 MATCH_FIELD(HasInClassInitializer) 1623 MATCH_FIELD(HasUninitializedReferenceMember) 1624 MATCH_FIELD(HasUninitializedFields) 1625 MATCH_FIELD(HasInheritedConstructor) 1626 MATCH_FIELD(HasInheritedAssignment) 1627 MATCH_FIELD(NeedOverloadResolutionForMoveConstructor) 1628 MATCH_FIELD(NeedOverloadResolutionForMoveAssignment) 1629 MATCH_FIELD(NeedOverloadResolutionForDestructor) 1630 MATCH_FIELD(DefaultedMoveConstructorIsDeleted) 1631 MATCH_FIELD(DefaultedMoveAssignmentIsDeleted) 1632 MATCH_FIELD(DefaultedDestructorIsDeleted) 1633 OR_FIELD(HasTrivialSpecialMembers) 1634 OR_FIELD(DeclaredNonTrivialSpecialMembers) 1635 MATCH_FIELD(HasIrrelevantDestructor) 1636 OR_FIELD(HasConstexprNonCopyMoveConstructor) 1637 OR_FIELD(HasDefaultedDefaultConstructor) 1638 MATCH_FIELD(DefaultedDefaultConstructorIsConstexpr) 1639 OR_FIELD(HasConstexprDefaultConstructor) 1640 MATCH_FIELD(HasNonLiteralTypeFieldsOrBases) 1641 // ComputedVisibleConversions is handled below. 1642 MATCH_FIELD(UserProvidedDefaultConstructor) 1643 OR_FIELD(DeclaredSpecialMembers) 1644 MATCH_FIELD(ImplicitCopyConstructorHasConstParam) 1645 MATCH_FIELD(ImplicitCopyAssignmentHasConstParam) 1646 OR_FIELD(HasDeclaredCopyConstructorWithConstParam) 1647 OR_FIELD(HasDeclaredCopyAssignmentWithConstParam) 1648 MATCH_FIELD(IsLambda) 1649 #undef OR_FIELD 1650 #undef MATCH_FIELD 1651 1652 if (DD.NumBases != MergeDD.NumBases || DD.NumVBases != MergeDD.NumVBases) 1653 DetectedOdrViolation = true; 1654 // FIXME: Issue a diagnostic if the base classes don't match when we come 1655 // to lazily load them. 1656 1657 // FIXME: Issue a diagnostic if the list of conversion functions doesn't 1658 // match when we come to lazily load them. 1659 if (MergeDD.ComputedVisibleConversions && !DD.ComputedVisibleConversions) { 1660 DD.VisibleConversions = std::move(MergeDD.VisibleConversions); 1661 DD.ComputedVisibleConversions = true; 1662 } 1663 1664 // FIXME: Issue a diagnostic if FirstFriend doesn't match when we come to 1665 // lazily load it. 1666 1667 if (DD.IsLambda) { 1668 // FIXME: ODR-checking for merging lambdas (this happens, for instance, 1669 // when they occur within the body of a function template specialization). 1670 } 1671 1672 if (DetectedOdrViolation) 1673 Reader.PendingOdrMergeFailures[DD.Definition].push_back(MergeDD.Definition); 1674 } 1675 1676 void ASTDeclReader::ReadCXXRecordDefinition(CXXRecordDecl *D, bool Update) { 1677 struct CXXRecordDecl::DefinitionData *DD; 1678 ASTContext &C = Reader.getContext(); 1679 1680 // Determine whether this is a lambda closure type, so that we can 1681 // allocate the appropriate DefinitionData structure. 1682 bool IsLambda = Record.readInt(); 1683 if (IsLambda) 1684 DD = new (C) CXXRecordDecl::LambdaDefinitionData(D, nullptr, false, false, 1685 LCD_None); 1686 else 1687 DD = new (C) struct CXXRecordDecl::DefinitionData(D); 1688 1689 ReadCXXDefinitionData(*DD); 1690 1691 // We might already have a definition for this record. This can happen either 1692 // because we're reading an update record, or because we've already done some 1693 // merging. Either way, just merge into it. 1694 CXXRecordDecl *Canon = D->getCanonicalDecl(); 1695 if (Canon->DefinitionData) { 1696 MergeDefinitionData(Canon, std::move(*DD)); 1697 D->DefinitionData = Canon->DefinitionData; 1698 return; 1699 } 1700 1701 // Mark this declaration as being a definition. 1702 D->IsCompleteDefinition = true; 1703 D->DefinitionData = DD; 1704 1705 // If this is not the first declaration or is an update record, we can have 1706 // other redeclarations already. Make a note that we need to propagate the 1707 // DefinitionData pointer onto them. 1708 if (Update || Canon != D) { 1709 Canon->DefinitionData = D->DefinitionData; 1710 Reader.PendingDefinitions.insert(D); 1711 } 1712 } 1713 1714 ASTDeclReader::RedeclarableResult 1715 ASTDeclReader::VisitCXXRecordDeclImpl(CXXRecordDecl *D) { 1716 RedeclarableResult Redecl = VisitRecordDeclImpl(D); 1717 1718 ASTContext &C = Reader.getContext(); 1719 1720 enum CXXRecKind { 1721 CXXRecNotTemplate = 0, CXXRecTemplate, CXXRecMemberSpecialization 1722 }; 1723 switch ((CXXRecKind)Record.readInt()) { 1724 case CXXRecNotTemplate: 1725 // Merged when we merge the folding set entry in the primary template. 1726 if (!isa<ClassTemplateSpecializationDecl>(D)) 1727 mergeRedeclarable(D, Redecl); 1728 break; 1729 case CXXRecTemplate: { 1730 // Merged when we merge the template. 1731 ClassTemplateDecl *Template = ReadDeclAs<ClassTemplateDecl>(); 1732 D->TemplateOrInstantiation = Template; 1733 if (!Template->getTemplatedDecl()) { 1734 // We've not actually loaded the ClassTemplateDecl yet, because we're 1735 // currently being loaded as its pattern. Rely on it to set up our 1736 // TypeForDecl (see VisitClassTemplateDecl). 1737 // 1738 // Beware: we do not yet know our canonical declaration, and may still 1739 // get merged once the surrounding class template has got off the ground. 1740 TypeIDForTypeDecl = 0; 1741 } 1742 break; 1743 } 1744 case CXXRecMemberSpecialization: { 1745 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(); 1746 TemplateSpecializationKind TSK = 1747 (TemplateSpecializationKind)Record.readInt(); 1748 SourceLocation POI = ReadSourceLocation(); 1749 MemberSpecializationInfo *MSI = new (C) MemberSpecializationInfo(RD, TSK); 1750 MSI->setPointOfInstantiation(POI); 1751 D->TemplateOrInstantiation = MSI; 1752 mergeRedeclarable(D, Redecl); 1753 break; 1754 } 1755 } 1756 1757 bool WasDefinition = Record.readInt(); 1758 if (WasDefinition) 1759 ReadCXXRecordDefinition(D, /*Update*/false); 1760 else 1761 // Propagate DefinitionData pointer from the canonical declaration. 1762 D->DefinitionData = D->getCanonicalDecl()->DefinitionData; 1763 1764 // Lazily load the key function to avoid deserializing every method so we can 1765 // compute it. 1766 if (WasDefinition) { 1767 DeclID KeyFn = ReadDeclID(); 1768 if (KeyFn && D->IsCompleteDefinition) 1769 // FIXME: This is wrong for the ARM ABI, where some other module may have 1770 // made this function no longer be a key function. We need an update 1771 // record or similar for that case. 1772 C.KeyFunctions[D] = KeyFn; 1773 } 1774 1775 return Redecl; 1776 } 1777 1778 void ASTDeclReader::VisitCXXMethodDecl(CXXMethodDecl *D) { 1779 VisitFunctionDecl(D); 1780 1781 unsigned NumOverridenMethods = Record.readInt(); 1782 if (D->isCanonicalDecl()) { 1783 while (NumOverridenMethods--) { 1784 // Avoid invariant checking of CXXMethodDecl::addOverriddenMethod, 1785 // MD may be initializing. 1786 if (CXXMethodDecl *MD = ReadDeclAs<CXXMethodDecl>()) 1787 Reader.getContext().addOverriddenMethod(D, MD->getCanonicalDecl()); 1788 } 1789 } else { 1790 // We don't care about which declarations this used to override; we get 1791 // the relevant information from the canonical declaration. 1792 Record.skipInts(NumOverridenMethods); 1793 } 1794 } 1795 1796 void ASTDeclReader::VisitCXXConstructorDecl(CXXConstructorDecl *D) { 1797 // We need the inherited constructor information to merge the declaration, 1798 // so we have to read it before we call VisitCXXMethodDecl. 1799 if (D->isInheritingConstructor()) { 1800 auto *Shadow = ReadDeclAs<ConstructorUsingShadowDecl>(); 1801 auto *Ctor = ReadDeclAs<CXXConstructorDecl>(); 1802 *D->getTrailingObjects<InheritedConstructor>() = 1803 InheritedConstructor(Shadow, Ctor); 1804 } 1805 1806 VisitCXXMethodDecl(D); 1807 1808 D->IsExplicitSpecified = Record.readInt(); 1809 } 1810 1811 void ASTDeclReader::VisitCXXDestructorDecl(CXXDestructorDecl *D) { 1812 VisitCXXMethodDecl(D); 1813 1814 if (auto *OperatorDelete = ReadDeclAs<FunctionDecl>()) { 1815 auto *Canon = cast<CXXDestructorDecl>(D->getCanonicalDecl()); 1816 // FIXME: Check consistency if we have an old and new operator delete. 1817 if (!Canon->OperatorDelete) 1818 Canon->OperatorDelete = OperatorDelete; 1819 } 1820 } 1821 1822 void ASTDeclReader::VisitCXXConversionDecl(CXXConversionDecl *D) { 1823 VisitCXXMethodDecl(D); 1824 D->IsExplicitSpecified = Record.readInt(); 1825 } 1826 1827 void ASTDeclReader::VisitImportDecl(ImportDecl *D) { 1828 VisitDecl(D); 1829 D->ImportedAndComplete.setPointer(readModule()); 1830 D->ImportedAndComplete.setInt(Record.readInt()); 1831 SourceLocation *StoredLocs = D->getTrailingObjects<SourceLocation>(); 1832 for (unsigned I = 0, N = Record.back(); I != N; ++I) 1833 StoredLocs[I] = ReadSourceLocation(); 1834 (void)Record.readInt(); // The number of stored source locations. 1835 } 1836 1837 void ASTDeclReader::VisitAccessSpecDecl(AccessSpecDecl *D) { 1838 VisitDecl(D); 1839 D->setColonLoc(ReadSourceLocation()); 1840 } 1841 1842 void ASTDeclReader::VisitFriendDecl(FriendDecl *D) { 1843 VisitDecl(D); 1844 if (Record.readInt()) // hasFriendDecl 1845 D->Friend = ReadDeclAs<NamedDecl>(); 1846 else 1847 D->Friend = GetTypeSourceInfo(); 1848 for (unsigned i = 0; i != D->NumTPLists; ++i) 1849 D->getTrailingObjects<TemplateParameterList *>()[i] = 1850 Record.readTemplateParameterList(); 1851 D->NextFriend = ReadDeclID(); 1852 D->UnsupportedFriend = (Record.readInt() != 0); 1853 D->FriendLoc = ReadSourceLocation(); 1854 } 1855 1856 void ASTDeclReader::VisitFriendTemplateDecl(FriendTemplateDecl *D) { 1857 VisitDecl(D); 1858 unsigned NumParams = Record.readInt(); 1859 D->NumParams = NumParams; 1860 D->Params = new TemplateParameterList*[NumParams]; 1861 for (unsigned i = 0; i != NumParams; ++i) 1862 D->Params[i] = Record.readTemplateParameterList(); 1863 if (Record.readInt()) // HasFriendDecl 1864 D->Friend = ReadDeclAs<NamedDecl>(); 1865 else 1866 D->Friend = GetTypeSourceInfo(); 1867 D->FriendLoc = ReadSourceLocation(); 1868 } 1869 1870 DeclID ASTDeclReader::VisitTemplateDecl(TemplateDecl *D) { 1871 VisitNamedDecl(D); 1872 1873 DeclID PatternID = ReadDeclID(); 1874 NamedDecl *TemplatedDecl = cast_or_null<NamedDecl>(Reader.GetDecl(PatternID)); 1875 TemplateParameterList *TemplateParams = Record.readTemplateParameterList(); 1876 D->init(TemplatedDecl, TemplateParams); 1877 1878 return PatternID; 1879 } 1880 1881 ASTDeclReader::RedeclarableResult 1882 ASTDeclReader::VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D) { 1883 RedeclarableResult Redecl = VisitRedeclarable(D); 1884 1885 // Make sure we've allocated the Common pointer first. We do this before 1886 // VisitTemplateDecl so that getCommonPtr() can be used during initialization. 1887 RedeclarableTemplateDecl *CanonD = D->getCanonicalDecl(); 1888 if (!CanonD->Common) { 1889 CanonD->Common = CanonD->newCommon(Reader.getContext()); 1890 Reader.PendingDefinitions.insert(CanonD); 1891 } 1892 D->Common = CanonD->Common; 1893 1894 // If this is the first declaration of the template, fill in the information 1895 // for the 'common' pointer. 1896 if (ThisDeclID == Redecl.getFirstID()) { 1897 if (RedeclarableTemplateDecl *RTD 1898 = ReadDeclAs<RedeclarableTemplateDecl>()) { 1899 assert(RTD->getKind() == D->getKind() && 1900 "InstantiatedFromMemberTemplate kind mismatch"); 1901 D->setInstantiatedFromMemberTemplate(RTD); 1902 if (Record.readInt()) 1903 D->setMemberSpecialization(); 1904 } 1905 } 1906 1907 DeclID PatternID = VisitTemplateDecl(D); 1908 D->IdentifierNamespace = Record.readInt(); 1909 1910 mergeRedeclarable(D, Redecl, PatternID); 1911 1912 // If we merged the template with a prior declaration chain, merge the common 1913 // pointer. 1914 // FIXME: Actually merge here, don't just overwrite. 1915 D->Common = D->getCanonicalDecl()->Common; 1916 1917 return Redecl; 1918 } 1919 1920 static DeclID *newDeclIDList(ASTContext &Context, DeclID *Old, 1921 SmallVectorImpl<DeclID> &IDs) { 1922 assert(!IDs.empty() && "no IDs to add to list"); 1923 if (Old) { 1924 IDs.insert(IDs.end(), Old + 1, Old + 1 + Old[0]); 1925 std::sort(IDs.begin(), IDs.end()); 1926 IDs.erase(std::unique(IDs.begin(), IDs.end()), IDs.end()); 1927 } 1928 1929 auto *Result = new (Context) DeclID[1 + IDs.size()]; 1930 *Result = IDs.size(); 1931 std::copy(IDs.begin(), IDs.end(), Result + 1); 1932 return Result; 1933 } 1934 1935 void ASTDeclReader::VisitClassTemplateDecl(ClassTemplateDecl *D) { 1936 RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D); 1937 1938 if (ThisDeclID == Redecl.getFirstID()) { 1939 // This ClassTemplateDecl owns a CommonPtr; read it to keep track of all of 1940 // the specializations. 1941 SmallVector<serialization::DeclID, 32> SpecIDs; 1942 ReadDeclIDList(SpecIDs); 1943 1944 if (!SpecIDs.empty()) { 1945 auto *CommonPtr = D->getCommonPtr(); 1946 CommonPtr->LazySpecializations = newDeclIDList( 1947 Reader.getContext(), CommonPtr->LazySpecializations, SpecIDs); 1948 } 1949 } 1950 1951 if (D->getTemplatedDecl()->TemplateOrInstantiation) { 1952 // We were loaded before our templated declaration was. We've not set up 1953 // its corresponding type yet (see VisitCXXRecordDeclImpl), so reconstruct 1954 // it now. 1955 Reader.Context.getInjectedClassNameType( 1956 D->getTemplatedDecl(), D->getInjectedClassNameSpecialization()); 1957 } 1958 } 1959 1960 void ASTDeclReader::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) { 1961 llvm_unreachable("BuiltinTemplates are not serialized"); 1962 } 1963 1964 /// TODO: Unify with ClassTemplateDecl version? 1965 /// May require unifying ClassTemplateDecl and 1966 /// VarTemplateDecl beyond TemplateDecl... 1967 void ASTDeclReader::VisitVarTemplateDecl(VarTemplateDecl *D) { 1968 RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D); 1969 1970 if (ThisDeclID == Redecl.getFirstID()) { 1971 // This VarTemplateDecl owns a CommonPtr; read it to keep track of all of 1972 // the specializations. 1973 SmallVector<serialization::DeclID, 32> SpecIDs; 1974 ReadDeclIDList(SpecIDs); 1975 1976 if (!SpecIDs.empty()) { 1977 auto *CommonPtr = D->getCommonPtr(); 1978 CommonPtr->LazySpecializations = newDeclIDList( 1979 Reader.getContext(), CommonPtr->LazySpecializations, SpecIDs); 1980 } 1981 } 1982 } 1983 1984 ASTDeclReader::RedeclarableResult 1985 ASTDeclReader::VisitClassTemplateSpecializationDeclImpl( 1986 ClassTemplateSpecializationDecl *D) { 1987 RedeclarableResult Redecl = VisitCXXRecordDeclImpl(D); 1988 1989 ASTContext &C = Reader.getContext(); 1990 if (Decl *InstD = ReadDecl()) { 1991 if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(InstD)) { 1992 D->SpecializedTemplate = CTD; 1993 } else { 1994 SmallVector<TemplateArgument, 8> TemplArgs; 1995 Record.readTemplateArgumentList(TemplArgs); 1996 TemplateArgumentList *ArgList 1997 = TemplateArgumentList::CreateCopy(C, TemplArgs); 1998 ClassTemplateSpecializationDecl::SpecializedPartialSpecialization *PS 1999 = new (C) ClassTemplateSpecializationDecl:: 2000 SpecializedPartialSpecialization(); 2001 PS->PartialSpecialization 2002 = cast<ClassTemplatePartialSpecializationDecl>(InstD); 2003 PS->TemplateArgs = ArgList; 2004 D->SpecializedTemplate = PS; 2005 } 2006 } 2007 2008 SmallVector<TemplateArgument, 8> TemplArgs; 2009 Record.readTemplateArgumentList(TemplArgs, /*Canonicalize*/ true); 2010 D->TemplateArgs = TemplateArgumentList::CreateCopy(C, TemplArgs); 2011 D->PointOfInstantiation = ReadSourceLocation(); 2012 D->SpecializationKind = (TemplateSpecializationKind)Record.readInt(); 2013 2014 bool writtenAsCanonicalDecl = Record.readInt(); 2015 if (writtenAsCanonicalDecl) { 2016 ClassTemplateDecl *CanonPattern = ReadDeclAs<ClassTemplateDecl>(); 2017 if (D->isCanonicalDecl()) { // It's kept in the folding set. 2018 // Set this as, or find, the canonical declaration for this specialization 2019 ClassTemplateSpecializationDecl *CanonSpec; 2020 if (ClassTemplatePartialSpecializationDecl *Partial = 2021 dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) { 2022 CanonSpec = CanonPattern->getCommonPtr()->PartialSpecializations 2023 .GetOrInsertNode(Partial); 2024 } else { 2025 CanonSpec = 2026 CanonPattern->getCommonPtr()->Specializations.GetOrInsertNode(D); 2027 } 2028 // If there was already a canonical specialization, merge into it. 2029 if (CanonSpec != D) { 2030 mergeRedeclarable<TagDecl>(D, CanonSpec, Redecl); 2031 2032 // This declaration might be a definition. Merge with any existing 2033 // definition. 2034 if (auto *DDD = D->DefinitionData) { 2035 if (CanonSpec->DefinitionData) 2036 MergeDefinitionData(CanonSpec, std::move(*DDD)); 2037 else 2038 CanonSpec->DefinitionData = D->DefinitionData; 2039 } 2040 D->DefinitionData = CanonSpec->DefinitionData; 2041 } 2042 } 2043 } 2044 2045 // Explicit info. 2046 if (TypeSourceInfo *TyInfo = GetTypeSourceInfo()) { 2047 ClassTemplateSpecializationDecl::ExplicitSpecializationInfo *ExplicitInfo 2048 = new (C) ClassTemplateSpecializationDecl::ExplicitSpecializationInfo; 2049 ExplicitInfo->TypeAsWritten = TyInfo; 2050 ExplicitInfo->ExternLoc = ReadSourceLocation(); 2051 ExplicitInfo->TemplateKeywordLoc = ReadSourceLocation(); 2052 D->ExplicitInfo = ExplicitInfo; 2053 } 2054 2055 return Redecl; 2056 } 2057 2058 void ASTDeclReader::VisitClassTemplatePartialSpecializationDecl( 2059 ClassTemplatePartialSpecializationDecl *D) { 2060 RedeclarableResult Redecl = VisitClassTemplateSpecializationDeclImpl(D); 2061 2062 D->TemplateParams = Record.readTemplateParameterList(); 2063 D->ArgsAsWritten = Record.readASTTemplateArgumentListInfo(); 2064 2065 // These are read/set from/to the first declaration. 2066 if (ThisDeclID == Redecl.getFirstID()) { 2067 D->InstantiatedFromMember.setPointer( 2068 ReadDeclAs<ClassTemplatePartialSpecializationDecl>()); 2069 D->InstantiatedFromMember.setInt(Record.readInt()); 2070 } 2071 } 2072 2073 void ASTDeclReader::VisitClassScopeFunctionSpecializationDecl( 2074 ClassScopeFunctionSpecializationDecl *D) { 2075 VisitDecl(D); 2076 D->Specialization = ReadDeclAs<CXXMethodDecl>(); 2077 } 2078 2079 void ASTDeclReader::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) { 2080 RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D); 2081 2082 if (ThisDeclID == Redecl.getFirstID()) { 2083 // This FunctionTemplateDecl owns a CommonPtr; read it. 2084 SmallVector<serialization::DeclID, 32> SpecIDs; 2085 ReadDeclIDList(SpecIDs); 2086 2087 if (!SpecIDs.empty()) { 2088 auto *CommonPtr = D->getCommonPtr(); 2089 CommonPtr->LazySpecializations = newDeclIDList( 2090 Reader.getContext(), CommonPtr->LazySpecializations, SpecIDs); 2091 } 2092 } 2093 } 2094 2095 /// TODO: Unify with ClassTemplateSpecializationDecl version? 2096 /// May require unifying ClassTemplate(Partial)SpecializationDecl and 2097 /// VarTemplate(Partial)SpecializationDecl with a new data 2098 /// structure Template(Partial)SpecializationDecl, and 2099 /// using Template(Partial)SpecializationDecl as input type. 2100 ASTDeclReader::RedeclarableResult 2101 ASTDeclReader::VisitVarTemplateSpecializationDeclImpl( 2102 VarTemplateSpecializationDecl *D) { 2103 RedeclarableResult Redecl = VisitVarDeclImpl(D); 2104 2105 ASTContext &C = Reader.getContext(); 2106 if (Decl *InstD = ReadDecl()) { 2107 if (VarTemplateDecl *VTD = dyn_cast<VarTemplateDecl>(InstD)) { 2108 D->SpecializedTemplate = VTD; 2109 } else { 2110 SmallVector<TemplateArgument, 8> TemplArgs; 2111 Record.readTemplateArgumentList(TemplArgs); 2112 TemplateArgumentList *ArgList = TemplateArgumentList::CreateCopy( 2113 C, TemplArgs); 2114 VarTemplateSpecializationDecl::SpecializedPartialSpecialization *PS = 2115 new (C) 2116 VarTemplateSpecializationDecl::SpecializedPartialSpecialization(); 2117 PS->PartialSpecialization = 2118 cast<VarTemplatePartialSpecializationDecl>(InstD); 2119 PS->TemplateArgs = ArgList; 2120 D->SpecializedTemplate = PS; 2121 } 2122 } 2123 2124 // Explicit info. 2125 if (TypeSourceInfo *TyInfo = GetTypeSourceInfo()) { 2126 VarTemplateSpecializationDecl::ExplicitSpecializationInfo *ExplicitInfo = 2127 new (C) VarTemplateSpecializationDecl::ExplicitSpecializationInfo; 2128 ExplicitInfo->TypeAsWritten = TyInfo; 2129 ExplicitInfo->ExternLoc = ReadSourceLocation(); 2130 ExplicitInfo->TemplateKeywordLoc = ReadSourceLocation(); 2131 D->ExplicitInfo = ExplicitInfo; 2132 } 2133 2134 SmallVector<TemplateArgument, 8> TemplArgs; 2135 Record.readTemplateArgumentList(TemplArgs, /*Canonicalize*/ true); 2136 D->TemplateArgs = TemplateArgumentList::CreateCopy(C, TemplArgs); 2137 D->PointOfInstantiation = ReadSourceLocation(); 2138 D->SpecializationKind = (TemplateSpecializationKind)Record.readInt(); 2139 2140 bool writtenAsCanonicalDecl = Record.readInt(); 2141 if (writtenAsCanonicalDecl) { 2142 VarTemplateDecl *CanonPattern = ReadDeclAs<VarTemplateDecl>(); 2143 if (D->isCanonicalDecl()) { // It's kept in the folding set. 2144 // FIXME: If it's already present, merge it. 2145 if (VarTemplatePartialSpecializationDecl *Partial = 2146 dyn_cast<VarTemplatePartialSpecializationDecl>(D)) { 2147 CanonPattern->getCommonPtr()->PartialSpecializations 2148 .GetOrInsertNode(Partial); 2149 } else { 2150 CanonPattern->getCommonPtr()->Specializations.GetOrInsertNode(D); 2151 } 2152 } 2153 } 2154 2155 return Redecl; 2156 } 2157 2158 /// TODO: Unify with ClassTemplatePartialSpecializationDecl version? 2159 /// May require unifying ClassTemplate(Partial)SpecializationDecl and 2160 /// VarTemplate(Partial)SpecializationDecl with a new data 2161 /// structure Template(Partial)SpecializationDecl, and 2162 /// using Template(Partial)SpecializationDecl as input type. 2163 void ASTDeclReader::VisitVarTemplatePartialSpecializationDecl( 2164 VarTemplatePartialSpecializationDecl *D) { 2165 RedeclarableResult Redecl = VisitVarTemplateSpecializationDeclImpl(D); 2166 2167 D->TemplateParams = Record.readTemplateParameterList(); 2168 D->ArgsAsWritten = Record.readASTTemplateArgumentListInfo(); 2169 2170 // These are read/set from/to the first declaration. 2171 if (ThisDeclID == Redecl.getFirstID()) { 2172 D->InstantiatedFromMember.setPointer( 2173 ReadDeclAs<VarTemplatePartialSpecializationDecl>()); 2174 D->InstantiatedFromMember.setInt(Record.readInt()); 2175 } 2176 } 2177 2178 void ASTDeclReader::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) { 2179 VisitTypeDecl(D); 2180 2181 D->setDeclaredWithTypename(Record.readInt()); 2182 2183 if (Record.readInt()) 2184 D->setDefaultArgument(GetTypeSourceInfo()); 2185 } 2186 2187 void ASTDeclReader::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) { 2188 VisitDeclaratorDecl(D); 2189 // TemplateParmPosition. 2190 D->setDepth(Record.readInt()); 2191 D->setPosition(Record.readInt()); 2192 if (D->isExpandedParameterPack()) { 2193 auto TypesAndInfos = 2194 D->getTrailingObjects<std::pair<QualType, TypeSourceInfo *>>(); 2195 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) { 2196 new (&TypesAndInfos[I].first) QualType(Record.readType()); 2197 TypesAndInfos[I].second = GetTypeSourceInfo(); 2198 } 2199 } else { 2200 // Rest of NonTypeTemplateParmDecl. 2201 D->ParameterPack = Record.readInt(); 2202 if (Record.readInt()) 2203 D->setDefaultArgument(Record.readExpr()); 2204 } 2205 } 2206 2207 void ASTDeclReader::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) { 2208 VisitTemplateDecl(D); 2209 // TemplateParmPosition. 2210 D->setDepth(Record.readInt()); 2211 D->setPosition(Record.readInt()); 2212 if (D->isExpandedParameterPack()) { 2213 TemplateParameterList **Data = 2214 D->getTrailingObjects<TemplateParameterList *>(); 2215 for (unsigned I = 0, N = D->getNumExpansionTemplateParameters(); 2216 I != N; ++I) 2217 Data[I] = Record.readTemplateParameterList(); 2218 } else { 2219 // Rest of TemplateTemplateParmDecl. 2220 D->ParameterPack = Record.readInt(); 2221 if (Record.readInt()) 2222 D->setDefaultArgument(Reader.getContext(), 2223 Record.readTemplateArgumentLoc()); 2224 } 2225 } 2226 2227 void ASTDeclReader::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) { 2228 VisitRedeclarableTemplateDecl(D); 2229 } 2230 2231 void ASTDeclReader::VisitStaticAssertDecl(StaticAssertDecl *D) { 2232 VisitDecl(D); 2233 D->AssertExprAndFailed.setPointer(Record.readExpr()); 2234 D->AssertExprAndFailed.setInt(Record.readInt()); 2235 D->Message = cast_or_null<StringLiteral>(Record.readExpr()); 2236 D->RParenLoc = ReadSourceLocation(); 2237 } 2238 2239 void ASTDeclReader::VisitEmptyDecl(EmptyDecl *D) { 2240 VisitDecl(D); 2241 } 2242 2243 std::pair<uint64_t, uint64_t> 2244 ASTDeclReader::VisitDeclContext(DeclContext *DC) { 2245 uint64_t LexicalOffset = ReadLocalOffset(); 2246 uint64_t VisibleOffset = ReadLocalOffset(); 2247 return std::make_pair(LexicalOffset, VisibleOffset); 2248 } 2249 2250 template <typename T> 2251 ASTDeclReader::RedeclarableResult 2252 ASTDeclReader::VisitRedeclarable(Redeclarable<T> *D) { 2253 DeclID FirstDeclID = ReadDeclID(); 2254 Decl *MergeWith = nullptr; 2255 2256 bool IsKeyDecl = ThisDeclID == FirstDeclID; 2257 bool IsFirstLocalDecl = false; 2258 2259 uint64_t RedeclOffset = 0; 2260 2261 // 0 indicates that this declaration was the only declaration of its entity, 2262 // and is used for space optimization. 2263 if (FirstDeclID == 0) { 2264 FirstDeclID = ThisDeclID; 2265 IsKeyDecl = true; 2266 IsFirstLocalDecl = true; 2267 } else if (unsigned N = Record.readInt()) { 2268 // This declaration was the first local declaration, but may have imported 2269 // other declarations. 2270 IsKeyDecl = N == 1; 2271 IsFirstLocalDecl = true; 2272 2273 // We have some declarations that must be before us in our redeclaration 2274 // chain. Read them now, and remember that we ought to merge with one of 2275 // them. 2276 // FIXME: Provide a known merge target to the second and subsequent such 2277 // declaration. 2278 for (unsigned I = 0; I != N - 1; ++I) 2279 MergeWith = ReadDecl(); 2280 2281 RedeclOffset = ReadLocalOffset(); 2282 } else { 2283 // This declaration was not the first local declaration. Read the first 2284 // local declaration now, to trigger the import of other redeclarations. 2285 (void)ReadDecl(); 2286 } 2287 2288 T *FirstDecl = cast_or_null<T>(Reader.GetDecl(FirstDeclID)); 2289 if (FirstDecl != D) { 2290 // We delay loading of the redeclaration chain to avoid deeply nested calls. 2291 // We temporarily set the first (canonical) declaration as the previous one 2292 // which is the one that matters and mark the real previous DeclID to be 2293 // loaded & attached later on. 2294 D->RedeclLink = Redeclarable<T>::PreviousDeclLink(FirstDecl); 2295 D->First = FirstDecl->getCanonicalDecl(); 2296 } 2297 2298 T *DAsT = static_cast<T*>(D); 2299 2300 // Note that we need to load local redeclarations of this decl and build a 2301 // decl chain for them. This must happen *after* we perform the preloading 2302 // above; this ensures that the redeclaration chain is built in the correct 2303 // order. 2304 if (IsFirstLocalDecl) 2305 Reader.PendingDeclChains.push_back(std::make_pair(DAsT, RedeclOffset)); 2306 2307 return RedeclarableResult(MergeWith, FirstDeclID, IsKeyDecl); 2308 } 2309 2310 /// \brief Attempts to merge the given declaration (D) with another declaration 2311 /// of the same entity. 2312 template<typename T> 2313 void ASTDeclReader::mergeRedeclarable(Redeclarable<T> *DBase, 2314 RedeclarableResult &Redecl, 2315 DeclID TemplatePatternID) { 2316 // If modules are not available, there is no reason to perform this merge. 2317 if (!Reader.getContext().getLangOpts().Modules) 2318 return; 2319 2320 // If we're not the canonical declaration, we don't need to merge. 2321 if (!DBase->isFirstDecl()) 2322 return; 2323 2324 T *D = static_cast<T*>(DBase); 2325 2326 if (auto *Existing = Redecl.getKnownMergeTarget()) 2327 // We already know of an existing declaration we should merge with. 2328 mergeRedeclarable(D, cast<T>(Existing), Redecl, TemplatePatternID); 2329 else if (FindExistingResult ExistingRes = findExisting(D)) 2330 if (T *Existing = ExistingRes) 2331 mergeRedeclarable(D, Existing, Redecl, TemplatePatternID); 2332 } 2333 2334 /// \brief "Cast" to type T, asserting if we don't have an implicit conversion. 2335 /// We use this to put code in a template that will only be valid for certain 2336 /// instantiations. 2337 template<typename T> static T assert_cast(T t) { return t; } 2338 template<typename T> static T assert_cast(...) { 2339 llvm_unreachable("bad assert_cast"); 2340 } 2341 2342 /// \brief Merge together the pattern declarations from two template 2343 /// declarations. 2344 void ASTDeclReader::mergeTemplatePattern(RedeclarableTemplateDecl *D, 2345 RedeclarableTemplateDecl *Existing, 2346 DeclID DsID, bool IsKeyDecl) { 2347 auto *DPattern = D->getTemplatedDecl(); 2348 auto *ExistingPattern = Existing->getTemplatedDecl(); 2349 RedeclarableResult Result(/*MergeWith*/ ExistingPattern, 2350 DPattern->getCanonicalDecl()->getGlobalID(), 2351 IsKeyDecl); 2352 2353 if (auto *DClass = dyn_cast<CXXRecordDecl>(DPattern)) { 2354 // Merge with any existing definition. 2355 // FIXME: This is duplicated in several places. Refactor. 2356 auto *ExistingClass = 2357 cast<CXXRecordDecl>(ExistingPattern)->getCanonicalDecl(); 2358 if (auto *DDD = DClass->DefinitionData) { 2359 if (ExistingClass->DefinitionData) { 2360 MergeDefinitionData(ExistingClass, std::move(*DDD)); 2361 } else { 2362 ExistingClass->DefinitionData = DClass->DefinitionData; 2363 // We may have skipped this before because we thought that DClass 2364 // was the canonical declaration. 2365 Reader.PendingDefinitions.insert(DClass); 2366 } 2367 } 2368 DClass->DefinitionData = ExistingClass->DefinitionData; 2369 2370 return mergeRedeclarable(DClass, cast<TagDecl>(ExistingPattern), 2371 Result); 2372 } 2373 if (auto *DFunction = dyn_cast<FunctionDecl>(DPattern)) 2374 return mergeRedeclarable(DFunction, cast<FunctionDecl>(ExistingPattern), 2375 Result); 2376 if (auto *DVar = dyn_cast<VarDecl>(DPattern)) 2377 return mergeRedeclarable(DVar, cast<VarDecl>(ExistingPattern), Result); 2378 if (auto *DAlias = dyn_cast<TypeAliasDecl>(DPattern)) 2379 return mergeRedeclarable(DAlias, cast<TypedefNameDecl>(ExistingPattern), 2380 Result); 2381 llvm_unreachable("merged an unknown kind of redeclarable template"); 2382 } 2383 2384 /// \brief Attempts to merge the given declaration (D) with another declaration 2385 /// of the same entity. 2386 template<typename T> 2387 void ASTDeclReader::mergeRedeclarable(Redeclarable<T> *DBase, T *Existing, 2388 RedeclarableResult &Redecl, 2389 DeclID TemplatePatternID) { 2390 T *D = static_cast<T*>(DBase); 2391 T *ExistingCanon = Existing->getCanonicalDecl(); 2392 T *DCanon = D->getCanonicalDecl(); 2393 if (ExistingCanon != DCanon) { 2394 assert(DCanon->getGlobalID() == Redecl.getFirstID() && 2395 "already merged this declaration"); 2396 2397 // Have our redeclaration link point back at the canonical declaration 2398 // of the existing declaration, so that this declaration has the 2399 // appropriate canonical declaration. 2400 D->RedeclLink = Redeclarable<T>::PreviousDeclLink(ExistingCanon); 2401 D->First = ExistingCanon; 2402 ExistingCanon->Used |= D->Used; 2403 D->Used = false; 2404 2405 // When we merge a namespace, update its pointer to the first namespace. 2406 // We cannot have loaded any redeclarations of this declaration yet, so 2407 // there's nothing else that needs to be updated. 2408 if (auto *Namespace = dyn_cast<NamespaceDecl>(D)) 2409 Namespace->AnonOrFirstNamespaceAndInline.setPointer( 2410 assert_cast<NamespaceDecl*>(ExistingCanon)); 2411 2412 // When we merge a template, merge its pattern. 2413 if (auto *DTemplate = dyn_cast<RedeclarableTemplateDecl>(D)) 2414 mergeTemplatePattern( 2415 DTemplate, assert_cast<RedeclarableTemplateDecl*>(ExistingCanon), 2416 TemplatePatternID, Redecl.isKeyDecl()); 2417 2418 // If this declaration is a key declaration, make a note of that. 2419 if (Redecl.isKeyDecl()) 2420 Reader.KeyDecls[ExistingCanon].push_back(Redecl.getFirstID()); 2421 } 2422 } 2423 2424 /// \brief Attempts to merge the given declaration (D) with another declaration 2425 /// of the same entity, for the case where the entity is not actually 2426 /// redeclarable. This happens, for instance, when merging the fields of 2427 /// identical class definitions from two different modules. 2428 template<typename T> 2429 void ASTDeclReader::mergeMergeable(Mergeable<T> *D) { 2430 // If modules are not available, there is no reason to perform this merge. 2431 if (!Reader.getContext().getLangOpts().Modules) 2432 return; 2433 2434 // ODR-based merging is only performed in C++. In C, identically-named things 2435 // in different translation units are not redeclarations (but may still have 2436 // compatible types). 2437 if (!Reader.getContext().getLangOpts().CPlusPlus) 2438 return; 2439 2440 if (FindExistingResult ExistingRes = findExisting(static_cast<T*>(D))) 2441 if (T *Existing = ExistingRes) 2442 Reader.Context.setPrimaryMergedDecl(static_cast<T*>(D), 2443 Existing->getCanonicalDecl()); 2444 } 2445 2446 void ASTDeclReader::VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D) { 2447 VisitDecl(D); 2448 unsigned NumVars = D->varlist_size(); 2449 SmallVector<Expr *, 16> Vars; 2450 Vars.reserve(NumVars); 2451 for (unsigned i = 0; i != NumVars; ++i) { 2452 Vars.push_back(Record.readExpr()); 2453 } 2454 D->setVars(Vars); 2455 } 2456 2457 void ASTDeclReader::VisitOMPDeclareReductionDecl(OMPDeclareReductionDecl *D) { 2458 VisitValueDecl(D); 2459 D->setLocation(ReadSourceLocation()); 2460 D->setCombiner(Record.readExpr()); 2461 D->setInitializer(Record.readExpr()); 2462 D->PrevDeclInScope = ReadDeclID(); 2463 } 2464 2465 void ASTDeclReader::VisitOMPCapturedExprDecl(OMPCapturedExprDecl *D) { 2466 VisitVarDecl(D); 2467 } 2468 2469 //===----------------------------------------------------------------------===// 2470 // Attribute Reading 2471 //===----------------------------------------------------------------------===// 2472 2473 /// \brief Reads attributes from the current stream position. 2474 void ASTReader::ReadAttributes(ModuleFile &F, AttrVec &Attrs, 2475 const RecordData &Record, unsigned &Idx) { 2476 for (unsigned i = 0, e = Record[Idx++]; i != e; ++i) { 2477 Attr *New = nullptr; 2478 attr::Kind Kind = (attr::Kind)Record[Idx++]; 2479 SourceRange Range = ReadSourceRange(F, Record, Idx); 2480 2481 #include "clang/Serialization/AttrPCHRead.inc" 2482 2483 assert(New && "Unable to decode attribute?"); 2484 Attrs.push_back(New); 2485 } 2486 } 2487 2488 //===----------------------------------------------------------------------===// 2489 // ASTReader Implementation 2490 //===----------------------------------------------------------------------===// 2491 2492 /// \brief Note that we have loaded the declaration with the given 2493 /// Index. 2494 /// 2495 /// This routine notes that this declaration has already been loaded, 2496 /// so that future GetDecl calls will return this declaration rather 2497 /// than trying to load a new declaration. 2498 inline void ASTReader::LoadedDecl(unsigned Index, Decl *D) { 2499 assert(!DeclsLoaded[Index] && "Decl loaded twice?"); 2500 DeclsLoaded[Index] = D; 2501 } 2502 2503 2504 /// \brief Determine whether the consumer will be interested in seeing 2505 /// this declaration (via HandleTopLevelDecl). 2506 /// 2507 /// This routine should return true for anything that might affect 2508 /// code generation, e.g., inline function definitions, Objective-C 2509 /// declarations with metadata, etc. 2510 static bool isConsumerInterestedIn(ASTContext &Ctx, Decl *D, bool HasBody) { 2511 // An ObjCMethodDecl is never considered as "interesting" because its 2512 // implementation container always is. 2513 2514 // An ImportDecl or VarDecl imported from a module will get emitted when 2515 // we import the relevant module. 2516 if ((isa<ImportDecl>(D) || isa<VarDecl>(D)) && Ctx.DeclMustBeEmitted(D) && 2517 D->getImportedOwningModule()) 2518 return false; 2519 2520 if (isa<FileScopeAsmDecl>(D) || 2521 isa<ObjCProtocolDecl>(D) || 2522 isa<ObjCImplDecl>(D) || 2523 isa<ImportDecl>(D) || 2524 isa<PragmaCommentDecl>(D) || 2525 isa<PragmaDetectMismatchDecl>(D)) 2526 return true; 2527 if (isa<OMPThreadPrivateDecl>(D) || isa<OMPDeclareReductionDecl>(D)) 2528 return !D->getDeclContext()->isFunctionOrMethod(); 2529 if (VarDecl *Var = dyn_cast<VarDecl>(D)) 2530 return Var->isFileVarDecl() && 2531 Var->isThisDeclarationADefinition() == VarDecl::Definition; 2532 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(D)) 2533 return Func->doesThisDeclarationHaveABody() || HasBody; 2534 2535 return false; 2536 } 2537 2538 /// \brief Get the correct cursor and offset for loading a declaration. 2539 ASTReader::RecordLocation 2540 ASTReader::DeclCursorForID(DeclID ID, SourceLocation &Loc) { 2541 GlobalDeclMapType::iterator I = GlobalDeclMap.find(ID); 2542 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map"); 2543 ModuleFile *M = I->second; 2544 const DeclOffset &DOffs = 2545 M->DeclOffsets[ID - M->BaseDeclID - NUM_PREDEF_DECL_IDS]; 2546 Loc = TranslateSourceLocation(*M, DOffs.getLocation()); 2547 return RecordLocation(M, DOffs.BitOffset); 2548 } 2549 2550 ASTReader::RecordLocation ASTReader::getLocalBitOffset(uint64_t GlobalOffset) { 2551 ContinuousRangeMap<uint64_t, ModuleFile*, 4>::iterator I 2552 = GlobalBitOffsetsMap.find(GlobalOffset); 2553 2554 assert(I != GlobalBitOffsetsMap.end() && "Corrupted global bit offsets map"); 2555 return RecordLocation(I->second, GlobalOffset - I->second->GlobalBitOffset); 2556 } 2557 2558 uint64_t ASTReader::getGlobalBitOffset(ModuleFile &M, uint32_t LocalOffset) { 2559 return LocalOffset + M.GlobalBitOffset; 2560 } 2561 2562 static bool isSameTemplateParameterList(const TemplateParameterList *X, 2563 const TemplateParameterList *Y); 2564 2565 /// \brief Determine whether two template parameters are similar enough 2566 /// that they may be used in declarations of the same template. 2567 static bool isSameTemplateParameter(const NamedDecl *X, 2568 const NamedDecl *Y) { 2569 if (X->getKind() != Y->getKind()) 2570 return false; 2571 2572 if (const TemplateTypeParmDecl *TX = dyn_cast<TemplateTypeParmDecl>(X)) { 2573 const TemplateTypeParmDecl *TY = cast<TemplateTypeParmDecl>(Y); 2574 return TX->isParameterPack() == TY->isParameterPack(); 2575 } 2576 2577 if (const NonTypeTemplateParmDecl *TX = dyn_cast<NonTypeTemplateParmDecl>(X)) { 2578 const NonTypeTemplateParmDecl *TY = cast<NonTypeTemplateParmDecl>(Y); 2579 return TX->isParameterPack() == TY->isParameterPack() && 2580 TX->getASTContext().hasSameType(TX->getType(), TY->getType()); 2581 } 2582 2583 const TemplateTemplateParmDecl *TX = cast<TemplateTemplateParmDecl>(X); 2584 const TemplateTemplateParmDecl *TY = cast<TemplateTemplateParmDecl>(Y); 2585 return TX->isParameterPack() == TY->isParameterPack() && 2586 isSameTemplateParameterList(TX->getTemplateParameters(), 2587 TY->getTemplateParameters()); 2588 } 2589 2590 static NamespaceDecl *getNamespace(const NestedNameSpecifier *X) { 2591 if (auto *NS = X->getAsNamespace()) 2592 return NS; 2593 if (auto *NAS = X->getAsNamespaceAlias()) 2594 return NAS->getNamespace(); 2595 return nullptr; 2596 } 2597 2598 static bool isSameQualifier(const NestedNameSpecifier *X, 2599 const NestedNameSpecifier *Y) { 2600 if (auto *NSX = getNamespace(X)) { 2601 auto *NSY = getNamespace(Y); 2602 if (!NSY || NSX->getCanonicalDecl() != NSY->getCanonicalDecl()) 2603 return false; 2604 } else if (X->getKind() != Y->getKind()) 2605 return false; 2606 2607 // FIXME: For namespaces and types, we're permitted to check that the entity 2608 // is named via the same tokens. We should probably do so. 2609 switch (X->getKind()) { 2610 case NestedNameSpecifier::Identifier: 2611 if (X->getAsIdentifier() != Y->getAsIdentifier()) 2612 return false; 2613 break; 2614 case NestedNameSpecifier::Namespace: 2615 case NestedNameSpecifier::NamespaceAlias: 2616 // We've already checked that we named the same namespace. 2617 break; 2618 case NestedNameSpecifier::TypeSpec: 2619 case NestedNameSpecifier::TypeSpecWithTemplate: 2620 if (X->getAsType()->getCanonicalTypeInternal() != 2621 Y->getAsType()->getCanonicalTypeInternal()) 2622 return false; 2623 break; 2624 case NestedNameSpecifier::Global: 2625 case NestedNameSpecifier::Super: 2626 return true; 2627 } 2628 2629 // Recurse into earlier portion of NNS, if any. 2630 auto *PX = X->getPrefix(); 2631 auto *PY = Y->getPrefix(); 2632 if (PX && PY) 2633 return isSameQualifier(PX, PY); 2634 return !PX && !PY; 2635 } 2636 2637 /// \brief Determine whether two template parameter lists are similar enough 2638 /// that they may be used in declarations of the same template. 2639 static bool isSameTemplateParameterList(const TemplateParameterList *X, 2640 const TemplateParameterList *Y) { 2641 if (X->size() != Y->size()) 2642 return false; 2643 2644 for (unsigned I = 0, N = X->size(); I != N; ++I) 2645 if (!isSameTemplateParameter(X->getParam(I), Y->getParam(I))) 2646 return false; 2647 2648 return true; 2649 } 2650 2651 /// \brief Determine whether the two declarations refer to the same entity. 2652 static bool isSameEntity(NamedDecl *X, NamedDecl *Y) { 2653 assert(X->getDeclName() == Y->getDeclName() && "Declaration name mismatch!"); 2654 2655 if (X == Y) 2656 return true; 2657 2658 // Must be in the same context. 2659 if (!X->getDeclContext()->getRedeclContext()->Equals( 2660 Y->getDeclContext()->getRedeclContext())) 2661 return false; 2662 2663 // Two typedefs refer to the same entity if they have the same underlying 2664 // type. 2665 if (TypedefNameDecl *TypedefX = dyn_cast<TypedefNameDecl>(X)) 2666 if (TypedefNameDecl *TypedefY = dyn_cast<TypedefNameDecl>(Y)) 2667 return X->getASTContext().hasSameType(TypedefX->getUnderlyingType(), 2668 TypedefY->getUnderlyingType()); 2669 2670 // Must have the same kind. 2671 if (X->getKind() != Y->getKind()) 2672 return false; 2673 2674 // Objective-C classes and protocols with the same name always match. 2675 if (isa<ObjCInterfaceDecl>(X) || isa<ObjCProtocolDecl>(X)) 2676 return true; 2677 2678 if (isa<ClassTemplateSpecializationDecl>(X)) { 2679 // No need to handle these here: we merge them when adding them to the 2680 // template. 2681 return false; 2682 } 2683 2684 // Compatible tags match. 2685 if (TagDecl *TagX = dyn_cast<TagDecl>(X)) { 2686 TagDecl *TagY = cast<TagDecl>(Y); 2687 return (TagX->getTagKind() == TagY->getTagKind()) || 2688 ((TagX->getTagKind() == TTK_Struct || TagX->getTagKind() == TTK_Class || 2689 TagX->getTagKind() == TTK_Interface) && 2690 (TagY->getTagKind() == TTK_Struct || TagY->getTagKind() == TTK_Class || 2691 TagY->getTagKind() == TTK_Interface)); 2692 } 2693 2694 // Functions with the same type and linkage match. 2695 // FIXME: This needs to cope with merging of prototyped/non-prototyped 2696 // functions, etc. 2697 if (FunctionDecl *FuncX = dyn_cast<FunctionDecl>(X)) { 2698 FunctionDecl *FuncY = cast<FunctionDecl>(Y); 2699 if (CXXConstructorDecl *CtorX = dyn_cast<CXXConstructorDecl>(X)) { 2700 CXXConstructorDecl *CtorY = cast<CXXConstructorDecl>(Y); 2701 if (CtorX->getInheritedConstructor() && 2702 !isSameEntity(CtorX->getInheritedConstructor().getConstructor(), 2703 CtorY->getInheritedConstructor().getConstructor())) 2704 return false; 2705 } 2706 return (FuncX->getLinkageInternal() == FuncY->getLinkageInternal()) && 2707 FuncX->getASTContext().hasSameType(FuncX->getType(), FuncY->getType()); 2708 } 2709 2710 // Variables with the same type and linkage match. 2711 if (VarDecl *VarX = dyn_cast<VarDecl>(X)) { 2712 VarDecl *VarY = cast<VarDecl>(Y); 2713 if (VarX->getLinkageInternal() == VarY->getLinkageInternal()) { 2714 ASTContext &C = VarX->getASTContext(); 2715 if (C.hasSameType(VarX->getType(), VarY->getType())) 2716 return true; 2717 2718 // We can get decls with different types on the redecl chain. Eg. 2719 // template <typename T> struct S { static T Var[]; }; // #1 2720 // template <typename T> T S<T>::Var[sizeof(T)]; // #2 2721 // Only? happens when completing an incomplete array type. In this case 2722 // when comparing #1 and #2 we should go through their element type. 2723 const ArrayType *VarXTy = C.getAsArrayType(VarX->getType()); 2724 const ArrayType *VarYTy = C.getAsArrayType(VarY->getType()); 2725 if (!VarXTy || !VarYTy) 2726 return false; 2727 if (VarXTy->isIncompleteArrayType() || VarYTy->isIncompleteArrayType()) 2728 return C.hasSameType(VarXTy->getElementType(), VarYTy->getElementType()); 2729 } 2730 return false; 2731 } 2732 2733 // Namespaces with the same name and inlinedness match. 2734 if (NamespaceDecl *NamespaceX = dyn_cast<NamespaceDecl>(X)) { 2735 NamespaceDecl *NamespaceY = cast<NamespaceDecl>(Y); 2736 return NamespaceX->isInline() == NamespaceY->isInline(); 2737 } 2738 2739 // Identical template names and kinds match if their template parameter lists 2740 // and patterns match. 2741 if (TemplateDecl *TemplateX = dyn_cast<TemplateDecl>(X)) { 2742 TemplateDecl *TemplateY = cast<TemplateDecl>(Y); 2743 return isSameEntity(TemplateX->getTemplatedDecl(), 2744 TemplateY->getTemplatedDecl()) && 2745 isSameTemplateParameterList(TemplateX->getTemplateParameters(), 2746 TemplateY->getTemplateParameters()); 2747 } 2748 2749 // Fields with the same name and the same type match. 2750 if (FieldDecl *FDX = dyn_cast<FieldDecl>(X)) { 2751 FieldDecl *FDY = cast<FieldDecl>(Y); 2752 // FIXME: Also check the bitwidth is odr-equivalent, if any. 2753 return X->getASTContext().hasSameType(FDX->getType(), FDY->getType()); 2754 } 2755 2756 // Indirect fields with the same target field match. 2757 if (auto *IFDX = dyn_cast<IndirectFieldDecl>(X)) { 2758 auto *IFDY = cast<IndirectFieldDecl>(Y); 2759 return IFDX->getAnonField()->getCanonicalDecl() == 2760 IFDY->getAnonField()->getCanonicalDecl(); 2761 } 2762 2763 // Enumerators with the same name match. 2764 if (isa<EnumConstantDecl>(X)) 2765 // FIXME: Also check the value is odr-equivalent. 2766 return true; 2767 2768 // Using shadow declarations with the same target match. 2769 if (UsingShadowDecl *USX = dyn_cast<UsingShadowDecl>(X)) { 2770 UsingShadowDecl *USY = cast<UsingShadowDecl>(Y); 2771 return USX->getTargetDecl() == USY->getTargetDecl(); 2772 } 2773 2774 // Using declarations with the same qualifier match. (We already know that 2775 // the name matches.) 2776 if (auto *UX = dyn_cast<UsingDecl>(X)) { 2777 auto *UY = cast<UsingDecl>(Y); 2778 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) && 2779 UX->hasTypename() == UY->hasTypename() && 2780 UX->isAccessDeclaration() == UY->isAccessDeclaration(); 2781 } 2782 if (auto *UX = dyn_cast<UnresolvedUsingValueDecl>(X)) { 2783 auto *UY = cast<UnresolvedUsingValueDecl>(Y); 2784 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) && 2785 UX->isAccessDeclaration() == UY->isAccessDeclaration(); 2786 } 2787 if (auto *UX = dyn_cast<UnresolvedUsingTypenameDecl>(X)) 2788 return isSameQualifier( 2789 UX->getQualifier(), 2790 cast<UnresolvedUsingTypenameDecl>(Y)->getQualifier()); 2791 2792 // Namespace alias definitions with the same target match. 2793 if (auto *NAX = dyn_cast<NamespaceAliasDecl>(X)) { 2794 auto *NAY = cast<NamespaceAliasDecl>(Y); 2795 return NAX->getNamespace()->Equals(NAY->getNamespace()); 2796 } 2797 2798 return false; 2799 } 2800 2801 /// Find the context in which we should search for previous declarations when 2802 /// looking for declarations to merge. 2803 DeclContext *ASTDeclReader::getPrimaryContextForMerging(ASTReader &Reader, 2804 DeclContext *DC) { 2805 if (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC)) 2806 return ND->getOriginalNamespace(); 2807 2808 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 2809 // Try to dig out the definition. 2810 auto *DD = RD->DefinitionData; 2811 if (!DD) 2812 DD = RD->getCanonicalDecl()->DefinitionData; 2813 2814 // If there's no definition yet, then DC's definition is added by an update 2815 // record, but we've not yet loaded that update record. In this case, we 2816 // commit to DC being the canonical definition now, and will fix this when 2817 // we load the update record. 2818 if (!DD) { 2819 DD = new (Reader.Context) struct CXXRecordDecl::DefinitionData(RD); 2820 RD->IsCompleteDefinition = true; 2821 RD->DefinitionData = DD; 2822 RD->getCanonicalDecl()->DefinitionData = DD; 2823 2824 // Track that we did this horrible thing so that we can fix it later. 2825 Reader.PendingFakeDefinitionData.insert( 2826 std::make_pair(DD, ASTReader::PendingFakeDefinitionKind::Fake)); 2827 } 2828 2829 return DD->Definition; 2830 } 2831 2832 if (EnumDecl *ED = dyn_cast<EnumDecl>(DC)) 2833 return ED->getASTContext().getLangOpts().CPlusPlus? ED->getDefinition() 2834 : nullptr; 2835 2836 // We can see the TU here only if we have no Sema object. In that case, 2837 // there's no TU scope to look in, so using the DC alone is sufficient. 2838 if (auto *TU = dyn_cast<TranslationUnitDecl>(DC)) 2839 return TU; 2840 2841 return nullptr; 2842 } 2843 2844 ASTDeclReader::FindExistingResult::~FindExistingResult() { 2845 // Record that we had a typedef name for linkage whether or not we merge 2846 // with that declaration. 2847 if (TypedefNameForLinkage) { 2848 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 2849 Reader.ImportedTypedefNamesForLinkage.insert( 2850 std::make_pair(std::make_pair(DC, TypedefNameForLinkage), New)); 2851 return; 2852 } 2853 2854 if (!AddResult || Existing) 2855 return; 2856 2857 DeclarationName Name = New->getDeclName(); 2858 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 2859 if (needsAnonymousDeclarationNumber(New)) { 2860 setAnonymousDeclForMerging(Reader, New->getLexicalDeclContext(), 2861 AnonymousDeclNumber, New); 2862 } else if (DC->isTranslationUnit() && 2863 !Reader.getContext().getLangOpts().CPlusPlus) { 2864 if (Reader.getIdResolver().tryAddTopLevelDecl(New, Name)) 2865 Reader.PendingFakeLookupResults[Name.getAsIdentifierInfo()] 2866 .push_back(New); 2867 } else if (DeclContext *MergeDC = getPrimaryContextForMerging(Reader, DC)) { 2868 // Add the declaration to its redeclaration context so later merging 2869 // lookups will find it. 2870 MergeDC->makeDeclVisibleInContextImpl(New, /*Internal*/true); 2871 } 2872 } 2873 2874 /// Find the declaration that should be merged into, given the declaration found 2875 /// by name lookup. If we're merging an anonymous declaration within a typedef, 2876 /// we need a matching typedef, and we merge with the type inside it. 2877 static NamedDecl *getDeclForMerging(NamedDecl *Found, 2878 bool IsTypedefNameForLinkage) { 2879 if (!IsTypedefNameForLinkage) 2880 return Found; 2881 2882 // If we found a typedef declaration that gives a name to some other 2883 // declaration, then we want that inner declaration. Declarations from 2884 // AST files are handled via ImportedTypedefNamesForLinkage. 2885 if (Found->isFromASTFile()) 2886 return nullptr; 2887 2888 if (auto *TND = dyn_cast<TypedefNameDecl>(Found)) 2889 return TND->getAnonDeclWithTypedefName(/*AnyRedecl*/true); 2890 2891 return nullptr; 2892 } 2893 2894 NamedDecl *ASTDeclReader::getAnonymousDeclForMerging(ASTReader &Reader, 2895 DeclContext *DC, 2896 unsigned Index) { 2897 // If the lexical context has been merged, look into the now-canonical 2898 // definition. 2899 if (auto *Merged = Reader.MergedDeclContexts.lookup(DC)) 2900 DC = Merged; 2901 2902 // If we've seen this before, return the canonical declaration. 2903 auto &Previous = Reader.AnonymousDeclarationsForMerging[DC]; 2904 if (Index < Previous.size() && Previous[Index]) 2905 return Previous[Index]; 2906 2907 // If this is the first time, but we have parsed a declaration of the context, 2908 // build the anonymous declaration list from the parsed declaration. 2909 if (!cast<Decl>(DC)->isFromASTFile()) { 2910 numberAnonymousDeclsWithin(DC, [&](NamedDecl *ND, unsigned Number) { 2911 if (Previous.size() == Number) 2912 Previous.push_back(cast<NamedDecl>(ND->getCanonicalDecl())); 2913 else 2914 Previous[Number] = cast<NamedDecl>(ND->getCanonicalDecl()); 2915 }); 2916 } 2917 2918 return Index < Previous.size() ? Previous[Index] : nullptr; 2919 } 2920 2921 void ASTDeclReader::setAnonymousDeclForMerging(ASTReader &Reader, 2922 DeclContext *DC, unsigned Index, 2923 NamedDecl *D) { 2924 if (auto *Merged = Reader.MergedDeclContexts.lookup(DC)) 2925 DC = Merged; 2926 2927 auto &Previous = Reader.AnonymousDeclarationsForMerging[DC]; 2928 if (Index >= Previous.size()) 2929 Previous.resize(Index + 1); 2930 if (!Previous[Index]) 2931 Previous[Index] = D; 2932 } 2933 2934 ASTDeclReader::FindExistingResult ASTDeclReader::findExisting(NamedDecl *D) { 2935 DeclarationName Name = TypedefNameForLinkage ? TypedefNameForLinkage 2936 : D->getDeclName(); 2937 2938 if (!Name && !needsAnonymousDeclarationNumber(D)) { 2939 // Don't bother trying to find unnamed declarations that are in 2940 // unmergeable contexts. 2941 FindExistingResult Result(Reader, D, /*Existing=*/nullptr, 2942 AnonymousDeclNumber, TypedefNameForLinkage); 2943 Result.suppress(); 2944 return Result; 2945 } 2946 2947 DeclContext *DC = D->getDeclContext()->getRedeclContext(); 2948 if (TypedefNameForLinkage) { 2949 auto It = Reader.ImportedTypedefNamesForLinkage.find( 2950 std::make_pair(DC, TypedefNameForLinkage)); 2951 if (It != Reader.ImportedTypedefNamesForLinkage.end()) 2952 if (isSameEntity(It->second, D)) 2953 return FindExistingResult(Reader, D, It->second, AnonymousDeclNumber, 2954 TypedefNameForLinkage); 2955 // Go on to check in other places in case an existing typedef name 2956 // was not imported. 2957 } 2958 2959 if (needsAnonymousDeclarationNumber(D)) { 2960 // This is an anonymous declaration that we may need to merge. Look it up 2961 // in its context by number. 2962 if (auto *Existing = getAnonymousDeclForMerging( 2963 Reader, D->getLexicalDeclContext(), AnonymousDeclNumber)) 2964 if (isSameEntity(Existing, D)) 2965 return FindExistingResult(Reader, D, Existing, AnonymousDeclNumber, 2966 TypedefNameForLinkage); 2967 } else if (DC->isTranslationUnit() && 2968 !Reader.getContext().getLangOpts().CPlusPlus) { 2969 IdentifierResolver &IdResolver = Reader.getIdResolver(); 2970 2971 // Temporarily consider the identifier to be up-to-date. We don't want to 2972 // cause additional lookups here. 2973 class UpToDateIdentifierRAII { 2974 IdentifierInfo *II; 2975 bool WasOutToDate; 2976 2977 public: 2978 explicit UpToDateIdentifierRAII(IdentifierInfo *II) 2979 : II(II), WasOutToDate(false) 2980 { 2981 if (II) { 2982 WasOutToDate = II->isOutOfDate(); 2983 if (WasOutToDate) 2984 II->setOutOfDate(false); 2985 } 2986 } 2987 2988 ~UpToDateIdentifierRAII() { 2989 if (WasOutToDate) 2990 II->setOutOfDate(true); 2991 } 2992 } UpToDate(Name.getAsIdentifierInfo()); 2993 2994 for (IdentifierResolver::iterator I = IdResolver.begin(Name), 2995 IEnd = IdResolver.end(); 2996 I != IEnd; ++I) { 2997 if (NamedDecl *Existing = getDeclForMerging(*I, TypedefNameForLinkage)) 2998 if (isSameEntity(Existing, D)) 2999 return FindExistingResult(Reader, D, Existing, AnonymousDeclNumber, 3000 TypedefNameForLinkage); 3001 } 3002 } else if (DeclContext *MergeDC = getPrimaryContextForMerging(Reader, DC)) { 3003 DeclContext::lookup_result R = MergeDC->noload_lookup(Name); 3004 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 3005 if (NamedDecl *Existing = getDeclForMerging(*I, TypedefNameForLinkage)) 3006 if (isSameEntity(Existing, D)) 3007 return FindExistingResult(Reader, D, Existing, AnonymousDeclNumber, 3008 TypedefNameForLinkage); 3009 } 3010 } else { 3011 // Not in a mergeable context. 3012 return FindExistingResult(Reader); 3013 } 3014 3015 // If this declaration is from a merged context, make a note that we need to 3016 // check that the canonical definition of that context contains the decl. 3017 // 3018 // FIXME: We should do something similar if we merge two definitions of the 3019 // same template specialization into the same CXXRecordDecl. 3020 auto MergedDCIt = Reader.MergedDeclContexts.find(D->getLexicalDeclContext()); 3021 if (MergedDCIt != Reader.MergedDeclContexts.end() && 3022 MergedDCIt->second == D->getDeclContext()) 3023 Reader.PendingOdrMergeChecks.push_back(D); 3024 3025 return FindExistingResult(Reader, D, /*Existing=*/nullptr, 3026 AnonymousDeclNumber, TypedefNameForLinkage); 3027 } 3028 3029 template<typename DeclT> 3030 Decl *ASTDeclReader::getMostRecentDeclImpl(Redeclarable<DeclT> *D) { 3031 return D->RedeclLink.getLatestNotUpdated(); 3032 } 3033 Decl *ASTDeclReader::getMostRecentDeclImpl(...) { 3034 llvm_unreachable("getMostRecentDecl on non-redeclarable declaration"); 3035 } 3036 3037 Decl *ASTDeclReader::getMostRecentDecl(Decl *D) { 3038 assert(D); 3039 3040 switch (D->getKind()) { 3041 #define ABSTRACT_DECL(TYPE) 3042 #define DECL(TYPE, BASE) \ 3043 case Decl::TYPE: \ 3044 return getMostRecentDeclImpl(cast<TYPE##Decl>(D)); 3045 #include "clang/AST/DeclNodes.inc" 3046 } 3047 llvm_unreachable("unknown decl kind"); 3048 } 3049 3050 Decl *ASTReader::getMostRecentExistingDecl(Decl *D) { 3051 return ASTDeclReader::getMostRecentDecl(D->getCanonicalDecl()); 3052 } 3053 3054 template<typename DeclT> 3055 void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader, 3056 Redeclarable<DeclT> *D, 3057 Decl *Previous, Decl *Canon) { 3058 D->RedeclLink.setPrevious(cast<DeclT>(Previous)); 3059 D->First = cast<DeclT>(Previous)->First; 3060 } 3061 3062 namespace clang { 3063 template<> 3064 void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader, 3065 Redeclarable<VarDecl> *D, 3066 Decl *Previous, Decl *Canon) { 3067 VarDecl *VD = static_cast<VarDecl*>(D); 3068 VarDecl *PrevVD = cast<VarDecl>(Previous); 3069 D->RedeclLink.setPrevious(PrevVD); 3070 D->First = PrevVD->First; 3071 3072 // We should keep at most one definition on the chain. 3073 // FIXME: Cache the definition once we've found it. Building a chain with 3074 // N definitions currently takes O(N^2) time here. 3075 if (VD->isThisDeclarationADefinition() == VarDecl::Definition) { 3076 for (VarDecl *CurD = PrevVD; CurD; CurD = CurD->getPreviousDecl()) { 3077 if (CurD->isThisDeclarationADefinition() == VarDecl::Definition) { 3078 Reader.mergeDefinitionVisibility(CurD, VD); 3079 VD->demoteThisDefinitionToDeclaration(); 3080 break; 3081 } 3082 } 3083 } 3084 } 3085 3086 template<> 3087 void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader, 3088 Redeclarable<FunctionDecl> *D, 3089 Decl *Previous, Decl *Canon) { 3090 FunctionDecl *FD = static_cast<FunctionDecl*>(D); 3091 FunctionDecl *PrevFD = cast<FunctionDecl>(Previous); 3092 3093 FD->RedeclLink.setPrevious(PrevFD); 3094 FD->First = PrevFD->First; 3095 3096 // If the previous declaration is an inline function declaration, then this 3097 // declaration is too. 3098 if (PrevFD->IsInline != FD->IsInline) { 3099 // FIXME: [dcl.fct.spec]p4: 3100 // If a function with external linkage is declared inline in one 3101 // translation unit, it shall be declared inline in all translation 3102 // units in which it appears. 3103 // 3104 // Be careful of this case: 3105 // 3106 // module A: 3107 // template<typename T> struct X { void f(); }; 3108 // template<typename T> inline void X<T>::f() {} 3109 // 3110 // module B instantiates the declaration of X<int>::f 3111 // module C instantiates the definition of X<int>::f 3112 // 3113 // If module B and C are merged, we do not have a violation of this rule. 3114 FD->IsInline = true; 3115 } 3116 3117 // If we need to propagate an exception specification along the redecl 3118 // chain, make a note of that so that we can do so later. 3119 auto *FPT = FD->getType()->getAs<FunctionProtoType>(); 3120 auto *PrevFPT = PrevFD->getType()->getAs<FunctionProtoType>(); 3121 if (FPT && PrevFPT) { 3122 bool IsUnresolved = isUnresolvedExceptionSpec(FPT->getExceptionSpecType()); 3123 bool WasUnresolved = 3124 isUnresolvedExceptionSpec(PrevFPT->getExceptionSpecType()); 3125 if (IsUnresolved != WasUnresolved) 3126 Reader.PendingExceptionSpecUpdates.insert( 3127 std::make_pair(Canon, IsUnresolved ? PrevFD : FD)); 3128 } 3129 } 3130 } // end namespace clang 3131 3132 void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader, ...) { 3133 llvm_unreachable("attachPreviousDecl on non-redeclarable declaration"); 3134 } 3135 3136 /// Inherit the default template argument from \p From to \p To. Returns 3137 /// \c false if there is no default template for \p From. 3138 template <typename ParmDecl> 3139 static bool inheritDefaultTemplateArgument(ASTContext &Context, ParmDecl *From, 3140 Decl *ToD) { 3141 auto *To = cast<ParmDecl>(ToD); 3142 if (!From->hasDefaultArgument()) 3143 return false; 3144 To->setInheritedDefaultArgument(Context, From); 3145 return true; 3146 } 3147 3148 static void inheritDefaultTemplateArguments(ASTContext &Context, 3149 TemplateDecl *From, 3150 TemplateDecl *To) { 3151 auto *FromTP = From->getTemplateParameters(); 3152 auto *ToTP = To->getTemplateParameters(); 3153 assert(FromTP->size() == ToTP->size() && "merged mismatched templates?"); 3154 3155 for (unsigned I = 0, N = FromTP->size(); I != N; ++I) { 3156 NamedDecl *FromParam = FromTP->getParam(N - I - 1); 3157 if (FromParam->isParameterPack()) 3158 continue; 3159 NamedDecl *ToParam = ToTP->getParam(N - I - 1); 3160 3161 if (auto *FTTP = dyn_cast<TemplateTypeParmDecl>(FromParam)) { 3162 if (!inheritDefaultTemplateArgument(Context, FTTP, ToParam)) 3163 break; 3164 } else if (auto *FNTTP = dyn_cast<NonTypeTemplateParmDecl>(FromParam)) { 3165 if (!inheritDefaultTemplateArgument(Context, FNTTP, ToParam)) 3166 break; 3167 } else { 3168 if (!inheritDefaultTemplateArgument( 3169 Context, cast<TemplateTemplateParmDecl>(FromParam), ToParam)) 3170 break; 3171 } 3172 } 3173 } 3174 3175 void ASTDeclReader::attachPreviousDecl(ASTReader &Reader, Decl *D, 3176 Decl *Previous, Decl *Canon) { 3177 assert(D && Previous); 3178 3179 switch (D->getKind()) { 3180 #define ABSTRACT_DECL(TYPE) 3181 #define DECL(TYPE, BASE) \ 3182 case Decl::TYPE: \ 3183 attachPreviousDeclImpl(Reader, cast<TYPE##Decl>(D), Previous, Canon); \ 3184 break; 3185 #include "clang/AST/DeclNodes.inc" 3186 } 3187 3188 // If the declaration was visible in one module, a redeclaration of it in 3189 // another module remains visible even if it wouldn't be visible by itself. 3190 // 3191 // FIXME: In this case, the declaration should only be visible if a module 3192 // that makes it visible has been imported. 3193 D->IdentifierNamespace |= 3194 Previous->IdentifierNamespace & 3195 (Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Type); 3196 3197 // If the declaration declares a template, it may inherit default arguments 3198 // from the previous declaration. 3199 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 3200 inheritDefaultTemplateArguments(Reader.getContext(), 3201 cast<TemplateDecl>(Previous), TD); 3202 } 3203 3204 template<typename DeclT> 3205 void ASTDeclReader::attachLatestDeclImpl(Redeclarable<DeclT> *D, Decl *Latest) { 3206 D->RedeclLink.setLatest(cast<DeclT>(Latest)); 3207 } 3208 void ASTDeclReader::attachLatestDeclImpl(...) { 3209 llvm_unreachable("attachLatestDecl on non-redeclarable declaration"); 3210 } 3211 3212 void ASTDeclReader::attachLatestDecl(Decl *D, Decl *Latest) { 3213 assert(D && Latest); 3214 3215 switch (D->getKind()) { 3216 #define ABSTRACT_DECL(TYPE) 3217 #define DECL(TYPE, BASE) \ 3218 case Decl::TYPE: \ 3219 attachLatestDeclImpl(cast<TYPE##Decl>(D), Latest); \ 3220 break; 3221 #include "clang/AST/DeclNodes.inc" 3222 } 3223 } 3224 3225 template<typename DeclT> 3226 void ASTDeclReader::markIncompleteDeclChainImpl(Redeclarable<DeclT> *D) { 3227 D->RedeclLink.markIncomplete(); 3228 } 3229 void ASTDeclReader::markIncompleteDeclChainImpl(...) { 3230 llvm_unreachable("markIncompleteDeclChain on non-redeclarable declaration"); 3231 } 3232 3233 void ASTReader::markIncompleteDeclChain(Decl *D) { 3234 switch (D->getKind()) { 3235 #define ABSTRACT_DECL(TYPE) 3236 #define DECL(TYPE, BASE) \ 3237 case Decl::TYPE: \ 3238 ASTDeclReader::markIncompleteDeclChainImpl(cast<TYPE##Decl>(D)); \ 3239 break; 3240 #include "clang/AST/DeclNodes.inc" 3241 } 3242 } 3243 3244 /// \brief Read the declaration at the given offset from the AST file. 3245 Decl *ASTReader::ReadDeclRecord(DeclID ID) { 3246 unsigned Index = ID - NUM_PREDEF_DECL_IDS; 3247 SourceLocation DeclLoc; 3248 RecordLocation Loc = DeclCursorForID(ID, DeclLoc); 3249 llvm::BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor; 3250 // Keep track of where we are in the stream, then jump back there 3251 // after reading this declaration. 3252 SavedStreamPosition SavedPosition(DeclsCursor); 3253 3254 ReadingKindTracker ReadingKind(Read_Decl, *this); 3255 3256 // Note that we are loading a declaration record. 3257 Deserializing ADecl(this); 3258 3259 DeclsCursor.JumpToBit(Loc.Offset); 3260 ASTRecordReader Record(*this, *Loc.F); 3261 ASTDeclReader Reader(*this, Record, Loc, ID, DeclLoc); 3262 unsigned Code = DeclsCursor.ReadCode(); 3263 3264 Decl *D = nullptr; 3265 switch ((DeclCode)Record.readRecord(DeclsCursor, Code)) { 3266 case DECL_CONTEXT_LEXICAL: 3267 case DECL_CONTEXT_VISIBLE: 3268 llvm_unreachable("Record cannot be de-serialized with ReadDeclRecord"); 3269 case DECL_TYPEDEF: 3270 D = TypedefDecl::CreateDeserialized(Context, ID); 3271 break; 3272 case DECL_TYPEALIAS: 3273 D = TypeAliasDecl::CreateDeserialized(Context, ID); 3274 break; 3275 case DECL_ENUM: 3276 D = EnumDecl::CreateDeserialized(Context, ID); 3277 break; 3278 case DECL_RECORD: 3279 D = RecordDecl::CreateDeserialized(Context, ID); 3280 break; 3281 case DECL_ENUM_CONSTANT: 3282 D = EnumConstantDecl::CreateDeserialized(Context, ID); 3283 break; 3284 case DECL_FUNCTION: 3285 D = FunctionDecl::CreateDeserialized(Context, ID); 3286 break; 3287 case DECL_LINKAGE_SPEC: 3288 D = LinkageSpecDecl::CreateDeserialized(Context, ID); 3289 break; 3290 case DECL_EXPORT: 3291 D = ExportDecl::CreateDeserialized(Context, ID); 3292 break; 3293 case DECL_LABEL: 3294 D = LabelDecl::CreateDeserialized(Context, ID); 3295 break; 3296 case DECL_NAMESPACE: 3297 D = NamespaceDecl::CreateDeserialized(Context, ID); 3298 break; 3299 case DECL_NAMESPACE_ALIAS: 3300 D = NamespaceAliasDecl::CreateDeserialized(Context, ID); 3301 break; 3302 case DECL_USING: 3303 D = UsingDecl::CreateDeserialized(Context, ID); 3304 break; 3305 case DECL_USING_PACK: 3306 D = UsingPackDecl::CreateDeserialized(Context, ID, Record.readInt()); 3307 break; 3308 case DECL_USING_SHADOW: 3309 D = UsingShadowDecl::CreateDeserialized(Context, ID); 3310 break; 3311 case DECL_CONSTRUCTOR_USING_SHADOW: 3312 D = ConstructorUsingShadowDecl::CreateDeserialized(Context, ID); 3313 break; 3314 case DECL_USING_DIRECTIVE: 3315 D = UsingDirectiveDecl::CreateDeserialized(Context, ID); 3316 break; 3317 case DECL_UNRESOLVED_USING_VALUE: 3318 D = UnresolvedUsingValueDecl::CreateDeserialized(Context, ID); 3319 break; 3320 case DECL_UNRESOLVED_USING_TYPENAME: 3321 D = UnresolvedUsingTypenameDecl::CreateDeserialized(Context, ID); 3322 break; 3323 case DECL_CXX_RECORD: 3324 D = CXXRecordDecl::CreateDeserialized(Context, ID); 3325 break; 3326 case DECL_CXX_METHOD: 3327 D = CXXMethodDecl::CreateDeserialized(Context, ID); 3328 break; 3329 case DECL_CXX_CONSTRUCTOR: 3330 D = CXXConstructorDecl::CreateDeserialized(Context, ID, false); 3331 break; 3332 case DECL_CXX_INHERITED_CONSTRUCTOR: 3333 D = CXXConstructorDecl::CreateDeserialized(Context, ID, true); 3334 break; 3335 case DECL_CXX_DESTRUCTOR: 3336 D = CXXDestructorDecl::CreateDeserialized(Context, ID); 3337 break; 3338 case DECL_CXX_CONVERSION: 3339 D = CXXConversionDecl::CreateDeserialized(Context, ID); 3340 break; 3341 case DECL_ACCESS_SPEC: 3342 D = AccessSpecDecl::CreateDeserialized(Context, ID); 3343 break; 3344 case DECL_FRIEND: 3345 D = FriendDecl::CreateDeserialized(Context, ID, Record.readInt()); 3346 break; 3347 case DECL_FRIEND_TEMPLATE: 3348 D = FriendTemplateDecl::CreateDeserialized(Context, ID); 3349 break; 3350 case DECL_CLASS_TEMPLATE: 3351 D = ClassTemplateDecl::CreateDeserialized(Context, ID); 3352 break; 3353 case DECL_CLASS_TEMPLATE_SPECIALIZATION: 3354 D = ClassTemplateSpecializationDecl::CreateDeserialized(Context, ID); 3355 break; 3356 case DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION: 3357 D = ClassTemplatePartialSpecializationDecl::CreateDeserialized(Context, ID); 3358 break; 3359 case DECL_VAR_TEMPLATE: 3360 D = VarTemplateDecl::CreateDeserialized(Context, ID); 3361 break; 3362 case DECL_VAR_TEMPLATE_SPECIALIZATION: 3363 D = VarTemplateSpecializationDecl::CreateDeserialized(Context, ID); 3364 break; 3365 case DECL_VAR_TEMPLATE_PARTIAL_SPECIALIZATION: 3366 D = VarTemplatePartialSpecializationDecl::CreateDeserialized(Context, ID); 3367 break; 3368 case DECL_CLASS_SCOPE_FUNCTION_SPECIALIZATION: 3369 D = ClassScopeFunctionSpecializationDecl::CreateDeserialized(Context, ID); 3370 break; 3371 case DECL_FUNCTION_TEMPLATE: 3372 D = FunctionTemplateDecl::CreateDeserialized(Context, ID); 3373 break; 3374 case DECL_TEMPLATE_TYPE_PARM: 3375 D = TemplateTypeParmDecl::CreateDeserialized(Context, ID); 3376 break; 3377 case DECL_NON_TYPE_TEMPLATE_PARM: 3378 D = NonTypeTemplateParmDecl::CreateDeserialized(Context, ID); 3379 break; 3380 case DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK: 3381 D = NonTypeTemplateParmDecl::CreateDeserialized(Context, ID, 3382 Record.readInt()); 3383 break; 3384 case DECL_TEMPLATE_TEMPLATE_PARM: 3385 D = TemplateTemplateParmDecl::CreateDeserialized(Context, ID); 3386 break; 3387 case DECL_EXPANDED_TEMPLATE_TEMPLATE_PARM_PACK: 3388 D = TemplateTemplateParmDecl::CreateDeserialized(Context, ID, 3389 Record.readInt()); 3390 break; 3391 case DECL_TYPE_ALIAS_TEMPLATE: 3392 D = TypeAliasTemplateDecl::CreateDeserialized(Context, ID); 3393 break; 3394 case DECL_STATIC_ASSERT: 3395 D = StaticAssertDecl::CreateDeserialized(Context, ID); 3396 break; 3397 case DECL_OBJC_METHOD: 3398 D = ObjCMethodDecl::CreateDeserialized(Context, ID); 3399 break; 3400 case DECL_OBJC_INTERFACE: 3401 D = ObjCInterfaceDecl::CreateDeserialized(Context, ID); 3402 break; 3403 case DECL_OBJC_IVAR: 3404 D = ObjCIvarDecl::CreateDeserialized(Context, ID); 3405 break; 3406 case DECL_OBJC_PROTOCOL: 3407 D = ObjCProtocolDecl::CreateDeserialized(Context, ID); 3408 break; 3409 case DECL_OBJC_AT_DEFS_FIELD: 3410 D = ObjCAtDefsFieldDecl::CreateDeserialized(Context, ID); 3411 break; 3412 case DECL_OBJC_CATEGORY: 3413 D = ObjCCategoryDecl::CreateDeserialized(Context, ID); 3414 break; 3415 case DECL_OBJC_CATEGORY_IMPL: 3416 D = ObjCCategoryImplDecl::CreateDeserialized(Context, ID); 3417 break; 3418 case DECL_OBJC_IMPLEMENTATION: 3419 D = ObjCImplementationDecl::CreateDeserialized(Context, ID); 3420 break; 3421 case DECL_OBJC_COMPATIBLE_ALIAS: 3422 D = ObjCCompatibleAliasDecl::CreateDeserialized(Context, ID); 3423 break; 3424 case DECL_OBJC_PROPERTY: 3425 D = ObjCPropertyDecl::CreateDeserialized(Context, ID); 3426 break; 3427 case DECL_OBJC_PROPERTY_IMPL: 3428 D = ObjCPropertyImplDecl::CreateDeserialized(Context, ID); 3429 break; 3430 case DECL_FIELD: 3431 D = FieldDecl::CreateDeserialized(Context, ID); 3432 break; 3433 case DECL_INDIRECTFIELD: 3434 D = IndirectFieldDecl::CreateDeserialized(Context, ID); 3435 break; 3436 case DECL_VAR: 3437 D = VarDecl::CreateDeserialized(Context, ID); 3438 break; 3439 case DECL_IMPLICIT_PARAM: 3440 D = ImplicitParamDecl::CreateDeserialized(Context, ID); 3441 break; 3442 case DECL_PARM_VAR: 3443 D = ParmVarDecl::CreateDeserialized(Context, ID); 3444 break; 3445 case DECL_DECOMPOSITION: 3446 D = DecompositionDecl::CreateDeserialized(Context, ID, Record.readInt()); 3447 break; 3448 case DECL_BINDING: 3449 D = BindingDecl::CreateDeserialized(Context, ID); 3450 break; 3451 case DECL_FILE_SCOPE_ASM: 3452 D = FileScopeAsmDecl::CreateDeserialized(Context, ID); 3453 break; 3454 case DECL_BLOCK: 3455 D = BlockDecl::CreateDeserialized(Context, ID); 3456 break; 3457 case DECL_MS_PROPERTY: 3458 D = MSPropertyDecl::CreateDeserialized(Context, ID); 3459 break; 3460 case DECL_CAPTURED: 3461 D = CapturedDecl::CreateDeserialized(Context, ID, Record.readInt()); 3462 break; 3463 case DECL_CXX_BASE_SPECIFIERS: 3464 Error("attempt to read a C++ base-specifier record as a declaration"); 3465 return nullptr; 3466 case DECL_CXX_CTOR_INITIALIZERS: 3467 Error("attempt to read a C++ ctor initializer record as a declaration"); 3468 return nullptr; 3469 case DECL_IMPORT: 3470 // Note: last entry of the ImportDecl record is the number of stored source 3471 // locations. 3472 D = ImportDecl::CreateDeserialized(Context, ID, Record.back()); 3473 break; 3474 case DECL_OMP_THREADPRIVATE: 3475 D = OMPThreadPrivateDecl::CreateDeserialized(Context, ID, Record.readInt()); 3476 break; 3477 case DECL_OMP_DECLARE_REDUCTION: 3478 D = OMPDeclareReductionDecl::CreateDeserialized(Context, ID); 3479 break; 3480 case DECL_OMP_CAPTUREDEXPR: 3481 D = OMPCapturedExprDecl::CreateDeserialized(Context, ID); 3482 break; 3483 case DECL_PRAGMA_COMMENT: 3484 D = PragmaCommentDecl::CreateDeserialized(Context, ID, Record.readInt()); 3485 break; 3486 case DECL_PRAGMA_DETECT_MISMATCH: 3487 D = PragmaDetectMismatchDecl::CreateDeserialized(Context, ID, 3488 Record.readInt()); 3489 break; 3490 case DECL_EMPTY: 3491 D = EmptyDecl::CreateDeserialized(Context, ID); 3492 break; 3493 case DECL_OBJC_TYPE_PARAM: 3494 D = ObjCTypeParamDecl::CreateDeserialized(Context, ID); 3495 break; 3496 } 3497 3498 assert(D && "Unknown declaration reading AST file"); 3499 LoadedDecl(Index, D); 3500 // Set the DeclContext before doing any deserialization, to make sure internal 3501 // calls to Decl::getASTContext() by Decl's methods will find the 3502 // TranslationUnitDecl without crashing. 3503 D->setDeclContext(Context.getTranslationUnitDecl()); 3504 Reader.Visit(D); 3505 3506 // If this declaration is also a declaration context, get the 3507 // offsets for its tables of lexical and visible declarations. 3508 if (DeclContext *DC = dyn_cast<DeclContext>(D)) { 3509 std::pair<uint64_t, uint64_t> Offsets = Reader.VisitDeclContext(DC); 3510 if (Offsets.first && 3511 ReadLexicalDeclContextStorage(*Loc.F, DeclsCursor, Offsets.first, DC)) 3512 return nullptr; 3513 if (Offsets.second && 3514 ReadVisibleDeclContextStorage(*Loc.F, DeclsCursor, Offsets.second, ID)) 3515 return nullptr; 3516 } 3517 assert(Record.getIdx() == Record.size()); 3518 3519 // Load any relevant update records. 3520 PendingUpdateRecords.push_back(std::make_pair(ID, D)); 3521 3522 // Load the categories after recursive loading is finished. 3523 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D)) 3524 // If we already have a definition when deserializing the ObjCInterfaceDecl, 3525 // we put the Decl in PendingDefinitions so we can pull the categories here. 3526 if (Class->isThisDeclarationADefinition() || 3527 PendingDefinitions.count(Class)) 3528 loadObjCCategories(ID, Class); 3529 3530 // If we have deserialized a declaration that has a definition the 3531 // AST consumer might need to know about, queue it. 3532 // We don't pass it to the consumer immediately because we may be in recursive 3533 // loading, and some declarations may still be initializing. 3534 if (isConsumerInterestedIn(Context, D, Reader.hasPendingBody())) 3535 InterestingDecls.push_back(D); 3536 3537 return D; 3538 } 3539 3540 void ASTReader::loadDeclUpdateRecords(serialization::DeclID ID, Decl *D) { 3541 // The declaration may have been modified by files later in the chain. 3542 // If this is the case, read the record containing the updates from each file 3543 // and pass it to ASTDeclReader to make the modifications. 3544 ProcessingUpdatesRAIIObj ProcessingUpdates(*this); 3545 DeclUpdateOffsetsMap::iterator UpdI = DeclUpdateOffsets.find(ID); 3546 if (UpdI != DeclUpdateOffsets.end()) { 3547 auto UpdateOffsets = std::move(UpdI->second); 3548 DeclUpdateOffsets.erase(UpdI); 3549 3550 bool WasInteresting = isConsumerInterestedIn(Context, D, false); 3551 for (auto &FileAndOffset : UpdateOffsets) { 3552 ModuleFile *F = FileAndOffset.first; 3553 uint64_t Offset = FileAndOffset.second; 3554 llvm::BitstreamCursor &Cursor = F->DeclsCursor; 3555 SavedStreamPosition SavedPosition(Cursor); 3556 Cursor.JumpToBit(Offset); 3557 unsigned Code = Cursor.ReadCode(); 3558 ASTRecordReader Record(*this, *F); 3559 unsigned RecCode = Record.readRecord(Cursor, Code); 3560 (void)RecCode; 3561 assert(RecCode == DECL_UPDATES && "Expected DECL_UPDATES record!"); 3562 3563 ASTDeclReader Reader(*this, Record, RecordLocation(F, Offset), ID, 3564 SourceLocation()); 3565 Reader.UpdateDecl(D); 3566 3567 // We might have made this declaration interesting. If so, remember that 3568 // we need to hand it off to the consumer. 3569 if (!WasInteresting && 3570 isConsumerInterestedIn(Context, D, Reader.hasPendingBody())) { 3571 InterestingDecls.push_back(D); 3572 WasInteresting = true; 3573 } 3574 } 3575 } 3576 3577 // Load the pending visible updates for this decl context, if it has any. 3578 auto I = PendingVisibleUpdates.find(ID); 3579 if (I != PendingVisibleUpdates.end()) { 3580 auto VisibleUpdates = std::move(I->second); 3581 PendingVisibleUpdates.erase(I); 3582 3583 auto *DC = cast<DeclContext>(D)->getPrimaryContext(); 3584 for (const PendingVisibleUpdate &Update : VisibleUpdates) 3585 Lookups[DC].Table.add( 3586 Update.Mod, Update.Data, 3587 reader::ASTDeclContextNameLookupTrait(*this, *Update.Mod)); 3588 DC->setHasExternalVisibleStorage(true); 3589 } 3590 } 3591 3592 void ASTReader::loadPendingDeclChain(Decl *FirstLocal, uint64_t LocalOffset) { 3593 // Attach FirstLocal to the end of the decl chain. 3594 Decl *CanonDecl = FirstLocal->getCanonicalDecl(); 3595 if (FirstLocal != CanonDecl) { 3596 Decl *PrevMostRecent = ASTDeclReader::getMostRecentDecl(CanonDecl); 3597 ASTDeclReader::attachPreviousDecl( 3598 *this, FirstLocal, PrevMostRecent ? PrevMostRecent : CanonDecl, 3599 CanonDecl); 3600 } 3601 3602 if (!LocalOffset) { 3603 ASTDeclReader::attachLatestDecl(CanonDecl, FirstLocal); 3604 return; 3605 } 3606 3607 // Load the list of other redeclarations from this module file. 3608 ModuleFile *M = getOwningModuleFile(FirstLocal); 3609 assert(M && "imported decl from no module file"); 3610 3611 llvm::BitstreamCursor &Cursor = M->DeclsCursor; 3612 SavedStreamPosition SavedPosition(Cursor); 3613 Cursor.JumpToBit(LocalOffset); 3614 3615 RecordData Record; 3616 unsigned Code = Cursor.ReadCode(); 3617 unsigned RecCode = Cursor.readRecord(Code, Record); 3618 (void)RecCode; 3619 assert(RecCode == LOCAL_REDECLARATIONS && "expected LOCAL_REDECLARATIONS record!"); 3620 3621 // FIXME: We have several different dispatches on decl kind here; maybe 3622 // we should instead generate one loop per kind and dispatch up-front? 3623 Decl *MostRecent = FirstLocal; 3624 for (unsigned I = 0, N = Record.size(); I != N; ++I) { 3625 auto *D = GetLocalDecl(*M, Record[N - I - 1]); 3626 ASTDeclReader::attachPreviousDecl(*this, D, MostRecent, CanonDecl); 3627 MostRecent = D; 3628 } 3629 ASTDeclReader::attachLatestDecl(CanonDecl, MostRecent); 3630 } 3631 3632 namespace { 3633 /// \brief Given an ObjC interface, goes through the modules and links to the 3634 /// interface all the categories for it. 3635 class ObjCCategoriesVisitor { 3636 ASTReader &Reader; 3637 ObjCInterfaceDecl *Interface; 3638 llvm::SmallPtrSetImpl<ObjCCategoryDecl *> &Deserialized; 3639 ObjCCategoryDecl *Tail; 3640 llvm::DenseMap<DeclarationName, ObjCCategoryDecl *> NameCategoryMap; 3641 serialization::GlobalDeclID InterfaceID; 3642 unsigned PreviousGeneration; 3643 3644 void add(ObjCCategoryDecl *Cat) { 3645 // Only process each category once. 3646 if (!Deserialized.erase(Cat)) 3647 return; 3648 3649 // Check for duplicate categories. 3650 if (Cat->getDeclName()) { 3651 ObjCCategoryDecl *&Existing = NameCategoryMap[Cat->getDeclName()]; 3652 if (Existing && 3653 Reader.getOwningModuleFile(Existing) 3654 != Reader.getOwningModuleFile(Cat)) { 3655 // FIXME: We should not warn for duplicates in diamond: 3656 // 3657 // MT // 3658 // / \ // 3659 // ML MR // 3660 // \ / // 3661 // MB // 3662 // 3663 // If there are duplicates in ML/MR, there will be warning when 3664 // creating MB *and* when importing MB. We should not warn when 3665 // importing. 3666 Reader.Diag(Cat->getLocation(), diag::warn_dup_category_def) 3667 << Interface->getDeclName() << Cat->getDeclName(); 3668 Reader.Diag(Existing->getLocation(), diag::note_previous_definition); 3669 } else if (!Existing) { 3670 // Record this category. 3671 Existing = Cat; 3672 } 3673 } 3674 3675 // Add this category to the end of the chain. 3676 if (Tail) 3677 ASTDeclReader::setNextObjCCategory(Tail, Cat); 3678 else 3679 Interface->setCategoryListRaw(Cat); 3680 Tail = Cat; 3681 } 3682 3683 public: 3684 ObjCCategoriesVisitor(ASTReader &Reader, 3685 ObjCInterfaceDecl *Interface, 3686 llvm::SmallPtrSetImpl<ObjCCategoryDecl *> &Deserialized, 3687 serialization::GlobalDeclID InterfaceID, 3688 unsigned PreviousGeneration) 3689 : Reader(Reader), Interface(Interface), Deserialized(Deserialized), 3690 Tail(nullptr), InterfaceID(InterfaceID), 3691 PreviousGeneration(PreviousGeneration) 3692 { 3693 // Populate the name -> category map with the set of known categories. 3694 for (auto *Cat : Interface->known_categories()) { 3695 if (Cat->getDeclName()) 3696 NameCategoryMap[Cat->getDeclName()] = Cat; 3697 3698 // Keep track of the tail of the category list. 3699 Tail = Cat; 3700 } 3701 } 3702 3703 bool operator()(ModuleFile &M) { 3704 // If we've loaded all of the category information we care about from 3705 // this module file, we're done. 3706 if (M.Generation <= PreviousGeneration) 3707 return true; 3708 3709 // Map global ID of the definition down to the local ID used in this 3710 // module file. If there is no such mapping, we'll find nothing here 3711 // (or in any module it imports). 3712 DeclID LocalID = Reader.mapGlobalIDToModuleFileGlobalID(M, InterfaceID); 3713 if (!LocalID) 3714 return true; 3715 3716 // Perform a binary search to find the local redeclarations for this 3717 // declaration (if any). 3718 const ObjCCategoriesInfo Compare = { LocalID, 0 }; 3719 const ObjCCategoriesInfo *Result 3720 = std::lower_bound(M.ObjCCategoriesMap, 3721 M.ObjCCategoriesMap + M.LocalNumObjCCategoriesInMap, 3722 Compare); 3723 if (Result == M.ObjCCategoriesMap + M.LocalNumObjCCategoriesInMap || 3724 Result->DefinitionID != LocalID) { 3725 // We didn't find anything. If the class definition is in this module 3726 // file, then the module files it depends on cannot have any categories, 3727 // so suppress further lookup. 3728 return Reader.isDeclIDFromModule(InterfaceID, M); 3729 } 3730 3731 // We found something. Dig out all of the categories. 3732 unsigned Offset = Result->Offset; 3733 unsigned N = M.ObjCCategories[Offset]; 3734 M.ObjCCategories[Offset++] = 0; // Don't try to deserialize again 3735 for (unsigned I = 0; I != N; ++I) 3736 add(cast_or_null<ObjCCategoryDecl>( 3737 Reader.GetLocalDecl(M, M.ObjCCategories[Offset++]))); 3738 return true; 3739 } 3740 }; 3741 } // end anonymous namespace 3742 3743 void ASTReader::loadObjCCategories(serialization::GlobalDeclID ID, 3744 ObjCInterfaceDecl *D, 3745 unsigned PreviousGeneration) { 3746 ObjCCategoriesVisitor Visitor(*this, D, CategoriesDeserialized, ID, 3747 PreviousGeneration); 3748 ModuleMgr.visit(Visitor); 3749 } 3750 3751 template<typename DeclT, typename Fn> 3752 static void forAllLaterRedecls(DeclT *D, Fn F) { 3753 F(D); 3754 3755 // Check whether we've already merged D into its redeclaration chain. 3756 // MostRecent may or may not be nullptr if D has not been merged. If 3757 // not, walk the merged redecl chain and see if it's there. 3758 auto *MostRecent = D->getMostRecentDecl(); 3759 bool Found = false; 3760 for (auto *Redecl = MostRecent; Redecl && !Found; 3761 Redecl = Redecl->getPreviousDecl()) 3762 Found = (Redecl == D); 3763 3764 // If this declaration is merged, apply the functor to all later decls. 3765 if (Found) { 3766 for (auto *Redecl = MostRecent; Redecl != D; 3767 Redecl = Redecl->getPreviousDecl()) 3768 F(Redecl); 3769 } 3770 } 3771 3772 void ASTDeclReader::UpdateDecl(Decl *D) { 3773 while (Record.getIdx() < Record.size()) { 3774 switch ((DeclUpdateKind)Record.readInt()) { 3775 case UPD_CXX_ADDED_IMPLICIT_MEMBER: { 3776 auto *RD = cast<CXXRecordDecl>(D); 3777 // FIXME: If we also have an update record for instantiating the 3778 // definition of D, we need that to happen before we get here. 3779 Decl *MD = Record.readDecl(); 3780 assert(MD && "couldn't read decl from update record"); 3781 // FIXME: We should call addHiddenDecl instead, to add the member 3782 // to its DeclContext. 3783 RD->addedMember(MD); 3784 break; 3785 } 3786 3787 case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION: 3788 // It will be added to the template's specializations set when loaded. 3789 (void)Record.readDecl(); 3790 break; 3791 3792 case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE: { 3793 NamespaceDecl *Anon = ReadDeclAs<NamespaceDecl>(); 3794 3795 // Each module has its own anonymous namespace, which is disjoint from 3796 // any other module's anonymous namespaces, so don't attach the anonymous 3797 // namespace at all. 3798 if (!Record.isModule()) { 3799 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(D)) 3800 TU->setAnonymousNamespace(Anon); 3801 else 3802 cast<NamespaceDecl>(D)->setAnonymousNamespace(Anon); 3803 } 3804 break; 3805 } 3806 3807 case UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER: 3808 cast<VarDecl>(D)->getMemberSpecializationInfo()->setPointOfInstantiation( 3809 ReadSourceLocation()); 3810 break; 3811 3812 case UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT: { 3813 auto Param = cast<ParmVarDecl>(D); 3814 3815 // We have to read the default argument regardless of whether we use it 3816 // so that hypothetical further update records aren't messed up. 3817 // TODO: Add a function to skip over the next expr record. 3818 auto DefaultArg = Record.readExpr(); 3819 3820 // Only apply the update if the parameter still has an uninstantiated 3821 // default argument. 3822 if (Param->hasUninstantiatedDefaultArg()) 3823 Param->setDefaultArg(DefaultArg); 3824 break; 3825 } 3826 3827 case UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER: { 3828 auto FD = cast<FieldDecl>(D); 3829 auto DefaultInit = Record.readExpr(); 3830 3831 // Only apply the update if the field still has an uninstantiated 3832 // default member initializer. 3833 if (FD->hasInClassInitializer() && !FD->getInClassInitializer()) { 3834 if (DefaultInit) 3835 FD->setInClassInitializer(DefaultInit); 3836 else 3837 // Instantiation failed. We can get here if we serialized an AST for 3838 // an invalid program. 3839 FD->removeInClassInitializer(); 3840 } 3841 break; 3842 } 3843 3844 case UPD_CXX_ADDED_FUNCTION_DEFINITION: { 3845 FunctionDecl *FD = cast<FunctionDecl>(D); 3846 if (Reader.PendingBodies[FD]) { 3847 // FIXME: Maybe check for ODR violations. 3848 // It's safe to stop now because this update record is always last. 3849 return; 3850 } 3851 3852 if (Record.readInt()) { 3853 // Maintain AST consistency: any later redeclarations of this function 3854 // are inline if this one is. (We might have merged another declaration 3855 // into this one.) 3856 forAllLaterRedecls(FD, [](FunctionDecl *FD) { 3857 FD->setImplicitlyInline(); 3858 }); 3859 } 3860 FD->setInnerLocStart(ReadSourceLocation()); 3861 if (auto *CD = dyn_cast<CXXConstructorDecl>(FD)) { 3862 CD->NumCtorInitializers = Record.readInt(); 3863 if (CD->NumCtorInitializers) 3864 CD->CtorInitializers = ReadGlobalOffset(); 3865 } 3866 // Store the offset of the body so we can lazily load it later. 3867 Reader.PendingBodies[FD] = GetCurrentCursorOffset(); 3868 HasPendingBody = true; 3869 assert(Record.getIdx() == Record.size() && "lazy body must be last"); 3870 break; 3871 } 3872 3873 case UPD_CXX_INSTANTIATED_CLASS_DEFINITION: { 3874 auto *RD = cast<CXXRecordDecl>(D); 3875 auto *OldDD = RD->getCanonicalDecl()->DefinitionData; 3876 bool HadRealDefinition = 3877 OldDD && (OldDD->Definition != RD || 3878 !Reader.PendingFakeDefinitionData.count(OldDD)); 3879 ReadCXXRecordDefinition(RD, /*Update*/true); 3880 3881 // Visible update is handled separately. 3882 uint64_t LexicalOffset = ReadLocalOffset(); 3883 if (!HadRealDefinition && LexicalOffset) { 3884 Record.readLexicalDeclContextStorage(LexicalOffset, RD); 3885 Reader.PendingFakeDefinitionData.erase(OldDD); 3886 } 3887 3888 auto TSK = (TemplateSpecializationKind)Record.readInt(); 3889 SourceLocation POI = ReadSourceLocation(); 3890 if (MemberSpecializationInfo *MSInfo = 3891 RD->getMemberSpecializationInfo()) { 3892 MSInfo->setTemplateSpecializationKind(TSK); 3893 MSInfo->setPointOfInstantiation(POI); 3894 } else { 3895 ClassTemplateSpecializationDecl *Spec = 3896 cast<ClassTemplateSpecializationDecl>(RD); 3897 Spec->setTemplateSpecializationKind(TSK); 3898 Spec->setPointOfInstantiation(POI); 3899 3900 if (Record.readInt()) { 3901 auto PartialSpec = 3902 ReadDeclAs<ClassTemplatePartialSpecializationDecl>(); 3903 SmallVector<TemplateArgument, 8> TemplArgs; 3904 Record.readTemplateArgumentList(TemplArgs); 3905 auto *TemplArgList = TemplateArgumentList::CreateCopy( 3906 Reader.getContext(), TemplArgs); 3907 3908 // FIXME: If we already have a partial specialization set, 3909 // check that it matches. 3910 if (!Spec->getSpecializedTemplateOrPartial() 3911 .is<ClassTemplatePartialSpecializationDecl *>()) 3912 Spec->setInstantiationOf(PartialSpec, TemplArgList); 3913 } 3914 } 3915 3916 RD->setTagKind((TagTypeKind)Record.readInt()); 3917 RD->setLocation(ReadSourceLocation()); 3918 RD->setLocStart(ReadSourceLocation()); 3919 RD->setBraceRange(ReadSourceRange()); 3920 3921 if (Record.readInt()) { 3922 AttrVec Attrs; 3923 Record.readAttributes(Attrs); 3924 // If the declaration already has attributes, we assume that some other 3925 // AST file already loaded them. 3926 if (!D->hasAttrs()) 3927 D->setAttrsImpl(Attrs, Reader.getContext()); 3928 } 3929 break; 3930 } 3931 3932 case UPD_CXX_RESOLVED_DTOR_DELETE: { 3933 // Set the 'operator delete' directly to avoid emitting another update 3934 // record. 3935 auto *Del = ReadDeclAs<FunctionDecl>(); 3936 auto *First = cast<CXXDestructorDecl>(D->getCanonicalDecl()); 3937 // FIXME: Check consistency if we have an old and new operator delete. 3938 if (!First->OperatorDelete) 3939 First->OperatorDelete = Del; 3940 break; 3941 } 3942 3943 case UPD_CXX_RESOLVED_EXCEPTION_SPEC: { 3944 FunctionProtoType::ExceptionSpecInfo ESI; 3945 SmallVector<QualType, 8> ExceptionStorage; 3946 Record.readExceptionSpec(ExceptionStorage, ESI); 3947 3948 // Update this declaration's exception specification, if needed. 3949 auto *FD = cast<FunctionDecl>(D); 3950 auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 3951 // FIXME: If the exception specification is already present, check that it 3952 // matches. 3953 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { 3954 FD->setType(Reader.Context.getFunctionType( 3955 FPT->getReturnType(), FPT->getParamTypes(), 3956 FPT->getExtProtoInfo().withExceptionSpec(ESI))); 3957 3958 // When we get to the end of deserializing, see if there are other decls 3959 // that we need to propagate this exception specification onto. 3960 Reader.PendingExceptionSpecUpdates.insert( 3961 std::make_pair(FD->getCanonicalDecl(), FD)); 3962 } 3963 break; 3964 } 3965 3966 case UPD_CXX_DEDUCED_RETURN_TYPE: { 3967 // FIXME: Also do this when merging redecls. 3968 QualType DeducedResultType = Record.readType(); 3969 for (auto *Redecl : merged_redecls(D)) { 3970 // FIXME: If the return type is already deduced, check that it matches. 3971 FunctionDecl *FD = cast<FunctionDecl>(Redecl); 3972 Reader.Context.adjustDeducedFunctionResultType(FD, DeducedResultType); 3973 } 3974 break; 3975 } 3976 3977 case UPD_DECL_MARKED_USED: { 3978 // Maintain AST consistency: any later redeclarations are used too. 3979 D->markUsed(Reader.Context); 3980 break; 3981 } 3982 3983 case UPD_MANGLING_NUMBER: 3984 Reader.Context.setManglingNumber(cast<NamedDecl>(D), Record.readInt()); 3985 break; 3986 3987 case UPD_STATIC_LOCAL_NUMBER: 3988 Reader.Context.setStaticLocalNumber(cast<VarDecl>(D), Record.readInt()); 3989 break; 3990 3991 case UPD_DECL_MARKED_OPENMP_THREADPRIVATE: 3992 D->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit( 3993 Reader.Context, ReadSourceRange())); 3994 break; 3995 3996 case UPD_DECL_EXPORTED: { 3997 unsigned SubmoduleID = readSubmoduleID(); 3998 auto *Exported = cast<NamedDecl>(D); 3999 if (auto *TD = dyn_cast<TagDecl>(Exported)) 4000 Exported = TD->getDefinition(); 4001 Module *Owner = SubmoduleID ? Reader.getSubmodule(SubmoduleID) : nullptr; 4002 if (Reader.getContext().getLangOpts().ModulesLocalVisibility) { 4003 Reader.getContext().mergeDefinitionIntoModule(cast<NamedDecl>(Exported), 4004 Owner); 4005 Reader.PendingMergedDefinitionsToDeduplicate.insert( 4006 cast<NamedDecl>(Exported)); 4007 } else if (Owner && Owner->NameVisibility != Module::AllVisible) { 4008 // If Owner is made visible at some later point, make this declaration 4009 // visible too. 4010 Reader.HiddenNamesMap[Owner].push_back(Exported); 4011 } else { 4012 // The declaration is now visible. 4013 Exported->Hidden = false; 4014 } 4015 break; 4016 } 4017 4018 case UPD_DECL_MARKED_OPENMP_DECLARETARGET: 4019 case UPD_ADDED_ATTR_TO_RECORD: 4020 AttrVec Attrs; 4021 Record.readAttributes(Attrs); 4022 assert(Attrs.size() == 1); 4023 D->addAttr(Attrs[0]); 4024 break; 4025 } 4026 } 4027 } 4028