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