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