1//===- ASTReaderDecl.cpp - Decl Deserialization ---------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the ASTReader::readDeclRecord method, which is the
10// entrypoint for loading a decl.
11//
12//===----------------------------------------------------------------------===//
13
14#include "ASTCommon.h"
15#include "ASTReaderInternals.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/Attr.h"
18#include "clang/AST/AttrIterator.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/DeclBase.h"
21#include "clang/AST/DeclCXX.h"
22#include "clang/AST/DeclFriend.h"
23#include "clang/AST/DeclObjC.h"
24#include "clang/AST/DeclOpenMP.h"
25#include "clang/AST/DeclTemplate.h"
26#include "clang/AST/DeclVisitor.h"
27#include "clang/AST/DeclarationName.h"
28#include "clang/AST/Expr.h"
29#include "clang/AST/ExternalASTSource.h"
30#include "clang/AST/LambdaCapture.h"
31#include "clang/AST/NestedNameSpecifier.h"
32#include "clang/AST/OpenMPClause.h"
33#include "clang/AST/Redeclarable.h"
34#include "clang/AST/Stmt.h"
35#include "clang/AST/TemplateBase.h"
36#include "clang/AST/Type.h"
37#include "clang/AST/UnresolvedSet.h"
38#include "clang/Basic/AttrKinds.h"
39#include "clang/Basic/ExceptionSpecificationType.h"
40#include "clang/Basic/IdentifierTable.h"
41#include "clang/Basic/LLVM.h"
42#include "clang/Basic/Lambda.h"
43#include "clang/Basic/LangOptions.h"
44#include "clang/Basic/Linkage.h"
45#include "clang/Basic/Module.h"
46#include "clang/Basic/PragmaKinds.h"
47#include "clang/Basic/SourceLocation.h"
48#include "clang/Basic/Specifiers.h"
49#include "clang/Sema/IdentifierResolver.h"
50#include "clang/Serialization/ASTBitCodes.h"
51#include "clang/Serialization/ASTRecordReader.h"
52#include "clang/Serialization/ContinuousRangeMap.h"
53#include "clang/Serialization/ModuleFile.h"
54#include "llvm/ADT/DenseMap.h"
55#include "llvm/ADT/FoldingSet.h"
56#include "llvm/ADT/STLExtras.h"
57#include "llvm/ADT/SmallPtrSet.h"
58#include "llvm/ADT/SmallVector.h"
59#include "llvm/ADT/iterator_range.h"
60#include "llvm/Bitstream/BitstreamReader.h"
61#include "llvm/Support/Casting.h"
62#include "llvm/Support/ErrorHandling.h"
63#include "llvm/Support/SaveAndRestore.h"
64#include <algorithm>
65#include <cassert>
66#include <cstdint>
67#include <cstring>
68#include <string>
69#include <utility>
70
71using namespace clang;
72using namespace serialization;
73
74//===----------------------------------------------------------------------===//
75// Declaration deserialization
76//===----------------------------------------------------------------------===//
77
78namespace clang {
79
80  class ASTDeclReader : public DeclVisitor<ASTDeclReader, void> {
81    ASTReader &Reader;
82    ASTRecordReader &Record;
83    ASTReader::RecordLocation Loc;
84    const DeclID ThisDeclID;
85    const SourceLocation ThisDeclLoc;
86
87    using RecordData = ASTReader::RecordData;
88
89    TypeID DeferredTypeID = 0;
90    unsigned AnonymousDeclNumber;
91    GlobalDeclID NamedDeclForTagDecl = 0;
92    IdentifierInfo *TypedefNameForLinkage = nullptr;
93
94    bool HasPendingBody = false;
95
96    ///A flag to carry the information for a decl from the entity is
97    /// used. We use it to delay the marking of the canonical decl as used until
98    /// the entire declaration is deserialized and merged.
99    bool IsDeclMarkedUsed = false;
100
101    uint64_t GetCurrentCursorOffset();
102
103    uint64_t ReadLocalOffset() {
104      uint64_t LocalOffset = Record.readInt();
105      assert(LocalOffset < Loc.Offset && "offset point after current record");
106      return LocalOffset ? Loc.Offset - LocalOffset : 0;
107    }
108
109    uint64_t ReadGlobalOffset() {
110      uint64_t Local = ReadLocalOffset();
111      return Local ? Record.getGlobalBitOffset(Local) : 0;
112    }
113
114    SourceLocation readSourceLocation() {
115      return Record.readSourceLocation();
116    }
117
118    SourceRange readSourceRange() {
119      return Record.readSourceRange();
120    }
121
122    TypeSourceInfo *readTypeSourceInfo() {
123      return Record.readTypeSourceInfo();
124    }
125
126    serialization::DeclID readDeclID() {
127      return Record.readDeclID();
128    }
129
130    std::string readString() {
131      return Record.readString();
132    }
133
134    void readDeclIDList(SmallVectorImpl<DeclID> &IDs) {
135      for (unsigned I = 0, Size = Record.readInt(); I != Size; ++I)
136        IDs.push_back(readDeclID());
137    }
138
139    Decl *readDecl() {
140      return Record.readDecl();
141    }
142
143    template<typename T>
144    T *readDeclAs() {
145      return Record.readDeclAs<T>();
146    }
147
148    serialization::SubmoduleID readSubmoduleID() {
149      if (Record.getIdx() == Record.size())
150        return 0;
151
152      return Record.getGlobalSubmoduleID(Record.readInt());
153    }
154
155    Module *readModule() {
156      return Record.getSubmodule(readSubmoduleID());
157    }
158
159    void ReadCXXRecordDefinition(CXXRecordDecl *D, bool Update);
160    void ReadCXXDefinitionData(struct CXXRecordDecl::DefinitionData &Data,
161                               const CXXRecordDecl *D);
162    void MergeDefinitionData(CXXRecordDecl *D,
163                             struct CXXRecordDecl::DefinitionData &&NewDD);
164    void ReadObjCDefinitionData(struct ObjCInterfaceDecl::DefinitionData &Data);
165    void MergeDefinitionData(ObjCInterfaceDecl *D,
166                             struct ObjCInterfaceDecl::DefinitionData &&NewDD);
167    void ReadObjCDefinitionData(struct ObjCProtocolDecl::DefinitionData &Data);
168    void MergeDefinitionData(ObjCProtocolDecl *D,
169                             struct ObjCProtocolDecl::DefinitionData &&NewDD);
170
171    static DeclContext *getPrimaryDCForAnonymousDecl(DeclContext *LexicalDC);
172
173    static NamedDecl *getAnonymousDeclForMerging(ASTReader &Reader,
174                                                 DeclContext *DC,
175                                                 unsigned Index);
176    static void setAnonymousDeclForMerging(ASTReader &Reader, DeclContext *DC,
177                                           unsigned Index, NamedDecl *D);
178
179    /// Results from loading a RedeclarableDecl.
180    class RedeclarableResult {
181      Decl *MergeWith;
182      GlobalDeclID FirstID;
183      bool IsKeyDecl;
184
185    public:
186      RedeclarableResult(Decl *MergeWith, GlobalDeclID FirstID, bool IsKeyDecl)
187          : MergeWith(MergeWith), FirstID(FirstID), IsKeyDecl(IsKeyDecl) {}
188
189      /// Retrieve the first ID.
190      GlobalDeclID getFirstID() const { return FirstID; }
191
192      /// Is this declaration a key declaration?
193      bool isKeyDecl() const { return IsKeyDecl; }
194
195      /// Get a known declaration that this should be merged with, if
196      /// any.
197      Decl *getKnownMergeTarget() const { return MergeWith; }
198    };
199
200    /// Class used to capture the result of searching for an existing
201    /// declaration of a specific kind and name, along with the ability
202    /// to update the place where this result was found (the declaration
203    /// chain hanging off an identifier or the DeclContext we searched in)
204    /// if requested.
205    class FindExistingResult {
206      ASTReader &Reader;
207      NamedDecl *New = nullptr;
208      NamedDecl *Existing = nullptr;
209      bool AddResult = false;
210      unsigned AnonymousDeclNumber = 0;
211      IdentifierInfo *TypedefNameForLinkage = nullptr;
212
213    public:
214      FindExistingResult(ASTReader &Reader) : Reader(Reader) {}
215
216      FindExistingResult(ASTReader &Reader, NamedDecl *New, NamedDecl *Existing,
217                         unsigned AnonymousDeclNumber,
218                         IdentifierInfo *TypedefNameForLinkage)
219          : Reader(Reader), New(New), Existing(Existing), AddResult(true),
220            AnonymousDeclNumber(AnonymousDeclNumber),
221            TypedefNameForLinkage(TypedefNameForLinkage) {}
222
223      FindExistingResult(FindExistingResult &&Other)
224          : Reader(Other.Reader), New(Other.New), Existing(Other.Existing),
225            AddResult(Other.AddResult),
226            AnonymousDeclNumber(Other.AnonymousDeclNumber),
227            TypedefNameForLinkage(Other.TypedefNameForLinkage) {
228        Other.AddResult = false;
229      }
230
231      FindExistingResult &operator=(FindExistingResult &&) = delete;
232      ~FindExistingResult();
233
234      /// Suppress the addition of this result into the known set of
235      /// names.
236      void suppress() { AddResult = false; }
237
238      operator NamedDecl*() const { return Existing; }
239
240      template<typename T>
241      operator T*() const { return dyn_cast_or_null<T>(Existing); }
242    };
243
244    static DeclContext *getPrimaryContextForMerging(ASTReader &Reader,
245                                                    DeclContext *DC);
246    FindExistingResult findExisting(NamedDecl *D);
247
248  public:
249    ASTDeclReader(ASTReader &Reader, ASTRecordReader &Record,
250                  ASTReader::RecordLocation Loc,
251                  DeclID thisDeclID, SourceLocation ThisDeclLoc)
252        : Reader(Reader), Record(Record), Loc(Loc), ThisDeclID(thisDeclID),
253          ThisDeclLoc(ThisDeclLoc) {}
254
255    template <typename T> static
256    void AddLazySpecializations(T *D,
257                                SmallVectorImpl<serialization::DeclID>& IDs) {
258      if (IDs.empty())
259        return;
260
261      // FIXME: We should avoid this pattern of getting the ASTContext.
262      ASTContext &C = D->getASTContext();
263
264      auto *&LazySpecializations = D->getCommonPtr()->LazySpecializations;
265
266      if (auto &Old = LazySpecializations) {
267        IDs.insert(IDs.end(), Old + 1, Old + 1 + Old[0]);
268        llvm::sort(IDs);
269        IDs.erase(std::unique(IDs.begin(), IDs.end()), IDs.end());
270      }
271
272      auto *Result = new (C) serialization::DeclID[1 + IDs.size()];
273      *Result = IDs.size();
274      std::copy(IDs.begin(), IDs.end(), Result + 1);
275
276      LazySpecializations = Result;
277    }
278
279    template <typename DeclT>
280    static Decl *getMostRecentDeclImpl(Redeclarable<DeclT> *D);
281    static Decl *getMostRecentDeclImpl(...);
282    static Decl *getMostRecentDecl(Decl *D);
283
284    template <typename DeclT>
285    static void attachPreviousDeclImpl(ASTReader &Reader,
286                                       Redeclarable<DeclT> *D, Decl *Previous,
287                                       Decl *Canon);
288    static void attachPreviousDeclImpl(ASTReader &Reader, ...);
289    static void attachPreviousDecl(ASTReader &Reader, Decl *D, Decl *Previous,
290                                   Decl *Canon);
291
292    template <typename DeclT>
293    static void attachLatestDeclImpl(Redeclarable<DeclT> *D, Decl *Latest);
294    static void attachLatestDeclImpl(...);
295    static void attachLatestDecl(Decl *D, Decl *latest);
296
297    template <typename DeclT>
298    static void markIncompleteDeclChainImpl(Redeclarable<DeclT> *D);
299    static void markIncompleteDeclChainImpl(...);
300
301    /// Determine whether this declaration has a pending body.
302    bool hasPendingBody() const { return HasPendingBody; }
303
304    void ReadFunctionDefinition(FunctionDecl *FD);
305    void Visit(Decl *D);
306
307    void UpdateDecl(Decl *D, SmallVectorImpl<serialization::DeclID> &);
308
309    static void setNextObjCCategory(ObjCCategoryDecl *Cat,
310                                    ObjCCategoryDecl *Next) {
311      Cat->NextClassCategory = Next;
312    }
313
314    void VisitDecl(Decl *D);
315    void VisitPragmaCommentDecl(PragmaCommentDecl *D);
316    void VisitPragmaDetectMismatchDecl(PragmaDetectMismatchDecl *D);
317    void VisitTranslationUnitDecl(TranslationUnitDecl *TU);
318    void VisitNamedDecl(NamedDecl *ND);
319    void VisitLabelDecl(LabelDecl *LD);
320    void VisitNamespaceDecl(NamespaceDecl *D);
321    void VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
322    void VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
323    void VisitTypeDecl(TypeDecl *TD);
324    RedeclarableResult VisitTypedefNameDecl(TypedefNameDecl *TD);
325    void VisitTypedefDecl(TypedefDecl *TD);
326    void VisitTypeAliasDecl(TypeAliasDecl *TD);
327    void VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
328    RedeclarableResult VisitTagDecl(TagDecl *TD);
329    void VisitEnumDecl(EnumDecl *ED);
330    RedeclarableResult VisitRecordDeclImpl(RecordDecl *RD);
331    void VisitRecordDecl(RecordDecl *RD) { VisitRecordDeclImpl(RD); }
332    RedeclarableResult VisitCXXRecordDeclImpl(CXXRecordDecl *D);
333    void VisitCXXRecordDecl(CXXRecordDecl *D) { VisitCXXRecordDeclImpl(D); }
334    RedeclarableResult VisitClassTemplateSpecializationDeclImpl(
335                                            ClassTemplateSpecializationDecl *D);
336
337    void VisitClassTemplateSpecializationDecl(
338        ClassTemplateSpecializationDecl *D) {
339      VisitClassTemplateSpecializationDeclImpl(D);
340    }
341
342    void VisitClassTemplatePartialSpecializationDecl(
343                                     ClassTemplatePartialSpecializationDecl *D);
344    void VisitClassScopeFunctionSpecializationDecl(
345                                       ClassScopeFunctionSpecializationDecl *D);
346    RedeclarableResult
347    VisitVarTemplateSpecializationDeclImpl(VarTemplateSpecializationDecl *D);
348
349    void VisitVarTemplateSpecializationDecl(VarTemplateSpecializationDecl *D) {
350      VisitVarTemplateSpecializationDeclImpl(D);
351    }
352
353    void VisitVarTemplatePartialSpecializationDecl(
354        VarTemplatePartialSpecializationDecl *D);
355    void VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
356    void VisitValueDecl(ValueDecl *VD);
357    void VisitEnumConstantDecl(EnumConstantDecl *ECD);
358    void VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
359    void VisitDeclaratorDecl(DeclaratorDecl *DD);
360    void VisitFunctionDecl(FunctionDecl *FD);
361    void VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *GD);
362    void VisitCXXMethodDecl(CXXMethodDecl *D);
363    void VisitCXXConstructorDecl(CXXConstructorDecl *D);
364    void VisitCXXDestructorDecl(CXXDestructorDecl *D);
365    void VisitCXXConversionDecl(CXXConversionDecl *D);
366    void VisitFieldDecl(FieldDecl *FD);
367    void VisitMSPropertyDecl(MSPropertyDecl *FD);
368    void VisitMSGuidDecl(MSGuidDecl *D);
369    void VisitIndirectFieldDecl(IndirectFieldDecl *FD);
370    RedeclarableResult VisitVarDeclImpl(VarDecl *D);
371    void VisitVarDecl(VarDecl *VD) { VisitVarDeclImpl(VD); }
372    void VisitImplicitParamDecl(ImplicitParamDecl *PD);
373    void VisitParmVarDecl(ParmVarDecl *PD);
374    void VisitDecompositionDecl(DecompositionDecl *DD);
375    void VisitBindingDecl(BindingDecl *BD);
376    void VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
377    DeclID VisitTemplateDecl(TemplateDecl *D);
378    void VisitConceptDecl(ConceptDecl *D);
379    void VisitRequiresExprBodyDecl(RequiresExprBodyDecl *D);
380    RedeclarableResult VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D);
381    void VisitClassTemplateDecl(ClassTemplateDecl *D);
382    void VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D);
383    void VisitVarTemplateDecl(VarTemplateDecl *D);
384    void VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
385    void VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
386    void VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D);
387    void VisitUsingDecl(UsingDecl *D);
388    void VisitUsingPackDecl(UsingPackDecl *D);
389    void VisitUsingShadowDecl(UsingShadowDecl *D);
390    void VisitConstructorUsingShadowDecl(ConstructorUsingShadowDecl *D);
391    void VisitLinkageSpecDecl(LinkageSpecDecl *D);
392    void VisitExportDecl(ExportDecl *D);
393    void VisitFileScopeAsmDecl(FileScopeAsmDecl *AD);
394    void VisitImportDecl(ImportDecl *D);
395    void VisitAccessSpecDecl(AccessSpecDecl *D);
396    void VisitFriendDecl(FriendDecl *D);
397    void VisitFriendTemplateDecl(FriendTemplateDecl *D);
398    void VisitStaticAssertDecl(StaticAssertDecl *D);
399    void VisitBlockDecl(BlockDecl *BD);
400    void VisitCapturedDecl(CapturedDecl *CD);
401    void VisitEmptyDecl(EmptyDecl *D);
402    void VisitLifetimeExtendedTemporaryDecl(LifetimeExtendedTemporaryDecl *D);
403
404    std::pair<uint64_t, uint64_t> VisitDeclContext(DeclContext *DC);
405
406    template<typename T>
407    RedeclarableResult VisitRedeclarable(Redeclarable<T> *D);
408
409    template<typename T>
410    void mergeRedeclarable(Redeclarable<T> *D, RedeclarableResult &Redecl,
411                           DeclID TemplatePatternID = 0);
412
413    template<typename T>
414    void mergeRedeclarable(Redeclarable<T> *D, T *Existing,
415                           RedeclarableResult &Redecl,
416                           DeclID TemplatePatternID = 0);
417
418    template<typename T>
419    void mergeMergeable(Mergeable<T> *D);
420
421    void mergeMergeable(LifetimeExtendedTemporaryDecl *D);
422
423    void mergeTemplatePattern(RedeclarableTemplateDecl *D,
424                              RedeclarableTemplateDecl *Existing,
425                              DeclID DsID, bool IsKeyDecl);
426
427    ObjCTypeParamList *ReadObjCTypeParamList();
428
429    // FIXME: Reorder according to DeclNodes.td?
430    void VisitObjCMethodDecl(ObjCMethodDecl *D);
431    void VisitObjCTypeParamDecl(ObjCTypeParamDecl *D);
432    void VisitObjCContainerDecl(ObjCContainerDecl *D);
433    void VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
434    void VisitObjCIvarDecl(ObjCIvarDecl *D);
435    void VisitObjCProtocolDecl(ObjCProtocolDecl *D);
436    void VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D);
437    void VisitObjCCategoryDecl(ObjCCategoryDecl *D);
438    void VisitObjCImplDecl(ObjCImplDecl *D);
439    void VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
440    void VisitObjCImplementationDecl(ObjCImplementationDecl *D);
441    void VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *D);
442    void VisitObjCPropertyDecl(ObjCPropertyDecl *D);
443    void VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D);
444    void VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D);
445    void VisitOMPAllocateDecl(OMPAllocateDecl *D);
446    void VisitOMPDeclareReductionDecl(OMPDeclareReductionDecl *D);
447    void VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D);
448    void VisitOMPRequiresDecl(OMPRequiresDecl *D);
449    void VisitOMPCapturedExprDecl(OMPCapturedExprDecl *D);
450  };
451
452} // namespace clang
453
454namespace {
455
456/// Iterator over the redeclarations of a declaration that have already
457/// been merged into the same redeclaration chain.
458template<typename DeclT>
459class MergedRedeclIterator {
460  DeclT *Start;
461  DeclT *Canonical = nullptr;
462  DeclT *Current = nullptr;
463
464public:
465  MergedRedeclIterator() = default;
466  MergedRedeclIterator(DeclT *Start) : Start(Start), Current(Start) {}
467
468  DeclT *operator*() { return Current; }
469
470  MergedRedeclIterator &operator++() {
471    if (Current->isFirstDecl()) {
472      Canonical = Current;
473      Current = Current->getMostRecentDecl();
474    } else
475      Current = Current->getPreviousDecl();
476
477    // If we started in the merged portion, we'll reach our start position
478    // eventually. Otherwise, we'll never reach it, but the second declaration
479    // we reached was the canonical declaration, so stop when we see that one
480    // again.
481    if (Current == Start || Current == Canonical)
482      Current = nullptr;
483    return *this;
484  }
485
486  friend bool operator!=(const MergedRedeclIterator &A,
487                         const MergedRedeclIterator &B) {
488    return A.Current != B.Current;
489  }
490};
491
492} // namespace
493
494template <typename DeclT>
495static llvm::iterator_range<MergedRedeclIterator<DeclT>>
496merged_redecls(DeclT *D) {
497  return llvm::make_range(MergedRedeclIterator<DeclT>(D),
498                          MergedRedeclIterator<DeclT>());
499}
500
501uint64_t ASTDeclReader::GetCurrentCursorOffset() {
502  return Loc.F->DeclsCursor.GetCurrentBitNo() + Loc.F->GlobalBitOffset;
503}
504
505void ASTDeclReader::ReadFunctionDefinition(FunctionDecl *FD) {
506  if (Record.readInt()) {
507    Reader.DefinitionSource[FD] = Loc.F->Kind == ModuleKind::MK_MainFile;
508    if (Reader.getContext().getLangOpts().BuildingPCHWithObjectFile &&
509        Reader.DeclIsFromPCHWithObjectFile(FD))
510      Reader.DefinitionSource[FD] = true;
511  }
512  if (auto *CD = dyn_cast<CXXConstructorDecl>(FD)) {
513    CD->setNumCtorInitializers(Record.readInt());
514    if (CD->getNumCtorInitializers())
515      CD->CtorInitializers = ReadGlobalOffset();
516  }
517  // Store the offset of the body so we can lazily load it later.
518  Reader.PendingBodies[FD] = GetCurrentCursorOffset();
519  HasPendingBody = true;
520}
521
522void ASTDeclReader::Visit(Decl *D) {
523  DeclVisitor<ASTDeclReader, void>::Visit(D);
524
525  // At this point we have deserialized and merged the decl and it is safe to
526  // update its canonical decl to signal that the entire entity is used.
527  D->getCanonicalDecl()->Used |= IsDeclMarkedUsed;
528  IsDeclMarkedUsed = false;
529
530  if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
531    if (auto *TInfo = DD->getTypeSourceInfo())
532      Record.readTypeLoc(TInfo->getTypeLoc());
533  }
534
535  if (auto *TD = dyn_cast<TypeDecl>(D)) {
536    // We have a fully initialized TypeDecl. Read its type now.
537    TD->setTypeForDecl(Reader.GetType(DeferredTypeID).getTypePtrOrNull());
538
539    // If this is a tag declaration with a typedef name for linkage, it's safe
540    // to load that typedef now.
541    if (NamedDeclForTagDecl)
542      cast<TagDecl>(D)->TypedefNameDeclOrQualifier =
543          cast<TypedefNameDecl>(Reader.GetDecl(NamedDeclForTagDecl));
544  } else if (auto *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
545    // if we have a fully initialized TypeDecl, we can safely read its type now.
546    ID->TypeForDecl = Reader.GetType(DeferredTypeID).getTypePtrOrNull();
547  } else if (auto *FD = dyn_cast<FunctionDecl>(D)) {
548    // FunctionDecl's body was written last after all other Stmts/Exprs.
549    // We only read it if FD doesn't already have a body (e.g., from another
550    // module).
551    // FIXME: Can we diagnose ODR violations somehow?
552    if (Record.readInt())
553      ReadFunctionDefinition(FD);
554  }
555}
556
557void ASTDeclReader::VisitDecl(Decl *D) {
558  if (D->isTemplateParameter() || D->isTemplateParameterPack() ||
559      isa<ParmVarDecl>(D) || isa<ObjCTypeParamDecl>(D)) {
560    // We don't want to deserialize the DeclContext of a template
561    // parameter or of a parameter of a function template immediately.   These
562    // entities might be used in the formulation of its DeclContext (for
563    // example, a function parameter can be used in decltype() in trailing
564    // return type of the function).  Use the translation unit DeclContext as a
565    // placeholder.
566    GlobalDeclID SemaDCIDForTemplateParmDecl = readDeclID();
567    GlobalDeclID LexicalDCIDForTemplateParmDecl = readDeclID();
568    if (!LexicalDCIDForTemplateParmDecl)
569      LexicalDCIDForTemplateParmDecl = SemaDCIDForTemplateParmDecl;
570    Reader.addPendingDeclContextInfo(D,
571                                     SemaDCIDForTemplateParmDecl,
572                                     LexicalDCIDForTemplateParmDecl);
573    D->setDeclContext(Reader.getContext().getTranslationUnitDecl());
574  } else {
575    auto *SemaDC = readDeclAs<DeclContext>();
576    auto *LexicalDC = readDeclAs<DeclContext>();
577    if (!LexicalDC)
578      LexicalDC = SemaDC;
579    DeclContext *MergedSemaDC = Reader.MergedDeclContexts.lookup(SemaDC);
580    // Avoid calling setLexicalDeclContext() directly because it uses
581    // Decl::getASTContext() internally which is unsafe during derialization.
582    D->setDeclContextsImpl(MergedSemaDC ? MergedSemaDC : SemaDC, LexicalDC,
583                           Reader.getContext());
584  }
585  D->setLocation(ThisDeclLoc);
586  D->InvalidDecl = Record.readInt();
587  if (Record.readInt()) { // hasAttrs
588    AttrVec Attrs;
589    Record.readAttributes(Attrs);
590    // Avoid calling setAttrs() directly because it uses Decl::getASTContext()
591    // internally which is unsafe during derialization.
592    D->setAttrsImpl(Attrs, Reader.getContext());
593  }
594  D->setImplicit(Record.readInt());
595  D->Used = Record.readInt();
596  IsDeclMarkedUsed |= D->Used;
597  D->setReferenced(Record.readInt());
598  D->setTopLevelDeclInObjCContainer(Record.readInt());
599  D->setAccess((AccessSpecifier)Record.readInt());
600  D->FromASTFile = true;
601  bool ModulePrivate = Record.readInt();
602
603  // Determine whether this declaration is part of a (sub)module. If so, it
604  // may not yet be visible.
605  if (unsigned SubmoduleID = readSubmoduleID()) {
606    // Store the owning submodule ID in the declaration.
607    D->setModuleOwnershipKind(
608        ModulePrivate ? Decl::ModuleOwnershipKind::ModulePrivate
609                      : Decl::ModuleOwnershipKind::VisibleWhenImported);
610    D->setOwningModuleID(SubmoduleID);
611
612    if (ModulePrivate) {
613      // Module-private declarations are never visible, so there is no work to
614      // do.
615    } else if (Reader.getContext().getLangOpts().ModulesLocalVisibility) {
616      // If local visibility is being tracked, this declaration will become
617      // hidden and visible as the owning module does.
618    } else if (Module *Owner = Reader.getSubmodule(SubmoduleID)) {
619      // Mark the declaration as visible when its owning module becomes visible.
620      if (Owner->NameVisibility == Module::AllVisible)
621        D->setVisibleDespiteOwningModule();
622      else
623        Reader.HiddenNamesMap[Owner].push_back(D);
624    }
625  } else if (ModulePrivate) {
626    D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate);
627  }
628}
629
630void ASTDeclReader::VisitPragmaCommentDecl(PragmaCommentDecl *D) {
631  VisitDecl(D);
632  D->setLocation(readSourceLocation());
633  D->CommentKind = (PragmaMSCommentKind)Record.readInt();
634  std::string Arg = readString();
635  memcpy(D->getTrailingObjects<char>(), Arg.data(), Arg.size());
636  D->getTrailingObjects<char>()[Arg.size()] = '\0';
637}
638
639void ASTDeclReader::VisitPragmaDetectMismatchDecl(PragmaDetectMismatchDecl *D) {
640  VisitDecl(D);
641  D->setLocation(readSourceLocation());
642  std::string Name = readString();
643  memcpy(D->getTrailingObjects<char>(), Name.data(), Name.size());
644  D->getTrailingObjects<char>()[Name.size()] = '\0';
645
646  D->ValueStart = Name.size() + 1;
647  std::string Value = readString();
648  memcpy(D->getTrailingObjects<char>() + D->ValueStart, Value.data(),
649         Value.size());
650  D->getTrailingObjects<char>()[D->ValueStart + Value.size()] = '\0';
651}
652
653void ASTDeclReader::VisitTranslationUnitDecl(TranslationUnitDecl *TU) {
654  llvm_unreachable("Translation units are not serialized");
655}
656
657void ASTDeclReader::VisitNamedDecl(NamedDecl *ND) {
658  VisitDecl(ND);
659  ND->setDeclName(Record.readDeclarationName());
660  AnonymousDeclNumber = Record.readInt();
661}
662
663void ASTDeclReader::VisitTypeDecl(TypeDecl *TD) {
664  VisitNamedDecl(TD);
665  TD->setLocStart(readSourceLocation());
666  // Delay type reading until after we have fully initialized the decl.
667  DeferredTypeID = Record.getGlobalTypeID(Record.readInt());
668}
669
670ASTDeclReader::RedeclarableResult
671ASTDeclReader::VisitTypedefNameDecl(TypedefNameDecl *TD) {
672  RedeclarableResult Redecl = VisitRedeclarable(TD);
673  VisitTypeDecl(TD);
674  TypeSourceInfo *TInfo = readTypeSourceInfo();
675  if (Record.readInt()) { // isModed
676    QualType modedT = Record.readType();
677    TD->setModedTypeSourceInfo(TInfo, modedT);
678  } else
679    TD->setTypeSourceInfo(TInfo);
680  // Read and discard the declaration for which this is a typedef name for
681  // linkage, if it exists. We cannot rely on our type to pull in this decl,
682  // because it might have been merged with a type from another module and
683  // thus might not refer to our version of the declaration.
684  readDecl();
685  return Redecl;
686}
687
688void ASTDeclReader::VisitTypedefDecl(TypedefDecl *TD) {
689  RedeclarableResult Redecl = VisitTypedefNameDecl(TD);
690  mergeRedeclarable(TD, Redecl);
691}
692
693void ASTDeclReader::VisitTypeAliasDecl(TypeAliasDecl *TD) {
694  RedeclarableResult Redecl = VisitTypedefNameDecl(TD);
695  if (auto *Template = readDeclAs<TypeAliasTemplateDecl>())
696    // Merged when we merge the template.
697    TD->setDescribedAliasTemplate(Template);
698  else
699    mergeRedeclarable(TD, Redecl);
700}
701
702ASTDeclReader::RedeclarableResult ASTDeclReader::VisitTagDecl(TagDecl *TD) {
703  RedeclarableResult Redecl = VisitRedeclarable(TD);
704  VisitTypeDecl(TD);
705
706  TD->IdentifierNamespace = Record.readInt();
707  TD->setTagKind((TagDecl::TagKind)Record.readInt());
708  if (!isa<CXXRecordDecl>(TD))
709    TD->setCompleteDefinition(Record.readInt());
710  TD->setEmbeddedInDeclarator(Record.readInt());
711  TD->setFreeStanding(Record.readInt());
712  TD->setCompleteDefinitionRequired(Record.readInt());
713  TD->setBraceRange(readSourceRange());
714
715  switch (Record.readInt()) {
716  case 0:
717    break;
718  case 1: { // ExtInfo
719    auto *Info = new (Reader.getContext()) TagDecl::ExtInfo();
720    Record.readQualifierInfo(*Info);
721    TD->TypedefNameDeclOrQualifier = Info;
722    break;
723  }
724  case 2: // TypedefNameForAnonDecl
725    NamedDeclForTagDecl = readDeclID();
726    TypedefNameForLinkage = Record.readIdentifier();
727    break;
728  default:
729    llvm_unreachable("unexpected tag info kind");
730  }
731
732  if (!isa<CXXRecordDecl>(TD))
733    mergeRedeclarable(TD, Redecl);
734  return Redecl;
735}
736
737void ASTDeclReader::VisitEnumDecl(EnumDecl *ED) {
738  VisitTagDecl(ED);
739  if (TypeSourceInfo *TI = readTypeSourceInfo())
740    ED->setIntegerTypeSourceInfo(TI);
741  else
742    ED->setIntegerType(Record.readType());
743  ED->setPromotionType(Record.readType());
744  ED->setNumPositiveBits(Record.readInt());
745  ED->setNumNegativeBits(Record.readInt());
746  ED->setScoped(Record.readInt());
747  ED->setScopedUsingClassTag(Record.readInt());
748  ED->setFixed(Record.readInt());
749
750  ED->setHasODRHash(true);
751  ED->ODRHash = Record.readInt();
752
753  // If this is a definition subject to the ODR, and we already have a
754  // definition, merge this one into it.
755  if (ED->isCompleteDefinition() &&
756      Reader.getContext().getLangOpts().Modules &&
757      Reader.getContext().getLangOpts().CPlusPlus) {
758    EnumDecl *&OldDef = Reader.EnumDefinitions[ED->getCanonicalDecl()];
759    if (!OldDef) {
760      // This is the first time we've seen an imported definition. Look for a
761      // local definition before deciding that we are the first definition.
762      for (auto *D : merged_redecls(ED->getCanonicalDecl())) {
763        if (!D->isFromASTFile() && D->isCompleteDefinition()) {
764          OldDef = D;
765          break;
766        }
767      }
768    }
769    if (OldDef) {
770      Reader.MergedDeclContexts.insert(std::make_pair(ED, OldDef));
771      ED->setCompleteDefinition(false);
772      Reader.mergeDefinitionVisibility(OldDef, ED);
773      if (OldDef->getODRHash() != ED->getODRHash())
774        Reader.PendingEnumOdrMergeFailures[OldDef].push_back(ED);
775    } else {
776      OldDef = ED;
777    }
778  }
779
780  if (auto *InstED = readDeclAs<EnumDecl>()) {
781    auto TSK = (TemplateSpecializationKind)Record.readInt();
782    SourceLocation POI = readSourceLocation();
783    ED->setInstantiationOfMemberEnum(Reader.getContext(), InstED, TSK);
784    ED->getMemberSpecializationInfo()->setPointOfInstantiation(POI);
785  }
786}
787
788ASTDeclReader::RedeclarableResult
789ASTDeclReader::VisitRecordDeclImpl(RecordDecl *RD) {
790  RedeclarableResult Redecl = VisitTagDecl(RD);
791  RD->setHasFlexibleArrayMember(Record.readInt());
792  RD->setAnonymousStructOrUnion(Record.readInt());
793  RD->setHasObjectMember(Record.readInt());
794  RD->setHasVolatileMember(Record.readInt());
795  RD->setNonTrivialToPrimitiveDefaultInitialize(Record.readInt());
796  RD->setNonTrivialToPrimitiveCopy(Record.readInt());
797  RD->setNonTrivialToPrimitiveDestroy(Record.readInt());
798  RD->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(Record.readInt());
799  RD->setHasNonTrivialToPrimitiveDestructCUnion(Record.readInt());
800  RD->setHasNonTrivialToPrimitiveCopyCUnion(Record.readInt());
801  RD->setParamDestroyedInCallee(Record.readInt());
802  RD->setArgPassingRestrictions((RecordDecl::ArgPassingKind)Record.readInt());
803  return Redecl;
804}
805
806void ASTDeclReader::VisitValueDecl(ValueDecl *VD) {
807  VisitNamedDecl(VD);
808  // For function declarations, defer reading the type in case the function has
809  // a deduced return type that references an entity declared within the
810  // function.
811  if (isa<FunctionDecl>(VD))
812    DeferredTypeID = Record.getGlobalTypeID(Record.readInt());
813  else
814    VD->setType(Record.readType());
815}
816
817void ASTDeclReader::VisitEnumConstantDecl(EnumConstantDecl *ECD) {
818  VisitValueDecl(ECD);
819  if (Record.readInt())
820    ECD->setInitExpr(Record.readExpr());
821  ECD->setInitVal(Record.readAPSInt());
822  mergeMergeable(ECD);
823}
824
825void ASTDeclReader::VisitDeclaratorDecl(DeclaratorDecl *DD) {
826  VisitValueDecl(DD);
827  DD->setInnerLocStart(readSourceLocation());
828  if (Record.readInt()) { // hasExtInfo
829    auto *Info = new (Reader.getContext()) DeclaratorDecl::ExtInfo();
830    Record.readQualifierInfo(*Info);
831    Info->TrailingRequiresClause = Record.readExpr();
832    DD->DeclInfo = Info;
833  }
834  QualType TSIType = Record.readType();
835  DD->setTypeSourceInfo(
836      TSIType.isNull() ? nullptr
837                       : Reader.getContext().CreateTypeSourceInfo(TSIType));
838}
839
840void ASTDeclReader::VisitFunctionDecl(FunctionDecl *FD) {
841  RedeclarableResult Redecl = VisitRedeclarable(FD);
842  VisitDeclaratorDecl(FD);
843
844  // Attach a type to this function. Use the real type if possible, but fall
845  // back to the type as written if it involves a deduced return type.
846  if (FD->getTypeSourceInfo() &&
847      FD->getTypeSourceInfo()->getType()->castAs<FunctionType>()
848                             ->getReturnType()->getContainedAutoType()) {
849    // We'll set up the real type in Visit, once we've finished loading the
850    // function.
851    FD->setType(FD->getTypeSourceInfo()->getType());
852    Reader.PendingFunctionTypes.push_back({FD, DeferredTypeID});
853  } else {
854    FD->setType(Reader.GetType(DeferredTypeID));
855  }
856  DeferredTypeID = 0;
857
858  FD->DNLoc = Record.readDeclarationNameLoc(FD->getDeclName());
859  FD->IdentifierNamespace = Record.readInt();
860
861  // FunctionDecl's body is handled last at ASTDeclReader::Visit,
862  // after everything else is read.
863
864  FD->setStorageClass(static_cast<StorageClass>(Record.readInt()));
865  FD->setInlineSpecified(Record.readInt());
866  FD->setImplicitlyInline(Record.readInt());
867  FD->setVirtualAsWritten(Record.readInt());
868  FD->setPure(Record.readInt());
869  FD->setHasInheritedPrototype(Record.readInt());
870  FD->setHasWrittenPrototype(Record.readInt());
871  FD->setDeletedAsWritten(Record.readInt());
872  FD->setTrivial(Record.readInt());
873  FD->setTrivialForCall(Record.readInt());
874  FD->setDefaulted(Record.readInt());
875  FD->setExplicitlyDefaulted(Record.readInt());
876  FD->setHasImplicitReturnZero(Record.readInt());
877  FD->setConstexprKind(static_cast<ConstexprSpecKind>(Record.readInt()));
878  FD->setUsesSEHTry(Record.readInt());
879  FD->setHasSkippedBody(Record.readInt());
880  FD->setIsMultiVersion(Record.readInt());
881  FD->setLateTemplateParsed(Record.readInt());
882
883  FD->setCachedLinkage(static_cast<Linkage>(Record.readInt()));
884  FD->EndRangeLoc = readSourceLocation();
885
886  FD->ODRHash = Record.readInt();
887  FD->setHasODRHash(true);
888  FD->setUsesFPIntrin(Record.readInt());
889
890  if (FD->isDefaulted()) {
891    if (unsigned NumLookups = Record.readInt()) {
892      SmallVector<DeclAccessPair, 8> Lookups;
893      for (unsigned I = 0; I != NumLookups; ++I) {
894        NamedDecl *ND = Record.readDeclAs<NamedDecl>();
895        AccessSpecifier AS = (AccessSpecifier)Record.readInt();
896        Lookups.push_back(DeclAccessPair::make(ND, AS));
897      }
898      FD->setDefaultedFunctionInfo(FunctionDecl::DefaultedFunctionInfo::Create(
899          Reader.getContext(), Lookups));
900    }
901  }
902
903  switch ((FunctionDecl::TemplatedKind)Record.readInt()) {
904  case FunctionDecl::TK_NonTemplate:
905    mergeRedeclarable(FD, Redecl);
906    break;
907  case FunctionDecl::TK_FunctionTemplate:
908    // Merged when we merge the template.
909    FD->setDescribedFunctionTemplate(readDeclAs<FunctionTemplateDecl>());
910    break;
911  case FunctionDecl::TK_MemberSpecialization: {
912    auto *InstFD = readDeclAs<FunctionDecl>();
913    auto TSK = (TemplateSpecializationKind)Record.readInt();
914    SourceLocation POI = readSourceLocation();
915    FD->setInstantiationOfMemberFunction(Reader.getContext(), InstFD, TSK);
916    FD->getMemberSpecializationInfo()->setPointOfInstantiation(POI);
917    mergeRedeclarable(FD, Redecl);
918    break;
919  }
920  case FunctionDecl::TK_FunctionTemplateSpecialization: {
921    auto *Template = readDeclAs<FunctionTemplateDecl>();
922    auto TSK = (TemplateSpecializationKind)Record.readInt();
923
924    // Template arguments.
925    SmallVector<TemplateArgument, 8> TemplArgs;
926    Record.readTemplateArgumentList(TemplArgs, /*Canonicalize*/ true);
927
928    // Template args as written.
929    SmallVector<TemplateArgumentLoc, 8> TemplArgLocs;
930    SourceLocation LAngleLoc, RAngleLoc;
931    bool HasTemplateArgumentsAsWritten = Record.readInt();
932    if (HasTemplateArgumentsAsWritten) {
933      unsigned NumTemplateArgLocs = Record.readInt();
934      TemplArgLocs.reserve(NumTemplateArgLocs);
935      for (unsigned i = 0; i != NumTemplateArgLocs; ++i)
936        TemplArgLocs.push_back(Record.readTemplateArgumentLoc());
937
938      LAngleLoc = readSourceLocation();
939      RAngleLoc = readSourceLocation();
940    }
941
942    SourceLocation POI = readSourceLocation();
943
944    ASTContext &C = Reader.getContext();
945    TemplateArgumentList *TemplArgList
946      = TemplateArgumentList::CreateCopy(C, TemplArgs);
947    TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
948    for (unsigned i = 0, e = TemplArgLocs.size(); i != e; ++i)
949      TemplArgsInfo.addArgument(TemplArgLocs[i]);
950
951    MemberSpecializationInfo *MSInfo = nullptr;
952    if (Record.readInt()) {
953      auto *FD = readDeclAs<FunctionDecl>();
954      auto TSK = (TemplateSpecializationKind)Record.readInt();
955      SourceLocation POI = readSourceLocation();
956
957      MSInfo = new (C) MemberSpecializationInfo(FD, TSK);
958      MSInfo->setPointOfInstantiation(POI);
959    }
960
961    FunctionTemplateSpecializationInfo *FTInfo =
962        FunctionTemplateSpecializationInfo::Create(
963            C, FD, Template, TSK, TemplArgList,
964            HasTemplateArgumentsAsWritten ? &TemplArgsInfo : nullptr, POI,
965            MSInfo);
966    FD->TemplateOrSpecialization = FTInfo;
967
968    if (FD->isCanonicalDecl()) { // if canonical add to template's set.
969      // The template that contains the specializations set. It's not safe to
970      // use getCanonicalDecl on Template since it may still be initializing.
971      auto *CanonTemplate = readDeclAs<FunctionTemplateDecl>();
972      // Get the InsertPos by FindNodeOrInsertPos() instead of calling
973      // InsertNode(FTInfo) directly to avoid the getASTContext() call in
974      // FunctionTemplateSpecializationInfo's Profile().
975      // We avoid getASTContext because a decl in the parent hierarchy may
976      // be initializing.
977      llvm::FoldingSetNodeID ID;
978      FunctionTemplateSpecializationInfo::Profile(ID, TemplArgs, C);
979      void *InsertPos = nullptr;
980      FunctionTemplateDecl::Common *CommonPtr = CanonTemplate->getCommonPtr();
981      FunctionTemplateSpecializationInfo *ExistingInfo =
982          CommonPtr->Specializations.FindNodeOrInsertPos(ID, InsertPos);
983      if (InsertPos)
984        CommonPtr->Specializations.InsertNode(FTInfo, InsertPos);
985      else {
986        assert(Reader.getContext().getLangOpts().Modules &&
987               "already deserialized this template specialization");
988        mergeRedeclarable(FD, ExistingInfo->getFunction(), Redecl);
989      }
990    }
991    break;
992  }
993  case FunctionDecl::TK_DependentFunctionTemplateSpecialization: {
994    // Templates.
995    UnresolvedSet<8> TemplDecls;
996    unsigned NumTemplates = Record.readInt();
997    while (NumTemplates--)
998      TemplDecls.addDecl(readDeclAs<NamedDecl>());
999
1000    // Templates args.
1001    TemplateArgumentListInfo TemplArgs;
1002    unsigned NumArgs = Record.readInt();
1003    while (NumArgs--)
1004      TemplArgs.addArgument(Record.readTemplateArgumentLoc());
1005    TemplArgs.setLAngleLoc(readSourceLocation());
1006    TemplArgs.setRAngleLoc(readSourceLocation());
1007
1008    FD->setDependentTemplateSpecialization(Reader.getContext(),
1009                                           TemplDecls, TemplArgs);
1010    // These are not merged; we don't need to merge redeclarations of dependent
1011    // template friends.
1012    break;
1013  }
1014  }
1015
1016  // Read in the parameters.
1017  unsigned NumParams = Record.readInt();
1018  SmallVector<ParmVarDecl *, 16> Params;
1019  Params.reserve(NumParams);
1020  for (unsigned I = 0; I != NumParams; ++I)
1021    Params.push_back(readDeclAs<ParmVarDecl>());
1022  FD->setParams(Reader.getContext(), Params);
1023}
1024
1025void ASTDeclReader::VisitObjCMethodDecl(ObjCMethodDecl *MD) {
1026  VisitNamedDecl(MD);
1027  if (Record.readInt()) {
1028    // Load the body on-demand. Most clients won't care, because method
1029    // definitions rarely show up in headers.
1030    Reader.PendingBodies[MD] = GetCurrentCursorOffset();
1031    HasPendingBody = true;
1032  }
1033  MD->setSelfDecl(readDeclAs<ImplicitParamDecl>());
1034  MD->setCmdDecl(readDeclAs<ImplicitParamDecl>());
1035  MD->setInstanceMethod(Record.readInt());
1036  MD->setVariadic(Record.readInt());
1037  MD->setPropertyAccessor(Record.readInt());
1038  MD->setSynthesizedAccessorStub(Record.readInt());
1039  MD->setDefined(Record.readInt());
1040  MD->setOverriding(Record.readInt());
1041  MD->setHasSkippedBody(Record.readInt());
1042
1043  MD->setIsRedeclaration(Record.readInt());
1044  MD->setHasRedeclaration(Record.readInt());
1045  if (MD->hasRedeclaration())
1046    Reader.getContext().setObjCMethodRedeclaration(MD,
1047                                       readDeclAs<ObjCMethodDecl>());
1048
1049  MD->setDeclImplementation((ObjCMethodDecl::ImplementationControl)Record.readInt());
1050  MD->setObjCDeclQualifier((Decl::ObjCDeclQualifier)Record.readInt());
1051  MD->setRelatedResultType(Record.readInt());
1052  MD->setReturnType(Record.readType());
1053  MD->setReturnTypeSourceInfo(readTypeSourceInfo());
1054  MD->DeclEndLoc = readSourceLocation();
1055  unsigned NumParams = Record.readInt();
1056  SmallVector<ParmVarDecl *, 16> Params;
1057  Params.reserve(NumParams);
1058  for (unsigned I = 0; I != NumParams; ++I)
1059    Params.push_back(readDeclAs<ParmVarDecl>());
1060
1061  MD->setSelLocsKind((SelectorLocationsKind)Record.readInt());
1062  unsigned NumStoredSelLocs = Record.readInt();
1063  SmallVector<SourceLocation, 16> SelLocs;
1064  SelLocs.reserve(NumStoredSelLocs);
1065  for (unsigned i = 0; i != NumStoredSelLocs; ++i)
1066    SelLocs.push_back(readSourceLocation());
1067
1068  MD->setParamsAndSelLocs(Reader.getContext(), Params, SelLocs);
1069}
1070
1071void ASTDeclReader::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
1072  VisitTypedefNameDecl(D);
1073
1074  D->Variance = Record.readInt();
1075  D->Index = Record.readInt();
1076  D->VarianceLoc = readSourceLocation();
1077  D->ColonLoc = readSourceLocation();
1078}
1079
1080void ASTDeclReader::VisitObjCContainerDecl(ObjCContainerDecl *CD) {
1081  VisitNamedDecl(CD);
1082  CD->setAtStartLoc(readSourceLocation());
1083  CD->setAtEndRange(readSourceRange());
1084}
1085
1086ObjCTypeParamList *ASTDeclReader::ReadObjCTypeParamList() {
1087  unsigned numParams = Record.readInt();
1088  if (numParams == 0)
1089    return nullptr;
1090
1091  SmallVector<ObjCTypeParamDecl *, 4> typeParams;
1092  typeParams.reserve(numParams);
1093  for (unsigned i = 0; i != numParams; ++i) {
1094    auto *typeParam = readDeclAs<ObjCTypeParamDecl>();
1095    if (!typeParam)
1096      return nullptr;
1097
1098    typeParams.push_back(typeParam);
1099  }
1100
1101  SourceLocation lAngleLoc = readSourceLocation();
1102  SourceLocation rAngleLoc = readSourceLocation();
1103
1104  return ObjCTypeParamList::create(Reader.getContext(), lAngleLoc,
1105                                   typeParams, rAngleLoc);
1106}
1107
1108void ASTDeclReader::ReadObjCDefinitionData(
1109         struct ObjCInterfaceDecl::DefinitionData &Data) {
1110  // Read the superclass.
1111  Data.SuperClassTInfo = readTypeSourceInfo();
1112
1113  Data.EndLoc = readSourceLocation();
1114  Data.HasDesignatedInitializers = Record.readInt();
1115
1116  // Read the directly referenced protocols and their SourceLocations.
1117  unsigned NumProtocols = Record.readInt();
1118  SmallVector<ObjCProtocolDecl *, 16> Protocols;
1119  Protocols.reserve(NumProtocols);
1120  for (unsigned I = 0; I != NumProtocols; ++I)
1121    Protocols.push_back(readDeclAs<ObjCProtocolDecl>());
1122  SmallVector<SourceLocation, 16> ProtoLocs;
1123  ProtoLocs.reserve(NumProtocols);
1124  for (unsigned I = 0; I != NumProtocols; ++I)
1125    ProtoLocs.push_back(readSourceLocation());
1126  Data.ReferencedProtocols.set(Protocols.data(), NumProtocols, ProtoLocs.data(),
1127                               Reader.getContext());
1128
1129  // Read the transitive closure of protocols referenced by this class.
1130  NumProtocols = Record.readInt();
1131  Protocols.clear();
1132  Protocols.reserve(NumProtocols);
1133  for (unsigned I = 0; I != NumProtocols; ++I)
1134    Protocols.push_back(readDeclAs<ObjCProtocolDecl>());
1135  Data.AllReferencedProtocols.set(Protocols.data(), NumProtocols,
1136                                  Reader.getContext());
1137}
1138
1139void ASTDeclReader::MergeDefinitionData(ObjCInterfaceDecl *D,
1140         struct ObjCInterfaceDecl::DefinitionData &&NewDD) {
1141  // FIXME: odr checking?
1142}
1143
1144void ASTDeclReader::VisitObjCInterfaceDecl(ObjCInterfaceDecl *ID) {
1145  RedeclarableResult Redecl = VisitRedeclarable(ID);
1146  VisitObjCContainerDecl(ID);
1147  DeferredTypeID = Record.getGlobalTypeID(Record.readInt());
1148  mergeRedeclarable(ID, Redecl);
1149
1150  ID->TypeParamList = ReadObjCTypeParamList();
1151  if (Record.readInt()) {
1152    // Read the definition.
1153    ID->allocateDefinitionData();
1154
1155    ReadObjCDefinitionData(ID->data());
1156    ObjCInterfaceDecl *Canon = ID->getCanonicalDecl();
1157    if (Canon->Data.getPointer()) {
1158      // If we already have a definition, keep the definition invariant and
1159      // merge the data.
1160      MergeDefinitionData(Canon, std::move(ID->data()));
1161      ID->Data = Canon->Data;
1162    } else {
1163      // Set the definition data of the canonical declaration, so other
1164      // redeclarations will see it.
1165      ID->getCanonicalDecl()->Data = ID->Data;
1166
1167      // We will rebuild this list lazily.
1168      ID->setIvarList(nullptr);
1169    }
1170
1171    // Note that we have deserialized a definition.
1172    Reader.PendingDefinitions.insert(ID);
1173
1174    // Note that we've loaded this Objective-C class.
1175    Reader.ObjCClassesLoaded.push_back(ID);
1176  } else {
1177    ID->Data = ID->getCanonicalDecl()->Data;
1178  }
1179}
1180
1181void ASTDeclReader::VisitObjCIvarDecl(ObjCIvarDecl *IVD) {
1182  VisitFieldDecl(IVD);
1183  IVD->setAccessControl((ObjCIvarDecl::AccessControl)Record.readInt());
1184  // This field will be built lazily.
1185  IVD->setNextIvar(nullptr);
1186  bool synth = Record.readInt();
1187  IVD->setSynthesize(synth);
1188}
1189
1190void ASTDeclReader::ReadObjCDefinitionData(
1191         struct ObjCProtocolDecl::DefinitionData &Data) {
1192    unsigned NumProtoRefs = Record.readInt();
1193    SmallVector<ObjCProtocolDecl *, 16> ProtoRefs;
1194    ProtoRefs.reserve(NumProtoRefs);
1195    for (unsigned I = 0; I != NumProtoRefs; ++I)
1196      ProtoRefs.push_back(readDeclAs<ObjCProtocolDecl>());
1197    SmallVector<SourceLocation, 16> ProtoLocs;
1198    ProtoLocs.reserve(NumProtoRefs);
1199    for (unsigned I = 0; I != NumProtoRefs; ++I)
1200      ProtoLocs.push_back(readSourceLocation());
1201    Data.ReferencedProtocols.set(ProtoRefs.data(), NumProtoRefs,
1202                                 ProtoLocs.data(), Reader.getContext());
1203}
1204
1205void ASTDeclReader::MergeDefinitionData(ObjCProtocolDecl *D,
1206         struct ObjCProtocolDecl::DefinitionData &&NewDD) {
1207  // FIXME: odr checking?
1208}
1209
1210void ASTDeclReader::VisitObjCProtocolDecl(ObjCProtocolDecl *PD) {
1211  RedeclarableResult Redecl = VisitRedeclarable(PD);
1212  VisitObjCContainerDecl(PD);
1213  mergeRedeclarable(PD, Redecl);
1214
1215  if (Record.readInt()) {
1216    // Read the definition.
1217    PD->allocateDefinitionData();
1218
1219    ReadObjCDefinitionData(PD->data());
1220
1221    ObjCProtocolDecl *Canon = PD->getCanonicalDecl();
1222    if (Canon->Data.getPointer()) {
1223      // If we already have a definition, keep the definition invariant and
1224      // merge the data.
1225      MergeDefinitionData(Canon, std::move(PD->data()));
1226      PD->Data = Canon->Data;
1227    } else {
1228      // Set the definition data of the canonical declaration, so other
1229      // redeclarations will see it.
1230      PD->getCanonicalDecl()->Data = PD->Data;
1231    }
1232    // Note that we have deserialized a definition.
1233    Reader.PendingDefinitions.insert(PD);
1234  } else {
1235    PD->Data = PD->getCanonicalDecl()->Data;
1236  }
1237}
1238
1239void ASTDeclReader::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *FD) {
1240  VisitFieldDecl(FD);
1241}
1242
1243void ASTDeclReader::VisitObjCCategoryDecl(ObjCCategoryDecl *CD) {
1244  VisitObjCContainerDecl(CD);
1245  CD->setCategoryNameLoc(readSourceLocation());
1246  CD->setIvarLBraceLoc(readSourceLocation());
1247  CD->setIvarRBraceLoc(readSourceLocation());
1248
1249  // Note that this category has been deserialized. We do this before
1250  // deserializing the interface declaration, so that it will consider this
1251  /// category.
1252  Reader.CategoriesDeserialized.insert(CD);
1253
1254  CD->ClassInterface = readDeclAs<ObjCInterfaceDecl>();
1255  CD->TypeParamList = ReadObjCTypeParamList();
1256  unsigned NumProtoRefs = Record.readInt();
1257  SmallVector<ObjCProtocolDecl *, 16> ProtoRefs;
1258  ProtoRefs.reserve(NumProtoRefs);
1259  for (unsigned I = 0; I != NumProtoRefs; ++I)
1260    ProtoRefs.push_back(readDeclAs<ObjCProtocolDecl>());
1261  SmallVector<SourceLocation, 16> ProtoLocs;
1262  ProtoLocs.reserve(NumProtoRefs);
1263  for (unsigned I = 0; I != NumProtoRefs; ++I)
1264    ProtoLocs.push_back(readSourceLocation());
1265  CD->setProtocolList(ProtoRefs.data(), NumProtoRefs, ProtoLocs.data(),
1266                      Reader.getContext());
1267
1268  // Protocols in the class extension belong to the class.
1269  if (NumProtoRefs > 0 && CD->ClassInterface && CD->IsClassExtension())
1270    CD->ClassInterface->mergeClassExtensionProtocolList(
1271        (ObjCProtocolDecl *const *)ProtoRefs.data(), NumProtoRefs,
1272        Reader.getContext());
1273}
1274
1275void ASTDeclReader::VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *CAD) {
1276  VisitNamedDecl(CAD);
1277  CAD->setClassInterface(readDeclAs<ObjCInterfaceDecl>());
1278}
1279
1280void ASTDeclReader::VisitObjCPropertyDecl(ObjCPropertyDecl *D) {
1281  VisitNamedDecl(D);
1282  D->setAtLoc(readSourceLocation());
1283  D->setLParenLoc(readSourceLocation());
1284  QualType T = Record.readType();
1285  TypeSourceInfo *TSI = readTypeSourceInfo();
1286  D->setType(T, TSI);
1287  D->setPropertyAttributes((ObjCPropertyAttribute::Kind)Record.readInt());
1288  D->setPropertyAttributesAsWritten(
1289      (ObjCPropertyAttribute::Kind)Record.readInt());
1290  D->setPropertyImplementation(
1291      (ObjCPropertyDecl::PropertyControl)Record.readInt());
1292  DeclarationName GetterName = Record.readDeclarationName();
1293  SourceLocation GetterLoc = readSourceLocation();
1294  D->setGetterName(GetterName.getObjCSelector(), GetterLoc);
1295  DeclarationName SetterName = Record.readDeclarationName();
1296  SourceLocation SetterLoc = readSourceLocation();
1297  D->setSetterName(SetterName.getObjCSelector(), SetterLoc);
1298  D->setGetterMethodDecl(readDeclAs<ObjCMethodDecl>());
1299  D->setSetterMethodDecl(readDeclAs<ObjCMethodDecl>());
1300  D->setPropertyIvarDecl(readDeclAs<ObjCIvarDecl>());
1301}
1302
1303void ASTDeclReader::VisitObjCImplDecl(ObjCImplDecl *D) {
1304  VisitObjCContainerDecl(D);
1305  D->setClassInterface(readDeclAs<ObjCInterfaceDecl>());
1306}
1307
1308void ASTDeclReader::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
1309  VisitObjCImplDecl(D);
1310  D->CategoryNameLoc = readSourceLocation();
1311}
1312
1313void ASTDeclReader::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1314  VisitObjCImplDecl(D);
1315  D->setSuperClass(readDeclAs<ObjCInterfaceDecl>());
1316  D->SuperLoc = readSourceLocation();
1317  D->setIvarLBraceLoc(readSourceLocation());
1318  D->setIvarRBraceLoc(readSourceLocation());
1319  D->setHasNonZeroConstructors(Record.readInt());
1320  D->setHasDestructors(Record.readInt());
1321  D->NumIvarInitializers = Record.readInt();
1322  if (D->NumIvarInitializers)
1323    D->IvarInitializers = ReadGlobalOffset();
1324}
1325
1326void ASTDeclReader::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) {
1327  VisitDecl(D);
1328  D->setAtLoc(readSourceLocation());
1329  D->setPropertyDecl(readDeclAs<ObjCPropertyDecl>());
1330  D->PropertyIvarDecl = readDeclAs<ObjCIvarDecl>();
1331  D->IvarLoc = readSourceLocation();
1332  D->setGetterMethodDecl(readDeclAs<ObjCMethodDecl>());
1333  D->setSetterMethodDecl(readDeclAs<ObjCMethodDecl>());
1334  D->setGetterCXXConstructor(Record.readExpr());
1335  D->setSetterCXXAssignment(Record.readExpr());
1336}
1337
1338void ASTDeclReader::VisitFieldDecl(FieldDecl *FD) {
1339  VisitDeclaratorDecl(FD);
1340  FD->Mutable = Record.readInt();
1341
1342  if (auto ISK = static_cast<FieldDecl::InitStorageKind>(Record.readInt())) {
1343    FD->InitStorage.setInt(ISK);
1344    FD->InitStorage.setPointer(ISK == FieldDecl::ISK_CapturedVLAType
1345                                   ? Record.readType().getAsOpaquePtr()
1346                                   : Record.readExpr());
1347  }
1348
1349  if (auto *BW = Record.readExpr())
1350    FD->setBitWidth(BW);
1351
1352  if (!FD->getDeclName()) {
1353    if (auto *Tmpl = readDeclAs<FieldDecl>())
1354      Reader.getContext().setInstantiatedFromUnnamedFieldDecl(FD, Tmpl);
1355  }
1356  mergeMergeable(FD);
1357}
1358
1359void ASTDeclReader::VisitMSPropertyDecl(MSPropertyDecl *PD) {
1360  VisitDeclaratorDecl(PD);
1361  PD->GetterId = Record.readIdentifier();
1362  PD->SetterId = Record.readIdentifier();
1363}
1364
1365void ASTDeclReader::VisitMSGuidDecl(MSGuidDecl *D) {
1366  VisitValueDecl(D);
1367  D->PartVal.Part1 = Record.readInt();
1368  D->PartVal.Part2 = Record.readInt();
1369  D->PartVal.Part3 = Record.readInt();
1370  for (auto &C : D->PartVal.Part4And5)
1371    C = Record.readInt();
1372
1373  // Add this GUID to the AST context's lookup structure, and merge if needed.
1374  if (MSGuidDecl *Existing = Reader.getContext().MSGuidDecls.GetOrInsertNode(D))
1375    Reader.getContext().setPrimaryMergedDecl(D, Existing->getCanonicalDecl());
1376}
1377
1378void ASTDeclReader::VisitIndirectFieldDecl(IndirectFieldDecl *FD) {
1379  VisitValueDecl(FD);
1380
1381  FD->ChainingSize = Record.readInt();
1382  assert(FD->ChainingSize >= 2 && "Anonymous chaining must be >= 2");
1383  FD->Chaining = new (Reader.getContext())NamedDecl*[FD->ChainingSize];
1384
1385  for (unsigned I = 0; I != FD->ChainingSize; ++I)
1386    FD->Chaining[I] = readDeclAs<NamedDecl>();
1387
1388  mergeMergeable(FD);
1389}
1390
1391ASTDeclReader::RedeclarableResult ASTDeclReader::VisitVarDeclImpl(VarDecl *VD) {
1392  RedeclarableResult Redecl = VisitRedeclarable(VD);
1393  VisitDeclaratorDecl(VD);
1394
1395  VD->VarDeclBits.SClass = (StorageClass)Record.readInt();
1396  VD->VarDeclBits.TSCSpec = Record.readInt();
1397  VD->VarDeclBits.InitStyle = Record.readInt();
1398  VD->VarDeclBits.ARCPseudoStrong = Record.readInt();
1399  if (!isa<ParmVarDecl>(VD)) {
1400    VD->NonParmVarDeclBits.IsThisDeclarationADemotedDefinition =
1401        Record.readInt();
1402    VD->NonParmVarDeclBits.ExceptionVar = Record.readInt();
1403    VD->NonParmVarDeclBits.NRVOVariable = Record.readInt();
1404    VD->NonParmVarDeclBits.CXXForRangeDecl = Record.readInt();
1405    VD->NonParmVarDeclBits.ObjCForDecl = Record.readInt();
1406    VD->NonParmVarDeclBits.IsInline = Record.readInt();
1407    VD->NonParmVarDeclBits.IsInlineSpecified = Record.readInt();
1408    VD->NonParmVarDeclBits.IsConstexpr = Record.readInt();
1409    VD->NonParmVarDeclBits.IsInitCapture = Record.readInt();
1410    VD->NonParmVarDeclBits.PreviousDeclInSameBlockScope = Record.readInt();
1411    VD->NonParmVarDeclBits.ImplicitParamKind = Record.readInt();
1412    VD->NonParmVarDeclBits.EscapingByref = Record.readInt();
1413  }
1414  auto VarLinkage = Linkage(Record.readInt());
1415  VD->setCachedLinkage(VarLinkage);
1416
1417  // Reconstruct the one piece of the IdentifierNamespace that we need.
1418  if (VD->getStorageClass() == SC_Extern && VarLinkage != NoLinkage &&
1419      VD->getLexicalDeclContext()->isFunctionOrMethod())
1420    VD->setLocalExternDecl();
1421
1422  if (uint64_t Val = Record.readInt()) {
1423    VD->setInit(Record.readExpr());
1424    if (Val > 1) {
1425      EvaluatedStmt *Eval = VD->ensureEvaluatedStmt();
1426      Eval->CheckedICE = true;
1427      Eval->IsICE = (Val & 1) != 0;
1428      Eval->HasConstantDestruction = (Val & 4) != 0;
1429    }
1430  }
1431
1432  if (VD->hasAttr<BlocksAttr>() && VD->getType()->getAsCXXRecordDecl()) {
1433    Expr *CopyExpr = Record.readExpr();
1434    if (CopyExpr)
1435      Reader.getContext().setBlockVarCopyInit(VD, CopyExpr, Record.readInt());
1436  }
1437
1438  if (VD->getStorageDuration() == SD_Static && Record.readInt()) {
1439    Reader.DefinitionSource[VD] = Loc.F->Kind == ModuleKind::MK_MainFile;
1440    if (Reader.getContext().getLangOpts().BuildingPCHWithObjectFile &&
1441        Reader.DeclIsFromPCHWithObjectFile(VD))
1442      Reader.DefinitionSource[VD] = true;
1443  }
1444
1445  enum VarKind {
1446    VarNotTemplate = 0, VarTemplate, StaticDataMemberSpecialization
1447  };
1448  switch ((VarKind)Record.readInt()) {
1449  case VarNotTemplate:
1450    // Only true variables (not parameters or implicit parameters) can be
1451    // merged; the other kinds are not really redeclarable at all.
1452    if (!isa<ParmVarDecl>(VD) && !isa<ImplicitParamDecl>(VD) &&
1453        !isa<VarTemplateSpecializationDecl>(VD))
1454      mergeRedeclarable(VD, Redecl);
1455    break;
1456  case VarTemplate:
1457    // Merged when we merge the template.
1458    VD->setDescribedVarTemplate(readDeclAs<VarTemplateDecl>());
1459    break;
1460  case StaticDataMemberSpecialization: { // HasMemberSpecializationInfo.
1461    auto *Tmpl = readDeclAs<VarDecl>();
1462    auto TSK = (TemplateSpecializationKind)Record.readInt();
1463    SourceLocation POI = readSourceLocation();
1464    Reader.getContext().setInstantiatedFromStaticDataMember(VD, Tmpl, TSK,POI);
1465    mergeRedeclarable(VD, Redecl);
1466    break;
1467  }
1468  }
1469
1470  return Redecl;
1471}
1472
1473void ASTDeclReader::VisitImplicitParamDecl(ImplicitParamDecl *PD) {
1474  VisitVarDecl(PD);
1475}
1476
1477void ASTDeclReader::VisitParmVarDecl(ParmVarDecl *PD) {
1478  VisitVarDecl(PD);
1479  unsigned isObjCMethodParam = Record.readInt();
1480  unsigned scopeDepth = Record.readInt();
1481  unsigned scopeIndex = Record.readInt();
1482  unsigned declQualifier = Record.readInt();
1483  if (isObjCMethodParam) {
1484    assert(scopeDepth == 0);
1485    PD->setObjCMethodScopeInfo(scopeIndex);
1486    PD->ParmVarDeclBits.ScopeDepthOrObjCQuals = declQualifier;
1487  } else {
1488    PD->setScopeInfo(scopeDepth, scopeIndex);
1489  }
1490  PD->ParmVarDeclBits.IsKNRPromoted = Record.readInt();
1491  PD->ParmVarDeclBits.HasInheritedDefaultArg = Record.readInt();
1492  if (Record.readInt()) // hasUninstantiatedDefaultArg.
1493    PD->setUninstantiatedDefaultArg(Record.readExpr());
1494
1495  // FIXME: If this is a redeclaration of a function from another module, handle
1496  // inheritance of default arguments.
1497}
1498
1499void ASTDeclReader::VisitDecompositionDecl(DecompositionDecl *DD) {
1500  VisitVarDecl(DD);
1501  auto **BDs = DD->getTrailingObjects<BindingDecl *>();
1502  for (unsigned I = 0; I != DD->NumBindings; ++I) {
1503    BDs[I] = readDeclAs<BindingDecl>();
1504    BDs[I]->setDecomposedDecl(DD);
1505  }
1506}
1507
1508void ASTDeclReader::VisitBindingDecl(BindingDecl *BD) {
1509  VisitValueDecl(BD);
1510  BD->Binding = Record.readExpr();
1511}
1512
1513void ASTDeclReader::VisitFileScopeAsmDecl(FileScopeAsmDecl *AD) {
1514  VisitDecl(AD);
1515  AD->setAsmString(cast<StringLiteral>(Record.readExpr()));
1516  AD->setRParenLoc(readSourceLocation());
1517}
1518
1519void ASTDeclReader::VisitBlockDecl(BlockDecl *BD) {
1520  VisitDecl(BD);
1521  BD->setBody(cast_or_null<CompoundStmt>(Record.readStmt()));
1522  BD->setSignatureAsWritten(readTypeSourceInfo());
1523  unsigned NumParams = Record.readInt();
1524  SmallVector<ParmVarDecl *, 16> Params;
1525  Params.reserve(NumParams);
1526  for (unsigned I = 0; I != NumParams; ++I)
1527    Params.push_back(readDeclAs<ParmVarDecl>());
1528  BD->setParams(Params);
1529
1530  BD->setIsVariadic(Record.readInt());
1531  BD->setBlockMissingReturnType(Record.readInt());
1532  BD->setIsConversionFromLambda(Record.readInt());
1533  BD->setDoesNotEscape(Record.readInt());
1534  BD->setCanAvoidCopyToHeap(Record.readInt());
1535
1536  bool capturesCXXThis = Record.readInt();
1537  unsigned numCaptures = Record.readInt();
1538  SmallVector<BlockDecl::Capture, 16> captures;
1539  captures.reserve(numCaptures);
1540  for (unsigned i = 0; i != numCaptures; ++i) {
1541    auto *decl = readDeclAs<VarDecl>();
1542    unsigned flags = Record.readInt();
1543    bool byRef = (flags & 1);
1544    bool nested = (flags & 2);
1545    Expr *copyExpr = ((flags & 4) ? Record.readExpr() : nullptr);
1546
1547    captures.push_back(BlockDecl::Capture(decl, byRef, nested, copyExpr));
1548  }
1549  BD->setCaptures(Reader.getContext(), captures, capturesCXXThis);
1550}
1551
1552void ASTDeclReader::VisitCapturedDecl(CapturedDecl *CD) {
1553  VisitDecl(CD);
1554  unsigned ContextParamPos = Record.readInt();
1555  CD->setNothrow(Record.readInt() != 0);
1556  // Body is set by VisitCapturedStmt.
1557  for (unsigned I = 0; I < CD->NumParams; ++I) {
1558    if (I != ContextParamPos)
1559      CD->setParam(I, readDeclAs<ImplicitParamDecl>());
1560    else
1561      CD->setContextParam(I, readDeclAs<ImplicitParamDecl>());
1562  }
1563}
1564
1565void ASTDeclReader::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1566  VisitDecl(D);
1567  D->setLanguage((LinkageSpecDecl::LanguageIDs)Record.readInt());
1568  D->setExternLoc(readSourceLocation());
1569  D->setRBraceLoc(readSourceLocation());
1570}
1571
1572void ASTDeclReader::VisitExportDecl(ExportDecl *D) {
1573  VisitDecl(D);
1574  D->RBraceLoc = readSourceLocation();
1575}
1576
1577void ASTDeclReader::VisitLabelDecl(LabelDecl *D) {
1578  VisitNamedDecl(D);
1579  D->setLocStart(readSourceLocation());
1580}
1581
1582void ASTDeclReader::VisitNamespaceDecl(NamespaceDecl *D) {
1583  RedeclarableResult Redecl = VisitRedeclarable(D);
1584  VisitNamedDecl(D);
1585  D->setInline(Record.readInt());
1586  D->LocStart = readSourceLocation();
1587  D->RBraceLoc = readSourceLocation();
1588
1589  // Defer loading the anonymous namespace until we've finished merging
1590  // this namespace; loading it might load a later declaration of the
1591  // same namespace, and we have an invariant that older declarations
1592  // get merged before newer ones try to merge.
1593  GlobalDeclID AnonNamespace = 0;
1594  if (Redecl.getFirstID() == ThisDeclID) {
1595    AnonNamespace = readDeclID();
1596  } else {
1597    // Link this namespace back to the first declaration, which has already
1598    // been deserialized.
1599    D->AnonOrFirstNamespaceAndInline.setPointer(D->getFirstDecl());
1600  }
1601
1602  mergeRedeclarable(D, Redecl);
1603
1604  if (AnonNamespace) {
1605    // Each module has its own anonymous namespace, which is disjoint from
1606    // any other module's anonymous namespaces, so don't attach the anonymous
1607    // namespace at all.
1608    auto *Anon = cast<NamespaceDecl>(Reader.GetDecl(AnonNamespace));
1609    if (!Record.isModule())
1610      D->setAnonymousNamespace(Anon);
1611  }
1612}
1613
1614void ASTDeclReader::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1615  RedeclarableResult Redecl = VisitRedeclarable(D);
1616  VisitNamedDecl(D);
1617  D->NamespaceLoc = readSourceLocation();
1618  D->IdentLoc = readSourceLocation();
1619  D->QualifierLoc = Record.readNestedNameSpecifierLoc();
1620  D->Namespace = readDeclAs<NamedDecl>();
1621  mergeRedeclarable(D, Redecl);
1622}
1623
1624void ASTDeclReader::VisitUsingDecl(UsingDecl *D) {
1625  VisitNamedDecl(D);
1626  D->setUsingLoc(readSourceLocation());
1627  D->QualifierLoc = Record.readNestedNameSpecifierLoc();
1628  D->DNLoc = Record.readDeclarationNameLoc(D->getDeclName());
1629  D->FirstUsingShadow.setPointer(readDeclAs<UsingShadowDecl>());
1630  D->setTypename(Record.readInt());
1631  if (auto *Pattern = readDeclAs<NamedDecl>())
1632    Reader.getContext().setInstantiatedFromUsingDecl(D, Pattern);
1633  mergeMergeable(D);
1634}
1635
1636void ASTDeclReader::VisitUsingPackDecl(UsingPackDecl *D) {
1637  VisitNamedDecl(D);
1638  D->InstantiatedFrom = readDeclAs<NamedDecl>();
1639  auto **Expansions = D->getTrailingObjects<NamedDecl *>();
1640  for (unsigned I = 0; I != D->NumExpansions; ++I)
1641    Expansions[I] = readDeclAs<NamedDecl>();
1642  mergeMergeable(D);
1643}
1644
1645void ASTDeclReader::VisitUsingShadowDecl(UsingShadowDecl *D) {
1646  RedeclarableResult Redecl = VisitRedeclarable(D);
1647  VisitNamedDecl(D);
1648  D->Underlying = readDeclAs<NamedDecl>();
1649  D->IdentifierNamespace = Record.readInt();
1650  D->UsingOrNextShadow = readDeclAs<NamedDecl>();
1651  auto *Pattern = readDeclAs<UsingShadowDecl>();
1652  if (Pattern)
1653    Reader.getContext().setInstantiatedFromUsingShadowDecl(D, Pattern);
1654  mergeRedeclarable(D, Redecl);
1655}
1656
1657void ASTDeclReader::VisitConstructorUsingShadowDecl(
1658    ConstructorUsingShadowDecl *D) {
1659  VisitUsingShadowDecl(D);
1660  D->NominatedBaseClassShadowDecl = readDeclAs<ConstructorUsingShadowDecl>();
1661  D->ConstructedBaseClassShadowDecl = readDeclAs<ConstructorUsingShadowDecl>();
1662  D->IsVirtual = Record.readInt();
1663}
1664
1665void ASTDeclReader::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1666  VisitNamedDecl(D);
1667  D->UsingLoc = readSourceLocation();
1668  D->NamespaceLoc = readSourceLocation();
1669  D->QualifierLoc = Record.readNestedNameSpecifierLoc();
1670  D->NominatedNamespace = readDeclAs<NamedDecl>();
1671  D->CommonAncestor = readDeclAs<DeclContext>();
1672}
1673
1674void ASTDeclReader::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1675  VisitValueDecl(D);
1676  D->setUsingLoc(readSourceLocation());
1677  D->QualifierLoc = Record.readNestedNameSpecifierLoc();
1678  D->DNLoc = Record.readDeclarationNameLoc(D->getDeclName());
1679  D->EllipsisLoc = readSourceLocation();
1680  mergeMergeable(D);
1681}
1682
1683void ASTDeclReader::VisitUnresolvedUsingTypenameDecl(
1684                                               UnresolvedUsingTypenameDecl *D) {
1685  VisitTypeDecl(D);
1686  D->TypenameLocation = readSourceLocation();
1687  D->QualifierLoc = Record.readNestedNameSpecifierLoc();
1688  D->EllipsisLoc = readSourceLocation();
1689  mergeMergeable(D);
1690}
1691
1692void ASTDeclReader::ReadCXXDefinitionData(
1693    struct CXXRecordDecl::DefinitionData &Data, const CXXRecordDecl *D) {
1694  #define FIELD(Name, Width, Merge) \
1695  Data.Name = Record.readInt();
1696  #include "clang/AST/CXXRecordDeclDefinitionBits.def"
1697
1698  // Note: the caller has deserialized the IsLambda bit already.
1699  Data.ODRHash = Record.readInt();
1700  Data.HasODRHash = true;
1701
1702  if (Record.readInt()) {
1703    Reader.DefinitionSource[D] = Loc.F->Kind == ModuleKind::MK_MainFile;
1704    if (Reader.getContext().getLangOpts().BuildingPCHWithObjectFile &&
1705        Reader.DeclIsFromPCHWithObjectFile(D))
1706      Reader.DefinitionSource[D] = true;
1707  }
1708
1709  Data.NumBases = Record.readInt();
1710  if (Data.NumBases)
1711    Data.Bases = ReadGlobalOffset();
1712  Data.NumVBases = Record.readInt();
1713  if (Data.NumVBases)
1714    Data.VBases = ReadGlobalOffset();
1715
1716  Record.readUnresolvedSet(Data.Conversions);
1717  Data.ComputedVisibleConversions = Record.readInt();
1718  if (Data.ComputedVisibleConversions)
1719    Record.readUnresolvedSet(Data.VisibleConversions);
1720  assert(Data.Definition && "Data.Definition should be already set!");
1721  Data.FirstFriend = readDeclID();
1722
1723  if (Data.IsLambda) {
1724    using Capture = LambdaCapture;
1725
1726    auto &Lambda = static_cast<CXXRecordDecl::LambdaDefinitionData &>(Data);
1727    Lambda.Dependent = Record.readInt();
1728    Lambda.IsGenericLambda = Record.readInt();
1729    Lambda.CaptureDefault = Record.readInt();
1730    Lambda.NumCaptures = Record.readInt();
1731    Lambda.NumExplicitCaptures = Record.readInt();
1732    Lambda.HasKnownInternalLinkage = Record.readInt();
1733    Lambda.ManglingNumber = Record.readInt();
1734    Lambda.ContextDecl = readDeclID();
1735    Lambda.Captures = (Capture *)Reader.getContext().Allocate(
1736        sizeof(Capture) * Lambda.NumCaptures);
1737    Capture *ToCapture = Lambda.Captures;
1738    Lambda.MethodTyInfo = readTypeSourceInfo();
1739    for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) {
1740      SourceLocation Loc = readSourceLocation();
1741      bool IsImplicit = Record.readInt();
1742      auto Kind = static_cast<LambdaCaptureKind>(Record.readInt());
1743      switch (Kind) {
1744      case LCK_StarThis:
1745      case LCK_This:
1746      case LCK_VLAType:
1747        *ToCapture++ = Capture(Loc, IsImplicit, Kind, nullptr,SourceLocation());
1748        break;
1749      case LCK_ByCopy:
1750      case LCK_ByRef:
1751        auto *Var = readDeclAs<VarDecl>();
1752        SourceLocation EllipsisLoc = readSourceLocation();
1753        *ToCapture++ = Capture(Loc, IsImplicit, Kind, Var, EllipsisLoc);
1754        break;
1755      }
1756    }
1757  }
1758}
1759
1760void ASTDeclReader::MergeDefinitionData(
1761    CXXRecordDecl *D, struct CXXRecordDecl::DefinitionData &&MergeDD) {
1762  assert(D->DefinitionData &&
1763         "merging class definition into non-definition");
1764  auto &DD = *D->DefinitionData;
1765
1766  if (DD.Definition != MergeDD.Definition) {
1767    // Track that we merged the definitions.
1768    Reader.MergedDeclContexts.insert(std::make_pair(MergeDD.Definition,
1769                                                    DD.Definition));
1770    Reader.PendingDefinitions.erase(MergeDD.Definition);
1771    MergeDD.Definition->setCompleteDefinition(false);
1772    Reader.mergeDefinitionVisibility(DD.Definition, MergeDD.Definition);
1773    assert(Reader.Lookups.find(MergeDD.Definition) == Reader.Lookups.end() &&
1774           "already loaded pending lookups for merged definition");
1775  }
1776
1777  auto PFDI = Reader.PendingFakeDefinitionData.find(&DD);
1778  if (PFDI != Reader.PendingFakeDefinitionData.end() &&
1779      PFDI->second == ASTReader::PendingFakeDefinitionKind::Fake) {
1780    // We faked up this definition data because we found a class for which we'd
1781    // not yet loaded the definition. Replace it with the real thing now.
1782    assert(!DD.IsLambda && !MergeDD.IsLambda && "faked up lambda definition?");
1783    PFDI->second = ASTReader::PendingFakeDefinitionKind::FakeLoaded;
1784
1785    // Don't change which declaration is the definition; that is required
1786    // to be invariant once we select it.
1787    auto *Def = DD.Definition;
1788    DD = std::move(MergeDD);
1789    DD.Definition = Def;
1790    return;
1791  }
1792
1793  bool DetectedOdrViolation = false;
1794
1795  #define FIELD(Name, Width, Merge) Merge(Name)
1796  #define MERGE_OR(Field) DD.Field |= MergeDD.Field;
1797  #define NO_MERGE(Field) \
1798    DetectedOdrViolation |= DD.Field != MergeDD.Field; \
1799    MERGE_OR(Field)
1800  #include "clang/AST/CXXRecordDeclDefinitionBits.def"
1801  NO_MERGE(IsLambda)
1802  #undef NO_MERGE
1803  #undef MERGE_OR
1804
1805  if (DD.NumBases != MergeDD.NumBases || DD.NumVBases != MergeDD.NumVBases)
1806    DetectedOdrViolation = true;
1807  // FIXME: Issue a diagnostic if the base classes don't match when we come
1808  // to lazily load them.
1809
1810  // FIXME: Issue a diagnostic if the list of conversion functions doesn't
1811  // match when we come to lazily load them.
1812  if (MergeDD.ComputedVisibleConversions && !DD.ComputedVisibleConversions) {
1813    DD.VisibleConversions = std::move(MergeDD.VisibleConversions);
1814    DD.ComputedVisibleConversions = true;
1815  }
1816
1817  // FIXME: Issue a diagnostic if FirstFriend doesn't match when we come to
1818  // lazily load it.
1819
1820  if (DD.IsLambda) {
1821    // FIXME: ODR-checking for merging lambdas (this happens, for instance,
1822    // when they occur within the body of a function template specialization).
1823  }
1824
1825  if (D->getODRHash() != MergeDD.ODRHash) {
1826    DetectedOdrViolation = true;
1827  }
1828
1829  if (DetectedOdrViolation)
1830    Reader.PendingOdrMergeFailures[DD.Definition].push_back(
1831        {MergeDD.Definition, &MergeDD});
1832}
1833
1834void ASTDeclReader::ReadCXXRecordDefinition(CXXRecordDecl *D, bool Update) {
1835  struct CXXRecordDecl::DefinitionData *DD;
1836  ASTContext &C = Reader.getContext();
1837
1838  // Determine whether this is a lambda closure type, so that we can
1839  // allocate the appropriate DefinitionData structure.
1840  bool IsLambda = Record.readInt();
1841  if (IsLambda)
1842    DD = new (C) CXXRecordDecl::LambdaDefinitionData(D, nullptr, false, false,
1843                                                     LCD_None);
1844  else
1845    DD = new (C) struct CXXRecordDecl::DefinitionData(D);
1846
1847  CXXRecordDecl *Canon = D->getCanonicalDecl();
1848  // Set decl definition data before reading it, so that during deserialization
1849  // when we read CXXRecordDecl, it already has definition data and we don't
1850  // set fake one.
1851  if (!Canon->DefinitionData)
1852    Canon->DefinitionData = DD;
1853  D->DefinitionData = Canon->DefinitionData;
1854  ReadCXXDefinitionData(*DD, D);
1855
1856  // We might already have a different definition for this record. This can
1857  // happen either because we're reading an update record, or because we've
1858  // already done some merging. Either way, just merge into it.
1859  if (Canon->DefinitionData != DD) {
1860    MergeDefinitionData(Canon, std::move(*DD));
1861    return;
1862  }
1863
1864  // Mark this declaration as being a definition.
1865  D->setCompleteDefinition(true);
1866
1867  // If this is not the first declaration or is an update record, we can have
1868  // other redeclarations already. Make a note that we need to propagate the
1869  // DefinitionData pointer onto them.
1870  if (Update || Canon != D)
1871    Reader.PendingDefinitions.insert(D);
1872}
1873
1874ASTDeclReader::RedeclarableResult
1875ASTDeclReader::VisitCXXRecordDeclImpl(CXXRecordDecl *D) {
1876  RedeclarableResult Redecl = VisitRecordDeclImpl(D);
1877
1878  ASTContext &C = Reader.getContext();
1879
1880  enum CXXRecKind {
1881    CXXRecNotTemplate = 0, CXXRecTemplate, CXXRecMemberSpecialization
1882  };
1883  switch ((CXXRecKind)Record.readInt()) {
1884  case CXXRecNotTemplate:
1885    // Merged when we merge the folding set entry in the primary template.
1886    if (!isa<ClassTemplateSpecializationDecl>(D))
1887      mergeRedeclarable(D, Redecl);
1888    break;
1889  case CXXRecTemplate: {
1890    // Merged when we merge the template.
1891    auto *Template = readDeclAs<ClassTemplateDecl>();
1892    D->TemplateOrInstantiation = Template;
1893    if (!Template->getTemplatedDecl()) {
1894      // We've not actually loaded the ClassTemplateDecl yet, because we're
1895      // currently being loaded as its pattern. Rely on it to set up our
1896      // TypeForDecl (see VisitClassTemplateDecl).
1897      //
1898      // Beware: we do not yet know our canonical declaration, and may still
1899      // get merged once the surrounding class template has got off the ground.
1900      DeferredTypeID = 0;
1901    }
1902    break;
1903  }
1904  case CXXRecMemberSpecialization: {
1905    auto *RD = readDeclAs<CXXRecordDecl>();
1906    auto TSK = (TemplateSpecializationKind)Record.readInt();
1907    SourceLocation POI = readSourceLocation();
1908    MemberSpecializationInfo *MSI = new (C) MemberSpecializationInfo(RD, TSK);
1909    MSI->setPointOfInstantiation(POI);
1910    D->TemplateOrInstantiation = MSI;
1911    mergeRedeclarable(D, Redecl);
1912    break;
1913  }
1914  }
1915
1916  bool WasDefinition = Record.readInt();
1917  if (WasDefinition)
1918    ReadCXXRecordDefinition(D, /*Update*/false);
1919  else
1920    // Propagate DefinitionData pointer from the canonical declaration.
1921    D->DefinitionData = D->getCanonicalDecl()->DefinitionData;
1922
1923  // Lazily load the key function to avoid deserializing every method so we can
1924  // compute it.
1925  if (WasDefinition) {
1926    DeclID KeyFn = readDeclID();
1927    if (KeyFn && D->isCompleteDefinition())
1928      // FIXME: This is wrong for the ARM ABI, where some other module may have
1929      // made this function no longer be a key function. We need an update
1930      // record or similar for that case.
1931      C.KeyFunctions[D] = KeyFn;
1932  }
1933
1934  return Redecl;
1935}
1936
1937void ASTDeclReader::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) {
1938  D->setExplicitSpecifier(Record.readExplicitSpec());
1939  VisitFunctionDecl(D);
1940  D->setIsCopyDeductionCandidate(Record.readInt());
1941}
1942
1943void ASTDeclReader::VisitCXXMethodDecl(CXXMethodDecl *D) {
1944  VisitFunctionDecl(D);
1945
1946  unsigned NumOverridenMethods = Record.readInt();
1947  if (D->isCanonicalDecl()) {
1948    while (NumOverridenMethods--) {
1949      // Avoid invariant checking of CXXMethodDecl::addOverriddenMethod,
1950      // MD may be initializing.
1951      if (auto *MD = readDeclAs<CXXMethodDecl>())
1952        Reader.getContext().addOverriddenMethod(D, MD->getCanonicalDecl());
1953    }
1954  } else {
1955    // We don't care about which declarations this used to override; we get
1956    // the relevant information from the canonical declaration.
1957    Record.skipInts(NumOverridenMethods);
1958  }
1959}
1960
1961void ASTDeclReader::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
1962  // We need the inherited constructor information to merge the declaration,
1963  // so we have to read it before we call VisitCXXMethodDecl.
1964  D->setExplicitSpecifier(Record.readExplicitSpec());
1965  if (D->isInheritingConstructor()) {
1966    auto *Shadow = readDeclAs<ConstructorUsingShadowDecl>();
1967    auto *Ctor = readDeclAs<CXXConstructorDecl>();
1968    *D->getTrailingObjects<InheritedConstructor>() =
1969        InheritedConstructor(Shadow, Ctor);
1970  }
1971
1972  VisitCXXMethodDecl(D);
1973}
1974
1975void ASTDeclReader::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
1976  VisitCXXMethodDecl(D);
1977
1978  if (auto *OperatorDelete = readDeclAs<FunctionDecl>()) {
1979    CXXDestructorDecl *Canon = D->getCanonicalDecl();
1980    auto *ThisArg = Record.readExpr();
1981    // FIXME: Check consistency if we have an old and new operator delete.
1982    if (!Canon->OperatorDelete) {
1983      Canon->OperatorDelete = OperatorDelete;
1984      Canon->OperatorDeleteThisArg = ThisArg;
1985    }
1986  }
1987}
1988
1989void ASTDeclReader::VisitCXXConversionDecl(CXXConversionDecl *D) {
1990  D->setExplicitSpecifier(Record.readExplicitSpec());
1991  VisitCXXMethodDecl(D);
1992}
1993
1994void ASTDeclReader::VisitImportDecl(ImportDecl *D) {
1995  VisitDecl(D);
1996  D->ImportedModule = readModule();
1997  D->setImportComplete(Record.readInt());
1998  auto *StoredLocs = D->getTrailingObjects<SourceLocation>();
1999  for (unsigned I = 0, N = Record.back(); I != N; ++I)
2000    StoredLocs[I] = readSourceLocation();
2001  Record.skipInts(1); // The number of stored source locations.
2002}
2003
2004void ASTDeclReader::VisitAccessSpecDecl(AccessSpecDecl *D) {
2005  VisitDecl(D);
2006  D->setColonLoc(readSourceLocation());
2007}
2008
2009void ASTDeclReader::VisitFriendDecl(FriendDecl *D) {
2010  VisitDecl(D);
2011  if (Record.readInt()) // hasFriendDecl
2012    D->Friend = readDeclAs<NamedDecl>();
2013  else
2014    D->Friend = readTypeSourceInfo();
2015  for (unsigned i = 0; i != D->NumTPLists; ++i)
2016    D->getTrailingObjects<TemplateParameterList *>()[i] =
2017        Record.readTemplateParameterList();
2018  D->NextFriend = readDeclID();
2019  D->UnsupportedFriend = (Record.readInt() != 0);
2020  D->FriendLoc = readSourceLocation();
2021}
2022
2023void ASTDeclReader::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
2024  VisitDecl(D);
2025  unsigned NumParams = Record.readInt();
2026  D->NumParams = NumParams;
2027  D->Params = new TemplateParameterList*[NumParams];
2028  for (unsigned i = 0; i != NumParams; ++i)
2029    D->Params[i] = Record.readTemplateParameterList();
2030  if (Record.readInt()) // HasFriendDecl
2031    D->Friend = readDeclAs<NamedDecl>();
2032  else
2033    D->Friend = readTypeSourceInfo();
2034  D->FriendLoc = readSourceLocation();
2035}
2036
2037DeclID ASTDeclReader::VisitTemplateDecl(TemplateDecl *D) {
2038  VisitNamedDecl(D);
2039
2040  DeclID PatternID = readDeclID();
2041  auto *TemplatedDecl = cast_or_null<NamedDecl>(Reader.GetDecl(PatternID));
2042  TemplateParameterList *TemplateParams = Record.readTemplateParameterList();
2043  D->init(TemplatedDecl, TemplateParams);
2044
2045  return PatternID;
2046}
2047
2048void ASTDeclReader::VisitConceptDecl(ConceptDecl *D) {
2049  VisitTemplateDecl(D);
2050  D->ConstraintExpr = Record.readExpr();
2051  mergeMergeable(D);
2052}
2053
2054void ASTDeclReader::VisitRequiresExprBodyDecl(RequiresExprBodyDecl *D) {
2055}
2056
2057ASTDeclReader::RedeclarableResult
2058ASTDeclReader::VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D) {
2059  RedeclarableResult Redecl = VisitRedeclarable(D);
2060
2061  // Make sure we've allocated the Common pointer first. We do this before
2062  // VisitTemplateDecl so that getCommonPtr() can be used during initialization.
2063  RedeclarableTemplateDecl *CanonD = D->getCanonicalDecl();
2064  if (!CanonD->Common) {
2065    CanonD->Common = CanonD->newCommon(Reader.getContext());
2066    Reader.PendingDefinitions.insert(CanonD);
2067  }
2068  D->Common = CanonD->Common;
2069
2070  // If this is the first declaration of the template, fill in the information
2071  // for the 'common' pointer.
2072  if (ThisDeclID == Redecl.getFirstID()) {
2073    if (auto *RTD = readDeclAs<RedeclarableTemplateDecl>()) {
2074      assert(RTD->getKind() == D->getKind() &&
2075             "InstantiatedFromMemberTemplate kind mismatch");
2076      D->setInstantiatedFromMemberTemplate(RTD);
2077      if (Record.readInt())
2078        D->setMemberSpecialization();
2079    }
2080  }
2081
2082  DeclID PatternID = VisitTemplateDecl(D);
2083  D->IdentifierNamespace = Record.readInt();
2084
2085  mergeRedeclarable(D, Redecl, PatternID);
2086
2087  // If we merged the template with a prior declaration chain, merge the common
2088  // pointer.
2089  // FIXME: Actually merge here, don't just overwrite.
2090  D->Common = D->getCanonicalDecl()->Common;
2091
2092  return Redecl;
2093}
2094
2095void ASTDeclReader::VisitClassTemplateDecl(ClassTemplateDecl *D) {
2096  RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
2097
2098  if (ThisDeclID == Redecl.getFirstID()) {
2099    // This ClassTemplateDecl owns a CommonPtr; read it to keep track of all of
2100    // the specializations.
2101    SmallVector<serialization::DeclID, 32> SpecIDs;
2102    readDeclIDList(SpecIDs);
2103    ASTDeclReader::AddLazySpecializations(D, SpecIDs);
2104  }
2105
2106  if (D->getTemplatedDecl()->TemplateOrInstantiation) {
2107    // We were loaded before our templated declaration was. We've not set up
2108    // its corresponding type yet (see VisitCXXRecordDeclImpl), so reconstruct
2109    // it now.
2110    Reader.getContext().getInjectedClassNameType(
2111        D->getTemplatedDecl(), D->getInjectedClassNameSpecialization());
2112  }
2113}
2114
2115void ASTDeclReader::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) {
2116  llvm_unreachable("BuiltinTemplates are not serialized");
2117}
2118
2119/// TODO: Unify with ClassTemplateDecl version?
2120///       May require unifying ClassTemplateDecl and
2121///        VarTemplateDecl beyond TemplateDecl...
2122void ASTDeclReader::VisitVarTemplateDecl(VarTemplateDecl *D) {
2123  RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
2124
2125  if (ThisDeclID == Redecl.getFirstID()) {
2126    // This VarTemplateDecl owns a CommonPtr; read it to keep track of all of
2127    // the specializations.
2128    SmallVector<serialization::DeclID, 32> SpecIDs;
2129    readDeclIDList(SpecIDs);
2130    ASTDeclReader::AddLazySpecializations(D, SpecIDs);
2131  }
2132}
2133
2134ASTDeclReader::RedeclarableResult
2135ASTDeclReader::VisitClassTemplateSpecializationDeclImpl(
2136    ClassTemplateSpecializationDecl *D) {
2137  RedeclarableResult Redecl = VisitCXXRecordDeclImpl(D);
2138
2139  ASTContext &C = Reader.getContext();
2140  if (Decl *InstD = readDecl()) {
2141    if (auto *CTD = dyn_cast<ClassTemplateDecl>(InstD)) {
2142      D->SpecializedTemplate = CTD;
2143    } else {
2144      SmallVector<TemplateArgument, 8> TemplArgs;
2145      Record.readTemplateArgumentList(TemplArgs);
2146      TemplateArgumentList *ArgList
2147        = TemplateArgumentList::CreateCopy(C, TemplArgs);
2148      auto *PS =
2149          new (C) ClassTemplateSpecializationDecl::
2150                                             SpecializedPartialSpecialization();
2151      PS->PartialSpecialization
2152          = cast<ClassTemplatePartialSpecializationDecl>(InstD);
2153      PS->TemplateArgs = ArgList;
2154      D->SpecializedTemplate = PS;
2155    }
2156  }
2157
2158  SmallVector<TemplateArgument, 8> TemplArgs;
2159  Record.readTemplateArgumentList(TemplArgs, /*Canonicalize*/ true);
2160  D->TemplateArgs = TemplateArgumentList::CreateCopy(C, TemplArgs);
2161  D->PointOfInstantiation = readSourceLocation();
2162  D->SpecializationKind = (TemplateSpecializationKind)Record.readInt();
2163
2164  bool writtenAsCanonicalDecl = Record.readInt();
2165  if (writtenAsCanonicalDecl) {
2166    auto *CanonPattern = readDeclAs<ClassTemplateDecl>();
2167    if (D->isCanonicalDecl()) { // It's kept in the folding set.
2168      // Set this as, or find, the canonical declaration for this specialization
2169      ClassTemplateSpecializationDecl *CanonSpec;
2170      if (auto *Partial = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) {
2171        CanonSpec = CanonPattern->getCommonPtr()->PartialSpecializations
2172            .GetOrInsertNode(Partial);
2173      } else {
2174        CanonSpec =
2175            CanonPattern->getCommonPtr()->Specializations.GetOrInsertNode(D);
2176      }
2177      // If there was already a canonical specialization, merge into it.
2178      if (CanonSpec != D) {
2179        mergeRedeclarable<TagDecl>(D, CanonSpec, Redecl);
2180
2181        // This declaration might be a definition. Merge with any existing
2182        // definition.
2183        if (auto *DDD = D->DefinitionData) {
2184          if (CanonSpec->DefinitionData)
2185            MergeDefinitionData(CanonSpec, std::move(*DDD));
2186          else
2187            CanonSpec->DefinitionData = D->DefinitionData;
2188        }
2189        D->DefinitionData = CanonSpec->DefinitionData;
2190      }
2191    }
2192  }
2193
2194  // Explicit info.
2195  if (TypeSourceInfo *TyInfo = readTypeSourceInfo()) {
2196    auto *ExplicitInfo =
2197        new (C) ClassTemplateSpecializationDecl::ExplicitSpecializationInfo;
2198    ExplicitInfo->TypeAsWritten = TyInfo;
2199    ExplicitInfo->ExternLoc = readSourceLocation();
2200    ExplicitInfo->TemplateKeywordLoc = readSourceLocation();
2201    D->ExplicitInfo = ExplicitInfo;
2202  }
2203
2204  return Redecl;
2205}
2206
2207void ASTDeclReader::VisitClassTemplatePartialSpecializationDecl(
2208                                    ClassTemplatePartialSpecializationDecl *D) {
2209  // We need to read the template params first because redeclarable is going to
2210  // need them for profiling
2211  TemplateParameterList *Params = Record.readTemplateParameterList();
2212  D->TemplateParams = Params;
2213  D->ArgsAsWritten = Record.readASTTemplateArgumentListInfo();
2214
2215  RedeclarableResult Redecl = VisitClassTemplateSpecializationDeclImpl(D);
2216
2217  // These are read/set from/to the first declaration.
2218  if (ThisDeclID == Redecl.getFirstID()) {
2219    D->InstantiatedFromMember.setPointer(
2220      readDeclAs<ClassTemplatePartialSpecializationDecl>());
2221    D->InstantiatedFromMember.setInt(Record.readInt());
2222  }
2223}
2224
2225void ASTDeclReader::VisitClassScopeFunctionSpecializationDecl(
2226                                    ClassScopeFunctionSpecializationDecl *D) {
2227  VisitDecl(D);
2228  D->Specialization = readDeclAs<CXXMethodDecl>();
2229  if (Record.readInt())
2230    D->TemplateArgs = Record.readASTTemplateArgumentListInfo();
2231}
2232
2233void ASTDeclReader::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
2234  RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
2235
2236  if (ThisDeclID == Redecl.getFirstID()) {
2237    // This FunctionTemplateDecl owns a CommonPtr; read it.
2238    SmallVector<serialization::DeclID, 32> SpecIDs;
2239    readDeclIDList(SpecIDs);
2240    ASTDeclReader::AddLazySpecializations(D, SpecIDs);
2241  }
2242}
2243
2244/// TODO: Unify with ClassTemplateSpecializationDecl version?
2245///       May require unifying ClassTemplate(Partial)SpecializationDecl and
2246///        VarTemplate(Partial)SpecializationDecl with a new data
2247///        structure Template(Partial)SpecializationDecl, and
2248///        using Template(Partial)SpecializationDecl as input type.
2249ASTDeclReader::RedeclarableResult
2250ASTDeclReader::VisitVarTemplateSpecializationDeclImpl(
2251    VarTemplateSpecializationDecl *D) {
2252  RedeclarableResult Redecl = VisitVarDeclImpl(D);
2253
2254  ASTContext &C = Reader.getContext();
2255  if (Decl *InstD = readDecl()) {
2256    if (auto *VTD = dyn_cast<VarTemplateDecl>(InstD)) {
2257      D->SpecializedTemplate = VTD;
2258    } else {
2259      SmallVector<TemplateArgument, 8> TemplArgs;
2260      Record.readTemplateArgumentList(TemplArgs);
2261      TemplateArgumentList *ArgList = TemplateArgumentList::CreateCopy(
2262          C, TemplArgs);
2263      auto *PS =
2264          new (C)
2265          VarTemplateSpecializationDecl::SpecializedPartialSpecialization();
2266      PS->PartialSpecialization =
2267          cast<VarTemplatePartialSpecializationDecl>(InstD);
2268      PS->TemplateArgs = ArgList;
2269      D->SpecializedTemplate = PS;
2270    }
2271  }
2272
2273  // Explicit info.
2274  if (TypeSourceInfo *TyInfo = readTypeSourceInfo()) {
2275    auto *ExplicitInfo =
2276        new (C) VarTemplateSpecializationDecl::ExplicitSpecializationInfo;
2277    ExplicitInfo->TypeAsWritten = TyInfo;
2278    ExplicitInfo->ExternLoc = readSourceLocation();
2279    ExplicitInfo->TemplateKeywordLoc = readSourceLocation();
2280    D->ExplicitInfo = ExplicitInfo;
2281  }
2282
2283  SmallVector<TemplateArgument, 8> TemplArgs;
2284  Record.readTemplateArgumentList(TemplArgs, /*Canonicalize*/ true);
2285  D->TemplateArgs = TemplateArgumentList::CreateCopy(C, TemplArgs);
2286  D->PointOfInstantiation = readSourceLocation();
2287  D->SpecializationKind = (TemplateSpecializationKind)Record.readInt();
2288  D->IsCompleteDefinition = Record.readInt();
2289
2290  bool writtenAsCanonicalDecl = Record.readInt();
2291  if (writtenAsCanonicalDecl) {
2292    auto *CanonPattern = readDeclAs<VarTemplateDecl>();
2293    if (D->isCanonicalDecl()) { // It's kept in the folding set.
2294      // FIXME: If it's already present, merge it.
2295      if (auto *Partial = dyn_cast<VarTemplatePartialSpecializationDecl>(D)) {
2296        CanonPattern->getCommonPtr()->PartialSpecializations
2297            .GetOrInsertNode(Partial);
2298      } else {
2299        CanonPattern->getCommonPtr()->Specializations.GetOrInsertNode(D);
2300      }
2301    }
2302  }
2303
2304  return Redecl;
2305}
2306
2307/// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
2308///       May require unifying ClassTemplate(Partial)SpecializationDecl and
2309///        VarTemplate(Partial)SpecializationDecl with a new data
2310///        structure Template(Partial)SpecializationDecl, and
2311///        using Template(Partial)SpecializationDecl as input type.
2312void ASTDeclReader::VisitVarTemplatePartialSpecializationDecl(
2313    VarTemplatePartialSpecializationDecl *D) {
2314  TemplateParameterList *Params = Record.readTemplateParameterList();
2315  D->TemplateParams = Params;
2316  D->ArgsAsWritten = Record.readASTTemplateArgumentListInfo();
2317
2318  RedeclarableResult Redecl = VisitVarTemplateSpecializationDeclImpl(D);
2319
2320  // These are read/set from/to the first declaration.
2321  if (ThisDeclID == Redecl.getFirstID()) {
2322    D->InstantiatedFromMember.setPointer(
2323        readDeclAs<VarTemplatePartialSpecializationDecl>());
2324    D->InstantiatedFromMember.setInt(Record.readInt());
2325  }
2326}
2327
2328void ASTDeclReader::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
2329  VisitTypeDecl(D);
2330
2331  D->setDeclaredWithTypename(Record.readInt());
2332
2333  if (Record.readBool()) {
2334    NestedNameSpecifierLoc NNS = Record.readNestedNameSpecifierLoc();
2335    DeclarationNameInfo DN = Record.readDeclarationNameInfo();
2336    ConceptDecl *NamedConcept = Record.readDeclAs<ConceptDecl>();
2337    const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr;
2338    if (Record.readBool())
2339        ArgsAsWritten = Record.readASTTemplateArgumentListInfo();
2340    Expr *ImmediatelyDeclaredConstraint = Record.readExpr();
2341    D->setTypeConstraint(NNS, DN, /*FoundDecl=*/nullptr, NamedConcept,
2342                         ArgsAsWritten, ImmediatelyDeclaredConstraint);
2343    if ((D->ExpandedParameterPack = Record.readInt()))
2344      D->NumExpanded = Record.readInt();
2345  }
2346
2347  if (Record.readInt())
2348    D->setDefaultArgument(readTypeSourceInfo());
2349}
2350
2351void ASTDeclReader::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
2352  VisitDeclaratorDecl(D);
2353  // TemplateParmPosition.
2354  D->setDepth(Record.readInt());
2355  D->setPosition(Record.readInt());
2356  if (D->hasPlaceholderTypeConstraint())
2357    D->setPlaceholderTypeConstraint(Record.readExpr());
2358  if (D->isExpandedParameterPack()) {
2359    auto TypesAndInfos =
2360        D->getTrailingObjects<std::pair<QualType, TypeSourceInfo *>>();
2361    for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
2362      new (&TypesAndInfos[I].first) QualType(Record.readType());
2363      TypesAndInfos[I].second = readTypeSourceInfo();
2364    }
2365  } else {
2366    // Rest of NonTypeTemplateParmDecl.
2367    D->ParameterPack = Record.readInt();
2368    if (Record.readInt())
2369      D->setDefaultArgument(Record.readExpr());
2370  }
2371}
2372
2373void ASTDeclReader::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
2374  VisitTemplateDecl(D);
2375  // TemplateParmPosition.
2376  D->setDepth(Record.readInt());
2377  D->setPosition(Record.readInt());
2378  if (D->isExpandedParameterPack()) {
2379    auto **Data = D->getTrailingObjects<TemplateParameterList *>();
2380    for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
2381         I != N; ++I)
2382      Data[I] = Record.readTemplateParameterList();
2383  } else {
2384    // Rest of TemplateTemplateParmDecl.
2385    D->ParameterPack = Record.readInt();
2386    if (Record.readInt())
2387      D->setDefaultArgument(Reader.getContext(),
2388                            Record.readTemplateArgumentLoc());
2389  }
2390}
2391
2392void ASTDeclReader::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
2393  VisitRedeclarableTemplateDecl(D);
2394}
2395
2396void ASTDeclReader::VisitStaticAssertDecl(StaticAssertDecl *D) {
2397  VisitDecl(D);
2398  D->AssertExprAndFailed.setPointer(Record.readExpr());
2399  D->AssertExprAndFailed.setInt(Record.readInt());
2400  D->Message = cast_or_null<StringLiteral>(Record.readExpr());
2401  D->RParenLoc = readSourceLocation();
2402}
2403
2404void ASTDeclReader::VisitEmptyDecl(EmptyDecl *D) {
2405  VisitDecl(D);
2406}
2407
2408void ASTDeclReader::VisitLifetimeExtendedTemporaryDecl(
2409    LifetimeExtendedTemporaryDecl *D) {
2410  VisitDecl(D);
2411  D->ExtendingDecl = readDeclAs<ValueDecl>();
2412  D->ExprWithTemporary = Record.readStmt();
2413  if (Record.readInt())
2414    D->Value = new (D->getASTContext()) APValue(Record.readAPValue());
2415  D->ManglingNumber = Record.readInt();
2416  mergeMergeable(D);
2417}
2418
2419std::pair<uint64_t, uint64_t>
2420ASTDeclReader::VisitDeclContext(DeclContext *DC) {
2421  uint64_t LexicalOffset = ReadLocalOffset();
2422  uint64_t VisibleOffset = ReadLocalOffset();
2423  return std::make_pair(LexicalOffset, VisibleOffset);
2424}
2425
2426template <typename T>
2427ASTDeclReader::RedeclarableResult
2428ASTDeclReader::VisitRedeclarable(Redeclarable<T> *D) {
2429  DeclID FirstDeclID = readDeclID();
2430  Decl *MergeWith = nullptr;
2431
2432  bool IsKeyDecl = ThisDeclID == FirstDeclID;
2433  bool IsFirstLocalDecl = false;
2434
2435  uint64_t RedeclOffset = 0;
2436
2437  // 0 indicates that this declaration was the only declaration of its entity,
2438  // and is used for space optimization.
2439  if (FirstDeclID == 0) {
2440    FirstDeclID = ThisDeclID;
2441    IsKeyDecl = true;
2442    IsFirstLocalDecl = true;
2443  } else if (unsigned N = Record.readInt()) {
2444    // This declaration was the first local declaration, but may have imported
2445    // other declarations.
2446    IsKeyDecl = N == 1;
2447    IsFirstLocalDecl = true;
2448
2449    // We have some declarations that must be before us in our redeclaration
2450    // chain. Read them now, and remember that we ought to merge with one of
2451    // them.
2452    // FIXME: Provide a known merge target to the second and subsequent such
2453    // declaration.
2454    for (unsigned I = 0; I != N - 1; ++I)
2455      MergeWith = readDecl();
2456
2457    RedeclOffset = ReadLocalOffset();
2458  } else {
2459    // This declaration was not the first local declaration. Read the first
2460    // local declaration now, to trigger the import of other redeclarations.
2461    (void)readDecl();
2462  }
2463
2464  auto *FirstDecl = cast_or_null<T>(Reader.GetDecl(FirstDeclID));
2465  if (FirstDecl != D) {
2466    // We delay loading of the redeclaration chain to avoid deeply nested calls.
2467    // We temporarily set the first (canonical) declaration as the previous one
2468    // which is the one that matters and mark the real previous DeclID to be
2469    // loaded & attached later on.
2470    D->RedeclLink = Redeclarable<T>::PreviousDeclLink(FirstDecl);
2471    D->First = FirstDecl->getCanonicalDecl();
2472  }
2473
2474  auto *DAsT = static_cast<T *>(D);
2475
2476  // Note that we need to load local redeclarations of this decl and build a
2477  // decl chain for them. This must happen *after* we perform the preloading
2478  // above; this ensures that the redeclaration chain is built in the correct
2479  // order.
2480  if (IsFirstLocalDecl)
2481    Reader.PendingDeclChains.push_back(std::make_pair(DAsT, RedeclOffset));
2482
2483  return RedeclarableResult(MergeWith, FirstDeclID, IsKeyDecl);
2484}
2485
2486/// Attempts to merge the given declaration (D) with another declaration
2487/// of the same entity.
2488template<typename T>
2489void ASTDeclReader::mergeRedeclarable(Redeclarable<T> *DBase,
2490                                      RedeclarableResult &Redecl,
2491                                      DeclID TemplatePatternID) {
2492  // If modules are not available, there is no reason to perform this merge.
2493  if (!Reader.getContext().getLangOpts().Modules)
2494    return;
2495
2496  // If we're not the canonical declaration, we don't need to merge.
2497  if (!DBase->isFirstDecl())
2498    return;
2499
2500  auto *D = static_cast<T *>(DBase);
2501
2502  if (auto *Existing = Redecl.getKnownMergeTarget())
2503    // We already know of an existing declaration we should merge with.
2504    mergeRedeclarable(D, cast<T>(Existing), Redecl, TemplatePatternID);
2505  else if (FindExistingResult ExistingRes = findExisting(D))
2506    if (T *Existing = ExistingRes)
2507      mergeRedeclarable(D, Existing, Redecl, TemplatePatternID);
2508}
2509
2510/// "Cast" to type T, asserting if we don't have an implicit conversion.
2511/// We use this to put code in a template that will only be valid for certain
2512/// instantiations.
2513template<typename T> static T assert_cast(T t) { return t; }
2514template<typename T> static T assert_cast(...) {
2515  llvm_unreachable("bad assert_cast");
2516}
2517
2518/// Merge together the pattern declarations from two template
2519/// declarations.
2520void ASTDeclReader::mergeTemplatePattern(RedeclarableTemplateDecl *D,
2521                                         RedeclarableTemplateDecl *Existing,
2522                                         DeclID DsID, bool IsKeyDecl) {
2523  auto *DPattern = D->getTemplatedDecl();
2524  auto *ExistingPattern = Existing->getTemplatedDecl();
2525  RedeclarableResult Result(/*MergeWith*/ ExistingPattern,
2526                            DPattern->getCanonicalDecl()->getGlobalID(),
2527                            IsKeyDecl);
2528
2529  if (auto *DClass = dyn_cast<CXXRecordDecl>(DPattern)) {
2530    // Merge with any existing definition.
2531    // FIXME: This is duplicated in several places. Refactor.
2532    auto *ExistingClass =
2533        cast<CXXRecordDecl>(ExistingPattern)->getCanonicalDecl();
2534    if (auto *DDD = DClass->DefinitionData) {
2535      if (ExistingClass->DefinitionData) {
2536        MergeDefinitionData(ExistingClass, std::move(*DDD));
2537      } else {
2538        ExistingClass->DefinitionData = DClass->DefinitionData;
2539        // We may have skipped this before because we thought that DClass
2540        // was the canonical declaration.
2541        Reader.PendingDefinitions.insert(DClass);
2542      }
2543    }
2544    DClass->DefinitionData = ExistingClass->DefinitionData;
2545
2546    return mergeRedeclarable(DClass, cast<TagDecl>(ExistingPattern),
2547                             Result);
2548  }
2549  if (auto *DFunction = dyn_cast<FunctionDecl>(DPattern))
2550    return mergeRedeclarable(DFunction, cast<FunctionDecl>(ExistingPattern),
2551                             Result);
2552  if (auto *DVar = dyn_cast<VarDecl>(DPattern))
2553    return mergeRedeclarable(DVar, cast<VarDecl>(ExistingPattern), Result);
2554  if (auto *DAlias = dyn_cast<TypeAliasDecl>(DPattern))
2555    return mergeRedeclarable(DAlias, cast<TypedefNameDecl>(ExistingPattern),
2556                             Result);
2557  llvm_unreachable("merged an unknown kind of redeclarable template");
2558}
2559
2560/// Attempts to merge the given declaration (D) with another declaration
2561/// of the same entity.
2562template<typename T>
2563void ASTDeclReader::mergeRedeclarable(Redeclarable<T> *DBase, T *Existing,
2564                                      RedeclarableResult &Redecl,
2565                                      DeclID TemplatePatternID) {
2566  auto *D = static_cast<T *>(DBase);
2567  T *ExistingCanon = Existing->getCanonicalDecl();
2568  T *DCanon = D->getCanonicalDecl();
2569  if (ExistingCanon != DCanon) {
2570    assert(DCanon->getGlobalID() == Redecl.getFirstID() &&
2571           "already merged this declaration");
2572
2573    // Have our redeclaration link point back at the canonical declaration
2574    // of the existing declaration, so that this declaration has the
2575    // appropriate canonical declaration.
2576    D->RedeclLink = Redeclarable<T>::PreviousDeclLink(ExistingCanon);
2577    D->First = ExistingCanon;
2578    ExistingCanon->Used |= D->Used;
2579    D->Used = false;
2580
2581    // When we merge a namespace, update its pointer to the first namespace.
2582    // We cannot have loaded any redeclarations of this declaration yet, so
2583    // there's nothing else that needs to be updated.
2584    if (auto *Namespace = dyn_cast<NamespaceDecl>(D))
2585      Namespace->AnonOrFirstNamespaceAndInline.setPointer(
2586          assert_cast<NamespaceDecl*>(ExistingCanon));
2587
2588    // When we merge a template, merge its pattern.
2589    if (auto *DTemplate = dyn_cast<RedeclarableTemplateDecl>(D))
2590      mergeTemplatePattern(
2591          DTemplate, assert_cast<RedeclarableTemplateDecl*>(ExistingCanon),
2592          TemplatePatternID, Redecl.isKeyDecl());
2593
2594    // If this declaration is a key declaration, make a note of that.
2595    if (Redecl.isKeyDecl())
2596      Reader.KeyDecls[ExistingCanon].push_back(Redecl.getFirstID());
2597  }
2598}
2599
2600/// ODR-like semantics for C/ObjC allow us to merge tag types and a structural
2601/// check in Sema guarantees the types can be merged (see C11 6.2.7/1 or C89
2602/// 6.1.2.6/1). Although most merging is done in Sema, we need to guarantee
2603/// that some types are mergeable during deserialization, otherwise name
2604/// lookup fails. This is the case for EnumConstantDecl.
2605static bool allowODRLikeMergeInC(NamedDecl *ND) {
2606  if (!ND)
2607    return false;
2608  // TODO: implement merge for other necessary decls.
2609  if (isa<EnumConstantDecl>(ND))
2610    return true;
2611  return false;
2612}
2613
2614/// Attempts to merge LifetimeExtendedTemporaryDecl with
2615/// identical class definitions from two different modules.
2616void ASTDeclReader::mergeMergeable(LifetimeExtendedTemporaryDecl *D) {
2617  // If modules are not available, there is no reason to perform this merge.
2618  if (!Reader.getContext().getLangOpts().Modules)
2619    return;
2620
2621  LifetimeExtendedTemporaryDecl *LETDecl = D;
2622
2623  LifetimeExtendedTemporaryDecl *&LookupResult =
2624      Reader.LETemporaryForMerging[std::make_pair(
2625          LETDecl->getExtendingDecl(), LETDecl->getManglingNumber())];
2626  if (LookupResult)
2627    Reader.getContext().setPrimaryMergedDecl(LETDecl,
2628                                             LookupResult->getCanonicalDecl());
2629  else
2630    LookupResult = LETDecl;
2631}
2632
2633/// Attempts to merge the given declaration (D) with another declaration
2634/// of the same entity, for the case where the entity is not actually
2635/// redeclarable. This happens, for instance, when merging the fields of
2636/// identical class definitions from two different modules.
2637template<typename T>
2638void ASTDeclReader::mergeMergeable(Mergeable<T> *D) {
2639  // If modules are not available, there is no reason to perform this merge.
2640  if (!Reader.getContext().getLangOpts().Modules)
2641    return;
2642
2643  // ODR-based merging is performed in C++ and in some cases (tag types) in C.
2644  // Note that C identically-named things in different translation units are
2645  // not redeclarations, but may still have compatible types, where ODR-like
2646  // semantics may apply.
2647  if (!Reader.getContext().getLangOpts().CPlusPlus &&
2648      !allowODRLikeMergeInC(dyn_cast<NamedDecl>(static_cast<T*>(D))))
2649    return;
2650
2651  if (FindExistingResult ExistingRes = findExisting(static_cast<T*>(D)))
2652    if (T *Existing = ExistingRes)
2653      Reader.getContext().setPrimaryMergedDecl(static_cast<T *>(D),
2654                                               Existing->getCanonicalDecl());
2655}
2656
2657void ASTDeclReader::VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D) {
2658  VisitDecl(D);
2659  unsigned NumVars = D->varlist_size();
2660  SmallVector<Expr *, 16> Vars;
2661  Vars.reserve(NumVars);
2662  for (unsigned i = 0; i != NumVars; ++i) {
2663    Vars.push_back(Record.readExpr());
2664  }
2665  D->setVars(Vars);
2666}
2667
2668void ASTDeclReader::VisitOMPAllocateDecl(OMPAllocateDecl *D) {
2669  VisitDecl(D);
2670  unsigned NumVars = D->varlist_size();
2671  unsigned NumClauses = D->clauselist_size();
2672  SmallVector<Expr *, 16> Vars;
2673  Vars.reserve(NumVars);
2674  for (unsigned i = 0; i != NumVars; ++i) {
2675    Vars.push_back(Record.readExpr());
2676  }
2677  D->setVars(Vars);
2678  SmallVector<OMPClause *, 8> Clauses;
2679  Clauses.reserve(NumClauses);
2680  for (unsigned I = 0; I != NumClauses; ++I)
2681    Clauses.push_back(Record.readOMPClause());
2682  D->setClauses(Clauses);
2683}
2684
2685void ASTDeclReader::VisitOMPRequiresDecl(OMPRequiresDecl * D) {
2686  VisitDecl(D);
2687  unsigned NumClauses = D->clauselist_size();
2688  SmallVector<OMPClause *, 8> Clauses;
2689  Clauses.reserve(NumClauses);
2690  for (unsigned I = 0; I != NumClauses; ++I)
2691    Clauses.push_back(Record.readOMPClause());
2692  D->setClauses(Clauses);
2693}
2694
2695void ASTDeclReader::VisitOMPDeclareReductionDecl(OMPDeclareReductionDecl *D) {
2696  VisitValueDecl(D);
2697  D->setLocation(readSourceLocation());
2698  Expr *In = Record.readExpr();
2699  Expr *Out = Record.readExpr();
2700  D->setCombinerData(In, Out);
2701  Expr *Combiner = Record.readExpr();
2702  D->setCombiner(Combiner);
2703  Expr *Orig = Record.readExpr();
2704  Expr *Priv = Record.readExpr();
2705  D->setInitializerData(Orig, Priv);
2706  Expr *Init = Record.readExpr();
2707  auto IK = static_cast<OMPDeclareReductionDecl::InitKind>(Record.readInt());
2708  D->setInitializer(Init, IK);
2709  D->PrevDeclInScope = readDeclID();
2710}
2711
2712void ASTDeclReader::VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D) {
2713  VisitValueDecl(D);
2714  D->setLocation(readSourceLocation());
2715  Expr *MapperVarRefE = Record.readExpr();
2716  D->setMapperVarRef(MapperVarRefE);
2717  D->VarName = Record.readDeclarationName();
2718  D->PrevDeclInScope = readDeclID();
2719  unsigned NumClauses = D->clauselist_size();
2720  SmallVector<OMPClause *, 8> Clauses;
2721  Clauses.reserve(NumClauses);
2722  for (unsigned I = 0; I != NumClauses; ++I)
2723    Clauses.push_back(Record.readOMPClause());
2724  D->setClauses(Clauses);
2725}
2726
2727void ASTDeclReader::VisitOMPCapturedExprDecl(OMPCapturedExprDecl *D) {
2728  VisitVarDecl(D);
2729}
2730
2731//===----------------------------------------------------------------------===//
2732// Attribute Reading
2733//===----------------------------------------------------------------------===//
2734
2735namespace {
2736class AttrReader {
2737  ASTRecordReader &Reader;
2738
2739public:
2740  AttrReader(ASTRecordReader &Reader) : Reader(Reader) {}
2741
2742  uint64_t readInt() {
2743    return Reader.readInt();
2744  }
2745
2746  SourceRange readSourceRange() {
2747    return Reader.readSourceRange();
2748  }
2749
2750  SourceLocation readSourceLocation() {
2751    return Reader.readSourceLocation();
2752  }
2753
2754  Expr *readExpr() { return Reader.readExpr(); }
2755
2756  std::string readString() {
2757    return Reader.readString();
2758  }
2759
2760  TypeSourceInfo *readTypeSourceInfo() {
2761    return Reader.readTypeSourceInfo();
2762  }
2763
2764  IdentifierInfo *readIdentifier() {
2765    return Reader.readIdentifier();
2766  }
2767
2768  VersionTuple readVersionTuple() {
2769    return Reader.readVersionTuple();
2770  }
2771
2772  OMPTraitInfo *readOMPTraitInfo() { return Reader.readOMPTraitInfo(); }
2773
2774  template <typename T> T *GetLocalDeclAs(uint32_t LocalID) {
2775    return Reader.GetLocalDeclAs<T>(LocalID);
2776  }
2777};
2778}
2779
2780Attr *ASTRecordReader::readAttr() {
2781  AttrReader Record(*this);
2782  auto V = Record.readInt();
2783  if (!V)
2784    return nullptr;
2785
2786  Attr *New = nullptr;
2787  // Kind is stored as a 1-based integer because 0 is used to indicate a null
2788  // Attr pointer.
2789  auto Kind = static_cast<attr::Kind>(V - 1);
2790  ASTContext &Context = getContext();
2791
2792  IdentifierInfo *AttrName = Record.readIdentifier();
2793  IdentifierInfo *ScopeName = Record.readIdentifier();
2794  SourceRange AttrRange = Record.readSourceRange();
2795  SourceLocation ScopeLoc = Record.readSourceLocation();
2796  unsigned ParsedKind = Record.readInt();
2797  unsigned Syntax = Record.readInt();
2798  unsigned SpellingIndex = Record.readInt();
2799
2800  AttributeCommonInfo Info(AttrName, ScopeName, AttrRange, ScopeLoc,
2801                           AttributeCommonInfo::Kind(ParsedKind),
2802                           AttributeCommonInfo::Syntax(Syntax), SpellingIndex);
2803
2804#include "clang/Serialization/AttrPCHRead.inc"
2805
2806  assert(New && "Unable to decode attribute?");
2807  return New;
2808}
2809
2810/// Reads attributes from the current stream position.
2811void ASTRecordReader::readAttributes(AttrVec &Attrs) {
2812  for (unsigned I = 0, E = readInt(); I != E; ++I)
2813    Attrs.push_back(readAttr());
2814}
2815
2816//===----------------------------------------------------------------------===//
2817// ASTReader Implementation
2818//===----------------------------------------------------------------------===//
2819
2820/// Note that we have loaded the declaration with the given
2821/// Index.
2822///
2823/// This routine notes that this declaration has already been loaded,
2824/// so that future GetDecl calls will return this declaration rather
2825/// than trying to load a new declaration.
2826inline void ASTReader::LoadedDecl(unsigned Index, Decl *D) {
2827  assert(!DeclsLoaded[Index] && "Decl loaded twice?");
2828  DeclsLoaded[Index] = D;
2829}
2830
2831/// Determine whether the consumer will be interested in seeing
2832/// this declaration (via HandleTopLevelDecl).
2833///
2834/// This routine should return true for anything that might affect
2835/// code generation, e.g., inline function definitions, Objective-C
2836/// declarations with metadata, etc.
2837static bool isConsumerInterestedIn(ASTContext &Ctx, Decl *D, bool HasBody) {
2838  // An ObjCMethodDecl is never considered as "interesting" because its
2839  // implementation container always is.
2840
2841  // An ImportDecl or VarDecl imported from a module map module will get
2842  // emitted when we import the relevant module.
2843  if (isPartOfPerModuleInitializer(D)) {
2844    auto *M = D->getImportedOwningModule();
2845    if (M && M->Kind == Module::ModuleMapModule &&
2846        Ctx.DeclMustBeEmitted(D))
2847      return false;
2848  }
2849
2850  if (isa<FileScopeAsmDecl>(D) ||
2851      isa<ObjCProtocolDecl>(D) ||
2852      isa<ObjCImplDecl>(D) ||
2853      isa<ImportDecl>(D) ||
2854      isa<PragmaCommentDecl>(D) ||
2855      isa<PragmaDetectMismatchDecl>(D))
2856    return true;
2857  if (isa<OMPThreadPrivateDecl>(D) || isa<OMPDeclareReductionDecl>(D) ||
2858      isa<OMPDeclareMapperDecl>(D) || isa<OMPAllocateDecl>(D) ||
2859      isa<OMPRequiresDecl>(D))
2860    return !D->getDeclContext()->isFunctionOrMethod();
2861  if (const auto *Var = dyn_cast<VarDecl>(D))
2862    return Var->isFileVarDecl() &&
2863           (Var->isThisDeclarationADefinition() == VarDecl::Definition ||
2864            OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Var));
2865  if (const auto *Func = dyn_cast<FunctionDecl>(D))
2866    return Func->doesThisDeclarationHaveABody() || HasBody;
2867
2868  if (auto *ES = D->getASTContext().getExternalSource())
2869    if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
2870      return true;
2871
2872  return false;
2873}
2874
2875/// Get the correct cursor and offset for loading a declaration.
2876ASTReader::RecordLocation
2877ASTReader::DeclCursorForID(DeclID ID, SourceLocation &Loc) {
2878  GlobalDeclMapType::iterator I = GlobalDeclMap.find(ID);
2879  assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
2880  ModuleFile *M = I->second;
2881  const DeclOffset &DOffs =
2882      M->DeclOffsets[ID - M->BaseDeclID - NUM_PREDEF_DECL_IDS];
2883  Loc = TranslateSourceLocation(*M, DOffs.getLocation());
2884  return RecordLocation(M, DOffs.getBitOffset(M->DeclsBlockStartOffset));
2885}
2886
2887ASTReader::RecordLocation ASTReader::getLocalBitOffset(uint64_t GlobalOffset) {
2888  auto I = GlobalBitOffsetsMap.find(GlobalOffset);
2889
2890  assert(I != GlobalBitOffsetsMap.end() && "Corrupted global bit offsets map");
2891  return RecordLocation(I->second, GlobalOffset - I->second->GlobalBitOffset);
2892}
2893
2894uint64_t ASTReader::getGlobalBitOffset(ModuleFile &M, uint64_t LocalOffset) {
2895  return LocalOffset + M.GlobalBitOffset;
2896}
2897
2898static bool isSameTemplateParameterList(const ASTContext &C,
2899                                        const TemplateParameterList *X,
2900                                        const TemplateParameterList *Y);
2901
2902/// Determine whether two template parameters are similar enough
2903/// that they may be used in declarations of the same template.
2904static bool isSameTemplateParameter(const NamedDecl *X,
2905                                    const NamedDecl *Y) {
2906  if (X->getKind() != Y->getKind())
2907    return false;
2908
2909  if (const auto *TX = dyn_cast<TemplateTypeParmDecl>(X)) {
2910    const auto *TY = cast<TemplateTypeParmDecl>(Y);
2911    if (TX->isParameterPack() != TY->isParameterPack())
2912      return false;
2913    if (TX->hasTypeConstraint() != TY->hasTypeConstraint())
2914      return false;
2915    const TypeConstraint *TXTC = TX->getTypeConstraint();
2916    const TypeConstraint *TYTC = TY->getTypeConstraint();
2917    if (!TXTC != !TYTC)
2918      return false;
2919    if (TXTC && TYTC) {
2920      if (TXTC->getNamedConcept() != TYTC->getNamedConcept())
2921        return false;
2922      if (TXTC->hasExplicitTemplateArgs() != TYTC->hasExplicitTemplateArgs())
2923        return false;
2924      if (TXTC->hasExplicitTemplateArgs()) {
2925        const auto *TXTCArgs = TXTC->getTemplateArgsAsWritten();
2926        const auto *TYTCArgs = TYTC->getTemplateArgsAsWritten();
2927        if (TXTCArgs->NumTemplateArgs != TYTCArgs->NumTemplateArgs)
2928          return false;
2929        llvm::FoldingSetNodeID XID, YID;
2930        for (const auto &ArgLoc : TXTCArgs->arguments())
2931          ArgLoc.getArgument().Profile(XID, X->getASTContext());
2932        for (const auto &ArgLoc : TYTCArgs->arguments())
2933          ArgLoc.getArgument().Profile(YID, Y->getASTContext());
2934        if (XID != YID)
2935          return false;
2936      }
2937    }
2938    return true;
2939  }
2940
2941  if (const auto *TX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
2942    const auto *TY = cast<NonTypeTemplateParmDecl>(Y);
2943    return TX->isParameterPack() == TY->isParameterPack() &&
2944           TX->getASTContext().hasSameType(TX->getType(), TY->getType());
2945  }
2946
2947  const auto *TX = cast<TemplateTemplateParmDecl>(X);
2948  const auto *TY = cast<TemplateTemplateParmDecl>(Y);
2949  return TX->isParameterPack() == TY->isParameterPack() &&
2950         isSameTemplateParameterList(TX->getASTContext(),
2951                                     TX->getTemplateParameters(),
2952                                     TY->getTemplateParameters());
2953}
2954
2955static NamespaceDecl *getNamespace(const NestedNameSpecifier *X) {
2956  if (auto *NS = X->getAsNamespace())
2957    return NS;
2958  if (auto *NAS = X->getAsNamespaceAlias())
2959    return NAS->getNamespace();
2960  return nullptr;
2961}
2962
2963static bool isSameQualifier(const NestedNameSpecifier *X,
2964                            const NestedNameSpecifier *Y) {
2965  if (auto *NSX = getNamespace(X)) {
2966    auto *NSY = getNamespace(Y);
2967    if (!NSY || NSX->getCanonicalDecl() != NSY->getCanonicalDecl())
2968      return false;
2969  } else if (X->getKind() != Y->getKind())
2970    return false;
2971
2972  // FIXME: For namespaces and types, we're permitted to check that the entity
2973  // is named via the same tokens. We should probably do so.
2974  switch (X->getKind()) {
2975  case NestedNameSpecifier::Identifier:
2976    if (X->getAsIdentifier() != Y->getAsIdentifier())
2977      return false;
2978    break;
2979  case NestedNameSpecifier::Namespace:
2980  case NestedNameSpecifier::NamespaceAlias:
2981    // We've already checked that we named the same namespace.
2982    break;
2983  case NestedNameSpecifier::TypeSpec:
2984  case NestedNameSpecifier::TypeSpecWithTemplate:
2985    if (X->getAsType()->getCanonicalTypeInternal() !=
2986        Y->getAsType()->getCanonicalTypeInternal())
2987      return false;
2988    break;
2989  case NestedNameSpecifier::Global:
2990  case NestedNameSpecifier::Super:
2991    return true;
2992  }
2993
2994  // Recurse into earlier portion of NNS, if any.
2995  auto *PX = X->getPrefix();
2996  auto *PY = Y->getPrefix();
2997  if (PX && PY)
2998    return isSameQualifier(PX, PY);
2999  return !PX && !PY;
3000}
3001
3002/// Determine whether two template parameter lists are similar enough
3003/// that they may be used in declarations of the same template.
3004static bool isSameTemplateParameterList(const ASTContext &C,
3005                                        const TemplateParameterList *X,
3006                                        const TemplateParameterList *Y) {
3007  if (X->size() != Y->size())
3008    return false;
3009
3010  for (unsigned I = 0, N = X->size(); I != N; ++I)
3011    if (!isSameTemplateParameter(X->getParam(I), Y->getParam(I)))
3012      return false;
3013
3014  const Expr *XRC = X->getRequiresClause();
3015  const Expr *YRC = Y->getRequiresClause();
3016  if (!XRC != !YRC)
3017    return false;
3018  if (XRC) {
3019    llvm::FoldingSetNodeID XRCID, YRCID;
3020    XRC->Profile(XRCID, C, /*Canonical=*/true);
3021    YRC->Profile(YRCID, C, /*Canonical=*/true);
3022    if (XRCID != YRCID)
3023      return false;
3024  }
3025
3026  return true;
3027}
3028
3029/// Determine whether the attributes we can overload on are identical for A and
3030/// B. Will ignore any overloadable attrs represented in the type of A and B.
3031static bool hasSameOverloadableAttrs(const FunctionDecl *A,
3032                                     const FunctionDecl *B) {
3033  // Note that pass_object_size attributes are represented in the function's
3034  // ExtParameterInfo, so we don't need to check them here.
3035
3036  llvm::FoldingSetNodeID Cand1ID, Cand2ID;
3037  auto AEnableIfAttrs = A->specific_attrs<EnableIfAttr>();
3038  auto BEnableIfAttrs = B->specific_attrs<EnableIfAttr>();
3039
3040  for (auto Pair : zip_longest(AEnableIfAttrs, BEnableIfAttrs)) {
3041    Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
3042    Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
3043
3044    // Return false if the number of enable_if attributes is different.
3045    if (!Cand1A || !Cand2A)
3046      return false;
3047
3048    Cand1ID.clear();
3049    Cand2ID.clear();
3050
3051    (*Cand1A)->getCond()->Profile(Cand1ID, A->getASTContext(), true);
3052    (*Cand2A)->getCond()->Profile(Cand2ID, B->getASTContext(), true);
3053
3054    // Return false if any of the enable_if expressions of A and B are
3055    // different.
3056    if (Cand1ID != Cand2ID)
3057      return false;
3058  }
3059  return true;
3060}
3061
3062/// Determine whether the two declarations refer to the same entity.pr
3063static bool isSameEntity(NamedDecl *X, NamedDecl *Y) {
3064  assert(X->getDeclName() == Y->getDeclName() && "Declaration name mismatch!");
3065
3066  if (X == Y)
3067    return true;
3068
3069  // Must be in the same context.
3070  //
3071  // Note that we can't use DeclContext::Equals here, because the DeclContexts
3072  // could be two different declarations of the same function. (We will fix the
3073  // semantic DC to refer to the primary definition after merging.)
3074  if (!declaresSameEntity(cast<Decl>(X->getDeclContext()->getRedeclContext()),
3075                          cast<Decl>(Y->getDeclContext()->getRedeclContext())))
3076    return false;
3077
3078  // Two typedefs refer to the same entity if they have the same underlying
3079  // type.
3080  if (const auto *TypedefX = dyn_cast<TypedefNameDecl>(X))
3081    if (const auto *TypedefY = dyn_cast<TypedefNameDecl>(Y))
3082      return X->getASTContext().hasSameType(TypedefX->getUnderlyingType(),
3083                                            TypedefY->getUnderlyingType());
3084
3085  // Must have the same kind.
3086  if (X->getKind() != Y->getKind())
3087    return false;
3088
3089  // Objective-C classes and protocols with the same name always match.
3090  if (isa<ObjCInterfaceDecl>(X) || isa<ObjCProtocolDecl>(X))
3091    return true;
3092
3093  if (isa<ClassTemplateSpecializationDecl>(X)) {
3094    // No need to handle these here: we merge them when adding them to the
3095    // template.
3096    return false;
3097  }
3098
3099  // Compatible tags match.
3100  if (const auto *TagX = dyn_cast<TagDecl>(X)) {
3101    const auto *TagY = cast<TagDecl>(Y);
3102    return (TagX->getTagKind() == TagY->getTagKind()) ||
3103      ((TagX->getTagKind() == TTK_Struct || TagX->getTagKind() == TTK_Class ||
3104        TagX->getTagKind() == TTK_Interface) &&
3105       (TagY->getTagKind() == TTK_Struct || TagY->getTagKind() == TTK_Class ||
3106        TagY->getTagKind() == TTK_Interface));
3107  }
3108
3109  // Functions with the same type and linkage match.
3110  // FIXME: This needs to cope with merging of prototyped/non-prototyped
3111  // functions, etc.
3112  if (const auto *FuncX = dyn_cast<FunctionDecl>(X)) {
3113    const auto *FuncY = cast<FunctionDecl>(Y);
3114    if (const auto *CtorX = dyn_cast<CXXConstructorDecl>(X)) {
3115      const auto *CtorY = cast<CXXConstructorDecl>(Y);
3116      if (CtorX->getInheritedConstructor() &&
3117          !isSameEntity(CtorX->getInheritedConstructor().getConstructor(),
3118                        CtorY->getInheritedConstructor().getConstructor()))
3119        return false;
3120    }
3121
3122    if (FuncX->isMultiVersion() != FuncY->isMultiVersion())
3123      return false;
3124
3125    // Multiversioned functions with different feature strings are represented
3126    // as separate declarations.
3127    if (FuncX->isMultiVersion()) {
3128      const auto *TAX = FuncX->getAttr<TargetAttr>();
3129      const auto *TAY = FuncY->getAttr<TargetAttr>();
3130      assert(TAX && TAY && "Multiversion Function without target attribute");
3131
3132      if (TAX->getFeaturesStr() != TAY->getFeaturesStr())
3133        return false;
3134    }
3135
3136    ASTContext &C = FuncX->getASTContext();
3137
3138    const Expr *XRC = FuncX->getTrailingRequiresClause();
3139    const Expr *YRC = FuncY->getTrailingRequiresClause();
3140    if (!XRC != !YRC)
3141      return false;
3142    if (XRC) {
3143      llvm::FoldingSetNodeID XRCID, YRCID;
3144      XRC->Profile(XRCID, C, /*Canonical=*/true);
3145      YRC->Profile(YRCID, C, /*Canonical=*/true);
3146      if (XRCID != YRCID)
3147        return false;
3148    }
3149
3150    auto GetTypeAsWritten = [](const FunctionDecl *FD) {
3151      // Map to the first declaration that we've already merged into this one.
3152      // The TSI of redeclarations might not match (due to calling conventions
3153      // being inherited onto the type but not the TSI), but the TSI type of
3154      // the first declaration of the function should match across modules.
3155      FD = FD->getCanonicalDecl();
3156      return FD->getTypeSourceInfo() ? FD->getTypeSourceInfo()->getType()
3157                                     : FD->getType();
3158    };
3159    QualType XT = GetTypeAsWritten(FuncX), YT = GetTypeAsWritten(FuncY);
3160    if (!C.hasSameType(XT, YT)) {
3161      // We can get functions with different types on the redecl chain in C++17
3162      // if they have differing exception specifications and at least one of
3163      // the excpetion specs is unresolved.
3164      auto *XFPT = XT->getAs<FunctionProtoType>();
3165      auto *YFPT = YT->getAs<FunctionProtoType>();
3166      if (C.getLangOpts().CPlusPlus17 && XFPT && YFPT &&
3167          (isUnresolvedExceptionSpec(XFPT->getExceptionSpecType()) ||
3168           isUnresolvedExceptionSpec(YFPT->getExceptionSpecType())) &&
3169          C.hasSameFunctionTypeIgnoringExceptionSpec(XT, YT))
3170        return true;
3171      return false;
3172    }
3173
3174    return FuncX->getLinkageInternal() == FuncY->getLinkageInternal() &&
3175           hasSameOverloadableAttrs(FuncX, FuncY);
3176  }
3177
3178  // Variables with the same type and linkage match.
3179  if (const auto *VarX = dyn_cast<VarDecl>(X)) {
3180    const auto *VarY = cast<VarDecl>(Y);
3181    if (VarX->getLinkageInternal() == VarY->getLinkageInternal()) {
3182      ASTContext &C = VarX->getASTContext();
3183      if (C.hasSameType(VarX->getType(), VarY->getType()))
3184        return true;
3185
3186      // We can get decls with different types on the redecl chain. Eg.
3187      // template <typename T> struct S { static T Var[]; }; // #1
3188      // template <typename T> T S<T>::Var[sizeof(T)]; // #2
3189      // Only? happens when completing an incomplete array type. In this case
3190      // when comparing #1 and #2 we should go through their element type.
3191      const ArrayType *VarXTy = C.getAsArrayType(VarX->getType());
3192      const ArrayType *VarYTy = C.getAsArrayType(VarY->getType());
3193      if (!VarXTy || !VarYTy)
3194        return false;
3195      if (VarXTy->isIncompleteArrayType() || VarYTy->isIncompleteArrayType())
3196        return C.hasSameType(VarXTy->getElementType(), VarYTy->getElementType());
3197    }
3198    return false;
3199  }
3200
3201  // Namespaces with the same name and inlinedness match.
3202  if (const auto *NamespaceX = dyn_cast<NamespaceDecl>(X)) {
3203    const auto *NamespaceY = cast<NamespaceDecl>(Y);
3204    return NamespaceX->isInline() == NamespaceY->isInline();
3205  }
3206
3207  // Identical template names and kinds match if their template parameter lists
3208  // and patterns match.
3209  if (const auto *TemplateX = dyn_cast<TemplateDecl>(X)) {
3210    const auto *TemplateY = cast<TemplateDecl>(Y);
3211    return isSameEntity(TemplateX->getTemplatedDecl(),
3212                        TemplateY->getTemplatedDecl()) &&
3213           isSameTemplateParameterList(TemplateX->getASTContext(),
3214                                       TemplateX->getTemplateParameters(),
3215                                       TemplateY->getTemplateParameters());
3216  }
3217
3218  // Fields with the same name and the same type match.
3219  if (const auto *FDX = dyn_cast<FieldDecl>(X)) {
3220    const auto *FDY = cast<FieldDecl>(Y);
3221    // FIXME: Also check the bitwidth is odr-equivalent, if any.
3222    return X->getASTContext().hasSameType(FDX->getType(), FDY->getType());
3223  }
3224
3225  // Indirect fields with the same target field match.
3226  if (const auto *IFDX = dyn_cast<IndirectFieldDecl>(X)) {
3227    const auto *IFDY = cast<IndirectFieldDecl>(Y);
3228    return IFDX->getAnonField()->getCanonicalDecl() ==
3229           IFDY->getAnonField()->getCanonicalDecl();
3230  }
3231
3232  // Enumerators with the same name match.
3233  if (isa<EnumConstantDecl>(X))
3234    // FIXME: Also check the value is odr-equivalent.
3235    return true;
3236
3237  // Using shadow declarations with the same target match.
3238  if (const auto *USX = dyn_cast<UsingShadowDecl>(X)) {
3239    const auto *USY = cast<UsingShadowDecl>(Y);
3240    return USX->getTargetDecl() == USY->getTargetDecl();
3241  }
3242
3243  // Using declarations with the same qualifier match. (We already know that
3244  // the name matches.)
3245  if (const auto *UX = dyn_cast<UsingDecl>(X)) {
3246    const auto *UY = cast<UsingDecl>(Y);
3247    return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
3248           UX->hasTypename() == UY->hasTypename() &&
3249           UX->isAccessDeclaration() == UY->isAccessDeclaration();
3250  }
3251  if (const auto *UX = dyn_cast<UnresolvedUsingValueDecl>(X)) {
3252    const auto *UY = cast<UnresolvedUsingValueDecl>(Y);
3253    return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
3254           UX->isAccessDeclaration() == UY->isAccessDeclaration();
3255  }
3256  if (const auto *UX = dyn_cast<UnresolvedUsingTypenameDecl>(X))
3257    return isSameQualifier(
3258        UX->getQualifier(),
3259        cast<UnresolvedUsingTypenameDecl>(Y)->getQualifier());
3260
3261  // Namespace alias definitions with the same target match.
3262  if (const auto *NAX = dyn_cast<NamespaceAliasDecl>(X)) {
3263    const auto *NAY = cast<NamespaceAliasDecl>(Y);
3264    return NAX->getNamespace()->Equals(NAY->getNamespace());
3265  }
3266
3267  return false;
3268}
3269
3270/// Find the context in which we should search for previous declarations when
3271/// looking for declarations to merge.
3272DeclContext *ASTDeclReader::getPrimaryContextForMerging(ASTReader &Reader,
3273                                                        DeclContext *DC) {
3274  if (auto *ND = dyn_cast<NamespaceDecl>(DC))
3275    return ND->getOriginalNamespace();
3276
3277  if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) {
3278    // Try to dig out the definition.
3279    auto *DD = RD->DefinitionData;
3280    if (!DD)
3281      DD = RD->getCanonicalDecl()->DefinitionData;
3282
3283    // If there's no definition yet, then DC's definition is added by an update
3284    // record, but we've not yet loaded that update record. In this case, we
3285    // commit to DC being the canonical definition now, and will fix this when
3286    // we load the update record.
3287    if (!DD) {
3288      DD = new (Reader.getContext()) struct CXXRecordDecl::DefinitionData(RD);
3289      RD->setCompleteDefinition(true);
3290      RD->DefinitionData = DD;
3291      RD->getCanonicalDecl()->DefinitionData = DD;
3292
3293      // Track that we did this horrible thing so that we can fix it later.
3294      Reader.PendingFakeDefinitionData.insert(
3295          std::make_pair(DD, ASTReader::PendingFakeDefinitionKind::Fake));
3296    }
3297
3298    return DD->Definition;
3299  }
3300
3301  if (auto *ED = dyn_cast<EnumDecl>(DC))
3302    return ED->getASTContext().getLangOpts().CPlusPlus? ED->getDefinition()
3303                                                      : nullptr;
3304
3305  // We can see the TU here only if we have no Sema object. In that case,
3306  // there's no TU scope to look in, so using the DC alone is sufficient.
3307  if (auto *TU = dyn_cast<TranslationUnitDecl>(DC))
3308    return TU;
3309
3310  return nullptr;
3311}
3312
3313ASTDeclReader::FindExistingResult::~FindExistingResult() {
3314  // Record that we had a typedef name for linkage whether or not we merge
3315  // with that declaration.
3316  if (TypedefNameForLinkage) {
3317    DeclContext *DC = New->getDeclContext()->getRedeclContext();
3318    Reader.ImportedTypedefNamesForLinkage.insert(
3319        std::make_pair(std::make_pair(DC, TypedefNameForLinkage), New));
3320    return;
3321  }
3322
3323  if (!AddResult || Existing)
3324    return;
3325
3326  DeclarationName Name = New->getDeclName();
3327  DeclContext *DC = New->getDeclContext()->getRedeclContext();
3328  if (needsAnonymousDeclarationNumber(New)) {
3329    setAnonymousDeclForMerging(Reader, New->getLexicalDeclContext(),
3330                               AnonymousDeclNumber, New);
3331  } else if (DC->isTranslationUnit() &&
3332             !Reader.getContext().getLangOpts().CPlusPlus) {
3333    if (Reader.getIdResolver().tryAddTopLevelDecl(New, Name))
3334      Reader.PendingFakeLookupResults[Name.getAsIdentifierInfo()]
3335            .push_back(New);
3336  } else if (DeclContext *MergeDC = getPrimaryContextForMerging(Reader, DC)) {
3337    // Add the declaration to its redeclaration context so later merging
3338    // lookups will find it.
3339    MergeDC->makeDeclVisibleInContextImpl(New, /*Internal*/true);
3340  }
3341}
3342
3343/// Find the declaration that should be merged into, given the declaration found
3344/// by name lookup. If we're merging an anonymous declaration within a typedef,
3345/// we need a matching typedef, and we merge with the type inside it.
3346static NamedDecl *getDeclForMerging(NamedDecl *Found,
3347                                    bool IsTypedefNameForLinkage) {
3348  if (!IsTypedefNameForLinkage)
3349    return Found;
3350
3351  // If we found a typedef declaration that gives a name to some other
3352  // declaration, then we want that inner declaration. Declarations from
3353  // AST files are handled via ImportedTypedefNamesForLinkage.
3354  if (Found->isFromASTFile())
3355    return nullptr;
3356
3357  if (auto *TND = dyn_cast<TypedefNameDecl>(Found))
3358    return TND->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
3359
3360  return nullptr;
3361}
3362
3363/// Find the declaration to use to populate the anonymous declaration table
3364/// for the given lexical DeclContext. We only care about finding local
3365/// definitions of the context; we'll merge imported ones as we go.
3366DeclContext *
3367ASTDeclReader::getPrimaryDCForAnonymousDecl(DeclContext *LexicalDC) {
3368  // For classes, we track the definition as we merge.
3369  if (auto *RD = dyn_cast<CXXRecordDecl>(LexicalDC)) {
3370    auto *DD = RD->getCanonicalDecl()->DefinitionData;
3371    return DD ? DD->Definition : nullptr;
3372  }
3373
3374  // For anything else, walk its merged redeclarations looking for a definition.
3375  // Note that we can't just call getDefinition here because the redeclaration
3376  // chain isn't wired up.
3377  for (auto *D : merged_redecls(cast<Decl>(LexicalDC))) {
3378    if (auto *FD = dyn_cast<FunctionDecl>(D))
3379      if (FD->isThisDeclarationADefinition())
3380        return FD;
3381    if (auto *MD = dyn_cast<ObjCMethodDecl>(D))
3382      if (MD->isThisDeclarationADefinition())
3383        return MD;
3384  }
3385
3386  // No merged definition yet.
3387  return nullptr;
3388}
3389
3390NamedDecl *ASTDeclReader::getAnonymousDeclForMerging(ASTReader &Reader,
3391                                                     DeclContext *DC,
3392                                                     unsigned Index) {
3393  // If the lexical context has been merged, look into the now-canonical
3394  // definition.
3395  auto *CanonDC = cast<Decl>(DC)->getCanonicalDecl();
3396
3397  // If we've seen this before, return the canonical declaration.
3398  auto &Previous = Reader.AnonymousDeclarationsForMerging[CanonDC];
3399  if (Index < Previous.size() && Previous[Index])
3400    return Previous[Index];
3401
3402  // If this is the first time, but we have parsed a declaration of the context,
3403  // build the anonymous declaration list from the parsed declaration.
3404  auto *PrimaryDC = getPrimaryDCForAnonymousDecl(DC);
3405  if (PrimaryDC && !cast<Decl>(PrimaryDC)->isFromASTFile()) {
3406    numberAnonymousDeclsWithin(PrimaryDC, [&](NamedDecl *ND, unsigned Number) {
3407      if (Previous.size() == Number)
3408        Previous.push_back(cast<NamedDecl>(ND->getCanonicalDecl()));
3409      else
3410        Previous[Number] = cast<NamedDecl>(ND->getCanonicalDecl());
3411    });
3412  }
3413
3414  return Index < Previous.size() ? Previous[Index] : nullptr;
3415}
3416
3417void ASTDeclReader::setAnonymousDeclForMerging(ASTReader &Reader,
3418                                               DeclContext *DC, unsigned Index,
3419                                               NamedDecl *D) {
3420  auto *CanonDC = cast<Decl>(DC)->getCanonicalDecl();
3421
3422  auto &Previous = Reader.AnonymousDeclarationsForMerging[CanonDC];
3423  if (Index >= Previous.size())
3424    Previous.resize(Index + 1);
3425  if (!Previous[Index])
3426    Previous[Index] = D;
3427}
3428
3429ASTDeclReader::FindExistingResult ASTDeclReader::findExisting(NamedDecl *D) {
3430  DeclarationName Name = TypedefNameForLinkage ? TypedefNameForLinkage
3431                                               : D->getDeclName();
3432
3433  if (!Name && !needsAnonymousDeclarationNumber(D)) {
3434    // Don't bother trying to find unnamed declarations that are in
3435    // unmergeable contexts.
3436    FindExistingResult Result(Reader, D, /*Existing=*/nullptr,
3437                              AnonymousDeclNumber, TypedefNameForLinkage);
3438    Result.suppress();
3439    return Result;
3440  }
3441
3442  DeclContext *DC = D->getDeclContext()->getRedeclContext();
3443  if (TypedefNameForLinkage) {
3444    auto It = Reader.ImportedTypedefNamesForLinkage.find(
3445        std::make_pair(DC, TypedefNameForLinkage));
3446    if (It != Reader.ImportedTypedefNamesForLinkage.end())
3447      if (isSameEntity(It->second, D))
3448        return FindExistingResult(Reader, D, It->second, AnonymousDeclNumber,
3449                                  TypedefNameForLinkage);
3450    // Go on to check in other places in case an existing typedef name
3451    // was not imported.
3452  }
3453
3454  if (needsAnonymousDeclarationNumber(D)) {
3455    // This is an anonymous declaration that we may need to merge. Look it up
3456    // in its context by number.
3457    if (auto *Existing = getAnonymousDeclForMerging(
3458            Reader, D->getLexicalDeclContext(), AnonymousDeclNumber))
3459      if (isSameEntity(Existing, D))
3460        return FindExistingResult(Reader, D, Existing, AnonymousDeclNumber,
3461                                  TypedefNameForLinkage);
3462  } else if (DC->isTranslationUnit() &&
3463             !Reader.getContext().getLangOpts().CPlusPlus) {
3464    IdentifierResolver &IdResolver = Reader.getIdResolver();
3465
3466    // Temporarily consider the identifier to be up-to-date. We don't want to
3467    // cause additional lookups here.
3468    class UpToDateIdentifierRAII {
3469      IdentifierInfo *II;
3470      bool WasOutToDate = false;
3471
3472    public:
3473      explicit UpToDateIdentifierRAII(IdentifierInfo *II) : II(II) {
3474        if (II) {
3475          WasOutToDate = II->isOutOfDate();
3476          if (WasOutToDate)
3477            II->setOutOfDate(false);
3478        }
3479      }
3480
3481      ~UpToDateIdentifierRAII() {
3482        if (WasOutToDate)
3483          II->setOutOfDate(true);
3484      }
3485    } UpToDate(Name.getAsIdentifierInfo());
3486
3487    for (IdentifierResolver::iterator I = IdResolver.begin(Name),
3488                                   IEnd = IdResolver.end();
3489         I != IEnd; ++I) {
3490      if (NamedDecl *Existing = getDeclForMerging(*I, TypedefNameForLinkage))
3491        if (isSameEntity(Existing, D))
3492          return FindExistingResult(Reader, D, Existing, AnonymousDeclNumber,
3493                                    TypedefNameForLinkage);
3494    }
3495  } else if (DeclContext *MergeDC = getPrimaryContextForMerging(Reader, DC)) {
3496    DeclContext::lookup_result R = MergeDC->noload_lookup(Name);
3497    for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
3498      if (NamedDecl *Existing = getDeclForMerging(*I, TypedefNameForLinkage))
3499        if (isSameEntity(Existing, D))
3500          return FindExistingResult(Reader, D, Existing, AnonymousDeclNumber,
3501                                    TypedefNameForLinkage);
3502    }
3503  } else {
3504    // Not in a mergeable context.
3505    return FindExistingResult(Reader);
3506  }
3507
3508  // If this declaration is from a merged context, make a note that we need to
3509  // check that the canonical definition of that context contains the decl.
3510  //
3511  // FIXME: We should do something similar if we merge two definitions of the
3512  // same template specialization into the same CXXRecordDecl.
3513  auto MergedDCIt = Reader.MergedDeclContexts.find(D->getLexicalDeclContext());
3514  if (MergedDCIt != Reader.MergedDeclContexts.end() &&
3515      MergedDCIt->second == D->getDeclContext())
3516    Reader.PendingOdrMergeChecks.push_back(D);
3517
3518  return FindExistingResult(Reader, D, /*Existing=*/nullptr,
3519                            AnonymousDeclNumber, TypedefNameForLinkage);
3520}
3521
3522template<typename DeclT>
3523Decl *ASTDeclReader::getMostRecentDeclImpl(Redeclarable<DeclT> *D) {
3524  return D->RedeclLink.getLatestNotUpdated();
3525}
3526
3527Decl *ASTDeclReader::getMostRecentDeclImpl(...) {
3528  llvm_unreachable("getMostRecentDecl on non-redeclarable declaration");
3529}
3530
3531Decl *ASTDeclReader::getMostRecentDecl(Decl *D) {
3532  assert(D);
3533
3534  switch (D->getKind()) {
3535#define ABSTRACT_DECL(TYPE)
3536#define DECL(TYPE, BASE)                               \
3537  case Decl::TYPE:                                     \
3538    return getMostRecentDeclImpl(cast<TYPE##Decl>(D));
3539#include "clang/AST/DeclNodes.inc"
3540  }
3541  llvm_unreachable("unknown decl kind");
3542}
3543
3544Decl *ASTReader::getMostRecentExistingDecl(Decl *D) {
3545  return ASTDeclReader::getMostRecentDecl(D->getCanonicalDecl());
3546}
3547
3548template<typename DeclT>
3549void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader,
3550                                           Redeclarable<DeclT> *D,
3551                                           Decl *Previous, Decl *Canon) {
3552  D->RedeclLink.setPrevious(cast<DeclT>(Previous));
3553  D->First = cast<DeclT>(Previous)->First;
3554}
3555
3556namespace clang {
3557
3558template<>
3559void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader,
3560                                           Redeclarable<VarDecl> *D,
3561                                           Decl *Previous, Decl *Canon) {
3562  auto *VD = static_cast<VarDecl *>(D);
3563  auto *PrevVD = cast<VarDecl>(Previous);
3564  D->RedeclLink.setPrevious(PrevVD);
3565  D->First = PrevVD->First;
3566
3567  // We should keep at most one definition on the chain.
3568  // FIXME: Cache the definition once we've found it. Building a chain with
3569  // N definitions currently takes O(N^2) time here.
3570  if (VD->isThisDeclarationADefinition() == VarDecl::Definition) {
3571    for (VarDecl *CurD = PrevVD; CurD; CurD = CurD->getPreviousDecl()) {
3572      if (CurD->isThisDeclarationADefinition() == VarDecl::Definition) {
3573        Reader.mergeDefinitionVisibility(CurD, VD);
3574        VD->demoteThisDefinitionToDeclaration();
3575        break;
3576      }
3577    }
3578  }
3579}
3580
3581static bool isUndeducedReturnType(QualType T) {
3582  auto *DT = T->getContainedDeducedType();
3583  return DT && !DT->isDeduced();
3584}
3585
3586template<>
3587void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader,
3588                                           Redeclarable<FunctionDecl> *D,
3589                                           Decl *Previous, Decl *Canon) {
3590  auto *FD = static_cast<FunctionDecl *>(D);
3591  auto *PrevFD = cast<FunctionDecl>(Previous);
3592
3593  FD->RedeclLink.setPrevious(PrevFD);
3594  FD->First = PrevFD->First;
3595
3596  // If the previous declaration is an inline function declaration, then this
3597  // declaration is too.
3598  if (PrevFD->isInlined() != FD->isInlined()) {
3599    // FIXME: [dcl.fct.spec]p4:
3600    //   If a function with external linkage is declared inline in one
3601    //   translation unit, it shall be declared inline in all translation
3602    //   units in which it appears.
3603    //
3604    // Be careful of this case:
3605    //
3606    // module A:
3607    //   template<typename T> struct X { void f(); };
3608    //   template<typename T> inline void X<T>::f() {}
3609    //
3610    // module B instantiates the declaration of X<int>::f
3611    // module C instantiates the definition of X<int>::f
3612    //
3613    // If module B and C are merged, we do not have a violation of this rule.
3614    FD->setImplicitlyInline(true);
3615  }
3616
3617  auto *FPT = FD->getType()->getAs<FunctionProtoType>();
3618  auto *PrevFPT = PrevFD->getType()->getAs<FunctionProtoType>();
3619  if (FPT && PrevFPT) {
3620    // If we need to propagate an exception specification along the redecl
3621    // chain, make a note of that so that we can do so later.
3622    bool IsUnresolved = isUnresolvedExceptionSpec(FPT->getExceptionSpecType());
3623    bool WasUnresolved =
3624        isUnresolvedExceptionSpec(PrevFPT->getExceptionSpecType());
3625    if (IsUnresolved != WasUnresolved)
3626      Reader.PendingExceptionSpecUpdates.insert(
3627          {Canon, IsUnresolved ? PrevFD : FD});
3628
3629    // If we need to propagate a deduced return type along the redecl chain,
3630    // make a note of that so that we can do it later.
3631    bool IsUndeduced = isUndeducedReturnType(FPT->getReturnType());
3632    bool WasUndeduced = isUndeducedReturnType(PrevFPT->getReturnType());
3633    if (IsUndeduced != WasUndeduced)
3634      Reader.PendingDeducedTypeUpdates.insert(
3635          {cast<FunctionDecl>(Canon),
3636           (IsUndeduced ? PrevFPT : FPT)->getReturnType()});
3637  }
3638}
3639
3640} // namespace clang
3641
3642void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader, ...) {
3643  llvm_unreachable("attachPreviousDecl on non-redeclarable declaration");
3644}
3645
3646/// Inherit the default template argument from \p From to \p To. Returns
3647/// \c false if there is no default template for \p From.
3648template <typename ParmDecl>
3649static bool inheritDefaultTemplateArgument(ASTContext &Context, ParmDecl *From,
3650                                           Decl *ToD) {
3651  auto *To = cast<ParmDecl>(ToD);
3652  if (!From->hasDefaultArgument())
3653    return false;
3654  To->setInheritedDefaultArgument(Context, From);
3655  return true;
3656}
3657
3658static void inheritDefaultTemplateArguments(ASTContext &Context,
3659                                            TemplateDecl *From,
3660                                            TemplateDecl *To) {
3661  auto *FromTP = From->getTemplateParameters();
3662  auto *ToTP = To->getTemplateParameters();
3663  assert(FromTP->size() == ToTP->size() && "merged mismatched templates?");
3664
3665  for (unsigned I = 0, N = FromTP->size(); I != N; ++I) {
3666    NamedDecl *FromParam = FromTP->getParam(I);
3667    NamedDecl *ToParam = ToTP->getParam(I);
3668
3669    if (auto *FTTP = dyn_cast<TemplateTypeParmDecl>(FromParam))
3670      inheritDefaultTemplateArgument(Context, FTTP, ToParam);
3671    else if (auto *FNTTP = dyn_cast<NonTypeTemplateParmDecl>(FromParam))
3672      inheritDefaultTemplateArgument(Context, FNTTP, ToParam);
3673    else
3674      inheritDefaultTemplateArgument(
3675              Context, cast<TemplateTemplateParmDecl>(FromParam), ToParam);
3676  }
3677}
3678
3679void ASTDeclReader::attachPreviousDecl(ASTReader &Reader, Decl *D,
3680                                       Decl *Previous, Decl *Canon) {
3681  assert(D && Previous);
3682
3683  switch (D->getKind()) {
3684#define ABSTRACT_DECL(TYPE)
3685#define DECL(TYPE, BASE)                                                  \
3686  case Decl::TYPE:                                                        \
3687    attachPreviousDeclImpl(Reader, cast<TYPE##Decl>(D), Previous, Canon); \
3688    break;
3689#include "clang/AST/DeclNodes.inc"
3690  }
3691
3692  // If the declaration was visible in one module, a redeclaration of it in
3693  // another module remains visible even if it wouldn't be visible by itself.
3694  //
3695  // FIXME: In this case, the declaration should only be visible if a module
3696  //        that makes it visible has been imported.
3697  D->IdentifierNamespace |=
3698      Previous->IdentifierNamespace &
3699      (Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Type);
3700
3701  // If the declaration declares a template, it may inherit default arguments
3702  // from the previous declaration.
3703  if (auto *TD = dyn_cast<TemplateDecl>(D))
3704    inheritDefaultTemplateArguments(Reader.getContext(),
3705                                    cast<TemplateDecl>(Previous), TD);
3706}
3707
3708template<typename DeclT>
3709void ASTDeclReader::attachLatestDeclImpl(Redeclarable<DeclT> *D, Decl *Latest) {
3710  D->RedeclLink.setLatest(cast<DeclT>(Latest));
3711}
3712
3713void ASTDeclReader::attachLatestDeclImpl(...) {
3714  llvm_unreachable("attachLatestDecl on non-redeclarable declaration");
3715}
3716
3717void ASTDeclReader::attachLatestDecl(Decl *D, Decl *Latest) {
3718  assert(D && Latest);
3719
3720  switch (D->getKind()) {
3721#define ABSTRACT_DECL(TYPE)
3722#define DECL(TYPE, BASE)                                  \
3723  case Decl::TYPE:                                        \
3724    attachLatestDeclImpl(cast<TYPE##Decl>(D), Latest); \
3725    break;
3726#include "clang/AST/DeclNodes.inc"
3727  }
3728}
3729
3730template<typename DeclT>
3731void ASTDeclReader::markIncompleteDeclChainImpl(Redeclarable<DeclT> *D) {
3732  D->RedeclLink.markIncomplete();
3733}
3734
3735void ASTDeclReader::markIncompleteDeclChainImpl(...) {
3736  llvm_unreachable("markIncompleteDeclChain on non-redeclarable declaration");
3737}
3738
3739void ASTReader::markIncompleteDeclChain(Decl *D) {
3740  switch (D->getKind()) {
3741#define ABSTRACT_DECL(TYPE)
3742#define DECL(TYPE, BASE)                                             \
3743  case Decl::TYPE:                                                   \
3744    ASTDeclReader::markIncompleteDeclChainImpl(cast<TYPE##Decl>(D)); \
3745    break;
3746#include "clang/AST/DeclNodes.inc"
3747  }
3748}
3749
3750/// Read the declaration at the given offset from the AST file.
3751Decl *ASTReader::ReadDeclRecord(DeclID ID) {
3752  unsigned Index = ID - NUM_PREDEF_DECL_IDS;
3753  SourceLocation DeclLoc;
3754  RecordLocation Loc = DeclCursorForID(ID, DeclLoc);
3755  llvm::BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
3756  // Keep track of where we are in the stream, then jump back there
3757  // after reading this declaration.
3758  SavedStreamPosition SavedPosition(DeclsCursor);
3759
3760  ReadingKindTracker ReadingKind(Read_Decl, *this);
3761
3762  // Note that we are loading a declaration record.
3763  Deserializing ADecl(this);
3764
3765  auto Fail = [](const char *what, llvm::Error &&Err) {
3766    llvm::report_fatal_error(Twine("ASTReader::readDeclRecord failed ") + what +
3767                             ": " + toString(std::move(Err)));
3768  };
3769
3770  if (llvm::Error JumpFailed = DeclsCursor.JumpToBit(Loc.Offset))
3771    Fail("jumping", std::move(JumpFailed));
3772  ASTRecordReader Record(*this, *Loc.F);
3773  ASTDeclReader Reader(*this, Record, Loc, ID, DeclLoc);
3774  Expected<unsigned> MaybeCode = DeclsCursor.ReadCode();
3775  if (!MaybeCode)
3776    Fail("reading code", MaybeCode.takeError());
3777  unsigned Code = MaybeCode.get();
3778
3779  ASTContext &Context = getContext();
3780  Decl *D = nullptr;
3781  Expected<unsigned> MaybeDeclCode = Record.readRecord(DeclsCursor, Code);
3782  if (!MaybeDeclCode)
3783    llvm::report_fatal_error(
3784        "ASTReader::readDeclRecord failed reading decl code: " +
3785        toString(MaybeDeclCode.takeError()));
3786  switch ((DeclCode)MaybeDeclCode.get()) {
3787  case DECL_CONTEXT_LEXICAL:
3788  case DECL_CONTEXT_VISIBLE:
3789    llvm_unreachable("Record cannot be de-serialized with readDeclRecord");
3790  case DECL_TYPEDEF:
3791    D = TypedefDecl::CreateDeserialized(Context, ID);
3792    break;
3793  case DECL_TYPEALIAS:
3794    D = TypeAliasDecl::CreateDeserialized(Context, ID);
3795    break;
3796  case DECL_ENUM:
3797    D = EnumDecl::CreateDeserialized(Context, ID);
3798    break;
3799  case DECL_RECORD:
3800    D = RecordDecl::CreateDeserialized(Context, ID);
3801    break;
3802  case DECL_ENUM_CONSTANT:
3803    D = EnumConstantDecl::CreateDeserialized(Context, ID);
3804    break;
3805  case DECL_FUNCTION:
3806    D = FunctionDecl::CreateDeserialized(Context, ID);
3807    break;
3808  case DECL_LINKAGE_SPEC:
3809    D = LinkageSpecDecl::CreateDeserialized(Context, ID);
3810    break;
3811  case DECL_EXPORT:
3812    D = ExportDecl::CreateDeserialized(Context, ID);
3813    break;
3814  case DECL_LABEL:
3815    D = LabelDecl::CreateDeserialized(Context, ID);
3816    break;
3817  case DECL_NAMESPACE:
3818    D = NamespaceDecl::CreateDeserialized(Context, ID);
3819    break;
3820  case DECL_NAMESPACE_ALIAS:
3821    D = NamespaceAliasDecl::CreateDeserialized(Context, ID);
3822    break;
3823  case DECL_USING:
3824    D = UsingDecl::CreateDeserialized(Context, ID);
3825    break;
3826  case DECL_USING_PACK:
3827    D = UsingPackDecl::CreateDeserialized(Context, ID, Record.readInt());
3828    break;
3829  case DECL_USING_SHADOW:
3830    D = UsingShadowDecl::CreateDeserialized(Context, ID);
3831    break;
3832  case DECL_CONSTRUCTOR_USING_SHADOW:
3833    D = ConstructorUsingShadowDecl::CreateDeserialized(Context, ID);
3834    break;
3835  case DECL_USING_DIRECTIVE:
3836    D = UsingDirectiveDecl::CreateDeserialized(Context, ID);
3837    break;
3838  case DECL_UNRESOLVED_USING_VALUE:
3839    D = UnresolvedUsingValueDecl::CreateDeserialized(Context, ID);
3840    break;
3841  case DECL_UNRESOLVED_USING_TYPENAME:
3842    D = UnresolvedUsingTypenameDecl::CreateDeserialized(Context, ID);
3843    break;
3844  case DECL_CXX_RECORD:
3845    D = CXXRecordDecl::CreateDeserialized(Context, ID);
3846    break;
3847  case DECL_CXX_DEDUCTION_GUIDE:
3848    D = CXXDeductionGuideDecl::CreateDeserialized(Context, ID);
3849    break;
3850  case DECL_CXX_METHOD:
3851    D = CXXMethodDecl::CreateDeserialized(Context, ID);
3852    break;
3853  case DECL_CXX_CONSTRUCTOR:
3854    D = CXXConstructorDecl::CreateDeserialized(Context, ID, Record.readInt());
3855    break;
3856  case DECL_CXX_DESTRUCTOR:
3857    D = CXXDestructorDecl::CreateDeserialized(Context, ID);
3858    break;
3859  case DECL_CXX_CONVERSION:
3860    D = CXXConversionDecl::CreateDeserialized(Context, ID);
3861    break;
3862  case DECL_ACCESS_SPEC:
3863    D = AccessSpecDecl::CreateDeserialized(Context, ID);
3864    break;
3865  case DECL_FRIEND:
3866    D = FriendDecl::CreateDeserialized(Context, ID, Record.readInt());
3867    break;
3868  case DECL_FRIEND_TEMPLATE:
3869    D = FriendTemplateDecl::CreateDeserialized(Context, ID);
3870    break;
3871  case DECL_CLASS_TEMPLATE:
3872    D = ClassTemplateDecl::CreateDeserialized(Context, ID);
3873    break;
3874  case DECL_CLASS_TEMPLATE_SPECIALIZATION:
3875    D = ClassTemplateSpecializationDecl::CreateDeserialized(Context, ID);
3876    break;
3877  case DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION:
3878    D = ClassTemplatePartialSpecializationDecl::CreateDeserialized(Context, ID);
3879    break;
3880  case DECL_VAR_TEMPLATE:
3881    D = VarTemplateDecl::CreateDeserialized(Context, ID);
3882    break;
3883  case DECL_VAR_TEMPLATE_SPECIALIZATION:
3884    D = VarTemplateSpecializationDecl::CreateDeserialized(Context, ID);
3885    break;
3886  case DECL_VAR_TEMPLATE_PARTIAL_SPECIALIZATION:
3887    D = VarTemplatePartialSpecializationDecl::CreateDeserialized(Context, ID);
3888    break;
3889  case DECL_CLASS_SCOPE_FUNCTION_SPECIALIZATION:
3890    D = ClassScopeFunctionSpecializationDecl::CreateDeserialized(Context, ID);
3891    break;
3892  case DECL_FUNCTION_TEMPLATE:
3893    D = FunctionTemplateDecl::CreateDeserialized(Context, ID);
3894    break;
3895  case DECL_TEMPLATE_TYPE_PARM: {
3896    bool HasTypeConstraint = Record.readInt();
3897    D = TemplateTypeParmDecl::CreateDeserialized(Context, ID,
3898                                                 HasTypeConstraint);
3899    break;
3900  }
3901  case DECL_NON_TYPE_TEMPLATE_PARM: {
3902    bool HasTypeConstraint = Record.readInt();
3903    D = NonTypeTemplateParmDecl::CreateDeserialized(Context, ID,
3904                                                    HasTypeConstraint);
3905    break;
3906  }
3907  case DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK: {
3908    bool HasTypeConstraint = Record.readInt();
3909    D = NonTypeTemplateParmDecl::CreateDeserialized(Context, ID,
3910                                                    Record.readInt(),
3911                                                    HasTypeConstraint);
3912    break;
3913  }
3914  case DECL_TEMPLATE_TEMPLATE_PARM:
3915    D = TemplateTemplateParmDecl::CreateDeserialized(Context, ID);
3916    break;
3917  case DECL_EXPANDED_TEMPLATE_TEMPLATE_PARM_PACK:
3918    D = TemplateTemplateParmDecl::CreateDeserialized(Context, ID,
3919                                                     Record.readInt());
3920    break;
3921  case DECL_TYPE_ALIAS_TEMPLATE:
3922    D = TypeAliasTemplateDecl::CreateDeserialized(Context, ID);
3923    break;
3924  case DECL_CONCEPT:
3925    D = ConceptDecl::CreateDeserialized(Context, ID);
3926    break;
3927  case DECL_REQUIRES_EXPR_BODY:
3928    D = RequiresExprBodyDecl::CreateDeserialized(Context, ID);
3929    break;
3930  case DECL_STATIC_ASSERT:
3931    D = StaticAssertDecl::CreateDeserialized(Context, ID);
3932    break;
3933  case DECL_OBJC_METHOD:
3934    D = ObjCMethodDecl::CreateDeserialized(Context, ID);
3935    break;
3936  case DECL_OBJC_INTERFACE:
3937    D = ObjCInterfaceDecl::CreateDeserialized(Context, ID);
3938    break;
3939  case DECL_OBJC_IVAR:
3940    D = ObjCIvarDecl::CreateDeserialized(Context, ID);
3941    break;
3942  case DECL_OBJC_PROTOCOL:
3943    D = ObjCProtocolDecl::CreateDeserialized(Context, ID);
3944    break;
3945  case DECL_OBJC_AT_DEFS_FIELD:
3946    D = ObjCAtDefsFieldDecl::CreateDeserialized(Context, ID);
3947    break;
3948  case DECL_OBJC_CATEGORY:
3949    D = ObjCCategoryDecl::CreateDeserialized(Context, ID);
3950    break;
3951  case DECL_OBJC_CATEGORY_IMPL:
3952    D = ObjCCategoryImplDecl::CreateDeserialized(Context, ID);
3953    break;
3954  case DECL_OBJC_IMPLEMENTATION:
3955    D = ObjCImplementationDecl::CreateDeserialized(Context, ID);
3956    break;
3957  case DECL_OBJC_COMPATIBLE_ALIAS:
3958    D = ObjCCompatibleAliasDecl::CreateDeserialized(Context, ID);
3959    break;
3960  case DECL_OBJC_PROPERTY:
3961    D = ObjCPropertyDecl::CreateDeserialized(Context, ID);
3962    break;
3963  case DECL_OBJC_PROPERTY_IMPL:
3964    D = ObjCPropertyImplDecl::CreateDeserialized(Context, ID);
3965    break;
3966  case DECL_FIELD:
3967    D = FieldDecl::CreateDeserialized(Context, ID);
3968    break;
3969  case DECL_INDIRECTFIELD:
3970    D = IndirectFieldDecl::CreateDeserialized(Context, ID);
3971    break;
3972  case DECL_VAR:
3973    D = VarDecl::CreateDeserialized(Context, ID);
3974    break;
3975  case DECL_IMPLICIT_PARAM:
3976    D = ImplicitParamDecl::CreateDeserialized(Context, ID);
3977    break;
3978  case DECL_PARM_VAR:
3979    D = ParmVarDecl::CreateDeserialized(Context, ID);
3980    break;
3981  case DECL_DECOMPOSITION:
3982    D = DecompositionDecl::CreateDeserialized(Context, ID, Record.readInt());
3983    break;
3984  case DECL_BINDING:
3985    D = BindingDecl::CreateDeserialized(Context, ID);
3986    break;
3987  case DECL_FILE_SCOPE_ASM:
3988    D = FileScopeAsmDecl::CreateDeserialized(Context, ID);
3989    break;
3990  case DECL_BLOCK:
3991    D = BlockDecl::CreateDeserialized(Context, ID);
3992    break;
3993  case DECL_MS_PROPERTY:
3994    D = MSPropertyDecl::CreateDeserialized(Context, ID);
3995    break;
3996  case DECL_MS_GUID:
3997    D = MSGuidDecl::CreateDeserialized(Context, ID);
3998    break;
3999  case DECL_CAPTURED:
4000    D = CapturedDecl::CreateDeserialized(Context, ID, Record.readInt());
4001    break;
4002  case DECL_CXX_BASE_SPECIFIERS:
4003    Error("attempt to read a C++ base-specifier record as a declaration");
4004    return nullptr;
4005  case DECL_CXX_CTOR_INITIALIZERS:
4006    Error("attempt to read a C++ ctor initializer record as a declaration");
4007    return nullptr;
4008  case DECL_IMPORT:
4009    // Note: last entry of the ImportDecl record is the number of stored source
4010    // locations.
4011    D = ImportDecl::CreateDeserialized(Context, ID, Record.back());
4012    break;
4013  case DECL_OMP_THREADPRIVATE:
4014    D = OMPThreadPrivateDecl::CreateDeserialized(Context, ID, Record.readInt());
4015    break;
4016  case DECL_OMP_ALLOCATE: {
4017    unsigned NumVars = Record.readInt();
4018    unsigned NumClauses = Record.readInt();
4019    D = OMPAllocateDecl::CreateDeserialized(Context, ID, NumVars, NumClauses);
4020    break;
4021  }
4022  case DECL_OMP_REQUIRES:
4023    D = OMPRequiresDecl::CreateDeserialized(Context, ID, Record.readInt());
4024    break;
4025  case DECL_OMP_DECLARE_REDUCTION:
4026    D = OMPDeclareReductionDecl::CreateDeserialized(Context, ID);
4027    break;
4028  case DECL_OMP_DECLARE_MAPPER:
4029    D = OMPDeclareMapperDecl::CreateDeserialized(Context, ID, Record.readInt());
4030    break;
4031  case DECL_OMP_CAPTUREDEXPR:
4032    D = OMPCapturedExprDecl::CreateDeserialized(Context, ID);
4033    break;
4034  case DECL_PRAGMA_COMMENT:
4035    D = PragmaCommentDecl::CreateDeserialized(Context, ID, Record.readInt());
4036    break;
4037  case DECL_PRAGMA_DETECT_MISMATCH:
4038    D = PragmaDetectMismatchDecl::CreateDeserialized(Context, ID,
4039                                                     Record.readInt());
4040    break;
4041  case DECL_EMPTY:
4042    D = EmptyDecl::CreateDeserialized(Context, ID);
4043    break;
4044  case DECL_LIFETIME_EXTENDED_TEMPORARY:
4045    D = LifetimeExtendedTemporaryDecl::CreateDeserialized(Context, ID);
4046    break;
4047  case DECL_OBJC_TYPE_PARAM:
4048    D = ObjCTypeParamDecl::CreateDeserialized(Context, ID);
4049    break;
4050  }
4051
4052  assert(D && "Unknown declaration reading AST file");
4053  LoadedDecl(Index, D);
4054  // Set the DeclContext before doing any deserialization, to make sure internal
4055  // calls to Decl::getASTContext() by Decl's methods will find the
4056  // TranslationUnitDecl without crashing.
4057  D->setDeclContext(Context.getTranslationUnitDecl());
4058  Reader.Visit(D);
4059
4060  // If this declaration is also a declaration context, get the
4061  // offsets for its tables of lexical and visible declarations.
4062  if (auto *DC = dyn_cast<DeclContext>(D)) {
4063    std::pair<uint64_t, uint64_t> Offsets = Reader.VisitDeclContext(DC);
4064    if (Offsets.first &&
4065        ReadLexicalDeclContextStorage(*Loc.F, DeclsCursor, Offsets.first, DC))
4066      return nullptr;
4067    if (Offsets.second &&
4068        ReadVisibleDeclContextStorage(*Loc.F, DeclsCursor, Offsets.second, ID))
4069      return nullptr;
4070  }
4071  assert(Record.getIdx() == Record.size());
4072
4073  // Load any relevant update records.
4074  PendingUpdateRecords.push_back(
4075      PendingUpdateRecord(ID, D, /*JustLoaded=*/true));
4076
4077  // Load the categories after recursive loading is finished.
4078  if (auto *Class = dyn_cast<ObjCInterfaceDecl>(D))
4079    // If we already have a definition when deserializing the ObjCInterfaceDecl,
4080    // we put the Decl in PendingDefinitions so we can pull the categories here.
4081    if (Class->isThisDeclarationADefinition() ||
4082        PendingDefinitions.count(Class))
4083      loadObjCCategories(ID, Class);
4084
4085  // If we have deserialized a declaration that has a definition the
4086  // AST consumer might need to know about, queue it.
4087  // We don't pass it to the consumer immediately because we may be in recursive
4088  // loading, and some declarations may still be initializing.
4089  PotentiallyInterestingDecls.push_back(
4090      InterestingDecl(D, Reader.hasPendingBody()));
4091
4092  return D;
4093}
4094
4095void ASTReader::PassInterestingDeclsToConsumer() {
4096  assert(Consumer);
4097
4098  if (PassingDeclsToConsumer)
4099    return;
4100
4101  // Guard variable to avoid recursively redoing the process of passing
4102  // decls to consumer.
4103  SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
4104                                                   true);
4105
4106  // Ensure that we've loaded all potentially-interesting declarations
4107  // that need to be eagerly loaded.
4108  for (auto ID : EagerlyDeserializedDecls)
4109    GetDecl(ID);
4110  EagerlyDeserializedDecls.clear();
4111
4112  while (!PotentiallyInterestingDecls.empty()) {
4113    InterestingDecl D = PotentiallyInterestingDecls.front();
4114    PotentiallyInterestingDecls.pop_front();
4115    if (isConsumerInterestedIn(getContext(), D.getDecl(), D.hasPendingBody()))
4116      PassInterestingDeclToConsumer(D.getDecl());
4117  }
4118}
4119
4120void ASTReader::loadDeclUpdateRecords(PendingUpdateRecord &Record) {
4121  // The declaration may have been modified by files later in the chain.
4122  // If this is the case, read the record containing the updates from each file
4123  // and pass it to ASTDeclReader to make the modifications.
4124  serialization::GlobalDeclID ID = Record.ID;
4125  Decl *D = Record.D;
4126  ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
4127  DeclUpdateOffsetsMap::iterator UpdI = DeclUpdateOffsets.find(ID);
4128
4129  SmallVector<serialization::DeclID, 8> PendingLazySpecializationIDs;
4130
4131  if (UpdI != DeclUpdateOffsets.end()) {
4132    auto UpdateOffsets = std::move(UpdI->second);
4133    DeclUpdateOffsets.erase(UpdI);
4134
4135    // Check if this decl was interesting to the consumer. If we just loaded
4136    // the declaration, then we know it was interesting and we skip the call
4137    // to isConsumerInterestedIn because it is unsafe to call in the
4138    // current ASTReader state.
4139    bool WasInteresting =
4140        Record.JustLoaded || isConsumerInterestedIn(getContext(), D, false);
4141    for (auto &FileAndOffset : UpdateOffsets) {
4142      ModuleFile *F = FileAndOffset.first;
4143      uint64_t Offset = FileAndOffset.second;
4144      llvm::BitstreamCursor &Cursor = F->DeclsCursor;
4145      SavedStreamPosition SavedPosition(Cursor);
4146      if (llvm::Error JumpFailed = Cursor.JumpToBit(Offset))
4147        // FIXME don't do a fatal error.
4148        llvm::report_fatal_error(
4149            "ASTReader::loadDeclUpdateRecords failed jumping: " +
4150            toString(std::move(JumpFailed)));
4151      Expected<unsigned> MaybeCode = Cursor.ReadCode();
4152      if (!MaybeCode)
4153        llvm::report_fatal_error(
4154            "ASTReader::loadDeclUpdateRecords failed reading code: " +
4155            toString(MaybeCode.takeError()));
4156      unsigned Code = MaybeCode.get();
4157      ASTRecordReader Record(*this, *F);
4158      if (Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code))
4159        assert(MaybeRecCode.get() == DECL_UPDATES &&
4160               "Expected DECL_UPDATES record!");
4161      else
4162        llvm::report_fatal_error(
4163            "ASTReader::loadDeclUpdateRecords failed reading rec code: " +
4164            toString(MaybeCode.takeError()));
4165
4166      ASTDeclReader Reader(*this, Record, RecordLocation(F, Offset), ID,
4167                           SourceLocation());
4168      Reader.UpdateDecl(D, PendingLazySpecializationIDs);
4169
4170      // We might have made this declaration interesting. If so, remember that
4171      // we need to hand it off to the consumer.
4172      if (!WasInteresting &&
4173          isConsumerInterestedIn(getContext(), D, Reader.hasPendingBody())) {
4174        PotentiallyInterestingDecls.push_back(
4175            InterestingDecl(D, Reader.hasPendingBody()));
4176        WasInteresting = true;
4177      }
4178    }
4179  }
4180  // Add the lazy specializations to the template.
4181  assert((PendingLazySpecializationIDs.empty() || isa<ClassTemplateDecl>(D) ||
4182          isa<FunctionTemplateDecl>(D) || isa<VarTemplateDecl>(D)) &&
4183         "Must not have pending specializations");
4184  if (auto *CTD = dyn_cast<ClassTemplateDecl>(D))
4185    ASTDeclReader::AddLazySpecializations(CTD, PendingLazySpecializationIDs);
4186  else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
4187    ASTDeclReader::AddLazySpecializations(FTD, PendingLazySpecializationIDs);
4188  else if (auto *VTD = dyn_cast<VarTemplateDecl>(D))
4189    ASTDeclReader::AddLazySpecializations(VTD, PendingLazySpecializationIDs);
4190  PendingLazySpecializationIDs.clear();
4191
4192  // Load the pending visible updates for this decl context, if it has any.
4193  auto I = PendingVisibleUpdates.find(ID);
4194  if (I != PendingVisibleUpdates.end()) {
4195    auto VisibleUpdates = std::move(I->second);
4196    PendingVisibleUpdates.erase(I);
4197
4198    auto *DC = cast<DeclContext>(D)->getPrimaryContext();
4199    for (const auto &Update : VisibleUpdates)
4200      Lookups[DC].Table.add(
4201          Update.Mod, Update.Data,
4202          reader::ASTDeclContextNameLookupTrait(*this, *Update.Mod));
4203    DC->setHasExternalVisibleStorage(true);
4204  }
4205}
4206
4207void ASTReader::loadPendingDeclChain(Decl *FirstLocal, uint64_t LocalOffset) {
4208  // Attach FirstLocal to the end of the decl chain.
4209  Decl *CanonDecl = FirstLocal->getCanonicalDecl();
4210  if (FirstLocal != CanonDecl) {
4211    Decl *PrevMostRecent = ASTDeclReader::getMostRecentDecl(CanonDecl);
4212    ASTDeclReader::attachPreviousDecl(
4213        *this, FirstLocal, PrevMostRecent ? PrevMostRecent : CanonDecl,
4214        CanonDecl);
4215  }
4216
4217  if (!LocalOffset) {
4218    ASTDeclReader::attachLatestDecl(CanonDecl, FirstLocal);
4219    return;
4220  }
4221
4222  // Load the list of other redeclarations from this module file.
4223  ModuleFile *M = getOwningModuleFile(FirstLocal);
4224  assert(M && "imported decl from no module file");
4225
4226  llvm::BitstreamCursor &Cursor = M->DeclsCursor;
4227  SavedStreamPosition SavedPosition(Cursor);
4228  if (llvm::Error JumpFailed = Cursor.JumpToBit(LocalOffset))
4229    llvm::report_fatal_error(
4230        "ASTReader::loadPendingDeclChain failed jumping: " +
4231        toString(std::move(JumpFailed)));
4232
4233  RecordData Record;
4234  Expected<unsigned> MaybeCode = Cursor.ReadCode();
4235  if (!MaybeCode)
4236    llvm::report_fatal_error(
4237        "ASTReader::loadPendingDeclChain failed reading code: " +
4238        toString(MaybeCode.takeError()));
4239  unsigned Code = MaybeCode.get();
4240  if (Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record))
4241    assert(MaybeRecCode.get() == LOCAL_REDECLARATIONS &&
4242           "expected LOCAL_REDECLARATIONS record!");
4243  else
4244    llvm::report_fatal_error(
4245        "ASTReader::loadPendingDeclChain failed reading rec code: " +
4246        toString(MaybeCode.takeError()));
4247
4248  // FIXME: We have several different dispatches on decl kind here; maybe
4249  // we should instead generate one loop per kind and dispatch up-front?
4250  Decl *MostRecent = FirstLocal;
4251  for (unsigned I = 0, N = Record.size(); I != N; ++I) {
4252    auto *D = GetLocalDecl(*M, Record[N - I - 1]);
4253    ASTDeclReader::attachPreviousDecl(*this, D, MostRecent, CanonDecl);
4254    MostRecent = D;
4255  }
4256  ASTDeclReader::attachLatestDecl(CanonDecl, MostRecent);
4257}
4258
4259namespace {
4260
4261  /// Given an ObjC interface, goes through the modules and links to the
4262  /// interface all the categories for it.
4263  class ObjCCategoriesVisitor {
4264    ASTReader &Reader;
4265    ObjCInterfaceDecl *Interface;
4266    llvm::SmallPtrSetImpl<ObjCCategoryDecl *> &Deserialized;
4267    ObjCCategoryDecl *Tail = nullptr;
4268    llvm::DenseMap<DeclarationName, ObjCCategoryDecl *> NameCategoryMap;
4269    serialization::GlobalDeclID InterfaceID;
4270    unsigned PreviousGeneration;
4271
4272    void add(ObjCCategoryDecl *Cat) {
4273      // Only process each category once.
4274      if (!Deserialized.erase(Cat))
4275        return;
4276
4277      // Check for duplicate categories.
4278      if (Cat->getDeclName()) {
4279        ObjCCategoryDecl *&Existing = NameCategoryMap[Cat->getDeclName()];
4280        if (Existing &&
4281            Reader.getOwningModuleFile(Existing)
4282                                          != Reader.getOwningModuleFile(Cat)) {
4283          // FIXME: We should not warn for duplicates in diamond:
4284          //
4285          //   MT     //
4286          //  /  \    //
4287          // ML  MR   //
4288          //  \  /    //
4289          //   MB     //
4290          //
4291          // If there are duplicates in ML/MR, there will be warning when
4292          // creating MB *and* when importing MB. We should not warn when
4293          // importing.
4294          Reader.Diag(Cat->getLocation(), diag::warn_dup_category_def)
4295            << Interface->getDeclName() << Cat->getDeclName();
4296          Reader.Diag(Existing->getLocation(), diag::note_previous_definition);
4297        } else if (!Existing) {
4298          // Record this category.
4299          Existing = Cat;
4300        }
4301      }
4302
4303      // Add this category to the end of the chain.
4304      if (Tail)
4305        ASTDeclReader::setNextObjCCategory(Tail, Cat);
4306      else
4307        Interface->setCategoryListRaw(Cat);
4308      Tail = Cat;
4309    }
4310
4311  public:
4312    ObjCCategoriesVisitor(ASTReader &Reader,
4313                          ObjCInterfaceDecl *Interface,
4314                          llvm::SmallPtrSetImpl<ObjCCategoryDecl *> &Deserialized,
4315                          serialization::GlobalDeclID InterfaceID,
4316                          unsigned PreviousGeneration)
4317        : Reader(Reader), Interface(Interface), Deserialized(Deserialized),
4318          InterfaceID(InterfaceID), PreviousGeneration(PreviousGeneration) {
4319      // Populate the name -> category map with the set of known categories.
4320      for (auto *Cat : Interface->known_categories()) {
4321        if (Cat->getDeclName())
4322          NameCategoryMap[Cat->getDeclName()] = Cat;
4323
4324        // Keep track of the tail of the category list.
4325        Tail = Cat;
4326      }
4327    }
4328
4329    bool operator()(ModuleFile &M) {
4330      // If we've loaded all of the category information we care about from
4331      // this module file, we're done.
4332      if (M.Generation <= PreviousGeneration)
4333        return true;
4334
4335      // Map global ID of the definition down to the local ID used in this
4336      // module file. If there is no such mapping, we'll find nothing here
4337      // (or in any module it imports).
4338      DeclID LocalID = Reader.mapGlobalIDToModuleFileGlobalID(M, InterfaceID);
4339      if (!LocalID)
4340        return true;
4341
4342      // Perform a binary search to find the local redeclarations for this
4343      // declaration (if any).
4344      const ObjCCategoriesInfo Compare = { LocalID, 0 };
4345      const ObjCCategoriesInfo *Result
4346        = std::lower_bound(M.ObjCCategoriesMap,
4347                           M.ObjCCategoriesMap + M.LocalNumObjCCategoriesInMap,
4348                           Compare);
4349      if (Result == M.ObjCCategoriesMap + M.LocalNumObjCCategoriesInMap ||
4350          Result->DefinitionID != LocalID) {
4351        // We didn't find anything. If the class definition is in this module
4352        // file, then the module files it depends on cannot have any categories,
4353        // so suppress further lookup.
4354        return Reader.isDeclIDFromModule(InterfaceID, M);
4355      }
4356
4357      // We found something. Dig out all of the categories.
4358      unsigned Offset = Result->Offset;
4359      unsigned N = M.ObjCCategories[Offset];
4360      M.ObjCCategories[Offset++] = 0; // Don't try to deserialize again
4361      for (unsigned I = 0; I != N; ++I)
4362        add(cast_or_null<ObjCCategoryDecl>(
4363              Reader.GetLocalDecl(M, M.ObjCCategories[Offset++])));
4364      return true;
4365    }
4366  };
4367
4368} // namespace
4369
4370void ASTReader::loadObjCCategories(serialization::GlobalDeclID ID,
4371                                   ObjCInterfaceDecl *D,
4372                                   unsigned PreviousGeneration) {
4373  ObjCCategoriesVisitor Visitor(*this, D, CategoriesDeserialized, ID,
4374                                PreviousGeneration);
4375  ModuleMgr.visit(Visitor);
4376}
4377
4378template<typename DeclT, typename Fn>
4379static void forAllLaterRedecls(DeclT *D, Fn F) {
4380  F(D);
4381
4382  // Check whether we've already merged D into its redeclaration chain.
4383  // MostRecent may or may not be nullptr if D has not been merged. If
4384  // not, walk the merged redecl chain and see if it's there.
4385  auto *MostRecent = D->getMostRecentDecl();
4386  bool Found = false;
4387  for (auto *Redecl = MostRecent; Redecl && !Found;
4388       Redecl = Redecl->getPreviousDecl())
4389    Found = (Redecl == D);
4390
4391  // If this declaration is merged, apply the functor to all later decls.
4392  if (Found) {
4393    for (auto *Redecl = MostRecent; Redecl != D;
4394         Redecl = Redecl->getPreviousDecl())
4395      F(Redecl);
4396  }
4397}
4398
4399void ASTDeclReader::UpdateDecl(Decl *D,
4400   llvm::SmallVectorImpl<serialization::DeclID> &PendingLazySpecializationIDs) {
4401  while (Record.getIdx() < Record.size()) {
4402    switch ((DeclUpdateKind)Record.readInt()) {
4403    case UPD_CXX_ADDED_IMPLICIT_MEMBER: {
4404      auto *RD = cast<CXXRecordDecl>(D);
4405      // FIXME: If we also have an update record for instantiating the
4406      // definition of D, we need that to happen before we get here.
4407      Decl *MD = Record.readDecl();
4408      assert(MD && "couldn't read decl from update record");
4409      // FIXME: We should call addHiddenDecl instead, to add the member
4410      // to its DeclContext.
4411      RD->addedMember(MD);
4412      break;
4413    }
4414
4415    case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
4416      // It will be added to the template's lazy specialization set.
4417      PendingLazySpecializationIDs.push_back(readDeclID());
4418      break;
4419
4420    case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE: {
4421      auto *Anon = readDeclAs<NamespaceDecl>();
4422
4423      // Each module has its own anonymous namespace, which is disjoint from
4424      // any other module's anonymous namespaces, so don't attach the anonymous
4425      // namespace at all.
4426      if (!Record.isModule()) {
4427        if (auto *TU = dyn_cast<TranslationUnitDecl>(D))
4428          TU->setAnonymousNamespace(Anon);
4429        else
4430          cast<NamespaceDecl>(D)->setAnonymousNamespace(Anon);
4431      }
4432      break;
4433    }
4434
4435    case UPD_CXX_ADDED_VAR_DEFINITION: {
4436      auto *VD = cast<VarDecl>(D);
4437      VD->NonParmVarDeclBits.IsInline = Record.readInt();
4438      VD->NonParmVarDeclBits.IsInlineSpecified = Record.readInt();
4439      uint64_t Val = Record.readInt();
4440      if (Val && !VD->getInit()) {
4441        VD->setInit(Record.readExpr());
4442        if (Val > 1) { // IsInitKnownICE = 1, IsInitNotICE = 2, IsInitICE = 3
4443          EvaluatedStmt *Eval = VD->ensureEvaluatedStmt();
4444          Eval->CheckedICE = true;
4445          Eval->IsICE = Val == 3;
4446        }
4447      }
4448      break;
4449    }
4450
4451    case UPD_CXX_POINT_OF_INSTANTIATION: {
4452      SourceLocation POI = Record.readSourceLocation();
4453      if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D)) {
4454        VTSD->setPointOfInstantiation(POI);
4455      } else if (auto *VD = dyn_cast<VarDecl>(D)) {
4456        VD->getMemberSpecializationInfo()->setPointOfInstantiation(POI);
4457      } else {
4458        auto *FD = cast<FunctionDecl>(D);
4459        if (auto *FTSInfo = FD->TemplateOrSpecialization
4460                    .dyn_cast<FunctionTemplateSpecializationInfo *>())
4461          FTSInfo->setPointOfInstantiation(POI);
4462        else
4463          FD->TemplateOrSpecialization.get<MemberSpecializationInfo *>()
4464              ->setPointOfInstantiation(POI);
4465      }
4466      break;
4467    }
4468
4469    case UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT: {
4470      auto *Param = cast<ParmVarDecl>(D);
4471
4472      // We have to read the default argument regardless of whether we use it
4473      // so that hypothetical further update records aren't messed up.
4474      // TODO: Add a function to skip over the next expr record.
4475      auto *DefaultArg = Record.readExpr();
4476
4477      // Only apply the update if the parameter still has an uninstantiated
4478      // default argument.
4479      if (Param->hasUninstantiatedDefaultArg())
4480        Param->setDefaultArg(DefaultArg);
4481      break;
4482    }
4483
4484    case UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER: {
4485      auto *FD = cast<FieldDecl>(D);
4486      auto *DefaultInit = Record.readExpr();
4487
4488      // Only apply the update if the field still has an uninstantiated
4489      // default member initializer.
4490      if (FD->hasInClassInitializer() && !FD->getInClassInitializer()) {
4491        if (DefaultInit)
4492          FD->setInClassInitializer(DefaultInit);
4493        else
4494          // Instantiation failed. We can get here if we serialized an AST for
4495          // an invalid program.
4496          FD->removeInClassInitializer();
4497      }
4498      break;
4499    }
4500
4501    case UPD_CXX_ADDED_FUNCTION_DEFINITION: {
4502      auto *FD = cast<FunctionDecl>(D);
4503      if (Reader.PendingBodies[FD]) {
4504        // FIXME: Maybe check for ODR violations.
4505        // It's safe to stop now because this update record is always last.
4506        return;
4507      }
4508
4509      if (Record.readInt()) {
4510        // Maintain AST consistency: any later redeclarations of this function
4511        // are inline if this one is. (We might have merged another declaration
4512        // into this one.)
4513        forAllLaterRedecls(FD, [](FunctionDecl *FD) {
4514          FD->setImplicitlyInline();
4515        });
4516      }
4517      FD->setInnerLocStart(readSourceLocation());
4518      ReadFunctionDefinition(FD);
4519      assert(Record.getIdx() == Record.size() && "lazy body must be last");
4520      break;
4521    }
4522
4523    case UPD_CXX_INSTANTIATED_CLASS_DEFINITION: {
4524      auto *RD = cast<CXXRecordDecl>(D);
4525      auto *OldDD = RD->getCanonicalDecl()->DefinitionData;
4526      bool HadRealDefinition =
4527          OldDD && (OldDD->Definition != RD ||
4528                    !Reader.PendingFakeDefinitionData.count(OldDD));
4529      RD->setParamDestroyedInCallee(Record.readInt());
4530      RD->setArgPassingRestrictions(
4531          (RecordDecl::ArgPassingKind)Record.readInt());
4532      ReadCXXRecordDefinition(RD, /*Update*/true);
4533
4534      // Visible update is handled separately.
4535      uint64_t LexicalOffset = ReadLocalOffset();
4536      if (!HadRealDefinition && LexicalOffset) {
4537        Record.readLexicalDeclContextStorage(LexicalOffset, RD);
4538        Reader.PendingFakeDefinitionData.erase(OldDD);
4539      }
4540
4541      auto TSK = (TemplateSpecializationKind)Record.readInt();
4542      SourceLocation POI = readSourceLocation();
4543      if (MemberSpecializationInfo *MSInfo =
4544              RD->getMemberSpecializationInfo()) {
4545        MSInfo->setTemplateSpecializationKind(TSK);
4546        MSInfo->setPointOfInstantiation(POI);
4547      } else {
4548        auto *Spec = cast<ClassTemplateSpecializationDecl>(RD);
4549        Spec->setTemplateSpecializationKind(TSK);
4550        Spec->setPointOfInstantiation(POI);
4551
4552        if (Record.readInt()) {
4553          auto *PartialSpec =
4554              readDeclAs<ClassTemplatePartialSpecializationDecl>();
4555          SmallVector<TemplateArgument, 8> TemplArgs;
4556          Record.readTemplateArgumentList(TemplArgs);
4557          auto *TemplArgList = TemplateArgumentList::CreateCopy(
4558              Reader.getContext(), TemplArgs);
4559
4560          // FIXME: If we already have a partial specialization set,
4561          // check that it matches.
4562          if (!Spec->getSpecializedTemplateOrPartial()
4563                   .is<ClassTemplatePartialSpecializationDecl *>())
4564            Spec->setInstantiationOf(PartialSpec, TemplArgList);
4565        }
4566      }
4567
4568      RD->setTagKind((TagTypeKind)Record.readInt());
4569      RD->setLocation(readSourceLocation());
4570      RD->setLocStart(readSourceLocation());
4571      RD->setBraceRange(readSourceRange());
4572
4573      if (Record.readInt()) {
4574        AttrVec Attrs;
4575        Record.readAttributes(Attrs);
4576        // If the declaration already has attributes, we assume that some other
4577        // AST file already loaded them.
4578        if (!D->hasAttrs())
4579          D->setAttrsImpl(Attrs, Reader.getContext());
4580      }
4581      break;
4582    }
4583
4584    case UPD_CXX_RESOLVED_DTOR_DELETE: {
4585      // Set the 'operator delete' directly to avoid emitting another update
4586      // record.
4587      auto *Del = readDeclAs<FunctionDecl>();
4588      auto *First = cast<CXXDestructorDecl>(D->getCanonicalDecl());
4589      auto *ThisArg = Record.readExpr();
4590      // FIXME: Check consistency if we have an old and new operator delete.
4591      if (!First->OperatorDelete) {
4592        First->OperatorDelete = Del;
4593        First->OperatorDeleteThisArg = ThisArg;
4594      }
4595      break;
4596    }
4597
4598    case UPD_CXX_RESOLVED_EXCEPTION_SPEC: {
4599      SmallVector<QualType, 8> ExceptionStorage;
4600      auto ESI = Record.readExceptionSpecInfo(ExceptionStorage);
4601
4602      // Update this declaration's exception specification, if needed.
4603      auto *FD = cast<FunctionDecl>(D);
4604      auto *FPT = FD->getType()->castAs<FunctionProtoType>();
4605      // FIXME: If the exception specification is already present, check that it
4606      // matches.
4607      if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
4608        FD->setType(Reader.getContext().getFunctionType(
4609            FPT->getReturnType(), FPT->getParamTypes(),
4610            FPT->getExtProtoInfo().withExceptionSpec(ESI)));
4611
4612        // When we get to the end of deserializing, see if there are other decls
4613        // that we need to propagate this exception specification onto.
4614        Reader.PendingExceptionSpecUpdates.insert(
4615            std::make_pair(FD->getCanonicalDecl(), FD));
4616      }
4617      break;
4618    }
4619
4620    case UPD_CXX_DEDUCED_RETURN_TYPE: {
4621      auto *FD = cast<FunctionDecl>(D);
4622      QualType DeducedResultType = Record.readType();
4623      Reader.PendingDeducedTypeUpdates.insert(
4624          {FD->getCanonicalDecl(), DeducedResultType});
4625      break;
4626    }
4627
4628    case UPD_DECL_MARKED_USED:
4629      // Maintain AST consistency: any later redeclarations are used too.
4630      D->markUsed(Reader.getContext());
4631      break;
4632
4633    case UPD_MANGLING_NUMBER:
4634      Reader.getContext().setManglingNumber(cast<NamedDecl>(D),
4635                                            Record.readInt());
4636      break;
4637
4638    case UPD_STATIC_LOCAL_NUMBER:
4639      Reader.getContext().setStaticLocalNumber(cast<VarDecl>(D),
4640                                               Record.readInt());
4641      break;
4642
4643    case UPD_DECL_MARKED_OPENMP_THREADPRIVATE:
4644      D->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
4645          Reader.getContext(), readSourceRange(),
4646          AttributeCommonInfo::AS_Pragma));
4647      break;
4648
4649    case UPD_DECL_MARKED_OPENMP_ALLOCATE: {
4650      auto AllocatorKind =
4651          static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(Record.readInt());
4652      Expr *Allocator = Record.readExpr();
4653      SourceRange SR = readSourceRange();
4654      D->addAttr(OMPAllocateDeclAttr::CreateImplicit(
4655          Reader.getContext(), AllocatorKind, Allocator, SR,
4656          AttributeCommonInfo::AS_Pragma));
4657      break;
4658    }
4659
4660    case UPD_DECL_EXPORTED: {
4661      unsigned SubmoduleID = readSubmoduleID();
4662      auto *Exported = cast<NamedDecl>(D);
4663      Module *Owner = SubmoduleID ? Reader.getSubmodule(SubmoduleID) : nullptr;
4664      Reader.getContext().mergeDefinitionIntoModule(Exported, Owner);
4665      Reader.PendingMergedDefinitionsToDeduplicate.insert(Exported);
4666      break;
4667    }
4668
4669    case UPD_DECL_MARKED_OPENMP_DECLARETARGET: {
4670      OMPDeclareTargetDeclAttr::MapTypeTy MapType =
4671          static_cast<OMPDeclareTargetDeclAttr::MapTypeTy>(Record.readInt());
4672      OMPDeclareTargetDeclAttr::DevTypeTy DevType =
4673          static_cast<OMPDeclareTargetDeclAttr::DevTypeTy>(Record.readInt());
4674      D->addAttr(OMPDeclareTargetDeclAttr::CreateImplicit(
4675          Reader.getContext(), MapType, DevType, readSourceRange(),
4676          AttributeCommonInfo::AS_Pragma));
4677      break;
4678    }
4679
4680    case UPD_ADDED_ATTR_TO_RECORD:
4681      AttrVec Attrs;
4682      Record.readAttributes(Attrs);
4683      assert(Attrs.size() == 1);
4684      D->addAttr(Attrs[0]);
4685      break;
4686    }
4687  }
4688}
4689