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 "ASTCommon.h"
16 #include "clang/Serialization/ASTReader.h"
17 #include "clang/Sema/SemaDiagnostic.h"
18 #include "clang/AST/ASTConsumer.h"
19 #include "clang/AST/ASTContext.h"
20 #include "clang/AST/DeclVisitor.h"
21 #include "clang/AST/DeclGroup.h"
22 #include "clang/AST/DeclCXX.h"
23 #include "clang/AST/DeclTemplate.h"
24 #include "clang/AST/Expr.h"
25 using namespace clang;
26 using namespace clang::serialization;
27 
28 //===----------------------------------------------------------------------===//
29 // Declaration deserialization
30 //===----------------------------------------------------------------------===//
31 
32 namespace clang {
33   class ASTDeclReader : public DeclVisitor<ASTDeclReader, void> {
34     ASTReader &Reader;
35     Module &F;
36     llvm::BitstreamCursor &Cursor;
37     const DeclID ThisDeclID;
38     const unsigned RawLocation;
39     typedef ASTReader::RecordData RecordData;
40     const RecordData &Record;
41     unsigned &Idx;
42     TypeID TypeIDForTypeDecl;
43 
44     DeclID DeclContextIDForTemplateParmDecl;
45     DeclID LexicalDeclContextIDForTemplateParmDecl;
46 
47     uint64_t GetCurrentCursorOffset();
48 
49     SourceLocation ReadSourceLocation(const RecordData &R, unsigned &I) {
50       return Reader.ReadSourceLocation(F, R, I);
51     }
52 
53     SourceRange ReadSourceRange(const RecordData &R, unsigned &I) {
54       return Reader.ReadSourceRange(F, R, I);
55     }
56 
57     TypeSourceInfo *GetTypeSourceInfo(const RecordData &R, unsigned &I) {
58       return Reader.GetTypeSourceInfo(F, R, I);
59     }
60 
61     serialization::DeclID ReadDeclID(const RecordData &R, unsigned &I) {
62       return Reader.ReadDeclID(F, R, I);
63     }
64 
65     Decl *ReadDecl(const RecordData &R, unsigned &I) {
66       return Reader.ReadDecl(F, R, I);
67     }
68 
69     template<typename T>
70     T *ReadDeclAs(const RecordData &R, unsigned &I) {
71       return Reader.ReadDeclAs<T>(F, R, I);
72     }
73 
74     void ReadQualifierInfo(QualifierInfo &Info,
75                            const RecordData &R, unsigned &I) {
76       Reader.ReadQualifierInfo(F, Info, R, I);
77     }
78 
79     void ReadDeclarationNameLoc(DeclarationNameLoc &DNLoc, DeclarationName Name,
80                                 const RecordData &R, unsigned &I) {
81       Reader.ReadDeclarationNameLoc(F, DNLoc, Name, R, I);
82     }
83 
84     void ReadDeclarationNameInfo(DeclarationNameInfo &NameInfo,
85                                 const RecordData &R, unsigned &I) {
86       Reader.ReadDeclarationNameInfo(F, NameInfo, R, I);
87     }
88 
89     void ReadCXXDefinitionData(struct CXXRecordDecl::DefinitionData &Data,
90                                const RecordData &R, unsigned &I);
91 
92     void InitializeCXXDefinitionData(CXXRecordDecl *D,
93                                      CXXRecordDecl *DefinitionDecl,
94                                      const RecordData &Record, unsigned &Idx);
95   public:
96     ASTDeclReader(ASTReader &Reader, Module &F,
97                   llvm::BitstreamCursor &Cursor, DeclID thisDeclID,
98                   unsigned RawLocation,
99                   const RecordData &Record, unsigned &Idx)
100       : Reader(Reader), F(F), Cursor(Cursor), ThisDeclID(thisDeclID),
101         RawLocation(RawLocation), Record(Record), Idx(Idx),
102         TypeIDForTypeDecl(0) { }
103 
104     static void attachPreviousDecl(Decl *D, Decl *previous);
105 
106     void Visit(Decl *D);
107 
108     void UpdateDecl(Decl *D, Module &Module,
109                     const RecordData &Record);
110 
111     static void setNextObjCCategory(ObjCCategoryDecl *Cat,
112                                     ObjCCategoryDecl *Next) {
113       Cat->NextClassCategory = Next;
114     }
115 
116     void VisitDecl(Decl *D);
117     void VisitTranslationUnitDecl(TranslationUnitDecl *TU);
118     void VisitNamedDecl(NamedDecl *ND);
119     void VisitLabelDecl(LabelDecl *LD);
120     void VisitNamespaceDecl(NamespaceDecl *D);
121     void VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
122     void VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
123     void VisitTypeDecl(TypeDecl *TD);
124     void VisitTypedefDecl(TypedefDecl *TD);
125     void VisitTypeAliasDecl(TypeAliasDecl *TD);
126     void VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
127     void VisitTagDecl(TagDecl *TD);
128     void VisitEnumDecl(EnumDecl *ED);
129     void VisitRecordDecl(RecordDecl *RD);
130     void VisitCXXRecordDecl(CXXRecordDecl *D);
131     void VisitClassTemplateSpecializationDecl(
132                                             ClassTemplateSpecializationDecl *D);
133     void VisitClassTemplatePartialSpecializationDecl(
134                                      ClassTemplatePartialSpecializationDecl *D);
135     void VisitClassScopeFunctionSpecializationDecl(
136                                        ClassScopeFunctionSpecializationDecl *D);
137     void VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
138     void VisitValueDecl(ValueDecl *VD);
139     void VisitEnumConstantDecl(EnumConstantDecl *ECD);
140     void VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
141     void VisitDeclaratorDecl(DeclaratorDecl *DD);
142     void VisitFunctionDecl(FunctionDecl *FD);
143     void VisitCXXMethodDecl(CXXMethodDecl *D);
144     void VisitCXXConstructorDecl(CXXConstructorDecl *D);
145     void VisitCXXDestructorDecl(CXXDestructorDecl *D);
146     void VisitCXXConversionDecl(CXXConversionDecl *D);
147     void VisitFieldDecl(FieldDecl *FD);
148     void VisitIndirectFieldDecl(IndirectFieldDecl *FD);
149     void VisitVarDecl(VarDecl *VD);
150     void VisitImplicitParamDecl(ImplicitParamDecl *PD);
151     void VisitParmVarDecl(ParmVarDecl *PD);
152     void VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
153     void VisitTemplateDecl(TemplateDecl *D);
154     void VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D);
155     void VisitClassTemplateDecl(ClassTemplateDecl *D);
156     void VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
157     void VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
158     void VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D);
159     void VisitUsingDecl(UsingDecl *D);
160     void VisitUsingShadowDecl(UsingShadowDecl *D);
161     void VisitLinkageSpecDecl(LinkageSpecDecl *D);
162     void VisitFileScopeAsmDecl(FileScopeAsmDecl *AD);
163     void VisitAccessSpecDecl(AccessSpecDecl *D);
164     void VisitFriendDecl(FriendDecl *D);
165     void VisitFriendTemplateDecl(FriendTemplateDecl *D);
166     void VisitStaticAssertDecl(StaticAssertDecl *D);
167     void VisitBlockDecl(BlockDecl *BD);
168 
169     std::pair<uint64_t, uint64_t> VisitDeclContext(DeclContext *DC);
170     template <typename T> void VisitRedeclarable(Redeclarable<T> *D);
171 
172     // FIXME: Reorder according to DeclNodes.td?
173     void VisitObjCMethodDecl(ObjCMethodDecl *D);
174     void VisitObjCContainerDecl(ObjCContainerDecl *D);
175     void VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
176     void VisitObjCIvarDecl(ObjCIvarDecl *D);
177     void VisitObjCProtocolDecl(ObjCProtocolDecl *D);
178     void VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D);
179     void VisitObjCClassDecl(ObjCClassDecl *D);
180     void VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
181     void VisitObjCCategoryDecl(ObjCCategoryDecl *D);
182     void VisitObjCImplDecl(ObjCImplDecl *D);
183     void VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
184     void VisitObjCImplementationDecl(ObjCImplementationDecl *D);
185     void VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *D);
186     void VisitObjCPropertyDecl(ObjCPropertyDecl *D);
187     void VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D);
188   };
189 }
190 
191 uint64_t ASTDeclReader::GetCurrentCursorOffset() {
192   return F.DeclsCursor.GetCurrentBitNo() + F.GlobalBitOffset;
193 }
194 
195 void ASTDeclReader::Visit(Decl *D) {
196   DeclVisitor<ASTDeclReader, void>::Visit(D);
197 
198   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
199     if (DD->DeclInfo) {
200       DeclaratorDecl::ExtInfo *Info =
201           DD->DeclInfo.get<DeclaratorDecl::ExtInfo *>();
202       Info->TInfo =
203           GetTypeSourceInfo(Record, Idx);
204     }
205     else {
206       DD->DeclInfo = GetTypeSourceInfo(Record, Idx);
207     }
208   }
209 
210   if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
211     // if we have a fully initialized TypeDecl, we can safely read its type now.
212     TD->setTypeForDecl(Reader.GetType(TypeIDForTypeDecl).getTypePtrOrNull());
213   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
214     // FunctionDecl's body was written last after all other Stmts/Exprs.
215     if (Record[Idx++])
216       FD->setLazyBody(GetCurrentCursorOffset());
217   } else if (D->isTemplateParameter()) {
218     // If we have a fully initialized template parameter, we can now
219     // set its DeclContext.
220     D->setDeclContext(
221           cast_or_null<DeclContext>(
222                             Reader.GetDecl(DeclContextIDForTemplateParmDecl)));
223     D->setLexicalDeclContext(
224           cast_or_null<DeclContext>(
225                       Reader.GetDecl(LexicalDeclContextIDForTemplateParmDecl)));
226   }
227 }
228 
229 void ASTDeclReader::VisitDecl(Decl *D) {
230   if (D->isTemplateParameter()) {
231     // We don't want to deserialize the DeclContext of a template
232     // parameter immediately, because the template parameter might be
233     // used in the formulation of its DeclContext. Use the translation
234     // unit DeclContext as a placeholder.
235     DeclContextIDForTemplateParmDecl = ReadDeclID(Record, Idx);
236     LexicalDeclContextIDForTemplateParmDecl = ReadDeclID(Record, Idx);
237     D->setDeclContext(Reader.getContext().getTranslationUnitDecl());
238   } else {
239     D->setDeclContext(ReadDeclAs<DeclContext>(Record, Idx));
240     D->setLexicalDeclContext(ReadDeclAs<DeclContext>(Record, Idx));
241   }
242   D->setLocation(Reader.ReadSourceLocation(F, RawLocation));
243   D->setInvalidDecl(Record[Idx++]);
244   if (Record[Idx++]) { // hasAttrs
245     AttrVec Attrs;
246     Reader.ReadAttributes(F, Attrs, Record, Idx);
247     D->setAttrs(Attrs);
248   }
249   D->setImplicit(Record[Idx++]);
250   D->setUsed(Record[Idx++]);
251   D->setReferenced(Record[Idx++]);
252   D->setAccess((AccessSpecifier)Record[Idx++]);
253   D->FromASTFile = true;
254   D->ModulePrivate = Record[Idx++];
255 }
256 
257 void ASTDeclReader::VisitTranslationUnitDecl(TranslationUnitDecl *TU) {
258   llvm_unreachable("Translation units are not serialized");
259 }
260 
261 void ASTDeclReader::VisitNamedDecl(NamedDecl *ND) {
262   VisitDecl(ND);
263   ND->setDeclName(Reader.ReadDeclarationName(F, Record, Idx));
264 }
265 
266 void ASTDeclReader::VisitTypeDecl(TypeDecl *TD) {
267   VisitNamedDecl(TD);
268   TD->setLocStart(ReadSourceLocation(Record, Idx));
269   // Delay type reading until after we have fully initialized the decl.
270   TypeIDForTypeDecl = Reader.getGlobalTypeID(F, Record[Idx++]);
271 }
272 
273 void ASTDeclReader::VisitTypedefDecl(TypedefDecl *TD) {
274   VisitTypeDecl(TD);
275   TD->setTypeSourceInfo(GetTypeSourceInfo(Record, Idx));
276 }
277 
278 void ASTDeclReader::VisitTypeAliasDecl(TypeAliasDecl *TD) {
279   VisitTypeDecl(TD);
280   TD->setTypeSourceInfo(GetTypeSourceInfo(Record, Idx));
281 }
282 
283 void ASTDeclReader::VisitTagDecl(TagDecl *TD) {
284   VisitRedeclarable(TD);
285   VisitTypeDecl(TD);
286   TD->IdentifierNamespace = Record[Idx++];
287   TD->setTagKind((TagDecl::TagKind)Record[Idx++]);
288   TD->setCompleteDefinition(Record[Idx++]);
289   TD->setEmbeddedInDeclarator(Record[Idx++]);
290   TD->setFreeStanding(Record[Idx++]);
291   TD->setRBraceLoc(ReadSourceLocation(Record, Idx));
292   if (Record[Idx++]) { // hasExtInfo
293     TagDecl::ExtInfo *Info = new (Reader.getContext()) TagDecl::ExtInfo();
294     ReadQualifierInfo(*Info, Record, Idx);
295     TD->TypedefNameDeclOrQualifier = Info;
296   } else
297     TD->setTypedefNameForAnonDecl(ReadDeclAs<TypedefNameDecl>(Record, Idx));
298 }
299 
300 void ASTDeclReader::VisitEnumDecl(EnumDecl *ED) {
301   VisitTagDecl(ED);
302   if (TypeSourceInfo *TI = Reader.GetTypeSourceInfo(F, Record, Idx))
303     ED->setIntegerTypeSourceInfo(TI);
304   else
305     ED->setIntegerType(Reader.readType(F, Record, Idx));
306   ED->setPromotionType(Reader.readType(F, Record, Idx));
307   ED->setNumPositiveBits(Record[Idx++]);
308   ED->setNumNegativeBits(Record[Idx++]);
309   ED->IsScoped = Record[Idx++];
310   ED->IsScopedUsingClassTag = Record[Idx++];
311   ED->IsFixed = Record[Idx++];
312   ED->setInstantiationOfMemberEnum(ReadDeclAs<EnumDecl>(Record, Idx));
313 }
314 
315 void ASTDeclReader::VisitRecordDecl(RecordDecl *RD) {
316   VisitTagDecl(RD);
317   RD->setHasFlexibleArrayMember(Record[Idx++]);
318   RD->setAnonymousStructOrUnion(Record[Idx++]);
319   RD->setHasObjectMember(Record[Idx++]);
320 }
321 
322 void ASTDeclReader::VisitValueDecl(ValueDecl *VD) {
323   VisitNamedDecl(VD);
324   VD->setType(Reader.readType(F, Record, Idx));
325 }
326 
327 void ASTDeclReader::VisitEnumConstantDecl(EnumConstantDecl *ECD) {
328   VisitValueDecl(ECD);
329   if (Record[Idx++])
330     ECD->setInitExpr(Reader.ReadExpr(F));
331   ECD->setInitVal(Reader.ReadAPSInt(Record, Idx));
332 }
333 
334 void ASTDeclReader::VisitDeclaratorDecl(DeclaratorDecl *DD) {
335   VisitValueDecl(DD);
336   DD->setInnerLocStart(ReadSourceLocation(Record, Idx));
337   if (Record[Idx++]) { // hasExtInfo
338     DeclaratorDecl::ExtInfo *Info
339         = new (Reader.getContext()) DeclaratorDecl::ExtInfo();
340     ReadQualifierInfo(*Info, Record, Idx);
341     DD->DeclInfo = Info;
342   }
343 }
344 
345 void ASTDeclReader::VisitFunctionDecl(FunctionDecl *FD) {
346   VisitRedeclarable(FD);
347   VisitDeclaratorDecl(FD);
348 
349   ReadDeclarationNameLoc(FD->DNLoc, FD->getDeclName(), Record, Idx);
350   FD->IdentifierNamespace = Record[Idx++];
351   switch ((FunctionDecl::TemplatedKind)Record[Idx++]) {
352   default: llvm_unreachable("Unhandled TemplatedKind!");
353   case FunctionDecl::TK_NonTemplate:
354     break;
355   case FunctionDecl::TK_FunctionTemplate:
356     FD->setDescribedFunctionTemplate(ReadDeclAs<FunctionTemplateDecl>(Record,
357                                                                       Idx));
358     break;
359   case FunctionDecl::TK_MemberSpecialization: {
360     FunctionDecl *InstFD = ReadDeclAs<FunctionDecl>(Record, Idx);
361     TemplateSpecializationKind TSK = (TemplateSpecializationKind)Record[Idx++];
362     SourceLocation POI = ReadSourceLocation(Record, Idx);
363     FD->setInstantiationOfMemberFunction(Reader.getContext(), InstFD, TSK);
364     FD->getMemberSpecializationInfo()->setPointOfInstantiation(POI);
365     break;
366   }
367   case FunctionDecl::TK_FunctionTemplateSpecialization: {
368     FunctionTemplateDecl *Template = ReadDeclAs<FunctionTemplateDecl>(Record,
369                                                                       Idx);
370     TemplateSpecializationKind TSK = (TemplateSpecializationKind)Record[Idx++];
371 
372     // Template arguments.
373     SmallVector<TemplateArgument, 8> TemplArgs;
374     Reader.ReadTemplateArgumentList(TemplArgs, F, Record, Idx);
375 
376     // Template args as written.
377     SmallVector<TemplateArgumentLoc, 8> TemplArgLocs;
378     SourceLocation LAngleLoc, RAngleLoc;
379     bool HasTemplateArgumentsAsWritten = Record[Idx++];
380     if (HasTemplateArgumentsAsWritten) {
381       unsigned NumTemplateArgLocs = Record[Idx++];
382       TemplArgLocs.reserve(NumTemplateArgLocs);
383       for (unsigned i=0; i != NumTemplateArgLocs; ++i)
384         TemplArgLocs.push_back(
385             Reader.ReadTemplateArgumentLoc(F, Record, Idx));
386 
387       LAngleLoc = ReadSourceLocation(Record, Idx);
388       RAngleLoc = ReadSourceLocation(Record, Idx);
389     }
390 
391     SourceLocation POI = ReadSourceLocation(Record, Idx);
392 
393     ASTContext &C = Reader.getContext();
394     TemplateArgumentList *TemplArgList
395       = TemplateArgumentList::CreateCopy(C, TemplArgs.data(), TemplArgs.size());
396     TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
397     for (unsigned i=0, e = TemplArgLocs.size(); i != e; ++i)
398       TemplArgsInfo.addArgument(TemplArgLocs[i]);
399     FunctionTemplateSpecializationInfo *FTInfo
400         = FunctionTemplateSpecializationInfo::Create(C, FD, Template, TSK,
401                                                      TemplArgList,
402                              HasTemplateArgumentsAsWritten ? &TemplArgsInfo : 0,
403                                                      POI);
404     FD->TemplateOrSpecialization = FTInfo;
405 
406     if (FD->isCanonicalDecl()) { // if canonical add to template's set.
407       // The template that contains the specializations set. It's not safe to
408       // use getCanonicalDecl on Template since it may still be initializing.
409       FunctionTemplateDecl *CanonTemplate
410         = ReadDeclAs<FunctionTemplateDecl>(Record, Idx);
411       // Get the InsertPos by FindNodeOrInsertPos() instead of calling
412       // InsertNode(FTInfo) directly to avoid the getASTContext() call in
413       // FunctionTemplateSpecializationInfo's Profile().
414       // We avoid getASTContext because a decl in the parent hierarchy may
415       // be initializing.
416       llvm::FoldingSetNodeID ID;
417       FunctionTemplateSpecializationInfo::Profile(ID, TemplArgs.data(),
418                                                   TemplArgs.size(), C);
419       void *InsertPos = 0;
420       CanonTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
421       assert(InsertPos && "Another specialization already inserted!");
422       CanonTemplate->getSpecializations().InsertNode(FTInfo, InsertPos);
423     }
424     break;
425   }
426   case FunctionDecl::TK_DependentFunctionTemplateSpecialization: {
427     // Templates.
428     UnresolvedSet<8> TemplDecls;
429     unsigned NumTemplates = Record[Idx++];
430     while (NumTemplates--)
431       TemplDecls.addDecl(ReadDeclAs<NamedDecl>(Record, Idx));
432 
433     // Templates args.
434     TemplateArgumentListInfo TemplArgs;
435     unsigned NumArgs = Record[Idx++];
436     while (NumArgs--)
437       TemplArgs.addArgument(Reader.ReadTemplateArgumentLoc(F, Record, Idx));
438     TemplArgs.setLAngleLoc(ReadSourceLocation(Record, Idx));
439     TemplArgs.setRAngleLoc(ReadSourceLocation(Record, Idx));
440 
441     FD->setDependentTemplateSpecialization(Reader.getContext(),
442                                            TemplDecls, TemplArgs);
443     break;
444   }
445   }
446 
447   // FunctionDecl's body is handled last at ASTDeclReader::Visit,
448   // after everything else is read.
449 
450   FD->SClass = (StorageClass)Record[Idx++];
451   FD->SClassAsWritten = (StorageClass)Record[Idx++];
452   FD->IsInline = Record[Idx++];
453   FD->IsInlineSpecified = Record[Idx++];
454   FD->IsVirtualAsWritten = Record[Idx++];
455   FD->IsPure = Record[Idx++];
456   FD->HasInheritedPrototype = Record[Idx++];
457   FD->HasWrittenPrototype = Record[Idx++];
458   FD->IsDeleted = Record[Idx++];
459   FD->IsTrivial = Record[Idx++];
460   FD->IsDefaulted = Record[Idx++];
461   FD->IsExplicitlyDefaulted = Record[Idx++];
462   FD->HasImplicitReturnZero = Record[Idx++];
463   FD->IsConstexpr = Record[Idx++];
464   FD->EndRangeLoc = ReadSourceLocation(Record, Idx);
465 
466   // Read in the parameters.
467   unsigned NumParams = Record[Idx++];
468   SmallVector<ParmVarDecl *, 16> Params;
469   Params.reserve(NumParams);
470   for (unsigned I = 0; I != NumParams; ++I)
471     Params.push_back(ReadDeclAs<ParmVarDecl>(Record, Idx));
472   FD->setParams(Reader.getContext(), Params);
473 }
474 
475 void ASTDeclReader::VisitObjCMethodDecl(ObjCMethodDecl *MD) {
476   VisitNamedDecl(MD);
477   if (Record[Idx++]) {
478     // In practice, this won't be executed (since method definitions
479     // don't occur in header files).
480     MD->setBody(Reader.ReadStmt(F));
481     MD->setSelfDecl(ReadDeclAs<ImplicitParamDecl>(Record, Idx));
482     MD->setCmdDecl(ReadDeclAs<ImplicitParamDecl>(Record, Idx));
483   }
484   MD->setInstanceMethod(Record[Idx++]);
485   MD->setVariadic(Record[Idx++]);
486   MD->setSynthesized(Record[Idx++]);
487   MD->setDefined(Record[Idx++]);
488 
489   MD->IsRedeclaration = Record[Idx++];
490   MD->HasRedeclaration = Record[Idx++];
491   if (MD->HasRedeclaration)
492     Reader.getContext().setObjCMethodRedeclaration(MD,
493                                        ReadDeclAs<ObjCMethodDecl>(Record, Idx));
494 
495   MD->setDeclImplementation((ObjCMethodDecl::ImplementationControl)Record[Idx++]);
496   MD->setObjCDeclQualifier((Decl::ObjCDeclQualifier)Record[Idx++]);
497   MD->SetRelatedResultType(Record[Idx++]);
498   MD->setResultType(Reader.readType(F, Record, Idx));
499   MD->setResultTypeSourceInfo(GetTypeSourceInfo(Record, Idx));
500   MD->setEndLoc(ReadSourceLocation(Record, Idx));
501   unsigned NumParams = Record[Idx++];
502   SmallVector<ParmVarDecl *, 16> Params;
503   Params.reserve(NumParams);
504   for (unsigned I = 0; I != NumParams; ++I)
505     Params.push_back(ReadDeclAs<ParmVarDecl>(Record, Idx));
506 
507   MD->SelLocsKind = Record[Idx++];
508   unsigned NumStoredSelLocs = Record[Idx++];
509   SmallVector<SourceLocation, 16> SelLocs;
510   SelLocs.reserve(NumStoredSelLocs);
511   for (unsigned i = 0; i != NumStoredSelLocs; ++i)
512     SelLocs.push_back(ReadSourceLocation(Record, Idx));
513 
514   MD->setParamsAndSelLocs(Reader.getContext(), Params, SelLocs);
515 }
516 
517 void ASTDeclReader::VisitObjCContainerDecl(ObjCContainerDecl *CD) {
518   VisitNamedDecl(CD);
519   CD->setAtStartLoc(ReadSourceLocation(Record, Idx));
520   CD->setAtEndRange(ReadSourceRange(Record, Idx));
521 }
522 
523 void ASTDeclReader::VisitObjCInterfaceDecl(ObjCInterfaceDecl *ID) {
524   VisitObjCContainerDecl(ID);
525   ID->setTypeForDecl(Reader.readType(F, Record, Idx).getTypePtrOrNull());
526   ID->setSuperClass(ReadDeclAs<ObjCInterfaceDecl>(Record, Idx));
527 
528   // Read the directly referenced protocols and their SourceLocations.
529   unsigned NumProtocols = Record[Idx++];
530   SmallVector<ObjCProtocolDecl *, 16> Protocols;
531   Protocols.reserve(NumProtocols);
532   for (unsigned I = 0; I != NumProtocols; ++I)
533     Protocols.push_back(ReadDeclAs<ObjCProtocolDecl>(Record, Idx));
534   SmallVector<SourceLocation, 16> ProtoLocs;
535   ProtoLocs.reserve(NumProtocols);
536   for (unsigned I = 0; I != NumProtocols; ++I)
537     ProtoLocs.push_back(ReadSourceLocation(Record, Idx));
538   ID->setProtocolList(Protocols.data(), NumProtocols, ProtoLocs.data(),
539                       Reader.getContext());
540 
541   // Read the transitive closure of protocols referenced by this class.
542   NumProtocols = Record[Idx++];
543   Protocols.clear();
544   Protocols.reserve(NumProtocols);
545   for (unsigned I = 0; I != NumProtocols; ++I)
546     Protocols.push_back(ReadDeclAs<ObjCProtocolDecl>(Record, Idx));
547   ID->AllReferencedProtocols.set(Protocols.data(), NumProtocols,
548                                  Reader.getContext());
549 
550   // Read the ivars.
551   unsigned NumIvars = Record[Idx++];
552   SmallVector<ObjCIvarDecl *, 16> IVars;
553   IVars.reserve(NumIvars);
554   for (unsigned I = 0; I != NumIvars; ++I)
555     IVars.push_back(ReadDeclAs<ObjCIvarDecl>(Record, Idx));
556   ID->setCategoryList(ReadDeclAs<ObjCCategoryDecl>(Record, Idx));
557 
558   // We will rebuild this list lazily.
559   ID->setIvarList(0);
560   ID->InitiallyForwardDecl = Record[Idx++];
561   ID->ForwardDecl = Record[Idx++];
562   ID->setSuperClassLoc(ReadSourceLocation(Record, Idx));
563   ID->setLocEnd(ReadSourceLocation(Record, Idx));
564 }
565 
566 void ASTDeclReader::VisitObjCIvarDecl(ObjCIvarDecl *IVD) {
567   VisitFieldDecl(IVD);
568   IVD->setAccessControl((ObjCIvarDecl::AccessControl)Record[Idx++]);
569   // This field will be built lazily.
570   IVD->setNextIvar(0);
571   bool synth = Record[Idx++];
572   IVD->setSynthesize(synth);
573 }
574 
575 void ASTDeclReader::VisitObjCProtocolDecl(ObjCProtocolDecl *PD) {
576   VisitObjCContainerDecl(PD);
577   PD->InitiallyForwardDecl = Record[Idx++];
578   PD->isForwardProtoDecl = Record[Idx++];
579   PD->setLocEnd(ReadSourceLocation(Record, Idx));
580   unsigned NumProtoRefs = Record[Idx++];
581   SmallVector<ObjCProtocolDecl *, 16> ProtoRefs;
582   ProtoRefs.reserve(NumProtoRefs);
583   for (unsigned I = 0; I != NumProtoRefs; ++I)
584     ProtoRefs.push_back(ReadDeclAs<ObjCProtocolDecl>(Record, Idx));
585   SmallVector<SourceLocation, 16> ProtoLocs;
586   ProtoLocs.reserve(NumProtoRefs);
587   for (unsigned I = 0; I != NumProtoRefs; ++I)
588     ProtoLocs.push_back(ReadSourceLocation(Record, Idx));
589   PD->setProtocolList(ProtoRefs.data(), NumProtoRefs, ProtoLocs.data(),
590                       Reader.getContext());
591 }
592 
593 void ASTDeclReader::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *FD) {
594   VisitFieldDecl(FD);
595 }
596 
597 void ASTDeclReader::VisitObjCClassDecl(ObjCClassDecl *CD) {
598   VisitDecl(CD);
599   ObjCInterfaceDecl *ClassRef = ReadDeclAs<ObjCInterfaceDecl>(Record, Idx);
600   SourceLocation SLoc = ReadSourceLocation(Record, Idx);
601   CD->setClass(Reader.getContext(), ClassRef, SLoc);
602 }
603 
604 void ASTDeclReader::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *FPD) {
605   VisitDecl(FPD);
606   unsigned NumProtoRefs = Record[Idx++];
607   SmallVector<ObjCProtocolDecl *, 16> ProtoRefs;
608   ProtoRefs.reserve(NumProtoRefs);
609   for (unsigned I = 0; I != NumProtoRefs; ++I)
610     ProtoRefs.push_back(ReadDeclAs<ObjCProtocolDecl>(Record, Idx));
611   SmallVector<SourceLocation, 16> ProtoLocs;
612   ProtoLocs.reserve(NumProtoRefs);
613   for (unsigned I = 0; I != NumProtoRefs; ++I)
614     ProtoLocs.push_back(ReadSourceLocation(Record, Idx));
615   FPD->setProtocolList(ProtoRefs.data(), NumProtoRefs, ProtoLocs.data(),
616                        Reader.getContext());
617 }
618 
619 void ASTDeclReader::VisitObjCCategoryDecl(ObjCCategoryDecl *CD) {
620   VisitObjCContainerDecl(CD);
621   CD->ClassInterface = ReadDeclAs<ObjCInterfaceDecl>(Record, Idx);
622   unsigned NumProtoRefs = Record[Idx++];
623   SmallVector<ObjCProtocolDecl *, 16> ProtoRefs;
624   ProtoRefs.reserve(NumProtoRefs);
625   for (unsigned I = 0; I != NumProtoRefs; ++I)
626     ProtoRefs.push_back(ReadDeclAs<ObjCProtocolDecl>(Record, Idx));
627   SmallVector<SourceLocation, 16> ProtoLocs;
628   ProtoLocs.reserve(NumProtoRefs);
629   for (unsigned I = 0; I != NumProtoRefs; ++I)
630     ProtoLocs.push_back(ReadSourceLocation(Record, Idx));
631   CD->setProtocolList(ProtoRefs.data(), NumProtoRefs, ProtoLocs.data(),
632                       Reader.getContext());
633   CD->NextClassCategory = ReadDeclAs<ObjCCategoryDecl>(Record, Idx);
634   CD->setHasSynthBitfield(Record[Idx++]);
635   CD->setCategoryNameLoc(ReadSourceLocation(Record, Idx));
636 }
637 
638 void ASTDeclReader::VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *CAD) {
639   VisitNamedDecl(CAD);
640   CAD->setClassInterface(ReadDeclAs<ObjCInterfaceDecl>(Record, Idx));
641 }
642 
643 void ASTDeclReader::VisitObjCPropertyDecl(ObjCPropertyDecl *D) {
644   VisitNamedDecl(D);
645   D->setAtLoc(ReadSourceLocation(Record, Idx));
646   D->setType(GetTypeSourceInfo(Record, Idx));
647   // FIXME: stable encoding
648   D->setPropertyAttributes(
649                       (ObjCPropertyDecl::PropertyAttributeKind)Record[Idx++]);
650   D->setPropertyAttributesAsWritten(
651                       (ObjCPropertyDecl::PropertyAttributeKind)Record[Idx++]);
652   // FIXME: stable encoding
653   D->setPropertyImplementation(
654                             (ObjCPropertyDecl::PropertyControl)Record[Idx++]);
655   D->setGetterName(Reader.ReadDeclarationName(F,Record, Idx).getObjCSelector());
656   D->setSetterName(Reader.ReadDeclarationName(F,Record, Idx).getObjCSelector());
657   D->setGetterMethodDecl(ReadDeclAs<ObjCMethodDecl>(Record, Idx));
658   D->setSetterMethodDecl(ReadDeclAs<ObjCMethodDecl>(Record, Idx));
659   D->setPropertyIvarDecl(ReadDeclAs<ObjCIvarDecl>(Record, Idx));
660 }
661 
662 void ASTDeclReader::VisitObjCImplDecl(ObjCImplDecl *D) {
663   VisitObjCContainerDecl(D);
664   D->setClassInterface(ReadDeclAs<ObjCInterfaceDecl>(Record, Idx));
665 }
666 
667 void ASTDeclReader::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
668   VisitObjCImplDecl(D);
669   D->setIdentifier(Reader.GetIdentifierInfo(F, Record, Idx));
670 }
671 
672 void ASTDeclReader::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
673   VisitObjCImplDecl(D);
674   D->setSuperClass(ReadDeclAs<ObjCInterfaceDecl>(Record, Idx));
675   llvm::tie(D->IvarInitializers, D->NumIvarInitializers)
676       = Reader.ReadCXXCtorInitializers(F, Record, Idx);
677   D->setHasSynthBitfield(Record[Idx++]);
678 }
679 
680 
681 void ASTDeclReader::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) {
682   VisitDecl(D);
683   D->setAtLoc(ReadSourceLocation(Record, Idx));
684   D->setPropertyDecl(ReadDeclAs<ObjCPropertyDecl>(Record, Idx));
685   D->PropertyIvarDecl = ReadDeclAs<ObjCIvarDecl>(Record, Idx);
686   D->IvarLoc = ReadSourceLocation(Record, Idx);
687   D->setGetterCXXConstructor(Reader.ReadExpr(F));
688   D->setSetterCXXAssignment(Reader.ReadExpr(F));
689 }
690 
691 void ASTDeclReader::VisitFieldDecl(FieldDecl *FD) {
692   VisitDeclaratorDecl(FD);
693   FD->setMutable(Record[Idx++]);
694   int BitWidthOrInitializer = Record[Idx++];
695   if (BitWidthOrInitializer == 1)
696     FD->setBitWidth(Reader.ReadExpr(F));
697   else if (BitWidthOrInitializer == 2)
698     FD->setInClassInitializer(Reader.ReadExpr(F));
699   if (!FD->getDeclName()) {
700     if (FieldDecl *Tmpl = ReadDeclAs<FieldDecl>(Record, Idx))
701       Reader.getContext().setInstantiatedFromUnnamedFieldDecl(FD, Tmpl);
702   }
703 }
704 
705 void ASTDeclReader::VisitIndirectFieldDecl(IndirectFieldDecl *FD) {
706   VisitValueDecl(FD);
707 
708   FD->ChainingSize = Record[Idx++];
709   assert(FD->ChainingSize >= 2 && "Anonymous chaining must be >= 2");
710   FD->Chaining = new (Reader.getContext())NamedDecl*[FD->ChainingSize];
711 
712   for (unsigned I = 0; I != FD->ChainingSize; ++I)
713     FD->Chaining[I] = ReadDeclAs<NamedDecl>(Record, Idx);
714 }
715 
716 void ASTDeclReader::VisitVarDecl(VarDecl *VD) {
717   VisitRedeclarable(VD);
718   VisitDeclaratorDecl(VD);
719   VD->VarDeclBits.SClass = (StorageClass)Record[Idx++];
720   VD->VarDeclBits.SClassAsWritten = (StorageClass)Record[Idx++];
721   VD->VarDeclBits.ThreadSpecified = Record[Idx++];
722   VD->VarDeclBits.HasCXXDirectInit = Record[Idx++];
723   VD->VarDeclBits.ExceptionVar = Record[Idx++];
724   VD->VarDeclBits.NRVOVariable = Record[Idx++];
725   VD->VarDeclBits.CXXForRangeDecl = Record[Idx++];
726   VD->VarDeclBits.ARCPseudoStrong = Record[Idx++];
727   if (Record[Idx++])
728     VD->setInit(Reader.ReadExpr(F));
729 
730   if (Record[Idx++]) { // HasMemberSpecializationInfo.
731     VarDecl *Tmpl = ReadDeclAs<VarDecl>(Record, Idx);
732     TemplateSpecializationKind TSK = (TemplateSpecializationKind)Record[Idx++];
733     SourceLocation POI = ReadSourceLocation(Record, Idx);
734     Reader.getContext().setInstantiatedFromStaticDataMember(VD, Tmpl, TSK,POI);
735   }
736 }
737 
738 void ASTDeclReader::VisitImplicitParamDecl(ImplicitParamDecl *PD) {
739   VisitVarDecl(PD);
740 }
741 
742 void ASTDeclReader::VisitParmVarDecl(ParmVarDecl *PD) {
743   VisitVarDecl(PD);
744   unsigned isObjCMethodParam = Record[Idx++];
745   unsigned scopeDepth = Record[Idx++];
746   unsigned scopeIndex = Record[Idx++];
747   unsigned declQualifier = Record[Idx++];
748   if (isObjCMethodParam) {
749     assert(scopeDepth == 0);
750     PD->setObjCMethodScopeInfo(scopeIndex);
751     PD->ParmVarDeclBits.ScopeDepthOrObjCQuals = declQualifier;
752   } else {
753     PD->setScopeInfo(scopeDepth, scopeIndex);
754   }
755   PD->ParmVarDeclBits.IsKNRPromoted = Record[Idx++];
756   PD->ParmVarDeclBits.HasInheritedDefaultArg = Record[Idx++];
757   if (Record[Idx++]) // hasUninstantiatedDefaultArg.
758     PD->setUninstantiatedDefaultArg(Reader.ReadExpr(F));
759 }
760 
761 void ASTDeclReader::VisitFileScopeAsmDecl(FileScopeAsmDecl *AD) {
762   VisitDecl(AD);
763   AD->setAsmString(cast<StringLiteral>(Reader.ReadExpr(F)));
764   AD->setRParenLoc(ReadSourceLocation(Record, Idx));
765 }
766 
767 void ASTDeclReader::VisitBlockDecl(BlockDecl *BD) {
768   VisitDecl(BD);
769   BD->setBody(cast_or_null<CompoundStmt>(Reader.ReadStmt(F)));
770   BD->setSignatureAsWritten(GetTypeSourceInfo(Record, Idx));
771   unsigned NumParams = Record[Idx++];
772   SmallVector<ParmVarDecl *, 16> Params;
773   Params.reserve(NumParams);
774   for (unsigned I = 0; I != NumParams; ++I)
775     Params.push_back(ReadDeclAs<ParmVarDecl>(Record, Idx));
776   BD->setParams(Params);
777 
778   bool capturesCXXThis = Record[Idx++];
779   unsigned numCaptures = Record[Idx++];
780   SmallVector<BlockDecl::Capture, 16> captures;
781   captures.reserve(numCaptures);
782   for (unsigned i = 0; i != numCaptures; ++i) {
783     VarDecl *decl = ReadDeclAs<VarDecl>(Record, Idx);
784     unsigned flags = Record[Idx++];
785     bool byRef = (flags & 1);
786     bool nested = (flags & 2);
787     Expr *copyExpr = ((flags & 4) ? Reader.ReadExpr(F) : 0);
788 
789     captures.push_back(BlockDecl::Capture(decl, byRef, nested, copyExpr));
790   }
791   BD->setCaptures(Reader.getContext(), captures.begin(),
792                   captures.end(), capturesCXXThis);
793 }
794 
795 void ASTDeclReader::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
796   VisitDecl(D);
797   D->setLanguage((LinkageSpecDecl::LanguageIDs)Record[Idx++]);
798   D->setExternLoc(ReadSourceLocation(Record, Idx));
799   D->setRBraceLoc(ReadSourceLocation(Record, Idx));
800 }
801 
802 void ASTDeclReader::VisitLabelDecl(LabelDecl *D) {
803   VisitNamedDecl(D);
804   D->setLocStart(ReadSourceLocation(Record, Idx));
805 }
806 
807 
808 void ASTDeclReader::VisitNamespaceDecl(NamespaceDecl *D) {
809   VisitNamedDecl(D);
810   D->IsInline = Record[Idx++];
811   D->LocStart = ReadSourceLocation(Record, Idx);
812   D->RBraceLoc = ReadSourceLocation(Record, Idx);
813   D->NextNamespace = Record[Idx++];
814 
815   bool IsOriginal = Record[Idx++];
816   // FIXME: Modules will likely have trouble with pointing directly at
817   // the original namespace.
818   D->OrigOrAnonNamespace.setInt(IsOriginal);
819   D->OrigOrAnonNamespace.setPointer(ReadDeclAs<NamespaceDecl>(Record, Idx));
820 }
821 
822 void ASTDeclReader::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
823   VisitNamedDecl(D);
824   D->NamespaceLoc = ReadSourceLocation(Record, Idx);
825   D->IdentLoc = ReadSourceLocation(Record, Idx);
826   D->QualifierLoc = Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
827   D->Namespace = ReadDeclAs<NamedDecl>(Record, Idx);
828 }
829 
830 void ASTDeclReader::VisitUsingDecl(UsingDecl *D) {
831   VisitNamedDecl(D);
832   D->setUsingLocation(ReadSourceLocation(Record, Idx));
833   D->QualifierLoc = Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
834   ReadDeclarationNameLoc(D->DNLoc, D->getDeclName(), Record, Idx);
835   D->FirstUsingShadow = ReadDeclAs<UsingShadowDecl>(Record, Idx);
836   D->setTypeName(Record[Idx++]);
837   if (NamedDecl *Pattern = ReadDeclAs<NamedDecl>(Record, Idx))
838     Reader.getContext().setInstantiatedFromUsingDecl(D, Pattern);
839 }
840 
841 void ASTDeclReader::VisitUsingShadowDecl(UsingShadowDecl *D) {
842   VisitNamedDecl(D);
843   D->setTargetDecl(ReadDeclAs<NamedDecl>(Record, Idx));
844   D->UsingOrNextShadow = ReadDeclAs<NamedDecl>(Record, Idx);
845   UsingShadowDecl *Pattern = ReadDeclAs<UsingShadowDecl>(Record, Idx);
846   if (Pattern)
847     Reader.getContext().setInstantiatedFromUsingShadowDecl(D, Pattern);
848 }
849 
850 void ASTDeclReader::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
851   VisitNamedDecl(D);
852   D->UsingLoc = ReadSourceLocation(Record, Idx);
853   D->NamespaceLoc = ReadSourceLocation(Record, Idx);
854   D->QualifierLoc = Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
855   D->NominatedNamespace = ReadDeclAs<NamedDecl>(Record, Idx);
856   D->CommonAncestor = ReadDeclAs<DeclContext>(Record, Idx);
857 }
858 
859 void ASTDeclReader::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
860   VisitValueDecl(D);
861   D->setUsingLoc(ReadSourceLocation(Record, Idx));
862   D->QualifierLoc = Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
863   ReadDeclarationNameLoc(D->DNLoc, D->getDeclName(), Record, Idx);
864 }
865 
866 void ASTDeclReader::VisitUnresolvedUsingTypenameDecl(
867                                                UnresolvedUsingTypenameDecl *D) {
868   VisitTypeDecl(D);
869   D->TypenameLocation = ReadSourceLocation(Record, Idx);
870   D->QualifierLoc = Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
871 }
872 
873 void ASTDeclReader::ReadCXXDefinitionData(
874                                    struct CXXRecordDecl::DefinitionData &Data,
875                                    const RecordData &Record, unsigned &Idx) {
876   Data.UserDeclaredConstructor = Record[Idx++];
877   Data.UserDeclaredCopyConstructor = Record[Idx++];
878   Data.UserDeclaredMoveConstructor = Record[Idx++];
879   Data.UserDeclaredCopyAssignment = Record[Idx++];
880   Data.UserDeclaredMoveAssignment = Record[Idx++];
881   Data.UserDeclaredDestructor = Record[Idx++];
882   Data.Aggregate = Record[Idx++];
883   Data.PlainOldData = Record[Idx++];
884   Data.Empty = Record[Idx++];
885   Data.Polymorphic = Record[Idx++];
886   Data.Abstract = Record[Idx++];
887   Data.IsStandardLayout = Record[Idx++];
888   Data.HasNoNonEmptyBases = Record[Idx++];
889   Data.HasPrivateFields = Record[Idx++];
890   Data.HasProtectedFields = Record[Idx++];
891   Data.HasPublicFields = Record[Idx++];
892   Data.HasMutableFields = Record[Idx++];
893   Data.HasTrivialDefaultConstructor = Record[Idx++];
894   Data.HasConstexprNonCopyMoveConstructor = Record[Idx++];
895   Data.HasTrivialCopyConstructor = Record[Idx++];
896   Data.HasTrivialMoveConstructor = Record[Idx++];
897   Data.HasTrivialCopyAssignment = Record[Idx++];
898   Data.HasTrivialMoveAssignment = Record[Idx++];
899   Data.HasTrivialDestructor = Record[Idx++];
900   Data.HasNonLiteralTypeFieldsOrBases = Record[Idx++];
901   Data.ComputedVisibleConversions = Record[Idx++];
902   Data.UserProvidedDefaultConstructor = Record[Idx++];
903   Data.DeclaredDefaultConstructor = Record[Idx++];
904   Data.DeclaredCopyConstructor = Record[Idx++];
905   Data.DeclaredMoveConstructor = Record[Idx++];
906   Data.DeclaredCopyAssignment = Record[Idx++];
907   Data.DeclaredMoveAssignment = Record[Idx++];
908   Data.DeclaredDestructor = Record[Idx++];
909   Data.FailedImplicitMoveConstructor = Record[Idx++];
910   Data.FailedImplicitMoveAssignment = Record[Idx++];
911 
912   Data.NumBases = Record[Idx++];
913   if (Data.NumBases)
914     Data.Bases = Reader.readCXXBaseSpecifiers(F, Record, Idx);
915   Data.NumVBases = Record[Idx++];
916   if (Data.NumVBases)
917     Data.VBases = Reader.readCXXBaseSpecifiers(F, Record, Idx);
918 
919   Reader.ReadUnresolvedSet(F, Data.Conversions, Record, Idx);
920   Reader.ReadUnresolvedSet(F, Data.VisibleConversions, Record, Idx);
921   assert(Data.Definition && "Data.Definition should be already set!");
922   Data.FirstFriend = ReadDeclAs<FriendDecl>(Record, Idx);
923 }
924 
925 void ASTDeclReader::InitializeCXXDefinitionData(CXXRecordDecl *D,
926                                                 CXXRecordDecl *DefinitionDecl,
927                                                 const RecordData &Record,
928                                                 unsigned &Idx) {
929   ASTContext &C = Reader.getContext();
930 
931   if (D == DefinitionDecl) {
932     D->DefinitionData = new (C) struct CXXRecordDecl::DefinitionData(D);
933     ReadCXXDefinitionData(*D->DefinitionData, Record, Idx);
934     // We read the definition info. Check if there are pending forward
935     // references that need to point to this DefinitionData pointer.
936     ASTReader::PendingForwardRefsMap::iterator
937         FindI = Reader.PendingForwardRefs.find(D);
938     if (FindI != Reader.PendingForwardRefs.end()) {
939       ASTReader::ForwardRefs &Refs = FindI->second;
940       for (ASTReader::ForwardRefs::iterator
941              I = Refs.begin(), E = Refs.end(); I != E; ++I)
942         (*I)->DefinitionData = D->DefinitionData;
943 #ifndef NDEBUG
944       // We later check whether PendingForwardRefs is empty to make sure all
945       // pending references were linked.
946       Reader.PendingForwardRefs.erase(D);
947 #endif
948     }
949   } else if (DefinitionDecl) {
950     if (DefinitionDecl->DefinitionData) {
951       D->DefinitionData = DefinitionDecl->DefinitionData;
952     } else {
953       // The definition is still initializing.
954       Reader.PendingForwardRefs[DefinitionDecl].push_back(D);
955     }
956   }
957 }
958 
959 void ASTDeclReader::VisitCXXRecordDecl(CXXRecordDecl *D) {
960   VisitRecordDecl(D);
961 
962   CXXRecordDecl *DefinitionDecl = ReadDeclAs<CXXRecordDecl>(Record, Idx);
963   InitializeCXXDefinitionData(D, DefinitionDecl, Record, Idx);
964 
965   ASTContext &C = Reader.getContext();
966 
967   enum CXXRecKind {
968     CXXRecNotTemplate = 0, CXXRecTemplate, CXXRecMemberSpecialization
969   };
970   switch ((CXXRecKind)Record[Idx++]) {
971   default:
972     llvm_unreachable("Out of sync with ASTDeclWriter::VisitCXXRecordDecl?");
973   case CXXRecNotTemplate:
974     break;
975   case CXXRecTemplate:
976     D->TemplateOrInstantiation = ReadDeclAs<ClassTemplateDecl>(Record, Idx);
977     break;
978   case CXXRecMemberSpecialization: {
979     CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(Record, Idx);
980     TemplateSpecializationKind TSK = (TemplateSpecializationKind)Record[Idx++];
981     SourceLocation POI = ReadSourceLocation(Record, Idx);
982     MemberSpecializationInfo *MSI = new (C) MemberSpecializationInfo(RD, TSK);
983     MSI->setPointOfInstantiation(POI);
984     D->TemplateOrInstantiation = MSI;
985     break;
986   }
987   }
988 
989   // Load the key function to avoid deserializing every method so we can
990   // compute it.
991   if (D->IsCompleteDefinition) {
992     if (CXXMethodDecl *Key = ReadDeclAs<CXXMethodDecl>(Record, Idx))
993       C.KeyFunctions[D] = Key;
994   }
995 }
996 
997 void ASTDeclReader::VisitCXXMethodDecl(CXXMethodDecl *D) {
998   VisitFunctionDecl(D);
999   unsigned NumOverridenMethods = Record[Idx++];
1000   while (NumOverridenMethods--) {
1001     // Avoid invariant checking of CXXMethodDecl::addOverriddenMethod,
1002     // MD may be initializing.
1003     if (CXXMethodDecl *MD = ReadDeclAs<CXXMethodDecl>(Record, Idx))
1004       Reader.getContext().addOverriddenMethod(D, MD);
1005   }
1006 }
1007 
1008 void ASTDeclReader::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
1009   VisitCXXMethodDecl(D);
1010 
1011   D->IsExplicitSpecified = Record[Idx++];
1012   D->ImplicitlyDefined = Record[Idx++];
1013   llvm::tie(D->CtorInitializers, D->NumCtorInitializers)
1014       = Reader.ReadCXXCtorInitializers(F, Record, Idx);
1015 }
1016 
1017 void ASTDeclReader::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
1018   VisitCXXMethodDecl(D);
1019 
1020   D->ImplicitlyDefined = Record[Idx++];
1021   D->OperatorDelete = ReadDeclAs<FunctionDecl>(Record, Idx);
1022 }
1023 
1024 void ASTDeclReader::VisitCXXConversionDecl(CXXConversionDecl *D) {
1025   VisitCXXMethodDecl(D);
1026   D->IsExplicitSpecified = Record[Idx++];
1027 }
1028 
1029 void ASTDeclReader::VisitAccessSpecDecl(AccessSpecDecl *D) {
1030   VisitDecl(D);
1031   D->setColonLoc(ReadSourceLocation(Record, Idx));
1032 }
1033 
1034 void ASTDeclReader::VisitFriendDecl(FriendDecl *D) {
1035   VisitDecl(D);
1036   if (Record[Idx++])
1037     D->Friend = GetTypeSourceInfo(Record, Idx);
1038   else
1039     D->Friend = ReadDeclAs<NamedDecl>(Record, Idx);
1040   D->NextFriend = Record[Idx++];
1041   D->UnsupportedFriend = (Record[Idx++] != 0);
1042   D->FriendLoc = ReadSourceLocation(Record, Idx);
1043 }
1044 
1045 void ASTDeclReader::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
1046   VisitDecl(D);
1047   unsigned NumParams = Record[Idx++];
1048   D->NumParams = NumParams;
1049   D->Params = new TemplateParameterList*[NumParams];
1050   for (unsigned i = 0; i != NumParams; ++i)
1051     D->Params[i] = Reader.ReadTemplateParameterList(F, Record, Idx);
1052   if (Record[Idx++]) // HasFriendDecl
1053     D->Friend = ReadDeclAs<NamedDecl>(Record, Idx);
1054   else
1055     D->Friend = GetTypeSourceInfo(Record, Idx);
1056   D->FriendLoc = ReadSourceLocation(Record, Idx);
1057 }
1058 
1059 void ASTDeclReader::VisitTemplateDecl(TemplateDecl *D) {
1060   VisitNamedDecl(D);
1061 
1062   NamedDecl *TemplatedDecl = ReadDeclAs<NamedDecl>(Record, Idx);
1063   TemplateParameterList* TemplateParams
1064       = Reader.ReadTemplateParameterList(F, Record, Idx);
1065   D->init(TemplatedDecl, TemplateParams);
1066 }
1067 
1068 void ASTDeclReader::VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D) {
1069   // Initialize CommonOrPrev before VisitTemplateDecl so that getCommonPtr()
1070   // can be used while this is still initializing.
1071 
1072   assert(D->CommonOrPrev.isNull() && "getCommonPtr was called earlier on this");
1073   DeclID PreviousDeclID = ReadDeclID(Record, Idx);
1074   DeclID FirstDeclID =  PreviousDeclID ? ReadDeclID(Record, Idx) : 0;
1075   // We delay loading of the redeclaration chain to avoid deeply nested calls.
1076   // We temporarily set the first (canonical) declaration as the previous one
1077   // which is the one that matters and mark the real previous DeclID to be
1078   // loaded & attached later on.
1079   RedeclarableTemplateDecl *FirstDecl =
1080       cast_or_null<RedeclarableTemplateDecl>(Reader.GetDecl(FirstDeclID));
1081   assert((FirstDecl == 0 || FirstDecl->getKind() == D->getKind()) &&
1082          "FirstDecl kind mismatch");
1083   if (FirstDecl) {
1084     D->CommonOrPrev = FirstDecl;
1085     // Mark the real previous DeclID to be loaded & attached later on.
1086     if (PreviousDeclID != FirstDeclID)
1087       Reader.PendingPreviousDecls.push_back(std::make_pair(D, PreviousDeclID));
1088   } else {
1089     D->CommonOrPrev = D->newCommon(Reader.getContext());
1090     if (RedeclarableTemplateDecl *RTD
1091           = ReadDeclAs<RedeclarableTemplateDecl>(Record, Idx)) {
1092       assert(RTD->getKind() == D->getKind() &&
1093              "InstantiatedFromMemberTemplate kind mismatch");
1094       D->setInstantiatedFromMemberTemplateImpl(RTD);
1095       if (Record[Idx++])
1096         D->setMemberSpecialization();
1097     }
1098 
1099     RedeclarableTemplateDecl *LatestDecl
1100       = ReadDeclAs<RedeclarableTemplateDecl>(Record, Idx);
1101 
1102     // This decl is a first one and the latest declaration that it points to is
1103     // in the same AST file. However, if this actually needs to point to a
1104     // redeclaration in another AST file, we need to update it by checking
1105     // the FirstLatestDeclIDs map which tracks this kind of decls.
1106     assert(Reader.GetDecl(ThisDeclID) == D && "Invalid ThisDeclID ?");
1107     ASTReader::FirstLatestDeclIDMap::iterator I
1108         = Reader.FirstLatestDeclIDs.find(ThisDeclID);
1109     if (I != Reader.FirstLatestDeclIDs.end()) {
1110       if (Decl *NewLatest = Reader.GetDecl(I->second))
1111         LatestDecl = cast<RedeclarableTemplateDecl>(NewLatest);
1112     }
1113 
1114     assert(LatestDecl->getKind() == D->getKind() && "Latest kind mismatch");
1115     D->getCommonPtr()->Latest = LatestDecl;
1116   }
1117 
1118   VisitTemplateDecl(D);
1119   D->IdentifierNamespace = Record[Idx++];
1120 }
1121 
1122 void ASTDeclReader::VisitClassTemplateDecl(ClassTemplateDecl *D) {
1123   VisitRedeclarableTemplateDecl(D);
1124 
1125   if (D->getPreviousDeclaration() == 0) {
1126     // This ClassTemplateDecl owns a CommonPtr; read it to keep track of all of
1127     // the specializations.
1128     SmallVector<serialization::DeclID, 2> SpecIDs;
1129     SpecIDs.push_back(0);
1130 
1131     // Specializations.
1132     unsigned Size = Record[Idx++];
1133     SpecIDs[0] += Size;
1134     for (unsigned I = 0; I != Size; ++I)
1135       SpecIDs.push_back(ReadDeclID(Record, Idx));
1136 
1137     // Partial specializations.
1138     Size = Record[Idx++];
1139     SpecIDs[0] += Size;
1140     for (unsigned I = 0; I != Size; ++I)
1141       SpecIDs.push_back(ReadDeclID(Record, Idx));
1142 
1143     if (SpecIDs[0]) {
1144       typedef serialization::DeclID DeclID;
1145 
1146       ClassTemplateDecl::Common *CommonPtr = D->getCommonPtr();
1147       CommonPtr->LazySpecializations
1148         = new (Reader.getContext()) DeclID [SpecIDs.size()];
1149       memcpy(CommonPtr->LazySpecializations, SpecIDs.data(),
1150              SpecIDs.size() * sizeof(DeclID));
1151     }
1152 
1153     // InjectedClassNameType is computed.
1154   }
1155 }
1156 
1157 void ASTDeclReader::VisitClassTemplateSpecializationDecl(
1158                                            ClassTemplateSpecializationDecl *D) {
1159   VisitCXXRecordDecl(D);
1160 
1161   ASTContext &C = Reader.getContext();
1162   if (Decl *InstD = ReadDecl(Record, Idx)) {
1163     if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(InstD)) {
1164       D->SpecializedTemplate = CTD;
1165     } else {
1166       SmallVector<TemplateArgument, 8> TemplArgs;
1167       Reader.ReadTemplateArgumentList(TemplArgs, F, Record, Idx);
1168       TemplateArgumentList *ArgList
1169         = TemplateArgumentList::CreateCopy(C, TemplArgs.data(),
1170                                            TemplArgs.size());
1171       ClassTemplateSpecializationDecl::SpecializedPartialSpecialization *PS
1172           = new (C) ClassTemplateSpecializationDecl::
1173                                              SpecializedPartialSpecialization();
1174       PS->PartialSpecialization
1175           = cast<ClassTemplatePartialSpecializationDecl>(InstD);
1176       PS->TemplateArgs = ArgList;
1177       D->SpecializedTemplate = PS;
1178     }
1179   }
1180 
1181   // Explicit info.
1182   if (TypeSourceInfo *TyInfo = GetTypeSourceInfo(Record, Idx)) {
1183     ClassTemplateSpecializationDecl::ExplicitSpecializationInfo *ExplicitInfo
1184         = new (C) ClassTemplateSpecializationDecl::ExplicitSpecializationInfo;
1185     ExplicitInfo->TypeAsWritten = TyInfo;
1186     ExplicitInfo->ExternLoc = ReadSourceLocation(Record, Idx);
1187     ExplicitInfo->TemplateKeywordLoc = ReadSourceLocation(Record, Idx);
1188     D->ExplicitInfo = ExplicitInfo;
1189   }
1190 
1191   SmallVector<TemplateArgument, 8> TemplArgs;
1192   Reader.ReadTemplateArgumentList(TemplArgs, F, Record, Idx);
1193   D->TemplateArgs = TemplateArgumentList::CreateCopy(C, TemplArgs.data(),
1194                                                      TemplArgs.size());
1195   D->PointOfInstantiation = ReadSourceLocation(Record, Idx);
1196   D->SpecializationKind = (TemplateSpecializationKind)Record[Idx++];
1197 
1198   if (D->isCanonicalDecl()) { // It's kept in the folding set.
1199     ClassTemplateDecl *CanonPattern = ReadDeclAs<ClassTemplateDecl>(Record,Idx);
1200     if (ClassTemplatePartialSpecializationDecl *Partial
1201                        = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) {
1202       CanonPattern->getCommonPtr()->PartialSpecializations.InsertNode(Partial);
1203     } else {
1204       CanonPattern->getCommonPtr()->Specializations.InsertNode(D);
1205     }
1206   }
1207 }
1208 
1209 void ASTDeclReader::VisitClassTemplatePartialSpecializationDecl(
1210                                     ClassTemplatePartialSpecializationDecl *D) {
1211   VisitClassTemplateSpecializationDecl(D);
1212 
1213   ASTContext &C = Reader.getContext();
1214   D->TemplateParams = Reader.ReadTemplateParameterList(F, Record, Idx);
1215 
1216   unsigned NumArgs = Record[Idx++];
1217   if (NumArgs) {
1218     D->NumArgsAsWritten = NumArgs;
1219     D->ArgsAsWritten = new (C) TemplateArgumentLoc[NumArgs];
1220     for (unsigned i=0; i != NumArgs; ++i)
1221       D->ArgsAsWritten[i] = Reader.ReadTemplateArgumentLoc(F, Record, Idx);
1222   }
1223 
1224   D->SequenceNumber = Record[Idx++];
1225 
1226   // These are read/set from/to the first declaration.
1227   if (D->getPreviousDeclaration() == 0) {
1228     D->InstantiatedFromMember.setPointer(
1229       ReadDeclAs<ClassTemplatePartialSpecializationDecl>(Record, Idx));
1230     D->InstantiatedFromMember.setInt(Record[Idx++]);
1231   }
1232 }
1233 
1234 void ASTDeclReader::VisitClassScopeFunctionSpecializationDecl(
1235                                     ClassScopeFunctionSpecializationDecl *D) {
1236   VisitDecl(D);
1237   D->Specialization = ReadDeclAs<CXXMethodDecl>(Record, Idx);
1238 }
1239 
1240 void ASTDeclReader::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
1241   VisitRedeclarableTemplateDecl(D);
1242 
1243   if (D->getPreviousDeclaration() == 0) {
1244     // This FunctionTemplateDecl owns a CommonPtr; read it.
1245 
1246     // Read the function specialization declarations.
1247     // FunctionTemplateDecl's FunctionTemplateSpecializationInfos are filled
1248     // when reading the specialized FunctionDecl.
1249     unsigned NumSpecs = Record[Idx++];
1250     while (NumSpecs--)
1251       (void)ReadDecl(Record, Idx);
1252   }
1253 }
1254 
1255 void ASTDeclReader::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
1256   VisitTypeDecl(D);
1257 
1258   D->setDeclaredWithTypename(Record[Idx++]);
1259 
1260   bool Inherited = Record[Idx++];
1261   TypeSourceInfo *DefArg = GetTypeSourceInfo(Record, Idx);
1262   D->setDefaultArgument(DefArg, Inherited);
1263 }
1264 
1265 void ASTDeclReader::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
1266   VisitDeclaratorDecl(D);
1267   // TemplateParmPosition.
1268   D->setDepth(Record[Idx++]);
1269   D->setPosition(Record[Idx++]);
1270   if (D->isExpandedParameterPack()) {
1271     void **Data = reinterpret_cast<void **>(D + 1);
1272     for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
1273       Data[2*I] = Reader.readType(F, Record, Idx).getAsOpaquePtr();
1274       Data[2*I + 1] = GetTypeSourceInfo(Record, Idx);
1275     }
1276   } else {
1277     // Rest of NonTypeTemplateParmDecl.
1278     D->ParameterPack = Record[Idx++];
1279     if (Record[Idx++]) {
1280       Expr *DefArg = Reader.ReadExpr(F);
1281       bool Inherited = Record[Idx++];
1282       D->setDefaultArgument(DefArg, Inherited);
1283    }
1284   }
1285 }
1286 
1287 void ASTDeclReader::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
1288   VisitTemplateDecl(D);
1289   // TemplateParmPosition.
1290   D->setDepth(Record[Idx++]);
1291   D->setPosition(Record[Idx++]);
1292   // Rest of TemplateTemplateParmDecl.
1293   TemplateArgumentLoc Arg = Reader.ReadTemplateArgumentLoc(F, Record, Idx);
1294   bool IsInherited = Record[Idx++];
1295   D->setDefaultArgument(Arg, IsInherited);
1296   D->ParameterPack = Record[Idx++];
1297 }
1298 
1299 void ASTDeclReader::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
1300   VisitRedeclarableTemplateDecl(D);
1301 }
1302 
1303 void ASTDeclReader::VisitStaticAssertDecl(StaticAssertDecl *D) {
1304   VisitDecl(D);
1305   D->AssertExpr = Reader.ReadExpr(F);
1306   D->Message = cast<StringLiteral>(Reader.ReadExpr(F));
1307   D->RParenLoc = ReadSourceLocation(Record, Idx);
1308 }
1309 
1310 std::pair<uint64_t, uint64_t>
1311 ASTDeclReader::VisitDeclContext(DeclContext *DC) {
1312   uint64_t LexicalOffset = Record[Idx++];
1313   uint64_t VisibleOffset = Record[Idx++];
1314   return std::make_pair(LexicalOffset, VisibleOffset);
1315 }
1316 
1317 template <typename T>
1318 void ASTDeclReader::VisitRedeclarable(Redeclarable<T> *D) {
1319   enum RedeclKind { NoRedeclaration = 0, PointsToPrevious, PointsToLatest };
1320   RedeclKind Kind = (RedeclKind)Record[Idx++];
1321   switch (Kind) {
1322   default:
1323     llvm_unreachable("Out of sync with ASTDeclWriter::VisitRedeclarable or"
1324                      " messed up reading");
1325   case NoRedeclaration:
1326     break;
1327   case PointsToPrevious: {
1328     DeclID PreviousDeclID = ReadDeclID(Record, Idx);
1329     DeclID FirstDeclID = ReadDeclID(Record, Idx);
1330     // We delay loading of the redeclaration chain to avoid deeply nested calls.
1331     // We temporarily set the first (canonical) declaration as the previous one
1332     // which is the one that matters and mark the real previous DeclID to be
1333     // loaded & attached later on.
1334     T *FirstDecl = cast_or_null<T>(Reader.GetDecl(FirstDeclID));
1335     D->RedeclLink = typename Redeclarable<T>::PreviousDeclLink(FirstDecl);
1336     if (PreviousDeclID != FirstDeclID)
1337       Reader.PendingPreviousDecls.push_back(std::make_pair(static_cast<T*>(D),
1338                                                            PreviousDeclID));
1339 
1340     // If the first declaration in the chain is in an inconsistent
1341     // state where it thinks that it is the only declaration, fix its
1342     // redeclaration link now to point at this declaration, so that we have a
1343     // proper redeclaration chain.
1344     if (FirstDecl->RedeclLink.getPointer() == FirstDecl) {
1345       FirstDecl->RedeclLink
1346         = typename Redeclarable<T>::LatestDeclLink(static_cast<T*>(D));
1347     }
1348     break;
1349   }
1350   case PointsToLatest: {
1351     T *LatestDecl = ReadDeclAs<T>(Record, Idx);
1352     D->RedeclLink = typename Redeclarable<T>::LatestDeclLink(LatestDecl);
1353 
1354     // If the latest declaration in the chain is in an inconsistent
1355     // state where it thinks that it is the only declaration, fix its
1356     // redeclaration link now to point at this declaration, so that we have a
1357     // proper redeclaration chain.
1358     if (LatestDecl->RedeclLink.getPointer() == LatestDecl) {
1359       LatestDecl->RedeclLink
1360         = typename Redeclarable<T>::PreviousDeclLink(static_cast<T*>(D));
1361     }
1362     break;
1363   }
1364   }
1365 
1366   assert(!(Kind == PointsToPrevious &&
1367            Reader.FirstLatestDeclIDs.find(ThisDeclID) !=
1368                Reader.FirstLatestDeclIDs.end()) &&
1369          "This decl is not first, it should not be in the map");
1370   if (Kind == PointsToPrevious)
1371     return;
1372 
1373   // This decl is a first one and the latest declaration that it points to is in
1374   // the same AST file. However, if this actually needs to point to a
1375   // redeclaration in another AST file, we need to update it by checking the
1376   // FirstLatestDeclIDs map which tracks this kind of decls.
1377   assert(Reader.GetDecl(ThisDeclID) == static_cast<T*>(D) &&
1378          "Invalid ThisDeclID ?");
1379   ASTReader::FirstLatestDeclIDMap::iterator I
1380       = Reader.FirstLatestDeclIDs.find(ThisDeclID);
1381   if (I != Reader.FirstLatestDeclIDs.end()) {
1382     Decl *NewLatest = Reader.GetDecl(I->second);
1383     D->RedeclLink
1384         = typename Redeclarable<T>::LatestDeclLink(cast_or_null<T>(NewLatest));
1385   }
1386 }
1387 
1388 //===----------------------------------------------------------------------===//
1389 // Attribute Reading
1390 //===----------------------------------------------------------------------===//
1391 
1392 /// \brief Reads attributes from the current stream position.
1393 void ASTReader::ReadAttributes(Module &F, AttrVec &Attrs,
1394                                const RecordData &Record, unsigned &Idx) {
1395   for (unsigned i = 0, e = Record[Idx++]; i != e; ++i) {
1396     Attr *New = 0;
1397     attr::Kind Kind = (attr::Kind)Record[Idx++];
1398     SourceRange Range = ReadSourceRange(F, Record, Idx);
1399 
1400 #include "clang/Serialization/AttrPCHRead.inc"
1401 
1402     assert(New && "Unable to decode attribute?");
1403     Attrs.push_back(New);
1404   }
1405 }
1406 
1407 //===----------------------------------------------------------------------===//
1408 // ASTReader Implementation
1409 //===----------------------------------------------------------------------===//
1410 
1411 /// \brief Note that we have loaded the declaration with the given
1412 /// Index.
1413 ///
1414 /// This routine notes that this declaration has already been loaded,
1415 /// so that future GetDecl calls will return this declaration rather
1416 /// than trying to load a new declaration.
1417 inline void ASTReader::LoadedDecl(unsigned Index, Decl *D) {
1418   assert(!DeclsLoaded[Index] && "Decl loaded twice?");
1419   DeclsLoaded[Index] = D;
1420 }
1421 
1422 
1423 /// \brief Determine whether the consumer will be interested in seeing
1424 /// this declaration (via HandleTopLevelDecl).
1425 ///
1426 /// This routine should return true for anything that might affect
1427 /// code generation, e.g., inline function definitions, Objective-C
1428 /// declarations with metadata, etc.
1429 static bool isConsumerInterestedIn(Decl *D) {
1430   // An ObjCMethodDecl is never considered as "interesting" because its
1431   // implementation container always is.
1432 
1433   if (isa<FileScopeAsmDecl>(D) ||
1434       isa<ObjCProtocolDecl>(D) ||
1435       isa<ObjCImplDecl>(D))
1436     return true;
1437   if (VarDecl *Var = dyn_cast<VarDecl>(D))
1438     return Var->isFileVarDecl() &&
1439            Var->isThisDeclarationADefinition() == VarDecl::Definition;
1440   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(D))
1441     return Func->doesThisDeclarationHaveABody();
1442 
1443   return false;
1444 }
1445 
1446 /// \brief Get the correct cursor and offset for loading a declaration.
1447 ASTReader::RecordLocation
1448 ASTReader::DeclCursorForID(DeclID ID, unsigned &RawLocation) {
1449   // See if there's an override.
1450   DeclReplacementMap::iterator It = ReplacedDecls.find(ID);
1451   if (It != ReplacedDecls.end()) {
1452     RawLocation = It->second.RawLoc;
1453     return RecordLocation(It->second.Mod, It->second.Offset);
1454   }
1455 
1456   GlobalDeclMapType::iterator I = GlobalDeclMap.find(ID);
1457   assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
1458   Module *M = I->second;
1459   const DeclOffset &
1460     DOffs =  M->DeclOffsets[ID - M->BaseDeclID - NUM_PREDEF_DECL_IDS];
1461   RawLocation = DOffs.Loc;
1462   return RecordLocation(M, DOffs.BitOffset);
1463 }
1464 
1465 ASTReader::RecordLocation ASTReader::getLocalBitOffset(uint64_t GlobalOffset) {
1466   ContinuousRangeMap<uint64_t, Module*, 4>::iterator I
1467     = GlobalBitOffsetsMap.find(GlobalOffset);
1468 
1469   assert(I != GlobalBitOffsetsMap.end() && "Corrupted global bit offsets map");
1470   return RecordLocation(I->second, GlobalOffset - I->second->GlobalBitOffset);
1471 }
1472 
1473 uint64_t ASTReader::getGlobalBitOffset(Module &M, uint32_t LocalOffset) {
1474   return LocalOffset + M.GlobalBitOffset;
1475 }
1476 
1477 void ASTDeclReader::attachPreviousDecl(Decl *D, Decl *previous) {
1478   assert(D && previous);
1479   if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
1480     TD->RedeclLink.setPointer(cast<TagDecl>(previous));
1481   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1482     FD->RedeclLink.setPointer(cast<FunctionDecl>(previous));
1483   } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
1484     VD->RedeclLink.setPointer(cast<VarDecl>(previous));
1485   } else {
1486     RedeclarableTemplateDecl *TD = cast<RedeclarableTemplateDecl>(D);
1487     TD->CommonOrPrev = cast<RedeclarableTemplateDecl>(previous);
1488   }
1489 }
1490 
1491 void ASTReader::loadAndAttachPreviousDecl(Decl *D, serialization::DeclID ID) {
1492   Decl *previous = GetDecl(ID);
1493   ASTDeclReader::attachPreviousDecl(D, previous);
1494 }
1495 
1496 /// \brief Read the declaration at the given offset from the AST file.
1497 Decl *ASTReader::ReadDeclRecord(DeclID ID) {
1498   unsigned Index = ID - NUM_PREDEF_DECL_IDS;
1499   unsigned RawLocation = 0;
1500   RecordLocation Loc = DeclCursorForID(ID, RawLocation);
1501   llvm::BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
1502   // Keep track of where we are in the stream, then jump back there
1503   // after reading this declaration.
1504   SavedStreamPosition SavedPosition(DeclsCursor);
1505 
1506   ReadingKindTracker ReadingKind(Read_Decl, *this);
1507 
1508   // Note that we are loading a declaration record.
1509   Deserializing ADecl(this);
1510 
1511   DeclsCursor.JumpToBit(Loc.Offset);
1512   RecordData Record;
1513   unsigned Code = DeclsCursor.ReadCode();
1514   unsigned Idx = 0;
1515   ASTDeclReader Reader(*this, *Loc.F, DeclsCursor, ID, RawLocation, Record,Idx);
1516 
1517   Decl *D = 0;
1518   switch ((DeclCode)DeclsCursor.ReadRecord(Code, Record)) {
1519   case DECL_CONTEXT_LEXICAL:
1520   case DECL_CONTEXT_VISIBLE:
1521     llvm_unreachable("Record cannot be de-serialized with ReadDeclRecord");
1522   case DECL_TYPEDEF:
1523     D = TypedefDecl::Create(Context, 0, SourceLocation(), SourceLocation(),
1524                             0, 0);
1525     break;
1526   case DECL_TYPEALIAS:
1527     D = TypeAliasDecl::Create(Context, 0, SourceLocation(), SourceLocation(),
1528                               0, 0);
1529     break;
1530   case DECL_ENUM:
1531     D = EnumDecl::Create(Context, Decl::EmptyShell());
1532     break;
1533   case DECL_RECORD:
1534     D = RecordDecl::Create(Context, Decl::EmptyShell());
1535     break;
1536   case DECL_ENUM_CONSTANT:
1537     D = EnumConstantDecl::Create(Context, 0, SourceLocation(), 0, QualType(),
1538                                  0, llvm::APSInt());
1539     break;
1540   case DECL_FUNCTION:
1541     D = FunctionDecl::Create(Context, 0, SourceLocation(), SourceLocation(),
1542                              DeclarationName(), QualType(), 0);
1543     break;
1544   case DECL_LINKAGE_SPEC:
1545     D = LinkageSpecDecl::Create(Context, 0, SourceLocation(), SourceLocation(),
1546                                 (LinkageSpecDecl::LanguageIDs)0,
1547                                 SourceLocation());
1548     break;
1549   case DECL_LABEL:
1550     D = LabelDecl::Create(Context, 0, SourceLocation(), 0);
1551     break;
1552   case DECL_NAMESPACE:
1553     D = NamespaceDecl::Create(Context, 0, SourceLocation(),
1554                               SourceLocation(), 0);
1555     break;
1556   case DECL_NAMESPACE_ALIAS:
1557     D = NamespaceAliasDecl::Create(Context, 0, SourceLocation(),
1558                                    SourceLocation(), 0,
1559                                    NestedNameSpecifierLoc(),
1560                                    SourceLocation(), 0);
1561     break;
1562   case DECL_USING:
1563     D = UsingDecl::Create(Context, 0, SourceLocation(),
1564                           NestedNameSpecifierLoc(), DeclarationNameInfo(),
1565                           false);
1566     break;
1567   case DECL_USING_SHADOW:
1568     D = UsingShadowDecl::Create(Context, 0, SourceLocation(), 0, 0);
1569     break;
1570   case DECL_USING_DIRECTIVE:
1571     D = UsingDirectiveDecl::Create(Context, 0, SourceLocation(),
1572                                    SourceLocation(), NestedNameSpecifierLoc(),
1573                                    SourceLocation(), 0, 0);
1574     break;
1575   case DECL_UNRESOLVED_USING_VALUE:
1576     D = UnresolvedUsingValueDecl::Create(Context, 0, SourceLocation(),
1577                                          NestedNameSpecifierLoc(),
1578                                          DeclarationNameInfo());
1579     break;
1580   case DECL_UNRESOLVED_USING_TYPENAME:
1581     D = UnresolvedUsingTypenameDecl::Create(Context, 0, SourceLocation(),
1582                                             SourceLocation(),
1583                                             NestedNameSpecifierLoc(),
1584                                             SourceLocation(),
1585                                             DeclarationName());
1586     break;
1587   case DECL_CXX_RECORD:
1588     D = CXXRecordDecl::Create(Context, Decl::EmptyShell());
1589     break;
1590   case DECL_CXX_METHOD:
1591     D = CXXMethodDecl::Create(Context, 0, SourceLocation(),
1592                               DeclarationNameInfo(), QualType(), 0,
1593                               false, SC_None, false, false, SourceLocation());
1594     break;
1595   case DECL_CXX_CONSTRUCTOR:
1596     D = CXXConstructorDecl::Create(Context, Decl::EmptyShell());
1597     break;
1598   case DECL_CXX_DESTRUCTOR:
1599     D = CXXDestructorDecl::Create(Context, Decl::EmptyShell());
1600     break;
1601   case DECL_CXX_CONVERSION:
1602     D = CXXConversionDecl::Create(Context, Decl::EmptyShell());
1603     break;
1604   case DECL_ACCESS_SPEC:
1605     D = AccessSpecDecl::Create(Context, Decl::EmptyShell());
1606     break;
1607   case DECL_FRIEND:
1608     D = FriendDecl::Create(Context, Decl::EmptyShell());
1609     break;
1610   case DECL_FRIEND_TEMPLATE:
1611     D = FriendTemplateDecl::Create(Context, Decl::EmptyShell());
1612     break;
1613   case DECL_CLASS_TEMPLATE:
1614     D = ClassTemplateDecl::Create(Context, Decl::EmptyShell());
1615     break;
1616   case DECL_CLASS_TEMPLATE_SPECIALIZATION:
1617     D = ClassTemplateSpecializationDecl::Create(Context, Decl::EmptyShell());
1618     break;
1619   case DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION:
1620     D = ClassTemplatePartialSpecializationDecl::Create(Context,
1621                                                        Decl::EmptyShell());
1622     break;
1623   case DECL_CLASS_SCOPE_FUNCTION_SPECIALIZATION:
1624     D = ClassScopeFunctionSpecializationDecl::Create(Context,
1625                                                      Decl::EmptyShell());
1626     break;
1627   case DECL_FUNCTION_TEMPLATE:
1628       D = FunctionTemplateDecl::Create(Context, Decl::EmptyShell());
1629     break;
1630   case DECL_TEMPLATE_TYPE_PARM:
1631     D = TemplateTypeParmDecl::Create(Context, Decl::EmptyShell());
1632     break;
1633   case DECL_NON_TYPE_TEMPLATE_PARM:
1634     D = NonTypeTemplateParmDecl::Create(Context, 0, SourceLocation(),
1635                                         SourceLocation(), 0, 0, 0, QualType(),
1636                                         false, 0);
1637     break;
1638   case DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK:
1639     D = NonTypeTemplateParmDecl::Create(Context, 0, SourceLocation(),
1640                                         SourceLocation(), 0, 0, 0, QualType(),
1641                                         0, 0, Record[Idx++], 0);
1642     break;
1643   case DECL_TEMPLATE_TEMPLATE_PARM:
1644     D = TemplateTemplateParmDecl::Create(Context, 0, SourceLocation(), 0, 0,
1645                                          false, 0, 0);
1646     break;
1647   case DECL_TYPE_ALIAS_TEMPLATE:
1648     D = TypeAliasTemplateDecl::Create(Context, Decl::EmptyShell());
1649     break;
1650   case DECL_STATIC_ASSERT:
1651     D = StaticAssertDecl::Create(Context, 0, SourceLocation(), 0, 0,
1652                                  SourceLocation());
1653     break;
1654 
1655   case DECL_OBJC_METHOD:
1656     D = ObjCMethodDecl::Create(Context, SourceLocation(), SourceLocation(),
1657                                Selector(), QualType(), 0, 0);
1658     break;
1659   case DECL_OBJC_INTERFACE:
1660     D = ObjCInterfaceDecl::Create(Context, 0, SourceLocation(), 0);
1661     break;
1662   case DECL_OBJC_IVAR:
1663     D = ObjCIvarDecl::Create(Context, 0, SourceLocation(), SourceLocation(),
1664                              0, QualType(), 0, ObjCIvarDecl::None);
1665     break;
1666   case DECL_OBJC_PROTOCOL:
1667     D = ObjCProtocolDecl::Create(Context, 0, 0, SourceLocation(),
1668                                  SourceLocation(), 0);
1669     break;
1670   case DECL_OBJC_AT_DEFS_FIELD:
1671     D = ObjCAtDefsFieldDecl::Create(Context, 0, SourceLocation(),
1672                                     SourceLocation(), 0, QualType(), 0);
1673     break;
1674   case DECL_OBJC_CLASS:
1675     D = ObjCClassDecl::Create(Context, 0, SourceLocation());
1676     break;
1677   case DECL_OBJC_FORWARD_PROTOCOL:
1678     D = ObjCForwardProtocolDecl::Create(Context, 0, SourceLocation());
1679     break;
1680   case DECL_OBJC_CATEGORY:
1681     D = ObjCCategoryDecl::Create(Context, Decl::EmptyShell());
1682     break;
1683   case DECL_OBJC_CATEGORY_IMPL:
1684     D = ObjCCategoryImplDecl::Create(Context, 0, 0, 0, SourceLocation(),
1685                                      SourceLocation());
1686     break;
1687   case DECL_OBJC_IMPLEMENTATION:
1688     D = ObjCImplementationDecl::Create(Context, 0, 0, 0, SourceLocation(),
1689                                        SourceLocation());
1690     break;
1691   case DECL_OBJC_COMPATIBLE_ALIAS:
1692     D = ObjCCompatibleAliasDecl::Create(Context, 0, SourceLocation(), 0, 0);
1693     break;
1694   case DECL_OBJC_PROPERTY:
1695     D = ObjCPropertyDecl::Create(Context, 0, SourceLocation(), 0, SourceLocation(),
1696                                  0);
1697     break;
1698   case DECL_OBJC_PROPERTY_IMPL:
1699     D = ObjCPropertyImplDecl::Create(Context, 0, SourceLocation(),
1700                                      SourceLocation(), 0,
1701                                      ObjCPropertyImplDecl::Dynamic, 0,
1702                                      SourceLocation());
1703     break;
1704   case DECL_FIELD:
1705     D = FieldDecl::Create(Context, 0, SourceLocation(), SourceLocation(), 0,
1706                           QualType(), 0, 0, false, false);
1707     break;
1708   case DECL_INDIRECTFIELD:
1709     D = IndirectFieldDecl::Create(Context, 0, SourceLocation(), 0, QualType(),
1710                                   0, 0);
1711     break;
1712   case DECL_VAR:
1713     D = VarDecl::Create(Context, 0, SourceLocation(), SourceLocation(), 0,
1714                         QualType(), 0, SC_None, SC_None);
1715     break;
1716 
1717   case DECL_IMPLICIT_PARAM:
1718     D = ImplicitParamDecl::Create(Context, 0, SourceLocation(), 0, QualType());
1719     break;
1720 
1721   case DECL_PARM_VAR:
1722     D = ParmVarDecl::Create(Context, 0, SourceLocation(), SourceLocation(), 0,
1723                             QualType(), 0, SC_None, SC_None, 0);
1724     break;
1725   case DECL_FILE_SCOPE_ASM:
1726     D = FileScopeAsmDecl::Create(Context, 0, 0, SourceLocation(),
1727                                  SourceLocation());
1728     break;
1729   case DECL_BLOCK:
1730     D = BlockDecl::Create(Context, 0, SourceLocation());
1731     break;
1732   case DECL_CXX_BASE_SPECIFIERS:
1733     Error("attempt to read a C++ base-specifier record as a declaration");
1734     return 0;
1735   }
1736 
1737   assert(D && "Unknown declaration reading AST file");
1738   LoadedDecl(Index, D);
1739   Reader.Visit(D);
1740 
1741   // If this declaration is also a declaration context, get the
1742   // offsets for its tables of lexical and visible declarations.
1743   if (DeclContext *DC = dyn_cast<DeclContext>(D)) {
1744     std::pair<uint64_t, uint64_t> Offsets = Reader.VisitDeclContext(DC);
1745     if (Offsets.first || Offsets.second) {
1746       if (Offsets.first != 0)
1747         DC->setHasExternalLexicalStorage(true);
1748       if (Offsets.second != 0)
1749         DC->setHasExternalVisibleStorage(true);
1750       if (ReadDeclContextStorage(*Loc.F, DeclsCursor, Offsets,
1751                                  Loc.F->DeclContextInfos[DC]))
1752         return 0;
1753     }
1754 
1755     // Now add the pending visible updates for this decl context, if it has any.
1756     DeclContextVisibleUpdatesPending::iterator I =
1757         PendingVisibleUpdates.find(ID);
1758     if (I != PendingVisibleUpdates.end()) {
1759       // There are updates. This means the context has external visible
1760       // storage, even if the original stored version didn't.
1761       DC->setHasExternalVisibleStorage(true);
1762       DeclContextVisibleUpdates &U = I->second;
1763       for (DeclContextVisibleUpdates::iterator UI = U.begin(), UE = U.end();
1764            UI != UE; ++UI) {
1765         UI->second->DeclContextInfos[DC].NameLookupTableData = UI->first;
1766       }
1767       PendingVisibleUpdates.erase(I);
1768     }
1769   }
1770   assert(Idx == Record.size());
1771 
1772   // Load any relevant update records.
1773   loadDeclUpdateRecords(ID, D);
1774 
1775   // Load the category chain after recursive loading is finished.
1776   if (ObjCChainedCategoriesInterfaces.count(ID))
1777     PendingChainedObjCCategories.push_back(
1778                                 std::make_pair(cast<ObjCInterfaceDecl>(D), ID));
1779 
1780   // If we have deserialized a declaration that has a definition the
1781   // AST consumer might need to know about, queue it.
1782   // We don't pass it to the consumer immediately because we may be in recursive
1783   // loading, and some declarations may still be initializing.
1784   if (isConsumerInterestedIn(D))
1785       InterestingDecls.push_back(D);
1786 
1787   return D;
1788 }
1789 
1790 void ASTReader::loadDeclUpdateRecords(serialization::DeclID ID, Decl *D) {
1791   // The declaration may have been modified by files later in the chain.
1792   // If this is the case, read the record containing the updates from each file
1793   // and pass it to ASTDeclReader to make the modifications.
1794   DeclUpdateOffsetsMap::iterator UpdI = DeclUpdateOffsets.find(ID);
1795   if (UpdI != DeclUpdateOffsets.end()) {
1796     FileOffsetsTy &UpdateOffsets = UpdI->second;
1797     for (FileOffsetsTy::iterator
1798          I = UpdateOffsets.begin(), E = UpdateOffsets.end(); I != E; ++I) {
1799       Module *F = I->first;
1800       uint64_t Offset = I->second;
1801       llvm::BitstreamCursor &Cursor = F->DeclsCursor;
1802       SavedStreamPosition SavedPosition(Cursor);
1803       Cursor.JumpToBit(Offset);
1804       RecordData Record;
1805       unsigned Code = Cursor.ReadCode();
1806       unsigned RecCode = Cursor.ReadRecord(Code, Record);
1807       (void)RecCode;
1808       assert(RecCode == DECL_UPDATES && "Expected DECL_UPDATES record!");
1809 
1810       unsigned Idx = 0;
1811       ASTDeclReader Reader(*this, *F, Cursor, ID, 0, Record, Idx);
1812       Reader.UpdateDecl(D, *F, Record);
1813     }
1814   }
1815 }
1816 
1817 namespace {
1818   /// \brief Given an ObjC interface, goes through the modules and links to the
1819   /// interface all the categories for it.
1820   class ObjCChainedCategoriesVisitor {
1821     ASTReader &Reader;
1822     serialization::GlobalDeclID InterfaceID;
1823     ObjCInterfaceDecl *Interface;
1824     ObjCCategoryDecl *GlobHeadCat, *GlobTailCat;
1825     llvm::DenseMap<DeclarationName, ObjCCategoryDecl *> NameCategoryMap;
1826 
1827   public:
1828     ObjCChainedCategoriesVisitor(ASTReader &Reader,
1829                                  serialization::GlobalDeclID InterfaceID,
1830                                  ObjCInterfaceDecl *Interface)
1831       : Reader(Reader), InterfaceID(InterfaceID), Interface(Interface),
1832         GlobHeadCat(0), GlobTailCat(0) { }
1833 
1834     static bool visit(Module &M, void *UserData) {
1835       return static_cast<ObjCChainedCategoriesVisitor *>(UserData)->visit(M);
1836     }
1837 
1838     bool visit(Module &M) {
1839       if (Reader.isDeclIDFromModule(InterfaceID, M))
1840         return true; // We reached the module where the interface originated
1841                     // from. Stop traversing the imported modules.
1842 
1843       Module::ChainedObjCCategoriesMap::iterator
1844         I = M.ChainedObjCCategories.find(InterfaceID);
1845       if (I == M.ChainedObjCCategories.end())
1846         return false;
1847 
1848       ObjCCategoryDecl *
1849         HeadCat = Reader.GetLocalDeclAs<ObjCCategoryDecl>(M, I->second.first);
1850       ObjCCategoryDecl *
1851         TailCat = Reader.GetLocalDeclAs<ObjCCategoryDecl>(M, I->second.second);
1852 
1853       addCategories(HeadCat, TailCat);
1854       return false;
1855     }
1856 
1857     void addCategories(ObjCCategoryDecl *HeadCat,
1858                        ObjCCategoryDecl *TailCat = 0) {
1859       if (!HeadCat) {
1860         assert(!TailCat);
1861         return;
1862       }
1863 
1864       if (!TailCat) {
1865         TailCat = HeadCat;
1866         while (TailCat->getNextClassCategory())
1867           TailCat = TailCat->getNextClassCategory();
1868       }
1869 
1870       if (!GlobHeadCat) {
1871         GlobHeadCat = HeadCat;
1872         GlobTailCat = TailCat;
1873       } else {
1874         ASTDeclReader::setNextObjCCategory(GlobTailCat, HeadCat);
1875         GlobTailCat = TailCat;
1876       }
1877 
1878       llvm::DenseSet<DeclarationName> Checked;
1879       for (ObjCCategoryDecl *Cat = HeadCat,
1880                             *CatEnd = TailCat->getNextClassCategory();
1881              Cat != CatEnd; Cat = Cat->getNextClassCategory()) {
1882         if (Checked.count(Cat->getDeclName()))
1883           continue;
1884         Checked.insert(Cat->getDeclName());
1885         checkForDuplicate(Cat);
1886       }
1887     }
1888 
1889     /// \brief Warns for duplicate categories that come from different modules.
1890     void checkForDuplicate(ObjCCategoryDecl *Cat) {
1891       DeclarationName Name = Cat->getDeclName();
1892       // Find the top category with the same name. We do not want to warn for
1893       // duplicates along the established chain because there were already
1894       // warnings for them when the module was created. We only want to warn for
1895       // duplicates between non-dependent modules:
1896       //
1897       //   MT     //
1898       //  /  \    //
1899       // ML  MR   //
1900       //
1901       // We want to warn for duplicates between ML and MR,not between ML and MT.
1902       //
1903       // FIXME: We should not warn for duplicates in diamond:
1904       //
1905       //   MT     //
1906       //  /  \    //
1907       // ML  MR   //
1908       //  \  /    //
1909       //   MB     //
1910       //
1911       // If there are duplicates in ML/MR, there will be warning when creating
1912       // MB *and* when importing MB. We should not warn when importing.
1913       for (ObjCCategoryDecl *Next = Cat->getNextClassCategory(); Next;
1914              Next = Next->getNextClassCategory()) {
1915         if (Next->getDeclName() == Name)
1916           Cat = Next;
1917       }
1918 
1919       ObjCCategoryDecl *&PrevCat = NameCategoryMap[Name];
1920       if (!PrevCat)
1921         PrevCat = Cat;
1922 
1923       if (PrevCat != Cat) {
1924         Reader.Diag(Cat->getLocation(), diag::warn_dup_category_def)
1925           << Interface->getDeclName() << Name;
1926         Reader.Diag(PrevCat->getLocation(), diag::note_previous_definition);
1927       }
1928     }
1929 
1930     ObjCCategoryDecl *getHeadCategory() const { return GlobHeadCat; }
1931   };
1932 }
1933 
1934 void ASTReader::loadObjCChainedCategories(serialization::GlobalDeclID ID,
1935                                           ObjCInterfaceDecl *D) {
1936   ObjCChainedCategoriesVisitor Visitor(*this, ID, D);
1937   ModuleMgr.visit(ObjCChainedCategoriesVisitor::visit, &Visitor);
1938   // Also add the categories that the interface already links to.
1939   Visitor.addCategories(D->getCategoryList());
1940   D->setCategoryList(Visitor.getHeadCategory());
1941 }
1942 
1943 void ASTDeclReader::UpdateDecl(Decl *D, Module &Module,
1944                                const RecordData &Record) {
1945   unsigned Idx = 0;
1946   while (Idx < Record.size()) {
1947     switch ((DeclUpdateKind)Record[Idx++]) {
1948     case UPD_CXX_SET_DEFINITIONDATA: {
1949       CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
1950       CXXRecordDecl *DefinitionDecl
1951         = Reader.ReadDeclAs<CXXRecordDecl>(Module, Record, Idx);
1952       assert(!RD->DefinitionData && "DefinitionData is already set!");
1953       InitializeCXXDefinitionData(RD, DefinitionDecl, Record, Idx);
1954       break;
1955     }
1956 
1957     case UPD_CXX_ADDED_IMPLICIT_MEMBER:
1958       cast<CXXRecordDecl>(D)->addedMember(Reader.ReadDecl(Module, Record, Idx));
1959       break;
1960 
1961     case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
1962       // It will be added to the template's specializations set when loaded.
1963       (void)Reader.ReadDecl(Module, Record, Idx);
1964       break;
1965 
1966     case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE: {
1967       NamespaceDecl *Anon
1968         = Reader.ReadDeclAs<NamespaceDecl>(Module, Record, Idx);
1969       // Guard against these being loaded out of original order. Don't use
1970       // getNextNamespace(), since it tries to access the context and can't in
1971       // the middle of deserialization.
1972       if (!Anon->NextNamespace) {
1973         if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(D))
1974           TU->setAnonymousNamespace(Anon);
1975         else
1976           cast<NamespaceDecl>(D)->OrigOrAnonNamespace.setPointer(Anon);
1977       }
1978       break;
1979     }
1980 
1981     case UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER:
1982       cast<VarDecl>(D)->getMemberSpecializationInfo()->setPointOfInstantiation(
1983           Reader.ReadSourceLocation(Module, Record, Idx));
1984       break;
1985     }
1986   }
1987 }
1988