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/AST/ASTConsumer.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/DeclVisitor.h"
20 #include "clang/AST/DeclGroup.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/Expr.h"
24 using namespace clang;
25 using namespace clang::serialization;
26 
27 //===----------------------------------------------------------------------===//
28 // Declaration deserialization
29 //===----------------------------------------------------------------------===//
30 
31 namespace clang {
32   class ASTDeclReader : public DeclVisitor<ASTDeclReader, void> {
33     ASTReader &Reader;
34     ASTReader::PerFileData &F;
35     llvm::BitstreamCursor &Cursor;
36     const DeclID ThisDeclID;
37     typedef ASTReader::RecordData RecordData;
38     const RecordData &Record;
39     unsigned &Idx;
40     TypeID TypeIDForTypeDecl;
41 
42     uint64_t GetCurrentCursorOffset();
43     SourceLocation ReadSourceLocation(const RecordData &R, unsigned &I) {
44       return Reader.ReadSourceLocation(F, R, I);
45     }
46     SourceRange ReadSourceRange(const RecordData &R, unsigned &I) {
47       return Reader.ReadSourceRange(F, R, I);
48     }
49     TypeSourceInfo *GetTypeSourceInfo(const RecordData &R, unsigned &I) {
50       return Reader.GetTypeSourceInfo(F, R, I);
51     }
52     void ReadQualifierInfo(QualifierInfo &Info,
53                            const RecordData &R, unsigned &I) {
54       Reader.ReadQualifierInfo(F, Info, R, I);
55     }
56     void ReadDeclarationNameLoc(DeclarationNameLoc &DNLoc, DeclarationName Name,
57                                 const RecordData &R, unsigned &I) {
58       Reader.ReadDeclarationNameLoc(F, DNLoc, Name, R, I);
59     }
60     void ReadDeclarationNameInfo(DeclarationNameInfo &NameInfo,
61                                 const RecordData &R, unsigned &I) {
62       Reader.ReadDeclarationNameInfo(F, NameInfo, R, I);
63     }
64 
65     void ReadCXXDefinitionData(struct CXXRecordDecl::DefinitionData &Data,
66                                const RecordData &R, unsigned &I);
67 
68     void InitializeCXXDefinitionData(CXXRecordDecl *D,
69                                      CXXRecordDecl *DefinitionDecl,
70                                      const RecordData &Record, unsigned &Idx);
71   public:
72     ASTDeclReader(ASTReader &Reader, ASTReader::PerFileData &F,
73                   llvm::BitstreamCursor &Cursor, DeclID thisDeclID,
74                   const RecordData &Record, unsigned &Idx)
75       : Reader(Reader), F(F), Cursor(Cursor), ThisDeclID(thisDeclID),
76         Record(Record), Idx(Idx), TypeIDForTypeDecl(0) { }
77 
78     void Visit(Decl *D);
79 
80     void UpdateDecl(Decl *D, const RecordData &Record);
81 
82     void VisitDecl(Decl *D);
83     void VisitTranslationUnitDecl(TranslationUnitDecl *TU);
84     void VisitNamedDecl(NamedDecl *ND);
85     void VisitNamespaceDecl(NamespaceDecl *D);
86     void VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
87     void VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
88     void VisitTypeDecl(TypeDecl *TD);
89     void VisitTypedefDecl(TypedefDecl *TD);
90     void VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
91     void VisitTagDecl(TagDecl *TD);
92     void VisitEnumDecl(EnumDecl *ED);
93     void VisitRecordDecl(RecordDecl *RD);
94     void VisitCXXRecordDecl(CXXRecordDecl *D);
95     void VisitClassTemplateSpecializationDecl(
96                                             ClassTemplateSpecializationDecl *D);
97     void VisitClassTemplatePartialSpecializationDecl(
98                                      ClassTemplatePartialSpecializationDecl *D);
99     void VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
100     void VisitValueDecl(ValueDecl *VD);
101     void VisitEnumConstantDecl(EnumConstantDecl *ECD);
102     void VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
103     void VisitDeclaratorDecl(DeclaratorDecl *DD);
104     void VisitFunctionDecl(FunctionDecl *FD);
105     void VisitCXXMethodDecl(CXXMethodDecl *D);
106     void VisitCXXConstructorDecl(CXXConstructorDecl *D);
107     void VisitCXXDestructorDecl(CXXDestructorDecl *D);
108     void VisitCXXConversionDecl(CXXConversionDecl *D);
109     void VisitFieldDecl(FieldDecl *FD);
110     void VisitIndirectFieldDecl(IndirectFieldDecl *FD);
111     void VisitVarDecl(VarDecl *VD);
112     void VisitImplicitParamDecl(ImplicitParamDecl *PD);
113     void VisitParmVarDecl(ParmVarDecl *PD);
114     void VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
115     void VisitTemplateDecl(TemplateDecl *D);
116     void VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D);
117     void VisitClassTemplateDecl(ClassTemplateDecl *D);
118     void VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
119     void VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
120     void VisitUsingDecl(UsingDecl *D);
121     void VisitUsingShadowDecl(UsingShadowDecl *D);
122     void VisitLinkageSpecDecl(LinkageSpecDecl *D);
123     void VisitFileScopeAsmDecl(FileScopeAsmDecl *AD);
124     void VisitAccessSpecDecl(AccessSpecDecl *D);
125     void VisitFriendDecl(FriendDecl *D);
126     void VisitFriendTemplateDecl(FriendTemplateDecl *D);
127     void VisitStaticAssertDecl(StaticAssertDecl *D);
128     void VisitBlockDecl(BlockDecl *BD);
129 
130     std::pair<uint64_t, uint64_t> VisitDeclContext(DeclContext *DC);
131     template <typename T> void VisitRedeclarable(Redeclarable<T> *D);
132 
133     // FIXME: Reorder according to DeclNodes.td?
134     void VisitObjCMethodDecl(ObjCMethodDecl *D);
135     void VisitObjCContainerDecl(ObjCContainerDecl *D);
136     void VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
137     void VisitObjCIvarDecl(ObjCIvarDecl *D);
138     void VisitObjCProtocolDecl(ObjCProtocolDecl *D);
139     void VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D);
140     void VisitObjCClassDecl(ObjCClassDecl *D);
141     void VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
142     void VisitObjCCategoryDecl(ObjCCategoryDecl *D);
143     void VisitObjCImplDecl(ObjCImplDecl *D);
144     void VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
145     void VisitObjCImplementationDecl(ObjCImplementationDecl *D);
146     void VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *D);
147     void VisitObjCPropertyDecl(ObjCPropertyDecl *D);
148     void VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D);
149   };
150 }
151 
152 uint64_t ASTDeclReader::GetCurrentCursorOffset() {
153   uint64_t Off = 0;
154   for (unsigned I = 0, N = Reader.Chain.size(); I != N; ++I) {
155     ASTReader::PerFileData &F = *Reader.Chain[N - I - 1];
156     if (&Cursor == &F.DeclsCursor) {
157       Off += F.DeclsCursor.GetCurrentBitNo();
158       break;
159     }
160     Off += F.SizeInBits;
161   }
162   return Off;
163 }
164 
165 void ASTDeclReader::Visit(Decl *D) {
166   DeclVisitor<ASTDeclReader, void>::Visit(D);
167 
168   if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
169     // if we have a fully initialized TypeDecl, we can safely read its type now.
170     TD->setTypeForDecl(Reader.GetType(TypeIDForTypeDecl).getTypePtrOrNull());
171   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
172     // FunctionDecl's body was written last after all other Stmts/Exprs.
173     if (Record[Idx++])
174       FD->setLazyBody(GetCurrentCursorOffset());
175   }
176 }
177 
178 void ASTDeclReader::VisitDecl(Decl *D) {
179   D->setDeclContext(cast_or_null<DeclContext>(Reader.GetDecl(Record[Idx++])));
180   D->setLexicalDeclContext(
181                      cast_or_null<DeclContext>(Reader.GetDecl(Record[Idx++])));
182   D->setLocation(ReadSourceLocation(Record, Idx));
183   D->setInvalidDecl(Record[Idx++]);
184   if (Record[Idx++]) { // hasAttrs
185     AttrVec Attrs;
186     Reader.ReadAttributes(F, Attrs, Record, Idx);
187     D->setAttrs(Attrs);
188   }
189   D->setImplicit(Record[Idx++]);
190   D->setUsed(Record[Idx++]);
191   D->setAccess((AccessSpecifier)Record[Idx++]);
192   D->setPCHLevel(Record[Idx++] + (F.Type <= ASTReader::PCH));
193 }
194 
195 void ASTDeclReader::VisitTranslationUnitDecl(TranslationUnitDecl *TU) {
196   VisitDecl(TU);
197   TU->setAnonymousNamespace(
198                     cast_or_null<NamespaceDecl>(Reader.GetDecl(Record[Idx++])));
199 }
200 
201 void ASTDeclReader::VisitNamedDecl(NamedDecl *ND) {
202   VisitDecl(ND);
203   ND->setDeclName(Reader.ReadDeclarationName(Record, Idx));
204 }
205 
206 void ASTDeclReader::VisitTypeDecl(TypeDecl *TD) {
207   VisitNamedDecl(TD);
208   // Delay type reading until after we have fully initialized the decl.
209   TypeIDForTypeDecl = Record[Idx++];
210 }
211 
212 void ASTDeclReader::VisitTypedefDecl(TypedefDecl *TD) {
213   VisitTypeDecl(TD);
214   TD->setTypeSourceInfo(GetTypeSourceInfo(Record, Idx));
215 }
216 
217 void ASTDeclReader::VisitTagDecl(TagDecl *TD) {
218   VisitTypeDecl(TD);
219   VisitRedeclarable(TD);
220   TD->IdentifierNamespace = Record[Idx++];
221   TD->setTagKind((TagDecl::TagKind)Record[Idx++]);
222   TD->setDefinition(Record[Idx++]);
223   TD->setEmbeddedInDeclarator(Record[Idx++]);
224   TD->setRBraceLoc(ReadSourceLocation(Record, Idx));
225   TD->setTagKeywordLoc(ReadSourceLocation(Record, Idx));
226   if (Record[Idx++]) { // hasExtInfo
227     TagDecl::ExtInfo *Info = new (*Reader.getContext()) TagDecl::ExtInfo();
228     ReadQualifierInfo(*Info, Record, Idx);
229     TD->TypedefDeclOrQualifier = Info;
230   } else
231     TD->setTypedefForAnonDecl(
232                       cast_or_null<TypedefDecl>(Reader.GetDecl(Record[Idx++])));
233 }
234 
235 void ASTDeclReader::VisitEnumDecl(EnumDecl *ED) {
236   VisitTagDecl(ED);
237   if (TypeSourceInfo *TI = Reader.GetTypeSourceInfo(F, Record, Idx))
238     ED->setIntegerTypeSourceInfo(TI);
239   else
240     ED->setIntegerType(Reader.GetType(Record[Idx++]));
241   ED->setPromotionType(Reader.GetType(Record[Idx++]));
242   ED->setNumPositiveBits(Record[Idx++]);
243   ED->setNumNegativeBits(Record[Idx++]);
244   ED->IsScoped = Record[Idx++];
245   ED->IsScopedUsingClassTag = Record[Idx++];
246   ED->IsFixed = Record[Idx++];
247   ED->setInstantiationOfMemberEnum(
248                          cast_or_null<EnumDecl>(Reader.GetDecl(Record[Idx++])));
249 }
250 
251 void ASTDeclReader::VisitRecordDecl(RecordDecl *RD) {
252   VisitTagDecl(RD);
253   RD->setHasFlexibleArrayMember(Record[Idx++]);
254   RD->setAnonymousStructOrUnion(Record[Idx++]);
255   RD->setHasObjectMember(Record[Idx++]);
256 }
257 
258 void ASTDeclReader::VisitValueDecl(ValueDecl *VD) {
259   VisitNamedDecl(VD);
260   VD->setType(Reader.GetType(Record[Idx++]));
261 }
262 
263 void ASTDeclReader::VisitEnumConstantDecl(EnumConstantDecl *ECD) {
264   VisitValueDecl(ECD);
265   if (Record[Idx++])
266     ECD->setInitExpr(Reader.ReadExpr(F));
267   ECD->setInitVal(Reader.ReadAPSInt(Record, Idx));
268 }
269 
270 void ASTDeclReader::VisitDeclaratorDecl(DeclaratorDecl *DD) {
271   VisitValueDecl(DD);
272   if (Record[Idx++]) { // hasExtInfo
273     DeclaratorDecl::ExtInfo *Info
274         = new (*Reader.getContext()) DeclaratorDecl::ExtInfo();
275     ReadQualifierInfo(*Info, Record, Idx);
276     Info->TInfo = GetTypeSourceInfo(Record, Idx);
277     DD->DeclInfo = Info;
278   } else
279     DD->DeclInfo = GetTypeSourceInfo(Record, Idx);
280 }
281 
282 void ASTDeclReader::VisitFunctionDecl(FunctionDecl *FD) {
283   VisitDeclaratorDecl(FD);
284   VisitRedeclarable(FD);
285 
286   ReadDeclarationNameLoc(FD->DNLoc, FD->getDeclName(), Record, Idx);
287   FD->IdentifierNamespace = Record[Idx++];
288   switch ((FunctionDecl::TemplatedKind)Record[Idx++]) {
289   default: assert(false && "Unhandled TemplatedKind!");
290     break;
291   case FunctionDecl::TK_NonTemplate:
292     break;
293   case FunctionDecl::TK_FunctionTemplate:
294     FD->setDescribedFunctionTemplate(
295                      cast<FunctionTemplateDecl>(Reader.GetDecl(Record[Idx++])));
296     break;
297   case FunctionDecl::TK_MemberSpecialization: {
298     FunctionDecl *InstFD = cast<FunctionDecl>(Reader.GetDecl(Record[Idx++]));
299     TemplateSpecializationKind TSK = (TemplateSpecializationKind)Record[Idx++];
300     SourceLocation POI = ReadSourceLocation(Record, Idx);
301     FD->setInstantiationOfMemberFunction(*Reader.getContext(), InstFD, TSK);
302     FD->getMemberSpecializationInfo()->setPointOfInstantiation(POI);
303     break;
304   }
305   case FunctionDecl::TK_FunctionTemplateSpecialization: {
306     FunctionTemplateDecl *Template
307       = cast<FunctionTemplateDecl>(Reader.GetDecl(Record[Idx++]));
308     TemplateSpecializationKind TSK = (TemplateSpecializationKind)Record[Idx++];
309 
310     // Template arguments.
311     llvm::SmallVector<TemplateArgument, 8> TemplArgs;
312     Reader.ReadTemplateArgumentList(TemplArgs, F, Record, Idx);
313 
314     // Template args as written.
315     llvm::SmallVector<TemplateArgumentLoc, 8> TemplArgLocs;
316     SourceLocation LAngleLoc, RAngleLoc;
317     if (Record[Idx++]) {  // TemplateArgumentsAsWritten != 0
318       unsigned NumTemplateArgLocs = Record[Idx++];
319       TemplArgLocs.reserve(NumTemplateArgLocs);
320       for (unsigned i=0; i != NumTemplateArgLocs; ++i)
321         TemplArgLocs.push_back(
322             Reader.ReadTemplateArgumentLoc(F, Record, Idx));
323 
324       LAngleLoc = ReadSourceLocation(Record, Idx);
325       RAngleLoc = ReadSourceLocation(Record, Idx);
326     }
327 
328     SourceLocation POI = ReadSourceLocation(Record, Idx);
329 
330     ASTContext &C = *Reader.getContext();
331     TemplateArgumentList *TemplArgList
332       = TemplateArgumentList::CreateCopy(C, TemplArgs.data(), TemplArgs.size());
333     TemplateArgumentListInfo *TemplArgsInfo
334       = new (C) TemplateArgumentListInfo(LAngleLoc, RAngleLoc);
335     for (unsigned i=0, e = TemplArgLocs.size(); i != e; ++i)
336       TemplArgsInfo->addArgument(TemplArgLocs[i]);
337     FunctionTemplateSpecializationInfo *FTInfo
338         = FunctionTemplateSpecializationInfo::Create(C, FD, Template, TSK,
339                                                      TemplArgList,
340                                                      TemplArgsInfo, POI);
341     FD->TemplateOrSpecialization = FTInfo;
342 
343     if (FD->isCanonicalDecl()) { // if canonical add to template's set.
344       // The template that contains the specializations set. It's not safe to
345       // use getCanonicalDecl on Template since it may still be initializing.
346       FunctionTemplateDecl *CanonTemplate
347         = cast<FunctionTemplateDecl>(Reader.GetDecl(Record[Idx++]));
348       // Get the InsertPos by FindNodeOrInsertPos() instead of calling
349       // InsertNode(FTInfo) directly to avoid the getASTContext() call in
350       // FunctionTemplateSpecializationInfo's Profile().
351       // We avoid getASTContext because a decl in the parent hierarchy may
352       // be initializing.
353       llvm::FoldingSetNodeID ID;
354       FunctionTemplateSpecializationInfo::Profile(ID, TemplArgs.data(),
355                                                   TemplArgs.size(), C);
356       void *InsertPos = 0;
357       CanonTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
358       assert(InsertPos && "Another specialization already inserted!");
359       CanonTemplate->getSpecializations().InsertNode(FTInfo, InsertPos);
360     }
361     break;
362   }
363   case FunctionDecl::TK_DependentFunctionTemplateSpecialization: {
364     // Templates.
365     UnresolvedSet<8> TemplDecls;
366     unsigned NumTemplates = Record[Idx++];
367     while (NumTemplates--)
368       TemplDecls.addDecl(cast<NamedDecl>(Reader.GetDecl(Record[Idx++])));
369 
370     // Templates args.
371     TemplateArgumentListInfo TemplArgs;
372     unsigned NumArgs = Record[Idx++];
373     while (NumArgs--)
374       TemplArgs.addArgument(Reader.ReadTemplateArgumentLoc(F, Record, Idx));
375     TemplArgs.setLAngleLoc(ReadSourceLocation(Record, Idx));
376     TemplArgs.setRAngleLoc(ReadSourceLocation(Record, Idx));
377 
378     FD->setDependentTemplateSpecialization(*Reader.getContext(),
379                                            TemplDecls, TemplArgs);
380     break;
381   }
382   }
383 
384   // FunctionDecl's body is handled last at ASTDeclReader::Visit,
385   // after everything else is read.
386 
387   FD->SClass = (StorageClass)Record[Idx++];
388   FD->SClassAsWritten = (StorageClass)Record[Idx++];
389   FD->IsInline = Record[Idx++];
390   FD->IsInlineSpecified = Record[Idx++];
391   FD->IsVirtualAsWritten = Record[Idx++];
392   FD->IsPure = Record[Idx++];
393   FD->HasInheritedPrototype = Record[Idx++];
394   FD->HasWrittenPrototype = Record[Idx++];
395   FD->IsDeleted = Record[Idx++];
396   FD->IsTrivial = Record[Idx++];
397   FD->HasImplicitReturnZero = Record[Idx++];
398   FD->EndRangeLoc = ReadSourceLocation(Record, Idx);
399 
400   // Read in the parameters.
401   unsigned NumParams = Record[Idx++];
402   llvm::SmallVector<ParmVarDecl *, 16> Params;
403   Params.reserve(NumParams);
404   for (unsigned I = 0; I != NumParams; ++I)
405     Params.push_back(cast<ParmVarDecl>(Reader.GetDecl(Record[Idx++])));
406   FD->setParams(*Reader.getContext(), Params.data(), NumParams);
407 }
408 
409 void ASTDeclReader::VisitObjCMethodDecl(ObjCMethodDecl *MD) {
410   VisitNamedDecl(MD);
411   if (Record[Idx++]) {
412     // In practice, this won't be executed (since method definitions
413     // don't occur in header files).
414     MD->setBody(Reader.ReadStmt(F));
415     MD->setSelfDecl(cast<ImplicitParamDecl>(Reader.GetDecl(Record[Idx++])));
416     MD->setCmdDecl(cast<ImplicitParamDecl>(Reader.GetDecl(Record[Idx++])));
417   }
418   MD->setInstanceMethod(Record[Idx++]);
419   MD->setVariadic(Record[Idx++]);
420   MD->setSynthesized(Record[Idx++]);
421   MD->setDefined(Record[Idx++]);
422   MD->setDeclImplementation((ObjCMethodDecl::ImplementationControl)Record[Idx++]);
423   MD->setObjCDeclQualifier((Decl::ObjCDeclQualifier)Record[Idx++]);
424   MD->setNumSelectorArgs(unsigned(Record[Idx++]));
425   MD->setResultType(Reader.GetType(Record[Idx++]));
426   MD->setResultTypeSourceInfo(GetTypeSourceInfo(Record, Idx));
427   MD->setEndLoc(ReadSourceLocation(Record, Idx));
428   unsigned NumParams = Record[Idx++];
429   llvm::SmallVector<ParmVarDecl *, 16> Params;
430   Params.reserve(NumParams);
431   for (unsigned I = 0; I != NumParams; ++I)
432     Params.push_back(cast<ParmVarDecl>(Reader.GetDecl(Record[Idx++])));
433   MD->setMethodParams(*Reader.getContext(), Params.data(), NumParams,
434                       NumParams);
435 }
436 
437 void ASTDeclReader::VisitObjCContainerDecl(ObjCContainerDecl *CD) {
438   VisitNamedDecl(CD);
439   SourceLocation A = ReadSourceLocation(Record, Idx);
440   SourceLocation B = ReadSourceLocation(Record, Idx);
441   CD->setAtEndRange(SourceRange(A, B));
442 }
443 
444 void ASTDeclReader::VisitObjCInterfaceDecl(ObjCInterfaceDecl *ID) {
445   VisitObjCContainerDecl(ID);
446   ID->setTypeForDecl(Reader.GetType(Record[Idx++]).getTypePtrOrNull());
447   ID->setSuperClass(cast_or_null<ObjCInterfaceDecl>
448                        (Reader.GetDecl(Record[Idx++])));
449 
450   // Read the directly referenced protocols and their SourceLocations.
451   unsigned NumProtocols = Record[Idx++];
452   llvm::SmallVector<ObjCProtocolDecl *, 16> Protocols;
453   Protocols.reserve(NumProtocols);
454   for (unsigned I = 0; I != NumProtocols; ++I)
455     Protocols.push_back(cast<ObjCProtocolDecl>(Reader.GetDecl(Record[Idx++])));
456   llvm::SmallVector<SourceLocation, 16> ProtoLocs;
457   ProtoLocs.reserve(NumProtocols);
458   for (unsigned I = 0; I != NumProtocols; ++I)
459     ProtoLocs.push_back(ReadSourceLocation(Record, Idx));
460   ID->setProtocolList(Protocols.data(), NumProtocols, ProtoLocs.data(),
461                       *Reader.getContext());
462 
463   // Read the transitive closure of protocols referenced by this class.
464   NumProtocols = Record[Idx++];
465   Protocols.clear();
466   Protocols.reserve(NumProtocols);
467   for (unsigned I = 0; I != NumProtocols; ++I)
468     Protocols.push_back(cast<ObjCProtocolDecl>(Reader.GetDecl(Record[Idx++])));
469   ID->AllReferencedProtocols.set(Protocols.data(), NumProtocols,
470                                  *Reader.getContext());
471 
472   // Read the ivars.
473   unsigned NumIvars = Record[Idx++];
474   llvm::SmallVector<ObjCIvarDecl *, 16> IVars;
475   IVars.reserve(NumIvars);
476   for (unsigned I = 0; I != NumIvars; ++I)
477     IVars.push_back(cast<ObjCIvarDecl>(Reader.GetDecl(Record[Idx++])));
478   ID->setCategoryList(
479                cast_or_null<ObjCCategoryDecl>(Reader.GetDecl(Record[Idx++])));
480   // We will rebuild this list lazily.
481   ID->setIvarList(0);
482   ID->setForwardDecl(Record[Idx++]);
483   ID->setImplicitInterfaceDecl(Record[Idx++]);
484   ID->setClassLoc(ReadSourceLocation(Record, Idx));
485   ID->setSuperClassLoc(ReadSourceLocation(Record, Idx));
486   ID->setLocEnd(ReadSourceLocation(Record, Idx));
487 }
488 
489 void ASTDeclReader::VisitObjCIvarDecl(ObjCIvarDecl *IVD) {
490   VisitFieldDecl(IVD);
491   IVD->setAccessControl((ObjCIvarDecl::AccessControl)Record[Idx++]);
492   // This field will be built lazily.
493   IVD->setNextIvar(0);
494   bool synth = Record[Idx++];
495   IVD->setSynthesize(synth);
496 }
497 
498 void ASTDeclReader::VisitObjCProtocolDecl(ObjCProtocolDecl *PD) {
499   VisitObjCContainerDecl(PD);
500   PD->setForwardDecl(Record[Idx++]);
501   PD->setLocEnd(ReadSourceLocation(Record, Idx));
502   unsigned NumProtoRefs = Record[Idx++];
503   llvm::SmallVector<ObjCProtocolDecl *, 16> ProtoRefs;
504   ProtoRefs.reserve(NumProtoRefs);
505   for (unsigned I = 0; I != NumProtoRefs; ++I)
506     ProtoRefs.push_back(cast<ObjCProtocolDecl>(Reader.GetDecl(Record[Idx++])));
507   llvm::SmallVector<SourceLocation, 16> ProtoLocs;
508   ProtoLocs.reserve(NumProtoRefs);
509   for (unsigned I = 0; I != NumProtoRefs; ++I)
510     ProtoLocs.push_back(ReadSourceLocation(Record, Idx));
511   PD->setProtocolList(ProtoRefs.data(), NumProtoRefs, ProtoLocs.data(),
512                       *Reader.getContext());
513 }
514 
515 void ASTDeclReader::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *FD) {
516   VisitFieldDecl(FD);
517 }
518 
519 void ASTDeclReader::VisitObjCClassDecl(ObjCClassDecl *CD) {
520   VisitDecl(CD);
521   unsigned NumClassRefs = Record[Idx++];
522   llvm::SmallVector<ObjCInterfaceDecl *, 16> ClassRefs;
523   ClassRefs.reserve(NumClassRefs);
524   for (unsigned I = 0; I != NumClassRefs; ++I)
525     ClassRefs.push_back(cast<ObjCInterfaceDecl>(Reader.GetDecl(Record[Idx++])));
526   llvm::SmallVector<SourceLocation, 16> SLocs;
527   SLocs.reserve(NumClassRefs);
528   for (unsigned I = 0; I != NumClassRefs; ++I)
529     SLocs.push_back(ReadSourceLocation(Record, Idx));
530   CD->setClassList(*Reader.getContext(), ClassRefs.data(), SLocs.data(),
531                    NumClassRefs);
532 }
533 
534 void ASTDeclReader::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *FPD) {
535   VisitDecl(FPD);
536   unsigned NumProtoRefs = Record[Idx++];
537   llvm::SmallVector<ObjCProtocolDecl *, 16> ProtoRefs;
538   ProtoRefs.reserve(NumProtoRefs);
539   for (unsigned I = 0; I != NumProtoRefs; ++I)
540     ProtoRefs.push_back(cast<ObjCProtocolDecl>(Reader.GetDecl(Record[Idx++])));
541   llvm::SmallVector<SourceLocation, 16> ProtoLocs;
542   ProtoLocs.reserve(NumProtoRefs);
543   for (unsigned I = 0; I != NumProtoRefs; ++I)
544     ProtoLocs.push_back(ReadSourceLocation(Record, Idx));
545   FPD->setProtocolList(ProtoRefs.data(), NumProtoRefs, ProtoLocs.data(),
546                        *Reader.getContext());
547 }
548 
549 void ASTDeclReader::VisitObjCCategoryDecl(ObjCCategoryDecl *CD) {
550   VisitObjCContainerDecl(CD);
551   CD->setClassInterface(cast<ObjCInterfaceDecl>(Reader.GetDecl(Record[Idx++])));
552   unsigned NumProtoRefs = Record[Idx++];
553   llvm::SmallVector<ObjCProtocolDecl *, 16> ProtoRefs;
554   ProtoRefs.reserve(NumProtoRefs);
555   for (unsigned I = 0; I != NumProtoRefs; ++I)
556     ProtoRefs.push_back(cast<ObjCProtocolDecl>(Reader.GetDecl(Record[Idx++])));
557   llvm::SmallVector<SourceLocation, 16> ProtoLocs;
558   ProtoLocs.reserve(NumProtoRefs);
559   for (unsigned I = 0; I != NumProtoRefs; ++I)
560     ProtoLocs.push_back(ReadSourceLocation(Record, Idx));
561   CD->setProtocolList(ProtoRefs.data(), NumProtoRefs, ProtoLocs.data(),
562                       *Reader.getContext());
563   CD->setNextClassCategory(cast_or_null<ObjCCategoryDecl>(Reader.GetDecl(Record[Idx++])));
564   CD->setHasSynthBitfield(Record[Idx++]);
565   CD->setAtLoc(ReadSourceLocation(Record, Idx));
566   CD->setCategoryNameLoc(ReadSourceLocation(Record, Idx));
567 }
568 
569 void ASTDeclReader::VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *CAD) {
570   VisitNamedDecl(CAD);
571   CAD->setClassInterface(cast<ObjCInterfaceDecl>(Reader.GetDecl(Record[Idx++])));
572 }
573 
574 void ASTDeclReader::VisitObjCPropertyDecl(ObjCPropertyDecl *D) {
575   VisitNamedDecl(D);
576   D->setAtLoc(ReadSourceLocation(Record, Idx));
577   D->setType(GetTypeSourceInfo(Record, Idx));
578   // FIXME: stable encoding
579   D->setPropertyAttributes(
580                       (ObjCPropertyDecl::PropertyAttributeKind)Record[Idx++]);
581   D->setPropertyAttributesAsWritten(
582                       (ObjCPropertyDecl::PropertyAttributeKind)Record[Idx++]);
583   // FIXME: stable encoding
584   D->setPropertyImplementation(
585                             (ObjCPropertyDecl::PropertyControl)Record[Idx++]);
586   D->setGetterName(Reader.ReadDeclarationName(Record, Idx).getObjCSelector());
587   D->setSetterName(Reader.ReadDeclarationName(Record, Idx).getObjCSelector());
588   D->setGetterMethodDecl(
589                  cast_or_null<ObjCMethodDecl>(Reader.GetDecl(Record[Idx++])));
590   D->setSetterMethodDecl(
591                  cast_or_null<ObjCMethodDecl>(Reader.GetDecl(Record[Idx++])));
592   D->setPropertyIvarDecl(
593                    cast_or_null<ObjCIvarDecl>(Reader.GetDecl(Record[Idx++])));
594 }
595 
596 void ASTDeclReader::VisitObjCImplDecl(ObjCImplDecl *D) {
597   VisitObjCContainerDecl(D);
598   D->setClassInterface(
599               cast_or_null<ObjCInterfaceDecl>(Reader.GetDecl(Record[Idx++])));
600 }
601 
602 void ASTDeclReader::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
603   VisitObjCImplDecl(D);
604   D->setIdentifier(Reader.GetIdentifierInfo(Record, Idx));
605 }
606 
607 void ASTDeclReader::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
608   VisitObjCImplDecl(D);
609   D->setSuperClass(
610               cast_or_null<ObjCInterfaceDecl>(Reader.GetDecl(Record[Idx++])));
611   llvm::tie(D->IvarInitializers, D->NumIvarInitializers)
612       = Reader.ReadCXXCtorInitializers(F, Record, Idx);
613   D->setHasSynthBitfield(Record[Idx++]);
614 }
615 
616 
617 void ASTDeclReader::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) {
618   VisitDecl(D);
619   D->setAtLoc(ReadSourceLocation(Record, Idx));
620   D->setPropertyDecl(
621                cast_or_null<ObjCPropertyDecl>(Reader.GetDecl(Record[Idx++])));
622   D->PropertyIvarDecl =
623                    cast_or_null<ObjCIvarDecl>(Reader.GetDecl(Record[Idx++]));
624   D->IvarLoc = ReadSourceLocation(Record, Idx);
625   D->setGetterCXXConstructor(Reader.ReadExpr(F));
626   D->setSetterCXXAssignment(Reader.ReadExpr(F));
627 }
628 
629 void ASTDeclReader::VisitFieldDecl(FieldDecl *FD) {
630   VisitDeclaratorDecl(FD);
631   FD->setMutable(Record[Idx++]);
632   if (Record[Idx++])
633     FD->setBitWidth(Reader.ReadExpr(F));
634   if (!FD->getDeclName()) {
635     FieldDecl *Tmpl = cast_or_null<FieldDecl>(Reader.GetDecl(Record[Idx++]));
636     if (Tmpl)
637       Reader.getContext()->setInstantiatedFromUnnamedFieldDecl(FD, Tmpl);
638   }
639 }
640 
641 void ASTDeclReader::VisitIndirectFieldDecl(IndirectFieldDecl *FD) {
642   VisitValueDecl(FD);
643 
644   FD->ChainingSize = Record[Idx++];
645   assert(FD->ChainingSize >= 2 && "Anonymous chaining must be >= 2");
646   FD->Chaining = new (*Reader.getContext())NamedDecl*[FD->ChainingSize];
647 
648   for (unsigned I = 0; I != FD->ChainingSize; ++I)
649     FD->Chaining[I] = cast<NamedDecl>(Reader.GetDecl(Record[Idx++]));
650 }
651 
652 void ASTDeclReader::VisitVarDecl(VarDecl *VD) {
653   VisitDeclaratorDecl(VD);
654   VisitRedeclarable(VD);
655   VD->SClass = (StorageClass)Record[Idx++];
656   VD->setStorageClassAsWritten((StorageClass)Record[Idx++]);
657   VD->setThreadSpecified(Record[Idx++]);
658   VD->setCXXDirectInitializer(Record[Idx++]);
659   VD->setExceptionVariable(Record[Idx++]);
660   VD->setNRVOVariable(Record[Idx++]);
661   if (Record[Idx++])
662     VD->setInit(Reader.ReadExpr(F));
663 
664   if (Record[Idx++]) { // HasMemberSpecializationInfo.
665     VarDecl *Tmpl = cast<VarDecl>(Reader.GetDecl(Record[Idx++]));
666     TemplateSpecializationKind TSK = (TemplateSpecializationKind)Record[Idx++];
667     SourceLocation POI = ReadSourceLocation(Record, Idx);
668     Reader.getContext()->setInstantiatedFromStaticDataMember(VD, Tmpl, TSK,POI);
669   }
670 }
671 
672 void ASTDeclReader::VisitImplicitParamDecl(ImplicitParamDecl *PD) {
673   VisitVarDecl(PD);
674 }
675 
676 void ASTDeclReader::VisitParmVarDecl(ParmVarDecl *PD) {
677   VisitVarDecl(PD);
678   PD->setObjCDeclQualifier((Decl::ObjCDeclQualifier)Record[Idx++]);
679   PD->setHasInheritedDefaultArg(Record[Idx++]);
680   if (Record[Idx++]) // hasUninstantiatedDefaultArg.
681     PD->setUninstantiatedDefaultArg(Reader.ReadExpr(F));
682 }
683 
684 void ASTDeclReader::VisitFileScopeAsmDecl(FileScopeAsmDecl *AD) {
685   VisitDecl(AD);
686   AD->setAsmString(cast<StringLiteral>(Reader.ReadExpr(F)));
687 }
688 
689 void ASTDeclReader::VisitBlockDecl(BlockDecl *BD) {
690   VisitDecl(BD);
691   BD->setBody(cast_or_null<CompoundStmt>(Reader.ReadStmt(F)));
692   BD->setSignatureAsWritten(GetTypeSourceInfo(Record, Idx));
693   unsigned NumParams = Record[Idx++];
694   llvm::SmallVector<ParmVarDecl *, 16> Params;
695   Params.reserve(NumParams);
696   for (unsigned I = 0; I != NumParams; ++I)
697     Params.push_back(cast<ParmVarDecl>(Reader.GetDecl(Record[Idx++])));
698   BD->setParams(Params.data(), NumParams);
699 }
700 
701 void ASTDeclReader::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
702   VisitDecl(D);
703   D->setLanguage((LinkageSpecDecl::LanguageIDs)Record[Idx++]);
704   D->setHasBraces(Record[Idx++]);
705 }
706 
707 void ASTDeclReader::VisitNamespaceDecl(NamespaceDecl *D) {
708   VisitNamedDecl(D);
709   D->IsInline = Record[Idx++];
710   D->LBracLoc = ReadSourceLocation(Record, Idx);
711   D->RBracLoc = ReadSourceLocation(Record, Idx);
712   D->NextNamespace = Record[Idx++];
713 
714   bool IsOriginal = Record[Idx++];
715   D->OrigOrAnonNamespace.setInt(IsOriginal);
716   D->OrigOrAnonNamespace.setPointer(
717                     cast_or_null<NamespaceDecl>(Reader.GetDecl(Record[Idx++])));
718 }
719 
720 void ASTDeclReader::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
721   VisitNamedDecl(D);
722   D->NamespaceLoc = ReadSourceLocation(Record, Idx);
723   D->setQualifierRange(ReadSourceRange(Record, Idx));
724   D->setQualifier(Reader.ReadNestedNameSpecifier(Record, Idx));
725   D->IdentLoc = ReadSourceLocation(Record, Idx);
726   D->Namespace = cast<NamedDecl>(Reader.GetDecl(Record[Idx++]));
727 }
728 
729 void ASTDeclReader::VisitUsingDecl(UsingDecl *D) {
730   VisitNamedDecl(D);
731   D->setUsingLocation(ReadSourceLocation(Record, Idx));
732   D->setNestedNameRange(ReadSourceRange(Record, Idx));
733   D->setTargetNestedNameDecl(Reader.ReadNestedNameSpecifier(Record, Idx));
734   ReadDeclarationNameLoc(D->DNLoc, D->getDeclName(), Record, Idx);
735   D->FirstUsingShadow = cast_or_null<UsingShadowDecl>(Reader.GetDecl(Record[Idx++]));
736   D->setTypeName(Record[Idx++]);
737   NamedDecl *Pattern = cast_or_null<NamedDecl>(Reader.GetDecl(Record[Idx++]));
738   if (Pattern)
739     Reader.getContext()->setInstantiatedFromUsingDecl(D, Pattern);
740 }
741 
742 void ASTDeclReader::VisitUsingShadowDecl(UsingShadowDecl *D) {
743   VisitNamedDecl(D);
744   D->setTargetDecl(cast<NamedDecl>(Reader.GetDecl(Record[Idx++])));
745   D->UsingOrNextShadow = cast_or_null<NamedDecl>(Reader.GetDecl(Record[Idx++]));
746   UsingShadowDecl *Pattern
747       = cast_or_null<UsingShadowDecl>(Reader.GetDecl(Record[Idx++]));
748   if (Pattern)
749     Reader.getContext()->setInstantiatedFromUsingShadowDecl(D, Pattern);
750 }
751 
752 void ASTDeclReader::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
753   VisitNamedDecl(D);
754   D->UsingLoc = ReadSourceLocation(Record, Idx);
755   D->NamespaceLoc = ReadSourceLocation(Record, Idx);
756   D->QualifierRange = ReadSourceRange(Record, Idx);
757   D->Qualifier = Reader.ReadNestedNameSpecifier(Record, Idx);
758   D->NominatedNamespace = cast<NamedDecl>(Reader.GetDecl(Record[Idx++]));
759   D->CommonAncestor = cast_or_null<DeclContext>(Reader.GetDecl(Record[Idx++]));
760 }
761 
762 void ASTDeclReader::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
763   VisitValueDecl(D);
764   D->setTargetNestedNameRange(ReadSourceRange(Record, Idx));
765   D->setUsingLoc(ReadSourceLocation(Record, Idx));
766   D->setTargetNestedNameSpecifier(Reader.ReadNestedNameSpecifier(Record, Idx));
767   ReadDeclarationNameLoc(D->DNLoc, D->getDeclName(), Record, Idx);
768 }
769 
770 void ASTDeclReader::VisitUnresolvedUsingTypenameDecl(
771                                                UnresolvedUsingTypenameDecl *D) {
772   VisitTypeDecl(D);
773   D->TargetNestedNameRange = ReadSourceRange(Record, Idx);
774   D->UsingLocation = ReadSourceLocation(Record, Idx);
775   D->TypenameLocation = ReadSourceLocation(Record, Idx);
776   D->TargetNestedNameSpecifier = Reader.ReadNestedNameSpecifier(Record, Idx);
777 }
778 
779 void ASTDeclReader::ReadCXXDefinitionData(
780                                    struct CXXRecordDecl::DefinitionData &Data,
781                                    const RecordData &Record, unsigned &Idx) {
782   Data.UserDeclaredConstructor = Record[Idx++];
783   Data.UserDeclaredCopyConstructor = Record[Idx++];
784   Data.UserDeclaredCopyAssignment = Record[Idx++];
785   Data.UserDeclaredDestructor = Record[Idx++];
786   Data.Aggregate = Record[Idx++];
787   Data.PlainOldData = Record[Idx++];
788   Data.Empty = Record[Idx++];
789   Data.Polymorphic = Record[Idx++];
790   Data.Abstract = Record[Idx++];
791   Data.HasTrivialConstructor = Record[Idx++];
792   Data.HasTrivialCopyConstructor = Record[Idx++];
793   Data.HasTrivialCopyAssignment = Record[Idx++];
794   Data.HasTrivialDestructor = Record[Idx++];
795   Data.ComputedVisibleConversions = Record[Idx++];
796   Data.DeclaredDefaultConstructor = Record[Idx++];
797   Data.DeclaredCopyConstructor = Record[Idx++];
798   Data.DeclaredCopyAssignment = Record[Idx++];
799   Data.DeclaredDestructor = Record[Idx++];
800   Data.NumBases = Record[Idx++];
801   if (Data.NumBases)
802     Data.Bases = Reader.GetCXXBaseSpecifiersOffset(Record[Idx++]);
803   Data.NumVBases = Record[Idx++];
804   if (Data.NumVBases)
805     Data.VBases = Reader.GetCXXBaseSpecifiersOffset(Record[Idx++]);
806 
807   Reader.ReadUnresolvedSet(Data.Conversions, Record, Idx);
808   Reader.ReadUnresolvedSet(Data.VisibleConversions, Record, Idx);
809   assert(Data.Definition && "Data.Definition should be already set!");
810   Data.FirstFriend
811       = cast_or_null<FriendDecl>(Reader.GetDecl(Record[Idx++]));
812 }
813 
814 void ASTDeclReader::InitializeCXXDefinitionData(CXXRecordDecl *D,
815                                                 CXXRecordDecl *DefinitionDecl,
816                                                 const RecordData &Record,
817                                                 unsigned &Idx) {
818   ASTContext &C = *Reader.getContext();
819 
820   if (D == DefinitionDecl) {
821     D->DefinitionData = new (C) struct CXXRecordDecl::DefinitionData(D);
822     ReadCXXDefinitionData(*D->DefinitionData, Record, Idx);
823     // We read the definition info. Check if there are pending forward
824     // references that need to point to this DefinitionData pointer.
825     ASTReader::PendingForwardRefsMap::iterator
826         FindI = Reader.PendingForwardRefs.find(D);
827     if (FindI != Reader.PendingForwardRefs.end()) {
828       ASTReader::ForwardRefs &Refs = FindI->second;
829       for (ASTReader::ForwardRefs::iterator
830              I = Refs.begin(), E = Refs.end(); I != E; ++I)
831         (*I)->DefinitionData = D->DefinitionData;
832 #ifndef NDEBUG
833       // We later check whether PendingForwardRefs is empty to make sure all
834       // pending references were linked.
835       Reader.PendingForwardRefs.erase(D);
836 #endif
837     }
838   } else if (DefinitionDecl) {
839     if (DefinitionDecl->DefinitionData) {
840       D->DefinitionData = DefinitionDecl->DefinitionData;
841     } else {
842       // The definition is still initializing.
843       Reader.PendingForwardRefs[DefinitionDecl].push_back(D);
844     }
845   }
846 }
847 
848 void ASTDeclReader::VisitCXXRecordDecl(CXXRecordDecl *D) {
849   VisitRecordDecl(D);
850 
851   CXXRecordDecl *DefinitionDecl
852       = cast_or_null<CXXRecordDecl>(Reader.GetDecl(Record[Idx++]));
853   InitializeCXXDefinitionData(D, DefinitionDecl, Record, Idx);
854 
855   ASTContext &C = *Reader.getContext();
856 
857   enum CXXRecKind {
858     CXXRecNotTemplate = 0, CXXRecTemplate, CXXRecMemberSpecialization
859   };
860   switch ((CXXRecKind)Record[Idx++]) {
861   default:
862     assert(false && "Out of sync with ASTDeclWriter::VisitCXXRecordDecl?");
863   case CXXRecNotTemplate:
864     break;
865   case CXXRecTemplate:
866     D->TemplateOrInstantiation
867         = cast<ClassTemplateDecl>(Reader.GetDecl(Record[Idx++]));
868     break;
869   case CXXRecMemberSpecialization: {
870     CXXRecordDecl *RD = cast<CXXRecordDecl>(Reader.GetDecl(Record[Idx++]));
871     TemplateSpecializationKind TSK = (TemplateSpecializationKind)Record[Idx++];
872     SourceLocation POI = ReadSourceLocation(Record, Idx);
873     MemberSpecializationInfo *MSI = new (C) MemberSpecializationInfo(RD, TSK);
874     MSI->setPointOfInstantiation(POI);
875     D->TemplateOrInstantiation = MSI;
876     break;
877   }
878   }
879 
880   // Load the key function to avoid deserializing every method so we can
881   // compute it.
882   if (D->IsDefinition) {
883     CXXMethodDecl *Key
884         = cast_or_null<CXXMethodDecl>(Reader.GetDecl(Record[Idx++]));
885     if (Key)
886       C.KeyFunctions[D] = Key;
887   }
888 }
889 
890 void ASTDeclReader::VisitCXXMethodDecl(CXXMethodDecl *D) {
891   VisitFunctionDecl(D);
892   unsigned NumOverridenMethods = Record[Idx++];
893   while (NumOverridenMethods--) {
894     CXXMethodDecl *MD = cast<CXXMethodDecl>(Reader.GetDecl(Record[Idx++]));
895     // Avoid invariant checking of CXXMethodDecl::addOverriddenMethod,
896     // MD may be initializing.
897     Reader.getContext()->addOverriddenMethod(D, MD);
898   }
899 }
900 
901 void ASTDeclReader::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
902   VisitCXXMethodDecl(D);
903 
904   D->IsExplicitSpecified = Record[Idx++];
905   D->ImplicitlyDefined = Record[Idx++];
906   llvm::tie(D->CtorInitializers, D->NumCtorInitializers)
907       = Reader.ReadCXXCtorInitializers(F, Record, Idx);
908 }
909 
910 void ASTDeclReader::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
911   VisitCXXMethodDecl(D);
912 
913   D->ImplicitlyDefined = Record[Idx++];
914   D->OperatorDelete = cast_or_null<FunctionDecl>(Reader.GetDecl(Record[Idx++]));
915 }
916 
917 void ASTDeclReader::VisitCXXConversionDecl(CXXConversionDecl *D) {
918   VisitCXXMethodDecl(D);
919   D->IsExplicitSpecified = Record[Idx++];
920 }
921 
922 void ASTDeclReader::VisitAccessSpecDecl(AccessSpecDecl *D) {
923   VisitDecl(D);
924   D->setColonLoc(ReadSourceLocation(Record, Idx));
925 }
926 
927 void ASTDeclReader::VisitFriendDecl(FriendDecl *D) {
928   VisitDecl(D);
929   if (Record[Idx++])
930     D->Friend = GetTypeSourceInfo(Record, Idx);
931   else
932     D->Friend = cast<NamedDecl>(Reader.GetDecl(Record[Idx++]));
933   D->NextFriend = Record[Idx++];
934   D->UnsupportedFriend = (Record[Idx++] != 0);
935   D->FriendLoc = ReadSourceLocation(Record, Idx);
936 }
937 
938 void ASTDeclReader::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
939   VisitDecl(D);
940   unsigned NumParams = Record[Idx++];
941   D->NumParams = NumParams;
942   D->Params = new TemplateParameterList*[NumParams];
943   for (unsigned i = 0; i != NumParams; ++i)
944     D->Params[i] = Reader.ReadTemplateParameterList(F, Record, Idx);
945   if (Record[Idx++]) // HasFriendDecl
946     D->Friend = cast<NamedDecl>(Reader.GetDecl(Record[Idx++]));
947   else
948     D->Friend = GetTypeSourceInfo(Record, Idx);
949   D->FriendLoc = ReadSourceLocation(Record, Idx);
950 }
951 
952 void ASTDeclReader::VisitTemplateDecl(TemplateDecl *D) {
953   VisitNamedDecl(D);
954 
955   NamedDecl *TemplatedDecl
956     = cast_or_null<NamedDecl>(Reader.GetDecl(Record[Idx++]));
957   TemplateParameterList* TemplateParams
958       = Reader.ReadTemplateParameterList(F, Record, Idx);
959   D->init(TemplatedDecl, TemplateParams);
960 }
961 
962 void ASTDeclReader::VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D) {
963   // Initialize CommonOrPrev before VisitTemplateDecl so that getCommonPtr()
964   // can be used while this is still initializing.
965 
966   assert(D->CommonOrPrev.isNull() && "getCommonPtr was called earlier on this");
967   RedeclarableTemplateDecl *PrevDecl =
968       cast_or_null<RedeclarableTemplateDecl>(Reader.GetDecl(Record[Idx++]));
969   assert((PrevDecl == 0 || PrevDecl->getKind() == D->getKind()) &&
970          "PrevDecl kind mismatch");
971   if (PrevDecl)
972     D->CommonOrPrev = PrevDecl;
973   if (PrevDecl == 0) {
974     D->CommonOrPrev = D->newCommon(*Reader.getContext());
975     if (RedeclarableTemplateDecl *RTD
976           = cast_or_null<RedeclarableTemplateDecl>(Reader.GetDecl(Record[Idx++]))) {
977       assert(RTD->getKind() == D->getKind() &&
978              "InstantiatedFromMemberTemplate kind mismatch");
979       D->setInstantiatedFromMemberTemplateImpl(RTD);
980       if (Record[Idx++])
981         D->setMemberSpecialization();
982     }
983 
984     RedeclarableTemplateDecl *LatestDecl =
985         cast_or_null<RedeclarableTemplateDecl>(Reader.GetDecl(Record[Idx++]));
986 
987     // This decl is a first one and the latest declaration that it points to is
988     // in the same AST file. However, if this actually needs to point to a
989     // redeclaration in another AST file, we need to update it by checking
990     // the FirstLatestDeclIDs map which tracks this kind of decls.
991     assert(Reader.GetDecl(ThisDeclID) == D && "Invalid ThisDeclID ?");
992     ASTReader::FirstLatestDeclIDMap::iterator I
993         = Reader.FirstLatestDeclIDs.find(ThisDeclID);
994     if (I != Reader.FirstLatestDeclIDs.end()) {
995       Decl *NewLatest = Reader.GetDecl(I->second);
996       assert((LatestDecl->getLocation().isInvalid() ||
997               NewLatest->getLocation().isInvalid()  ||
998               !Reader.SourceMgr.isBeforeInTranslationUnit(
999                                                   NewLatest->getLocation(),
1000                                                   LatestDecl->getLocation())) &&
1001              "The new latest is supposed to come after the previous latest");
1002       LatestDecl = cast<RedeclarableTemplateDecl>(NewLatest);
1003     }
1004 
1005     assert(LatestDecl->getKind() == D->getKind() && "Latest kind mismatch");
1006     D->getCommonPtr()->Latest = LatestDecl;
1007   }
1008 
1009   VisitTemplateDecl(D);
1010   D->IdentifierNamespace = Record[Idx++];
1011 }
1012 
1013 void ASTDeclReader::VisitClassTemplateDecl(ClassTemplateDecl *D) {
1014   VisitRedeclarableTemplateDecl(D);
1015 
1016   if (D->getPreviousDeclaration() == 0) {
1017     // This ClassTemplateDecl owns a CommonPtr; read it to keep track of all of
1018     // the specializations.
1019     llvm::SmallVector<serialization::DeclID, 2> SpecIDs;
1020     SpecIDs.push_back(0);
1021 
1022     // Specializations.
1023     unsigned Size = Record[Idx++];
1024     SpecIDs[0] += Size;
1025     SpecIDs.append(Record.begin() + Idx, Record.begin() + Idx + Size);
1026     Idx += Size;
1027 
1028     // Partial specializations.
1029     Size = Record[Idx++];
1030     SpecIDs[0] += Size;
1031     SpecIDs.append(Record.begin() + Idx, Record.begin() + Idx + Size);
1032     Idx += Size;
1033 
1034     if (SpecIDs[0]) {
1035       typedef serialization::DeclID DeclID;
1036 
1037       ClassTemplateDecl::Common *CommonPtr = D->getCommonPtr();
1038       CommonPtr->LazySpecializations
1039         = new (*Reader.getContext()) DeclID [SpecIDs.size()];
1040       memcpy(CommonPtr->LazySpecializations, SpecIDs.data(),
1041              SpecIDs.size() * sizeof(DeclID));
1042     }
1043 
1044     // InjectedClassNameType is computed.
1045   }
1046 }
1047 
1048 void ASTDeclReader::VisitClassTemplateSpecializationDecl(
1049                                            ClassTemplateSpecializationDecl *D) {
1050   VisitCXXRecordDecl(D);
1051 
1052   ASTContext &C = *Reader.getContext();
1053   if (Decl *InstD = Reader.GetDecl(Record[Idx++])) {
1054     if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(InstD)) {
1055       D->SpecializedTemplate = CTD;
1056     } else {
1057       llvm::SmallVector<TemplateArgument, 8> TemplArgs;
1058       Reader.ReadTemplateArgumentList(TemplArgs, F, Record, Idx);
1059       TemplateArgumentList *ArgList
1060         = TemplateArgumentList::CreateCopy(C, TemplArgs.data(),
1061                                            TemplArgs.size());
1062       ClassTemplateSpecializationDecl::SpecializedPartialSpecialization *PS
1063           = new (C) ClassTemplateSpecializationDecl::
1064                                              SpecializedPartialSpecialization();
1065       PS->PartialSpecialization
1066           = cast<ClassTemplatePartialSpecializationDecl>(InstD);
1067       PS->TemplateArgs = ArgList;
1068       D->SpecializedTemplate = PS;
1069     }
1070   }
1071 
1072   // Explicit info.
1073   if (TypeSourceInfo *TyInfo = GetTypeSourceInfo(Record, Idx)) {
1074     ClassTemplateSpecializationDecl::ExplicitSpecializationInfo *ExplicitInfo
1075         = new (C) ClassTemplateSpecializationDecl::ExplicitSpecializationInfo;
1076     ExplicitInfo->TypeAsWritten = TyInfo;
1077     ExplicitInfo->ExternLoc = ReadSourceLocation(Record, Idx);
1078     ExplicitInfo->TemplateKeywordLoc = ReadSourceLocation(Record, Idx);
1079     D->ExplicitInfo = ExplicitInfo;
1080   }
1081 
1082   llvm::SmallVector<TemplateArgument, 8> TemplArgs;
1083   Reader.ReadTemplateArgumentList(TemplArgs, F, Record, Idx);
1084   D->TemplateArgs = TemplateArgumentList::CreateCopy(C, TemplArgs.data(),
1085                                                      TemplArgs.size());
1086   D->PointOfInstantiation = ReadSourceLocation(Record, Idx);
1087   D->SpecializationKind = (TemplateSpecializationKind)Record[Idx++];
1088 
1089   if (D->isCanonicalDecl()) { // It's kept in the folding set.
1090     ClassTemplateDecl *CanonPattern
1091                        = cast<ClassTemplateDecl>(Reader.GetDecl(Record[Idx++]));
1092     if (ClassTemplatePartialSpecializationDecl *Partial
1093                        = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) {
1094       CanonPattern->getCommonPtr()->PartialSpecializations.InsertNode(Partial);
1095     } else {
1096       CanonPattern->getCommonPtr()->Specializations.InsertNode(D);
1097     }
1098   }
1099 }
1100 
1101 void ASTDeclReader::VisitClassTemplatePartialSpecializationDecl(
1102                                     ClassTemplatePartialSpecializationDecl *D) {
1103   VisitClassTemplateSpecializationDecl(D);
1104 
1105   ASTContext &C = *Reader.getContext();
1106   D->TemplateParams = Reader.ReadTemplateParameterList(F, Record, Idx);
1107 
1108   unsigned NumArgs = Record[Idx++];
1109   if (NumArgs) {
1110     D->NumArgsAsWritten = NumArgs;
1111     D->ArgsAsWritten = new (C) TemplateArgumentLoc[NumArgs];
1112     for (unsigned i=0; i != NumArgs; ++i)
1113       D->ArgsAsWritten[i] = Reader.ReadTemplateArgumentLoc(F, Record, Idx);
1114   }
1115 
1116   D->SequenceNumber = Record[Idx++];
1117 
1118   // These are read/set from/to the first declaration.
1119   if (D->getPreviousDeclaration() == 0) {
1120     D->InstantiatedFromMember.setPointer(
1121         cast_or_null<ClassTemplatePartialSpecializationDecl>(
1122                                                 Reader.GetDecl(Record[Idx++])));
1123     D->InstantiatedFromMember.setInt(Record[Idx++]);
1124   }
1125 }
1126 
1127 void ASTDeclReader::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
1128   VisitRedeclarableTemplateDecl(D);
1129 
1130   if (D->getPreviousDeclaration() == 0) {
1131     // This FunctionTemplateDecl owns a CommonPtr; read it.
1132 
1133     // Read the function specialization declarations.
1134     // FunctionTemplateDecl's FunctionTemplateSpecializationInfos are filled
1135     // when reading the specialized FunctionDecl.
1136     unsigned NumSpecs = Record[Idx++];
1137     while (NumSpecs--)
1138       Reader.GetDecl(Record[Idx++]);
1139   }
1140 }
1141 
1142 void ASTDeclReader::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
1143   VisitTypeDecl(D);
1144 
1145   D->setDeclaredWithTypename(Record[Idx++]);
1146   D->setParameterPack(Record[Idx++]);
1147 
1148   bool Inherited = Record[Idx++];
1149   TypeSourceInfo *DefArg = GetTypeSourceInfo(Record, Idx);
1150   D->setDefaultArgument(DefArg, Inherited);
1151 }
1152 
1153 void ASTDeclReader::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
1154   VisitVarDecl(D);
1155   // TemplateParmPosition.
1156   D->setDepth(Record[Idx++]);
1157   D->setPosition(Record[Idx++]);
1158   // Rest of NonTypeTemplateParmDecl.
1159   D->ParameterPack = Record[Idx++];
1160   if (Record[Idx++]) {
1161     Expr *DefArg = Reader.ReadExpr(F);
1162     bool Inherited = Record[Idx++];
1163     D->setDefaultArgument(DefArg, Inherited);
1164  }
1165 }
1166 
1167 void ASTDeclReader::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
1168   VisitTemplateDecl(D);
1169   // TemplateParmPosition.
1170   D->setDepth(Record[Idx++]);
1171   D->setPosition(Record[Idx++]);
1172   // Rest of TemplateTemplateParmDecl.
1173   TemplateArgumentLoc Arg = Reader.ReadTemplateArgumentLoc(F, Record, Idx);
1174   bool IsInherited = Record[Idx++];
1175   D->setDefaultArgument(Arg, IsInherited);
1176   D->ParameterPack = Record[Idx++];
1177 }
1178 
1179 void ASTDeclReader::VisitStaticAssertDecl(StaticAssertDecl *D) {
1180   VisitDecl(D);
1181   D->AssertExpr = Reader.ReadExpr(F);
1182   D->Message = cast<StringLiteral>(Reader.ReadExpr(F));
1183 }
1184 
1185 std::pair<uint64_t, uint64_t>
1186 ASTDeclReader::VisitDeclContext(DeclContext *DC) {
1187   uint64_t LexicalOffset = Record[Idx++];
1188   uint64_t VisibleOffset = Record[Idx++];
1189   return std::make_pair(LexicalOffset, VisibleOffset);
1190 }
1191 
1192 template <typename T>
1193 void ASTDeclReader::VisitRedeclarable(Redeclarable<T> *D) {
1194   enum RedeclKind { NoRedeclaration = 0, PointsToPrevious, PointsToLatest };
1195   RedeclKind Kind = (RedeclKind)Record[Idx++];
1196   switch (Kind) {
1197   default:
1198     assert(0 && "Out of sync with ASTDeclWriter::VisitRedeclarable or messed up"
1199                 " reading");
1200   case NoRedeclaration:
1201     break;
1202   case PointsToPrevious:
1203     D->RedeclLink = typename Redeclarable<T>::PreviousDeclLink(
1204                                 cast_or_null<T>(Reader.GetDecl(Record[Idx++])));
1205     break;
1206   case PointsToLatest:
1207     D->RedeclLink = typename Redeclarable<T>::LatestDeclLink(
1208                                 cast_or_null<T>(Reader.GetDecl(Record[Idx++])));
1209     break;
1210   }
1211 
1212   assert(!(Kind == PointsToPrevious &&
1213            Reader.FirstLatestDeclIDs.find(ThisDeclID) !=
1214                Reader.FirstLatestDeclIDs.end()) &&
1215          "This decl is not first, it should not be in the map");
1216   if (Kind == PointsToPrevious)
1217     return;
1218 
1219   // This decl is a first one and the latest declaration that it points to is in
1220   // the same AST file. However, if this actually needs to point to a
1221   // redeclaration in another AST file, we need to update it by checking the
1222   // FirstLatestDeclIDs map which tracks this kind of decls.
1223   assert(Reader.GetDecl(ThisDeclID) == static_cast<T*>(D) &&
1224          "Invalid ThisDeclID ?");
1225   ASTReader::FirstLatestDeclIDMap::iterator I
1226       = Reader.FirstLatestDeclIDs.find(ThisDeclID);
1227   if (I != Reader.FirstLatestDeclIDs.end()) {
1228     Decl *NewLatest = Reader.GetDecl(I->second);
1229     D->RedeclLink
1230         = typename Redeclarable<T>::LatestDeclLink(cast_or_null<T>(NewLatest));
1231   }
1232 }
1233 
1234 //===----------------------------------------------------------------------===//
1235 // Attribute Reading
1236 //===----------------------------------------------------------------------===//
1237 
1238 /// \brief Reads attributes from the current stream position.
1239 void ASTReader::ReadAttributes(PerFileData &F, AttrVec &Attrs,
1240                                const RecordData &Record, unsigned &Idx) {
1241   for (unsigned i = 0, e = Record[Idx++]; i != e; ++i) {
1242     Attr *New = 0;
1243     attr::Kind Kind = (attr::Kind)Record[Idx++];
1244     SourceLocation Loc = ReadSourceLocation(F, Record, Idx);
1245     bool isInherited = Record[Idx++];
1246 
1247 #include "clang/Serialization/AttrPCHRead.inc"
1248 
1249     assert(New && "Unable to decode attribute?");
1250     New->setInherited(isInherited);
1251     Attrs.push_back(New);
1252   }
1253 }
1254 
1255 //===----------------------------------------------------------------------===//
1256 // ASTReader Implementation
1257 //===----------------------------------------------------------------------===//
1258 
1259 /// \brief Note that we have loaded the declaration with the given
1260 /// Index.
1261 ///
1262 /// This routine notes that this declaration has already been loaded,
1263 /// so that future GetDecl calls will return this declaration rather
1264 /// than trying to load a new declaration.
1265 inline void ASTReader::LoadedDecl(unsigned Index, Decl *D) {
1266   assert(!DeclsLoaded[Index] && "Decl loaded twice?");
1267   DeclsLoaded[Index] = D;
1268 }
1269 
1270 
1271 /// \brief Determine whether the consumer will be interested in seeing
1272 /// this declaration (via HandleTopLevelDecl).
1273 ///
1274 /// This routine should return true for anything that might affect
1275 /// code generation, e.g., inline function definitions, Objective-C
1276 /// declarations with metadata, etc.
1277 static bool isConsumerInterestedIn(Decl *D) {
1278   if (isa<FileScopeAsmDecl>(D))
1279     return true;
1280   if (VarDecl *Var = dyn_cast<VarDecl>(D))
1281     return Var->isFileVarDecl() &&
1282            Var->isThisDeclarationADefinition() == VarDecl::Definition;
1283   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(D))
1284     return Func->isThisDeclarationADefinition();
1285   return isa<ObjCProtocolDecl>(D) || isa<ObjCImplementationDecl>(D);
1286 }
1287 
1288 /// \brief Get the correct cursor and offset for loading a type.
1289 ASTReader::RecordLocation
1290 ASTReader::DeclCursorForIndex(unsigned Index, DeclID ID) {
1291   // See if there's an override.
1292   DeclReplacementMap::iterator It = ReplacedDecls.find(ID);
1293   if (It != ReplacedDecls.end())
1294     return RecordLocation(It->second.first, It->second.second);
1295 
1296   PerFileData *F = 0;
1297   for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
1298     F = Chain[N - I - 1];
1299     if (Index < F->LocalNumDecls)
1300       break;
1301     Index -= F->LocalNumDecls;
1302   }
1303   assert(F && F->LocalNumDecls > Index && "Broken chain");
1304   return RecordLocation(F, F->DeclOffsets[Index]);
1305 }
1306 
1307 /// \brief Read the declaration at the given offset from the AST file.
1308 Decl *ASTReader::ReadDeclRecord(unsigned Index, DeclID ID) {
1309   RecordLocation Loc = DeclCursorForIndex(Index, ID);
1310   llvm::BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
1311   // Keep track of where we are in the stream, then jump back there
1312   // after reading this declaration.
1313   SavedStreamPosition SavedPosition(DeclsCursor);
1314 
1315   ReadingKindTracker ReadingKind(Read_Decl, *this);
1316 
1317   // Note that we are loading a declaration record.
1318   Deserializing ADecl(this);
1319 
1320   DeclsCursor.JumpToBit(Loc.Offset);
1321   RecordData Record;
1322   unsigned Code = DeclsCursor.ReadCode();
1323   unsigned Idx = 0;
1324   ASTDeclReader Reader(*this, *Loc.F, DeclsCursor, ID, Record, Idx);
1325 
1326   Decl *D = 0;
1327   switch ((DeclCode)DeclsCursor.ReadRecord(Code, Record)) {
1328   case DECL_CONTEXT_LEXICAL:
1329   case DECL_CONTEXT_VISIBLE:
1330     assert(false && "Record cannot be de-serialized with ReadDeclRecord");
1331     break;
1332   case DECL_TRANSLATION_UNIT:
1333     assert(Index == 0 && "Translation unit must be at index 0");
1334     D = Context->getTranslationUnitDecl();
1335     break;
1336   case DECL_TYPEDEF:
1337     D = TypedefDecl::Create(*Context, 0, SourceLocation(), 0, 0);
1338     break;
1339   case DECL_ENUM:
1340     D = EnumDecl::Create(*Context, Decl::EmptyShell());
1341     break;
1342   case DECL_RECORD:
1343     D = RecordDecl::Create(*Context, Decl::EmptyShell());
1344     break;
1345   case DECL_ENUM_CONSTANT:
1346     D = EnumConstantDecl::Create(*Context, 0, SourceLocation(), 0, QualType(),
1347                                  0, llvm::APSInt());
1348     break;
1349   case DECL_FUNCTION:
1350     D = FunctionDecl::Create(*Context, 0, SourceLocation(), DeclarationName(),
1351                              QualType(), 0);
1352     break;
1353   case DECL_LINKAGE_SPEC:
1354     D = LinkageSpecDecl::Create(*Context, 0, SourceLocation(),
1355                                 (LinkageSpecDecl::LanguageIDs)0,
1356                                 false);
1357     break;
1358   case DECL_NAMESPACE:
1359     D = NamespaceDecl::Create(*Context, 0, SourceLocation(), 0);
1360     break;
1361   case DECL_NAMESPACE_ALIAS:
1362     D = NamespaceAliasDecl::Create(*Context, 0, SourceLocation(),
1363                                    SourceLocation(), 0, SourceRange(), 0,
1364                                    SourceLocation(), 0);
1365     break;
1366   case DECL_USING:
1367     D = UsingDecl::Create(*Context, 0, SourceRange(), SourceLocation(),
1368                           0, DeclarationNameInfo(), false);
1369     break;
1370   case DECL_USING_SHADOW:
1371     D = UsingShadowDecl::Create(*Context, 0, SourceLocation(), 0, 0);
1372     break;
1373   case DECL_USING_DIRECTIVE:
1374     D = UsingDirectiveDecl::Create(*Context, 0, SourceLocation(),
1375                                    SourceLocation(), SourceRange(), 0,
1376                                    SourceLocation(), 0, 0);
1377     break;
1378   case DECL_UNRESOLVED_USING_VALUE:
1379     D = UnresolvedUsingValueDecl::Create(*Context, 0, SourceLocation(),
1380                                          SourceRange(), 0,
1381                                          DeclarationNameInfo());
1382     break;
1383   case DECL_UNRESOLVED_USING_TYPENAME:
1384     D = UnresolvedUsingTypenameDecl::Create(*Context, 0, SourceLocation(),
1385                                             SourceLocation(), SourceRange(),
1386                                             0, SourceLocation(),
1387                                             DeclarationName());
1388     break;
1389   case DECL_CXX_RECORD:
1390     D = CXXRecordDecl::Create(*Context, Decl::EmptyShell());
1391     break;
1392   case DECL_CXX_METHOD:
1393     D = CXXMethodDecl::Create(*Context, 0, DeclarationNameInfo(),
1394                               QualType(), 0);
1395     break;
1396   case DECL_CXX_CONSTRUCTOR:
1397     D = CXXConstructorDecl::Create(*Context, Decl::EmptyShell());
1398     break;
1399   case DECL_CXX_DESTRUCTOR:
1400     D = CXXDestructorDecl::Create(*Context, Decl::EmptyShell());
1401     break;
1402   case DECL_CXX_CONVERSION:
1403     D = CXXConversionDecl::Create(*Context, Decl::EmptyShell());
1404     break;
1405   case DECL_ACCESS_SPEC:
1406     D = AccessSpecDecl::Create(*Context, Decl::EmptyShell());
1407     break;
1408   case DECL_FRIEND:
1409     D = FriendDecl::Create(*Context, Decl::EmptyShell());
1410     break;
1411   case DECL_FRIEND_TEMPLATE:
1412     D = FriendTemplateDecl::Create(*Context, Decl::EmptyShell());
1413     break;
1414   case DECL_CLASS_TEMPLATE:
1415     D = ClassTemplateDecl::Create(*Context, 0, SourceLocation(),
1416                                   DeclarationName(), 0, 0, 0);
1417     break;
1418   case DECL_CLASS_TEMPLATE_SPECIALIZATION:
1419     D = ClassTemplateSpecializationDecl::Create(*Context, Decl::EmptyShell());
1420     break;
1421   case DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION:
1422     D = ClassTemplatePartialSpecializationDecl::Create(*Context,
1423                                                             Decl::EmptyShell());
1424     break;
1425   case DECL_FUNCTION_TEMPLATE:
1426     D = FunctionTemplateDecl::Create(*Context, 0, SourceLocation(),
1427                                      DeclarationName(), 0, 0);
1428     break;
1429   case DECL_TEMPLATE_TYPE_PARM:
1430     D = TemplateTypeParmDecl::Create(*Context, Decl::EmptyShell());
1431     break;
1432   case DECL_NON_TYPE_TEMPLATE_PARM:
1433     D = NonTypeTemplateParmDecl::Create(*Context, 0, SourceLocation(), 0,0,0,
1434                                         QualType(), false, 0);
1435     break;
1436   case DECL_TEMPLATE_TEMPLATE_PARM:
1437     D = TemplateTemplateParmDecl::Create(*Context, 0, SourceLocation(), 0, 0,
1438                                          false, 0, 0);
1439     break;
1440   case DECL_STATIC_ASSERT:
1441     D = StaticAssertDecl::Create(*Context, 0, SourceLocation(), 0, 0);
1442     break;
1443 
1444   case DECL_OBJC_METHOD:
1445     D = ObjCMethodDecl::Create(*Context, SourceLocation(), SourceLocation(),
1446                                Selector(), QualType(), 0, 0);
1447     break;
1448   case DECL_OBJC_INTERFACE:
1449     D = ObjCInterfaceDecl::Create(*Context, 0, SourceLocation(), 0);
1450     break;
1451   case DECL_OBJC_IVAR:
1452     D = ObjCIvarDecl::Create(*Context, 0, SourceLocation(), 0, QualType(), 0,
1453                              ObjCIvarDecl::None);
1454     break;
1455   case DECL_OBJC_PROTOCOL:
1456     D = ObjCProtocolDecl::Create(*Context, 0, SourceLocation(), 0);
1457     break;
1458   case DECL_OBJC_AT_DEFS_FIELD:
1459     D = ObjCAtDefsFieldDecl::Create(*Context, 0, SourceLocation(), 0,
1460                                     QualType(), 0);
1461     break;
1462   case DECL_OBJC_CLASS:
1463     D = ObjCClassDecl::Create(*Context, 0, SourceLocation());
1464     break;
1465   case DECL_OBJC_FORWARD_PROTOCOL:
1466     D = ObjCForwardProtocolDecl::Create(*Context, 0, SourceLocation());
1467     break;
1468   case DECL_OBJC_CATEGORY:
1469     D = ObjCCategoryDecl::Create(*Context, 0, SourceLocation(),
1470                                  SourceLocation(), SourceLocation(), 0);
1471     break;
1472   case DECL_OBJC_CATEGORY_IMPL:
1473     D = ObjCCategoryImplDecl::Create(*Context, 0, SourceLocation(), 0, 0);
1474     break;
1475   case DECL_OBJC_IMPLEMENTATION:
1476     D = ObjCImplementationDecl::Create(*Context, 0, SourceLocation(), 0, 0);
1477     break;
1478   case DECL_OBJC_COMPATIBLE_ALIAS:
1479     D = ObjCCompatibleAliasDecl::Create(*Context, 0, SourceLocation(), 0, 0);
1480     break;
1481   case DECL_OBJC_PROPERTY:
1482     D = ObjCPropertyDecl::Create(*Context, 0, SourceLocation(), 0, SourceLocation(),
1483                                  0);
1484     break;
1485   case DECL_OBJC_PROPERTY_IMPL:
1486     D = ObjCPropertyImplDecl::Create(*Context, 0, SourceLocation(),
1487                                      SourceLocation(), 0,
1488                                      ObjCPropertyImplDecl::Dynamic, 0,
1489                                      SourceLocation());
1490     break;
1491   case DECL_FIELD:
1492     D = FieldDecl::Create(*Context, 0, SourceLocation(), 0, QualType(), 0, 0,
1493                           false);
1494     break;
1495   case DECL_INDIRECTFIELD:
1496     D = IndirectFieldDecl::Create(*Context, 0, SourceLocation(), 0, QualType(),
1497                                   0, 0);
1498     break;
1499   case DECL_VAR:
1500     D = VarDecl::Create(*Context, 0, SourceLocation(), 0, QualType(), 0,
1501                         SC_None, SC_None);
1502     break;
1503 
1504   case DECL_IMPLICIT_PARAM:
1505     D = ImplicitParamDecl::Create(*Context, 0, SourceLocation(), 0, QualType());
1506     break;
1507 
1508   case DECL_PARM_VAR:
1509     D = ParmVarDecl::Create(*Context, 0, SourceLocation(), 0, QualType(), 0,
1510                             SC_None, SC_None, 0);
1511     break;
1512   case DECL_FILE_SCOPE_ASM:
1513     D = FileScopeAsmDecl::Create(*Context, 0, SourceLocation(), 0);
1514     break;
1515   case DECL_BLOCK:
1516     D = BlockDecl::Create(*Context, 0, SourceLocation());
1517     break;
1518   case DECL_CXX_BASE_SPECIFIERS:
1519     Error("attempt to read a C++ base-specifier record as a declaration");
1520     return 0;
1521   }
1522 
1523   assert(D && "Unknown declaration reading AST file");
1524   LoadedDecl(Index, D);
1525   Reader.Visit(D);
1526 
1527   // If this declaration is also a declaration context, get the
1528   // offsets for its tables of lexical and visible declarations.
1529   if (DeclContext *DC = dyn_cast<DeclContext>(D)) {
1530     std::pair<uint64_t, uint64_t> Offsets = Reader.VisitDeclContext(DC);
1531     if (Offsets.first || Offsets.second) {
1532       DC->setHasExternalLexicalStorage(Offsets.first != 0);
1533       DC->setHasExternalVisibleStorage(Offsets.second != 0);
1534       DeclContextInfo Info;
1535       if (ReadDeclContextStorage(DeclsCursor, Offsets, Info))
1536         return 0;
1537       DeclContextInfos &Infos = DeclContextOffsets[DC];
1538       // Reading the TU will happen after reading its lexical update blocks,
1539       // so we need to make sure we insert in front. For all other contexts,
1540       // the vector is empty here anyway, so there's no loss in efficiency.
1541       Infos.insert(Infos.begin(), Info);
1542 
1543       // Now add the pending visible updates for this decl context, if it has
1544       // any.
1545       DeclContextVisibleUpdatesPending::iterator I =
1546           PendingVisibleUpdates.find(ID);
1547       if (I != PendingVisibleUpdates.end()) {
1548         DeclContextVisibleUpdates &U = I->second;
1549         Info.LexicalDecls = 0;
1550         Info.NumLexicalDecls = 0;
1551         for (DeclContextVisibleUpdates::iterator UI = U.begin(), UE = U.end();
1552              UI != UE; ++UI) {
1553           Info.NameLookupTableData = *UI;
1554           Infos.push_back(Info);
1555         }
1556         PendingVisibleUpdates.erase(I);
1557       }
1558     }
1559   }
1560   assert(Idx == Record.size());
1561 
1562   // The declaration may have been modified by files later in the chain.
1563   // If this is the case, read the record containing the updates from each file
1564   // and pass it to ASTDeclReader to make the modifications.
1565   DeclUpdateOffsetsMap::iterator UpdI = DeclUpdateOffsets.find(ID);
1566   if (UpdI != DeclUpdateOffsets.end()) {
1567     FileOffsetsTy &UpdateOffsets = UpdI->second;
1568     for (FileOffsetsTy::iterator
1569            I = UpdateOffsets.begin(), E = UpdateOffsets.end(); I != E; ++I) {
1570       PerFileData *F = I->first;
1571       uint64_t Offset = I->second;
1572       llvm::BitstreamCursor &Cursor = F->DeclsCursor;
1573       SavedStreamPosition SavedPosition(Cursor);
1574       Cursor.JumpToBit(Offset);
1575       RecordData Record;
1576       unsigned Code = Cursor.ReadCode();
1577       unsigned RecCode = Cursor.ReadRecord(Code, Record);
1578       (void)RecCode;
1579       assert(RecCode == DECL_UPDATES && "Expected DECL_UPDATES record!");
1580       Reader.UpdateDecl(D, Record);
1581     }
1582   }
1583 
1584   // If we have deserialized a declaration that has a definition the
1585   // AST consumer might need to know about, queue it.
1586   // We don't pass it to the consumer immediately because we may be in recursive
1587   // loading, and some declarations may still be initializing.
1588   if (isConsumerInterestedIn(D))
1589     InterestingDecls.push_back(D);
1590 
1591   return D;
1592 }
1593 
1594 void ASTDeclReader::UpdateDecl(Decl *D, const RecordData &Record) {
1595   unsigned Idx = 0;
1596   while (Idx < Record.size()) {
1597     switch ((DeclUpdateKind)Record[Idx++]) {
1598     case UPD_CXX_SET_DEFINITIONDATA: {
1599       CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
1600       CXXRecordDecl *
1601           DefinitionDecl = cast<CXXRecordDecl>(Reader.GetDecl(Record[Idx++]));
1602       assert(!RD->DefinitionData && "DefinitionData is already set!");
1603       InitializeCXXDefinitionData(RD, DefinitionDecl, Record, Idx);
1604       break;
1605     }
1606 
1607     case UPD_CXX_ADDED_IMPLICIT_MEMBER:
1608       cast<CXXRecordDecl>(D)->addedMember(Reader.GetDecl(Record[Idx++]));
1609       break;
1610 
1611     case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
1612       // It will be added to the template's specializations set when loaded.
1613       Reader.GetDecl(Record[Idx++]);
1614     }
1615   }
1616 }
1617