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