1212795Sdim//===--- ASTReaderDecl.cpp - Decl Deserialization ---------------*- C++ -*-===//
2212795Sdim//
3212795Sdim//                     The LLVM Compiler Infrastructure
4212795Sdim//
5212795Sdim// This file is distributed under the University of Illinois Open Source
6212795Sdim// License. See LICENSE.TXT for details.
7212795Sdim//
8212795Sdim//===----------------------------------------------------------------------===//
9212795Sdim//
10212795Sdim// This file implements the ASTReader::ReadDeclRecord method, which is the
11212795Sdim// entrypoint for loading a decl.
12212795Sdim//
13212795Sdim//===----------------------------------------------------------------------===//
14212795Sdim
15249423Sdim#include "clang/Serialization/ASTReader.h"
16218893Sdim#include "ASTCommon.h"
17234982Sdim#include "ASTReaderInternals.h"
18212795Sdim#include "clang/AST/ASTConsumer.h"
19212795Sdim#include "clang/AST/ASTContext.h"
20249423Sdim#include "clang/AST/DeclCXX.h"
21212795Sdim#include "clang/AST/DeclGroup.h"
22212795Sdim#include "clang/AST/DeclTemplate.h"
23249423Sdim#include "clang/AST/DeclVisitor.h"
24212795Sdim#include "clang/AST/Expr.h"
25249423Sdim#include "clang/Sema/IdentifierResolver.h"
26249423Sdim#include "clang/Sema/Sema.h"
27249423Sdim#include "clang/Sema/SemaDiagnostic.h"
28239462Sdim#include "llvm/Support/SaveAndRestore.h"
29212795Sdimusing namespace clang;
30212795Sdimusing namespace clang::serialization;
31212795Sdim
32212795Sdim//===----------------------------------------------------------------------===//
33212795Sdim// Declaration deserialization
34212795Sdim//===----------------------------------------------------------------------===//
35212795Sdim
36212795Sdimnamespace clang {
37212795Sdim  class ASTDeclReader : public DeclVisitor<ASTDeclReader, void> {
38212795Sdim    ASTReader &Reader;
39234353Sdim    ModuleFile &F;
40212795Sdim    const DeclID ThisDeclID;
41234353Sdim    const unsigned RawLocation;
42218893Sdim    typedef ASTReader::RecordData RecordData;
43218893Sdim    const RecordData &Record;
44212795Sdim    unsigned &Idx;
45212795Sdim    TypeID TypeIDForTypeDecl;
46221345Sdim
47243830Sdim    bool HasPendingBody;
48243830Sdim
49212795Sdim    uint64_t GetCurrentCursorOffset();
50226633Sdim
51218893Sdim    SourceLocation ReadSourceLocation(const RecordData &R, unsigned &I) {
52218893Sdim      return Reader.ReadSourceLocation(F, R, I);
53218893Sdim    }
54226633Sdim
55218893Sdim    SourceRange ReadSourceRange(const RecordData &R, unsigned &I) {
56218893Sdim      return Reader.ReadSourceRange(F, R, I);
57218893Sdim    }
58226633Sdim
59218893Sdim    TypeSourceInfo *GetTypeSourceInfo(const RecordData &R, unsigned &I) {
60218893Sdim      return Reader.GetTypeSourceInfo(F, R, I);
61218893Sdim    }
62226633Sdim
63226633Sdim    serialization::DeclID ReadDeclID(const RecordData &R, unsigned &I) {
64226633Sdim      return Reader.ReadDeclID(F, R, I);
65226633Sdim    }
66226633Sdim
67226633Sdim    Decl *ReadDecl(const RecordData &R, unsigned &I) {
68226633Sdim      return Reader.ReadDecl(F, R, I);
69226633Sdim    }
70226633Sdim
71226633Sdim    template<typename T>
72226633Sdim    T *ReadDeclAs(const RecordData &R, unsigned &I) {
73226633Sdim      return Reader.ReadDeclAs<T>(F, R, I);
74226633Sdim    }
75226633Sdim
76218893Sdim    void ReadQualifierInfo(QualifierInfo &Info,
77218893Sdim                           const RecordData &R, unsigned &I) {
78218893Sdim      Reader.ReadQualifierInfo(F, Info, R, I);
79218893Sdim    }
80226633Sdim
81218893Sdim    void ReadDeclarationNameLoc(DeclarationNameLoc &DNLoc, DeclarationName Name,
82218893Sdim                                const RecordData &R, unsigned &I) {
83218893Sdim      Reader.ReadDeclarationNameLoc(F, DNLoc, Name, R, I);
84218893Sdim    }
85226633Sdim
86218893Sdim    void ReadDeclarationNameInfo(DeclarationNameInfo &NameInfo,
87218893Sdim                                const RecordData &R, unsigned &I) {
88218893Sdim      Reader.ReadDeclarationNameInfo(F, NameInfo, R, I);
89218893Sdim    }
90212795Sdim
91234353Sdim    serialization::SubmoduleID readSubmoduleID(const RecordData &R,
92234353Sdim                                               unsigned &I) {
93234353Sdim      if (I >= R.size())
94234353Sdim        return 0;
95234353Sdim
96234353Sdim      return Reader.getGlobalSubmoduleID(F, R[I++]);
97234353Sdim    }
98234353Sdim
99234353Sdim    Module *readModule(const RecordData &R, unsigned &I) {
100234353Sdim      return Reader.getSubmodule(readSubmoduleID(R, I));
101234353Sdim    }
102234353Sdim
103218893Sdim    void ReadCXXDefinitionData(struct CXXRecordDecl::DefinitionData &Data,
104218893Sdim                               const RecordData &R, unsigned &I);
105218893Sdim
106234353Sdim    /// \brief RAII class used to capture the first ID within a redeclaration
107234353Sdim    /// chain and to introduce it into the list of pending redeclaration chains
108234353Sdim    /// on destruction.
109234353Sdim    ///
110234353Sdim    /// The caller can choose not to introduce this ID into the redeclaration
111234353Sdim    /// chain by calling \c suppress().
112234353Sdim    class RedeclarableResult {
113234353Sdim      ASTReader &Reader;
114234353Sdim      GlobalDeclID FirstID;
115234353Sdim      mutable bool Owning;
116249423Sdim      Decl::Kind DeclKind;
117234353Sdim
118243830Sdim      void operator=(RedeclarableResult &) LLVM_DELETED_FUNCTION;
119234353Sdim
120234353Sdim    public:
121249423Sdim      RedeclarableResult(ASTReader &Reader, GlobalDeclID FirstID,
122249423Sdim                         Decl::Kind DeclKind)
123249423Sdim        : Reader(Reader), FirstID(FirstID), Owning(true), DeclKind(DeclKind) { }
124234353Sdim
125234353Sdim      RedeclarableResult(const RedeclarableResult &Other)
126249423Sdim        : Reader(Other.Reader), FirstID(Other.FirstID), Owning(Other.Owning) ,
127249423Sdim          DeclKind(Other.DeclKind)
128234353Sdim      {
129234353Sdim        Other.Owning = false;
130234353Sdim      }
131234353Sdim
132234353Sdim      ~RedeclarableResult() {
133249423Sdim        if (FirstID && Owning && isRedeclarableDeclKind(DeclKind) &&
134249423Sdim            Reader.PendingDeclChainsKnown.insert(FirstID))
135234353Sdim          Reader.PendingDeclChains.push_back(FirstID);
136234353Sdim      }
137234353Sdim
138234353Sdim      /// \brief Retrieve the first ID.
139234353Sdim      GlobalDeclID getFirstID() const { return FirstID; }
140234353Sdim
141234353Sdim      /// \brief Do not introduce this declaration ID into the set of pending
142234353Sdim      /// declaration chains.
143234353Sdim      void suppress() {
144234353Sdim        Owning = false;
145234353Sdim      }
146234353Sdim    };
147249423Sdim
148234353Sdim    /// \brief Class used to capture the result of searching for an existing
149234353Sdim    /// declaration of a specific kind and name, along with the ability
150234353Sdim    /// to update the place where this result was found (the declaration
151234353Sdim    /// chain hanging off an identifier or the DeclContext we searched in)
152234353Sdim    /// if requested.
153234353Sdim    class FindExistingResult {
154234353Sdim      ASTReader &Reader;
155234353Sdim      NamedDecl *New;
156234353Sdim      NamedDecl *Existing;
157234353Sdim      mutable bool AddResult;
158234353Sdim
159243830Sdim      void operator=(FindExistingResult&) LLVM_DELETED_FUNCTION;
160234353Sdim
161234353Sdim    public:
162234353Sdim      FindExistingResult(ASTReader &Reader)
163234353Sdim        : Reader(Reader), New(0), Existing(0), AddResult(false) { }
164234353Sdim
165234353Sdim      FindExistingResult(ASTReader &Reader, NamedDecl *New, NamedDecl *Existing)
166234353Sdim        : Reader(Reader), New(New), Existing(Existing), AddResult(true) { }
167234353Sdim
168234353Sdim      FindExistingResult(const FindExistingResult &Other)
169234353Sdim        : Reader(Other.Reader), New(Other.New), Existing(Other.Existing),
170234353Sdim          AddResult(Other.AddResult)
171234353Sdim      {
172234353Sdim        Other.AddResult = false;
173234353Sdim      }
174234353Sdim
175234353Sdim      ~FindExistingResult();
176234353Sdim
177234353Sdim      /// \brief Suppress the addition of this result into the known set of
178234353Sdim      /// names.
179234353Sdim      void suppress() { AddResult = false; }
180234353Sdim
181234353Sdim      operator NamedDecl*() const { return Existing; }
182234353Sdim
183234353Sdim      template<typename T>
184234353Sdim      operator T*() const { return dyn_cast_or_null<T>(Existing); }
185234353Sdim    };
186234353Sdim
187234353Sdim    FindExistingResult findExisting(NamedDecl *D);
188234353Sdim
189212795Sdim  public:
190234353Sdim    ASTDeclReader(ASTReader &Reader, ModuleFile &F,
191243830Sdim                  DeclID thisDeclID,
192234353Sdim                  unsigned RawLocation,
193218893Sdim                  const RecordData &Record, unsigned &Idx)
194243830Sdim      : Reader(Reader), F(F), ThisDeclID(thisDeclID),
195234353Sdim        RawLocation(RawLocation), Record(Record), Idx(Idx),
196243830Sdim        TypeIDForTypeDecl(0), HasPendingBody(false) { }
197212795Sdim
198218893Sdim    static void attachPreviousDecl(Decl *D, Decl *previous);
199234353Sdim    static void attachLatestDecl(Decl *D, Decl *latest);
200218893Sdim
201243830Sdim    /// \brief Determine whether this declaration has a pending body.
202243830Sdim    bool hasPendingBody() const { return HasPendingBody; }
203243830Sdim
204212795Sdim    void Visit(Decl *D);
205212795Sdim
206234353Sdim    void UpdateDecl(Decl *D, ModuleFile &ModuleFile,
207221345Sdim                    const RecordData &Record);
208218893Sdim
209226633Sdim    static void setNextObjCCategory(ObjCCategoryDecl *Cat,
210226633Sdim                                    ObjCCategoryDecl *Next) {
211226633Sdim      Cat->NextClassCategory = Next;
212226633Sdim    }
213226633Sdim
214212795Sdim    void VisitDecl(Decl *D);
215212795Sdim    void VisitTranslationUnitDecl(TranslationUnitDecl *TU);
216212795Sdim    void VisitNamedDecl(NamedDecl *ND);
217218893Sdim    void VisitLabelDecl(LabelDecl *LD);
218212795Sdim    void VisitNamespaceDecl(NamespaceDecl *D);
219212795Sdim    void VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
220212795Sdim    void VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
221212795Sdim    void VisitTypeDecl(TypeDecl *TD);
222234353Sdim    void VisitTypedefNameDecl(TypedefNameDecl *TD);
223212795Sdim    void VisitTypedefDecl(TypedefDecl *TD);
224221345Sdim    void VisitTypeAliasDecl(TypeAliasDecl *TD);
225212795Sdim    void VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
226263508Sdim    RedeclarableResult VisitTagDecl(TagDecl *TD);
227212795Sdim    void VisitEnumDecl(EnumDecl *ED);
228263508Sdim    RedeclarableResult VisitRecordDeclImpl(RecordDecl *RD);
229263508Sdim    void VisitRecordDecl(RecordDecl *RD) { VisitRecordDeclImpl(RD); }
230263508Sdim    RedeclarableResult VisitCXXRecordDeclImpl(CXXRecordDecl *D);
231263508Sdim    void VisitCXXRecordDecl(CXXRecordDecl *D) { VisitCXXRecordDeclImpl(D); }
232263508Sdim    RedeclarableResult VisitClassTemplateSpecializationDeclImpl(
233263508Sdim                                            ClassTemplateSpecializationDecl *D);
234212795Sdim    void VisitClassTemplateSpecializationDecl(
235263508Sdim        ClassTemplateSpecializationDecl *D) {
236263508Sdim      VisitClassTemplateSpecializationDeclImpl(D);
237263508Sdim    }
238212795Sdim    void VisitClassTemplatePartialSpecializationDecl(
239212795Sdim                                     ClassTemplatePartialSpecializationDecl *D);
240226633Sdim    void VisitClassScopeFunctionSpecializationDecl(
241226633Sdim                                       ClassScopeFunctionSpecializationDecl *D);
242263508Sdim    RedeclarableResult
243263508Sdim    VisitVarTemplateSpecializationDeclImpl(VarTemplateSpecializationDecl *D);
244263508Sdim    void VisitVarTemplateSpecializationDecl(VarTemplateSpecializationDecl *D) {
245263508Sdim      VisitVarTemplateSpecializationDeclImpl(D);
246263508Sdim    }
247263508Sdim    void VisitVarTemplatePartialSpecializationDecl(
248263508Sdim        VarTemplatePartialSpecializationDecl *D);
249212795Sdim    void VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
250212795Sdim    void VisitValueDecl(ValueDecl *VD);
251212795Sdim    void VisitEnumConstantDecl(EnumConstantDecl *ECD);
252212795Sdim    void VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
253212795Sdim    void VisitDeclaratorDecl(DeclaratorDecl *DD);
254212795Sdim    void VisitFunctionDecl(FunctionDecl *FD);
255212795Sdim    void VisitCXXMethodDecl(CXXMethodDecl *D);
256212795Sdim    void VisitCXXConstructorDecl(CXXConstructorDecl *D);
257212795Sdim    void VisitCXXDestructorDecl(CXXDestructorDecl *D);
258212795Sdim    void VisitCXXConversionDecl(CXXConversionDecl *D);
259212795Sdim    void VisitFieldDecl(FieldDecl *FD);
260251662Sdim    void VisitMSPropertyDecl(MSPropertyDecl *FD);
261218893Sdim    void VisitIndirectFieldDecl(IndirectFieldDecl *FD);
262263508Sdim    RedeclarableResult VisitVarDeclImpl(VarDecl *D);
263263508Sdim    void VisitVarDecl(VarDecl *VD) { VisitVarDeclImpl(VD); }
264212795Sdim    void VisitImplicitParamDecl(ImplicitParamDecl *PD);
265212795Sdim    void VisitParmVarDecl(ParmVarDecl *PD);
266212795Sdim    void VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
267212795Sdim    void VisitTemplateDecl(TemplateDecl *D);
268234353Sdim    RedeclarableResult VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D);
269212795Sdim    void VisitClassTemplateDecl(ClassTemplateDecl *D);
270263508Sdim    void VisitVarTemplateDecl(VarTemplateDecl *D);
271212795Sdim    void VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
272212795Sdim    void VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
273223017Sdim    void VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D);
274212795Sdim    void VisitUsingDecl(UsingDecl *D);
275212795Sdim    void VisitUsingShadowDecl(UsingShadowDecl *D);
276212795Sdim    void VisitLinkageSpecDecl(LinkageSpecDecl *D);
277212795Sdim    void VisitFileScopeAsmDecl(FileScopeAsmDecl *AD);
278234353Sdim    void VisitImportDecl(ImportDecl *D);
279212795Sdim    void VisitAccessSpecDecl(AccessSpecDecl *D);
280212795Sdim    void VisitFriendDecl(FriendDecl *D);
281212795Sdim    void VisitFriendTemplateDecl(FriendTemplateDecl *D);
282212795Sdim    void VisitStaticAssertDecl(StaticAssertDecl *D);
283212795Sdim    void VisitBlockDecl(BlockDecl *BD);
284251662Sdim    void VisitCapturedDecl(CapturedDecl *CD);
285249423Sdim    void VisitEmptyDecl(EmptyDecl *D);
286212795Sdim
287212795Sdim    std::pair<uint64_t, uint64_t> VisitDeclContext(DeclContext *DC);
288234353Sdim
289234353Sdim    template<typename T>
290234353Sdim    RedeclarableResult VisitRedeclarable(Redeclarable<T> *D);
291212795Sdim
292234353Sdim    template<typename T>
293234353Sdim    void mergeRedeclarable(Redeclarable<T> *D, RedeclarableResult &Redecl);
294263508Sdim
295263508Sdim    template<typename T>
296263508Sdim    void mergeRedeclarable(Redeclarable<T> *D, T *Existing,
297263508Sdim                           RedeclarableResult &Redecl);
298263508Sdim
299263508Sdim    template<typename T>
300263508Sdim    void mergeMergeable(Mergeable<T> *D);
301263508Sdim
302212795Sdim    // FIXME: Reorder according to DeclNodes.td?
303212795Sdim    void VisitObjCMethodDecl(ObjCMethodDecl *D);
304212795Sdim    void VisitObjCContainerDecl(ObjCContainerDecl *D);
305212795Sdim    void VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
306212795Sdim    void VisitObjCIvarDecl(ObjCIvarDecl *D);
307212795Sdim    void VisitObjCProtocolDecl(ObjCProtocolDecl *D);
308212795Sdim    void VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D);
309212795Sdim    void VisitObjCCategoryDecl(ObjCCategoryDecl *D);
310212795Sdim    void VisitObjCImplDecl(ObjCImplDecl *D);
311212795Sdim    void VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
312212795Sdim    void VisitObjCImplementationDecl(ObjCImplementationDecl *D);
313212795Sdim    void VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *D);
314212795Sdim    void VisitObjCPropertyDecl(ObjCPropertyDecl *D);
315212795Sdim    void VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D);
316249423Sdim    void VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D);
317212795Sdim  };
318212795Sdim}
319212795Sdim
320212795Sdimuint64_t ASTDeclReader::GetCurrentCursorOffset() {
321226633Sdim  return F.DeclsCursor.GetCurrentBitNo() + F.GlobalBitOffset;
322212795Sdim}
323212795Sdim
324212795Sdimvoid ASTDeclReader::Visit(Decl *D) {
325212795Sdim  DeclVisitor<ASTDeclReader, void>::Visit(D);
326212795Sdim
327223017Sdim  if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
328223017Sdim    if (DD->DeclInfo) {
329223017Sdim      DeclaratorDecl::ExtInfo *Info =
330223017Sdim          DD->DeclInfo.get<DeclaratorDecl::ExtInfo *>();
331223017Sdim      Info->TInfo =
332223017Sdim          GetTypeSourceInfo(Record, Idx);
333223017Sdim    }
334223017Sdim    else {
335223017Sdim      DD->DeclInfo = GetTypeSourceInfo(Record, Idx);
336223017Sdim    }
337223017Sdim  }
338223017Sdim
339212795Sdim  if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
340212795Sdim    // if we have a fully initialized TypeDecl, we can safely read its type now.
341218893Sdim    TD->setTypeForDecl(Reader.GetType(TypeIDForTypeDecl).getTypePtrOrNull());
342234353Sdim  } else if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
343234353Sdim    // if we have a fully initialized TypeDecl, we can safely read its type now.
344234353Sdim    ID->TypeForDecl = Reader.GetType(TypeIDForTypeDecl).getTypePtrOrNull();
345212795Sdim  } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
346212795Sdim    // FunctionDecl's body was written last after all other Stmts/Exprs.
347243830Sdim    // We only read it if FD doesn't already have a body (e.g., from another
348243830Sdim    // module).
349243830Sdim    // FIXME: Also consider = default and = delete.
350243830Sdim    // FIXME: Can we diagnose ODR violations somehow?
351243830Sdim    if (Record[Idx++]) {
352243830Sdim      Reader.PendingBodies[FD] = GetCurrentCursorOffset();
353243830Sdim      HasPendingBody = true;
354243830Sdim    }
355212795Sdim  }
356212795Sdim}
357212795Sdim
358212795Sdimvoid ASTDeclReader::VisitDecl(Decl *D) {
359221345Sdim  if (D->isTemplateParameter()) {
360221345Sdim    // We don't want to deserialize the DeclContext of a template
361221345Sdim    // parameter immediately, because the template parameter might be
362221345Sdim    // used in the formulation of its DeclContext. Use the translation
363221345Sdim    // unit DeclContext as a placeholder.
364249423Sdim    GlobalDeclID SemaDCIDForTemplateParmDecl = ReadDeclID(Record, Idx);
365249423Sdim    GlobalDeclID LexicalDCIDForTemplateParmDecl = ReadDeclID(Record, Idx);
366249423Sdim    Reader.addPendingDeclContextInfo(D,
367249423Sdim                                     SemaDCIDForTemplateParmDecl,
368249423Sdim                                     LexicalDCIDForTemplateParmDecl);
369226633Sdim    D->setDeclContext(Reader.getContext().getTranslationUnitDecl());
370221345Sdim  } else {
371234353Sdim    DeclContext *SemaDC = ReadDeclAs<DeclContext>(Record, Idx);
372234353Sdim    DeclContext *LexicalDC = ReadDeclAs<DeclContext>(Record, Idx);
373263508Sdim    DeclContext *MergedSemaDC = Reader.MergedDeclContexts.lookup(SemaDC);
374234353Sdim    // Avoid calling setLexicalDeclContext() directly because it uses
375234353Sdim    // Decl::getASTContext() internally which is unsafe during derialization.
376263508Sdim    D->setDeclContextsImpl(MergedSemaDC ? MergedSemaDC : SemaDC, LexicalDC,
377263508Sdim                           Reader.getContext());
378221345Sdim  }
379234353Sdim  D->setLocation(Reader.ReadSourceLocation(F, RawLocation));
380212795Sdim  D->setInvalidDecl(Record[Idx++]);
381218893Sdim  if (Record[Idx++]) { // hasAttrs
382212795Sdim    AttrVec Attrs;
383218893Sdim    Reader.ReadAttributes(F, Attrs, Record, Idx);
384234353Sdim    // Avoid calling setAttrs() directly because it uses Decl::getASTContext()
385234353Sdim    // internally which is unsafe during derialization.
386234353Sdim    D->setAttrsImpl(Attrs, Reader.getContext());
387212795Sdim  }
388212795Sdim  D->setImplicit(Record[Idx++]);
389263508Sdim  D->Used = Record[Idx++];
390221345Sdim  D->setReferenced(Record[Idx++]);
391234353Sdim  D->setTopLevelDeclInObjCContainer(Record[Idx++]);
392212795Sdim  D->setAccess((AccessSpecifier)Record[Idx++]);
393226633Sdim  D->FromASTFile = true;
394234353Sdim  D->setModulePrivate(Record[Idx++]);
395234353Sdim  D->Hidden = D->isModulePrivate();
396234353Sdim
397234353Sdim  // Determine whether this declaration is part of a (sub)module. If so, it
398234353Sdim  // may not yet be visible.
399234353Sdim  if (unsigned SubmoduleID = readSubmoduleID(Record, Idx)) {
400234353Sdim    // Store the owning submodule ID in the declaration.
401234353Sdim    D->setOwningModuleID(SubmoduleID);
402234353Sdim
403234353Sdim    // Module-private declarations are never visible, so there is no work to do.
404234353Sdim    if (!D->isModulePrivate()) {
405234353Sdim      if (Module *Owner = Reader.getSubmodule(SubmoduleID)) {
406234353Sdim        if (Owner->NameVisibility != Module::AllVisible) {
407234353Sdim          // The owning module is not visible. Mark this declaration as hidden.
408234353Sdim          D->Hidden = true;
409234353Sdim
410234353Sdim          // Note that this declaration was hidden because its owning module is
411234353Sdim          // not yet visible.
412234353Sdim          Reader.HiddenNamesMap[Owner].push_back(D);
413234353Sdim        }
414234353Sdim      }
415234353Sdim    }
416234353Sdim  }
417212795Sdim}
418212795Sdim
419212795Sdimvoid ASTDeclReader::VisitTranslationUnitDecl(TranslationUnitDecl *TU) {
420226633Sdim  llvm_unreachable("Translation units are not serialized");
421212795Sdim}
422212795Sdim
423212795Sdimvoid ASTDeclReader::VisitNamedDecl(NamedDecl *ND) {
424212795Sdim  VisitDecl(ND);
425226633Sdim  ND->setDeclName(Reader.ReadDeclarationName(F, Record, Idx));
426212795Sdim}
427212795Sdim
428212795Sdimvoid ASTDeclReader::VisitTypeDecl(TypeDecl *TD) {
429212795Sdim  VisitNamedDecl(TD);
430221345Sdim  TD->setLocStart(ReadSourceLocation(Record, Idx));
431212795Sdim  // Delay type reading until after we have fully initialized the decl.
432226633Sdim  TypeIDForTypeDecl = Reader.getGlobalTypeID(F, Record[Idx++]);
433212795Sdim}
434212795Sdim
435234353Sdimvoid ASTDeclReader::VisitTypedefNameDecl(TypedefNameDecl *TD) {
436234353Sdim  RedeclarableResult Redecl = VisitRedeclarable(TD);
437212795Sdim  VisitTypeDecl(TD);
438263508Sdim  TypeSourceInfo *TInfo = GetTypeSourceInfo(Record, Idx);
439263508Sdim  if (Record[Idx++]) { // isModed
440263508Sdim    QualType modedT = Reader.readType(F, Record, Idx);
441263508Sdim    TD->setModedTypeSourceInfo(TInfo, modedT);
442263508Sdim  } else
443263508Sdim    TD->setTypeSourceInfo(TInfo);
444234353Sdim  mergeRedeclarable(TD, Redecl);
445212795Sdim}
446212795Sdim
447234353Sdimvoid ASTDeclReader::VisitTypedefDecl(TypedefDecl *TD) {
448234353Sdim  VisitTypedefNameDecl(TD);
449234353Sdim}
450234353Sdim
451221345Sdimvoid ASTDeclReader::VisitTypeAliasDecl(TypeAliasDecl *TD) {
452234353Sdim  VisitTypedefNameDecl(TD);
453221345Sdim}
454221345Sdim
455263508SdimASTDeclReader::RedeclarableResult ASTDeclReader::VisitTagDecl(TagDecl *TD) {
456234353Sdim  RedeclarableResult Redecl = VisitRedeclarable(TD);
457212795Sdim  VisitTypeDecl(TD);
458234353Sdim
459212795Sdim  TD->IdentifierNamespace = Record[Idx++];
460212795Sdim  TD->setTagKind((TagDecl::TagKind)Record[Idx++]);
461226633Sdim  TD->setCompleteDefinition(Record[Idx++]);
462212795Sdim  TD->setEmbeddedInDeclarator(Record[Idx++]);
463226633Sdim  TD->setFreeStanding(Record[Idx++]);
464263508Sdim  TD->setCompleteDefinitionRequired(Record[Idx++]);
465218893Sdim  TD->setRBraceLoc(ReadSourceLocation(Record, Idx));
466234353Sdim
467218893Sdim  if (Record[Idx++]) { // hasExtInfo
468226633Sdim    TagDecl::ExtInfo *Info = new (Reader.getContext()) TagDecl::ExtInfo();
469218893Sdim    ReadQualifierInfo(*Info, Record, Idx);
470263508Sdim    TD->NamedDeclOrQualifier = Info;
471218893Sdim  } else
472263508Sdim    TD->NamedDeclOrQualifier = ReadDeclAs<NamedDecl>(Record, Idx);
473234353Sdim
474263508Sdim  mergeRedeclarable(TD, Redecl);
475263508Sdim  return Redecl;
476212795Sdim}
477212795Sdim
478212795Sdimvoid ASTDeclReader::VisitEnumDecl(EnumDecl *ED) {
479212795Sdim  VisitTagDecl(ED);
480218893Sdim  if (TypeSourceInfo *TI = Reader.GetTypeSourceInfo(F, Record, Idx))
481218893Sdim    ED->setIntegerTypeSourceInfo(TI);
482218893Sdim  else
483226633Sdim    ED->setIntegerType(Reader.readType(F, Record, Idx));
484226633Sdim  ED->setPromotionType(Reader.readType(F, Record, Idx));
485212795Sdim  ED->setNumPositiveBits(Record[Idx++]);
486212795Sdim  ED->setNumNegativeBits(Record[Idx++]);
487218893Sdim  ED->IsScoped = Record[Idx++];
488218893Sdim  ED->IsScopedUsingClassTag = Record[Idx++];
489218893Sdim  ED->IsFixed = Record[Idx++];
490234353Sdim
491263508Sdim  // If this is a definition subject to the ODR, and we already have a
492263508Sdim  // definition, merge this one into it.
493263508Sdim  if (ED->IsCompleteDefinition &&
494263508Sdim      Reader.getContext().getLangOpts().Modules &&
495263508Sdim      Reader.getContext().getLangOpts().CPlusPlus) {
496263508Sdim    if (EnumDecl *&OldDef = Reader.EnumDefinitions[ED->getCanonicalDecl()]) {
497263508Sdim      Reader.MergedDeclContexts.insert(std::make_pair(ED, OldDef));
498263508Sdim      ED->IsCompleteDefinition = false;
499263508Sdim    } else {
500263508Sdim      OldDef = ED;
501263508Sdim    }
502263508Sdim  }
503263508Sdim
504234353Sdim  if (EnumDecl *InstED = ReadDeclAs<EnumDecl>(Record, Idx)) {
505234353Sdim    TemplateSpecializationKind TSK = (TemplateSpecializationKind)Record[Idx++];
506234353Sdim    SourceLocation POI = ReadSourceLocation(Record, Idx);
507234353Sdim    ED->setInstantiationOfMemberEnum(Reader.getContext(), InstED, TSK);
508234353Sdim    ED->getMemberSpecializationInfo()->setPointOfInstantiation(POI);
509234353Sdim  }
510212795Sdim}
511212795Sdim
512263508SdimASTDeclReader::RedeclarableResult
513263508SdimASTDeclReader::VisitRecordDeclImpl(RecordDecl *RD) {
514263508Sdim  RedeclarableResult Redecl = VisitTagDecl(RD);
515212795Sdim  RD->setHasFlexibleArrayMember(Record[Idx++]);
516212795Sdim  RD->setAnonymousStructOrUnion(Record[Idx++]);
517212795Sdim  RD->setHasObjectMember(Record[Idx++]);
518249423Sdim  RD->setHasVolatileMember(Record[Idx++]);
519263508Sdim  return Redecl;
520212795Sdim}
521212795Sdim
522212795Sdimvoid ASTDeclReader::VisitValueDecl(ValueDecl *VD) {
523212795Sdim  VisitNamedDecl(VD);
524226633Sdim  VD->setType(Reader.readType(F, Record, Idx));
525212795Sdim}
526212795Sdim
527212795Sdimvoid ASTDeclReader::VisitEnumConstantDecl(EnumConstantDecl *ECD) {
528212795Sdim  VisitValueDecl(ECD);
529212795Sdim  if (Record[Idx++])
530218893Sdim    ECD->setInitExpr(Reader.ReadExpr(F));
531212795Sdim  ECD->setInitVal(Reader.ReadAPSInt(Record, Idx));
532263508Sdim  mergeMergeable(ECD);
533212795Sdim}
534212795Sdim
535212795Sdimvoid ASTDeclReader::VisitDeclaratorDecl(DeclaratorDecl *DD) {
536212795Sdim  VisitValueDecl(DD);
537221345Sdim  DD->setInnerLocStart(ReadSourceLocation(Record, Idx));
538218893Sdim  if (Record[Idx++]) { // hasExtInfo
539218893Sdim    DeclaratorDecl::ExtInfo *Info
540226633Sdim        = new (Reader.getContext()) DeclaratorDecl::ExtInfo();
541218893Sdim    ReadQualifierInfo(*Info, Record, Idx);
542218893Sdim    DD->DeclInfo = Info;
543223017Sdim  }
544212795Sdim}
545212795Sdim
546212795Sdimvoid ASTDeclReader::VisitFunctionDecl(FunctionDecl *FD) {
547234353Sdim  RedeclarableResult Redecl = VisitRedeclarable(FD);
548212795Sdim  VisitDeclaratorDecl(FD);
549212795Sdim
550218893Sdim  ReadDeclarationNameLoc(FD->DNLoc, FD->getDeclName(), Record, Idx);
551212795Sdim  FD->IdentifierNamespace = Record[Idx++];
552234353Sdim
553234353Sdim  // FunctionDecl's body is handled last at ASTDeclReader::Visit,
554234353Sdim  // after everything else is read.
555249423Sdim
556234353Sdim  FD->SClass = (StorageClass)Record[Idx++];
557234353Sdim  FD->IsInline = Record[Idx++];
558234353Sdim  FD->IsInlineSpecified = Record[Idx++];
559234353Sdim  FD->IsVirtualAsWritten = Record[Idx++];
560234353Sdim  FD->IsPure = Record[Idx++];
561234353Sdim  FD->HasInheritedPrototype = Record[Idx++];
562234353Sdim  FD->HasWrittenPrototype = Record[Idx++];
563234353Sdim  FD->IsDeleted = Record[Idx++];
564234353Sdim  FD->IsTrivial = Record[Idx++];
565234353Sdim  FD->IsDefaulted = Record[Idx++];
566234353Sdim  FD->IsExplicitlyDefaulted = Record[Idx++];
567234353Sdim  FD->HasImplicitReturnZero = Record[Idx++];
568234353Sdim  FD->IsConstexpr = Record[Idx++];
569249423Sdim  FD->HasSkippedBody = Record[Idx++];
570263508Sdim  FD->IsLateTemplateParsed = Record[Idx++];
571263508Sdim  FD->setCachedLinkage(Linkage(Record[Idx++]));
572234353Sdim  FD->EndRangeLoc = ReadSourceLocation(Record, Idx);
573234353Sdim
574212795Sdim  switch ((FunctionDecl::TemplatedKind)Record[Idx++]) {
575212795Sdim  case FunctionDecl::TK_NonTemplate:
576234353Sdim    mergeRedeclarable(FD, Redecl);
577212795Sdim    break;
578212795Sdim  case FunctionDecl::TK_FunctionTemplate:
579226633Sdim    FD->setDescribedFunctionTemplate(ReadDeclAs<FunctionTemplateDecl>(Record,
580226633Sdim                                                                      Idx));
581212795Sdim    break;
582212795Sdim  case FunctionDecl::TK_MemberSpecialization: {
583226633Sdim    FunctionDecl *InstFD = ReadDeclAs<FunctionDecl>(Record, Idx);
584212795Sdim    TemplateSpecializationKind TSK = (TemplateSpecializationKind)Record[Idx++];
585218893Sdim    SourceLocation POI = ReadSourceLocation(Record, Idx);
586226633Sdim    FD->setInstantiationOfMemberFunction(Reader.getContext(), InstFD, TSK);
587212795Sdim    FD->getMemberSpecializationInfo()->setPointOfInstantiation(POI);
588212795Sdim    break;
589212795Sdim  }
590212795Sdim  case FunctionDecl::TK_FunctionTemplateSpecialization: {
591226633Sdim    FunctionTemplateDecl *Template = ReadDeclAs<FunctionTemplateDecl>(Record,
592226633Sdim                                                                      Idx);
593212795Sdim    TemplateSpecializationKind TSK = (TemplateSpecializationKind)Record[Idx++];
594212795Sdim
595212795Sdim    // Template arguments.
596226633Sdim    SmallVector<TemplateArgument, 8> TemplArgs;
597218893Sdim    Reader.ReadTemplateArgumentList(TemplArgs, F, Record, Idx);
598212795Sdim
599212795Sdim    // Template args as written.
600226633Sdim    SmallVector<TemplateArgumentLoc, 8> TemplArgLocs;
601212795Sdim    SourceLocation LAngleLoc, RAngleLoc;
602226633Sdim    bool HasTemplateArgumentsAsWritten = Record[Idx++];
603226633Sdim    if (HasTemplateArgumentsAsWritten) {
604212795Sdim      unsigned NumTemplateArgLocs = Record[Idx++];
605212795Sdim      TemplArgLocs.reserve(NumTemplateArgLocs);
606212795Sdim      for (unsigned i=0; i != NumTemplateArgLocs; ++i)
607212795Sdim        TemplArgLocs.push_back(
608218893Sdim            Reader.ReadTemplateArgumentLoc(F, Record, Idx));
609212795Sdim
610218893Sdim      LAngleLoc = ReadSourceLocation(Record, Idx);
611218893Sdim      RAngleLoc = ReadSourceLocation(Record, Idx);
612212795Sdim    }
613212795Sdim
614218893Sdim    SourceLocation POI = ReadSourceLocation(Record, Idx);
615212795Sdim
616226633Sdim    ASTContext &C = Reader.getContext();
617218893Sdim    TemplateArgumentList *TemplArgList
618218893Sdim      = TemplateArgumentList::CreateCopy(C, TemplArgs.data(), TemplArgs.size());
619226633Sdim    TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
620218893Sdim    for (unsigned i=0, e = TemplArgLocs.size(); i != e; ++i)
621226633Sdim      TemplArgsInfo.addArgument(TemplArgLocs[i]);
622218893Sdim    FunctionTemplateSpecializationInfo *FTInfo
623218893Sdim        = FunctionTemplateSpecializationInfo::Create(C, FD, Template, TSK,
624218893Sdim                                                     TemplArgList,
625226633Sdim                             HasTemplateArgumentsAsWritten ? &TemplArgsInfo : 0,
626226633Sdim                                                     POI);
627218893Sdim    FD->TemplateOrSpecialization = FTInfo;
628218893Sdim
629218893Sdim    if (FD->isCanonicalDecl()) { // if canonical add to template's set.
630218893Sdim      // The template that contains the specializations set. It's not safe to
631218893Sdim      // use getCanonicalDecl on Template since it may still be initializing.
632218893Sdim      FunctionTemplateDecl *CanonTemplate
633226633Sdim        = ReadDeclAs<FunctionTemplateDecl>(Record, Idx);
634218893Sdim      // Get the InsertPos by FindNodeOrInsertPos() instead of calling
635218893Sdim      // InsertNode(FTInfo) directly to avoid the getASTContext() call in
636218893Sdim      // FunctionTemplateSpecializationInfo's Profile().
637218893Sdim      // We avoid getASTContext because a decl in the parent hierarchy may
638218893Sdim      // be initializing.
639218893Sdim      llvm::FoldingSetNodeID ID;
640218893Sdim      FunctionTemplateSpecializationInfo::Profile(ID, TemplArgs.data(),
641218893Sdim                                                  TemplArgs.size(), C);
642218893Sdim      void *InsertPos = 0;
643263508Sdim      FunctionTemplateDecl::Common *CommonPtr = CanonTemplate->getCommonPtr();
644263508Sdim      CommonPtr->Specializations.FindNodeOrInsertPos(ID, InsertPos);
645243830Sdim      if (InsertPos)
646263508Sdim        CommonPtr->Specializations.InsertNode(FTInfo, InsertPos);
647263508Sdim      else {
648263508Sdim        assert(Reader.getContext().getLangOpts().Modules &&
649263508Sdim               "already deserialized this template specialization");
650263508Sdim        // FIXME: This specialization is a redeclaration of one from another
651263508Sdim        // module. Merge it.
652263508Sdim      }
653218893Sdim    }
654212795Sdim    break;
655212795Sdim  }
656212795Sdim  case FunctionDecl::TK_DependentFunctionTemplateSpecialization: {
657212795Sdim    // Templates.
658212795Sdim    UnresolvedSet<8> TemplDecls;
659212795Sdim    unsigned NumTemplates = Record[Idx++];
660212795Sdim    while (NumTemplates--)
661226633Sdim      TemplDecls.addDecl(ReadDeclAs<NamedDecl>(Record, Idx));
662212795Sdim
663212795Sdim    // Templates args.
664212795Sdim    TemplateArgumentListInfo TemplArgs;
665212795Sdim    unsigned NumArgs = Record[Idx++];
666212795Sdim    while (NumArgs--)
667218893Sdim      TemplArgs.addArgument(Reader.ReadTemplateArgumentLoc(F, Record, Idx));
668218893Sdim    TemplArgs.setLAngleLoc(ReadSourceLocation(Record, Idx));
669218893Sdim    TemplArgs.setRAngleLoc(ReadSourceLocation(Record, Idx));
670212795Sdim
671226633Sdim    FD->setDependentTemplateSpecialization(Reader.getContext(),
672212795Sdim                                           TemplDecls, TemplArgs);
673212795Sdim    break;
674212795Sdim  }
675212795Sdim  }
676212795Sdim
677212795Sdim  // Read in the parameters.
678212795Sdim  unsigned NumParams = Record[Idx++];
679226633Sdim  SmallVector<ParmVarDecl *, 16> Params;
680212795Sdim  Params.reserve(NumParams);
681212795Sdim  for (unsigned I = 0; I != NumParams; ++I)
682226633Sdim    Params.push_back(ReadDeclAs<ParmVarDecl>(Record, Idx));
683226633Sdim  FD->setParams(Reader.getContext(), Params);
684212795Sdim}
685212795Sdim
686212795Sdimvoid ASTDeclReader::VisitObjCMethodDecl(ObjCMethodDecl *MD) {
687212795Sdim  VisitNamedDecl(MD);
688212795Sdim  if (Record[Idx++]) {
689243830Sdim    // Load the body on-demand. Most clients won't care, because method
690243830Sdim    // definitions rarely show up in headers.
691243830Sdim    Reader.PendingBodies[MD] = GetCurrentCursorOffset();
692243830Sdim    HasPendingBody = true;
693226633Sdim    MD->setSelfDecl(ReadDeclAs<ImplicitParamDecl>(Record, Idx));
694226633Sdim    MD->setCmdDecl(ReadDeclAs<ImplicitParamDecl>(Record, Idx));
695212795Sdim  }
696212795Sdim  MD->setInstanceMethod(Record[Idx++]);
697212795Sdim  MD->setVariadic(Record[Idx++]);
698243830Sdim  MD->setPropertyAccessor(Record[Idx++]);
699212795Sdim  MD->setDefined(Record[Idx++]);
700239462Sdim  MD->IsOverriding = Record[Idx++];
701249423Sdim  MD->HasSkippedBody = Record[Idx++];
702226633Sdim
703226633Sdim  MD->IsRedeclaration = Record[Idx++];
704226633Sdim  MD->HasRedeclaration = Record[Idx++];
705226633Sdim  if (MD->HasRedeclaration)
706226633Sdim    Reader.getContext().setObjCMethodRedeclaration(MD,
707226633Sdim                                       ReadDeclAs<ObjCMethodDecl>(Record, Idx));
708226633Sdim
709212795Sdim  MD->setDeclImplementation((ObjCMethodDecl::ImplementationControl)Record[Idx++]);
710212795Sdim  MD->setObjCDeclQualifier((Decl::ObjCDeclQualifier)Record[Idx++]);
711223017Sdim  MD->SetRelatedResultType(Record[Idx++]);
712226633Sdim  MD->setResultType(Reader.readType(F, Record, Idx));
713218893Sdim  MD->setResultTypeSourceInfo(GetTypeSourceInfo(Record, Idx));
714239462Sdim  MD->DeclEndLoc = ReadSourceLocation(Record, Idx);
715212795Sdim  unsigned NumParams = Record[Idx++];
716226633Sdim  SmallVector<ParmVarDecl *, 16> Params;
717212795Sdim  Params.reserve(NumParams);
718212795Sdim  for (unsigned I = 0; I != NumParams; ++I)
719226633Sdim    Params.push_back(ReadDeclAs<ParmVarDecl>(Record, Idx));
720226633Sdim
721226633Sdim  MD->SelLocsKind = Record[Idx++];
722226633Sdim  unsigned NumStoredSelLocs = Record[Idx++];
723226633Sdim  SmallVector<SourceLocation, 16> SelLocs;
724226633Sdim  SelLocs.reserve(NumStoredSelLocs);
725226633Sdim  for (unsigned i = 0; i != NumStoredSelLocs; ++i)
726226633Sdim    SelLocs.push_back(ReadSourceLocation(Record, Idx));
727226633Sdim
728226633Sdim  MD->setParamsAndSelLocs(Reader.getContext(), Params, SelLocs);
729212795Sdim}
730212795Sdim
731212795Sdimvoid ASTDeclReader::VisitObjCContainerDecl(ObjCContainerDecl *CD) {
732212795Sdim  VisitNamedDecl(CD);
733226633Sdim  CD->setAtStartLoc(ReadSourceLocation(Record, Idx));
734226633Sdim  CD->setAtEndRange(ReadSourceRange(Record, Idx));
735212795Sdim}
736212795Sdim
737212795Sdimvoid ASTDeclReader::VisitObjCInterfaceDecl(ObjCInterfaceDecl *ID) {
738234353Sdim  RedeclarableResult Redecl = VisitRedeclarable(ID);
739212795Sdim  VisitObjCContainerDecl(ID);
740234353Sdim  TypeIDForTypeDecl = Reader.getGlobalTypeID(F, Record[Idx++]);
741234353Sdim  mergeRedeclarable(ID, Redecl);
742212795Sdim
743234353Sdim  if (Record[Idx++]) {
744234353Sdim    // Read the definition.
745234353Sdim    ID->allocateDefinitionData();
746234353Sdim
747234353Sdim    // Set the definition data of the canonical declaration, so other
748234353Sdim    // redeclarations will see it.
749234353Sdim    ID->getCanonicalDecl()->Data = ID->Data;
750234353Sdim
751234353Sdim    ObjCInterfaceDecl::DefinitionData &Data = ID->data();
752234353Sdim
753234353Sdim    // Read the superclass.
754234353Sdim    Data.SuperClass = ReadDeclAs<ObjCInterfaceDecl>(Record, Idx);
755234353Sdim    Data.SuperClassLoc = ReadSourceLocation(Record, Idx);
756234353Sdim
757234353Sdim    Data.EndLoc = ReadSourceLocation(Record, Idx);
758234353Sdim
759234353Sdim    // Read the directly referenced protocols and their SourceLocations.
760234353Sdim    unsigned NumProtocols = Record[Idx++];
761234353Sdim    SmallVector<ObjCProtocolDecl *, 16> Protocols;
762234353Sdim    Protocols.reserve(NumProtocols);
763234353Sdim    for (unsigned I = 0; I != NumProtocols; ++I)
764234353Sdim      Protocols.push_back(ReadDeclAs<ObjCProtocolDecl>(Record, Idx));
765234353Sdim    SmallVector<SourceLocation, 16> ProtoLocs;
766234353Sdim    ProtoLocs.reserve(NumProtocols);
767234353Sdim    for (unsigned I = 0; I != NumProtocols; ++I)
768234353Sdim      ProtoLocs.push_back(ReadSourceLocation(Record, Idx));
769234353Sdim    ID->setProtocolList(Protocols.data(), NumProtocols, ProtoLocs.data(),
770234353Sdim                        Reader.getContext());
771212795Sdim
772234353Sdim    // Read the transitive closure of protocols referenced by this class.
773234353Sdim    NumProtocols = Record[Idx++];
774234353Sdim    Protocols.clear();
775234353Sdim    Protocols.reserve(NumProtocols);
776234353Sdim    for (unsigned I = 0; I != NumProtocols; ++I)
777234353Sdim      Protocols.push_back(ReadDeclAs<ObjCProtocolDecl>(Record, Idx));
778234353Sdim    ID->data().AllReferencedProtocols.set(Protocols.data(), NumProtocols,
779234353Sdim                                          Reader.getContext());
780212795Sdim
781234353Sdim    // We will rebuild this list lazily.
782234353Sdim    ID->setIvarList(0);
783234353Sdim
784234353Sdim    // Note that we have deserialized a definition.
785234353Sdim    Reader.PendingDefinitions.insert(ID);
786234353Sdim
787234353Sdim    // Note that we've loaded this Objective-C class.
788234353Sdim    Reader.ObjCClassesLoaded.push_back(ID);
789234353Sdim  } else {
790234353Sdim    ID->Data = ID->getCanonicalDecl()->Data;
791234353Sdim  }
792212795Sdim}
793212795Sdim
794212795Sdimvoid ASTDeclReader::VisitObjCIvarDecl(ObjCIvarDecl *IVD) {
795212795Sdim  VisitFieldDecl(IVD);
796212795Sdim  IVD->setAccessControl((ObjCIvarDecl::AccessControl)Record[Idx++]);
797212795Sdim  // This field will be built lazily.
798212795Sdim  IVD->setNextIvar(0);
799212795Sdim  bool synth = Record[Idx++];
800212795Sdim  IVD->setSynthesize(synth);
801263508Sdim  bool backingIvarReferencedInAccessor = Record[Idx++];
802263508Sdim  IVD->setBackingIvarReferencedInAccessor(backingIvarReferencedInAccessor);
803212795Sdim}
804212795Sdim
805212795Sdimvoid ASTDeclReader::VisitObjCProtocolDecl(ObjCProtocolDecl *PD) {
806234353Sdim  RedeclarableResult Redecl = VisitRedeclarable(PD);
807212795Sdim  VisitObjCContainerDecl(PD);
808234353Sdim  mergeRedeclarable(PD, Redecl);
809234353Sdim
810234353Sdim  if (Record[Idx++]) {
811234353Sdim    // Read the definition.
812234353Sdim    PD->allocateDefinitionData();
813234353Sdim
814234353Sdim    // Set the definition data of the canonical declaration, so other
815234353Sdim    // redeclarations will see it.
816234353Sdim    PD->getCanonicalDecl()->Data = PD->Data;
817234353Sdim
818234353Sdim    unsigned NumProtoRefs = Record[Idx++];
819234353Sdim    SmallVector<ObjCProtocolDecl *, 16> ProtoRefs;
820234353Sdim    ProtoRefs.reserve(NumProtoRefs);
821234353Sdim    for (unsigned I = 0; I != NumProtoRefs; ++I)
822234353Sdim      ProtoRefs.push_back(ReadDeclAs<ObjCProtocolDecl>(Record, Idx));
823234353Sdim    SmallVector<SourceLocation, 16> ProtoLocs;
824234353Sdim    ProtoLocs.reserve(NumProtoRefs);
825234353Sdim    for (unsigned I = 0; I != NumProtoRefs; ++I)
826234353Sdim      ProtoLocs.push_back(ReadSourceLocation(Record, Idx));
827234353Sdim    PD->setProtocolList(ProtoRefs.data(), NumProtoRefs, ProtoLocs.data(),
828234353Sdim                        Reader.getContext());
829234353Sdim
830234353Sdim    // Note that we have deserialized a definition.
831234353Sdim    Reader.PendingDefinitions.insert(PD);
832234353Sdim  } else {
833234353Sdim    PD->Data = PD->getCanonicalDecl()->Data;
834234353Sdim  }
835212795Sdim}
836212795Sdim
837212795Sdimvoid ASTDeclReader::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *FD) {
838212795Sdim  VisitFieldDecl(FD);
839212795Sdim}
840212795Sdim
841212795Sdimvoid ASTDeclReader::VisitObjCCategoryDecl(ObjCCategoryDecl *CD) {
842212795Sdim  VisitObjCContainerDecl(CD);
843234353Sdim  CD->setCategoryNameLoc(ReadSourceLocation(Record, Idx));
844234353Sdim  CD->setIvarLBraceLoc(ReadSourceLocation(Record, Idx));
845234353Sdim  CD->setIvarRBraceLoc(ReadSourceLocation(Record, Idx));
846234353Sdim
847234353Sdim  // Note that this category has been deserialized. We do this before
848234353Sdim  // deserializing the interface declaration, so that it will consider this
849234353Sdim  /// category.
850234353Sdim  Reader.CategoriesDeserialized.insert(CD);
851234353Sdim
852226633Sdim  CD->ClassInterface = ReadDeclAs<ObjCInterfaceDecl>(Record, Idx);
853212795Sdim  unsigned NumProtoRefs = Record[Idx++];
854226633Sdim  SmallVector<ObjCProtocolDecl *, 16> ProtoRefs;
855212795Sdim  ProtoRefs.reserve(NumProtoRefs);
856212795Sdim  for (unsigned I = 0; I != NumProtoRefs; ++I)
857226633Sdim    ProtoRefs.push_back(ReadDeclAs<ObjCProtocolDecl>(Record, Idx));
858226633Sdim  SmallVector<SourceLocation, 16> ProtoLocs;
859212795Sdim  ProtoLocs.reserve(NumProtoRefs);
860212795Sdim  for (unsigned I = 0; I != NumProtoRefs; ++I)
861218893Sdim    ProtoLocs.push_back(ReadSourceLocation(Record, Idx));
862212795Sdim  CD->setProtocolList(ProtoRefs.data(), NumProtoRefs, ProtoLocs.data(),
863226633Sdim                      Reader.getContext());
864212795Sdim}
865212795Sdim
866212795Sdimvoid ASTDeclReader::VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *CAD) {
867212795Sdim  VisitNamedDecl(CAD);
868226633Sdim  CAD->setClassInterface(ReadDeclAs<ObjCInterfaceDecl>(Record, Idx));
869212795Sdim}
870212795Sdim
871212795Sdimvoid ASTDeclReader::VisitObjCPropertyDecl(ObjCPropertyDecl *D) {
872212795Sdim  VisitNamedDecl(D);
873218893Sdim  D->setAtLoc(ReadSourceLocation(Record, Idx));
874234353Sdim  D->setLParenLoc(ReadSourceLocation(Record, Idx));
875218893Sdim  D->setType(GetTypeSourceInfo(Record, Idx));
876212795Sdim  // FIXME: stable encoding
877212795Sdim  D->setPropertyAttributes(
878212795Sdim                      (ObjCPropertyDecl::PropertyAttributeKind)Record[Idx++]);
879212795Sdim  D->setPropertyAttributesAsWritten(
880212795Sdim                      (ObjCPropertyDecl::PropertyAttributeKind)Record[Idx++]);
881212795Sdim  // FIXME: stable encoding
882212795Sdim  D->setPropertyImplementation(
883212795Sdim                            (ObjCPropertyDecl::PropertyControl)Record[Idx++]);
884226633Sdim  D->setGetterName(Reader.ReadDeclarationName(F,Record, Idx).getObjCSelector());
885226633Sdim  D->setSetterName(Reader.ReadDeclarationName(F,Record, Idx).getObjCSelector());
886226633Sdim  D->setGetterMethodDecl(ReadDeclAs<ObjCMethodDecl>(Record, Idx));
887226633Sdim  D->setSetterMethodDecl(ReadDeclAs<ObjCMethodDecl>(Record, Idx));
888226633Sdim  D->setPropertyIvarDecl(ReadDeclAs<ObjCIvarDecl>(Record, Idx));
889212795Sdim}
890212795Sdim
891212795Sdimvoid ASTDeclReader::VisitObjCImplDecl(ObjCImplDecl *D) {
892212795Sdim  VisitObjCContainerDecl(D);
893226633Sdim  D->setClassInterface(ReadDeclAs<ObjCInterfaceDecl>(Record, Idx));
894212795Sdim}
895212795Sdim
896212795Sdimvoid ASTDeclReader::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
897212795Sdim  VisitObjCImplDecl(D);
898226633Sdim  D->setIdentifier(Reader.GetIdentifierInfo(F, Record, Idx));
899234353Sdim  D->CategoryNameLoc = ReadSourceLocation(Record, Idx);
900212795Sdim}
901212795Sdim
902212795Sdimvoid ASTDeclReader::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
903212795Sdim  VisitObjCImplDecl(D);
904226633Sdim  D->setSuperClass(ReadDeclAs<ObjCInterfaceDecl>(Record, Idx));
905251662Sdim  D->SuperLoc = ReadSourceLocation(Record, Idx);
906234353Sdim  D->setIvarLBraceLoc(ReadSourceLocation(Record, Idx));
907234353Sdim  D->setIvarRBraceLoc(ReadSourceLocation(Record, Idx));
908243830Sdim  D->setHasNonZeroConstructors(Record[Idx++]);
909243830Sdim  D->setHasDestructors(Record[Idx++]);
910212795Sdim  llvm::tie(D->IvarInitializers, D->NumIvarInitializers)
911218893Sdim      = Reader.ReadCXXCtorInitializers(F, Record, Idx);
912212795Sdim}
913212795Sdim
914212795Sdim
915212795Sdimvoid ASTDeclReader::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) {
916212795Sdim  VisitDecl(D);
917218893Sdim  D->setAtLoc(ReadSourceLocation(Record, Idx));
918226633Sdim  D->setPropertyDecl(ReadDeclAs<ObjCPropertyDecl>(Record, Idx));
919226633Sdim  D->PropertyIvarDecl = ReadDeclAs<ObjCIvarDecl>(Record, Idx);
920218893Sdim  D->IvarLoc = ReadSourceLocation(Record, Idx);
921218893Sdim  D->setGetterCXXConstructor(Reader.ReadExpr(F));
922218893Sdim  D->setSetterCXXAssignment(Reader.ReadExpr(F));
923212795Sdim}
924212795Sdim
925212795Sdimvoid ASTDeclReader::VisitFieldDecl(FieldDecl *FD) {
926212795Sdim  VisitDeclaratorDecl(FD);
927239462Sdim  FD->Mutable = Record[Idx++];
928239462Sdim  if (int BitWidthOrInitializer = Record[Idx++]) {
929239462Sdim    FD->InitializerOrBitWidth.setInt(BitWidthOrInitializer - 1);
930239462Sdim    FD->InitializerOrBitWidth.setPointer(Reader.ReadExpr(F));
931239462Sdim  }
932212795Sdim  if (!FD->getDeclName()) {
933226633Sdim    if (FieldDecl *Tmpl = ReadDeclAs<FieldDecl>(Record, Idx))
934226633Sdim      Reader.getContext().setInstantiatedFromUnnamedFieldDecl(FD, Tmpl);
935212795Sdim  }
936263508Sdim  mergeMergeable(FD);
937212795Sdim}
938212795Sdim
939251662Sdimvoid ASTDeclReader::VisitMSPropertyDecl(MSPropertyDecl *PD) {
940251662Sdim  VisitDeclaratorDecl(PD);
941251662Sdim  PD->GetterId = Reader.GetIdentifierInfo(F, Record, Idx);
942251662Sdim  PD->SetterId = Reader.GetIdentifierInfo(F, Record, Idx);
943251662Sdim}
944251662Sdim
945218893Sdimvoid ASTDeclReader::VisitIndirectFieldDecl(IndirectFieldDecl *FD) {
946218893Sdim  VisitValueDecl(FD);
947218893Sdim
948218893Sdim  FD->ChainingSize = Record[Idx++];
949218893Sdim  assert(FD->ChainingSize >= 2 && "Anonymous chaining must be >= 2");
950226633Sdim  FD->Chaining = new (Reader.getContext())NamedDecl*[FD->ChainingSize];
951218893Sdim
952218893Sdim  for (unsigned I = 0; I != FD->ChainingSize; ++I)
953226633Sdim    FD->Chaining[I] = ReadDeclAs<NamedDecl>(Record, Idx);
954218893Sdim}
955218893Sdim
956263508SdimASTDeclReader::RedeclarableResult ASTDeclReader::VisitVarDeclImpl(VarDecl *VD) {
957234353Sdim  RedeclarableResult Redecl = VisitRedeclarable(VD);
958212795Sdim  VisitDeclaratorDecl(VD);
959249423Sdim
960221345Sdim  VD->VarDeclBits.SClass = (StorageClass)Record[Idx++];
961251662Sdim  VD->VarDeclBits.TSCSpec = Record[Idx++];
962234353Sdim  VD->VarDeclBits.InitStyle = Record[Idx++];
963221345Sdim  VD->VarDeclBits.ExceptionVar = Record[Idx++];
964221345Sdim  VD->VarDeclBits.NRVOVariable = Record[Idx++];
965221345Sdim  VD->VarDeclBits.CXXForRangeDecl = Record[Idx++];
966224145Sdim  VD->VarDeclBits.ARCPseudoStrong = Record[Idx++];
967243830Sdim  VD->VarDeclBits.IsConstexpr = Record[Idx++];
968263508Sdim  VD->VarDeclBits.IsInitCapture = Record[Idx++];
969263508Sdim  VD->VarDeclBits.PreviousDeclInSameBlockScope = Record[Idx++];
970263508Sdim  Linkage VarLinkage = Linkage(Record[Idx++]);
971263508Sdim  VD->setCachedLinkage(VarLinkage);
972263508Sdim
973263508Sdim  // Reconstruct the one piece of the IdentifierNamespace that we need.
974278788Sdim  if (VD->getStorageClass() == SC_Extern && VarLinkage != NoLinkage &&
975263508Sdim      VD->getLexicalDeclContext()->isFunctionOrMethod())
976263508Sdim    VD->setLocalExternDecl();
977263508Sdim
978234353Sdim  // Only true variables (not parameters or implicit parameters) can be merged.
979263508Sdim  if (VD->getKind() != Decl::ParmVar && VD->getKind() != Decl::ImplicitParam)
980234353Sdim    mergeRedeclarable(VD, Redecl);
981234353Sdim
982234353Sdim  if (uint64_t Val = Record[Idx++]) {
983218893Sdim    VD->setInit(Reader.ReadExpr(F));
984234353Sdim    if (Val > 1) {
985234353Sdim      EvaluatedStmt *Eval = VD->ensureEvaluatedStmt();
986234353Sdim      Eval->CheckedICE = true;
987234353Sdim      Eval->IsICE = Val == 3;
988234353Sdim    }
989234353Sdim  }
990212795Sdim
991263508Sdim  enum VarKind {
992263508Sdim    VarNotTemplate = 0, VarTemplate, StaticDataMemberSpecialization
993263508Sdim  };
994263508Sdim  switch ((VarKind)Record[Idx++]) {
995263508Sdim  case VarNotTemplate:
996263508Sdim    break;
997263508Sdim  case VarTemplate:
998263508Sdim    VD->setDescribedVarTemplate(ReadDeclAs<VarTemplateDecl>(Record, Idx));
999263508Sdim    break;
1000263508Sdim  case StaticDataMemberSpecialization: { // HasMemberSpecializationInfo.
1001226633Sdim    VarDecl *Tmpl = ReadDeclAs<VarDecl>(Record, Idx);
1002212795Sdim    TemplateSpecializationKind TSK = (TemplateSpecializationKind)Record[Idx++];
1003218893Sdim    SourceLocation POI = ReadSourceLocation(Record, Idx);
1004226633Sdim    Reader.getContext().setInstantiatedFromStaticDataMember(VD, Tmpl, TSK,POI);
1005263508Sdim    break;
1006212795Sdim  }
1007263508Sdim  }
1008263508Sdim
1009263508Sdim  return Redecl;
1010212795Sdim}
1011212795Sdim
1012212795Sdimvoid ASTDeclReader::VisitImplicitParamDecl(ImplicitParamDecl *PD) {
1013212795Sdim  VisitVarDecl(PD);
1014212795Sdim}
1015212795Sdim
1016212795Sdimvoid ASTDeclReader::VisitParmVarDecl(ParmVarDecl *PD) {
1017212795Sdim  VisitVarDecl(PD);
1018221345Sdim  unsigned isObjCMethodParam = Record[Idx++];
1019221345Sdim  unsigned scopeDepth = Record[Idx++];
1020221345Sdim  unsigned scopeIndex = Record[Idx++];
1021221345Sdim  unsigned declQualifier = Record[Idx++];
1022221345Sdim  if (isObjCMethodParam) {
1023221345Sdim    assert(scopeDepth == 0);
1024221345Sdim    PD->setObjCMethodScopeInfo(scopeIndex);
1025221345Sdim    PD->ParmVarDeclBits.ScopeDepthOrObjCQuals = declQualifier;
1026221345Sdim  } else {
1027221345Sdim    PD->setScopeInfo(scopeDepth, scopeIndex);
1028221345Sdim  }
1029221345Sdim  PD->ParmVarDeclBits.IsKNRPromoted = Record[Idx++];
1030221345Sdim  PD->ParmVarDeclBits.HasInheritedDefaultArg = Record[Idx++];
1031212795Sdim  if (Record[Idx++]) // hasUninstantiatedDefaultArg.
1032218893Sdim    PD->setUninstantiatedDefaultArg(Reader.ReadExpr(F));
1033263508Sdim
1034263508Sdim  // FIXME: If this is a redeclaration of a function from another module, handle
1035263508Sdim  // inheritance of default arguments.
1036212795Sdim}
1037212795Sdim
1038212795Sdimvoid ASTDeclReader::VisitFileScopeAsmDecl(FileScopeAsmDecl *AD) {
1039212795Sdim  VisitDecl(AD);
1040218893Sdim  AD->setAsmString(cast<StringLiteral>(Reader.ReadExpr(F)));
1041221345Sdim  AD->setRParenLoc(ReadSourceLocation(Record, Idx));
1042212795Sdim}
1043212795Sdim
1044212795Sdimvoid ASTDeclReader::VisitBlockDecl(BlockDecl *BD) {
1045212795Sdim  VisitDecl(BD);
1046218893Sdim  BD->setBody(cast_or_null<CompoundStmt>(Reader.ReadStmt(F)));
1047218893Sdim  BD->setSignatureAsWritten(GetTypeSourceInfo(Record, Idx));
1048212795Sdim  unsigned NumParams = Record[Idx++];
1049226633Sdim  SmallVector<ParmVarDecl *, 16> Params;
1050212795Sdim  Params.reserve(NumParams);
1051212795Sdim  for (unsigned I = 0; I != NumParams; ++I)
1052226633Sdim    Params.push_back(ReadDeclAs<ParmVarDecl>(Record, Idx));
1053226633Sdim  BD->setParams(Params);
1054218893Sdim
1055234982Sdim  BD->setIsVariadic(Record[Idx++]);
1056234982Sdim  BD->setBlockMissingReturnType(Record[Idx++]);
1057234982Sdim  BD->setIsConversionFromLambda(Record[Idx++]);
1058234982Sdim
1059218893Sdim  bool capturesCXXThis = Record[Idx++];
1060218893Sdim  unsigned numCaptures = Record[Idx++];
1061226633Sdim  SmallVector<BlockDecl::Capture, 16> captures;
1062218893Sdim  captures.reserve(numCaptures);
1063218893Sdim  for (unsigned i = 0; i != numCaptures; ++i) {
1064226633Sdim    VarDecl *decl = ReadDeclAs<VarDecl>(Record, Idx);
1065218893Sdim    unsigned flags = Record[Idx++];
1066218893Sdim    bool byRef = (flags & 1);
1067218893Sdim    bool nested = (flags & 2);
1068218893Sdim    Expr *copyExpr = ((flags & 4) ? Reader.ReadExpr(F) : 0);
1069218893Sdim
1070218893Sdim    captures.push_back(BlockDecl::Capture(decl, byRef, nested, copyExpr));
1071218893Sdim  }
1072226633Sdim  BD->setCaptures(Reader.getContext(), captures.begin(),
1073218893Sdim                  captures.end(), capturesCXXThis);
1074212795Sdim}
1075212795Sdim
1076251662Sdimvoid ASTDeclReader::VisitCapturedDecl(CapturedDecl *CD) {
1077251662Sdim  VisitDecl(CD);
1078251662Sdim  // Body is set by VisitCapturedStmt.
1079251662Sdim  for (unsigned i = 0; i < CD->NumParams; ++i)
1080251662Sdim    CD->setParam(i, ReadDeclAs<ImplicitParamDecl>(Record, Idx));
1081251662Sdim}
1082251662Sdim
1083212795Sdimvoid ASTDeclReader::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1084212795Sdim  VisitDecl(D);
1085212795Sdim  D->setLanguage((LinkageSpecDecl::LanguageIDs)Record[Idx++]);
1086221345Sdim  D->setExternLoc(ReadSourceLocation(Record, Idx));
1087221345Sdim  D->setRBraceLoc(ReadSourceLocation(Record, Idx));
1088212795Sdim}
1089212795Sdim
1090218893Sdimvoid ASTDeclReader::VisitLabelDecl(LabelDecl *D) {
1091218893Sdim  VisitNamedDecl(D);
1092221345Sdim  D->setLocStart(ReadSourceLocation(Record, Idx));
1093218893Sdim}
1094218893Sdim
1095218893Sdim
1096212795Sdimvoid ASTDeclReader::VisitNamespaceDecl(NamespaceDecl *D) {
1097234353Sdim  RedeclarableResult Redecl = VisitRedeclarable(D);
1098212795Sdim  VisitNamedDecl(D);
1099234353Sdim  D->setInline(Record[Idx++]);
1100221345Sdim  D->LocStart = ReadSourceLocation(Record, Idx);
1101221345Sdim  D->RBraceLoc = ReadSourceLocation(Record, Idx);
1102263508Sdim  // FIXME: At the point of this call, D->getCanonicalDecl() returns 0.
1103234353Sdim  mergeRedeclarable(D, Redecl);
1104212795Sdim
1105234353Sdim  if (Redecl.getFirstID() == ThisDeclID) {
1106234353Sdim    // Each module has its own anonymous namespace, which is disjoint from
1107234353Sdim    // any other module's anonymous namespaces, so don't attach the anonymous
1108234353Sdim    // namespace at all.
1109234353Sdim    NamespaceDecl *Anon = ReadDeclAs<NamespaceDecl>(Record, Idx);
1110234353Sdim    if (F.Kind != MK_Module)
1111234353Sdim      D->setAnonymousNamespace(Anon);
1112234353Sdim  } else {
1113234353Sdim    // Link this namespace back to the first declaration, which has already
1114234353Sdim    // been deserialized.
1115263508Sdim    D->AnonOrFirstNamespaceAndInline.setPointer(D->getFirstDecl());
1116234353Sdim  }
1117212795Sdim}
1118212795Sdim
1119212795Sdimvoid ASTDeclReader::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1120212795Sdim  VisitNamedDecl(D);
1121218893Sdim  D->NamespaceLoc = ReadSourceLocation(Record, Idx);
1122218893Sdim  D->IdentLoc = ReadSourceLocation(Record, Idx);
1123219077Sdim  D->QualifierLoc = Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
1124226633Sdim  D->Namespace = ReadDeclAs<NamedDecl>(Record, Idx);
1125212795Sdim}
1126212795Sdim
1127212795Sdimvoid ASTDeclReader::VisitUsingDecl(UsingDecl *D) {
1128212795Sdim  VisitNamedDecl(D);
1129263508Sdim  D->setUsingLoc(ReadSourceLocation(Record, Idx));
1130219077Sdim  D->QualifierLoc = Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
1131218893Sdim  ReadDeclarationNameLoc(D->DNLoc, D->getDeclName(), Record, Idx);
1132234353Sdim  D->FirstUsingShadow.setPointer(ReadDeclAs<UsingShadowDecl>(Record, Idx));
1133263508Sdim  D->setTypename(Record[Idx++]);
1134226633Sdim  if (NamedDecl *Pattern = ReadDeclAs<NamedDecl>(Record, Idx))
1135226633Sdim    Reader.getContext().setInstantiatedFromUsingDecl(D, Pattern);
1136212795Sdim}
1137212795Sdim
1138212795Sdimvoid ASTDeclReader::VisitUsingShadowDecl(UsingShadowDecl *D) {
1139263508Sdim  RedeclarableResult Redecl = VisitRedeclarable(D);
1140212795Sdim  VisitNamedDecl(D);
1141226633Sdim  D->setTargetDecl(ReadDeclAs<NamedDecl>(Record, Idx));
1142226633Sdim  D->UsingOrNextShadow = ReadDeclAs<NamedDecl>(Record, Idx);
1143226633Sdim  UsingShadowDecl *Pattern = ReadDeclAs<UsingShadowDecl>(Record, Idx);
1144212795Sdim  if (Pattern)
1145226633Sdim    Reader.getContext().setInstantiatedFromUsingShadowDecl(D, Pattern);
1146263508Sdim  mergeRedeclarable(D, Redecl);
1147212795Sdim}
1148212795Sdim
1149212795Sdimvoid ASTDeclReader::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1150212795Sdim  VisitNamedDecl(D);
1151218893Sdim  D->UsingLoc = ReadSourceLocation(Record, Idx);
1152218893Sdim  D->NamespaceLoc = ReadSourceLocation(Record, Idx);
1153219077Sdim  D->QualifierLoc = Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
1154226633Sdim  D->NominatedNamespace = ReadDeclAs<NamedDecl>(Record, Idx);
1155226633Sdim  D->CommonAncestor = ReadDeclAs<DeclContext>(Record, Idx);
1156212795Sdim}
1157212795Sdim
1158212795Sdimvoid ASTDeclReader::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1159212795Sdim  VisitValueDecl(D);
1160218893Sdim  D->setUsingLoc(ReadSourceLocation(Record, Idx));
1161219077Sdim  D->QualifierLoc = Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
1162218893Sdim  ReadDeclarationNameLoc(D->DNLoc, D->getDeclName(), Record, Idx);
1163212795Sdim}
1164212795Sdim
1165212795Sdimvoid ASTDeclReader::VisitUnresolvedUsingTypenameDecl(
1166212795Sdim                                               UnresolvedUsingTypenameDecl *D) {
1167212795Sdim  VisitTypeDecl(D);
1168218893Sdim  D->TypenameLocation = ReadSourceLocation(Record, Idx);
1169219077Sdim  D->QualifierLoc = Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
1170212795Sdim}
1171212795Sdim
1172218893Sdimvoid ASTDeclReader::ReadCXXDefinitionData(
1173218893Sdim                                   struct CXXRecordDecl::DefinitionData &Data,
1174218893Sdim                                   const RecordData &Record, unsigned &Idx) {
1175234353Sdim  // Note: the caller has deserialized the IsLambda bit already.
1176218893Sdim  Data.UserDeclaredConstructor = Record[Idx++];
1177249423Sdim  Data.UserDeclaredSpecialMembers = Record[Idx++];
1178218893Sdim  Data.Aggregate = Record[Idx++];
1179218893Sdim  Data.PlainOldData = Record[Idx++];
1180218893Sdim  Data.Empty = Record[Idx++];
1181218893Sdim  Data.Polymorphic = Record[Idx++];
1182218893Sdim  Data.Abstract = Record[Idx++];
1183221345Sdim  Data.IsStandardLayout = Record[Idx++];
1184221345Sdim  Data.HasNoNonEmptyBases = Record[Idx++];
1185221345Sdim  Data.HasPrivateFields = Record[Idx++];
1186221345Sdim  Data.HasProtectedFields = Record[Idx++];
1187221345Sdim  Data.HasPublicFields = Record[Idx++];
1188223017Sdim  Data.HasMutableFields = Record[Idx++];
1189234353Sdim  Data.HasOnlyCMembers = Record[Idx++];
1190239462Sdim  Data.HasInClassInitializer = Record[Idx++];
1191249423Sdim  Data.HasUninitializedReferenceMember = Record[Idx++];
1192249423Sdim  Data.NeedOverloadResolutionForMoveConstructor = Record[Idx++];
1193249423Sdim  Data.NeedOverloadResolutionForMoveAssignment = Record[Idx++];
1194249423Sdim  Data.NeedOverloadResolutionForDestructor = Record[Idx++];
1195249423Sdim  Data.DefaultedMoveConstructorIsDeleted = Record[Idx++];
1196249423Sdim  Data.DefaultedMoveAssignmentIsDeleted = Record[Idx++];
1197249423Sdim  Data.DefaultedDestructorIsDeleted = Record[Idx++];
1198249423Sdim  Data.HasTrivialSpecialMembers = Record[Idx++];
1199249423Sdim  Data.HasIrrelevantDestructor = Record[Idx++];
1200226633Sdim  Data.HasConstexprNonCopyMoveConstructor = Record[Idx++];
1201234353Sdim  Data.DefaultedDefaultConstructorIsConstexpr = Record[Idx++];
1202234353Sdim  Data.HasConstexprDefaultConstructor = Record[Idx++];
1203221345Sdim  Data.HasNonLiteralTypeFieldsOrBases = Record[Idx++];
1204218893Sdim  Data.ComputedVisibleConversions = Record[Idx++];
1205223017Sdim  Data.UserProvidedDefaultConstructor = Record[Idx++];
1206249423Sdim  Data.DeclaredSpecialMembers = Record[Idx++];
1207249423Sdim  Data.ImplicitCopyConstructorHasConstParam = Record[Idx++];
1208249423Sdim  Data.ImplicitCopyAssignmentHasConstParam = Record[Idx++];
1209249423Sdim  Data.HasDeclaredCopyConstructorWithConstParam = Record[Idx++];
1210249423Sdim  Data.HasDeclaredCopyAssignmentWithConstParam = Record[Idx++];
1211218893Sdim
1212218893Sdim  Data.NumBases = Record[Idx++];
1213218893Sdim  if (Data.NumBases)
1214226633Sdim    Data.Bases = Reader.readCXXBaseSpecifiers(F, Record, Idx);
1215218893Sdim  Data.NumVBases = Record[Idx++];
1216218893Sdim  if (Data.NumVBases)
1217226633Sdim    Data.VBases = Reader.readCXXBaseSpecifiers(F, Record, Idx);
1218218893Sdim
1219226633Sdim  Reader.ReadUnresolvedSet(F, Data.Conversions, Record, Idx);
1220226633Sdim  Reader.ReadUnresolvedSet(F, Data.VisibleConversions, Record, Idx);
1221218893Sdim  assert(Data.Definition && "Data.Definition should be already set!");
1222263508Sdim  Data.FirstFriend = ReadDeclID(Record, Idx);
1223263508Sdim
1224234353Sdim  if (Data.IsLambda) {
1225234353Sdim    typedef LambdaExpr::Capture Capture;
1226234353Sdim    CXXRecordDecl::LambdaDefinitionData &Lambda
1227234353Sdim      = static_cast<CXXRecordDecl::LambdaDefinitionData &>(Data);
1228234353Sdim    Lambda.Dependent = Record[Idx++];
1229263508Sdim    Lambda.IsGenericLambda = Record[Idx++];
1230263508Sdim    Lambda.CaptureDefault = Record[Idx++];
1231234353Sdim    Lambda.NumCaptures = Record[Idx++];
1232234353Sdim    Lambda.NumExplicitCaptures = Record[Idx++];
1233234353Sdim    Lambda.ManglingNumber = Record[Idx++];
1234234353Sdim    Lambda.ContextDecl = ReadDecl(Record, Idx);
1235234353Sdim    Lambda.Captures
1236234353Sdim      = (Capture*)Reader.Context.Allocate(sizeof(Capture)*Lambda.NumCaptures);
1237234353Sdim    Capture *ToCapture = Lambda.Captures;
1238243830Sdim    Lambda.MethodTyInfo = GetTypeSourceInfo(Record, Idx);
1239234353Sdim    for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) {
1240234353Sdim      SourceLocation Loc = ReadSourceLocation(Record, Idx);
1241234353Sdim      bool IsImplicit = Record[Idx++];
1242234353Sdim      LambdaCaptureKind Kind = static_cast<LambdaCaptureKind>(Record[Idx++]);
1243263508Sdim      switch (Kind) {
1244263508Sdim      case LCK_This:
1245263508Sdim        *ToCapture++ = Capture(Loc, IsImplicit, Kind, 0, SourceLocation());
1246263508Sdim        break;
1247263508Sdim      case LCK_ByCopy:
1248263508Sdim      case LCK_ByRef:
1249263508Sdim        VarDecl *Var = ReadDeclAs<VarDecl>(Record, Idx);
1250263508Sdim        SourceLocation EllipsisLoc = ReadSourceLocation(Record, Idx);
1251263508Sdim        *ToCapture++ = Capture(Loc, IsImplicit, Kind, Var, EllipsisLoc);
1252263508Sdim        break;
1253263508Sdim      }
1254218893Sdim    }
1255212795Sdim  }
1256218893Sdim}
1257212795Sdim
1258263508SdimASTDeclReader::RedeclarableResult
1259263508SdimASTDeclReader::VisitCXXRecordDeclImpl(CXXRecordDecl *D) {
1260263508Sdim  RedeclarableResult Redecl = VisitRecordDeclImpl(D);
1261212795Sdim
1262226633Sdim  ASTContext &C = Reader.getContext();
1263263508Sdim  bool WasDefinition = Record[Idx++];
1264263508Sdim  if (WasDefinition) {
1265234353Sdim    // Determine whether this is a lambda closure type, so that we can
1266234353Sdim    // allocate the appropriate DefinitionData structure.
1267234353Sdim    bool IsLambda = Record[Idx++];
1268234353Sdim    if (IsLambda)
1269243830Sdim      D->DefinitionData = new (C) CXXRecordDecl::LambdaDefinitionData(D, 0,
1270263508Sdim                                                                      false,
1271263508Sdim                                                                      false, LCD_None);
1272234353Sdim    else
1273234353Sdim      D->DefinitionData = new (C) struct CXXRecordDecl::DefinitionData(D);
1274263508Sdim
1275263508Sdim    ReadCXXDefinitionData(*D->DefinitionData, Record, Idx);
1276263508Sdim
1277234353Sdim    // Propagate the DefinitionData pointer to the canonical declaration, so
1278234353Sdim    // that all other deserialized declarations will see it.
1279263508Sdim    CXXRecordDecl *Canon = D->getCanonicalDecl();
1280263508Sdim    if (Canon == D) {
1281263508Sdim      // Nothing to do.
1282263508Sdim    } else if (!Canon->DefinitionData) {
1283263508Sdim      Canon->DefinitionData = D->DefinitionData;
1284263508Sdim
1285263508Sdim      // Note that we have deserialized a definition. Any declarations
1286263508Sdim      // deserialized before this one will be be given the DefinitionData
1287263508Sdim      // pointer at the end.
1288263508Sdim      Reader.PendingDefinitions.insert(D);
1289263508Sdim    } else {
1290263508Sdim      // We have already deserialized a definition of this record. This
1291263508Sdim      // definition is no longer really a definition. Note that the pre-existing
1292263508Sdim      // definition is the *real* definition.
1293263508Sdim      // FIXME: Check DefinitionData for consistency with prior definition.
1294263508Sdim      Reader.MergedDeclContexts.insert(
1295263508Sdim          std::make_pair(D, D->getCanonicalDecl()->DefinitionData->Definition));
1296263508Sdim      D->IsCompleteDefinition = false;
1297263508Sdim      D->DefinitionData = D->getCanonicalDecl()->DefinitionData;
1298263508Sdim    }
1299234353Sdim  } else {
1300234353Sdim    // Propagate DefinitionData pointer from the canonical declaration.
1301263508Sdim    D->DefinitionData = D->getCanonicalDecl()->DefinitionData;
1302234353Sdim  }
1303212795Sdim
1304212795Sdim  enum CXXRecKind {
1305212795Sdim    CXXRecNotTemplate = 0, CXXRecTemplate, CXXRecMemberSpecialization
1306212795Sdim  };
1307212795Sdim  switch ((CXXRecKind)Record[Idx++]) {
1308212795Sdim  case CXXRecNotTemplate:
1309212795Sdim    break;
1310212795Sdim  case CXXRecTemplate:
1311226633Sdim    D->TemplateOrInstantiation = ReadDeclAs<ClassTemplateDecl>(Record, Idx);
1312212795Sdim    break;
1313212795Sdim  case CXXRecMemberSpecialization: {
1314226633Sdim    CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(Record, Idx);
1315212795Sdim    TemplateSpecializationKind TSK = (TemplateSpecializationKind)Record[Idx++];
1316218893Sdim    SourceLocation POI = ReadSourceLocation(Record, Idx);
1317218893Sdim    MemberSpecializationInfo *MSI = new (C) MemberSpecializationInfo(RD, TSK);
1318218893Sdim    MSI->setPointOfInstantiation(POI);
1319218893Sdim    D->TemplateOrInstantiation = MSI;
1320212795Sdim    break;
1321212795Sdim  }
1322212795Sdim  }
1323218893Sdim
1324263508Sdim  // Lazily load the key function to avoid deserializing every method so we can
1325218893Sdim  // compute it.
1326263508Sdim  if (WasDefinition) {
1327263508Sdim    DeclID KeyFn = ReadDeclID(Record, Idx);
1328263508Sdim    if (KeyFn && D->IsCompleteDefinition)
1329263508Sdim      C.KeyFunctions[D] = KeyFn;
1330218893Sdim  }
1331263508Sdim
1332263508Sdim  return Redecl;
1333212795Sdim}
1334212795Sdim
1335212795Sdimvoid ASTDeclReader::VisitCXXMethodDecl(CXXMethodDecl *D) {
1336212795Sdim  VisitFunctionDecl(D);
1337212795Sdim  unsigned NumOverridenMethods = Record[Idx++];
1338212795Sdim  while (NumOverridenMethods--) {
1339212795Sdim    // Avoid invariant checking of CXXMethodDecl::addOverriddenMethod,
1340212795Sdim    // MD may be initializing.
1341226633Sdim    if (CXXMethodDecl *MD = ReadDeclAs<CXXMethodDecl>(Record, Idx))
1342226633Sdim      Reader.getContext().addOverriddenMethod(D, MD);
1343212795Sdim  }
1344212795Sdim}
1345212795Sdim
1346212795Sdimvoid ASTDeclReader::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
1347212795Sdim  VisitCXXMethodDecl(D);
1348212795Sdim
1349212795Sdim  D->IsExplicitSpecified = Record[Idx++];
1350218893Sdim  llvm::tie(D->CtorInitializers, D->NumCtorInitializers)
1351218893Sdim      = Reader.ReadCXXCtorInitializers(F, Record, Idx);
1352212795Sdim}
1353212795Sdim
1354212795Sdimvoid ASTDeclReader::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
1355212795Sdim  VisitCXXMethodDecl(D);
1356212795Sdim
1357226633Sdim  D->OperatorDelete = ReadDeclAs<FunctionDecl>(Record, Idx);
1358212795Sdim}
1359212795Sdim
1360212795Sdimvoid ASTDeclReader::VisitCXXConversionDecl(CXXConversionDecl *D) {
1361212795Sdim  VisitCXXMethodDecl(D);
1362212795Sdim  D->IsExplicitSpecified = Record[Idx++];
1363212795Sdim}
1364212795Sdim
1365234353Sdimvoid ASTDeclReader::VisitImportDecl(ImportDecl *D) {
1366234353Sdim  VisitDecl(D);
1367234353Sdim  D->ImportedAndComplete.setPointer(readModule(Record, Idx));
1368234353Sdim  D->ImportedAndComplete.setInt(Record[Idx++]);
1369234353Sdim  SourceLocation *StoredLocs = reinterpret_cast<SourceLocation *>(D + 1);
1370234353Sdim  for (unsigned I = 0, N = Record.back(); I != N; ++I)
1371234353Sdim    StoredLocs[I] = ReadSourceLocation(Record, Idx);
1372243830Sdim  ++Idx; // The number of stored source locations.
1373234353Sdim}
1374234353Sdim
1375212795Sdimvoid ASTDeclReader::VisitAccessSpecDecl(AccessSpecDecl *D) {
1376212795Sdim  VisitDecl(D);
1377218893Sdim  D->setColonLoc(ReadSourceLocation(Record, Idx));
1378212795Sdim}
1379212795Sdim
1380212795Sdimvoid ASTDeclReader::VisitFriendDecl(FriendDecl *D) {
1381212795Sdim  VisitDecl(D);
1382249423Sdim  if (Record[Idx++]) // hasFriendDecl
1383249423Sdim    D->Friend = ReadDeclAs<NamedDecl>(Record, Idx);
1384249423Sdim  else
1385218893Sdim    D->Friend = GetTypeSourceInfo(Record, Idx);
1386249423Sdim  for (unsigned i = 0; i != D->NumTPLists; ++i)
1387249423Sdim    D->getTPLists()[i] = Reader.ReadTemplateParameterList(F, Record, Idx);
1388263508Sdim  D->NextFriend = ReadDeclID(Record, Idx);
1389218893Sdim  D->UnsupportedFriend = (Record[Idx++] != 0);
1390218893Sdim  D->FriendLoc = ReadSourceLocation(Record, Idx);
1391212795Sdim}
1392212795Sdim
1393212795Sdimvoid ASTDeclReader::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
1394212795Sdim  VisitDecl(D);
1395212795Sdim  unsigned NumParams = Record[Idx++];
1396212795Sdim  D->NumParams = NumParams;
1397212795Sdim  D->Params = new TemplateParameterList*[NumParams];
1398212795Sdim  for (unsigned i = 0; i != NumParams; ++i)
1399218893Sdim    D->Params[i] = Reader.ReadTemplateParameterList(F, Record, Idx);
1400212795Sdim  if (Record[Idx++]) // HasFriendDecl
1401226633Sdim    D->Friend = ReadDeclAs<NamedDecl>(Record, Idx);
1402212795Sdim  else
1403218893Sdim    D->Friend = GetTypeSourceInfo(Record, Idx);
1404218893Sdim  D->FriendLoc = ReadSourceLocation(Record, Idx);
1405212795Sdim}
1406212795Sdim
1407212795Sdimvoid ASTDeclReader::VisitTemplateDecl(TemplateDecl *D) {
1408212795Sdim  VisitNamedDecl(D);
1409212795Sdim
1410226633Sdim  NamedDecl *TemplatedDecl = ReadDeclAs<NamedDecl>(Record, Idx);
1411212795Sdim  TemplateParameterList* TemplateParams
1412218893Sdim      = Reader.ReadTemplateParameterList(F, Record, Idx);
1413212795Sdim  D->init(TemplatedDecl, TemplateParams);
1414263508Sdim
1415263508Sdim  // FIXME: If this is a redeclaration of a template from another module, handle
1416263508Sdim  // inheritance of default template arguments.
1417212795Sdim}
1418212795Sdim
1419234353SdimASTDeclReader::RedeclarableResult
1420234353SdimASTDeclReader::VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D) {
1421234353Sdim  RedeclarableResult Redecl = VisitRedeclarable(D);
1422212795Sdim
1423234353Sdim  // Make sure we've allocated the Common pointer first. We do this before
1424234353Sdim  // VisitTemplateDecl so that getCommonPtr() can be used during initialization.
1425234353Sdim  RedeclarableTemplateDecl *CanonD = D->getCanonicalDecl();
1426234353Sdim  if (!CanonD->Common) {
1427234353Sdim    CanonD->Common = CanonD->newCommon(Reader.getContext());
1428234353Sdim    Reader.PendingDefinitions.insert(CanonD);
1429234353Sdim  }
1430234353Sdim  D->Common = CanonD->Common;
1431234353Sdim
1432234353Sdim  // If this is the first declaration of the template, fill in the information
1433234353Sdim  // for the 'common' pointer.
1434234353Sdim  if (ThisDeclID == Redecl.getFirstID()) {
1435212795Sdim    if (RedeclarableTemplateDecl *RTD
1436226633Sdim          = ReadDeclAs<RedeclarableTemplateDecl>(Record, Idx)) {
1437212795Sdim      assert(RTD->getKind() == D->getKind() &&
1438212795Sdim             "InstantiatedFromMemberTemplate kind mismatch");
1439234353Sdim      D->setInstantiatedFromMemberTemplate(RTD);
1440212795Sdim      if (Record[Idx++])
1441212795Sdim        D->setMemberSpecialization();
1442212795Sdim    }
1443212795Sdim  }
1444243830Sdim
1445218893Sdim  VisitTemplateDecl(D);
1446218893Sdim  D->IdentifierNamespace = Record[Idx++];
1447243830Sdim
1448243830Sdim  mergeRedeclarable(D, Redecl);
1449243830Sdim
1450263508Sdim  // If we merged the template with a prior declaration chain, merge the common
1451263508Sdim  // pointer.
1452263508Sdim  // FIXME: Actually merge here, don't just overwrite.
1453263508Sdim  D->Common = D->getCanonicalDecl()->Common;
1454263508Sdim
1455234353Sdim  return Redecl;
1456212795Sdim}
1457212795Sdim
1458212795Sdimvoid ASTDeclReader::VisitClassTemplateDecl(ClassTemplateDecl *D) {
1459234353Sdim  RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
1460212795Sdim
1461234353Sdim  if (ThisDeclID == Redecl.getFirstID()) {
1462218893Sdim    // This ClassTemplateDecl owns a CommonPtr; read it to keep track of all of
1463218893Sdim    // the specializations.
1464226633Sdim    SmallVector<serialization::DeclID, 2> SpecIDs;
1465218893Sdim    SpecIDs.push_back(0);
1466218893Sdim
1467218893Sdim    // Specializations.
1468218893Sdim    unsigned Size = Record[Idx++];
1469218893Sdim    SpecIDs[0] += Size;
1470226633Sdim    for (unsigned I = 0; I != Size; ++I)
1471226633Sdim      SpecIDs.push_back(ReadDeclID(Record, Idx));
1472212795Sdim
1473218893Sdim    // Partial specializations.
1474218893Sdim    Size = Record[Idx++];
1475218893Sdim    SpecIDs[0] += Size;
1476226633Sdim    for (unsigned I = 0; I != Size; ++I)
1477226633Sdim      SpecIDs.push_back(ReadDeclID(Record, Idx));
1478212795Sdim
1479243830Sdim    ClassTemplateDecl::Common *CommonPtr = D->getCommonPtr();
1480218893Sdim    if (SpecIDs[0]) {
1481218893Sdim      typedef serialization::DeclID DeclID;
1482218893Sdim
1483234353Sdim      // FIXME: Append specializations!
1484218893Sdim      CommonPtr->LazySpecializations
1485226633Sdim        = new (Reader.getContext()) DeclID [SpecIDs.size()];
1486218893Sdim      memcpy(CommonPtr->LazySpecializations, SpecIDs.data(),
1487218893Sdim             SpecIDs.size() * sizeof(DeclID));
1488218893Sdim    }
1489218893Sdim
1490243830Sdim    CommonPtr->InjectedClassNameType = Reader.readType(F, Record, Idx);
1491212795Sdim  }
1492212795Sdim}
1493212795Sdim
1494263508Sdim/// TODO: Unify with ClassTemplateDecl version?
1495263508Sdim///       May require unifying ClassTemplateDecl and
1496263508Sdim///        VarTemplateDecl beyond TemplateDecl...
1497263508Sdimvoid ASTDeclReader::VisitVarTemplateDecl(VarTemplateDecl *D) {
1498263508Sdim  RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
1499263508Sdim
1500263508Sdim  if (ThisDeclID == Redecl.getFirstID()) {
1501263508Sdim    // This VarTemplateDecl owns a CommonPtr; read it to keep track of all of
1502263508Sdim    // the specializations.
1503263508Sdim    SmallVector<serialization::DeclID, 2> SpecIDs;
1504263508Sdim    SpecIDs.push_back(0);
1505263508Sdim
1506263508Sdim    // Specializations.
1507263508Sdim    unsigned Size = Record[Idx++];
1508263508Sdim    SpecIDs[0] += Size;
1509263508Sdim    for (unsigned I = 0; I != Size; ++I)
1510263508Sdim      SpecIDs.push_back(ReadDeclID(Record, Idx));
1511263508Sdim
1512263508Sdim    // Partial specializations.
1513263508Sdim    Size = Record[Idx++];
1514263508Sdim    SpecIDs[0] += Size;
1515263508Sdim    for (unsigned I = 0; I != Size; ++I)
1516263508Sdim      SpecIDs.push_back(ReadDeclID(Record, Idx));
1517263508Sdim
1518263508Sdim    VarTemplateDecl::Common *CommonPtr = D->getCommonPtr();
1519263508Sdim    if (SpecIDs[0]) {
1520263508Sdim      typedef serialization::DeclID DeclID;
1521263508Sdim
1522263508Sdim      // FIXME: Append specializations!
1523263508Sdim      CommonPtr->LazySpecializations =
1524263508Sdim          new (Reader.getContext()) DeclID[SpecIDs.size()];
1525263508Sdim      memcpy(CommonPtr->LazySpecializations, SpecIDs.data(),
1526263508Sdim             SpecIDs.size() * sizeof(DeclID));
1527263508Sdim    }
1528263508Sdim  }
1529263508Sdim}
1530263508Sdim
1531263508SdimASTDeclReader::RedeclarableResult
1532263508SdimASTDeclReader::VisitClassTemplateSpecializationDeclImpl(
1533263508Sdim    ClassTemplateSpecializationDecl *D) {
1534263508Sdim  RedeclarableResult Redecl = VisitCXXRecordDeclImpl(D);
1535218893Sdim
1536226633Sdim  ASTContext &C = Reader.getContext();
1537226633Sdim  if (Decl *InstD = ReadDecl(Record, Idx)) {
1538212795Sdim    if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(InstD)) {
1539218893Sdim      D->SpecializedTemplate = CTD;
1540212795Sdim    } else {
1541226633Sdim      SmallVector<TemplateArgument, 8> TemplArgs;
1542218893Sdim      Reader.ReadTemplateArgumentList(TemplArgs, F, Record, Idx);
1543218893Sdim      TemplateArgumentList *ArgList
1544218893Sdim        = TemplateArgumentList::CreateCopy(C, TemplArgs.data(),
1545218893Sdim                                           TemplArgs.size());
1546218893Sdim      ClassTemplateSpecializationDecl::SpecializedPartialSpecialization *PS
1547218893Sdim          = new (C) ClassTemplateSpecializationDecl::
1548218893Sdim                                             SpecializedPartialSpecialization();
1549218893Sdim      PS->PartialSpecialization
1550218893Sdim          = cast<ClassTemplatePartialSpecializationDecl>(InstD);
1551218893Sdim      PS->TemplateArgs = ArgList;
1552218893Sdim      D->SpecializedTemplate = PS;
1553212795Sdim    }
1554212795Sdim  }
1555212795Sdim
1556226633Sdim  SmallVector<TemplateArgument, 8> TemplArgs;
1557218893Sdim  Reader.ReadTemplateArgumentList(TemplArgs, F, Record, Idx);
1558218893Sdim  D->TemplateArgs = TemplateArgumentList::CreateCopy(C, TemplArgs.data(),
1559218893Sdim                                                     TemplArgs.size());
1560218893Sdim  D->PointOfInstantiation = ReadSourceLocation(Record, Idx);
1561218893Sdim  D->SpecializationKind = (TemplateSpecializationKind)Record[Idx++];
1562243830Sdim
1563243830Sdim  bool writtenAsCanonicalDecl = Record[Idx++];
1564243830Sdim  if (writtenAsCanonicalDecl) {
1565226633Sdim    ClassTemplateDecl *CanonPattern = ReadDeclAs<ClassTemplateDecl>(Record,Idx);
1566243830Sdim    if (D->isCanonicalDecl()) { // It's kept in the folding set.
1567263508Sdim      // Set this as, or find, the canonical declaration for this specialization
1568263508Sdim      ClassTemplateSpecializationDecl *CanonSpec;
1569263508Sdim      if (ClassTemplatePartialSpecializationDecl *Partial =
1570263508Sdim              dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) {
1571263508Sdim        CanonSpec = CanonPattern->getCommonPtr()->PartialSpecializations
1572263508Sdim            .GetOrInsertNode(Partial);
1573243830Sdim      } else {
1574263508Sdim        CanonSpec =
1575263508Sdim            CanonPattern->getCommonPtr()->Specializations.GetOrInsertNode(D);
1576243830Sdim      }
1577263508Sdim      // If there was already a canonical specialization, merge into it.
1578263508Sdim      if (CanonSpec != D) {
1579263508Sdim        mergeRedeclarable<TagDecl>(D, CanonSpec, Redecl);
1580263508Sdim
1581263508Sdim        // This declaration might be a definition. Merge with any existing
1582263508Sdim        // definition.
1583263508Sdim        if (D->DefinitionData) {
1584263508Sdim          if (!CanonSpec->DefinitionData) {
1585263508Sdim            CanonSpec->DefinitionData = D->DefinitionData;
1586263508Sdim          } else {
1587263508Sdim            // FIXME: Check DefinitionData for consistency with prior definition
1588263508Sdim            Reader.PendingDefinitions.erase(D);
1589263508Sdim            Reader.MergedDeclContexts.insert(
1590263508Sdim                std::make_pair(D, CanonSpec->DefinitionData->Definition));
1591263508Sdim            D->IsCompleteDefinition = false;
1592263508Sdim            D->DefinitionData = CanonSpec->DefinitionData;
1593263508Sdim          }
1594263508Sdim        }
1595263508Sdim      }
1596212795Sdim    }
1597212795Sdim  }
1598263508Sdim
1599263508Sdim  // Explicit info.
1600263508Sdim  if (TypeSourceInfo *TyInfo = GetTypeSourceInfo(Record, Idx)) {
1601263508Sdim    ClassTemplateSpecializationDecl::ExplicitSpecializationInfo *ExplicitInfo
1602263508Sdim        = new (C) ClassTemplateSpecializationDecl::ExplicitSpecializationInfo;
1603263508Sdim    ExplicitInfo->TypeAsWritten = TyInfo;
1604263508Sdim    ExplicitInfo->ExternLoc = ReadSourceLocation(Record, Idx);
1605263508Sdim    ExplicitInfo->TemplateKeywordLoc = ReadSourceLocation(Record, Idx);
1606263508Sdim    D->ExplicitInfo = ExplicitInfo;
1607263508Sdim  }
1608263508Sdim
1609263508Sdim  return Redecl;
1610212795Sdim}
1611212795Sdim
1612212795Sdimvoid ASTDeclReader::VisitClassTemplatePartialSpecializationDecl(
1613212795Sdim                                    ClassTemplatePartialSpecializationDecl *D) {
1614263508Sdim  RedeclarableResult Redecl = VisitClassTemplateSpecializationDeclImpl(D);
1615212795Sdim
1616218893Sdim  D->TemplateParams = Reader.ReadTemplateParameterList(F, Record, Idx);
1617263508Sdim  D->ArgsAsWritten = Reader.ReadASTTemplateArgumentListInfo(F, Record, Idx);
1618218893Sdim
1619212795Sdim  // These are read/set from/to the first declaration.
1620263508Sdim  if (ThisDeclID == Redecl.getFirstID()) {
1621218893Sdim    D->InstantiatedFromMember.setPointer(
1622226633Sdim      ReadDeclAs<ClassTemplatePartialSpecializationDecl>(Record, Idx));
1623218893Sdim    D->InstantiatedFromMember.setInt(Record[Idx++]);
1624212795Sdim  }
1625212795Sdim}
1626212795Sdim
1627226633Sdimvoid ASTDeclReader::VisitClassScopeFunctionSpecializationDecl(
1628226633Sdim                                    ClassScopeFunctionSpecializationDecl *D) {
1629226633Sdim  VisitDecl(D);
1630226633Sdim  D->Specialization = ReadDeclAs<CXXMethodDecl>(Record, Idx);
1631226633Sdim}
1632226633Sdim
1633212795Sdimvoid ASTDeclReader::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
1634234353Sdim  RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
1635212795Sdim
1636234353Sdim  if (ThisDeclID == Redecl.getFirstID()) {
1637212795Sdim    // This FunctionTemplateDecl owns a CommonPtr; read it.
1638212795Sdim
1639263508Sdim    // Read the function specialization declaration IDs. The specializations
1640263508Sdim    // themselves will be loaded if they're needed.
1641263508Sdim    if (unsigned NumSpecs = Record[Idx++]) {
1642263508Sdim      // FIXME: Append specializations!
1643263508Sdim      FunctionTemplateDecl::Common *CommonPtr = D->getCommonPtr();
1644263508Sdim      CommonPtr->LazySpecializations = new (Reader.getContext())
1645263508Sdim          serialization::DeclID[NumSpecs + 1];
1646263508Sdim      CommonPtr->LazySpecializations[0] = NumSpecs;
1647263508Sdim      for (unsigned I = 0; I != NumSpecs; ++I)
1648263508Sdim        CommonPtr->LazySpecializations[I + 1] = ReadDeclID(Record, Idx);
1649263508Sdim    }
1650212795Sdim  }
1651212795Sdim}
1652212795Sdim
1653263508Sdim/// TODO: Unify with ClassTemplateSpecializationDecl version?
1654263508Sdim///       May require unifying ClassTemplate(Partial)SpecializationDecl and
1655263508Sdim///        VarTemplate(Partial)SpecializationDecl with a new data
1656263508Sdim///        structure Template(Partial)SpecializationDecl, and
1657263508Sdim///        using Template(Partial)SpecializationDecl as input type.
1658263508SdimASTDeclReader::RedeclarableResult
1659263508SdimASTDeclReader::VisitVarTemplateSpecializationDeclImpl(
1660263508Sdim    VarTemplateSpecializationDecl *D) {
1661263508Sdim  RedeclarableResult Redecl = VisitVarDeclImpl(D);
1662263508Sdim
1663263508Sdim  ASTContext &C = Reader.getContext();
1664263508Sdim  if (Decl *InstD = ReadDecl(Record, Idx)) {
1665263508Sdim    if (VarTemplateDecl *VTD = dyn_cast<VarTemplateDecl>(InstD)) {
1666263508Sdim      D->SpecializedTemplate = VTD;
1667263508Sdim    } else {
1668263508Sdim      SmallVector<TemplateArgument, 8> TemplArgs;
1669263508Sdim      Reader.ReadTemplateArgumentList(TemplArgs, F, Record, Idx);
1670263508Sdim      TemplateArgumentList *ArgList = TemplateArgumentList::CreateCopy(
1671263508Sdim          C, TemplArgs.data(), TemplArgs.size());
1672263508Sdim      VarTemplateSpecializationDecl::SpecializedPartialSpecialization *PS =
1673263508Sdim          new (C)
1674263508Sdim          VarTemplateSpecializationDecl::SpecializedPartialSpecialization();
1675263508Sdim      PS->PartialSpecialization =
1676263508Sdim          cast<VarTemplatePartialSpecializationDecl>(InstD);
1677263508Sdim      PS->TemplateArgs = ArgList;
1678263508Sdim      D->SpecializedTemplate = PS;
1679263508Sdim    }
1680263508Sdim  }
1681263508Sdim
1682263508Sdim  // Explicit info.
1683263508Sdim  if (TypeSourceInfo *TyInfo = GetTypeSourceInfo(Record, Idx)) {
1684263508Sdim    VarTemplateSpecializationDecl::ExplicitSpecializationInfo *ExplicitInfo =
1685263508Sdim        new (C) VarTemplateSpecializationDecl::ExplicitSpecializationInfo;
1686263508Sdim    ExplicitInfo->TypeAsWritten = TyInfo;
1687263508Sdim    ExplicitInfo->ExternLoc = ReadSourceLocation(Record, Idx);
1688263508Sdim    ExplicitInfo->TemplateKeywordLoc = ReadSourceLocation(Record, Idx);
1689263508Sdim    D->ExplicitInfo = ExplicitInfo;
1690263508Sdim  }
1691263508Sdim
1692263508Sdim  SmallVector<TemplateArgument, 8> TemplArgs;
1693263508Sdim  Reader.ReadTemplateArgumentList(TemplArgs, F, Record, Idx);
1694263508Sdim  D->TemplateArgs =
1695263508Sdim      TemplateArgumentList::CreateCopy(C, TemplArgs.data(), TemplArgs.size());
1696263508Sdim  D->PointOfInstantiation = ReadSourceLocation(Record, Idx);
1697263508Sdim  D->SpecializationKind = (TemplateSpecializationKind)Record[Idx++];
1698263508Sdim
1699263508Sdim  bool writtenAsCanonicalDecl = Record[Idx++];
1700263508Sdim  if (writtenAsCanonicalDecl) {
1701263508Sdim    VarTemplateDecl *CanonPattern = ReadDeclAs<VarTemplateDecl>(Record, Idx);
1702263508Sdim    if (D->isCanonicalDecl()) { // It's kept in the folding set.
1703263508Sdim      if (VarTemplatePartialSpecializationDecl *Partial =
1704263508Sdim              dyn_cast<VarTemplatePartialSpecializationDecl>(D)) {
1705263508Sdim        CanonPattern->getCommonPtr()->PartialSpecializations
1706263508Sdim            .GetOrInsertNode(Partial);
1707263508Sdim      } else {
1708263508Sdim        CanonPattern->getCommonPtr()->Specializations.GetOrInsertNode(D);
1709263508Sdim      }
1710263508Sdim    }
1711263508Sdim  }
1712263508Sdim
1713263508Sdim  return Redecl;
1714263508Sdim}
1715263508Sdim
1716263508Sdim/// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
1717263508Sdim///       May require unifying ClassTemplate(Partial)SpecializationDecl and
1718263508Sdim///        VarTemplate(Partial)SpecializationDecl with a new data
1719263508Sdim///        structure Template(Partial)SpecializationDecl, and
1720263508Sdim///        using Template(Partial)SpecializationDecl as input type.
1721263508Sdimvoid ASTDeclReader::VisitVarTemplatePartialSpecializationDecl(
1722263508Sdim    VarTemplatePartialSpecializationDecl *D) {
1723263508Sdim  RedeclarableResult Redecl = VisitVarTemplateSpecializationDeclImpl(D);
1724263508Sdim
1725263508Sdim  D->TemplateParams = Reader.ReadTemplateParameterList(F, Record, Idx);
1726263508Sdim  D->ArgsAsWritten = Reader.ReadASTTemplateArgumentListInfo(F, Record, Idx);
1727263508Sdim
1728263508Sdim  // These are read/set from/to the first declaration.
1729263508Sdim  if (ThisDeclID == Redecl.getFirstID()) {
1730263508Sdim    D->InstantiatedFromMember.setPointer(
1731263508Sdim        ReadDeclAs<VarTemplatePartialSpecializationDecl>(Record, Idx));
1732263508Sdim    D->InstantiatedFromMember.setInt(Record[Idx++]);
1733263508Sdim  }
1734263508Sdim}
1735263508Sdim
1736212795Sdimvoid ASTDeclReader::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
1737212795Sdim  VisitTypeDecl(D);
1738212795Sdim
1739212795Sdim  D->setDeclaredWithTypename(Record[Idx++]);
1740212795Sdim
1741212795Sdim  bool Inherited = Record[Idx++];
1742218893Sdim  TypeSourceInfo *DefArg = GetTypeSourceInfo(Record, Idx);
1743212795Sdim  D->setDefaultArgument(DefArg, Inherited);
1744212795Sdim}
1745212795Sdim
1746212795Sdimvoid ASTDeclReader::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
1747218893Sdim  VisitDeclaratorDecl(D);
1748212795Sdim  // TemplateParmPosition.
1749212795Sdim  D->setDepth(Record[Idx++]);
1750212795Sdim  D->setPosition(Record[Idx++]);
1751218893Sdim  if (D->isExpandedParameterPack()) {
1752218893Sdim    void **Data = reinterpret_cast<void **>(D + 1);
1753218893Sdim    for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
1754226633Sdim      Data[2*I] = Reader.readType(F, Record, Idx).getAsOpaquePtr();
1755218893Sdim      Data[2*I + 1] = GetTypeSourceInfo(Record, Idx);
1756218893Sdim    }
1757218893Sdim  } else {
1758218893Sdim    // Rest of NonTypeTemplateParmDecl.
1759218893Sdim    D->ParameterPack = Record[Idx++];
1760218893Sdim    if (Record[Idx++]) {
1761218893Sdim      Expr *DefArg = Reader.ReadExpr(F);
1762218893Sdim      bool Inherited = Record[Idx++];
1763218893Sdim      D->setDefaultArgument(DefArg, Inherited);
1764218893Sdim   }
1765218893Sdim  }
1766212795Sdim}
1767212795Sdim
1768212795Sdimvoid ASTDeclReader::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
1769212795Sdim  VisitTemplateDecl(D);
1770212795Sdim  // TemplateParmPosition.
1771212795Sdim  D->setDepth(Record[Idx++]);
1772212795Sdim  D->setPosition(Record[Idx++]);
1773243830Sdim  if (D->isExpandedParameterPack()) {
1774243830Sdim    void **Data = reinterpret_cast<void **>(D + 1);
1775243830Sdim    for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
1776243830Sdim         I != N; ++I)
1777243830Sdim      Data[I] = Reader.ReadTemplateParameterList(F, Record, Idx);
1778243830Sdim  } else {
1779243830Sdim    // Rest of TemplateTemplateParmDecl.
1780243830Sdim    TemplateArgumentLoc Arg = Reader.ReadTemplateArgumentLoc(F, Record, Idx);
1781243830Sdim    bool IsInherited = Record[Idx++];
1782243830Sdim    D->setDefaultArgument(Arg, IsInherited);
1783243830Sdim    D->ParameterPack = Record[Idx++];
1784243830Sdim  }
1785212795Sdim}
1786212795Sdim
1787223017Sdimvoid ASTDeclReader::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
1788223017Sdim  VisitRedeclarableTemplateDecl(D);
1789223017Sdim}
1790223017Sdim
1791212795Sdimvoid ASTDeclReader::VisitStaticAssertDecl(StaticAssertDecl *D) {
1792212795Sdim  VisitDecl(D);
1793239462Sdim  D->AssertExprAndFailed.setPointer(Reader.ReadExpr(F));
1794239462Sdim  D->AssertExprAndFailed.setInt(Record[Idx++]);
1795218893Sdim  D->Message = cast<StringLiteral>(Reader.ReadExpr(F));
1796221345Sdim  D->RParenLoc = ReadSourceLocation(Record, Idx);
1797212795Sdim}
1798212795Sdim
1799249423Sdimvoid ASTDeclReader::VisitEmptyDecl(EmptyDecl *D) {
1800249423Sdim  VisitDecl(D);
1801249423Sdim}
1802249423Sdim
1803212795Sdimstd::pair<uint64_t, uint64_t>
1804212795SdimASTDeclReader::VisitDeclContext(DeclContext *DC) {
1805212795Sdim  uint64_t LexicalOffset = Record[Idx++];
1806212795Sdim  uint64_t VisibleOffset = Record[Idx++];
1807212795Sdim  return std::make_pair(LexicalOffset, VisibleOffset);
1808212795Sdim}
1809212795Sdim
1810212795Sdimtemplate <typename T>
1811234353SdimASTDeclReader::RedeclarableResult
1812234353SdimASTDeclReader::VisitRedeclarable(Redeclarable<T> *D) {
1813234353Sdim  DeclID FirstDeclID = ReadDeclID(Record, Idx);
1814234353Sdim
1815234353Sdim  // 0 indicates that this declaration was the only declaration of its entity,
1816234353Sdim  // and is used for space optimization.
1817234353Sdim  if (FirstDeclID == 0)
1818234353Sdim    FirstDeclID = ThisDeclID;
1819234353Sdim
1820234353Sdim  T *FirstDecl = cast_or_null<T>(Reader.GetDecl(FirstDeclID));
1821234353Sdim  if (FirstDecl != D) {
1822218893Sdim    // We delay loading of the redeclaration chain to avoid deeply nested calls.
1823218893Sdim    // We temporarily set the first (canonical) declaration as the previous one
1824218893Sdim    // which is the one that matters and mark the real previous DeclID to be
1825218893Sdim    // loaded & attached later on.
1826239462Sdim    D->RedeclLink = Redeclarable<T>::PreviousDeclLink(FirstDecl);
1827234353Sdim  }
1828234353Sdim
1829234353Sdim  // Note that this declaration has been deserialized.
1830234353Sdim  Reader.RedeclsDeserialized.insert(static_cast<T *>(D));
1831234353Sdim
1832234353Sdim  // The result structure takes care to note that we need to load the
1833234353Sdim  // other declaration chains for this ID.
1834249423Sdim  return RedeclarableResult(Reader, FirstDeclID,
1835249423Sdim                            static_cast<T *>(D)->getKind());
1836234353Sdim}
1837212795Sdim
1838234353Sdim/// \brief Attempts to merge the given declaration (D) with another declaration
1839234353Sdim/// of the same entity.
1840234353Sdimtemplate<typename T>
1841263508Sdimvoid ASTDeclReader::mergeRedeclarable(Redeclarable<T> *D,
1842234353Sdim                                      RedeclarableResult &Redecl) {
1843234353Sdim  // If modules are not available, there is no reason to perform this merge.
1844234353Sdim  if (!Reader.getContext().getLangOpts().Modules)
1845212795Sdim    return;
1846263508Sdim
1847263508Sdim  if (FindExistingResult ExistingRes = findExisting(static_cast<T*>(D)))
1848263508Sdim    if (T *Existing = ExistingRes)
1849263508Sdim      mergeRedeclarable(D, Existing, Redecl);
1850263508Sdim}
1851263508Sdim
1852263508Sdim/// \brief Attempts to merge the given declaration (D) with another declaration
1853263508Sdim/// of the same entity.
1854263508Sdimtemplate<typename T>
1855263508Sdimvoid ASTDeclReader::mergeRedeclarable(Redeclarable<T> *D, T *Existing,
1856263508Sdim                                      RedeclarableResult &Redecl) {
1857263508Sdim  T *ExistingCanon = Existing->getCanonicalDecl();
1858263508Sdim  T *DCanon = static_cast<T*>(D)->getCanonicalDecl();
1859263508Sdim  if (ExistingCanon != DCanon) {
1860263508Sdim    // Have our redeclaration link point back at the canonical declaration
1861263508Sdim    // of the existing declaration, so that this declaration has the
1862263508Sdim    // appropriate canonical declaration.
1863263508Sdim    D->RedeclLink = Redeclarable<T>::PreviousDeclLink(ExistingCanon);
1864263508Sdim
1865263508Sdim    // When we merge a namespace, update its pointer to the first namespace.
1866263508Sdim    if (NamespaceDecl *Namespace
1867263508Sdim          = dyn_cast<NamespaceDecl>(static_cast<T*>(D))) {
1868263508Sdim      Namespace->AnonOrFirstNamespaceAndInline.setPointer(
1869263508Sdim        static_cast<NamespaceDecl *>(static_cast<void*>(ExistingCanon)));
1870234353Sdim    }
1871263508Sdim
1872263508Sdim    // Don't introduce DCanon into the set of pending declaration chains.
1873263508Sdim    Redecl.suppress();
1874263508Sdim
1875263508Sdim    // Introduce ExistingCanon into the set of pending declaration chains,
1876263508Sdim    // if in fact it came from a module file.
1877263508Sdim    if (ExistingCanon->isFromASTFile()) {
1878263508Sdim      GlobalDeclID ExistingCanonID = ExistingCanon->getGlobalID();
1879263508Sdim      assert(ExistingCanonID && "Unrecorded canonical declaration ID?");
1880263508Sdim      if (Reader.PendingDeclChainsKnown.insert(ExistingCanonID))
1881263508Sdim        Reader.PendingDeclChains.push_back(ExistingCanonID);
1882263508Sdim    }
1883263508Sdim
1884263508Sdim    // If this declaration was the canonical declaration, make a note of
1885263508Sdim    // that. We accept the linear algorithm here because the number of
1886263508Sdim    // unique canonical declarations of an entity should always be tiny.
1887263508Sdim    if (DCanon == static_cast<T*>(D)) {
1888263508Sdim      SmallVectorImpl<DeclID> &Merged = Reader.MergedDecls[ExistingCanon];
1889263508Sdim      if (std::find(Merged.begin(), Merged.end(), Redecl.getFirstID())
1890263508Sdim            == Merged.end())
1891263508Sdim        Merged.push_back(Redecl.getFirstID());
1892263508Sdim
1893263508Sdim      // If ExistingCanon did not come from a module file, introduce the
1894263508Sdim      // first declaration that *does* come from a module file to the
1895263508Sdim      // set of pending declaration chains, so that we merge this
1896263508Sdim      // declaration.
1897263508Sdim      if (!ExistingCanon->isFromASTFile() &&
1898263508Sdim          Reader.PendingDeclChainsKnown.insert(Redecl.getFirstID()))
1899263508Sdim        Reader.PendingDeclChains.push_back(Merged[0]);
1900263508Sdim    }
1901212795Sdim  }
1902212795Sdim}
1903212795Sdim
1904263508Sdim/// \brief Attempts to merge the given declaration (D) with another declaration
1905263508Sdim/// of the same entity, for the case where the entity is not actually
1906263508Sdim/// redeclarable. This happens, for instance, when merging the fields of
1907263508Sdim/// identical class definitions from two different modules.
1908263508Sdimtemplate<typename T>
1909263508Sdimvoid ASTDeclReader::mergeMergeable(Mergeable<T> *D) {
1910263508Sdim  // If modules are not available, there is no reason to perform this merge.
1911263508Sdim  if (!Reader.getContext().getLangOpts().Modules)
1912263508Sdim    return;
1913263508Sdim
1914263508Sdim  // ODR-based merging is only performed in C++. In C, identically-named things
1915263508Sdim  // in different translation units are not redeclarations (but may still have
1916263508Sdim  // compatible types).
1917263508Sdim  if (!Reader.getContext().getLangOpts().CPlusPlus)
1918263508Sdim    return;
1919263508Sdim
1920263508Sdim  if (FindExistingResult ExistingRes = findExisting(static_cast<T*>(D)))
1921263508Sdim    if (T *Existing = ExistingRes)
1922263508Sdim      Reader.Context.setPrimaryMergedDecl(static_cast<T*>(D),
1923263508Sdim                                          Existing->getCanonicalDecl());
1924263508Sdim}
1925263508Sdim
1926249423Sdimvoid ASTDeclReader::VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D) {
1927249423Sdim  VisitDecl(D);
1928249423Sdim  unsigned NumVars = D->varlist_size();
1929263508Sdim  SmallVector<Expr *, 16> Vars;
1930249423Sdim  Vars.reserve(NumVars);
1931249423Sdim  for (unsigned i = 0; i != NumVars; ++i) {
1932263508Sdim    Vars.push_back(Reader.ReadExpr(F));
1933249423Sdim  }
1934249423Sdim  D->setVars(Vars);
1935249423Sdim}
1936249423Sdim
1937212795Sdim//===----------------------------------------------------------------------===//
1938212795Sdim// Attribute Reading
1939212795Sdim//===----------------------------------------------------------------------===//
1940212795Sdim
1941212795Sdim/// \brief Reads attributes from the current stream position.
1942234353Sdimvoid ASTReader::ReadAttributes(ModuleFile &F, AttrVec &Attrs,
1943218893Sdim                               const RecordData &Record, unsigned &Idx) {
1944218893Sdim  for (unsigned i = 0, e = Record[Idx++]; i != e; ++i) {
1945212795Sdim    Attr *New = 0;
1946212795Sdim    attr::Kind Kind = (attr::Kind)Record[Idx++];
1947226633Sdim    SourceRange Range = ReadSourceRange(F, Record, Idx);
1948212795Sdim
1949212795Sdim#include "clang/Serialization/AttrPCHRead.inc"
1950212795Sdim
1951212795Sdim    assert(New && "Unable to decode attribute?");
1952212795Sdim    Attrs.push_back(New);
1953212795Sdim  }
1954212795Sdim}
1955212795Sdim
1956212795Sdim//===----------------------------------------------------------------------===//
1957212795Sdim// ASTReader Implementation
1958212795Sdim//===----------------------------------------------------------------------===//
1959212795Sdim
1960212795Sdim/// \brief Note that we have loaded the declaration with the given
1961212795Sdim/// Index.
1962212795Sdim///
1963212795Sdim/// This routine notes that this declaration has already been loaded,
1964212795Sdim/// so that future GetDecl calls will return this declaration rather
1965212795Sdim/// than trying to load a new declaration.
1966212795Sdiminline void ASTReader::LoadedDecl(unsigned Index, Decl *D) {
1967212795Sdim  assert(!DeclsLoaded[Index] && "Decl loaded twice?");
1968212795Sdim  DeclsLoaded[Index] = D;
1969212795Sdim}
1970212795Sdim
1971212795Sdim
1972212795Sdim/// \brief Determine whether the consumer will be interested in seeing
1973212795Sdim/// this declaration (via HandleTopLevelDecl).
1974212795Sdim///
1975212795Sdim/// This routine should return true for anything that might affect
1976212795Sdim/// code generation, e.g., inline function definitions, Objective-C
1977212795Sdim/// declarations with metadata, etc.
1978243830Sdimstatic bool isConsumerInterestedIn(Decl *D, bool HasBody) {
1979226633Sdim  // An ObjCMethodDecl is never considered as "interesting" because its
1980226633Sdim  // implementation container always is.
1981226633Sdim
1982226633Sdim  if (isa<FileScopeAsmDecl>(D) ||
1983226633Sdim      isa<ObjCProtocolDecl>(D) ||
1984226633Sdim      isa<ObjCImplDecl>(D))
1985212795Sdim    return true;
1986212795Sdim  if (VarDecl *Var = dyn_cast<VarDecl>(D))
1987212795Sdim    return Var->isFileVarDecl() &&
1988212795Sdim           Var->isThisDeclarationADefinition() == VarDecl::Definition;
1989212795Sdim  if (FunctionDecl *Func = dyn_cast<FunctionDecl>(D))
1990243830Sdim    return Func->doesThisDeclarationHaveABody() || HasBody;
1991226633Sdim
1992226633Sdim  return false;
1993212795Sdim}
1994212795Sdim
1995226633Sdim/// \brief Get the correct cursor and offset for loading a declaration.
1996212795SdimASTReader::RecordLocation
1997234353SdimASTReader::DeclCursorForID(DeclID ID, unsigned &RawLocation) {
1998212795Sdim  // See if there's an override.
1999212795Sdim  DeclReplacementMap::iterator It = ReplacedDecls.find(ID);
2000234353Sdim  if (It != ReplacedDecls.end()) {
2001234353Sdim    RawLocation = It->second.RawLoc;
2002234353Sdim    return RecordLocation(It->second.Mod, It->second.Offset);
2003234353Sdim  }
2004212795Sdim
2005226633Sdim  GlobalDeclMapType::iterator I = GlobalDeclMap.find(ID);
2006226633Sdim  assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
2007234353Sdim  ModuleFile *M = I->second;
2008234353Sdim  const DeclOffset &
2009234353Sdim    DOffs =  M->DeclOffsets[ID - M->BaseDeclID - NUM_PREDEF_DECL_IDS];
2010234353Sdim  RawLocation = DOffs.Loc;
2011234353Sdim  return RecordLocation(M, DOffs.BitOffset);
2012212795Sdim}
2013212795Sdim
2014226633SdimASTReader::RecordLocation ASTReader::getLocalBitOffset(uint64_t GlobalOffset) {
2015234353Sdim  ContinuousRangeMap<uint64_t, ModuleFile*, 4>::iterator I
2016226633Sdim    = GlobalBitOffsetsMap.find(GlobalOffset);
2017226633Sdim
2018226633Sdim  assert(I != GlobalBitOffsetsMap.end() && "Corrupted global bit offsets map");
2019226633Sdim  return RecordLocation(I->second, GlobalOffset - I->second->GlobalBitOffset);
2020226633Sdim}
2021226633Sdim
2022234353Sdimuint64_t ASTReader::getGlobalBitOffset(ModuleFile &M, uint32_t LocalOffset) {
2023226633Sdim  return LocalOffset + M.GlobalBitOffset;
2024226633Sdim}
2025226633Sdim
2026263508Sdimstatic bool isSameTemplateParameterList(const TemplateParameterList *X,
2027263508Sdim                                        const TemplateParameterList *Y);
2028263508Sdim
2029263508Sdim/// \brief Determine whether two template parameters are similar enough
2030263508Sdim/// that they may be used in declarations of the same template.
2031263508Sdimstatic bool isSameTemplateParameter(const NamedDecl *X,
2032263508Sdim                                    const NamedDecl *Y) {
2033263508Sdim  if (X->getKind() != Y->getKind())
2034263508Sdim    return false;
2035263508Sdim
2036263508Sdim  if (const TemplateTypeParmDecl *TX = dyn_cast<TemplateTypeParmDecl>(X)) {
2037263508Sdim    const TemplateTypeParmDecl *TY = cast<TemplateTypeParmDecl>(Y);
2038263508Sdim    return TX->isParameterPack() == TY->isParameterPack();
2039263508Sdim  }
2040263508Sdim
2041263508Sdim  if (const NonTypeTemplateParmDecl *TX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
2042263508Sdim    const NonTypeTemplateParmDecl *TY = cast<NonTypeTemplateParmDecl>(Y);
2043263508Sdim    return TX->isParameterPack() == TY->isParameterPack() &&
2044263508Sdim           TX->getASTContext().hasSameType(TX->getType(), TY->getType());
2045263508Sdim  }
2046263508Sdim
2047263508Sdim  const TemplateTemplateParmDecl *TX = cast<TemplateTemplateParmDecl>(X);
2048263508Sdim  const TemplateTemplateParmDecl *TY = cast<TemplateTemplateParmDecl>(Y);
2049263508Sdim  return TX->isParameterPack() == TY->isParameterPack() &&
2050263508Sdim         isSameTemplateParameterList(TX->getTemplateParameters(),
2051263508Sdim                                     TY->getTemplateParameters());
2052263508Sdim}
2053263508Sdim
2054263508Sdim/// \brief Determine whether two template parameter lists are similar enough
2055263508Sdim/// that they may be used in declarations of the same template.
2056263508Sdimstatic bool isSameTemplateParameterList(const TemplateParameterList *X,
2057263508Sdim                                        const TemplateParameterList *Y) {
2058263508Sdim  if (X->size() != Y->size())
2059263508Sdim    return false;
2060263508Sdim
2061263508Sdim  for (unsigned I = 0, N = X->size(); I != N; ++I)
2062263508Sdim    if (!isSameTemplateParameter(X->getParam(I), Y->getParam(I)))
2063263508Sdim      return false;
2064263508Sdim
2065263508Sdim  return true;
2066263508Sdim}
2067263508Sdim
2068234353Sdim/// \brief Determine whether the two declarations refer to the same entity.
2069234353Sdimstatic bool isSameEntity(NamedDecl *X, NamedDecl *Y) {
2070234353Sdim  assert(X->getDeclName() == Y->getDeclName() && "Declaration name mismatch!");
2071234353Sdim
2072234353Sdim  if (X == Y)
2073234353Sdim    return true;
2074234353Sdim
2075234353Sdim  // Must be in the same context.
2076234353Sdim  if (!X->getDeclContext()->getRedeclContext()->Equals(
2077234353Sdim         Y->getDeclContext()->getRedeclContext()))
2078234353Sdim    return false;
2079234353Sdim
2080234353Sdim  // Two typedefs refer to the same entity if they have the same underlying
2081234353Sdim  // type.
2082234353Sdim  if (TypedefNameDecl *TypedefX = dyn_cast<TypedefNameDecl>(X))
2083234353Sdim    if (TypedefNameDecl *TypedefY = dyn_cast<TypedefNameDecl>(Y))
2084234353Sdim      return X->getASTContext().hasSameType(TypedefX->getUnderlyingType(),
2085234353Sdim                                            TypedefY->getUnderlyingType());
2086234353Sdim
2087234353Sdim  // Must have the same kind.
2088234353Sdim  if (X->getKind() != Y->getKind())
2089234353Sdim    return false;
2090234353Sdim
2091234353Sdim  // Objective-C classes and protocols with the same name always match.
2092234353Sdim  if (isa<ObjCInterfaceDecl>(X) || isa<ObjCProtocolDecl>(X))
2093234353Sdim    return true;
2094263508Sdim
2095263508Sdim  if (isa<ClassTemplateSpecializationDecl>(X)) {
2096263508Sdim    // No need to handle these here: we merge them when adding them to the
2097263508Sdim    // template.
2098263508Sdim    return false;
2099263508Sdim  }
2100263508Sdim
2101234353Sdim  // Compatible tags match.
2102234353Sdim  if (TagDecl *TagX = dyn_cast<TagDecl>(X)) {
2103234353Sdim    TagDecl *TagY = cast<TagDecl>(Y);
2104234353Sdim    return (TagX->getTagKind() == TagY->getTagKind()) ||
2105243830Sdim      ((TagX->getTagKind() == TTK_Struct || TagX->getTagKind() == TTK_Class ||
2106243830Sdim        TagX->getTagKind() == TTK_Interface) &&
2107243830Sdim       (TagY->getTagKind() == TTK_Struct || TagY->getTagKind() == TTK_Class ||
2108243830Sdim        TagY->getTagKind() == TTK_Interface));
2109234353Sdim  }
2110263508Sdim
2111234353Sdim  // Functions with the same type and linkage match.
2112263508Sdim  // FIXME: This needs to cope with function template specializations,
2113263508Sdim  // merging of prototyped/non-prototyped functions, etc.
2114234353Sdim  if (FunctionDecl *FuncX = dyn_cast<FunctionDecl>(X)) {
2115234353Sdim    FunctionDecl *FuncY = cast<FunctionDecl>(Y);
2116263508Sdim    return (FuncX->getLinkageInternal() == FuncY->getLinkageInternal()) &&
2117234353Sdim      FuncX->getASTContext().hasSameType(FuncX->getType(), FuncY->getType());
2118234353Sdim  }
2119243830Sdim
2120234353Sdim  // Variables with the same type and linkage match.
2121234353Sdim  if (VarDecl *VarX = dyn_cast<VarDecl>(X)) {
2122234353Sdim    VarDecl *VarY = cast<VarDecl>(Y);
2123263508Sdim    return (VarX->getLinkageInternal() == VarY->getLinkageInternal()) &&
2124234353Sdim      VarX->getASTContext().hasSameType(VarX->getType(), VarY->getType());
2125234353Sdim  }
2126263508Sdim
2127234353Sdim  // Namespaces with the same name and inlinedness match.
2128234353Sdim  if (NamespaceDecl *NamespaceX = dyn_cast<NamespaceDecl>(X)) {
2129234353Sdim    NamespaceDecl *NamespaceY = cast<NamespaceDecl>(Y);
2130234353Sdim    return NamespaceX->isInline() == NamespaceY->isInline();
2131234353Sdim  }
2132243830Sdim
2133263508Sdim  // Identical template names and kinds match if their template parameter lists
2134263508Sdim  // and patterns match.
2135263508Sdim  if (TemplateDecl *TemplateX = dyn_cast<TemplateDecl>(X)) {
2136263508Sdim    TemplateDecl *TemplateY = cast<TemplateDecl>(Y);
2137263508Sdim    return isSameEntity(TemplateX->getTemplatedDecl(),
2138263508Sdim                        TemplateY->getTemplatedDecl()) &&
2139263508Sdim           isSameTemplateParameterList(TemplateX->getTemplateParameters(),
2140263508Sdim                                       TemplateY->getTemplateParameters());
2141263508Sdim  }
2142263508Sdim
2143263508Sdim  // Fields with the same name and the same type match.
2144263508Sdim  if (FieldDecl *FDX = dyn_cast<FieldDecl>(X)) {
2145263508Sdim    FieldDecl *FDY = cast<FieldDecl>(Y);
2146263508Sdim    // FIXME: Diagnose if the types don't match. More generally, diagnose if we
2147263508Sdim    // get a declaration in a class definition that isn't in the canonical class
2148263508Sdim    // definition.
2149263508Sdim    // FIXME: Also check the bitwidth is odr-equivalent, if any.
2150263508Sdim    return X->getASTContext().hasSameType(FDX->getType(), FDY->getType());
2151263508Sdim  }
2152263508Sdim
2153263508Sdim  // Enumerators with the same name match.
2154263508Sdim  if (isa<EnumConstantDecl>(X))
2155263508Sdim    // FIXME: Also check the value is odr-equivalent.
2156243830Sdim    return true;
2157243830Sdim
2158263508Sdim  // Using shadow declarations with the same target match.
2159263508Sdim  if (UsingShadowDecl *USX = dyn_cast<UsingShadowDecl>(X)) {
2160263508Sdim    UsingShadowDecl *USY = cast<UsingShadowDecl>(Y);
2161263508Sdim    return USX->getTargetDecl() == USY->getTargetDecl();
2162263508Sdim  }
2163263508Sdim
2164234353Sdim  // FIXME: Many other cases to implement.
2165234353Sdim  return false;
2166234353Sdim}
2167234353Sdim
2168263508Sdim/// Find the context in which we should search for previous declarations when
2169263508Sdim/// looking for declarations to merge.
2170263508Sdimstatic DeclContext *getPrimaryContextForMerging(DeclContext *DC) {
2171263508Sdim  if (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC))
2172263508Sdim    return ND->getOriginalNamespace();
2173263508Sdim
2174263508Sdim  if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC))
2175263508Sdim    return RD->getDefinition();
2176263508Sdim
2177263508Sdim  if (EnumDecl *ED = dyn_cast<EnumDecl>(DC))
2178263508Sdim    return ED->getASTContext().getLangOpts().CPlusPlus? ED->getDefinition() : 0;
2179263508Sdim
2180263508Sdim  return 0;
2181263508Sdim}
2182263508Sdim
2183234353SdimASTDeclReader::FindExistingResult::~FindExistingResult() {
2184234353Sdim  if (!AddResult || Existing)
2185234353Sdim    return;
2186263508Sdim
2187263508Sdim  DeclContext *DC = New->getDeclContext()->getRedeclContext();
2188263508Sdim  if (DC->isTranslationUnit() && Reader.SemaObj) {
2189234353Sdim    Reader.SemaObj->IdResolver.tryAddTopLevelDecl(New, New->getDeclName());
2190263508Sdim  } else if (DeclContext *MergeDC = getPrimaryContextForMerging(DC)) {
2191263508Sdim    // Add the declaration to its redeclaration context so later merging
2192263508Sdim    // lookups will find it.
2193263508Sdim    MergeDC->makeDeclVisibleInContextImpl(New, /*Internal*/true);
2194234353Sdim  }
2195234353Sdim}
2196234353Sdim
2197234353SdimASTDeclReader::FindExistingResult ASTDeclReader::findExisting(NamedDecl *D) {
2198234353Sdim  DeclarationName Name = D->getDeclName();
2199234353Sdim  if (!Name) {
2200234353Sdim    // Don't bother trying to find unnamed declarations.
2201234353Sdim    FindExistingResult Result(Reader, D, /*Existing=*/0);
2202234353Sdim    Result.suppress();
2203234353Sdim    return Result;
2204234353Sdim  }
2205263508Sdim
2206263508Sdim  // FIXME: Bail out for non-canonical declarations. We will have performed any
2207263508Sdim  // necessary merging already.
2208263508Sdim
2209234353Sdim  DeclContext *DC = D->getDeclContext()->getRedeclContext();
2210234353Sdim  if (DC->isTranslationUnit() && Reader.SemaObj) {
2211234353Sdim    IdentifierResolver &IdResolver = Reader.SemaObj->IdResolver;
2212249423Sdim
2213249423Sdim    // Temporarily consider the identifier to be up-to-date. We don't want to
2214249423Sdim    // cause additional lookups here.
2215249423Sdim    class UpToDateIdentifierRAII {
2216249423Sdim      IdentifierInfo *II;
2217249423Sdim      bool WasOutToDate;
2218249423Sdim
2219249423Sdim    public:
2220249423Sdim      explicit UpToDateIdentifierRAII(IdentifierInfo *II)
2221249423Sdim        : II(II), WasOutToDate(false)
2222249423Sdim      {
2223249423Sdim        if (II) {
2224249423Sdim          WasOutToDate = II->isOutOfDate();
2225249423Sdim          if (WasOutToDate)
2226249423Sdim            II->setOutOfDate(false);
2227249423Sdim        }
2228249423Sdim      }
2229249423Sdim
2230249423Sdim      ~UpToDateIdentifierRAII() {
2231249423Sdim        if (WasOutToDate)
2232249423Sdim          II->setOutOfDate(true);
2233249423Sdim      }
2234249423Sdim    } UpToDate(Name.getAsIdentifierInfo());
2235249423Sdim
2236234353Sdim    for (IdentifierResolver::iterator I = IdResolver.begin(Name),
2237234353Sdim                                   IEnd = IdResolver.end();
2238234353Sdim         I != IEnd; ++I) {
2239234353Sdim      if (isSameEntity(*I, D))
2240234353Sdim        return FindExistingResult(Reader, D, *I);
2241234353Sdim    }
2242263508Sdim  } else if (DeclContext *MergeDC = getPrimaryContextForMerging(DC)) {
2243263508Sdim    DeclContext::lookup_result R = MergeDC->noload_lookup(Name);
2244263508Sdim    for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
2245249423Sdim      if (isSameEntity(*I, D))
2246249423Sdim        return FindExistingResult(Reader, D, *I);
2247234353Sdim    }
2248263508Sdim  } else {
2249263508Sdim    // Not in a mergeable context.
2250263508Sdim    return FindExistingResult(Reader);
2251234353Sdim  }
2252263508Sdim
2253263508Sdim  // If this declaration is from a merged context, make a note that we need to
2254263508Sdim  // check that the canonical definition of that context contains the decl.
2255263508Sdim  if (Reader.MergedDeclContexts.count(D->getLexicalDeclContext()))
2256263508Sdim    Reader.PendingOdrMergeChecks.push_back(D);
2257263508Sdim
2258234353Sdim  return FindExistingResult(Reader, D, /*Existing=*/0);
2259234353Sdim}
2260234353Sdim
2261218893Sdimvoid ASTDeclReader::attachPreviousDecl(Decl *D, Decl *previous) {
2262218893Sdim  assert(D && previous);
2263218893Sdim  if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
2264239462Sdim    TD->RedeclLink.setNext(cast<TagDecl>(previous));
2265218893Sdim  } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2266239462Sdim    FD->RedeclLink.setNext(cast<FunctionDecl>(previous));
2267218893Sdim  } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2268239462Sdim    VD->RedeclLink.setNext(cast<VarDecl>(previous));
2269234353Sdim  } else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
2270239462Sdim    TD->RedeclLink.setNext(cast<TypedefNameDecl>(previous));
2271263508Sdim  } else if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D)) {
2272263508Sdim    USD->RedeclLink.setNext(cast<UsingShadowDecl>(previous));
2273234353Sdim  } else if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
2274239462Sdim    ID->RedeclLink.setNext(cast<ObjCInterfaceDecl>(previous));
2275234353Sdim  } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
2276239462Sdim    PD->RedeclLink.setNext(cast<ObjCProtocolDecl>(previous));
2277234353Sdim  } else if (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(D)) {
2278239462Sdim    ND->RedeclLink.setNext(cast<NamespaceDecl>(previous));
2279218893Sdim  } else {
2280218893Sdim    RedeclarableTemplateDecl *TD = cast<RedeclarableTemplateDecl>(D);
2281239462Sdim    TD->RedeclLink.setNext(cast<RedeclarableTemplateDecl>(previous));
2282218893Sdim  }
2283263508Sdim
2284263508Sdim  // If the declaration was visible in one module, a redeclaration of it in
2285263508Sdim  // another module remains visible even if it wouldn't be visible by itself.
2286263508Sdim  //
2287263508Sdim  // FIXME: In this case, the declaration should only be visible if a module
2288263508Sdim  //        that makes it visible has been imported.
2289263508Sdim  D->IdentifierNamespace |=
2290263508Sdim      previous->IdentifierNamespace &
2291263508Sdim      (Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Type);
2292218893Sdim}
2293218893Sdim
2294234353Sdimvoid ASTDeclReader::attachLatestDecl(Decl *D, Decl *Latest) {
2295234353Sdim  assert(D && Latest);
2296234353Sdim  if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
2297234353Sdim    TD->RedeclLink
2298234353Sdim      = Redeclarable<TagDecl>::LatestDeclLink(cast<TagDecl>(Latest));
2299234353Sdim  } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2300263508Sdim    FD->RedeclLink
2301234353Sdim      = Redeclarable<FunctionDecl>::LatestDeclLink(cast<FunctionDecl>(Latest));
2302234353Sdim  } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2303234353Sdim    VD->RedeclLink
2304234353Sdim      = Redeclarable<VarDecl>::LatestDeclLink(cast<VarDecl>(Latest));
2305234353Sdim  } else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
2306234353Sdim    TD->RedeclLink
2307234353Sdim      = Redeclarable<TypedefNameDecl>::LatestDeclLink(
2308234353Sdim                                                cast<TypedefNameDecl>(Latest));
2309263508Sdim  } else if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D)) {
2310263508Sdim    USD->RedeclLink
2311263508Sdim      = Redeclarable<UsingShadowDecl>::LatestDeclLink(
2312263508Sdim                                             cast<UsingShadowDecl>(Latest));
2313234353Sdim  } else if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
2314234353Sdim    ID->RedeclLink
2315234353Sdim      = Redeclarable<ObjCInterfaceDecl>::LatestDeclLink(
2316234353Sdim                                              cast<ObjCInterfaceDecl>(Latest));
2317234353Sdim  } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
2318234353Sdim    PD->RedeclLink
2319234353Sdim      = Redeclarable<ObjCProtocolDecl>::LatestDeclLink(
2320234353Sdim                                                cast<ObjCProtocolDecl>(Latest));
2321234353Sdim  } else if (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(D)) {
2322234353Sdim    ND->RedeclLink
2323234353Sdim      = Redeclarable<NamespaceDecl>::LatestDeclLink(
2324234353Sdim                                                   cast<NamespaceDecl>(Latest));
2325234353Sdim  } else {
2326234353Sdim    RedeclarableTemplateDecl *TD = cast<RedeclarableTemplateDecl>(D);
2327234353Sdim    TD->RedeclLink
2328234353Sdim      = Redeclarable<RedeclarableTemplateDecl>::LatestDeclLink(
2329234353Sdim                                        cast<RedeclarableTemplateDecl>(Latest));
2330234353Sdim  }
2331234353Sdim}
2332234353Sdim
2333234353SdimASTReader::MergedDeclsMap::iterator
2334234353SdimASTReader::combineStoredMergedDecls(Decl *Canon, GlobalDeclID CanonID) {
2335234353Sdim  // If we don't have any stored merged declarations, just look in the
2336234353Sdim  // merged declarations set.
2337234353Sdim  StoredMergedDeclsMap::iterator StoredPos = StoredMergedDecls.find(CanonID);
2338234353Sdim  if (StoredPos == StoredMergedDecls.end())
2339234353Sdim    return MergedDecls.find(Canon);
2340234353Sdim
2341234353Sdim  // Append the stored merged declarations to the merged declarations set.
2342234353Sdim  MergedDeclsMap::iterator Pos = MergedDecls.find(Canon);
2343234353Sdim  if (Pos == MergedDecls.end())
2344234353Sdim    Pos = MergedDecls.insert(std::make_pair(Canon,
2345234353Sdim                                            SmallVector<DeclID, 2>())).first;
2346234353Sdim  Pos->second.append(StoredPos->second.begin(), StoredPos->second.end());
2347234353Sdim  StoredMergedDecls.erase(StoredPos);
2348234353Sdim
2349234353Sdim  // Sort and uniquify the set of merged declarations.
2350234353Sdim  llvm::array_pod_sort(Pos->second.begin(), Pos->second.end());
2351234353Sdim  Pos->second.erase(std::unique(Pos->second.begin(), Pos->second.end()),
2352234353Sdim                    Pos->second.end());
2353234353Sdim  return Pos;
2354234353Sdim}
2355234353Sdim
2356212795Sdim/// \brief Read the declaration at the given offset from the AST file.
2357226633SdimDecl *ASTReader::ReadDeclRecord(DeclID ID) {
2358226633Sdim  unsigned Index = ID - NUM_PREDEF_DECL_IDS;
2359234353Sdim  unsigned RawLocation = 0;
2360234353Sdim  RecordLocation Loc = DeclCursorForID(ID, RawLocation);
2361218893Sdim  llvm::BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
2362212795Sdim  // Keep track of where we are in the stream, then jump back there
2363212795Sdim  // after reading this declaration.
2364212795Sdim  SavedStreamPosition SavedPosition(DeclsCursor);
2365212795Sdim
2366212795Sdim  ReadingKindTracker ReadingKind(Read_Decl, *this);
2367212795Sdim
2368212795Sdim  // Note that we are loading a declaration record.
2369212795Sdim  Deserializing ADecl(this);
2370212795Sdim
2371218893Sdim  DeclsCursor.JumpToBit(Loc.Offset);
2372212795Sdim  RecordData Record;
2373212795Sdim  unsigned Code = DeclsCursor.ReadCode();
2374212795Sdim  unsigned Idx = 0;
2375243830Sdim  ASTDeclReader Reader(*this, *Loc.F, ID, RawLocation, Record,Idx);
2376212795Sdim
2377212795Sdim  Decl *D = 0;
2378249423Sdim  switch ((DeclCode)DeclsCursor.readRecord(Code, Record)) {
2379212795Sdim  case DECL_CONTEXT_LEXICAL:
2380212795Sdim  case DECL_CONTEXT_VISIBLE:
2381226633Sdim    llvm_unreachable("Record cannot be de-serialized with ReadDeclRecord");
2382212795Sdim  case DECL_TYPEDEF:
2383234353Sdim    D = TypedefDecl::CreateDeserialized(Context, ID);
2384212795Sdim    break;
2385221345Sdim  case DECL_TYPEALIAS:
2386234353Sdim    D = TypeAliasDecl::CreateDeserialized(Context, ID);
2387221345Sdim    break;
2388212795Sdim  case DECL_ENUM:
2389234353Sdim    D = EnumDecl::CreateDeserialized(Context, ID);
2390212795Sdim    break;
2391212795Sdim  case DECL_RECORD:
2392234353Sdim    D = RecordDecl::CreateDeserialized(Context, ID);
2393212795Sdim    break;
2394212795Sdim  case DECL_ENUM_CONSTANT:
2395234353Sdim    D = EnumConstantDecl::CreateDeserialized(Context, ID);
2396212795Sdim    break;
2397212795Sdim  case DECL_FUNCTION:
2398234353Sdim    D = FunctionDecl::CreateDeserialized(Context, ID);
2399212795Sdim    break;
2400212795Sdim  case DECL_LINKAGE_SPEC:
2401234353Sdim    D = LinkageSpecDecl::CreateDeserialized(Context, ID);
2402212795Sdim    break;
2403218893Sdim  case DECL_LABEL:
2404234353Sdim    D = LabelDecl::CreateDeserialized(Context, ID);
2405218893Sdim    break;
2406212795Sdim  case DECL_NAMESPACE:
2407234353Sdim    D = NamespaceDecl::CreateDeserialized(Context, ID);
2408212795Sdim    break;
2409212795Sdim  case DECL_NAMESPACE_ALIAS:
2410234353Sdim    D = NamespaceAliasDecl::CreateDeserialized(Context, ID);
2411212795Sdim    break;
2412212795Sdim  case DECL_USING:
2413234353Sdim    D = UsingDecl::CreateDeserialized(Context, ID);
2414212795Sdim    break;
2415212795Sdim  case DECL_USING_SHADOW:
2416234353Sdim    D = UsingShadowDecl::CreateDeserialized(Context, ID);
2417212795Sdim    break;
2418212795Sdim  case DECL_USING_DIRECTIVE:
2419234353Sdim    D = UsingDirectiveDecl::CreateDeserialized(Context, ID);
2420212795Sdim    break;
2421212795Sdim  case DECL_UNRESOLVED_USING_VALUE:
2422234353Sdim    D = UnresolvedUsingValueDecl::CreateDeserialized(Context, ID);
2423212795Sdim    break;
2424212795Sdim  case DECL_UNRESOLVED_USING_TYPENAME:
2425234353Sdim    D = UnresolvedUsingTypenameDecl::CreateDeserialized(Context, ID);
2426212795Sdim    break;
2427212795Sdim  case DECL_CXX_RECORD:
2428234353Sdim    D = CXXRecordDecl::CreateDeserialized(Context, ID);
2429212795Sdim    break;
2430212795Sdim  case DECL_CXX_METHOD:
2431234353Sdim    D = CXXMethodDecl::CreateDeserialized(Context, ID);
2432212795Sdim    break;
2433212795Sdim  case DECL_CXX_CONSTRUCTOR:
2434234353Sdim    D = CXXConstructorDecl::CreateDeserialized(Context, ID);
2435212795Sdim    break;
2436212795Sdim  case DECL_CXX_DESTRUCTOR:
2437234353Sdim    D = CXXDestructorDecl::CreateDeserialized(Context, ID);
2438212795Sdim    break;
2439212795Sdim  case DECL_CXX_CONVERSION:
2440234353Sdim    D = CXXConversionDecl::CreateDeserialized(Context, ID);
2441212795Sdim    break;
2442212795Sdim  case DECL_ACCESS_SPEC:
2443234353Sdim    D = AccessSpecDecl::CreateDeserialized(Context, ID);
2444212795Sdim    break;
2445212795Sdim  case DECL_FRIEND:
2446249423Sdim    D = FriendDecl::CreateDeserialized(Context, ID, Record[Idx++]);
2447212795Sdim    break;
2448212795Sdim  case DECL_FRIEND_TEMPLATE:
2449234353Sdim    D = FriendTemplateDecl::CreateDeserialized(Context, ID);
2450212795Sdim    break;
2451212795Sdim  case DECL_CLASS_TEMPLATE:
2452234353Sdim    D = ClassTemplateDecl::CreateDeserialized(Context, ID);
2453212795Sdim    break;
2454212795Sdim  case DECL_CLASS_TEMPLATE_SPECIALIZATION:
2455234353Sdim    D = ClassTemplateSpecializationDecl::CreateDeserialized(Context, ID);
2456212795Sdim    break;
2457212795Sdim  case DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION:
2458234353Sdim    D = ClassTemplatePartialSpecializationDecl::CreateDeserialized(Context, ID);
2459212795Sdim    break;
2460263508Sdim  case DECL_VAR_TEMPLATE:
2461263508Sdim    D = VarTemplateDecl::CreateDeserialized(Context, ID);
2462263508Sdim    break;
2463263508Sdim  case DECL_VAR_TEMPLATE_SPECIALIZATION:
2464263508Sdim    D = VarTemplateSpecializationDecl::CreateDeserialized(Context, ID);
2465263508Sdim    break;
2466263508Sdim  case DECL_VAR_TEMPLATE_PARTIAL_SPECIALIZATION:
2467263508Sdim    D = VarTemplatePartialSpecializationDecl::CreateDeserialized(Context, ID);
2468263508Sdim    break;
2469226633Sdim  case DECL_CLASS_SCOPE_FUNCTION_SPECIALIZATION:
2470234353Sdim    D = ClassScopeFunctionSpecializationDecl::CreateDeserialized(Context, ID);
2471226633Sdim    break;
2472212795Sdim  case DECL_FUNCTION_TEMPLATE:
2473234353Sdim    D = FunctionTemplateDecl::CreateDeserialized(Context, ID);
2474212795Sdim    break;
2475212795Sdim  case DECL_TEMPLATE_TYPE_PARM:
2476234353Sdim    D = TemplateTypeParmDecl::CreateDeserialized(Context, ID);
2477212795Sdim    break;
2478212795Sdim  case DECL_NON_TYPE_TEMPLATE_PARM:
2479234353Sdim    D = NonTypeTemplateParmDecl::CreateDeserialized(Context, ID);
2480212795Sdim    break;
2481218893Sdim  case DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK:
2482234353Sdim    D = NonTypeTemplateParmDecl::CreateDeserialized(Context, ID, Record[Idx++]);
2483218893Sdim    break;
2484212795Sdim  case DECL_TEMPLATE_TEMPLATE_PARM:
2485234353Sdim    D = TemplateTemplateParmDecl::CreateDeserialized(Context, ID);
2486212795Sdim    break;
2487243830Sdim  case DECL_EXPANDED_TEMPLATE_TEMPLATE_PARM_PACK:
2488243830Sdim    D = TemplateTemplateParmDecl::CreateDeserialized(Context, ID,
2489243830Sdim                                                     Record[Idx++]);
2490243830Sdim    break;
2491223017Sdim  case DECL_TYPE_ALIAS_TEMPLATE:
2492234353Sdim    D = TypeAliasTemplateDecl::CreateDeserialized(Context, ID);
2493223017Sdim    break;
2494212795Sdim  case DECL_STATIC_ASSERT:
2495234353Sdim    D = StaticAssertDecl::CreateDeserialized(Context, ID);
2496212795Sdim    break;
2497212795Sdim  case DECL_OBJC_METHOD:
2498234353Sdim    D = ObjCMethodDecl::CreateDeserialized(Context, ID);
2499212795Sdim    break;
2500212795Sdim  case DECL_OBJC_INTERFACE:
2501234353Sdim    D = ObjCInterfaceDecl::CreateDeserialized(Context, ID);
2502212795Sdim    break;
2503212795Sdim  case DECL_OBJC_IVAR:
2504234353Sdim    D = ObjCIvarDecl::CreateDeserialized(Context, ID);
2505212795Sdim    break;
2506212795Sdim  case DECL_OBJC_PROTOCOL:
2507234353Sdim    D = ObjCProtocolDecl::CreateDeserialized(Context, ID);
2508212795Sdim    break;
2509212795Sdim  case DECL_OBJC_AT_DEFS_FIELD:
2510234353Sdim    D = ObjCAtDefsFieldDecl::CreateDeserialized(Context, ID);
2511212795Sdim    break;
2512212795Sdim  case DECL_OBJC_CATEGORY:
2513234353Sdim    D = ObjCCategoryDecl::CreateDeserialized(Context, ID);
2514212795Sdim    break;
2515212795Sdim  case DECL_OBJC_CATEGORY_IMPL:
2516234353Sdim    D = ObjCCategoryImplDecl::CreateDeserialized(Context, ID);
2517212795Sdim    break;
2518212795Sdim  case DECL_OBJC_IMPLEMENTATION:
2519234353Sdim    D = ObjCImplementationDecl::CreateDeserialized(Context, ID);
2520212795Sdim    break;
2521212795Sdim  case DECL_OBJC_COMPATIBLE_ALIAS:
2522234353Sdim    D = ObjCCompatibleAliasDecl::CreateDeserialized(Context, ID);
2523212795Sdim    break;
2524212795Sdim  case DECL_OBJC_PROPERTY:
2525234353Sdim    D = ObjCPropertyDecl::CreateDeserialized(Context, ID);
2526212795Sdim    break;
2527212795Sdim  case DECL_OBJC_PROPERTY_IMPL:
2528234353Sdim    D = ObjCPropertyImplDecl::CreateDeserialized(Context, ID);
2529212795Sdim    break;
2530212795Sdim  case DECL_FIELD:
2531234353Sdim    D = FieldDecl::CreateDeserialized(Context, ID);
2532212795Sdim    break;
2533218893Sdim  case DECL_INDIRECTFIELD:
2534234353Sdim    D = IndirectFieldDecl::CreateDeserialized(Context, ID);
2535218893Sdim    break;
2536212795Sdim  case DECL_VAR:
2537234353Sdim    D = VarDecl::CreateDeserialized(Context, ID);
2538212795Sdim    break;
2539212795Sdim  case DECL_IMPLICIT_PARAM:
2540234353Sdim    D = ImplicitParamDecl::CreateDeserialized(Context, ID);
2541212795Sdim    break;
2542212795Sdim  case DECL_PARM_VAR:
2543234353Sdim    D = ParmVarDecl::CreateDeserialized(Context, ID);
2544212795Sdim    break;
2545212795Sdim  case DECL_FILE_SCOPE_ASM:
2546234353Sdim    D = FileScopeAsmDecl::CreateDeserialized(Context, ID);
2547212795Sdim    break;
2548212795Sdim  case DECL_BLOCK:
2549234353Sdim    D = BlockDecl::CreateDeserialized(Context, ID);
2550212795Sdim    break;
2551251662Sdim  case DECL_MS_PROPERTY:
2552251662Sdim    D = MSPropertyDecl::CreateDeserialized(Context, ID);
2553251662Sdim    break;
2554251662Sdim  case DECL_CAPTURED:
2555251662Sdim    D = CapturedDecl::CreateDeserialized(Context, ID, Record[Idx++]);
2556251662Sdim    break;
2557218893Sdim  case DECL_CXX_BASE_SPECIFIERS:
2558218893Sdim    Error("attempt to read a C++ base-specifier record as a declaration");
2559218893Sdim    return 0;
2560234353Sdim  case DECL_IMPORT:
2561234353Sdim    // Note: last entry of the ImportDecl record is the number of stored source
2562234353Sdim    // locations.
2563234353Sdim    D = ImportDecl::CreateDeserialized(Context, ID, Record.back());
2564234353Sdim    break;
2565249423Sdim  case DECL_OMP_THREADPRIVATE:
2566249423Sdim    D = OMPThreadPrivateDecl::CreateDeserialized(Context, ID, Record[Idx++]);
2567249423Sdim    break;
2568249423Sdim  case DECL_EMPTY:
2569249423Sdim    D = EmptyDecl::CreateDeserialized(Context, ID);
2570249423Sdim    break;
2571212795Sdim  }
2572212795Sdim
2573212795Sdim  assert(D && "Unknown declaration reading AST file");
2574212795Sdim  LoadedDecl(Index, D);
2575234353Sdim  // Set the DeclContext before doing any deserialization, to make sure internal
2576234353Sdim  // calls to Decl::getASTContext() by Decl's methods will find the
2577234353Sdim  // TranslationUnitDecl without crashing.
2578234353Sdim  D->setDeclContext(Context.getTranslationUnitDecl());
2579212795Sdim  Reader.Visit(D);
2580212795Sdim
2581212795Sdim  // If this declaration is also a declaration context, get the
2582212795Sdim  // offsets for its tables of lexical and visible declarations.
2583212795Sdim  if (DeclContext *DC = dyn_cast<DeclContext>(D)) {
2584249423Sdim    // FIXME: This should really be
2585249423Sdim    //     DeclContext *LookupDC = DC->getPrimaryContext();
2586249423Sdim    // but that can walk the redeclaration chain, which might not work yet.
2587249423Sdim    DeclContext *LookupDC = DC;
2588249423Sdim    if (isa<NamespaceDecl>(DC))
2589249423Sdim      LookupDC = DC->getPrimaryContext();
2590212795Sdim    std::pair<uint64_t, uint64_t> Offsets = Reader.VisitDeclContext(DC);
2591212795Sdim    if (Offsets.first || Offsets.second) {
2592226633Sdim      if (Offsets.first != 0)
2593226633Sdim        DC->setHasExternalLexicalStorage(true);
2594226633Sdim      if (Offsets.second != 0)
2595249423Sdim        LookupDC->setHasExternalVisibleStorage(true);
2596226633Sdim      if (ReadDeclContextStorage(*Loc.F, DeclsCursor, Offsets,
2597226633Sdim                                 Loc.F->DeclContextInfos[DC]))
2598212795Sdim        return 0;
2599221345Sdim    }
2600212795Sdim
2601221345Sdim    // Now add the pending visible updates for this decl context, if it has any.
2602221345Sdim    DeclContextVisibleUpdatesPending::iterator I =
2603221345Sdim        PendingVisibleUpdates.find(ID);
2604221345Sdim    if (I != PendingVisibleUpdates.end()) {
2605221345Sdim      // There are updates. This means the context has external visible
2606221345Sdim      // storage, even if the original stored version didn't.
2607249423Sdim      LookupDC->setHasExternalVisibleStorage(true);
2608221345Sdim      DeclContextVisibleUpdates &U = I->second;
2609221345Sdim      for (DeclContextVisibleUpdates::iterator UI = U.begin(), UE = U.end();
2610221345Sdim           UI != UE; ++UI) {
2611234982Sdim        DeclContextInfo &Info = UI->second->DeclContextInfos[DC];
2612234982Sdim        delete Info.NameLookupTableData;
2613234982Sdim        Info.NameLookupTableData = UI->first;
2614212795Sdim      }
2615221345Sdim      PendingVisibleUpdates.erase(I);
2616212795Sdim    }
2617212795Sdim  }
2618218893Sdim  assert(Idx == Record.size());
2619212795Sdim
2620226633Sdim  // Load any relevant update records.
2621226633Sdim  loadDeclUpdateRecords(ID, D);
2622234353Sdim
2623234353Sdim  // Load the categories after recursive loading is finished.
2624234353Sdim  if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
2625234353Sdim    if (Class->isThisDeclarationADefinition())
2626234353Sdim      loadObjCCategories(ID, Class);
2627226633Sdim
2628226633Sdim  // If we have deserialized a declaration that has a definition the
2629226633Sdim  // AST consumer might need to know about, queue it.
2630226633Sdim  // We don't pass it to the consumer immediately because we may be in recursive
2631226633Sdim  // loading, and some declarations may still be initializing.
2632243830Sdim  if (isConsumerInterestedIn(D, Reader.hasPendingBody()))
2633234353Sdim    InterestingDecls.push_back(D);
2634243830Sdim
2635226633Sdim  return D;
2636226633Sdim}
2637226633Sdim
2638226633Sdimvoid ASTReader::loadDeclUpdateRecords(serialization::DeclID ID, Decl *D) {
2639218893Sdim  // The declaration may have been modified by files later in the chain.
2640218893Sdim  // If this is the case, read the record containing the updates from each file
2641218893Sdim  // and pass it to ASTDeclReader to make the modifications.
2642218893Sdim  DeclUpdateOffsetsMap::iterator UpdI = DeclUpdateOffsets.find(ID);
2643218893Sdim  if (UpdI != DeclUpdateOffsets.end()) {
2644218893Sdim    FileOffsetsTy &UpdateOffsets = UpdI->second;
2645218893Sdim    for (FileOffsetsTy::iterator
2646226633Sdim         I = UpdateOffsets.begin(), E = UpdateOffsets.end(); I != E; ++I) {
2647234353Sdim      ModuleFile *F = I->first;
2648218893Sdim      uint64_t Offset = I->second;
2649218893Sdim      llvm::BitstreamCursor &Cursor = F->DeclsCursor;
2650218893Sdim      SavedStreamPosition SavedPosition(Cursor);
2651218893Sdim      Cursor.JumpToBit(Offset);
2652218893Sdim      RecordData Record;
2653218893Sdim      unsigned Code = Cursor.ReadCode();
2654249423Sdim      unsigned RecCode = Cursor.readRecord(Code, Record);
2655218893Sdim      (void)RecCode;
2656218893Sdim      assert(RecCode == DECL_UPDATES && "Expected DECL_UPDATES record!");
2657226633Sdim
2658226633Sdim      unsigned Idx = 0;
2659243830Sdim      ASTDeclReader Reader(*this, *F, ID, 0, Record, Idx);
2660221345Sdim      Reader.UpdateDecl(D, *F, Record);
2661212795Sdim    }
2662212795Sdim  }
2663226633Sdim}
2664212795Sdim
2665226633Sdimnamespace {
2666234353Sdim  struct CompareLocalRedeclarationsInfoToID {
2667234353Sdim    bool operator()(const LocalRedeclarationsInfo &X, DeclID Y) {
2668234353Sdim      return X.FirstID < Y;
2669234353Sdim    }
2670212795Sdim
2671234353Sdim    bool operator()(DeclID X, const LocalRedeclarationsInfo &Y) {
2672234353Sdim      return X < Y.FirstID;
2673234353Sdim    }
2674226633Sdim
2675234353Sdim    bool operator()(const LocalRedeclarationsInfo &X,
2676234353Sdim                    const LocalRedeclarationsInfo &Y) {
2677234353Sdim      return X.FirstID < Y.FirstID;
2678226633Sdim    }
2679234353Sdim    bool operator()(DeclID X, DeclID Y) {
2680234353Sdim      return X < Y;
2681234353Sdim    }
2682234353Sdim  };
2683234353Sdim
2684234353Sdim  /// \brief Module visitor class that finds all of the redeclarations of a
2685234353Sdim  ///
2686234353Sdim  class RedeclChainVisitor {
2687234353Sdim    ASTReader &Reader;
2688234353Sdim    SmallVectorImpl<DeclID> &SearchDecls;
2689234353Sdim    llvm::SmallPtrSet<Decl *, 16> &Deserialized;
2690234353Sdim    GlobalDeclID CanonID;
2691249423Sdim    SmallVector<Decl *, 4> Chain;
2692234353Sdim
2693234353Sdim  public:
2694234353Sdim    RedeclChainVisitor(ASTReader &Reader, SmallVectorImpl<DeclID> &SearchDecls,
2695234353Sdim                       llvm::SmallPtrSet<Decl *, 16> &Deserialized,
2696234353Sdim                       GlobalDeclID CanonID)
2697234353Sdim      : Reader(Reader), SearchDecls(SearchDecls), Deserialized(Deserialized),
2698234353Sdim        CanonID(CanonID) {
2699234353Sdim      for (unsigned I = 0, N = SearchDecls.size(); I != N; ++I)
2700234353Sdim        addToChain(Reader.GetDecl(SearchDecls[I]));
2701234353Sdim    }
2702234353Sdim
2703234353Sdim    static bool visit(ModuleFile &M, bool Preorder, void *UserData) {
2704234353Sdim      if (Preorder)
2705226633Sdim        return false;
2706234353Sdim
2707234353Sdim      return static_cast<RedeclChainVisitor *>(UserData)->visit(M);
2708234353Sdim    }
2709234353Sdim
2710234353Sdim    void addToChain(Decl *D) {
2711234353Sdim      if (!D)
2712234353Sdim        return;
2713234353Sdim
2714243830Sdim      if (Deserialized.erase(D))
2715234353Sdim        Chain.push_back(D);
2716234353Sdim    }
2717234353Sdim
2718234353Sdim    void searchForID(ModuleFile &M, GlobalDeclID GlobalID) {
2719234353Sdim      // Map global ID of the first declaration down to the local ID
2720234353Sdim      // used in this module file.
2721234353Sdim      DeclID ID = Reader.mapGlobalIDToModuleFileGlobalID(M, GlobalID);
2722234353Sdim      if (!ID)
2723234353Sdim        return;
2724234353Sdim
2725234353Sdim      // Perform a binary search to find the local redeclarations for this
2726234353Sdim      // declaration (if any).
2727234353Sdim      const LocalRedeclarationsInfo *Result
2728234353Sdim        = std::lower_bound(M.RedeclarationsMap,
2729234353Sdim                           M.RedeclarationsMap + M.LocalNumRedeclarationsInMap,
2730234353Sdim                           ID, CompareLocalRedeclarationsInfoToID());
2731234353Sdim      if (Result == M.RedeclarationsMap + M.LocalNumRedeclarationsInMap ||
2732234353Sdim          Result->FirstID != ID) {
2733234353Sdim        // If we have a previously-canonical singleton declaration that was
2734234353Sdim        // merged into another redeclaration chain, create a trivial chain
2735234353Sdim        // for this single declaration so that it will get wired into the
2736234353Sdim        // complete redeclaration chain.
2737234353Sdim        if (GlobalID != CanonID &&
2738234353Sdim            GlobalID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
2739234353Sdim            GlobalID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls) {
2740234353Sdim          addToChain(Reader.GetDecl(GlobalID));
2741234353Sdim        }
2742234353Sdim
2743234353Sdim        return;
2744234353Sdim      }
2745234353Sdim
2746234353Sdim      // Dig out all of the redeclarations.
2747234353Sdim      unsigned Offset = Result->Offset;
2748234353Sdim      unsigned N = M.RedeclarationChains[Offset];
2749234353Sdim      M.RedeclarationChains[Offset++] = 0; // Don't try to deserialize again
2750234353Sdim      for (unsigned I = 0; I != N; ++I)
2751234353Sdim        addToChain(Reader.GetLocalDecl(M, M.RedeclarationChains[Offset++]));
2752234353Sdim    }
2753234353Sdim
2754234353Sdim    bool visit(ModuleFile &M) {
2755234353Sdim      // Visit each of the declarations.
2756234353Sdim      for (unsigned I = 0, N = SearchDecls.size(); I != N; ++I)
2757234353Sdim        searchForID(M, SearchDecls[I]);
2758234353Sdim      return false;
2759234353Sdim    }
2760234353Sdim
2761234353Sdim    ArrayRef<Decl *> getChain() const {
2762234353Sdim      return Chain;
2763234353Sdim    }
2764234353Sdim  };
2765234353Sdim}
2766226633Sdim
2767234353Sdimvoid ASTReader::loadPendingDeclChain(serialization::GlobalDeclID ID) {
2768234353Sdim  Decl *D = GetDecl(ID);
2769234353Sdim  Decl *CanonDecl = D->getCanonicalDecl();
2770234353Sdim
2771234353Sdim  // Determine the set of declaration IDs we'll be searching for.
2772249423Sdim  SmallVector<DeclID, 1> SearchDecls;
2773234353Sdim  GlobalDeclID CanonID = 0;
2774234353Sdim  if (D == CanonDecl) {
2775234353Sdim    SearchDecls.push_back(ID); // Always first.
2776234353Sdim    CanonID = ID;
2777234353Sdim  }
2778234353Sdim  MergedDeclsMap::iterator MergedPos = combineStoredMergedDecls(CanonDecl, ID);
2779234353Sdim  if (MergedPos != MergedDecls.end())
2780243830Sdim    SearchDecls.append(MergedPos->second.begin(), MergedPos->second.end());
2781234353Sdim
2782234353Sdim  // Build up the list of redeclarations.
2783234353Sdim  RedeclChainVisitor Visitor(*this, SearchDecls, RedeclsDeserialized, CanonID);
2784234353Sdim  ModuleMgr.visitDepthFirst(&RedeclChainVisitor::visit, &Visitor);
2785234353Sdim
2786234353Sdim  // Retrieve the chains.
2787234353Sdim  ArrayRef<Decl *> Chain = Visitor.getChain();
2788234353Sdim  if (Chain.empty())
2789234353Sdim    return;
2790234353Sdim
2791234353Sdim  // Hook up the chains.
2792234353Sdim  Decl *MostRecent = CanonDecl->getMostRecentDecl();
2793234353Sdim  for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
2794234353Sdim    if (Chain[I] == CanonDecl)
2795234353Sdim      continue;
2796263508Sdim
2797234353Sdim    ASTDeclReader::attachPreviousDecl(Chain[I], MostRecent);
2798234353Sdim    MostRecent = Chain[I];
2799234353Sdim  }
2800234353Sdim
2801234353Sdim  ASTDeclReader::attachLatestDecl(CanonDecl, MostRecent);
2802234353Sdim}
2803226633Sdim
2804234353Sdimnamespace {
2805234353Sdim  struct CompareObjCCategoriesInfo {
2806234353Sdim    bool operator()(const ObjCCategoriesInfo &X, DeclID Y) {
2807234353Sdim      return X.DefinitionID < Y;
2808226633Sdim    }
2809234353Sdim
2810234353Sdim    bool operator()(DeclID X, const ObjCCategoriesInfo &Y) {
2811234353Sdim      return X < Y.DefinitionID;
2812234353Sdim    }
2813234353Sdim
2814234353Sdim    bool operator()(const ObjCCategoriesInfo &X,
2815234353Sdim                    const ObjCCategoriesInfo &Y) {
2816234353Sdim      return X.DefinitionID < Y.DefinitionID;
2817234353Sdim    }
2818234353Sdim    bool operator()(DeclID X, DeclID Y) {
2819234353Sdim      return X < Y;
2820234353Sdim    }
2821234353Sdim  };
2822226633Sdim
2823234353Sdim  /// \brief Given an ObjC interface, goes through the modules and links to the
2824234353Sdim  /// interface all the categories for it.
2825234353Sdim  class ObjCCategoriesVisitor {
2826234353Sdim    ASTReader &Reader;
2827234353Sdim    serialization::GlobalDeclID InterfaceID;
2828234353Sdim    ObjCInterfaceDecl *Interface;
2829234353Sdim    llvm::SmallPtrSet<ObjCCategoryDecl *, 16> &Deserialized;
2830234353Sdim    unsigned PreviousGeneration;
2831234353Sdim    ObjCCategoryDecl *Tail;
2832234353Sdim    llvm::DenseMap<DeclarationName, ObjCCategoryDecl *> NameCategoryMap;
2833234353Sdim
2834234353Sdim    void add(ObjCCategoryDecl *Cat) {
2835234353Sdim      // Only process each category once.
2836243830Sdim      if (!Deserialized.erase(Cat))
2837226633Sdim        return;
2838234353Sdim
2839234353Sdim      // Check for duplicate categories.
2840234353Sdim      if (Cat->getDeclName()) {
2841234353Sdim        ObjCCategoryDecl *&Existing = NameCategoryMap[Cat->getDeclName()];
2842234353Sdim        if (Existing &&
2843234353Sdim            Reader.getOwningModuleFile(Existing)
2844234353Sdim                                          != Reader.getOwningModuleFile(Cat)) {
2845234353Sdim          // FIXME: We should not warn for duplicates in diamond:
2846234353Sdim          //
2847234353Sdim          //   MT     //
2848234353Sdim          //  /  \    //
2849234353Sdim          // ML  MR   //
2850234353Sdim          //  \  /    //
2851234353Sdim          //   MB     //
2852234353Sdim          //
2853234353Sdim          // If there are duplicates in ML/MR, there will be warning when
2854234353Sdim          // creating MB *and* when importing MB. We should not warn when
2855234353Sdim          // importing.
2856234353Sdim          Reader.Diag(Cat->getLocation(), diag::warn_dup_category_def)
2857234353Sdim            << Interface->getDeclName() << Cat->getDeclName();
2858234353Sdim          Reader.Diag(Existing->getLocation(), diag::note_previous_definition);
2859234353Sdim        } else if (!Existing) {
2860234353Sdim          // Record this category.
2861234353Sdim          Existing = Cat;
2862234353Sdim        }
2863226633Sdim      }
2864234353Sdim
2865234353Sdim      // Add this category to the end of the chain.
2866234353Sdim      if (Tail)
2867234353Sdim        ASTDeclReader::setNextObjCCategory(Tail, Cat);
2868234353Sdim      else
2869249423Sdim        Interface->setCategoryListRaw(Cat);
2870234353Sdim      Tail = Cat;
2871234353Sdim    }
2872234353Sdim
2873234353Sdim  public:
2874234353Sdim    ObjCCategoriesVisitor(ASTReader &Reader,
2875234353Sdim                          serialization::GlobalDeclID InterfaceID,
2876234353Sdim                          ObjCInterfaceDecl *Interface,
2877234353Sdim                        llvm::SmallPtrSet<ObjCCategoryDecl *, 16> &Deserialized,
2878234353Sdim                          unsigned PreviousGeneration)
2879234353Sdim      : Reader(Reader), InterfaceID(InterfaceID), Interface(Interface),
2880234353Sdim        Deserialized(Deserialized), PreviousGeneration(PreviousGeneration),
2881234353Sdim        Tail(0)
2882234353Sdim    {
2883234353Sdim      // Populate the name -> category map with the set of known categories.
2884249423Sdim      for (ObjCInterfaceDecl::known_categories_iterator
2885249423Sdim             Cat = Interface->known_categories_begin(),
2886249423Sdim             CatEnd = Interface->known_categories_end();
2887249423Sdim           Cat != CatEnd; ++Cat) {
2888234353Sdim        if (Cat->getDeclName())
2889249423Sdim          NameCategoryMap[Cat->getDeclName()] = *Cat;
2890234353Sdim
2891234353Sdim        // Keep track of the tail of the category list.
2892249423Sdim        Tail = *Cat;
2893226633Sdim      }
2894234353Sdim    }
2895226633Sdim
2896234353Sdim    static bool visit(ModuleFile &M, void *UserData) {
2897234353Sdim      return static_cast<ObjCCategoriesVisitor *>(UserData)->visit(M);
2898226633Sdim    }
2899226633Sdim
2900234353Sdim    bool visit(ModuleFile &M) {
2901234353Sdim      // If we've loaded all of the category information we care about from
2902234353Sdim      // this module file, we're done.
2903234353Sdim      if (M.Generation <= PreviousGeneration)
2904234353Sdim        return true;
2905234353Sdim
2906234353Sdim      // Map global ID of the definition down to the local ID used in this
2907234353Sdim      // module file. If there is no such mapping, we'll find nothing here
2908234353Sdim      // (or in any module it imports).
2909234353Sdim      DeclID LocalID = Reader.mapGlobalIDToModuleFileGlobalID(M, InterfaceID);
2910234353Sdim      if (!LocalID)
2911234353Sdim        return true;
2912226633Sdim
2913234353Sdim      // Perform a binary search to find the local redeclarations for this
2914234353Sdim      // declaration (if any).
2915234353Sdim      const ObjCCategoriesInfo *Result
2916234353Sdim        = std::lower_bound(M.ObjCCategoriesMap,
2917234353Sdim                           M.ObjCCategoriesMap + M.LocalNumObjCCategoriesInMap,
2918234353Sdim                           LocalID, CompareObjCCategoriesInfo());
2919234353Sdim      if (Result == M.ObjCCategoriesMap + M.LocalNumObjCCategoriesInMap ||
2920234353Sdim          Result->DefinitionID != LocalID) {
2921234353Sdim        // We didn't find anything. If the class definition is in this module
2922234353Sdim        // file, then the module files it depends on cannot have any categories,
2923234353Sdim        // so suppress further lookup.
2924234353Sdim        return Reader.isDeclIDFromModule(InterfaceID, M);
2925226633Sdim      }
2926234353Sdim
2927234353Sdim      // We found something. Dig out all of the categories.
2928234353Sdim      unsigned Offset = Result->Offset;
2929234353Sdim      unsigned N = M.ObjCCategories[Offset];
2930234353Sdim      M.ObjCCategories[Offset++] = 0; // Don't try to deserialize again
2931234353Sdim      for (unsigned I = 0; I != N; ++I)
2932234353Sdim        add(cast_or_null<ObjCCategoryDecl>(
2933234353Sdim              Reader.GetLocalDecl(M, M.ObjCCategories[Offset++])));
2934234353Sdim      return true;
2935226633Sdim    }
2936226633Sdim  };
2937212795Sdim}
2938218893Sdim
2939234353Sdimvoid ASTReader::loadObjCCategories(serialization::GlobalDeclID ID,
2940234353Sdim                                   ObjCInterfaceDecl *D,
2941234353Sdim                                   unsigned PreviousGeneration) {
2942234353Sdim  ObjCCategoriesVisitor Visitor(*this, ID, D, CategoriesDeserialized,
2943234353Sdim                                PreviousGeneration);
2944234353Sdim  ModuleMgr.visit(ObjCCategoriesVisitor::visit, &Visitor);
2945226633Sdim}
2946226633Sdim
2947234353Sdimvoid ASTDeclReader::UpdateDecl(Decl *D, ModuleFile &ModuleFile,
2948221345Sdim                               const RecordData &Record) {
2949218893Sdim  unsigned Idx = 0;
2950218893Sdim  while (Idx < Record.size()) {
2951218893Sdim    switch ((DeclUpdateKind)Record[Idx++]) {
2952218893Sdim    case UPD_CXX_ADDED_IMPLICIT_MEMBER:
2953234353Sdim      cast<CXXRecordDecl>(D)->addedMember(Reader.ReadDecl(ModuleFile, Record, Idx));
2954218893Sdim      break;
2955218893Sdim
2956218893Sdim    case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
2957218893Sdim      // It will be added to the template's specializations set when loaded.
2958234353Sdim      (void)Reader.ReadDecl(ModuleFile, Record, Idx);
2959221345Sdim      break;
2960221345Sdim
2961221345Sdim    case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE: {
2962226633Sdim      NamespaceDecl *Anon
2963234353Sdim        = Reader.ReadDeclAs<NamespaceDecl>(ModuleFile, Record, Idx);
2964234353Sdim
2965234353Sdim      // Each module has its own anonymous namespace, which is disjoint from
2966234353Sdim      // any other module's anonymous namespaces, so don't attach the anonymous
2967234353Sdim      // namespace at all.
2968234353Sdim      if (ModuleFile.Kind != MK_Module) {
2969221345Sdim        if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(D))
2970221345Sdim          TU->setAnonymousNamespace(Anon);
2971221345Sdim        else
2972234353Sdim          cast<NamespaceDecl>(D)->setAnonymousNamespace(Anon);
2973221345Sdim      }
2974221345Sdim      break;
2975218893Sdim    }
2976221345Sdim
2977221345Sdim    case UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER:
2978221345Sdim      cast<VarDecl>(D)->getMemberSpecializationInfo()->setPointOfInstantiation(
2979234353Sdim          Reader.ReadSourceLocation(ModuleFile, Record, Idx));
2980221345Sdim      break;
2981263508Sdim
2982263508Sdim    case UPD_CXX_DEDUCED_RETURN_TYPE: {
2983263508Sdim      FunctionDecl *FD = cast<FunctionDecl>(D);
2984263508Sdim      Reader.Context.adjustDeducedFunctionResultType(
2985263508Sdim          FD, Reader.readType(ModuleFile, Record, Idx));
2986263508Sdim      break;
2987221345Sdim    }
2988263508Sdim
2989263508Sdim    case UPD_DECL_MARKED_USED: {
2990263508Sdim      // FIXME: This doesn't send the right notifications if there are
2991263508Sdim      // ASTMutationListeners other than an ASTWriter.
2992263508Sdim      D->Used = true;
2993263508Sdim      break;
2994263508Sdim    }
2995263508Sdim    }
2996218893Sdim  }
2997218893Sdim}
2998