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