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