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