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