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