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