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