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