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