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