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