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