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