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 /// Determine whether the attributes we can overload on are identical for A and 2660 /// B. Expects A and B to (otherwise) have the same type. 2661 static bool hasSameOverloadableAttrs(const FunctionDecl *A, 2662 const FunctionDecl *B) { 2663 SmallVector<const EnableIfAttr *, 4> AEnableIfs; 2664 // Since this is an equality check, we can ignore that enable_if attrs show up 2665 // in reverse order. 2666 for (const auto *EIA : A->specific_attrs<EnableIfAttr>()) 2667 AEnableIfs.push_back(EIA); 2668 2669 SmallVector<const EnableIfAttr *, 4> BEnableIfs; 2670 for (const auto *EIA : B->specific_attrs<EnableIfAttr>()) 2671 BEnableIfs.push_back(EIA); 2672 2673 // Two very common cases: either we have 0 enable_if attrs, or we have an 2674 // unequal number of enable_if attrs. 2675 if (AEnableIfs.empty() && BEnableIfs.empty()) 2676 return true; 2677 2678 if (AEnableIfs.size() != BEnableIfs.size()) 2679 return false; 2680 2681 llvm::FoldingSetNodeID Cand1ID, Cand2ID; 2682 for (unsigned I = 0, E = AEnableIfs.size(); I != E; ++I) { 2683 Cand1ID.clear(); 2684 Cand2ID.clear(); 2685 2686 AEnableIfs[I]->getCond()->Profile(Cand1ID, A->getASTContext(), true); 2687 BEnableIfs[I]->getCond()->Profile(Cand2ID, B->getASTContext(), true); 2688 if (Cand1ID != Cand2ID) 2689 return false; 2690 } 2691 2692 // FIXME: This doesn't currently consider pass_object_size attributes, since 2693 // we aren't guaranteed that A and B have valid parameter lists yet. 2694 return true; 2695 } 2696 2697 /// \brief Determine whether the two declarations refer to the same entity. 2698 static bool isSameEntity(NamedDecl *X, NamedDecl *Y) { 2699 assert(X->getDeclName() == Y->getDeclName() && "Declaration name mismatch!"); 2700 2701 if (X == Y) 2702 return true; 2703 2704 // Must be in the same context. 2705 if (!X->getDeclContext()->getRedeclContext()->Equals( 2706 Y->getDeclContext()->getRedeclContext())) 2707 return false; 2708 2709 // Two typedefs refer to the same entity if they have the same underlying 2710 // type. 2711 if (TypedefNameDecl *TypedefX = dyn_cast<TypedefNameDecl>(X)) 2712 if (TypedefNameDecl *TypedefY = dyn_cast<TypedefNameDecl>(Y)) 2713 return X->getASTContext().hasSameType(TypedefX->getUnderlyingType(), 2714 TypedefY->getUnderlyingType()); 2715 2716 // Must have the same kind. 2717 if (X->getKind() != Y->getKind()) 2718 return false; 2719 2720 // Objective-C classes and protocols with the same name always match. 2721 if (isa<ObjCInterfaceDecl>(X) || isa<ObjCProtocolDecl>(X)) 2722 return true; 2723 2724 if (isa<ClassTemplateSpecializationDecl>(X)) { 2725 // No need to handle these here: we merge them when adding them to the 2726 // template. 2727 return false; 2728 } 2729 2730 // Compatible tags match. 2731 if (TagDecl *TagX = dyn_cast<TagDecl>(X)) { 2732 TagDecl *TagY = cast<TagDecl>(Y); 2733 return (TagX->getTagKind() == TagY->getTagKind()) || 2734 ((TagX->getTagKind() == TTK_Struct || TagX->getTagKind() == TTK_Class || 2735 TagX->getTagKind() == TTK_Interface) && 2736 (TagY->getTagKind() == TTK_Struct || TagY->getTagKind() == TTK_Class || 2737 TagY->getTagKind() == TTK_Interface)); 2738 } 2739 2740 // Functions with the same type and linkage match. 2741 // FIXME: This needs to cope with merging of prototyped/non-prototyped 2742 // functions, etc. 2743 if (FunctionDecl *FuncX = dyn_cast<FunctionDecl>(X)) { 2744 FunctionDecl *FuncY = cast<FunctionDecl>(Y); 2745 if (CXXConstructorDecl *CtorX = dyn_cast<CXXConstructorDecl>(X)) { 2746 CXXConstructorDecl *CtorY = cast<CXXConstructorDecl>(Y); 2747 if (CtorX->getInheritedConstructor() && 2748 !isSameEntity(CtorX->getInheritedConstructor().getConstructor(), 2749 CtorY->getInheritedConstructor().getConstructor())) 2750 return false; 2751 } 2752 return FuncX->getLinkageInternal() == FuncY->getLinkageInternal() && 2753 FuncX->getASTContext().hasSameType(FuncX->getType(), 2754 FuncY->getType()) && 2755 hasSameOverloadableAttrs(FuncX, FuncY); 2756 } 2757 2758 // Variables with the same type and linkage match. 2759 if (VarDecl *VarX = dyn_cast<VarDecl>(X)) { 2760 VarDecl *VarY = cast<VarDecl>(Y); 2761 if (VarX->getLinkageInternal() == VarY->getLinkageInternal()) { 2762 ASTContext &C = VarX->getASTContext(); 2763 if (C.hasSameType(VarX->getType(), VarY->getType())) 2764 return true; 2765 2766 // We can get decls with different types on the redecl chain. Eg. 2767 // template <typename T> struct S { static T Var[]; }; // #1 2768 // template <typename T> T S<T>::Var[sizeof(T)]; // #2 2769 // Only? happens when completing an incomplete array type. In this case 2770 // when comparing #1 and #2 we should go through their element type. 2771 const ArrayType *VarXTy = C.getAsArrayType(VarX->getType()); 2772 const ArrayType *VarYTy = C.getAsArrayType(VarY->getType()); 2773 if (!VarXTy || !VarYTy) 2774 return false; 2775 if (VarXTy->isIncompleteArrayType() || VarYTy->isIncompleteArrayType()) 2776 return C.hasSameType(VarXTy->getElementType(), VarYTy->getElementType()); 2777 } 2778 return false; 2779 } 2780 2781 // Namespaces with the same name and inlinedness match. 2782 if (NamespaceDecl *NamespaceX = dyn_cast<NamespaceDecl>(X)) { 2783 NamespaceDecl *NamespaceY = cast<NamespaceDecl>(Y); 2784 return NamespaceX->isInline() == NamespaceY->isInline(); 2785 } 2786 2787 // Identical template names and kinds match if their template parameter lists 2788 // and patterns match. 2789 if (TemplateDecl *TemplateX = dyn_cast<TemplateDecl>(X)) { 2790 TemplateDecl *TemplateY = cast<TemplateDecl>(Y); 2791 return isSameEntity(TemplateX->getTemplatedDecl(), 2792 TemplateY->getTemplatedDecl()) && 2793 isSameTemplateParameterList(TemplateX->getTemplateParameters(), 2794 TemplateY->getTemplateParameters()); 2795 } 2796 2797 // Fields with the same name and the same type match. 2798 if (FieldDecl *FDX = dyn_cast<FieldDecl>(X)) { 2799 FieldDecl *FDY = cast<FieldDecl>(Y); 2800 // FIXME: Also check the bitwidth is odr-equivalent, if any. 2801 return X->getASTContext().hasSameType(FDX->getType(), FDY->getType()); 2802 } 2803 2804 // Indirect fields with the same target field match. 2805 if (auto *IFDX = dyn_cast<IndirectFieldDecl>(X)) { 2806 auto *IFDY = cast<IndirectFieldDecl>(Y); 2807 return IFDX->getAnonField()->getCanonicalDecl() == 2808 IFDY->getAnonField()->getCanonicalDecl(); 2809 } 2810 2811 // Enumerators with the same name match. 2812 if (isa<EnumConstantDecl>(X)) 2813 // FIXME: Also check the value is odr-equivalent. 2814 return true; 2815 2816 // Using shadow declarations with the same target match. 2817 if (UsingShadowDecl *USX = dyn_cast<UsingShadowDecl>(X)) { 2818 UsingShadowDecl *USY = cast<UsingShadowDecl>(Y); 2819 return USX->getTargetDecl() == USY->getTargetDecl(); 2820 } 2821 2822 // Using declarations with the same qualifier match. (We already know that 2823 // the name matches.) 2824 if (auto *UX = dyn_cast<UsingDecl>(X)) { 2825 auto *UY = cast<UsingDecl>(Y); 2826 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) && 2827 UX->hasTypename() == UY->hasTypename() && 2828 UX->isAccessDeclaration() == UY->isAccessDeclaration(); 2829 } 2830 if (auto *UX = dyn_cast<UnresolvedUsingValueDecl>(X)) { 2831 auto *UY = cast<UnresolvedUsingValueDecl>(Y); 2832 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) && 2833 UX->isAccessDeclaration() == UY->isAccessDeclaration(); 2834 } 2835 if (auto *UX = dyn_cast<UnresolvedUsingTypenameDecl>(X)) 2836 return isSameQualifier( 2837 UX->getQualifier(), 2838 cast<UnresolvedUsingTypenameDecl>(Y)->getQualifier()); 2839 2840 // Namespace alias definitions with the same target match. 2841 if (auto *NAX = dyn_cast<NamespaceAliasDecl>(X)) { 2842 auto *NAY = cast<NamespaceAliasDecl>(Y); 2843 return NAX->getNamespace()->Equals(NAY->getNamespace()); 2844 } 2845 2846 return false; 2847 } 2848 2849 /// Find the context in which we should search for previous declarations when 2850 /// looking for declarations to merge. 2851 DeclContext *ASTDeclReader::getPrimaryContextForMerging(ASTReader &Reader, 2852 DeclContext *DC) { 2853 if (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC)) 2854 return ND->getOriginalNamespace(); 2855 2856 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 2857 // Try to dig out the definition. 2858 auto *DD = RD->DefinitionData; 2859 if (!DD) 2860 DD = RD->getCanonicalDecl()->DefinitionData; 2861 2862 // If there's no definition yet, then DC's definition is added by an update 2863 // record, but we've not yet loaded that update record. In this case, we 2864 // commit to DC being the canonical definition now, and will fix this when 2865 // we load the update record. 2866 if (!DD) { 2867 DD = new (Reader.Context) struct CXXRecordDecl::DefinitionData(RD); 2868 RD->IsCompleteDefinition = true; 2869 RD->DefinitionData = DD; 2870 RD->getCanonicalDecl()->DefinitionData = DD; 2871 2872 // Track that we did this horrible thing so that we can fix it later. 2873 Reader.PendingFakeDefinitionData.insert( 2874 std::make_pair(DD, ASTReader::PendingFakeDefinitionKind::Fake)); 2875 } 2876 2877 return DD->Definition; 2878 } 2879 2880 if (EnumDecl *ED = dyn_cast<EnumDecl>(DC)) 2881 return ED->getASTContext().getLangOpts().CPlusPlus? ED->getDefinition() 2882 : nullptr; 2883 2884 // We can see the TU here only if we have no Sema object. In that case, 2885 // there's no TU scope to look in, so using the DC alone is sufficient. 2886 if (auto *TU = dyn_cast<TranslationUnitDecl>(DC)) 2887 return TU; 2888 2889 return nullptr; 2890 } 2891 2892 ASTDeclReader::FindExistingResult::~FindExistingResult() { 2893 // Record that we had a typedef name for linkage whether or not we merge 2894 // with that declaration. 2895 if (TypedefNameForLinkage) { 2896 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 2897 Reader.ImportedTypedefNamesForLinkage.insert( 2898 std::make_pair(std::make_pair(DC, TypedefNameForLinkage), New)); 2899 return; 2900 } 2901 2902 if (!AddResult || Existing) 2903 return; 2904 2905 DeclarationName Name = New->getDeclName(); 2906 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 2907 if (needsAnonymousDeclarationNumber(New)) { 2908 setAnonymousDeclForMerging(Reader, New->getLexicalDeclContext(), 2909 AnonymousDeclNumber, New); 2910 } else if (DC->isTranslationUnit() && 2911 !Reader.getContext().getLangOpts().CPlusPlus) { 2912 if (Reader.getIdResolver().tryAddTopLevelDecl(New, Name)) 2913 Reader.PendingFakeLookupResults[Name.getAsIdentifierInfo()] 2914 .push_back(New); 2915 } else if (DeclContext *MergeDC = getPrimaryContextForMerging(Reader, DC)) { 2916 // Add the declaration to its redeclaration context so later merging 2917 // lookups will find it. 2918 MergeDC->makeDeclVisibleInContextImpl(New, /*Internal*/true); 2919 } 2920 } 2921 2922 /// Find the declaration that should be merged into, given the declaration found 2923 /// by name lookup. If we're merging an anonymous declaration within a typedef, 2924 /// we need a matching typedef, and we merge with the type inside it. 2925 static NamedDecl *getDeclForMerging(NamedDecl *Found, 2926 bool IsTypedefNameForLinkage) { 2927 if (!IsTypedefNameForLinkage) 2928 return Found; 2929 2930 // If we found a typedef declaration that gives a name to some other 2931 // declaration, then we want that inner declaration. Declarations from 2932 // AST files are handled via ImportedTypedefNamesForLinkage. 2933 if (Found->isFromASTFile()) 2934 return nullptr; 2935 2936 if (auto *TND = dyn_cast<TypedefNameDecl>(Found)) 2937 return TND->getAnonDeclWithTypedefName(/*AnyRedecl*/true); 2938 2939 return nullptr; 2940 } 2941 2942 NamedDecl *ASTDeclReader::getAnonymousDeclForMerging(ASTReader &Reader, 2943 DeclContext *DC, 2944 unsigned Index) { 2945 // If the lexical context has been merged, look into the now-canonical 2946 // definition. 2947 if (auto *Merged = Reader.MergedDeclContexts.lookup(DC)) 2948 DC = Merged; 2949 2950 // If we've seen this before, return the canonical declaration. 2951 auto &Previous = Reader.AnonymousDeclarationsForMerging[DC]; 2952 if (Index < Previous.size() && Previous[Index]) 2953 return Previous[Index]; 2954 2955 // If this is the first time, but we have parsed a declaration of the context, 2956 // build the anonymous declaration list from the parsed declaration. 2957 if (!cast<Decl>(DC)->isFromASTFile()) { 2958 numberAnonymousDeclsWithin(DC, [&](NamedDecl *ND, unsigned Number) { 2959 if (Previous.size() == Number) 2960 Previous.push_back(cast<NamedDecl>(ND->getCanonicalDecl())); 2961 else 2962 Previous[Number] = cast<NamedDecl>(ND->getCanonicalDecl()); 2963 }); 2964 } 2965 2966 return Index < Previous.size() ? Previous[Index] : nullptr; 2967 } 2968 2969 void ASTDeclReader::setAnonymousDeclForMerging(ASTReader &Reader, 2970 DeclContext *DC, unsigned Index, 2971 NamedDecl *D) { 2972 if (auto *Merged = Reader.MergedDeclContexts.lookup(DC)) 2973 DC = Merged; 2974 2975 auto &Previous = Reader.AnonymousDeclarationsForMerging[DC]; 2976 if (Index >= Previous.size()) 2977 Previous.resize(Index + 1); 2978 if (!Previous[Index]) 2979 Previous[Index] = D; 2980 } 2981 2982 ASTDeclReader::FindExistingResult ASTDeclReader::findExisting(NamedDecl *D) { 2983 DeclarationName Name = TypedefNameForLinkage ? TypedefNameForLinkage 2984 : D->getDeclName(); 2985 2986 if (!Name && !needsAnonymousDeclarationNumber(D)) { 2987 // Don't bother trying to find unnamed declarations that are in 2988 // unmergeable contexts. 2989 FindExistingResult Result(Reader, D, /*Existing=*/nullptr, 2990 AnonymousDeclNumber, TypedefNameForLinkage); 2991 Result.suppress(); 2992 return Result; 2993 } 2994 2995 DeclContext *DC = D->getDeclContext()->getRedeclContext(); 2996 if (TypedefNameForLinkage) { 2997 auto It = Reader.ImportedTypedefNamesForLinkage.find( 2998 std::make_pair(DC, TypedefNameForLinkage)); 2999 if (It != Reader.ImportedTypedefNamesForLinkage.end()) 3000 if (isSameEntity(It->second, D)) 3001 return FindExistingResult(Reader, D, It->second, AnonymousDeclNumber, 3002 TypedefNameForLinkage); 3003 // Go on to check in other places in case an existing typedef name 3004 // was not imported. 3005 } 3006 3007 if (needsAnonymousDeclarationNumber(D)) { 3008 // This is an anonymous declaration that we may need to merge. Look it up 3009 // in its context by number. 3010 if (auto *Existing = getAnonymousDeclForMerging( 3011 Reader, D->getLexicalDeclContext(), AnonymousDeclNumber)) 3012 if (isSameEntity(Existing, D)) 3013 return FindExistingResult(Reader, D, Existing, AnonymousDeclNumber, 3014 TypedefNameForLinkage); 3015 } else if (DC->isTranslationUnit() && 3016 !Reader.getContext().getLangOpts().CPlusPlus) { 3017 IdentifierResolver &IdResolver = Reader.getIdResolver(); 3018 3019 // Temporarily consider the identifier to be up-to-date. We don't want to 3020 // cause additional lookups here. 3021 class UpToDateIdentifierRAII { 3022 IdentifierInfo *II; 3023 bool WasOutToDate; 3024 3025 public: 3026 explicit UpToDateIdentifierRAII(IdentifierInfo *II) 3027 : II(II), WasOutToDate(false) 3028 { 3029 if (II) { 3030 WasOutToDate = II->isOutOfDate(); 3031 if (WasOutToDate) 3032 II->setOutOfDate(false); 3033 } 3034 } 3035 3036 ~UpToDateIdentifierRAII() { 3037 if (WasOutToDate) 3038 II->setOutOfDate(true); 3039 } 3040 } UpToDate(Name.getAsIdentifierInfo()); 3041 3042 for (IdentifierResolver::iterator I = IdResolver.begin(Name), 3043 IEnd = IdResolver.end(); 3044 I != IEnd; ++I) { 3045 if (NamedDecl *Existing = getDeclForMerging(*I, TypedefNameForLinkage)) 3046 if (isSameEntity(Existing, D)) 3047 return FindExistingResult(Reader, D, Existing, AnonymousDeclNumber, 3048 TypedefNameForLinkage); 3049 } 3050 } else if (DeclContext *MergeDC = getPrimaryContextForMerging(Reader, DC)) { 3051 DeclContext::lookup_result R = MergeDC->noload_lookup(Name); 3052 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 3053 if (NamedDecl *Existing = getDeclForMerging(*I, TypedefNameForLinkage)) 3054 if (isSameEntity(Existing, D)) 3055 return FindExistingResult(Reader, D, Existing, AnonymousDeclNumber, 3056 TypedefNameForLinkage); 3057 } 3058 } else { 3059 // Not in a mergeable context. 3060 return FindExistingResult(Reader); 3061 } 3062 3063 // If this declaration is from a merged context, make a note that we need to 3064 // check that the canonical definition of that context contains the decl. 3065 // 3066 // FIXME: We should do something similar if we merge two definitions of the 3067 // same template specialization into the same CXXRecordDecl. 3068 auto MergedDCIt = Reader.MergedDeclContexts.find(D->getLexicalDeclContext()); 3069 if (MergedDCIt != Reader.MergedDeclContexts.end() && 3070 MergedDCIt->second == D->getDeclContext()) 3071 Reader.PendingOdrMergeChecks.push_back(D); 3072 3073 return FindExistingResult(Reader, D, /*Existing=*/nullptr, 3074 AnonymousDeclNumber, TypedefNameForLinkage); 3075 } 3076 3077 template<typename DeclT> 3078 Decl *ASTDeclReader::getMostRecentDeclImpl(Redeclarable<DeclT> *D) { 3079 return D->RedeclLink.getLatestNotUpdated(); 3080 } 3081 Decl *ASTDeclReader::getMostRecentDeclImpl(...) { 3082 llvm_unreachable("getMostRecentDecl on non-redeclarable declaration"); 3083 } 3084 3085 Decl *ASTDeclReader::getMostRecentDecl(Decl *D) { 3086 assert(D); 3087 3088 switch (D->getKind()) { 3089 #define ABSTRACT_DECL(TYPE) 3090 #define DECL(TYPE, BASE) \ 3091 case Decl::TYPE: \ 3092 return getMostRecentDeclImpl(cast<TYPE##Decl>(D)); 3093 #include "clang/AST/DeclNodes.inc" 3094 } 3095 llvm_unreachable("unknown decl kind"); 3096 } 3097 3098 Decl *ASTReader::getMostRecentExistingDecl(Decl *D) { 3099 return ASTDeclReader::getMostRecentDecl(D->getCanonicalDecl()); 3100 } 3101 3102 template<typename DeclT> 3103 void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader, 3104 Redeclarable<DeclT> *D, 3105 Decl *Previous, Decl *Canon) { 3106 D->RedeclLink.setPrevious(cast<DeclT>(Previous)); 3107 D->First = cast<DeclT>(Previous)->First; 3108 } 3109 3110 namespace clang { 3111 template<> 3112 void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader, 3113 Redeclarable<VarDecl> *D, 3114 Decl *Previous, Decl *Canon) { 3115 VarDecl *VD = static_cast<VarDecl*>(D); 3116 VarDecl *PrevVD = cast<VarDecl>(Previous); 3117 D->RedeclLink.setPrevious(PrevVD); 3118 D->First = PrevVD->First; 3119 3120 // We should keep at most one definition on the chain. 3121 // FIXME: Cache the definition once we've found it. Building a chain with 3122 // N definitions currently takes O(N^2) time here. 3123 if (VD->isThisDeclarationADefinition() == VarDecl::Definition) { 3124 for (VarDecl *CurD = PrevVD; CurD; CurD = CurD->getPreviousDecl()) { 3125 if (CurD->isThisDeclarationADefinition() == VarDecl::Definition) { 3126 Reader.mergeDefinitionVisibility(CurD, VD); 3127 VD->demoteThisDefinitionToDeclaration(); 3128 break; 3129 } 3130 } 3131 } 3132 } 3133 3134 template<> 3135 void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader, 3136 Redeclarable<FunctionDecl> *D, 3137 Decl *Previous, Decl *Canon) { 3138 FunctionDecl *FD = static_cast<FunctionDecl*>(D); 3139 FunctionDecl *PrevFD = cast<FunctionDecl>(Previous); 3140 3141 FD->RedeclLink.setPrevious(PrevFD); 3142 FD->First = PrevFD->First; 3143 3144 // If the previous declaration is an inline function declaration, then this 3145 // declaration is too. 3146 if (PrevFD->IsInline != FD->IsInline) { 3147 // FIXME: [dcl.fct.spec]p4: 3148 // If a function with external linkage is declared inline in one 3149 // translation unit, it shall be declared inline in all translation 3150 // units in which it appears. 3151 // 3152 // Be careful of this case: 3153 // 3154 // module A: 3155 // template<typename T> struct X { void f(); }; 3156 // template<typename T> inline void X<T>::f() {} 3157 // 3158 // module B instantiates the declaration of X<int>::f 3159 // module C instantiates the definition of X<int>::f 3160 // 3161 // If module B and C are merged, we do not have a violation of this rule. 3162 FD->IsInline = true; 3163 } 3164 3165 // If we need to propagate an exception specification along the redecl 3166 // chain, make a note of that so that we can do so later. 3167 auto *FPT = FD->getType()->getAs<FunctionProtoType>(); 3168 auto *PrevFPT = PrevFD->getType()->getAs<FunctionProtoType>(); 3169 if (FPT && PrevFPT) { 3170 bool IsUnresolved = isUnresolvedExceptionSpec(FPT->getExceptionSpecType()); 3171 bool WasUnresolved = 3172 isUnresolvedExceptionSpec(PrevFPT->getExceptionSpecType()); 3173 if (IsUnresolved != WasUnresolved) 3174 Reader.PendingExceptionSpecUpdates.insert( 3175 std::make_pair(Canon, IsUnresolved ? PrevFD : FD)); 3176 } 3177 } 3178 } // end namespace clang 3179 3180 void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader, ...) { 3181 llvm_unreachable("attachPreviousDecl on non-redeclarable declaration"); 3182 } 3183 3184 /// Inherit the default template argument from \p From to \p To. Returns 3185 /// \c false if there is no default template for \p From. 3186 template <typename ParmDecl> 3187 static bool inheritDefaultTemplateArgument(ASTContext &Context, ParmDecl *From, 3188 Decl *ToD) { 3189 auto *To = cast<ParmDecl>(ToD); 3190 if (!From->hasDefaultArgument()) 3191 return false; 3192 To->setInheritedDefaultArgument(Context, From); 3193 return true; 3194 } 3195 3196 static void inheritDefaultTemplateArguments(ASTContext &Context, 3197 TemplateDecl *From, 3198 TemplateDecl *To) { 3199 auto *FromTP = From->getTemplateParameters(); 3200 auto *ToTP = To->getTemplateParameters(); 3201 assert(FromTP->size() == ToTP->size() && "merged mismatched templates?"); 3202 3203 for (unsigned I = 0, N = FromTP->size(); I != N; ++I) { 3204 NamedDecl *FromParam = FromTP->getParam(N - I - 1); 3205 if (FromParam->isParameterPack()) 3206 continue; 3207 NamedDecl *ToParam = ToTP->getParam(N - I - 1); 3208 3209 if (auto *FTTP = dyn_cast<TemplateTypeParmDecl>(FromParam)) { 3210 if (!inheritDefaultTemplateArgument(Context, FTTP, ToParam)) 3211 break; 3212 } else if (auto *FNTTP = dyn_cast<NonTypeTemplateParmDecl>(FromParam)) { 3213 if (!inheritDefaultTemplateArgument(Context, FNTTP, ToParam)) 3214 break; 3215 } else { 3216 if (!inheritDefaultTemplateArgument( 3217 Context, cast<TemplateTemplateParmDecl>(FromParam), ToParam)) 3218 break; 3219 } 3220 } 3221 } 3222 3223 void ASTDeclReader::attachPreviousDecl(ASTReader &Reader, Decl *D, 3224 Decl *Previous, Decl *Canon) { 3225 assert(D && Previous); 3226 3227 switch (D->getKind()) { 3228 #define ABSTRACT_DECL(TYPE) 3229 #define DECL(TYPE, BASE) \ 3230 case Decl::TYPE: \ 3231 attachPreviousDeclImpl(Reader, cast<TYPE##Decl>(D), Previous, Canon); \ 3232 break; 3233 #include "clang/AST/DeclNodes.inc" 3234 } 3235 3236 // If the declaration was visible in one module, a redeclaration of it in 3237 // another module remains visible even if it wouldn't be visible by itself. 3238 // 3239 // FIXME: In this case, the declaration should only be visible if a module 3240 // that makes it visible has been imported. 3241 D->IdentifierNamespace |= 3242 Previous->IdentifierNamespace & 3243 (Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Type); 3244 3245 // If the declaration declares a template, it may inherit default arguments 3246 // from the previous declaration. 3247 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 3248 inheritDefaultTemplateArguments(Reader.getContext(), 3249 cast<TemplateDecl>(Previous), TD); 3250 } 3251 3252 template<typename DeclT> 3253 void ASTDeclReader::attachLatestDeclImpl(Redeclarable<DeclT> *D, Decl *Latest) { 3254 D->RedeclLink.setLatest(cast<DeclT>(Latest)); 3255 } 3256 void ASTDeclReader::attachLatestDeclImpl(...) { 3257 llvm_unreachable("attachLatestDecl on non-redeclarable declaration"); 3258 } 3259 3260 void ASTDeclReader::attachLatestDecl(Decl *D, Decl *Latest) { 3261 assert(D && Latest); 3262 3263 switch (D->getKind()) { 3264 #define ABSTRACT_DECL(TYPE) 3265 #define DECL(TYPE, BASE) \ 3266 case Decl::TYPE: \ 3267 attachLatestDeclImpl(cast<TYPE##Decl>(D), Latest); \ 3268 break; 3269 #include "clang/AST/DeclNodes.inc" 3270 } 3271 } 3272 3273 template<typename DeclT> 3274 void ASTDeclReader::markIncompleteDeclChainImpl(Redeclarable<DeclT> *D) { 3275 D->RedeclLink.markIncomplete(); 3276 } 3277 void ASTDeclReader::markIncompleteDeclChainImpl(...) { 3278 llvm_unreachable("markIncompleteDeclChain on non-redeclarable declaration"); 3279 } 3280 3281 void ASTReader::markIncompleteDeclChain(Decl *D) { 3282 switch (D->getKind()) { 3283 #define ABSTRACT_DECL(TYPE) 3284 #define DECL(TYPE, BASE) \ 3285 case Decl::TYPE: \ 3286 ASTDeclReader::markIncompleteDeclChainImpl(cast<TYPE##Decl>(D)); \ 3287 break; 3288 #include "clang/AST/DeclNodes.inc" 3289 } 3290 } 3291 3292 /// \brief Read the declaration at the given offset from the AST file. 3293 Decl *ASTReader::ReadDeclRecord(DeclID ID) { 3294 unsigned Index = ID - NUM_PREDEF_DECL_IDS; 3295 SourceLocation DeclLoc; 3296 RecordLocation Loc = DeclCursorForID(ID, DeclLoc); 3297 llvm::BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor; 3298 // Keep track of where we are in the stream, then jump back there 3299 // after reading this declaration. 3300 SavedStreamPosition SavedPosition(DeclsCursor); 3301 3302 ReadingKindTracker ReadingKind(Read_Decl, *this); 3303 3304 // Note that we are loading a declaration record. 3305 Deserializing ADecl(this); 3306 3307 DeclsCursor.JumpToBit(Loc.Offset); 3308 ASTRecordReader Record(*this, *Loc.F); 3309 ASTDeclReader Reader(*this, Record, Loc, ID, DeclLoc); 3310 unsigned Code = DeclsCursor.ReadCode(); 3311 3312 Decl *D = nullptr; 3313 switch ((DeclCode)Record.readRecord(DeclsCursor, Code)) { 3314 case DECL_CONTEXT_LEXICAL: 3315 case DECL_CONTEXT_VISIBLE: 3316 llvm_unreachable("Record cannot be de-serialized with ReadDeclRecord"); 3317 case DECL_TYPEDEF: 3318 D = TypedefDecl::CreateDeserialized(Context, ID); 3319 break; 3320 case DECL_TYPEALIAS: 3321 D = TypeAliasDecl::CreateDeserialized(Context, ID); 3322 break; 3323 case DECL_ENUM: 3324 D = EnumDecl::CreateDeserialized(Context, ID); 3325 break; 3326 case DECL_RECORD: 3327 D = RecordDecl::CreateDeserialized(Context, ID); 3328 break; 3329 case DECL_ENUM_CONSTANT: 3330 D = EnumConstantDecl::CreateDeserialized(Context, ID); 3331 break; 3332 case DECL_FUNCTION: 3333 D = FunctionDecl::CreateDeserialized(Context, ID); 3334 break; 3335 case DECL_LINKAGE_SPEC: 3336 D = LinkageSpecDecl::CreateDeserialized(Context, ID); 3337 break; 3338 case DECL_EXPORT: 3339 D = ExportDecl::CreateDeserialized(Context, ID); 3340 break; 3341 case DECL_LABEL: 3342 D = LabelDecl::CreateDeserialized(Context, ID); 3343 break; 3344 case DECL_NAMESPACE: 3345 D = NamespaceDecl::CreateDeserialized(Context, ID); 3346 break; 3347 case DECL_NAMESPACE_ALIAS: 3348 D = NamespaceAliasDecl::CreateDeserialized(Context, ID); 3349 break; 3350 case DECL_USING: 3351 D = UsingDecl::CreateDeserialized(Context, ID); 3352 break; 3353 case DECL_USING_PACK: 3354 D = UsingPackDecl::CreateDeserialized(Context, ID, Record.readInt()); 3355 break; 3356 case DECL_USING_SHADOW: 3357 D = UsingShadowDecl::CreateDeserialized(Context, ID); 3358 break; 3359 case DECL_CONSTRUCTOR_USING_SHADOW: 3360 D = ConstructorUsingShadowDecl::CreateDeserialized(Context, ID); 3361 break; 3362 case DECL_USING_DIRECTIVE: 3363 D = UsingDirectiveDecl::CreateDeserialized(Context, ID); 3364 break; 3365 case DECL_UNRESOLVED_USING_VALUE: 3366 D = UnresolvedUsingValueDecl::CreateDeserialized(Context, ID); 3367 break; 3368 case DECL_UNRESOLVED_USING_TYPENAME: 3369 D = UnresolvedUsingTypenameDecl::CreateDeserialized(Context, ID); 3370 break; 3371 case DECL_CXX_RECORD: 3372 D = CXXRecordDecl::CreateDeserialized(Context, ID); 3373 break; 3374 case DECL_CXX_METHOD: 3375 D = CXXMethodDecl::CreateDeserialized(Context, ID); 3376 break; 3377 case DECL_CXX_CONSTRUCTOR: 3378 D = CXXConstructorDecl::CreateDeserialized(Context, ID, false); 3379 break; 3380 case DECL_CXX_INHERITED_CONSTRUCTOR: 3381 D = CXXConstructorDecl::CreateDeserialized(Context, ID, true); 3382 break; 3383 case DECL_CXX_DESTRUCTOR: 3384 D = CXXDestructorDecl::CreateDeserialized(Context, ID); 3385 break; 3386 case DECL_CXX_CONVERSION: 3387 D = CXXConversionDecl::CreateDeserialized(Context, ID); 3388 break; 3389 case DECL_ACCESS_SPEC: 3390 D = AccessSpecDecl::CreateDeserialized(Context, ID); 3391 break; 3392 case DECL_FRIEND: 3393 D = FriendDecl::CreateDeserialized(Context, ID, Record.readInt()); 3394 break; 3395 case DECL_FRIEND_TEMPLATE: 3396 D = FriendTemplateDecl::CreateDeserialized(Context, ID); 3397 break; 3398 case DECL_CLASS_TEMPLATE: 3399 D = ClassTemplateDecl::CreateDeserialized(Context, ID); 3400 break; 3401 case DECL_CLASS_TEMPLATE_SPECIALIZATION: 3402 D = ClassTemplateSpecializationDecl::CreateDeserialized(Context, ID); 3403 break; 3404 case DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION: 3405 D = ClassTemplatePartialSpecializationDecl::CreateDeserialized(Context, ID); 3406 break; 3407 case DECL_VAR_TEMPLATE: 3408 D = VarTemplateDecl::CreateDeserialized(Context, ID); 3409 break; 3410 case DECL_VAR_TEMPLATE_SPECIALIZATION: 3411 D = VarTemplateSpecializationDecl::CreateDeserialized(Context, ID); 3412 break; 3413 case DECL_VAR_TEMPLATE_PARTIAL_SPECIALIZATION: 3414 D = VarTemplatePartialSpecializationDecl::CreateDeserialized(Context, ID); 3415 break; 3416 case DECL_CLASS_SCOPE_FUNCTION_SPECIALIZATION: 3417 D = ClassScopeFunctionSpecializationDecl::CreateDeserialized(Context, ID); 3418 break; 3419 case DECL_FUNCTION_TEMPLATE: 3420 D = FunctionTemplateDecl::CreateDeserialized(Context, ID); 3421 break; 3422 case DECL_TEMPLATE_TYPE_PARM: 3423 D = TemplateTypeParmDecl::CreateDeserialized(Context, ID); 3424 break; 3425 case DECL_NON_TYPE_TEMPLATE_PARM: 3426 D = NonTypeTemplateParmDecl::CreateDeserialized(Context, ID); 3427 break; 3428 case DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK: 3429 D = NonTypeTemplateParmDecl::CreateDeserialized(Context, ID, 3430 Record.readInt()); 3431 break; 3432 case DECL_TEMPLATE_TEMPLATE_PARM: 3433 D = TemplateTemplateParmDecl::CreateDeserialized(Context, ID); 3434 break; 3435 case DECL_EXPANDED_TEMPLATE_TEMPLATE_PARM_PACK: 3436 D = TemplateTemplateParmDecl::CreateDeserialized(Context, ID, 3437 Record.readInt()); 3438 break; 3439 case DECL_TYPE_ALIAS_TEMPLATE: 3440 D = TypeAliasTemplateDecl::CreateDeserialized(Context, ID); 3441 break; 3442 case DECL_STATIC_ASSERT: 3443 D = StaticAssertDecl::CreateDeserialized(Context, ID); 3444 break; 3445 case DECL_OBJC_METHOD: 3446 D = ObjCMethodDecl::CreateDeserialized(Context, ID); 3447 break; 3448 case DECL_OBJC_INTERFACE: 3449 D = ObjCInterfaceDecl::CreateDeserialized(Context, ID); 3450 break; 3451 case DECL_OBJC_IVAR: 3452 D = ObjCIvarDecl::CreateDeserialized(Context, ID); 3453 break; 3454 case DECL_OBJC_PROTOCOL: 3455 D = ObjCProtocolDecl::CreateDeserialized(Context, ID); 3456 break; 3457 case DECL_OBJC_AT_DEFS_FIELD: 3458 D = ObjCAtDefsFieldDecl::CreateDeserialized(Context, ID); 3459 break; 3460 case DECL_OBJC_CATEGORY: 3461 D = ObjCCategoryDecl::CreateDeserialized(Context, ID); 3462 break; 3463 case DECL_OBJC_CATEGORY_IMPL: 3464 D = ObjCCategoryImplDecl::CreateDeserialized(Context, ID); 3465 break; 3466 case DECL_OBJC_IMPLEMENTATION: 3467 D = ObjCImplementationDecl::CreateDeserialized(Context, ID); 3468 break; 3469 case DECL_OBJC_COMPATIBLE_ALIAS: 3470 D = ObjCCompatibleAliasDecl::CreateDeserialized(Context, ID); 3471 break; 3472 case DECL_OBJC_PROPERTY: 3473 D = ObjCPropertyDecl::CreateDeserialized(Context, ID); 3474 break; 3475 case DECL_OBJC_PROPERTY_IMPL: 3476 D = ObjCPropertyImplDecl::CreateDeserialized(Context, ID); 3477 break; 3478 case DECL_FIELD: 3479 D = FieldDecl::CreateDeserialized(Context, ID); 3480 break; 3481 case DECL_INDIRECTFIELD: 3482 D = IndirectFieldDecl::CreateDeserialized(Context, ID); 3483 break; 3484 case DECL_VAR: 3485 D = VarDecl::CreateDeserialized(Context, ID); 3486 break; 3487 case DECL_IMPLICIT_PARAM: 3488 D = ImplicitParamDecl::CreateDeserialized(Context, ID); 3489 break; 3490 case DECL_PARM_VAR: 3491 D = ParmVarDecl::CreateDeserialized(Context, ID); 3492 break; 3493 case DECL_DECOMPOSITION: 3494 D = DecompositionDecl::CreateDeserialized(Context, ID, Record.readInt()); 3495 break; 3496 case DECL_BINDING: 3497 D = BindingDecl::CreateDeserialized(Context, ID); 3498 break; 3499 case DECL_FILE_SCOPE_ASM: 3500 D = FileScopeAsmDecl::CreateDeserialized(Context, ID); 3501 break; 3502 case DECL_BLOCK: 3503 D = BlockDecl::CreateDeserialized(Context, ID); 3504 break; 3505 case DECL_MS_PROPERTY: 3506 D = MSPropertyDecl::CreateDeserialized(Context, ID); 3507 break; 3508 case DECL_CAPTURED: 3509 D = CapturedDecl::CreateDeserialized(Context, ID, Record.readInt()); 3510 break; 3511 case DECL_CXX_BASE_SPECIFIERS: 3512 Error("attempt to read a C++ base-specifier record as a declaration"); 3513 return nullptr; 3514 case DECL_CXX_CTOR_INITIALIZERS: 3515 Error("attempt to read a C++ ctor initializer record as a declaration"); 3516 return nullptr; 3517 case DECL_IMPORT: 3518 // Note: last entry of the ImportDecl record is the number of stored source 3519 // locations. 3520 D = ImportDecl::CreateDeserialized(Context, ID, Record.back()); 3521 break; 3522 case DECL_OMP_THREADPRIVATE: 3523 D = OMPThreadPrivateDecl::CreateDeserialized(Context, ID, Record.readInt()); 3524 break; 3525 case DECL_OMP_DECLARE_REDUCTION: 3526 D = OMPDeclareReductionDecl::CreateDeserialized(Context, ID); 3527 break; 3528 case DECL_OMP_CAPTUREDEXPR: 3529 D = OMPCapturedExprDecl::CreateDeserialized(Context, ID); 3530 break; 3531 case DECL_PRAGMA_COMMENT: 3532 D = PragmaCommentDecl::CreateDeserialized(Context, ID, Record.readInt()); 3533 break; 3534 case DECL_PRAGMA_DETECT_MISMATCH: 3535 D = PragmaDetectMismatchDecl::CreateDeserialized(Context, ID, 3536 Record.readInt()); 3537 break; 3538 case DECL_EMPTY: 3539 D = EmptyDecl::CreateDeserialized(Context, ID); 3540 break; 3541 case DECL_OBJC_TYPE_PARAM: 3542 D = ObjCTypeParamDecl::CreateDeserialized(Context, ID); 3543 break; 3544 } 3545 3546 assert(D && "Unknown declaration reading AST file"); 3547 LoadedDecl(Index, D); 3548 // Set the DeclContext before doing any deserialization, to make sure internal 3549 // calls to Decl::getASTContext() by Decl's methods will find the 3550 // TranslationUnitDecl without crashing. 3551 D->setDeclContext(Context.getTranslationUnitDecl()); 3552 Reader.Visit(D); 3553 3554 // If this declaration is also a declaration context, get the 3555 // offsets for its tables of lexical and visible declarations. 3556 if (DeclContext *DC = dyn_cast<DeclContext>(D)) { 3557 std::pair<uint64_t, uint64_t> Offsets = Reader.VisitDeclContext(DC); 3558 if (Offsets.first && 3559 ReadLexicalDeclContextStorage(*Loc.F, DeclsCursor, Offsets.first, DC)) 3560 return nullptr; 3561 if (Offsets.second && 3562 ReadVisibleDeclContextStorage(*Loc.F, DeclsCursor, Offsets.second, ID)) 3563 return nullptr; 3564 } 3565 assert(Record.getIdx() == Record.size()); 3566 3567 // Load any relevant update records. 3568 PendingUpdateRecords.push_back(std::make_pair(ID, D)); 3569 3570 // Load the categories after recursive loading is finished. 3571 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D)) 3572 // If we already have a definition when deserializing the ObjCInterfaceDecl, 3573 // we put the Decl in PendingDefinitions so we can pull the categories here. 3574 if (Class->isThisDeclarationADefinition() || 3575 PendingDefinitions.count(Class)) 3576 loadObjCCategories(ID, Class); 3577 3578 // If we have deserialized a declaration that has a definition the 3579 // AST consumer might need to know about, queue it. 3580 // We don't pass it to the consumer immediately because we may be in recursive 3581 // loading, and some declarations may still be initializing. 3582 if (isConsumerInterestedIn(Context, D, Reader.hasPendingBody())) 3583 InterestingDecls.push_back(D); 3584 3585 return D; 3586 } 3587 3588 void ASTReader::loadDeclUpdateRecords(serialization::DeclID ID, Decl *D) { 3589 // The declaration may have been modified by files later in the chain. 3590 // If this is the case, read the record containing the updates from each file 3591 // and pass it to ASTDeclReader to make the modifications. 3592 ProcessingUpdatesRAIIObj ProcessingUpdates(*this); 3593 DeclUpdateOffsetsMap::iterator UpdI = DeclUpdateOffsets.find(ID); 3594 if (UpdI != DeclUpdateOffsets.end()) { 3595 auto UpdateOffsets = std::move(UpdI->second); 3596 DeclUpdateOffsets.erase(UpdI); 3597 3598 bool WasInteresting = isConsumerInterestedIn(Context, D, false); 3599 for (auto &FileAndOffset : UpdateOffsets) { 3600 ModuleFile *F = FileAndOffset.first; 3601 uint64_t Offset = FileAndOffset.second; 3602 llvm::BitstreamCursor &Cursor = F->DeclsCursor; 3603 SavedStreamPosition SavedPosition(Cursor); 3604 Cursor.JumpToBit(Offset); 3605 unsigned Code = Cursor.ReadCode(); 3606 ASTRecordReader Record(*this, *F); 3607 unsigned RecCode = Record.readRecord(Cursor, Code); 3608 (void)RecCode; 3609 assert(RecCode == DECL_UPDATES && "Expected DECL_UPDATES record!"); 3610 3611 ASTDeclReader Reader(*this, Record, RecordLocation(F, Offset), ID, 3612 SourceLocation()); 3613 Reader.UpdateDecl(D); 3614 3615 // We might have made this declaration interesting. If so, remember that 3616 // we need to hand it off to the consumer. 3617 if (!WasInteresting && 3618 isConsumerInterestedIn(Context, D, Reader.hasPendingBody())) { 3619 InterestingDecls.push_back(D); 3620 WasInteresting = true; 3621 } 3622 } 3623 } 3624 3625 // Load the pending visible updates for this decl context, if it has any. 3626 auto I = PendingVisibleUpdates.find(ID); 3627 if (I != PendingVisibleUpdates.end()) { 3628 auto VisibleUpdates = std::move(I->second); 3629 PendingVisibleUpdates.erase(I); 3630 3631 auto *DC = cast<DeclContext>(D)->getPrimaryContext(); 3632 for (const PendingVisibleUpdate &Update : VisibleUpdates) 3633 Lookups[DC].Table.add( 3634 Update.Mod, Update.Data, 3635 reader::ASTDeclContextNameLookupTrait(*this, *Update.Mod)); 3636 DC->setHasExternalVisibleStorage(true); 3637 } 3638 } 3639 3640 void ASTReader::loadPendingDeclChain(Decl *FirstLocal, uint64_t LocalOffset) { 3641 // Attach FirstLocal to the end of the decl chain. 3642 Decl *CanonDecl = FirstLocal->getCanonicalDecl(); 3643 if (FirstLocal != CanonDecl) { 3644 Decl *PrevMostRecent = ASTDeclReader::getMostRecentDecl(CanonDecl); 3645 ASTDeclReader::attachPreviousDecl( 3646 *this, FirstLocal, PrevMostRecent ? PrevMostRecent : CanonDecl, 3647 CanonDecl); 3648 } 3649 3650 if (!LocalOffset) { 3651 ASTDeclReader::attachLatestDecl(CanonDecl, FirstLocal); 3652 return; 3653 } 3654 3655 // Load the list of other redeclarations from this module file. 3656 ModuleFile *M = getOwningModuleFile(FirstLocal); 3657 assert(M && "imported decl from no module file"); 3658 3659 llvm::BitstreamCursor &Cursor = M->DeclsCursor; 3660 SavedStreamPosition SavedPosition(Cursor); 3661 Cursor.JumpToBit(LocalOffset); 3662 3663 RecordData Record; 3664 unsigned Code = Cursor.ReadCode(); 3665 unsigned RecCode = Cursor.readRecord(Code, Record); 3666 (void)RecCode; 3667 assert(RecCode == LOCAL_REDECLARATIONS && "expected LOCAL_REDECLARATIONS record!"); 3668 3669 // FIXME: We have several different dispatches on decl kind here; maybe 3670 // we should instead generate one loop per kind and dispatch up-front? 3671 Decl *MostRecent = FirstLocal; 3672 for (unsigned I = 0, N = Record.size(); I != N; ++I) { 3673 auto *D = GetLocalDecl(*M, Record[N - I - 1]); 3674 ASTDeclReader::attachPreviousDecl(*this, D, MostRecent, CanonDecl); 3675 MostRecent = D; 3676 } 3677 ASTDeclReader::attachLatestDecl(CanonDecl, MostRecent); 3678 } 3679 3680 namespace { 3681 /// \brief Given an ObjC interface, goes through the modules and links to the 3682 /// interface all the categories for it. 3683 class ObjCCategoriesVisitor { 3684 ASTReader &Reader; 3685 ObjCInterfaceDecl *Interface; 3686 llvm::SmallPtrSetImpl<ObjCCategoryDecl *> &Deserialized; 3687 ObjCCategoryDecl *Tail; 3688 llvm::DenseMap<DeclarationName, ObjCCategoryDecl *> NameCategoryMap; 3689 serialization::GlobalDeclID InterfaceID; 3690 unsigned PreviousGeneration; 3691 3692 void add(ObjCCategoryDecl *Cat) { 3693 // Only process each category once. 3694 if (!Deserialized.erase(Cat)) 3695 return; 3696 3697 // Check for duplicate categories. 3698 if (Cat->getDeclName()) { 3699 ObjCCategoryDecl *&Existing = NameCategoryMap[Cat->getDeclName()]; 3700 if (Existing && 3701 Reader.getOwningModuleFile(Existing) 3702 != Reader.getOwningModuleFile(Cat)) { 3703 // FIXME: We should not warn for duplicates in diamond: 3704 // 3705 // MT // 3706 // / \ // 3707 // ML MR // 3708 // \ / // 3709 // MB // 3710 // 3711 // If there are duplicates in ML/MR, there will be warning when 3712 // creating MB *and* when importing MB. We should not warn when 3713 // importing. 3714 Reader.Diag(Cat->getLocation(), diag::warn_dup_category_def) 3715 << Interface->getDeclName() << Cat->getDeclName(); 3716 Reader.Diag(Existing->getLocation(), diag::note_previous_definition); 3717 } else if (!Existing) { 3718 // Record this category. 3719 Existing = Cat; 3720 } 3721 } 3722 3723 // Add this category to the end of the chain. 3724 if (Tail) 3725 ASTDeclReader::setNextObjCCategory(Tail, Cat); 3726 else 3727 Interface->setCategoryListRaw(Cat); 3728 Tail = Cat; 3729 } 3730 3731 public: 3732 ObjCCategoriesVisitor(ASTReader &Reader, 3733 ObjCInterfaceDecl *Interface, 3734 llvm::SmallPtrSetImpl<ObjCCategoryDecl *> &Deserialized, 3735 serialization::GlobalDeclID InterfaceID, 3736 unsigned PreviousGeneration) 3737 : Reader(Reader), Interface(Interface), Deserialized(Deserialized), 3738 Tail(nullptr), InterfaceID(InterfaceID), 3739 PreviousGeneration(PreviousGeneration) 3740 { 3741 // Populate the name -> category map with the set of known categories. 3742 for (auto *Cat : Interface->known_categories()) { 3743 if (Cat->getDeclName()) 3744 NameCategoryMap[Cat->getDeclName()] = Cat; 3745 3746 // Keep track of the tail of the category list. 3747 Tail = Cat; 3748 } 3749 } 3750 3751 bool operator()(ModuleFile &M) { 3752 // If we've loaded all of the category information we care about from 3753 // this module file, we're done. 3754 if (M.Generation <= PreviousGeneration) 3755 return true; 3756 3757 // Map global ID of the definition down to the local ID used in this 3758 // module file. If there is no such mapping, we'll find nothing here 3759 // (or in any module it imports). 3760 DeclID LocalID = Reader.mapGlobalIDToModuleFileGlobalID(M, InterfaceID); 3761 if (!LocalID) 3762 return true; 3763 3764 // Perform a binary search to find the local redeclarations for this 3765 // declaration (if any). 3766 const ObjCCategoriesInfo Compare = { LocalID, 0 }; 3767 const ObjCCategoriesInfo *Result 3768 = std::lower_bound(M.ObjCCategoriesMap, 3769 M.ObjCCategoriesMap + M.LocalNumObjCCategoriesInMap, 3770 Compare); 3771 if (Result == M.ObjCCategoriesMap + M.LocalNumObjCCategoriesInMap || 3772 Result->DefinitionID != LocalID) { 3773 // We didn't find anything. If the class definition is in this module 3774 // file, then the module files it depends on cannot have any categories, 3775 // so suppress further lookup. 3776 return Reader.isDeclIDFromModule(InterfaceID, M); 3777 } 3778 3779 // We found something. Dig out all of the categories. 3780 unsigned Offset = Result->Offset; 3781 unsigned N = M.ObjCCategories[Offset]; 3782 M.ObjCCategories[Offset++] = 0; // Don't try to deserialize again 3783 for (unsigned I = 0; I != N; ++I) 3784 add(cast_or_null<ObjCCategoryDecl>( 3785 Reader.GetLocalDecl(M, M.ObjCCategories[Offset++]))); 3786 return true; 3787 } 3788 }; 3789 } // end anonymous namespace 3790 3791 void ASTReader::loadObjCCategories(serialization::GlobalDeclID ID, 3792 ObjCInterfaceDecl *D, 3793 unsigned PreviousGeneration) { 3794 ObjCCategoriesVisitor Visitor(*this, D, CategoriesDeserialized, ID, 3795 PreviousGeneration); 3796 ModuleMgr.visit(Visitor); 3797 } 3798 3799 template<typename DeclT, typename Fn> 3800 static void forAllLaterRedecls(DeclT *D, Fn F) { 3801 F(D); 3802 3803 // Check whether we've already merged D into its redeclaration chain. 3804 // MostRecent may or may not be nullptr if D has not been merged. If 3805 // not, walk the merged redecl chain and see if it's there. 3806 auto *MostRecent = D->getMostRecentDecl(); 3807 bool Found = false; 3808 for (auto *Redecl = MostRecent; Redecl && !Found; 3809 Redecl = Redecl->getPreviousDecl()) 3810 Found = (Redecl == D); 3811 3812 // If this declaration is merged, apply the functor to all later decls. 3813 if (Found) { 3814 for (auto *Redecl = MostRecent; Redecl != D; 3815 Redecl = Redecl->getPreviousDecl()) 3816 F(Redecl); 3817 } 3818 } 3819 3820 void ASTDeclReader::UpdateDecl(Decl *D) { 3821 while (Record.getIdx() < Record.size()) { 3822 switch ((DeclUpdateKind)Record.readInt()) { 3823 case UPD_CXX_ADDED_IMPLICIT_MEMBER: { 3824 auto *RD = cast<CXXRecordDecl>(D); 3825 // FIXME: If we also have an update record for instantiating the 3826 // definition of D, we need that to happen before we get here. 3827 Decl *MD = Record.readDecl(); 3828 assert(MD && "couldn't read decl from update record"); 3829 // FIXME: We should call addHiddenDecl instead, to add the member 3830 // to its DeclContext. 3831 RD->addedMember(MD); 3832 break; 3833 } 3834 3835 case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION: 3836 // It will be added to the template's specializations set when loaded. 3837 (void)Record.readDecl(); 3838 break; 3839 3840 case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE: { 3841 NamespaceDecl *Anon = ReadDeclAs<NamespaceDecl>(); 3842 3843 // Each module has its own anonymous namespace, which is disjoint from 3844 // any other module's anonymous namespaces, so don't attach the anonymous 3845 // namespace at all. 3846 if (!Record.isModule()) { 3847 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(D)) 3848 TU->setAnonymousNamespace(Anon); 3849 else 3850 cast<NamespaceDecl>(D)->setAnonymousNamespace(Anon); 3851 } 3852 break; 3853 } 3854 3855 case UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER: 3856 cast<VarDecl>(D)->getMemberSpecializationInfo()->setPointOfInstantiation( 3857 ReadSourceLocation()); 3858 break; 3859 3860 case UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT: { 3861 auto Param = cast<ParmVarDecl>(D); 3862 3863 // We have to read the default argument regardless of whether we use it 3864 // so that hypothetical further update records aren't messed up. 3865 // TODO: Add a function to skip over the next expr record. 3866 auto DefaultArg = Record.readExpr(); 3867 3868 // Only apply the update if the parameter still has an uninstantiated 3869 // default argument. 3870 if (Param->hasUninstantiatedDefaultArg()) 3871 Param->setDefaultArg(DefaultArg); 3872 break; 3873 } 3874 3875 case UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER: { 3876 auto FD = cast<FieldDecl>(D); 3877 auto DefaultInit = Record.readExpr(); 3878 3879 // Only apply the update if the field still has an uninstantiated 3880 // default member initializer. 3881 if (FD->hasInClassInitializer() && !FD->getInClassInitializer()) { 3882 if (DefaultInit) 3883 FD->setInClassInitializer(DefaultInit); 3884 else 3885 // Instantiation failed. We can get here if we serialized an AST for 3886 // an invalid program. 3887 FD->removeInClassInitializer(); 3888 } 3889 break; 3890 } 3891 3892 case UPD_CXX_ADDED_FUNCTION_DEFINITION: { 3893 FunctionDecl *FD = cast<FunctionDecl>(D); 3894 if (Reader.PendingBodies[FD]) { 3895 // FIXME: Maybe check for ODR violations. 3896 // It's safe to stop now because this update record is always last. 3897 return; 3898 } 3899 3900 if (Record.readInt()) { 3901 // Maintain AST consistency: any later redeclarations of this function 3902 // are inline if this one is. (We might have merged another declaration 3903 // into this one.) 3904 forAllLaterRedecls(FD, [](FunctionDecl *FD) { 3905 FD->setImplicitlyInline(); 3906 }); 3907 } 3908 FD->setInnerLocStart(ReadSourceLocation()); 3909 ReadFunctionDefinition(FD); 3910 assert(Record.getIdx() == Record.size() && "lazy body must be last"); 3911 break; 3912 } 3913 3914 case UPD_CXX_INSTANTIATED_CLASS_DEFINITION: { 3915 auto *RD = cast<CXXRecordDecl>(D); 3916 auto *OldDD = RD->getCanonicalDecl()->DefinitionData; 3917 bool HadRealDefinition = 3918 OldDD && (OldDD->Definition != RD || 3919 !Reader.PendingFakeDefinitionData.count(OldDD)); 3920 ReadCXXRecordDefinition(RD, /*Update*/true); 3921 3922 // Visible update is handled separately. 3923 uint64_t LexicalOffset = ReadLocalOffset(); 3924 if (!HadRealDefinition && LexicalOffset) { 3925 Record.readLexicalDeclContextStorage(LexicalOffset, RD); 3926 Reader.PendingFakeDefinitionData.erase(OldDD); 3927 } 3928 3929 auto TSK = (TemplateSpecializationKind)Record.readInt(); 3930 SourceLocation POI = ReadSourceLocation(); 3931 if (MemberSpecializationInfo *MSInfo = 3932 RD->getMemberSpecializationInfo()) { 3933 MSInfo->setTemplateSpecializationKind(TSK); 3934 MSInfo->setPointOfInstantiation(POI); 3935 } else { 3936 ClassTemplateSpecializationDecl *Spec = 3937 cast<ClassTemplateSpecializationDecl>(RD); 3938 Spec->setTemplateSpecializationKind(TSK); 3939 Spec->setPointOfInstantiation(POI); 3940 3941 if (Record.readInt()) { 3942 auto PartialSpec = 3943 ReadDeclAs<ClassTemplatePartialSpecializationDecl>(); 3944 SmallVector<TemplateArgument, 8> TemplArgs; 3945 Record.readTemplateArgumentList(TemplArgs); 3946 auto *TemplArgList = TemplateArgumentList::CreateCopy( 3947 Reader.getContext(), TemplArgs); 3948 3949 // FIXME: If we already have a partial specialization set, 3950 // check that it matches. 3951 if (!Spec->getSpecializedTemplateOrPartial() 3952 .is<ClassTemplatePartialSpecializationDecl *>()) 3953 Spec->setInstantiationOf(PartialSpec, TemplArgList); 3954 } 3955 } 3956 3957 RD->setTagKind((TagTypeKind)Record.readInt()); 3958 RD->setLocation(ReadSourceLocation()); 3959 RD->setLocStart(ReadSourceLocation()); 3960 RD->setBraceRange(ReadSourceRange()); 3961 3962 if (Record.readInt()) { 3963 AttrVec Attrs; 3964 Record.readAttributes(Attrs); 3965 // If the declaration already has attributes, we assume that some other 3966 // AST file already loaded them. 3967 if (!D->hasAttrs()) 3968 D->setAttrsImpl(Attrs, Reader.getContext()); 3969 } 3970 break; 3971 } 3972 3973 case UPD_CXX_RESOLVED_DTOR_DELETE: { 3974 // Set the 'operator delete' directly to avoid emitting another update 3975 // record. 3976 auto *Del = ReadDeclAs<FunctionDecl>(); 3977 auto *First = cast<CXXDestructorDecl>(D->getCanonicalDecl()); 3978 // FIXME: Check consistency if we have an old and new operator delete. 3979 if (!First->OperatorDelete) 3980 First->OperatorDelete = Del; 3981 break; 3982 } 3983 3984 case UPD_CXX_RESOLVED_EXCEPTION_SPEC: { 3985 FunctionProtoType::ExceptionSpecInfo ESI; 3986 SmallVector<QualType, 8> ExceptionStorage; 3987 Record.readExceptionSpec(ExceptionStorage, ESI); 3988 3989 // Update this declaration's exception specification, if needed. 3990 auto *FD = cast<FunctionDecl>(D); 3991 auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 3992 // FIXME: If the exception specification is already present, check that it 3993 // matches. 3994 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { 3995 FD->setType(Reader.Context.getFunctionType( 3996 FPT->getReturnType(), FPT->getParamTypes(), 3997 FPT->getExtProtoInfo().withExceptionSpec(ESI))); 3998 3999 // When we get to the end of deserializing, see if there are other decls 4000 // that we need to propagate this exception specification onto. 4001 Reader.PendingExceptionSpecUpdates.insert( 4002 std::make_pair(FD->getCanonicalDecl(), FD)); 4003 } 4004 break; 4005 } 4006 4007 case UPD_CXX_DEDUCED_RETURN_TYPE: { 4008 // FIXME: Also do this when merging redecls. 4009 QualType DeducedResultType = Record.readType(); 4010 for (auto *Redecl : merged_redecls(D)) { 4011 // FIXME: If the return type is already deduced, check that it matches. 4012 FunctionDecl *FD = cast<FunctionDecl>(Redecl); 4013 Reader.Context.adjustDeducedFunctionResultType(FD, DeducedResultType); 4014 } 4015 break; 4016 } 4017 4018 case UPD_DECL_MARKED_USED: { 4019 // Maintain AST consistency: any later redeclarations are used too. 4020 D->markUsed(Reader.Context); 4021 break; 4022 } 4023 4024 case UPD_MANGLING_NUMBER: 4025 Reader.Context.setManglingNumber(cast<NamedDecl>(D), Record.readInt()); 4026 break; 4027 4028 case UPD_STATIC_LOCAL_NUMBER: 4029 Reader.Context.setStaticLocalNumber(cast<VarDecl>(D), Record.readInt()); 4030 break; 4031 4032 case UPD_DECL_MARKED_OPENMP_THREADPRIVATE: 4033 D->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit( 4034 Reader.Context, ReadSourceRange())); 4035 break; 4036 4037 case UPD_DECL_EXPORTED: { 4038 unsigned SubmoduleID = readSubmoduleID(); 4039 auto *Exported = cast<NamedDecl>(D); 4040 if (auto *TD = dyn_cast<TagDecl>(Exported)) 4041 Exported = TD->getDefinition(); 4042 Module *Owner = SubmoduleID ? Reader.getSubmodule(SubmoduleID) : nullptr; 4043 if (Reader.getContext().getLangOpts().ModulesLocalVisibility) { 4044 Reader.getContext().mergeDefinitionIntoModule(cast<NamedDecl>(Exported), 4045 Owner); 4046 Reader.PendingMergedDefinitionsToDeduplicate.insert( 4047 cast<NamedDecl>(Exported)); 4048 } else if (Owner && Owner->NameVisibility != Module::AllVisible) { 4049 // If Owner is made visible at some later point, make this declaration 4050 // visible too. 4051 Reader.HiddenNamesMap[Owner].push_back(Exported); 4052 } else { 4053 // The declaration is now visible. 4054 Exported->Hidden = false; 4055 } 4056 break; 4057 } 4058 4059 case UPD_DECL_MARKED_OPENMP_DECLARETARGET: 4060 case UPD_ADDED_ATTR_TO_RECORD: 4061 AttrVec Attrs; 4062 Record.readAttributes(Attrs); 4063 assert(Attrs.size() == 1); 4064 D->addAttr(Attrs[0]); 4065 break; 4066 } 4067 } 4068 } 4069