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