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