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