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