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