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