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