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