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