clang API Documentation

ASTReaderDecl.cpp
Go to the documentation of this file.
00001 //===--- ASTReaderDecl.cpp - Decl Deserialization ---------------*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the ASTReader::ReadDeclRecord method, which is the
00011 // entrypoint for loading a decl.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "clang/Serialization/ASTReader.h"
00016 #include "ASTCommon.h"
00017 #include "ASTReaderInternals.h"
00018 #include "clang/AST/ASTConsumer.h"
00019 #include "clang/AST/ASTContext.h"
00020 #include "clang/AST/DeclCXX.h"
00021 #include "clang/AST/DeclGroup.h"
00022 #include "clang/AST/DeclTemplate.h"
00023 #include "clang/AST/DeclVisitor.h"
00024 #include "clang/AST/Expr.h"
00025 #include "clang/Sema/IdentifierResolver.h"
00026 #include "clang/Sema/Sema.h"
00027 #include "clang/Sema/SemaDiagnostic.h"
00028 #include "llvm/Support/SaveAndRestore.h"
00029 using namespace clang;
00030 using namespace clang::serialization;
00031 
00032 //===----------------------------------------------------------------------===//
00033 // Declaration deserialization
00034 //===----------------------------------------------------------------------===//
00035 
00036 namespace clang {
00037   class ASTDeclReader : public DeclVisitor<ASTDeclReader, void> {
00038     ASTReader &Reader;
00039     ModuleFile &F;
00040     const DeclID ThisDeclID;
00041     const unsigned RawLocation;
00042     typedef ASTReader::RecordData RecordData;
00043     const RecordData &Record;
00044     unsigned &Idx;
00045     TypeID TypeIDForTypeDecl;
00046     unsigned AnonymousDeclNumber;
00047     GlobalDeclID NamedDeclForTagDecl;
00048     IdentifierInfo *TypedefNameForLinkage;
00049     
00050     bool HasPendingBody;
00051 
00052     uint64_t GetCurrentCursorOffset();
00053     
00054     SourceLocation ReadSourceLocation(const RecordData &R, unsigned &I) {
00055       return Reader.ReadSourceLocation(F, R, I);
00056     }
00057     
00058     SourceRange ReadSourceRange(const RecordData &R, unsigned &I) {
00059       return Reader.ReadSourceRange(F, R, I);
00060     }
00061     
00062     TypeSourceInfo *GetTypeSourceInfo(const RecordData &R, unsigned &I) {
00063       return Reader.GetTypeSourceInfo(F, R, I);
00064     }
00065     
00066     serialization::DeclID ReadDeclID(const RecordData &R, unsigned &I) {
00067       return Reader.ReadDeclID(F, R, I);
00068     }
00069     
00070     Decl *ReadDecl(const RecordData &R, unsigned &I) {
00071       return Reader.ReadDecl(F, R, I);
00072     }
00073 
00074     template<typename T>
00075     T *ReadDeclAs(const RecordData &R, unsigned &I) {
00076       return Reader.ReadDeclAs<T>(F, R, I);
00077     }
00078 
00079     void ReadQualifierInfo(QualifierInfo &Info,
00080                            const RecordData &R, unsigned &I) {
00081       Reader.ReadQualifierInfo(F, Info, R, I);
00082     }
00083     
00084     void ReadDeclarationNameLoc(DeclarationNameLoc &DNLoc, DeclarationName Name,
00085                                 const RecordData &R, unsigned &I) {
00086       Reader.ReadDeclarationNameLoc(F, DNLoc, Name, R, I);
00087     }
00088     
00089     void ReadDeclarationNameInfo(DeclarationNameInfo &NameInfo,
00090                                 const RecordData &R, unsigned &I) {
00091       Reader.ReadDeclarationNameInfo(F, NameInfo, R, I);
00092     }
00093 
00094     serialization::SubmoduleID readSubmoduleID(const RecordData &R, 
00095                                                unsigned &I) {
00096       if (I >= R.size())
00097         return 0;
00098       
00099       return Reader.getGlobalSubmoduleID(F, R[I++]);
00100     }
00101     
00102     Module *readModule(const RecordData &R, unsigned &I) {
00103       return Reader.getSubmodule(readSubmoduleID(R, I));
00104     }
00105 
00106     void ReadCXXRecordDefinition(CXXRecordDecl *D);
00107     void ReadCXXDefinitionData(struct CXXRecordDecl::DefinitionData &Data,
00108                                const RecordData &R, unsigned &I);
00109     void MergeDefinitionData(CXXRecordDecl *D,
00110                              struct CXXRecordDecl::DefinitionData &NewDD);
00111 
00112     static NamedDecl *getAnonymousDeclForMerging(ASTReader &Reader,
00113                                                  DeclContext *DC,
00114                                                  unsigned Index);
00115     static void setAnonymousDeclForMerging(ASTReader &Reader, DeclContext *DC,
00116                                            unsigned Index, NamedDecl *D);
00117 
00118     /// \brief RAII class used to capture the first ID within a redeclaration
00119     /// chain and to introduce it into the list of pending redeclaration chains
00120     /// on destruction.
00121     ///
00122     /// The caller can choose not to introduce this ID into the list of pending
00123     /// redeclaration chains by calling \c suppress().
00124     class RedeclarableResult {
00125       ASTReader &Reader;
00126       GlobalDeclID FirstID;
00127       mutable bool Owning;
00128       Decl::Kind DeclKind;
00129       
00130       void operator=(RedeclarableResult &) LLVM_DELETED_FUNCTION;
00131       
00132     public:
00133       RedeclarableResult(ASTReader &Reader, GlobalDeclID FirstID,
00134                          Decl::Kind DeclKind)
00135         : Reader(Reader), FirstID(FirstID), Owning(true), DeclKind(DeclKind) { }
00136 
00137       RedeclarableResult(const RedeclarableResult &Other)
00138         : Reader(Other.Reader), FirstID(Other.FirstID), Owning(Other.Owning) ,
00139           DeclKind(Other.DeclKind)
00140       { 
00141         Other.Owning = false;
00142       }
00143 
00144       ~RedeclarableResult() {
00145         if (FirstID && Owning && isRedeclarableDeclKind(DeclKind) &&
00146             Reader.PendingDeclChainsKnown.insert(FirstID))
00147           Reader.PendingDeclChains.push_back(FirstID);
00148       }
00149       
00150       /// \brief Retrieve the first ID.
00151       GlobalDeclID getFirstID() const { return FirstID; }
00152       
00153       /// \brief Do not introduce this declaration ID into the set of pending
00154       /// declaration chains.
00155       void suppress() {
00156         Owning = false;
00157       }
00158     };
00159 
00160     /// \brief Class used to capture the result of searching for an existing
00161     /// declaration of a specific kind and name, along with the ability
00162     /// to update the place where this result was found (the declaration
00163     /// chain hanging off an identifier or the DeclContext we searched in)
00164     /// if requested.
00165     class FindExistingResult {
00166       ASTReader &Reader;
00167       NamedDecl *New;
00168       NamedDecl *Existing;
00169       mutable bool AddResult;
00170 
00171       unsigned AnonymousDeclNumber;
00172       IdentifierInfo *TypedefNameForLinkage;
00173 
00174       void operator=(FindExistingResult&) LLVM_DELETED_FUNCTION;
00175 
00176     public:
00177       FindExistingResult(ASTReader &Reader)
00178           : Reader(Reader), New(nullptr), Existing(nullptr), AddResult(false),
00179             AnonymousDeclNumber(0), TypedefNameForLinkage(0) {}
00180 
00181       FindExistingResult(ASTReader &Reader, NamedDecl *New, NamedDecl *Existing,
00182                          unsigned AnonymousDeclNumber,
00183                          IdentifierInfo *TypedefNameForLinkage)
00184           : Reader(Reader), New(New), Existing(Existing), AddResult(true),
00185             AnonymousDeclNumber(AnonymousDeclNumber),
00186             TypedefNameForLinkage(TypedefNameForLinkage) {}
00187 
00188       FindExistingResult(const FindExistingResult &Other)
00189           : Reader(Other.Reader), New(Other.New), Existing(Other.Existing),
00190             AddResult(Other.AddResult),
00191             AnonymousDeclNumber(Other.AnonymousDeclNumber),
00192             TypedefNameForLinkage(Other.TypedefNameForLinkage) {
00193         Other.AddResult = false;
00194       }
00195 
00196       ~FindExistingResult();
00197 
00198       /// \brief Suppress the addition of this result into the known set of
00199       /// names.
00200       void suppress() { AddResult = false; }
00201 
00202       operator NamedDecl*() const { return Existing; }
00203 
00204       template<typename T>
00205       operator T*() const { return dyn_cast_or_null<T>(Existing); }
00206     };
00207 
00208     FindExistingResult findExisting(NamedDecl *D);
00209 
00210   public:
00211     ASTDeclReader(ASTReader &Reader, ModuleFile &F, DeclID thisDeclID,
00212                   unsigned RawLocation, const RecordData &Record, unsigned &Idx)
00213         : Reader(Reader), F(F), ThisDeclID(thisDeclID),
00214           RawLocation(RawLocation), Record(Record), Idx(Idx),
00215           TypeIDForTypeDecl(0), NamedDeclForTagDecl(0),
00216           TypedefNameForLinkage(nullptr), HasPendingBody(false) {}
00217 
00218     template <typename DeclT>
00219     static void attachPreviousDeclImpl(ASTReader &Reader,
00220                                        Redeclarable<DeclT> *D, Decl *Previous);
00221     static void attachPreviousDeclImpl(ASTReader &Reader, ...);
00222     static void attachPreviousDecl(ASTReader &Reader, Decl *D, Decl *Previous);
00223 
00224     template <typename DeclT>
00225     static void attachLatestDeclImpl(Redeclarable<DeclT> *D, Decl *Latest);
00226     static void attachLatestDeclImpl(...);
00227     static void attachLatestDecl(Decl *D, Decl *latest);
00228 
00229     template <typename DeclT>
00230     static void markIncompleteDeclChainImpl(Redeclarable<DeclT> *D);
00231     static void markIncompleteDeclChainImpl(...);
00232 
00233     /// \brief Determine whether this declaration has a pending body.
00234     bool hasPendingBody() const { return HasPendingBody; }
00235 
00236     void Visit(Decl *D);
00237 
00238     void UpdateDecl(Decl *D, ModuleFile &ModuleFile,
00239                     const RecordData &Record);
00240 
00241     static void setNextObjCCategory(ObjCCategoryDecl *Cat,
00242                                     ObjCCategoryDecl *Next) {
00243       Cat->NextClassCategory = Next;
00244     }
00245 
00246     void VisitDecl(Decl *D);
00247     void VisitTranslationUnitDecl(TranslationUnitDecl *TU);
00248     void VisitNamedDecl(NamedDecl *ND);
00249     void VisitLabelDecl(LabelDecl *LD);
00250     void VisitNamespaceDecl(NamespaceDecl *D);
00251     void VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
00252     void VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
00253     void VisitTypeDecl(TypeDecl *TD);
00254     RedeclarableResult VisitTypedefNameDecl(TypedefNameDecl *TD);
00255     void VisitTypedefDecl(TypedefDecl *TD);
00256     void VisitTypeAliasDecl(TypeAliasDecl *TD);
00257     void VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
00258     RedeclarableResult VisitTagDecl(TagDecl *TD);
00259     void VisitEnumDecl(EnumDecl *ED);
00260     RedeclarableResult VisitRecordDeclImpl(RecordDecl *RD);
00261     void VisitRecordDecl(RecordDecl *RD) { VisitRecordDeclImpl(RD); }
00262     RedeclarableResult VisitCXXRecordDeclImpl(CXXRecordDecl *D);
00263     void VisitCXXRecordDecl(CXXRecordDecl *D) { VisitCXXRecordDeclImpl(D); }
00264     RedeclarableResult VisitClassTemplateSpecializationDeclImpl(
00265                                             ClassTemplateSpecializationDecl *D);
00266     void VisitClassTemplateSpecializationDecl(
00267         ClassTemplateSpecializationDecl *D) {
00268       VisitClassTemplateSpecializationDeclImpl(D);
00269     }
00270     void VisitClassTemplatePartialSpecializationDecl(
00271                                      ClassTemplatePartialSpecializationDecl *D);
00272     void VisitClassScopeFunctionSpecializationDecl(
00273                                        ClassScopeFunctionSpecializationDecl *D);
00274     RedeclarableResult
00275     VisitVarTemplateSpecializationDeclImpl(VarTemplateSpecializationDecl *D);
00276     void VisitVarTemplateSpecializationDecl(VarTemplateSpecializationDecl *D) {
00277       VisitVarTemplateSpecializationDeclImpl(D);
00278     }
00279     void VisitVarTemplatePartialSpecializationDecl(
00280         VarTemplatePartialSpecializationDecl *D);
00281     void VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
00282     void VisitValueDecl(ValueDecl *VD);
00283     void VisitEnumConstantDecl(EnumConstantDecl *ECD);
00284     void VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
00285     void VisitDeclaratorDecl(DeclaratorDecl *DD);
00286     void VisitFunctionDecl(FunctionDecl *FD);
00287     void VisitCXXMethodDecl(CXXMethodDecl *D);
00288     void VisitCXXConstructorDecl(CXXConstructorDecl *D);
00289     void VisitCXXDestructorDecl(CXXDestructorDecl *D);
00290     void VisitCXXConversionDecl(CXXConversionDecl *D);
00291     void VisitFieldDecl(FieldDecl *FD);
00292     void VisitMSPropertyDecl(MSPropertyDecl *FD);
00293     void VisitIndirectFieldDecl(IndirectFieldDecl *FD);
00294     RedeclarableResult VisitVarDeclImpl(VarDecl *D);
00295     void VisitVarDecl(VarDecl *VD) { VisitVarDeclImpl(VD); }
00296     void VisitImplicitParamDecl(ImplicitParamDecl *PD);
00297     void VisitParmVarDecl(ParmVarDecl *PD);
00298     void VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
00299     DeclID VisitTemplateDecl(TemplateDecl *D);
00300     RedeclarableResult VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D);
00301     void VisitClassTemplateDecl(ClassTemplateDecl *D);
00302     void VisitVarTemplateDecl(VarTemplateDecl *D);
00303     void VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
00304     void VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
00305     void VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D);
00306     void VisitUsingDecl(UsingDecl *D);
00307     void VisitUsingShadowDecl(UsingShadowDecl *D);
00308     void VisitLinkageSpecDecl(LinkageSpecDecl *D);
00309     void VisitFileScopeAsmDecl(FileScopeAsmDecl *AD);
00310     void VisitImportDecl(ImportDecl *D);
00311     void VisitAccessSpecDecl(AccessSpecDecl *D);
00312     void VisitFriendDecl(FriendDecl *D);
00313     void VisitFriendTemplateDecl(FriendTemplateDecl *D);
00314     void VisitStaticAssertDecl(StaticAssertDecl *D);
00315     void VisitBlockDecl(BlockDecl *BD);
00316     void VisitCapturedDecl(CapturedDecl *CD);
00317     void VisitEmptyDecl(EmptyDecl *D);
00318 
00319     std::pair<uint64_t, uint64_t> VisitDeclContext(DeclContext *DC);
00320 
00321     template<typename T>
00322     RedeclarableResult VisitRedeclarable(Redeclarable<T> *D);
00323 
00324     template<typename T>
00325     void mergeRedeclarable(Redeclarable<T> *D, RedeclarableResult &Redecl,
00326                            DeclID TemplatePatternID = 0);
00327 
00328     template<typename T>
00329     void mergeRedeclarable(Redeclarable<T> *D, T *Existing,
00330                            RedeclarableResult &Redecl,
00331                            DeclID TemplatePatternID = 0);
00332 
00333     template<typename T>
00334     void mergeMergeable(Mergeable<T> *D);
00335 
00336     void mergeTemplatePattern(RedeclarableTemplateDecl *D,
00337                               RedeclarableTemplateDecl *Existing,
00338                               DeclID DsID);
00339 
00340     // FIXME: Reorder according to DeclNodes.td?
00341     void VisitObjCMethodDecl(ObjCMethodDecl *D);
00342     void VisitObjCContainerDecl(ObjCContainerDecl *D);
00343     void VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
00344     void VisitObjCIvarDecl(ObjCIvarDecl *D);
00345     void VisitObjCProtocolDecl(ObjCProtocolDecl *D);
00346     void VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D);
00347     void VisitObjCCategoryDecl(ObjCCategoryDecl *D);
00348     void VisitObjCImplDecl(ObjCImplDecl *D);
00349     void VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
00350     void VisitObjCImplementationDecl(ObjCImplementationDecl *D);
00351     void VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *D);
00352     void VisitObjCPropertyDecl(ObjCPropertyDecl *D);
00353     void VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D);
00354     void VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D);
00355   };
00356 }
00357 
00358 uint64_t ASTDeclReader::GetCurrentCursorOffset() {
00359   return F.DeclsCursor.GetCurrentBitNo() + F.GlobalBitOffset;
00360 }
00361 
00362 void ASTDeclReader::Visit(Decl *D) {
00363   DeclVisitor<ASTDeclReader, void>::Visit(D);
00364 
00365   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
00366     if (DD->DeclInfo) {
00367       DeclaratorDecl::ExtInfo *Info =
00368           DD->DeclInfo.get<DeclaratorDecl::ExtInfo *>();
00369       Info->TInfo =
00370           GetTypeSourceInfo(Record, Idx);
00371     }
00372     else {
00373       DD->DeclInfo = GetTypeSourceInfo(Record, Idx);
00374     }
00375   }
00376 
00377   if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
00378     // We have a fully initialized TypeDecl. Read its type now.
00379     TD->setTypeForDecl(Reader.GetType(TypeIDForTypeDecl).getTypePtrOrNull());
00380 
00381     // If this is a tag declaration with a typedef name for linkage, it's safe
00382     // to load that typedef now.
00383     if (NamedDeclForTagDecl)
00384       cast<TagDecl>(D)->NamedDeclOrQualifier =
00385           cast<NamedDecl>(Reader.GetDecl(NamedDeclForTagDecl));
00386   } else if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
00387     // if we have a fully initialized TypeDecl, we can safely read its type now.
00388     ID->TypeForDecl = Reader.GetType(TypeIDForTypeDecl).getTypePtrOrNull();
00389   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
00390     // FunctionDecl's body was written last after all other Stmts/Exprs.
00391     // We only read it if FD doesn't already have a body (e.g., from another
00392     // module).
00393     // FIXME: Also consider = default and = delete.
00394     // FIXME: Can we diagnose ODR violations somehow?
00395     if (Record[Idx++]) {
00396       Reader.PendingBodies[FD] = GetCurrentCursorOffset();
00397       HasPendingBody = true;
00398     }
00399   }
00400 }
00401 
00402 void ASTDeclReader::VisitDecl(Decl *D) {
00403   if (D->isTemplateParameter() || D->isTemplateParameterPack() ||
00404       isa<ParmVarDecl>(D)) {
00405     // We don't want to deserialize the DeclContext of a template
00406     // parameter or of a parameter of a function template immediately.   These
00407     // entities might be used in the formulation of its DeclContext (for
00408     // example, a function parameter can be used in decltype() in trailing
00409     // return type of the function).  Use the translation unit DeclContext as a
00410     // placeholder.
00411     GlobalDeclID SemaDCIDForTemplateParmDecl = ReadDeclID(Record, Idx);
00412     GlobalDeclID LexicalDCIDForTemplateParmDecl = ReadDeclID(Record, Idx);
00413     Reader.addPendingDeclContextInfo(D,
00414                                      SemaDCIDForTemplateParmDecl,
00415                                      LexicalDCIDForTemplateParmDecl);
00416     D->setDeclContext(Reader.getContext().getTranslationUnitDecl()); 
00417   } else {
00418     DeclContext *SemaDC = ReadDeclAs<DeclContext>(Record, Idx);
00419     DeclContext *LexicalDC = ReadDeclAs<DeclContext>(Record, Idx);
00420     DeclContext *MergedSemaDC = Reader.MergedDeclContexts.lookup(SemaDC);
00421     // Avoid calling setLexicalDeclContext() directly because it uses
00422     // Decl::getASTContext() internally which is unsafe during derialization.
00423     D->setDeclContextsImpl(MergedSemaDC ? MergedSemaDC : SemaDC, LexicalDC,
00424                            Reader.getContext());
00425   }
00426   D->setLocation(Reader.ReadSourceLocation(F, RawLocation));
00427   D->setInvalidDecl(Record[Idx++]);
00428   if (Record[Idx++]) { // hasAttrs
00429     AttrVec Attrs;
00430     Reader.ReadAttributes(F, Attrs, Record, Idx);
00431     // Avoid calling setAttrs() directly because it uses Decl::getASTContext()
00432     // internally which is unsafe during derialization.
00433     D->setAttrsImpl(Attrs, Reader.getContext());
00434   }
00435   D->setImplicit(Record[Idx++]);
00436   D->Used = Record[Idx++];
00437   D->setReferenced(Record[Idx++]);
00438   D->setTopLevelDeclInObjCContainer(Record[Idx++]);
00439   D->setAccess((AccessSpecifier)Record[Idx++]);
00440   D->FromASTFile = true;
00441   D->setModulePrivate(Record[Idx++]);
00442   D->Hidden = D->isModulePrivate();
00443   
00444   // Determine whether this declaration is part of a (sub)module. If so, it
00445   // may not yet be visible.
00446   if (unsigned SubmoduleID = readSubmoduleID(Record, Idx)) {
00447     // Store the owning submodule ID in the declaration.
00448     D->setOwningModuleID(SubmoduleID);
00449     
00450     // Module-private declarations are never visible, so there is no work to do.
00451     if (!D->isModulePrivate()) {
00452       if (Module *Owner = Reader.getSubmodule(SubmoduleID)) {
00453         if (Owner->NameVisibility != Module::AllVisible) {
00454           // The owning module is not visible. Mark this declaration as hidden.
00455           D->Hidden = true;
00456           
00457           // Note that this declaration was hidden because its owning module is 
00458           // not yet visible.
00459           Reader.HiddenNamesMap[Owner].HiddenDecls.push_back(D);
00460         }
00461       }
00462     }
00463   }
00464 }
00465 
00466 void ASTDeclReader::VisitTranslationUnitDecl(TranslationUnitDecl *TU) {
00467   llvm_unreachable("Translation units are not serialized");
00468 }
00469 
00470 void ASTDeclReader::VisitNamedDecl(NamedDecl *ND) {
00471   VisitDecl(ND);
00472   ND->setDeclName(Reader.ReadDeclarationName(F, Record, Idx));
00473   if (needsAnonymousDeclarationNumber(ND))
00474     AnonymousDeclNumber = Record[Idx++];
00475 }
00476 
00477 void ASTDeclReader::VisitTypeDecl(TypeDecl *TD) {
00478   VisitNamedDecl(TD);
00479   TD->setLocStart(ReadSourceLocation(Record, Idx));
00480   // Delay type reading until after we have fully initialized the decl.
00481   TypeIDForTypeDecl = Reader.getGlobalTypeID(F, Record[Idx++]);
00482 }
00483 
00484 ASTDeclReader::RedeclarableResult
00485 ASTDeclReader::VisitTypedefNameDecl(TypedefNameDecl *TD) {
00486   RedeclarableResult Redecl = VisitRedeclarable(TD);
00487   VisitTypeDecl(TD);
00488   TypeSourceInfo *TInfo = GetTypeSourceInfo(Record, Idx);
00489   if (Record[Idx++]) { // isModed
00490     QualType modedT = Reader.readType(F, Record, Idx);
00491     TD->setModedTypeSourceInfo(TInfo, modedT);
00492   } else
00493     TD->setTypeSourceInfo(TInfo);
00494   return Redecl;
00495 }
00496 
00497 void ASTDeclReader::VisitTypedefDecl(TypedefDecl *TD) {
00498   RedeclarableResult Redecl = VisitTypedefNameDecl(TD);
00499   mergeRedeclarable(TD, Redecl);
00500 }
00501 
00502 void ASTDeclReader::VisitTypeAliasDecl(TypeAliasDecl *TD) {
00503   RedeclarableResult Redecl = VisitTypedefNameDecl(TD);
00504   if (auto *Template = ReadDeclAs<TypeAliasTemplateDecl>(Record, Idx))
00505     // Merged when we merge the template.
00506     TD->setDescribedAliasTemplate(Template);
00507   else
00508     mergeRedeclarable(TD, Redecl);
00509 }
00510 
00511 ASTDeclReader::RedeclarableResult ASTDeclReader::VisitTagDecl(TagDecl *TD) {
00512   RedeclarableResult Redecl = VisitRedeclarable(TD);
00513   VisitTypeDecl(TD);
00514   
00515   TD->IdentifierNamespace = Record[Idx++];
00516   TD->setTagKind((TagDecl::TagKind)Record[Idx++]);
00517   if (!isa<CXXRecordDecl>(TD))
00518     TD->setCompleteDefinition(Record[Idx++]);
00519   TD->setEmbeddedInDeclarator(Record[Idx++]);
00520   TD->setFreeStanding(Record[Idx++]);
00521   TD->setCompleteDefinitionRequired(Record[Idx++]);
00522   TD->setRBraceLoc(ReadSourceLocation(Record, Idx));
00523   
00524   switch (Record[Idx++]) {
00525   case 0:
00526     break;
00527   case 1: { // ExtInfo
00528     TagDecl::ExtInfo *Info = new (Reader.getContext()) TagDecl::ExtInfo();
00529     ReadQualifierInfo(*Info, Record, Idx);
00530     TD->NamedDeclOrQualifier = Info;
00531     break;
00532   }
00533   case 2: // TypedefNameForAnonDecl
00534     NamedDeclForTagDecl = ReadDeclID(Record, Idx);
00535     TypedefNameForLinkage = Reader.GetIdentifierInfo(F, Record, Idx);
00536     break;
00537   case 3: // DeclaratorForAnonDecl
00538     NamedDeclForTagDecl = ReadDeclID(Record, Idx);
00539     break;
00540   default:
00541     llvm_unreachable("unexpected tag info kind");
00542   }
00543 
00544   if (!isa<CXXRecordDecl>(TD))
00545     mergeRedeclarable(TD, Redecl);
00546   return Redecl;
00547 }
00548 
00549 void ASTDeclReader::VisitEnumDecl(EnumDecl *ED) {
00550   VisitTagDecl(ED);
00551   if (TypeSourceInfo *TI = Reader.GetTypeSourceInfo(F, Record, Idx))
00552     ED->setIntegerTypeSourceInfo(TI);
00553   else
00554     ED->setIntegerType(Reader.readType(F, Record, Idx));
00555   ED->setPromotionType(Reader.readType(F, Record, Idx));
00556   ED->setNumPositiveBits(Record[Idx++]);
00557   ED->setNumNegativeBits(Record[Idx++]);
00558   ED->IsScoped = Record[Idx++];
00559   ED->IsScopedUsingClassTag = Record[Idx++];
00560   ED->IsFixed = Record[Idx++];
00561 
00562   // If this is a definition subject to the ODR, and we already have a
00563   // definition, merge this one into it.
00564   if (ED->IsCompleteDefinition &&
00565       Reader.getContext().getLangOpts().Modules &&
00566       Reader.getContext().getLangOpts().CPlusPlus) {
00567     if (EnumDecl *&OldDef = Reader.EnumDefinitions[ED->getCanonicalDecl()]) {
00568       Reader.MergedDeclContexts.insert(std::make_pair(ED, OldDef));
00569       ED->IsCompleteDefinition = false;
00570     } else {
00571       OldDef = ED;
00572     }
00573   }
00574 
00575   if (EnumDecl *InstED = ReadDeclAs<EnumDecl>(Record, Idx)) {
00576     TemplateSpecializationKind TSK = (TemplateSpecializationKind)Record[Idx++];
00577     SourceLocation POI = ReadSourceLocation(Record, Idx);
00578     ED->setInstantiationOfMemberEnum(Reader.getContext(), InstED, TSK);
00579     ED->getMemberSpecializationInfo()->setPointOfInstantiation(POI);
00580   }
00581 }
00582 
00583 ASTDeclReader::RedeclarableResult
00584 ASTDeclReader::VisitRecordDeclImpl(RecordDecl *RD) {
00585   RedeclarableResult Redecl = VisitTagDecl(RD);
00586   RD->setHasFlexibleArrayMember(Record[Idx++]);
00587   RD->setAnonymousStructOrUnion(Record[Idx++]);
00588   RD->setHasObjectMember(Record[Idx++]);
00589   RD->setHasVolatileMember(Record[Idx++]);
00590   return Redecl;
00591 }
00592 
00593 void ASTDeclReader::VisitValueDecl(ValueDecl *VD) {
00594   VisitNamedDecl(VD);
00595   VD->setType(Reader.readType(F, Record, Idx));
00596 }
00597 
00598 void ASTDeclReader::VisitEnumConstantDecl(EnumConstantDecl *ECD) {
00599   VisitValueDecl(ECD);
00600   if (Record[Idx++])
00601     ECD->setInitExpr(Reader.ReadExpr(F));
00602   ECD->setInitVal(Reader.ReadAPSInt(Record, Idx));
00603   mergeMergeable(ECD);
00604 }
00605 
00606 void ASTDeclReader::VisitDeclaratorDecl(DeclaratorDecl *DD) {
00607   VisitValueDecl(DD);
00608   DD->setInnerLocStart(ReadSourceLocation(Record, Idx));
00609   if (Record[Idx++]) { // hasExtInfo
00610     DeclaratorDecl::ExtInfo *Info
00611         = new (Reader.getContext()) DeclaratorDecl::ExtInfo();
00612     ReadQualifierInfo(*Info, Record, Idx);
00613     DD->DeclInfo = Info;
00614   }
00615 }
00616 
00617 void ASTDeclReader::VisitFunctionDecl(FunctionDecl *FD) {
00618   RedeclarableResult Redecl = VisitRedeclarable(FD);
00619   VisitDeclaratorDecl(FD);
00620 
00621   ReadDeclarationNameLoc(FD->DNLoc, FD->getDeclName(), Record, Idx);
00622   FD->IdentifierNamespace = Record[Idx++];
00623   
00624   // FunctionDecl's body is handled last at ASTDeclReader::Visit,
00625   // after everything else is read.
00626 
00627   FD->SClass = (StorageClass)Record[Idx++];
00628   FD->IsInline = Record[Idx++];
00629   FD->IsInlineSpecified = Record[Idx++];
00630   FD->IsVirtualAsWritten = Record[Idx++];
00631   FD->IsPure = Record[Idx++];
00632   FD->HasInheritedPrototype = Record[Idx++];
00633   FD->HasWrittenPrototype = Record[Idx++];
00634   FD->IsDeleted = Record[Idx++];
00635   FD->IsTrivial = Record[Idx++];
00636   FD->IsDefaulted = Record[Idx++];
00637   FD->IsExplicitlyDefaulted = Record[Idx++];
00638   FD->HasImplicitReturnZero = Record[Idx++];
00639   FD->IsConstexpr = Record[Idx++];
00640   FD->HasSkippedBody = Record[Idx++];
00641   FD->IsLateTemplateParsed = Record[Idx++];
00642   FD->setCachedLinkage(Linkage(Record[Idx++]));
00643   FD->EndRangeLoc = ReadSourceLocation(Record, Idx);
00644 
00645   switch ((FunctionDecl::TemplatedKind)Record[Idx++]) {
00646   case FunctionDecl::TK_NonTemplate:
00647     mergeRedeclarable(FD, Redecl);
00648     break;
00649   case FunctionDecl::TK_FunctionTemplate:
00650     // Merged when we merge the template.
00651     FD->setDescribedFunctionTemplate(ReadDeclAs<FunctionTemplateDecl>(Record, 
00652                                                                       Idx));
00653     break;
00654   case FunctionDecl::TK_MemberSpecialization: {
00655     FunctionDecl *InstFD = ReadDeclAs<FunctionDecl>(Record, Idx);
00656     TemplateSpecializationKind TSK = (TemplateSpecializationKind)Record[Idx++];
00657     SourceLocation POI = ReadSourceLocation(Record, Idx);
00658     FD->setInstantiationOfMemberFunction(Reader.getContext(), InstFD, TSK);
00659     FD->getMemberSpecializationInfo()->setPointOfInstantiation(POI);
00660     mergeRedeclarable(FD, Redecl);
00661     break;
00662   }
00663   case FunctionDecl::TK_FunctionTemplateSpecialization: {
00664     FunctionTemplateDecl *Template = ReadDeclAs<FunctionTemplateDecl>(Record, 
00665                                                                       Idx);
00666     TemplateSpecializationKind TSK = (TemplateSpecializationKind)Record[Idx++];
00667     
00668     // Template arguments.
00669     SmallVector<TemplateArgument, 8> TemplArgs;
00670     Reader.ReadTemplateArgumentList(TemplArgs, F, Record, Idx);
00671     
00672     // Template args as written.
00673     SmallVector<TemplateArgumentLoc, 8> TemplArgLocs;
00674     SourceLocation LAngleLoc, RAngleLoc;
00675     bool HasTemplateArgumentsAsWritten = Record[Idx++];
00676     if (HasTemplateArgumentsAsWritten) {
00677       unsigned NumTemplateArgLocs = Record[Idx++];
00678       TemplArgLocs.reserve(NumTemplateArgLocs);
00679       for (unsigned i=0; i != NumTemplateArgLocs; ++i)
00680         TemplArgLocs.push_back(
00681             Reader.ReadTemplateArgumentLoc(F, Record, Idx));
00682   
00683       LAngleLoc = ReadSourceLocation(Record, Idx);
00684       RAngleLoc = ReadSourceLocation(Record, Idx);
00685     }
00686     
00687     SourceLocation POI = ReadSourceLocation(Record, Idx);
00688 
00689     ASTContext &C = Reader.getContext();
00690     TemplateArgumentList *TemplArgList
00691       = TemplateArgumentList::CreateCopy(C, TemplArgs.data(), TemplArgs.size());
00692     TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
00693     for (unsigned i=0, e = TemplArgLocs.size(); i != e; ++i)
00694       TemplArgsInfo.addArgument(TemplArgLocs[i]);
00695     FunctionTemplateSpecializationInfo *FTInfo
00696         = FunctionTemplateSpecializationInfo::Create(C, FD, Template, TSK,
00697                                                      TemplArgList,
00698                              HasTemplateArgumentsAsWritten ? &TemplArgsInfo
00699                                                            : nullptr,
00700                                                      POI);
00701     FD->TemplateOrSpecialization = FTInfo;
00702 
00703     if (FD->isCanonicalDecl()) { // if canonical add to template's set.
00704       // The template that contains the specializations set. It's not safe to
00705       // use getCanonicalDecl on Template since it may still be initializing.
00706       FunctionTemplateDecl *CanonTemplate
00707         = ReadDeclAs<FunctionTemplateDecl>(Record, Idx);
00708       // Get the InsertPos by FindNodeOrInsertPos() instead of calling
00709       // InsertNode(FTInfo) directly to avoid the getASTContext() call in
00710       // FunctionTemplateSpecializationInfo's Profile().
00711       // We avoid getASTContext because a decl in the parent hierarchy may
00712       // be initializing.
00713       llvm::FoldingSetNodeID ID;
00714       FunctionTemplateSpecializationInfo::Profile(ID, TemplArgs, C);
00715       void *InsertPos = nullptr;
00716       FunctionTemplateDecl::Common *CommonPtr = CanonTemplate->getCommonPtr();
00717       CommonPtr->Specializations.FindNodeOrInsertPos(ID, InsertPos);
00718       if (InsertPos)
00719         CommonPtr->Specializations.InsertNode(FTInfo, InsertPos);
00720       else {
00721         assert(Reader.getContext().getLangOpts().Modules &&
00722                "already deserialized this template specialization");
00723         // FIXME: This specialization is a redeclaration of one from another
00724         // module. Merge it.
00725       }
00726     }
00727     break;
00728   }
00729   case FunctionDecl::TK_DependentFunctionTemplateSpecialization: {
00730     // Templates.
00731     UnresolvedSet<8> TemplDecls;
00732     unsigned NumTemplates = Record[Idx++];
00733     while (NumTemplates--)
00734       TemplDecls.addDecl(ReadDeclAs<NamedDecl>(Record, Idx));
00735     
00736     // Templates args.
00737     TemplateArgumentListInfo TemplArgs;
00738     unsigned NumArgs = Record[Idx++];
00739     while (NumArgs--)
00740       TemplArgs.addArgument(Reader.ReadTemplateArgumentLoc(F, Record, Idx));
00741     TemplArgs.setLAngleLoc(ReadSourceLocation(Record, Idx));
00742     TemplArgs.setRAngleLoc(ReadSourceLocation(Record, Idx));
00743     
00744     FD->setDependentTemplateSpecialization(Reader.getContext(),
00745                                            TemplDecls, TemplArgs);
00746 
00747     // FIXME: Merging.
00748     break;
00749   }
00750   }
00751 
00752   // Read in the parameters.
00753   unsigned NumParams = Record[Idx++];
00754   SmallVector<ParmVarDecl *, 16> Params;
00755   Params.reserve(NumParams);
00756   for (unsigned I = 0; I != NumParams; ++I)
00757     Params.push_back(ReadDeclAs<ParmVarDecl>(Record, Idx));
00758   FD->setParams(Reader.getContext(), Params);
00759 }
00760 
00761 void ASTDeclReader::VisitObjCMethodDecl(ObjCMethodDecl *MD) {
00762   VisitNamedDecl(MD);
00763   if (Record[Idx++]) {
00764     // Load the body on-demand. Most clients won't care, because method
00765     // definitions rarely show up in headers.
00766     Reader.PendingBodies[MD] = GetCurrentCursorOffset();
00767     HasPendingBody = true;
00768     MD->setSelfDecl(ReadDeclAs<ImplicitParamDecl>(Record, Idx));
00769     MD->setCmdDecl(ReadDeclAs<ImplicitParamDecl>(Record, Idx));
00770   }
00771   MD->setInstanceMethod(Record[Idx++]);
00772   MD->setVariadic(Record[Idx++]);
00773   MD->setPropertyAccessor(Record[Idx++]);
00774   MD->setDefined(Record[Idx++]);
00775   MD->IsOverriding = Record[Idx++];
00776   MD->HasSkippedBody = Record[Idx++];
00777 
00778   MD->IsRedeclaration = Record[Idx++];
00779   MD->HasRedeclaration = Record[Idx++];
00780   if (MD->HasRedeclaration)
00781     Reader.getContext().setObjCMethodRedeclaration(MD,
00782                                        ReadDeclAs<ObjCMethodDecl>(Record, Idx));
00783 
00784   MD->setDeclImplementation((ObjCMethodDecl::ImplementationControl)Record[Idx++]);
00785   MD->setObjCDeclQualifier((Decl::ObjCDeclQualifier)Record[Idx++]);
00786   MD->SetRelatedResultType(Record[Idx++]);
00787   MD->setReturnType(Reader.readType(F, Record, Idx));
00788   MD->setReturnTypeSourceInfo(GetTypeSourceInfo(Record, Idx));
00789   MD->DeclEndLoc = ReadSourceLocation(Record, Idx);
00790   unsigned NumParams = Record[Idx++];
00791   SmallVector<ParmVarDecl *, 16> Params;
00792   Params.reserve(NumParams);
00793   for (unsigned I = 0; I != NumParams; ++I)
00794     Params.push_back(ReadDeclAs<ParmVarDecl>(Record, Idx));
00795 
00796   MD->SelLocsKind = Record[Idx++];
00797   unsigned NumStoredSelLocs = Record[Idx++];
00798   SmallVector<SourceLocation, 16> SelLocs;
00799   SelLocs.reserve(NumStoredSelLocs);
00800   for (unsigned i = 0; i != NumStoredSelLocs; ++i)
00801     SelLocs.push_back(ReadSourceLocation(Record, Idx));
00802 
00803   MD->setParamsAndSelLocs(Reader.getContext(), Params, SelLocs);
00804 }
00805 
00806 void ASTDeclReader::VisitObjCContainerDecl(ObjCContainerDecl *CD) {
00807   VisitNamedDecl(CD);
00808   CD->setAtStartLoc(ReadSourceLocation(Record, Idx));
00809   CD->setAtEndRange(ReadSourceRange(Record, Idx));
00810 }
00811 
00812 void ASTDeclReader::VisitObjCInterfaceDecl(ObjCInterfaceDecl *ID) {
00813   RedeclarableResult Redecl = VisitRedeclarable(ID);
00814   VisitObjCContainerDecl(ID);
00815   TypeIDForTypeDecl = Reader.getGlobalTypeID(F, Record[Idx++]);
00816   mergeRedeclarable(ID, Redecl);
00817   
00818   if (Record[Idx++]) {
00819     // Read the definition.
00820     ID->allocateDefinitionData();
00821     
00822     // Set the definition data of the canonical declaration, so other
00823     // redeclarations will see it.
00824     ID->getCanonicalDecl()->Data = ID->Data;
00825     
00826     ObjCInterfaceDecl::DefinitionData &Data = ID->data();
00827     
00828     // Read the superclass.
00829     Data.SuperClass = ReadDeclAs<ObjCInterfaceDecl>(Record, Idx);
00830     Data.SuperClassLoc = ReadSourceLocation(Record, Idx);
00831 
00832     Data.EndLoc = ReadSourceLocation(Record, Idx);
00833     Data.HasDesignatedInitializers = Record[Idx++];
00834     
00835     // Read the directly referenced protocols and their SourceLocations.
00836     unsigned NumProtocols = Record[Idx++];
00837     SmallVector<ObjCProtocolDecl *, 16> Protocols;
00838     Protocols.reserve(NumProtocols);
00839     for (unsigned I = 0; I != NumProtocols; ++I)
00840       Protocols.push_back(ReadDeclAs<ObjCProtocolDecl>(Record, Idx));
00841     SmallVector<SourceLocation, 16> ProtoLocs;
00842     ProtoLocs.reserve(NumProtocols);
00843     for (unsigned I = 0; I != NumProtocols; ++I)
00844       ProtoLocs.push_back(ReadSourceLocation(Record, Idx));
00845     ID->setProtocolList(Protocols.data(), NumProtocols, ProtoLocs.data(),
00846                         Reader.getContext());
00847   
00848     // Read the transitive closure of protocols referenced by this class.
00849     NumProtocols = Record[Idx++];
00850     Protocols.clear();
00851     Protocols.reserve(NumProtocols);
00852     for (unsigned I = 0; I != NumProtocols; ++I)
00853       Protocols.push_back(ReadDeclAs<ObjCProtocolDecl>(Record, Idx));
00854     ID->data().AllReferencedProtocols.set(Protocols.data(), NumProtocols,
00855                                           Reader.getContext());
00856   
00857     // We will rebuild this list lazily.
00858     ID->setIvarList(nullptr);
00859 
00860     // Note that we have deserialized a definition.
00861     Reader.PendingDefinitions.insert(ID);
00862     
00863     // Note that we've loaded this Objective-C class.
00864     Reader.ObjCClassesLoaded.push_back(ID);
00865   } else {
00866     ID->Data = ID->getCanonicalDecl()->Data;
00867   }
00868 }
00869 
00870 void ASTDeclReader::VisitObjCIvarDecl(ObjCIvarDecl *IVD) {
00871   VisitFieldDecl(IVD);
00872   IVD->setAccessControl((ObjCIvarDecl::AccessControl)Record[Idx++]);
00873   // This field will be built lazily.
00874   IVD->setNextIvar(nullptr);
00875   bool synth = Record[Idx++];
00876   IVD->setSynthesize(synth);
00877 }
00878 
00879 void ASTDeclReader::VisitObjCProtocolDecl(ObjCProtocolDecl *PD) {
00880   RedeclarableResult Redecl = VisitRedeclarable(PD);
00881   VisitObjCContainerDecl(PD);
00882   mergeRedeclarable(PD, Redecl);
00883   
00884   if (Record[Idx++]) {
00885     // Read the definition.
00886     PD->allocateDefinitionData();
00887     
00888     // Set the definition data of the canonical declaration, so other
00889     // redeclarations will see it.
00890     PD->getCanonicalDecl()->Data = PD->Data;
00891 
00892     unsigned NumProtoRefs = Record[Idx++];
00893     SmallVector<ObjCProtocolDecl *, 16> ProtoRefs;
00894     ProtoRefs.reserve(NumProtoRefs);
00895     for (unsigned I = 0; I != NumProtoRefs; ++I)
00896       ProtoRefs.push_back(ReadDeclAs<ObjCProtocolDecl>(Record, Idx));
00897     SmallVector<SourceLocation, 16> ProtoLocs;
00898     ProtoLocs.reserve(NumProtoRefs);
00899     for (unsigned I = 0; I != NumProtoRefs; ++I)
00900       ProtoLocs.push_back(ReadSourceLocation(Record, Idx));
00901     PD->setProtocolList(ProtoRefs.data(), NumProtoRefs, ProtoLocs.data(),
00902                         Reader.getContext());
00903     
00904     // Note that we have deserialized a definition.
00905     Reader.PendingDefinitions.insert(PD);
00906   } else {
00907     PD->Data = PD->getCanonicalDecl()->Data;
00908   }
00909 }
00910 
00911 void ASTDeclReader::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *FD) {
00912   VisitFieldDecl(FD);
00913 }
00914 
00915 void ASTDeclReader::VisitObjCCategoryDecl(ObjCCategoryDecl *CD) {
00916   VisitObjCContainerDecl(CD);
00917   CD->setCategoryNameLoc(ReadSourceLocation(Record, Idx));
00918   CD->setIvarLBraceLoc(ReadSourceLocation(Record, Idx));
00919   CD->setIvarRBraceLoc(ReadSourceLocation(Record, Idx));
00920   
00921   // Note that this category has been deserialized. We do this before
00922   // deserializing the interface declaration, so that it will consider this
00923   /// category.
00924   Reader.CategoriesDeserialized.insert(CD);
00925 
00926   CD->ClassInterface = ReadDeclAs<ObjCInterfaceDecl>(Record, Idx);
00927   unsigned NumProtoRefs = Record[Idx++];
00928   SmallVector<ObjCProtocolDecl *, 16> ProtoRefs;
00929   ProtoRefs.reserve(NumProtoRefs);
00930   for (unsigned I = 0; I != NumProtoRefs; ++I)
00931     ProtoRefs.push_back(ReadDeclAs<ObjCProtocolDecl>(Record, Idx));
00932   SmallVector<SourceLocation, 16> ProtoLocs;
00933   ProtoLocs.reserve(NumProtoRefs);
00934   for (unsigned I = 0; I != NumProtoRefs; ++I)
00935     ProtoLocs.push_back(ReadSourceLocation(Record, Idx));
00936   CD->setProtocolList(ProtoRefs.data(), NumProtoRefs, ProtoLocs.data(),
00937                       Reader.getContext());
00938 }
00939 
00940 void ASTDeclReader::VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *CAD) {
00941   VisitNamedDecl(CAD);
00942   CAD->setClassInterface(ReadDeclAs<ObjCInterfaceDecl>(Record, Idx));
00943 }
00944 
00945 void ASTDeclReader::VisitObjCPropertyDecl(ObjCPropertyDecl *D) {
00946   VisitNamedDecl(D);
00947   D->setAtLoc(ReadSourceLocation(Record, Idx));
00948   D->setLParenLoc(ReadSourceLocation(Record, Idx));
00949   D->setType(GetTypeSourceInfo(Record, Idx));
00950   // FIXME: stable encoding
00951   D->setPropertyAttributes(
00952                       (ObjCPropertyDecl::PropertyAttributeKind)Record[Idx++]);
00953   D->setPropertyAttributesAsWritten(
00954                       (ObjCPropertyDecl::PropertyAttributeKind)Record[Idx++]);
00955   // FIXME: stable encoding
00956   D->setPropertyImplementation(
00957                             (ObjCPropertyDecl::PropertyControl)Record[Idx++]);
00958   D->setGetterName(Reader.ReadDeclarationName(F,Record, Idx).getObjCSelector());
00959   D->setSetterName(Reader.ReadDeclarationName(F,Record, Idx).getObjCSelector());
00960   D->setGetterMethodDecl(ReadDeclAs<ObjCMethodDecl>(Record, Idx));
00961   D->setSetterMethodDecl(ReadDeclAs<ObjCMethodDecl>(Record, Idx));
00962   D->setPropertyIvarDecl(ReadDeclAs<ObjCIvarDecl>(Record, Idx));
00963 }
00964 
00965 void ASTDeclReader::VisitObjCImplDecl(ObjCImplDecl *D) {
00966   VisitObjCContainerDecl(D);
00967   D->setClassInterface(ReadDeclAs<ObjCInterfaceDecl>(Record, Idx));
00968 }
00969 
00970 void ASTDeclReader::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
00971   VisitObjCImplDecl(D);
00972   D->setIdentifier(Reader.GetIdentifierInfo(F, Record, Idx));
00973   D->CategoryNameLoc = ReadSourceLocation(Record, Idx);
00974 }
00975 
00976 void ASTDeclReader::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
00977   VisitObjCImplDecl(D);
00978   D->setSuperClass(ReadDeclAs<ObjCInterfaceDecl>(Record, Idx));
00979   D->SuperLoc = ReadSourceLocation(Record, Idx);
00980   D->setIvarLBraceLoc(ReadSourceLocation(Record, Idx));
00981   D->setIvarRBraceLoc(ReadSourceLocation(Record, Idx));
00982   D->setHasNonZeroConstructors(Record[Idx++]);
00983   D->setHasDestructors(Record[Idx++]);
00984   std::tie(D->IvarInitializers, D->NumIvarInitializers) =
00985       Reader.ReadCXXCtorInitializers(F, Record, Idx);
00986 }
00987 
00988 
00989 void ASTDeclReader::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) {
00990   VisitDecl(D);
00991   D->setAtLoc(ReadSourceLocation(Record, Idx));
00992   D->setPropertyDecl(ReadDeclAs<ObjCPropertyDecl>(Record, Idx));
00993   D->PropertyIvarDecl = ReadDeclAs<ObjCIvarDecl>(Record, Idx);
00994   D->IvarLoc = ReadSourceLocation(Record, Idx);
00995   D->setGetterCXXConstructor(Reader.ReadExpr(F));
00996   D->setSetterCXXAssignment(Reader.ReadExpr(F));
00997 }
00998 
00999 void ASTDeclReader::VisitFieldDecl(FieldDecl *FD) {
01000   VisitDeclaratorDecl(FD);
01001   FD->Mutable = Record[Idx++];
01002   if (int BitWidthOrInitializer = Record[Idx++]) {
01003     FD->InitStorage.setInt(
01004           static_cast<FieldDecl::InitStorageKind>(BitWidthOrInitializer - 1));
01005     if (FD->InitStorage.getInt() == FieldDecl::ISK_CapturedVLAType) {
01006       // Read captured variable length array.
01007       FD->InitStorage.setPointer(
01008           Reader.readType(F, Record, Idx).getAsOpaquePtr());
01009     } else {
01010       FD->InitStorage.setPointer(Reader.ReadExpr(F));
01011     }
01012   }
01013   if (!FD->getDeclName()) {
01014     if (FieldDecl *Tmpl = ReadDeclAs<FieldDecl>(Record, Idx))
01015       Reader.getContext().setInstantiatedFromUnnamedFieldDecl(FD, Tmpl);
01016   }
01017   mergeMergeable(FD);
01018 }
01019 
01020 void ASTDeclReader::VisitMSPropertyDecl(MSPropertyDecl *PD) {
01021   VisitDeclaratorDecl(PD);
01022   PD->GetterId = Reader.GetIdentifierInfo(F, Record, Idx);
01023   PD->SetterId = Reader.GetIdentifierInfo(F, Record, Idx);
01024 }
01025 
01026 void ASTDeclReader::VisitIndirectFieldDecl(IndirectFieldDecl *FD) {
01027   VisitValueDecl(FD);
01028 
01029   FD->ChainingSize = Record[Idx++];
01030   assert(FD->ChainingSize >= 2 && "Anonymous chaining must be >= 2");
01031   FD->Chaining = new (Reader.getContext())NamedDecl*[FD->ChainingSize];
01032 
01033   for (unsigned I = 0; I != FD->ChainingSize; ++I)
01034     FD->Chaining[I] = ReadDeclAs<NamedDecl>(Record, Idx);
01035 }
01036 
01037 ASTDeclReader::RedeclarableResult ASTDeclReader::VisitVarDeclImpl(VarDecl *VD) {
01038   RedeclarableResult Redecl = VisitRedeclarable(VD);
01039   VisitDeclaratorDecl(VD);
01040 
01041   VD->VarDeclBits.SClass = (StorageClass)Record[Idx++];
01042   VD->VarDeclBits.TSCSpec = Record[Idx++];
01043   VD->VarDeclBits.InitStyle = Record[Idx++];
01044   VD->VarDeclBits.ExceptionVar = Record[Idx++];
01045   VD->VarDeclBits.NRVOVariable = Record[Idx++];
01046   VD->VarDeclBits.CXXForRangeDecl = Record[Idx++];
01047   VD->VarDeclBits.ARCPseudoStrong = Record[Idx++];
01048   VD->VarDeclBits.IsConstexpr = Record[Idx++];
01049   VD->VarDeclBits.IsInitCapture = Record[Idx++];
01050   VD->VarDeclBits.PreviousDeclInSameBlockScope = Record[Idx++];
01051   Linkage VarLinkage = Linkage(Record[Idx++]);
01052   VD->setCachedLinkage(VarLinkage);
01053 
01054   // Reconstruct the one piece of the IdentifierNamespace that we need.
01055   if (VD->getStorageClass() == SC_Extern && VarLinkage != NoLinkage &&
01056       VD->getLexicalDeclContext()->isFunctionOrMethod())
01057     VD->setLocalExternDecl();
01058 
01059   if (uint64_t Val = Record[Idx++]) {
01060     VD->setInit(Reader.ReadExpr(F));
01061     if (Val > 1) {
01062       EvaluatedStmt *Eval = VD->ensureEvaluatedStmt();
01063       Eval->CheckedICE = true;
01064       Eval->IsICE = Val == 3;
01065     }
01066   }
01067 
01068   enum VarKind {
01069     VarNotTemplate = 0, VarTemplate, StaticDataMemberSpecialization
01070   };
01071   switch ((VarKind)Record[Idx++]) {
01072   case VarNotTemplate:
01073     // Only true variables (not parameters or implicit parameters) can be merged
01074     if (VD->getKind() != Decl::ParmVar && VD->getKind() != Decl::ImplicitParam &&
01075         !isa<VarTemplateSpecializationDecl>(VD))
01076       mergeRedeclarable(VD, Redecl);
01077     break;
01078   case VarTemplate:
01079     // Merged when we merge the template.
01080     VD->setDescribedVarTemplate(ReadDeclAs<VarTemplateDecl>(Record, Idx));
01081     break;
01082   case StaticDataMemberSpecialization: { // HasMemberSpecializationInfo.
01083     VarDecl *Tmpl = ReadDeclAs<VarDecl>(Record, Idx);
01084     TemplateSpecializationKind TSK = (TemplateSpecializationKind)Record[Idx++];
01085     SourceLocation POI = ReadSourceLocation(Record, Idx);
01086     Reader.getContext().setInstantiatedFromStaticDataMember(VD, Tmpl, TSK,POI);
01087     mergeRedeclarable(VD, Redecl);
01088     break;
01089   }
01090   }
01091 
01092   return Redecl;
01093 }
01094 
01095 void ASTDeclReader::VisitImplicitParamDecl(ImplicitParamDecl *PD) {
01096   VisitVarDecl(PD);
01097 }
01098 
01099 void ASTDeclReader::VisitParmVarDecl(ParmVarDecl *PD) {
01100   VisitVarDecl(PD);
01101   unsigned isObjCMethodParam = Record[Idx++];
01102   unsigned scopeDepth = Record[Idx++];
01103   unsigned scopeIndex = Record[Idx++];
01104   unsigned declQualifier = Record[Idx++];
01105   if (isObjCMethodParam) {
01106     assert(scopeDepth == 0);
01107     PD->setObjCMethodScopeInfo(scopeIndex);
01108     PD->ParmVarDeclBits.ScopeDepthOrObjCQuals = declQualifier;
01109   } else {
01110     PD->setScopeInfo(scopeDepth, scopeIndex);
01111   }
01112   PD->ParmVarDeclBits.IsKNRPromoted = Record[Idx++];
01113   PD->ParmVarDeclBits.HasInheritedDefaultArg = Record[Idx++];
01114   if (Record[Idx++]) // hasUninstantiatedDefaultArg.
01115     PD->setUninstantiatedDefaultArg(Reader.ReadExpr(F));
01116 
01117   // FIXME: If this is a redeclaration of a function from another module, handle
01118   // inheritance of default arguments.
01119 }
01120 
01121 void ASTDeclReader::VisitFileScopeAsmDecl(FileScopeAsmDecl *AD) {
01122   VisitDecl(AD);
01123   AD->setAsmString(cast<StringLiteral>(Reader.ReadExpr(F)));
01124   AD->setRParenLoc(ReadSourceLocation(Record, Idx));
01125 }
01126 
01127 void ASTDeclReader::VisitBlockDecl(BlockDecl *BD) {
01128   VisitDecl(BD);
01129   BD->setBody(cast_or_null<CompoundStmt>(Reader.ReadStmt(F)));
01130   BD->setSignatureAsWritten(GetTypeSourceInfo(Record, Idx));
01131   unsigned NumParams = Record[Idx++];
01132   SmallVector<ParmVarDecl *, 16> Params;
01133   Params.reserve(NumParams);
01134   for (unsigned I = 0; I != NumParams; ++I)
01135     Params.push_back(ReadDeclAs<ParmVarDecl>(Record, Idx));
01136   BD->setParams(Params);
01137 
01138   BD->setIsVariadic(Record[Idx++]);
01139   BD->setBlockMissingReturnType(Record[Idx++]);
01140   BD->setIsConversionFromLambda(Record[Idx++]);
01141 
01142   bool capturesCXXThis = Record[Idx++];
01143   unsigned numCaptures = Record[Idx++];
01144   SmallVector<BlockDecl::Capture, 16> captures;
01145   captures.reserve(numCaptures);
01146   for (unsigned i = 0; i != numCaptures; ++i) {
01147     VarDecl *decl = ReadDeclAs<VarDecl>(Record, Idx);
01148     unsigned flags = Record[Idx++];
01149     bool byRef = (flags & 1);
01150     bool nested = (flags & 2);
01151     Expr *copyExpr = ((flags & 4) ? Reader.ReadExpr(F) : nullptr);
01152 
01153     captures.push_back(BlockDecl::Capture(decl, byRef, nested, copyExpr));
01154   }
01155   BD->setCaptures(Reader.getContext(), captures.begin(),
01156                   captures.end(), capturesCXXThis);
01157 }
01158 
01159 void ASTDeclReader::VisitCapturedDecl(CapturedDecl *CD) {
01160   VisitDecl(CD);
01161   unsigned ContextParamPos = Record[Idx++];
01162   CD->setNothrow(Record[Idx++] != 0);
01163   // Body is set by VisitCapturedStmt.
01164   for (unsigned I = 0; I < CD->NumParams; ++I) {
01165     if (I != ContextParamPos)
01166       CD->setParam(I, ReadDeclAs<ImplicitParamDecl>(Record, Idx));
01167     else
01168       CD->setContextParam(I, ReadDeclAs<ImplicitParamDecl>(Record, Idx));
01169   }
01170 }
01171 
01172 void ASTDeclReader::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
01173   VisitDecl(D);
01174   D->setLanguage((LinkageSpecDecl::LanguageIDs)Record[Idx++]);
01175   D->setExternLoc(ReadSourceLocation(Record, Idx));
01176   D->setRBraceLoc(ReadSourceLocation(Record, Idx));
01177 }
01178 
01179 void ASTDeclReader::VisitLabelDecl(LabelDecl *D) {
01180   VisitNamedDecl(D);
01181   D->setLocStart(ReadSourceLocation(Record, Idx));
01182 }
01183 
01184 
01185 void ASTDeclReader::VisitNamespaceDecl(NamespaceDecl *D) {
01186   RedeclarableResult Redecl = VisitRedeclarable(D);
01187   VisitNamedDecl(D);
01188   D->setInline(Record[Idx++]);
01189   D->LocStart = ReadSourceLocation(Record, Idx);
01190   D->RBraceLoc = ReadSourceLocation(Record, Idx);
01191 
01192   if (Redecl.getFirstID() == ThisDeclID) {
01193     // Each module has its own anonymous namespace, which is disjoint from
01194     // any other module's anonymous namespaces, so don't attach the anonymous
01195     // namespace at all.
01196     NamespaceDecl *Anon = ReadDeclAs<NamespaceDecl>(Record, Idx);
01197     if (F.Kind != MK_ImplicitModule && F.Kind != MK_ExplicitModule)
01198       D->setAnonymousNamespace(Anon);
01199   } else {
01200     // Link this namespace back to the first declaration, which has already
01201     // been deserialized.
01202     D->AnonOrFirstNamespaceAndInline.setPointer(D->getFirstDecl());
01203   }
01204 
01205   mergeRedeclarable(D, Redecl);
01206 }
01207 
01208 void ASTDeclReader::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
01209   RedeclarableResult Redecl = VisitRedeclarable(D);
01210   VisitNamedDecl(D);
01211   D->NamespaceLoc = ReadSourceLocation(Record, Idx);
01212   D->IdentLoc = ReadSourceLocation(Record, Idx);
01213   D->QualifierLoc = Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
01214   D->Namespace = ReadDeclAs<NamedDecl>(Record, Idx);
01215   mergeRedeclarable(D, Redecl);
01216 }
01217 
01218 void ASTDeclReader::VisitUsingDecl(UsingDecl *D) {
01219   VisitNamedDecl(D);
01220   D->setUsingLoc(ReadSourceLocation(Record, Idx));
01221   D->QualifierLoc = Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
01222   ReadDeclarationNameLoc(D->DNLoc, D->getDeclName(), Record, Idx);
01223   D->FirstUsingShadow.setPointer(ReadDeclAs<UsingShadowDecl>(Record, Idx));
01224   D->setTypename(Record[Idx++]);
01225   if (NamedDecl *Pattern = ReadDeclAs<NamedDecl>(Record, Idx))
01226     Reader.getContext().setInstantiatedFromUsingDecl(D, Pattern);
01227   mergeMergeable(D);
01228 }
01229 
01230 void ASTDeclReader::VisitUsingShadowDecl(UsingShadowDecl *D) {
01231   RedeclarableResult Redecl = VisitRedeclarable(D);
01232   VisitNamedDecl(D);
01233   D->setTargetDecl(ReadDeclAs<NamedDecl>(Record, Idx));
01234   D->UsingOrNextShadow = ReadDeclAs<NamedDecl>(Record, Idx);
01235   UsingShadowDecl *Pattern = ReadDeclAs<UsingShadowDecl>(Record, Idx);
01236   if (Pattern)
01237     Reader.getContext().setInstantiatedFromUsingShadowDecl(D, Pattern);
01238   mergeRedeclarable(D, Redecl);
01239 }
01240 
01241 void ASTDeclReader::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
01242   VisitNamedDecl(D);
01243   D->UsingLoc = ReadSourceLocation(Record, Idx);
01244   D->NamespaceLoc = ReadSourceLocation(Record, Idx);
01245   D->QualifierLoc = Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
01246   D->NominatedNamespace = ReadDeclAs<NamedDecl>(Record, Idx);
01247   D->CommonAncestor = ReadDeclAs<DeclContext>(Record, Idx);
01248 }
01249 
01250 void ASTDeclReader::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
01251   VisitValueDecl(D);
01252   D->setUsingLoc(ReadSourceLocation(Record, Idx));
01253   D->QualifierLoc = Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
01254   ReadDeclarationNameLoc(D->DNLoc, D->getDeclName(), Record, Idx);
01255   mergeMergeable(D);
01256 }
01257 
01258 void ASTDeclReader::VisitUnresolvedUsingTypenameDecl(
01259                                                UnresolvedUsingTypenameDecl *D) {
01260   VisitTypeDecl(D);
01261   D->TypenameLocation = ReadSourceLocation(Record, Idx);
01262   D->QualifierLoc = Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
01263   mergeMergeable(D);
01264 }
01265 
01266 void ASTDeclReader::ReadCXXDefinitionData(
01267                                    struct CXXRecordDecl::DefinitionData &Data,
01268                                    const RecordData &Record, unsigned &Idx) {
01269   // Note: the caller has deserialized the IsLambda bit already.
01270   Data.UserDeclaredConstructor = Record[Idx++];
01271   Data.UserDeclaredSpecialMembers = Record[Idx++];
01272   Data.Aggregate = Record[Idx++];
01273   Data.PlainOldData = Record[Idx++];
01274   Data.Empty = Record[Idx++];
01275   Data.Polymorphic = Record[Idx++];
01276   Data.Abstract = Record[Idx++];
01277   Data.IsStandardLayout = Record[Idx++];
01278   Data.HasNoNonEmptyBases = Record[Idx++];
01279   Data.HasPrivateFields = Record[Idx++];
01280   Data.HasProtectedFields = Record[Idx++];
01281   Data.HasPublicFields = Record[Idx++];
01282   Data.HasMutableFields = Record[Idx++];
01283   Data.HasVariantMembers = Record[Idx++];
01284   Data.HasOnlyCMembers = Record[Idx++];
01285   Data.HasInClassInitializer = Record[Idx++];
01286   Data.HasUninitializedReferenceMember = Record[Idx++];
01287   Data.NeedOverloadResolutionForMoveConstructor = Record[Idx++];
01288   Data.NeedOverloadResolutionForMoveAssignment = Record[Idx++];
01289   Data.NeedOverloadResolutionForDestructor = Record[Idx++];
01290   Data.DefaultedMoveConstructorIsDeleted = Record[Idx++];
01291   Data.DefaultedMoveAssignmentIsDeleted = Record[Idx++];
01292   Data.DefaultedDestructorIsDeleted = Record[Idx++];
01293   Data.HasTrivialSpecialMembers = Record[Idx++];
01294   Data.DeclaredNonTrivialSpecialMembers = Record[Idx++];
01295   Data.HasIrrelevantDestructor = Record[Idx++];
01296   Data.HasConstexprNonCopyMoveConstructor = Record[Idx++];
01297   Data.DefaultedDefaultConstructorIsConstexpr = Record[Idx++];
01298   Data.HasConstexprDefaultConstructor = Record[Idx++];
01299   Data.HasNonLiteralTypeFieldsOrBases = Record[Idx++];
01300   Data.ComputedVisibleConversions = Record[Idx++];
01301   Data.UserProvidedDefaultConstructor = Record[Idx++];
01302   Data.DeclaredSpecialMembers = Record[Idx++];
01303   Data.ImplicitCopyConstructorHasConstParam = Record[Idx++];
01304   Data.ImplicitCopyAssignmentHasConstParam = Record[Idx++];
01305   Data.HasDeclaredCopyConstructorWithConstParam = Record[Idx++];
01306   Data.HasDeclaredCopyAssignmentWithConstParam = Record[Idx++];
01307 
01308   Data.NumBases = Record[Idx++];
01309   if (Data.NumBases)
01310     Data.Bases = Reader.readCXXBaseSpecifiers(F, Record, Idx);
01311   Data.NumVBases = Record[Idx++];
01312   if (Data.NumVBases)
01313     Data.VBases = Reader.readCXXBaseSpecifiers(F, Record, Idx);
01314   
01315   Reader.ReadUnresolvedSet(F, Data.Conversions, Record, Idx);
01316   Reader.ReadUnresolvedSet(F, Data.VisibleConversions, Record, Idx);
01317   assert(Data.Definition && "Data.Definition should be already set!");
01318   Data.FirstFriend = ReadDeclID(Record, Idx);
01319 
01320   if (Data.IsLambda) {
01321     typedef LambdaCapture Capture;
01322     CXXRecordDecl::LambdaDefinitionData &Lambda
01323       = static_cast<CXXRecordDecl::LambdaDefinitionData &>(Data);
01324     Lambda.Dependent = Record[Idx++];
01325     Lambda.IsGenericLambda = Record[Idx++];
01326     Lambda.CaptureDefault = Record[Idx++];
01327     Lambda.NumCaptures = Record[Idx++];
01328     Lambda.NumExplicitCaptures = Record[Idx++];
01329     Lambda.ManglingNumber = Record[Idx++];
01330     Lambda.ContextDecl = ReadDecl(Record, Idx);
01331     Lambda.Captures 
01332       = (Capture*)Reader.Context.Allocate(sizeof(Capture)*Lambda.NumCaptures);
01333     Capture *ToCapture = Lambda.Captures;
01334     Lambda.MethodTyInfo = GetTypeSourceInfo(Record, Idx);
01335     for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) {
01336       SourceLocation Loc = ReadSourceLocation(Record, Idx);
01337       bool IsImplicit = Record[Idx++];
01338       LambdaCaptureKind Kind = static_cast<LambdaCaptureKind>(Record[Idx++]);
01339       switch (Kind) {
01340       case LCK_This:
01341       case LCK_VLAType:
01342         *ToCapture++ = Capture(Loc, IsImplicit, Kind, nullptr,SourceLocation());
01343         break;
01344       case LCK_ByCopy:
01345       case LCK_ByRef:
01346         VarDecl *Var = ReadDeclAs<VarDecl>(Record, Idx);
01347         SourceLocation EllipsisLoc = ReadSourceLocation(Record, Idx);
01348         *ToCapture++ = Capture(Loc, IsImplicit, Kind, Var, EllipsisLoc);
01349         break;
01350       }
01351     }
01352   }
01353 }
01354 
01355 void ASTDeclReader::MergeDefinitionData(
01356     CXXRecordDecl *D, struct CXXRecordDecl::DefinitionData &MergeDD) {
01357   assert(D->DefinitionData.getNotUpdated() &&
01358          "merging class definition into non-definition");
01359   auto &DD = *D->DefinitionData.getNotUpdated();
01360 
01361   // If the new definition has new special members, let the name lookup
01362   // code know that it needs to look in the new definition too.
01363   //
01364   // FIXME: We only need to do this if the merged definition declares members
01365   // that this definition did not declare, or if it defines members that this
01366   // definition did not define.
01367   if (MergeDD.DeclaredSpecialMembers && DD.Definition != MergeDD.Definition) {
01368     Reader.MergedLookups[DD.Definition].push_back(MergeDD.Definition);
01369     DD.Definition->setHasExternalVisibleStorage();
01370   }
01371 
01372   // FIXME: Move this out into a .def file?
01373   // FIXME: Issue a diagnostic on a mismatched MATCH_FIELD, rather than
01374   // asserting; this can happen in the case of an ODR violation.
01375   bool DetectedOdrViolation = false;
01376 #define OR_FIELD(Field) DD.Field |= MergeDD.Field;
01377 #define MATCH_FIELD(Field) \
01378     DetectedOdrViolation |= DD.Field != MergeDD.Field; \
01379     OR_FIELD(Field)
01380   MATCH_FIELD(UserDeclaredConstructor)
01381   MATCH_FIELD(UserDeclaredSpecialMembers)
01382   MATCH_FIELD(Aggregate)
01383   MATCH_FIELD(PlainOldData)
01384   MATCH_FIELD(Empty)
01385   MATCH_FIELD(Polymorphic)
01386   MATCH_FIELD(Abstract)
01387   MATCH_FIELD(IsStandardLayout)
01388   MATCH_FIELD(HasNoNonEmptyBases)
01389   MATCH_FIELD(HasPrivateFields)
01390   MATCH_FIELD(HasProtectedFields)
01391   MATCH_FIELD(HasPublicFields)
01392   MATCH_FIELD(HasMutableFields)
01393   MATCH_FIELD(HasVariantMembers)
01394   MATCH_FIELD(HasOnlyCMembers)
01395   MATCH_FIELD(HasInClassInitializer)
01396   MATCH_FIELD(HasUninitializedReferenceMember)
01397   MATCH_FIELD(NeedOverloadResolutionForMoveConstructor)
01398   MATCH_FIELD(NeedOverloadResolutionForMoveAssignment)
01399   MATCH_FIELD(NeedOverloadResolutionForDestructor)
01400   MATCH_FIELD(DefaultedMoveConstructorIsDeleted)
01401   MATCH_FIELD(DefaultedMoveAssignmentIsDeleted)
01402   MATCH_FIELD(DefaultedDestructorIsDeleted)
01403   OR_FIELD(HasTrivialSpecialMembers)
01404   OR_FIELD(DeclaredNonTrivialSpecialMembers)
01405   MATCH_FIELD(HasIrrelevantDestructor)
01406   OR_FIELD(HasConstexprNonCopyMoveConstructor)
01407   MATCH_FIELD(DefaultedDefaultConstructorIsConstexpr)
01408   OR_FIELD(HasConstexprDefaultConstructor)
01409   MATCH_FIELD(HasNonLiteralTypeFieldsOrBases)
01410   // ComputedVisibleConversions is handled below.
01411   MATCH_FIELD(UserProvidedDefaultConstructor)
01412   OR_FIELD(DeclaredSpecialMembers)
01413   MATCH_FIELD(ImplicitCopyConstructorHasConstParam)
01414   MATCH_FIELD(ImplicitCopyAssignmentHasConstParam)
01415   OR_FIELD(HasDeclaredCopyConstructorWithConstParam)
01416   OR_FIELD(HasDeclaredCopyAssignmentWithConstParam)
01417   MATCH_FIELD(IsLambda)
01418 #undef OR_FIELD
01419 #undef MATCH_FIELD
01420 
01421   if (DD.NumBases != MergeDD.NumBases || DD.NumVBases != MergeDD.NumVBases)
01422     DetectedOdrViolation = true;
01423   // FIXME: Issue a diagnostic if the base classes don't match when we come
01424   // to lazily load them.
01425 
01426   // FIXME: Issue a diagnostic if the list of conversion functions doesn't
01427   // match when we come to lazily load them.
01428   if (MergeDD.ComputedVisibleConversions && !DD.ComputedVisibleConversions) {
01429     DD.VisibleConversions = std::move(MergeDD.VisibleConversions);
01430     DD.ComputedVisibleConversions = true;
01431   }
01432 
01433   // FIXME: Issue a diagnostic if FirstFriend doesn't match when we come to
01434   // lazily load it.
01435 
01436   if (DD.IsLambda) {
01437     // FIXME: ODR-checking for merging lambdas (this happens, for instance,
01438     // when they occur within the body of a function template specialization).
01439   }
01440 
01441   if (DetectedOdrViolation)
01442     Reader.PendingOdrMergeFailures[DD.Definition].push_back(MergeDD.Definition);
01443 }
01444 
01445 void ASTDeclReader::ReadCXXRecordDefinition(CXXRecordDecl *D) {
01446   struct CXXRecordDecl::DefinitionData *DD;
01447   ASTContext &C = Reader.getContext();
01448 
01449   // Determine whether this is a lambda closure type, so that we can
01450   // allocate the appropriate DefinitionData structure.
01451   bool IsLambda = Record[Idx++];
01452   if (IsLambda)
01453     DD = new (C) CXXRecordDecl::LambdaDefinitionData(D, nullptr, false, false,
01454                                                      LCD_None);
01455   else
01456     DD = new (C) struct CXXRecordDecl::DefinitionData(D);
01457 
01458   ReadCXXDefinitionData(*DD, Record, Idx);
01459 
01460   // If we're reading an update record, we might already have a definition for
01461   // this record. If so, just merge into it.
01462   if (D->DefinitionData.getNotUpdated()) {
01463     MergeDefinitionData(D, *DD);
01464     return;
01465   }
01466 
01467   // Propagate the DefinitionData pointer to the canonical declaration, so
01468   // that all other deserialized declarations will see it.
01469   CXXRecordDecl *Canon = D->getCanonicalDecl();
01470   if (Canon == D) {
01471     D->DefinitionData = DD;
01472     D->IsCompleteDefinition = true;
01473   } else if (auto *CanonDD = Canon->DefinitionData.getNotUpdated()) {
01474     // We have already deserialized a definition of this record. This
01475     // definition is no longer really a definition. Note that the pre-existing
01476     // definition is the *real* definition.
01477     Reader.MergedDeclContexts.insert(
01478         std::make_pair(D, CanonDD->Definition));
01479     D->DefinitionData = Canon->DefinitionData;
01480     D->IsCompleteDefinition = false;
01481     MergeDefinitionData(D, *DD);
01482   } else {
01483     Canon->DefinitionData = DD;
01484     D->DefinitionData = Canon->DefinitionData;
01485     D->IsCompleteDefinition = true;
01486 
01487     // Note that we have deserialized a definition. Any declarations
01488     // deserialized before this one will be be given the DefinitionData
01489     // pointer at the end.
01490     Reader.PendingDefinitions.insert(D);
01491   }
01492 }
01493 
01494 ASTDeclReader::RedeclarableResult
01495 ASTDeclReader::VisitCXXRecordDeclImpl(CXXRecordDecl *D) {
01496   RedeclarableResult Redecl = VisitRecordDeclImpl(D);
01497 
01498   ASTContext &C = Reader.getContext();
01499 
01500   enum CXXRecKind {
01501     CXXRecNotTemplate = 0, CXXRecTemplate, CXXRecMemberSpecialization
01502   };
01503   switch ((CXXRecKind)Record[Idx++]) {
01504   case CXXRecNotTemplate:
01505     // Merged when we merge the folding set entry in the primary template.
01506     if (!isa<ClassTemplateSpecializationDecl>(D))
01507       mergeRedeclarable(D, Redecl);
01508     break;
01509   case CXXRecTemplate: {
01510     // Merged when we merge the template.
01511     ClassTemplateDecl *Template = ReadDeclAs<ClassTemplateDecl>(Record, Idx);
01512     D->TemplateOrInstantiation = Template;
01513     if (!Template->getTemplatedDecl()) {
01514       // We've not actually loaded the ClassTemplateDecl yet, because we're
01515       // currently being loaded as its pattern. Rely on it to set up our
01516       // TypeForDecl (see VisitClassTemplateDecl).
01517       //
01518       // Beware: we do not yet know our canonical declaration, and may still
01519       // get merged once the surrounding class template has got off the ground.
01520       TypeIDForTypeDecl = 0;
01521     }
01522     break;
01523   }
01524   case CXXRecMemberSpecialization: {
01525     CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(Record, Idx);
01526     TemplateSpecializationKind TSK = (TemplateSpecializationKind)Record[Idx++];
01527     SourceLocation POI = ReadSourceLocation(Record, Idx);
01528     MemberSpecializationInfo *MSI = new (C) MemberSpecializationInfo(RD, TSK);
01529     MSI->setPointOfInstantiation(POI);
01530     D->TemplateOrInstantiation = MSI;
01531     mergeRedeclarable(D, Redecl);
01532     break;
01533   }
01534   }
01535 
01536   bool WasDefinition = Record[Idx++];
01537   if (WasDefinition)
01538     ReadCXXRecordDefinition(D);
01539   else
01540     // Propagate DefinitionData pointer from the canonical declaration.
01541     D->DefinitionData = D->getCanonicalDecl()->DefinitionData;
01542 
01543   // Lazily load the key function to avoid deserializing every method so we can
01544   // compute it.
01545   if (WasDefinition) {
01546     DeclID KeyFn = ReadDeclID(Record, Idx);
01547     if (KeyFn && D->IsCompleteDefinition)
01548       // FIXME: This is wrong for the ARM ABI, where some other module may have
01549       // made this function no longer be a key function. We need an update
01550       // record or similar for that case.
01551       C.KeyFunctions[D] = KeyFn;
01552   }
01553 
01554   return Redecl;
01555 }
01556 
01557 void ASTDeclReader::VisitCXXMethodDecl(CXXMethodDecl *D) {
01558   VisitFunctionDecl(D);
01559 
01560   unsigned NumOverridenMethods = Record[Idx++];
01561   if (D->isCanonicalDecl()) {
01562     while (NumOverridenMethods--) {
01563       // Avoid invariant checking of CXXMethodDecl::addOverriddenMethod,
01564       // MD may be initializing.
01565       if (CXXMethodDecl *MD = ReadDeclAs<CXXMethodDecl>(Record, Idx))
01566         Reader.getContext().addOverriddenMethod(D, MD->getCanonicalDecl());
01567     }
01568   } else {
01569     // We don't care about which declarations this used to override; we get
01570     // the relevant information from the canonical declaration.
01571     Idx += NumOverridenMethods;
01572   }
01573 }
01574 
01575 void ASTDeclReader::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
01576   VisitCXXMethodDecl(D);
01577 
01578   if (auto *CD = ReadDeclAs<CXXConstructorDecl>(Record, Idx))
01579     D->setInheritedConstructor(CD);
01580   D->IsExplicitSpecified = Record[Idx++];
01581   // FIXME: We should defer loading this until we need the constructor's body.
01582   std::tie(D->CtorInitializers, D->NumCtorInitializers) =
01583       Reader.ReadCXXCtorInitializers(F, Record, Idx);
01584 }
01585 
01586 void ASTDeclReader::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
01587   VisitCXXMethodDecl(D);
01588 
01589   D->OperatorDelete = ReadDeclAs<FunctionDecl>(Record, Idx);
01590 }
01591 
01592 void ASTDeclReader::VisitCXXConversionDecl(CXXConversionDecl *D) {
01593   VisitCXXMethodDecl(D);
01594   D->IsExplicitSpecified = Record[Idx++];
01595 }
01596 
01597 void ASTDeclReader::VisitImportDecl(ImportDecl *D) {
01598   VisitDecl(D);
01599   D->ImportedAndComplete.setPointer(readModule(Record, Idx));
01600   D->ImportedAndComplete.setInt(Record[Idx++]);
01601   SourceLocation *StoredLocs = reinterpret_cast<SourceLocation *>(D + 1);
01602   for (unsigned I = 0, N = Record.back(); I != N; ++I)
01603     StoredLocs[I] = ReadSourceLocation(Record, Idx);
01604   ++Idx; // The number of stored source locations.
01605 }
01606 
01607 void ASTDeclReader::VisitAccessSpecDecl(AccessSpecDecl *D) {
01608   VisitDecl(D);
01609   D->setColonLoc(ReadSourceLocation(Record, Idx));
01610 }
01611 
01612 void ASTDeclReader::VisitFriendDecl(FriendDecl *D) {
01613   VisitDecl(D);
01614   if (Record[Idx++]) // hasFriendDecl
01615     D->Friend = ReadDeclAs<NamedDecl>(Record, Idx);
01616   else
01617     D->Friend = GetTypeSourceInfo(Record, Idx);
01618   for (unsigned i = 0; i != D->NumTPLists; ++i)
01619     D->getTPLists()[i] = Reader.ReadTemplateParameterList(F, Record, Idx);
01620   D->NextFriend = ReadDeclID(Record, Idx);
01621   D->UnsupportedFriend = (Record[Idx++] != 0);
01622   D->FriendLoc = ReadSourceLocation(Record, Idx);
01623 }
01624 
01625 void ASTDeclReader::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
01626   VisitDecl(D);
01627   unsigned NumParams = Record[Idx++];
01628   D->NumParams = NumParams;
01629   D->Params = new TemplateParameterList*[NumParams];
01630   for (unsigned i = 0; i != NumParams; ++i)
01631     D->Params[i] = Reader.ReadTemplateParameterList(F, Record, Idx);
01632   if (Record[Idx++]) // HasFriendDecl
01633     D->Friend = ReadDeclAs<NamedDecl>(Record, Idx);
01634   else
01635     D->Friend = GetTypeSourceInfo(Record, Idx);
01636   D->FriendLoc = ReadSourceLocation(Record, Idx);
01637 }
01638 
01639 DeclID ASTDeclReader::VisitTemplateDecl(TemplateDecl *D) {
01640   VisitNamedDecl(D);
01641 
01642   DeclID PatternID = ReadDeclID(Record, Idx);
01643   NamedDecl *TemplatedDecl = cast_or_null<NamedDecl>(Reader.GetDecl(PatternID));
01644   TemplateParameterList* TemplateParams
01645       = Reader.ReadTemplateParameterList(F, Record, Idx); 
01646   D->init(TemplatedDecl, TemplateParams);
01647 
01648   // FIXME: If this is a redeclaration of a template from another module, handle
01649   // inheritance of default template arguments.
01650 
01651   return PatternID;
01652 }
01653 
01654 ASTDeclReader::RedeclarableResult 
01655 ASTDeclReader::VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D) {
01656   RedeclarableResult Redecl = VisitRedeclarable(D);
01657 
01658   // Make sure we've allocated the Common pointer first. We do this before
01659   // VisitTemplateDecl so that getCommonPtr() can be used during initialization.
01660   RedeclarableTemplateDecl *CanonD = D->getCanonicalDecl();
01661   if (!CanonD->Common) {
01662     CanonD->Common = CanonD->newCommon(Reader.getContext());
01663     Reader.PendingDefinitions.insert(CanonD);
01664   }
01665   D->Common = CanonD->Common;
01666 
01667   // If this is the first declaration of the template, fill in the information
01668   // for the 'common' pointer.
01669   if (ThisDeclID == Redecl.getFirstID()) {
01670     if (RedeclarableTemplateDecl *RTD
01671           = ReadDeclAs<RedeclarableTemplateDecl>(Record, Idx)) {
01672       assert(RTD->getKind() == D->getKind() &&
01673              "InstantiatedFromMemberTemplate kind mismatch");
01674       D->setInstantiatedFromMemberTemplate(RTD);
01675       if (Record[Idx++])
01676         D->setMemberSpecialization();
01677     }
01678   }
01679 
01680   DeclID PatternID = VisitTemplateDecl(D);
01681   D->IdentifierNamespace = Record[Idx++];
01682 
01683   mergeRedeclarable(D, Redecl, PatternID);
01684 
01685   // If we merged the template with a prior declaration chain, merge the common
01686   // pointer.
01687   // FIXME: Actually merge here, don't just overwrite.
01688   D->Common = D->getCanonicalDecl()->Common;
01689 
01690   return Redecl;
01691 }
01692 
01693 void ASTDeclReader::VisitClassTemplateDecl(ClassTemplateDecl *D) {
01694   RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
01695 
01696   if (ThisDeclID == Redecl.getFirstID()) {
01697     // This ClassTemplateDecl owns a CommonPtr; read it to keep track of all of
01698     // the specializations.
01699     SmallVector<serialization::DeclID, 2> SpecIDs;
01700     SpecIDs.push_back(0);
01701     
01702     // Specializations.
01703     unsigned Size = Record[Idx++];
01704     SpecIDs[0] += Size;
01705     for (unsigned I = 0; I != Size; ++I)
01706       SpecIDs.push_back(ReadDeclID(Record, Idx));
01707 
01708     // Partial specializations.
01709     Size = Record[Idx++];
01710     SpecIDs[0] += Size;
01711     for (unsigned I = 0; I != Size; ++I)
01712       SpecIDs.push_back(ReadDeclID(Record, Idx));
01713 
01714     ClassTemplateDecl::Common *CommonPtr = D->getCommonPtr();
01715     if (SpecIDs[0]) {
01716       typedef serialization::DeclID DeclID;
01717       
01718       // FIXME: Append specializations!
01719       CommonPtr->LazySpecializations
01720         = new (Reader.getContext()) DeclID [SpecIDs.size()];
01721       memcpy(CommonPtr->LazySpecializations, SpecIDs.data(), 
01722              SpecIDs.size() * sizeof(DeclID));
01723     }
01724   }
01725 
01726   if (D->getTemplatedDecl()->TemplateOrInstantiation) {
01727     // We were loaded before our templated declaration was. We've not set up
01728     // its corresponding type yet (see VisitCXXRecordDeclImpl), so reconstruct
01729     // it now.
01730     Reader.Context.getInjectedClassNameType(
01731         D->getTemplatedDecl(), D->getInjectedClassNameSpecialization());
01732   }
01733 }
01734 
01735 /// TODO: Unify with ClassTemplateDecl version?
01736 ///       May require unifying ClassTemplateDecl and
01737 ///        VarTemplateDecl beyond TemplateDecl...
01738 void ASTDeclReader::VisitVarTemplateDecl(VarTemplateDecl *D) {
01739   RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
01740 
01741   if (ThisDeclID == Redecl.getFirstID()) {
01742     // This VarTemplateDecl owns a CommonPtr; read it to keep track of all of
01743     // the specializations.
01744     SmallVector<serialization::DeclID, 2> SpecIDs;
01745     SpecIDs.push_back(0);
01746 
01747     // Specializations.
01748     unsigned Size = Record[Idx++];
01749     SpecIDs[0] += Size;
01750     for (unsigned I = 0; I != Size; ++I)
01751       SpecIDs.push_back(ReadDeclID(Record, Idx));
01752 
01753     // Partial specializations.
01754     Size = Record[Idx++];
01755     SpecIDs[0] += Size;
01756     for (unsigned I = 0; I != Size; ++I)
01757       SpecIDs.push_back(ReadDeclID(Record, Idx));
01758 
01759     VarTemplateDecl::Common *CommonPtr = D->getCommonPtr();
01760     if (SpecIDs[0]) {
01761       typedef serialization::DeclID DeclID;
01762 
01763       // FIXME: Append specializations!
01764       CommonPtr->LazySpecializations =
01765           new (Reader.getContext()) DeclID[SpecIDs.size()];
01766       memcpy(CommonPtr->LazySpecializations, SpecIDs.data(),
01767              SpecIDs.size() * sizeof(DeclID));
01768     }
01769   }
01770 }
01771 
01772 ASTDeclReader::RedeclarableResult
01773 ASTDeclReader::VisitClassTemplateSpecializationDeclImpl(
01774     ClassTemplateSpecializationDecl *D) {
01775   RedeclarableResult Redecl = VisitCXXRecordDeclImpl(D);
01776   
01777   ASTContext &C = Reader.getContext();
01778   if (Decl *InstD = ReadDecl(Record, Idx)) {
01779     if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(InstD)) {
01780       D->SpecializedTemplate = CTD;
01781     } else {
01782       SmallVector<TemplateArgument, 8> TemplArgs;
01783       Reader.ReadTemplateArgumentList(TemplArgs, F, Record, Idx);
01784       TemplateArgumentList *ArgList
01785         = TemplateArgumentList::CreateCopy(C, TemplArgs.data(), 
01786                                            TemplArgs.size());
01787       ClassTemplateSpecializationDecl::SpecializedPartialSpecialization *PS
01788           = new (C) ClassTemplateSpecializationDecl::
01789                                              SpecializedPartialSpecialization();
01790       PS->PartialSpecialization
01791           = cast<ClassTemplatePartialSpecializationDecl>(InstD);
01792       PS->TemplateArgs = ArgList;
01793       D->SpecializedTemplate = PS;
01794     }
01795   }
01796 
01797   SmallVector<TemplateArgument, 8> TemplArgs;
01798   Reader.ReadTemplateArgumentList(TemplArgs, F, Record, Idx);
01799   D->TemplateArgs = TemplateArgumentList::CreateCopy(C, TemplArgs.data(), 
01800                                                      TemplArgs.size());
01801   D->PointOfInstantiation = ReadSourceLocation(Record, Idx);
01802   D->SpecializationKind = (TemplateSpecializationKind)Record[Idx++];
01803 
01804   bool writtenAsCanonicalDecl = Record[Idx++];
01805   if (writtenAsCanonicalDecl) {
01806     ClassTemplateDecl *CanonPattern = ReadDeclAs<ClassTemplateDecl>(Record,Idx);
01807     if (D->isCanonicalDecl()) { // It's kept in the folding set.
01808       // Set this as, or find, the canonical declaration for this specialization
01809       ClassTemplateSpecializationDecl *CanonSpec;
01810       if (ClassTemplatePartialSpecializationDecl *Partial =
01811               dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) {
01812         CanonSpec = CanonPattern->getCommonPtr()->PartialSpecializations
01813             .GetOrInsertNode(Partial);
01814       } else {
01815         CanonSpec =
01816             CanonPattern->getCommonPtr()->Specializations.GetOrInsertNode(D);
01817       }
01818       // If there was already a canonical specialization, merge into it.
01819       if (CanonSpec != D) {
01820         mergeRedeclarable<TagDecl>(D, CanonSpec, Redecl);
01821 
01822         // This declaration might be a definition. Merge with any existing
01823         // definition.
01824         if (auto *DDD = D->DefinitionData.getNotUpdated()) {
01825           if (auto *CanonDD = CanonSpec->DefinitionData.getNotUpdated()) {
01826             MergeDefinitionData(CanonSpec, *DDD);
01827             Reader.PendingDefinitions.erase(D);
01828             Reader.MergedDeclContexts.insert(
01829                 std::make_pair(D, CanonDD->Definition));
01830             D->IsCompleteDefinition = false;
01831           } else {
01832             CanonSpec->DefinitionData = D->DefinitionData;
01833           }
01834         }
01835         D->DefinitionData = CanonSpec->DefinitionData;
01836       }
01837     }
01838   }
01839 
01840   // Explicit info.
01841   if (TypeSourceInfo *TyInfo = GetTypeSourceInfo(Record, Idx)) {
01842     ClassTemplateSpecializationDecl::ExplicitSpecializationInfo *ExplicitInfo
01843         = new (C) ClassTemplateSpecializationDecl::ExplicitSpecializationInfo;
01844     ExplicitInfo->TypeAsWritten = TyInfo;
01845     ExplicitInfo->ExternLoc = ReadSourceLocation(Record, Idx);
01846     ExplicitInfo->TemplateKeywordLoc = ReadSourceLocation(Record, Idx);
01847     D->ExplicitInfo = ExplicitInfo;
01848   }
01849 
01850   return Redecl;
01851 }
01852 
01853 void ASTDeclReader::VisitClassTemplatePartialSpecializationDecl(
01854                                     ClassTemplatePartialSpecializationDecl *D) {
01855   RedeclarableResult Redecl = VisitClassTemplateSpecializationDeclImpl(D);
01856 
01857   D->TemplateParams = Reader.ReadTemplateParameterList(F, Record, Idx);
01858   D->ArgsAsWritten = Reader.ReadASTTemplateArgumentListInfo(F, Record, Idx);
01859 
01860   // These are read/set from/to the first declaration.
01861   if (ThisDeclID == Redecl.getFirstID()) {
01862     D->InstantiatedFromMember.setPointer(
01863       ReadDeclAs<ClassTemplatePartialSpecializationDecl>(Record, Idx));
01864     D->InstantiatedFromMember.setInt(Record[Idx++]);
01865   }
01866 }
01867 
01868 void ASTDeclReader::VisitClassScopeFunctionSpecializationDecl(
01869                                     ClassScopeFunctionSpecializationDecl *D) {
01870   VisitDecl(D);
01871   D->Specialization = ReadDeclAs<CXXMethodDecl>(Record, Idx);
01872 }
01873 
01874 void ASTDeclReader::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
01875   RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
01876 
01877   if (ThisDeclID == Redecl.getFirstID()) {
01878     // This FunctionTemplateDecl owns a CommonPtr; read it.
01879 
01880     // Read the function specialization declaration IDs. The specializations
01881     // themselves will be loaded if they're needed.
01882     if (unsigned NumSpecs = Record[Idx++]) {
01883       // FIXME: Append specializations!
01884       FunctionTemplateDecl::Common *CommonPtr = D->getCommonPtr();
01885       CommonPtr->LazySpecializations = new (Reader.getContext())
01886           serialization::DeclID[NumSpecs + 1];
01887       CommonPtr->LazySpecializations[0] = NumSpecs;
01888       for (unsigned I = 0; I != NumSpecs; ++I)
01889         CommonPtr->LazySpecializations[I + 1] = ReadDeclID(Record, Idx);
01890     }
01891   }
01892 }
01893 
01894 /// TODO: Unify with ClassTemplateSpecializationDecl version?
01895 ///       May require unifying ClassTemplate(Partial)SpecializationDecl and
01896 ///        VarTemplate(Partial)SpecializationDecl with a new data
01897 ///        structure Template(Partial)SpecializationDecl, and
01898 ///        using Template(Partial)SpecializationDecl as input type.
01899 ASTDeclReader::RedeclarableResult
01900 ASTDeclReader::VisitVarTemplateSpecializationDeclImpl(
01901     VarTemplateSpecializationDecl *D) {
01902   RedeclarableResult Redecl = VisitVarDeclImpl(D);
01903 
01904   ASTContext &C = Reader.getContext();
01905   if (Decl *InstD = ReadDecl(Record, Idx)) {
01906     if (VarTemplateDecl *VTD = dyn_cast<VarTemplateDecl>(InstD)) {
01907       D->SpecializedTemplate = VTD;
01908     } else {
01909       SmallVector<TemplateArgument, 8> TemplArgs;
01910       Reader.ReadTemplateArgumentList(TemplArgs, F, Record, Idx);
01911       TemplateArgumentList *ArgList = TemplateArgumentList::CreateCopy(
01912           C, TemplArgs.data(), TemplArgs.size());
01913       VarTemplateSpecializationDecl::SpecializedPartialSpecialization *PS =
01914           new (C)
01915           VarTemplateSpecializationDecl::SpecializedPartialSpecialization();
01916       PS->PartialSpecialization =
01917           cast<VarTemplatePartialSpecializationDecl>(InstD);
01918       PS->TemplateArgs = ArgList;
01919       D->SpecializedTemplate = PS;
01920     }
01921   }
01922 
01923   // Explicit info.
01924   if (TypeSourceInfo *TyInfo = GetTypeSourceInfo(Record, Idx)) {
01925     VarTemplateSpecializationDecl::ExplicitSpecializationInfo *ExplicitInfo =
01926         new (C) VarTemplateSpecializationDecl::ExplicitSpecializationInfo;
01927     ExplicitInfo->TypeAsWritten = TyInfo;
01928     ExplicitInfo->ExternLoc = ReadSourceLocation(Record, Idx);
01929     ExplicitInfo->TemplateKeywordLoc = ReadSourceLocation(Record, Idx);
01930     D->ExplicitInfo = ExplicitInfo;
01931   }
01932 
01933   SmallVector<TemplateArgument, 8> TemplArgs;
01934   Reader.ReadTemplateArgumentList(TemplArgs, F, Record, Idx);
01935   D->TemplateArgs =
01936       TemplateArgumentList::CreateCopy(C, TemplArgs.data(), TemplArgs.size());
01937   D->PointOfInstantiation = ReadSourceLocation(Record, Idx);
01938   D->SpecializationKind = (TemplateSpecializationKind)Record[Idx++];
01939 
01940   bool writtenAsCanonicalDecl = Record[Idx++];
01941   if (writtenAsCanonicalDecl) {
01942     VarTemplateDecl *CanonPattern = ReadDeclAs<VarTemplateDecl>(Record, Idx);
01943     if (D->isCanonicalDecl()) { // It's kept in the folding set.
01944       if (VarTemplatePartialSpecializationDecl *Partial =
01945               dyn_cast<VarTemplatePartialSpecializationDecl>(D)) {
01946         CanonPattern->getCommonPtr()->PartialSpecializations
01947             .GetOrInsertNode(Partial);
01948       } else {
01949         CanonPattern->getCommonPtr()->Specializations.GetOrInsertNode(D);
01950       }
01951     }
01952   }
01953 
01954   return Redecl;
01955 }
01956 
01957 /// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
01958 ///       May require unifying ClassTemplate(Partial)SpecializationDecl and
01959 ///        VarTemplate(Partial)SpecializationDecl with a new data
01960 ///        structure Template(Partial)SpecializationDecl, and
01961 ///        using Template(Partial)SpecializationDecl as input type.
01962 void ASTDeclReader::VisitVarTemplatePartialSpecializationDecl(
01963     VarTemplatePartialSpecializationDecl *D) {
01964   RedeclarableResult Redecl = VisitVarTemplateSpecializationDeclImpl(D);
01965 
01966   D->TemplateParams = Reader.ReadTemplateParameterList(F, Record, Idx);
01967   D->ArgsAsWritten = Reader.ReadASTTemplateArgumentListInfo(F, Record, Idx);
01968 
01969   // These are read/set from/to the first declaration.
01970   if (ThisDeclID == Redecl.getFirstID()) {
01971     D->InstantiatedFromMember.setPointer(
01972         ReadDeclAs<VarTemplatePartialSpecializationDecl>(Record, Idx));
01973     D->InstantiatedFromMember.setInt(Record[Idx++]);
01974   }
01975 }
01976 
01977 void ASTDeclReader::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
01978   VisitTypeDecl(D);
01979 
01980   D->setDeclaredWithTypename(Record[Idx++]);
01981 
01982   bool Inherited = Record[Idx++];
01983   TypeSourceInfo *DefArg = GetTypeSourceInfo(Record, Idx);
01984   D->setDefaultArgument(DefArg, Inherited);
01985 }
01986 
01987 void ASTDeclReader::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
01988   VisitDeclaratorDecl(D);
01989   // TemplateParmPosition.
01990   D->setDepth(Record[Idx++]);
01991   D->setPosition(Record[Idx++]);
01992   if (D->isExpandedParameterPack()) {
01993     void **Data = reinterpret_cast<void **>(D + 1);
01994     for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
01995       Data[2*I] = Reader.readType(F, Record, Idx).getAsOpaquePtr();
01996       Data[2*I + 1] = GetTypeSourceInfo(Record, Idx);
01997     }
01998   } else {
01999     // Rest of NonTypeTemplateParmDecl.
02000     D->ParameterPack = Record[Idx++];
02001     if (Record[Idx++]) {
02002       Expr *DefArg = Reader.ReadExpr(F);
02003       bool Inherited = Record[Idx++];
02004       D->setDefaultArgument(DefArg, Inherited);
02005    }
02006   }
02007 }
02008 
02009 void ASTDeclReader::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
02010   VisitTemplateDecl(D);
02011   // TemplateParmPosition.
02012   D->setDepth(Record[Idx++]);
02013   D->setPosition(Record[Idx++]);
02014   if (D->isExpandedParameterPack()) {
02015     void **Data = reinterpret_cast<void **>(D + 1);
02016     for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
02017          I != N; ++I)
02018       Data[I] = Reader.ReadTemplateParameterList(F, Record, Idx);
02019   } else {
02020     // Rest of TemplateTemplateParmDecl.
02021     TemplateArgumentLoc Arg = Reader.ReadTemplateArgumentLoc(F, Record, Idx);
02022     bool IsInherited = Record[Idx++];
02023     D->setDefaultArgument(Arg, IsInherited);
02024     D->ParameterPack = Record[Idx++];
02025   }
02026 }
02027 
02028 void ASTDeclReader::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
02029   VisitRedeclarableTemplateDecl(D);
02030 }
02031 
02032 void ASTDeclReader::VisitStaticAssertDecl(StaticAssertDecl *D) {
02033   VisitDecl(D);
02034   D->AssertExprAndFailed.setPointer(Reader.ReadExpr(F));
02035   D->AssertExprAndFailed.setInt(Record[Idx++]);
02036   D->Message = cast<StringLiteral>(Reader.ReadExpr(F));
02037   D->RParenLoc = ReadSourceLocation(Record, Idx);
02038 }
02039 
02040 void ASTDeclReader::VisitEmptyDecl(EmptyDecl *D) {
02041   VisitDecl(D);
02042 }
02043 
02044 std::pair<uint64_t, uint64_t>
02045 ASTDeclReader::VisitDeclContext(DeclContext *DC) {
02046   uint64_t LexicalOffset = Record[Idx++];
02047   uint64_t VisibleOffset = Record[Idx++];
02048   return std::make_pair(LexicalOffset, VisibleOffset);
02049 }
02050 
02051 template <typename T>
02052 ASTDeclReader::RedeclarableResult 
02053 ASTDeclReader::VisitRedeclarable(Redeclarable<T> *D) {
02054   DeclID FirstDeclID = ReadDeclID(Record, Idx);
02055   
02056   // 0 indicates that this declaration was the only declaration of its entity,
02057   // and is used for space optimization.
02058   if (FirstDeclID == 0)
02059     FirstDeclID = ThisDeclID;
02060   
02061   T *FirstDecl = cast_or_null<T>(Reader.GetDecl(FirstDeclID));
02062   if (FirstDecl != D) {
02063     // We delay loading of the redeclaration chain to avoid deeply nested calls.
02064     // We temporarily set the first (canonical) declaration as the previous one
02065     // which is the one that matters and mark the real previous DeclID to be
02066     // loaded & attached later on.
02067     D->RedeclLink = Redeclarable<T>::PreviousDeclLink(FirstDecl);
02068   }    
02069   
02070   // Note that this declaration has been deserialized.
02071   Reader.RedeclsDeserialized.insert(static_cast<T *>(D));
02072                              
02073   // The result structure takes care to note that we need to load the 
02074   // other declaration chains for this ID.
02075   return RedeclarableResult(Reader, FirstDeclID,
02076                             static_cast<T *>(D)->getKind());
02077 }
02078 
02079 /// \brief Attempts to merge the given declaration (D) with another declaration
02080 /// of the same entity.
02081 template<typename T>
02082 void ASTDeclReader::mergeRedeclarable(Redeclarable<T> *DBase,
02083                                       RedeclarableResult &Redecl,
02084                                       DeclID TemplatePatternID) {
02085   T *D = static_cast<T*>(DBase);
02086   T *DCanon = D->getCanonicalDecl();
02087   if (D != DCanon &&
02088       // IDs < NUM_PREDEF_DECL_IDS are not loaded from an AST file.
02089       Redecl.getFirstID() >= NUM_PREDEF_DECL_IDS &&
02090       (!Reader.getContext().getLangOpts().Modules ||
02091        Reader.getOwningModuleFile(DCanon) == Reader.getOwningModuleFile(D))) {
02092     // All redeclarations between this declaration and its originally-canonical
02093     // declaration get pulled in when we load DCanon; we don't need to
02094     // perform any more merging now.
02095     Redecl.suppress();
02096   }
02097 
02098   // If modules are not available, there is no reason to perform this merge.
02099   if (!Reader.getContext().getLangOpts().Modules)
02100     return;
02101 
02102   if (FindExistingResult ExistingRes = findExisting(D))
02103     if (T *Existing = ExistingRes)
02104       mergeRedeclarable(D, Existing, Redecl, TemplatePatternID);
02105 }
02106 
02107 /// \brief "Cast" to type T, asserting if we don't have an implicit conversion.
02108 /// We use this to put code in a template that will only be valid for certain
02109 /// instantiations.
02110 template<typename T> static T assert_cast(T t) { return t; }
02111 template<typename T> static T assert_cast(...) {
02112   llvm_unreachable("bad assert_cast");
02113 }
02114 
02115 /// \brief Merge together the pattern declarations from two template
02116 /// declarations.
02117 void ASTDeclReader::mergeTemplatePattern(RedeclarableTemplateDecl *D,
02118                                          RedeclarableTemplateDecl *Existing,
02119                                          DeclID DsID) {
02120   auto *DPattern = D->getTemplatedDecl();
02121   auto *ExistingPattern = Existing->getTemplatedDecl();
02122   RedeclarableResult Result(Reader, DPattern->getCanonicalDecl()->getGlobalID(),
02123                             DPattern->getKind());
02124   if (auto *DClass = dyn_cast<CXXRecordDecl>(DPattern)) {
02125     // Merge with any existing definition.
02126     // FIXME: This is duplicated in several places. Refactor.
02127     auto *ExistingClass =
02128         cast<CXXRecordDecl>(ExistingPattern)->getCanonicalDecl();
02129     if (auto *DDD = DClass->DefinitionData.getNotUpdated()) {
02130       if (auto *ExistingDD = ExistingClass->DefinitionData.getNotUpdated()) {
02131         MergeDefinitionData(ExistingClass, *DDD);
02132         Reader.PendingDefinitions.erase(DClass);
02133         Reader.MergedDeclContexts.insert(
02134             std::make_pair(DClass, ExistingDD->Definition));
02135         DClass->IsCompleteDefinition = false;
02136       } else {
02137         ExistingClass->DefinitionData = DClass->DefinitionData;
02138       }
02139     }
02140     DClass->DefinitionData = ExistingClass->DefinitionData;
02141 
02142     return mergeRedeclarable(DClass, cast<TagDecl>(ExistingPattern),
02143                              Result);
02144   }
02145   if (auto *DFunction = dyn_cast<FunctionDecl>(DPattern))
02146     return mergeRedeclarable(DFunction, cast<FunctionDecl>(ExistingPattern),
02147                              Result);
02148   if (auto *DVar = dyn_cast<VarDecl>(DPattern))
02149     return mergeRedeclarable(DVar, cast<VarDecl>(ExistingPattern), Result);
02150   if (auto *DAlias = dyn_cast<TypeAliasDecl>(DPattern))
02151     return mergeRedeclarable(DAlias, cast<TypedefNameDecl>(ExistingPattern),
02152                              Result);
02153   llvm_unreachable("merged an unknown kind of redeclarable template");
02154 }
02155 
02156 /// \brief Attempts to merge the given declaration (D) with another declaration
02157 /// of the same entity.
02158 template<typename T>
02159 void ASTDeclReader::mergeRedeclarable(Redeclarable<T> *DBase, T *Existing,
02160                                       RedeclarableResult &Redecl,
02161                                       DeclID TemplatePatternID) {
02162   T *D = static_cast<T*>(DBase);
02163   T *ExistingCanon = Existing->getCanonicalDecl();
02164   T *DCanon = D->getCanonicalDecl();
02165   if (ExistingCanon != DCanon) {
02166     assert(DCanon->getGlobalID() == Redecl.getFirstID());
02167 
02168     // Have our redeclaration link point back at the canonical declaration
02169     // of the existing declaration, so that this declaration has the
02170     // appropriate canonical declaration.
02171     D->RedeclLink = Redeclarable<T>::PreviousDeclLink(ExistingCanon);
02172 
02173     // When we merge a namespace, update its pointer to the first namespace.
02174     if (auto *Namespace = dyn_cast<NamespaceDecl>(D))
02175       Namespace->AnonOrFirstNamespaceAndInline.setPointer(
02176           assert_cast<NamespaceDecl*>(ExistingCanon));
02177 
02178     // When we merge a template, merge its pattern.
02179     if (auto *DTemplate = dyn_cast<RedeclarableTemplateDecl>(D))
02180       mergeTemplatePattern(
02181           DTemplate, assert_cast<RedeclarableTemplateDecl*>(ExistingCanon),
02182           TemplatePatternID);
02183 
02184     // If this declaration was the canonical declaration, make a note of
02185     // that. We accept the linear algorithm here because the number of
02186     // unique canonical declarations of an entity should always be tiny.
02187     if (DCanon == D) {
02188       SmallVectorImpl<DeclID> &Merged = Reader.MergedDecls[ExistingCanon];
02189       if (std::find(Merged.begin(), Merged.end(), Redecl.getFirstID())
02190             == Merged.end())
02191         Merged.push_back(Redecl.getFirstID());
02192     }
02193   }
02194 }
02195 
02196 /// \brief Attempts to merge the given declaration (D) with another declaration
02197 /// of the same entity, for the case where the entity is not actually
02198 /// redeclarable. This happens, for instance, when merging the fields of
02199 /// identical class definitions from two different modules.
02200 template<typename T>
02201 void ASTDeclReader::mergeMergeable(Mergeable<T> *D) {
02202   // If modules are not available, there is no reason to perform this merge.
02203   if (!Reader.getContext().getLangOpts().Modules)
02204     return;
02205 
02206   // ODR-based merging is only performed in C++. In C, identically-named things
02207   // in different translation units are not redeclarations (but may still have
02208   // compatible types).
02209   if (!Reader.getContext().getLangOpts().CPlusPlus)
02210     return;
02211 
02212   if (FindExistingResult ExistingRes = findExisting(static_cast<T*>(D)))
02213     if (T *Existing = ExistingRes)
02214       Reader.Context.setPrimaryMergedDecl(static_cast<T*>(D),
02215                                           Existing->getCanonicalDecl());
02216 }
02217 
02218 void ASTDeclReader::VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D) {
02219   VisitDecl(D);
02220   unsigned NumVars = D->varlist_size();
02221   SmallVector<Expr *, 16> Vars;
02222   Vars.reserve(NumVars);
02223   for (unsigned i = 0; i != NumVars; ++i) {
02224     Vars.push_back(Reader.ReadExpr(F));
02225   }
02226   D->setVars(Vars);
02227 }
02228 
02229 //===----------------------------------------------------------------------===//
02230 // Attribute Reading
02231 //===----------------------------------------------------------------------===//
02232 
02233 /// \brief Reads attributes from the current stream position.
02234 void ASTReader::ReadAttributes(ModuleFile &F, AttrVec &Attrs,
02235                                const RecordData &Record, unsigned &Idx) {
02236   for (unsigned i = 0, e = Record[Idx++]; i != e; ++i) {
02237     Attr *New = nullptr;
02238     attr::Kind Kind = (attr::Kind)Record[Idx++];
02239     SourceRange Range = ReadSourceRange(F, Record, Idx);
02240 
02241 #include "clang/Serialization/AttrPCHRead.inc"
02242 
02243     assert(New && "Unable to decode attribute?");
02244     Attrs.push_back(New);
02245   }
02246 }
02247 
02248 //===----------------------------------------------------------------------===//
02249 // ASTReader Implementation
02250 //===----------------------------------------------------------------------===//
02251 
02252 /// \brief Note that we have loaded the declaration with the given
02253 /// Index.
02254 ///
02255 /// This routine notes that this declaration has already been loaded,
02256 /// so that future GetDecl calls will return this declaration rather
02257 /// than trying to load a new declaration.
02258 inline void ASTReader::LoadedDecl(unsigned Index, Decl *D) {
02259   assert(!DeclsLoaded[Index] && "Decl loaded twice?");
02260   DeclsLoaded[Index] = D;
02261 }
02262 
02263 
02264 /// \brief Determine whether the consumer will be interested in seeing
02265 /// this declaration (via HandleTopLevelDecl).
02266 ///
02267 /// This routine should return true for anything that might affect
02268 /// code generation, e.g., inline function definitions, Objective-C
02269 /// declarations with metadata, etc.
02270 static bool isConsumerInterestedIn(Decl *D, bool HasBody) {
02271   // An ObjCMethodDecl is never considered as "interesting" because its
02272   // implementation container always is.
02273 
02274   if (isa<FileScopeAsmDecl>(D) || 
02275       isa<ObjCProtocolDecl>(D) || 
02276       isa<ObjCImplDecl>(D) ||
02277       isa<ImportDecl>(D) ||
02278       isa<OMPThreadPrivateDecl>(D))
02279     return true;
02280   if (VarDecl *Var = dyn_cast<VarDecl>(D))
02281     return Var->isFileVarDecl() &&
02282            Var->isThisDeclarationADefinition() == VarDecl::Definition;
02283   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(D))
02284     return Func->doesThisDeclarationHaveABody() || HasBody;
02285   
02286   return false;
02287 }
02288 
02289 /// \brief Get the correct cursor and offset for loading a declaration.
02290 ASTReader::RecordLocation
02291 ASTReader::DeclCursorForID(DeclID ID, unsigned &RawLocation) {
02292   // See if there's an override.
02293   DeclReplacementMap::iterator It = ReplacedDecls.find(ID);
02294   if (It != ReplacedDecls.end()) {
02295     RawLocation = It->second.RawLoc;
02296     return RecordLocation(It->second.Mod, It->second.Offset);
02297   }
02298 
02299   GlobalDeclMapType::iterator I = GlobalDeclMap.find(ID);
02300   assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
02301   ModuleFile *M = I->second;
02302   const DeclOffset &
02303     DOffs =  M->DeclOffsets[ID - M->BaseDeclID - NUM_PREDEF_DECL_IDS];
02304   RawLocation = DOffs.Loc;
02305   return RecordLocation(M, DOffs.BitOffset);
02306 }
02307 
02308 ASTReader::RecordLocation ASTReader::getLocalBitOffset(uint64_t GlobalOffset) {
02309   ContinuousRangeMap<uint64_t, ModuleFile*, 4>::iterator I
02310     = GlobalBitOffsetsMap.find(GlobalOffset);
02311 
02312   assert(I != GlobalBitOffsetsMap.end() && "Corrupted global bit offsets map");
02313   return RecordLocation(I->second, GlobalOffset - I->second->GlobalBitOffset);
02314 }
02315 
02316 uint64_t ASTReader::getGlobalBitOffset(ModuleFile &M, uint32_t LocalOffset) {
02317   return LocalOffset + M.GlobalBitOffset;
02318 }
02319 
02320 static bool isSameTemplateParameterList(const TemplateParameterList *X,
02321                                         const TemplateParameterList *Y);
02322 
02323 /// \brief Determine whether two template parameters are similar enough
02324 /// that they may be used in declarations of the same template.
02325 static bool isSameTemplateParameter(const NamedDecl *X,
02326                                     const NamedDecl *Y) {
02327   if (X->getKind() != Y->getKind())
02328     return false;
02329 
02330   if (const TemplateTypeParmDecl *TX = dyn_cast<TemplateTypeParmDecl>(X)) {
02331     const TemplateTypeParmDecl *TY = cast<TemplateTypeParmDecl>(Y);
02332     return TX->isParameterPack() == TY->isParameterPack();
02333   }
02334 
02335   if (const NonTypeTemplateParmDecl *TX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
02336     const NonTypeTemplateParmDecl *TY = cast<NonTypeTemplateParmDecl>(Y);
02337     return TX->isParameterPack() == TY->isParameterPack() &&
02338            TX->getASTContext().hasSameType(TX->getType(), TY->getType());
02339   }
02340 
02341   const TemplateTemplateParmDecl *TX = cast<TemplateTemplateParmDecl>(X);
02342   const TemplateTemplateParmDecl *TY = cast<TemplateTemplateParmDecl>(Y);
02343   return TX->isParameterPack() == TY->isParameterPack() &&
02344          isSameTemplateParameterList(TX->getTemplateParameters(),
02345                                      TY->getTemplateParameters());
02346 }
02347 
02348 static NamespaceDecl *getNamespace(const NestedNameSpecifier *X) {
02349   if (auto *NS = X->getAsNamespace())
02350     return NS;
02351   if (auto *NAS = X->getAsNamespaceAlias())
02352     return NAS->getNamespace();
02353   return nullptr;
02354 }
02355 
02356 static bool isSameQualifier(const NestedNameSpecifier *X,
02357                             const NestedNameSpecifier *Y) {
02358   if (auto *NSX = getNamespace(X)) {
02359     auto *NSY = getNamespace(Y);
02360     if (!NSY || NSX->getCanonicalDecl() != NSY->getCanonicalDecl())
02361       return false;
02362   } else if (X->getKind() != Y->getKind())
02363     return false;
02364 
02365   // FIXME: For namespaces and types, we're permitted to check that the entity
02366   // is named via the same tokens. We should probably do so.
02367   switch (X->getKind()) {
02368   case NestedNameSpecifier::Identifier:
02369     if (X->getAsIdentifier() != Y->getAsIdentifier())
02370       return false;
02371     break;
02372   case NestedNameSpecifier::Namespace:
02373   case NestedNameSpecifier::NamespaceAlias:
02374     // We've already checked that we named the same namespace.
02375     break;
02376   case NestedNameSpecifier::TypeSpec:
02377   case NestedNameSpecifier::TypeSpecWithTemplate:
02378     if (X->getAsType()->getCanonicalTypeInternal() !=
02379         Y->getAsType()->getCanonicalTypeInternal())
02380       return false;
02381     break;
02382   case NestedNameSpecifier::Global:
02383   case NestedNameSpecifier::Super:
02384     return true;
02385   }
02386 
02387   // Recurse into earlier portion of NNS, if any.
02388   auto *PX = X->getPrefix();
02389   auto *PY = Y->getPrefix();
02390   if (PX && PY)
02391     return isSameQualifier(PX, PY);
02392   return !PX && !PY;
02393 }
02394 
02395 /// \brief Determine whether two template parameter lists are similar enough
02396 /// that they may be used in declarations of the same template.
02397 static bool isSameTemplateParameterList(const TemplateParameterList *X,
02398                                         const TemplateParameterList *Y) {
02399   if (X->size() != Y->size())
02400     return false;
02401 
02402   for (unsigned I = 0, N = X->size(); I != N; ++I)
02403     if (!isSameTemplateParameter(X->getParam(I), Y->getParam(I)))
02404       return false;
02405 
02406   return true;
02407 }
02408 
02409 /// \brief Determine whether the two declarations refer to the same entity.
02410 static bool isSameEntity(NamedDecl *X, NamedDecl *Y) {
02411   assert(X->getDeclName() == Y->getDeclName() && "Declaration name mismatch!");
02412 
02413   if (X == Y)
02414     return true;
02415 
02416   // Must be in the same context.
02417   if (!X->getDeclContext()->getRedeclContext()->Equals(
02418          Y->getDeclContext()->getRedeclContext()))
02419     return false;
02420 
02421   // Two typedefs refer to the same entity if they have the same underlying
02422   // type.
02423   if (TypedefNameDecl *TypedefX = dyn_cast<TypedefNameDecl>(X))
02424     if (TypedefNameDecl *TypedefY = dyn_cast<TypedefNameDecl>(Y))
02425       return X->getASTContext().hasSameType(TypedefX->getUnderlyingType(),
02426                                             TypedefY->getUnderlyingType());
02427 
02428   // Must have the same kind.
02429   if (X->getKind() != Y->getKind())
02430     return false;
02431 
02432   // Objective-C classes and protocols with the same name always match.
02433   if (isa<ObjCInterfaceDecl>(X) || isa<ObjCProtocolDecl>(X))
02434     return true;
02435 
02436   if (isa<ClassTemplateSpecializationDecl>(X)) {
02437     // No need to handle these here: we merge them when adding them to the
02438     // template.
02439     return false;
02440   }
02441 
02442   // Compatible tags match.
02443   if (TagDecl *TagX = dyn_cast<TagDecl>(X)) {
02444     TagDecl *TagY = cast<TagDecl>(Y);
02445     return (TagX->getTagKind() == TagY->getTagKind()) ||
02446       ((TagX->getTagKind() == TTK_Struct || TagX->getTagKind() == TTK_Class ||
02447         TagX->getTagKind() == TTK_Interface) &&
02448        (TagY->getTagKind() == TTK_Struct || TagY->getTagKind() == TTK_Class ||
02449         TagY->getTagKind() == TTK_Interface));
02450   }
02451 
02452   // Functions with the same type and linkage match.
02453   // FIXME: This needs to cope with merging of prototyped/non-prototyped
02454   // functions, etc.
02455   if (FunctionDecl *FuncX = dyn_cast<FunctionDecl>(X)) {
02456     FunctionDecl *FuncY = cast<FunctionDecl>(Y);
02457     return (FuncX->getLinkageInternal() == FuncY->getLinkageInternal()) &&
02458       FuncX->getASTContext().hasSameType(FuncX->getType(), FuncY->getType());
02459   }
02460 
02461   // Variables with the same type and linkage match.
02462   if (VarDecl *VarX = dyn_cast<VarDecl>(X)) {
02463     VarDecl *VarY = cast<VarDecl>(Y);
02464     return (VarX->getLinkageInternal() == VarY->getLinkageInternal()) &&
02465       VarX->getASTContext().hasSameType(VarX->getType(), VarY->getType());
02466   }
02467 
02468   // Namespaces with the same name and inlinedness match.
02469   if (NamespaceDecl *NamespaceX = dyn_cast<NamespaceDecl>(X)) {
02470     NamespaceDecl *NamespaceY = cast<NamespaceDecl>(Y);
02471     return NamespaceX->isInline() == NamespaceY->isInline();
02472   }
02473 
02474   // Identical template names and kinds match if their template parameter lists
02475   // and patterns match.
02476   if (TemplateDecl *TemplateX = dyn_cast<TemplateDecl>(X)) {
02477     TemplateDecl *TemplateY = cast<TemplateDecl>(Y);
02478     return isSameEntity(TemplateX->getTemplatedDecl(),
02479                         TemplateY->getTemplatedDecl()) &&
02480            isSameTemplateParameterList(TemplateX->getTemplateParameters(),
02481                                        TemplateY->getTemplateParameters());
02482   }
02483 
02484   // Fields with the same name and the same type match.
02485   if (FieldDecl *FDX = dyn_cast<FieldDecl>(X)) {
02486     FieldDecl *FDY = cast<FieldDecl>(Y);
02487     // FIXME: Also check the bitwidth is odr-equivalent, if any.
02488     return X->getASTContext().hasSameType(FDX->getType(), FDY->getType());
02489   }
02490 
02491   // Enumerators with the same name match.
02492   if (isa<EnumConstantDecl>(X))
02493     // FIXME: Also check the value is odr-equivalent.
02494     return true;
02495 
02496   // Using shadow declarations with the same target match.
02497   if (UsingShadowDecl *USX = dyn_cast<UsingShadowDecl>(X)) {
02498     UsingShadowDecl *USY = cast<UsingShadowDecl>(Y);
02499     return USX->getTargetDecl() == USY->getTargetDecl();
02500   }
02501 
02502   // Using declarations with the same qualifier match. (We already know that
02503   // the name matches.)
02504   if (auto *UX = dyn_cast<UsingDecl>(X)) {
02505     auto *UY = cast<UsingDecl>(Y);
02506     return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
02507            UX->hasTypename() == UY->hasTypename() &&
02508            UX->isAccessDeclaration() == UY->isAccessDeclaration();
02509   }
02510   if (auto *UX = dyn_cast<UnresolvedUsingValueDecl>(X)) {
02511     auto *UY = cast<UnresolvedUsingValueDecl>(Y);
02512     return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
02513            UX->isAccessDeclaration() == UY->isAccessDeclaration();
02514   }
02515   if (auto *UX = dyn_cast<UnresolvedUsingTypenameDecl>(X))
02516     return isSameQualifier(
02517         UX->getQualifier(),
02518         cast<UnresolvedUsingTypenameDecl>(Y)->getQualifier());
02519 
02520   // Namespace alias definitions with the same target match.
02521   if (auto *NAX = dyn_cast<NamespaceAliasDecl>(X)) {
02522     auto *NAY = cast<NamespaceAliasDecl>(Y);
02523     return NAX->getNamespace()->Equals(NAY->getNamespace());
02524   }
02525 
02526   // FIXME: Many other cases to implement.
02527   return false;
02528 }
02529 
02530 /// Find the context in which we should search for previous declarations when
02531 /// looking for declarations to merge.
02532 static DeclContext *getPrimaryContextForMerging(DeclContext *DC) {
02533   if (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC))
02534     return ND->getOriginalNamespace();
02535 
02536   // There is one tricky case here: if DC is a class with no definition, then
02537   // we're merging a declaration whose definition is added by an update record,
02538   // but we've not yet loaded that update record. In this case, we use the
02539   // canonical declaration for merging until we get a real definition.
02540   // FIXME: When we add a definition, we may need to move the partial lookup
02541   // information from the canonical declaration onto the chosen definition.
02542   if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC))
02543     return RD->getPrimaryContext();
02544 
02545   if (EnumDecl *ED = dyn_cast<EnumDecl>(DC))
02546     return ED->getASTContext().getLangOpts().CPlusPlus? ED->getDefinition()
02547                                                       : nullptr;
02548 
02549   return nullptr;
02550 }
02551 
02552 ASTDeclReader::FindExistingResult::~FindExistingResult() {
02553   if (!AddResult || Existing)
02554     return;
02555 
02556   DeclarationName Name = New->getDeclName();
02557   DeclContext *DC = New->getDeclContext()->getRedeclContext();
02558   if (TypedefNameForLinkage) {
02559     Reader.ImportedTypedefNamesForLinkage.insert(
02560         std::make_pair(std::make_pair(DC, TypedefNameForLinkage), New));
02561   } else if (!Name) {
02562     assert(needsAnonymousDeclarationNumber(New));
02563     setAnonymousDeclForMerging(Reader, New->getLexicalDeclContext(),
02564                                AnonymousDeclNumber, New);
02565   } else if (DC->isTranslationUnit() && Reader.SemaObj) {
02566     Reader.SemaObj->IdResolver.tryAddTopLevelDecl(New, Name);
02567   } else if (DeclContext *MergeDC = getPrimaryContextForMerging(DC)) {
02568     // Add the declaration to its redeclaration context so later merging
02569     // lookups will find it.
02570     MergeDC->makeDeclVisibleInContextImpl(New, /*Internal*/true);
02571   }
02572 }
02573 
02574 /// Find the declaration that should be merged into, given the declaration found
02575 /// by name lookup. If we're merging an anonymous declaration within a typedef,
02576 /// we need a matching typedef, and we merge with the type inside it.
02577 static NamedDecl *getDeclForMerging(NamedDecl *Found,
02578                                     bool IsTypedefNameForLinkage) {
02579   if (!IsTypedefNameForLinkage)
02580     return Found;
02581 
02582   // If we found a typedef declaration that gives a name to some other
02583   // declaration, then we want that inner declaration. Declarations from
02584   // AST files are handled via ImportedTypedefNamesForLinkage.
02585   if (Found->isFromASTFile()) return 0;
02586   if (auto *TND = dyn_cast<TypedefNameDecl>(Found)) {
02587     if (auto *TT = TND->getTypeSourceInfo()->getType()->getAs<TagType>())
02588       if (TT->getDecl()->getTypedefNameForAnonDecl() == TND)
02589         return TT->getDecl();
02590   }
02591 
02592   return 0;
02593 }
02594 
02595 NamedDecl *ASTDeclReader::getAnonymousDeclForMerging(ASTReader &Reader,
02596                                                      DeclContext *DC,
02597                                                      unsigned Index) {
02598   // If the lexical context has been merged, look into the now-canonical
02599   // definition.
02600   if (auto *Merged = Reader.MergedDeclContexts.lookup(DC))
02601     DC = Merged;
02602 
02603   // If we've seen this before, return the canonical declaration.
02604   auto &Previous = Reader.AnonymousDeclarationsForMerging[DC];
02605   if (Index < Previous.size() && Previous[Index])
02606     return Previous[Index];
02607 
02608   // If this is the first time, but we have parsed a declaration of the context,
02609   // build the anonymous declaration list from the parsed declaration.
02610   if (!cast<Decl>(DC)->isFromASTFile()) {
02611     unsigned Index = 0;
02612     for (Decl *LexicalD : DC->decls()) {
02613       auto *ND = dyn_cast<NamedDecl>(LexicalD);
02614       if (!ND || !needsAnonymousDeclarationNumber(ND))
02615         continue;
02616       if (Previous.size() == Index)
02617         Previous.push_back(cast<NamedDecl>(ND->getCanonicalDecl()));
02618       else
02619         Previous[Index] = cast<NamedDecl>(ND->getCanonicalDecl());
02620       ++Index;
02621     }
02622   }
02623 
02624   return Index < Previous.size() ? Previous[Index] : nullptr;
02625 }
02626 
02627 void ASTDeclReader::setAnonymousDeclForMerging(ASTReader &Reader,
02628                                                DeclContext *DC, unsigned Index,
02629                                                NamedDecl *D) {
02630   if (auto *Merged = Reader.MergedDeclContexts.lookup(DC))
02631     DC = Merged;
02632 
02633   auto &Previous = Reader.AnonymousDeclarationsForMerging[DC];
02634   if (Index >= Previous.size())
02635     Previous.resize(Index + 1);
02636   if (!Previous[Index])
02637     Previous[Index] = D;
02638 }
02639 
02640 ASTDeclReader::FindExistingResult ASTDeclReader::findExisting(NamedDecl *D) {
02641   DeclarationName Name = TypedefNameForLinkage ? TypedefNameForLinkage
02642                                                : D->getDeclName();
02643 
02644   if (!Name && !needsAnonymousDeclarationNumber(D)) {
02645     // Don't bother trying to find unnamed declarations that are in
02646     // unmergeable contexts.
02647     FindExistingResult Result(Reader, D, /*Existing=*/nullptr,
02648                               AnonymousDeclNumber, TypedefNameForLinkage);
02649     // FIXME: We may still need to pull in the redeclaration chain; there can
02650     // be redeclarations via 'decltype'.
02651     Result.suppress();
02652     return Result;
02653   }
02654 
02655   // FIXME: Bail out for non-canonical declarations. We will have performed any
02656   // necessary merging already.
02657 
02658   DeclContext *DC = D->getDeclContext()->getRedeclContext();
02659   if (TypedefNameForLinkage) {
02660     auto It = Reader.ImportedTypedefNamesForLinkage.find(
02661         std::make_pair(DC, TypedefNameForLinkage));
02662     if (It != Reader.ImportedTypedefNamesForLinkage.end())
02663       if (isSameEntity(It->second, D))
02664         return FindExistingResult(Reader, D, It->second, AnonymousDeclNumber,
02665                                   TypedefNameForLinkage);
02666     // Go on to check in other places in case an existing typedef name
02667     // was not imported.
02668   }
02669 
02670   if (!Name) {
02671     // This is an anonymous declaration that we may need to merge. Look it up
02672     // in its context by number.
02673     assert(needsAnonymousDeclarationNumber(D));
02674     if (auto *Existing = getAnonymousDeclForMerging(
02675             Reader, D->getLexicalDeclContext(), AnonymousDeclNumber))
02676       if (isSameEntity(Existing, D))
02677         return FindExistingResult(Reader, D, Existing, AnonymousDeclNumber,
02678                                   TypedefNameForLinkage);
02679   } else if (DC->isTranslationUnit() && Reader.SemaObj) {
02680     IdentifierResolver &IdResolver = Reader.SemaObj->IdResolver;
02681 
02682     // Temporarily consider the identifier to be up-to-date. We don't want to
02683     // cause additional lookups here.
02684     class UpToDateIdentifierRAII {
02685       IdentifierInfo *II;
02686       bool WasOutToDate;
02687 
02688     public:
02689       explicit UpToDateIdentifierRAII(IdentifierInfo *II)
02690         : II(II), WasOutToDate(false)
02691       {
02692         if (II) {
02693           WasOutToDate = II->isOutOfDate();
02694           if (WasOutToDate)
02695             II->setOutOfDate(false);
02696         }
02697       }
02698 
02699       ~UpToDateIdentifierRAII() {
02700         if (WasOutToDate)
02701           II->setOutOfDate(true);
02702       }
02703     } UpToDate(Name.getAsIdentifierInfo());
02704 
02705     for (IdentifierResolver::iterator I = IdResolver.begin(Name), 
02706                                    IEnd = IdResolver.end();
02707          I != IEnd; ++I) {
02708       if (NamedDecl *Existing = getDeclForMerging(*I, TypedefNameForLinkage))
02709         if (isSameEntity(Existing, D))
02710           return FindExistingResult(Reader, D, Existing, AnonymousDeclNumber,
02711                                     TypedefNameForLinkage);
02712     }
02713   } else if (DeclContext *MergeDC = getPrimaryContextForMerging(DC)) {
02714     DeclContext::lookup_result R = MergeDC->noload_lookup(Name);
02715     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
02716       if (NamedDecl *Existing = getDeclForMerging(*I, TypedefNameForLinkage))
02717         if (isSameEntity(Existing, D))
02718           return FindExistingResult(Reader, D, Existing, AnonymousDeclNumber,
02719                                     TypedefNameForLinkage);
02720     }
02721   } else {
02722     // Not in a mergeable context.
02723     return FindExistingResult(Reader);
02724   }
02725 
02726   // If this declaration is from a merged context, make a note that we need to
02727   // check that the canonical definition of that context contains the decl.
02728   //
02729   // FIXME: We should do something similar if we merge two definitions of the
02730   // same template specialization into the same CXXRecordDecl.
02731   auto MergedDCIt = Reader.MergedDeclContexts.find(D->getLexicalDeclContext());
02732   if (MergedDCIt != Reader.MergedDeclContexts.end() &&
02733       MergedDCIt->second == D->getDeclContext())
02734     Reader.PendingOdrMergeChecks.push_back(D);
02735 
02736   return FindExistingResult(Reader, D, /*Existing=*/nullptr,
02737                             AnonymousDeclNumber, TypedefNameForLinkage);
02738 }
02739 
02740 template<typename DeclT>
02741 void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader,
02742                                            Redeclarable<DeclT> *D,
02743                                            Decl *Previous) {
02744   D->RedeclLink.setPrevious(cast<DeclT>(Previous));
02745 }
02746 namespace clang {
02747 template<>
02748 void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader,
02749                                            Redeclarable<FunctionDecl> *D,
02750                                            Decl *Previous) {
02751   FunctionDecl *FD = static_cast<FunctionDecl*>(D);
02752   FunctionDecl *PrevFD = cast<FunctionDecl>(Previous);
02753 
02754   FD->RedeclLink.setPrevious(PrevFD);
02755 
02756   // If the previous declaration is an inline function declaration, then this
02757   // declaration is too.
02758   if (PrevFD->IsInline != FD->IsInline) {
02759     // FIXME: [dcl.fct.spec]p4:
02760     //   If a function with external linkage is declared inline in one
02761     //   translation unit, it shall be declared inline in all translation
02762     //   units in which it appears.
02763     //
02764     // Be careful of this case:
02765     //
02766     // module A:
02767     //   template<typename T> struct X { void f(); };
02768     //   template<typename T> inline void X<T>::f() {}
02769     //
02770     // module B instantiates the declaration of X<int>::f
02771     // module C instantiates the definition of X<int>::f
02772     //
02773     // If module B and C are merged, we do not have a violation of this rule.
02774     FD->IsInline = true;
02775   }
02776 
02777   // If this declaration has an unresolved exception specification but the
02778   // previous declaration had a resolved one, resolve the exception
02779   // specification now.
02780   auto *FPT = FD->getType()->getAs<FunctionProtoType>();
02781   auto *PrevFPT = PrevFD->getType()->getAs<FunctionProtoType>();
02782   if (FPT && PrevFPT &&
02783       isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
02784       !isUnresolvedExceptionSpec(PrevFPT->getExceptionSpecType())) {
02785     Reader.Context.adjustExceptionSpec(
02786         FD, PrevFPT->getExtProtoInfo().ExceptionSpec);
02787   }
02788 }
02789 }
02790 void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader, ...) {
02791   llvm_unreachable("attachPreviousDecl on non-redeclarable declaration");
02792 }
02793 
02794 void ASTDeclReader::attachPreviousDecl(ASTReader &Reader, Decl *D,
02795                                        Decl *Previous) {
02796   assert(D && Previous);
02797 
02798   switch (D->getKind()) {
02799 #define ABSTRACT_DECL(TYPE)
02800 #define DECL(TYPE, BASE)                                           \
02801   case Decl::TYPE:                                                 \
02802     attachPreviousDeclImpl(Reader, cast<TYPE##Decl>(D), Previous); \
02803     break;
02804 #include "clang/AST/DeclNodes.inc"
02805   }
02806 
02807   // If the declaration was visible in one module, a redeclaration of it in
02808   // another module remains visible even if it wouldn't be visible by itself.
02809   //
02810   // FIXME: In this case, the declaration should only be visible if a module
02811   //        that makes it visible has been imported.
02812   D->IdentifierNamespace |=
02813       Previous->IdentifierNamespace &
02814       (Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Type);
02815 
02816   // If the previous declaration is marked as used, then this declaration should
02817   // be too.
02818   if (Previous->Used)
02819     D->Used = true;
02820 }
02821 
02822 template<typename DeclT>
02823 void ASTDeclReader::attachLatestDeclImpl(Redeclarable<DeclT> *D, Decl *Latest) {
02824   D->RedeclLink.setLatest(cast<DeclT>(Latest));
02825 }
02826 void ASTDeclReader::attachLatestDeclImpl(...) {
02827   llvm_unreachable("attachLatestDecl on non-redeclarable declaration");
02828 }
02829 
02830 void ASTDeclReader::attachLatestDecl(Decl *D, Decl *Latest) {
02831   assert(D && Latest);
02832 
02833   switch (D->getKind()) {
02834 #define ABSTRACT_DECL(TYPE)
02835 #define DECL(TYPE, BASE)                                  \
02836   case Decl::TYPE:                                        \
02837     attachLatestDeclImpl(cast<TYPE##Decl>(D), Latest); \
02838     break;
02839 #include "clang/AST/DeclNodes.inc"
02840   }
02841 }
02842 
02843 template<typename DeclT>
02844 void ASTDeclReader::markIncompleteDeclChainImpl(Redeclarable<DeclT> *D) {
02845   D->RedeclLink.markIncomplete();
02846 }
02847 void ASTDeclReader::markIncompleteDeclChainImpl(...) {
02848   llvm_unreachable("markIncompleteDeclChain on non-redeclarable declaration");
02849 }
02850 
02851 void ASTReader::markIncompleteDeclChain(Decl *D) {
02852   switch (D->getKind()) {
02853 #define ABSTRACT_DECL(TYPE)
02854 #define DECL(TYPE, BASE)                                             \
02855   case Decl::TYPE:                                                   \
02856     ASTDeclReader::markIncompleteDeclChainImpl(cast<TYPE##Decl>(D)); \
02857     break;
02858 #include "clang/AST/DeclNodes.inc"
02859   }
02860 }
02861 
02862 ASTReader::MergedDeclsMap::iterator
02863 ASTReader::combineStoredMergedDecls(Decl *Canon, GlobalDeclID CanonID) {
02864   // If we don't have any stored merged declarations, just look in the
02865   // merged declarations set.
02866   StoredMergedDeclsMap::iterator StoredPos = StoredMergedDecls.find(CanonID);
02867   if (StoredPos == StoredMergedDecls.end())
02868     return MergedDecls.find(Canon);
02869 
02870   // Append the stored merged declarations to the merged declarations set.
02871   MergedDeclsMap::iterator Pos = MergedDecls.find(Canon);
02872   if (Pos == MergedDecls.end())
02873     Pos = MergedDecls.insert(std::make_pair(Canon,
02874                                             SmallVector<DeclID, 2>())).first;
02875   Pos->second.append(StoredPos->second.begin(), StoredPos->second.end());
02876   StoredMergedDecls.erase(StoredPos);
02877 
02878   // Sort and uniquify the set of merged declarations.
02879   llvm::array_pod_sort(Pos->second.begin(), Pos->second.end());
02880   Pos->second.erase(std::unique(Pos->second.begin(), Pos->second.end()),
02881                     Pos->second.end());
02882   return Pos;
02883 }
02884 
02885 /// \brief Read the declaration at the given offset from the AST file.
02886 Decl *ASTReader::ReadDeclRecord(DeclID ID) {
02887   unsigned Index = ID - NUM_PREDEF_DECL_IDS;
02888   unsigned RawLocation = 0;
02889   RecordLocation Loc = DeclCursorForID(ID, RawLocation);
02890   llvm::BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
02891   // Keep track of where we are in the stream, then jump back there
02892   // after reading this declaration.
02893   SavedStreamPosition SavedPosition(DeclsCursor);
02894 
02895   ReadingKindTracker ReadingKind(Read_Decl, *this);
02896 
02897   // Note that we are loading a declaration record.
02898   Deserializing ADecl(this);
02899 
02900   DeclsCursor.JumpToBit(Loc.Offset);
02901   RecordData Record;
02902   unsigned Code = DeclsCursor.ReadCode();
02903   unsigned Idx = 0;
02904   ASTDeclReader Reader(*this, *Loc.F, ID, RawLocation, Record,Idx);
02905 
02906   Decl *D = nullptr;
02907   switch ((DeclCode)DeclsCursor.readRecord(Code, Record)) {
02908   case DECL_CONTEXT_LEXICAL:
02909   case DECL_CONTEXT_VISIBLE:
02910     llvm_unreachable("Record cannot be de-serialized with ReadDeclRecord");
02911   case DECL_TYPEDEF:
02912     D = TypedefDecl::CreateDeserialized(Context, ID);
02913     break;
02914   case DECL_TYPEALIAS:
02915     D = TypeAliasDecl::CreateDeserialized(Context, ID);
02916     break;
02917   case DECL_ENUM:
02918     D = EnumDecl::CreateDeserialized(Context, ID);
02919     break;
02920   case DECL_RECORD:
02921     D = RecordDecl::CreateDeserialized(Context, ID);
02922     break;
02923   case DECL_ENUM_CONSTANT:
02924     D = EnumConstantDecl::CreateDeserialized(Context, ID);
02925     break;
02926   case DECL_FUNCTION:
02927     D = FunctionDecl::CreateDeserialized(Context, ID);
02928     break;
02929   case DECL_LINKAGE_SPEC:
02930     D = LinkageSpecDecl::CreateDeserialized(Context, ID);
02931     break;
02932   case DECL_LABEL:
02933     D = LabelDecl::CreateDeserialized(Context, ID);
02934     break;
02935   case DECL_NAMESPACE:
02936     D = NamespaceDecl::CreateDeserialized(Context, ID);
02937     break;
02938   case DECL_NAMESPACE_ALIAS:
02939     D = NamespaceAliasDecl::CreateDeserialized(Context, ID);
02940     break;
02941   case DECL_USING:
02942     D = UsingDecl::CreateDeserialized(Context, ID);
02943     break;
02944   case DECL_USING_SHADOW:
02945     D = UsingShadowDecl::CreateDeserialized(Context, ID);
02946     break;
02947   case DECL_USING_DIRECTIVE:
02948     D = UsingDirectiveDecl::CreateDeserialized(Context, ID);
02949     break;
02950   case DECL_UNRESOLVED_USING_VALUE:
02951     D = UnresolvedUsingValueDecl::CreateDeserialized(Context, ID);
02952     break;
02953   case DECL_UNRESOLVED_USING_TYPENAME:
02954     D = UnresolvedUsingTypenameDecl::CreateDeserialized(Context, ID);
02955     break;
02956   case DECL_CXX_RECORD:
02957     D = CXXRecordDecl::CreateDeserialized(Context, ID);
02958     break;
02959   case DECL_CXX_METHOD:
02960     D = CXXMethodDecl::CreateDeserialized(Context, ID);
02961     break;
02962   case DECL_CXX_CONSTRUCTOR:
02963     D = CXXConstructorDecl::CreateDeserialized(Context, ID);
02964     break;
02965   case DECL_CXX_DESTRUCTOR:
02966     D = CXXDestructorDecl::CreateDeserialized(Context, ID);
02967     break;
02968   case DECL_CXX_CONVERSION:
02969     D = CXXConversionDecl::CreateDeserialized(Context, ID);
02970     break;
02971   case DECL_ACCESS_SPEC:
02972     D = AccessSpecDecl::CreateDeserialized(Context, ID);
02973     break;
02974   case DECL_FRIEND:
02975     D = FriendDecl::CreateDeserialized(Context, ID, Record[Idx++]);
02976     break;
02977   case DECL_FRIEND_TEMPLATE:
02978     D = FriendTemplateDecl::CreateDeserialized(Context, ID);
02979     break;
02980   case DECL_CLASS_TEMPLATE:
02981     D = ClassTemplateDecl::CreateDeserialized(Context, ID);
02982     break;
02983   case DECL_CLASS_TEMPLATE_SPECIALIZATION:
02984     D = ClassTemplateSpecializationDecl::CreateDeserialized(Context, ID);
02985     break;
02986   case DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION:
02987     D = ClassTemplatePartialSpecializationDecl::CreateDeserialized(Context, ID);
02988     break;
02989   case DECL_VAR_TEMPLATE:
02990     D = VarTemplateDecl::CreateDeserialized(Context, ID);
02991     break;
02992   case DECL_VAR_TEMPLATE_SPECIALIZATION:
02993     D = VarTemplateSpecializationDecl::CreateDeserialized(Context, ID);
02994     break;
02995   case DECL_VAR_TEMPLATE_PARTIAL_SPECIALIZATION:
02996     D = VarTemplatePartialSpecializationDecl::CreateDeserialized(Context, ID);
02997     break;
02998   case DECL_CLASS_SCOPE_FUNCTION_SPECIALIZATION:
02999     D = ClassScopeFunctionSpecializationDecl::CreateDeserialized(Context, ID);
03000     break;
03001   case DECL_FUNCTION_TEMPLATE:
03002     D = FunctionTemplateDecl::CreateDeserialized(Context, ID);
03003     break;
03004   case DECL_TEMPLATE_TYPE_PARM:
03005     D = TemplateTypeParmDecl::CreateDeserialized(Context, ID);
03006     break;
03007   case DECL_NON_TYPE_TEMPLATE_PARM:
03008     D = NonTypeTemplateParmDecl::CreateDeserialized(Context, ID);
03009     break;
03010   case DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK:
03011     D = NonTypeTemplateParmDecl::CreateDeserialized(Context, ID, Record[Idx++]);
03012     break;
03013   case DECL_TEMPLATE_TEMPLATE_PARM:
03014     D = TemplateTemplateParmDecl::CreateDeserialized(Context, ID);
03015     break;
03016   case DECL_EXPANDED_TEMPLATE_TEMPLATE_PARM_PACK:
03017     D = TemplateTemplateParmDecl::CreateDeserialized(Context, ID,
03018                                                      Record[Idx++]);
03019     break;
03020   case DECL_TYPE_ALIAS_TEMPLATE:
03021     D = TypeAliasTemplateDecl::CreateDeserialized(Context, ID);
03022     break;
03023   case DECL_STATIC_ASSERT:
03024     D = StaticAssertDecl::CreateDeserialized(Context, ID);
03025     break;
03026   case DECL_OBJC_METHOD:
03027     D = ObjCMethodDecl::CreateDeserialized(Context, ID);
03028     break;
03029   case DECL_OBJC_INTERFACE:
03030     D = ObjCInterfaceDecl::CreateDeserialized(Context, ID);
03031     break;
03032   case DECL_OBJC_IVAR:
03033     D = ObjCIvarDecl::CreateDeserialized(Context, ID);
03034     break;
03035   case DECL_OBJC_PROTOCOL:
03036     D = ObjCProtocolDecl::CreateDeserialized(Context, ID);
03037     break;
03038   case DECL_OBJC_AT_DEFS_FIELD:
03039     D = ObjCAtDefsFieldDecl::CreateDeserialized(Context, ID);
03040     break;
03041   case DECL_OBJC_CATEGORY:
03042     D = ObjCCategoryDecl::CreateDeserialized(Context, ID);
03043     break;
03044   case DECL_OBJC_CATEGORY_IMPL:
03045     D = ObjCCategoryImplDecl::CreateDeserialized(Context, ID);
03046     break;
03047   case DECL_OBJC_IMPLEMENTATION:
03048     D = ObjCImplementationDecl::CreateDeserialized(Context, ID);
03049     break;
03050   case DECL_OBJC_COMPATIBLE_ALIAS:
03051     D = ObjCCompatibleAliasDecl::CreateDeserialized(Context, ID);
03052     break;
03053   case DECL_OBJC_PROPERTY:
03054     D = ObjCPropertyDecl::CreateDeserialized(Context, ID);
03055     break;
03056   case DECL_OBJC_PROPERTY_IMPL:
03057     D = ObjCPropertyImplDecl::CreateDeserialized(Context, ID);
03058     break;
03059   case DECL_FIELD:
03060     D = FieldDecl::CreateDeserialized(Context, ID);
03061     break;
03062   case DECL_INDIRECTFIELD:
03063     D = IndirectFieldDecl::CreateDeserialized(Context, ID);
03064     break;
03065   case DECL_VAR:
03066     D = VarDecl::CreateDeserialized(Context, ID);
03067     break;
03068   case DECL_IMPLICIT_PARAM:
03069     D = ImplicitParamDecl::CreateDeserialized(Context, ID);
03070     break;
03071   case DECL_PARM_VAR:
03072     D = ParmVarDecl::CreateDeserialized(Context, ID);
03073     break;
03074   case DECL_FILE_SCOPE_ASM:
03075     D = FileScopeAsmDecl::CreateDeserialized(Context, ID);
03076     break;
03077   case DECL_BLOCK:
03078     D = BlockDecl::CreateDeserialized(Context, ID);
03079     break;
03080   case DECL_MS_PROPERTY:
03081     D = MSPropertyDecl::CreateDeserialized(Context, ID);
03082     break;
03083   case DECL_CAPTURED:
03084     D = CapturedDecl::CreateDeserialized(Context, ID, Record[Idx++]);
03085     break;
03086   case DECL_CXX_BASE_SPECIFIERS:
03087     Error("attempt to read a C++ base-specifier record as a declaration");
03088     return nullptr;
03089   case DECL_IMPORT:
03090     // Note: last entry of the ImportDecl record is the number of stored source 
03091     // locations.
03092     D = ImportDecl::CreateDeserialized(Context, ID, Record.back());
03093     break;
03094   case DECL_OMP_THREADPRIVATE:
03095     D = OMPThreadPrivateDecl::CreateDeserialized(Context, ID, Record[Idx++]);
03096     break;
03097   case DECL_EMPTY:
03098     D = EmptyDecl::CreateDeserialized(Context, ID);
03099     break;
03100   }
03101 
03102   assert(D && "Unknown declaration reading AST file");
03103   LoadedDecl(Index, D);
03104   // Set the DeclContext before doing any deserialization, to make sure internal
03105   // calls to Decl::getASTContext() by Decl's methods will find the
03106   // TranslationUnitDecl without crashing.
03107   D->setDeclContext(Context.getTranslationUnitDecl());
03108   Reader.Visit(D);
03109 
03110   // If this declaration is also a declaration context, get the
03111   // offsets for its tables of lexical and visible declarations.
03112   if (DeclContext *DC = dyn_cast<DeclContext>(D)) {
03113     // FIXME: This should really be
03114     //     DeclContext *LookupDC = DC->getPrimaryContext();
03115     // but that can walk the redeclaration chain, which might not work yet.
03116     DeclContext *LookupDC = DC;
03117     if (isa<NamespaceDecl>(DC))
03118       LookupDC = DC->getPrimaryContext();
03119     std::pair<uint64_t, uint64_t> Offsets = Reader.VisitDeclContext(DC);
03120     if (Offsets.first || Offsets.second) {
03121       if (Offsets.first != 0)
03122         DC->setHasExternalLexicalStorage(true);
03123       if (Offsets.second != 0)
03124         LookupDC->setHasExternalVisibleStorage(true);
03125       if (ReadDeclContextStorage(*Loc.F, DeclsCursor, Offsets, 
03126                                  Loc.F->DeclContextInfos[DC]))
03127         return nullptr;
03128     }
03129 
03130     // Now add the pending visible updates for this decl context, if it has any.
03131     DeclContextVisibleUpdatesPending::iterator I =
03132         PendingVisibleUpdates.find(ID);
03133     if (I != PendingVisibleUpdates.end()) {
03134       // There are updates. This means the context has external visible
03135       // storage, even if the original stored version didn't.
03136       LookupDC->setHasExternalVisibleStorage(true);
03137       for (const auto &Update : I->second) {
03138         DeclContextInfo &Info = Update.second->DeclContextInfos[DC];
03139         delete Info.NameLookupTableData;
03140         Info.NameLookupTableData = Update.first;
03141       }
03142       PendingVisibleUpdates.erase(I);
03143     }
03144   }
03145   assert(Idx == Record.size());
03146 
03147   // Load any relevant update records.
03148   PendingUpdateRecords.push_back(std::make_pair(ID, D));
03149 
03150   // Load the categories after recursive loading is finished.
03151   if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
03152     if (Class->isThisDeclarationADefinition())
03153       loadObjCCategories(ID, Class);
03154   
03155   // If we have deserialized a declaration that has a definition the
03156   // AST consumer might need to know about, queue it.
03157   // We don't pass it to the consumer immediately because we may be in recursive
03158   // loading, and some declarations may still be initializing.
03159   if (isConsumerInterestedIn(D, Reader.hasPendingBody()))
03160     InterestingDecls.push_back(D);
03161 
03162   return D;
03163 }
03164 
03165 void ASTReader::loadDeclUpdateRecords(serialization::DeclID ID, Decl *D) {
03166   // The declaration may have been modified by files later in the chain.
03167   // If this is the case, read the record containing the updates from each file
03168   // and pass it to ASTDeclReader to make the modifications.
03169   DeclUpdateOffsetsMap::iterator UpdI = DeclUpdateOffsets.find(ID);
03170   if (UpdI != DeclUpdateOffsets.end()) {
03171     FileOffsetsTy &UpdateOffsets = UpdI->second;
03172     bool WasInteresting = isConsumerInterestedIn(D, false);
03173     for (FileOffsetsTy::iterator
03174          I = UpdateOffsets.begin(), E = UpdateOffsets.end(); I != E; ++I) {
03175       ModuleFile *F = I->first;
03176       uint64_t Offset = I->second;
03177       llvm::BitstreamCursor &Cursor = F->DeclsCursor;
03178       SavedStreamPosition SavedPosition(Cursor);
03179       Cursor.JumpToBit(Offset);
03180       RecordData Record;
03181       unsigned Code = Cursor.ReadCode();
03182       unsigned RecCode = Cursor.readRecord(Code, Record);
03183       (void)RecCode;
03184       assert(RecCode == DECL_UPDATES && "Expected DECL_UPDATES record!");
03185 
03186       unsigned Idx = 0;
03187       ASTDeclReader Reader(*this, *F, ID, 0, Record, Idx);
03188       Reader.UpdateDecl(D, *F, Record);
03189 
03190       // We might have made this declaration interesting. If so, remember that
03191       // we need to hand it off to the consumer.
03192       if (!WasInteresting &&
03193           isConsumerInterestedIn(D, Reader.hasPendingBody())) {
03194         InterestingDecls.push_back(D);
03195         WasInteresting = true;
03196       }
03197     }
03198   }
03199 }
03200 
03201 namespace {
03202   /// \brief Module visitor class that finds all of the redeclarations of a 
03203   /// 
03204   class RedeclChainVisitor {
03205     ASTReader &Reader;
03206     SmallVectorImpl<DeclID> &SearchDecls;
03207     llvm::SmallPtrSetImpl<Decl *> &Deserialized;
03208     GlobalDeclID CanonID;
03209     SmallVector<Decl *, 4> Chain;
03210     
03211   public:
03212     RedeclChainVisitor(ASTReader &Reader, SmallVectorImpl<DeclID> &SearchDecls,
03213                        llvm::SmallPtrSetImpl<Decl *> &Deserialized,
03214                        GlobalDeclID CanonID)
03215       : Reader(Reader), SearchDecls(SearchDecls), Deserialized(Deserialized),
03216         CanonID(CanonID) { 
03217       for (unsigned I = 0, N = SearchDecls.size(); I != N; ++I)
03218         addToChain(Reader.GetDecl(SearchDecls[I]));
03219     }
03220     
03221     static bool visit(ModuleFile &M, bool Preorder, void *UserData) {
03222       if (Preorder)
03223         return false;
03224       
03225       return static_cast<RedeclChainVisitor *>(UserData)->visit(M);
03226     }
03227     
03228     void addToChain(Decl *D) {
03229       if (!D)
03230         return;
03231       
03232       if (Deserialized.erase(D))
03233         Chain.push_back(D);
03234     }
03235     
03236     void searchForID(ModuleFile &M, GlobalDeclID GlobalID) {
03237       // Map global ID of the first declaration down to the local ID
03238       // used in this module file.
03239       DeclID ID = Reader.mapGlobalIDToModuleFileGlobalID(M, GlobalID);
03240       if (!ID)
03241         return;
03242       
03243       // Perform a binary search to find the local redeclarations for this
03244       // declaration (if any).
03245       const LocalRedeclarationsInfo Compare = { ID, 0 };
03246       const LocalRedeclarationsInfo *Result
03247         = std::lower_bound(M.RedeclarationsMap,
03248                            M.RedeclarationsMap + M.LocalNumRedeclarationsInMap, 
03249                            Compare);
03250       if (Result == M.RedeclarationsMap + M.LocalNumRedeclarationsInMap ||
03251           Result->FirstID != ID) {
03252         // If we have a previously-canonical singleton declaration that was 
03253         // merged into another redeclaration chain, create a trivial chain
03254         // for this single declaration so that it will get wired into the 
03255         // complete redeclaration chain.
03256         if (GlobalID != CanonID && 
03257             GlobalID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID && 
03258             GlobalID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls) {
03259           addToChain(Reader.GetDecl(GlobalID));
03260         }
03261         
03262         return;
03263       }
03264       
03265       // Dig out all of the redeclarations.
03266       unsigned Offset = Result->Offset;
03267       unsigned N = M.RedeclarationChains[Offset];
03268       M.RedeclarationChains[Offset++] = 0; // Don't try to deserialize again
03269       for (unsigned I = 0; I != N; ++I)
03270         addToChain(Reader.GetLocalDecl(M, M.RedeclarationChains[Offset++]));
03271     }
03272     
03273     bool visit(ModuleFile &M) {
03274       // Visit each of the declarations.
03275       for (unsigned I = 0, N = SearchDecls.size(); I != N; ++I)
03276         searchForID(M, SearchDecls[I]);
03277       // FIXME: If none of the SearchDecls had local IDs in this module, can
03278       // we avoid searching any ancestor module files?
03279       return false;
03280     }
03281     
03282     ArrayRef<Decl *> getChain() const {
03283       return Chain;
03284     }
03285   };
03286 }
03287 
03288 void ASTReader::loadPendingDeclChain(serialization::GlobalDeclID ID) {
03289   Decl *D = GetDecl(ID);  
03290   Decl *CanonDecl = D->getCanonicalDecl();
03291   
03292   // Determine the set of declaration IDs we'll be searching for.
03293   SmallVector<DeclID, 1> SearchDecls;
03294   GlobalDeclID CanonID = 0;
03295   if (D == CanonDecl) {
03296     SearchDecls.push_back(ID); // Always first.
03297     CanonID = ID;
03298   }
03299   MergedDeclsMap::iterator MergedPos = combineStoredMergedDecls(CanonDecl, ID);
03300   if (MergedPos != MergedDecls.end())
03301     SearchDecls.append(MergedPos->second.begin(), MergedPos->second.end());
03302   
03303   // Build up the list of redeclarations.
03304   RedeclChainVisitor Visitor(*this, SearchDecls, RedeclsDeserialized, CanonID);
03305   ModuleMgr.visitDepthFirst(&RedeclChainVisitor::visit, &Visitor);
03306   
03307   // Retrieve the chains.
03308   ArrayRef<Decl *> Chain = Visitor.getChain();
03309   if (Chain.empty())
03310     return;
03311     
03312   // Hook up the chains.
03313   Decl *MostRecent = CanonDecl->getMostRecentDecl();
03314   for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
03315     if (Chain[I] == CanonDecl)
03316       continue;
03317 
03318     ASTDeclReader::attachPreviousDecl(*this, Chain[I], MostRecent);
03319     MostRecent = Chain[I];
03320   }
03321   
03322   ASTDeclReader::attachLatestDecl(CanonDecl, MostRecent);  
03323 }
03324 
03325 namespace {
03326   /// \brief Given an ObjC interface, goes through the modules and links to the
03327   /// interface all the categories for it.
03328   class ObjCCategoriesVisitor {
03329     ASTReader &Reader;
03330     serialization::GlobalDeclID InterfaceID;
03331     ObjCInterfaceDecl *Interface;
03332     llvm::SmallPtrSetImpl<ObjCCategoryDecl *> &Deserialized;
03333     unsigned PreviousGeneration;
03334     ObjCCategoryDecl *Tail;
03335     llvm::DenseMap<DeclarationName, ObjCCategoryDecl *> NameCategoryMap;
03336     
03337     void add(ObjCCategoryDecl *Cat) {
03338       // Only process each category once.
03339       if (!Deserialized.erase(Cat))
03340         return;
03341       
03342       // Check for duplicate categories.
03343       if (Cat->getDeclName()) {
03344         ObjCCategoryDecl *&Existing = NameCategoryMap[Cat->getDeclName()];
03345         if (Existing && 
03346             Reader.getOwningModuleFile(Existing) 
03347                                           != Reader.getOwningModuleFile(Cat)) {
03348           // FIXME: We should not warn for duplicates in diamond:
03349           //
03350           //   MT     //
03351           //  /  \    //
03352           // ML  MR   //
03353           //  \  /    //
03354           //   MB     //
03355           //
03356           // If there are duplicates in ML/MR, there will be warning when 
03357           // creating MB *and* when importing MB. We should not warn when 
03358           // importing.
03359           Reader.Diag(Cat->getLocation(), diag::warn_dup_category_def)
03360             << Interface->getDeclName() << Cat->getDeclName();
03361           Reader.Diag(Existing->getLocation(), diag::note_previous_definition);
03362         } else if (!Existing) {
03363           // Record this category.
03364           Existing = Cat;
03365         }
03366       }
03367       
03368       // Add this category to the end of the chain.
03369       if (Tail)
03370         ASTDeclReader::setNextObjCCategory(Tail, Cat);
03371       else
03372         Interface->setCategoryListRaw(Cat);
03373       Tail = Cat;
03374     }
03375     
03376   public:
03377     ObjCCategoriesVisitor(ASTReader &Reader,
03378                           serialization::GlobalDeclID InterfaceID,
03379                           ObjCInterfaceDecl *Interface,
03380                         llvm::SmallPtrSetImpl<ObjCCategoryDecl *> &Deserialized,
03381                           unsigned PreviousGeneration)
03382       : Reader(Reader), InterfaceID(InterfaceID), Interface(Interface),
03383         Deserialized(Deserialized), PreviousGeneration(PreviousGeneration),
03384         Tail(nullptr)
03385     {
03386       // Populate the name -> category map with the set of known categories.
03387       for (auto *Cat : Interface->known_categories()) {
03388         if (Cat->getDeclName())
03389           NameCategoryMap[Cat->getDeclName()] = Cat;
03390         
03391         // Keep track of the tail of the category list.
03392         Tail = Cat;
03393       }
03394     }
03395 
03396     static bool visit(ModuleFile &M, void *UserData) {
03397       return static_cast<ObjCCategoriesVisitor *>(UserData)->visit(M);
03398     }
03399 
03400     bool visit(ModuleFile &M) {
03401       // If we've loaded all of the category information we care about from
03402       // this module file, we're done.
03403       if (M.Generation <= PreviousGeneration)
03404         return true;
03405       
03406       // Map global ID of the definition down to the local ID used in this 
03407       // module file. If there is no such mapping, we'll find nothing here
03408       // (or in any module it imports).
03409       DeclID LocalID = Reader.mapGlobalIDToModuleFileGlobalID(M, InterfaceID);
03410       if (!LocalID)
03411         return true;
03412 
03413       // Perform a binary search to find the local redeclarations for this
03414       // declaration (if any).
03415       const ObjCCategoriesInfo Compare = { LocalID, 0 };
03416       const ObjCCategoriesInfo *Result
03417         = std::lower_bound(M.ObjCCategoriesMap,
03418                            M.ObjCCategoriesMap + M.LocalNumObjCCategoriesInMap, 
03419                            Compare);
03420       if (Result == M.ObjCCategoriesMap + M.LocalNumObjCCategoriesInMap ||
03421           Result->DefinitionID != LocalID) {
03422         // We didn't find anything. If the class definition is in this module
03423         // file, then the module files it depends on cannot have any categories,
03424         // so suppress further lookup.
03425         return Reader.isDeclIDFromModule(InterfaceID, M);
03426       }
03427       
03428       // We found something. Dig out all of the categories.
03429       unsigned Offset = Result->Offset;
03430       unsigned N = M.ObjCCategories[Offset];
03431       M.ObjCCategories[Offset++] = 0; // Don't try to deserialize again
03432       for (unsigned I = 0; I != N; ++I)
03433         add(cast_or_null<ObjCCategoryDecl>(
03434               Reader.GetLocalDecl(M, M.ObjCCategories[Offset++])));
03435       return true;
03436     }
03437   };
03438 }
03439 
03440 void ASTReader::loadObjCCategories(serialization::GlobalDeclID ID,
03441                                    ObjCInterfaceDecl *D,
03442                                    unsigned PreviousGeneration) {
03443   ObjCCategoriesVisitor Visitor(*this, ID, D, CategoriesDeserialized,
03444                                 PreviousGeneration);
03445   ModuleMgr.visit(ObjCCategoriesVisitor::visit, &Visitor);
03446 }
03447 
03448 namespace {
03449 /// Iterator over the redeclarations of a declaration that have already
03450 /// been merged into the same redeclaration chain.
03451 template<typename DeclT>
03452 class MergedRedeclIterator {
03453   DeclT *Start, *Canonical, *Current;
03454 public:
03455   MergedRedeclIterator() : Current(nullptr) {}
03456   MergedRedeclIterator(DeclT *Start)
03457       : Start(Start), Canonical(nullptr), Current(Start) {}
03458 
03459   DeclT *operator*() { return Current; }
03460 
03461   MergedRedeclIterator &operator++() {
03462     if (Current->isFirstDecl()) {
03463       Canonical = Current;
03464       Current = Current->getMostRecentDecl();
03465     } else
03466       Current = Current->getPreviousDecl();
03467 
03468     // If we started in the merged portion, we'll reach our start position
03469     // eventually. Otherwise, we'll never reach it, but the second declaration
03470     // we reached was the canonical declaration, so stop when we see that one
03471     // again.
03472     if (Current == Start || Current == Canonical)
03473       Current = nullptr;
03474     return *this;
03475   }
03476 
03477   friend bool operator!=(const MergedRedeclIterator &A,
03478                          const MergedRedeclIterator &B) {
03479     return A.Current != B.Current;
03480   }
03481 };
03482 }
03483 template<typename DeclT>
03484 llvm::iterator_range<MergedRedeclIterator<DeclT>> merged_redecls(DeclT *D) {
03485   return llvm::iterator_range<MergedRedeclIterator<DeclT>>(
03486       MergedRedeclIterator<DeclT>(D),
03487       MergedRedeclIterator<DeclT>());
03488 }
03489 
03490 template<typename DeclT, typename Fn>
03491 static void forAllLaterRedecls(DeclT *D, Fn F) {
03492   F(D);
03493 
03494   // Check whether we've already merged D into its redeclaration chain.
03495   // MostRecent may or may not be nullptr if D has not been merged. If
03496   // not, walk the merged redecl chain and see if it's there.
03497   auto *MostRecent = D->getMostRecentDecl();
03498   bool Found = false;
03499   for (auto *Redecl = MostRecent; Redecl && !Found;
03500        Redecl = Redecl->getPreviousDecl())
03501     Found = (Redecl == D);
03502 
03503   // If this declaration is merged, apply the functor to all later decls.
03504   if (Found) {
03505     for (auto *Redecl = MostRecent; Redecl != D;
03506          Redecl = Redecl->getPreviousDecl())
03507       F(Redecl);
03508   }
03509 }
03510 
03511 void ASTDeclReader::UpdateDecl(Decl *D, ModuleFile &ModuleFile,
03512                                const RecordData &Record) {
03513   while (Idx < Record.size()) {
03514     switch ((DeclUpdateKind)Record[Idx++]) {
03515     case UPD_CXX_ADDED_IMPLICIT_MEMBER: {
03516       // FIXME: If we also have an update record for instantiating the
03517       // definition of D, we need that to happen before we get here.
03518       Decl *MD = Reader.ReadDecl(ModuleFile, Record, Idx);
03519       assert(MD && "couldn't read decl from update record");
03520       // FIXME: We should call addHiddenDecl instead, to add the member
03521       // to its DeclContext.
03522       cast<CXXRecordDecl>(D)->addedMember(MD);
03523       break;
03524     }
03525 
03526     case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
03527       // It will be added to the template's specializations set when loaded.
03528       (void)Reader.ReadDecl(ModuleFile, Record, Idx);
03529       break;
03530 
03531     case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE: {
03532       NamespaceDecl *Anon
03533         = Reader.ReadDeclAs<NamespaceDecl>(ModuleFile, Record, Idx);
03534       
03535       // Each module has its own anonymous namespace, which is disjoint from
03536       // any other module's anonymous namespaces, so don't attach the anonymous
03537       // namespace at all.
03538       if (ModuleFile.Kind != MK_ImplicitModule &&
03539           ModuleFile.Kind != MK_ExplicitModule) {
03540         if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(D))
03541           TU->setAnonymousNamespace(Anon);
03542         else
03543           cast<NamespaceDecl>(D)->setAnonymousNamespace(Anon);
03544       }
03545       break;
03546     }
03547 
03548     case UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER:
03549       cast<VarDecl>(D)->getMemberSpecializationInfo()->setPointOfInstantiation(
03550           Reader.ReadSourceLocation(ModuleFile, Record, Idx));
03551       break;
03552 
03553     case UPD_CXX_ADDED_FUNCTION_DEFINITION: {
03554       FunctionDecl *FD = cast<FunctionDecl>(D);
03555       if (Reader.PendingBodies[FD]) {
03556         // FIXME: Maybe check for ODR violations.
03557         // It's safe to stop now because this update record is always last.
03558         return;
03559       }
03560 
03561       if (Record[Idx++]) {
03562         // Maintain AST consistency: any later redeclarations of this function
03563         // are inline if this one is. (We might have merged another declaration
03564         // into this one.)
03565         forAllLaterRedecls(FD, [](FunctionDecl *FD) {
03566           FD->setImplicitlyInline();
03567         });
03568       }
03569       FD->setInnerLocStart(Reader.ReadSourceLocation(ModuleFile, Record, Idx));
03570       if (auto *CD = dyn_cast<CXXConstructorDecl>(FD))
03571         std::tie(CD->CtorInitializers, CD->NumCtorInitializers) =
03572             Reader.ReadCXXCtorInitializers(ModuleFile, Record, Idx);
03573       if (auto *DD = dyn_cast<CXXDestructorDecl>(FD))
03574         // FIXME: Check consistency.
03575         DD->setOperatorDelete(Reader.ReadDeclAs<FunctionDecl>(ModuleFile,
03576                                                               Record, Idx));
03577       // Store the offset of the body so we can lazily load it later.
03578       Reader.PendingBodies[FD] = GetCurrentCursorOffset();
03579       HasPendingBody = true;
03580       assert(Idx == Record.size() && "lazy body must be last");
03581       break;
03582     }
03583 
03584     case UPD_CXX_INSTANTIATED_CLASS_DEFINITION: {
03585       auto *RD = cast<CXXRecordDecl>(D);
03586       bool HadDefinition = RD->getDefinition();
03587       ReadCXXRecordDefinition(RD);
03588       // Visible update is handled separately.
03589       uint64_t LexicalOffset = Record[Idx++];
03590       if (!HadDefinition && LexicalOffset) {
03591         RD->setHasExternalLexicalStorage(true);
03592         Reader.ReadDeclContextStorage(ModuleFile, ModuleFile.DeclsCursor,
03593                                           std::make_pair(LexicalOffset, 0),
03594                                           ModuleFile.DeclContextInfos[RD]);
03595         Reader.PendingDefinitions.insert(RD);
03596       }
03597 
03598       auto TSK = (TemplateSpecializationKind)Record[Idx++];
03599       SourceLocation POI = Reader.ReadSourceLocation(ModuleFile, Record, Idx);
03600       if (MemberSpecializationInfo *MSInfo =
03601               RD->getMemberSpecializationInfo()) {
03602         MSInfo->setTemplateSpecializationKind(TSK);
03603         MSInfo->setPointOfInstantiation(POI);
03604       } else {
03605         ClassTemplateSpecializationDecl *Spec =
03606             cast<ClassTemplateSpecializationDecl>(RD);
03607         Spec->setTemplateSpecializationKind(TSK);
03608         Spec->setPointOfInstantiation(POI);
03609 
03610         if (Record[Idx++]) {
03611           auto PartialSpec =
03612               ReadDeclAs<ClassTemplatePartialSpecializationDecl>(Record, Idx);
03613           SmallVector<TemplateArgument, 8> TemplArgs;
03614           Reader.ReadTemplateArgumentList(TemplArgs, F, Record, Idx);
03615           auto *TemplArgList = TemplateArgumentList::CreateCopy(
03616               Reader.getContext(), TemplArgs.data(), TemplArgs.size());
03617 
03618           // FIXME: If we already have a partial specialization set,
03619           // check that it matches.
03620           if (!Spec->getSpecializedTemplateOrPartial()
03621                    .is<ClassTemplatePartialSpecializationDecl *>())
03622             Spec->setInstantiationOf(PartialSpec, TemplArgList);
03623         }
03624       }
03625 
03626       RD->setTagKind((TagTypeKind)Record[Idx++]);
03627       RD->setLocation(Reader.ReadSourceLocation(ModuleFile, Record, Idx));
03628       RD->setLocStart(Reader.ReadSourceLocation(ModuleFile, Record, Idx));
03629       RD->setRBraceLoc(Reader.ReadSourceLocation(ModuleFile, Record, Idx));
03630 
03631       if (Record[Idx++]) {
03632         AttrVec Attrs;
03633         Reader.ReadAttributes(F, Attrs, Record, Idx);
03634         D->setAttrsImpl(Attrs, Reader.getContext());
03635       }
03636       break;
03637     }
03638 
03639     case UPD_CXX_RESOLVED_EXCEPTION_SPEC: {
03640       // FIXME: This doesn't send the right notifications if there are
03641       // ASTMutationListeners other than an ASTWriter.
03642       FunctionProtoType::ExceptionSpecInfo ESI;
03643       SmallVector<QualType, 8> ExceptionStorage;
03644       Reader.readExceptionSpec(ModuleFile, ExceptionStorage, ESI, Record, Idx);
03645       for (auto *Redecl : merged_redecls(D)) {
03646         auto *FD = cast<FunctionDecl>(Redecl);
03647         auto *FPT = FD->getType()->castAs<FunctionProtoType>();
03648         if (!isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
03649           // AST invariant: if any exception spec in the redecl chain is
03650           // resolved, all are resolved. We don't need to go any further.
03651           // FIXME: If the exception spec is resolved, check that it matches.
03652           break;
03653         }
03654         FD->setType(Reader.Context.getFunctionType(
03655             FPT->getReturnType(), FPT->getParamTypes(),
03656             FPT->getExtProtoInfo().withExceptionSpec(ESI)));
03657       }
03658       break;
03659     }
03660 
03661     case UPD_CXX_DEDUCED_RETURN_TYPE: {
03662       // FIXME: Also do this when merging redecls.
03663       QualType DeducedResultType = Reader.readType(ModuleFile, Record, Idx);
03664       for (auto *Redecl : merged_redecls(D)) {
03665         // FIXME: If the return type is already deduced, check that it matches.
03666         FunctionDecl *FD = cast<FunctionDecl>(Redecl);
03667         Reader.Context.adjustDeducedFunctionResultType(FD, DeducedResultType);
03668       }
03669       break;
03670     }
03671 
03672     case UPD_DECL_MARKED_USED: {
03673       // FIXME: This doesn't send the right notifications if there are
03674       // ASTMutationListeners other than an ASTWriter.
03675 
03676       // Maintain AST consistency: any later redeclarations are used too.
03677       forAllLaterRedecls(D, [](Decl *D) { D->Used = true; });
03678       break;
03679     }
03680 
03681     case UPD_MANGLING_NUMBER:
03682       Reader.Context.setManglingNumber(cast<NamedDecl>(D), Record[Idx++]);
03683       break;
03684 
03685     case UPD_STATIC_LOCAL_NUMBER:
03686       Reader.Context.setStaticLocalNumber(cast<VarDecl>(D), Record[Idx++]);
03687       break;
03688     case UPD_DECL_MARKED_OPENMP_THREADPRIVATE:
03689       D->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
03690           Reader.Context, ReadSourceRange(Record, Idx)));
03691       break;
03692     }
03693   }
03694 }