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