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