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