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