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