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