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