ASTReaderDecl.cpp revision 219077
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->IdentLoc = ReadSourceLocation(Record, Idx);
748  D->QualifierLoc = Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
749  D->Namespace = cast<NamedDecl>(Reader.GetDecl(Record[Idx++]));
750}
751
752void ASTDeclReader::VisitUsingDecl(UsingDecl *D) {
753  VisitNamedDecl(D);
754  D->setUsingLocation(ReadSourceLocation(Record, Idx));
755  D->QualifierLoc = Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
756  ReadDeclarationNameLoc(D->DNLoc, D->getDeclName(), Record, Idx);
757  D->FirstUsingShadow = cast_or_null<UsingShadowDecl>(Reader.GetDecl(Record[Idx++]));
758  D->setTypeName(Record[Idx++]);
759  NamedDecl *Pattern = cast_or_null<NamedDecl>(Reader.GetDecl(Record[Idx++]));
760  if (Pattern)
761    Reader.getContext()->setInstantiatedFromUsingDecl(D, Pattern);
762}
763
764void ASTDeclReader::VisitUsingShadowDecl(UsingShadowDecl *D) {
765  VisitNamedDecl(D);
766  D->setTargetDecl(cast<NamedDecl>(Reader.GetDecl(Record[Idx++])));
767  D->UsingOrNextShadow = cast_or_null<NamedDecl>(Reader.GetDecl(Record[Idx++]));
768  UsingShadowDecl *Pattern
769      = cast_or_null<UsingShadowDecl>(Reader.GetDecl(Record[Idx++]));
770  if (Pattern)
771    Reader.getContext()->setInstantiatedFromUsingShadowDecl(D, Pattern);
772}
773
774void ASTDeclReader::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
775  VisitNamedDecl(D);
776  D->UsingLoc = ReadSourceLocation(Record, Idx);
777  D->NamespaceLoc = ReadSourceLocation(Record, Idx);
778  D->QualifierLoc = Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
779  D->NominatedNamespace = cast<NamedDecl>(Reader.GetDecl(Record[Idx++]));
780  D->CommonAncestor = cast_or_null<DeclContext>(Reader.GetDecl(Record[Idx++]));
781}
782
783void ASTDeclReader::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
784  VisitValueDecl(D);
785  D->setUsingLoc(ReadSourceLocation(Record, Idx));
786  D->QualifierLoc = Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
787  ReadDeclarationNameLoc(D->DNLoc, D->getDeclName(), Record, Idx);
788}
789
790void ASTDeclReader::VisitUnresolvedUsingTypenameDecl(
791                                               UnresolvedUsingTypenameDecl *D) {
792  VisitTypeDecl(D);
793  D->UsingLocation = ReadSourceLocation(Record, Idx);
794  D->TypenameLocation = ReadSourceLocation(Record, Idx);
795  D->QualifierLoc = Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
796}
797
798void ASTDeclReader::ReadCXXDefinitionData(
799                                   struct CXXRecordDecl::DefinitionData &Data,
800                                   const RecordData &Record, unsigned &Idx) {
801  Data.UserDeclaredConstructor = Record[Idx++];
802  Data.UserDeclaredCopyConstructor = Record[Idx++];
803  Data.UserDeclaredCopyAssignment = Record[Idx++];
804  Data.UserDeclaredDestructor = Record[Idx++];
805  Data.Aggregate = Record[Idx++];
806  Data.PlainOldData = Record[Idx++];
807  Data.Empty = Record[Idx++];
808  Data.Polymorphic = Record[Idx++];
809  Data.Abstract = Record[Idx++];
810  Data.HasTrivialConstructor = Record[Idx++];
811  Data.HasTrivialCopyConstructor = Record[Idx++];
812  Data.HasTrivialCopyAssignment = Record[Idx++];
813  Data.HasTrivialDestructor = Record[Idx++];
814  Data.ComputedVisibleConversions = Record[Idx++];
815  Data.DeclaredDefaultConstructor = Record[Idx++];
816  Data.DeclaredCopyConstructor = Record[Idx++];
817  Data.DeclaredCopyAssignment = Record[Idx++];
818  Data.DeclaredDestructor = Record[Idx++];
819
820  Data.NumBases = Record[Idx++];
821  if (Data.NumBases)
822    Data.Bases = Reader.GetCXXBaseSpecifiersOffset(Record[Idx++]);
823  Data.NumVBases = Record[Idx++];
824  if (Data.NumVBases)
825    Data.VBases = Reader.GetCXXBaseSpecifiersOffset(Record[Idx++]);
826
827  Reader.ReadUnresolvedSet(Data.Conversions, Record, Idx);
828  Reader.ReadUnresolvedSet(Data.VisibleConversions, Record, Idx);
829  assert(Data.Definition && "Data.Definition should be already set!");
830  Data.FirstFriend
831      = cast_or_null<FriendDecl>(Reader.GetDecl(Record[Idx++]));
832}
833
834void ASTDeclReader::InitializeCXXDefinitionData(CXXRecordDecl *D,
835                                                CXXRecordDecl *DefinitionDecl,
836                                                const RecordData &Record,
837                                                unsigned &Idx) {
838  ASTContext &C = *Reader.getContext();
839
840  if (D == DefinitionDecl) {
841    D->DefinitionData = new (C) struct CXXRecordDecl::DefinitionData(D);
842    ReadCXXDefinitionData(*D->DefinitionData, Record, Idx);
843    // We read the definition info. Check if there are pending forward
844    // references that need to point to this DefinitionData pointer.
845    ASTReader::PendingForwardRefsMap::iterator
846        FindI = Reader.PendingForwardRefs.find(D);
847    if (FindI != Reader.PendingForwardRefs.end()) {
848      ASTReader::ForwardRefs &Refs = FindI->second;
849      for (ASTReader::ForwardRefs::iterator
850             I = Refs.begin(), E = Refs.end(); I != E; ++I)
851        (*I)->DefinitionData = D->DefinitionData;
852#ifndef NDEBUG
853      // We later check whether PendingForwardRefs is empty to make sure all
854      // pending references were linked.
855      Reader.PendingForwardRefs.erase(D);
856#endif
857    }
858  } else if (DefinitionDecl) {
859    if (DefinitionDecl->DefinitionData) {
860      D->DefinitionData = DefinitionDecl->DefinitionData;
861    } else {
862      // The definition is still initializing.
863      Reader.PendingForwardRefs[DefinitionDecl].push_back(D);
864    }
865  }
866}
867
868void ASTDeclReader::VisitCXXRecordDecl(CXXRecordDecl *D) {
869  VisitRecordDecl(D);
870
871  CXXRecordDecl *DefinitionDecl
872      = cast_or_null<CXXRecordDecl>(Reader.GetDecl(Record[Idx++]));
873  InitializeCXXDefinitionData(D, DefinitionDecl, Record, Idx);
874
875  ASTContext &C = *Reader.getContext();
876
877  enum CXXRecKind {
878    CXXRecNotTemplate = 0, CXXRecTemplate, CXXRecMemberSpecialization
879  };
880  switch ((CXXRecKind)Record[Idx++]) {
881  default:
882    assert(false && "Out of sync with ASTDeclWriter::VisitCXXRecordDecl?");
883  case CXXRecNotTemplate:
884    break;
885  case CXXRecTemplate:
886    D->TemplateOrInstantiation
887        = cast<ClassTemplateDecl>(Reader.GetDecl(Record[Idx++]));
888    break;
889  case CXXRecMemberSpecialization: {
890    CXXRecordDecl *RD = cast<CXXRecordDecl>(Reader.GetDecl(Record[Idx++]));
891    TemplateSpecializationKind TSK = (TemplateSpecializationKind)Record[Idx++];
892    SourceLocation POI = ReadSourceLocation(Record, Idx);
893    MemberSpecializationInfo *MSI = new (C) MemberSpecializationInfo(RD, TSK);
894    MSI->setPointOfInstantiation(POI);
895    D->TemplateOrInstantiation = MSI;
896    break;
897  }
898  }
899
900  // Load the key function to avoid deserializing every method so we can
901  // compute it.
902  if (D->IsDefinition) {
903    CXXMethodDecl *Key
904        = cast_or_null<CXXMethodDecl>(Reader.GetDecl(Record[Idx++]));
905    if (Key)
906      C.KeyFunctions[D] = Key;
907  }
908}
909
910void ASTDeclReader::VisitCXXMethodDecl(CXXMethodDecl *D) {
911  VisitFunctionDecl(D);
912  unsigned NumOverridenMethods = Record[Idx++];
913  while (NumOverridenMethods--) {
914    CXXMethodDecl *MD = cast<CXXMethodDecl>(Reader.GetDecl(Record[Idx++]));
915    // Avoid invariant checking of CXXMethodDecl::addOverriddenMethod,
916    // MD may be initializing.
917    Reader.getContext()->addOverriddenMethod(D, MD);
918  }
919}
920
921void ASTDeclReader::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
922  VisitCXXMethodDecl(D);
923
924  D->IsExplicitSpecified = Record[Idx++];
925  D->ImplicitlyDefined = Record[Idx++];
926  llvm::tie(D->CtorInitializers, D->NumCtorInitializers)
927      = Reader.ReadCXXCtorInitializers(F, Record, Idx);
928}
929
930void ASTDeclReader::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
931  VisitCXXMethodDecl(D);
932
933  D->ImplicitlyDefined = Record[Idx++];
934  D->OperatorDelete = cast_or_null<FunctionDecl>(Reader.GetDecl(Record[Idx++]));
935}
936
937void ASTDeclReader::VisitCXXConversionDecl(CXXConversionDecl *D) {
938  VisitCXXMethodDecl(D);
939  D->IsExplicitSpecified = Record[Idx++];
940}
941
942void ASTDeclReader::VisitAccessSpecDecl(AccessSpecDecl *D) {
943  VisitDecl(D);
944  D->setColonLoc(ReadSourceLocation(Record, Idx));
945}
946
947void ASTDeclReader::VisitFriendDecl(FriendDecl *D) {
948  VisitDecl(D);
949  if (Record[Idx++])
950    D->Friend = GetTypeSourceInfo(Record, Idx);
951  else
952    D->Friend = cast<NamedDecl>(Reader.GetDecl(Record[Idx++]));
953  D->NextFriend = Record[Idx++];
954  D->UnsupportedFriend = (Record[Idx++] != 0);
955  D->FriendLoc = ReadSourceLocation(Record, Idx);
956}
957
958void ASTDeclReader::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
959  VisitDecl(D);
960  unsigned NumParams = Record[Idx++];
961  D->NumParams = NumParams;
962  D->Params = new TemplateParameterList*[NumParams];
963  for (unsigned i = 0; i != NumParams; ++i)
964    D->Params[i] = Reader.ReadTemplateParameterList(F, Record, Idx);
965  if (Record[Idx++]) // HasFriendDecl
966    D->Friend = cast<NamedDecl>(Reader.GetDecl(Record[Idx++]));
967  else
968    D->Friend = GetTypeSourceInfo(Record, Idx);
969  D->FriendLoc = ReadSourceLocation(Record, Idx);
970}
971
972void ASTDeclReader::VisitTemplateDecl(TemplateDecl *D) {
973  VisitNamedDecl(D);
974
975  NamedDecl *TemplatedDecl
976    = cast_or_null<NamedDecl>(Reader.GetDecl(Record[Idx++]));
977  TemplateParameterList* TemplateParams
978      = Reader.ReadTemplateParameterList(F, Record, Idx);
979  D->init(TemplatedDecl, TemplateParams);
980}
981
982void ASTDeclReader::VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D) {
983  // Initialize CommonOrPrev before VisitTemplateDecl so that getCommonPtr()
984  // can be used while this is still initializing.
985
986  assert(D->CommonOrPrev.isNull() && "getCommonPtr was called earlier on this");
987  DeclID PreviousDeclID = Record[Idx++];
988  DeclID FirstDeclID =  PreviousDeclID ? Record[Idx++] : 0;
989  // We delay loading of the redeclaration chain to avoid deeply nested calls.
990  // We temporarily set the first (canonical) declaration as the previous one
991  // which is the one that matters and mark the real previous DeclID to be
992  // loaded & attached later on.
993  RedeclarableTemplateDecl *FirstDecl =
994      cast_or_null<RedeclarableTemplateDecl>(Reader.GetDecl(FirstDeclID));
995  assert((FirstDecl == 0 || FirstDecl->getKind() == D->getKind()) &&
996         "FirstDecl kind mismatch");
997  if (FirstDecl) {
998    D->CommonOrPrev = FirstDecl;
999    // Mark the real previous DeclID to be loaded & attached later on.
1000    if (PreviousDeclID != FirstDeclID)
1001      Reader.PendingPreviousDecls.push_back(std::make_pair(D, PreviousDeclID));
1002  } else {
1003    D->CommonOrPrev = D->newCommon(*Reader.getContext());
1004    if (RedeclarableTemplateDecl *RTD
1005          = cast_or_null<RedeclarableTemplateDecl>(Reader.GetDecl(Record[Idx++]))) {
1006      assert(RTD->getKind() == D->getKind() &&
1007             "InstantiatedFromMemberTemplate kind mismatch");
1008      D->setInstantiatedFromMemberTemplateImpl(RTD);
1009      if (Record[Idx++])
1010        D->setMemberSpecialization();
1011    }
1012
1013    RedeclarableTemplateDecl *LatestDecl =
1014        cast_or_null<RedeclarableTemplateDecl>(Reader.GetDecl(Record[Idx++]));
1015
1016    // This decl is a first one and the latest declaration that it points to is
1017    // in the same AST file. However, if this actually needs to point to a
1018    // redeclaration in another AST file, we need to update it by checking
1019    // the FirstLatestDeclIDs map which tracks this kind of decls.
1020    assert(Reader.GetDecl(ThisDeclID) == D && "Invalid ThisDeclID ?");
1021    ASTReader::FirstLatestDeclIDMap::iterator I
1022        = Reader.FirstLatestDeclIDs.find(ThisDeclID);
1023    if (I != Reader.FirstLatestDeclIDs.end()) {
1024      Decl *NewLatest = Reader.GetDecl(I->second);
1025      assert((LatestDecl->getLocation().isInvalid() ||
1026              NewLatest->getLocation().isInvalid()  ||
1027              !Reader.SourceMgr.isBeforeInTranslationUnit(
1028                                                  NewLatest->getLocation(),
1029                                                  LatestDecl->getLocation())) &&
1030             "The new latest is supposed to come after the previous latest");
1031      LatestDecl = cast<RedeclarableTemplateDecl>(NewLatest);
1032    }
1033
1034    assert(LatestDecl->getKind() == D->getKind() && "Latest kind mismatch");
1035    D->getCommonPtr()->Latest = LatestDecl;
1036  }
1037
1038  VisitTemplateDecl(D);
1039  D->IdentifierNamespace = Record[Idx++];
1040}
1041
1042void ASTDeclReader::VisitClassTemplateDecl(ClassTemplateDecl *D) {
1043  VisitRedeclarableTemplateDecl(D);
1044
1045  if (D->getPreviousDeclaration() == 0) {
1046    // This ClassTemplateDecl owns a CommonPtr; read it to keep track of all of
1047    // the specializations.
1048    llvm::SmallVector<serialization::DeclID, 2> SpecIDs;
1049    SpecIDs.push_back(0);
1050
1051    // Specializations.
1052    unsigned Size = Record[Idx++];
1053    SpecIDs[0] += Size;
1054    SpecIDs.append(Record.begin() + Idx, Record.begin() + Idx + Size);
1055    Idx += Size;
1056
1057    // Partial specializations.
1058    Size = Record[Idx++];
1059    SpecIDs[0] += Size;
1060    SpecIDs.append(Record.begin() + Idx, Record.begin() + Idx + Size);
1061    Idx += Size;
1062
1063    if (SpecIDs[0]) {
1064      typedef serialization::DeclID DeclID;
1065
1066      ClassTemplateDecl::Common *CommonPtr = D->getCommonPtr();
1067      CommonPtr->LazySpecializations
1068        = new (*Reader.getContext()) DeclID [SpecIDs.size()];
1069      memcpy(CommonPtr->LazySpecializations, SpecIDs.data(),
1070             SpecIDs.size() * sizeof(DeclID));
1071    }
1072
1073    // InjectedClassNameType is computed.
1074  }
1075}
1076
1077void ASTDeclReader::VisitClassTemplateSpecializationDecl(
1078                                           ClassTemplateSpecializationDecl *D) {
1079  VisitCXXRecordDecl(D);
1080
1081  ASTContext &C = *Reader.getContext();
1082  if (Decl *InstD = Reader.GetDecl(Record[Idx++])) {
1083    if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(InstD)) {
1084      D->SpecializedTemplate = CTD;
1085    } else {
1086      llvm::SmallVector<TemplateArgument, 8> TemplArgs;
1087      Reader.ReadTemplateArgumentList(TemplArgs, F, Record, Idx);
1088      TemplateArgumentList *ArgList
1089        = TemplateArgumentList::CreateCopy(C, TemplArgs.data(),
1090                                           TemplArgs.size());
1091      ClassTemplateSpecializationDecl::SpecializedPartialSpecialization *PS
1092          = new (C) ClassTemplateSpecializationDecl::
1093                                             SpecializedPartialSpecialization();
1094      PS->PartialSpecialization
1095          = cast<ClassTemplatePartialSpecializationDecl>(InstD);
1096      PS->TemplateArgs = ArgList;
1097      D->SpecializedTemplate = PS;
1098    }
1099  }
1100
1101  // Explicit info.
1102  if (TypeSourceInfo *TyInfo = GetTypeSourceInfo(Record, Idx)) {
1103    ClassTemplateSpecializationDecl::ExplicitSpecializationInfo *ExplicitInfo
1104        = new (C) ClassTemplateSpecializationDecl::ExplicitSpecializationInfo;
1105    ExplicitInfo->TypeAsWritten = TyInfo;
1106    ExplicitInfo->ExternLoc = ReadSourceLocation(Record, Idx);
1107    ExplicitInfo->TemplateKeywordLoc = ReadSourceLocation(Record, Idx);
1108    D->ExplicitInfo = ExplicitInfo;
1109  }
1110
1111  llvm::SmallVector<TemplateArgument, 8> TemplArgs;
1112  Reader.ReadTemplateArgumentList(TemplArgs, F, Record, Idx);
1113  D->TemplateArgs = TemplateArgumentList::CreateCopy(C, TemplArgs.data(),
1114                                                     TemplArgs.size());
1115  D->PointOfInstantiation = ReadSourceLocation(Record, Idx);
1116  D->SpecializationKind = (TemplateSpecializationKind)Record[Idx++];
1117
1118  if (D->isCanonicalDecl()) { // It's kept in the folding set.
1119    ClassTemplateDecl *CanonPattern
1120                       = cast<ClassTemplateDecl>(Reader.GetDecl(Record[Idx++]));
1121    if (ClassTemplatePartialSpecializationDecl *Partial
1122                       = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) {
1123      CanonPattern->getCommonPtr()->PartialSpecializations.InsertNode(Partial);
1124    } else {
1125      CanonPattern->getCommonPtr()->Specializations.InsertNode(D);
1126    }
1127  }
1128}
1129
1130void ASTDeclReader::VisitClassTemplatePartialSpecializationDecl(
1131                                    ClassTemplatePartialSpecializationDecl *D) {
1132  VisitClassTemplateSpecializationDecl(D);
1133
1134  ASTContext &C = *Reader.getContext();
1135  D->TemplateParams = Reader.ReadTemplateParameterList(F, Record, Idx);
1136
1137  unsigned NumArgs = Record[Idx++];
1138  if (NumArgs) {
1139    D->NumArgsAsWritten = NumArgs;
1140    D->ArgsAsWritten = new (C) TemplateArgumentLoc[NumArgs];
1141    for (unsigned i=0; i != NumArgs; ++i)
1142      D->ArgsAsWritten[i] = Reader.ReadTemplateArgumentLoc(F, Record, Idx);
1143  }
1144
1145  D->SequenceNumber = Record[Idx++];
1146
1147  // These are read/set from/to the first declaration.
1148  if (D->getPreviousDeclaration() == 0) {
1149    D->InstantiatedFromMember.setPointer(
1150        cast_or_null<ClassTemplatePartialSpecializationDecl>(
1151                                                Reader.GetDecl(Record[Idx++])));
1152    D->InstantiatedFromMember.setInt(Record[Idx++]);
1153  }
1154}
1155
1156void ASTDeclReader::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
1157  VisitRedeclarableTemplateDecl(D);
1158
1159  if (D->getPreviousDeclaration() == 0) {
1160    // This FunctionTemplateDecl owns a CommonPtr; read it.
1161
1162    // Read the function specialization declarations.
1163    // FunctionTemplateDecl's FunctionTemplateSpecializationInfos are filled
1164    // when reading the specialized FunctionDecl.
1165    unsigned NumSpecs = Record[Idx++];
1166    while (NumSpecs--)
1167      Reader.GetDecl(Record[Idx++]);
1168  }
1169}
1170
1171void ASTDeclReader::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
1172  VisitTypeDecl(D);
1173
1174  D->setDeclaredWithTypename(Record[Idx++]);
1175  D->setParameterPack(Record[Idx++]);
1176
1177  bool Inherited = Record[Idx++];
1178  TypeSourceInfo *DefArg = GetTypeSourceInfo(Record, Idx);
1179  D->setDefaultArgument(DefArg, Inherited);
1180}
1181
1182void ASTDeclReader::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
1183  VisitDeclaratorDecl(D);
1184  // TemplateParmPosition.
1185  D->setDepth(Record[Idx++]);
1186  D->setPosition(Record[Idx++]);
1187  if (D->isExpandedParameterPack()) {
1188    void **Data = reinterpret_cast<void **>(D + 1);
1189    for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
1190      Data[2*I] = Reader.GetType(Record[Idx++]).getAsOpaquePtr();
1191      Data[2*I + 1] = GetTypeSourceInfo(Record, Idx);
1192    }
1193  } else {
1194    // Rest of NonTypeTemplateParmDecl.
1195    D->ParameterPack = Record[Idx++];
1196    if (Record[Idx++]) {
1197      Expr *DefArg = Reader.ReadExpr(F);
1198      bool Inherited = Record[Idx++];
1199      D->setDefaultArgument(DefArg, Inherited);
1200   }
1201  }
1202}
1203
1204void ASTDeclReader::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
1205  VisitTemplateDecl(D);
1206  // TemplateParmPosition.
1207  D->setDepth(Record[Idx++]);
1208  D->setPosition(Record[Idx++]);
1209  // Rest of TemplateTemplateParmDecl.
1210  TemplateArgumentLoc Arg = Reader.ReadTemplateArgumentLoc(F, Record, Idx);
1211  bool IsInherited = Record[Idx++];
1212  D->setDefaultArgument(Arg, IsInherited);
1213  D->ParameterPack = Record[Idx++];
1214}
1215
1216void ASTDeclReader::VisitStaticAssertDecl(StaticAssertDecl *D) {
1217  VisitDecl(D);
1218  D->AssertExpr = Reader.ReadExpr(F);
1219  D->Message = cast<StringLiteral>(Reader.ReadExpr(F));
1220}
1221
1222std::pair<uint64_t, uint64_t>
1223ASTDeclReader::VisitDeclContext(DeclContext *DC) {
1224  uint64_t LexicalOffset = Record[Idx++];
1225  uint64_t VisibleOffset = Record[Idx++];
1226  return std::make_pair(LexicalOffset, VisibleOffset);
1227}
1228
1229template <typename T>
1230void ASTDeclReader::VisitRedeclarable(Redeclarable<T> *D) {
1231  enum RedeclKind { NoRedeclaration = 0, PointsToPrevious, PointsToLatest };
1232  RedeclKind Kind = (RedeclKind)Record[Idx++];
1233  switch (Kind) {
1234  default:
1235    assert(0 && "Out of sync with ASTDeclWriter::VisitRedeclarable or messed up"
1236                " reading");
1237  case NoRedeclaration:
1238    break;
1239  case PointsToPrevious: {
1240    DeclID PreviousDeclID = Record[Idx++];
1241    DeclID FirstDeclID = Record[Idx++];
1242    // We delay loading of the redeclaration chain to avoid deeply nested calls.
1243    // We temporarily set the first (canonical) declaration as the previous one
1244    // which is the one that matters and mark the real previous DeclID to be
1245    // loaded & attached later on.
1246    D->RedeclLink = typename Redeclarable<T>::PreviousDeclLink(
1247                                cast_or_null<T>(Reader.GetDecl(FirstDeclID)));
1248    if (PreviousDeclID != FirstDeclID)
1249      Reader.PendingPreviousDecls.push_back(std::make_pair(static_cast<T*>(D),
1250                                                           PreviousDeclID));
1251    break;
1252  }
1253  case PointsToLatest:
1254    D->RedeclLink = typename Redeclarable<T>::LatestDeclLink(
1255                                cast_or_null<T>(Reader.GetDecl(Record[Idx++])));
1256    break;
1257  }
1258
1259  assert(!(Kind == PointsToPrevious &&
1260           Reader.FirstLatestDeclIDs.find(ThisDeclID) !=
1261               Reader.FirstLatestDeclIDs.end()) &&
1262         "This decl is not first, it should not be in the map");
1263  if (Kind == PointsToPrevious)
1264    return;
1265
1266  // This decl is a first one and the latest declaration that it points to is in
1267  // the same AST file. However, if this actually needs to point to a
1268  // redeclaration in another AST file, we need to update it by checking the
1269  // FirstLatestDeclIDs map which tracks this kind of decls.
1270  assert(Reader.GetDecl(ThisDeclID) == static_cast<T*>(D) &&
1271         "Invalid ThisDeclID ?");
1272  ASTReader::FirstLatestDeclIDMap::iterator I
1273      = Reader.FirstLatestDeclIDs.find(ThisDeclID);
1274  if (I != Reader.FirstLatestDeclIDs.end()) {
1275    Decl *NewLatest = Reader.GetDecl(I->second);
1276    D->RedeclLink
1277        = typename Redeclarable<T>::LatestDeclLink(cast_or_null<T>(NewLatest));
1278  }
1279}
1280
1281//===----------------------------------------------------------------------===//
1282// Attribute Reading
1283//===----------------------------------------------------------------------===//
1284
1285/// \brief Reads attributes from the current stream position.
1286void ASTReader::ReadAttributes(PerFileData &F, AttrVec &Attrs,
1287                               const RecordData &Record, unsigned &Idx) {
1288  for (unsigned i = 0, e = Record[Idx++]; i != e; ++i) {
1289    Attr *New = 0;
1290    attr::Kind Kind = (attr::Kind)Record[Idx++];
1291    SourceLocation Loc = ReadSourceLocation(F, Record, Idx);
1292
1293#include "clang/Serialization/AttrPCHRead.inc"
1294
1295    assert(New && "Unable to decode attribute?");
1296    Attrs.push_back(New);
1297  }
1298}
1299
1300//===----------------------------------------------------------------------===//
1301// ASTReader Implementation
1302//===----------------------------------------------------------------------===//
1303
1304/// \brief Note that we have loaded the declaration with the given
1305/// Index.
1306///
1307/// This routine notes that this declaration has already been loaded,
1308/// so that future GetDecl calls will return this declaration rather
1309/// than trying to load a new declaration.
1310inline void ASTReader::LoadedDecl(unsigned Index, Decl *D) {
1311  assert(!DeclsLoaded[Index] && "Decl loaded twice?");
1312  DeclsLoaded[Index] = D;
1313}
1314
1315
1316/// \brief Determine whether the consumer will be interested in seeing
1317/// this declaration (via HandleTopLevelDecl).
1318///
1319/// This routine should return true for anything that might affect
1320/// code generation, e.g., inline function definitions, Objective-C
1321/// declarations with metadata, etc.
1322static bool isConsumerInterestedIn(Decl *D) {
1323  if (isa<FileScopeAsmDecl>(D))
1324    return true;
1325  if (VarDecl *Var = dyn_cast<VarDecl>(D))
1326    return Var->isFileVarDecl() &&
1327           Var->isThisDeclarationADefinition() == VarDecl::Definition;
1328  if (FunctionDecl *Func = dyn_cast<FunctionDecl>(D))
1329    return Func->isThisDeclarationADefinition();
1330  return isa<ObjCProtocolDecl>(D) || isa<ObjCImplementationDecl>(D);
1331}
1332
1333/// \brief Get the correct cursor and offset for loading a type.
1334ASTReader::RecordLocation
1335ASTReader::DeclCursorForIndex(unsigned Index, DeclID ID) {
1336  // See if there's an override.
1337  DeclReplacementMap::iterator It = ReplacedDecls.find(ID);
1338  if (It != ReplacedDecls.end())
1339    return RecordLocation(It->second.first, It->second.second);
1340
1341  PerFileData *F = 0;
1342  for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
1343    F = Chain[N - I - 1];
1344    if (Index < F->LocalNumDecls)
1345      break;
1346    Index -= F->LocalNumDecls;
1347  }
1348  assert(F && F->LocalNumDecls > Index && "Broken chain");
1349  return RecordLocation(F, F->DeclOffsets[Index]);
1350}
1351
1352void ASTDeclReader::attachPreviousDecl(Decl *D, Decl *previous) {
1353  assert(D && previous);
1354  if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
1355    TD->RedeclLink.setPointer(cast<TagDecl>(previous));
1356  } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1357    FD->RedeclLink.setPointer(cast<FunctionDecl>(previous));
1358  } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
1359    VD->RedeclLink.setPointer(cast<VarDecl>(previous));
1360  } else {
1361    RedeclarableTemplateDecl *TD = cast<RedeclarableTemplateDecl>(D);
1362    TD->CommonOrPrev = cast<RedeclarableTemplateDecl>(previous);
1363  }
1364}
1365
1366void ASTReader::loadAndAttachPreviousDecl(Decl *D, serialization::DeclID ID) {
1367  Decl *previous = GetDecl(ID);
1368  ASTDeclReader::attachPreviousDecl(D, previous);
1369}
1370
1371/// \brief Read the declaration at the given offset from the AST file.
1372Decl *ASTReader::ReadDeclRecord(unsigned Index, DeclID ID) {
1373  RecordLocation Loc = DeclCursorForIndex(Index, ID);
1374  llvm::BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
1375  // Keep track of where we are in the stream, then jump back there
1376  // after reading this declaration.
1377  SavedStreamPosition SavedPosition(DeclsCursor);
1378
1379  ReadingKindTracker ReadingKind(Read_Decl, *this);
1380
1381  // Note that we are loading a declaration record.
1382  Deserializing ADecl(this);
1383
1384  DeclsCursor.JumpToBit(Loc.Offset);
1385  RecordData Record;
1386  unsigned Code = DeclsCursor.ReadCode();
1387  unsigned Idx = 0;
1388  ASTDeclReader Reader(*this, *Loc.F, DeclsCursor, ID, Record, Idx);
1389
1390  Decl *D = 0;
1391  switch ((DeclCode)DeclsCursor.ReadRecord(Code, Record)) {
1392  case DECL_CONTEXT_LEXICAL:
1393  case DECL_CONTEXT_VISIBLE:
1394    assert(false && "Record cannot be de-serialized with ReadDeclRecord");
1395    break;
1396  case DECL_TRANSLATION_UNIT:
1397    assert(Index == 0 && "Translation unit must be at index 0");
1398    D = Context->getTranslationUnitDecl();
1399    break;
1400  case DECL_TYPEDEF:
1401    D = TypedefDecl::Create(*Context, 0, SourceLocation(), 0, 0);
1402    break;
1403  case DECL_ENUM:
1404    D = EnumDecl::Create(*Context, Decl::EmptyShell());
1405    break;
1406  case DECL_RECORD:
1407    D = RecordDecl::Create(*Context, Decl::EmptyShell());
1408    break;
1409  case DECL_ENUM_CONSTANT:
1410    D = EnumConstantDecl::Create(*Context, 0, SourceLocation(), 0, QualType(),
1411                                 0, llvm::APSInt());
1412    break;
1413  case DECL_FUNCTION:
1414    D = FunctionDecl::Create(*Context, 0, SourceLocation(), DeclarationName(),
1415                             QualType(), 0);
1416    break;
1417  case DECL_LINKAGE_SPEC:
1418    D = LinkageSpecDecl::Create(*Context, 0, SourceLocation(),
1419                                (LinkageSpecDecl::LanguageIDs)0,
1420                                false);
1421    break;
1422  case DECL_LABEL:
1423    D = LabelDecl::Create(*Context, 0, SourceLocation(), 0);
1424    break;
1425  case DECL_NAMESPACE:
1426    D = NamespaceDecl::Create(*Context, 0, SourceLocation(), 0);
1427    break;
1428  case DECL_NAMESPACE_ALIAS:
1429    D = NamespaceAliasDecl::Create(*Context, 0, SourceLocation(),
1430                                   SourceLocation(), 0,
1431                                   NestedNameSpecifierLoc(),
1432                                   SourceLocation(), 0);
1433    break;
1434  case DECL_USING:
1435    D = UsingDecl::Create(*Context, 0, SourceLocation(),
1436                          NestedNameSpecifierLoc(), DeclarationNameInfo(),
1437                          false);
1438    break;
1439  case DECL_USING_SHADOW:
1440    D = UsingShadowDecl::Create(*Context, 0, SourceLocation(), 0, 0);
1441    break;
1442  case DECL_USING_DIRECTIVE:
1443    D = UsingDirectiveDecl::Create(*Context, 0, SourceLocation(),
1444                                   SourceLocation(), NestedNameSpecifierLoc(),
1445                                   SourceLocation(), 0, 0);
1446    break;
1447  case DECL_UNRESOLVED_USING_VALUE:
1448    D = UnresolvedUsingValueDecl::Create(*Context, 0, SourceLocation(),
1449                                         NestedNameSpecifierLoc(),
1450                                         DeclarationNameInfo());
1451    break;
1452  case DECL_UNRESOLVED_USING_TYPENAME:
1453    D = UnresolvedUsingTypenameDecl::Create(*Context, 0, SourceLocation(),
1454                                            SourceLocation(),
1455                                            NestedNameSpecifierLoc(),
1456                                            SourceLocation(),
1457                                            DeclarationName());
1458    break;
1459  case DECL_CXX_RECORD:
1460    D = CXXRecordDecl::Create(*Context, Decl::EmptyShell());
1461    break;
1462  case DECL_CXX_METHOD:
1463    D = CXXMethodDecl::Create(*Context, 0, DeclarationNameInfo(),
1464                              QualType(), 0);
1465    break;
1466  case DECL_CXX_CONSTRUCTOR:
1467    D = CXXConstructorDecl::Create(*Context, Decl::EmptyShell());
1468    break;
1469  case DECL_CXX_DESTRUCTOR:
1470    D = CXXDestructorDecl::Create(*Context, Decl::EmptyShell());
1471    break;
1472  case DECL_CXX_CONVERSION:
1473    D = CXXConversionDecl::Create(*Context, Decl::EmptyShell());
1474    break;
1475  case DECL_ACCESS_SPEC:
1476    D = AccessSpecDecl::Create(*Context, Decl::EmptyShell());
1477    break;
1478  case DECL_FRIEND:
1479    D = FriendDecl::Create(*Context, Decl::EmptyShell());
1480    break;
1481  case DECL_FRIEND_TEMPLATE:
1482    D = FriendTemplateDecl::Create(*Context, Decl::EmptyShell());
1483    break;
1484  case DECL_CLASS_TEMPLATE:
1485    D = ClassTemplateDecl::Create(*Context, 0, SourceLocation(),
1486                                  DeclarationName(), 0, 0, 0);
1487    break;
1488  case DECL_CLASS_TEMPLATE_SPECIALIZATION:
1489    D = ClassTemplateSpecializationDecl::Create(*Context, Decl::EmptyShell());
1490    break;
1491  case DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION:
1492    D = ClassTemplatePartialSpecializationDecl::Create(*Context,
1493                                                            Decl::EmptyShell());
1494    break;
1495  case DECL_FUNCTION_TEMPLATE:
1496    D = FunctionTemplateDecl::Create(*Context, 0, SourceLocation(),
1497                                     DeclarationName(), 0, 0);
1498    break;
1499  case DECL_TEMPLATE_TYPE_PARM:
1500    D = TemplateTypeParmDecl::Create(*Context, Decl::EmptyShell());
1501    break;
1502  case DECL_NON_TYPE_TEMPLATE_PARM:
1503    D = NonTypeTemplateParmDecl::Create(*Context, 0, SourceLocation(), 0,0,0,
1504                                        QualType(), false, 0);
1505    break;
1506  case DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK:
1507    D = NonTypeTemplateParmDecl::Create(*Context, 0, SourceLocation(), 0, 0,
1508                                        0, QualType(), 0, 0, Record[Idx++],
1509                                        0);
1510    break;
1511  case DECL_TEMPLATE_TEMPLATE_PARM:
1512    D = TemplateTemplateParmDecl::Create(*Context, 0, SourceLocation(), 0, 0,
1513                                         false, 0, 0);
1514    break;
1515  case DECL_STATIC_ASSERT:
1516    D = StaticAssertDecl::Create(*Context, 0, SourceLocation(), 0, 0);
1517    break;
1518
1519  case DECL_OBJC_METHOD:
1520    D = ObjCMethodDecl::Create(*Context, SourceLocation(), SourceLocation(),
1521                               Selector(), QualType(), 0, 0);
1522    break;
1523  case DECL_OBJC_INTERFACE:
1524    D = ObjCInterfaceDecl::Create(*Context, 0, SourceLocation(), 0);
1525    break;
1526  case DECL_OBJC_IVAR:
1527    D = ObjCIvarDecl::Create(*Context, 0, SourceLocation(), 0, QualType(), 0,
1528                             ObjCIvarDecl::None);
1529    break;
1530  case DECL_OBJC_PROTOCOL:
1531    D = ObjCProtocolDecl::Create(*Context, 0, SourceLocation(), 0);
1532    break;
1533  case DECL_OBJC_AT_DEFS_FIELD:
1534    D = ObjCAtDefsFieldDecl::Create(*Context, 0, SourceLocation(), 0,
1535                                    QualType(), 0);
1536    break;
1537  case DECL_OBJC_CLASS:
1538    D = ObjCClassDecl::Create(*Context, 0, SourceLocation());
1539    break;
1540  case DECL_OBJC_FORWARD_PROTOCOL:
1541    D = ObjCForwardProtocolDecl::Create(*Context, 0, SourceLocation());
1542    break;
1543  case DECL_OBJC_CATEGORY:
1544    D = ObjCCategoryDecl::Create(*Context, 0, SourceLocation(),
1545                                 SourceLocation(), SourceLocation(), 0);
1546    break;
1547  case DECL_OBJC_CATEGORY_IMPL:
1548    D = ObjCCategoryImplDecl::Create(*Context, 0, SourceLocation(), 0, 0);
1549    break;
1550  case DECL_OBJC_IMPLEMENTATION:
1551    D = ObjCImplementationDecl::Create(*Context, 0, SourceLocation(), 0, 0);
1552    break;
1553  case DECL_OBJC_COMPATIBLE_ALIAS:
1554    D = ObjCCompatibleAliasDecl::Create(*Context, 0, SourceLocation(), 0, 0);
1555    break;
1556  case DECL_OBJC_PROPERTY:
1557    D = ObjCPropertyDecl::Create(*Context, 0, SourceLocation(), 0, SourceLocation(),
1558                                 0);
1559    break;
1560  case DECL_OBJC_PROPERTY_IMPL:
1561    D = ObjCPropertyImplDecl::Create(*Context, 0, SourceLocation(),
1562                                     SourceLocation(), 0,
1563                                     ObjCPropertyImplDecl::Dynamic, 0,
1564                                     SourceLocation());
1565    break;
1566  case DECL_FIELD:
1567    D = FieldDecl::Create(*Context, 0, SourceLocation(), 0, QualType(), 0, 0,
1568                          false);
1569    break;
1570  case DECL_INDIRECTFIELD:
1571    D = IndirectFieldDecl::Create(*Context, 0, SourceLocation(), 0, QualType(),
1572                                  0, 0);
1573    break;
1574  case DECL_VAR:
1575    D = VarDecl::Create(*Context, 0, SourceLocation(), 0, QualType(), 0,
1576                        SC_None, SC_None);
1577    break;
1578
1579  case DECL_IMPLICIT_PARAM:
1580    D = ImplicitParamDecl::Create(*Context, 0, SourceLocation(), 0, QualType());
1581    break;
1582
1583  case DECL_PARM_VAR:
1584    D = ParmVarDecl::Create(*Context, 0, SourceLocation(), 0, QualType(), 0,
1585                            SC_None, SC_None, 0);
1586    break;
1587  case DECL_FILE_SCOPE_ASM:
1588    D = FileScopeAsmDecl::Create(*Context, 0, SourceLocation(), 0);
1589    break;
1590  case DECL_BLOCK:
1591    D = BlockDecl::Create(*Context, 0, SourceLocation());
1592    break;
1593  case DECL_CXX_BASE_SPECIFIERS:
1594    Error("attempt to read a C++ base-specifier record as a declaration");
1595    return 0;
1596  }
1597
1598  assert(D && "Unknown declaration reading AST file");
1599  LoadedDecl(Index, D);
1600  Reader.Visit(D);
1601
1602  // If this declaration is also a declaration context, get the
1603  // offsets for its tables of lexical and visible declarations.
1604  if (DeclContext *DC = dyn_cast<DeclContext>(D)) {
1605    std::pair<uint64_t, uint64_t> Offsets = Reader.VisitDeclContext(DC);
1606    if (Offsets.first || Offsets.second) {
1607      DC->setHasExternalLexicalStorage(Offsets.first != 0);
1608      DC->setHasExternalVisibleStorage(Offsets.second != 0);
1609      DeclContextInfo Info;
1610      if (ReadDeclContextStorage(DeclsCursor, Offsets, Info))
1611        return 0;
1612      DeclContextInfos &Infos = DeclContextOffsets[DC];
1613      // Reading the TU will happen after reading its lexical update blocks,
1614      // so we need to make sure we insert in front. For all other contexts,
1615      // the vector is empty here anyway, so there's no loss in efficiency.
1616      Infos.insert(Infos.begin(), Info);
1617
1618      // Now add the pending visible updates for this decl context, if it has
1619      // any.
1620      DeclContextVisibleUpdatesPending::iterator I =
1621          PendingVisibleUpdates.find(ID);
1622      if (I != PendingVisibleUpdates.end()) {
1623        DeclContextVisibleUpdates &U = I->second;
1624        Info.LexicalDecls = 0;
1625        Info.NumLexicalDecls = 0;
1626        for (DeclContextVisibleUpdates::iterator UI = U.begin(), UE = U.end();
1627             UI != UE; ++UI) {
1628          Info.NameLookupTableData = *UI;
1629          Infos.push_back(Info);
1630        }
1631        PendingVisibleUpdates.erase(I);
1632      }
1633    }
1634  }
1635  assert(Idx == Record.size());
1636
1637  // The declaration may have been modified by files later in the chain.
1638  // If this is the case, read the record containing the updates from each file
1639  // and pass it to ASTDeclReader to make the modifications.
1640  DeclUpdateOffsetsMap::iterator UpdI = DeclUpdateOffsets.find(ID);
1641  if (UpdI != DeclUpdateOffsets.end()) {
1642    FileOffsetsTy &UpdateOffsets = UpdI->second;
1643    for (FileOffsetsTy::iterator
1644           I = UpdateOffsets.begin(), E = UpdateOffsets.end(); I != E; ++I) {
1645      PerFileData *F = I->first;
1646      uint64_t Offset = I->second;
1647      llvm::BitstreamCursor &Cursor = F->DeclsCursor;
1648      SavedStreamPosition SavedPosition(Cursor);
1649      Cursor.JumpToBit(Offset);
1650      RecordData Record;
1651      unsigned Code = Cursor.ReadCode();
1652      unsigned RecCode = Cursor.ReadRecord(Code, Record);
1653      (void)RecCode;
1654      assert(RecCode == DECL_UPDATES && "Expected DECL_UPDATES record!");
1655      Reader.UpdateDecl(D, Record);
1656    }
1657  }
1658
1659  // If we have deserialized a declaration that has a definition the
1660  // AST consumer might need to know about, queue it.
1661  // We don't pass it to the consumer immediately because we may be in recursive
1662  // loading, and some declarations may still be initializing.
1663  if (isConsumerInterestedIn(D))
1664    InterestingDecls.push_back(D);
1665
1666  return D;
1667}
1668
1669void ASTDeclReader::UpdateDecl(Decl *D, const RecordData &Record) {
1670  unsigned Idx = 0;
1671  while (Idx < Record.size()) {
1672    switch ((DeclUpdateKind)Record[Idx++]) {
1673    case UPD_CXX_SET_DEFINITIONDATA: {
1674      CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
1675      CXXRecordDecl *
1676          DefinitionDecl = cast<CXXRecordDecl>(Reader.GetDecl(Record[Idx++]));
1677      assert(!RD->DefinitionData && "DefinitionData is already set!");
1678      InitializeCXXDefinitionData(RD, DefinitionDecl, Record, Idx);
1679      break;
1680    }
1681
1682    case UPD_CXX_ADDED_IMPLICIT_MEMBER:
1683      cast<CXXRecordDecl>(D)->addedMember(Reader.GetDecl(Record[Idx++]));
1684      break;
1685
1686    case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
1687      // It will be added to the template's specializations set when loaded.
1688      Reader.GetDecl(Record[Idx++]);
1689    }
1690  }
1691}
1692