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