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->setForwardDecl(Record[Idx++]);
562   ID->setImplicitInterfaceDecl(Record[Idx++]);
563   ID->setSuperClassLoc(ReadSourceLocation(Record, Idx));
564   ID->setLocEnd(ReadSourceLocation(Record, Idx));
565 }
566 
567 void ASTDeclReader::VisitObjCIvarDecl(ObjCIvarDecl *IVD) {
568   VisitFieldDecl(IVD);
569   IVD->setAccessControl((ObjCIvarDecl::AccessControl)Record[Idx++]);
570   // This field will be built lazily.
571   IVD->setNextIvar(0);
572   bool synth = Record[Idx++];
573   IVD->setSynthesize(synth);
574 }
575 
576 void ASTDeclReader::VisitObjCProtocolDecl(ObjCProtocolDecl *PD) {
577   VisitObjCContainerDecl(PD);
578   PD->InitiallyForwardDecl = Record[Idx++];
579   PD->setForwardDecl(Record[Idx++]);
580   PD->setLocEnd(ReadSourceLocation(Record, Idx));
581   unsigned NumProtoRefs = Record[Idx++];
582   SmallVector<ObjCProtocolDecl *, 16> ProtoRefs;
583   ProtoRefs.reserve(NumProtoRefs);
584   for (unsigned I = 0; I != NumProtoRefs; ++I)
585     ProtoRefs.push_back(ReadDeclAs<ObjCProtocolDecl>(Record, Idx));
586   SmallVector<SourceLocation, 16> ProtoLocs;
587   ProtoLocs.reserve(NumProtoRefs);
588   for (unsigned I = 0; I != NumProtoRefs; ++I)
589     ProtoLocs.push_back(ReadSourceLocation(Record, Idx));
590   PD->setProtocolList(ProtoRefs.data(), NumProtoRefs, ProtoLocs.data(),
591                       Reader.getContext());
592 }
593 
594 void ASTDeclReader::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *FD) {
595   VisitFieldDecl(FD);
596 }
597 
598 void ASTDeclReader::VisitObjCClassDecl(ObjCClassDecl *CD) {
599   VisitDecl(CD);
600   ObjCInterfaceDecl *ClassRef = ReadDeclAs<ObjCInterfaceDecl>(Record, Idx);
601   SourceLocation SLoc = ReadSourceLocation(Record, Idx);
602   CD->setClass(Reader.getContext(), ClassRef, SLoc);
603 }
604 
605 void ASTDeclReader::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *FPD) {
606   VisitDecl(FPD);
607   unsigned NumProtoRefs = Record[Idx++];
608   SmallVector<ObjCProtocolDecl *, 16> ProtoRefs;
609   ProtoRefs.reserve(NumProtoRefs);
610   for (unsigned I = 0; I != NumProtoRefs; ++I)
611     ProtoRefs.push_back(ReadDeclAs<ObjCProtocolDecl>(Record, Idx));
612   SmallVector<SourceLocation, 16> ProtoLocs;
613   ProtoLocs.reserve(NumProtoRefs);
614   for (unsigned I = 0; I != NumProtoRefs; ++I)
615     ProtoLocs.push_back(ReadSourceLocation(Record, Idx));
616   FPD->setProtocolList(ProtoRefs.data(), NumProtoRefs, ProtoLocs.data(),
617                        Reader.getContext());
618 }
619 
620 void ASTDeclReader::VisitObjCCategoryDecl(ObjCCategoryDecl *CD) {
621   VisitObjCContainerDecl(CD);
622   CD->ClassInterface = ReadDeclAs<ObjCInterfaceDecl>(Record, Idx);
623   unsigned NumProtoRefs = Record[Idx++];
624   SmallVector<ObjCProtocolDecl *, 16> ProtoRefs;
625   ProtoRefs.reserve(NumProtoRefs);
626   for (unsigned I = 0; I != NumProtoRefs; ++I)
627     ProtoRefs.push_back(ReadDeclAs<ObjCProtocolDecl>(Record, Idx));
628   SmallVector<SourceLocation, 16> ProtoLocs;
629   ProtoLocs.reserve(NumProtoRefs);
630   for (unsigned I = 0; I != NumProtoRefs; ++I)
631     ProtoLocs.push_back(ReadSourceLocation(Record, Idx));
632   CD->setProtocolList(ProtoRefs.data(), NumProtoRefs, ProtoLocs.data(),
633                       Reader.getContext());
634   CD->NextClassCategory = ReadDeclAs<ObjCCategoryDecl>(Record, Idx);
635   CD->setHasSynthBitfield(Record[Idx++]);
636   CD->setCategoryNameLoc(ReadSourceLocation(Record, Idx));
637 }
638 
639 void ASTDeclReader::VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *CAD) {
640   VisitNamedDecl(CAD);
641   CAD->setClassInterface(ReadDeclAs<ObjCInterfaceDecl>(Record, Idx));
642 }
643 
644 void ASTDeclReader::VisitObjCPropertyDecl(ObjCPropertyDecl *D) {
645   VisitNamedDecl(D);
646   D->setAtLoc(ReadSourceLocation(Record, Idx));
647   D->setType(GetTypeSourceInfo(Record, Idx));
648   // FIXME: stable encoding
649   D->setPropertyAttributes(
650                       (ObjCPropertyDecl::PropertyAttributeKind)Record[Idx++]);
651   D->setPropertyAttributesAsWritten(
652                       (ObjCPropertyDecl::PropertyAttributeKind)Record[Idx++]);
653   // FIXME: stable encoding
654   D->setPropertyImplementation(
655                             (ObjCPropertyDecl::PropertyControl)Record[Idx++]);
656   D->setGetterName(Reader.ReadDeclarationName(F,Record, Idx).getObjCSelector());
657   D->setSetterName(Reader.ReadDeclarationName(F,Record, Idx).getObjCSelector());
658   D->setGetterMethodDecl(ReadDeclAs<ObjCMethodDecl>(Record, Idx));
659   D->setSetterMethodDecl(ReadDeclAs<ObjCMethodDecl>(Record, Idx));
660   D->setPropertyIvarDecl(ReadDeclAs<ObjCIvarDecl>(Record, Idx));
661 }
662 
663 void ASTDeclReader::VisitObjCImplDecl(ObjCImplDecl *D) {
664   VisitObjCContainerDecl(D);
665   D->setClassInterface(ReadDeclAs<ObjCInterfaceDecl>(Record, Idx));
666 }
667 
668 void ASTDeclReader::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
669   VisitObjCImplDecl(D);
670   D->setIdentifier(Reader.GetIdentifierInfo(F, Record, Idx));
671 }
672 
673 void ASTDeclReader::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
674   VisitObjCImplDecl(D);
675   D->setSuperClass(ReadDeclAs<ObjCInterfaceDecl>(Record, Idx));
676   llvm::tie(D->IvarInitializers, D->NumIvarInitializers)
677       = Reader.ReadCXXCtorInitializers(F, Record, Idx);
678   D->setHasSynthBitfield(Record[Idx++]);
679 }
680 
681 
682 void ASTDeclReader::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) {
683   VisitDecl(D);
684   D->setAtLoc(ReadSourceLocation(Record, Idx));
685   D->setPropertyDecl(ReadDeclAs<ObjCPropertyDecl>(Record, Idx));
686   D->PropertyIvarDecl = ReadDeclAs<ObjCIvarDecl>(Record, Idx);
687   D->IvarLoc = ReadSourceLocation(Record, Idx);
688   D->setGetterCXXConstructor(Reader.ReadExpr(F));
689   D->setSetterCXXAssignment(Reader.ReadExpr(F));
690 }
691 
692 void ASTDeclReader::VisitFieldDecl(FieldDecl *FD) {
693   VisitDeclaratorDecl(FD);
694   FD->setMutable(Record[Idx++]);
695   int BitWidthOrInitializer = Record[Idx++];
696   if (BitWidthOrInitializer == 1)
697     FD->setBitWidth(Reader.ReadExpr(F));
698   else if (BitWidthOrInitializer == 2)
699     FD->setInClassInitializer(Reader.ReadExpr(F));
700   if (!FD->getDeclName()) {
701     if (FieldDecl *Tmpl = ReadDeclAs<FieldDecl>(Record, Idx))
702       Reader.getContext().setInstantiatedFromUnnamedFieldDecl(FD, Tmpl);
703   }
704 }
705 
706 void ASTDeclReader::VisitIndirectFieldDecl(IndirectFieldDecl *FD) {
707   VisitValueDecl(FD);
708 
709   FD->ChainingSize = Record[Idx++];
710   assert(FD->ChainingSize >= 2 && "Anonymous chaining must be >= 2");
711   FD->Chaining = new (Reader.getContext())NamedDecl*[FD->ChainingSize];
712 
713   for (unsigned I = 0; I != FD->ChainingSize; ++I)
714     FD->Chaining[I] = ReadDeclAs<NamedDecl>(Record, Idx);
715 }
716 
717 void ASTDeclReader::VisitVarDecl(VarDecl *VD) {
718   VisitRedeclarable(VD);
719   VisitDeclaratorDecl(VD);
720   VD->VarDeclBits.SClass = (StorageClass)Record[Idx++];
721   VD->VarDeclBits.SClassAsWritten = (StorageClass)Record[Idx++];
722   VD->VarDeclBits.ThreadSpecified = Record[Idx++];
723   VD->VarDeclBits.HasCXXDirectInit = Record[Idx++];
724   VD->VarDeclBits.ExceptionVar = Record[Idx++];
725   VD->VarDeclBits.NRVOVariable = Record[Idx++];
726   VD->VarDeclBits.CXXForRangeDecl = Record[Idx++];
727   VD->VarDeclBits.ARCPseudoStrong = Record[Idx++];
728   if (Record[Idx++])
729     VD->setInit(Reader.ReadExpr(F));
730 
731   if (Record[Idx++]) { // HasMemberSpecializationInfo.
732     VarDecl *Tmpl = ReadDeclAs<VarDecl>(Record, Idx);
733     TemplateSpecializationKind TSK = (TemplateSpecializationKind)Record[Idx++];
734     SourceLocation POI = ReadSourceLocation(Record, Idx);
735     Reader.getContext().setInstantiatedFromStaticDataMember(VD, Tmpl, TSK,POI);
736   }
737 }
738 
739 void ASTDeclReader::VisitImplicitParamDecl(ImplicitParamDecl *PD) {
740   VisitVarDecl(PD);
741 }
742 
743 void ASTDeclReader::VisitParmVarDecl(ParmVarDecl *PD) {
744   VisitVarDecl(PD);
745   unsigned isObjCMethodParam = Record[Idx++];
746   unsigned scopeDepth = Record[Idx++];
747   unsigned scopeIndex = Record[Idx++];
748   unsigned declQualifier = Record[Idx++];
749   if (isObjCMethodParam) {
750     assert(scopeDepth == 0);
751     PD->setObjCMethodScopeInfo(scopeIndex);
752     PD->ParmVarDeclBits.ScopeDepthOrObjCQuals = declQualifier;
753   } else {
754     PD->setScopeInfo(scopeDepth, scopeIndex);
755   }
756   PD->ParmVarDeclBits.IsKNRPromoted = Record[Idx++];
757   PD->ParmVarDeclBits.HasInheritedDefaultArg = Record[Idx++];
758   if (Record[Idx++]) // hasUninstantiatedDefaultArg.
759     PD->setUninstantiatedDefaultArg(Reader.ReadExpr(F));
760 }
761 
762 void ASTDeclReader::VisitFileScopeAsmDecl(FileScopeAsmDecl *AD) {
763   VisitDecl(AD);
764   AD->setAsmString(cast<StringLiteral>(Reader.ReadExpr(F)));
765   AD->setRParenLoc(ReadSourceLocation(Record, Idx));
766 }
767 
768 void ASTDeclReader::VisitBlockDecl(BlockDecl *BD) {
769   VisitDecl(BD);
770   BD->setBody(cast_or_null<CompoundStmt>(Reader.ReadStmt(F)));
771   BD->setSignatureAsWritten(GetTypeSourceInfo(Record, Idx));
772   unsigned NumParams = Record[Idx++];
773   SmallVector<ParmVarDecl *, 16> Params;
774   Params.reserve(NumParams);
775   for (unsigned I = 0; I != NumParams; ++I)
776     Params.push_back(ReadDeclAs<ParmVarDecl>(Record, Idx));
777   BD->setParams(Params);
778 
779   bool capturesCXXThis = Record[Idx++];
780   unsigned numCaptures = Record[Idx++];
781   SmallVector<BlockDecl::Capture, 16> captures;
782   captures.reserve(numCaptures);
783   for (unsigned i = 0; i != numCaptures; ++i) {
784     VarDecl *decl = ReadDeclAs<VarDecl>(Record, Idx);
785     unsigned flags = Record[Idx++];
786     bool byRef = (flags & 1);
787     bool nested = (flags & 2);
788     Expr *copyExpr = ((flags & 4) ? Reader.ReadExpr(F) : 0);
789 
790     captures.push_back(BlockDecl::Capture(decl, byRef, nested, copyExpr));
791   }
792   BD->setCaptures(Reader.getContext(), captures.begin(),
793                   captures.end(), capturesCXXThis);
794 }
795 
796 void ASTDeclReader::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
797   VisitDecl(D);
798   D->setLanguage((LinkageSpecDecl::LanguageIDs)Record[Idx++]);
799   D->setExternLoc(ReadSourceLocation(Record, Idx));
800   D->setRBraceLoc(ReadSourceLocation(Record, Idx));
801 }
802 
803 void ASTDeclReader::VisitLabelDecl(LabelDecl *D) {
804   VisitNamedDecl(D);
805   D->setLocStart(ReadSourceLocation(Record, Idx));
806 }
807 
808 
809 void ASTDeclReader::VisitNamespaceDecl(NamespaceDecl *D) {
810   VisitNamedDecl(D);
811   D->IsInline = Record[Idx++];
812   D->LocStart = ReadSourceLocation(Record, Idx);
813   D->RBraceLoc = ReadSourceLocation(Record, Idx);
814   D->NextNamespace = Record[Idx++];
815 
816   bool IsOriginal = Record[Idx++];
817   // FIXME: Modules will likely have trouble with pointing directly at
818   // the original namespace.
819   D->OrigOrAnonNamespace.setInt(IsOriginal);
820   D->OrigOrAnonNamespace.setPointer(ReadDeclAs<NamespaceDecl>(Record, Idx));
821 }
822 
823 void ASTDeclReader::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
824   VisitNamedDecl(D);
825   D->NamespaceLoc = ReadSourceLocation(Record, Idx);
826   D->IdentLoc = ReadSourceLocation(Record, Idx);
827   D->QualifierLoc = Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
828   D->Namespace = ReadDeclAs<NamedDecl>(Record, Idx);
829 }
830 
831 void ASTDeclReader::VisitUsingDecl(UsingDecl *D) {
832   VisitNamedDecl(D);
833   D->setUsingLocation(ReadSourceLocation(Record, Idx));
834   D->QualifierLoc = Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
835   ReadDeclarationNameLoc(D->DNLoc, D->getDeclName(), Record, Idx);
836   D->FirstUsingShadow = ReadDeclAs<UsingShadowDecl>(Record, Idx);
837   D->setTypeName(Record[Idx++]);
838   if (NamedDecl *Pattern = ReadDeclAs<NamedDecl>(Record, Idx))
839     Reader.getContext().setInstantiatedFromUsingDecl(D, Pattern);
840 }
841 
842 void ASTDeclReader::VisitUsingShadowDecl(UsingShadowDecl *D) {
843   VisitNamedDecl(D);
844   D->setTargetDecl(ReadDeclAs<NamedDecl>(Record, Idx));
845   D->UsingOrNextShadow = ReadDeclAs<NamedDecl>(Record, Idx);
846   UsingShadowDecl *Pattern = ReadDeclAs<UsingShadowDecl>(Record, Idx);
847   if (Pattern)
848     Reader.getContext().setInstantiatedFromUsingShadowDecl(D, Pattern);
849 }
850 
851 void ASTDeclReader::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
852   VisitNamedDecl(D);
853   D->UsingLoc = ReadSourceLocation(Record, Idx);
854   D->NamespaceLoc = ReadSourceLocation(Record, Idx);
855   D->QualifierLoc = Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
856   D->NominatedNamespace = ReadDeclAs<NamedDecl>(Record, Idx);
857   D->CommonAncestor = ReadDeclAs<DeclContext>(Record, Idx);
858 }
859 
860 void ASTDeclReader::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
861   VisitValueDecl(D);
862   D->setUsingLoc(ReadSourceLocation(Record, Idx));
863   D->QualifierLoc = Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
864   ReadDeclarationNameLoc(D->DNLoc, D->getDeclName(), Record, Idx);
865 }
866 
867 void ASTDeclReader::VisitUnresolvedUsingTypenameDecl(
868                                                UnresolvedUsingTypenameDecl *D) {
869   VisitTypeDecl(D);
870   D->TypenameLocation = ReadSourceLocation(Record, Idx);
871   D->QualifierLoc = Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
872 }
873 
874 void ASTDeclReader::ReadCXXDefinitionData(
875                                    struct CXXRecordDecl::DefinitionData &Data,
876                                    const RecordData &Record, unsigned &Idx) {
877   Data.UserDeclaredConstructor = Record[Idx++];
878   Data.UserDeclaredCopyConstructor = Record[Idx++];
879   Data.UserDeclaredMoveConstructor = Record[Idx++];
880   Data.UserDeclaredCopyAssignment = Record[Idx++];
881   Data.UserDeclaredMoveAssignment = Record[Idx++];
882   Data.UserDeclaredDestructor = Record[Idx++];
883   Data.Aggregate = Record[Idx++];
884   Data.PlainOldData = Record[Idx++];
885   Data.Empty = Record[Idx++];
886   Data.Polymorphic = Record[Idx++];
887   Data.Abstract = Record[Idx++];
888   Data.IsStandardLayout = Record[Idx++];
889   Data.HasNoNonEmptyBases = Record[Idx++];
890   Data.HasPrivateFields = Record[Idx++];
891   Data.HasProtectedFields = Record[Idx++];
892   Data.HasPublicFields = Record[Idx++];
893   Data.HasMutableFields = Record[Idx++];
894   Data.HasTrivialDefaultConstructor = Record[Idx++];
895   Data.HasConstexprNonCopyMoveConstructor = Record[Idx++];
896   Data.HasTrivialCopyConstructor = Record[Idx++];
897   Data.HasTrivialMoveConstructor = Record[Idx++];
898   Data.HasTrivialCopyAssignment = Record[Idx++];
899   Data.HasTrivialMoveAssignment = Record[Idx++];
900   Data.HasTrivialDestructor = Record[Idx++];
901   Data.HasNonLiteralTypeFieldsOrBases = Record[Idx++];
902   Data.ComputedVisibleConversions = Record[Idx++];
903   Data.UserProvidedDefaultConstructor = Record[Idx++];
904   Data.DeclaredDefaultConstructor = Record[Idx++];
905   Data.DeclaredCopyConstructor = Record[Idx++];
906   Data.DeclaredMoveConstructor = Record[Idx++];
907   Data.DeclaredCopyAssignment = Record[Idx++];
908   Data.DeclaredMoveAssignment = Record[Idx++];
909   Data.DeclaredDestructor = Record[Idx++];
910   Data.FailedImplicitMoveConstructor = Record[Idx++];
911   Data.FailedImplicitMoveAssignment = Record[Idx++];
912 
913   Data.NumBases = Record[Idx++];
914   if (Data.NumBases)
915     Data.Bases = Reader.readCXXBaseSpecifiers(F, Record, Idx);
916   Data.NumVBases = Record[Idx++];
917   if (Data.NumVBases)
918     Data.VBases = Reader.readCXXBaseSpecifiers(F, Record, Idx);
919 
920   Reader.ReadUnresolvedSet(F, Data.Conversions, Record, Idx);
921   Reader.ReadUnresolvedSet(F, Data.VisibleConversions, Record, Idx);
922   assert(Data.Definition && "Data.Definition should be already set!");
923   Data.FirstFriend = ReadDeclAs<FriendDecl>(Record, Idx);
924 }
925 
926 void ASTDeclReader::InitializeCXXDefinitionData(CXXRecordDecl *D,
927                                                 CXXRecordDecl *DefinitionDecl,
928                                                 const RecordData &Record,
929                                                 unsigned &Idx) {
930   ASTContext &C = Reader.getContext();
931 
932   if (D == DefinitionDecl) {
933     D->DefinitionData = new (C) struct CXXRecordDecl::DefinitionData(D);
934     ReadCXXDefinitionData(*D->DefinitionData, Record, Idx);
935     // We read the definition info. Check if there are pending forward
936     // references that need to point to this DefinitionData pointer.
937     ASTReader::PendingForwardRefsMap::iterator
938         FindI = Reader.PendingForwardRefs.find(D);
939     if (FindI != Reader.PendingForwardRefs.end()) {
940       ASTReader::ForwardRefs &Refs = FindI->second;
941       for (ASTReader::ForwardRefs::iterator
942              I = Refs.begin(), E = Refs.end(); I != E; ++I)
943         (*I)->DefinitionData = D->DefinitionData;
944 #ifndef NDEBUG
945       // We later check whether PendingForwardRefs is empty to make sure all
946       // pending references were linked.
947       Reader.PendingForwardRefs.erase(D);
948 #endif
949     }
950   } else if (DefinitionDecl) {
951     if (DefinitionDecl->DefinitionData) {
952       D->DefinitionData = DefinitionDecl->DefinitionData;
953     } else {
954       // The definition is still initializing.
955       Reader.PendingForwardRefs[DefinitionDecl].push_back(D);
956     }
957   }
958 }
959 
960 void ASTDeclReader::VisitCXXRecordDecl(CXXRecordDecl *D) {
961   VisitRecordDecl(D);
962 
963   CXXRecordDecl *DefinitionDecl = ReadDeclAs<CXXRecordDecl>(Record, Idx);
964   InitializeCXXDefinitionData(D, DefinitionDecl, Record, Idx);
965 
966   ASTContext &C = Reader.getContext();
967 
968   enum CXXRecKind {
969     CXXRecNotTemplate = 0, CXXRecTemplate, CXXRecMemberSpecialization
970   };
971   switch ((CXXRecKind)Record[Idx++]) {
972   default:
973     llvm_unreachable("Out of sync with ASTDeclWriter::VisitCXXRecordDecl?");
974   case CXXRecNotTemplate:
975     break;
976   case CXXRecTemplate:
977     D->TemplateOrInstantiation = ReadDeclAs<ClassTemplateDecl>(Record, Idx);
978     break;
979   case CXXRecMemberSpecialization: {
980     CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(Record, Idx);
981     TemplateSpecializationKind TSK = (TemplateSpecializationKind)Record[Idx++];
982     SourceLocation POI = ReadSourceLocation(Record, Idx);
983     MemberSpecializationInfo *MSI = new (C) MemberSpecializationInfo(RD, TSK);
984     MSI->setPointOfInstantiation(POI);
985     D->TemplateOrInstantiation = MSI;
986     break;
987   }
988   }
989 
990   // Load the key function to avoid deserializing every method so we can
991   // compute it.
992   if (D->IsCompleteDefinition) {
993     if (CXXMethodDecl *Key = ReadDeclAs<CXXMethodDecl>(Record, Idx))
994       C.KeyFunctions[D] = Key;
995   }
996 }
997 
998 void ASTDeclReader::VisitCXXMethodDecl(CXXMethodDecl *D) {
999   VisitFunctionDecl(D);
1000   unsigned NumOverridenMethods = Record[Idx++];
1001   while (NumOverridenMethods--) {
1002     // Avoid invariant checking of CXXMethodDecl::addOverriddenMethod,
1003     // MD may be initializing.
1004     if (CXXMethodDecl *MD = ReadDeclAs<CXXMethodDecl>(Record, Idx))
1005       Reader.getContext().addOverriddenMethod(D, MD);
1006   }
1007 }
1008 
1009 void ASTDeclReader::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
1010   VisitCXXMethodDecl(D);
1011 
1012   D->IsExplicitSpecified = Record[Idx++];
1013   D->ImplicitlyDefined = Record[Idx++];
1014   llvm::tie(D->CtorInitializers, D->NumCtorInitializers)
1015       = Reader.ReadCXXCtorInitializers(F, Record, Idx);
1016 }
1017 
1018 void ASTDeclReader::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
1019   VisitCXXMethodDecl(D);
1020 
1021   D->ImplicitlyDefined = Record[Idx++];
1022   D->OperatorDelete = ReadDeclAs<FunctionDecl>(Record, Idx);
1023 }
1024 
1025 void ASTDeclReader::VisitCXXConversionDecl(CXXConversionDecl *D) {
1026   VisitCXXMethodDecl(D);
1027   D->IsExplicitSpecified = Record[Idx++];
1028 }
1029 
1030 void ASTDeclReader::VisitAccessSpecDecl(AccessSpecDecl *D) {
1031   VisitDecl(D);
1032   D->setColonLoc(ReadSourceLocation(Record, Idx));
1033 }
1034 
1035 void ASTDeclReader::VisitFriendDecl(FriendDecl *D) {
1036   VisitDecl(D);
1037   if (Record[Idx++])
1038     D->Friend = GetTypeSourceInfo(Record, Idx);
1039   else
1040     D->Friend = ReadDeclAs<NamedDecl>(Record, Idx);
1041   D->NextFriend = Record[Idx++];
1042   D->UnsupportedFriend = (Record[Idx++] != 0);
1043   D->FriendLoc = ReadSourceLocation(Record, Idx);
1044 }
1045 
1046 void ASTDeclReader::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
1047   VisitDecl(D);
1048   unsigned NumParams = Record[Idx++];
1049   D->NumParams = NumParams;
1050   D->Params = new TemplateParameterList*[NumParams];
1051   for (unsigned i = 0; i != NumParams; ++i)
1052     D->Params[i] = Reader.ReadTemplateParameterList(F, Record, Idx);
1053   if (Record[Idx++]) // HasFriendDecl
1054     D->Friend = ReadDeclAs<NamedDecl>(Record, Idx);
1055   else
1056     D->Friend = GetTypeSourceInfo(Record, Idx);
1057   D->FriendLoc = ReadSourceLocation(Record, Idx);
1058 }
1059 
1060 void ASTDeclReader::VisitTemplateDecl(TemplateDecl *D) {
1061   VisitNamedDecl(D);
1062 
1063   NamedDecl *TemplatedDecl = ReadDeclAs<NamedDecl>(Record, Idx);
1064   TemplateParameterList* TemplateParams
1065       = Reader.ReadTemplateParameterList(F, Record, Idx);
1066   D->init(TemplatedDecl, TemplateParams);
1067 }
1068 
1069 void ASTDeclReader::VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D) {
1070   // Initialize CommonOrPrev before VisitTemplateDecl so that getCommonPtr()
1071   // can be used while this is still initializing.
1072 
1073   assert(D->CommonOrPrev.isNull() && "getCommonPtr was called earlier on this");
1074   DeclID PreviousDeclID = ReadDeclID(Record, Idx);
1075   DeclID FirstDeclID =  PreviousDeclID ? ReadDeclID(Record, Idx) : 0;
1076   // We delay loading of the redeclaration chain to avoid deeply nested calls.
1077   // We temporarily set the first (canonical) declaration as the previous one
1078   // which is the one that matters and mark the real previous DeclID to be
1079   // loaded & attached later on.
1080   RedeclarableTemplateDecl *FirstDecl =
1081       cast_or_null<RedeclarableTemplateDecl>(Reader.GetDecl(FirstDeclID));
1082   assert((FirstDecl == 0 || FirstDecl->getKind() == D->getKind()) &&
1083          "FirstDecl kind mismatch");
1084   if (FirstDecl) {
1085     D->CommonOrPrev = FirstDecl;
1086     // Mark the real previous DeclID to be loaded & attached later on.
1087     if (PreviousDeclID != FirstDeclID)
1088       Reader.PendingPreviousDecls.push_back(std::make_pair(D, PreviousDeclID));
1089   } else {
1090     D->CommonOrPrev = D->newCommon(Reader.getContext());
1091     if (RedeclarableTemplateDecl *RTD
1092           = ReadDeclAs<RedeclarableTemplateDecl>(Record, Idx)) {
1093       assert(RTD->getKind() == D->getKind() &&
1094              "InstantiatedFromMemberTemplate kind mismatch");
1095       D->setInstantiatedFromMemberTemplateImpl(RTD);
1096       if (Record[Idx++])
1097         D->setMemberSpecialization();
1098     }
1099 
1100     RedeclarableTemplateDecl *LatestDecl
1101       = ReadDeclAs<RedeclarableTemplateDecl>(Record, Idx);
1102 
1103     // This decl is a first one and the latest declaration that it points to is
1104     // in the same AST file. However, if this actually needs to point to a
1105     // redeclaration in another AST file, we need to update it by checking
1106     // the FirstLatestDeclIDs map which tracks this kind of decls.
1107     assert(Reader.GetDecl(ThisDeclID) == D && "Invalid ThisDeclID ?");
1108     ASTReader::FirstLatestDeclIDMap::iterator I
1109         = Reader.FirstLatestDeclIDs.find(ThisDeclID);
1110     if (I != Reader.FirstLatestDeclIDs.end()) {
1111       if (Decl *NewLatest = Reader.GetDecl(I->second))
1112         LatestDecl = cast<RedeclarableTemplateDecl>(NewLatest);
1113     }
1114 
1115     assert(LatestDecl->getKind() == D->getKind() && "Latest kind mismatch");
1116     D->getCommonPtr()->Latest = LatestDecl;
1117   }
1118 
1119   VisitTemplateDecl(D);
1120   D->IdentifierNamespace = Record[Idx++];
1121 }
1122 
1123 void ASTDeclReader::VisitClassTemplateDecl(ClassTemplateDecl *D) {
1124   VisitRedeclarableTemplateDecl(D);
1125 
1126   if (D->getPreviousDeclaration() == 0) {
1127     // This ClassTemplateDecl owns a CommonPtr; read it to keep track of all of
1128     // the specializations.
1129     SmallVector<serialization::DeclID, 2> SpecIDs;
1130     SpecIDs.push_back(0);
1131 
1132     // Specializations.
1133     unsigned Size = Record[Idx++];
1134     SpecIDs[0] += Size;
1135     for (unsigned I = 0; I != Size; ++I)
1136       SpecIDs.push_back(ReadDeclID(Record, Idx));
1137 
1138     // Partial specializations.
1139     Size = Record[Idx++];
1140     SpecIDs[0] += Size;
1141     for (unsigned I = 0; I != Size; ++I)
1142       SpecIDs.push_back(ReadDeclID(Record, Idx));
1143 
1144     if (SpecIDs[0]) {
1145       typedef serialization::DeclID DeclID;
1146 
1147       ClassTemplateDecl::Common *CommonPtr = D->getCommonPtr();
1148       CommonPtr->LazySpecializations
1149         = new (Reader.getContext()) DeclID [SpecIDs.size()];
1150       memcpy(CommonPtr->LazySpecializations, SpecIDs.data(),
1151              SpecIDs.size() * sizeof(DeclID));
1152     }
1153 
1154     // InjectedClassNameType is computed.
1155   }
1156 }
1157 
1158 void ASTDeclReader::VisitClassTemplateSpecializationDecl(
1159                                            ClassTemplateSpecializationDecl *D) {
1160   VisitCXXRecordDecl(D);
1161 
1162   ASTContext &C = Reader.getContext();
1163   if (Decl *InstD = ReadDecl(Record, Idx)) {
1164     if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(InstD)) {
1165       D->SpecializedTemplate = CTD;
1166     } else {
1167       SmallVector<TemplateArgument, 8> TemplArgs;
1168       Reader.ReadTemplateArgumentList(TemplArgs, F, Record, Idx);
1169       TemplateArgumentList *ArgList
1170         = TemplateArgumentList::CreateCopy(C, TemplArgs.data(),
1171                                            TemplArgs.size());
1172       ClassTemplateSpecializationDecl::SpecializedPartialSpecialization *PS
1173           = new (C) ClassTemplateSpecializationDecl::
1174                                              SpecializedPartialSpecialization();
1175       PS->PartialSpecialization
1176           = cast<ClassTemplatePartialSpecializationDecl>(InstD);
1177       PS->TemplateArgs = ArgList;
1178       D->SpecializedTemplate = PS;
1179     }
1180   }
1181 
1182   // Explicit info.
1183   if (TypeSourceInfo *TyInfo = GetTypeSourceInfo(Record, Idx)) {
1184     ClassTemplateSpecializationDecl::ExplicitSpecializationInfo *ExplicitInfo
1185         = new (C) ClassTemplateSpecializationDecl::ExplicitSpecializationInfo;
1186     ExplicitInfo->TypeAsWritten = TyInfo;
1187     ExplicitInfo->ExternLoc = ReadSourceLocation(Record, Idx);
1188     ExplicitInfo->TemplateKeywordLoc = ReadSourceLocation(Record, Idx);
1189     D->ExplicitInfo = ExplicitInfo;
1190   }
1191 
1192   SmallVector<TemplateArgument, 8> TemplArgs;
1193   Reader.ReadTemplateArgumentList(TemplArgs, F, Record, Idx);
1194   D->TemplateArgs = TemplateArgumentList::CreateCopy(C, TemplArgs.data(),
1195                                                      TemplArgs.size());
1196   D->PointOfInstantiation = ReadSourceLocation(Record, Idx);
1197   D->SpecializationKind = (TemplateSpecializationKind)Record[Idx++];
1198 
1199   if (D->isCanonicalDecl()) { // It's kept in the folding set.
1200     ClassTemplateDecl *CanonPattern = ReadDeclAs<ClassTemplateDecl>(Record,Idx);
1201     if (ClassTemplatePartialSpecializationDecl *Partial
1202                        = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) {
1203       CanonPattern->getCommonPtr()->PartialSpecializations.InsertNode(Partial);
1204     } else {
1205       CanonPattern->getCommonPtr()->Specializations.InsertNode(D);
1206     }
1207   }
1208 }
1209 
1210 void ASTDeclReader::VisitClassTemplatePartialSpecializationDecl(
1211                                     ClassTemplatePartialSpecializationDecl *D) {
1212   VisitClassTemplateSpecializationDecl(D);
1213 
1214   ASTContext &C = Reader.getContext();
1215   D->TemplateParams = Reader.ReadTemplateParameterList(F, Record, Idx);
1216 
1217   unsigned NumArgs = Record[Idx++];
1218   if (NumArgs) {
1219     D->NumArgsAsWritten = NumArgs;
1220     D->ArgsAsWritten = new (C) TemplateArgumentLoc[NumArgs];
1221     for (unsigned i=0; i != NumArgs; ++i)
1222       D->ArgsAsWritten[i] = Reader.ReadTemplateArgumentLoc(F, Record, Idx);
1223   }
1224 
1225   D->SequenceNumber = Record[Idx++];
1226 
1227   // These are read/set from/to the first declaration.
1228   if (D->getPreviousDeclaration() == 0) {
1229     D->InstantiatedFromMember.setPointer(
1230       ReadDeclAs<ClassTemplatePartialSpecializationDecl>(Record, Idx));
1231     D->InstantiatedFromMember.setInt(Record[Idx++]);
1232   }
1233 }
1234 
1235 void ASTDeclReader::VisitClassScopeFunctionSpecializationDecl(
1236                                     ClassScopeFunctionSpecializationDecl *D) {
1237   VisitDecl(D);
1238   D->Specialization = ReadDeclAs<CXXMethodDecl>(Record, Idx);
1239 }
1240 
1241 void ASTDeclReader::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
1242   VisitRedeclarableTemplateDecl(D);
1243 
1244   if (D->getPreviousDeclaration() == 0) {
1245     // This FunctionTemplateDecl owns a CommonPtr; read it.
1246 
1247     // Read the function specialization declarations.
1248     // FunctionTemplateDecl's FunctionTemplateSpecializationInfos are filled
1249     // when reading the specialized FunctionDecl.
1250     unsigned NumSpecs = Record[Idx++];
1251     while (NumSpecs--)
1252       (void)ReadDecl(Record, Idx);
1253   }
1254 }
1255 
1256 void ASTDeclReader::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
1257   VisitTypeDecl(D);
1258 
1259   D->setDeclaredWithTypename(Record[Idx++]);
1260 
1261   bool Inherited = Record[Idx++];
1262   TypeSourceInfo *DefArg = GetTypeSourceInfo(Record, Idx);
1263   D->setDefaultArgument(DefArg, Inherited);
1264 }
1265 
1266 void ASTDeclReader::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
1267   VisitDeclaratorDecl(D);
1268   // TemplateParmPosition.
1269   D->setDepth(Record[Idx++]);
1270   D->setPosition(Record[Idx++]);
1271   if (D->isExpandedParameterPack()) {
1272     void **Data = reinterpret_cast<void **>(D + 1);
1273     for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
1274       Data[2*I] = Reader.readType(F, Record, Idx).getAsOpaquePtr();
1275       Data[2*I + 1] = GetTypeSourceInfo(Record, Idx);
1276     }
1277   } else {
1278     // Rest of NonTypeTemplateParmDecl.
1279     D->ParameterPack = Record[Idx++];
1280     if (Record[Idx++]) {
1281       Expr *DefArg = Reader.ReadExpr(F);
1282       bool Inherited = Record[Idx++];
1283       D->setDefaultArgument(DefArg, Inherited);
1284    }
1285   }
1286 }
1287 
1288 void ASTDeclReader::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
1289   VisitTemplateDecl(D);
1290   // TemplateParmPosition.
1291   D->setDepth(Record[Idx++]);
1292   D->setPosition(Record[Idx++]);
1293   // Rest of TemplateTemplateParmDecl.
1294   TemplateArgumentLoc Arg = Reader.ReadTemplateArgumentLoc(F, Record, Idx);
1295   bool IsInherited = Record[Idx++];
1296   D->setDefaultArgument(Arg, IsInherited);
1297   D->ParameterPack = Record[Idx++];
1298 }
1299 
1300 void ASTDeclReader::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
1301   VisitRedeclarableTemplateDecl(D);
1302 }
1303 
1304 void ASTDeclReader::VisitStaticAssertDecl(StaticAssertDecl *D) {
1305   VisitDecl(D);
1306   D->AssertExpr = Reader.ReadExpr(F);
1307   D->Message = cast<StringLiteral>(Reader.ReadExpr(F));
1308   D->RParenLoc = ReadSourceLocation(Record, Idx);
1309 }
1310 
1311 std::pair<uint64_t, uint64_t>
1312 ASTDeclReader::VisitDeclContext(DeclContext *DC) {
1313   uint64_t LexicalOffset = Record[Idx++];
1314   uint64_t VisibleOffset = Record[Idx++];
1315   return std::make_pair(LexicalOffset, VisibleOffset);
1316 }
1317 
1318 template <typename T>
1319 void ASTDeclReader::VisitRedeclarable(Redeclarable<T> *D) {
1320   enum RedeclKind { NoRedeclaration = 0, PointsToPrevious, PointsToLatest };
1321   RedeclKind Kind = (RedeclKind)Record[Idx++];
1322   switch (Kind) {
1323   default:
1324     llvm_unreachable("Out of sync with ASTDeclWriter::VisitRedeclarable or"
1325                      " messed up reading");
1326   case NoRedeclaration:
1327     break;
1328   case PointsToPrevious: {
1329     DeclID PreviousDeclID = ReadDeclID(Record, Idx);
1330     DeclID FirstDeclID = ReadDeclID(Record, Idx);
1331     // We delay loading of the redeclaration chain to avoid deeply nested calls.
1332     // We temporarily set the first (canonical) declaration as the previous one
1333     // which is the one that matters and mark the real previous DeclID to be
1334     // loaded & attached later on.
1335     T *FirstDecl = cast_or_null<T>(Reader.GetDecl(FirstDeclID));
1336     D->RedeclLink = typename Redeclarable<T>::PreviousDeclLink(FirstDecl);
1337     if (PreviousDeclID != FirstDeclID)
1338       Reader.PendingPreviousDecls.push_back(std::make_pair(static_cast<T*>(D),
1339                                                            PreviousDeclID));
1340 
1341     // If the first declaration in the chain is in an inconsistent
1342     // state where it thinks that it is the only declaration, fix its
1343     // redeclaration link now to point at this declaration, so that we have a
1344     // proper redeclaration chain.
1345     if (FirstDecl->RedeclLink.getPointer() == FirstDecl) {
1346       FirstDecl->RedeclLink
1347         = typename Redeclarable<T>::LatestDeclLink(static_cast<T*>(D));
1348     }
1349     break;
1350   }
1351   case PointsToLatest: {
1352     T *LatestDecl = ReadDeclAs<T>(Record, Idx);
1353     D->RedeclLink = typename Redeclarable<T>::LatestDeclLink(LatestDecl);
1354 
1355     // If the latest declaration in the chain is in an inconsistent
1356     // state where it thinks that it is the only declaration, fix its
1357     // redeclaration link now to point at this declaration, so that we have a
1358     // proper redeclaration chain.
1359     if (LatestDecl->RedeclLink.getPointer() == LatestDecl) {
1360       LatestDecl->RedeclLink
1361         = typename Redeclarable<T>::PreviousDeclLink(static_cast<T*>(D));
1362     }
1363     break;
1364   }
1365   }
1366 
1367   assert(!(Kind == PointsToPrevious &&
1368            Reader.FirstLatestDeclIDs.find(ThisDeclID) !=
1369                Reader.FirstLatestDeclIDs.end()) &&
1370          "This decl is not first, it should not be in the map");
1371   if (Kind == PointsToPrevious)
1372     return;
1373 
1374   // This decl is a first one and the latest declaration that it points to is in
1375   // the same AST file. However, if this actually needs to point to a
1376   // redeclaration in another AST file, we need to update it by checking the
1377   // FirstLatestDeclIDs map which tracks this kind of decls.
1378   assert(Reader.GetDecl(ThisDeclID) == static_cast<T*>(D) &&
1379          "Invalid ThisDeclID ?");
1380   ASTReader::FirstLatestDeclIDMap::iterator I
1381       = Reader.FirstLatestDeclIDs.find(ThisDeclID);
1382   if (I != Reader.FirstLatestDeclIDs.end()) {
1383     Decl *NewLatest = Reader.GetDecl(I->second);
1384     D->RedeclLink
1385         = typename Redeclarable<T>::LatestDeclLink(cast_or_null<T>(NewLatest));
1386   }
1387 }
1388 
1389 //===----------------------------------------------------------------------===//
1390 // Attribute Reading
1391 //===----------------------------------------------------------------------===//
1392 
1393 /// \brief Reads attributes from the current stream position.
1394 void ASTReader::ReadAttributes(Module &F, AttrVec &Attrs,
1395                                const RecordData &Record, unsigned &Idx) {
1396   for (unsigned i = 0, e = Record[Idx++]; i != e; ++i) {
1397     Attr *New = 0;
1398     attr::Kind Kind = (attr::Kind)Record[Idx++];
1399     SourceRange Range = ReadSourceRange(F, Record, Idx);
1400 
1401 #include "clang/Serialization/AttrPCHRead.inc"
1402 
1403     assert(New && "Unable to decode attribute?");
1404     Attrs.push_back(New);
1405   }
1406 }
1407 
1408 //===----------------------------------------------------------------------===//
1409 // ASTReader Implementation
1410 //===----------------------------------------------------------------------===//
1411 
1412 /// \brief Note that we have loaded the declaration with the given
1413 /// Index.
1414 ///
1415 /// This routine notes that this declaration has already been loaded,
1416 /// so that future GetDecl calls will return this declaration rather
1417 /// than trying to load a new declaration.
1418 inline void ASTReader::LoadedDecl(unsigned Index, Decl *D) {
1419   assert(!DeclsLoaded[Index] && "Decl loaded twice?");
1420   DeclsLoaded[Index] = D;
1421 }
1422 
1423 
1424 /// \brief Determine whether the consumer will be interested in seeing
1425 /// this declaration (via HandleTopLevelDecl).
1426 ///
1427 /// This routine should return true for anything that might affect
1428 /// code generation, e.g., inline function definitions, Objective-C
1429 /// declarations with metadata, etc.
1430 static bool isConsumerInterestedIn(Decl *D) {
1431   // An ObjCMethodDecl is never considered as "interesting" because its
1432   // implementation container always is.
1433 
1434   if (isa<FileScopeAsmDecl>(D) ||
1435       isa<ObjCProtocolDecl>(D) ||
1436       isa<ObjCImplDecl>(D))
1437     return true;
1438   if (VarDecl *Var = dyn_cast<VarDecl>(D))
1439     return Var->isFileVarDecl() &&
1440            Var->isThisDeclarationADefinition() == VarDecl::Definition;
1441   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(D))
1442     return Func->doesThisDeclarationHaveABody();
1443 
1444   return false;
1445 }
1446 
1447 /// \brief Get the correct cursor and offset for loading a declaration.
1448 ASTReader::RecordLocation
1449 ASTReader::DeclCursorForID(DeclID ID, unsigned &RawLocation) {
1450   // See if there's an override.
1451   DeclReplacementMap::iterator It = ReplacedDecls.find(ID);
1452   if (It != ReplacedDecls.end()) {
1453     RawLocation = It->second.RawLoc;
1454     return RecordLocation(It->second.Mod, It->second.Offset);
1455   }
1456 
1457   GlobalDeclMapType::iterator I = GlobalDeclMap.find(ID);
1458   assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
1459   Module *M = I->second;
1460   const DeclOffset &
1461     DOffs =  M->DeclOffsets[ID - M->BaseDeclID - NUM_PREDEF_DECL_IDS];
1462   RawLocation = DOffs.Loc;
1463   return RecordLocation(M, DOffs.BitOffset);
1464 }
1465 
1466 ASTReader::RecordLocation ASTReader::getLocalBitOffset(uint64_t GlobalOffset) {
1467   ContinuousRangeMap<uint64_t, Module*, 4>::iterator I
1468     = GlobalBitOffsetsMap.find(GlobalOffset);
1469 
1470   assert(I != GlobalBitOffsetsMap.end() && "Corrupted global bit offsets map");
1471   return RecordLocation(I->second, GlobalOffset - I->second->GlobalBitOffset);
1472 }
1473 
1474 uint64_t ASTReader::getGlobalBitOffset(Module &M, uint32_t LocalOffset) {
1475   return LocalOffset + M.GlobalBitOffset;
1476 }
1477 
1478 void ASTDeclReader::attachPreviousDecl(Decl *D, Decl *previous) {
1479   assert(D && previous);
1480   if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
1481     TD->RedeclLink.setPointer(cast<TagDecl>(previous));
1482   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1483     FD->RedeclLink.setPointer(cast<FunctionDecl>(previous));
1484   } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
1485     VD->RedeclLink.setPointer(cast<VarDecl>(previous));
1486   } else {
1487     RedeclarableTemplateDecl *TD = cast<RedeclarableTemplateDecl>(D);
1488     TD->CommonOrPrev = cast<RedeclarableTemplateDecl>(previous);
1489   }
1490 }
1491 
1492 void ASTReader::loadAndAttachPreviousDecl(Decl *D, serialization::DeclID ID) {
1493   Decl *previous = GetDecl(ID);
1494   ASTDeclReader::attachPreviousDecl(D, previous);
1495 }
1496 
1497 /// \brief Read the declaration at the given offset from the AST file.
1498 Decl *ASTReader::ReadDeclRecord(DeclID ID) {
1499   unsigned Index = ID - NUM_PREDEF_DECL_IDS;
1500   unsigned RawLocation = 0;
1501   RecordLocation Loc = DeclCursorForID(ID, RawLocation);
1502   llvm::BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
1503   // Keep track of where we are in the stream, then jump back there
1504   // after reading this declaration.
1505   SavedStreamPosition SavedPosition(DeclsCursor);
1506 
1507   ReadingKindTracker ReadingKind(Read_Decl, *this);
1508 
1509   // Note that we are loading a declaration record.
1510   Deserializing ADecl(this);
1511 
1512   DeclsCursor.JumpToBit(Loc.Offset);
1513   RecordData Record;
1514   unsigned Code = DeclsCursor.ReadCode();
1515   unsigned Idx = 0;
1516   ASTDeclReader Reader(*this, *Loc.F, DeclsCursor, ID, RawLocation, Record,Idx);
1517 
1518   Decl *D = 0;
1519   switch ((DeclCode)DeclsCursor.ReadRecord(Code, Record)) {
1520   case DECL_CONTEXT_LEXICAL:
1521   case DECL_CONTEXT_VISIBLE:
1522     llvm_unreachable("Record cannot be de-serialized with ReadDeclRecord");
1523   case DECL_TYPEDEF:
1524     D = TypedefDecl::Create(Context, 0, SourceLocation(), SourceLocation(),
1525                             0, 0);
1526     break;
1527   case DECL_TYPEALIAS:
1528     D = TypeAliasDecl::Create(Context, 0, SourceLocation(), SourceLocation(),
1529                               0, 0);
1530     break;
1531   case DECL_ENUM:
1532     D = EnumDecl::Create(Context, Decl::EmptyShell());
1533     break;
1534   case DECL_RECORD:
1535     D = RecordDecl::Create(Context, Decl::EmptyShell());
1536     break;
1537   case DECL_ENUM_CONSTANT:
1538     D = EnumConstantDecl::Create(Context, 0, SourceLocation(), 0, QualType(),
1539                                  0, llvm::APSInt());
1540     break;
1541   case DECL_FUNCTION:
1542     D = FunctionDecl::Create(Context, 0, SourceLocation(), SourceLocation(),
1543                              DeclarationName(), QualType(), 0);
1544     break;
1545   case DECL_LINKAGE_SPEC:
1546     D = LinkageSpecDecl::Create(Context, 0, SourceLocation(), SourceLocation(),
1547                                 (LinkageSpecDecl::LanguageIDs)0,
1548                                 SourceLocation());
1549     break;
1550   case DECL_LABEL:
1551     D = LabelDecl::Create(Context, 0, SourceLocation(), 0);
1552     break;
1553   case DECL_NAMESPACE:
1554     D = NamespaceDecl::Create(Context, 0, SourceLocation(),
1555                               SourceLocation(), 0);
1556     break;
1557   case DECL_NAMESPACE_ALIAS:
1558     D = NamespaceAliasDecl::Create(Context, 0, SourceLocation(),
1559                                    SourceLocation(), 0,
1560                                    NestedNameSpecifierLoc(),
1561                                    SourceLocation(), 0);
1562     break;
1563   case DECL_USING:
1564     D = UsingDecl::Create(Context, 0, SourceLocation(),
1565                           NestedNameSpecifierLoc(), DeclarationNameInfo(),
1566                           false);
1567     break;
1568   case DECL_USING_SHADOW:
1569     D = UsingShadowDecl::Create(Context, 0, SourceLocation(), 0, 0);
1570     break;
1571   case DECL_USING_DIRECTIVE:
1572     D = UsingDirectiveDecl::Create(Context, 0, SourceLocation(),
1573                                    SourceLocation(), NestedNameSpecifierLoc(),
1574                                    SourceLocation(), 0, 0);
1575     break;
1576   case DECL_UNRESOLVED_USING_VALUE:
1577     D = UnresolvedUsingValueDecl::Create(Context, 0, SourceLocation(),
1578                                          NestedNameSpecifierLoc(),
1579                                          DeclarationNameInfo());
1580     break;
1581   case DECL_UNRESOLVED_USING_TYPENAME:
1582     D = UnresolvedUsingTypenameDecl::Create(Context, 0, SourceLocation(),
1583                                             SourceLocation(),
1584                                             NestedNameSpecifierLoc(),
1585                                             SourceLocation(),
1586                                             DeclarationName());
1587     break;
1588   case DECL_CXX_RECORD:
1589     D = CXXRecordDecl::Create(Context, Decl::EmptyShell());
1590     break;
1591   case DECL_CXX_METHOD:
1592     D = CXXMethodDecl::Create(Context, 0, SourceLocation(),
1593                               DeclarationNameInfo(), QualType(), 0,
1594                               false, SC_None, false, false, SourceLocation());
1595     break;
1596   case DECL_CXX_CONSTRUCTOR:
1597     D = CXXConstructorDecl::Create(Context, Decl::EmptyShell());
1598     break;
1599   case DECL_CXX_DESTRUCTOR:
1600     D = CXXDestructorDecl::Create(Context, Decl::EmptyShell());
1601     break;
1602   case DECL_CXX_CONVERSION:
1603     D = CXXConversionDecl::Create(Context, Decl::EmptyShell());
1604     break;
1605   case DECL_ACCESS_SPEC:
1606     D = AccessSpecDecl::Create(Context, Decl::EmptyShell());
1607     break;
1608   case DECL_FRIEND:
1609     D = FriendDecl::Create(Context, Decl::EmptyShell());
1610     break;
1611   case DECL_FRIEND_TEMPLATE:
1612     D = FriendTemplateDecl::Create(Context, Decl::EmptyShell());
1613     break;
1614   case DECL_CLASS_TEMPLATE:
1615     D = ClassTemplateDecl::Create(Context, Decl::EmptyShell());
1616     break;
1617   case DECL_CLASS_TEMPLATE_SPECIALIZATION:
1618     D = ClassTemplateSpecializationDecl::Create(Context, Decl::EmptyShell());
1619     break;
1620   case DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION:
1621     D = ClassTemplatePartialSpecializationDecl::Create(Context,
1622                                                        Decl::EmptyShell());
1623     break;
1624   case DECL_CLASS_SCOPE_FUNCTION_SPECIALIZATION:
1625     D = ClassScopeFunctionSpecializationDecl::Create(Context,
1626                                                      Decl::EmptyShell());
1627     break;
1628   case DECL_FUNCTION_TEMPLATE:
1629       D = FunctionTemplateDecl::Create(Context, Decl::EmptyShell());
1630     break;
1631   case DECL_TEMPLATE_TYPE_PARM:
1632     D = TemplateTypeParmDecl::Create(Context, Decl::EmptyShell());
1633     break;
1634   case DECL_NON_TYPE_TEMPLATE_PARM:
1635     D = NonTypeTemplateParmDecl::Create(Context, 0, SourceLocation(),
1636                                         SourceLocation(), 0, 0, 0, QualType(),
1637                                         false, 0);
1638     break;
1639   case DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK:
1640     D = NonTypeTemplateParmDecl::Create(Context, 0, SourceLocation(),
1641                                         SourceLocation(), 0, 0, 0, QualType(),
1642                                         0, 0, Record[Idx++], 0);
1643     break;
1644   case DECL_TEMPLATE_TEMPLATE_PARM:
1645     D = TemplateTemplateParmDecl::Create(Context, 0, SourceLocation(), 0, 0,
1646                                          false, 0, 0);
1647     break;
1648   case DECL_TYPE_ALIAS_TEMPLATE:
1649     D = TypeAliasTemplateDecl::Create(Context, Decl::EmptyShell());
1650     break;
1651   case DECL_STATIC_ASSERT:
1652     D = StaticAssertDecl::Create(Context, 0, SourceLocation(), 0, 0,
1653                                  SourceLocation());
1654     break;
1655 
1656   case DECL_OBJC_METHOD:
1657     D = ObjCMethodDecl::Create(Context, SourceLocation(), SourceLocation(),
1658                                Selector(), QualType(), 0, 0);
1659     break;
1660   case DECL_OBJC_INTERFACE:
1661     D = ObjCInterfaceDecl::Create(Context, 0, SourceLocation(), 0);
1662     break;
1663   case DECL_OBJC_IVAR:
1664     D = ObjCIvarDecl::Create(Context, 0, SourceLocation(), SourceLocation(),
1665                              0, QualType(), 0, ObjCIvarDecl::None);
1666     break;
1667   case DECL_OBJC_PROTOCOL:
1668     D = ObjCProtocolDecl::Create(Context, 0, 0, SourceLocation(),
1669                                  SourceLocation(), 0);
1670     break;
1671   case DECL_OBJC_AT_DEFS_FIELD:
1672     D = ObjCAtDefsFieldDecl::Create(Context, 0, SourceLocation(),
1673                                     SourceLocation(), 0, QualType(), 0);
1674     break;
1675   case DECL_OBJC_CLASS:
1676     D = ObjCClassDecl::Create(Context, 0, SourceLocation());
1677     break;
1678   case DECL_OBJC_FORWARD_PROTOCOL:
1679     D = ObjCForwardProtocolDecl::Create(Context, 0, SourceLocation());
1680     break;
1681   case DECL_OBJC_CATEGORY:
1682     D = ObjCCategoryDecl::Create(Context, Decl::EmptyShell());
1683     break;
1684   case DECL_OBJC_CATEGORY_IMPL:
1685     D = ObjCCategoryImplDecl::Create(Context, 0, 0, 0, SourceLocation(),
1686                                      SourceLocation());
1687     break;
1688   case DECL_OBJC_IMPLEMENTATION:
1689     D = ObjCImplementationDecl::Create(Context, 0, 0, 0, SourceLocation(),
1690                                        SourceLocation());
1691     break;
1692   case DECL_OBJC_COMPATIBLE_ALIAS:
1693     D = ObjCCompatibleAliasDecl::Create(Context, 0, SourceLocation(), 0, 0);
1694     break;
1695   case DECL_OBJC_PROPERTY:
1696     D = ObjCPropertyDecl::Create(Context, 0, SourceLocation(), 0, SourceLocation(),
1697                                  0);
1698     break;
1699   case DECL_OBJC_PROPERTY_IMPL:
1700     D = ObjCPropertyImplDecl::Create(Context, 0, SourceLocation(),
1701                                      SourceLocation(), 0,
1702                                      ObjCPropertyImplDecl::Dynamic, 0,
1703                                      SourceLocation());
1704     break;
1705   case DECL_FIELD:
1706     D = FieldDecl::Create(Context, 0, SourceLocation(), SourceLocation(), 0,
1707                           QualType(), 0, 0, false, false);
1708     break;
1709   case DECL_INDIRECTFIELD:
1710     D = IndirectFieldDecl::Create(Context, 0, SourceLocation(), 0, QualType(),
1711                                   0, 0);
1712     break;
1713   case DECL_VAR:
1714     D = VarDecl::Create(Context, 0, SourceLocation(), SourceLocation(), 0,
1715                         QualType(), 0, SC_None, SC_None);
1716     break;
1717 
1718   case DECL_IMPLICIT_PARAM:
1719     D = ImplicitParamDecl::Create(Context, 0, SourceLocation(), 0, QualType());
1720     break;
1721 
1722   case DECL_PARM_VAR:
1723     D = ParmVarDecl::Create(Context, 0, SourceLocation(), SourceLocation(), 0,
1724                             QualType(), 0, SC_None, SC_None, 0);
1725     break;
1726   case DECL_FILE_SCOPE_ASM:
1727     D = FileScopeAsmDecl::Create(Context, 0, 0, SourceLocation(),
1728                                  SourceLocation());
1729     break;
1730   case DECL_BLOCK:
1731     D = BlockDecl::Create(Context, 0, SourceLocation());
1732     break;
1733   case DECL_CXX_BASE_SPECIFIERS:
1734     Error("attempt to read a C++ base-specifier record as a declaration");
1735     return 0;
1736   }
1737 
1738   assert(D && "Unknown declaration reading AST file");
1739   LoadedDecl(Index, D);
1740   Reader.Visit(D);
1741 
1742   // If this declaration is also a declaration context, get the
1743   // offsets for its tables of lexical and visible declarations.
1744   if (DeclContext *DC = dyn_cast<DeclContext>(D)) {
1745     std::pair<uint64_t, uint64_t> Offsets = Reader.VisitDeclContext(DC);
1746     if (Offsets.first || Offsets.second) {
1747       if (Offsets.first != 0)
1748         DC->setHasExternalLexicalStorage(true);
1749       if (Offsets.second != 0)
1750         DC->setHasExternalVisibleStorage(true);
1751       if (ReadDeclContextStorage(*Loc.F, DeclsCursor, Offsets,
1752                                  Loc.F->DeclContextInfos[DC]))
1753         return 0;
1754     }
1755 
1756     // Now add the pending visible updates for this decl context, if it has any.
1757     DeclContextVisibleUpdatesPending::iterator I =
1758         PendingVisibleUpdates.find(ID);
1759     if (I != PendingVisibleUpdates.end()) {
1760       // There are updates. This means the context has external visible
1761       // storage, even if the original stored version didn't.
1762       DC->setHasExternalVisibleStorage(true);
1763       DeclContextVisibleUpdates &U = I->second;
1764       for (DeclContextVisibleUpdates::iterator UI = U.begin(), UE = U.end();
1765            UI != UE; ++UI) {
1766         UI->second->DeclContextInfos[DC].NameLookupTableData = UI->first;
1767       }
1768       PendingVisibleUpdates.erase(I);
1769     }
1770   }
1771   assert(Idx == Record.size());
1772 
1773   // Load any relevant update records.
1774   loadDeclUpdateRecords(ID, D);
1775 
1776   if (ObjCChainedCategoriesInterfaces.count(ID))
1777     loadObjCChainedCategories(ID, cast<ObjCInterfaceDecl>(D));
1778 
1779   // If we have deserialized a declaration that has a definition the
1780   // AST consumer might need to know about, queue it.
1781   // We don't pass it to the consumer immediately because we may be in recursive
1782   // loading, and some declarations may still be initializing.
1783   if (isConsumerInterestedIn(D))
1784       InterestingDecls.push_back(D);
1785 
1786   return D;
1787 }
1788 
1789 void ASTReader::loadDeclUpdateRecords(serialization::DeclID ID, Decl *D) {
1790   // The declaration may have been modified by files later in the chain.
1791   // If this is the case, read the record containing the updates from each file
1792   // and pass it to ASTDeclReader to make the modifications.
1793   DeclUpdateOffsetsMap::iterator UpdI = DeclUpdateOffsets.find(ID);
1794   if (UpdI != DeclUpdateOffsets.end()) {
1795     FileOffsetsTy &UpdateOffsets = UpdI->second;
1796     for (FileOffsetsTy::iterator
1797          I = UpdateOffsets.begin(), E = UpdateOffsets.end(); I != E; ++I) {
1798       Module *F = I->first;
1799       uint64_t Offset = I->second;
1800       llvm::BitstreamCursor &Cursor = F->DeclsCursor;
1801       SavedStreamPosition SavedPosition(Cursor);
1802       Cursor.JumpToBit(Offset);
1803       RecordData Record;
1804       unsigned Code = Cursor.ReadCode();
1805       unsigned RecCode = Cursor.ReadRecord(Code, Record);
1806       (void)RecCode;
1807       assert(RecCode == DECL_UPDATES && "Expected DECL_UPDATES record!");
1808 
1809       unsigned Idx = 0;
1810       ASTDeclReader Reader(*this, *F, Cursor, ID, 0, Record, Idx);
1811       Reader.UpdateDecl(D, *F, Record);
1812     }
1813   }
1814 }
1815 
1816 namespace {
1817   /// \brief Given an ObjC interface, goes through the modules and links to the
1818   /// interface all the categories for it.
1819   class ObjCChainedCategoriesVisitor {
1820     ASTReader &Reader;
1821     serialization::GlobalDeclID InterfaceID;
1822     ObjCInterfaceDecl *Interface;
1823     ObjCCategoryDecl *GlobHeadCat, *GlobTailCat;
1824     llvm::DenseMap<DeclarationName, ObjCCategoryDecl *> NameCategoryMap;
1825 
1826   public:
1827     ObjCChainedCategoriesVisitor(ASTReader &Reader,
1828                                  serialization::GlobalDeclID InterfaceID,
1829                                  ObjCInterfaceDecl *Interface)
1830       : Reader(Reader), InterfaceID(InterfaceID), Interface(Interface),
1831         GlobHeadCat(0), GlobTailCat(0) { }
1832 
1833     static bool visit(Module &M, void *UserData) {
1834       return static_cast<ObjCChainedCategoriesVisitor *>(UserData)->visit(M);
1835     }
1836 
1837     bool visit(Module &M) {
1838       if (Reader.isDeclIDFromModule(InterfaceID, M))
1839         return true; // We reached the module where the interface originated
1840                     // from. Stop traversing the imported modules.
1841 
1842       Module::ChainedObjCCategoriesMap::iterator
1843         I = M.ChainedObjCCategories.find(InterfaceID);
1844       if (I == M.ChainedObjCCategories.end())
1845         return false;
1846 
1847       ObjCCategoryDecl *
1848         HeadCat = Reader.GetLocalDeclAs<ObjCCategoryDecl>(M, I->second.first);
1849       ObjCCategoryDecl *
1850         TailCat = Reader.GetLocalDeclAs<ObjCCategoryDecl>(M, I->second.second);
1851 
1852       addCategories(HeadCat, TailCat);
1853       return false;
1854     }
1855 
1856     void addCategories(ObjCCategoryDecl *HeadCat,
1857                        ObjCCategoryDecl *TailCat = 0) {
1858       if (!HeadCat) {
1859         assert(!TailCat);
1860         return;
1861       }
1862 
1863       if (!TailCat) {
1864         TailCat = HeadCat;
1865         while (TailCat->getNextClassCategory())
1866           TailCat = TailCat->getNextClassCategory();
1867       }
1868 
1869       if (!GlobHeadCat) {
1870         GlobHeadCat = HeadCat;
1871         GlobTailCat = TailCat;
1872       } else {
1873         ASTDeclReader::setNextObjCCategory(GlobTailCat, HeadCat);
1874         GlobTailCat = TailCat;
1875       }
1876 
1877       llvm::DenseSet<DeclarationName> Checked;
1878       for (ObjCCategoryDecl *Cat = HeadCat,
1879                             *CatEnd = TailCat->getNextClassCategory();
1880              Cat != CatEnd; Cat = Cat->getNextClassCategory()) {
1881         if (Checked.count(Cat->getDeclName()))
1882           continue;
1883         Checked.insert(Cat->getDeclName());
1884         checkForDuplicate(Cat);
1885       }
1886     }
1887 
1888     /// \brief Warns for duplicate categories that come from different modules.
1889     void checkForDuplicate(ObjCCategoryDecl *Cat) {
1890       DeclarationName Name = Cat->getDeclName();
1891       // Find the top category with the same name. We do not want to warn for
1892       // duplicates along the established chain because there were already
1893       // warnings for them when the module was created. We only want to warn for
1894       // duplicates between non-dependent modules:
1895       //
1896       //   MT     //
1897       //  /  \    //
1898       // ML  MR   //
1899       //
1900       // We want to warn for duplicates between ML and MR,not between ML and MT.
1901       //
1902       // FIXME: We should not warn for duplicates in diamond:
1903       //
1904       //   MT     //
1905       //  /  \    //
1906       // ML  MR   //
1907       //  \  /    //
1908       //   MB     //
1909       //
1910       // If there are duplicates in ML/MR, there will be warning when creating
1911       // MB *and* when importing MB. We should not warn when importing.
1912       for (ObjCCategoryDecl *Next = Cat->getNextClassCategory(); Next;
1913              Next = Next->getNextClassCategory()) {
1914         if (Next->getDeclName() == Name)
1915           Cat = Next;
1916       }
1917 
1918       ObjCCategoryDecl *&PrevCat = NameCategoryMap[Name];
1919       if (!PrevCat)
1920         PrevCat = Cat;
1921 
1922       if (PrevCat != Cat) {
1923         Reader.Diag(Cat->getLocation(), diag::warn_dup_category_def)
1924           << Interface->getDeclName() << Name;
1925         Reader.Diag(PrevCat->getLocation(), diag::note_previous_definition);
1926       }
1927     }
1928 
1929     ObjCCategoryDecl *getHeadCategory() const { return GlobHeadCat; }
1930   };
1931 }
1932 
1933 void ASTReader::loadObjCChainedCategories(serialization::GlobalDeclID ID,
1934                                           ObjCInterfaceDecl *D) {
1935   ObjCChainedCategoriesVisitor Visitor(*this, ID, D);
1936   ModuleMgr.visit(ObjCChainedCategoriesVisitor::visit, &Visitor);
1937   // Also add the categories that the interface already links to.
1938   Visitor.addCategories(D->getCategoryList());
1939   D->setCategoryList(Visitor.getHeadCategory());
1940 }
1941 
1942 void ASTDeclReader::UpdateDecl(Decl *D, Module &Module,
1943                                const RecordData &Record) {
1944   unsigned Idx = 0;
1945   while (Idx < Record.size()) {
1946     switch ((DeclUpdateKind)Record[Idx++]) {
1947     case UPD_CXX_SET_DEFINITIONDATA: {
1948       CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
1949       CXXRecordDecl *DefinitionDecl
1950         = Reader.ReadDeclAs<CXXRecordDecl>(Module, Record, Idx);
1951       assert(!RD->DefinitionData && "DefinitionData is already set!");
1952       InitializeCXXDefinitionData(RD, DefinitionDecl, Record, Idx);
1953       break;
1954     }
1955 
1956     case UPD_CXX_ADDED_IMPLICIT_MEMBER:
1957       cast<CXXRecordDecl>(D)->addedMember(Reader.ReadDecl(Module, Record, Idx));
1958       break;
1959 
1960     case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
1961       // It will be added to the template's specializations set when loaded.
1962       (void)Reader.ReadDecl(Module, Record, Idx);
1963       break;
1964 
1965     case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE: {
1966       NamespaceDecl *Anon
1967         = Reader.ReadDeclAs<NamespaceDecl>(Module, Record, Idx);
1968       // Guard against these being loaded out of original order. Don't use
1969       // getNextNamespace(), since it tries to access the context and can't in
1970       // the middle of deserialization.
1971       if (!Anon->NextNamespace) {
1972         if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(D))
1973           TU->setAnonymousNamespace(Anon);
1974         else
1975           cast<NamespaceDecl>(D)->OrigOrAnonNamespace.setPointer(Anon);
1976       }
1977       break;
1978     }
1979 
1980     case UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER:
1981       cast<VarDecl>(D)->getMemberSpecializationInfo()->setPointOfInstantiation(
1982           Reader.ReadSourceLocation(Module, Record, Idx));
1983       break;
1984     }
1985   }
1986 }
1987