Home | History | Annotate | Download | only in Serialization
      1 //===--- ASTReaderDecl.cpp - Decl Deserialization ---------------*- C++ -*-===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 // This file implements the ASTReader::ReadDeclRecord method, which is the
     11 // entrypoint for loading a decl.
     12 //
     13 //===----------------------------------------------------------------------===//
     14 
     15 #include "clang/Serialization/ASTReader.h"
     16 #include "ASTCommon.h"
     17 #include "ASTReaderInternals.h"
     18 #include "clang/AST/ASTConsumer.h"
     19 #include "clang/AST/ASTContext.h"
     20 #include "clang/AST/DeclCXX.h"
     21 #include "clang/AST/DeclGroup.h"
     22 #include "clang/AST/DeclTemplate.h"
     23 #include "clang/AST/DeclVisitor.h"
     24 #include "clang/AST/Expr.h"
     25 #include "clang/Sema/IdentifierResolver.h"
     26 #include "clang/Sema/Sema.h"
     27 #include "clang/Sema/SemaDiagnostic.h"
     28 #include "llvm/Support/SaveAndRestore.h"
     29 using namespace clang;
     30 using namespace clang::serialization;
     31 
     32 //===----------------------------------------------------------------------===//
     33 // Declaration deserialization
     34 //===----------------------------------------------------------------------===//
     35 
     36 namespace clang {
     37   class ASTDeclReader : public DeclVisitor<ASTDeclReader, void> {
     38     ASTReader &Reader;
     39     ModuleFile &F;
     40     const DeclID ThisDeclID;
     41     const unsigned RawLocation;
     42     typedef ASTReader::RecordData RecordData;
     43     const RecordData &Record;
     44     unsigned &Idx;
     45     TypeID TypeIDForTypeDecl;
     46 
     47     bool HasPendingBody;
     48 
     49     uint64_t GetCurrentCursorOffset();
     50 
     51     SourceLocation ReadSourceLocation(const RecordData &R, unsigned &I) {
     52       return Reader.ReadSourceLocation(F, R, I);
     53     }
     54 
     55     SourceRange ReadSourceRange(const RecordData &R, unsigned &I) {
     56       return Reader.ReadSourceRange(F, R, I);
     57     }
     58 
     59     TypeSourceInfo *GetTypeSourceInfo(const RecordData &R, unsigned &I) {
     60       return Reader.GetTypeSourceInfo(F, R, I);
     61     }
     62 
     63     serialization::DeclID ReadDeclID(const RecordData &R, unsigned &I) {
     64       return Reader.ReadDeclID(F, R, I);
     65     }
     66 
     67     Decl *ReadDecl(const RecordData &R, unsigned &I) {
     68       return Reader.ReadDecl(F, R, I);
     69     }
     70 
     71     template<typename T>
     72     T *ReadDeclAs(const RecordData &R, unsigned &I) {
     73       return Reader.ReadDeclAs<T>(F, R, I);
     74     }
     75 
     76     void ReadQualifierInfo(QualifierInfo &Info,
     77                            const RecordData &R, unsigned &I) {
     78       Reader.ReadQualifierInfo(F, Info, R, I);
     79     }
     80 
     81     void ReadDeclarationNameLoc(DeclarationNameLoc &DNLoc, DeclarationName Name,
     82                                 const RecordData &R, unsigned &I) {
     83       Reader.ReadDeclarationNameLoc(F, DNLoc, Name, R, I);
     84     }
     85 
     86     void ReadDeclarationNameInfo(DeclarationNameInfo &NameInfo,
     87                                 const RecordData &R, unsigned &I) {
     88       Reader.ReadDeclarationNameInfo(F, NameInfo, R, I);
     89     }
     90 
     91     serialization::SubmoduleID readSubmoduleID(const RecordData &R,
     92                                                unsigned &I) {
     93       if (I >= R.size())
     94         return 0;
     95 
     96       return Reader.getGlobalSubmoduleID(F, R[I++]);
     97     }
     98 
     99     Module *readModule(const RecordData &R, unsigned &I) {
    100       return Reader.getSubmodule(readSubmoduleID(R, I));
    101     }
    102 
    103     void ReadCXXDefinitionData(struct CXXRecordDecl::DefinitionData &Data,
    104                                const RecordData &R, unsigned &I);
    105 
    106     /// \brief RAII class used to capture the first ID within a redeclaration
    107     /// chain and to introduce it into the list of pending redeclaration chains
    108     /// on destruction.
    109     ///
    110     /// The caller can choose not to introduce this ID into the redeclaration
    111     /// chain by calling \c suppress().
    112     class RedeclarableResult {
    113       ASTReader &Reader;
    114       GlobalDeclID FirstID;
    115       mutable bool Owning;
    116       Decl::Kind DeclKind;
    117 
    118       void operator=(RedeclarableResult &) LLVM_DELETED_FUNCTION;
    119 
    120     public:
    121       RedeclarableResult(ASTReader &Reader, GlobalDeclID FirstID,
    122                          Decl::Kind DeclKind)
    123         : Reader(Reader), FirstID(FirstID), Owning(true), DeclKind(DeclKind) { }
    124 
    125       RedeclarableResult(const RedeclarableResult &Other)
    126         : Reader(Other.Reader), FirstID(Other.FirstID), Owning(Other.Owning) ,
    127           DeclKind(Other.DeclKind)
    128       {
    129         Other.Owning = false;
    130       }
    131 
    132       ~RedeclarableResult() {
    133         if (FirstID && Owning && isRedeclarableDeclKind(DeclKind) &&
    134             Reader.PendingDeclChainsKnown.insert(FirstID))
    135           Reader.PendingDeclChains.push_back(FirstID);
    136       }
    137 
    138       /// \brief Retrieve the first ID.
    139       GlobalDeclID getFirstID() const { return FirstID; }
    140 
    141       /// \brief Do not introduce this declaration ID into the set of pending
    142       /// declaration chains.
    143       void suppress() {
    144         Owning = false;
    145       }
    146     };
    147 
    148     /// \brief Class used to capture the result of searching for an existing
    149     /// declaration of a specific kind and name, along with the ability
    150     /// to update the place where this result was found (the declaration
    151     /// chain hanging off an identifier or the DeclContext we searched in)
    152     /// if requested.
    153     class FindExistingResult {
    154       ASTReader &Reader;
    155       NamedDecl *New;
    156       NamedDecl *Existing;
    157       mutable bool AddResult;
    158 
    159       void operator=(FindExistingResult&) LLVM_DELETED_FUNCTION;
    160 
    161     public:
    162       FindExistingResult(ASTReader &Reader)
    163         : Reader(Reader), New(0), Existing(0), AddResult(false) { }
    164 
    165       FindExistingResult(ASTReader &Reader, NamedDecl *New, NamedDecl *Existing)
    166         : Reader(Reader), New(New), Existing(Existing), AddResult(true) { }
    167 
    168       FindExistingResult(const FindExistingResult &Other)
    169         : Reader(Other.Reader), New(Other.New), Existing(Other.Existing),
    170           AddResult(Other.AddResult)
    171       {
    172         Other.AddResult = false;
    173       }
    174 
    175       ~FindExistingResult();
    176 
    177       /// \brief Suppress the addition of this result into the known set of
    178       /// names.
    179       void suppress() { AddResult = false; }
    180 
    181       operator NamedDecl*() const { return Existing; }
    182 
    183       template<typename T>
    184       operator T*() const { return dyn_cast_or_null<T>(Existing); }
    185     };
    186 
    187     FindExistingResult findExisting(NamedDecl *D);
    188 
    189   public:
    190     ASTDeclReader(ASTReader &Reader, ModuleFile &F,
    191                   DeclID thisDeclID,
    192                   unsigned RawLocation,
    193                   const RecordData &Record, unsigned &Idx)
    194       : Reader(Reader), F(F), ThisDeclID(thisDeclID),
    195         RawLocation(RawLocation), Record(Record), Idx(Idx),
    196         TypeIDForTypeDecl(0), HasPendingBody(false) { }
    197 
    198     static void attachPreviousDecl(Decl *D, Decl *previous);
    199     static void attachLatestDecl(Decl *D, Decl *latest);
    200 
    201     /// \brief Determine whether this declaration has a pending body.
    202     bool hasPendingBody() const { return HasPendingBody; }
    203 
    204     void Visit(Decl *D);
    205 
    206     void UpdateDecl(Decl *D, ModuleFile &ModuleFile,
    207                     const RecordData &Record);
    208 
    209     static void setNextObjCCategory(ObjCCategoryDecl *Cat,
    210                                     ObjCCategoryDecl *Next) {
    211       Cat->NextClassCategory = Next;
    212     }
    213 
    214     void VisitDecl(Decl *D);
    215     void VisitTranslationUnitDecl(TranslationUnitDecl *TU);
    216     void VisitNamedDecl(NamedDecl *ND);
    217     void VisitLabelDecl(LabelDecl *LD);
    218     void VisitNamespaceDecl(NamespaceDecl *D);
    219     void VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
    220     void VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
    221     void VisitTypeDecl(TypeDecl *TD);
    222     void VisitTypedefNameDecl(TypedefNameDecl *TD);
    223     void VisitTypedefDecl(TypedefDecl *TD);
    224     void VisitTypeAliasDecl(TypeAliasDecl *TD);
    225     void VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
    226     void VisitTagDecl(TagDecl *TD);
    227     void VisitEnumDecl(EnumDecl *ED);
    228     void VisitRecordDecl(RecordDecl *RD);
    229     void VisitCXXRecordDecl(CXXRecordDecl *D);
    230     void VisitClassTemplateSpecializationDecl(
    231                                             ClassTemplateSpecializationDecl *D);
    232     void VisitClassTemplatePartialSpecializationDecl(
    233                                      ClassTemplatePartialSpecializationDecl *D);
    234     void VisitClassScopeFunctionSpecializationDecl(
    235                                        ClassScopeFunctionSpecializationDecl *D);
    236     void VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
    237     void VisitValueDecl(ValueDecl *VD);
    238     void VisitEnumConstantDecl(EnumConstantDecl *ECD);
    239     void VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
    240     void VisitDeclaratorDecl(DeclaratorDecl *DD);
    241     void VisitFunctionDecl(FunctionDecl *FD);
    242     void VisitCXXMethodDecl(CXXMethodDecl *D);
    243     void VisitCXXConstructorDecl(CXXConstructorDecl *D);
    244     void VisitCXXDestructorDecl(CXXDestructorDecl *D);
    245     void VisitCXXConversionDecl(CXXConversionDecl *D);
    246     void VisitFieldDecl(FieldDecl *FD);
    247     void VisitIndirectFieldDecl(IndirectFieldDecl *FD);
    248     void VisitVarDecl(VarDecl *VD);
    249     void VisitImplicitParamDecl(ImplicitParamDecl *PD);
    250     void VisitParmVarDecl(ParmVarDecl *PD);
    251     void VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
    252     void VisitTemplateDecl(TemplateDecl *D);
    253     RedeclarableResult VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D);
    254     void VisitClassTemplateDecl(ClassTemplateDecl *D);
    255     void VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
    256     void VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
    257     void VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D);
    258     void VisitUsingDecl(UsingDecl *D);
    259     void VisitUsingShadowDecl(UsingShadowDecl *D);
    260     void VisitLinkageSpecDecl(LinkageSpecDecl *D);
    261     void VisitFileScopeAsmDecl(FileScopeAsmDecl *AD);
    262     void VisitImportDecl(ImportDecl *D);
    263     void VisitAccessSpecDecl(AccessSpecDecl *D);
    264     void VisitFriendDecl(FriendDecl *D);
    265     void VisitFriendTemplateDecl(FriendTemplateDecl *D);
    266     void VisitStaticAssertDecl(StaticAssertDecl *D);
    267     void VisitBlockDecl(BlockDecl *BD);
    268     void VisitEmptyDecl(EmptyDecl *D);
    269 
    270     std::pair<uint64_t, uint64_t> VisitDeclContext(DeclContext *DC);
    271 
    272     template<typename T>
    273     RedeclarableResult VisitRedeclarable(Redeclarable<T> *D);
    274 
    275     template<typename T>
    276     void mergeRedeclarable(Redeclarable<T> *D, RedeclarableResult &Redecl);
    277 
    278     // FIXME: Reorder according to DeclNodes.td?
    279     void VisitObjCMethodDecl(ObjCMethodDecl *D);
    280     void VisitObjCContainerDecl(ObjCContainerDecl *D);
    281     void VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
    282     void VisitObjCIvarDecl(ObjCIvarDecl *D);
    283     void VisitObjCProtocolDecl(ObjCProtocolDecl *D);
    284     void VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D);
    285     void VisitObjCCategoryDecl(ObjCCategoryDecl *D);
    286     void VisitObjCImplDecl(ObjCImplDecl *D);
    287     void VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
    288     void VisitObjCImplementationDecl(ObjCImplementationDecl *D);
    289     void VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *D);
    290     void VisitObjCPropertyDecl(ObjCPropertyDecl *D);
    291     void VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D);
    292   };
    293 }
    294 
    295 uint64_t ASTDeclReader::GetCurrentCursorOffset() {
    296   return F.DeclsCursor.GetCurrentBitNo() + F.GlobalBitOffset;
    297 }
    298 
    299 void ASTDeclReader::Visit(Decl *D) {
    300   DeclVisitor<ASTDeclReader, void>::Visit(D);
    301 
    302   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
    303     if (DD->DeclInfo) {
    304       DeclaratorDecl::ExtInfo *Info =
    305           DD->DeclInfo.get<DeclaratorDecl::ExtInfo *>();
    306       Info->TInfo =
    307           GetTypeSourceInfo(Record, Idx);
    308     }
    309     else {
    310       DD->DeclInfo = GetTypeSourceInfo(Record, Idx);
    311     }
    312   }
    313 
    314   if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
    315     // if we have a fully initialized TypeDecl, we can safely read its type now.
    316     TD->setTypeForDecl(Reader.GetType(TypeIDForTypeDecl).getTypePtrOrNull());
    317   } else if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
    318     // if we have a fully initialized TypeDecl, we can safely read its type now.
    319     ID->TypeForDecl = Reader.GetType(TypeIDForTypeDecl).getTypePtrOrNull();
    320   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
    321     // FunctionDecl's body was written last after all other Stmts/Exprs.
    322     // We only read it if FD doesn't already have a body (e.g., from another
    323     // module).
    324     // FIXME: Also consider = default and = delete.
    325     // FIXME: Can we diagnose ODR violations somehow?
    326     if (Record[Idx++]) {
    327       Reader.PendingBodies[FD] = GetCurrentCursorOffset();
    328       HasPendingBody = true;
    329     }
    330   }
    331 }
    332 
    333 void ASTDeclReader::VisitDecl(Decl *D) {
    334   if (D->isTemplateParameter()) {
    335     // We don't want to deserialize the DeclContext of a template
    336     // parameter immediately, because the template parameter might be
    337     // used in the formulation of its DeclContext. Use the translation
    338     // unit DeclContext as a placeholder.
    339     GlobalDeclID SemaDCIDForTemplateParmDecl = ReadDeclID(Record, Idx);
    340     GlobalDeclID LexicalDCIDForTemplateParmDecl = ReadDeclID(Record, Idx);
    341     Reader.addPendingDeclContextInfo(D,
    342                                      SemaDCIDForTemplateParmDecl,
    343                                      LexicalDCIDForTemplateParmDecl);
    344     D->setDeclContext(Reader.getContext().getTranslationUnitDecl());
    345   } else {
    346     DeclContext *SemaDC = ReadDeclAs<DeclContext>(Record, Idx);
    347     DeclContext *LexicalDC = ReadDeclAs<DeclContext>(Record, Idx);
    348     // Avoid calling setLexicalDeclContext() directly because it uses
    349     // Decl::getASTContext() internally which is unsafe during derialization.
    350     D->setDeclContextsImpl(SemaDC, LexicalDC, Reader.getContext());
    351   }
    352   D->setLocation(Reader.ReadSourceLocation(F, RawLocation));
    353   D->setInvalidDecl(Record[Idx++]);
    354   if (Record[Idx++]) { // hasAttrs
    355     AttrVec Attrs;
    356     Reader.ReadAttributes(F, Attrs, Record, Idx);
    357     // Avoid calling setAttrs() directly because it uses Decl::getASTContext()
    358     // internally which is unsafe during derialization.
    359     D->setAttrsImpl(Attrs, Reader.getContext());
    360   }
    361   D->setImplicit(Record[Idx++]);
    362   D->setUsed(Record[Idx++]);
    363   D->setReferenced(Record[Idx++]);
    364   D->setTopLevelDeclInObjCContainer(Record[Idx++]);
    365   D->setAccess((AccessSpecifier)Record[Idx++]);
    366   D->FromASTFile = true;
    367   D->setModulePrivate(Record[Idx++]);
    368   D->Hidden = D->isModulePrivate();
    369 
    370   // Determine whether this declaration is part of a (sub)module. If so, it
    371   // may not yet be visible.
    372   if (unsigned SubmoduleID = readSubmoduleID(Record, Idx)) {
    373     // Store the owning submodule ID in the declaration.
    374     D->setOwningModuleID(SubmoduleID);
    375 
    376     // Module-private declarations are never visible, so there is no work to do.
    377     if (!D->isModulePrivate()) {
    378       if (Module *Owner = Reader.getSubmodule(SubmoduleID)) {
    379         if (Owner->NameVisibility != Module::AllVisible) {
    380           // The owning module is not visible. Mark this declaration as hidden.
    381           D->Hidden = true;
    382 
    383           // Note that this declaration was hidden because its owning module is
    384           // not yet visible.
    385           Reader.HiddenNamesMap[Owner].push_back(D);
    386         }
    387       }
    388     }
    389   }
    390 }
    391 
    392 void ASTDeclReader::VisitTranslationUnitDecl(TranslationUnitDecl *TU) {
    393   llvm_unreachable("Translation units are not serialized");
    394 }
    395 
    396 void ASTDeclReader::VisitNamedDecl(NamedDecl *ND) {
    397   VisitDecl(ND);
    398   ND->setDeclName(Reader.ReadDeclarationName(F, Record, Idx));
    399 }
    400 
    401 void ASTDeclReader::VisitTypeDecl(TypeDecl *TD) {
    402   VisitNamedDecl(TD);
    403   TD->setLocStart(ReadSourceLocation(Record, Idx));
    404   // Delay type reading until after we have fully initialized the decl.
    405   TypeIDForTypeDecl = Reader.getGlobalTypeID(F, Record[Idx++]);
    406 }
    407 
    408 void ASTDeclReader::VisitTypedefNameDecl(TypedefNameDecl *TD) {
    409   RedeclarableResult Redecl = VisitRedeclarable(TD);
    410   VisitTypeDecl(TD);
    411 
    412   TD->setTypeSourceInfo(GetTypeSourceInfo(Record, Idx));
    413   mergeRedeclarable(TD, Redecl);
    414 }
    415 
    416 void ASTDeclReader::VisitTypedefDecl(TypedefDecl *TD) {
    417   VisitTypedefNameDecl(TD);
    418 }
    419 
    420 void ASTDeclReader::VisitTypeAliasDecl(TypeAliasDecl *TD) {
    421   VisitTypedefNameDecl(TD);
    422 }
    423 
    424 void ASTDeclReader::VisitTagDecl(TagDecl *TD) {
    425   RedeclarableResult Redecl = VisitRedeclarable(TD);
    426   VisitTypeDecl(TD);
    427 
    428   TD->IdentifierNamespace = Record[Idx++];
    429   TD->setTagKind((TagDecl::TagKind)Record[Idx++]);
    430   TD->setCompleteDefinition(Record[Idx++]);
    431   TD->setEmbeddedInDeclarator(Record[Idx++]);
    432   TD->setFreeStanding(Record[Idx++]);
    433   TD->setRBraceLoc(ReadSourceLocation(Record, Idx));
    434 
    435   if (Record[Idx++]) { // hasExtInfo
    436     TagDecl::ExtInfo *Info = new (Reader.getContext()) TagDecl::ExtInfo();
    437     ReadQualifierInfo(*Info, Record, Idx);
    438     TD->TypedefNameDeclOrQualifier = Info;
    439   } else
    440     TD->setTypedefNameForAnonDecl(ReadDeclAs<TypedefNameDecl>(Record, Idx));
    441 
    442   mergeRedeclarable(TD, Redecl);
    443 }
    444 
    445 void ASTDeclReader::VisitEnumDecl(EnumDecl *ED) {
    446   VisitTagDecl(ED);
    447   if (TypeSourceInfo *TI = Reader.GetTypeSourceInfo(F, Record, Idx))
    448     ED->setIntegerTypeSourceInfo(TI);
    449   else
    450     ED->setIntegerType(Reader.readType(F, Record, Idx));
    451   ED->setPromotionType(Reader.readType(F, Record, Idx));
    452   ED->setNumPositiveBits(Record[Idx++]);
    453   ED->setNumNegativeBits(Record[Idx++]);
    454   ED->IsScoped = Record[Idx++];
    455   ED->IsScopedUsingClassTag = Record[Idx++];
    456   ED->IsFixed = Record[Idx++];
    457 
    458   if (EnumDecl *InstED = ReadDeclAs<EnumDecl>(Record, Idx)) {
    459     TemplateSpecializationKind TSK = (TemplateSpecializationKind)Record[Idx++];
    460     SourceLocation POI = ReadSourceLocation(Record, Idx);
    461     ED->setInstantiationOfMemberEnum(Reader.getContext(), InstED, TSK);
    462     ED->getMemberSpecializationInfo()->setPointOfInstantiation(POI);
    463   }
    464 }
    465 
    466 void ASTDeclReader::VisitRecordDecl(RecordDecl *RD) {
    467   VisitTagDecl(RD);
    468   RD->setHasFlexibleArrayMember(Record[Idx++]);
    469   RD->setAnonymousStructOrUnion(Record[Idx++]);
    470   RD->setHasObjectMember(Record[Idx++]);
    471   RD->setHasVolatileMember(Record[Idx++]);
    472 }
    473 
    474 void ASTDeclReader::VisitValueDecl(ValueDecl *VD) {
    475   VisitNamedDecl(VD);
    476   VD->setType(Reader.readType(F, Record, Idx));
    477 }
    478 
    479 void ASTDeclReader::VisitEnumConstantDecl(EnumConstantDecl *ECD) {
    480   VisitValueDecl(ECD);
    481   if (Record[Idx++])
    482     ECD->setInitExpr(Reader.ReadExpr(F));
    483   ECD->setInitVal(Reader.ReadAPSInt(Record, Idx));
    484 }
    485 
    486 void ASTDeclReader::VisitDeclaratorDecl(DeclaratorDecl *DD) {
    487   VisitValueDecl(DD);
    488   DD->setInnerLocStart(ReadSourceLocation(Record, Idx));
    489   if (Record[Idx++]) { // hasExtInfo
    490     DeclaratorDecl::ExtInfo *Info
    491         = new (Reader.getContext()) DeclaratorDecl::ExtInfo();
    492     ReadQualifierInfo(*Info, Record, Idx);
    493     DD->DeclInfo = Info;
    494   }
    495 }
    496 
    497 void ASTDeclReader::VisitFunctionDecl(FunctionDecl *FD) {
    498   RedeclarableResult Redecl = VisitRedeclarable(FD);
    499   VisitDeclaratorDecl(FD);
    500 
    501   ReadDeclarationNameLoc(FD->DNLoc, FD->getDeclName(), Record, Idx);
    502   FD->IdentifierNamespace = Record[Idx++];
    503 
    504   // FunctionDecl's body is handled last at ASTDeclReader::Visit,
    505   // after everything else is read.
    506 
    507   FD->SClass = (StorageClass)Record[Idx++];
    508   FD->SClassAsWritten = (StorageClass)Record[Idx++];
    509   FD->IsInline = Record[Idx++];
    510   FD->IsInlineSpecified = Record[Idx++];
    511   FD->IsVirtualAsWritten = Record[Idx++];
    512   FD->IsPure = Record[Idx++];
    513   FD->HasInheritedPrototype = Record[Idx++];
    514   FD->HasWrittenPrototype = Record[Idx++];
    515   FD->IsDeleted = Record[Idx++];
    516   FD->IsTrivial = Record[Idx++];
    517   FD->IsDefaulted = Record[Idx++];
    518   FD->IsExplicitlyDefaulted = Record[Idx++];
    519   FD->HasImplicitReturnZero = Record[Idx++];
    520   FD->IsConstexpr = Record[Idx++];
    521   FD->HasSkippedBody = Record[Idx++];
    522   FD->HasCachedLinkage = true;
    523   FD->CachedLinkage = Record[Idx++];
    524   FD->EndRangeLoc = ReadSourceLocation(Record, Idx);
    525 
    526   switch ((FunctionDecl::TemplatedKind)Record[Idx++]) {
    527   case FunctionDecl::TK_NonTemplate:
    528     mergeRedeclarable(FD, Redecl);
    529     break;
    530   case FunctionDecl::TK_FunctionTemplate:
    531     FD->setDescribedFunctionTemplate(ReadDeclAs<FunctionTemplateDecl>(Record,
    532                                                                       Idx));
    533     break;
    534   case FunctionDecl::TK_MemberSpecialization: {
    535     FunctionDecl *InstFD = ReadDeclAs<FunctionDecl>(Record, Idx);
    536     TemplateSpecializationKind TSK = (TemplateSpecializationKind)Record[Idx++];
    537     SourceLocation POI = ReadSourceLocation(Record, Idx);
    538     FD->setInstantiationOfMemberFunction(Reader.getContext(), InstFD, TSK);
    539     FD->getMemberSpecializationInfo()->setPointOfInstantiation(POI);
    540     break;
    541   }
    542   case FunctionDecl::TK_FunctionTemplateSpecialization: {
    543     FunctionTemplateDecl *Template = ReadDeclAs<FunctionTemplateDecl>(Record,
    544                                                                       Idx);
    545     TemplateSpecializationKind TSK = (TemplateSpecializationKind)Record[Idx++];
    546 
    547     // Template arguments.
    548     SmallVector<TemplateArgument, 8> TemplArgs;
    549     Reader.ReadTemplateArgumentList(TemplArgs, F, Record, Idx);
    550 
    551     // Template args as written.
    552     SmallVector<TemplateArgumentLoc, 8> TemplArgLocs;
    553     SourceLocation LAngleLoc, RAngleLoc;
    554     bool HasTemplateArgumentsAsWritten = Record[Idx++];
    555     if (HasTemplateArgumentsAsWritten) {
    556       unsigned NumTemplateArgLocs = Record[Idx++];
    557       TemplArgLocs.reserve(NumTemplateArgLocs);
    558       for (unsigned i=0; i != NumTemplateArgLocs; ++i)
    559         TemplArgLocs.push_back(
    560             Reader.ReadTemplateArgumentLoc(F, Record, Idx));
    561 
    562       LAngleLoc = ReadSourceLocation(Record, Idx);
    563       RAngleLoc = ReadSourceLocation(Record, Idx);
    564     }
    565 
    566     SourceLocation POI = ReadSourceLocation(Record, Idx);
    567 
    568     ASTContext &C = Reader.getContext();
    569     TemplateArgumentList *TemplArgList
    570       = TemplateArgumentList::CreateCopy(C, TemplArgs.data(), TemplArgs.size());
    571     TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
    572     for (unsigned i=0, e = TemplArgLocs.size(); i != e; ++i)
    573       TemplArgsInfo.addArgument(TemplArgLocs[i]);
    574     FunctionTemplateSpecializationInfo *FTInfo
    575         = FunctionTemplateSpecializationInfo::Create(C, FD, Template, TSK,
    576                                                      TemplArgList,
    577                              HasTemplateArgumentsAsWritten ? &TemplArgsInfo : 0,
    578                                                      POI);
    579     FD->TemplateOrSpecialization = FTInfo;
    580 
    581     if (FD->isCanonicalDecl()) { // if canonical add to template's set.
    582       // The template that contains the specializations set. It's not safe to
    583       // use getCanonicalDecl on Template since it may still be initializing.
    584       FunctionTemplateDecl *CanonTemplate
    585         = ReadDeclAs<FunctionTemplateDecl>(Record, Idx);
    586       // Get the InsertPos by FindNodeOrInsertPos() instead of calling
    587       // InsertNode(FTInfo) directly to avoid the getASTContext() call in
    588       // FunctionTemplateSpecializationInfo's Profile().
    589       // We avoid getASTContext because a decl in the parent hierarchy may
    590       // be initializing.
    591       llvm::FoldingSetNodeID ID;
    592       FunctionTemplateSpecializationInfo::Profile(ID, TemplArgs.data(),
    593                                                   TemplArgs.size(), C);
    594       void *InsertPos = 0;
    595       CanonTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
    596       if (InsertPos)
    597         CanonTemplate->getSpecializations().InsertNode(FTInfo, InsertPos);
    598       else
    599         assert(0 && "Another specialization already inserted!");
    600     }
    601     break;
    602   }
    603   case FunctionDecl::TK_DependentFunctionTemplateSpecialization: {
    604     // Templates.
    605     UnresolvedSet<8> TemplDecls;
    606     unsigned NumTemplates = Record[Idx++];
    607     while (NumTemplates--)
    608       TemplDecls.addDecl(ReadDeclAs<NamedDecl>(Record, Idx));
    609 
    610     // Templates args.
    611     TemplateArgumentListInfo TemplArgs;
    612     unsigned NumArgs = Record[Idx++];
    613     while (NumArgs--)
    614       TemplArgs.addArgument(Reader.ReadTemplateArgumentLoc(F, Record, Idx));
    615     TemplArgs.setLAngleLoc(ReadSourceLocation(Record, Idx));
    616     TemplArgs.setRAngleLoc(ReadSourceLocation(Record, Idx));
    617 
    618     FD->setDependentTemplateSpecialization(Reader.getContext(),
    619                                            TemplDecls, TemplArgs);
    620     break;
    621   }
    622   }
    623 
    624   // Read in the parameters.
    625   unsigned NumParams = Record[Idx++];
    626   SmallVector<ParmVarDecl *, 16> Params;
    627   Params.reserve(NumParams);
    628   for (unsigned I = 0; I != NumParams; ++I)
    629     Params.push_back(ReadDeclAs<ParmVarDecl>(Record, Idx));
    630   FD->setParams(Reader.getContext(), Params);
    631 }
    632 
    633 void ASTDeclReader::VisitObjCMethodDecl(ObjCMethodDecl *MD) {
    634   VisitNamedDecl(MD);
    635   if (Record[Idx++]) {
    636     // Load the body on-demand. Most clients won't care, because method
    637     // definitions rarely show up in headers.
    638     Reader.PendingBodies[MD] = GetCurrentCursorOffset();
    639     HasPendingBody = true;
    640     MD->setSelfDecl(ReadDeclAs<ImplicitParamDecl>(Record, Idx));
    641     MD->setCmdDecl(ReadDeclAs<ImplicitParamDecl>(Record, Idx));
    642   }
    643   MD->setInstanceMethod(Record[Idx++]);
    644   MD->setVariadic(Record[Idx++]);
    645   MD->setPropertyAccessor(Record[Idx++]);
    646   MD->setDefined(Record[Idx++]);
    647   MD->IsOverriding = Record[Idx++];
    648   MD->HasSkippedBody = Record[Idx++];
    649 
    650   MD->IsRedeclaration = Record[Idx++];
    651   MD->HasRedeclaration = Record[Idx++];
    652   if (MD->HasRedeclaration)
    653     Reader.getContext().setObjCMethodRedeclaration(MD,
    654                                        ReadDeclAs<ObjCMethodDecl>(Record, Idx));
    655 
    656   MD->setDeclImplementation((ObjCMethodDecl::ImplementationControl)Record[Idx++]);
    657   MD->setObjCDeclQualifier((Decl::ObjCDeclQualifier)Record[Idx++]);
    658   MD->SetRelatedResultType(Record[Idx++]);
    659   MD->setResultType(Reader.readType(F, Record, Idx));
    660   MD->setResultTypeSourceInfo(GetTypeSourceInfo(Record, Idx));
    661   MD->DeclEndLoc = ReadSourceLocation(Record, Idx);
    662   unsigned NumParams = Record[Idx++];
    663   SmallVector<ParmVarDecl *, 16> Params;
    664   Params.reserve(NumParams);
    665   for (unsigned I = 0; I != NumParams; ++I)
    666     Params.push_back(ReadDeclAs<ParmVarDecl>(Record, Idx));
    667 
    668   MD->SelLocsKind = Record[Idx++];
    669   unsigned NumStoredSelLocs = Record[Idx++];
    670   SmallVector<SourceLocation, 16> SelLocs;
    671   SelLocs.reserve(NumStoredSelLocs);
    672   for (unsigned i = 0; i != NumStoredSelLocs; ++i)
    673     SelLocs.push_back(ReadSourceLocation(Record, Idx));
    674 
    675   MD->setParamsAndSelLocs(Reader.getContext(), Params, SelLocs);
    676 }
    677 
    678 void ASTDeclReader::VisitObjCContainerDecl(ObjCContainerDecl *CD) {
    679   VisitNamedDecl(CD);
    680   CD->setAtStartLoc(ReadSourceLocation(Record, Idx));
    681   CD->setAtEndRange(ReadSourceRange(Record, Idx));
    682 }
    683 
    684 void ASTDeclReader::VisitObjCInterfaceDecl(ObjCInterfaceDecl *ID) {
    685   RedeclarableResult Redecl = VisitRedeclarable(ID);
    686   VisitObjCContainerDecl(ID);
    687   TypeIDForTypeDecl = Reader.getGlobalTypeID(F, Record[Idx++]);
    688   mergeRedeclarable(ID, Redecl);
    689 
    690   if (Record[Idx++]) {
    691     // Read the definition.
    692     ID->allocateDefinitionData();
    693 
    694     // Set the definition data of the canonical declaration, so other
    695     // redeclarations will see it.
    696     ID->getCanonicalDecl()->Data = ID->Data;
    697 
    698     ObjCInterfaceDecl::DefinitionData &Data = ID->data();
    699 
    700     // Read the superclass.
    701     Data.SuperClass = ReadDeclAs<ObjCInterfaceDecl>(Record, Idx);
    702     Data.SuperClassLoc = ReadSourceLocation(Record, Idx);
    703 
    704     Data.EndLoc = ReadSourceLocation(Record, Idx);
    705 
    706     // Read the directly referenced protocols and their SourceLocations.
    707     unsigned NumProtocols = Record[Idx++];
    708     SmallVector<ObjCProtocolDecl *, 16> Protocols;
    709     Protocols.reserve(NumProtocols);
    710     for (unsigned I = 0; I != NumProtocols; ++I)
    711       Protocols.push_back(ReadDeclAs<ObjCProtocolDecl>(Record, Idx));
    712     SmallVector<SourceLocation, 16> ProtoLocs;
    713     ProtoLocs.reserve(NumProtocols);
    714     for (unsigned I = 0; I != NumProtocols; ++I)
    715       ProtoLocs.push_back(ReadSourceLocation(Record, Idx));
    716     ID->setProtocolList(Protocols.data(), NumProtocols, ProtoLocs.data(),
    717                         Reader.getContext());
    718 
    719     // Read the transitive closure of protocols referenced by this class.
    720     NumProtocols = Record[Idx++];
    721     Protocols.clear();
    722     Protocols.reserve(NumProtocols);
    723     for (unsigned I = 0; I != NumProtocols; ++I)
    724       Protocols.push_back(ReadDeclAs<ObjCProtocolDecl>(Record, Idx));
    725     ID->data().AllReferencedProtocols.set(Protocols.data(), NumProtocols,
    726                                           Reader.getContext());
    727 
    728     // We will rebuild this list lazily.
    729     ID->setIvarList(0);
    730 
    731     // Note that we have deserialized a definition.
    732     Reader.PendingDefinitions.insert(ID);
    733 
    734     // Note that we've loaded this Objective-C class.
    735     Reader.ObjCClassesLoaded.push_back(ID);
    736   } else {
    737     ID->Data = ID->getCanonicalDecl()->Data;
    738   }
    739 }
    740 
    741 void ASTDeclReader::VisitObjCIvarDecl(ObjCIvarDecl *IVD) {
    742   VisitFieldDecl(IVD);
    743   IVD->setAccessControl((ObjCIvarDecl::AccessControl)Record[Idx++]);
    744   // This field will be built lazily.
    745   IVD->setNextIvar(0);
    746   bool synth = Record[Idx++];
    747   IVD->setSynthesize(synth);
    748 }
    749 
    750 void ASTDeclReader::VisitObjCProtocolDecl(ObjCProtocolDecl *PD) {
    751   RedeclarableResult Redecl = VisitRedeclarable(PD);
    752   VisitObjCContainerDecl(PD);
    753   mergeRedeclarable(PD, Redecl);
    754 
    755   if (Record[Idx++]) {
    756     // Read the definition.
    757     PD->allocateDefinitionData();
    758 
    759     // Set the definition data of the canonical declaration, so other
    760     // redeclarations will see it.
    761     PD->getCanonicalDecl()->Data = PD->Data;
    762 
    763     unsigned NumProtoRefs = Record[Idx++];
    764     SmallVector<ObjCProtocolDecl *, 16> ProtoRefs;
    765     ProtoRefs.reserve(NumProtoRefs);
    766     for (unsigned I = 0; I != NumProtoRefs; ++I)
    767       ProtoRefs.push_back(ReadDeclAs<ObjCProtocolDecl>(Record, Idx));
    768     SmallVector<SourceLocation, 16> ProtoLocs;
    769     ProtoLocs.reserve(NumProtoRefs);
    770     for (unsigned I = 0; I != NumProtoRefs; ++I)
    771       ProtoLocs.push_back(ReadSourceLocation(Record, Idx));
    772     PD->setProtocolList(ProtoRefs.data(), NumProtoRefs, ProtoLocs.data(),
    773                         Reader.getContext());
    774 
    775     // Note that we have deserialized a definition.
    776     Reader.PendingDefinitions.insert(PD);
    777   } else {
    778     PD->Data = PD->getCanonicalDecl()->Data;
    779   }
    780 }
    781 
    782 void ASTDeclReader::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *FD) {
    783   VisitFieldDecl(FD);
    784 }
    785 
    786 void ASTDeclReader::VisitObjCCategoryDecl(ObjCCategoryDecl *CD) {
    787   VisitObjCContainerDecl(CD);
    788   CD->setCategoryNameLoc(ReadSourceLocation(Record, Idx));
    789   CD->setIvarLBraceLoc(ReadSourceLocation(Record, Idx));
    790   CD->setIvarRBraceLoc(ReadSourceLocation(Record, Idx));
    791 
    792   // Note that this category has been deserialized. We do this before
    793   // deserializing the interface declaration, so that it will consider this
    794   /// category.
    795   Reader.CategoriesDeserialized.insert(CD);
    796 
    797   CD->ClassInterface = ReadDeclAs<ObjCInterfaceDecl>(Record, Idx);
    798   unsigned NumProtoRefs = Record[Idx++];
    799   SmallVector<ObjCProtocolDecl *, 16> ProtoRefs;
    800   ProtoRefs.reserve(NumProtoRefs);
    801   for (unsigned I = 0; I != NumProtoRefs; ++I)
    802     ProtoRefs.push_back(ReadDeclAs<ObjCProtocolDecl>(Record, Idx));
    803   SmallVector<SourceLocation, 16> ProtoLocs;
    804   ProtoLocs.reserve(NumProtoRefs);
    805   for (unsigned I = 0; I != NumProtoRefs; ++I)
    806     ProtoLocs.push_back(ReadSourceLocation(Record, Idx));
    807   CD->setProtocolList(ProtoRefs.data(), NumProtoRefs, ProtoLocs.data(),
    808                       Reader.getContext());
    809 }
    810 
    811 void ASTDeclReader::VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *CAD) {
    812   VisitNamedDecl(CAD);
    813   CAD->setClassInterface(ReadDeclAs<ObjCInterfaceDecl>(Record, Idx));
    814 }
    815 
    816 void ASTDeclReader::VisitObjCPropertyDecl(ObjCPropertyDecl *D) {
    817   VisitNamedDecl(D);
    818   D->setAtLoc(ReadSourceLocation(Record, Idx));
    819   D->setLParenLoc(ReadSourceLocation(Record, Idx));
    820   D->setType(GetTypeSourceInfo(Record, Idx));
    821   // FIXME: stable encoding
    822   D->setPropertyAttributes(
    823                       (ObjCPropertyDecl::PropertyAttributeKind)Record[Idx++]);
    824   D->setPropertyAttributesAsWritten(
    825                       (ObjCPropertyDecl::PropertyAttributeKind)Record[Idx++]);
    826   // FIXME: stable encoding
    827   D->setPropertyImplementation(
    828                             (ObjCPropertyDecl::PropertyControl)Record[Idx++]);
    829   D->setGetterName(Reader.ReadDeclarationName(F,Record, Idx).getObjCSelector());
    830   D->setSetterName(Reader.ReadDeclarationName(F,Record, Idx).getObjCSelector());
    831   D->setGetterMethodDecl(ReadDeclAs<ObjCMethodDecl>(Record, Idx));
    832   D->setSetterMethodDecl(ReadDeclAs<ObjCMethodDecl>(Record, Idx));
    833   D->setPropertyIvarDecl(ReadDeclAs<ObjCIvarDecl>(Record, Idx));
    834 }
    835 
    836 void ASTDeclReader::VisitObjCImplDecl(ObjCImplDecl *D) {
    837   VisitObjCContainerDecl(D);
    838   D->setClassInterface(ReadDeclAs<ObjCInterfaceDecl>(Record, Idx));
    839 }
    840 
    841 void ASTDeclReader::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
    842   VisitObjCImplDecl(D);
    843   D->setIdentifier(Reader.GetIdentifierInfo(F, Record, Idx));
    844   D->CategoryNameLoc = ReadSourceLocation(Record, Idx);
    845 }
    846 
    847 void ASTDeclReader::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
    848   VisitObjCImplDecl(D);
    849   D->setSuperClass(ReadDeclAs<ObjCInterfaceDecl>(Record, Idx));
    850   D->setIvarLBraceLoc(ReadSourceLocation(Record, Idx));
    851   D->setIvarRBraceLoc(ReadSourceLocation(Record, Idx));
    852   D->setHasNonZeroConstructors(Record[Idx++]);
    853   D->setHasDestructors(Record[Idx++]);
    854   llvm::tie(D->IvarInitializers, D->NumIvarInitializers)
    855       = Reader.ReadCXXCtorInitializers(F, Record, Idx);
    856 }
    857 
    858 
    859 void ASTDeclReader::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) {
    860   VisitDecl(D);
    861   D->setAtLoc(ReadSourceLocation(Record, Idx));
    862   D->setPropertyDecl(ReadDeclAs<ObjCPropertyDecl>(Record, Idx));
    863   D->PropertyIvarDecl = ReadDeclAs<ObjCIvarDecl>(Record, Idx);
    864   D->IvarLoc = ReadSourceLocation(Record, Idx);
    865   D->setGetterCXXConstructor(Reader.ReadExpr(F));
    866   D->setSetterCXXAssignment(Reader.ReadExpr(F));
    867 }
    868 
    869 void ASTDeclReader::VisitFieldDecl(FieldDecl *FD) {
    870   VisitDeclaratorDecl(FD);
    871   FD->Mutable = Record[Idx++];
    872   if (int BitWidthOrInitializer = Record[Idx++]) {
    873     FD->InitializerOrBitWidth.setInt(BitWidthOrInitializer - 1);
    874     FD->InitializerOrBitWidth.setPointer(Reader.ReadExpr(F));
    875   }
    876   if (!FD->getDeclName()) {
    877     if (FieldDecl *Tmpl = ReadDeclAs<FieldDecl>(Record, Idx))
    878       Reader.getContext().setInstantiatedFromUnnamedFieldDecl(FD, Tmpl);
    879   }
    880 }
    881 
    882 void ASTDeclReader::VisitIndirectFieldDecl(IndirectFieldDecl *FD) {
    883   VisitValueDecl(FD);
    884 
    885   FD->ChainingSize = Record[Idx++];
    886   assert(FD->ChainingSize >= 2 && "Anonymous chaining must be >= 2");
    887   FD->Chaining = new (Reader.getContext())NamedDecl*[FD->ChainingSize];
    888 
    889   for (unsigned I = 0; I != FD->ChainingSize; ++I)
    890     FD->Chaining[I] = ReadDeclAs<NamedDecl>(Record, Idx);
    891 }
    892 
    893 void ASTDeclReader::VisitVarDecl(VarDecl *VD) {
    894   RedeclarableResult Redecl = VisitRedeclarable(VD);
    895   VisitDeclaratorDecl(VD);
    896 
    897   VD->VarDeclBits.SClass = (StorageClass)Record[Idx++];
    898   VD->VarDeclBits.SClassAsWritten = (StorageClass)Record[Idx++];
    899   VD->VarDeclBits.ThreadSpecified = Record[Idx++];
    900   VD->VarDeclBits.InitStyle = Record[Idx++];
    901   VD->VarDeclBits.ExceptionVar = Record[Idx++];
    902   VD->VarDeclBits.NRVOVariable = Record[Idx++];
    903   VD->VarDeclBits.CXXForRangeDecl = Record[Idx++];
    904   VD->VarDeclBits.ARCPseudoStrong = Record[Idx++];
    905   VD->VarDeclBits.IsConstexpr = Record[Idx++];
    906   VD->HasCachedLinkage = true;
    907   VD->CachedLinkage = Record[Idx++];
    908 
    909   // Only true variables (not parameters or implicit parameters) can be merged.
    910   if (VD->getKind() == Decl::Var)
    911     mergeRedeclarable(VD, Redecl);
    912 
    913   if (uint64_t Val = Record[Idx++]) {
    914     VD->setInit(Reader.ReadExpr(F));
    915     if (Val > 1) {
    916       EvaluatedStmt *Eval = VD->ensureEvaluatedStmt();
    917       Eval->CheckedICE = true;
    918       Eval->IsICE = Val == 3;
    919     }
    920   }
    921 
    922   if (Record[Idx++]) { // HasMemberSpecializationInfo.
    923     VarDecl *Tmpl = ReadDeclAs<VarDecl>(Record, Idx);
    924     TemplateSpecializationKind TSK = (TemplateSpecializationKind)Record[Idx++];
    925     SourceLocation POI = ReadSourceLocation(Record, Idx);
    926     Reader.getContext().setInstantiatedFromStaticDataMember(VD, Tmpl, TSK,POI);
    927   }
    928 }
    929 
    930 void ASTDeclReader::VisitImplicitParamDecl(ImplicitParamDecl *PD) {
    931   VisitVarDecl(PD);
    932 }
    933 
    934 void ASTDeclReader::VisitParmVarDecl(ParmVarDecl *PD) {
    935   VisitVarDecl(PD);
    936   unsigned isObjCMethodParam = Record[Idx++];
    937   unsigned scopeDepth = Record[Idx++];
    938   unsigned scopeIndex = Record[Idx++];
    939   unsigned declQualifier = Record[Idx++];
    940   if (isObjCMethodParam) {
    941     assert(scopeDepth == 0);
    942     PD->setObjCMethodScopeInfo(scopeIndex);
    943     PD->ParmVarDeclBits.ScopeDepthOrObjCQuals = declQualifier;
    944   } else {
    945     PD->setScopeInfo(scopeDepth, scopeIndex);
    946   }
    947   PD->ParmVarDeclBits.IsKNRPromoted = Record[Idx++];
    948   PD->ParmVarDeclBits.HasInheritedDefaultArg = Record[Idx++];
    949   if (Record[Idx++]) // hasUninstantiatedDefaultArg.
    950     PD->setUninstantiatedDefaultArg(Reader.ReadExpr(F));
    951 }
    952 
    953 void ASTDeclReader::VisitFileScopeAsmDecl(FileScopeAsmDecl *AD) {
    954   VisitDecl(AD);
    955   AD->setAsmString(cast<StringLiteral>(Reader.ReadExpr(F)));
    956   AD->setRParenLoc(ReadSourceLocation(Record, Idx));
    957 }
    958 
    959 void ASTDeclReader::VisitBlockDecl(BlockDecl *BD) {
    960   VisitDecl(BD);
    961   BD->setBody(cast_or_null<CompoundStmt>(Reader.ReadStmt(F)));
    962   BD->setSignatureAsWritten(GetTypeSourceInfo(Record, Idx));
    963   unsigned NumParams = Record[Idx++];
    964   SmallVector<ParmVarDecl *, 16> Params;
    965   Params.reserve(NumParams);
    966   for (unsigned I = 0; I != NumParams; ++I)
    967     Params.push_back(ReadDeclAs<ParmVarDecl>(Record, Idx));
    968   BD->setParams(Params);
    969 
    970   BD->setIsVariadic(Record[Idx++]);
    971   BD->setBlockMissingReturnType(Record[Idx++]);
    972   BD->setIsConversionFromLambda(Record[Idx++]);
    973 
    974   bool capturesCXXThis = Record[Idx++];
    975   unsigned numCaptures = Record[Idx++];
    976   SmallVector<BlockDecl::Capture, 16> captures;
    977   captures.reserve(numCaptures);
    978   for (unsigned i = 0; i != numCaptures; ++i) {
    979     VarDecl *decl = ReadDeclAs<VarDecl>(Record, Idx);
    980     unsigned flags = Record[Idx++];
    981     bool byRef = (flags & 1);
    982     bool nested = (flags & 2);
    983     Expr *copyExpr = ((flags & 4) ? Reader.ReadExpr(F) : 0);
    984 
    985     captures.push_back(BlockDecl::Capture(decl, byRef, nested, copyExpr));
    986   }
    987   BD->setCaptures(Reader.getContext(), captures.begin(),
    988                   captures.end(), capturesCXXThis);
    989 }
    990 
    991 void ASTDeclReader::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
    992   VisitDecl(D);
    993   D->setLanguage((LinkageSpecDecl::LanguageIDs)Record[Idx++]);
    994   D->setExternLoc(ReadSourceLocation(Record, Idx));
    995   D->setRBraceLoc(ReadSourceLocation(Record, Idx));
    996 }
    997 
    998 void ASTDeclReader::VisitLabelDecl(LabelDecl *D) {
    999   VisitNamedDecl(D);
   1000   D->setLocStart(ReadSourceLocation(Record, Idx));
   1001 }
   1002 
   1003 
   1004 void ASTDeclReader::VisitNamespaceDecl(NamespaceDecl *D) {
   1005   RedeclarableResult Redecl = VisitRedeclarable(D);
   1006   VisitNamedDecl(D);
   1007   D->setInline(Record[Idx++]);
   1008   D->LocStart = ReadSourceLocation(Record, Idx);
   1009   D->RBraceLoc = ReadSourceLocation(Record, Idx);
   1010   mergeRedeclarable(D, Redecl);
   1011 
   1012   if (Redecl.getFirstID() == ThisDeclID) {
   1013     // Each module has its own anonymous namespace, which is disjoint from
   1014     // any other module's anonymous namespaces, so don't attach the anonymous
   1015     // namespace at all.
   1016     NamespaceDecl *Anon = ReadDeclAs<NamespaceDecl>(Record, Idx);
   1017     if (F.Kind != MK_Module)
   1018       D->setAnonymousNamespace(Anon);
   1019   } else {
   1020     // Link this namespace back to the first declaration, which has already
   1021     // been deserialized.
   1022     D->AnonOrFirstNamespaceAndInline.setPointer(D->getFirstDeclaration());
   1023   }
   1024 }
   1025 
   1026 void ASTDeclReader::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
   1027   VisitNamedDecl(D);
   1028   D->NamespaceLoc = ReadSourceLocation(Record, Idx);
   1029   D->IdentLoc = ReadSourceLocation(Record, Idx);
   1030   D->QualifierLoc = Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
   1031   D->Namespace = ReadDeclAs<NamedDecl>(Record, Idx);
   1032 }
   1033 
   1034 void ASTDeclReader::VisitUsingDecl(UsingDecl *D) {
   1035   VisitNamedDecl(D);
   1036   D->setUsingLocation(ReadSourceLocation(Record, Idx));
   1037   D->QualifierLoc = Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
   1038   ReadDeclarationNameLoc(D->DNLoc, D->getDeclName(), Record, Idx);
   1039   D->FirstUsingShadow.setPointer(ReadDeclAs<UsingShadowDecl>(Record, Idx));
   1040   D->setTypeName(Record[Idx++]);
   1041   if (NamedDecl *Pattern = ReadDeclAs<NamedDecl>(Record, Idx))
   1042     Reader.getContext().setInstantiatedFromUsingDecl(D, Pattern);
   1043 }
   1044 
   1045 void ASTDeclReader::VisitUsingShadowDecl(UsingShadowDecl *D) {
   1046   VisitNamedDecl(D);
   1047   D->setTargetDecl(ReadDeclAs<NamedDecl>(Record, Idx));
   1048   D->UsingOrNextShadow = ReadDeclAs<NamedDecl>(Record, Idx);
   1049   UsingShadowDecl *Pattern = ReadDeclAs<UsingShadowDecl>(Record, Idx);
   1050   if (Pattern)
   1051     Reader.getContext().setInstantiatedFromUsingShadowDecl(D, Pattern);
   1052 }
   1053 
   1054 void ASTDeclReader::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
   1055   VisitNamedDecl(D);
   1056   D->UsingLoc = ReadSourceLocation(Record, Idx);
   1057   D->NamespaceLoc = ReadSourceLocation(Record, Idx);
   1058   D->QualifierLoc = Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
   1059   D->NominatedNamespace = ReadDeclAs<NamedDecl>(Record, Idx);
   1060   D->CommonAncestor = ReadDeclAs<DeclContext>(Record, Idx);
   1061 }
   1062 
   1063 void ASTDeclReader::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
   1064   VisitValueDecl(D);
   1065   D->setUsingLoc(ReadSourceLocation(Record, Idx));
   1066   D->QualifierLoc = Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
   1067   ReadDeclarationNameLoc(D->DNLoc, D->getDeclName(), Record, Idx);
   1068 }
   1069 
   1070 void ASTDeclReader::VisitUnresolvedUsingTypenameDecl(
   1071                                                UnresolvedUsingTypenameDecl *D) {
   1072   VisitTypeDecl(D);
   1073   D->TypenameLocation = ReadSourceLocation(Record, Idx);
   1074   D->QualifierLoc = Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
   1075 }
   1076 
   1077 void ASTDeclReader::ReadCXXDefinitionData(
   1078                                    struct CXXRecordDecl::DefinitionData &Data,
   1079                                    const RecordData &Record, unsigned &Idx) {
   1080   // Note: the caller has deserialized the IsLambda bit already.
   1081   Data.UserDeclaredConstructor = Record[Idx++];
   1082   Data.UserDeclaredSpecialMembers = Record[Idx++];
   1083   Data.Aggregate = Record[Idx++];
   1084   Data.PlainOldData = Record[Idx++];
   1085   Data.Empty = Record[Idx++];
   1086   Data.Polymorphic = Record[Idx++];
   1087   Data.Abstract = Record[Idx++];
   1088   Data.IsStandardLayout = Record[Idx++];
   1089   Data.HasNoNonEmptyBases = Record[Idx++];
   1090   Data.HasPrivateFields = Record[Idx++];
   1091   Data.HasProtectedFields = Record[Idx++];
   1092   Data.HasPublicFields = Record[Idx++];
   1093   Data.HasMutableFields = Record[Idx++];
   1094   Data.HasOnlyCMembers = Record[Idx++];
   1095   Data.HasInClassInitializer = Record[Idx++];
   1096   Data.HasUninitializedReferenceMember = Record[Idx++];
   1097   Data.NeedOverloadResolutionForMoveConstructor = Record[Idx++];
   1098   Data.NeedOverloadResolutionForMoveAssignment = Record[Idx++];
   1099   Data.NeedOverloadResolutionForDestructor = Record[Idx++];
   1100   Data.DefaultedMoveConstructorIsDeleted = Record[Idx++];
   1101   Data.DefaultedMoveAssignmentIsDeleted = Record[Idx++];
   1102   Data.DefaultedDestructorIsDeleted = Record[Idx++];
   1103   Data.HasTrivialSpecialMembers = Record[Idx++];
   1104   Data.HasIrrelevantDestructor = Record[Idx++];
   1105   Data.HasConstexprNonCopyMoveConstructor = Record[Idx++];
   1106   Data.DefaultedDefaultConstructorIsConstexpr = Record[Idx++];
   1107   Data.HasConstexprDefaultConstructor = Record[Idx++];
   1108   Data.HasNonLiteralTypeFieldsOrBases = Record[Idx++];
   1109   Data.ComputedVisibleConversions = Record[Idx++];
   1110   Data.UserProvidedDefaultConstructor = Record[Idx++];
   1111   Data.DeclaredSpecialMembers = Record[Idx++];
   1112   Data.ImplicitCopyConstructorHasConstParam = Record[Idx++];
   1113   Data.ImplicitCopyAssignmentHasConstParam = Record[Idx++];
   1114   Data.HasDeclaredCopyConstructorWithConstParam = Record[Idx++];
   1115   Data.HasDeclaredCopyAssignmentWithConstParam = Record[Idx++];
   1116   Data.FailedImplicitMoveConstructor = Record[Idx++];
   1117   Data.FailedImplicitMoveAssignment = Record[Idx++];
   1118 
   1119   Data.NumBases = Record[Idx++];
   1120   if (Data.NumBases)
   1121     Data.Bases = Reader.readCXXBaseSpecifiers(F, Record, Idx);
   1122   Data.NumVBases = Record[Idx++];
   1123   if (Data.NumVBases)
   1124     Data.VBases = Reader.readCXXBaseSpecifiers(F, Record, Idx);
   1125 
   1126   Reader.ReadUnresolvedSet(F, Data.Conversions, Record, Idx);
   1127   Reader.ReadUnresolvedSet(F, Data.VisibleConversions, Record, Idx);
   1128   assert(Data.Definition && "Data.Definition should be already set!");
   1129   Data.FirstFriend = ReadDeclAs<FriendDecl>(Record, Idx);
   1130 
   1131   if (Data.IsLambda) {
   1132     typedef LambdaExpr::Capture Capture;
   1133     CXXRecordDecl::LambdaDefinitionData &Lambda
   1134       = static_cast<CXXRecordDecl::LambdaDefinitionData &>(Data);
   1135     Lambda.Dependent = Record[Idx++];
   1136     Lambda.NumCaptures = Record[Idx++];
   1137     Lambda.NumExplicitCaptures = Record[Idx++];
   1138     Lambda.ManglingNumber = Record[Idx++];
   1139     Lambda.ContextDecl = ReadDecl(Record, Idx);
   1140     Lambda.Captures
   1141       = (Capture*)Reader.Context.Allocate(sizeof(Capture)*Lambda.NumCaptures);
   1142     Capture *ToCapture = Lambda.Captures;
   1143     Lambda.MethodTyInfo = GetTypeSourceInfo(Record, Idx);
   1144     for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) {
   1145       SourceLocation Loc = ReadSourceLocation(Record, Idx);
   1146       bool IsImplicit = Record[Idx++];
   1147       LambdaCaptureKind Kind = static_cast<LambdaCaptureKind>(Record[Idx++]);
   1148       VarDecl *Var = ReadDeclAs<VarDecl>(Record, Idx);
   1149       SourceLocation EllipsisLoc = ReadSourceLocation(Record, Idx);
   1150       *ToCapture++ = Capture(Loc, IsImplicit, Kind, Var, EllipsisLoc);
   1151     }
   1152   }
   1153 }
   1154 
   1155 void ASTDeclReader::VisitCXXRecordDecl(CXXRecordDecl *D) {
   1156   VisitRecordDecl(D);
   1157 
   1158   ASTContext &C = Reader.getContext();
   1159   if (Record[Idx++]) {
   1160     // Determine whether this is a lambda closure type, so that we can
   1161     // allocate the appropriate DefinitionData structure.
   1162     bool IsLambda = Record[Idx++];
   1163     if (IsLambda)
   1164       D->DefinitionData = new (C) CXXRecordDecl::LambdaDefinitionData(D, 0,
   1165                                                                       false);
   1166     else
   1167       D->DefinitionData = new (C) struct CXXRecordDecl::DefinitionData(D);
   1168 
   1169     // Propagate the DefinitionData pointer to the canonical declaration, so
   1170     // that all other deserialized declarations will see it.
   1171     // FIXME: Complain if there already is a DefinitionData!
   1172     D->getCanonicalDecl()->DefinitionData = D->DefinitionData;
   1173 
   1174     ReadCXXDefinitionData(*D->DefinitionData, Record, Idx);
   1175 
   1176     // Note that we have deserialized a definition. Any declarations
   1177     // deserialized before this one will be be given the DefinitionData pointer
   1178     // at the end.
   1179     Reader.PendingDefinitions.insert(D);
   1180   } else {
   1181     // Propagate DefinitionData pointer from the canonical declaration.
   1182     D->DefinitionData = D->getCanonicalDecl()->DefinitionData;
   1183   }
   1184 
   1185   enum CXXRecKind {
   1186     CXXRecNotTemplate = 0, CXXRecTemplate, CXXRecMemberSpecialization
   1187   };
   1188   switch ((CXXRecKind)Record[Idx++]) {
   1189   case CXXRecNotTemplate:
   1190     break;
   1191   case CXXRecTemplate:
   1192     D->TemplateOrInstantiation = ReadDeclAs<ClassTemplateDecl>(Record, Idx);
   1193     break;
   1194   case CXXRecMemberSpecialization: {
   1195     CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(Record, Idx);
   1196     TemplateSpecializationKind TSK = (TemplateSpecializationKind)Record[Idx++];
   1197     SourceLocation POI = ReadSourceLocation(Record, Idx);
   1198     MemberSpecializationInfo *MSI = new (C) MemberSpecializationInfo(RD, TSK);
   1199     MSI->setPointOfInstantiation(POI);
   1200     D->TemplateOrInstantiation = MSI;
   1201     break;
   1202   }
   1203   }
   1204 
   1205   // Load the key function to avoid deserializing every method so we can
   1206   // compute it.
   1207   if (D->IsCompleteDefinition) {
   1208     if (CXXMethodDecl *Key = ReadDeclAs<CXXMethodDecl>(Record, Idx))
   1209       C.KeyFunctions[D] = Key;
   1210   }
   1211 }
   1212 
   1213 void ASTDeclReader::VisitCXXMethodDecl(CXXMethodDecl *D) {
   1214   VisitFunctionDecl(D);
   1215   unsigned NumOverridenMethods = Record[Idx++];
   1216   while (NumOverridenMethods--) {
   1217     // Avoid invariant checking of CXXMethodDecl::addOverriddenMethod,
   1218     // MD may be initializing.
   1219     if (CXXMethodDecl *MD = ReadDeclAs<CXXMethodDecl>(Record, Idx))
   1220       Reader.getContext().addOverriddenMethod(D, MD);
   1221   }
   1222 }
   1223 
   1224 void ASTDeclReader::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
   1225   VisitCXXMethodDecl(D);
   1226 
   1227   D->IsExplicitSpecified = Record[Idx++];
   1228   D->ImplicitlyDefined = Record[Idx++];
   1229   llvm::tie(D->CtorInitializers, D->NumCtorInitializers)
   1230       = Reader.ReadCXXCtorInitializers(F, Record, Idx);
   1231 }
   1232 
   1233 void ASTDeclReader::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
   1234   VisitCXXMethodDecl(D);
   1235 
   1236   D->ImplicitlyDefined = Record[Idx++];
   1237   D->OperatorDelete = ReadDeclAs<FunctionDecl>(Record, Idx);
   1238 }
   1239 
   1240 void ASTDeclReader::VisitCXXConversionDecl(CXXConversionDecl *D) {
   1241   VisitCXXMethodDecl(D);
   1242   D->IsExplicitSpecified = Record[Idx++];
   1243 }
   1244 
   1245 void ASTDeclReader::VisitImportDecl(ImportDecl *D) {
   1246   VisitDecl(D);
   1247   D->ImportedAndComplete.setPointer(readModule(Record, Idx));
   1248   D->ImportedAndComplete.setInt(Record[Idx++]);
   1249   SourceLocation *StoredLocs = reinterpret_cast<SourceLocation *>(D + 1);
   1250   for (unsigned I = 0, N = Record.back(); I != N; ++I)
   1251     StoredLocs[I] = ReadSourceLocation(Record, Idx);
   1252   ++Idx; // The number of stored source locations.
   1253 }
   1254 
   1255 void ASTDeclReader::VisitAccessSpecDecl(AccessSpecDecl *D) {
   1256   VisitDecl(D);
   1257   D->setColonLoc(ReadSourceLocation(Record, Idx));
   1258 }
   1259 
   1260 void ASTDeclReader::VisitFriendDecl(FriendDecl *D) {
   1261   VisitDecl(D);
   1262   if (Record[Idx++]) // hasFriendDecl
   1263     D->Friend = ReadDeclAs<NamedDecl>(Record, Idx);
   1264   else
   1265     D->Friend = GetTypeSourceInfo(Record, Idx);
   1266   for (unsigned i = 0; i != D->NumTPLists; ++i)
   1267     D->getTPLists()[i] = Reader.ReadTemplateParameterList(F, Record, Idx);
   1268   D->NextFriend = Record[Idx++];
   1269   D->UnsupportedFriend = (Record[Idx++] != 0);
   1270   D->FriendLoc = ReadSourceLocation(Record, Idx);
   1271 }
   1272 
   1273 void ASTDeclReader::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
   1274   VisitDecl(D);
   1275   unsigned NumParams = Record[Idx++];
   1276   D->NumParams = NumParams;
   1277   D->Params = new TemplateParameterList*[NumParams];
   1278   for (unsigned i = 0; i != NumParams; ++i)
   1279     D->Params[i] = Reader.ReadTemplateParameterList(F, Record, Idx);
   1280   if (Record[Idx++]) // HasFriendDecl
   1281     D->Friend = ReadDeclAs<NamedDecl>(Record, Idx);
   1282   else
   1283     D->Friend = GetTypeSourceInfo(Record, Idx);
   1284   D->FriendLoc = ReadSourceLocation(Record, Idx);
   1285 }
   1286 
   1287 void ASTDeclReader::VisitTemplateDecl(TemplateDecl *D) {
   1288   VisitNamedDecl(D);
   1289 
   1290   NamedDecl *TemplatedDecl = ReadDeclAs<NamedDecl>(Record, Idx);
   1291   TemplateParameterList* TemplateParams
   1292       = Reader.ReadTemplateParameterList(F, Record, Idx);
   1293   D->init(TemplatedDecl, TemplateParams);
   1294 }
   1295 
   1296 ASTDeclReader::RedeclarableResult
   1297 ASTDeclReader::VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D) {
   1298   RedeclarableResult Redecl = VisitRedeclarable(D);
   1299 
   1300   // Make sure we've allocated the Common pointer first. We do this before
   1301   // VisitTemplateDecl so that getCommonPtr() can be used during initialization.
   1302   RedeclarableTemplateDecl *CanonD = D->getCanonicalDecl();
   1303   if (!CanonD->Common) {
   1304     CanonD->Common = CanonD->newCommon(Reader.getContext());
   1305     Reader.PendingDefinitions.insert(CanonD);
   1306   }
   1307   D->Common = CanonD->Common;
   1308 
   1309   // If this is the first declaration of the template, fill in the information
   1310   // for the 'common' pointer.
   1311   if (ThisDeclID == Redecl.getFirstID()) {
   1312     if (RedeclarableTemplateDecl *RTD
   1313           = ReadDeclAs<RedeclarableTemplateDecl>(Record, Idx)) {
   1314       assert(RTD->getKind() == D->getKind() &&
   1315              "InstantiatedFromMemberTemplate kind mismatch");
   1316       D->setInstantiatedFromMemberTemplate(RTD);
   1317       if (Record[Idx++])
   1318         D->setMemberSpecialization();
   1319     }
   1320   }
   1321 
   1322   VisitTemplateDecl(D);
   1323   D->IdentifierNamespace = Record[Idx++];
   1324 
   1325   mergeRedeclarable(D, Redecl);
   1326 
   1327   return Redecl;
   1328 }
   1329 
   1330 void ASTDeclReader::VisitClassTemplateDecl(ClassTemplateDecl *D) {
   1331   RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
   1332 
   1333   if (ThisDeclID == Redecl.getFirstID()) {
   1334     // This ClassTemplateDecl owns a CommonPtr; read it to keep track of all of
   1335     // the specializations.
   1336     SmallVector<serialization::DeclID, 2> SpecIDs;
   1337     SpecIDs.push_back(0);
   1338 
   1339     // Specializations.
   1340     unsigned Size = Record[Idx++];
   1341     SpecIDs[0] += Size;
   1342     for (unsigned I = 0; I != Size; ++I)
   1343       SpecIDs.push_back(ReadDeclID(Record, Idx));
   1344 
   1345     // Partial specializations.
   1346     Size = Record[Idx++];
   1347     SpecIDs[0] += Size;
   1348     for (unsigned I = 0; I != Size; ++I)
   1349       SpecIDs.push_back(ReadDeclID(Record, Idx));
   1350 
   1351     ClassTemplateDecl::Common *CommonPtr = D->getCommonPtr();
   1352     if (SpecIDs[0]) {
   1353       typedef serialization::DeclID DeclID;
   1354 
   1355       // FIXME: Append specializations!
   1356       CommonPtr->LazySpecializations
   1357         = new (Reader.getContext()) DeclID [SpecIDs.size()];
   1358       memcpy(CommonPtr->LazySpecializations, SpecIDs.data(),
   1359              SpecIDs.size() * sizeof(DeclID));
   1360     }
   1361 
   1362     CommonPtr->InjectedClassNameType = Reader.readType(F, Record, Idx);
   1363   }
   1364 }
   1365 
   1366 void ASTDeclReader::VisitClassTemplateSpecializationDecl(
   1367                                            ClassTemplateSpecializationDecl *D) {
   1368   VisitCXXRecordDecl(D);
   1369 
   1370   ASTContext &C = Reader.getContext();
   1371   if (Decl *InstD = ReadDecl(Record, Idx)) {
   1372     if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(InstD)) {
   1373       D->SpecializedTemplate = CTD;
   1374     } else {
   1375       SmallVector<TemplateArgument, 8> TemplArgs;
   1376       Reader.ReadTemplateArgumentList(TemplArgs, F, Record, Idx);
   1377       TemplateArgumentList *ArgList
   1378         = TemplateArgumentList::CreateCopy(C, TemplArgs.data(),
   1379                                            TemplArgs.size());
   1380       ClassTemplateSpecializationDecl::SpecializedPartialSpecialization *PS
   1381           = new (C) ClassTemplateSpecializationDecl::
   1382                                              SpecializedPartialSpecialization();
   1383       PS->PartialSpecialization
   1384           = cast<ClassTemplatePartialSpecializationDecl>(InstD);
   1385       PS->TemplateArgs = ArgList;
   1386       D->SpecializedTemplate = PS;
   1387     }
   1388   }
   1389 
   1390   // Explicit info.
   1391   if (TypeSourceInfo *TyInfo = GetTypeSourceInfo(Record, Idx)) {
   1392     ClassTemplateSpecializationDecl::ExplicitSpecializationInfo *ExplicitInfo
   1393         = new (C) ClassTemplateSpecializationDecl::ExplicitSpecializationInfo;
   1394     ExplicitInfo->TypeAsWritten = TyInfo;
   1395     ExplicitInfo->ExternLoc = ReadSourceLocation(Record, Idx);
   1396     ExplicitInfo->TemplateKeywordLoc = ReadSourceLocation(Record, Idx);
   1397     D->ExplicitInfo = ExplicitInfo;
   1398   }
   1399 
   1400   SmallVector<TemplateArgument, 8> TemplArgs;
   1401   Reader.ReadTemplateArgumentList(TemplArgs, F, Record, Idx);
   1402   D->TemplateArgs = TemplateArgumentList::CreateCopy(C, TemplArgs.data(),
   1403                                                      TemplArgs.size());
   1404   D->PointOfInstantiation = ReadSourceLocation(Record, Idx);
   1405   D->SpecializationKind = (TemplateSpecializationKind)Record[Idx++];
   1406 
   1407   bool writtenAsCanonicalDecl = Record[Idx++];
   1408   if (writtenAsCanonicalDecl) {
   1409     ClassTemplateDecl *CanonPattern = ReadDeclAs<ClassTemplateDecl>(Record,Idx);
   1410     if (D->isCanonicalDecl()) { // It's kept in the folding set.
   1411       if (ClassTemplatePartialSpecializationDecl *Partial
   1412                         = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) {
   1413   CanonPattern->getCommonPtr()->PartialSpecializations.GetOrInsertNode(Partial);
   1414       } else {
   1415         CanonPattern->getCommonPtr()->Specializations.GetOrInsertNode(D);
   1416       }
   1417     }
   1418   }
   1419 }
   1420 
   1421 void ASTDeclReader::VisitClassTemplatePartialSpecializationDecl(
   1422                                     ClassTemplatePartialSpecializationDecl *D) {
   1423   VisitClassTemplateSpecializationDecl(D);
   1424 
   1425   ASTContext &C = Reader.getContext();
   1426   D->TemplateParams = Reader.ReadTemplateParameterList(F, Record, Idx);
   1427 
   1428   unsigned NumArgs = Record[Idx++];
   1429   if (NumArgs) {
   1430     D->NumArgsAsWritten = NumArgs;
   1431     D->ArgsAsWritten = new (C) TemplateArgumentLoc[NumArgs];
   1432     for (unsigned i=0; i != NumArgs; ++i)
   1433       D->ArgsAsWritten[i] = Reader.ReadTemplateArgumentLoc(F, Record, Idx);
   1434   }
   1435 
   1436   D->SequenceNumber = Record[Idx++];
   1437 
   1438   // These are read/set from/to the first declaration.
   1439   if (D->getPreviousDecl() == 0) {
   1440     D->InstantiatedFromMember.setPointer(
   1441       ReadDeclAs<ClassTemplatePartialSpecializationDecl>(Record, Idx));
   1442     D->InstantiatedFromMember.setInt(Record[Idx++]);
   1443   }
   1444 }
   1445 
   1446 void ASTDeclReader::VisitClassScopeFunctionSpecializationDecl(
   1447                                     ClassScopeFunctionSpecializationDecl *D) {
   1448   VisitDecl(D);
   1449   D->Specialization = ReadDeclAs<CXXMethodDecl>(Record, Idx);
   1450 }
   1451 
   1452 void ASTDeclReader::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
   1453   RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
   1454 
   1455   if (ThisDeclID == Redecl.getFirstID()) {
   1456     // This FunctionTemplateDecl owns a CommonPtr; read it.
   1457 
   1458     // Read the function specialization declarations.
   1459     // FunctionTemplateDecl's FunctionTemplateSpecializationInfos are filled
   1460     // when reading the specialized FunctionDecl.
   1461     unsigned NumSpecs = Record[Idx++];
   1462     while (NumSpecs--)
   1463       (void)ReadDecl(Record, Idx);
   1464   }
   1465 }
   1466 
   1467 void ASTDeclReader::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
   1468   VisitTypeDecl(D);
   1469 
   1470   D->setDeclaredWithTypename(Record[Idx++]);
   1471 
   1472   bool Inherited = Record[Idx++];
   1473   TypeSourceInfo *DefArg = GetTypeSourceInfo(Record, Idx);
   1474   D->setDefaultArgument(DefArg, Inherited);
   1475 }
   1476 
   1477 void ASTDeclReader::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
   1478   VisitDeclaratorDecl(D);
   1479   // TemplateParmPosition.
   1480   D->setDepth(Record[Idx++]);
   1481   D->setPosition(Record[Idx++]);
   1482   if (D->isExpandedParameterPack()) {
   1483     void **Data = reinterpret_cast<void **>(D + 1);
   1484     for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
   1485       Data[2*I] = Reader.readType(F, Record, Idx).getAsOpaquePtr();
   1486       Data[2*I + 1] = GetTypeSourceInfo(Record, Idx);
   1487     }
   1488   } else {
   1489     // Rest of NonTypeTemplateParmDecl.
   1490     D->ParameterPack = Record[Idx++];
   1491     if (Record[Idx++]) {
   1492       Expr *DefArg = Reader.ReadExpr(F);
   1493       bool Inherited = Record[Idx++];
   1494       D->setDefaultArgument(DefArg, Inherited);
   1495    }
   1496   }
   1497 }
   1498 
   1499 void ASTDeclReader::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
   1500   VisitTemplateDecl(D);
   1501   // TemplateParmPosition.
   1502   D->setDepth(Record[Idx++]);
   1503   D->setPosition(Record[Idx++]);
   1504   if (D->isExpandedParameterPack()) {
   1505     void **Data = reinterpret_cast<void **>(D + 1);
   1506     for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
   1507          I != N; ++I)
   1508       Data[I] = Reader.ReadTemplateParameterList(F, Record, Idx);
   1509   } else {
   1510     // Rest of TemplateTemplateParmDecl.
   1511     TemplateArgumentLoc Arg = Reader.ReadTemplateArgumentLoc(F, Record, Idx);
   1512     bool IsInherited = Record[Idx++];
   1513     D->setDefaultArgument(Arg, IsInherited);
   1514     D->ParameterPack = Record[Idx++];
   1515   }
   1516 }
   1517 
   1518 void ASTDeclReader::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
   1519   VisitRedeclarableTemplateDecl(D);
   1520 }
   1521 
   1522 void ASTDeclReader::VisitStaticAssertDecl(StaticAssertDecl *D) {
   1523   VisitDecl(D);
   1524   D->AssertExprAndFailed.setPointer(Reader.ReadExpr(F));
   1525   D->AssertExprAndFailed.setInt(Record[Idx++]);
   1526   D->Message = cast<StringLiteral>(Reader.ReadExpr(F));
   1527   D->RParenLoc = ReadSourceLocation(Record, Idx);
   1528 }
   1529 
   1530 void ASTDeclReader::VisitEmptyDecl(EmptyDecl *D) {
   1531   VisitDecl(D);
   1532 }
   1533 
   1534 std::pair<uint64_t, uint64_t>
   1535 ASTDeclReader::VisitDeclContext(DeclContext *DC) {
   1536   uint64_t LexicalOffset = Record[Idx++];
   1537   uint64_t VisibleOffset = Record[Idx++];
   1538   return std::make_pair(LexicalOffset, VisibleOffset);
   1539 }
   1540 
   1541 template <typename T>
   1542 ASTDeclReader::RedeclarableResult
   1543 ASTDeclReader::VisitRedeclarable(Redeclarable<T> *D) {
   1544   DeclID FirstDeclID = ReadDeclID(Record, Idx);
   1545 
   1546   // 0 indicates that this declaration was the only declaration of its entity,
   1547   // and is used for space optimization.
   1548   if (FirstDeclID == 0)
   1549     FirstDeclID = ThisDeclID;
   1550 
   1551   T *FirstDecl = cast_or_null<T>(Reader.GetDecl(FirstDeclID));
   1552   if (FirstDecl != D) {
   1553     // We delay loading of the redeclaration chain to avoid deeply nested calls.
   1554     // We temporarily set the first (canonical) declaration as the previous one
   1555     // which is the one that matters and mark the real previous DeclID to be
   1556     // loaded & attached later on.
   1557     D->RedeclLink = Redeclarable<T>::PreviousDeclLink(FirstDecl);
   1558   }
   1559 
   1560   // Note that this declaration has been deserialized.
   1561   Reader.RedeclsDeserialized.insert(static_cast<T *>(D));
   1562 
   1563   // The result structure takes care to note that we need to load the
   1564   // other declaration chains for this ID.
   1565   return RedeclarableResult(Reader, FirstDeclID,
   1566                             static_cast<T *>(D)->getKind());
   1567 }
   1568 
   1569 /// \brief Attempts to merge the given declaration (D) with another declaration
   1570 /// of the same entity.
   1571 template<typename T>
   1572 void ASTDeclReader::mergeRedeclarable(Redeclarable<T> *D,
   1573                                       RedeclarableResult &Redecl) {
   1574   // If modules are not available, there is no reason to perform this merge.
   1575   if (!Reader.getContext().getLangOpts().Modules)
   1576     return;
   1577 
   1578   if (FindExistingResult ExistingRes = findExisting(static_cast<T*>(D))) {
   1579     if (T *Existing = ExistingRes) {
   1580       T *ExistingCanon = Existing->getCanonicalDecl();
   1581       T *DCanon = static_cast<T*>(D)->getCanonicalDecl();
   1582       if (ExistingCanon != DCanon) {
   1583         // Have our redeclaration link point back at the canonical declaration
   1584         // of the existing declaration, so that this declaration has the
   1585         // appropriate canonical declaration.
   1586         D->RedeclLink = Redeclarable<T>::PreviousDeclLink(ExistingCanon);
   1587 
   1588         // When we merge a namespace, update its pointer to the first namespace.
   1589         if (NamespaceDecl *Namespace
   1590               = dyn_cast<NamespaceDecl>(static_cast<T*>(D))) {
   1591           Namespace->AnonOrFirstNamespaceAndInline.setPointer(
   1592             static_cast<NamespaceDecl *>(static_cast<void*>(ExistingCanon)));
   1593         }
   1594 
   1595         // Don't introduce DCanon into the set of pending declaration chains.
   1596         Redecl.suppress();
   1597 
   1598         // Introduce ExistingCanon into the set of pending declaration chains,
   1599         // if in fact it came from a module file.
   1600         if (ExistingCanon->isFromASTFile()) {
   1601           GlobalDeclID ExistingCanonID = ExistingCanon->getGlobalID();
   1602           assert(ExistingCanonID && "Unrecorded canonical declaration ID?");
   1603           if (Reader.PendingDeclChainsKnown.insert(ExistingCanonID))
   1604             Reader.PendingDeclChains.push_back(ExistingCanonID);
   1605         }
   1606 
   1607         // If this declaration was the canonical declaration, make a note of
   1608         // that. We accept the linear algorithm here because the number of
   1609         // unique canonical declarations of an entity should always be tiny.
   1610         if (DCanon == static_cast<T*>(D)) {
   1611           SmallVectorImpl<DeclID> &Merged = Reader.MergedDecls[ExistingCanon];
   1612           if (std::find(Merged.begin(), Merged.end(), Redecl.getFirstID())
   1613                 == Merged.end())
   1614             Merged.push_back(Redecl.getFirstID());
   1615 
   1616           // If ExistingCanon did not come from a module file, introduce the
   1617           // first declaration that *does* come from a module file to the
   1618           // set of pending declaration chains, so that we merge this
   1619           // declaration.
   1620           if (!ExistingCanon->isFromASTFile() &&
   1621               Reader.PendingDeclChainsKnown.insert(Redecl.getFirstID()))
   1622             Reader.PendingDeclChains.push_back(Merged[0]);
   1623         }
   1624       }
   1625     }
   1626   }
   1627 }
   1628 
   1629 //===----------------------------------------------------------------------===//
   1630 // Attribute Reading
   1631 //===----------------------------------------------------------------------===//
   1632 
   1633 /// \brief Reads attributes from the current stream position.
   1634 void ASTReader::ReadAttributes(ModuleFile &F, AttrVec &Attrs,
   1635                                const RecordData &Record, unsigned &Idx) {
   1636   for (unsigned i = 0, e = Record[Idx++]; i != e; ++i) {
   1637     Attr *New = 0;
   1638     attr::Kind Kind = (attr::Kind)Record[Idx++];
   1639     SourceRange Range = ReadSourceRange(F, Record, Idx);
   1640 
   1641 #include "clang/Serialization/AttrPCHRead.inc"
   1642 
   1643     assert(New && "Unable to decode attribute?");
   1644     Attrs.push_back(New);
   1645   }
   1646 }
   1647 
   1648 //===----------------------------------------------------------------------===//
   1649 // ASTReader Implementation
   1650 //===----------------------------------------------------------------------===//
   1651 
   1652 /// \brief Note that we have loaded the declaration with the given
   1653 /// Index.
   1654 ///
   1655 /// This routine notes that this declaration has already been loaded,
   1656 /// so that future GetDecl calls will return this declaration rather
   1657 /// than trying to load a new declaration.
   1658 inline void ASTReader::LoadedDecl(unsigned Index, Decl *D) {
   1659   assert(!DeclsLoaded[Index] && "Decl loaded twice?");
   1660   DeclsLoaded[Index] = D;
   1661 }
   1662 
   1663 
   1664 /// \brief Determine whether the consumer will be interested in seeing
   1665 /// this declaration (via HandleTopLevelDecl).
   1666 ///
   1667 /// This routine should return true for anything that might affect
   1668 /// code generation, e.g., inline function definitions, Objective-C
   1669 /// declarations with metadata, etc.
   1670 static bool isConsumerInterestedIn(Decl *D, bool HasBody) {
   1671   // An ObjCMethodDecl is never considered as "interesting" because its
   1672   // implementation container always is.
   1673 
   1674   if (isa<FileScopeAsmDecl>(D) ||
   1675       isa<ObjCProtocolDecl>(D) ||
   1676       isa<ObjCImplDecl>(D))
   1677     return true;
   1678   if (VarDecl *Var = dyn_cast<VarDecl>(D))
   1679     return Var->isFileVarDecl() &&
   1680            Var->isThisDeclarationADefinition() == VarDecl::Definition;
   1681   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(D))
   1682     return Func->doesThisDeclarationHaveABody() || HasBody;
   1683 
   1684   return false;
   1685 }
   1686 
   1687 /// \brief Get the correct cursor and offset for loading a declaration.
   1688 ASTReader::RecordLocation
   1689 ASTReader::DeclCursorForID(DeclID ID, unsigned &RawLocation) {
   1690   // See if there's an override.
   1691   DeclReplacementMap::iterator It = ReplacedDecls.find(ID);
   1692   if (It != ReplacedDecls.end()) {
   1693     RawLocation = It->second.RawLoc;
   1694     return RecordLocation(It->second.Mod, It->second.Offset);
   1695   }
   1696 
   1697   GlobalDeclMapType::iterator I = GlobalDeclMap.find(ID);
   1698   assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
   1699   ModuleFile *M = I->second;
   1700   const DeclOffset &
   1701     DOffs =  M->DeclOffsets[ID - M->BaseDeclID - NUM_PREDEF_DECL_IDS];
   1702   RawLocation = DOffs.Loc;
   1703   return RecordLocation(M, DOffs.BitOffset);
   1704 }
   1705 
   1706 ASTReader::RecordLocation ASTReader::getLocalBitOffset(uint64_t GlobalOffset) {
   1707   ContinuousRangeMap<uint64_t, ModuleFile*, 4>::iterator I
   1708     = GlobalBitOffsetsMap.find(GlobalOffset);
   1709 
   1710   assert(I != GlobalBitOffsetsMap.end() && "Corrupted global bit offsets map");
   1711   return RecordLocation(I->second, GlobalOffset - I->second->GlobalBitOffset);
   1712 }
   1713 
   1714 uint64_t ASTReader::getGlobalBitOffset(ModuleFile &M, uint32_t LocalOffset) {
   1715   return LocalOffset + M.GlobalBitOffset;
   1716 }
   1717 
   1718 /// \brief Determine whether the two declarations refer to the same entity.
   1719 static bool isSameEntity(NamedDecl *X, NamedDecl *Y) {
   1720   assert(X->getDeclName() == Y->getDeclName() && "Declaration name mismatch!");
   1721 
   1722   if (X == Y)
   1723     return true;
   1724 
   1725   // Must be in the same context.
   1726   if (!X->getDeclContext()->getRedeclContext()->Equals(
   1727          Y->getDeclContext()->getRedeclContext()))
   1728     return false;
   1729 
   1730   // Two typedefs refer to the same entity if they have the same underlying
   1731   // type.
   1732   if (TypedefNameDecl *TypedefX = dyn_cast<TypedefNameDecl>(X))
   1733     if (TypedefNameDecl *TypedefY = dyn_cast<TypedefNameDecl>(Y))
   1734       return X->getASTContext().hasSameType(TypedefX->getUnderlyingType(),
   1735                                             TypedefY->getUnderlyingType());
   1736 
   1737   // Must have the same kind.
   1738   if (X->getKind() != Y->getKind())
   1739     return false;
   1740 
   1741   // Objective-C classes and protocols with the same name always match.
   1742   if (isa<ObjCInterfaceDecl>(X) || isa<ObjCProtocolDecl>(X))
   1743     return true;
   1744 
   1745   // Compatible tags match.
   1746   if (TagDecl *TagX = dyn_cast<TagDecl>(X)) {
   1747     TagDecl *TagY = cast<TagDecl>(Y);
   1748     return (TagX->getTagKind() == TagY->getTagKind()) ||
   1749       ((TagX->getTagKind() == TTK_Struct || TagX->getTagKind() == TTK_Class ||
   1750         TagX->getTagKind() == TTK_Interface) &&
   1751        (TagY->getTagKind() == TTK_Struct || TagY->getTagKind() == TTK_Class ||
   1752         TagY->getTagKind() == TTK_Interface));
   1753   }
   1754 
   1755   // Functions with the same type and linkage match.
   1756   // FIXME: This needs to cope with function templates, merging of
   1757   //prototyped/non-prototyped functions, etc.
   1758   if (FunctionDecl *FuncX = dyn_cast<FunctionDecl>(X)) {
   1759     FunctionDecl *FuncY = cast<FunctionDecl>(Y);
   1760     return (FuncX->getLinkage() == FuncY->getLinkage()) &&
   1761       FuncX->getASTContext().hasSameType(FuncX->getType(), FuncY->getType());
   1762   }
   1763 
   1764   // Variables with the same type and linkage match.
   1765   if (VarDecl *VarX = dyn_cast<VarDecl>(X)) {
   1766     VarDecl *VarY = cast<VarDecl>(Y);
   1767     return (VarX->getLinkage() == VarY->getLinkage()) &&
   1768       VarX->getASTContext().hasSameType(VarX->getType(), VarY->getType());
   1769   }
   1770 
   1771   // Namespaces with the same name and inlinedness match.
   1772   if (NamespaceDecl *NamespaceX = dyn_cast<NamespaceDecl>(X)) {
   1773     NamespaceDecl *NamespaceY = cast<NamespaceDecl>(Y);
   1774     return NamespaceX->isInline() == NamespaceY->isInline();
   1775   }
   1776 
   1777   // Identical template names and kinds match.
   1778   if (isa<TemplateDecl>(X))
   1779     return true;
   1780 
   1781   // FIXME: Many other cases to implement.
   1782   return false;
   1783 }
   1784 
   1785 ASTDeclReader::FindExistingResult::~FindExistingResult() {
   1786   if (!AddResult || Existing)
   1787     return;
   1788 
   1789   if (New->getDeclContext()->getRedeclContext()->isTranslationUnit()
   1790       && Reader.SemaObj) {
   1791     Reader.SemaObj->IdResolver.tryAddTopLevelDecl(New, New->getDeclName());
   1792   } else {
   1793     DeclContext *DC = New->getLexicalDeclContext();
   1794     if (DC->isNamespace())
   1795       DC->addDecl(New);
   1796   }
   1797 }
   1798 
   1799 ASTDeclReader::FindExistingResult ASTDeclReader::findExisting(NamedDecl *D) {
   1800   DeclarationName Name = D->getDeclName();
   1801   if (!Name) {
   1802     // Don't bother trying to find unnamed declarations.
   1803     FindExistingResult Result(Reader, D, /*Existing=*/0);
   1804     Result.suppress();
   1805     return Result;
   1806   }
   1807 
   1808   DeclContext *DC = D->getDeclContext()->getRedeclContext();
   1809   if (!DC->isFileContext())
   1810     return FindExistingResult(Reader);
   1811 
   1812   if (DC->isTranslationUnit() && Reader.SemaObj) {
   1813     IdentifierResolver &IdResolver = Reader.SemaObj->IdResolver;
   1814 
   1815     // Temporarily consider the identifier to be up-to-date. We don't want to
   1816     // cause additional lookups here.
   1817     class UpToDateIdentifierRAII {
   1818       IdentifierInfo *II;
   1819       bool WasOutToDate;
   1820 
   1821     public:
   1822       explicit UpToDateIdentifierRAII(IdentifierInfo *II)
   1823         : II(II), WasOutToDate(false)
   1824       {
   1825         if (II) {
   1826           WasOutToDate = II->isOutOfDate();
   1827           if (WasOutToDate)
   1828             II->setOutOfDate(false);
   1829         }
   1830       }
   1831 
   1832       ~UpToDateIdentifierRAII() {
   1833         if (WasOutToDate)
   1834           II->setOutOfDate(true);
   1835       }
   1836     } UpToDate(Name.getAsIdentifierInfo());
   1837 
   1838     for (IdentifierResolver::iterator I = IdResolver.begin(Name),
   1839                                    IEnd = IdResolver.end();
   1840          I != IEnd; ++I) {
   1841       if (isSameEntity(*I, D))
   1842         return FindExistingResult(Reader, D, *I);
   1843     }
   1844   }
   1845 
   1846   if (DC->isNamespace()) {
   1847     DeclContext::lookup_result R = DC->lookup(Name);
   1848     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
   1849          ++I) {
   1850       if (isSameEntity(*I, D))
   1851         return FindExistingResult(Reader, D, *I);
   1852     }
   1853   }
   1854 
   1855   return FindExistingResult(Reader, D, /*Existing=*/0);
   1856 }
   1857 
   1858 void ASTDeclReader::attachPreviousDecl(Decl *D, Decl *previous) {
   1859   assert(D && previous);
   1860   if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
   1861     TD->RedeclLink.setNext(cast<TagDecl>(previous));
   1862   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
   1863     FD->RedeclLink.setNext(cast<FunctionDecl>(previous));
   1864   } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
   1865     VD->RedeclLink.setNext(cast<VarDecl>(previous));
   1866   } else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
   1867     TD->RedeclLink.setNext(cast<TypedefNameDecl>(previous));
   1868   } else if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
   1869     ID->RedeclLink.setNext(cast<ObjCInterfaceDecl>(previous));
   1870   } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
   1871     PD->RedeclLink.setNext(cast<ObjCProtocolDecl>(previous));
   1872   } else if (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(D)) {
   1873     ND->RedeclLink.setNext(cast<NamespaceDecl>(previous));
   1874   } else {
   1875     RedeclarableTemplateDecl *TD = cast<RedeclarableTemplateDecl>(D);
   1876     TD->RedeclLink.setNext(cast<RedeclarableTemplateDecl>(previous));
   1877   }
   1878 }
   1879 
   1880 void ASTDeclReader::attachLatestDecl(Decl *D, Decl *Latest) {
   1881   assert(D && Latest);
   1882   if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
   1883     TD->RedeclLink
   1884       = Redeclarable<TagDecl>::LatestDeclLink(cast<TagDecl>(Latest));
   1885   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
   1886     FD->RedeclLink
   1887       = Redeclarable<FunctionDecl>::LatestDeclLink(cast<FunctionDecl>(Latest));
   1888   } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
   1889     VD->RedeclLink
   1890       = Redeclarable<VarDecl>::LatestDeclLink(cast<VarDecl>(Latest));
   1891   } else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
   1892     TD->RedeclLink
   1893       = Redeclarable<TypedefNameDecl>::LatestDeclLink(
   1894                                                 cast<TypedefNameDecl>(Latest));
   1895   } else if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
   1896     ID->RedeclLink
   1897       = Redeclarable<ObjCInterfaceDecl>::LatestDeclLink(
   1898                                               cast<ObjCInterfaceDecl>(Latest));
   1899   } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
   1900     PD->RedeclLink
   1901       = Redeclarable<ObjCProtocolDecl>::LatestDeclLink(
   1902                                                 cast<ObjCProtocolDecl>(Latest));
   1903   } else if (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(D)) {
   1904     ND->RedeclLink
   1905       = Redeclarable<NamespaceDecl>::LatestDeclLink(
   1906                                                    cast<NamespaceDecl>(Latest));
   1907   } else {
   1908     RedeclarableTemplateDecl *TD = cast<RedeclarableTemplateDecl>(D);
   1909     TD->RedeclLink
   1910       = Redeclarable<RedeclarableTemplateDecl>::LatestDeclLink(
   1911                                         cast<RedeclarableTemplateDecl>(Latest));
   1912   }
   1913 }
   1914 
   1915 ASTReader::MergedDeclsMap::iterator
   1916 ASTReader::combineStoredMergedDecls(Decl *Canon, GlobalDeclID CanonID) {
   1917   // If we don't have any stored merged declarations, just look in the
   1918   // merged declarations set.
   1919   StoredMergedDeclsMap::iterator StoredPos = StoredMergedDecls.find(CanonID);
   1920   if (StoredPos == StoredMergedDecls.end())
   1921     return MergedDecls.find(Canon);
   1922 
   1923   // Append the stored merged declarations to the merged declarations set.
   1924   MergedDeclsMap::iterator Pos = MergedDecls.find(Canon);
   1925   if (Pos == MergedDecls.end())
   1926     Pos = MergedDecls.insert(std::make_pair(Canon,
   1927                                             SmallVector<DeclID, 2>())).first;
   1928   Pos->second.append(StoredPos->second.begin(), StoredPos->second.end());
   1929   StoredMergedDecls.erase(StoredPos);
   1930 
   1931   // Sort and uniquify the set of merged declarations.
   1932   llvm::array_pod_sort(Pos->second.begin(), Pos->second.end());
   1933   Pos->second.erase(std::unique(Pos->second.begin(), Pos->second.end()),
   1934                     Pos->second.end());
   1935   return Pos;
   1936 }
   1937 
   1938 void ASTReader::loadAndAttachPreviousDecl(Decl *D, serialization::DeclID ID) {
   1939   Decl *previous = GetDecl(ID);
   1940   ASTDeclReader::attachPreviousDecl(D, previous);
   1941 }
   1942 
   1943 /// \brief Read the declaration at the given offset from the AST file.
   1944 Decl *ASTReader::ReadDeclRecord(DeclID ID) {
   1945   unsigned Index = ID - NUM_PREDEF_DECL_IDS;
   1946   unsigned RawLocation = 0;
   1947   RecordLocation Loc = DeclCursorForID(ID, RawLocation);
   1948   llvm::BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
   1949   // Keep track of where we are in the stream, then jump back there
   1950   // after reading this declaration.
   1951   SavedStreamPosition SavedPosition(DeclsCursor);
   1952 
   1953   ReadingKindTracker ReadingKind(Read_Decl, *this);
   1954 
   1955   // Note that we are loading a declaration record.
   1956   Deserializing ADecl(this);
   1957 
   1958   DeclsCursor.JumpToBit(Loc.Offset);
   1959   RecordData Record;
   1960   unsigned Code = DeclsCursor.ReadCode();
   1961   unsigned Idx = 0;
   1962   ASTDeclReader Reader(*this, *Loc.F, ID, RawLocation, Record,Idx);
   1963 
   1964   Decl *D = 0;
   1965   switch ((DeclCode)DeclsCursor.readRecord(Code, Record)) {
   1966   case DECL_CONTEXT_LEXICAL:
   1967   case DECL_CONTEXT_VISIBLE:
   1968     llvm_unreachable("Record cannot be de-serialized with ReadDeclRecord");
   1969   case DECL_TYPEDEF:
   1970     D = TypedefDecl::CreateDeserialized(Context, ID);
   1971     break;
   1972   case DECL_TYPEALIAS:
   1973     D = TypeAliasDecl::CreateDeserialized(Context, ID);
   1974     break;
   1975   case DECL_ENUM:
   1976     D = EnumDecl::CreateDeserialized(Context, ID);
   1977     break;
   1978   case DECL_RECORD:
   1979     D = RecordDecl::CreateDeserialized(Context, ID);
   1980     break;
   1981   case DECL_ENUM_CONSTANT:
   1982     D = EnumConstantDecl::CreateDeserialized(Context, ID);
   1983     break;
   1984   case DECL_FUNCTION:
   1985     D = FunctionDecl::CreateDeserialized(Context, ID);
   1986     break;
   1987   case DECL_LINKAGE_SPEC:
   1988     D = LinkageSpecDecl::CreateDeserialized(Context, ID);
   1989     break;
   1990   case DECL_LABEL:
   1991     D = LabelDecl::CreateDeserialized(Context, ID);
   1992     break;
   1993   case DECL_NAMESPACE:
   1994     D = NamespaceDecl::CreateDeserialized(Context, ID);
   1995     break;
   1996   case DECL_NAMESPACE_ALIAS:
   1997     D = NamespaceAliasDecl::CreateDeserialized(Context, ID);
   1998     break;
   1999   case DECL_USING:
   2000     D = UsingDecl::CreateDeserialized(Context, ID);
   2001     break;
   2002   case DECL_USING_SHADOW:
   2003     D = UsingShadowDecl::CreateDeserialized(Context, ID);
   2004     break;
   2005   case DECL_USING_DIRECTIVE:
   2006     D = UsingDirectiveDecl::CreateDeserialized(Context, ID);
   2007     break;
   2008   case DECL_UNRESOLVED_USING_VALUE:
   2009     D = UnresolvedUsingValueDecl::CreateDeserialized(Context, ID);
   2010     break;
   2011   case DECL_UNRESOLVED_USING_TYPENAME:
   2012     D = UnresolvedUsingTypenameDecl::CreateDeserialized(Context, ID);
   2013     break;
   2014   case DECL_CXX_RECORD:
   2015     D = CXXRecordDecl::CreateDeserialized(Context, ID);
   2016     break;
   2017   case DECL_CXX_METHOD:
   2018     D = CXXMethodDecl::CreateDeserialized(Context, ID);
   2019     break;
   2020   case DECL_CXX_CONSTRUCTOR:
   2021     D = CXXConstructorDecl::CreateDeserialized(Context, ID);
   2022     break;
   2023   case DECL_CXX_DESTRUCTOR:
   2024     D = CXXDestructorDecl::CreateDeserialized(Context, ID);
   2025     break;
   2026   case DECL_CXX_CONVERSION:
   2027     D = CXXConversionDecl::CreateDeserialized(Context, ID);
   2028     break;
   2029   case DECL_ACCESS_SPEC:
   2030     D = AccessSpecDecl::CreateDeserialized(Context, ID);
   2031     break;
   2032   case DECL_FRIEND:
   2033     D = FriendDecl::CreateDeserialized(Context, ID, Record[Idx++]);
   2034     break;
   2035   case DECL_FRIEND_TEMPLATE:
   2036     D = FriendTemplateDecl::CreateDeserialized(Context, ID);
   2037     break;
   2038   case DECL_CLASS_TEMPLATE:
   2039     D = ClassTemplateDecl::CreateDeserialized(Context, ID);
   2040     break;
   2041   case DECL_CLASS_TEMPLATE_SPECIALIZATION:
   2042     D = ClassTemplateSpecializationDecl::CreateDeserialized(Context, ID);
   2043     break;
   2044   case DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION:
   2045     D = ClassTemplatePartialSpecializationDecl::CreateDeserialized(Context, ID);
   2046     break;
   2047   case DECL_CLASS_SCOPE_FUNCTION_SPECIALIZATION:
   2048     D = ClassScopeFunctionSpecializationDecl::CreateDeserialized(Context, ID);
   2049     break;
   2050   case DECL_FUNCTION_TEMPLATE:
   2051     D = FunctionTemplateDecl::CreateDeserialized(Context, ID);
   2052     break;
   2053   case DECL_TEMPLATE_TYPE_PARM:
   2054     D = TemplateTypeParmDecl::CreateDeserialized(Context, ID);
   2055     break;
   2056   case DECL_NON_TYPE_TEMPLATE_PARM:
   2057     D = NonTypeTemplateParmDecl::CreateDeserialized(Context, ID);
   2058     break;
   2059   case DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK:
   2060     D = NonTypeTemplateParmDecl::CreateDeserialized(Context, ID, Record[Idx++]);
   2061     break;
   2062   case DECL_TEMPLATE_TEMPLATE_PARM:
   2063     D = TemplateTemplateParmDecl::CreateDeserialized(Context, ID);
   2064     break;
   2065   case DECL_EXPANDED_TEMPLATE_TEMPLATE_PARM_PACK:
   2066     D = TemplateTemplateParmDecl::CreateDeserialized(Context, ID,
   2067                                                      Record[Idx++]);
   2068     break;
   2069   case DECL_TYPE_ALIAS_TEMPLATE:
   2070     D = TypeAliasTemplateDecl::CreateDeserialized(Context, ID);
   2071     break;
   2072   case DECL_STATIC_ASSERT:
   2073     D = StaticAssertDecl::CreateDeserialized(Context, ID);
   2074     break;
   2075   case DECL_OBJC_METHOD:
   2076     D = ObjCMethodDecl::CreateDeserialized(Context, ID);
   2077     break;
   2078   case DECL_OBJC_INTERFACE:
   2079     D = ObjCInterfaceDecl::CreateDeserialized(Context, ID);
   2080     break;
   2081   case DECL_OBJC_IVAR:
   2082     D = ObjCIvarDecl::CreateDeserialized(Context, ID);
   2083     break;
   2084   case DECL_OBJC_PROTOCOL:
   2085     D = ObjCProtocolDecl::CreateDeserialized(Context, ID);
   2086     break;
   2087   case DECL_OBJC_AT_DEFS_FIELD:
   2088     D = ObjCAtDefsFieldDecl::CreateDeserialized(Context, ID);
   2089     break;
   2090   case DECL_OBJC_CATEGORY:
   2091     D = ObjCCategoryDecl::CreateDeserialized(Context, ID);
   2092     break;
   2093   case DECL_OBJC_CATEGORY_IMPL:
   2094     D = ObjCCategoryImplDecl::CreateDeserialized(Context, ID);
   2095     break;
   2096   case DECL_OBJC_IMPLEMENTATION:
   2097     D = ObjCImplementationDecl::CreateDeserialized(Context, ID);
   2098     break;
   2099   case DECL_OBJC_COMPATIBLE_ALIAS:
   2100     D = ObjCCompatibleAliasDecl::CreateDeserialized(Context, ID);
   2101     break;
   2102   case DECL_OBJC_PROPERTY:
   2103     D = ObjCPropertyDecl::CreateDeserialized(Context, ID);
   2104     break;
   2105   case DECL_OBJC_PROPERTY_IMPL:
   2106     D = ObjCPropertyImplDecl::CreateDeserialized(Context, ID);
   2107     break;
   2108   case DECL_FIELD:
   2109     D = FieldDecl::CreateDeserialized(Context, ID);
   2110     break;
   2111   case DECL_INDIRECTFIELD:
   2112     D = IndirectFieldDecl::CreateDeserialized(Context, ID);
   2113     break;
   2114   case DECL_VAR:
   2115     D = VarDecl::CreateDeserialized(Context, ID);
   2116     break;
   2117   case DECL_IMPLICIT_PARAM:
   2118     D = ImplicitParamDecl::CreateDeserialized(Context, ID);
   2119     break;
   2120   case DECL_PARM_VAR:
   2121     D = ParmVarDecl::CreateDeserialized(Context, ID);
   2122     break;
   2123   case DECL_FILE_SCOPE_ASM:
   2124     D = FileScopeAsmDecl::CreateDeserialized(Context, ID);
   2125     break;
   2126   case DECL_BLOCK:
   2127     D = BlockDecl::CreateDeserialized(Context, ID);
   2128     break;
   2129   case DECL_CXX_BASE_SPECIFIERS:
   2130     Error("attempt to read a C++ base-specifier record as a declaration");
   2131     return 0;
   2132   case DECL_IMPORT:
   2133     // Note: last entry of the ImportDecl record is the number of stored source
   2134     // locations.
   2135     D = ImportDecl::CreateDeserialized(Context, ID, Record.back());
   2136     break;
   2137   case DECL_EMPTY:
   2138     D = EmptyDecl::CreateDeserialized(Context, ID);
   2139     break;
   2140   }
   2141 
   2142   assert(D && "Unknown declaration reading AST file");
   2143   LoadedDecl(Index, D);
   2144   // Set the DeclContext before doing any deserialization, to make sure internal
   2145   // calls to Decl::getASTContext() by Decl's methods will find the
   2146   // TranslationUnitDecl without crashing.
   2147   D->setDeclContext(Context.getTranslationUnitDecl());
   2148   Reader.Visit(D);
   2149 
   2150   // If this declaration is also a declaration context, get the
   2151   // offsets for its tables of lexical and visible declarations.
   2152   if (DeclContext *DC = dyn_cast<DeclContext>(D)) {
   2153     // FIXME: This should really be
   2154     //     DeclContext *LookupDC = DC->getPrimaryContext();
   2155     // but that can walk the redeclaration chain, which might not work yet.
   2156     DeclContext *LookupDC = DC;
   2157     if (isa<NamespaceDecl>(DC))
   2158       LookupDC = DC->getPrimaryContext();
   2159     std::pair<uint64_t, uint64_t> Offsets = Reader.VisitDeclContext(DC);
   2160     if (Offsets.first || Offsets.second) {
   2161       if (Offsets.first != 0)
   2162         DC->setHasExternalLexicalStorage(true);
   2163       if (Offsets.second != 0)
   2164         LookupDC->setHasExternalVisibleStorage(true);
   2165       if (ReadDeclContextStorage(*Loc.F, DeclsCursor, Offsets,
   2166                                  Loc.F->DeclContextInfos[DC]))
   2167         return 0;
   2168     }
   2169 
   2170     // Now add the pending visible updates for this decl context, if it has any.
   2171     DeclContextVisibleUpdatesPending::iterator I =
   2172         PendingVisibleUpdates.find(ID);
   2173     if (I != PendingVisibleUpdates.end()) {
   2174       // There are updates. This means the context has external visible
   2175       // storage, even if the original stored version didn't.
   2176       LookupDC->setHasExternalVisibleStorage(true);
   2177       DeclContextVisibleUpdates &U = I->second;
   2178       for (DeclContextVisibleUpdates::iterator UI = U.begin(), UE = U.end();
   2179            UI != UE; ++UI) {
   2180         DeclContextInfo &Info = UI->second->DeclContextInfos[DC];
   2181         delete Info.NameLookupTableData;
   2182         Info.NameLookupTableData = UI->first;
   2183       }
   2184       PendingVisibleUpdates.erase(I);
   2185     }
   2186 
   2187     if (!LookupDC->hasExternalVisibleStorage() &&
   2188         DC->hasExternalLexicalStorage())
   2189       LookupDC->setMustBuildLookupTable();
   2190   }
   2191   assert(Idx == Record.size());
   2192 
   2193   // Load any relevant update records.
   2194   loadDeclUpdateRecords(ID, D);
   2195 
   2196   // Load the categories after recursive loading is finished.
   2197   if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
   2198     if (Class->isThisDeclarationADefinition())
   2199       loadObjCCategories(ID, Class);
   2200 
   2201   // If we have deserialized a declaration that has a definition the
   2202   // AST consumer might need to know about, queue it.
   2203   // We don't pass it to the consumer immediately because we may be in recursive
   2204   // loading, and some declarations may still be initializing.
   2205   if (isConsumerInterestedIn(D, Reader.hasPendingBody()))
   2206     InterestingDecls.push_back(D);
   2207 
   2208   return D;
   2209 }
   2210 
   2211 void ASTReader::loadDeclUpdateRecords(serialization::DeclID ID, Decl *D) {
   2212   // The declaration may have been modified by files later in the chain.
   2213   // If this is the case, read the record containing the updates from each file
   2214   // and pass it to ASTDeclReader to make the modifications.
   2215   DeclUpdateOffsetsMap::iterator UpdI = DeclUpdateOffsets.find(ID);
   2216   if (UpdI != DeclUpdateOffsets.end()) {
   2217     FileOffsetsTy &UpdateOffsets = UpdI->second;
   2218     for (FileOffsetsTy::iterator
   2219          I = UpdateOffsets.begin(), E = UpdateOffsets.end(); I != E; ++I) {
   2220       ModuleFile *F = I->first;
   2221       uint64_t Offset = I->second;
   2222       llvm::BitstreamCursor &Cursor = F->DeclsCursor;
   2223       SavedStreamPosition SavedPosition(Cursor);
   2224       Cursor.JumpToBit(Offset);
   2225       RecordData Record;
   2226       unsigned Code = Cursor.ReadCode();
   2227       unsigned RecCode = Cursor.readRecord(Code, Record);
   2228       (void)RecCode;
   2229       assert(RecCode == DECL_UPDATES && "Expected DECL_UPDATES record!");
   2230 
   2231       unsigned Idx = 0;
   2232       ASTDeclReader Reader(*this, *F, ID, 0, Record, Idx);
   2233       Reader.UpdateDecl(D, *F, Record);
   2234     }
   2235   }
   2236 }
   2237 
   2238 namespace {
   2239   struct CompareLocalRedeclarationsInfoToID {
   2240     bool operator()(const LocalRedeclarationsInfo &X, DeclID Y) {
   2241       return X.FirstID < Y;
   2242     }
   2243 
   2244     bool operator()(DeclID X, const LocalRedeclarationsInfo &Y) {
   2245       return X < Y.FirstID;
   2246     }
   2247 
   2248     bool operator()(const LocalRedeclarationsInfo &X,
   2249                     const LocalRedeclarationsInfo &Y) {
   2250       return X.FirstID < Y.FirstID;
   2251     }
   2252     bool operator()(DeclID X, DeclID Y) {
   2253       return X < Y;
   2254     }
   2255   };
   2256 
   2257   /// \brief Module visitor class that finds all of the redeclarations of a
   2258   ///
   2259   class RedeclChainVisitor {
   2260     ASTReader &Reader;
   2261     SmallVectorImpl<DeclID> &SearchDecls;
   2262     llvm::SmallPtrSet<Decl *, 16> &Deserialized;
   2263     GlobalDeclID CanonID;
   2264     SmallVector<Decl *, 4> Chain;
   2265 
   2266   public:
   2267     RedeclChainVisitor(ASTReader &Reader, SmallVectorImpl<DeclID> &SearchDecls,
   2268                        llvm::SmallPtrSet<Decl *, 16> &Deserialized,
   2269                        GlobalDeclID CanonID)
   2270       : Reader(Reader), SearchDecls(SearchDecls), Deserialized(Deserialized),
   2271         CanonID(CanonID) {
   2272       for (unsigned I = 0, N = SearchDecls.size(); I != N; ++I)
   2273         addToChain(Reader.GetDecl(SearchDecls[I]));
   2274     }
   2275 
   2276     static bool visit(ModuleFile &M, bool Preorder, void *UserData) {
   2277       if (Preorder)
   2278         return false;
   2279 
   2280       return static_cast<RedeclChainVisitor *>(UserData)->visit(M);
   2281     }
   2282 
   2283     void addToChain(Decl *D) {
   2284       if (!D)
   2285         return;
   2286 
   2287       if (Deserialized.erase(D))
   2288         Chain.push_back(D);
   2289     }
   2290 
   2291     void searchForID(ModuleFile &M, GlobalDeclID GlobalID) {
   2292       // Map global ID of the first declaration down to the local ID
   2293       // used in this module file.
   2294       DeclID ID = Reader.mapGlobalIDToModuleFileGlobalID(M, GlobalID);
   2295       if (!ID)
   2296         return;
   2297 
   2298       // Perform a binary search to find the local redeclarations for this
   2299       // declaration (if any).
   2300       const LocalRedeclarationsInfo *Result
   2301         = std::lower_bound(M.RedeclarationsMap,
   2302                            M.RedeclarationsMap + M.LocalNumRedeclarationsInMap,
   2303                            ID, CompareLocalRedeclarationsInfoToID());
   2304       if (Result == M.RedeclarationsMap + M.LocalNumRedeclarationsInMap ||
   2305           Result->FirstID != ID) {
   2306         // If we have a previously-canonical singleton declaration that was
   2307         // merged into another redeclaration chain, create a trivial chain
   2308         // for this single declaration so that it will get wired into the
   2309         // complete redeclaration chain.
   2310         if (GlobalID != CanonID &&
   2311             GlobalID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
   2312             GlobalID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls) {
   2313           addToChain(Reader.GetDecl(GlobalID));
   2314         }
   2315 
   2316         return;
   2317       }
   2318 
   2319       // Dig out all of the redeclarations.
   2320       unsigned Offset = Result->Offset;
   2321       unsigned N = M.RedeclarationChains[Offset];
   2322       M.RedeclarationChains[Offset++] = 0; // Don't try to deserialize again
   2323       for (unsigned I = 0; I != N; ++I)
   2324         addToChain(Reader.GetLocalDecl(M, M.RedeclarationChains[Offset++]));
   2325     }
   2326 
   2327     bool visit(ModuleFile &M) {
   2328       // Visit each of the declarations.
   2329       for (unsigned I = 0, N = SearchDecls.size(); I != N; ++I)
   2330         searchForID(M, SearchDecls[I]);
   2331       return false;
   2332     }
   2333 
   2334     ArrayRef<Decl *> getChain() const {
   2335       return Chain;
   2336     }
   2337   };
   2338 }
   2339 
   2340 void ASTReader::loadPendingDeclChain(serialization::GlobalDeclID ID) {
   2341   Decl *D = GetDecl(ID);
   2342   Decl *CanonDecl = D->getCanonicalDecl();
   2343 
   2344   // Determine the set of declaration IDs we'll be searching for.
   2345   SmallVector<DeclID, 1> SearchDecls;
   2346   GlobalDeclID CanonID = 0;
   2347   if (D == CanonDecl) {
   2348     SearchDecls.push_back(ID); // Always first.
   2349     CanonID = ID;
   2350   }
   2351   MergedDeclsMap::iterator MergedPos = combineStoredMergedDecls(CanonDecl, ID);
   2352   if (MergedPos != MergedDecls.end())
   2353     SearchDecls.append(MergedPos->second.begin(), MergedPos->second.end());
   2354 
   2355   // Build up the list of redeclarations.
   2356   RedeclChainVisitor Visitor(*this, SearchDecls, RedeclsDeserialized, CanonID);
   2357   ModuleMgr.visitDepthFirst(&RedeclChainVisitor::visit, &Visitor);
   2358 
   2359   // Retrieve the chains.
   2360   ArrayRef<Decl *> Chain = Visitor.getChain();
   2361   if (Chain.empty())
   2362     return;
   2363 
   2364   // Hook up the chains.
   2365   Decl *MostRecent = CanonDecl->getMostRecentDecl();
   2366   for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
   2367     if (Chain[I] == CanonDecl)
   2368       continue;
   2369 
   2370     ASTDeclReader::attachPreviousDecl(Chain[I], MostRecent);
   2371     MostRecent = Chain[I];
   2372   }
   2373 
   2374   ASTDeclReader::attachLatestDecl(CanonDecl, MostRecent);
   2375 }
   2376 
   2377 namespace {
   2378   struct CompareObjCCategoriesInfo {
   2379     bool operator()(const ObjCCategoriesInfo &X, DeclID Y) {
   2380       return X.DefinitionID < Y;
   2381     }
   2382 
   2383     bool operator()(DeclID X, const ObjCCategoriesInfo &Y) {
   2384       return X < Y.DefinitionID;
   2385     }
   2386 
   2387     bool operator()(const ObjCCategoriesInfo &X,
   2388                     const ObjCCategoriesInfo &Y) {
   2389       return X.DefinitionID < Y.DefinitionID;
   2390     }
   2391     bool operator()(DeclID X, DeclID Y) {
   2392       return X < Y;
   2393     }
   2394   };
   2395 
   2396   /// \brief Given an ObjC interface, goes through the modules and links to the
   2397   /// interface all the categories for it.
   2398   class ObjCCategoriesVisitor {
   2399     ASTReader &Reader;
   2400     serialization::GlobalDeclID InterfaceID;
   2401     ObjCInterfaceDecl *Interface;
   2402     llvm::SmallPtrSet<ObjCCategoryDecl *, 16> &Deserialized;
   2403     unsigned PreviousGeneration;
   2404     ObjCCategoryDecl *Tail;
   2405     llvm::DenseMap<DeclarationName, ObjCCategoryDecl *> NameCategoryMap;
   2406 
   2407     void add(ObjCCategoryDecl *Cat) {
   2408       // Only process each category once.
   2409       if (!Deserialized.erase(Cat))
   2410         return;
   2411 
   2412       // Check for duplicate categories.
   2413       if (Cat->getDeclName()) {
   2414         ObjCCategoryDecl *&Existing = NameCategoryMap[Cat->getDeclName()];
   2415         if (Existing &&
   2416             Reader.getOwningModuleFile(Existing)
   2417                                           != Reader.getOwningModuleFile(Cat)) {
   2418           // FIXME: We should not warn for duplicates in diamond:
   2419           //
   2420           //   MT     //
   2421           //  /  \    //
   2422           // ML  MR   //
   2423           //  \  /    //
   2424           //   MB     //
   2425           //
   2426           // If there are duplicates in ML/MR, there will be warning when
   2427           // creating MB *and* when importing MB. We should not warn when
   2428           // importing.
   2429           Reader.Diag(Cat->getLocation(), diag::warn_dup_category_def)
   2430             << Interface->getDeclName() << Cat->getDeclName();
   2431           Reader.Diag(Existing->getLocation(), diag::note_previous_definition);
   2432         } else if (!Existing) {
   2433           // Record this category.
   2434           Existing = Cat;
   2435         }
   2436       }
   2437 
   2438       // Add this category to the end of the chain.
   2439       if (Tail)
   2440         ASTDeclReader::setNextObjCCategory(Tail, Cat);
   2441       else
   2442         Interface->setCategoryListRaw(Cat);
   2443       Tail = Cat;
   2444     }
   2445 
   2446   public:
   2447     ObjCCategoriesVisitor(ASTReader &Reader,
   2448                           serialization::GlobalDeclID InterfaceID,
   2449                           ObjCInterfaceDecl *Interface,
   2450                         llvm::SmallPtrSet<ObjCCategoryDecl *, 16> &Deserialized,
   2451                           unsigned PreviousGeneration)
   2452       : Reader(Reader), InterfaceID(InterfaceID), Interface(Interface),
   2453         Deserialized(Deserialized), PreviousGeneration(PreviousGeneration),
   2454         Tail(0)
   2455     {
   2456       // Populate the name -> category map with the set of known categories.
   2457       for (ObjCInterfaceDecl::known_categories_iterator
   2458              Cat = Interface->known_categories_begin(),
   2459              CatEnd = Interface->known_categories_end();
   2460            Cat != CatEnd; ++Cat) {
   2461         if (Cat->getDeclName())
   2462           NameCategoryMap[Cat->getDeclName()] = *Cat;
   2463 
   2464         // Keep track of the tail of the category list.
   2465         Tail = *Cat;
   2466       }
   2467     }
   2468 
   2469     static bool visit(ModuleFile &M, void *UserData) {
   2470       return static_cast<ObjCCategoriesVisitor *>(UserData)->visit(M);
   2471     }
   2472 
   2473     bool visit(ModuleFile &M) {
   2474       // If we've loaded all of the category information we care about from
   2475       // this module file, we're done.
   2476       if (M.Generation <= PreviousGeneration)
   2477         return true;
   2478 
   2479       // Map global ID of the definition down to the local ID used in this
   2480       // module file. If there is no such mapping, we'll find nothing here
   2481       // (or in any module it imports).
   2482       DeclID LocalID = Reader.mapGlobalIDToModuleFileGlobalID(M, InterfaceID);
   2483       if (!LocalID)
   2484         return true;
   2485 
   2486       // Perform a binary search to find the local redeclarations for this
   2487       // declaration (if any).
   2488       const ObjCCategoriesInfo *Result
   2489         = std::lower_bound(M.ObjCCategoriesMap,
   2490                            M.ObjCCategoriesMap + M.LocalNumObjCCategoriesInMap,
   2491                            LocalID, CompareObjCCategoriesInfo());
   2492       if (Result == M.ObjCCategoriesMap + M.LocalNumObjCCategoriesInMap ||
   2493           Result->DefinitionID != LocalID) {
   2494         // We didn't find anything. If the class definition is in this module
   2495         // file, then the module files it depends on cannot have any categories,
   2496         // so suppress further lookup.
   2497         return Reader.isDeclIDFromModule(InterfaceID, M);
   2498       }
   2499 
   2500       // We found something. Dig out all of the categories.
   2501       unsigned Offset = Result->Offset;
   2502       unsigned N = M.ObjCCategories[Offset];
   2503       M.ObjCCategories[Offset++] = 0; // Don't try to deserialize again
   2504       for (unsigned I = 0; I != N; ++I)
   2505         add(cast_or_null<ObjCCategoryDecl>(
   2506               Reader.GetLocalDecl(M, M.ObjCCategories[Offset++])));
   2507       return true;
   2508     }
   2509   };
   2510 }
   2511 
   2512 void ASTReader::loadObjCCategories(serialization::GlobalDeclID ID,
   2513                                    ObjCInterfaceDecl *D,
   2514                                    unsigned PreviousGeneration) {
   2515   ObjCCategoriesVisitor Visitor(*this, ID, D, CategoriesDeserialized,
   2516                                 PreviousGeneration);
   2517   ModuleMgr.visit(ObjCCategoriesVisitor::visit, &Visitor);
   2518 }
   2519 
   2520 void ASTDeclReader::UpdateDecl(Decl *D, ModuleFile &ModuleFile,
   2521                                const RecordData &Record) {
   2522   unsigned Idx = 0;
   2523   while (Idx < Record.size()) {
   2524     switch ((DeclUpdateKind)Record[Idx++]) {
   2525     case UPD_CXX_ADDED_IMPLICIT_MEMBER:
   2526       cast<CXXRecordDecl>(D)->addedMember(Reader.ReadDecl(ModuleFile, Record, Idx));
   2527       break;
   2528 
   2529     case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
   2530       // It will be added to the template's specializations set when loaded.
   2531       (void)Reader.ReadDecl(ModuleFile, Record, Idx);
   2532       break;
   2533 
   2534     case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE: {
   2535       NamespaceDecl *Anon
   2536         = Reader.ReadDeclAs<NamespaceDecl>(ModuleFile, Record, Idx);
   2537 
   2538       // Each module has its own anonymous namespace, which is disjoint from
   2539       // any other module's anonymous namespaces, so don't attach the anonymous
   2540       // namespace at all.
   2541       if (ModuleFile.Kind != MK_Module) {
   2542         if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(D))
   2543           TU->setAnonymousNamespace(Anon);
   2544         else
   2545           cast<NamespaceDecl>(D)->setAnonymousNamespace(Anon);
   2546       }
   2547       break;
   2548     }
   2549 
   2550     case UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER:
   2551       cast<VarDecl>(D)->getMemberSpecializationInfo()->setPointOfInstantiation(
   2552           Reader.ReadSourceLocation(ModuleFile, Record, Idx));
   2553       break;
   2554     }
   2555   }
   2556 }
   2557