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