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