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