Path: blob/main/contrib/llvm-project/clang/lib/Serialization/ASTReaderDecl.cpp
35233 views
//===- ASTReaderDecl.cpp - Decl Deserialization ---------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file implements the ASTReader::readDeclRecord method, which is the9// entrypoint for loading a decl.10//11//===----------------------------------------------------------------------===//1213#include "ASTCommon.h"14#include "ASTReaderInternals.h"15#include "clang/AST/ASTConcept.h"16#include "clang/AST/ASTContext.h"17#include "clang/AST/ASTStructuralEquivalence.h"18#include "clang/AST/Attr.h"19#include "clang/AST/AttrIterator.h"20#include "clang/AST/Decl.h"21#include "clang/AST/DeclBase.h"22#include "clang/AST/DeclCXX.h"23#include "clang/AST/DeclFriend.h"24#include "clang/AST/DeclObjC.h"25#include "clang/AST/DeclOpenMP.h"26#include "clang/AST/DeclTemplate.h"27#include "clang/AST/DeclVisitor.h"28#include "clang/AST/DeclarationName.h"29#include "clang/AST/Expr.h"30#include "clang/AST/ExternalASTSource.h"31#include "clang/AST/LambdaCapture.h"32#include "clang/AST/NestedNameSpecifier.h"33#include "clang/AST/OpenMPClause.h"34#include "clang/AST/Redeclarable.h"35#include "clang/AST/Stmt.h"36#include "clang/AST/TemplateBase.h"37#include "clang/AST/Type.h"38#include "clang/AST/UnresolvedSet.h"39#include "clang/Basic/AttrKinds.h"40#include "clang/Basic/DiagnosticSema.h"41#include "clang/Basic/ExceptionSpecificationType.h"42#include "clang/Basic/IdentifierTable.h"43#include "clang/Basic/LLVM.h"44#include "clang/Basic/Lambda.h"45#include "clang/Basic/LangOptions.h"46#include "clang/Basic/Linkage.h"47#include "clang/Basic/Module.h"48#include "clang/Basic/PragmaKinds.h"49#include "clang/Basic/SourceLocation.h"50#include "clang/Basic/Specifiers.h"51#include "clang/Basic/Stack.h"52#include "clang/Sema/IdentifierResolver.h"53#include "clang/Serialization/ASTBitCodes.h"54#include "clang/Serialization/ASTRecordReader.h"55#include "clang/Serialization/ContinuousRangeMap.h"56#include "clang/Serialization/ModuleFile.h"57#include "llvm/ADT/DenseMap.h"58#include "llvm/ADT/FoldingSet.h"59#include "llvm/ADT/STLExtras.h"60#include "llvm/ADT/SmallPtrSet.h"61#include "llvm/ADT/SmallVector.h"62#include "llvm/ADT/iterator_range.h"63#include "llvm/Bitstream/BitstreamReader.h"64#include "llvm/Support/Casting.h"65#include "llvm/Support/ErrorHandling.h"66#include "llvm/Support/SaveAndRestore.h"67#include <algorithm>68#include <cassert>69#include <cstdint>70#include <cstring>71#include <string>72#include <utility>7374using namespace clang;75using namespace serialization;7677//===----------------------------------------------------------------------===//78// Declaration deserialization79//===----------------------------------------------------------------------===//8081namespace clang {8283class ASTDeclReader : public DeclVisitor<ASTDeclReader, void> {84ASTReader &Reader;85ASTRecordReader &Record;86ASTReader::RecordLocation Loc;87const GlobalDeclID ThisDeclID;88const SourceLocation ThisDeclLoc;8990using RecordData = ASTReader::RecordData;9192TypeID DeferredTypeID = 0;93unsigned AnonymousDeclNumber = 0;94GlobalDeclID NamedDeclForTagDecl = GlobalDeclID();95IdentifierInfo *TypedefNameForLinkage = nullptr;9697///A flag to carry the information for a decl from the entity is98/// used. We use it to delay the marking of the canonical decl as used until99/// the entire declaration is deserialized and merged.100bool IsDeclMarkedUsed = false;101102uint64_t GetCurrentCursorOffset();103104uint64_t ReadLocalOffset() {105uint64_t LocalOffset = Record.readInt();106assert(LocalOffset < Loc.Offset && "offset point after current record");107return LocalOffset ? Loc.Offset - LocalOffset : 0;108}109110uint64_t ReadGlobalOffset() {111uint64_t Local = ReadLocalOffset();112return Local ? Record.getGlobalBitOffset(Local) : 0;113}114115SourceLocation readSourceLocation() {116return Record.readSourceLocation();117}118119SourceRange readSourceRange() {120return Record.readSourceRange();121}122123TypeSourceInfo *readTypeSourceInfo() {124return Record.readTypeSourceInfo();125}126127GlobalDeclID readDeclID() { return Record.readDeclID(); }128129std::string readString() {130return Record.readString();131}132133void readDeclIDList(SmallVectorImpl<GlobalDeclID> &IDs) {134for (unsigned I = 0, Size = Record.readInt(); I != Size; ++I)135IDs.push_back(readDeclID());136}137138Decl *readDecl() {139return Record.readDecl();140}141142template<typename T>143T *readDeclAs() {144return Record.readDeclAs<T>();145}146147serialization::SubmoduleID readSubmoduleID() {148if (Record.getIdx() == Record.size())149return 0;150151return Record.getGlobalSubmoduleID(Record.readInt());152}153154Module *readModule() {155return Record.getSubmodule(readSubmoduleID());156}157158void ReadCXXRecordDefinition(CXXRecordDecl *D, bool Update,159Decl *LambdaContext = nullptr,160unsigned IndexInLambdaContext = 0);161void ReadCXXDefinitionData(struct CXXRecordDecl::DefinitionData &Data,162const CXXRecordDecl *D, Decl *LambdaContext,163unsigned IndexInLambdaContext);164void MergeDefinitionData(CXXRecordDecl *D,165struct CXXRecordDecl::DefinitionData &&NewDD);166void ReadObjCDefinitionData(struct ObjCInterfaceDecl::DefinitionData &Data);167void MergeDefinitionData(ObjCInterfaceDecl *D,168struct ObjCInterfaceDecl::DefinitionData &&NewDD);169void ReadObjCDefinitionData(struct ObjCProtocolDecl::DefinitionData &Data);170void MergeDefinitionData(ObjCProtocolDecl *D,171struct ObjCProtocolDecl::DefinitionData &&NewDD);172173static DeclContext *getPrimaryDCForAnonymousDecl(DeclContext *LexicalDC);174175static NamedDecl *getAnonymousDeclForMerging(ASTReader &Reader,176DeclContext *DC,177unsigned Index);178static void setAnonymousDeclForMerging(ASTReader &Reader, DeclContext *DC,179unsigned Index, NamedDecl *D);180181/// Commit to a primary definition of the class RD, which is known to be182/// a definition of the class. We might not have read the definition data183/// for it yet. If we haven't then allocate placeholder definition data184/// now too.185static CXXRecordDecl *getOrFakePrimaryClassDefinition(ASTReader &Reader,186CXXRecordDecl *RD);187188/// Results from loading a RedeclarableDecl.189class RedeclarableResult {190Decl *MergeWith;191GlobalDeclID FirstID;192bool IsKeyDecl;193194public:195RedeclarableResult(Decl *MergeWith, GlobalDeclID FirstID, bool IsKeyDecl)196: MergeWith(MergeWith), FirstID(FirstID), IsKeyDecl(IsKeyDecl) {}197198/// Retrieve the first ID.199GlobalDeclID getFirstID() const { return FirstID; }200201/// Is this declaration a key declaration?202bool isKeyDecl() const { return IsKeyDecl; }203204/// Get a known declaration that this should be merged with, if205/// any.206Decl *getKnownMergeTarget() const { return MergeWith; }207};208209/// Class used to capture the result of searching for an existing210/// declaration of a specific kind and name, along with the ability211/// to update the place where this result was found (the declaration212/// chain hanging off an identifier or the DeclContext we searched in)213/// if requested.214class FindExistingResult {215ASTReader &Reader;216NamedDecl *New = nullptr;217NamedDecl *Existing = nullptr;218bool AddResult = false;219unsigned AnonymousDeclNumber = 0;220IdentifierInfo *TypedefNameForLinkage = nullptr;221222public:223FindExistingResult(ASTReader &Reader) : Reader(Reader) {}224225FindExistingResult(ASTReader &Reader, NamedDecl *New, NamedDecl *Existing,226unsigned AnonymousDeclNumber,227IdentifierInfo *TypedefNameForLinkage)228: Reader(Reader), New(New), Existing(Existing), AddResult(true),229AnonymousDeclNumber(AnonymousDeclNumber),230TypedefNameForLinkage(TypedefNameForLinkage) {}231232FindExistingResult(FindExistingResult &&Other)233: Reader(Other.Reader), New(Other.New), Existing(Other.Existing),234AddResult(Other.AddResult),235AnonymousDeclNumber(Other.AnonymousDeclNumber),236TypedefNameForLinkage(Other.TypedefNameForLinkage) {237Other.AddResult = false;238}239240FindExistingResult &operator=(FindExistingResult &&) = delete;241~FindExistingResult();242243/// Suppress the addition of this result into the known set of244/// names.245void suppress() { AddResult = false; }246247operator NamedDecl*() const { return Existing; }248249template<typename T>250operator T*() const { return dyn_cast_or_null<T>(Existing); }251};252253static DeclContext *getPrimaryContextForMerging(ASTReader &Reader,254DeclContext *DC);255FindExistingResult findExisting(NamedDecl *D);256257public:258ASTDeclReader(ASTReader &Reader, ASTRecordReader &Record,259ASTReader::RecordLocation Loc, GlobalDeclID thisDeclID,260SourceLocation ThisDeclLoc)261: Reader(Reader), Record(Record), Loc(Loc), ThisDeclID(thisDeclID),262ThisDeclLoc(ThisDeclLoc) {}263264template <typename T>265static void AddLazySpecializations(T *D,266SmallVectorImpl<GlobalDeclID> &IDs) {267if (IDs.empty())268return;269270// FIXME: We should avoid this pattern of getting the ASTContext.271ASTContext &C = D->getASTContext();272273auto *&LazySpecializations = D->getCommonPtr()->LazySpecializations;274275if (auto &Old = LazySpecializations) {276IDs.insert(IDs.end(), Old + 1, Old + 1 + Old[0].getRawValue());277llvm::sort(IDs);278IDs.erase(std::unique(IDs.begin(), IDs.end()), IDs.end());279}280281auto *Result = new (C) GlobalDeclID[1 + IDs.size()];282*Result = GlobalDeclID(IDs.size());283284std::copy(IDs.begin(), IDs.end(), Result + 1);285286LazySpecializations = Result;287}288289template <typename DeclT>290static Decl *getMostRecentDeclImpl(Redeclarable<DeclT> *D);291static Decl *getMostRecentDeclImpl(...);292static Decl *getMostRecentDecl(Decl *D);293294static void mergeInheritableAttributes(ASTReader &Reader, Decl *D,295Decl *Previous);296297template <typename DeclT>298static void attachPreviousDeclImpl(ASTReader &Reader,299Redeclarable<DeclT> *D, Decl *Previous,300Decl *Canon);301static void attachPreviousDeclImpl(ASTReader &Reader, ...);302static void attachPreviousDecl(ASTReader &Reader, Decl *D, Decl *Previous,303Decl *Canon);304305template <typename DeclT>306static void attachLatestDeclImpl(Redeclarable<DeclT> *D, Decl *Latest);307static void attachLatestDeclImpl(...);308static void attachLatestDecl(Decl *D, Decl *latest);309310template <typename DeclT>311static void markIncompleteDeclChainImpl(Redeclarable<DeclT> *D);312static void markIncompleteDeclChainImpl(...);313314void ReadFunctionDefinition(FunctionDecl *FD);315void Visit(Decl *D);316317void UpdateDecl(Decl *D, SmallVectorImpl<GlobalDeclID> &);318319static void setNextObjCCategory(ObjCCategoryDecl *Cat,320ObjCCategoryDecl *Next) {321Cat->NextClassCategory = Next;322}323324void VisitDecl(Decl *D);325void VisitPragmaCommentDecl(PragmaCommentDecl *D);326void VisitPragmaDetectMismatchDecl(PragmaDetectMismatchDecl *D);327void VisitTranslationUnitDecl(TranslationUnitDecl *TU);328void VisitNamedDecl(NamedDecl *ND);329void VisitLabelDecl(LabelDecl *LD);330void VisitNamespaceDecl(NamespaceDecl *D);331void VisitHLSLBufferDecl(HLSLBufferDecl *D);332void VisitUsingDirectiveDecl(UsingDirectiveDecl *D);333void VisitNamespaceAliasDecl(NamespaceAliasDecl *D);334void VisitTypeDecl(TypeDecl *TD);335RedeclarableResult VisitTypedefNameDecl(TypedefNameDecl *TD);336void VisitTypedefDecl(TypedefDecl *TD);337void VisitTypeAliasDecl(TypeAliasDecl *TD);338void VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);339void VisitUnresolvedUsingIfExistsDecl(UnresolvedUsingIfExistsDecl *D);340RedeclarableResult VisitTagDecl(TagDecl *TD);341void VisitEnumDecl(EnumDecl *ED);342RedeclarableResult VisitRecordDeclImpl(RecordDecl *RD);343void VisitRecordDecl(RecordDecl *RD);344RedeclarableResult VisitCXXRecordDeclImpl(CXXRecordDecl *D);345void VisitCXXRecordDecl(CXXRecordDecl *D) { VisitCXXRecordDeclImpl(D); }346RedeclarableResult VisitClassTemplateSpecializationDeclImpl(347ClassTemplateSpecializationDecl *D);348349void VisitClassTemplateSpecializationDecl(350ClassTemplateSpecializationDecl *D) {351VisitClassTemplateSpecializationDeclImpl(D);352}353354void VisitClassTemplatePartialSpecializationDecl(355ClassTemplatePartialSpecializationDecl *D);356RedeclarableResult357VisitVarTemplateSpecializationDeclImpl(VarTemplateSpecializationDecl *D);358359void VisitVarTemplateSpecializationDecl(VarTemplateSpecializationDecl *D) {360VisitVarTemplateSpecializationDeclImpl(D);361}362363void VisitVarTemplatePartialSpecializationDecl(364VarTemplatePartialSpecializationDecl *D);365void VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);366void VisitValueDecl(ValueDecl *VD);367void VisitEnumConstantDecl(EnumConstantDecl *ECD);368void VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);369void VisitDeclaratorDecl(DeclaratorDecl *DD);370void VisitFunctionDecl(FunctionDecl *FD);371void VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *GD);372void VisitCXXMethodDecl(CXXMethodDecl *D);373void VisitCXXConstructorDecl(CXXConstructorDecl *D);374void VisitCXXDestructorDecl(CXXDestructorDecl *D);375void VisitCXXConversionDecl(CXXConversionDecl *D);376void VisitFieldDecl(FieldDecl *FD);377void VisitMSPropertyDecl(MSPropertyDecl *FD);378void VisitMSGuidDecl(MSGuidDecl *D);379void VisitUnnamedGlobalConstantDecl(UnnamedGlobalConstantDecl *D);380void VisitTemplateParamObjectDecl(TemplateParamObjectDecl *D);381void VisitIndirectFieldDecl(IndirectFieldDecl *FD);382RedeclarableResult VisitVarDeclImpl(VarDecl *D);383void ReadVarDeclInit(VarDecl *VD);384void VisitVarDecl(VarDecl *VD) { VisitVarDeclImpl(VD); }385void VisitImplicitParamDecl(ImplicitParamDecl *PD);386void VisitParmVarDecl(ParmVarDecl *PD);387void VisitDecompositionDecl(DecompositionDecl *DD);388void VisitBindingDecl(BindingDecl *BD);389void VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);390void VisitTemplateDecl(TemplateDecl *D);391void VisitConceptDecl(ConceptDecl *D);392void VisitImplicitConceptSpecializationDecl(393ImplicitConceptSpecializationDecl *D);394void VisitRequiresExprBodyDecl(RequiresExprBodyDecl *D);395RedeclarableResult VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D);396void VisitClassTemplateDecl(ClassTemplateDecl *D);397void VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D);398void VisitVarTemplateDecl(VarTemplateDecl *D);399void VisitFunctionTemplateDecl(FunctionTemplateDecl *D);400void VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);401void VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D);402void VisitUsingDecl(UsingDecl *D);403void VisitUsingEnumDecl(UsingEnumDecl *D);404void VisitUsingPackDecl(UsingPackDecl *D);405void VisitUsingShadowDecl(UsingShadowDecl *D);406void VisitConstructorUsingShadowDecl(ConstructorUsingShadowDecl *D);407void VisitLinkageSpecDecl(LinkageSpecDecl *D);408void VisitExportDecl(ExportDecl *D);409void VisitFileScopeAsmDecl(FileScopeAsmDecl *AD);410void VisitTopLevelStmtDecl(TopLevelStmtDecl *D);411void VisitImportDecl(ImportDecl *D);412void VisitAccessSpecDecl(AccessSpecDecl *D);413void VisitFriendDecl(FriendDecl *D);414void VisitFriendTemplateDecl(FriendTemplateDecl *D);415void VisitStaticAssertDecl(StaticAssertDecl *D);416void VisitBlockDecl(BlockDecl *BD);417void VisitCapturedDecl(CapturedDecl *CD);418void VisitEmptyDecl(EmptyDecl *D);419void VisitLifetimeExtendedTemporaryDecl(LifetimeExtendedTemporaryDecl *D);420421std::pair<uint64_t, uint64_t> VisitDeclContext(DeclContext *DC);422423template<typename T>424RedeclarableResult VisitRedeclarable(Redeclarable<T> *D);425426template <typename T>427void mergeRedeclarable(Redeclarable<T> *D, RedeclarableResult &Redecl);428429void mergeLambda(CXXRecordDecl *D, RedeclarableResult &Redecl,430Decl *Context, unsigned Number);431432void mergeRedeclarableTemplate(RedeclarableTemplateDecl *D,433RedeclarableResult &Redecl);434435template <typename T>436void mergeRedeclarable(Redeclarable<T> *D, T *Existing,437RedeclarableResult &Redecl);438439template<typename T>440void mergeMergeable(Mergeable<T> *D);441442void mergeMergeable(LifetimeExtendedTemporaryDecl *D);443444void mergeTemplatePattern(RedeclarableTemplateDecl *D,445RedeclarableTemplateDecl *Existing,446bool IsKeyDecl);447448ObjCTypeParamList *ReadObjCTypeParamList();449450// FIXME: Reorder according to DeclNodes.td?451void VisitObjCMethodDecl(ObjCMethodDecl *D);452void VisitObjCTypeParamDecl(ObjCTypeParamDecl *D);453void VisitObjCContainerDecl(ObjCContainerDecl *D);454void VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);455void VisitObjCIvarDecl(ObjCIvarDecl *D);456void VisitObjCProtocolDecl(ObjCProtocolDecl *D);457void VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D);458void VisitObjCCategoryDecl(ObjCCategoryDecl *D);459void VisitObjCImplDecl(ObjCImplDecl *D);460void VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);461void VisitObjCImplementationDecl(ObjCImplementationDecl *D);462void VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *D);463void VisitObjCPropertyDecl(ObjCPropertyDecl *D);464void VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D);465void VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D);466void VisitOMPAllocateDecl(OMPAllocateDecl *D);467void VisitOMPDeclareReductionDecl(OMPDeclareReductionDecl *D);468void VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D);469void VisitOMPRequiresDecl(OMPRequiresDecl *D);470void VisitOMPCapturedExprDecl(OMPCapturedExprDecl *D);471};472473} // namespace clang474475namespace {476477/// Iterator over the redeclarations of a declaration that have already478/// been merged into the same redeclaration chain.479template <typename DeclT> class MergedRedeclIterator {480DeclT *Start = nullptr;481DeclT *Canonical = nullptr;482DeclT *Current = nullptr;483484public:485MergedRedeclIterator() = default;486MergedRedeclIterator(DeclT *Start) : Start(Start), Current(Start) {}487488DeclT *operator*() { return Current; }489490MergedRedeclIterator &operator++() {491if (Current->isFirstDecl()) {492Canonical = Current;493Current = Current->getMostRecentDecl();494} else495Current = Current->getPreviousDecl();496497// If we started in the merged portion, we'll reach our start position498// eventually. Otherwise, we'll never reach it, but the second declaration499// we reached was the canonical declaration, so stop when we see that one500// again.501if (Current == Start || Current == Canonical)502Current = nullptr;503return *this;504}505506friend bool operator!=(const MergedRedeclIterator &A,507const MergedRedeclIterator &B) {508return A.Current != B.Current;509}510};511512} // namespace513514template <typename DeclT>515static llvm::iterator_range<MergedRedeclIterator<DeclT>>516merged_redecls(DeclT *D) {517return llvm::make_range(MergedRedeclIterator<DeclT>(D),518MergedRedeclIterator<DeclT>());519}520521uint64_t ASTDeclReader::GetCurrentCursorOffset() {522return Loc.F->DeclsCursor.GetCurrentBitNo() + Loc.F->GlobalBitOffset;523}524525void ASTDeclReader::ReadFunctionDefinition(FunctionDecl *FD) {526if (Record.readInt()) {527Reader.DefinitionSource[FD] =528Loc.F->Kind == ModuleKind::MK_MainFile ||529Reader.getContext().getLangOpts().BuildingPCHWithObjectFile;530}531if (auto *CD = dyn_cast<CXXConstructorDecl>(FD)) {532CD->setNumCtorInitializers(Record.readInt());533if (CD->getNumCtorInitializers())534CD->CtorInitializers = ReadGlobalOffset();535}536// Store the offset of the body so we can lazily load it later.537Reader.PendingBodies[FD] = GetCurrentCursorOffset();538}539540void ASTDeclReader::Visit(Decl *D) {541DeclVisitor<ASTDeclReader, void>::Visit(D);542543// At this point we have deserialized and merged the decl and it is safe to544// update its canonical decl to signal that the entire entity is used.545D->getCanonicalDecl()->Used |= IsDeclMarkedUsed;546IsDeclMarkedUsed = false;547548if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {549if (auto *TInfo = DD->getTypeSourceInfo())550Record.readTypeLoc(TInfo->getTypeLoc());551}552553if (auto *TD = dyn_cast<TypeDecl>(D)) {554// We have a fully initialized TypeDecl. Read its type now.555TD->setTypeForDecl(Reader.GetType(DeferredTypeID).getTypePtrOrNull());556557// If this is a tag declaration with a typedef name for linkage, it's safe558// to load that typedef now.559if (NamedDeclForTagDecl.isValid())560cast<TagDecl>(D)->TypedefNameDeclOrQualifier =561cast<TypedefNameDecl>(Reader.GetDecl(NamedDeclForTagDecl));562} else if (auto *ID = dyn_cast<ObjCInterfaceDecl>(D)) {563// if we have a fully initialized TypeDecl, we can safely read its type now.564ID->TypeForDecl = Reader.GetType(DeferredTypeID).getTypePtrOrNull();565} else if (auto *FD = dyn_cast<FunctionDecl>(D)) {566// FunctionDecl's body was written last after all other Stmts/Exprs.567if (Record.readInt())568ReadFunctionDefinition(FD);569} else if (auto *VD = dyn_cast<VarDecl>(D)) {570ReadVarDeclInit(VD);571} else if (auto *FD = dyn_cast<FieldDecl>(D)) {572if (FD->hasInClassInitializer() && Record.readInt()) {573FD->setLazyInClassInitializer(LazyDeclStmtPtr(GetCurrentCursorOffset()));574}575}576}577578void ASTDeclReader::VisitDecl(Decl *D) {579BitsUnpacker DeclBits(Record.readInt());580auto ModuleOwnership =581(Decl::ModuleOwnershipKind)DeclBits.getNextBits(/*Width=*/3);582D->setReferenced(DeclBits.getNextBit());583D->Used = DeclBits.getNextBit();584IsDeclMarkedUsed |= D->Used;585D->setAccess((AccessSpecifier)DeclBits.getNextBits(/*Width=*/2));586D->setImplicit(DeclBits.getNextBit());587bool HasStandaloneLexicalDC = DeclBits.getNextBit();588bool HasAttrs = DeclBits.getNextBit();589D->setTopLevelDeclInObjCContainer(DeclBits.getNextBit());590D->InvalidDecl = DeclBits.getNextBit();591D->FromASTFile = true;592593if (D->isTemplateParameter() || D->isTemplateParameterPack() ||594isa<ParmVarDecl, ObjCTypeParamDecl>(D)) {595// We don't want to deserialize the DeclContext of a template596// parameter or of a parameter of a function template immediately. These597// entities might be used in the formulation of its DeclContext (for598// example, a function parameter can be used in decltype() in trailing599// return type of the function). Use the translation unit DeclContext as a600// placeholder.601GlobalDeclID SemaDCIDForTemplateParmDecl = readDeclID();602GlobalDeclID LexicalDCIDForTemplateParmDecl =603HasStandaloneLexicalDC ? readDeclID() : GlobalDeclID();604if (LexicalDCIDForTemplateParmDecl.isInvalid())605LexicalDCIDForTemplateParmDecl = SemaDCIDForTemplateParmDecl;606Reader.addPendingDeclContextInfo(D,607SemaDCIDForTemplateParmDecl,608LexicalDCIDForTemplateParmDecl);609D->setDeclContext(Reader.getContext().getTranslationUnitDecl());610} else {611auto *SemaDC = readDeclAs<DeclContext>();612auto *LexicalDC =613HasStandaloneLexicalDC ? readDeclAs<DeclContext>() : nullptr;614if (!LexicalDC)615LexicalDC = SemaDC;616// If the context is a class, we might not have actually merged it yet, in617// the case where the definition comes from an update record.618DeclContext *MergedSemaDC;619if (auto *RD = dyn_cast<CXXRecordDecl>(SemaDC))620MergedSemaDC = getOrFakePrimaryClassDefinition(Reader, RD);621else622MergedSemaDC = Reader.MergedDeclContexts.lookup(SemaDC);623// Avoid calling setLexicalDeclContext() directly because it uses624// Decl::getASTContext() internally which is unsafe during derialization.625D->setDeclContextsImpl(MergedSemaDC ? MergedSemaDC : SemaDC, LexicalDC,626Reader.getContext());627}628D->setLocation(ThisDeclLoc);629630if (HasAttrs) {631AttrVec Attrs;632Record.readAttributes(Attrs);633// Avoid calling setAttrs() directly because it uses Decl::getASTContext()634// internally which is unsafe during derialization.635D->setAttrsImpl(Attrs, Reader.getContext());636}637638// Determine whether this declaration is part of a (sub)module. If so, it639// may not yet be visible.640bool ModulePrivate =641(ModuleOwnership == Decl::ModuleOwnershipKind::ModulePrivate);642if (unsigned SubmoduleID = readSubmoduleID()) {643switch (ModuleOwnership) {644case Decl::ModuleOwnershipKind::Visible:645ModuleOwnership = Decl::ModuleOwnershipKind::VisibleWhenImported;646break;647case Decl::ModuleOwnershipKind::Unowned:648case Decl::ModuleOwnershipKind::VisibleWhenImported:649case Decl::ModuleOwnershipKind::ReachableWhenImported:650case Decl::ModuleOwnershipKind::ModulePrivate:651break;652}653654D->setModuleOwnershipKind(ModuleOwnership);655// Store the owning submodule ID in the declaration.656D->setOwningModuleID(SubmoduleID);657658if (ModulePrivate) {659// Module-private declarations are never visible, so there is no work to660// do.661} else if (Reader.getContext().getLangOpts().ModulesLocalVisibility) {662// If local visibility is being tracked, this declaration will become663// hidden and visible as the owning module does.664} else if (Module *Owner = Reader.getSubmodule(SubmoduleID)) {665// Mark the declaration as visible when its owning module becomes visible.666if (Owner->NameVisibility == Module::AllVisible)667D->setVisibleDespiteOwningModule();668else669Reader.HiddenNamesMap[Owner].push_back(D);670}671} else if (ModulePrivate) {672D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate);673}674}675676void ASTDeclReader::VisitPragmaCommentDecl(PragmaCommentDecl *D) {677VisitDecl(D);678D->setLocation(readSourceLocation());679D->CommentKind = (PragmaMSCommentKind)Record.readInt();680std::string Arg = readString();681memcpy(D->getTrailingObjects<char>(), Arg.data(), Arg.size());682D->getTrailingObjects<char>()[Arg.size()] = '\0';683}684685void ASTDeclReader::VisitPragmaDetectMismatchDecl(PragmaDetectMismatchDecl *D) {686VisitDecl(D);687D->setLocation(readSourceLocation());688std::string Name = readString();689memcpy(D->getTrailingObjects<char>(), Name.data(), Name.size());690D->getTrailingObjects<char>()[Name.size()] = '\0';691692D->ValueStart = Name.size() + 1;693std::string Value = readString();694memcpy(D->getTrailingObjects<char>() + D->ValueStart, Value.data(),695Value.size());696D->getTrailingObjects<char>()[D->ValueStart + Value.size()] = '\0';697}698699void ASTDeclReader::VisitTranslationUnitDecl(TranslationUnitDecl *TU) {700llvm_unreachable("Translation units are not serialized");701}702703void ASTDeclReader::VisitNamedDecl(NamedDecl *ND) {704VisitDecl(ND);705ND->setDeclName(Record.readDeclarationName());706AnonymousDeclNumber = Record.readInt();707}708709void ASTDeclReader::VisitTypeDecl(TypeDecl *TD) {710VisitNamedDecl(TD);711TD->setLocStart(readSourceLocation());712// Delay type reading until after we have fully initialized the decl.713DeferredTypeID = Record.getGlobalTypeID(Record.readInt());714}715716ASTDeclReader::RedeclarableResult717ASTDeclReader::VisitTypedefNameDecl(TypedefNameDecl *TD) {718RedeclarableResult Redecl = VisitRedeclarable(TD);719VisitTypeDecl(TD);720TypeSourceInfo *TInfo = readTypeSourceInfo();721if (Record.readInt()) { // isModed722QualType modedT = Record.readType();723TD->setModedTypeSourceInfo(TInfo, modedT);724} else725TD->setTypeSourceInfo(TInfo);726// Read and discard the declaration for which this is a typedef name for727// linkage, if it exists. We cannot rely on our type to pull in this decl,728// because it might have been merged with a type from another module and729// thus might not refer to our version of the declaration.730readDecl();731return Redecl;732}733734void ASTDeclReader::VisitTypedefDecl(TypedefDecl *TD) {735RedeclarableResult Redecl = VisitTypedefNameDecl(TD);736mergeRedeclarable(TD, Redecl);737}738739void ASTDeclReader::VisitTypeAliasDecl(TypeAliasDecl *TD) {740RedeclarableResult Redecl = VisitTypedefNameDecl(TD);741if (auto *Template = readDeclAs<TypeAliasTemplateDecl>())742// Merged when we merge the template.743TD->setDescribedAliasTemplate(Template);744else745mergeRedeclarable(TD, Redecl);746}747748ASTDeclReader::RedeclarableResult ASTDeclReader::VisitTagDecl(TagDecl *TD) {749RedeclarableResult Redecl = VisitRedeclarable(TD);750VisitTypeDecl(TD);751752TD->IdentifierNamespace = Record.readInt();753754BitsUnpacker TagDeclBits(Record.readInt());755TD->setTagKind(756static_cast<TagTypeKind>(TagDeclBits.getNextBits(/*Width=*/3)));757TD->setCompleteDefinition(TagDeclBits.getNextBit());758TD->setEmbeddedInDeclarator(TagDeclBits.getNextBit());759TD->setFreeStanding(TagDeclBits.getNextBit());760TD->setCompleteDefinitionRequired(TagDeclBits.getNextBit());761TD->setBraceRange(readSourceRange());762763switch (TagDeclBits.getNextBits(/*Width=*/2)) {764case 0:765break;766case 1: { // ExtInfo767auto *Info = new (Reader.getContext()) TagDecl::ExtInfo();768Record.readQualifierInfo(*Info);769TD->TypedefNameDeclOrQualifier = Info;770break;771}772case 2: // TypedefNameForAnonDecl773NamedDeclForTagDecl = readDeclID();774TypedefNameForLinkage = Record.readIdentifier();775break;776default:777llvm_unreachable("unexpected tag info kind");778}779780if (!isa<CXXRecordDecl>(TD))781mergeRedeclarable(TD, Redecl);782return Redecl;783}784785void ASTDeclReader::VisitEnumDecl(EnumDecl *ED) {786VisitTagDecl(ED);787if (TypeSourceInfo *TI = readTypeSourceInfo())788ED->setIntegerTypeSourceInfo(TI);789else790ED->setIntegerType(Record.readType());791ED->setPromotionType(Record.readType());792793BitsUnpacker EnumDeclBits(Record.readInt());794ED->setNumPositiveBits(EnumDeclBits.getNextBits(/*Width=*/8));795ED->setNumNegativeBits(EnumDeclBits.getNextBits(/*Width=*/8));796ED->setScoped(EnumDeclBits.getNextBit());797ED->setScopedUsingClassTag(EnumDeclBits.getNextBit());798ED->setFixed(EnumDeclBits.getNextBit());799800ED->setHasODRHash(true);801ED->ODRHash = Record.readInt();802803// If this is a definition subject to the ODR, and we already have a804// definition, merge this one into it.805if (ED->isCompleteDefinition() && Reader.getContext().getLangOpts().Modules) {806EnumDecl *&OldDef = Reader.EnumDefinitions[ED->getCanonicalDecl()];807if (!OldDef) {808// This is the first time we've seen an imported definition. Look for a809// local definition before deciding that we are the first definition.810for (auto *D : merged_redecls(ED->getCanonicalDecl())) {811if (!D->isFromASTFile() && D->isCompleteDefinition()) {812OldDef = D;813break;814}815}816}817if (OldDef) {818Reader.MergedDeclContexts.insert(std::make_pair(ED, OldDef));819ED->demoteThisDefinitionToDeclaration();820Reader.mergeDefinitionVisibility(OldDef, ED);821// We don't want to check the ODR hash value for declarations from global822// module fragment.823if (!shouldSkipCheckingODR(ED) && !shouldSkipCheckingODR(OldDef) &&824OldDef->getODRHash() != ED->getODRHash())825Reader.PendingEnumOdrMergeFailures[OldDef].push_back(ED);826} else {827OldDef = ED;828}829}830831if (auto *InstED = readDeclAs<EnumDecl>()) {832auto TSK = (TemplateSpecializationKind)Record.readInt();833SourceLocation POI = readSourceLocation();834ED->setInstantiationOfMemberEnum(Reader.getContext(), InstED, TSK);835ED->getMemberSpecializationInfo()->setPointOfInstantiation(POI);836}837}838839ASTDeclReader::RedeclarableResult840ASTDeclReader::VisitRecordDeclImpl(RecordDecl *RD) {841RedeclarableResult Redecl = VisitTagDecl(RD);842843BitsUnpacker RecordDeclBits(Record.readInt());844RD->setHasFlexibleArrayMember(RecordDeclBits.getNextBit());845RD->setAnonymousStructOrUnion(RecordDeclBits.getNextBit());846RD->setHasObjectMember(RecordDeclBits.getNextBit());847RD->setHasVolatileMember(RecordDeclBits.getNextBit());848RD->setNonTrivialToPrimitiveDefaultInitialize(RecordDeclBits.getNextBit());849RD->setNonTrivialToPrimitiveCopy(RecordDeclBits.getNextBit());850RD->setNonTrivialToPrimitiveDestroy(RecordDeclBits.getNextBit());851RD->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(852RecordDeclBits.getNextBit());853RD->setHasNonTrivialToPrimitiveDestructCUnion(RecordDeclBits.getNextBit());854RD->setHasNonTrivialToPrimitiveCopyCUnion(RecordDeclBits.getNextBit());855RD->setParamDestroyedInCallee(RecordDeclBits.getNextBit());856RD->setArgPassingRestrictions(857(RecordArgPassingKind)RecordDeclBits.getNextBits(/*Width=*/2));858return Redecl;859}860861void ASTDeclReader::VisitRecordDecl(RecordDecl *RD) {862VisitRecordDeclImpl(RD);863RD->setODRHash(Record.readInt());864865// Maintain the invariant of a redeclaration chain containing only866// a single definition.867if (RD->isCompleteDefinition()) {868RecordDecl *Canon = static_cast<RecordDecl *>(RD->getCanonicalDecl());869RecordDecl *&OldDef = Reader.RecordDefinitions[Canon];870if (!OldDef) {871// This is the first time we've seen an imported definition. Look for a872// local definition before deciding that we are the first definition.873for (auto *D : merged_redecls(Canon)) {874if (!D->isFromASTFile() && D->isCompleteDefinition()) {875OldDef = D;876break;877}878}879}880if (OldDef) {881Reader.MergedDeclContexts.insert(std::make_pair(RD, OldDef));882RD->demoteThisDefinitionToDeclaration();883Reader.mergeDefinitionVisibility(OldDef, RD);884if (OldDef->getODRHash() != RD->getODRHash())885Reader.PendingRecordOdrMergeFailures[OldDef].push_back(RD);886} else {887OldDef = RD;888}889}890}891892void ASTDeclReader::VisitValueDecl(ValueDecl *VD) {893VisitNamedDecl(VD);894// For function or variable declarations, defer reading the type in case the895// declaration has a deduced type that references an entity declared within896// the function definition or variable initializer.897if (isa<FunctionDecl, VarDecl>(VD))898DeferredTypeID = Record.getGlobalTypeID(Record.readInt());899else900VD->setType(Record.readType());901}902903void ASTDeclReader::VisitEnumConstantDecl(EnumConstantDecl *ECD) {904VisitValueDecl(ECD);905if (Record.readInt())906ECD->setInitExpr(Record.readExpr());907ECD->setInitVal(Reader.getContext(), Record.readAPSInt());908mergeMergeable(ECD);909}910911void ASTDeclReader::VisitDeclaratorDecl(DeclaratorDecl *DD) {912VisitValueDecl(DD);913DD->setInnerLocStart(readSourceLocation());914if (Record.readInt()) { // hasExtInfo915auto *Info = new (Reader.getContext()) DeclaratorDecl::ExtInfo();916Record.readQualifierInfo(*Info);917Info->TrailingRequiresClause = Record.readExpr();918DD->DeclInfo = Info;919}920QualType TSIType = Record.readType();921DD->setTypeSourceInfo(922TSIType.isNull() ? nullptr923: Reader.getContext().CreateTypeSourceInfo(TSIType));924}925926void ASTDeclReader::VisitFunctionDecl(FunctionDecl *FD) {927RedeclarableResult Redecl = VisitRedeclarable(FD);928929FunctionDecl *Existing = nullptr;930931switch ((FunctionDecl::TemplatedKind)Record.readInt()) {932case FunctionDecl::TK_NonTemplate:933break;934case FunctionDecl::TK_DependentNonTemplate:935FD->setInstantiatedFromDecl(readDeclAs<FunctionDecl>());936break;937case FunctionDecl::TK_FunctionTemplate: {938auto *Template = readDeclAs<FunctionTemplateDecl>();939Template->init(FD);940FD->setDescribedFunctionTemplate(Template);941break;942}943case FunctionDecl::TK_MemberSpecialization: {944auto *InstFD = readDeclAs<FunctionDecl>();945auto TSK = (TemplateSpecializationKind)Record.readInt();946SourceLocation POI = readSourceLocation();947FD->setInstantiationOfMemberFunction(Reader.getContext(), InstFD, TSK);948FD->getMemberSpecializationInfo()->setPointOfInstantiation(POI);949break;950}951case FunctionDecl::TK_FunctionTemplateSpecialization: {952auto *Template = readDeclAs<FunctionTemplateDecl>();953auto TSK = (TemplateSpecializationKind)Record.readInt();954955// Template arguments.956SmallVector<TemplateArgument, 8> TemplArgs;957Record.readTemplateArgumentList(TemplArgs, /*Canonicalize*/ true);958959// Template args as written.960TemplateArgumentListInfo TemplArgsWritten;961bool HasTemplateArgumentsAsWritten = Record.readBool();962if (HasTemplateArgumentsAsWritten)963Record.readTemplateArgumentListInfo(TemplArgsWritten);964965SourceLocation POI = readSourceLocation();966967ASTContext &C = Reader.getContext();968TemplateArgumentList *TemplArgList =969TemplateArgumentList::CreateCopy(C, TemplArgs);970971MemberSpecializationInfo *MSInfo = nullptr;972if (Record.readInt()) {973auto *FD = readDeclAs<FunctionDecl>();974auto TSK = (TemplateSpecializationKind)Record.readInt();975SourceLocation POI = readSourceLocation();976977MSInfo = new (C) MemberSpecializationInfo(FD, TSK);978MSInfo->setPointOfInstantiation(POI);979}980981FunctionTemplateSpecializationInfo *FTInfo =982FunctionTemplateSpecializationInfo::Create(983C, FD, Template, TSK, TemplArgList,984HasTemplateArgumentsAsWritten ? &TemplArgsWritten : nullptr, POI,985MSInfo);986FD->TemplateOrSpecialization = FTInfo;987988if (FD->isCanonicalDecl()) { // if canonical add to template's set.989// The template that contains the specializations set. It's not safe to990// use getCanonicalDecl on Template since it may still be initializing.991auto *CanonTemplate = readDeclAs<FunctionTemplateDecl>();992// Get the InsertPos by FindNodeOrInsertPos() instead of calling993// InsertNode(FTInfo) directly to avoid the getASTContext() call in994// FunctionTemplateSpecializationInfo's Profile().995// We avoid getASTContext because a decl in the parent hierarchy may996// be initializing.997llvm::FoldingSetNodeID ID;998FunctionTemplateSpecializationInfo::Profile(ID, TemplArgs, C);999void *InsertPos = nullptr;1000FunctionTemplateDecl::Common *CommonPtr = CanonTemplate->getCommonPtr();1001FunctionTemplateSpecializationInfo *ExistingInfo =1002CommonPtr->Specializations.FindNodeOrInsertPos(ID, InsertPos);1003if (InsertPos)1004CommonPtr->Specializations.InsertNode(FTInfo, InsertPos);1005else {1006assert(Reader.getContext().getLangOpts().Modules &&1007"already deserialized this template specialization");1008Existing = ExistingInfo->getFunction();1009}1010}1011break;1012}1013case FunctionDecl::TK_DependentFunctionTemplateSpecialization: {1014// Templates.1015UnresolvedSet<8> Candidates;1016unsigned NumCandidates = Record.readInt();1017while (NumCandidates--)1018Candidates.addDecl(readDeclAs<NamedDecl>());10191020// Templates args.1021TemplateArgumentListInfo TemplArgsWritten;1022bool HasTemplateArgumentsAsWritten = Record.readBool();1023if (HasTemplateArgumentsAsWritten)1024Record.readTemplateArgumentListInfo(TemplArgsWritten);10251026FD->setDependentTemplateSpecialization(1027Reader.getContext(), Candidates,1028HasTemplateArgumentsAsWritten ? &TemplArgsWritten : nullptr);1029// These are not merged; we don't need to merge redeclarations of dependent1030// template friends.1031break;1032}1033}10341035VisitDeclaratorDecl(FD);10361037// Attach a type to this function. Use the real type if possible, but fall1038// back to the type as written if it involves a deduced return type.1039if (FD->getTypeSourceInfo() && FD->getTypeSourceInfo()1040->getType()1041->castAs<FunctionType>()1042->getReturnType()1043->getContainedAutoType()) {1044// We'll set up the real type in Visit, once we've finished loading the1045// function.1046FD->setType(FD->getTypeSourceInfo()->getType());1047Reader.PendingDeducedFunctionTypes.push_back({FD, DeferredTypeID});1048} else {1049FD->setType(Reader.GetType(DeferredTypeID));1050}1051DeferredTypeID = 0;10521053FD->DNLoc = Record.readDeclarationNameLoc(FD->getDeclName());1054FD->IdentifierNamespace = Record.readInt();10551056// FunctionDecl's body is handled last at ASTDeclReader::Visit,1057// after everything else is read.1058BitsUnpacker FunctionDeclBits(Record.readInt());10591060FD->setCachedLinkage((Linkage)FunctionDeclBits.getNextBits(/*Width=*/3));1061FD->setStorageClass((StorageClass)FunctionDeclBits.getNextBits(/*Width=*/3));1062FD->setInlineSpecified(FunctionDeclBits.getNextBit());1063FD->setImplicitlyInline(FunctionDeclBits.getNextBit());1064FD->setHasSkippedBody(FunctionDeclBits.getNextBit());1065FD->setVirtualAsWritten(FunctionDeclBits.getNextBit());1066// We defer calling `FunctionDecl::setPure()` here as for methods of1067// `CXXTemplateSpecializationDecl`s, we may not have connected up the1068// definition (which is required for `setPure`).1069const bool Pure = FunctionDeclBits.getNextBit();1070FD->setHasInheritedPrototype(FunctionDeclBits.getNextBit());1071FD->setHasWrittenPrototype(FunctionDeclBits.getNextBit());1072FD->setDeletedAsWritten(FunctionDeclBits.getNextBit());1073FD->setTrivial(FunctionDeclBits.getNextBit());1074FD->setTrivialForCall(FunctionDeclBits.getNextBit());1075FD->setDefaulted(FunctionDeclBits.getNextBit());1076FD->setExplicitlyDefaulted(FunctionDeclBits.getNextBit());1077FD->setIneligibleOrNotSelected(FunctionDeclBits.getNextBit());1078FD->setConstexprKind(1079(ConstexprSpecKind)FunctionDeclBits.getNextBits(/*Width=*/2));1080FD->setHasImplicitReturnZero(FunctionDeclBits.getNextBit());1081FD->setIsMultiVersion(FunctionDeclBits.getNextBit());1082FD->setLateTemplateParsed(FunctionDeclBits.getNextBit());1083FD->setFriendConstraintRefersToEnclosingTemplate(1084FunctionDeclBits.getNextBit());1085FD->setUsesSEHTry(FunctionDeclBits.getNextBit());10861087FD->EndRangeLoc = readSourceLocation();1088if (FD->isExplicitlyDefaulted())1089FD->setDefaultLoc(readSourceLocation());10901091FD->ODRHash = Record.readInt();1092FD->setHasODRHash(true);10931094if (FD->isDefaulted() || FD->isDeletedAsWritten()) {1095// If 'Info' is nonzero, we need to read an DefaultedOrDeletedInfo; if,1096// additionally, the second bit is also set, we also need to read1097// a DeletedMessage for the DefaultedOrDeletedInfo.1098if (auto Info = Record.readInt()) {1099bool HasMessage = Info & 2;1100StringLiteral *DeletedMessage =1101HasMessage ? cast<StringLiteral>(Record.readExpr()) : nullptr;11021103unsigned NumLookups = Record.readInt();1104SmallVector<DeclAccessPair, 8> Lookups;1105for (unsigned I = 0; I != NumLookups; ++I) {1106NamedDecl *ND = Record.readDeclAs<NamedDecl>();1107AccessSpecifier AS = (AccessSpecifier)Record.readInt();1108Lookups.push_back(DeclAccessPair::make(ND, AS));1109}11101111FD->setDefaultedOrDeletedInfo(1112FunctionDecl::DefaultedOrDeletedFunctionInfo::Create(1113Reader.getContext(), Lookups, DeletedMessage));1114}1115}11161117if (Existing)1118mergeRedeclarable(FD, Existing, Redecl);1119else if (auto Kind = FD->getTemplatedKind();1120Kind == FunctionDecl::TK_FunctionTemplate ||1121Kind == FunctionDecl::TK_FunctionTemplateSpecialization) {1122// Function Templates have their FunctionTemplateDecls merged instead of1123// their FunctionDecls.1124auto merge = [this, &Redecl, FD](auto &&F) {1125auto *Existing = cast_or_null<FunctionDecl>(Redecl.getKnownMergeTarget());1126RedeclarableResult NewRedecl(Existing ? F(Existing) : nullptr,1127Redecl.getFirstID(), Redecl.isKeyDecl());1128mergeRedeclarableTemplate(F(FD), NewRedecl);1129};1130if (Kind == FunctionDecl::TK_FunctionTemplate)1131merge(1132[](FunctionDecl *FD) { return FD->getDescribedFunctionTemplate(); });1133else1134merge([](FunctionDecl *FD) {1135return FD->getTemplateSpecializationInfo()->getTemplate();1136});1137} else1138mergeRedeclarable(FD, Redecl);11391140// Defer calling `setPure` until merging above has guaranteed we've set1141// `DefinitionData` (as this will need to access it).1142FD->setIsPureVirtual(Pure);11431144// Read in the parameters.1145unsigned NumParams = Record.readInt();1146SmallVector<ParmVarDecl *, 16> Params;1147Params.reserve(NumParams);1148for (unsigned I = 0; I != NumParams; ++I)1149Params.push_back(readDeclAs<ParmVarDecl>());1150FD->setParams(Reader.getContext(), Params);1151}11521153void ASTDeclReader::VisitObjCMethodDecl(ObjCMethodDecl *MD) {1154VisitNamedDecl(MD);1155if (Record.readInt()) {1156// Load the body on-demand. Most clients won't care, because method1157// definitions rarely show up in headers.1158Reader.PendingBodies[MD] = GetCurrentCursorOffset();1159}1160MD->setSelfDecl(readDeclAs<ImplicitParamDecl>());1161MD->setCmdDecl(readDeclAs<ImplicitParamDecl>());1162MD->setInstanceMethod(Record.readInt());1163MD->setVariadic(Record.readInt());1164MD->setPropertyAccessor(Record.readInt());1165MD->setSynthesizedAccessorStub(Record.readInt());1166MD->setDefined(Record.readInt());1167MD->setOverriding(Record.readInt());1168MD->setHasSkippedBody(Record.readInt());11691170MD->setIsRedeclaration(Record.readInt());1171MD->setHasRedeclaration(Record.readInt());1172if (MD->hasRedeclaration())1173Reader.getContext().setObjCMethodRedeclaration(MD,1174readDeclAs<ObjCMethodDecl>());11751176MD->setDeclImplementation(1177static_cast<ObjCImplementationControl>(Record.readInt()));1178MD->setObjCDeclQualifier((Decl::ObjCDeclQualifier)Record.readInt());1179MD->setRelatedResultType(Record.readInt());1180MD->setReturnType(Record.readType());1181MD->setReturnTypeSourceInfo(readTypeSourceInfo());1182MD->DeclEndLoc = readSourceLocation();1183unsigned NumParams = Record.readInt();1184SmallVector<ParmVarDecl *, 16> Params;1185Params.reserve(NumParams);1186for (unsigned I = 0; I != NumParams; ++I)1187Params.push_back(readDeclAs<ParmVarDecl>());11881189MD->setSelLocsKind((SelectorLocationsKind)Record.readInt());1190unsigned NumStoredSelLocs = Record.readInt();1191SmallVector<SourceLocation, 16> SelLocs;1192SelLocs.reserve(NumStoredSelLocs);1193for (unsigned i = 0; i != NumStoredSelLocs; ++i)1194SelLocs.push_back(readSourceLocation());11951196MD->setParamsAndSelLocs(Reader.getContext(), Params, SelLocs);1197}11981199void ASTDeclReader::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {1200VisitTypedefNameDecl(D);12011202D->Variance = Record.readInt();1203D->Index = Record.readInt();1204D->VarianceLoc = readSourceLocation();1205D->ColonLoc = readSourceLocation();1206}12071208void ASTDeclReader::VisitObjCContainerDecl(ObjCContainerDecl *CD) {1209VisitNamedDecl(CD);1210CD->setAtStartLoc(readSourceLocation());1211CD->setAtEndRange(readSourceRange());1212}12131214ObjCTypeParamList *ASTDeclReader::ReadObjCTypeParamList() {1215unsigned numParams = Record.readInt();1216if (numParams == 0)1217return nullptr;12181219SmallVector<ObjCTypeParamDecl *, 4> typeParams;1220typeParams.reserve(numParams);1221for (unsigned i = 0; i != numParams; ++i) {1222auto *typeParam = readDeclAs<ObjCTypeParamDecl>();1223if (!typeParam)1224return nullptr;12251226typeParams.push_back(typeParam);1227}12281229SourceLocation lAngleLoc = readSourceLocation();1230SourceLocation rAngleLoc = readSourceLocation();12311232return ObjCTypeParamList::create(Reader.getContext(), lAngleLoc,1233typeParams, rAngleLoc);1234}12351236void ASTDeclReader::ReadObjCDefinitionData(1237struct ObjCInterfaceDecl::DefinitionData &Data) {1238// Read the superclass.1239Data.SuperClassTInfo = readTypeSourceInfo();12401241Data.EndLoc = readSourceLocation();1242Data.HasDesignatedInitializers = Record.readInt();1243Data.ODRHash = Record.readInt();1244Data.HasODRHash = true;12451246// Read the directly referenced protocols and their SourceLocations.1247unsigned NumProtocols = Record.readInt();1248SmallVector<ObjCProtocolDecl *, 16> Protocols;1249Protocols.reserve(NumProtocols);1250for (unsigned I = 0; I != NumProtocols; ++I)1251Protocols.push_back(readDeclAs<ObjCProtocolDecl>());1252SmallVector<SourceLocation, 16> ProtoLocs;1253ProtoLocs.reserve(NumProtocols);1254for (unsigned I = 0; I != NumProtocols; ++I)1255ProtoLocs.push_back(readSourceLocation());1256Data.ReferencedProtocols.set(Protocols.data(), NumProtocols, ProtoLocs.data(),1257Reader.getContext());12581259// Read the transitive closure of protocols referenced by this class.1260NumProtocols = Record.readInt();1261Protocols.clear();1262Protocols.reserve(NumProtocols);1263for (unsigned I = 0; I != NumProtocols; ++I)1264Protocols.push_back(readDeclAs<ObjCProtocolDecl>());1265Data.AllReferencedProtocols.set(Protocols.data(), NumProtocols,1266Reader.getContext());1267}12681269void ASTDeclReader::MergeDefinitionData(ObjCInterfaceDecl *D,1270struct ObjCInterfaceDecl::DefinitionData &&NewDD) {1271struct ObjCInterfaceDecl::DefinitionData &DD = D->data();1272if (DD.Definition == NewDD.Definition)1273return;12741275Reader.MergedDeclContexts.insert(1276std::make_pair(NewDD.Definition, DD.Definition));1277Reader.mergeDefinitionVisibility(DD.Definition, NewDD.Definition);12781279if (D->getODRHash() != NewDD.ODRHash)1280Reader.PendingObjCInterfaceOdrMergeFailures[DD.Definition].push_back(1281{NewDD.Definition, &NewDD});1282}12831284void ASTDeclReader::VisitObjCInterfaceDecl(ObjCInterfaceDecl *ID) {1285RedeclarableResult Redecl = VisitRedeclarable(ID);1286VisitObjCContainerDecl(ID);1287DeferredTypeID = Record.getGlobalTypeID(Record.readInt());1288mergeRedeclarable(ID, Redecl);12891290ID->TypeParamList = ReadObjCTypeParamList();1291if (Record.readInt()) {1292// Read the definition.1293ID->allocateDefinitionData();12941295ReadObjCDefinitionData(ID->data());1296ObjCInterfaceDecl *Canon = ID->getCanonicalDecl();1297if (Canon->Data.getPointer()) {1298// If we already have a definition, keep the definition invariant and1299// merge the data.1300MergeDefinitionData(Canon, std::move(ID->data()));1301ID->Data = Canon->Data;1302} else {1303// Set the definition data of the canonical declaration, so other1304// redeclarations will see it.1305ID->getCanonicalDecl()->Data = ID->Data;13061307// We will rebuild this list lazily.1308ID->setIvarList(nullptr);1309}13101311// Note that we have deserialized a definition.1312Reader.PendingDefinitions.insert(ID);13131314// Note that we've loaded this Objective-C class.1315Reader.ObjCClassesLoaded.push_back(ID);1316} else {1317ID->Data = ID->getCanonicalDecl()->Data;1318}1319}13201321void ASTDeclReader::VisitObjCIvarDecl(ObjCIvarDecl *IVD) {1322VisitFieldDecl(IVD);1323IVD->setAccessControl((ObjCIvarDecl::AccessControl)Record.readInt());1324// This field will be built lazily.1325IVD->setNextIvar(nullptr);1326bool synth = Record.readInt();1327IVD->setSynthesize(synth);13281329// Check ivar redeclaration.1330if (IVD->isInvalidDecl())1331return;1332// Don't check ObjCInterfaceDecl as interfaces are named and mismatches can be1333// detected in VisitObjCInterfaceDecl. Here we are looking for redeclarations1334// in extensions.1335if (isa<ObjCInterfaceDecl>(IVD->getDeclContext()))1336return;1337ObjCInterfaceDecl *CanonIntf =1338IVD->getContainingInterface()->getCanonicalDecl();1339IdentifierInfo *II = IVD->getIdentifier();1340ObjCIvarDecl *PrevIvar = CanonIntf->lookupInstanceVariable(II);1341if (PrevIvar && PrevIvar != IVD) {1342auto *ParentExt = dyn_cast<ObjCCategoryDecl>(IVD->getDeclContext());1343auto *PrevParentExt =1344dyn_cast<ObjCCategoryDecl>(PrevIvar->getDeclContext());1345if (ParentExt && PrevParentExt) {1346// Postpone diagnostic as we should merge identical extensions from1347// different modules.1348Reader1349.PendingObjCExtensionIvarRedeclarations[std::make_pair(ParentExt,1350PrevParentExt)]1351.push_back(std::make_pair(IVD, PrevIvar));1352} else if (ParentExt || PrevParentExt) {1353// Duplicate ivars in extension + implementation are never compatible.1354// Compatibility of implementation + implementation should be handled in1355// VisitObjCImplementationDecl.1356Reader.Diag(IVD->getLocation(), diag::err_duplicate_ivar_declaration)1357<< II;1358Reader.Diag(PrevIvar->getLocation(), diag::note_previous_definition);1359}1360}1361}13621363void ASTDeclReader::ReadObjCDefinitionData(1364struct ObjCProtocolDecl::DefinitionData &Data) {1365unsigned NumProtoRefs = Record.readInt();1366SmallVector<ObjCProtocolDecl *, 16> ProtoRefs;1367ProtoRefs.reserve(NumProtoRefs);1368for (unsigned I = 0; I != NumProtoRefs; ++I)1369ProtoRefs.push_back(readDeclAs<ObjCProtocolDecl>());1370SmallVector<SourceLocation, 16> ProtoLocs;1371ProtoLocs.reserve(NumProtoRefs);1372for (unsigned I = 0; I != NumProtoRefs; ++I)1373ProtoLocs.push_back(readSourceLocation());1374Data.ReferencedProtocols.set(ProtoRefs.data(), NumProtoRefs,1375ProtoLocs.data(), Reader.getContext());1376Data.ODRHash = Record.readInt();1377Data.HasODRHash = true;1378}13791380void ASTDeclReader::MergeDefinitionData(1381ObjCProtocolDecl *D, struct ObjCProtocolDecl::DefinitionData &&NewDD) {1382struct ObjCProtocolDecl::DefinitionData &DD = D->data();1383if (DD.Definition == NewDD.Definition)1384return;13851386Reader.MergedDeclContexts.insert(1387std::make_pair(NewDD.Definition, DD.Definition));1388Reader.mergeDefinitionVisibility(DD.Definition, NewDD.Definition);13891390if (D->getODRHash() != NewDD.ODRHash)1391Reader.PendingObjCProtocolOdrMergeFailures[DD.Definition].push_back(1392{NewDD.Definition, &NewDD});1393}13941395void ASTDeclReader::VisitObjCProtocolDecl(ObjCProtocolDecl *PD) {1396RedeclarableResult Redecl = VisitRedeclarable(PD);1397VisitObjCContainerDecl(PD);1398mergeRedeclarable(PD, Redecl);13991400if (Record.readInt()) {1401// Read the definition.1402PD->allocateDefinitionData();14031404ReadObjCDefinitionData(PD->data());14051406ObjCProtocolDecl *Canon = PD->getCanonicalDecl();1407if (Canon->Data.getPointer()) {1408// If we already have a definition, keep the definition invariant and1409// merge the data.1410MergeDefinitionData(Canon, std::move(PD->data()));1411PD->Data = Canon->Data;1412} else {1413// Set the definition data of the canonical declaration, so other1414// redeclarations will see it.1415PD->getCanonicalDecl()->Data = PD->Data;1416}1417// Note that we have deserialized a definition.1418Reader.PendingDefinitions.insert(PD);1419} else {1420PD->Data = PD->getCanonicalDecl()->Data;1421}1422}14231424void ASTDeclReader::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *FD) {1425VisitFieldDecl(FD);1426}14271428void ASTDeclReader::VisitObjCCategoryDecl(ObjCCategoryDecl *CD) {1429VisitObjCContainerDecl(CD);1430CD->setCategoryNameLoc(readSourceLocation());1431CD->setIvarLBraceLoc(readSourceLocation());1432CD->setIvarRBraceLoc(readSourceLocation());14331434// Note that this category has been deserialized. We do this before1435// deserializing the interface declaration, so that it will consider this1436/// category.1437Reader.CategoriesDeserialized.insert(CD);14381439CD->ClassInterface = readDeclAs<ObjCInterfaceDecl>();1440CD->TypeParamList = ReadObjCTypeParamList();1441unsigned NumProtoRefs = Record.readInt();1442SmallVector<ObjCProtocolDecl *, 16> ProtoRefs;1443ProtoRefs.reserve(NumProtoRefs);1444for (unsigned I = 0; I != NumProtoRefs; ++I)1445ProtoRefs.push_back(readDeclAs<ObjCProtocolDecl>());1446SmallVector<SourceLocation, 16> ProtoLocs;1447ProtoLocs.reserve(NumProtoRefs);1448for (unsigned I = 0; I != NumProtoRefs; ++I)1449ProtoLocs.push_back(readSourceLocation());1450CD->setProtocolList(ProtoRefs.data(), NumProtoRefs, ProtoLocs.data(),1451Reader.getContext());14521453// Protocols in the class extension belong to the class.1454if (NumProtoRefs > 0 && CD->ClassInterface && CD->IsClassExtension())1455CD->ClassInterface->mergeClassExtensionProtocolList(1456(ObjCProtocolDecl *const *)ProtoRefs.data(), NumProtoRefs,1457Reader.getContext());1458}14591460void ASTDeclReader::VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *CAD) {1461VisitNamedDecl(CAD);1462CAD->setClassInterface(readDeclAs<ObjCInterfaceDecl>());1463}14641465void ASTDeclReader::VisitObjCPropertyDecl(ObjCPropertyDecl *D) {1466VisitNamedDecl(D);1467D->setAtLoc(readSourceLocation());1468D->setLParenLoc(readSourceLocation());1469QualType T = Record.readType();1470TypeSourceInfo *TSI = readTypeSourceInfo();1471D->setType(T, TSI);1472D->setPropertyAttributes((ObjCPropertyAttribute::Kind)Record.readInt());1473D->setPropertyAttributesAsWritten(1474(ObjCPropertyAttribute::Kind)Record.readInt());1475D->setPropertyImplementation(1476(ObjCPropertyDecl::PropertyControl)Record.readInt());1477DeclarationName GetterName = Record.readDeclarationName();1478SourceLocation GetterLoc = readSourceLocation();1479D->setGetterName(GetterName.getObjCSelector(), GetterLoc);1480DeclarationName SetterName = Record.readDeclarationName();1481SourceLocation SetterLoc = readSourceLocation();1482D->setSetterName(SetterName.getObjCSelector(), SetterLoc);1483D->setGetterMethodDecl(readDeclAs<ObjCMethodDecl>());1484D->setSetterMethodDecl(readDeclAs<ObjCMethodDecl>());1485D->setPropertyIvarDecl(readDeclAs<ObjCIvarDecl>());1486}14871488void ASTDeclReader::VisitObjCImplDecl(ObjCImplDecl *D) {1489VisitObjCContainerDecl(D);1490D->setClassInterface(readDeclAs<ObjCInterfaceDecl>());1491}14921493void ASTDeclReader::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {1494VisitObjCImplDecl(D);1495D->CategoryNameLoc = readSourceLocation();1496}14971498void ASTDeclReader::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {1499VisitObjCImplDecl(D);1500D->setSuperClass(readDeclAs<ObjCInterfaceDecl>());1501D->SuperLoc = readSourceLocation();1502D->setIvarLBraceLoc(readSourceLocation());1503D->setIvarRBraceLoc(readSourceLocation());1504D->setHasNonZeroConstructors(Record.readInt());1505D->setHasDestructors(Record.readInt());1506D->NumIvarInitializers = Record.readInt();1507if (D->NumIvarInitializers)1508D->IvarInitializers = ReadGlobalOffset();1509}15101511void ASTDeclReader::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) {1512VisitDecl(D);1513D->setAtLoc(readSourceLocation());1514D->setPropertyDecl(readDeclAs<ObjCPropertyDecl>());1515D->PropertyIvarDecl = readDeclAs<ObjCIvarDecl>();1516D->IvarLoc = readSourceLocation();1517D->setGetterMethodDecl(readDeclAs<ObjCMethodDecl>());1518D->setSetterMethodDecl(readDeclAs<ObjCMethodDecl>());1519D->setGetterCXXConstructor(Record.readExpr());1520D->setSetterCXXAssignment(Record.readExpr());1521}15221523void ASTDeclReader::VisitFieldDecl(FieldDecl *FD) {1524VisitDeclaratorDecl(FD);1525FD->Mutable = Record.readInt();15261527unsigned Bits = Record.readInt();1528FD->StorageKind = Bits >> 1;1529if (FD->StorageKind == FieldDecl::ISK_CapturedVLAType)1530FD->CapturedVLAType =1531cast<VariableArrayType>(Record.readType().getTypePtr());1532else if (Bits & 1)1533FD->setBitWidth(Record.readExpr());15341535if (!FD->getDeclName()) {1536if (auto *Tmpl = readDeclAs<FieldDecl>())1537Reader.getContext().setInstantiatedFromUnnamedFieldDecl(FD, Tmpl);1538}1539mergeMergeable(FD);1540}15411542void ASTDeclReader::VisitMSPropertyDecl(MSPropertyDecl *PD) {1543VisitDeclaratorDecl(PD);1544PD->GetterId = Record.readIdentifier();1545PD->SetterId = Record.readIdentifier();1546}15471548void ASTDeclReader::VisitMSGuidDecl(MSGuidDecl *D) {1549VisitValueDecl(D);1550D->PartVal.Part1 = Record.readInt();1551D->PartVal.Part2 = Record.readInt();1552D->PartVal.Part3 = Record.readInt();1553for (auto &C : D->PartVal.Part4And5)1554C = Record.readInt();15551556// Add this GUID to the AST context's lookup structure, and merge if needed.1557if (MSGuidDecl *Existing = Reader.getContext().MSGuidDecls.GetOrInsertNode(D))1558Reader.getContext().setPrimaryMergedDecl(D, Existing->getCanonicalDecl());1559}15601561void ASTDeclReader::VisitUnnamedGlobalConstantDecl(1562UnnamedGlobalConstantDecl *D) {1563VisitValueDecl(D);1564D->Value = Record.readAPValue();15651566// Add this to the AST context's lookup structure, and merge if needed.1567if (UnnamedGlobalConstantDecl *Existing =1568Reader.getContext().UnnamedGlobalConstantDecls.GetOrInsertNode(D))1569Reader.getContext().setPrimaryMergedDecl(D, Existing->getCanonicalDecl());1570}15711572void ASTDeclReader::VisitTemplateParamObjectDecl(TemplateParamObjectDecl *D) {1573VisitValueDecl(D);1574D->Value = Record.readAPValue();15751576// Add this template parameter object to the AST context's lookup structure,1577// and merge if needed.1578if (TemplateParamObjectDecl *Existing =1579Reader.getContext().TemplateParamObjectDecls.GetOrInsertNode(D))1580Reader.getContext().setPrimaryMergedDecl(D, Existing->getCanonicalDecl());1581}15821583void ASTDeclReader::VisitIndirectFieldDecl(IndirectFieldDecl *FD) {1584VisitValueDecl(FD);15851586FD->ChainingSize = Record.readInt();1587assert(FD->ChainingSize >= 2 && "Anonymous chaining must be >= 2");1588FD->Chaining = new (Reader.getContext())NamedDecl*[FD->ChainingSize];15891590for (unsigned I = 0; I != FD->ChainingSize; ++I)1591FD->Chaining[I] = readDeclAs<NamedDecl>();15921593mergeMergeable(FD);1594}15951596ASTDeclReader::RedeclarableResult ASTDeclReader::VisitVarDeclImpl(VarDecl *VD) {1597RedeclarableResult Redecl = VisitRedeclarable(VD);1598VisitDeclaratorDecl(VD);15991600BitsUnpacker VarDeclBits(Record.readInt());1601auto VarLinkage = Linkage(VarDeclBits.getNextBits(/*Width=*/3));1602bool DefGeneratedInModule = VarDeclBits.getNextBit();1603VD->VarDeclBits.SClass = (StorageClass)VarDeclBits.getNextBits(/*Width=*/3);1604VD->VarDeclBits.TSCSpec = VarDeclBits.getNextBits(/*Width=*/2);1605VD->VarDeclBits.InitStyle = VarDeclBits.getNextBits(/*Width=*/2);1606VD->VarDeclBits.ARCPseudoStrong = VarDeclBits.getNextBit();1607bool HasDeducedType = false;1608if (!isa<ParmVarDecl>(VD)) {1609VD->NonParmVarDeclBits.IsThisDeclarationADemotedDefinition =1610VarDeclBits.getNextBit();1611VD->NonParmVarDeclBits.ExceptionVar = VarDeclBits.getNextBit();1612VD->NonParmVarDeclBits.NRVOVariable = VarDeclBits.getNextBit();1613VD->NonParmVarDeclBits.CXXForRangeDecl = VarDeclBits.getNextBit();16141615VD->NonParmVarDeclBits.IsInline = VarDeclBits.getNextBit();1616VD->NonParmVarDeclBits.IsInlineSpecified = VarDeclBits.getNextBit();1617VD->NonParmVarDeclBits.IsConstexpr = VarDeclBits.getNextBit();1618VD->NonParmVarDeclBits.IsInitCapture = VarDeclBits.getNextBit();1619VD->NonParmVarDeclBits.PreviousDeclInSameBlockScope =1620VarDeclBits.getNextBit();16211622VD->NonParmVarDeclBits.EscapingByref = VarDeclBits.getNextBit();1623HasDeducedType = VarDeclBits.getNextBit();1624VD->NonParmVarDeclBits.ImplicitParamKind =1625VarDeclBits.getNextBits(/*Width*/ 3);16261627VD->NonParmVarDeclBits.ObjCForDecl = VarDeclBits.getNextBit();1628}16291630// If this variable has a deduced type, defer reading that type until we are1631// done deserializing this variable, because the type might refer back to the1632// variable.1633if (HasDeducedType)1634Reader.PendingDeducedVarTypes.push_back({VD, DeferredTypeID});1635else1636VD->setType(Reader.GetType(DeferredTypeID));1637DeferredTypeID = 0;16381639VD->setCachedLinkage(VarLinkage);16401641// Reconstruct the one piece of the IdentifierNamespace that we need.1642if (VD->getStorageClass() == SC_Extern && VarLinkage != Linkage::None &&1643VD->getLexicalDeclContext()->isFunctionOrMethod())1644VD->setLocalExternDecl();16451646if (DefGeneratedInModule) {1647Reader.DefinitionSource[VD] =1648Loc.F->Kind == ModuleKind::MK_MainFile ||1649Reader.getContext().getLangOpts().BuildingPCHWithObjectFile;1650}16511652if (VD->hasAttr<BlocksAttr>()) {1653Expr *CopyExpr = Record.readExpr();1654if (CopyExpr)1655Reader.getContext().setBlockVarCopyInit(VD, CopyExpr, Record.readInt());1656}16571658enum VarKind {1659VarNotTemplate = 0, VarTemplate, StaticDataMemberSpecialization1660};1661switch ((VarKind)Record.readInt()) {1662case VarNotTemplate:1663// Only true variables (not parameters or implicit parameters) can be1664// merged; the other kinds are not really redeclarable at all.1665if (!isa<ParmVarDecl>(VD) && !isa<ImplicitParamDecl>(VD) &&1666!isa<VarTemplateSpecializationDecl>(VD))1667mergeRedeclarable(VD, Redecl);1668break;1669case VarTemplate:1670// Merged when we merge the template.1671VD->setDescribedVarTemplate(readDeclAs<VarTemplateDecl>());1672break;1673case StaticDataMemberSpecialization: { // HasMemberSpecializationInfo.1674auto *Tmpl = readDeclAs<VarDecl>();1675auto TSK = (TemplateSpecializationKind)Record.readInt();1676SourceLocation POI = readSourceLocation();1677Reader.getContext().setInstantiatedFromStaticDataMember(VD, Tmpl, TSK,POI);1678mergeRedeclarable(VD, Redecl);1679break;1680}1681}16821683return Redecl;1684}16851686void ASTDeclReader::ReadVarDeclInit(VarDecl *VD) {1687if (uint64_t Val = Record.readInt()) {1688EvaluatedStmt *Eval = VD->ensureEvaluatedStmt();1689Eval->HasConstantInitialization = (Val & 2) != 0;1690Eval->HasConstantDestruction = (Val & 4) != 0;1691Eval->WasEvaluated = (Val & 8) != 0;1692if (Eval->WasEvaluated) {1693Eval->Evaluated = Record.readAPValue();1694if (Eval->Evaluated.needsCleanup())1695Reader.getContext().addDestruction(&Eval->Evaluated);1696}16971698// Store the offset of the initializer. Don't deserialize it yet: it might1699// not be needed, and might refer back to the variable, for example if it1700// contains a lambda.1701Eval->Value = GetCurrentCursorOffset();1702}1703}17041705void ASTDeclReader::VisitImplicitParamDecl(ImplicitParamDecl *PD) {1706VisitVarDecl(PD);1707}17081709void ASTDeclReader::VisitParmVarDecl(ParmVarDecl *PD) {1710VisitVarDecl(PD);17111712unsigned scopeIndex = Record.readInt();1713BitsUnpacker ParmVarDeclBits(Record.readInt());1714unsigned isObjCMethodParam = ParmVarDeclBits.getNextBit();1715unsigned scopeDepth = ParmVarDeclBits.getNextBits(/*Width=*/7);1716unsigned declQualifier = ParmVarDeclBits.getNextBits(/*Width=*/7);1717if (isObjCMethodParam) {1718assert(scopeDepth == 0);1719PD->setObjCMethodScopeInfo(scopeIndex);1720PD->ParmVarDeclBits.ScopeDepthOrObjCQuals = declQualifier;1721} else {1722PD->setScopeInfo(scopeDepth, scopeIndex);1723}1724PD->ParmVarDeclBits.IsKNRPromoted = ParmVarDeclBits.getNextBit();17251726PD->ParmVarDeclBits.HasInheritedDefaultArg = ParmVarDeclBits.getNextBit();1727if (ParmVarDeclBits.getNextBit()) // hasUninstantiatedDefaultArg.1728PD->setUninstantiatedDefaultArg(Record.readExpr());17291730if (ParmVarDeclBits.getNextBit()) // Valid explicit object parameter1731PD->ExplicitObjectParameterIntroducerLoc = Record.readSourceLocation();17321733// FIXME: If this is a redeclaration of a function from another module, handle1734// inheritance of default arguments.1735}17361737void ASTDeclReader::VisitDecompositionDecl(DecompositionDecl *DD) {1738VisitVarDecl(DD);1739auto **BDs = DD->getTrailingObjects<BindingDecl *>();1740for (unsigned I = 0; I != DD->NumBindings; ++I) {1741BDs[I] = readDeclAs<BindingDecl>();1742BDs[I]->setDecomposedDecl(DD);1743}1744}17451746void ASTDeclReader::VisitBindingDecl(BindingDecl *BD) {1747VisitValueDecl(BD);1748BD->Binding = Record.readExpr();1749}17501751void ASTDeclReader::VisitFileScopeAsmDecl(FileScopeAsmDecl *AD) {1752VisitDecl(AD);1753AD->setAsmString(cast<StringLiteral>(Record.readExpr()));1754AD->setRParenLoc(readSourceLocation());1755}17561757void ASTDeclReader::VisitTopLevelStmtDecl(TopLevelStmtDecl *D) {1758VisitDecl(D);1759D->Statement = Record.readStmt();1760}17611762void ASTDeclReader::VisitBlockDecl(BlockDecl *BD) {1763VisitDecl(BD);1764BD->setBody(cast_or_null<CompoundStmt>(Record.readStmt()));1765BD->setSignatureAsWritten(readTypeSourceInfo());1766unsigned NumParams = Record.readInt();1767SmallVector<ParmVarDecl *, 16> Params;1768Params.reserve(NumParams);1769for (unsigned I = 0; I != NumParams; ++I)1770Params.push_back(readDeclAs<ParmVarDecl>());1771BD->setParams(Params);17721773BD->setIsVariadic(Record.readInt());1774BD->setBlockMissingReturnType(Record.readInt());1775BD->setIsConversionFromLambda(Record.readInt());1776BD->setDoesNotEscape(Record.readInt());1777BD->setCanAvoidCopyToHeap(Record.readInt());17781779bool capturesCXXThis = Record.readInt();1780unsigned numCaptures = Record.readInt();1781SmallVector<BlockDecl::Capture, 16> captures;1782captures.reserve(numCaptures);1783for (unsigned i = 0; i != numCaptures; ++i) {1784auto *decl = readDeclAs<VarDecl>();1785unsigned flags = Record.readInt();1786bool byRef = (flags & 1);1787bool nested = (flags & 2);1788Expr *copyExpr = ((flags & 4) ? Record.readExpr() : nullptr);17891790captures.push_back(BlockDecl::Capture(decl, byRef, nested, copyExpr));1791}1792BD->setCaptures(Reader.getContext(), captures, capturesCXXThis);1793}17941795void ASTDeclReader::VisitCapturedDecl(CapturedDecl *CD) {1796VisitDecl(CD);1797unsigned ContextParamPos = Record.readInt();1798CD->setNothrow(Record.readInt() != 0);1799// Body is set by VisitCapturedStmt.1800for (unsigned I = 0; I < CD->NumParams; ++I) {1801if (I != ContextParamPos)1802CD->setParam(I, readDeclAs<ImplicitParamDecl>());1803else1804CD->setContextParam(I, readDeclAs<ImplicitParamDecl>());1805}1806}18071808void ASTDeclReader::VisitLinkageSpecDecl(LinkageSpecDecl *D) {1809VisitDecl(D);1810D->setLanguage(static_cast<LinkageSpecLanguageIDs>(Record.readInt()));1811D->setExternLoc(readSourceLocation());1812D->setRBraceLoc(readSourceLocation());1813}18141815void ASTDeclReader::VisitExportDecl(ExportDecl *D) {1816VisitDecl(D);1817D->RBraceLoc = readSourceLocation();1818}18191820void ASTDeclReader::VisitLabelDecl(LabelDecl *D) {1821VisitNamedDecl(D);1822D->setLocStart(readSourceLocation());1823}18241825void ASTDeclReader::VisitNamespaceDecl(NamespaceDecl *D) {1826RedeclarableResult Redecl = VisitRedeclarable(D);1827VisitNamedDecl(D);18281829BitsUnpacker NamespaceDeclBits(Record.readInt());1830D->setInline(NamespaceDeclBits.getNextBit());1831D->setNested(NamespaceDeclBits.getNextBit());1832D->LocStart = readSourceLocation();1833D->RBraceLoc = readSourceLocation();18341835// Defer loading the anonymous namespace until we've finished merging1836// this namespace; loading it might load a later declaration of the1837// same namespace, and we have an invariant that older declarations1838// get merged before newer ones try to merge.1839GlobalDeclID AnonNamespace;1840if (Redecl.getFirstID() == ThisDeclID)1841AnonNamespace = readDeclID();18421843mergeRedeclarable(D, Redecl);18441845if (AnonNamespace.isValid()) {1846// Each module has its own anonymous namespace, which is disjoint from1847// any other module's anonymous namespaces, so don't attach the anonymous1848// namespace at all.1849auto *Anon = cast<NamespaceDecl>(Reader.GetDecl(AnonNamespace));1850if (!Record.isModule())1851D->setAnonymousNamespace(Anon);1852}1853}18541855void ASTDeclReader::VisitHLSLBufferDecl(HLSLBufferDecl *D) {1856VisitNamedDecl(D);1857VisitDeclContext(D);1858D->IsCBuffer = Record.readBool();1859D->KwLoc = readSourceLocation();1860D->LBraceLoc = readSourceLocation();1861D->RBraceLoc = readSourceLocation();1862}18631864void ASTDeclReader::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {1865RedeclarableResult Redecl = VisitRedeclarable(D);1866VisitNamedDecl(D);1867D->NamespaceLoc = readSourceLocation();1868D->IdentLoc = readSourceLocation();1869D->QualifierLoc = Record.readNestedNameSpecifierLoc();1870D->Namespace = readDeclAs<NamedDecl>();1871mergeRedeclarable(D, Redecl);1872}18731874void ASTDeclReader::VisitUsingDecl(UsingDecl *D) {1875VisitNamedDecl(D);1876D->setUsingLoc(readSourceLocation());1877D->QualifierLoc = Record.readNestedNameSpecifierLoc();1878D->DNLoc = Record.readDeclarationNameLoc(D->getDeclName());1879D->FirstUsingShadow.setPointer(readDeclAs<UsingShadowDecl>());1880D->setTypename(Record.readInt());1881if (auto *Pattern = readDeclAs<NamedDecl>())1882Reader.getContext().setInstantiatedFromUsingDecl(D, Pattern);1883mergeMergeable(D);1884}18851886void ASTDeclReader::VisitUsingEnumDecl(UsingEnumDecl *D) {1887VisitNamedDecl(D);1888D->setUsingLoc(readSourceLocation());1889D->setEnumLoc(readSourceLocation());1890D->setEnumType(Record.readTypeSourceInfo());1891D->FirstUsingShadow.setPointer(readDeclAs<UsingShadowDecl>());1892if (auto *Pattern = readDeclAs<UsingEnumDecl>())1893Reader.getContext().setInstantiatedFromUsingEnumDecl(D, Pattern);1894mergeMergeable(D);1895}18961897void ASTDeclReader::VisitUsingPackDecl(UsingPackDecl *D) {1898VisitNamedDecl(D);1899D->InstantiatedFrom = readDeclAs<NamedDecl>();1900auto **Expansions = D->getTrailingObjects<NamedDecl *>();1901for (unsigned I = 0; I != D->NumExpansions; ++I)1902Expansions[I] = readDeclAs<NamedDecl>();1903mergeMergeable(D);1904}19051906void ASTDeclReader::VisitUsingShadowDecl(UsingShadowDecl *D) {1907RedeclarableResult Redecl = VisitRedeclarable(D);1908VisitNamedDecl(D);1909D->Underlying = readDeclAs<NamedDecl>();1910D->IdentifierNamespace = Record.readInt();1911D->UsingOrNextShadow = readDeclAs<NamedDecl>();1912auto *Pattern = readDeclAs<UsingShadowDecl>();1913if (Pattern)1914Reader.getContext().setInstantiatedFromUsingShadowDecl(D, Pattern);1915mergeRedeclarable(D, Redecl);1916}19171918void ASTDeclReader::VisitConstructorUsingShadowDecl(1919ConstructorUsingShadowDecl *D) {1920VisitUsingShadowDecl(D);1921D->NominatedBaseClassShadowDecl = readDeclAs<ConstructorUsingShadowDecl>();1922D->ConstructedBaseClassShadowDecl = readDeclAs<ConstructorUsingShadowDecl>();1923D->IsVirtual = Record.readInt();1924}19251926void ASTDeclReader::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {1927VisitNamedDecl(D);1928D->UsingLoc = readSourceLocation();1929D->NamespaceLoc = readSourceLocation();1930D->QualifierLoc = Record.readNestedNameSpecifierLoc();1931D->NominatedNamespace = readDeclAs<NamedDecl>();1932D->CommonAncestor = readDeclAs<DeclContext>();1933}19341935void ASTDeclReader::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {1936VisitValueDecl(D);1937D->setUsingLoc(readSourceLocation());1938D->QualifierLoc = Record.readNestedNameSpecifierLoc();1939D->DNLoc = Record.readDeclarationNameLoc(D->getDeclName());1940D->EllipsisLoc = readSourceLocation();1941mergeMergeable(D);1942}19431944void ASTDeclReader::VisitUnresolvedUsingTypenameDecl(1945UnresolvedUsingTypenameDecl *D) {1946VisitTypeDecl(D);1947D->TypenameLocation = readSourceLocation();1948D->QualifierLoc = Record.readNestedNameSpecifierLoc();1949D->EllipsisLoc = readSourceLocation();1950mergeMergeable(D);1951}19521953void ASTDeclReader::VisitUnresolvedUsingIfExistsDecl(1954UnresolvedUsingIfExistsDecl *D) {1955VisitNamedDecl(D);1956}19571958void ASTDeclReader::ReadCXXDefinitionData(1959struct CXXRecordDecl::DefinitionData &Data, const CXXRecordDecl *D,1960Decl *LambdaContext, unsigned IndexInLambdaContext) {19611962BitsUnpacker CXXRecordDeclBits = Record.readInt();19631964#define FIELD(Name, Width, Merge) \1965if (!CXXRecordDeclBits.canGetNextNBits(Width)) \1966CXXRecordDeclBits.updateValue(Record.readInt()); \1967Data.Name = CXXRecordDeclBits.getNextBits(Width);19681969#include "clang/AST/CXXRecordDeclDefinitionBits.def"1970#undef FIELD19711972// Note: the caller has deserialized the IsLambda bit already.1973Data.ODRHash = Record.readInt();1974Data.HasODRHash = true;19751976if (Record.readInt()) {1977Reader.DefinitionSource[D] =1978Loc.F->Kind == ModuleKind::MK_MainFile ||1979Reader.getContext().getLangOpts().BuildingPCHWithObjectFile;1980}19811982Record.readUnresolvedSet(Data.Conversions);1983Data.ComputedVisibleConversions = Record.readInt();1984if (Data.ComputedVisibleConversions)1985Record.readUnresolvedSet(Data.VisibleConversions);1986assert(Data.Definition && "Data.Definition should be already set!");19871988if (!Data.IsLambda) {1989assert(!LambdaContext && !IndexInLambdaContext &&1990"given lambda context for non-lambda");19911992Data.NumBases = Record.readInt();1993if (Data.NumBases)1994Data.Bases = ReadGlobalOffset();19951996Data.NumVBases = Record.readInt();1997if (Data.NumVBases)1998Data.VBases = ReadGlobalOffset();19992000Data.FirstFriend = readDeclID().getRawValue();2001} else {2002using Capture = LambdaCapture;20032004auto &Lambda = static_cast<CXXRecordDecl::LambdaDefinitionData &>(Data);20052006BitsUnpacker LambdaBits(Record.readInt());2007Lambda.DependencyKind = LambdaBits.getNextBits(/*Width=*/2);2008Lambda.IsGenericLambda = LambdaBits.getNextBit();2009Lambda.CaptureDefault = LambdaBits.getNextBits(/*Width=*/2);2010Lambda.NumCaptures = LambdaBits.getNextBits(/*Width=*/15);2011Lambda.HasKnownInternalLinkage = LambdaBits.getNextBit();20122013Lambda.NumExplicitCaptures = Record.readInt();2014Lambda.ManglingNumber = Record.readInt();2015if (unsigned DeviceManglingNumber = Record.readInt())2016Reader.getContext().DeviceLambdaManglingNumbers[D] = DeviceManglingNumber;2017Lambda.IndexInContext = IndexInLambdaContext;2018Lambda.ContextDecl = LambdaContext;2019Capture *ToCapture = nullptr;2020if (Lambda.NumCaptures) {2021ToCapture = (Capture *)Reader.getContext().Allocate(sizeof(Capture) *2022Lambda.NumCaptures);2023Lambda.AddCaptureList(Reader.getContext(), ToCapture);2024}2025Lambda.MethodTyInfo = readTypeSourceInfo();2026for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) {2027SourceLocation Loc = readSourceLocation();2028BitsUnpacker CaptureBits(Record.readInt());2029bool IsImplicit = CaptureBits.getNextBit();2030auto Kind =2031static_cast<LambdaCaptureKind>(CaptureBits.getNextBits(/*Width=*/3));2032switch (Kind) {2033case LCK_StarThis:2034case LCK_This:2035case LCK_VLAType:2036new (ToCapture)2037Capture(Loc, IsImplicit, Kind, nullptr, SourceLocation());2038ToCapture++;2039break;2040case LCK_ByCopy:2041case LCK_ByRef:2042auto *Var = readDeclAs<ValueDecl>();2043SourceLocation EllipsisLoc = readSourceLocation();2044new (ToCapture) Capture(Loc, IsImplicit, Kind, Var, EllipsisLoc);2045ToCapture++;2046break;2047}2048}2049}2050}20512052void ASTDeclReader::MergeDefinitionData(2053CXXRecordDecl *D, struct CXXRecordDecl::DefinitionData &&MergeDD) {2054assert(D->DefinitionData &&2055"merging class definition into non-definition");2056auto &DD = *D->DefinitionData;20572058if (DD.Definition != MergeDD.Definition) {2059// Track that we merged the definitions.2060Reader.MergedDeclContexts.insert(std::make_pair(MergeDD.Definition,2061DD.Definition));2062Reader.PendingDefinitions.erase(MergeDD.Definition);2063MergeDD.Definition->setCompleteDefinition(false);2064Reader.mergeDefinitionVisibility(DD.Definition, MergeDD.Definition);2065assert(!Reader.Lookups.contains(MergeDD.Definition) &&2066"already loaded pending lookups for merged definition");2067}20682069auto PFDI = Reader.PendingFakeDefinitionData.find(&DD);2070if (PFDI != Reader.PendingFakeDefinitionData.end() &&2071PFDI->second == ASTReader::PendingFakeDefinitionKind::Fake) {2072// We faked up this definition data because we found a class for which we'd2073// not yet loaded the definition. Replace it with the real thing now.2074assert(!DD.IsLambda && !MergeDD.IsLambda && "faked up lambda definition?");2075PFDI->second = ASTReader::PendingFakeDefinitionKind::FakeLoaded;20762077// Don't change which declaration is the definition; that is required2078// to be invariant once we select it.2079auto *Def = DD.Definition;2080DD = std::move(MergeDD);2081DD.Definition = Def;2082return;2083}20842085bool DetectedOdrViolation = false;20862087#define FIELD(Name, Width, Merge) Merge(Name)2088#define MERGE_OR(Field) DD.Field |= MergeDD.Field;2089#define NO_MERGE(Field) \2090DetectedOdrViolation |= DD.Field != MergeDD.Field; \2091MERGE_OR(Field)2092#include "clang/AST/CXXRecordDeclDefinitionBits.def"2093NO_MERGE(IsLambda)2094#undef NO_MERGE2095#undef MERGE_OR20962097if (DD.NumBases != MergeDD.NumBases || DD.NumVBases != MergeDD.NumVBases)2098DetectedOdrViolation = true;2099// FIXME: Issue a diagnostic if the base classes don't match when we come2100// to lazily load them.21012102// FIXME: Issue a diagnostic if the list of conversion functions doesn't2103// match when we come to lazily load them.2104if (MergeDD.ComputedVisibleConversions && !DD.ComputedVisibleConversions) {2105DD.VisibleConversions = std::move(MergeDD.VisibleConversions);2106DD.ComputedVisibleConversions = true;2107}21082109// FIXME: Issue a diagnostic if FirstFriend doesn't match when we come to2110// lazily load it.21112112if (DD.IsLambda) {2113auto &Lambda1 = static_cast<CXXRecordDecl::LambdaDefinitionData &>(DD);2114auto &Lambda2 = static_cast<CXXRecordDecl::LambdaDefinitionData &>(MergeDD);2115DetectedOdrViolation |= Lambda1.DependencyKind != Lambda2.DependencyKind;2116DetectedOdrViolation |= Lambda1.IsGenericLambda != Lambda2.IsGenericLambda;2117DetectedOdrViolation |= Lambda1.CaptureDefault != Lambda2.CaptureDefault;2118DetectedOdrViolation |= Lambda1.NumCaptures != Lambda2.NumCaptures;2119DetectedOdrViolation |=2120Lambda1.NumExplicitCaptures != Lambda2.NumExplicitCaptures;2121DetectedOdrViolation |=2122Lambda1.HasKnownInternalLinkage != Lambda2.HasKnownInternalLinkage;2123DetectedOdrViolation |= Lambda1.ManglingNumber != Lambda2.ManglingNumber;21242125if (Lambda1.NumCaptures && Lambda1.NumCaptures == Lambda2.NumCaptures) {2126for (unsigned I = 0, N = Lambda1.NumCaptures; I != N; ++I) {2127LambdaCapture &Cap1 = Lambda1.Captures.front()[I];2128LambdaCapture &Cap2 = Lambda2.Captures.front()[I];2129DetectedOdrViolation |= Cap1.getCaptureKind() != Cap2.getCaptureKind();2130}2131Lambda1.AddCaptureList(Reader.getContext(), Lambda2.Captures.front());2132}2133}21342135// We don't want to check ODR for decls in the global module fragment.2136if (shouldSkipCheckingODR(MergeDD.Definition) || shouldSkipCheckingODR(D))2137return;21382139if (D->getODRHash() != MergeDD.ODRHash) {2140DetectedOdrViolation = true;2141}21422143if (DetectedOdrViolation)2144Reader.PendingOdrMergeFailures[DD.Definition].push_back(2145{MergeDD.Definition, &MergeDD});2146}21472148void ASTDeclReader::ReadCXXRecordDefinition(CXXRecordDecl *D, bool Update,2149Decl *LambdaContext,2150unsigned IndexInLambdaContext) {2151struct CXXRecordDecl::DefinitionData *DD;2152ASTContext &C = Reader.getContext();21532154// Determine whether this is a lambda closure type, so that we can2155// allocate the appropriate DefinitionData structure.2156bool IsLambda = Record.readInt();2157assert(!(IsLambda && Update) &&2158"lambda definition should not be added by update record");2159if (IsLambda)2160DD = new (C) CXXRecordDecl::LambdaDefinitionData(2161D, nullptr, CXXRecordDecl::LDK_Unknown, false, LCD_None);2162else2163DD = new (C) struct CXXRecordDecl::DefinitionData(D);21642165CXXRecordDecl *Canon = D->getCanonicalDecl();2166// Set decl definition data before reading it, so that during deserialization2167// when we read CXXRecordDecl, it already has definition data and we don't2168// set fake one.2169if (!Canon->DefinitionData)2170Canon->DefinitionData = DD;2171D->DefinitionData = Canon->DefinitionData;2172ReadCXXDefinitionData(*DD, D, LambdaContext, IndexInLambdaContext);21732174// We might already have a different definition for this record. This can2175// happen either because we're reading an update record, or because we've2176// already done some merging. Either way, just merge into it.2177if (Canon->DefinitionData != DD) {2178MergeDefinitionData(Canon, std::move(*DD));2179return;2180}21812182// Mark this declaration as being a definition.2183D->setCompleteDefinition(true);21842185// If this is not the first declaration or is an update record, we can have2186// other redeclarations already. Make a note that we need to propagate the2187// DefinitionData pointer onto them.2188if (Update || Canon != D)2189Reader.PendingDefinitions.insert(D);2190}21912192ASTDeclReader::RedeclarableResult2193ASTDeclReader::VisitCXXRecordDeclImpl(CXXRecordDecl *D) {2194RedeclarableResult Redecl = VisitRecordDeclImpl(D);21952196ASTContext &C = Reader.getContext();21972198enum CXXRecKind {2199CXXRecNotTemplate = 0,2200CXXRecTemplate,2201CXXRecMemberSpecialization,2202CXXLambda2203};22042205Decl *LambdaContext = nullptr;2206unsigned IndexInLambdaContext = 0;22072208switch ((CXXRecKind)Record.readInt()) {2209case CXXRecNotTemplate:2210// Merged when we merge the folding set entry in the primary template.2211if (!isa<ClassTemplateSpecializationDecl>(D))2212mergeRedeclarable(D, Redecl);2213break;2214case CXXRecTemplate: {2215// Merged when we merge the template.2216auto *Template = readDeclAs<ClassTemplateDecl>();2217D->TemplateOrInstantiation = Template;2218if (!Template->getTemplatedDecl()) {2219// We've not actually loaded the ClassTemplateDecl yet, because we're2220// currently being loaded as its pattern. Rely on it to set up our2221// TypeForDecl (see VisitClassTemplateDecl).2222//2223// Beware: we do not yet know our canonical declaration, and may still2224// get merged once the surrounding class template has got off the ground.2225DeferredTypeID = 0;2226}2227break;2228}2229case CXXRecMemberSpecialization: {2230auto *RD = readDeclAs<CXXRecordDecl>();2231auto TSK = (TemplateSpecializationKind)Record.readInt();2232SourceLocation POI = readSourceLocation();2233MemberSpecializationInfo *MSI = new (C) MemberSpecializationInfo(RD, TSK);2234MSI->setPointOfInstantiation(POI);2235D->TemplateOrInstantiation = MSI;2236mergeRedeclarable(D, Redecl);2237break;2238}2239case CXXLambda: {2240LambdaContext = readDecl();2241if (LambdaContext)2242IndexInLambdaContext = Record.readInt();2243mergeLambda(D, Redecl, LambdaContext, IndexInLambdaContext);2244break;2245}2246}22472248bool WasDefinition = Record.readInt();2249if (WasDefinition)2250ReadCXXRecordDefinition(D, /*Update=*/false, LambdaContext,2251IndexInLambdaContext);2252else2253// Propagate DefinitionData pointer from the canonical declaration.2254D->DefinitionData = D->getCanonicalDecl()->DefinitionData;22552256// Lazily load the key function to avoid deserializing every method so we can2257// compute it.2258if (WasDefinition) {2259GlobalDeclID KeyFn = readDeclID();2260if (KeyFn.isValid() && D->isCompleteDefinition())2261// FIXME: This is wrong for the ARM ABI, where some other module may have2262// made this function no longer be a key function. We need an update2263// record or similar for that case.2264C.KeyFunctions[D] = KeyFn.getRawValue();2265}22662267return Redecl;2268}22692270void ASTDeclReader::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) {2271D->setExplicitSpecifier(Record.readExplicitSpec());2272D->Ctor = readDeclAs<CXXConstructorDecl>();2273VisitFunctionDecl(D);2274D->setDeductionCandidateKind(2275static_cast<DeductionCandidate>(Record.readInt()));2276}22772278void ASTDeclReader::VisitCXXMethodDecl(CXXMethodDecl *D) {2279VisitFunctionDecl(D);22802281unsigned NumOverridenMethods = Record.readInt();2282if (D->isCanonicalDecl()) {2283while (NumOverridenMethods--) {2284// Avoid invariant checking of CXXMethodDecl::addOverriddenMethod,2285// MD may be initializing.2286if (auto *MD = readDeclAs<CXXMethodDecl>())2287Reader.getContext().addOverriddenMethod(D, MD->getCanonicalDecl());2288}2289} else {2290// We don't care about which declarations this used to override; we get2291// the relevant information from the canonical declaration.2292Record.skipInts(NumOverridenMethods);2293}2294}22952296void ASTDeclReader::VisitCXXConstructorDecl(CXXConstructorDecl *D) {2297// We need the inherited constructor information to merge the declaration,2298// so we have to read it before we call VisitCXXMethodDecl.2299D->setExplicitSpecifier(Record.readExplicitSpec());2300if (D->isInheritingConstructor()) {2301auto *Shadow = readDeclAs<ConstructorUsingShadowDecl>();2302auto *Ctor = readDeclAs<CXXConstructorDecl>();2303*D->getTrailingObjects<InheritedConstructor>() =2304InheritedConstructor(Shadow, Ctor);2305}23062307VisitCXXMethodDecl(D);2308}23092310void ASTDeclReader::VisitCXXDestructorDecl(CXXDestructorDecl *D) {2311VisitCXXMethodDecl(D);23122313if (auto *OperatorDelete = readDeclAs<FunctionDecl>()) {2314CXXDestructorDecl *Canon = D->getCanonicalDecl();2315auto *ThisArg = Record.readExpr();2316// FIXME: Check consistency if we have an old and new operator delete.2317if (!Canon->OperatorDelete) {2318Canon->OperatorDelete = OperatorDelete;2319Canon->OperatorDeleteThisArg = ThisArg;2320}2321}2322}23232324void ASTDeclReader::VisitCXXConversionDecl(CXXConversionDecl *D) {2325D->setExplicitSpecifier(Record.readExplicitSpec());2326VisitCXXMethodDecl(D);2327}23282329void ASTDeclReader::VisitImportDecl(ImportDecl *D) {2330VisitDecl(D);2331D->ImportedModule = readModule();2332D->setImportComplete(Record.readInt());2333auto *StoredLocs = D->getTrailingObjects<SourceLocation>();2334for (unsigned I = 0, N = Record.back(); I != N; ++I)2335StoredLocs[I] = readSourceLocation();2336Record.skipInts(1); // The number of stored source locations.2337}23382339void ASTDeclReader::VisitAccessSpecDecl(AccessSpecDecl *D) {2340VisitDecl(D);2341D->setColonLoc(readSourceLocation());2342}23432344void ASTDeclReader::VisitFriendDecl(FriendDecl *D) {2345VisitDecl(D);2346if (Record.readInt()) // hasFriendDecl2347D->Friend = readDeclAs<NamedDecl>();2348else2349D->Friend = readTypeSourceInfo();2350for (unsigned i = 0; i != D->NumTPLists; ++i)2351D->getTrailingObjects<TemplateParameterList *>()[i] =2352Record.readTemplateParameterList();2353D->NextFriend = readDeclID().getRawValue();2354D->UnsupportedFriend = (Record.readInt() != 0);2355D->FriendLoc = readSourceLocation();2356}23572358void ASTDeclReader::VisitFriendTemplateDecl(FriendTemplateDecl *D) {2359VisitDecl(D);2360unsigned NumParams = Record.readInt();2361D->NumParams = NumParams;2362D->Params = new (Reader.getContext()) TemplateParameterList *[NumParams];2363for (unsigned i = 0; i != NumParams; ++i)2364D->Params[i] = Record.readTemplateParameterList();2365if (Record.readInt()) // HasFriendDecl2366D->Friend = readDeclAs<NamedDecl>();2367else2368D->Friend = readTypeSourceInfo();2369D->FriendLoc = readSourceLocation();2370}23712372void ASTDeclReader::VisitTemplateDecl(TemplateDecl *D) {2373VisitNamedDecl(D);23742375assert(!D->TemplateParams && "TemplateParams already set!");2376D->TemplateParams = Record.readTemplateParameterList();2377D->init(readDeclAs<NamedDecl>());2378}23792380void ASTDeclReader::VisitConceptDecl(ConceptDecl *D) {2381VisitTemplateDecl(D);2382D->ConstraintExpr = Record.readExpr();2383mergeMergeable(D);2384}23852386void ASTDeclReader::VisitImplicitConceptSpecializationDecl(2387ImplicitConceptSpecializationDecl *D) {2388// The size of the template list was read during creation of the Decl, so we2389// don't have to re-read it here.2390VisitDecl(D);2391llvm::SmallVector<TemplateArgument, 4> Args;2392for (unsigned I = 0; I < D->NumTemplateArgs; ++I)2393Args.push_back(Record.readTemplateArgument(/*Canonicalize=*/true));2394D->setTemplateArguments(Args);2395}23962397void ASTDeclReader::VisitRequiresExprBodyDecl(RequiresExprBodyDecl *D) {2398}23992400ASTDeclReader::RedeclarableResult2401ASTDeclReader::VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D) {2402RedeclarableResult Redecl = VisitRedeclarable(D);24032404// Make sure we've allocated the Common pointer first. We do this before2405// VisitTemplateDecl so that getCommonPtr() can be used during initialization.2406RedeclarableTemplateDecl *CanonD = D->getCanonicalDecl();2407if (!CanonD->Common) {2408CanonD->Common = CanonD->newCommon(Reader.getContext());2409Reader.PendingDefinitions.insert(CanonD);2410}2411D->Common = CanonD->Common;24122413// If this is the first declaration of the template, fill in the information2414// for the 'common' pointer.2415if (ThisDeclID == Redecl.getFirstID()) {2416if (auto *RTD = readDeclAs<RedeclarableTemplateDecl>()) {2417assert(RTD->getKind() == D->getKind() &&2418"InstantiatedFromMemberTemplate kind mismatch");2419D->setInstantiatedFromMemberTemplate(RTD);2420if (Record.readInt())2421D->setMemberSpecialization();2422}2423}24242425VisitTemplateDecl(D);2426D->IdentifierNamespace = Record.readInt();24272428return Redecl;2429}24302431void ASTDeclReader::VisitClassTemplateDecl(ClassTemplateDecl *D) {2432RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);2433mergeRedeclarableTemplate(D, Redecl);24342435if (ThisDeclID == Redecl.getFirstID()) {2436// This ClassTemplateDecl owns a CommonPtr; read it to keep track of all of2437// the specializations.2438SmallVector<GlobalDeclID, 32> SpecIDs;2439readDeclIDList(SpecIDs);2440ASTDeclReader::AddLazySpecializations(D, SpecIDs);2441}24422443if (D->getTemplatedDecl()->TemplateOrInstantiation) {2444// We were loaded before our templated declaration was. We've not set up2445// its corresponding type yet (see VisitCXXRecordDeclImpl), so reconstruct2446// it now.2447Reader.getContext().getInjectedClassNameType(2448D->getTemplatedDecl(), D->getInjectedClassNameSpecialization());2449}2450}24512452void ASTDeclReader::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) {2453llvm_unreachable("BuiltinTemplates are not serialized");2454}24552456/// TODO: Unify with ClassTemplateDecl version?2457/// May require unifying ClassTemplateDecl and2458/// VarTemplateDecl beyond TemplateDecl...2459void ASTDeclReader::VisitVarTemplateDecl(VarTemplateDecl *D) {2460RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);2461mergeRedeclarableTemplate(D, Redecl);24622463if (ThisDeclID == Redecl.getFirstID()) {2464// This VarTemplateDecl owns a CommonPtr; read it to keep track of all of2465// the specializations.2466SmallVector<GlobalDeclID, 32> SpecIDs;2467readDeclIDList(SpecIDs);2468ASTDeclReader::AddLazySpecializations(D, SpecIDs);2469}2470}24712472ASTDeclReader::RedeclarableResult2473ASTDeclReader::VisitClassTemplateSpecializationDeclImpl(2474ClassTemplateSpecializationDecl *D) {2475RedeclarableResult Redecl = VisitCXXRecordDeclImpl(D);24762477ASTContext &C = Reader.getContext();2478if (Decl *InstD = readDecl()) {2479if (auto *CTD = dyn_cast<ClassTemplateDecl>(InstD)) {2480D->SpecializedTemplate = CTD;2481} else {2482SmallVector<TemplateArgument, 8> TemplArgs;2483Record.readTemplateArgumentList(TemplArgs);2484TemplateArgumentList *ArgList2485= TemplateArgumentList::CreateCopy(C, TemplArgs);2486auto *PS =2487new (C) ClassTemplateSpecializationDecl::2488SpecializedPartialSpecialization();2489PS->PartialSpecialization2490= cast<ClassTemplatePartialSpecializationDecl>(InstD);2491PS->TemplateArgs = ArgList;2492D->SpecializedTemplate = PS;2493}2494}24952496SmallVector<TemplateArgument, 8> TemplArgs;2497Record.readTemplateArgumentList(TemplArgs, /*Canonicalize*/ true);2498D->TemplateArgs = TemplateArgumentList::CreateCopy(C, TemplArgs);2499D->PointOfInstantiation = readSourceLocation();2500D->SpecializationKind = (TemplateSpecializationKind)Record.readInt();25012502bool writtenAsCanonicalDecl = Record.readInt();2503if (writtenAsCanonicalDecl) {2504auto *CanonPattern = readDeclAs<ClassTemplateDecl>();2505if (D->isCanonicalDecl()) { // It's kept in the folding set.2506// Set this as, or find, the canonical declaration for this specialization2507ClassTemplateSpecializationDecl *CanonSpec;2508if (auto *Partial = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) {2509CanonSpec = CanonPattern->getCommonPtr()->PartialSpecializations2510.GetOrInsertNode(Partial);2511} else {2512CanonSpec =2513CanonPattern->getCommonPtr()->Specializations.GetOrInsertNode(D);2514}2515// If there was already a canonical specialization, merge into it.2516if (CanonSpec != D) {2517mergeRedeclarable<TagDecl>(D, CanonSpec, Redecl);25182519// This declaration might be a definition. Merge with any existing2520// definition.2521if (auto *DDD = D->DefinitionData) {2522if (CanonSpec->DefinitionData)2523MergeDefinitionData(CanonSpec, std::move(*DDD));2524else2525CanonSpec->DefinitionData = D->DefinitionData;2526}2527D->DefinitionData = CanonSpec->DefinitionData;2528}2529}2530}25312532// extern/template keyword locations for explicit instantiations2533if (Record.readBool()) {2534auto *ExplicitInfo = new (C) ExplicitInstantiationInfo;2535ExplicitInfo->ExternKeywordLoc = readSourceLocation();2536ExplicitInfo->TemplateKeywordLoc = readSourceLocation();2537D->ExplicitInfo = ExplicitInfo;2538}25392540if (Record.readBool())2541D->setTemplateArgsAsWritten(Record.readASTTemplateArgumentListInfo());25422543return Redecl;2544}25452546void ASTDeclReader::VisitClassTemplatePartialSpecializationDecl(2547ClassTemplatePartialSpecializationDecl *D) {2548// We need to read the template params first because redeclarable is going to2549// need them for profiling2550TemplateParameterList *Params = Record.readTemplateParameterList();2551D->TemplateParams = Params;25522553RedeclarableResult Redecl = VisitClassTemplateSpecializationDeclImpl(D);25542555// These are read/set from/to the first declaration.2556if (ThisDeclID == Redecl.getFirstID()) {2557D->InstantiatedFromMember.setPointer(2558readDeclAs<ClassTemplatePartialSpecializationDecl>());2559D->InstantiatedFromMember.setInt(Record.readInt());2560}2561}25622563void ASTDeclReader::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {2564RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);25652566if (ThisDeclID == Redecl.getFirstID()) {2567// This FunctionTemplateDecl owns a CommonPtr; read it.2568SmallVector<GlobalDeclID, 32> SpecIDs;2569readDeclIDList(SpecIDs);2570ASTDeclReader::AddLazySpecializations(D, SpecIDs);2571}2572}25732574/// TODO: Unify with ClassTemplateSpecializationDecl version?2575/// May require unifying ClassTemplate(Partial)SpecializationDecl and2576/// VarTemplate(Partial)SpecializationDecl with a new data2577/// structure Template(Partial)SpecializationDecl, and2578/// using Template(Partial)SpecializationDecl as input type.2579ASTDeclReader::RedeclarableResult2580ASTDeclReader::VisitVarTemplateSpecializationDeclImpl(2581VarTemplateSpecializationDecl *D) {2582ASTContext &C = Reader.getContext();2583if (Decl *InstD = readDecl()) {2584if (auto *VTD = dyn_cast<VarTemplateDecl>(InstD)) {2585D->SpecializedTemplate = VTD;2586} else {2587SmallVector<TemplateArgument, 8> TemplArgs;2588Record.readTemplateArgumentList(TemplArgs);2589TemplateArgumentList *ArgList = TemplateArgumentList::CreateCopy(2590C, TemplArgs);2591auto *PS =2592new (C)2593VarTemplateSpecializationDecl::SpecializedPartialSpecialization();2594PS->PartialSpecialization =2595cast<VarTemplatePartialSpecializationDecl>(InstD);2596PS->TemplateArgs = ArgList;2597D->SpecializedTemplate = PS;2598}2599}26002601// extern/template keyword locations for explicit instantiations2602if (Record.readBool()) {2603auto *ExplicitInfo = new (C) ExplicitInstantiationInfo;2604ExplicitInfo->ExternKeywordLoc = readSourceLocation();2605ExplicitInfo->TemplateKeywordLoc = readSourceLocation();2606D->ExplicitInfo = ExplicitInfo;2607}26082609if (Record.readBool())2610D->setTemplateArgsAsWritten(Record.readASTTemplateArgumentListInfo());26112612SmallVector<TemplateArgument, 8> TemplArgs;2613Record.readTemplateArgumentList(TemplArgs, /*Canonicalize*/ true);2614D->TemplateArgs = TemplateArgumentList::CreateCopy(C, TemplArgs);2615D->PointOfInstantiation = readSourceLocation();2616D->SpecializationKind = (TemplateSpecializationKind)Record.readInt();2617D->IsCompleteDefinition = Record.readInt();26182619RedeclarableResult Redecl = VisitVarDeclImpl(D);26202621bool writtenAsCanonicalDecl = Record.readInt();2622if (writtenAsCanonicalDecl) {2623auto *CanonPattern = readDeclAs<VarTemplateDecl>();2624if (D->isCanonicalDecl()) { // It's kept in the folding set.2625VarTemplateSpecializationDecl *CanonSpec;2626if (auto *Partial = dyn_cast<VarTemplatePartialSpecializationDecl>(D)) {2627CanonSpec = CanonPattern->getCommonPtr()2628->PartialSpecializations.GetOrInsertNode(Partial);2629} else {2630CanonSpec =2631CanonPattern->getCommonPtr()->Specializations.GetOrInsertNode(D);2632}2633// If we already have a matching specialization, merge it.2634if (CanonSpec != D)2635mergeRedeclarable<VarDecl>(D, CanonSpec, Redecl);2636}2637}26382639return Redecl;2640}26412642/// TODO: Unify with ClassTemplatePartialSpecializationDecl version?2643/// May require unifying ClassTemplate(Partial)SpecializationDecl and2644/// VarTemplate(Partial)SpecializationDecl with a new data2645/// structure Template(Partial)SpecializationDecl, and2646/// using Template(Partial)SpecializationDecl as input type.2647void ASTDeclReader::VisitVarTemplatePartialSpecializationDecl(2648VarTemplatePartialSpecializationDecl *D) {2649TemplateParameterList *Params = Record.readTemplateParameterList();2650D->TemplateParams = Params;26512652RedeclarableResult Redecl = VisitVarTemplateSpecializationDeclImpl(D);26532654// These are read/set from/to the first declaration.2655if (ThisDeclID == Redecl.getFirstID()) {2656D->InstantiatedFromMember.setPointer(2657readDeclAs<VarTemplatePartialSpecializationDecl>());2658D->InstantiatedFromMember.setInt(Record.readInt());2659}2660}26612662void ASTDeclReader::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {2663VisitTypeDecl(D);26642665D->setDeclaredWithTypename(Record.readInt());26662667const bool TypeConstraintInitialized = Record.readBool();2668if (TypeConstraintInitialized && D->hasTypeConstraint()) {2669ConceptReference *CR = nullptr;2670if (Record.readBool())2671CR = Record.readConceptReference();2672Expr *ImmediatelyDeclaredConstraint = Record.readExpr();26732674D->setTypeConstraint(CR, ImmediatelyDeclaredConstraint);2675if ((D->ExpandedParameterPack = Record.readInt()))2676D->NumExpanded = Record.readInt();2677}26782679if (Record.readInt())2680D->setDefaultArgument(Reader.getContext(),2681Record.readTemplateArgumentLoc());2682}26832684void ASTDeclReader::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {2685VisitDeclaratorDecl(D);2686// TemplateParmPosition.2687D->setDepth(Record.readInt());2688D->setPosition(Record.readInt());2689if (D->hasPlaceholderTypeConstraint())2690D->setPlaceholderTypeConstraint(Record.readExpr());2691if (D->isExpandedParameterPack()) {2692auto TypesAndInfos =2693D->getTrailingObjects<std::pair<QualType, TypeSourceInfo *>>();2694for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {2695new (&TypesAndInfos[I].first) QualType(Record.readType());2696TypesAndInfos[I].second = readTypeSourceInfo();2697}2698} else {2699// Rest of NonTypeTemplateParmDecl.2700D->ParameterPack = Record.readInt();2701if (Record.readInt())2702D->setDefaultArgument(Reader.getContext(),2703Record.readTemplateArgumentLoc());2704}2705}27062707void ASTDeclReader::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {2708VisitTemplateDecl(D);2709D->setDeclaredWithTypename(Record.readBool());2710// TemplateParmPosition.2711D->setDepth(Record.readInt());2712D->setPosition(Record.readInt());2713if (D->isExpandedParameterPack()) {2714auto **Data = D->getTrailingObjects<TemplateParameterList *>();2715for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();2716I != N; ++I)2717Data[I] = Record.readTemplateParameterList();2718} else {2719// Rest of TemplateTemplateParmDecl.2720D->ParameterPack = Record.readInt();2721if (Record.readInt())2722D->setDefaultArgument(Reader.getContext(),2723Record.readTemplateArgumentLoc());2724}2725}27262727void ASTDeclReader::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {2728RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);2729mergeRedeclarableTemplate(D, Redecl);2730}27312732void ASTDeclReader::VisitStaticAssertDecl(StaticAssertDecl *D) {2733VisitDecl(D);2734D->AssertExprAndFailed.setPointer(Record.readExpr());2735D->AssertExprAndFailed.setInt(Record.readInt());2736D->Message = cast_or_null<StringLiteral>(Record.readExpr());2737D->RParenLoc = readSourceLocation();2738}27392740void ASTDeclReader::VisitEmptyDecl(EmptyDecl *D) {2741VisitDecl(D);2742}27432744void ASTDeclReader::VisitLifetimeExtendedTemporaryDecl(2745LifetimeExtendedTemporaryDecl *D) {2746VisitDecl(D);2747D->ExtendingDecl = readDeclAs<ValueDecl>();2748D->ExprWithTemporary = Record.readStmt();2749if (Record.readInt()) {2750D->Value = new (D->getASTContext()) APValue(Record.readAPValue());2751D->getASTContext().addDestruction(D->Value);2752}2753D->ManglingNumber = Record.readInt();2754mergeMergeable(D);2755}27562757std::pair<uint64_t, uint64_t>2758ASTDeclReader::VisitDeclContext(DeclContext *DC) {2759uint64_t LexicalOffset = ReadLocalOffset();2760uint64_t VisibleOffset = ReadLocalOffset();2761return std::make_pair(LexicalOffset, VisibleOffset);2762}27632764template <typename T>2765ASTDeclReader::RedeclarableResult2766ASTDeclReader::VisitRedeclarable(Redeclarable<T> *D) {2767GlobalDeclID FirstDeclID = readDeclID();2768Decl *MergeWith = nullptr;27692770bool IsKeyDecl = ThisDeclID == FirstDeclID;2771bool IsFirstLocalDecl = false;27722773uint64_t RedeclOffset = 0;27742775// invalid FirstDeclID indicates that this declaration was the only2776// declaration of its entity, and is used for space optimization.2777if (FirstDeclID.isInvalid()) {2778FirstDeclID = ThisDeclID;2779IsKeyDecl = true;2780IsFirstLocalDecl = true;2781} else if (unsigned N = Record.readInt()) {2782// This declaration was the first local declaration, but may have imported2783// other declarations.2784IsKeyDecl = N == 1;2785IsFirstLocalDecl = true;27862787// We have some declarations that must be before us in our redeclaration2788// chain. Read them now, and remember that we ought to merge with one of2789// them.2790// FIXME: Provide a known merge target to the second and subsequent such2791// declaration.2792for (unsigned I = 0; I != N - 1; ++I)2793MergeWith = readDecl();27942795RedeclOffset = ReadLocalOffset();2796} else {2797// This declaration was not the first local declaration. Read the first2798// local declaration now, to trigger the import of other redeclarations.2799(void)readDecl();2800}28012802auto *FirstDecl = cast_or_null<T>(Reader.GetDecl(FirstDeclID));2803if (FirstDecl != D) {2804// We delay loading of the redeclaration chain to avoid deeply nested calls.2805// We temporarily set the first (canonical) declaration as the previous one2806// which is the one that matters and mark the real previous DeclID to be2807// loaded & attached later on.2808D->RedeclLink = Redeclarable<T>::PreviousDeclLink(FirstDecl);2809D->First = FirstDecl->getCanonicalDecl();2810}28112812auto *DAsT = static_cast<T *>(D);28132814// Note that we need to load local redeclarations of this decl and build a2815// decl chain for them. This must happen *after* we perform the preloading2816// above; this ensures that the redeclaration chain is built in the correct2817// order.2818if (IsFirstLocalDecl)2819Reader.PendingDeclChains.push_back(std::make_pair(DAsT, RedeclOffset));28202821return RedeclarableResult(MergeWith, FirstDeclID, IsKeyDecl);2822}28232824/// Attempts to merge the given declaration (D) with another declaration2825/// of the same entity.2826template <typename T>2827void ASTDeclReader::mergeRedeclarable(Redeclarable<T> *DBase,2828RedeclarableResult &Redecl) {2829// If modules are not available, there is no reason to perform this merge.2830if (!Reader.getContext().getLangOpts().Modules)2831return;28322833// If we're not the canonical declaration, we don't need to merge.2834if (!DBase->isFirstDecl())2835return;28362837auto *D = static_cast<T *>(DBase);28382839if (auto *Existing = Redecl.getKnownMergeTarget())2840// We already know of an existing declaration we should merge with.2841mergeRedeclarable(D, cast<T>(Existing), Redecl);2842else if (FindExistingResult ExistingRes = findExisting(D))2843if (T *Existing = ExistingRes)2844mergeRedeclarable(D, Existing, Redecl);2845}28462847/// Attempt to merge D with a previous declaration of the same lambda, which is2848/// found by its index within its context declaration, if it has one.2849///2850/// We can't look up lambdas in their enclosing lexical or semantic context in2851/// general, because for lambdas in variables, both of those might be a2852/// namespace or the translation unit.2853void ASTDeclReader::mergeLambda(CXXRecordDecl *D, RedeclarableResult &Redecl,2854Decl *Context, unsigned IndexInContext) {2855// If we don't have a mangling context, treat this like any other2856// declaration.2857if (!Context)2858return mergeRedeclarable(D, Redecl);28592860// If modules are not available, there is no reason to perform this merge.2861if (!Reader.getContext().getLangOpts().Modules)2862return;28632864// If we're not the canonical declaration, we don't need to merge.2865if (!D->isFirstDecl())2866return;28672868if (auto *Existing = Redecl.getKnownMergeTarget())2869// We already know of an existing declaration we should merge with.2870mergeRedeclarable(D, cast<TagDecl>(Existing), Redecl);28712872// Look up this lambda to see if we've seen it before. If so, merge with the2873// one we already loaded.2874NamedDecl *&Slot = Reader.LambdaDeclarationsForMerging[{2875Context->getCanonicalDecl(), IndexInContext}];2876if (Slot)2877mergeRedeclarable(D, cast<TagDecl>(Slot), Redecl);2878else2879Slot = D;2880}28812882void ASTDeclReader::mergeRedeclarableTemplate(RedeclarableTemplateDecl *D,2883RedeclarableResult &Redecl) {2884mergeRedeclarable(D, Redecl);2885// If we merged the template with a prior declaration chain, merge the2886// common pointer.2887// FIXME: Actually merge here, don't just overwrite.2888D->Common = D->getCanonicalDecl()->Common;2889}28902891/// "Cast" to type T, asserting if we don't have an implicit conversion.2892/// We use this to put code in a template that will only be valid for certain2893/// instantiations.2894template<typename T> static T assert_cast(T t) { return t; }2895template<typename T> static T assert_cast(...) {2896llvm_unreachable("bad assert_cast");2897}28982899/// Merge together the pattern declarations from two template2900/// declarations.2901void ASTDeclReader::mergeTemplatePattern(RedeclarableTemplateDecl *D,2902RedeclarableTemplateDecl *Existing,2903bool IsKeyDecl) {2904auto *DPattern = D->getTemplatedDecl();2905auto *ExistingPattern = Existing->getTemplatedDecl();2906RedeclarableResult Result(2907/*MergeWith*/ ExistingPattern,2908DPattern->getCanonicalDecl()->getGlobalID(), IsKeyDecl);29092910if (auto *DClass = dyn_cast<CXXRecordDecl>(DPattern)) {2911// Merge with any existing definition.2912// FIXME: This is duplicated in several places. Refactor.2913auto *ExistingClass =2914cast<CXXRecordDecl>(ExistingPattern)->getCanonicalDecl();2915if (auto *DDD = DClass->DefinitionData) {2916if (ExistingClass->DefinitionData) {2917MergeDefinitionData(ExistingClass, std::move(*DDD));2918} else {2919ExistingClass->DefinitionData = DClass->DefinitionData;2920// We may have skipped this before because we thought that DClass2921// was the canonical declaration.2922Reader.PendingDefinitions.insert(DClass);2923}2924}2925DClass->DefinitionData = ExistingClass->DefinitionData;29262927return mergeRedeclarable(DClass, cast<TagDecl>(ExistingPattern),2928Result);2929}2930if (auto *DFunction = dyn_cast<FunctionDecl>(DPattern))2931return mergeRedeclarable(DFunction, cast<FunctionDecl>(ExistingPattern),2932Result);2933if (auto *DVar = dyn_cast<VarDecl>(DPattern))2934return mergeRedeclarable(DVar, cast<VarDecl>(ExistingPattern), Result);2935if (auto *DAlias = dyn_cast<TypeAliasDecl>(DPattern))2936return mergeRedeclarable(DAlias, cast<TypedefNameDecl>(ExistingPattern),2937Result);2938llvm_unreachable("merged an unknown kind of redeclarable template");2939}29402941/// Attempts to merge the given declaration (D) with another declaration2942/// of the same entity.2943template <typename T>2944void ASTDeclReader::mergeRedeclarable(Redeclarable<T> *DBase, T *Existing,2945RedeclarableResult &Redecl) {2946auto *D = static_cast<T *>(DBase);2947T *ExistingCanon = Existing->getCanonicalDecl();2948T *DCanon = D->getCanonicalDecl();2949if (ExistingCanon != DCanon) {2950// Have our redeclaration link point back at the canonical declaration2951// of the existing declaration, so that this declaration has the2952// appropriate canonical declaration.2953D->RedeclLink = Redeclarable<T>::PreviousDeclLink(ExistingCanon);2954D->First = ExistingCanon;2955ExistingCanon->Used |= D->Used;2956D->Used = false;29572958// When we merge a template, merge its pattern.2959if (auto *DTemplate = dyn_cast<RedeclarableTemplateDecl>(D))2960mergeTemplatePattern(2961DTemplate, assert_cast<RedeclarableTemplateDecl *>(ExistingCanon),2962Redecl.isKeyDecl());29632964// If this declaration is a key declaration, make a note of that.2965if (Redecl.isKeyDecl())2966Reader.KeyDecls[ExistingCanon].push_back(Redecl.getFirstID());2967}2968}29692970/// ODR-like semantics for C/ObjC allow us to merge tag types and a structural2971/// check in Sema guarantees the types can be merged (see C11 6.2.7/1 or C892972/// 6.1.2.6/1). Although most merging is done in Sema, we need to guarantee2973/// that some types are mergeable during deserialization, otherwise name2974/// lookup fails. This is the case for EnumConstantDecl.2975static bool allowODRLikeMergeInC(NamedDecl *ND) {2976if (!ND)2977return false;2978// TODO: implement merge for other necessary decls.2979if (isa<EnumConstantDecl, FieldDecl, IndirectFieldDecl>(ND))2980return true;2981return false;2982}29832984/// Attempts to merge LifetimeExtendedTemporaryDecl with2985/// identical class definitions from two different modules.2986void ASTDeclReader::mergeMergeable(LifetimeExtendedTemporaryDecl *D) {2987// If modules are not available, there is no reason to perform this merge.2988if (!Reader.getContext().getLangOpts().Modules)2989return;29902991LifetimeExtendedTemporaryDecl *LETDecl = D;29922993LifetimeExtendedTemporaryDecl *&LookupResult =2994Reader.LETemporaryForMerging[std::make_pair(2995LETDecl->getExtendingDecl(), LETDecl->getManglingNumber())];2996if (LookupResult)2997Reader.getContext().setPrimaryMergedDecl(LETDecl,2998LookupResult->getCanonicalDecl());2999else3000LookupResult = LETDecl;3001}30023003/// Attempts to merge the given declaration (D) with another declaration3004/// of the same entity, for the case where the entity is not actually3005/// redeclarable. This happens, for instance, when merging the fields of3006/// identical class definitions from two different modules.3007template<typename T>3008void ASTDeclReader::mergeMergeable(Mergeable<T> *D) {3009// If modules are not available, there is no reason to perform this merge.3010if (!Reader.getContext().getLangOpts().Modules)3011return;30123013// ODR-based merging is performed in C++ and in some cases (tag types) in C.3014// Note that C identically-named things in different translation units are3015// not redeclarations, but may still have compatible types, where ODR-like3016// semantics may apply.3017if (!Reader.getContext().getLangOpts().CPlusPlus &&3018!allowODRLikeMergeInC(dyn_cast<NamedDecl>(static_cast<T*>(D))))3019return;30203021if (FindExistingResult ExistingRes = findExisting(static_cast<T*>(D)))3022if (T *Existing = ExistingRes)3023Reader.getContext().setPrimaryMergedDecl(static_cast<T *>(D),3024Existing->getCanonicalDecl());3025}30263027void ASTDeclReader::VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D) {3028Record.readOMPChildren(D->Data);3029VisitDecl(D);3030}30313032void ASTDeclReader::VisitOMPAllocateDecl(OMPAllocateDecl *D) {3033Record.readOMPChildren(D->Data);3034VisitDecl(D);3035}30363037void ASTDeclReader::VisitOMPRequiresDecl(OMPRequiresDecl * D) {3038Record.readOMPChildren(D->Data);3039VisitDecl(D);3040}30413042void ASTDeclReader::VisitOMPDeclareReductionDecl(OMPDeclareReductionDecl *D) {3043VisitValueDecl(D);3044D->setLocation(readSourceLocation());3045Expr *In = Record.readExpr();3046Expr *Out = Record.readExpr();3047D->setCombinerData(In, Out);3048Expr *Combiner = Record.readExpr();3049D->setCombiner(Combiner);3050Expr *Orig = Record.readExpr();3051Expr *Priv = Record.readExpr();3052D->setInitializerData(Orig, Priv);3053Expr *Init = Record.readExpr();3054auto IK = static_cast<OMPDeclareReductionInitKind>(Record.readInt());3055D->setInitializer(Init, IK);3056D->PrevDeclInScope = readDeclID().getRawValue();3057}30583059void ASTDeclReader::VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D) {3060Record.readOMPChildren(D->Data);3061VisitValueDecl(D);3062D->VarName = Record.readDeclarationName();3063D->PrevDeclInScope = readDeclID().getRawValue();3064}30653066void ASTDeclReader::VisitOMPCapturedExprDecl(OMPCapturedExprDecl *D) {3067VisitVarDecl(D);3068}30693070//===----------------------------------------------------------------------===//3071// Attribute Reading3072//===----------------------------------------------------------------------===//30733074namespace {3075class AttrReader {3076ASTRecordReader &Reader;30773078public:3079AttrReader(ASTRecordReader &Reader) : Reader(Reader) {}30803081uint64_t readInt() {3082return Reader.readInt();3083}30843085bool readBool() { return Reader.readBool(); }30863087SourceRange readSourceRange() {3088return Reader.readSourceRange();3089}30903091SourceLocation readSourceLocation() {3092return Reader.readSourceLocation();3093}30943095Expr *readExpr() { return Reader.readExpr(); }30963097Attr *readAttr() { return Reader.readAttr(); }30983099std::string readString() {3100return Reader.readString();3101}31023103TypeSourceInfo *readTypeSourceInfo() {3104return Reader.readTypeSourceInfo();3105}31063107IdentifierInfo *readIdentifier() {3108return Reader.readIdentifier();3109}31103111VersionTuple readVersionTuple() {3112return Reader.readVersionTuple();3113}31143115OMPTraitInfo *readOMPTraitInfo() { return Reader.readOMPTraitInfo(); }31163117template <typename T> T *readDeclAs() { return Reader.readDeclAs<T>(); }3118};3119}31203121Attr *ASTRecordReader::readAttr() {3122AttrReader Record(*this);3123auto V = Record.readInt();3124if (!V)3125return nullptr;31263127Attr *New = nullptr;3128// Kind is stored as a 1-based integer because 0 is used to indicate a null3129// Attr pointer.3130auto Kind = static_cast<attr::Kind>(V - 1);3131ASTContext &Context = getContext();31323133IdentifierInfo *AttrName = Record.readIdentifier();3134IdentifierInfo *ScopeName = Record.readIdentifier();3135SourceRange AttrRange = Record.readSourceRange();3136SourceLocation ScopeLoc = Record.readSourceLocation();3137unsigned ParsedKind = Record.readInt();3138unsigned Syntax = Record.readInt();3139unsigned SpellingIndex = Record.readInt();3140bool IsAlignas = (ParsedKind == AttributeCommonInfo::AT_Aligned &&3141Syntax == AttributeCommonInfo::AS_Keyword &&3142SpellingIndex == AlignedAttr::Keyword_alignas);3143bool IsRegularKeywordAttribute = Record.readBool();31443145AttributeCommonInfo Info(AttrName, ScopeName, AttrRange, ScopeLoc,3146AttributeCommonInfo::Kind(ParsedKind),3147{AttributeCommonInfo::Syntax(Syntax), SpellingIndex,3148IsAlignas, IsRegularKeywordAttribute});31493150#include "clang/Serialization/AttrPCHRead.inc"31513152assert(New && "Unable to decode attribute?");3153return New;3154}31553156/// Reads attributes from the current stream position.3157void ASTRecordReader::readAttributes(AttrVec &Attrs) {3158for (unsigned I = 0, E = readInt(); I != E; ++I)3159if (auto *A = readAttr())3160Attrs.push_back(A);3161}31623163//===----------------------------------------------------------------------===//3164// ASTReader Implementation3165//===----------------------------------------------------------------------===//31663167/// Note that we have loaded the declaration with the given3168/// Index.3169///3170/// This routine notes that this declaration has already been loaded,3171/// so that future GetDecl calls will return this declaration rather3172/// than trying to load a new declaration.3173inline void ASTReader::LoadedDecl(unsigned Index, Decl *D) {3174assert(!DeclsLoaded[Index] && "Decl loaded twice?");3175DeclsLoaded[Index] = D;3176}31773178/// Determine whether the consumer will be interested in seeing3179/// this declaration (via HandleTopLevelDecl).3180///3181/// This routine should return true for anything that might affect3182/// code generation, e.g., inline function definitions, Objective-C3183/// declarations with metadata, etc.3184bool ASTReader::isConsumerInterestedIn(Decl *D) {3185// An ObjCMethodDecl is never considered as "interesting" because its3186// implementation container always is.31873188// An ImportDecl or VarDecl imported from a module map module will get3189// emitted when we import the relevant module.3190if (isPartOfPerModuleInitializer(D)) {3191auto *M = D->getImportedOwningModule();3192if (M && M->Kind == Module::ModuleMapModule &&3193getContext().DeclMustBeEmitted(D))3194return false;3195}31963197if (isa<FileScopeAsmDecl, TopLevelStmtDecl, ObjCProtocolDecl, ObjCImplDecl,3198ImportDecl, PragmaCommentDecl, PragmaDetectMismatchDecl>(D))3199return true;3200if (isa<OMPThreadPrivateDecl, OMPDeclareReductionDecl, OMPDeclareMapperDecl,3201OMPAllocateDecl, OMPRequiresDecl>(D))3202return !D->getDeclContext()->isFunctionOrMethod();3203if (const auto *Var = dyn_cast<VarDecl>(D))3204return Var->isFileVarDecl() &&3205(Var->isThisDeclarationADefinition() == VarDecl::Definition ||3206OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Var));3207if (const auto *Func = dyn_cast<FunctionDecl>(D))3208return Func->doesThisDeclarationHaveABody() || PendingBodies.count(D);32093210if (auto *ES = D->getASTContext().getExternalSource())3211if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)3212return true;32133214return false;3215}32163217/// Get the correct cursor and offset for loading a declaration.3218ASTReader::RecordLocation ASTReader::DeclCursorForID(GlobalDeclID ID,3219SourceLocation &Loc) {3220ModuleFile *M = getOwningModuleFile(ID);3221assert(M);3222unsigned LocalDeclIndex = ID.getLocalDeclIndex();3223const DeclOffset &DOffs = M->DeclOffsets[LocalDeclIndex];3224Loc = ReadSourceLocation(*M, DOffs.getRawLoc());3225return RecordLocation(M, DOffs.getBitOffset(M->DeclsBlockStartOffset));3226}32273228ASTReader::RecordLocation ASTReader::getLocalBitOffset(uint64_t GlobalOffset) {3229auto I = GlobalBitOffsetsMap.find(GlobalOffset);32303231assert(I != GlobalBitOffsetsMap.end() && "Corrupted global bit offsets map");3232return RecordLocation(I->second, GlobalOffset - I->second->GlobalBitOffset);3233}32343235uint64_t ASTReader::getGlobalBitOffset(ModuleFile &M, uint64_t LocalOffset) {3236return LocalOffset + M.GlobalBitOffset;3237}32383239CXXRecordDecl *3240ASTDeclReader::getOrFakePrimaryClassDefinition(ASTReader &Reader,3241CXXRecordDecl *RD) {3242// Try to dig out the definition.3243auto *DD = RD->DefinitionData;3244if (!DD)3245DD = RD->getCanonicalDecl()->DefinitionData;32463247// If there's no definition yet, then DC's definition is added by an update3248// record, but we've not yet loaded that update record. In this case, we3249// commit to DC being the canonical definition now, and will fix this when3250// we load the update record.3251if (!DD) {3252DD = new (Reader.getContext()) struct CXXRecordDecl::DefinitionData(RD);3253RD->setCompleteDefinition(true);3254RD->DefinitionData = DD;3255RD->getCanonicalDecl()->DefinitionData = DD;32563257// Track that we did this horrible thing so that we can fix it later.3258Reader.PendingFakeDefinitionData.insert(3259std::make_pair(DD, ASTReader::PendingFakeDefinitionKind::Fake));3260}32613262return DD->Definition;3263}32643265/// Find the context in which we should search for previous declarations when3266/// looking for declarations to merge.3267DeclContext *ASTDeclReader::getPrimaryContextForMerging(ASTReader &Reader,3268DeclContext *DC) {3269if (auto *ND = dyn_cast<NamespaceDecl>(DC))3270return ND->getFirstDecl();32713272if (auto *RD = dyn_cast<CXXRecordDecl>(DC))3273return getOrFakePrimaryClassDefinition(Reader, RD);32743275if (auto *RD = dyn_cast<RecordDecl>(DC))3276return RD->getDefinition();32773278if (auto *ED = dyn_cast<EnumDecl>(DC))3279return ED->getDefinition();32803281if (auto *OID = dyn_cast<ObjCInterfaceDecl>(DC))3282return OID->getDefinition();32833284// We can see the TU here only if we have no Sema object. It is possible3285// we're in clang-repl so we still need to get the primary context.3286if (auto *TU = dyn_cast<TranslationUnitDecl>(DC))3287return TU->getPrimaryContext();32883289return nullptr;3290}32913292ASTDeclReader::FindExistingResult::~FindExistingResult() {3293// Record that we had a typedef name for linkage whether or not we merge3294// with that declaration.3295if (TypedefNameForLinkage) {3296DeclContext *DC = New->getDeclContext()->getRedeclContext();3297Reader.ImportedTypedefNamesForLinkage.insert(3298std::make_pair(std::make_pair(DC, TypedefNameForLinkage), New));3299return;3300}33013302if (!AddResult || Existing)3303return;33043305DeclarationName Name = New->getDeclName();3306DeclContext *DC = New->getDeclContext()->getRedeclContext();3307if (needsAnonymousDeclarationNumber(New)) {3308setAnonymousDeclForMerging(Reader, New->getLexicalDeclContext(),3309AnonymousDeclNumber, New);3310} else if (DC->isTranslationUnit() &&3311!Reader.getContext().getLangOpts().CPlusPlus) {3312if (Reader.getIdResolver().tryAddTopLevelDecl(New, Name))3313Reader.PendingFakeLookupResults[Name.getAsIdentifierInfo()]3314.push_back(New);3315} else if (DeclContext *MergeDC = getPrimaryContextForMerging(Reader, DC)) {3316// Add the declaration to its redeclaration context so later merging3317// lookups will find it.3318MergeDC->makeDeclVisibleInContextImpl(New, /*Internal*/true);3319}3320}33213322/// Find the declaration that should be merged into, given the declaration found3323/// by name lookup. If we're merging an anonymous declaration within a typedef,3324/// we need a matching typedef, and we merge with the type inside it.3325static NamedDecl *getDeclForMerging(NamedDecl *Found,3326bool IsTypedefNameForLinkage) {3327if (!IsTypedefNameForLinkage)3328return Found;33293330// If we found a typedef declaration that gives a name to some other3331// declaration, then we want that inner declaration. Declarations from3332// AST files are handled via ImportedTypedefNamesForLinkage.3333if (Found->isFromASTFile())3334return nullptr;33353336if (auto *TND = dyn_cast<TypedefNameDecl>(Found))3337return TND->getAnonDeclWithTypedefName(/*AnyRedecl*/true);33383339return nullptr;3340}33413342/// Find the declaration to use to populate the anonymous declaration table3343/// for the given lexical DeclContext. We only care about finding local3344/// definitions of the context; we'll merge imported ones as we go.3345DeclContext *3346ASTDeclReader::getPrimaryDCForAnonymousDecl(DeclContext *LexicalDC) {3347// For classes, we track the definition as we merge.3348if (auto *RD = dyn_cast<CXXRecordDecl>(LexicalDC)) {3349auto *DD = RD->getCanonicalDecl()->DefinitionData;3350return DD ? DD->Definition : nullptr;3351} else if (auto *OID = dyn_cast<ObjCInterfaceDecl>(LexicalDC)) {3352return OID->getCanonicalDecl()->getDefinition();3353}33543355// For anything else, walk its merged redeclarations looking for a definition.3356// Note that we can't just call getDefinition here because the redeclaration3357// chain isn't wired up.3358for (auto *D : merged_redecls(cast<Decl>(LexicalDC))) {3359if (auto *FD = dyn_cast<FunctionDecl>(D))3360if (FD->isThisDeclarationADefinition())3361return FD;3362if (auto *MD = dyn_cast<ObjCMethodDecl>(D))3363if (MD->isThisDeclarationADefinition())3364return MD;3365if (auto *RD = dyn_cast<RecordDecl>(D))3366if (RD->isThisDeclarationADefinition())3367return RD;3368}33693370// No merged definition yet.3371return nullptr;3372}33733374NamedDecl *ASTDeclReader::getAnonymousDeclForMerging(ASTReader &Reader,3375DeclContext *DC,3376unsigned Index) {3377// If the lexical context has been merged, look into the now-canonical3378// definition.3379auto *CanonDC = cast<Decl>(DC)->getCanonicalDecl();33803381// If we've seen this before, return the canonical declaration.3382auto &Previous = Reader.AnonymousDeclarationsForMerging[CanonDC];3383if (Index < Previous.size() && Previous[Index])3384return Previous[Index];33853386// If this is the first time, but we have parsed a declaration of the context,3387// build the anonymous declaration list from the parsed declaration.3388auto *PrimaryDC = getPrimaryDCForAnonymousDecl(DC);3389if (PrimaryDC && !cast<Decl>(PrimaryDC)->isFromASTFile()) {3390numberAnonymousDeclsWithin(PrimaryDC, [&](NamedDecl *ND, unsigned Number) {3391if (Previous.size() == Number)3392Previous.push_back(cast<NamedDecl>(ND->getCanonicalDecl()));3393else3394Previous[Number] = cast<NamedDecl>(ND->getCanonicalDecl());3395});3396}33973398return Index < Previous.size() ? Previous[Index] : nullptr;3399}34003401void ASTDeclReader::setAnonymousDeclForMerging(ASTReader &Reader,3402DeclContext *DC, unsigned Index,3403NamedDecl *D) {3404auto *CanonDC = cast<Decl>(DC)->getCanonicalDecl();34053406auto &Previous = Reader.AnonymousDeclarationsForMerging[CanonDC];3407if (Index >= Previous.size())3408Previous.resize(Index + 1);3409if (!Previous[Index])3410Previous[Index] = D;3411}34123413ASTDeclReader::FindExistingResult ASTDeclReader::findExisting(NamedDecl *D) {3414DeclarationName Name = TypedefNameForLinkage ? TypedefNameForLinkage3415: D->getDeclName();34163417if (!Name && !needsAnonymousDeclarationNumber(D)) {3418// Don't bother trying to find unnamed declarations that are in3419// unmergeable contexts.3420FindExistingResult Result(Reader, D, /*Existing=*/nullptr,3421AnonymousDeclNumber, TypedefNameForLinkage);3422Result.suppress();3423return Result;3424}34253426ASTContext &C = Reader.getContext();3427DeclContext *DC = D->getDeclContext()->getRedeclContext();3428if (TypedefNameForLinkage) {3429auto It = Reader.ImportedTypedefNamesForLinkage.find(3430std::make_pair(DC, TypedefNameForLinkage));3431if (It != Reader.ImportedTypedefNamesForLinkage.end())3432if (C.isSameEntity(It->second, D))3433return FindExistingResult(Reader, D, It->second, AnonymousDeclNumber,3434TypedefNameForLinkage);3435// Go on to check in other places in case an existing typedef name3436// was not imported.3437}34383439if (needsAnonymousDeclarationNumber(D)) {3440// This is an anonymous declaration that we may need to merge. Look it up3441// in its context by number.3442if (auto *Existing = getAnonymousDeclForMerging(3443Reader, D->getLexicalDeclContext(), AnonymousDeclNumber))3444if (C.isSameEntity(Existing, D))3445return FindExistingResult(Reader, D, Existing, AnonymousDeclNumber,3446TypedefNameForLinkage);3447} else if (DC->isTranslationUnit() &&3448!Reader.getContext().getLangOpts().CPlusPlus) {3449IdentifierResolver &IdResolver = Reader.getIdResolver();34503451// Temporarily consider the identifier to be up-to-date. We don't want to3452// cause additional lookups here.3453class UpToDateIdentifierRAII {3454IdentifierInfo *II;3455bool WasOutToDate = false;34563457public:3458explicit UpToDateIdentifierRAII(IdentifierInfo *II) : II(II) {3459if (II) {3460WasOutToDate = II->isOutOfDate();3461if (WasOutToDate)3462II->setOutOfDate(false);3463}3464}34653466~UpToDateIdentifierRAII() {3467if (WasOutToDate)3468II->setOutOfDate(true);3469}3470} UpToDate(Name.getAsIdentifierInfo());34713472for (IdentifierResolver::iterator I = IdResolver.begin(Name),3473IEnd = IdResolver.end();3474I != IEnd; ++I) {3475if (NamedDecl *Existing = getDeclForMerging(*I, TypedefNameForLinkage))3476if (C.isSameEntity(Existing, D))3477return FindExistingResult(Reader, D, Existing, AnonymousDeclNumber,3478TypedefNameForLinkage);3479}3480} else if (DeclContext *MergeDC = getPrimaryContextForMerging(Reader, DC)) {3481DeclContext::lookup_result R = MergeDC->noload_lookup(Name);3482for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {3483if (NamedDecl *Existing = getDeclForMerging(*I, TypedefNameForLinkage))3484if (C.isSameEntity(Existing, D))3485return FindExistingResult(Reader, D, Existing, AnonymousDeclNumber,3486TypedefNameForLinkage);3487}3488} else {3489// Not in a mergeable context.3490return FindExistingResult(Reader);3491}34923493// If this declaration is from a merged context, make a note that we need to3494// check that the canonical definition of that context contains the decl.3495//3496// Note that we don't perform ODR checks for decls from the global module3497// fragment.3498//3499// FIXME: We should do something similar if we merge two definitions of the3500// same template specialization into the same CXXRecordDecl.3501auto MergedDCIt = Reader.MergedDeclContexts.find(D->getLexicalDeclContext());3502if (MergedDCIt != Reader.MergedDeclContexts.end() &&3503!shouldSkipCheckingODR(D) && MergedDCIt->second == D->getDeclContext())3504Reader.PendingOdrMergeChecks.push_back(D);35053506return FindExistingResult(Reader, D, /*Existing=*/nullptr,3507AnonymousDeclNumber, TypedefNameForLinkage);3508}35093510template<typename DeclT>3511Decl *ASTDeclReader::getMostRecentDeclImpl(Redeclarable<DeclT> *D) {3512return D->RedeclLink.getLatestNotUpdated();3513}35143515Decl *ASTDeclReader::getMostRecentDeclImpl(...) {3516llvm_unreachable("getMostRecentDecl on non-redeclarable declaration");3517}35183519Decl *ASTDeclReader::getMostRecentDecl(Decl *D) {3520assert(D);35213522switch (D->getKind()) {3523#define ABSTRACT_DECL(TYPE)3524#define DECL(TYPE, BASE) \3525case Decl::TYPE: \3526return getMostRecentDeclImpl(cast<TYPE##Decl>(D));3527#include "clang/AST/DeclNodes.inc"3528}3529llvm_unreachable("unknown decl kind");3530}35313532Decl *ASTReader::getMostRecentExistingDecl(Decl *D) {3533return ASTDeclReader::getMostRecentDecl(D->getCanonicalDecl());3534}35353536void ASTDeclReader::mergeInheritableAttributes(ASTReader &Reader, Decl *D,3537Decl *Previous) {3538InheritableAttr *NewAttr = nullptr;3539ASTContext &Context = Reader.getContext();3540const auto *IA = Previous->getAttr<MSInheritanceAttr>();35413542if (IA && !D->hasAttr<MSInheritanceAttr>()) {3543NewAttr = cast<InheritableAttr>(IA->clone(Context));3544NewAttr->setInherited(true);3545D->addAttr(NewAttr);3546}35473548const auto *AA = Previous->getAttr<AvailabilityAttr>();3549if (AA && !D->hasAttr<AvailabilityAttr>()) {3550NewAttr = AA->clone(Context);3551NewAttr->setInherited(true);3552D->addAttr(NewAttr);3553}3554}35553556template<typename DeclT>3557void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader,3558Redeclarable<DeclT> *D,3559Decl *Previous, Decl *Canon) {3560D->RedeclLink.setPrevious(cast<DeclT>(Previous));3561D->First = cast<DeclT>(Previous)->First;3562}35633564namespace clang {35653566template<>3567void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader,3568Redeclarable<VarDecl> *D,3569Decl *Previous, Decl *Canon) {3570auto *VD = static_cast<VarDecl *>(D);3571auto *PrevVD = cast<VarDecl>(Previous);3572D->RedeclLink.setPrevious(PrevVD);3573D->First = PrevVD->First;35743575// We should keep at most one definition on the chain.3576// FIXME: Cache the definition once we've found it. Building a chain with3577// N definitions currently takes O(N^2) time here.3578if (VD->isThisDeclarationADefinition() == VarDecl::Definition) {3579for (VarDecl *CurD = PrevVD; CurD; CurD = CurD->getPreviousDecl()) {3580if (CurD->isThisDeclarationADefinition() == VarDecl::Definition) {3581Reader.mergeDefinitionVisibility(CurD, VD);3582VD->demoteThisDefinitionToDeclaration();3583break;3584}3585}3586}3587}35883589static bool isUndeducedReturnType(QualType T) {3590auto *DT = T->getContainedDeducedType();3591return DT && !DT->isDeduced();3592}35933594template<>3595void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader,3596Redeclarable<FunctionDecl> *D,3597Decl *Previous, Decl *Canon) {3598auto *FD = static_cast<FunctionDecl *>(D);3599auto *PrevFD = cast<FunctionDecl>(Previous);36003601FD->RedeclLink.setPrevious(PrevFD);3602FD->First = PrevFD->First;36033604// If the previous declaration is an inline function declaration, then this3605// declaration is too.3606if (PrevFD->isInlined() != FD->isInlined()) {3607// FIXME: [dcl.fct.spec]p4:3608// If a function with external linkage is declared inline in one3609// translation unit, it shall be declared inline in all translation3610// units in which it appears.3611//3612// Be careful of this case:3613//3614// module A:3615// template<typename T> struct X { void f(); };3616// template<typename T> inline void X<T>::f() {}3617//3618// module B instantiates the declaration of X<int>::f3619// module C instantiates the definition of X<int>::f3620//3621// If module B and C are merged, we do not have a violation of this rule.3622FD->setImplicitlyInline(true);3623}36243625auto *FPT = FD->getType()->getAs<FunctionProtoType>();3626auto *PrevFPT = PrevFD->getType()->getAs<FunctionProtoType>();3627if (FPT && PrevFPT) {3628// If we need to propagate an exception specification along the redecl3629// chain, make a note of that so that we can do so later.3630bool IsUnresolved = isUnresolvedExceptionSpec(FPT->getExceptionSpecType());3631bool WasUnresolved =3632isUnresolvedExceptionSpec(PrevFPT->getExceptionSpecType());3633if (IsUnresolved != WasUnresolved)3634Reader.PendingExceptionSpecUpdates.insert(3635{Canon, IsUnresolved ? PrevFD : FD});36363637// If we need to propagate a deduced return type along the redecl chain,3638// make a note of that so that we can do it later.3639bool IsUndeduced = isUndeducedReturnType(FPT->getReturnType());3640bool WasUndeduced = isUndeducedReturnType(PrevFPT->getReturnType());3641if (IsUndeduced != WasUndeduced)3642Reader.PendingDeducedTypeUpdates.insert(3643{cast<FunctionDecl>(Canon),3644(IsUndeduced ? PrevFPT : FPT)->getReturnType()});3645}3646}36473648} // namespace clang36493650void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader, ...) {3651llvm_unreachable("attachPreviousDecl on non-redeclarable declaration");3652}36533654/// Inherit the default template argument from \p From to \p To. Returns3655/// \c false if there is no default template for \p From.3656template <typename ParmDecl>3657static bool inheritDefaultTemplateArgument(ASTContext &Context, ParmDecl *From,3658Decl *ToD) {3659auto *To = cast<ParmDecl>(ToD);3660if (!From->hasDefaultArgument())3661return false;3662To->setInheritedDefaultArgument(Context, From);3663return true;3664}36653666static void inheritDefaultTemplateArguments(ASTContext &Context,3667TemplateDecl *From,3668TemplateDecl *To) {3669auto *FromTP = From->getTemplateParameters();3670auto *ToTP = To->getTemplateParameters();3671assert(FromTP->size() == ToTP->size() && "merged mismatched templates?");36723673for (unsigned I = 0, N = FromTP->size(); I != N; ++I) {3674NamedDecl *FromParam = FromTP->getParam(I);3675NamedDecl *ToParam = ToTP->getParam(I);36763677if (auto *FTTP = dyn_cast<TemplateTypeParmDecl>(FromParam))3678inheritDefaultTemplateArgument(Context, FTTP, ToParam);3679else if (auto *FNTTP = dyn_cast<NonTypeTemplateParmDecl>(FromParam))3680inheritDefaultTemplateArgument(Context, FNTTP, ToParam);3681else3682inheritDefaultTemplateArgument(3683Context, cast<TemplateTemplateParmDecl>(FromParam), ToParam);3684}3685}36863687// [basic.link]/p10:3688// If two declarations of an entity are attached to different modules,3689// the program is ill-formed;3690static void checkMultipleDefinitionInNamedModules(ASTReader &Reader, Decl *D,3691Decl *Previous) {3692Module *M = Previous->getOwningModule();36933694// We only care about the case in named modules.3695if (!M || !M->isNamedModule())3696return;36973698// If it is previous implcitly introduced, it is not meaningful to3699// diagnose it.3700if (Previous->isImplicit())3701return;37023703// FIXME: Get rid of the enumeration of decl types once we have an appropriate3704// abstract for decls of an entity. e.g., the namespace decl and using decl3705// doesn't introduce an entity.3706if (!isa<VarDecl, FunctionDecl, TagDecl, RedeclarableTemplateDecl>(Previous))3707return;37083709// Skip implicit instantiations since it may give false positive diagnostic3710// messages.3711// FIXME: Maybe this shows the implicit instantiations may have incorrect3712// module owner ships. But given we've finished the compilation of a module,3713// how can we add new entities to that module?3714if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Previous);3715VTSD && !VTSD->isExplicitSpecialization())3716return;3717if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Previous);3718CTSD && !CTSD->isExplicitSpecialization())3719return;3720if (auto *Func = dyn_cast<FunctionDecl>(Previous))3721if (auto *FTSI = Func->getTemplateSpecializationInfo();3722FTSI && !FTSI->isExplicitSpecialization())3723return;37243725// It is fine if they are in the same module.3726if (Reader.getContext().isInSameModule(M, D->getOwningModule()))3727return;37283729Reader.Diag(Previous->getLocation(),3730diag::err_multiple_decl_in_different_modules)3731<< cast<NamedDecl>(Previous) << M->Name;3732Reader.Diag(D->getLocation(), diag::note_also_found);3733}37343735void ASTDeclReader::attachPreviousDecl(ASTReader &Reader, Decl *D,3736Decl *Previous, Decl *Canon) {3737assert(D && Previous);37383739switch (D->getKind()) {3740#define ABSTRACT_DECL(TYPE)3741#define DECL(TYPE, BASE) \3742case Decl::TYPE: \3743attachPreviousDeclImpl(Reader, cast<TYPE##Decl>(D), Previous, Canon); \3744break;3745#include "clang/AST/DeclNodes.inc"3746}37473748checkMultipleDefinitionInNamedModules(Reader, D, Previous);37493750// If the declaration was visible in one module, a redeclaration of it in3751// another module remains visible even if it wouldn't be visible by itself.3752//3753// FIXME: In this case, the declaration should only be visible if a module3754// that makes it visible has been imported.3755D->IdentifierNamespace |=3756Previous->IdentifierNamespace &3757(Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Type);37583759// If the declaration declares a template, it may inherit default arguments3760// from the previous declaration.3761if (auto *TD = dyn_cast<TemplateDecl>(D))3762inheritDefaultTemplateArguments(Reader.getContext(),3763cast<TemplateDecl>(Previous), TD);37643765// If any of the declaration in the chain contains an Inheritable attribute,3766// it needs to be added to all the declarations in the redeclarable chain.3767// FIXME: Only the logic of merging MSInheritableAttr is present, it should3768// be extended for all inheritable attributes.3769mergeInheritableAttributes(Reader, D, Previous);3770}37713772template<typename DeclT>3773void ASTDeclReader::attachLatestDeclImpl(Redeclarable<DeclT> *D, Decl *Latest) {3774D->RedeclLink.setLatest(cast<DeclT>(Latest));3775}37763777void ASTDeclReader::attachLatestDeclImpl(...) {3778llvm_unreachable("attachLatestDecl on non-redeclarable declaration");3779}37803781void ASTDeclReader::attachLatestDecl(Decl *D, Decl *Latest) {3782assert(D && Latest);37833784switch (D->getKind()) {3785#define ABSTRACT_DECL(TYPE)3786#define DECL(TYPE, BASE) \3787case Decl::TYPE: \3788attachLatestDeclImpl(cast<TYPE##Decl>(D), Latest); \3789break;3790#include "clang/AST/DeclNodes.inc"3791}3792}37933794template<typename DeclT>3795void ASTDeclReader::markIncompleteDeclChainImpl(Redeclarable<DeclT> *D) {3796D->RedeclLink.markIncomplete();3797}37983799void ASTDeclReader::markIncompleteDeclChainImpl(...) {3800llvm_unreachable("markIncompleteDeclChain on non-redeclarable declaration");3801}38023803void ASTReader::markIncompleteDeclChain(Decl *D) {3804switch (D->getKind()) {3805#define ABSTRACT_DECL(TYPE)3806#define DECL(TYPE, BASE) \3807case Decl::TYPE: \3808ASTDeclReader::markIncompleteDeclChainImpl(cast<TYPE##Decl>(D)); \3809break;3810#include "clang/AST/DeclNodes.inc"3811}3812}38133814/// Read the declaration at the given offset from the AST file.3815Decl *ASTReader::ReadDeclRecord(GlobalDeclID ID) {3816SourceLocation DeclLoc;3817RecordLocation Loc = DeclCursorForID(ID, DeclLoc);3818llvm::BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;3819// Keep track of where we are in the stream, then jump back there3820// after reading this declaration.3821SavedStreamPosition SavedPosition(DeclsCursor);38223823ReadingKindTracker ReadingKind(Read_Decl, *this);38243825// Note that we are loading a declaration record.3826Deserializing ADecl(this);38273828auto Fail = [](const char *what, llvm::Error &&Err) {3829llvm::report_fatal_error(Twine("ASTReader::readDeclRecord failed ") + what +3830": " + toString(std::move(Err)));3831};38323833if (llvm::Error JumpFailed = DeclsCursor.JumpToBit(Loc.Offset))3834Fail("jumping", std::move(JumpFailed));3835ASTRecordReader Record(*this, *Loc.F);3836ASTDeclReader Reader(*this, Record, Loc, ID, DeclLoc);3837Expected<unsigned> MaybeCode = DeclsCursor.ReadCode();3838if (!MaybeCode)3839Fail("reading code", MaybeCode.takeError());3840unsigned Code = MaybeCode.get();38413842ASTContext &Context = getContext();3843Decl *D = nullptr;3844Expected<unsigned> MaybeDeclCode = Record.readRecord(DeclsCursor, Code);3845if (!MaybeDeclCode)3846llvm::report_fatal_error(3847Twine("ASTReader::readDeclRecord failed reading decl code: ") +3848toString(MaybeDeclCode.takeError()));38493850switch ((DeclCode)MaybeDeclCode.get()) {3851case DECL_CONTEXT_LEXICAL:3852case DECL_CONTEXT_VISIBLE:3853llvm_unreachable("Record cannot be de-serialized with readDeclRecord");3854case DECL_TYPEDEF:3855D = TypedefDecl::CreateDeserialized(Context, ID);3856break;3857case DECL_TYPEALIAS:3858D = TypeAliasDecl::CreateDeserialized(Context, ID);3859break;3860case DECL_ENUM:3861D = EnumDecl::CreateDeserialized(Context, ID);3862break;3863case DECL_RECORD:3864D = RecordDecl::CreateDeserialized(Context, ID);3865break;3866case DECL_ENUM_CONSTANT:3867D = EnumConstantDecl::CreateDeserialized(Context, ID);3868break;3869case DECL_FUNCTION:3870D = FunctionDecl::CreateDeserialized(Context, ID);3871break;3872case DECL_LINKAGE_SPEC:3873D = LinkageSpecDecl::CreateDeserialized(Context, ID);3874break;3875case DECL_EXPORT:3876D = ExportDecl::CreateDeserialized(Context, ID);3877break;3878case DECL_LABEL:3879D = LabelDecl::CreateDeserialized(Context, ID);3880break;3881case DECL_NAMESPACE:3882D = NamespaceDecl::CreateDeserialized(Context, ID);3883break;3884case DECL_NAMESPACE_ALIAS:3885D = NamespaceAliasDecl::CreateDeserialized(Context, ID);3886break;3887case DECL_USING:3888D = UsingDecl::CreateDeserialized(Context, ID);3889break;3890case DECL_USING_PACK:3891D = UsingPackDecl::CreateDeserialized(Context, ID, Record.readInt());3892break;3893case DECL_USING_SHADOW:3894D = UsingShadowDecl::CreateDeserialized(Context, ID);3895break;3896case DECL_USING_ENUM:3897D = UsingEnumDecl::CreateDeserialized(Context, ID);3898break;3899case DECL_CONSTRUCTOR_USING_SHADOW:3900D = ConstructorUsingShadowDecl::CreateDeserialized(Context, ID);3901break;3902case DECL_USING_DIRECTIVE:3903D = UsingDirectiveDecl::CreateDeserialized(Context, ID);3904break;3905case DECL_UNRESOLVED_USING_VALUE:3906D = UnresolvedUsingValueDecl::CreateDeserialized(Context, ID);3907break;3908case DECL_UNRESOLVED_USING_TYPENAME:3909D = UnresolvedUsingTypenameDecl::CreateDeserialized(Context, ID);3910break;3911case DECL_UNRESOLVED_USING_IF_EXISTS:3912D = UnresolvedUsingIfExistsDecl::CreateDeserialized(Context, ID);3913break;3914case DECL_CXX_RECORD:3915D = CXXRecordDecl::CreateDeserialized(Context, ID);3916break;3917case DECL_CXX_DEDUCTION_GUIDE:3918D = CXXDeductionGuideDecl::CreateDeserialized(Context, ID);3919break;3920case DECL_CXX_METHOD:3921D = CXXMethodDecl::CreateDeserialized(Context, ID);3922break;3923case DECL_CXX_CONSTRUCTOR:3924D = CXXConstructorDecl::CreateDeserialized(Context, ID, Record.readInt());3925break;3926case DECL_CXX_DESTRUCTOR:3927D = CXXDestructorDecl::CreateDeserialized(Context, ID);3928break;3929case DECL_CXX_CONVERSION:3930D = CXXConversionDecl::CreateDeserialized(Context, ID);3931break;3932case DECL_ACCESS_SPEC:3933D = AccessSpecDecl::CreateDeserialized(Context, ID);3934break;3935case DECL_FRIEND:3936D = FriendDecl::CreateDeserialized(Context, ID, Record.readInt());3937break;3938case DECL_FRIEND_TEMPLATE:3939D = FriendTemplateDecl::CreateDeserialized(Context, ID);3940break;3941case DECL_CLASS_TEMPLATE:3942D = ClassTemplateDecl::CreateDeserialized(Context, ID);3943break;3944case DECL_CLASS_TEMPLATE_SPECIALIZATION:3945D = ClassTemplateSpecializationDecl::CreateDeserialized(Context, ID);3946break;3947case DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION:3948D = ClassTemplatePartialSpecializationDecl::CreateDeserialized(Context, ID);3949break;3950case DECL_VAR_TEMPLATE:3951D = VarTemplateDecl::CreateDeserialized(Context, ID);3952break;3953case DECL_VAR_TEMPLATE_SPECIALIZATION:3954D = VarTemplateSpecializationDecl::CreateDeserialized(Context, ID);3955break;3956case DECL_VAR_TEMPLATE_PARTIAL_SPECIALIZATION:3957D = VarTemplatePartialSpecializationDecl::CreateDeserialized(Context, ID);3958break;3959case DECL_FUNCTION_TEMPLATE:3960D = FunctionTemplateDecl::CreateDeserialized(Context, ID);3961break;3962case DECL_TEMPLATE_TYPE_PARM: {3963bool HasTypeConstraint = Record.readInt();3964D = TemplateTypeParmDecl::CreateDeserialized(Context, ID,3965HasTypeConstraint);3966break;3967}3968case DECL_NON_TYPE_TEMPLATE_PARM: {3969bool HasTypeConstraint = Record.readInt();3970D = NonTypeTemplateParmDecl::CreateDeserialized(Context, ID,3971HasTypeConstraint);3972break;3973}3974case DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK: {3975bool HasTypeConstraint = Record.readInt();3976D = NonTypeTemplateParmDecl::CreateDeserialized(3977Context, ID, Record.readInt(), HasTypeConstraint);3978break;3979}3980case DECL_TEMPLATE_TEMPLATE_PARM:3981D = TemplateTemplateParmDecl::CreateDeserialized(Context, ID);3982break;3983case DECL_EXPANDED_TEMPLATE_TEMPLATE_PARM_PACK:3984D = TemplateTemplateParmDecl::CreateDeserialized(Context, ID,3985Record.readInt());3986break;3987case DECL_TYPE_ALIAS_TEMPLATE:3988D = TypeAliasTemplateDecl::CreateDeserialized(Context, ID);3989break;3990case DECL_CONCEPT:3991D = ConceptDecl::CreateDeserialized(Context, ID);3992break;3993case DECL_REQUIRES_EXPR_BODY:3994D = RequiresExprBodyDecl::CreateDeserialized(Context, ID);3995break;3996case DECL_STATIC_ASSERT:3997D = StaticAssertDecl::CreateDeserialized(Context, ID);3998break;3999case DECL_OBJC_METHOD:4000D = ObjCMethodDecl::CreateDeserialized(Context, ID);4001break;4002case DECL_OBJC_INTERFACE:4003D = ObjCInterfaceDecl::CreateDeserialized(Context, ID);4004break;4005case DECL_OBJC_IVAR:4006D = ObjCIvarDecl::CreateDeserialized(Context, ID);4007break;4008case DECL_OBJC_PROTOCOL:4009D = ObjCProtocolDecl::CreateDeserialized(Context, ID);4010break;4011case DECL_OBJC_AT_DEFS_FIELD:4012D = ObjCAtDefsFieldDecl::CreateDeserialized(Context, ID);4013break;4014case DECL_OBJC_CATEGORY:4015D = ObjCCategoryDecl::CreateDeserialized(Context, ID);4016break;4017case DECL_OBJC_CATEGORY_IMPL:4018D = ObjCCategoryImplDecl::CreateDeserialized(Context, ID);4019break;4020case DECL_OBJC_IMPLEMENTATION:4021D = ObjCImplementationDecl::CreateDeserialized(Context, ID);4022break;4023case DECL_OBJC_COMPATIBLE_ALIAS:4024D = ObjCCompatibleAliasDecl::CreateDeserialized(Context, ID);4025break;4026case DECL_OBJC_PROPERTY:4027D = ObjCPropertyDecl::CreateDeserialized(Context, ID);4028break;4029case DECL_OBJC_PROPERTY_IMPL:4030D = ObjCPropertyImplDecl::CreateDeserialized(Context, ID);4031break;4032case DECL_FIELD:4033D = FieldDecl::CreateDeserialized(Context, ID);4034break;4035case DECL_INDIRECTFIELD:4036D = IndirectFieldDecl::CreateDeserialized(Context, ID);4037break;4038case DECL_VAR:4039D = VarDecl::CreateDeserialized(Context, ID);4040break;4041case DECL_IMPLICIT_PARAM:4042D = ImplicitParamDecl::CreateDeserialized(Context, ID);4043break;4044case DECL_PARM_VAR:4045D = ParmVarDecl::CreateDeserialized(Context, ID);4046break;4047case DECL_DECOMPOSITION:4048D = DecompositionDecl::CreateDeserialized(Context, ID, Record.readInt());4049break;4050case DECL_BINDING:4051D = BindingDecl::CreateDeserialized(Context, ID);4052break;4053case DECL_FILE_SCOPE_ASM:4054D = FileScopeAsmDecl::CreateDeserialized(Context, ID);4055break;4056case DECL_TOP_LEVEL_STMT_DECL:4057D = TopLevelStmtDecl::CreateDeserialized(Context, ID);4058break;4059case DECL_BLOCK:4060D = BlockDecl::CreateDeserialized(Context, ID);4061break;4062case DECL_MS_PROPERTY:4063D = MSPropertyDecl::CreateDeserialized(Context, ID);4064break;4065case DECL_MS_GUID:4066D = MSGuidDecl::CreateDeserialized(Context, ID);4067break;4068case DECL_UNNAMED_GLOBAL_CONSTANT:4069D = UnnamedGlobalConstantDecl::CreateDeserialized(Context, ID);4070break;4071case DECL_TEMPLATE_PARAM_OBJECT:4072D = TemplateParamObjectDecl::CreateDeserialized(Context, ID);4073break;4074case DECL_CAPTURED:4075D = CapturedDecl::CreateDeserialized(Context, ID, Record.readInt());4076break;4077case DECL_CXX_BASE_SPECIFIERS:4078Error("attempt to read a C++ base-specifier record as a declaration");4079return nullptr;4080case DECL_CXX_CTOR_INITIALIZERS:4081Error("attempt to read a C++ ctor initializer record as a declaration");4082return nullptr;4083case DECL_IMPORT:4084// Note: last entry of the ImportDecl record is the number of stored source4085// locations.4086D = ImportDecl::CreateDeserialized(Context, ID, Record.back());4087break;4088case DECL_OMP_THREADPRIVATE: {4089Record.skipInts(1);4090unsigned NumChildren = Record.readInt();4091Record.skipInts(1);4092D = OMPThreadPrivateDecl::CreateDeserialized(Context, ID, NumChildren);4093break;4094}4095case DECL_OMP_ALLOCATE: {4096unsigned NumClauses = Record.readInt();4097unsigned NumVars = Record.readInt();4098Record.skipInts(1);4099D = OMPAllocateDecl::CreateDeserialized(Context, ID, NumVars, NumClauses);4100break;4101}4102case DECL_OMP_REQUIRES: {4103unsigned NumClauses = Record.readInt();4104Record.skipInts(2);4105D = OMPRequiresDecl::CreateDeserialized(Context, ID, NumClauses);4106break;4107}4108case DECL_OMP_DECLARE_REDUCTION:4109D = OMPDeclareReductionDecl::CreateDeserialized(Context, ID);4110break;4111case DECL_OMP_DECLARE_MAPPER: {4112unsigned NumClauses = Record.readInt();4113Record.skipInts(2);4114D = OMPDeclareMapperDecl::CreateDeserialized(Context, ID, NumClauses);4115break;4116}4117case DECL_OMP_CAPTUREDEXPR:4118D = OMPCapturedExprDecl::CreateDeserialized(Context, ID);4119break;4120case DECL_PRAGMA_COMMENT:4121D = PragmaCommentDecl::CreateDeserialized(Context, ID, Record.readInt());4122break;4123case DECL_PRAGMA_DETECT_MISMATCH:4124D = PragmaDetectMismatchDecl::CreateDeserialized(Context, ID,4125Record.readInt());4126break;4127case DECL_EMPTY:4128D = EmptyDecl::CreateDeserialized(Context, ID);4129break;4130case DECL_LIFETIME_EXTENDED_TEMPORARY:4131D = LifetimeExtendedTemporaryDecl::CreateDeserialized(Context, ID);4132break;4133case DECL_OBJC_TYPE_PARAM:4134D = ObjCTypeParamDecl::CreateDeserialized(Context, ID);4135break;4136case DECL_HLSL_BUFFER:4137D = HLSLBufferDecl::CreateDeserialized(Context, ID);4138break;4139case DECL_IMPLICIT_CONCEPT_SPECIALIZATION:4140D = ImplicitConceptSpecializationDecl::CreateDeserialized(Context, ID,4141Record.readInt());4142break;4143}41444145assert(D && "Unknown declaration reading AST file");4146LoadedDecl(translateGlobalDeclIDToIndex(ID), D);4147// Set the DeclContext before doing any deserialization, to make sure internal4148// calls to Decl::getASTContext() by Decl's methods will find the4149// TranslationUnitDecl without crashing.4150D->setDeclContext(Context.getTranslationUnitDecl());41514152// Reading some declarations can result in deep recursion.4153clang::runWithSufficientStackSpace([&] { warnStackExhausted(DeclLoc); },4154[&] { Reader.Visit(D); });41554156// If this declaration is also a declaration context, get the4157// offsets for its tables of lexical and visible declarations.4158if (auto *DC = dyn_cast<DeclContext>(D)) {4159std::pair<uint64_t, uint64_t> Offsets = Reader.VisitDeclContext(DC);41604161// Get the lexical and visible block for the delayed namespace.4162// It is sufficient to judge if ID is in DelayedNamespaceOffsetMap.4163// But it may be more efficient to filter the other cases.4164if (!Offsets.first && !Offsets.second && isa<NamespaceDecl>(D))4165if (auto Iter = DelayedNamespaceOffsetMap.find(ID);4166Iter != DelayedNamespaceOffsetMap.end())4167Offsets = Iter->second;41684169if (Offsets.first &&4170ReadLexicalDeclContextStorage(*Loc.F, DeclsCursor, Offsets.first, DC))4171return nullptr;4172if (Offsets.second &&4173ReadVisibleDeclContextStorage(*Loc.F, DeclsCursor, Offsets.second, ID))4174return nullptr;4175}4176assert(Record.getIdx() == Record.size());41774178// Load any relevant update records.4179PendingUpdateRecords.push_back(4180PendingUpdateRecord(ID, D, /*JustLoaded=*/true));41814182// Load the categories after recursive loading is finished.4183if (auto *Class = dyn_cast<ObjCInterfaceDecl>(D))4184// If we already have a definition when deserializing the ObjCInterfaceDecl,4185// we put the Decl in PendingDefinitions so we can pull the categories here.4186if (Class->isThisDeclarationADefinition() ||4187PendingDefinitions.count(Class))4188loadObjCCategories(ID, Class);41894190// If we have deserialized a declaration that has a definition the4191// AST consumer might need to know about, queue it.4192// We don't pass it to the consumer immediately because we may be in recursive4193// loading, and some declarations may still be initializing.4194PotentiallyInterestingDecls.push_back(D);41954196return D;4197}41984199void ASTReader::PassInterestingDeclsToConsumer() {4200assert(Consumer);42014202if (PassingDeclsToConsumer)4203return;42044205// Guard variable to avoid recursively redoing the process of passing4206// decls to consumer.4207SaveAndRestore GuardPassingDeclsToConsumer(PassingDeclsToConsumer, true);42084209// Ensure that we've loaded all potentially-interesting declarations4210// that need to be eagerly loaded.4211for (auto ID : EagerlyDeserializedDecls)4212GetDecl(ID);4213EagerlyDeserializedDecls.clear();42144215auto ConsumingPotentialInterestingDecls = [this]() {4216while (!PotentiallyInterestingDecls.empty()) {4217Decl *D = PotentiallyInterestingDecls.front();4218PotentiallyInterestingDecls.pop_front();4219if (isConsumerInterestedIn(D))4220PassInterestingDeclToConsumer(D);4221}4222};4223std::deque<Decl *> MaybeInterestingDecls =4224std::move(PotentiallyInterestingDecls);4225PotentiallyInterestingDecls.clear();4226assert(PotentiallyInterestingDecls.empty());4227while (!MaybeInterestingDecls.empty()) {4228Decl *D = MaybeInterestingDecls.front();4229MaybeInterestingDecls.pop_front();4230// Since we load the variable's initializers lazily, it'd be problematic4231// if the initializers dependent on each other. So here we try to load the4232// initializers of static variables to make sure they are passed to code4233// generator by order. If we read anything interesting, we would consume4234// that before emitting the current declaration.4235if (auto *VD = dyn_cast<VarDecl>(D);4236VD && VD->isFileVarDecl() && !VD->isExternallyVisible())4237VD->getInit();4238ConsumingPotentialInterestingDecls();4239if (isConsumerInterestedIn(D))4240PassInterestingDeclToConsumer(D);4241}42424243// If we add any new potential interesting decl in the last call, consume it.4244ConsumingPotentialInterestingDecls();42454246for (GlobalDeclID ID : VTablesToEmit) {4247auto *RD = cast<CXXRecordDecl>(GetDecl(ID));4248assert(!RD->shouldEmitInExternalSource());4249PassVTableToConsumer(RD);4250}4251VTablesToEmit.clear();4252}42534254void ASTReader::loadDeclUpdateRecords(PendingUpdateRecord &Record) {4255// The declaration may have been modified by files later in the chain.4256// If this is the case, read the record containing the updates from each file4257// and pass it to ASTDeclReader to make the modifications.4258GlobalDeclID ID = Record.ID;4259Decl *D = Record.D;4260ProcessingUpdatesRAIIObj ProcessingUpdates(*this);4261DeclUpdateOffsetsMap::iterator UpdI = DeclUpdateOffsets.find(ID);42624263SmallVector<GlobalDeclID, 8> PendingLazySpecializationIDs;42644265if (UpdI != DeclUpdateOffsets.end()) {4266auto UpdateOffsets = std::move(UpdI->second);4267DeclUpdateOffsets.erase(UpdI);42684269// Check if this decl was interesting to the consumer. If we just loaded4270// the declaration, then we know it was interesting and we skip the call4271// to isConsumerInterestedIn because it is unsafe to call in the4272// current ASTReader state.4273bool WasInteresting = Record.JustLoaded || isConsumerInterestedIn(D);4274for (auto &FileAndOffset : UpdateOffsets) {4275ModuleFile *F = FileAndOffset.first;4276uint64_t Offset = FileAndOffset.second;4277llvm::BitstreamCursor &Cursor = F->DeclsCursor;4278SavedStreamPosition SavedPosition(Cursor);4279if (llvm::Error JumpFailed = Cursor.JumpToBit(Offset))4280// FIXME don't do a fatal error.4281llvm::report_fatal_error(4282Twine("ASTReader::loadDeclUpdateRecords failed jumping: ") +4283toString(std::move(JumpFailed)));4284Expected<unsigned> MaybeCode = Cursor.ReadCode();4285if (!MaybeCode)4286llvm::report_fatal_error(4287Twine("ASTReader::loadDeclUpdateRecords failed reading code: ") +4288toString(MaybeCode.takeError()));4289unsigned Code = MaybeCode.get();4290ASTRecordReader Record(*this, *F);4291if (Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code))4292assert(MaybeRecCode.get() == DECL_UPDATES &&4293"Expected DECL_UPDATES record!");4294else4295llvm::report_fatal_error(4296Twine("ASTReader::loadDeclUpdateRecords failed reading rec code: ") +4297toString(MaybeCode.takeError()));42984299ASTDeclReader Reader(*this, Record, RecordLocation(F, Offset), ID,4300SourceLocation());4301Reader.UpdateDecl(D, PendingLazySpecializationIDs);43024303// We might have made this declaration interesting. If so, remember that4304// we need to hand it off to the consumer.4305if (!WasInteresting && isConsumerInterestedIn(D)) {4306PotentiallyInterestingDecls.push_back(D);4307WasInteresting = true;4308}4309}4310}4311// Add the lazy specializations to the template.4312assert((PendingLazySpecializationIDs.empty() || isa<ClassTemplateDecl>(D) ||4313isa<FunctionTemplateDecl, VarTemplateDecl>(D)) &&4314"Must not have pending specializations");4315if (auto *CTD = dyn_cast<ClassTemplateDecl>(D))4316ASTDeclReader::AddLazySpecializations(CTD, PendingLazySpecializationIDs);4317else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D))4318ASTDeclReader::AddLazySpecializations(FTD, PendingLazySpecializationIDs);4319else if (auto *VTD = dyn_cast<VarTemplateDecl>(D))4320ASTDeclReader::AddLazySpecializations(VTD, PendingLazySpecializationIDs);4321PendingLazySpecializationIDs.clear();43224323// Load the pending visible updates for this decl context, if it has any.4324auto I = PendingVisibleUpdates.find(ID);4325if (I != PendingVisibleUpdates.end()) {4326auto VisibleUpdates = std::move(I->second);4327PendingVisibleUpdates.erase(I);43284329auto *DC = cast<DeclContext>(D)->getPrimaryContext();4330for (const auto &Update : VisibleUpdates)4331Lookups[DC].Table.add(4332Update.Mod, Update.Data,4333reader::ASTDeclContextNameLookupTrait(*this, *Update.Mod));4334DC->setHasExternalVisibleStorage(true);4335}4336}43374338void ASTReader::loadPendingDeclChain(Decl *FirstLocal, uint64_t LocalOffset) {4339// Attach FirstLocal to the end of the decl chain.4340Decl *CanonDecl = FirstLocal->getCanonicalDecl();4341if (FirstLocal != CanonDecl) {4342Decl *PrevMostRecent = ASTDeclReader::getMostRecentDecl(CanonDecl);4343ASTDeclReader::attachPreviousDecl(4344*this, FirstLocal, PrevMostRecent ? PrevMostRecent : CanonDecl,4345CanonDecl);4346}43474348if (!LocalOffset) {4349ASTDeclReader::attachLatestDecl(CanonDecl, FirstLocal);4350return;4351}43524353// Load the list of other redeclarations from this module file.4354ModuleFile *M = getOwningModuleFile(FirstLocal);4355assert(M && "imported decl from no module file");43564357llvm::BitstreamCursor &Cursor = M->DeclsCursor;4358SavedStreamPosition SavedPosition(Cursor);4359if (llvm::Error JumpFailed = Cursor.JumpToBit(LocalOffset))4360llvm::report_fatal_error(4361Twine("ASTReader::loadPendingDeclChain failed jumping: ") +4362toString(std::move(JumpFailed)));43634364RecordData Record;4365Expected<unsigned> MaybeCode = Cursor.ReadCode();4366if (!MaybeCode)4367llvm::report_fatal_error(4368Twine("ASTReader::loadPendingDeclChain failed reading code: ") +4369toString(MaybeCode.takeError()));4370unsigned Code = MaybeCode.get();4371if (Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record))4372assert(MaybeRecCode.get() == LOCAL_REDECLARATIONS &&4373"expected LOCAL_REDECLARATIONS record!");4374else4375llvm::report_fatal_error(4376Twine("ASTReader::loadPendingDeclChain failed reading rec code: ") +4377toString(MaybeCode.takeError()));43784379// FIXME: We have several different dispatches on decl kind here; maybe4380// we should instead generate one loop per kind and dispatch up-front?4381Decl *MostRecent = FirstLocal;4382for (unsigned I = 0, N = Record.size(); I != N; ++I) {4383unsigned Idx = N - I - 1;4384auto *D = ReadDecl(*M, Record, Idx);4385ASTDeclReader::attachPreviousDecl(*this, D, MostRecent, CanonDecl);4386MostRecent = D;4387}4388ASTDeclReader::attachLatestDecl(CanonDecl, MostRecent);4389}43904391namespace {43924393/// Given an ObjC interface, goes through the modules and links to the4394/// interface all the categories for it.4395class ObjCCategoriesVisitor {4396ASTReader &Reader;4397ObjCInterfaceDecl *Interface;4398llvm::SmallPtrSetImpl<ObjCCategoryDecl *> &Deserialized;4399ObjCCategoryDecl *Tail = nullptr;4400llvm::DenseMap<DeclarationName, ObjCCategoryDecl *> NameCategoryMap;4401GlobalDeclID InterfaceID;4402unsigned PreviousGeneration;44034404void add(ObjCCategoryDecl *Cat) {4405// Only process each category once.4406if (!Deserialized.erase(Cat))4407return;44084409// Check for duplicate categories.4410if (Cat->getDeclName()) {4411ObjCCategoryDecl *&Existing = NameCategoryMap[Cat->getDeclName()];4412if (Existing && Reader.getOwningModuleFile(Existing) !=4413Reader.getOwningModuleFile(Cat)) {4414llvm::DenseSet<std::pair<Decl *, Decl *>> NonEquivalentDecls;4415StructuralEquivalenceContext Ctx(4416Cat->getASTContext(), Existing->getASTContext(),4417NonEquivalentDecls, StructuralEquivalenceKind::Default,4418/*StrictTypeSpelling =*/false,4419/*Complain =*/false,4420/*ErrorOnTagTypeMismatch =*/true);4421if (!Ctx.IsEquivalent(Cat, Existing)) {4422// Warn only if the categories with the same name are different.4423Reader.Diag(Cat->getLocation(), diag::warn_dup_category_def)4424<< Interface->getDeclName() << Cat->getDeclName();4425Reader.Diag(Existing->getLocation(),4426diag::note_previous_definition);4427}4428} else if (!Existing) {4429// Record this category.4430Existing = Cat;4431}4432}44334434// Add this category to the end of the chain.4435if (Tail)4436ASTDeclReader::setNextObjCCategory(Tail, Cat);4437else4438Interface->setCategoryListRaw(Cat);4439Tail = Cat;4440}44414442public:4443ObjCCategoriesVisitor(4444ASTReader &Reader, ObjCInterfaceDecl *Interface,4445llvm::SmallPtrSetImpl<ObjCCategoryDecl *> &Deserialized,4446GlobalDeclID InterfaceID, unsigned PreviousGeneration)4447: Reader(Reader), Interface(Interface), Deserialized(Deserialized),4448InterfaceID(InterfaceID), PreviousGeneration(PreviousGeneration) {4449// Populate the name -> category map with the set of known categories.4450for (auto *Cat : Interface->known_categories()) {4451if (Cat->getDeclName())4452NameCategoryMap[Cat->getDeclName()] = Cat;44534454// Keep track of the tail of the category list.4455Tail = Cat;4456}4457}44584459bool operator()(ModuleFile &M) {4460// If we've loaded all of the category information we care about from4461// this module file, we're done.4462if (M.Generation <= PreviousGeneration)4463return true;44644465// Map global ID of the definition down to the local ID used in this4466// module file. If there is no such mapping, we'll find nothing here4467// (or in any module it imports).4468LocalDeclID LocalID =4469Reader.mapGlobalIDToModuleFileGlobalID(M, InterfaceID);4470if (LocalID.isInvalid())4471return true;44724473// Perform a binary search to find the local redeclarations for this4474// declaration (if any).4475const ObjCCategoriesInfo Compare = { LocalID, 0 };4476const ObjCCategoriesInfo *Result4477= std::lower_bound(M.ObjCCategoriesMap,4478M.ObjCCategoriesMap + M.LocalNumObjCCategoriesInMap,4479Compare);4480if (Result == M.ObjCCategoriesMap + M.LocalNumObjCCategoriesInMap ||4481LocalID != Result->getDefinitionID()) {4482// We didn't find anything. If the class definition is in this module4483// file, then the module files it depends on cannot have any categories,4484// so suppress further lookup.4485return Reader.isDeclIDFromModule(InterfaceID, M);4486}44874488// We found something. Dig out all of the categories.4489unsigned Offset = Result->Offset;4490unsigned N = M.ObjCCategories[Offset];4491M.ObjCCategories[Offset++] = 0; // Don't try to deserialize again4492for (unsigned I = 0; I != N; ++I)4493add(Reader.ReadDeclAs<ObjCCategoryDecl>(M, M.ObjCCategories, Offset));4494return true;4495}4496};44974498} // namespace44994500void ASTReader::loadObjCCategories(GlobalDeclID ID, ObjCInterfaceDecl *D,4501unsigned PreviousGeneration) {4502ObjCCategoriesVisitor Visitor(*this, D, CategoriesDeserialized, ID,4503PreviousGeneration);4504ModuleMgr.visit(Visitor);4505}45064507template<typename DeclT, typename Fn>4508static void forAllLaterRedecls(DeclT *D, Fn F) {4509F(D);45104511// Check whether we've already merged D into its redeclaration chain.4512// MostRecent may or may not be nullptr if D has not been merged. If4513// not, walk the merged redecl chain and see if it's there.4514auto *MostRecent = D->getMostRecentDecl();4515bool Found = false;4516for (auto *Redecl = MostRecent; Redecl && !Found;4517Redecl = Redecl->getPreviousDecl())4518Found = (Redecl == D);45194520// If this declaration is merged, apply the functor to all later decls.4521if (Found) {4522for (auto *Redecl = MostRecent; Redecl != D;4523Redecl = Redecl->getPreviousDecl())4524F(Redecl);4525}4526}45274528void ASTDeclReader::UpdateDecl(4529Decl *D,4530llvm::SmallVectorImpl<GlobalDeclID> &PendingLazySpecializationIDs) {4531while (Record.getIdx() < Record.size()) {4532switch ((DeclUpdateKind)Record.readInt()) {4533case UPD_CXX_ADDED_IMPLICIT_MEMBER: {4534auto *RD = cast<CXXRecordDecl>(D);4535Decl *MD = Record.readDecl();4536assert(MD && "couldn't read decl from update record");4537Reader.PendingAddedClassMembers.push_back({RD, MD});4538break;4539}45404541case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:4542// It will be added to the template's lazy specialization set.4543PendingLazySpecializationIDs.push_back(readDeclID());4544break;45454546case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE: {4547auto *Anon = readDeclAs<NamespaceDecl>();45484549// Each module has its own anonymous namespace, which is disjoint from4550// any other module's anonymous namespaces, so don't attach the anonymous4551// namespace at all.4552if (!Record.isModule()) {4553if (auto *TU = dyn_cast<TranslationUnitDecl>(D))4554TU->setAnonymousNamespace(Anon);4555else4556cast<NamespaceDecl>(D)->setAnonymousNamespace(Anon);4557}4558break;4559}45604561case UPD_CXX_ADDED_VAR_DEFINITION: {4562auto *VD = cast<VarDecl>(D);4563VD->NonParmVarDeclBits.IsInline = Record.readInt();4564VD->NonParmVarDeclBits.IsInlineSpecified = Record.readInt();4565ReadVarDeclInit(VD);4566break;4567}45684569case UPD_CXX_POINT_OF_INSTANTIATION: {4570SourceLocation POI = Record.readSourceLocation();4571if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D)) {4572VTSD->setPointOfInstantiation(POI);4573} else if (auto *VD = dyn_cast<VarDecl>(D)) {4574MemberSpecializationInfo *MSInfo = VD->getMemberSpecializationInfo();4575assert(MSInfo && "No member specialization information");4576MSInfo->setPointOfInstantiation(POI);4577} else {4578auto *FD = cast<FunctionDecl>(D);4579if (auto *FTSInfo = FD->TemplateOrSpecialization4580.dyn_cast<FunctionTemplateSpecializationInfo *>())4581FTSInfo->setPointOfInstantiation(POI);4582else4583FD->TemplateOrSpecialization.get<MemberSpecializationInfo *>()4584->setPointOfInstantiation(POI);4585}4586break;4587}45884589case UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT: {4590auto *Param = cast<ParmVarDecl>(D);45914592// We have to read the default argument regardless of whether we use it4593// so that hypothetical further update records aren't messed up.4594// TODO: Add a function to skip over the next expr record.4595auto *DefaultArg = Record.readExpr();45964597// Only apply the update if the parameter still has an uninstantiated4598// default argument.4599if (Param->hasUninstantiatedDefaultArg())4600Param->setDefaultArg(DefaultArg);4601break;4602}46034604case UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER: {4605auto *FD = cast<FieldDecl>(D);4606auto *DefaultInit = Record.readExpr();46074608// Only apply the update if the field still has an uninstantiated4609// default member initializer.4610if (FD->hasInClassInitializer() && !FD->hasNonNullInClassInitializer()) {4611if (DefaultInit)4612FD->setInClassInitializer(DefaultInit);4613else4614// Instantiation failed. We can get here if we serialized an AST for4615// an invalid program.4616FD->removeInClassInitializer();4617}4618break;4619}46204621case UPD_CXX_ADDED_FUNCTION_DEFINITION: {4622auto *FD = cast<FunctionDecl>(D);4623if (Reader.PendingBodies[FD]) {4624// FIXME: Maybe check for ODR violations.4625// It's safe to stop now because this update record is always last.4626return;4627}46284629if (Record.readInt()) {4630// Maintain AST consistency: any later redeclarations of this function4631// are inline if this one is. (We might have merged another declaration4632// into this one.)4633forAllLaterRedecls(FD, [](FunctionDecl *FD) {4634FD->setImplicitlyInline();4635});4636}4637FD->setInnerLocStart(readSourceLocation());4638ReadFunctionDefinition(FD);4639assert(Record.getIdx() == Record.size() && "lazy body must be last");4640break;4641}46424643case UPD_CXX_INSTANTIATED_CLASS_DEFINITION: {4644auto *RD = cast<CXXRecordDecl>(D);4645auto *OldDD = RD->getCanonicalDecl()->DefinitionData;4646bool HadRealDefinition =4647OldDD && (OldDD->Definition != RD ||4648!Reader.PendingFakeDefinitionData.count(OldDD));4649RD->setParamDestroyedInCallee(Record.readInt());4650RD->setArgPassingRestrictions(4651static_cast<RecordArgPassingKind>(Record.readInt()));4652ReadCXXRecordDefinition(RD, /*Update*/true);46534654// Visible update is handled separately.4655uint64_t LexicalOffset = ReadLocalOffset();4656if (!HadRealDefinition && LexicalOffset) {4657Record.readLexicalDeclContextStorage(LexicalOffset, RD);4658Reader.PendingFakeDefinitionData.erase(OldDD);4659}46604661auto TSK = (TemplateSpecializationKind)Record.readInt();4662SourceLocation POI = readSourceLocation();4663if (MemberSpecializationInfo *MSInfo =4664RD->getMemberSpecializationInfo()) {4665MSInfo->setTemplateSpecializationKind(TSK);4666MSInfo->setPointOfInstantiation(POI);4667} else {4668auto *Spec = cast<ClassTemplateSpecializationDecl>(RD);4669Spec->setTemplateSpecializationKind(TSK);4670Spec->setPointOfInstantiation(POI);46714672if (Record.readInt()) {4673auto *PartialSpec =4674readDeclAs<ClassTemplatePartialSpecializationDecl>();4675SmallVector<TemplateArgument, 8> TemplArgs;4676Record.readTemplateArgumentList(TemplArgs);4677auto *TemplArgList = TemplateArgumentList::CreateCopy(4678Reader.getContext(), TemplArgs);46794680// FIXME: If we already have a partial specialization set,4681// check that it matches.4682if (!Spec->getSpecializedTemplateOrPartial()4683.is<ClassTemplatePartialSpecializationDecl *>())4684Spec->setInstantiationOf(PartialSpec, TemplArgList);4685}4686}46874688RD->setTagKind(static_cast<TagTypeKind>(Record.readInt()));4689RD->setLocation(readSourceLocation());4690RD->setLocStart(readSourceLocation());4691RD->setBraceRange(readSourceRange());46924693if (Record.readInt()) {4694AttrVec Attrs;4695Record.readAttributes(Attrs);4696// If the declaration already has attributes, we assume that some other4697// AST file already loaded them.4698if (!D->hasAttrs())4699D->setAttrsImpl(Attrs, Reader.getContext());4700}4701break;4702}47034704case UPD_CXX_RESOLVED_DTOR_DELETE: {4705// Set the 'operator delete' directly to avoid emitting another update4706// record.4707auto *Del = readDeclAs<FunctionDecl>();4708auto *First = cast<CXXDestructorDecl>(D->getCanonicalDecl());4709auto *ThisArg = Record.readExpr();4710// FIXME: Check consistency if we have an old and new operator delete.4711if (!First->OperatorDelete) {4712First->OperatorDelete = Del;4713First->OperatorDeleteThisArg = ThisArg;4714}4715break;4716}47174718case UPD_CXX_RESOLVED_EXCEPTION_SPEC: {4719SmallVector<QualType, 8> ExceptionStorage;4720auto ESI = Record.readExceptionSpecInfo(ExceptionStorage);47214722// Update this declaration's exception specification, if needed.4723auto *FD = cast<FunctionDecl>(D);4724auto *FPT = FD->getType()->castAs<FunctionProtoType>();4725// FIXME: If the exception specification is already present, check that it4726// matches.4727if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {4728FD->setType(Reader.getContext().getFunctionType(4729FPT->getReturnType(), FPT->getParamTypes(),4730FPT->getExtProtoInfo().withExceptionSpec(ESI)));47314732// When we get to the end of deserializing, see if there are other decls4733// that we need to propagate this exception specification onto.4734Reader.PendingExceptionSpecUpdates.insert(4735std::make_pair(FD->getCanonicalDecl(), FD));4736}4737break;4738}47394740case UPD_CXX_DEDUCED_RETURN_TYPE: {4741auto *FD = cast<FunctionDecl>(D);4742QualType DeducedResultType = Record.readType();4743Reader.PendingDeducedTypeUpdates.insert(4744{FD->getCanonicalDecl(), DeducedResultType});4745break;4746}47474748case UPD_DECL_MARKED_USED:4749// Maintain AST consistency: any later redeclarations are used too.4750D->markUsed(Reader.getContext());4751break;47524753case UPD_MANGLING_NUMBER:4754Reader.getContext().setManglingNumber(cast<NamedDecl>(D),4755Record.readInt());4756break;47574758case UPD_STATIC_LOCAL_NUMBER:4759Reader.getContext().setStaticLocalNumber(cast<VarDecl>(D),4760Record.readInt());4761break;47624763case UPD_DECL_MARKED_OPENMP_THREADPRIVATE:4764D->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(Reader.getContext(),4765readSourceRange()));4766break;47674768case UPD_DECL_MARKED_OPENMP_ALLOCATE: {4769auto AllocatorKind =4770static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(Record.readInt());4771Expr *Allocator = Record.readExpr();4772Expr *Alignment = Record.readExpr();4773SourceRange SR = readSourceRange();4774D->addAttr(OMPAllocateDeclAttr::CreateImplicit(4775Reader.getContext(), AllocatorKind, Allocator, Alignment, SR));4776break;4777}47784779case UPD_DECL_EXPORTED: {4780unsigned SubmoduleID = readSubmoduleID();4781auto *Exported = cast<NamedDecl>(D);4782Module *Owner = SubmoduleID ? Reader.getSubmodule(SubmoduleID) : nullptr;4783Reader.getContext().mergeDefinitionIntoModule(Exported, Owner);4784Reader.PendingMergedDefinitionsToDeduplicate.insert(Exported);4785break;4786}47874788case UPD_DECL_MARKED_OPENMP_DECLARETARGET: {4789auto MapType = Record.readEnum<OMPDeclareTargetDeclAttr::MapTypeTy>();4790auto DevType = Record.readEnum<OMPDeclareTargetDeclAttr::DevTypeTy>();4791Expr *IndirectE = Record.readExpr();4792bool Indirect = Record.readBool();4793unsigned Level = Record.readInt();4794D->addAttr(OMPDeclareTargetDeclAttr::CreateImplicit(4795Reader.getContext(), MapType, DevType, IndirectE, Indirect, Level,4796readSourceRange()));4797break;4798}47994800case UPD_ADDED_ATTR_TO_RECORD:4801AttrVec Attrs;4802Record.readAttributes(Attrs);4803assert(Attrs.size() == 1);4804D->addAttr(Attrs[0]);4805break;4806}4807}4808}480948104811