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