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