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