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