1 //===- ASTReaderDecl.cpp - Decl Deserialization ---------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file implements the ASTReader::ReadDeclRecord method, which is the
10 // entrypoint for loading a decl.
12 //===----------------------------------------------------------------------===//
14 #include "ASTCommon.h"
15 #include "ASTReaderInternals.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/Attr.h"
18 #include "clang/AST/AttrIterator.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/DeclBase.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclFriend.h"
23 #include "clang/AST/DeclObjC.h"
24 #include "clang/AST/DeclOpenMP.h"
25 #include "clang/AST/DeclTemplate.h"
26 #include "clang/AST/DeclVisitor.h"
27 #include "clang/AST/DeclarationName.h"
28 #include "clang/AST/Expr.h"
29 #include "clang/AST/ExternalASTSource.h"
30 #include "clang/AST/LambdaCapture.h"
31 #include "clang/AST/NestedNameSpecifier.h"
32 #include "clang/AST/OpenMPClause.h"
33 #include "clang/AST/Redeclarable.h"
34 #include "clang/AST/Stmt.h"
35 #include "clang/AST/TemplateBase.h"
36 #include "clang/AST/Type.h"
37 #include "clang/AST/UnresolvedSet.h"
38 #include "clang/Basic/AttrKinds.h"
39 #include "clang/Basic/ExceptionSpecificationType.h"
40 #include "clang/Basic/IdentifierTable.h"
41 #include "clang/Basic/LLVM.h"
42 #include "clang/Basic/Lambda.h"
43 #include "clang/Basic/LangOptions.h"
44 #include "clang/Basic/Linkage.h"
45 #include "clang/Basic/Module.h"
46 #include "clang/Basic/PragmaKinds.h"
47 #include "clang/Basic/SourceLocation.h"
48 #include "clang/Basic/Specifiers.h"
49 #include "clang/Sema/IdentifierResolver.h"
50 #include "clang/Serialization/ASTBitCodes.h"
51 #include "clang/Serialization/ASTReader.h"
52 #include "clang/Serialization/ContinuousRangeMap.h"
53 #include "clang/Serialization/Module.h"
54 #include "llvm/ADT/DenseMap.h"
55 #include "llvm/ADT/FoldingSet.h"
56 #include "llvm/ADT/STLExtras.h"
57 #include "llvm/ADT/SmallPtrSet.h"
58 #include "llvm/ADT/SmallVector.h"
59 #include "llvm/ADT/iterator_range.h"
60 #include "llvm/Bitstream/BitstreamReader.h"
61 #include "llvm/Support/Casting.h"
62 #include "llvm/Support/ErrorHandling.h"
63 #include "llvm/Support/SaveAndRestore.h"
71 using namespace clang;
72 using namespace serialization;
74 //===----------------------------------------------------------------------===//
75 // Declaration deserialization
76 //===----------------------------------------------------------------------===//
80 class ASTDeclReader : public DeclVisitor<ASTDeclReader, void> {
82 ASTRecordReader &Record;
83 ASTReader::RecordLocation Loc;
84 const DeclID ThisDeclID;
85 const SourceLocation ThisDeclLoc;
87 using RecordData = ASTReader::RecordData;
89 TypeID DeferredTypeID = 0;
90 unsigned AnonymousDeclNumber;
91 GlobalDeclID NamedDeclForTagDecl = 0;
92 IdentifierInfo *TypedefNameForLinkage = nullptr;
94 bool HasPendingBody = false;
96 ///A flag to carry the information for a decl from the entity is
97 /// used. We use it to delay the marking of the canonical decl as used until
98 /// the entire declaration is deserialized and merged.
99 bool IsDeclMarkedUsed = false;
101 uint64_t GetCurrentCursorOffset();
103 uint64_t ReadLocalOffset() {
104 uint64_t LocalOffset = Record.readInt();
105 assert(LocalOffset < Loc.Offset && "offset point after current record");
106 return LocalOffset ? Loc.Offset - LocalOffset : 0;
109 uint64_t ReadGlobalOffset() {
110 uint64_t Local = ReadLocalOffset();
111 return Local ? Record.getGlobalBitOffset(Local) : 0;
114 SourceLocation ReadSourceLocation() {
115 return Record.readSourceLocation();
118 SourceRange ReadSourceRange() {
119 return Record.readSourceRange();
122 TypeSourceInfo *GetTypeSourceInfo() {
123 return Record.getTypeSourceInfo();
126 serialization::DeclID ReadDeclID() {
127 return Record.readDeclID();
130 std::string ReadString() {
131 return Record.readString();
134 void ReadDeclIDList(SmallVectorImpl<DeclID> &IDs) {
135 for (unsigned I = 0, Size = Record.readInt(); I != Size; ++I)
136 IDs.push_back(ReadDeclID());
140 return Record.readDecl();
145 return Record.readDeclAs<T>();
148 void ReadQualifierInfo(QualifierInfo &Info) {
149 Record.readQualifierInfo(Info);
152 void ReadDeclarationNameLoc(DeclarationNameLoc &DNLoc, DeclarationName Name) {
153 Record.readDeclarationNameLoc(DNLoc, Name);
156 serialization::SubmoduleID readSubmoduleID() {
157 if (Record.getIdx() == Record.size())
160 return Record.getGlobalSubmoduleID(Record.readInt());
163 Module *readModule() {
164 return Record.getSubmodule(readSubmoduleID());
167 void ReadCXXRecordDefinition(CXXRecordDecl *D, bool Update);
168 void ReadCXXDefinitionData(struct CXXRecordDecl::DefinitionData &Data,
169 const CXXRecordDecl *D);
170 void MergeDefinitionData(CXXRecordDecl *D,
171 struct CXXRecordDecl::DefinitionData &&NewDD);
172 void ReadObjCDefinitionData(struct ObjCInterfaceDecl::DefinitionData &Data);
173 void MergeDefinitionData(ObjCInterfaceDecl *D,
174 struct ObjCInterfaceDecl::DefinitionData &&NewDD);
175 void ReadObjCDefinitionData(struct ObjCProtocolDecl::DefinitionData &Data);
176 void MergeDefinitionData(ObjCProtocolDecl *D,
177 struct ObjCProtocolDecl::DefinitionData &&NewDD);
179 static DeclContext *getPrimaryDCForAnonymousDecl(DeclContext *LexicalDC);
181 static NamedDecl *getAnonymousDeclForMerging(ASTReader &Reader,
184 static void setAnonymousDeclForMerging(ASTReader &Reader, DeclContext *DC,
185 unsigned Index, NamedDecl *D);
187 /// Results from loading a RedeclarableDecl.
188 class RedeclarableResult {
190 GlobalDeclID FirstID;
194 RedeclarableResult(Decl *MergeWith, GlobalDeclID FirstID, bool IsKeyDecl)
195 : MergeWith(MergeWith), FirstID(FirstID), IsKeyDecl(IsKeyDecl) {}
197 /// Retrieve the first ID.
198 GlobalDeclID getFirstID() const { return FirstID; }
200 /// Is this declaration a key declaration?
201 bool isKeyDecl() const { return IsKeyDecl; }
203 /// Get a known declaration that this should be merged with, if
205 Decl *getKnownMergeTarget() const { return MergeWith; }
208 /// Class used to capture the result of searching for an existing
209 /// declaration of a specific kind and name, along with the ability
210 /// to update the place where this result was found (the declaration
211 /// chain hanging off an identifier or the DeclContext we searched in)
213 class FindExistingResult {
215 NamedDecl *New = nullptr;
216 NamedDecl *Existing = nullptr;
217 bool AddResult = false;
218 unsigned AnonymousDeclNumber = 0;
219 IdentifierInfo *TypedefNameForLinkage = nullptr;
222 FindExistingResult(ASTReader &Reader) : Reader(Reader) {}
224 FindExistingResult(ASTReader &Reader, NamedDecl *New, NamedDecl *Existing,
225 unsigned AnonymousDeclNumber,
226 IdentifierInfo *TypedefNameForLinkage)
227 : Reader(Reader), New(New), Existing(Existing), AddResult(true),
228 AnonymousDeclNumber(AnonymousDeclNumber),
229 TypedefNameForLinkage(TypedefNameForLinkage) {}
231 FindExistingResult(FindExistingResult &&Other)
232 : Reader(Other.Reader), New(Other.New), Existing(Other.Existing),
233 AddResult(Other.AddResult),
234 AnonymousDeclNumber(Other.AnonymousDeclNumber),
235 TypedefNameForLinkage(Other.TypedefNameForLinkage) {
236 Other.AddResult = false;
239 FindExistingResult &operator=(FindExistingResult &&) = delete;
240 ~FindExistingResult();
242 /// Suppress the addition of this result into the known set of
244 void suppress() { AddResult = false; }
246 operator NamedDecl*() const { return Existing; }
249 operator T*() const { return dyn_cast_or_null<T>(Existing); }
252 static DeclContext *getPrimaryContextForMerging(ASTReader &Reader,
254 FindExistingResult findExisting(NamedDecl *D);
257 ASTDeclReader(ASTReader &Reader, ASTRecordReader &Record,
258 ASTReader::RecordLocation Loc,
259 DeclID thisDeclID, SourceLocation ThisDeclLoc)
260 : Reader(Reader), Record(Record), Loc(Loc), ThisDeclID(thisDeclID),
261 ThisDeclLoc(ThisDeclLoc) {}
263 template <typename T> static
264 void AddLazySpecializations(T *D,
265 SmallVectorImpl<serialization::DeclID>& IDs) {
269 // FIXME: We should avoid this pattern of getting the ASTContext.
270 ASTContext &C = D->getASTContext();
272 auto *&LazySpecializations = D->getCommonPtr()->LazySpecializations;
274 if (auto &Old = LazySpecializations) {
275 IDs.insert(IDs.end(), Old + 1, Old + 1 + Old[0]);
277 IDs.erase(std::unique(IDs.begin(), IDs.end()), IDs.end());
280 auto *Result = new (C) serialization::DeclID[1 + IDs.size()];
281 *Result = IDs.size();
282 std::copy(IDs.begin(), IDs.end(), Result + 1);
284 LazySpecializations = Result;
287 template <typename DeclT>
288 static Decl *getMostRecentDeclImpl(Redeclarable<DeclT> *D);
289 static Decl *getMostRecentDeclImpl(...);
290 static Decl *getMostRecentDecl(Decl *D);
292 template <typename DeclT>
293 static void attachPreviousDeclImpl(ASTReader &Reader,
294 Redeclarable<DeclT> *D, Decl *Previous,
296 static void attachPreviousDeclImpl(ASTReader &Reader, ...);
297 static void attachPreviousDecl(ASTReader &Reader, Decl *D, Decl *Previous,
300 template <typename DeclT>
301 static void attachLatestDeclImpl(Redeclarable<DeclT> *D, Decl *Latest);
302 static void attachLatestDeclImpl(...);
303 static void attachLatestDecl(Decl *D, Decl *latest);
305 template <typename DeclT>
306 static void markIncompleteDeclChainImpl(Redeclarable<DeclT> *D);
307 static void markIncompleteDeclChainImpl(...);
309 /// Determine whether this declaration has a pending body.
310 bool hasPendingBody() const { return HasPendingBody; }
312 void ReadFunctionDefinition(FunctionDecl *FD);
315 void UpdateDecl(Decl *D, SmallVectorImpl<serialization::DeclID> &);
317 static void setNextObjCCategory(ObjCCategoryDecl *Cat,
318 ObjCCategoryDecl *Next) {
319 Cat->NextClassCategory = Next;
322 void VisitDecl(Decl *D);
323 void VisitPragmaCommentDecl(PragmaCommentDecl *D);
324 void VisitPragmaDetectMismatchDecl(PragmaDetectMismatchDecl *D);
325 void VisitTranslationUnitDecl(TranslationUnitDecl *TU);
326 void VisitNamedDecl(NamedDecl *ND);
327 void VisitLabelDecl(LabelDecl *LD);
328 void VisitNamespaceDecl(NamespaceDecl *D);
329 void VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
330 void VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
331 void VisitTypeDecl(TypeDecl *TD);
332 RedeclarableResult VisitTypedefNameDecl(TypedefNameDecl *TD);
333 void VisitTypedefDecl(TypedefDecl *TD);
334 void VisitTypeAliasDecl(TypeAliasDecl *TD);
335 void VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
336 RedeclarableResult VisitTagDecl(TagDecl *TD);
337 void VisitEnumDecl(EnumDecl *ED);
338 RedeclarableResult VisitRecordDeclImpl(RecordDecl *RD);
339 void VisitRecordDecl(RecordDecl *RD) { VisitRecordDeclImpl(RD); }
340 RedeclarableResult VisitCXXRecordDeclImpl(CXXRecordDecl *D);
341 void VisitCXXRecordDecl(CXXRecordDecl *D) { VisitCXXRecordDeclImpl(D); }
342 RedeclarableResult VisitClassTemplateSpecializationDeclImpl(
343 ClassTemplateSpecializationDecl *D);
345 void VisitClassTemplateSpecializationDecl(
346 ClassTemplateSpecializationDecl *D) {
347 VisitClassTemplateSpecializationDeclImpl(D);
350 void VisitClassTemplatePartialSpecializationDecl(
351 ClassTemplatePartialSpecializationDecl *D);
352 void VisitClassScopeFunctionSpecializationDecl(
353 ClassScopeFunctionSpecializationDecl *D);
355 VisitVarTemplateSpecializationDeclImpl(VarTemplateSpecializationDecl *D);
357 void VisitVarTemplateSpecializationDecl(VarTemplateSpecializationDecl *D) {
358 VisitVarTemplateSpecializationDeclImpl(D);
361 void VisitVarTemplatePartialSpecializationDecl(
362 VarTemplatePartialSpecializationDecl *D);
363 void VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
364 void VisitValueDecl(ValueDecl *VD);
365 void VisitEnumConstantDecl(EnumConstantDecl *ECD);
366 void VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
367 void VisitDeclaratorDecl(DeclaratorDecl *DD);
368 void VisitFunctionDecl(FunctionDecl *FD);
369 void VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *GD);
370 void VisitCXXMethodDecl(CXXMethodDecl *D);
371 void VisitCXXConstructorDecl(CXXConstructorDecl *D);
372 void VisitCXXDestructorDecl(CXXDestructorDecl *D);
373 void VisitCXXConversionDecl(CXXConversionDecl *D);
374 void VisitFieldDecl(FieldDecl *FD);
375 void VisitMSPropertyDecl(MSPropertyDecl *FD);
376 void VisitIndirectFieldDecl(IndirectFieldDecl *FD);
377 RedeclarableResult VisitVarDeclImpl(VarDecl *D);
378 void VisitVarDecl(VarDecl *VD) { VisitVarDeclImpl(VD); }
379 void VisitImplicitParamDecl(ImplicitParamDecl *PD);
380 void VisitParmVarDecl(ParmVarDecl *PD);
381 void VisitDecompositionDecl(DecompositionDecl *DD);
382 void VisitBindingDecl(BindingDecl *BD);
383 void VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
384 DeclID VisitTemplateDecl(TemplateDecl *D);
385 void VisitConceptDecl(ConceptDecl *D);
386 RedeclarableResult VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D);
387 void VisitClassTemplateDecl(ClassTemplateDecl *D);
388 void VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D);
389 void VisitVarTemplateDecl(VarTemplateDecl *D);
390 void VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
391 void VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
392 void VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D);
393 void VisitUsingDecl(UsingDecl *D);
394 void VisitUsingPackDecl(UsingPackDecl *D);
395 void VisitUsingShadowDecl(UsingShadowDecl *D);
396 void VisitConstructorUsingShadowDecl(ConstructorUsingShadowDecl *D);
397 void VisitLinkageSpecDecl(LinkageSpecDecl *D);
398 void VisitExportDecl(ExportDecl *D);
399 void VisitFileScopeAsmDecl(FileScopeAsmDecl *AD);
400 void VisitImportDecl(ImportDecl *D);
401 void VisitAccessSpecDecl(AccessSpecDecl *D);
402 void VisitFriendDecl(FriendDecl *D);
403 void VisitFriendTemplateDecl(FriendTemplateDecl *D);
404 void VisitStaticAssertDecl(StaticAssertDecl *D);
405 void VisitBlockDecl(BlockDecl *BD);
406 void VisitCapturedDecl(CapturedDecl *CD);
407 void VisitEmptyDecl(EmptyDecl *D);
409 std::pair<uint64_t, uint64_t> VisitDeclContext(DeclContext *DC);
412 RedeclarableResult VisitRedeclarable(Redeclarable<T> *D);
415 void mergeRedeclarable(Redeclarable<T> *D, RedeclarableResult &Redecl,
416 DeclID TemplatePatternID = 0);
419 void mergeRedeclarable(Redeclarable<T> *D, T *Existing,
420 RedeclarableResult &Redecl,
421 DeclID TemplatePatternID = 0);
424 void mergeMergeable(Mergeable<T> *D);
426 void mergeTemplatePattern(RedeclarableTemplateDecl *D,
427 RedeclarableTemplateDecl *Existing,
428 DeclID DsID, bool IsKeyDecl);
430 ObjCTypeParamList *ReadObjCTypeParamList();
432 // FIXME: Reorder according to DeclNodes.td?
433 void VisitObjCMethodDecl(ObjCMethodDecl *D);
434 void VisitObjCTypeParamDecl(ObjCTypeParamDecl *D);
435 void VisitObjCContainerDecl(ObjCContainerDecl *D);
436 void VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
437 void VisitObjCIvarDecl(ObjCIvarDecl *D);
438 void VisitObjCProtocolDecl(ObjCProtocolDecl *D);
439 void VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D);
440 void VisitObjCCategoryDecl(ObjCCategoryDecl *D);
441 void VisitObjCImplDecl(ObjCImplDecl *D);
442 void VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
443 void VisitObjCImplementationDecl(ObjCImplementationDecl *D);
444 void VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *D);
445 void VisitObjCPropertyDecl(ObjCPropertyDecl *D);
446 void VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D);
447 void VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D);
448 void VisitOMPAllocateDecl(OMPAllocateDecl *D);
449 void VisitOMPDeclareReductionDecl(OMPDeclareReductionDecl *D);
450 void VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D);
451 void VisitOMPRequiresDecl(OMPRequiresDecl *D);
452 void VisitOMPCapturedExprDecl(OMPCapturedExprDecl *D);
459 /// Iterator over the redeclarations of a declaration that have already
460 /// been merged into the same redeclaration chain.
461 template<typename DeclT>
462 class MergedRedeclIterator {
464 DeclT *Canonical = nullptr;
465 DeclT *Current = nullptr;
468 MergedRedeclIterator() = default;
469 MergedRedeclIterator(DeclT *Start) : Start(Start), Current(Start) {}
471 DeclT *operator*() { return Current; }
473 MergedRedeclIterator &operator++() {
474 if (Current->isFirstDecl()) {
476 Current = Current->getMostRecentDecl();
478 Current = Current->getPreviousDecl();
480 // If we started in the merged portion, we'll reach our start position
481 // eventually. Otherwise, we'll never reach it, but the second declaration
482 // we reached was the canonical declaration, so stop when we see that one
484 if (Current == Start || Current == Canonical)
489 friend bool operator!=(const MergedRedeclIterator &A,
490 const MergedRedeclIterator &B) {
491 return A.Current != B.Current;
497 template <typename DeclT>
498 static llvm::iterator_range<MergedRedeclIterator<DeclT>>
499 merged_redecls(DeclT *D) {
500 return llvm::make_range(MergedRedeclIterator<DeclT>(D),
501 MergedRedeclIterator<DeclT>());
504 uint64_t ASTDeclReader::GetCurrentCursorOffset() {
505 return Loc.F->DeclsCursor.GetCurrentBitNo() + Loc.F->GlobalBitOffset;
508 void ASTDeclReader::ReadFunctionDefinition(FunctionDecl *FD) {
509 if (Record.readInt())
510 Reader.DefinitionSource[FD] = Loc.F->Kind == ModuleKind::MK_MainFile;
511 if (auto *CD = dyn_cast<CXXConstructorDecl>(FD)) {
512 CD->setNumCtorInitializers(Record.readInt());
513 if (CD->getNumCtorInitializers())
514 CD->CtorInitializers = ReadGlobalOffset();
516 // Store the offset of the body so we can lazily load it later.
517 Reader.PendingBodies[FD] = GetCurrentCursorOffset();
518 HasPendingBody = true;
521 void ASTDeclReader::Visit(Decl *D) {
522 DeclVisitor<ASTDeclReader, void>::Visit(D);
524 // At this point we have deserialized and merged the decl and it is safe to
525 // update its canonical decl to signal that the entire entity is used.
526 D->getCanonicalDecl()->Used |= IsDeclMarkedUsed;
527 IsDeclMarkedUsed = false;
529 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
530 if (auto *TInfo = DD->getTypeSourceInfo())
531 Record.readTypeLoc(TInfo->getTypeLoc());
534 if (auto *TD = dyn_cast<TypeDecl>(D)) {
535 // We have a fully initialized TypeDecl. Read its type now.
536 TD->setTypeForDecl(Reader.GetType(DeferredTypeID).getTypePtrOrNull());
538 // If this is a tag declaration with a typedef name for linkage, it's safe
539 // to load that typedef now.
540 if (NamedDeclForTagDecl)
541 cast<TagDecl>(D)->TypedefNameDeclOrQualifier =
542 cast<TypedefNameDecl>(Reader.GetDecl(NamedDeclForTagDecl));
543 } else if (auto *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
544 // if we have a fully initialized TypeDecl, we can safely read its type now.
545 ID->TypeForDecl = Reader.GetType(DeferredTypeID).getTypePtrOrNull();
546 } else if (auto *FD = dyn_cast<FunctionDecl>(D)) {
547 // FunctionDecl's body was written last after all other Stmts/Exprs.
548 // We only read it if FD doesn't already have a body (e.g., from another
550 // FIXME: Can we diagnose ODR violations somehow?
551 if (Record.readInt())
552 ReadFunctionDefinition(FD);
556 void ASTDeclReader::VisitDecl(Decl *D) {
557 if (D->isTemplateParameter() || D->isTemplateParameterPack() ||
558 isa<ParmVarDecl>(D)) {
559 // We don't want to deserialize the DeclContext of a template
560 // parameter or of a parameter of a function template immediately. These
561 // entities might be used in the formulation of its DeclContext (for
562 // example, a function parameter can be used in decltype() in trailing
563 // return type of the function). Use the translation unit DeclContext as a
565 GlobalDeclID SemaDCIDForTemplateParmDecl = ReadDeclID();
566 GlobalDeclID LexicalDCIDForTemplateParmDecl = ReadDeclID();
567 if (!LexicalDCIDForTemplateParmDecl)
568 LexicalDCIDForTemplateParmDecl = SemaDCIDForTemplateParmDecl;
569 Reader.addPendingDeclContextInfo(D,
570 SemaDCIDForTemplateParmDecl,
571 LexicalDCIDForTemplateParmDecl);
572 D->setDeclContext(Reader.getContext().getTranslationUnitDecl());
574 auto *SemaDC = ReadDeclAs<DeclContext>();
575 auto *LexicalDC = ReadDeclAs<DeclContext>();
578 DeclContext *MergedSemaDC = Reader.MergedDeclContexts.lookup(SemaDC);
579 // Avoid calling setLexicalDeclContext() directly because it uses
580 // Decl::getASTContext() internally which is unsafe during derialization.
581 D->setDeclContextsImpl(MergedSemaDC ? MergedSemaDC : SemaDC, LexicalDC,
582 Reader.getContext());
584 D->setLocation(ThisDeclLoc);
585 D->setInvalidDecl(Record.readInt());
586 if (Record.readInt()) { // hasAttrs
588 Record.readAttributes(Attrs);
589 // Avoid calling setAttrs() directly because it uses Decl::getASTContext()
590 // internally which is unsafe during derialization.
591 D->setAttrsImpl(Attrs, Reader.getContext());
593 D->setImplicit(Record.readInt());
594 D->Used = Record.readInt();
595 IsDeclMarkedUsed |= D->Used;
596 D->setReferenced(Record.readInt());
597 D->setTopLevelDeclInObjCContainer(Record.readInt());
598 D->setAccess((AccessSpecifier)Record.readInt());
599 D->FromASTFile = true;
600 bool ModulePrivate = Record.readInt();
602 // Determine whether this declaration is part of a (sub)module. If so, it
603 // may not yet be visible.
604 if (unsigned SubmoduleID = readSubmoduleID()) {
605 // Store the owning submodule ID in the declaration.
606 D->setModuleOwnershipKind(
607 ModulePrivate ? Decl::ModuleOwnershipKind::ModulePrivate
608 : Decl::ModuleOwnershipKind::VisibleWhenImported);
609 D->setOwningModuleID(SubmoduleID);
612 // Module-private declarations are never visible, so there is no work to
614 } else if (Reader.getContext().getLangOpts().ModulesLocalVisibility) {
615 // If local visibility is being tracked, this declaration will become
616 // hidden and visible as the owning module does.
617 } else if (Module *Owner = Reader.getSubmodule(SubmoduleID)) {
618 // Mark the declaration as visible when its owning module becomes visible.
619 if (Owner->NameVisibility == Module::AllVisible)
620 D->setVisibleDespiteOwningModule();
622 Reader.HiddenNamesMap[Owner].push_back(D);
624 } else if (ModulePrivate) {
625 D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate);
629 void ASTDeclReader::VisitPragmaCommentDecl(PragmaCommentDecl *D) {
631 D->setLocation(ReadSourceLocation());
632 D->CommentKind = (PragmaMSCommentKind)Record.readInt();
633 std::string Arg = ReadString();
634 memcpy(D->getTrailingObjects<char>(), Arg.data(), Arg.size());
635 D->getTrailingObjects<char>()[Arg.size()] = '\0';
638 void ASTDeclReader::VisitPragmaDetectMismatchDecl(PragmaDetectMismatchDecl *D) {
640 D->setLocation(ReadSourceLocation());
641 std::string Name = ReadString();
642 memcpy(D->getTrailingObjects<char>(), Name.data(), Name.size());
643 D->getTrailingObjects<char>()[Name.size()] = '\0';
645 D->ValueStart = Name.size() + 1;
646 std::string Value = ReadString();
647 memcpy(D->getTrailingObjects<char>() + D->ValueStart, Value.data(),
649 D->getTrailingObjects<char>()[D->ValueStart + Value.size()] = '\0';
652 void ASTDeclReader::VisitTranslationUnitDecl(TranslationUnitDecl *TU) {
653 llvm_unreachable("Translation units are not serialized");
656 void ASTDeclReader::VisitNamedDecl(NamedDecl *ND) {
658 ND->setDeclName(Record.readDeclarationName());
659 AnonymousDeclNumber = Record.readInt();
662 void ASTDeclReader::VisitTypeDecl(TypeDecl *TD) {
664 TD->setLocStart(ReadSourceLocation());
665 // Delay type reading until after we have fully initialized the decl.
666 DeferredTypeID = Record.getGlobalTypeID(Record.readInt());
669 ASTDeclReader::RedeclarableResult
670 ASTDeclReader::VisitTypedefNameDecl(TypedefNameDecl *TD) {
671 RedeclarableResult Redecl = VisitRedeclarable(TD);
673 TypeSourceInfo *TInfo = GetTypeSourceInfo();
674 if (Record.readInt()) { // isModed
675 QualType modedT = Record.readType();
676 TD->setModedTypeSourceInfo(TInfo, modedT);
678 TD->setTypeSourceInfo(TInfo);
679 // Read and discard the declaration for which this is a typedef name for
680 // linkage, if it exists. We cannot rely on our type to pull in this decl,
681 // because it might have been merged with a type from another module and
682 // thus might not refer to our version of the declaration.
687 void ASTDeclReader::VisitTypedefDecl(TypedefDecl *TD) {
688 RedeclarableResult Redecl = VisitTypedefNameDecl(TD);
689 mergeRedeclarable(TD, Redecl);
692 void ASTDeclReader::VisitTypeAliasDecl(TypeAliasDecl *TD) {
693 RedeclarableResult Redecl = VisitTypedefNameDecl(TD);
694 if (auto *Template = ReadDeclAs<TypeAliasTemplateDecl>())
695 // Merged when we merge the template.
696 TD->setDescribedAliasTemplate(Template);
698 mergeRedeclarable(TD, Redecl);
701 ASTDeclReader::RedeclarableResult ASTDeclReader::VisitTagDecl(TagDecl *TD) {
702 RedeclarableResult Redecl = VisitRedeclarable(TD);
705 TD->IdentifierNamespace = Record.readInt();
706 TD->setTagKind((TagDecl::TagKind)Record.readInt());
707 if (!isa<CXXRecordDecl>(TD))
708 TD->setCompleteDefinition(Record.readInt());
709 TD->setEmbeddedInDeclarator(Record.readInt());
710 TD->setFreeStanding(Record.readInt());
711 TD->setCompleteDefinitionRequired(Record.readInt());
712 TD->setBraceRange(ReadSourceRange());
714 switch (Record.readInt()) {
718 auto *Info = new (Reader.getContext()) TagDecl::ExtInfo();
719 ReadQualifierInfo(*Info);
720 TD->TypedefNameDeclOrQualifier = Info;
723 case 2: // TypedefNameForAnonDecl
724 NamedDeclForTagDecl = ReadDeclID();
725 TypedefNameForLinkage = Record.getIdentifierInfo();
728 llvm_unreachable("unexpected tag info kind");
731 if (!isa<CXXRecordDecl>(TD))
732 mergeRedeclarable(TD, Redecl);
736 void ASTDeclReader::VisitEnumDecl(EnumDecl *ED) {
738 if (TypeSourceInfo *TI = GetTypeSourceInfo())
739 ED->setIntegerTypeSourceInfo(TI);
741 ED->setIntegerType(Record.readType());
742 ED->setPromotionType(Record.readType());
743 ED->setNumPositiveBits(Record.readInt());
744 ED->setNumNegativeBits(Record.readInt());
745 ED->setScoped(Record.readInt());
746 ED->setScopedUsingClassTag(Record.readInt());
747 ED->setFixed(Record.readInt());
749 ED->setHasODRHash(true);
750 ED->ODRHash = Record.readInt();
752 // If this is a definition subject to the ODR, and we already have a
753 // definition, merge this one into it.
754 if (ED->isCompleteDefinition() &&
755 Reader.getContext().getLangOpts().Modules &&
756 Reader.getContext().getLangOpts().CPlusPlus) {
757 EnumDecl *&OldDef = Reader.EnumDefinitions[ED->getCanonicalDecl()];
759 // This is the first time we've seen an imported definition. Look for a
760 // local definition before deciding that we are the first definition.
761 for (auto *D : merged_redecls(ED->getCanonicalDecl())) {
762 if (!D->isFromASTFile() && D->isCompleteDefinition()) {
769 Reader.MergedDeclContexts.insert(std::make_pair(ED, OldDef));
770 ED->setCompleteDefinition(false);
771 Reader.mergeDefinitionVisibility(OldDef, ED);
772 if (OldDef->getODRHash() != ED->getODRHash())
773 Reader.PendingEnumOdrMergeFailures[OldDef].push_back(ED);
779 if (auto *InstED = ReadDeclAs<EnumDecl>()) {
780 auto TSK = (TemplateSpecializationKind)Record.readInt();
781 SourceLocation POI = ReadSourceLocation();
782 ED->setInstantiationOfMemberEnum(Reader.getContext(), InstED, TSK);
783 ED->getMemberSpecializationInfo()->setPointOfInstantiation(POI);
787 ASTDeclReader::RedeclarableResult
788 ASTDeclReader::VisitRecordDeclImpl(RecordDecl *RD) {
789 RedeclarableResult Redecl = VisitTagDecl(RD);
790 RD->setHasFlexibleArrayMember(Record.readInt());
791 RD->setAnonymousStructOrUnion(Record.readInt());
792 RD->setHasObjectMember(Record.readInt());
793 RD->setHasVolatileMember(Record.readInt());
794 RD->setNonTrivialToPrimitiveDefaultInitialize(Record.readInt());
795 RD->setNonTrivialToPrimitiveCopy(Record.readInt());
796 RD->setNonTrivialToPrimitiveDestroy(Record.readInt());
797 RD->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(Record.readInt());
798 RD->setHasNonTrivialToPrimitiveDestructCUnion(Record.readInt());
799 RD->setHasNonTrivialToPrimitiveCopyCUnion(Record.readInt());
800 RD->setParamDestroyedInCallee(Record.readInt());
801 RD->setArgPassingRestrictions((RecordDecl::ArgPassingKind)Record.readInt());
805 void ASTDeclReader::VisitValueDecl(ValueDecl *VD) {
807 // For function declarations, defer reading the type in case the function has
808 // a deduced return type that references an entity declared within the
810 if (isa<FunctionDecl>(VD))
811 DeferredTypeID = Record.getGlobalTypeID(Record.readInt());
813 VD->setType(Record.readType());
816 void ASTDeclReader::VisitEnumConstantDecl(EnumConstantDecl *ECD) {
818 if (Record.readInt())
819 ECD->setInitExpr(Record.readExpr());
820 ECD->setInitVal(Record.readAPSInt());
824 void ASTDeclReader::VisitDeclaratorDecl(DeclaratorDecl *DD) {
826 DD->setInnerLocStart(ReadSourceLocation());
827 if (Record.readInt()) { // hasExtInfo
828 auto *Info = new (Reader.getContext()) DeclaratorDecl::ExtInfo();
829 ReadQualifierInfo(*Info);
832 QualType TSIType = Record.readType();
833 DD->setTypeSourceInfo(
834 TSIType.isNull() ? nullptr
835 : Reader.getContext().CreateTypeSourceInfo(TSIType));
838 void ASTDeclReader::VisitFunctionDecl(FunctionDecl *FD) {
839 RedeclarableResult Redecl = VisitRedeclarable(FD);
840 VisitDeclaratorDecl(FD);
842 // Attach a type to this function. Use the real type if possible, but fall
843 // back to the type as written if it involves a deduced return type.
844 if (FD->getTypeSourceInfo() &&
845 FD->getTypeSourceInfo()->getType()->castAs<FunctionType>()
846 ->getReturnType()->getContainedAutoType()) {
847 // We'll set up the real type in Visit, once we've finished loading the
849 FD->setType(FD->getTypeSourceInfo()->getType());
850 Reader.PendingFunctionTypes.push_back({FD, DeferredTypeID});
852 FD->setType(Reader.GetType(DeferredTypeID));
856 ReadDeclarationNameLoc(FD->DNLoc, FD->getDeclName());
857 FD->IdentifierNamespace = Record.readInt();
859 // FunctionDecl's body is handled last at ASTDeclReader::Visit,
860 // after everything else is read.
862 FD->setStorageClass(static_cast<StorageClass>(Record.readInt()));
863 FD->setInlineSpecified(Record.readInt());
864 FD->setImplicitlyInline(Record.readInt());
865 FD->setVirtualAsWritten(Record.readInt());
866 FD->setPure(Record.readInt());
867 FD->setHasInheritedPrototype(Record.readInt());
868 FD->setHasWrittenPrototype(Record.readInt());
869 FD->setDeletedAsWritten(Record.readInt());
870 FD->setTrivial(Record.readInt());
871 FD->setTrivialForCall(Record.readInt());
872 FD->setDefaulted(Record.readInt());
873 FD->setExplicitlyDefaulted(Record.readInt());
874 FD->setHasImplicitReturnZero(Record.readInt());
875 FD->setConstexprKind(static_cast<ConstexprSpecKind>(Record.readInt()));
876 FD->setUsesSEHTry(Record.readInt());
877 FD->setHasSkippedBody(Record.readInt());
878 FD->setIsMultiVersion(Record.readInt());
879 FD->setLateTemplateParsed(Record.readInt());
881 FD->setCachedLinkage(static_cast<Linkage>(Record.readInt()));
882 FD->EndRangeLoc = ReadSourceLocation();
884 FD->ODRHash = Record.readInt();
885 FD->setHasODRHash(true);
887 switch ((FunctionDecl::TemplatedKind)Record.readInt()) {
888 case FunctionDecl::TK_NonTemplate:
889 mergeRedeclarable(FD, Redecl);
891 case FunctionDecl::TK_FunctionTemplate:
892 // Merged when we merge the template.
893 FD->setDescribedFunctionTemplate(ReadDeclAs<FunctionTemplateDecl>());
895 case FunctionDecl::TK_MemberSpecialization: {
896 auto *InstFD = ReadDeclAs<FunctionDecl>();
897 auto TSK = (TemplateSpecializationKind)Record.readInt();
898 SourceLocation POI = ReadSourceLocation();
899 FD->setInstantiationOfMemberFunction(Reader.getContext(), InstFD, TSK);
900 FD->getMemberSpecializationInfo()->setPointOfInstantiation(POI);
901 mergeRedeclarable(FD, Redecl);
904 case FunctionDecl::TK_FunctionTemplateSpecialization: {
905 auto *Template = ReadDeclAs<FunctionTemplateDecl>();
906 auto TSK = (TemplateSpecializationKind)Record.readInt();
908 // Template arguments.
909 SmallVector<TemplateArgument, 8> TemplArgs;
910 Record.readTemplateArgumentList(TemplArgs, /*Canonicalize*/ true);
912 // Template args as written.
913 SmallVector<TemplateArgumentLoc, 8> TemplArgLocs;
914 SourceLocation LAngleLoc, RAngleLoc;
915 bool HasTemplateArgumentsAsWritten = Record.readInt();
916 if (HasTemplateArgumentsAsWritten) {
917 unsigned NumTemplateArgLocs = Record.readInt();
918 TemplArgLocs.reserve(NumTemplateArgLocs);
919 for (unsigned i = 0; i != NumTemplateArgLocs; ++i)
920 TemplArgLocs.push_back(Record.readTemplateArgumentLoc());
922 LAngleLoc = ReadSourceLocation();
923 RAngleLoc = ReadSourceLocation();
926 SourceLocation POI = ReadSourceLocation();
928 ASTContext &C = Reader.getContext();
929 TemplateArgumentList *TemplArgList
930 = TemplateArgumentList::CreateCopy(C, TemplArgs);
931 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
932 for (unsigned i = 0, e = TemplArgLocs.size(); i != e; ++i)
933 TemplArgsInfo.addArgument(TemplArgLocs[i]);
935 MemberSpecializationInfo *MSInfo = nullptr;
936 if (Record.readInt()) {
937 auto *FD = ReadDeclAs<FunctionDecl>();
938 auto TSK = (TemplateSpecializationKind)Record.readInt();
939 SourceLocation POI = ReadSourceLocation();
941 MSInfo = new (C) MemberSpecializationInfo(FD, TSK);
942 MSInfo->setPointOfInstantiation(POI);
945 FunctionTemplateSpecializationInfo *FTInfo =
946 FunctionTemplateSpecializationInfo::Create(
947 C, FD, Template, TSK, TemplArgList,
948 HasTemplateArgumentsAsWritten ? &TemplArgsInfo : nullptr, POI,
950 FD->TemplateOrSpecialization = FTInfo;
952 if (FD->isCanonicalDecl()) { // if canonical add to template's set.
953 // The template that contains the specializations set. It's not safe to
954 // use getCanonicalDecl on Template since it may still be initializing.
955 auto *CanonTemplate = ReadDeclAs<FunctionTemplateDecl>();
956 // Get the InsertPos by FindNodeOrInsertPos() instead of calling
957 // InsertNode(FTInfo) directly to avoid the getASTContext() call in
958 // FunctionTemplateSpecializationInfo's Profile().
959 // We avoid getASTContext because a decl in the parent hierarchy may
961 llvm::FoldingSetNodeID ID;
962 FunctionTemplateSpecializationInfo::Profile(ID, TemplArgs, C);
963 void *InsertPos = nullptr;
964 FunctionTemplateDecl::Common *CommonPtr = CanonTemplate->getCommonPtr();
965 FunctionTemplateSpecializationInfo *ExistingInfo =
966 CommonPtr->Specializations.FindNodeOrInsertPos(ID, InsertPos);
968 CommonPtr->Specializations.InsertNode(FTInfo, InsertPos);
970 assert(Reader.getContext().getLangOpts().Modules &&
971 "already deserialized this template specialization");
972 mergeRedeclarable(FD, ExistingInfo->getFunction(), Redecl);
977 case FunctionDecl::TK_DependentFunctionTemplateSpecialization: {
979 UnresolvedSet<8> TemplDecls;
980 unsigned NumTemplates = Record.readInt();
981 while (NumTemplates--)
982 TemplDecls.addDecl(ReadDeclAs<NamedDecl>());
985 TemplateArgumentListInfo TemplArgs;
986 unsigned NumArgs = Record.readInt();
988 TemplArgs.addArgument(Record.readTemplateArgumentLoc());
989 TemplArgs.setLAngleLoc(ReadSourceLocation());
990 TemplArgs.setRAngleLoc(ReadSourceLocation());
992 FD->setDependentTemplateSpecialization(Reader.getContext(),
993 TemplDecls, TemplArgs);
994 // These are not merged; we don't need to merge redeclarations of dependent
1000 // Read in the parameters.
1001 unsigned NumParams = Record.readInt();
1002 SmallVector<ParmVarDecl *, 16> Params;
1003 Params.reserve(NumParams);
1004 for (unsigned I = 0; I != NumParams; ++I)
1005 Params.push_back(ReadDeclAs<ParmVarDecl>());
1006 FD->setParams(Reader.getContext(), Params);
1009 void ASTDeclReader::VisitObjCMethodDecl(ObjCMethodDecl *MD) {
1011 if (Record.readInt()) {
1012 // Load the body on-demand. Most clients won't care, because method
1013 // definitions rarely show up in headers.
1014 Reader.PendingBodies[MD] = GetCurrentCursorOffset();
1015 HasPendingBody = true;
1016 MD->setSelfDecl(ReadDeclAs<ImplicitParamDecl>());
1017 MD->setCmdDecl(ReadDeclAs<ImplicitParamDecl>());
1019 MD->setInstanceMethod(Record.readInt());
1020 MD->setVariadic(Record.readInt());
1021 MD->setPropertyAccessor(Record.readInt());
1022 MD->setDefined(Record.readInt());
1023 MD->setOverriding(Record.readInt());
1024 MD->setHasSkippedBody(Record.readInt());
1026 MD->setIsRedeclaration(Record.readInt());
1027 MD->setHasRedeclaration(Record.readInt());
1028 if (MD->hasRedeclaration())
1029 Reader.getContext().setObjCMethodRedeclaration(MD,
1030 ReadDeclAs<ObjCMethodDecl>());
1032 MD->setDeclImplementation((ObjCMethodDecl::ImplementationControl)Record.readInt());
1033 MD->setObjCDeclQualifier((Decl::ObjCDeclQualifier)Record.readInt());
1034 MD->setRelatedResultType(Record.readInt());
1035 MD->setReturnType(Record.readType());
1036 MD->setReturnTypeSourceInfo(GetTypeSourceInfo());
1037 MD->DeclEndLoc = ReadSourceLocation();
1038 unsigned NumParams = Record.readInt();
1039 SmallVector<ParmVarDecl *, 16> Params;
1040 Params.reserve(NumParams);
1041 for (unsigned I = 0; I != NumParams; ++I)
1042 Params.push_back(ReadDeclAs<ParmVarDecl>());
1044 MD->setSelLocsKind((SelectorLocationsKind)Record.readInt());
1045 unsigned NumStoredSelLocs = Record.readInt();
1046 SmallVector<SourceLocation, 16> SelLocs;
1047 SelLocs.reserve(NumStoredSelLocs);
1048 for (unsigned i = 0; i != NumStoredSelLocs; ++i)
1049 SelLocs.push_back(ReadSourceLocation());
1051 MD->setParamsAndSelLocs(Reader.getContext(), Params, SelLocs);
1054 void ASTDeclReader::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
1055 VisitTypedefNameDecl(D);
1057 D->Variance = Record.readInt();
1058 D->Index = Record.readInt();
1059 D->VarianceLoc = ReadSourceLocation();
1060 D->ColonLoc = ReadSourceLocation();
1063 void ASTDeclReader::VisitObjCContainerDecl(ObjCContainerDecl *CD) {
1065 CD->setAtStartLoc(ReadSourceLocation());
1066 CD->setAtEndRange(ReadSourceRange());
1069 ObjCTypeParamList *ASTDeclReader::ReadObjCTypeParamList() {
1070 unsigned numParams = Record.readInt();
1074 SmallVector<ObjCTypeParamDecl *, 4> typeParams;
1075 typeParams.reserve(numParams);
1076 for (unsigned i = 0; i != numParams; ++i) {
1077 auto *typeParam = ReadDeclAs<ObjCTypeParamDecl>();
1081 typeParams.push_back(typeParam);
1084 SourceLocation lAngleLoc = ReadSourceLocation();
1085 SourceLocation rAngleLoc = ReadSourceLocation();
1087 return ObjCTypeParamList::create(Reader.getContext(), lAngleLoc,
1088 typeParams, rAngleLoc);
1091 void ASTDeclReader::ReadObjCDefinitionData(
1092 struct ObjCInterfaceDecl::DefinitionData &Data) {
1093 // Read the superclass.
1094 Data.SuperClassTInfo = GetTypeSourceInfo();
1096 Data.EndLoc = ReadSourceLocation();
1097 Data.HasDesignatedInitializers = Record.readInt();
1099 // Read the directly referenced protocols and their SourceLocations.
1100 unsigned NumProtocols = Record.readInt();
1101 SmallVector<ObjCProtocolDecl *, 16> Protocols;
1102 Protocols.reserve(NumProtocols);
1103 for (unsigned I = 0; I != NumProtocols; ++I)
1104 Protocols.push_back(ReadDeclAs<ObjCProtocolDecl>());
1105 SmallVector<SourceLocation, 16> ProtoLocs;
1106 ProtoLocs.reserve(NumProtocols);
1107 for (unsigned I = 0; I != NumProtocols; ++I)
1108 ProtoLocs.push_back(ReadSourceLocation());
1109 Data.ReferencedProtocols.set(Protocols.data(), NumProtocols, ProtoLocs.data(),
1110 Reader.getContext());
1112 // Read the transitive closure of protocols referenced by this class.
1113 NumProtocols = Record.readInt();
1115 Protocols.reserve(NumProtocols);
1116 for (unsigned I = 0; I != NumProtocols; ++I)
1117 Protocols.push_back(ReadDeclAs<ObjCProtocolDecl>());
1118 Data.AllReferencedProtocols.set(Protocols.data(), NumProtocols,
1119 Reader.getContext());
1122 void ASTDeclReader::MergeDefinitionData(ObjCInterfaceDecl *D,
1123 struct ObjCInterfaceDecl::DefinitionData &&NewDD) {
1124 // FIXME: odr checking?
1127 void ASTDeclReader::VisitObjCInterfaceDecl(ObjCInterfaceDecl *ID) {
1128 RedeclarableResult Redecl = VisitRedeclarable(ID);
1129 VisitObjCContainerDecl(ID);
1130 DeferredTypeID = Record.getGlobalTypeID(Record.readInt());
1131 mergeRedeclarable(ID, Redecl);
1133 ID->TypeParamList = ReadObjCTypeParamList();
1134 if (Record.readInt()) {
1135 // Read the definition.
1136 ID->allocateDefinitionData();
1138 ReadObjCDefinitionData(ID->data());
1139 ObjCInterfaceDecl *Canon = ID->getCanonicalDecl();
1140 if (Canon->Data.getPointer()) {
1141 // If we already have a definition, keep the definition invariant and
1143 MergeDefinitionData(Canon, std::move(ID->data()));
1144 ID->Data = Canon->Data;
1146 // Set the definition data of the canonical declaration, so other
1147 // redeclarations will see it.
1148 ID->getCanonicalDecl()->Data = ID->Data;
1150 // We will rebuild this list lazily.
1151 ID->setIvarList(nullptr);
1154 // Note that we have deserialized a definition.
1155 Reader.PendingDefinitions.insert(ID);
1157 // Note that we've loaded this Objective-C class.
1158 Reader.ObjCClassesLoaded.push_back(ID);
1160 ID->Data = ID->getCanonicalDecl()->Data;
1164 void ASTDeclReader::VisitObjCIvarDecl(ObjCIvarDecl *IVD) {
1165 VisitFieldDecl(IVD);
1166 IVD->setAccessControl((ObjCIvarDecl::AccessControl)Record.readInt());
1167 // This field will be built lazily.
1168 IVD->setNextIvar(nullptr);
1169 bool synth = Record.readInt();
1170 IVD->setSynthesize(synth);
1173 void ASTDeclReader::ReadObjCDefinitionData(
1174 struct ObjCProtocolDecl::DefinitionData &Data) {
1175 unsigned NumProtoRefs = Record.readInt();
1176 SmallVector<ObjCProtocolDecl *, 16> ProtoRefs;
1177 ProtoRefs.reserve(NumProtoRefs);
1178 for (unsigned I = 0; I != NumProtoRefs; ++I)
1179 ProtoRefs.push_back(ReadDeclAs<ObjCProtocolDecl>());
1180 SmallVector<SourceLocation, 16> ProtoLocs;
1181 ProtoLocs.reserve(NumProtoRefs);
1182 for (unsigned I = 0; I != NumProtoRefs; ++I)
1183 ProtoLocs.push_back(ReadSourceLocation());
1184 Data.ReferencedProtocols.set(ProtoRefs.data(), NumProtoRefs,
1185 ProtoLocs.data(), Reader.getContext());
1188 void ASTDeclReader::MergeDefinitionData(ObjCProtocolDecl *D,
1189 struct ObjCProtocolDecl::DefinitionData &&NewDD) {
1190 // FIXME: odr checking?
1193 void ASTDeclReader::VisitObjCProtocolDecl(ObjCProtocolDecl *PD) {
1194 RedeclarableResult Redecl = VisitRedeclarable(PD);
1195 VisitObjCContainerDecl(PD);
1196 mergeRedeclarable(PD, Redecl);
1198 if (Record.readInt()) {
1199 // Read the definition.
1200 PD->allocateDefinitionData();
1202 ReadObjCDefinitionData(PD->data());
1204 ObjCProtocolDecl *Canon = PD->getCanonicalDecl();
1205 if (Canon->Data.getPointer()) {
1206 // If we already have a definition, keep the definition invariant and
1208 MergeDefinitionData(Canon, std::move(PD->data()));
1209 PD->Data = Canon->Data;
1211 // Set the definition data of the canonical declaration, so other
1212 // redeclarations will see it.
1213 PD->getCanonicalDecl()->Data = PD->Data;
1215 // Note that we have deserialized a definition.
1216 Reader.PendingDefinitions.insert(PD);
1218 PD->Data = PD->getCanonicalDecl()->Data;
1222 void ASTDeclReader::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *FD) {
1226 void ASTDeclReader::VisitObjCCategoryDecl(ObjCCategoryDecl *CD) {
1227 VisitObjCContainerDecl(CD);
1228 CD->setCategoryNameLoc(ReadSourceLocation());
1229 CD->setIvarLBraceLoc(ReadSourceLocation());
1230 CD->setIvarRBraceLoc(ReadSourceLocation());
1232 // Note that this category has been deserialized. We do this before
1233 // deserializing the interface declaration, so that it will consider this
1235 Reader.CategoriesDeserialized.insert(CD);
1237 CD->ClassInterface = ReadDeclAs<ObjCInterfaceDecl>();
1238 CD->TypeParamList = ReadObjCTypeParamList();
1239 unsigned NumProtoRefs = Record.readInt();
1240 SmallVector<ObjCProtocolDecl *, 16> ProtoRefs;
1241 ProtoRefs.reserve(NumProtoRefs);
1242 for (unsigned I = 0; I != NumProtoRefs; ++I)
1243 ProtoRefs.push_back(ReadDeclAs<ObjCProtocolDecl>());
1244 SmallVector<SourceLocation, 16> ProtoLocs;
1245 ProtoLocs.reserve(NumProtoRefs);
1246 for (unsigned I = 0; I != NumProtoRefs; ++I)
1247 ProtoLocs.push_back(ReadSourceLocation());
1248 CD->setProtocolList(ProtoRefs.data(), NumProtoRefs, ProtoLocs.data(),
1249 Reader.getContext());
1251 // Protocols in the class extension belong to the class.
1252 if (NumProtoRefs > 0 && CD->ClassInterface && CD->IsClassExtension())
1253 CD->ClassInterface->mergeClassExtensionProtocolList(
1254 (ObjCProtocolDecl *const *)ProtoRefs.data(), NumProtoRefs,
1255 Reader.getContext());
1258 void ASTDeclReader::VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *CAD) {
1259 VisitNamedDecl(CAD);
1260 CAD->setClassInterface(ReadDeclAs<ObjCInterfaceDecl>());
1263 void ASTDeclReader::VisitObjCPropertyDecl(ObjCPropertyDecl *D) {
1265 D->setAtLoc(ReadSourceLocation());
1266 D->setLParenLoc(ReadSourceLocation());
1267 QualType T = Record.readType();
1268 TypeSourceInfo *TSI = GetTypeSourceInfo();
1270 D->setPropertyAttributes(
1271 (ObjCPropertyDecl::PropertyAttributeKind)Record.readInt());
1272 D->setPropertyAttributesAsWritten(
1273 (ObjCPropertyDecl::PropertyAttributeKind)Record.readInt());
1274 D->setPropertyImplementation(
1275 (ObjCPropertyDecl::PropertyControl)Record.readInt());
1276 DeclarationName GetterName = Record.readDeclarationName();
1277 SourceLocation GetterLoc = ReadSourceLocation();
1278 D->setGetterName(GetterName.getObjCSelector(), GetterLoc);
1279 DeclarationName SetterName = Record.readDeclarationName();
1280 SourceLocation SetterLoc = ReadSourceLocation();
1281 D->setSetterName(SetterName.getObjCSelector(), SetterLoc);
1282 D->setGetterMethodDecl(ReadDeclAs<ObjCMethodDecl>());
1283 D->setSetterMethodDecl(ReadDeclAs<ObjCMethodDecl>());
1284 D->setPropertyIvarDecl(ReadDeclAs<ObjCIvarDecl>());
1287 void ASTDeclReader::VisitObjCImplDecl(ObjCImplDecl *D) {
1288 VisitObjCContainerDecl(D);
1289 D->setClassInterface(ReadDeclAs<ObjCInterfaceDecl>());
1292 void ASTDeclReader::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
1293 VisitObjCImplDecl(D);
1294 D->CategoryNameLoc = ReadSourceLocation();
1297 void ASTDeclReader::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1298 VisitObjCImplDecl(D);
1299 D->setSuperClass(ReadDeclAs<ObjCInterfaceDecl>());
1300 D->SuperLoc = ReadSourceLocation();
1301 D->setIvarLBraceLoc(ReadSourceLocation());
1302 D->setIvarRBraceLoc(ReadSourceLocation());
1303 D->setHasNonZeroConstructors(Record.readInt());
1304 D->setHasDestructors(Record.readInt());
1305 D->NumIvarInitializers = Record.readInt();
1306 if (D->NumIvarInitializers)
1307 D->IvarInitializers = ReadGlobalOffset();
1310 void ASTDeclReader::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) {
1312 D->setAtLoc(ReadSourceLocation());
1313 D->setPropertyDecl(ReadDeclAs<ObjCPropertyDecl>());
1314 D->PropertyIvarDecl = ReadDeclAs<ObjCIvarDecl>();
1315 D->IvarLoc = ReadSourceLocation();
1316 D->setGetterCXXConstructor(Record.readExpr());
1317 D->setSetterCXXAssignment(Record.readExpr());
1320 void ASTDeclReader::VisitFieldDecl(FieldDecl *FD) {
1321 VisitDeclaratorDecl(FD);
1322 FD->Mutable = Record.readInt();
1324 if (auto ISK = static_cast<FieldDecl::InitStorageKind>(Record.readInt())) {
1325 FD->InitStorage.setInt(ISK);
1326 FD->InitStorage.setPointer(ISK == FieldDecl::ISK_CapturedVLAType
1327 ? Record.readType().getAsOpaquePtr()
1328 : Record.readExpr());
1331 if (auto *BW = Record.readExpr())
1332 FD->setBitWidth(BW);
1334 if (!FD->getDeclName()) {
1335 if (auto *Tmpl = ReadDeclAs<FieldDecl>())
1336 Reader.getContext().setInstantiatedFromUnnamedFieldDecl(FD, Tmpl);
1341 void ASTDeclReader::VisitMSPropertyDecl(MSPropertyDecl *PD) {
1342 VisitDeclaratorDecl(PD);
1343 PD->GetterId = Record.getIdentifierInfo();
1344 PD->SetterId = Record.getIdentifierInfo();
1347 void ASTDeclReader::VisitIndirectFieldDecl(IndirectFieldDecl *FD) {
1350 FD->ChainingSize = Record.readInt();
1351 assert(FD->ChainingSize >= 2 && "Anonymous chaining must be >= 2");
1352 FD->Chaining = new (Reader.getContext())NamedDecl*[FD->ChainingSize];
1354 for (unsigned I = 0; I != FD->ChainingSize; ++I)
1355 FD->Chaining[I] = ReadDeclAs<NamedDecl>();
1360 ASTDeclReader::RedeclarableResult ASTDeclReader::VisitVarDeclImpl(VarDecl *VD) {
1361 RedeclarableResult Redecl = VisitRedeclarable(VD);
1362 VisitDeclaratorDecl(VD);
1364 VD->VarDeclBits.SClass = (StorageClass)Record.readInt();
1365 VD->VarDeclBits.TSCSpec = Record.readInt();
1366 VD->VarDeclBits.InitStyle = Record.readInt();
1367 VD->VarDeclBits.ARCPseudoStrong = Record.readInt();
1368 if (!isa<ParmVarDecl>(VD)) {
1369 VD->NonParmVarDeclBits.IsThisDeclarationADemotedDefinition =
1371 VD->NonParmVarDeclBits.ExceptionVar = Record.readInt();
1372 VD->NonParmVarDeclBits.NRVOVariable = Record.readInt();
1373 VD->NonParmVarDeclBits.CXXForRangeDecl = Record.readInt();
1374 VD->NonParmVarDeclBits.ObjCForDecl = Record.readInt();
1375 VD->NonParmVarDeclBits.IsInline = Record.readInt();
1376 VD->NonParmVarDeclBits.IsInlineSpecified = Record.readInt();
1377 VD->NonParmVarDeclBits.IsConstexpr = Record.readInt();
1378 VD->NonParmVarDeclBits.IsInitCapture = Record.readInt();
1379 VD->NonParmVarDeclBits.PreviousDeclInSameBlockScope = Record.readInt();
1380 VD->NonParmVarDeclBits.ImplicitParamKind = Record.readInt();
1381 VD->NonParmVarDeclBits.EscapingByref = Record.readInt();
1383 auto VarLinkage = Linkage(Record.readInt());
1384 VD->setCachedLinkage(VarLinkage);
1386 // Reconstruct the one piece of the IdentifierNamespace that we need.
1387 if (VD->getStorageClass() == SC_Extern && VarLinkage != NoLinkage &&
1388 VD->getLexicalDeclContext()->isFunctionOrMethod())
1389 VD->setLocalExternDecl();
1391 if (uint64_t Val = Record.readInt()) {
1392 VD->setInit(Record.readExpr());
1393 if (Val > 1) { // IsInitKnownICE = 1, IsInitNotICE = 2, IsInitICE = 3
1394 EvaluatedStmt *Eval = VD->ensureEvaluatedStmt();
1395 Eval->CheckedICE = true;
1396 Eval->IsICE = Val == 3;
1400 if (VD->hasAttr<BlocksAttr>() && VD->getType()->getAsCXXRecordDecl()) {
1401 Expr *CopyExpr = Record.readExpr();
1403 Reader.getContext().setBlockVarCopyInit(VD, CopyExpr, Record.readInt());
1406 if (VD->getStorageDuration() == SD_Static && Record.readInt())
1407 Reader.DefinitionSource[VD] = Loc.F->Kind == ModuleKind::MK_MainFile;
1410 VarNotTemplate = 0, VarTemplate, StaticDataMemberSpecialization
1412 switch ((VarKind)Record.readInt()) {
1413 case VarNotTemplate:
1414 // Only true variables (not parameters or implicit parameters) can be
1415 // merged; the other kinds are not really redeclarable at all.
1416 if (!isa<ParmVarDecl>(VD) && !isa<ImplicitParamDecl>(VD) &&
1417 !isa<VarTemplateSpecializationDecl>(VD))
1418 mergeRedeclarable(VD, Redecl);
1421 // Merged when we merge the template.
1422 VD->setDescribedVarTemplate(ReadDeclAs<VarTemplateDecl>());
1424 case StaticDataMemberSpecialization: { // HasMemberSpecializationInfo.
1425 auto *Tmpl = ReadDeclAs<VarDecl>();
1426 auto TSK = (TemplateSpecializationKind)Record.readInt();
1427 SourceLocation POI = ReadSourceLocation();
1428 Reader.getContext().setInstantiatedFromStaticDataMember(VD, Tmpl, TSK,POI);
1429 mergeRedeclarable(VD, Redecl);
1437 void ASTDeclReader::VisitImplicitParamDecl(ImplicitParamDecl *PD) {
1441 void ASTDeclReader::VisitParmVarDecl(ParmVarDecl *PD) {
1443 unsigned isObjCMethodParam = Record.readInt();
1444 unsigned scopeDepth = Record.readInt();
1445 unsigned scopeIndex = Record.readInt();
1446 unsigned declQualifier = Record.readInt();
1447 if (isObjCMethodParam) {
1448 assert(scopeDepth == 0);
1449 PD->setObjCMethodScopeInfo(scopeIndex);
1450 PD->ParmVarDeclBits.ScopeDepthOrObjCQuals = declQualifier;
1452 PD->setScopeInfo(scopeDepth, scopeIndex);
1454 PD->ParmVarDeclBits.IsKNRPromoted = Record.readInt();
1455 PD->ParmVarDeclBits.HasInheritedDefaultArg = Record.readInt();
1456 if (Record.readInt()) // hasUninstantiatedDefaultArg.
1457 PD->setUninstantiatedDefaultArg(Record.readExpr());
1459 // FIXME: If this is a redeclaration of a function from another module, handle
1460 // inheritance of default arguments.
1463 void ASTDeclReader::VisitDecompositionDecl(DecompositionDecl *DD) {
1465 auto **BDs = DD->getTrailingObjects<BindingDecl *>();
1466 for (unsigned I = 0; I != DD->NumBindings; ++I) {
1467 BDs[I] = ReadDeclAs<BindingDecl>();
1468 BDs[I]->setDecomposedDecl(DD);
1472 void ASTDeclReader::VisitBindingDecl(BindingDecl *BD) {
1474 BD->Binding = Record.readExpr();
1477 void ASTDeclReader::VisitFileScopeAsmDecl(FileScopeAsmDecl *AD) {
1479 AD->setAsmString(cast<StringLiteral>(Record.readExpr()));
1480 AD->setRParenLoc(ReadSourceLocation());
1483 void ASTDeclReader::VisitBlockDecl(BlockDecl *BD) {
1485 BD->setBody(cast_or_null<CompoundStmt>(Record.readStmt()));
1486 BD->setSignatureAsWritten(GetTypeSourceInfo());
1487 unsigned NumParams = Record.readInt();
1488 SmallVector<ParmVarDecl *, 16> Params;
1489 Params.reserve(NumParams);
1490 for (unsigned I = 0; I != NumParams; ++I)
1491 Params.push_back(ReadDeclAs<ParmVarDecl>());
1492 BD->setParams(Params);
1494 BD->setIsVariadic(Record.readInt());
1495 BD->setBlockMissingReturnType(Record.readInt());
1496 BD->setIsConversionFromLambda(Record.readInt());
1497 BD->setDoesNotEscape(Record.readInt());
1498 BD->setCanAvoidCopyToHeap(Record.readInt());
1500 bool capturesCXXThis = Record.readInt();
1501 unsigned numCaptures = Record.readInt();
1502 SmallVector<BlockDecl::Capture, 16> captures;
1503 captures.reserve(numCaptures);
1504 for (unsigned i = 0; i != numCaptures; ++i) {
1505 auto *decl = ReadDeclAs<VarDecl>();
1506 unsigned flags = Record.readInt();
1507 bool byRef = (flags & 1);
1508 bool nested = (flags & 2);
1509 Expr *copyExpr = ((flags & 4) ? Record.readExpr() : nullptr);
1511 captures.push_back(BlockDecl::Capture(decl, byRef, nested, copyExpr));
1513 BD->setCaptures(Reader.getContext(), captures, capturesCXXThis);
1516 void ASTDeclReader::VisitCapturedDecl(CapturedDecl *CD) {
1518 unsigned ContextParamPos = Record.readInt();
1519 CD->setNothrow(Record.readInt() != 0);
1520 // Body is set by VisitCapturedStmt.
1521 for (unsigned I = 0; I < CD->NumParams; ++I) {
1522 if (I != ContextParamPos)
1523 CD->setParam(I, ReadDeclAs<ImplicitParamDecl>());
1525 CD->setContextParam(I, ReadDeclAs<ImplicitParamDecl>());
1529 void ASTDeclReader::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1531 D->setLanguage((LinkageSpecDecl::LanguageIDs)Record.readInt());
1532 D->setExternLoc(ReadSourceLocation());
1533 D->setRBraceLoc(ReadSourceLocation());
1536 void ASTDeclReader::VisitExportDecl(ExportDecl *D) {
1538 D->RBraceLoc = ReadSourceLocation();
1541 void ASTDeclReader::VisitLabelDecl(LabelDecl *D) {
1543 D->setLocStart(ReadSourceLocation());
1546 void ASTDeclReader::VisitNamespaceDecl(NamespaceDecl *D) {
1547 RedeclarableResult Redecl = VisitRedeclarable(D);
1549 D->setInline(Record.readInt());
1550 D->LocStart = ReadSourceLocation();
1551 D->RBraceLoc = ReadSourceLocation();
1553 // Defer loading the anonymous namespace until we've finished merging
1554 // this namespace; loading it might load a later declaration of the
1555 // same namespace, and we have an invariant that older declarations
1556 // get merged before newer ones try to merge.
1557 GlobalDeclID AnonNamespace = 0;
1558 if (Redecl.getFirstID() == ThisDeclID) {
1559 AnonNamespace = ReadDeclID();
1561 // Link this namespace back to the first declaration, which has already
1562 // been deserialized.
1563 D->AnonOrFirstNamespaceAndInline.setPointer(D->getFirstDecl());
1566 mergeRedeclarable(D, Redecl);
1568 if (AnonNamespace) {
1569 // Each module has its own anonymous namespace, which is disjoint from
1570 // any other module's anonymous namespaces, so don't attach the anonymous
1571 // namespace at all.
1572 auto *Anon = cast<NamespaceDecl>(Reader.GetDecl(AnonNamespace));
1573 if (!Record.isModule())
1574 D->setAnonymousNamespace(Anon);
1578 void ASTDeclReader::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1579 RedeclarableResult Redecl = VisitRedeclarable(D);
1581 D->NamespaceLoc = ReadSourceLocation();
1582 D->IdentLoc = ReadSourceLocation();
1583 D->QualifierLoc = Record.readNestedNameSpecifierLoc();
1584 D->Namespace = ReadDeclAs<NamedDecl>();
1585 mergeRedeclarable(D, Redecl);
1588 void ASTDeclReader::VisitUsingDecl(UsingDecl *D) {
1590 D->setUsingLoc(ReadSourceLocation());
1591 D->QualifierLoc = Record.readNestedNameSpecifierLoc();
1592 ReadDeclarationNameLoc(D->DNLoc, D->getDeclName());
1593 D->FirstUsingShadow.setPointer(ReadDeclAs<UsingShadowDecl>());
1594 D->setTypename(Record.readInt());
1595 if (auto *Pattern = ReadDeclAs<NamedDecl>())
1596 Reader.getContext().setInstantiatedFromUsingDecl(D, Pattern);
1600 void ASTDeclReader::VisitUsingPackDecl(UsingPackDecl *D) {
1602 D->InstantiatedFrom = ReadDeclAs<NamedDecl>();
1603 auto **Expansions = D->getTrailingObjects<NamedDecl *>();
1604 for (unsigned I = 0; I != D->NumExpansions; ++I)
1605 Expansions[I] = ReadDeclAs<NamedDecl>();
1609 void ASTDeclReader::VisitUsingShadowDecl(UsingShadowDecl *D) {
1610 RedeclarableResult Redecl = VisitRedeclarable(D);
1612 D->Underlying = ReadDeclAs<NamedDecl>();
1613 D->IdentifierNamespace = Record.readInt();
1614 D->UsingOrNextShadow = ReadDeclAs<NamedDecl>();
1615 auto *Pattern = ReadDeclAs<UsingShadowDecl>();
1617 Reader.getContext().setInstantiatedFromUsingShadowDecl(D, Pattern);
1618 mergeRedeclarable(D, Redecl);
1621 void ASTDeclReader::VisitConstructorUsingShadowDecl(
1622 ConstructorUsingShadowDecl *D) {
1623 VisitUsingShadowDecl(D);
1624 D->NominatedBaseClassShadowDecl = ReadDeclAs<ConstructorUsingShadowDecl>();
1625 D->ConstructedBaseClassShadowDecl = ReadDeclAs<ConstructorUsingShadowDecl>();
1626 D->IsVirtual = Record.readInt();
1629 void ASTDeclReader::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1631 D->UsingLoc = ReadSourceLocation();
1632 D->NamespaceLoc = ReadSourceLocation();
1633 D->QualifierLoc = Record.readNestedNameSpecifierLoc();
1634 D->NominatedNamespace = ReadDeclAs<NamedDecl>();
1635 D->CommonAncestor = ReadDeclAs<DeclContext>();
1638 void ASTDeclReader::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1640 D->setUsingLoc(ReadSourceLocation());
1641 D->QualifierLoc = Record.readNestedNameSpecifierLoc();
1642 ReadDeclarationNameLoc(D->DNLoc, D->getDeclName());
1643 D->EllipsisLoc = ReadSourceLocation();
1647 void ASTDeclReader::VisitUnresolvedUsingTypenameDecl(
1648 UnresolvedUsingTypenameDecl *D) {
1650 D->TypenameLocation = ReadSourceLocation();
1651 D->QualifierLoc = Record.readNestedNameSpecifierLoc();
1652 D->EllipsisLoc = ReadSourceLocation();
1656 void ASTDeclReader::ReadCXXDefinitionData(
1657 struct CXXRecordDecl::DefinitionData &Data, const CXXRecordDecl *D) {
1658 // Note: the caller has deserialized the IsLambda bit already.
1659 Data.UserDeclaredConstructor = Record.readInt();
1660 Data.UserDeclaredSpecialMembers = Record.readInt();
1661 Data.Aggregate = Record.readInt();
1662 Data.PlainOldData = Record.readInt();
1663 Data.Empty = Record.readInt();
1664 Data.Polymorphic = Record.readInt();
1665 Data.Abstract = Record.readInt();
1666 Data.IsStandardLayout = Record.readInt();
1667 Data.IsCXX11StandardLayout = Record.readInt();
1668 Data.HasBasesWithFields = Record.readInt();
1669 Data.HasBasesWithNonStaticDataMembers = Record.readInt();
1670 Data.HasPrivateFields = Record.readInt();
1671 Data.HasProtectedFields = Record.readInt();
1672 Data.HasPublicFields = Record.readInt();
1673 Data.HasMutableFields = Record.readInt();
1674 Data.HasVariantMembers = Record.readInt();
1675 Data.HasOnlyCMembers = Record.readInt();
1676 Data.HasInClassInitializer = Record.readInt();
1677 Data.HasUninitializedReferenceMember = Record.readInt();
1678 Data.HasUninitializedFields = Record.readInt();
1679 Data.HasInheritedConstructor = Record.readInt();
1680 Data.HasInheritedAssignment = Record.readInt();
1681 Data.NeedOverloadResolutionForCopyConstructor = Record.readInt();
1682 Data.NeedOverloadResolutionForMoveConstructor = Record.readInt();
1683 Data.NeedOverloadResolutionForMoveAssignment = Record.readInt();
1684 Data.NeedOverloadResolutionForDestructor = Record.readInt();
1685 Data.DefaultedCopyConstructorIsDeleted = Record.readInt();
1686 Data.DefaultedMoveConstructorIsDeleted = Record.readInt();
1687 Data.DefaultedMoveAssignmentIsDeleted = Record.readInt();
1688 Data.DefaultedDestructorIsDeleted = Record.readInt();
1689 Data.HasTrivialSpecialMembers = Record.readInt();
1690 Data.HasTrivialSpecialMembersForCall = Record.readInt();
1691 Data.DeclaredNonTrivialSpecialMembers = Record.readInt();
1692 Data.DeclaredNonTrivialSpecialMembersForCall = Record.readInt();
1693 Data.HasIrrelevantDestructor = Record.readInt();
1694 Data.HasConstexprNonCopyMoveConstructor = Record.readInt();
1695 Data.HasDefaultedDefaultConstructor = Record.readInt();
1696 Data.DefaultedDefaultConstructorIsConstexpr = Record.readInt();
1697 Data.HasConstexprDefaultConstructor = Record.readInt();
1698 Data.HasNonLiteralTypeFieldsOrBases = Record.readInt();
1699 Data.ComputedVisibleConversions = Record.readInt();
1700 Data.UserProvidedDefaultConstructor = Record.readInt();
1701 Data.DeclaredSpecialMembers = Record.readInt();
1702 Data.ImplicitCopyConstructorCanHaveConstParamForVBase = Record.readInt();
1703 Data.ImplicitCopyConstructorCanHaveConstParamForNonVBase = Record.readInt();
1704 Data.ImplicitCopyAssignmentHasConstParam = Record.readInt();
1705 Data.HasDeclaredCopyConstructorWithConstParam = Record.readInt();
1706 Data.HasDeclaredCopyAssignmentWithConstParam = Record.readInt();
1707 Data.ODRHash = Record.readInt();
1708 Data.HasODRHash = true;
1710 if (Record.readInt())
1711 Reader.DefinitionSource[D] = Loc.F->Kind == ModuleKind::MK_MainFile;
1713 Data.NumBases = Record.readInt();
1715 Data.Bases = ReadGlobalOffset();
1716 Data.NumVBases = Record.readInt();
1718 Data.VBases = ReadGlobalOffset();
1720 Record.readUnresolvedSet(Data.Conversions);
1721 Record.readUnresolvedSet(Data.VisibleConversions);
1722 assert(Data.Definition && "Data.Definition should be already set!");
1723 Data.FirstFriend = ReadDeclID();
1725 if (Data.IsLambda) {
1726 using Capture = LambdaCapture;
1728 auto &Lambda = static_cast<CXXRecordDecl::LambdaDefinitionData &>(Data);
1729 Lambda.Dependent = Record.readInt();
1730 Lambda.IsGenericLambda = Record.readInt();
1731 Lambda.CaptureDefault = Record.readInt();
1732 Lambda.NumCaptures = Record.readInt();
1733 Lambda.NumExplicitCaptures = Record.readInt();
1734 Lambda.ManglingNumber = Record.readInt();
1735 Lambda.ContextDecl = ReadDeclID();
1736 Lambda.Captures = (Capture *)Reader.getContext().Allocate(
1737 sizeof(Capture) * Lambda.NumCaptures);
1738 Capture *ToCapture = Lambda.Captures;
1739 Lambda.MethodTyInfo = GetTypeSourceInfo();
1740 for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) {
1741 SourceLocation Loc = ReadSourceLocation();
1742 bool IsImplicit = Record.readInt();
1743 auto Kind = static_cast<LambdaCaptureKind>(Record.readInt());
1748 *ToCapture++ = Capture(Loc, IsImplicit, Kind, nullptr,SourceLocation());
1752 auto *Var = ReadDeclAs<VarDecl>();
1753 SourceLocation EllipsisLoc = ReadSourceLocation();
1754 *ToCapture++ = Capture(Loc, IsImplicit, Kind, Var, EllipsisLoc);
1761 void ASTDeclReader::MergeDefinitionData(
1762 CXXRecordDecl *D, struct CXXRecordDecl::DefinitionData &&MergeDD) {
1763 assert(D->DefinitionData &&
1764 "merging class definition into non-definition");
1765 auto &DD = *D->DefinitionData;
1767 if (DD.Definition != MergeDD.Definition) {
1768 // Track that we merged the definitions.
1769 Reader.MergedDeclContexts.insert(std::make_pair(MergeDD.Definition,
1771 Reader.PendingDefinitions.erase(MergeDD.Definition);
1772 MergeDD.Definition->setCompleteDefinition(false);
1773 Reader.mergeDefinitionVisibility(DD.Definition, MergeDD.Definition);
1774 assert(Reader.Lookups.find(MergeDD.Definition) == Reader.Lookups.end() &&
1775 "already loaded pending lookups for merged definition");
1778 auto PFDI = Reader.PendingFakeDefinitionData.find(&DD);
1779 if (PFDI != Reader.PendingFakeDefinitionData.end() &&
1780 PFDI->second == ASTReader::PendingFakeDefinitionKind::Fake) {
1781 // We faked up this definition data because we found a class for which we'd
1782 // not yet loaded the definition. Replace it with the real thing now.
1783 assert(!DD.IsLambda && !MergeDD.IsLambda && "faked up lambda definition?");
1784 PFDI->second = ASTReader::PendingFakeDefinitionKind::FakeLoaded;
1786 // Don't change which declaration is the definition; that is required
1787 // to be invariant once we select it.
1788 auto *Def = DD.Definition;
1789 DD = std::move(MergeDD);
1790 DD.Definition = Def;
1794 // FIXME: Move this out into a .def file?
1795 bool DetectedOdrViolation = false;
1796 #define OR_FIELD(Field) DD.Field |= MergeDD.Field;
1797 #define MATCH_FIELD(Field) \
1798 DetectedOdrViolation |= DD.Field != MergeDD.Field; \
1800 MATCH_FIELD(UserDeclaredConstructor)
1801 MATCH_FIELD(UserDeclaredSpecialMembers)
1802 MATCH_FIELD(Aggregate)
1803 MATCH_FIELD(PlainOldData)
1805 MATCH_FIELD(Polymorphic)
1806 MATCH_FIELD(Abstract)
1807 MATCH_FIELD(IsStandardLayout)
1808 MATCH_FIELD(IsCXX11StandardLayout)
1809 MATCH_FIELD(HasBasesWithFields)
1810 MATCH_FIELD(HasBasesWithNonStaticDataMembers)
1811 MATCH_FIELD(HasPrivateFields)
1812 MATCH_FIELD(HasProtectedFields)
1813 MATCH_FIELD(HasPublicFields)
1814 MATCH_FIELD(HasMutableFields)
1815 MATCH_FIELD(HasVariantMembers)
1816 MATCH_FIELD(HasOnlyCMembers)
1817 MATCH_FIELD(HasInClassInitializer)
1818 MATCH_FIELD(HasUninitializedReferenceMember)
1819 MATCH_FIELD(HasUninitializedFields)
1820 MATCH_FIELD(HasInheritedConstructor)
1821 MATCH_FIELD(HasInheritedAssignment)
1822 MATCH_FIELD(NeedOverloadResolutionForCopyConstructor)
1823 MATCH_FIELD(NeedOverloadResolutionForMoveConstructor)
1824 MATCH_FIELD(NeedOverloadResolutionForMoveAssignment)
1825 MATCH_FIELD(NeedOverloadResolutionForDestructor)
1826 MATCH_FIELD(DefaultedCopyConstructorIsDeleted)
1827 MATCH_FIELD(DefaultedMoveConstructorIsDeleted)
1828 MATCH_FIELD(DefaultedMoveAssignmentIsDeleted)
1829 MATCH_FIELD(DefaultedDestructorIsDeleted)
1830 OR_FIELD(HasTrivialSpecialMembers)
1831 OR_FIELD(HasTrivialSpecialMembersForCall)
1832 OR_FIELD(DeclaredNonTrivialSpecialMembers)
1833 OR_FIELD(DeclaredNonTrivialSpecialMembersForCall)
1834 MATCH_FIELD(HasIrrelevantDestructor)
1835 OR_FIELD(HasConstexprNonCopyMoveConstructor)
1836 OR_FIELD(HasDefaultedDefaultConstructor)
1837 MATCH_FIELD(DefaultedDefaultConstructorIsConstexpr)
1838 OR_FIELD(HasConstexprDefaultConstructor)
1839 MATCH_FIELD(HasNonLiteralTypeFieldsOrBases)
1840 // ComputedVisibleConversions is handled below.
1841 MATCH_FIELD(UserProvidedDefaultConstructor)
1842 OR_FIELD(DeclaredSpecialMembers)
1843 MATCH_FIELD(ImplicitCopyConstructorCanHaveConstParamForVBase)
1844 MATCH_FIELD(ImplicitCopyConstructorCanHaveConstParamForNonVBase)
1845 MATCH_FIELD(ImplicitCopyAssignmentHasConstParam)
1846 OR_FIELD(HasDeclaredCopyConstructorWithConstParam)
1847 OR_FIELD(HasDeclaredCopyAssignmentWithConstParam)
1848 MATCH_FIELD(IsLambda)
1852 if (DD.NumBases != MergeDD.NumBases || DD.NumVBases != MergeDD.NumVBases)
1853 DetectedOdrViolation = true;
1854 // FIXME: Issue a diagnostic if the base classes don't match when we come
1855 // to lazily load them.
1857 // FIXME: Issue a diagnostic if the list of conversion functions doesn't
1858 // match when we come to lazily load them.
1859 if (MergeDD.ComputedVisibleConversions && !DD.ComputedVisibleConversions) {
1860 DD.VisibleConversions = std::move(MergeDD.VisibleConversions);
1861 DD.ComputedVisibleConversions = true;
1864 // FIXME: Issue a diagnostic if FirstFriend doesn't match when we come to
1868 // FIXME: ODR-checking for merging lambdas (this happens, for instance,
1869 // when they occur within the body of a function template specialization).
1872 if (D->getODRHash() != MergeDD.ODRHash) {
1873 DetectedOdrViolation = true;
1876 if (DetectedOdrViolation)
1877 Reader.PendingOdrMergeFailures[DD.Definition].push_back(
1878 {MergeDD.Definition, &MergeDD});
1881 void ASTDeclReader::ReadCXXRecordDefinition(CXXRecordDecl *D, bool Update) {
1882 struct CXXRecordDecl::DefinitionData *DD;
1883 ASTContext &C = Reader.getContext();
1885 // Determine whether this is a lambda closure type, so that we can
1886 // allocate the appropriate DefinitionData structure.
1887 bool IsLambda = Record.readInt();
1889 DD = new (C) CXXRecordDecl::LambdaDefinitionData(D, nullptr, false, false,
1892 DD = new (C) struct CXXRecordDecl::DefinitionData(D);
1894 CXXRecordDecl *Canon = D->getCanonicalDecl();
1895 // Set decl definition data before reading it, so that during deserialization
1896 // when we read CXXRecordDecl, it already has definition data and we don't
1898 if (!Canon->DefinitionData)
1899 Canon->DefinitionData = DD;
1900 D->DefinitionData = Canon->DefinitionData;
1901 ReadCXXDefinitionData(*DD, D);
1903 // We might already have a different definition for this record. This can
1904 // happen either because we're reading an update record, or because we've
1905 // already done some merging. Either way, just merge into it.
1906 if (Canon->DefinitionData != DD) {
1907 MergeDefinitionData(Canon, std::move(*DD));
1911 // Mark this declaration as being a definition.
1912 D->setCompleteDefinition(true);
1914 // If this is not the first declaration or is an update record, we can have
1915 // other redeclarations already. Make a note that we need to propagate the
1916 // DefinitionData pointer onto them.
1917 if (Update || Canon != D)
1918 Reader.PendingDefinitions.insert(D);
1921 ASTDeclReader::RedeclarableResult
1922 ASTDeclReader::VisitCXXRecordDeclImpl(CXXRecordDecl *D) {
1923 RedeclarableResult Redecl = VisitRecordDeclImpl(D);
1925 ASTContext &C = Reader.getContext();
1928 CXXRecNotTemplate = 0, CXXRecTemplate, CXXRecMemberSpecialization
1930 switch ((CXXRecKind)Record.readInt()) {
1931 case CXXRecNotTemplate:
1932 // Merged when we merge the folding set entry in the primary template.
1933 if (!isa<ClassTemplateSpecializationDecl>(D))
1934 mergeRedeclarable(D, Redecl);
1936 case CXXRecTemplate: {
1937 // Merged when we merge the template.
1938 auto *Template = ReadDeclAs<ClassTemplateDecl>();
1939 D->TemplateOrInstantiation = Template;
1940 if (!Template->getTemplatedDecl()) {
1941 // We've not actually loaded the ClassTemplateDecl yet, because we're
1942 // currently being loaded as its pattern. Rely on it to set up our
1943 // TypeForDecl (see VisitClassTemplateDecl).
1945 // Beware: we do not yet know our canonical declaration, and may still
1946 // get merged once the surrounding class template has got off the ground.
1951 case CXXRecMemberSpecialization: {
1952 auto *RD = ReadDeclAs<CXXRecordDecl>();
1953 auto TSK = (TemplateSpecializationKind)Record.readInt();
1954 SourceLocation POI = ReadSourceLocation();
1955 MemberSpecializationInfo *MSI = new (C) MemberSpecializationInfo(RD, TSK);
1956 MSI->setPointOfInstantiation(POI);
1957 D->TemplateOrInstantiation = MSI;
1958 mergeRedeclarable(D, Redecl);
1963 bool WasDefinition = Record.readInt();
1965 ReadCXXRecordDefinition(D, /*Update*/false);
1967 // Propagate DefinitionData pointer from the canonical declaration.
1968 D->DefinitionData = D->getCanonicalDecl()->DefinitionData;
1970 // Lazily load the key function to avoid deserializing every method so we can
1972 if (WasDefinition) {
1973 DeclID KeyFn = ReadDeclID();
1974 if (KeyFn && D->isCompleteDefinition())
1975 // FIXME: This is wrong for the ARM ABI, where some other module may have
1976 // made this function no longer be a key function. We need an update
1977 // record or similar for that case.
1978 C.KeyFunctions[D] = KeyFn;
1984 void ASTDeclReader::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) {
1985 D->setExplicitSpecifier(Record.readExplicitSpec());
1986 VisitFunctionDecl(D);
1987 D->setIsCopyDeductionCandidate(Record.readInt());
1990 void ASTDeclReader::VisitCXXMethodDecl(CXXMethodDecl *D) {
1991 VisitFunctionDecl(D);
1993 unsigned NumOverridenMethods = Record.readInt();
1994 if (D->isCanonicalDecl()) {
1995 while (NumOverridenMethods--) {
1996 // Avoid invariant checking of CXXMethodDecl::addOverriddenMethod,
1997 // MD may be initializing.
1998 if (auto *MD = ReadDeclAs<CXXMethodDecl>())
1999 Reader.getContext().addOverriddenMethod(D, MD->getCanonicalDecl());
2002 // We don't care about which declarations this used to override; we get
2003 // the relevant information from the canonical declaration.
2004 Record.skipInts(NumOverridenMethods);
2008 void ASTDeclReader::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
2009 // We need the inherited constructor information to merge the declaration,
2010 // so we have to read it before we call VisitCXXMethodDecl.
2011 D->setExplicitSpecifier(Record.readExplicitSpec());
2012 if (D->isInheritingConstructor()) {
2013 auto *Shadow = ReadDeclAs<ConstructorUsingShadowDecl>();
2014 auto *Ctor = ReadDeclAs<CXXConstructorDecl>();
2015 *D->getTrailingObjects<InheritedConstructor>() =
2016 InheritedConstructor(Shadow, Ctor);
2019 VisitCXXMethodDecl(D);
2022 void ASTDeclReader::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
2023 VisitCXXMethodDecl(D);
2025 if (auto *OperatorDelete = ReadDeclAs<FunctionDecl>()) {
2026 CXXDestructorDecl *Canon = D->getCanonicalDecl();
2027 auto *ThisArg = Record.readExpr();
2028 // FIXME: Check consistency if we have an old and new operator delete.
2029 if (!Canon->OperatorDelete) {
2030 Canon->OperatorDelete = OperatorDelete;
2031 Canon->OperatorDeleteThisArg = ThisArg;
2036 void ASTDeclReader::VisitCXXConversionDecl(CXXConversionDecl *D) {
2037 D->setExplicitSpecifier(Record.readExplicitSpec());
2038 VisitCXXMethodDecl(D);
2041 void ASTDeclReader::VisitImportDecl(ImportDecl *D) {
2043 D->ImportedAndComplete.setPointer(readModule());
2044 D->ImportedAndComplete.setInt(Record.readInt());
2045 auto *StoredLocs = D->getTrailingObjects<SourceLocation>();
2046 for (unsigned I = 0, N = Record.back(); I != N; ++I)
2047 StoredLocs[I] = ReadSourceLocation();
2048 Record.skipInts(1); // The number of stored source locations.
2051 void ASTDeclReader::VisitAccessSpecDecl(AccessSpecDecl *D) {
2053 D->setColonLoc(ReadSourceLocation());
2056 void ASTDeclReader::VisitFriendDecl(FriendDecl *D) {
2058 if (Record.readInt()) // hasFriendDecl
2059 D->Friend = ReadDeclAs<NamedDecl>();
2061 D->Friend = GetTypeSourceInfo();
2062 for (unsigned i = 0; i != D->NumTPLists; ++i)
2063 D->getTrailingObjects<TemplateParameterList *>()[i] =
2064 Record.readTemplateParameterList();
2065 D->NextFriend = ReadDeclID();
2066 D->UnsupportedFriend = (Record.readInt() != 0);
2067 D->FriendLoc = ReadSourceLocation();
2070 void ASTDeclReader::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
2072 unsigned NumParams = Record.readInt();
2073 D->NumParams = NumParams;
2074 D->Params = new TemplateParameterList*[NumParams];
2075 for (unsigned i = 0; i != NumParams; ++i)
2076 D->Params[i] = Record.readTemplateParameterList();
2077 if (Record.readInt()) // HasFriendDecl
2078 D->Friend = ReadDeclAs<NamedDecl>();
2080 D->Friend = GetTypeSourceInfo();
2081 D->FriendLoc = ReadSourceLocation();
2084 DeclID ASTDeclReader::VisitTemplateDecl(TemplateDecl *D) {
2087 DeclID PatternID = ReadDeclID();
2088 auto *TemplatedDecl = cast_or_null<NamedDecl>(Reader.GetDecl(PatternID));
2089 TemplateParameterList *TemplateParams = Record.readTemplateParameterList();
2090 // FIXME handle associated constraints
2091 D->init(TemplatedDecl, TemplateParams);
2096 void ASTDeclReader::VisitConceptDecl(ConceptDecl *D) {
2097 VisitTemplateDecl(D);
2098 D->ConstraintExpr = Record.readExpr();
2102 ASTDeclReader::RedeclarableResult
2103 ASTDeclReader::VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D) {
2104 RedeclarableResult Redecl = VisitRedeclarable(D);
2106 // Make sure we've allocated the Common pointer first. We do this before
2107 // VisitTemplateDecl so that getCommonPtr() can be used during initialization.
2108 RedeclarableTemplateDecl *CanonD = D->getCanonicalDecl();
2109 if (!CanonD->Common) {
2110 CanonD->Common = CanonD->newCommon(Reader.getContext());
2111 Reader.PendingDefinitions.insert(CanonD);
2113 D->Common = CanonD->Common;
2115 // If this is the first declaration of the template, fill in the information
2116 // for the 'common' pointer.
2117 if (ThisDeclID == Redecl.getFirstID()) {
2118 if (auto *RTD = ReadDeclAs<RedeclarableTemplateDecl>()) {
2119 assert(RTD->getKind() == D->getKind() &&
2120 "InstantiatedFromMemberTemplate kind mismatch");
2121 D->setInstantiatedFromMemberTemplate(RTD);
2122 if (Record.readInt())
2123 D->setMemberSpecialization();
2127 DeclID PatternID = VisitTemplateDecl(D);
2128 D->IdentifierNamespace = Record.readInt();
2130 mergeRedeclarable(D, Redecl, PatternID);
2132 // If we merged the template with a prior declaration chain, merge the common
2134 // FIXME: Actually merge here, don't just overwrite.
2135 D->Common = D->getCanonicalDecl()->Common;
2140 void ASTDeclReader::VisitClassTemplateDecl(ClassTemplateDecl *D) {
2141 RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
2143 if (ThisDeclID == Redecl.getFirstID()) {
2144 // This ClassTemplateDecl owns a CommonPtr; read it to keep track of all of
2145 // the specializations.
2146 SmallVector<serialization::DeclID, 32> SpecIDs;
2147 ReadDeclIDList(SpecIDs);
2148 ASTDeclReader::AddLazySpecializations(D, SpecIDs);
2151 if (D->getTemplatedDecl()->TemplateOrInstantiation) {
2152 // We were loaded before our templated declaration was. We've not set up
2153 // its corresponding type yet (see VisitCXXRecordDeclImpl), so reconstruct
2155 Reader.getContext().getInjectedClassNameType(
2156 D->getTemplatedDecl(), D->getInjectedClassNameSpecialization());
2160 void ASTDeclReader::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) {
2161 llvm_unreachable("BuiltinTemplates are not serialized");
2164 /// TODO: Unify with ClassTemplateDecl version?
2165 /// May require unifying ClassTemplateDecl and
2166 /// VarTemplateDecl beyond TemplateDecl...
2167 void ASTDeclReader::VisitVarTemplateDecl(VarTemplateDecl *D) {
2168 RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
2170 if (ThisDeclID == Redecl.getFirstID()) {
2171 // This VarTemplateDecl owns a CommonPtr; read it to keep track of all of
2172 // the specializations.
2173 SmallVector<serialization::DeclID, 32> SpecIDs;
2174 ReadDeclIDList(SpecIDs);
2175 ASTDeclReader::AddLazySpecializations(D, SpecIDs);
2179 ASTDeclReader::RedeclarableResult
2180 ASTDeclReader::VisitClassTemplateSpecializationDeclImpl(
2181 ClassTemplateSpecializationDecl *D) {
2182 RedeclarableResult Redecl = VisitCXXRecordDeclImpl(D);
2184 ASTContext &C = Reader.getContext();
2185 if (Decl *InstD = ReadDecl()) {
2186 if (auto *CTD = dyn_cast<ClassTemplateDecl>(InstD)) {
2187 D->SpecializedTemplate = CTD;
2189 SmallVector<TemplateArgument, 8> TemplArgs;
2190 Record.readTemplateArgumentList(TemplArgs);
2191 TemplateArgumentList *ArgList
2192 = TemplateArgumentList::CreateCopy(C, TemplArgs);
2194 new (C) ClassTemplateSpecializationDecl::
2195 SpecializedPartialSpecialization();
2196 PS->PartialSpecialization
2197 = cast<ClassTemplatePartialSpecializationDecl>(InstD);
2198 PS->TemplateArgs = ArgList;
2199 D->SpecializedTemplate = PS;
2203 SmallVector<TemplateArgument, 8> TemplArgs;
2204 Record.readTemplateArgumentList(TemplArgs, /*Canonicalize*/ true);
2205 D->TemplateArgs = TemplateArgumentList::CreateCopy(C, TemplArgs);
2206 D->PointOfInstantiation = ReadSourceLocation();
2207 D->SpecializationKind = (TemplateSpecializationKind)Record.readInt();
2209 bool writtenAsCanonicalDecl = Record.readInt();
2210 if (writtenAsCanonicalDecl) {
2211 auto *CanonPattern = ReadDeclAs<ClassTemplateDecl>();
2212 if (D->isCanonicalDecl()) { // It's kept in the folding set.
2213 // Set this as, or find, the canonical declaration for this specialization
2214 ClassTemplateSpecializationDecl *CanonSpec;
2215 if (auto *Partial = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) {
2216 CanonSpec = CanonPattern->getCommonPtr()->PartialSpecializations
2217 .GetOrInsertNode(Partial);
2220 CanonPattern->getCommonPtr()->Specializations.GetOrInsertNode(D);
2222 // If there was already a canonical specialization, merge into it.
2223 if (CanonSpec != D) {
2224 mergeRedeclarable<TagDecl>(D, CanonSpec, Redecl);
2226 // This declaration might be a definition. Merge with any existing
2228 if (auto *DDD = D->DefinitionData) {
2229 if (CanonSpec->DefinitionData)
2230 MergeDefinitionData(CanonSpec, std::move(*DDD));
2232 CanonSpec->DefinitionData = D->DefinitionData;
2234 D->DefinitionData = CanonSpec->DefinitionData;
2240 if (TypeSourceInfo *TyInfo = GetTypeSourceInfo()) {
2241 auto *ExplicitInfo =
2242 new (C) ClassTemplateSpecializationDecl::ExplicitSpecializationInfo;
2243 ExplicitInfo->TypeAsWritten = TyInfo;
2244 ExplicitInfo->ExternLoc = ReadSourceLocation();
2245 ExplicitInfo->TemplateKeywordLoc = ReadSourceLocation();
2246 D->ExplicitInfo = ExplicitInfo;
2252 void ASTDeclReader::VisitClassTemplatePartialSpecializationDecl(
2253 ClassTemplatePartialSpecializationDecl *D) {
2254 RedeclarableResult Redecl = VisitClassTemplateSpecializationDeclImpl(D);
2256 D->TemplateParams = Record.readTemplateParameterList();
2257 D->ArgsAsWritten = Record.readASTTemplateArgumentListInfo();
2259 // These are read/set from/to the first declaration.
2260 if (ThisDeclID == Redecl.getFirstID()) {
2261 D->InstantiatedFromMember.setPointer(
2262 ReadDeclAs<ClassTemplatePartialSpecializationDecl>());
2263 D->InstantiatedFromMember.setInt(Record.readInt());
2267 void ASTDeclReader::VisitClassScopeFunctionSpecializationDecl(
2268 ClassScopeFunctionSpecializationDecl *D) {
2270 D->Specialization = ReadDeclAs<CXXMethodDecl>();
2271 if (Record.readInt())
2272 D->TemplateArgs = Record.readASTTemplateArgumentListInfo();
2275 void ASTDeclReader::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
2276 RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
2278 if (ThisDeclID == Redecl.getFirstID()) {
2279 // This FunctionTemplateDecl owns a CommonPtr; read it.
2280 SmallVector<serialization::DeclID, 32> SpecIDs;
2281 ReadDeclIDList(SpecIDs);
2282 ASTDeclReader::AddLazySpecializations(D, SpecIDs);
2286 /// TODO: Unify with ClassTemplateSpecializationDecl version?
2287 /// May require unifying ClassTemplate(Partial)SpecializationDecl and
2288 /// VarTemplate(Partial)SpecializationDecl with a new data
2289 /// structure Template(Partial)SpecializationDecl, and
2290 /// using Template(Partial)SpecializationDecl as input type.
2291 ASTDeclReader::RedeclarableResult
2292 ASTDeclReader::VisitVarTemplateSpecializationDeclImpl(
2293 VarTemplateSpecializationDecl *D) {
2294 RedeclarableResult Redecl = VisitVarDeclImpl(D);
2296 ASTContext &C = Reader.getContext();
2297 if (Decl *InstD = ReadDecl()) {
2298 if (auto *VTD = dyn_cast<VarTemplateDecl>(InstD)) {
2299 D->SpecializedTemplate = VTD;
2301 SmallVector<TemplateArgument, 8> TemplArgs;
2302 Record.readTemplateArgumentList(TemplArgs);
2303 TemplateArgumentList *ArgList = TemplateArgumentList::CreateCopy(
2307 VarTemplateSpecializationDecl::SpecializedPartialSpecialization();
2308 PS->PartialSpecialization =
2309 cast<VarTemplatePartialSpecializationDecl>(InstD);
2310 PS->TemplateArgs = ArgList;
2311 D->SpecializedTemplate = PS;
2316 if (TypeSourceInfo *TyInfo = GetTypeSourceInfo()) {
2317 auto *ExplicitInfo =
2318 new (C) VarTemplateSpecializationDecl::ExplicitSpecializationInfo;
2319 ExplicitInfo->TypeAsWritten = TyInfo;
2320 ExplicitInfo->ExternLoc = ReadSourceLocation();
2321 ExplicitInfo->TemplateKeywordLoc = ReadSourceLocation();
2322 D->ExplicitInfo = ExplicitInfo;
2325 SmallVector<TemplateArgument, 8> TemplArgs;
2326 Record.readTemplateArgumentList(TemplArgs, /*Canonicalize*/ true);
2327 D->TemplateArgs = TemplateArgumentList::CreateCopy(C, TemplArgs);
2328 D->PointOfInstantiation = ReadSourceLocation();
2329 D->SpecializationKind = (TemplateSpecializationKind)Record.readInt();
2330 D->IsCompleteDefinition = Record.readInt();
2332 bool writtenAsCanonicalDecl = Record.readInt();
2333 if (writtenAsCanonicalDecl) {
2334 auto *CanonPattern = ReadDeclAs<VarTemplateDecl>();
2335 if (D->isCanonicalDecl()) { // It's kept in the folding set.
2336 // FIXME: If it's already present, merge it.
2337 if (auto *Partial = dyn_cast<VarTemplatePartialSpecializationDecl>(D)) {
2338 CanonPattern->getCommonPtr()->PartialSpecializations
2339 .GetOrInsertNode(Partial);
2341 CanonPattern->getCommonPtr()->Specializations.GetOrInsertNode(D);
2349 /// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
2350 /// May require unifying ClassTemplate(Partial)SpecializationDecl and
2351 /// VarTemplate(Partial)SpecializationDecl with a new data
2352 /// structure Template(Partial)SpecializationDecl, and
2353 /// using Template(Partial)SpecializationDecl as input type.
2354 void ASTDeclReader::VisitVarTemplatePartialSpecializationDecl(
2355 VarTemplatePartialSpecializationDecl *D) {
2356 RedeclarableResult Redecl = VisitVarTemplateSpecializationDeclImpl(D);
2358 D->TemplateParams = Record.readTemplateParameterList();
2359 D->ArgsAsWritten = Record.readASTTemplateArgumentListInfo();
2361 // These are read/set from/to the first declaration.
2362 if (ThisDeclID == Redecl.getFirstID()) {
2363 D->InstantiatedFromMember.setPointer(
2364 ReadDeclAs<VarTemplatePartialSpecializationDecl>());
2365 D->InstantiatedFromMember.setInt(Record.readInt());
2369 void ASTDeclReader::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
2372 D->setDeclaredWithTypename(Record.readInt());
2374 if (Record.readInt())
2375 D->setDefaultArgument(GetTypeSourceInfo());
2378 void ASTDeclReader::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
2379 VisitDeclaratorDecl(D);
2380 // TemplateParmPosition.
2381 D->setDepth(Record.readInt());
2382 D->setPosition(Record.readInt());
2383 if (D->isExpandedParameterPack()) {
2384 auto TypesAndInfos =
2385 D->getTrailingObjects<std::pair<QualType, TypeSourceInfo *>>();
2386 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
2387 new (&TypesAndInfos[I].first) QualType(Record.readType());
2388 TypesAndInfos[I].second = GetTypeSourceInfo();
2391 // Rest of NonTypeTemplateParmDecl.
2392 D->ParameterPack = Record.readInt();
2393 if (Record.readInt())
2394 D->setDefaultArgument(Record.readExpr());
2398 void ASTDeclReader::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
2399 VisitTemplateDecl(D);
2400 // TemplateParmPosition.
2401 D->setDepth(Record.readInt());
2402 D->setPosition(Record.readInt());
2403 if (D->isExpandedParameterPack()) {
2404 auto **Data = D->getTrailingObjects<TemplateParameterList *>();
2405 for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
2407 Data[I] = Record.readTemplateParameterList();
2409 // Rest of TemplateTemplateParmDecl.
2410 D->ParameterPack = Record.readInt();
2411 if (Record.readInt())
2412 D->setDefaultArgument(Reader.getContext(),
2413 Record.readTemplateArgumentLoc());
2417 void ASTDeclReader::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
2418 VisitRedeclarableTemplateDecl(D);
2421 void ASTDeclReader::VisitStaticAssertDecl(StaticAssertDecl *D) {
2423 D->AssertExprAndFailed.setPointer(Record.readExpr());
2424 D->AssertExprAndFailed.setInt(Record.readInt());
2425 D->Message = cast_or_null<StringLiteral>(Record.readExpr());
2426 D->RParenLoc = ReadSourceLocation();
2429 void ASTDeclReader::VisitEmptyDecl(EmptyDecl *D) {
2433 std::pair<uint64_t, uint64_t>
2434 ASTDeclReader::VisitDeclContext(DeclContext *DC) {
2435 uint64_t LexicalOffset = ReadLocalOffset();
2436 uint64_t VisibleOffset = ReadLocalOffset();
2437 return std::make_pair(LexicalOffset, VisibleOffset);
2440 template <typename T>
2441 ASTDeclReader::RedeclarableResult
2442 ASTDeclReader::VisitRedeclarable(Redeclarable<T> *D) {
2443 DeclID FirstDeclID = ReadDeclID();
2444 Decl *MergeWith = nullptr;
2446 bool IsKeyDecl = ThisDeclID == FirstDeclID;
2447 bool IsFirstLocalDecl = false;
2449 uint64_t RedeclOffset = 0;
2451 // 0 indicates that this declaration was the only declaration of its entity,
2452 // and is used for space optimization.
2453 if (FirstDeclID == 0) {
2454 FirstDeclID = ThisDeclID;
2456 IsFirstLocalDecl = true;
2457 } else if (unsigned N = Record.readInt()) {
2458 // This declaration was the first local declaration, but may have imported
2459 // other declarations.
2461 IsFirstLocalDecl = true;
2463 // We have some declarations that must be before us in our redeclaration
2464 // chain. Read them now, and remember that we ought to merge with one of
2466 // FIXME: Provide a known merge target to the second and subsequent such
2468 for (unsigned I = 0; I != N - 1; ++I)
2469 MergeWith = ReadDecl();
2471 RedeclOffset = ReadLocalOffset();
2473 // This declaration was not the first local declaration. Read the first
2474 // local declaration now, to trigger the import of other redeclarations.
2478 auto *FirstDecl = cast_or_null<T>(Reader.GetDecl(FirstDeclID));
2479 if (FirstDecl != D) {
2480 // We delay loading of the redeclaration chain to avoid deeply nested calls.
2481 // We temporarily set the first (canonical) declaration as the previous one
2482 // which is the one that matters and mark the real previous DeclID to be
2483 // loaded & attached later on.
2484 D->RedeclLink = Redeclarable<T>::PreviousDeclLink(FirstDecl);
2485 D->First = FirstDecl->getCanonicalDecl();
2488 auto *DAsT = static_cast<T *>(D);
2490 // Note that we need to load local redeclarations of this decl and build a
2491 // decl chain for them. This must happen *after* we perform the preloading
2492 // above; this ensures that the redeclaration chain is built in the correct
2494 if (IsFirstLocalDecl)
2495 Reader.PendingDeclChains.push_back(std::make_pair(DAsT, RedeclOffset));
2497 return RedeclarableResult(MergeWith, FirstDeclID, IsKeyDecl);
2500 /// Attempts to merge the given declaration (D) with another declaration
2501 /// of the same entity.
2502 template<typename T>
2503 void ASTDeclReader::mergeRedeclarable(Redeclarable<T> *DBase,
2504 RedeclarableResult &Redecl,
2505 DeclID TemplatePatternID) {
2506 // If modules are not available, there is no reason to perform this merge.
2507 if (!Reader.getContext().getLangOpts().Modules)
2510 // If we're not the canonical declaration, we don't need to merge.
2511 if (!DBase->isFirstDecl())
2514 auto *D = static_cast<T *>(DBase);
2516 if (auto *Existing = Redecl.getKnownMergeTarget())
2517 // We already know of an existing declaration we should merge with.
2518 mergeRedeclarable(D, cast<T>(Existing), Redecl, TemplatePatternID);
2519 else if (FindExistingResult ExistingRes = findExisting(D))
2520 if (T *Existing = ExistingRes)
2521 mergeRedeclarable(D, Existing, Redecl, TemplatePatternID);
2524 /// "Cast" to type T, asserting if we don't have an implicit conversion.
2525 /// We use this to put code in a template that will only be valid for certain
2527 template<typename T> static T assert_cast(T t) { return t; }
2528 template<typename T> static T assert_cast(...) {
2529 llvm_unreachable("bad assert_cast");
2532 /// Merge together the pattern declarations from two template
2534 void ASTDeclReader::mergeTemplatePattern(RedeclarableTemplateDecl *D,
2535 RedeclarableTemplateDecl *Existing,
2536 DeclID DsID, bool IsKeyDecl) {
2537 auto *DPattern = D->getTemplatedDecl();
2538 auto *ExistingPattern = Existing->getTemplatedDecl();
2539 RedeclarableResult Result(/*MergeWith*/ ExistingPattern,
2540 DPattern->getCanonicalDecl()->getGlobalID(),
2543 if (auto *DClass = dyn_cast<CXXRecordDecl>(DPattern)) {
2544 // Merge with any existing definition.
2545 // FIXME: This is duplicated in several places. Refactor.
2546 auto *ExistingClass =
2547 cast<CXXRecordDecl>(ExistingPattern)->getCanonicalDecl();
2548 if (auto *DDD = DClass->DefinitionData) {
2549 if (ExistingClass->DefinitionData) {
2550 MergeDefinitionData(ExistingClass, std::move(*DDD));
2552 ExistingClass->DefinitionData = DClass->DefinitionData;
2553 // We may have skipped this before because we thought that DClass
2554 // was the canonical declaration.
2555 Reader.PendingDefinitions.insert(DClass);
2558 DClass->DefinitionData = ExistingClass->DefinitionData;
2560 return mergeRedeclarable(DClass, cast<TagDecl>(ExistingPattern),
2563 if (auto *DFunction = dyn_cast<FunctionDecl>(DPattern))
2564 return mergeRedeclarable(DFunction, cast<FunctionDecl>(ExistingPattern),
2566 if (auto *DVar = dyn_cast<VarDecl>(DPattern))
2567 return mergeRedeclarable(DVar, cast<VarDecl>(ExistingPattern), Result);
2568 if (auto *DAlias = dyn_cast<TypeAliasDecl>(DPattern))
2569 return mergeRedeclarable(DAlias, cast<TypedefNameDecl>(ExistingPattern),
2571 llvm_unreachable("merged an unknown kind of redeclarable template");
2574 /// Attempts to merge the given declaration (D) with another declaration
2575 /// of the same entity.
2576 template<typename T>
2577 void ASTDeclReader::mergeRedeclarable(Redeclarable<T> *DBase, T *Existing,
2578 RedeclarableResult &Redecl,
2579 DeclID TemplatePatternID) {
2580 auto *D = static_cast<T *>(DBase);
2581 T *ExistingCanon = Existing->getCanonicalDecl();
2582 T *DCanon = D->getCanonicalDecl();
2583 if (ExistingCanon != DCanon) {
2584 assert(DCanon->getGlobalID() == Redecl.getFirstID() &&
2585 "already merged this declaration");
2587 // Have our redeclaration link point back at the canonical declaration
2588 // of the existing declaration, so that this declaration has the
2589 // appropriate canonical declaration.
2590 D->RedeclLink = Redeclarable<T>::PreviousDeclLink(ExistingCanon);
2591 D->First = ExistingCanon;
2592 ExistingCanon->Used |= D->Used;
2595 // When we merge a namespace, update its pointer to the first namespace.
2596 // We cannot have loaded any redeclarations of this declaration yet, so
2597 // there's nothing else that needs to be updated.
2598 if (auto *Namespace = dyn_cast<NamespaceDecl>(D))
2599 Namespace->AnonOrFirstNamespaceAndInline.setPointer(
2600 assert_cast<NamespaceDecl*>(ExistingCanon));
2602 // When we merge a template, merge its pattern.
2603 if (auto *DTemplate = dyn_cast<RedeclarableTemplateDecl>(D))
2604 mergeTemplatePattern(
2605 DTemplate, assert_cast<RedeclarableTemplateDecl*>(ExistingCanon),
2606 TemplatePatternID, Redecl.isKeyDecl());
2608 // If this declaration is a key declaration, make a note of that.
2609 if (Redecl.isKeyDecl())
2610 Reader.KeyDecls[ExistingCanon].push_back(Redecl.getFirstID());
2614 /// ODR-like semantics for C/ObjC allow us to merge tag types and a structural
2615 /// check in Sema guarantees the types can be merged (see C11 6.2.7/1 or C89
2616 /// 6.1.2.6/1). Although most merging is done in Sema, we need to guarantee
2617 /// that some types are mergeable during deserialization, otherwise name
2618 /// lookup fails. This is the case for EnumConstantDecl.
2619 static bool allowODRLikeMergeInC(NamedDecl *ND) {
2622 // TODO: implement merge for other necessary decls.
2623 if (isa<EnumConstantDecl>(ND))
2628 /// Attempts to merge the given declaration (D) with another declaration
2629 /// of the same entity, for the case where the entity is not actually
2630 /// redeclarable. This happens, for instance, when merging the fields of
2631 /// identical class definitions from two different modules.
2632 template<typename T>
2633 void ASTDeclReader::mergeMergeable(Mergeable<T> *D) {
2634 // If modules are not available, there is no reason to perform this merge.
2635 if (!Reader.getContext().getLangOpts().Modules)
2638 // ODR-based merging is performed in C++ and in some cases (tag types) in C.
2639 // Note that C identically-named things in different translation units are
2640 // not redeclarations, but may still have compatible types, where ODR-like
2641 // semantics may apply.
2642 if (!Reader.getContext().getLangOpts().CPlusPlus &&
2643 !allowODRLikeMergeInC(dyn_cast<NamedDecl>(static_cast<T*>(D))))
2646 if (FindExistingResult ExistingRes = findExisting(static_cast<T*>(D)))
2647 if (T *Existing = ExistingRes)
2648 Reader.getContext().setPrimaryMergedDecl(static_cast<T *>(D),
2649 Existing->getCanonicalDecl());
2652 void ASTDeclReader::VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D) {
2654 unsigned NumVars = D->varlist_size();
2655 SmallVector<Expr *, 16> Vars;
2656 Vars.reserve(NumVars);
2657 for (unsigned i = 0; i != NumVars; ++i) {
2658 Vars.push_back(Record.readExpr());
2663 void ASTDeclReader::VisitOMPAllocateDecl(OMPAllocateDecl *D) {
2665 unsigned NumVars = D->varlist_size();
2666 unsigned NumClauses = D->clauselist_size();
2667 SmallVector<Expr *, 16> Vars;
2668 Vars.reserve(NumVars);
2669 for (unsigned i = 0; i != NumVars; ++i) {
2670 Vars.push_back(Record.readExpr());
2673 SmallVector<OMPClause *, 8> Clauses;
2674 Clauses.reserve(NumClauses);
2675 OMPClauseReader ClauseReader(Record);
2676 for (unsigned I = 0; I != NumClauses; ++I)
2677 Clauses.push_back(ClauseReader.readClause());
2678 D->setClauses(Clauses);
2681 void ASTDeclReader::VisitOMPRequiresDecl(OMPRequiresDecl * D) {
2683 unsigned NumClauses = D->clauselist_size();
2684 SmallVector<OMPClause *, 8> Clauses;
2685 Clauses.reserve(NumClauses);
2686 OMPClauseReader ClauseReader(Record);
2687 for (unsigned I = 0; I != NumClauses; ++I)
2688 Clauses.push_back(ClauseReader.readClause());
2689 D->setClauses(Clauses);
2692 void ASTDeclReader::VisitOMPDeclareReductionDecl(OMPDeclareReductionDecl *D) {
2694 D->setLocation(ReadSourceLocation());
2695 Expr *In = Record.readExpr();
2696 Expr *Out = Record.readExpr();
2697 D->setCombinerData(In, Out);
2698 Expr *Combiner = Record.readExpr();
2699 D->setCombiner(Combiner);
2700 Expr *Orig = Record.readExpr();
2701 Expr *Priv = Record.readExpr();
2702 D->setInitializerData(Orig, Priv);
2703 Expr *Init = Record.readExpr();
2704 auto IK = static_cast<OMPDeclareReductionDecl::InitKind>(Record.readInt());
2705 D->setInitializer(Init, IK);
2706 D->PrevDeclInScope = ReadDeclID();
2709 void ASTDeclReader::VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D) {
2711 D->setLocation(ReadSourceLocation());
2712 Expr *MapperVarRefE = Record.readExpr();
2713 D->setMapperVarRef(MapperVarRefE);
2714 D->VarName = Record.readDeclarationName();
2715 D->PrevDeclInScope = ReadDeclID();
2716 unsigned NumClauses = D->clauselist_size();
2717 SmallVector<OMPClause *, 8> Clauses;
2718 Clauses.reserve(NumClauses);
2719 OMPClauseReader ClauseReader(Record);
2720 for (unsigned I = 0; I != NumClauses; ++I)
2721 Clauses.push_back(ClauseReader.readClause());
2722 D->setClauses(Clauses);
2725 void ASTDeclReader::VisitOMPCapturedExprDecl(OMPCapturedExprDecl *D) {
2729 //===----------------------------------------------------------------------===//
2730 // Attribute Reading
2731 //===----------------------------------------------------------------------===//
2737 const ASTReader::RecordData &Record;
2741 AttrReader(ModuleFile &F, ASTReader &Reader,
2742 const ASTReader::RecordData &Record, unsigned &Idx)
2743 : F(&F), Reader(&Reader), Record(Record), Idx(Idx) {}
2745 const uint64_t &readInt() { return Record[Idx++]; }
2747 SourceRange readSourceRange() {
2748 return Reader->ReadSourceRange(*F, Record, Idx);
2751 Expr *readExpr() { return Reader->ReadExpr(*F); }
2753 std::string readString() {
2754 return Reader->ReadString(Record, Idx);
2757 TypeSourceInfo *getTypeSourceInfo() {
2758 return Reader->GetTypeSourceInfo(*F, Record, Idx);
2761 IdentifierInfo *getIdentifierInfo() {
2762 return Reader->GetIdentifierInfo(*F, Record, Idx);
2765 VersionTuple readVersionTuple() {
2766 return ASTReader::ReadVersionTuple(Record, Idx);
2769 template <typename T> T *GetLocalDeclAs(uint32_t LocalID) {
2770 return cast_or_null<T>(Reader->GetLocalDecl(*F, LocalID));
2775 Attr *ASTReader::ReadAttr(ModuleFile &M, const RecordData &Rec,
2777 AttrReader Record(M, *this, Rec, Idx);
2778 auto V = Record.readInt();
2782 Attr *New = nullptr;
2783 // Kind is stored as a 1-based integer because 0 is used to indicate a null
2785 auto Kind = static_cast<attr::Kind>(V - 1);
2786 SourceRange Range = Record.readSourceRange();
2787 ASTContext &Context = getContext();
2789 #include "clang/Serialization/AttrPCHRead.inc"
2791 assert(New && "Unable to decode attribute?");
2795 /// Reads attributes from the current stream position.
2796 void ASTReader::ReadAttributes(ASTRecordReader &Record, AttrVec &Attrs) {
2797 for (unsigned I = 0, E = Record.readInt(); I != E; ++I)
2798 Attrs.push_back(Record.readAttr());
2801 //===----------------------------------------------------------------------===//
2802 // ASTReader Implementation
2803 //===----------------------------------------------------------------------===//
2805 /// Note that we have loaded the declaration with the given
2808 /// This routine notes that this declaration has already been loaded,
2809 /// so that future GetDecl calls will return this declaration rather
2810 /// than trying to load a new declaration.
2811 inline void ASTReader::LoadedDecl(unsigned Index, Decl *D) {
2812 assert(!DeclsLoaded[Index] && "Decl loaded twice?");
2813 DeclsLoaded[Index] = D;
2816 /// Determine whether the consumer will be interested in seeing
2817 /// this declaration (via HandleTopLevelDecl).
2819 /// This routine should return true for anything that might affect
2820 /// code generation, e.g., inline function definitions, Objective-C
2821 /// declarations with metadata, etc.
2822 static bool isConsumerInterestedIn(ASTContext &Ctx, Decl *D, bool HasBody) {
2823 // An ObjCMethodDecl is never considered as "interesting" because its
2824 // implementation container always is.
2826 // An ImportDecl or VarDecl imported from a module map module will get
2827 // emitted when we import the relevant module.
2828 if (isPartOfPerModuleInitializer(D)) {
2829 auto *M = D->getImportedOwningModule();
2830 if (M && M->Kind == Module::ModuleMapModule &&
2831 Ctx.DeclMustBeEmitted(D))
2835 if (isa<FileScopeAsmDecl>(D) ||
2836 isa<ObjCProtocolDecl>(D) ||
2837 isa<ObjCImplDecl>(D) ||
2838 isa<ImportDecl>(D) ||
2839 isa<PragmaCommentDecl>(D) ||
2840 isa<PragmaDetectMismatchDecl>(D))
2842 if (isa<OMPThreadPrivateDecl>(D) || isa<OMPDeclareReductionDecl>(D) ||
2843 isa<OMPDeclareMapperDecl>(D) || isa<OMPAllocateDecl>(D))
2844 return !D->getDeclContext()->isFunctionOrMethod();
2845 if (const auto *Var = dyn_cast<VarDecl>(D))
2846 return Var->isFileVarDecl() &&
2847 (Var->isThisDeclarationADefinition() == VarDecl::Definition ||
2848 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Var));
2849 if (const auto *Func = dyn_cast<FunctionDecl>(D))
2850 return Func->doesThisDeclarationHaveABody() || HasBody;
2852 if (auto *ES = D->getASTContext().getExternalSource())
2853 if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
2859 /// Get the correct cursor and offset for loading a declaration.
2860 ASTReader::RecordLocation
2861 ASTReader::DeclCursorForID(DeclID ID, SourceLocation &Loc) {
2862 GlobalDeclMapType::iterator I = GlobalDeclMap.find(ID);
2863 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
2864 ModuleFile *M = I->second;
2865 const DeclOffset &DOffs =
2866 M->DeclOffsets[ID - M->BaseDeclID - NUM_PREDEF_DECL_IDS];
2867 Loc = TranslateSourceLocation(*M, DOffs.getLocation());
2868 return RecordLocation(M, DOffs.BitOffset);
2871 ASTReader::RecordLocation ASTReader::getLocalBitOffset(uint64_t GlobalOffset) {
2872 auto I = GlobalBitOffsetsMap.find(GlobalOffset);
2874 assert(I != GlobalBitOffsetsMap.end() && "Corrupted global bit offsets map");
2875 return RecordLocation(I->second, GlobalOffset - I->second->GlobalBitOffset);
2878 uint64_t ASTReader::getGlobalBitOffset(ModuleFile &M, uint32_t LocalOffset) {
2879 return LocalOffset + M.GlobalBitOffset;
2882 static bool isSameTemplateParameterList(const TemplateParameterList *X,
2883 const TemplateParameterList *Y);
2885 /// Determine whether two template parameters are similar enough
2886 /// that they may be used in declarations of the same template.
2887 static bool isSameTemplateParameter(const NamedDecl *X,
2888 const NamedDecl *Y) {
2889 if (X->getKind() != Y->getKind())
2892 if (const auto *TX = dyn_cast<TemplateTypeParmDecl>(X)) {
2893 const auto *TY = cast<TemplateTypeParmDecl>(Y);
2894 return TX->isParameterPack() == TY->isParameterPack();
2897 if (const auto *TX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
2898 const auto *TY = cast<NonTypeTemplateParmDecl>(Y);
2899 return TX->isParameterPack() == TY->isParameterPack() &&
2900 TX->getASTContext().hasSameType(TX->getType(), TY->getType());
2903 const auto *TX = cast<TemplateTemplateParmDecl>(X);
2904 const auto *TY = cast<TemplateTemplateParmDecl>(Y);
2905 return TX->isParameterPack() == TY->isParameterPack() &&
2906 isSameTemplateParameterList(TX->getTemplateParameters(),
2907 TY->getTemplateParameters());
2910 static NamespaceDecl *getNamespace(const NestedNameSpecifier *X) {
2911 if (auto *NS = X->getAsNamespace())
2913 if (auto *NAS = X->getAsNamespaceAlias())
2914 return NAS->getNamespace();
2918 static bool isSameQualifier(const NestedNameSpecifier *X,
2919 const NestedNameSpecifier *Y) {
2920 if (auto *NSX = getNamespace(X)) {
2921 auto *NSY = getNamespace(Y);
2922 if (!NSY || NSX->getCanonicalDecl() != NSY->getCanonicalDecl())
2924 } else if (X->getKind() != Y->getKind())
2927 // FIXME: For namespaces and types, we're permitted to check that the entity
2928 // is named via the same tokens. We should probably do so.
2929 switch (X->getKind()) {
2930 case NestedNameSpecifier::Identifier:
2931 if (X->getAsIdentifier() != Y->getAsIdentifier())
2934 case NestedNameSpecifier::Namespace:
2935 case NestedNameSpecifier::NamespaceAlias:
2936 // We've already checked that we named the same namespace.
2938 case NestedNameSpecifier::TypeSpec:
2939 case NestedNameSpecifier::TypeSpecWithTemplate:
2940 if (X->getAsType()->getCanonicalTypeInternal() !=
2941 Y->getAsType()->getCanonicalTypeInternal())
2944 case NestedNameSpecifier::Global:
2945 case NestedNameSpecifier::Super:
2949 // Recurse into earlier portion of NNS, if any.
2950 auto *PX = X->getPrefix();
2951 auto *PY = Y->getPrefix();
2953 return isSameQualifier(PX, PY);
2957 /// Determine whether two template parameter lists are similar enough
2958 /// that they may be used in declarations of the same template.
2959 static bool isSameTemplateParameterList(const TemplateParameterList *X,
2960 const TemplateParameterList *Y) {
2961 if (X->size() != Y->size())
2964 for (unsigned I = 0, N = X->size(); I != N; ++I)
2965 if (!isSameTemplateParameter(X->getParam(I), Y->getParam(I)))
2971 /// Determine whether the attributes we can overload on are identical for A and
2972 /// B. Will ignore any overloadable attrs represented in the type of A and B.
2973 static bool hasSameOverloadableAttrs(const FunctionDecl *A,
2974 const FunctionDecl *B) {
2975 // Note that pass_object_size attributes are represented in the function's
2976 // ExtParameterInfo, so we don't need to check them here.
2978 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
2979 auto AEnableIfAttrs = A->specific_attrs<EnableIfAttr>();
2980 auto BEnableIfAttrs = B->specific_attrs<EnableIfAttr>();
2982 for (auto Pair : zip_longest(AEnableIfAttrs, BEnableIfAttrs)) {
2983 Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
2984 Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
2986 // Return false if the number of enable_if attributes is different.
2987 if (!Cand1A || !Cand2A)
2993 (*Cand1A)->getCond()->Profile(Cand1ID, A->getASTContext(), true);
2994 (*Cand2A)->getCond()->Profile(Cand2ID, B->getASTContext(), true);
2996 // Return false if any of the enable_if expressions of A and B are
2998 if (Cand1ID != Cand2ID)
3004 /// Determine whether the two declarations refer to the same entity.
3005 static bool isSameEntity(NamedDecl *X, NamedDecl *Y) {
3006 assert(X->getDeclName() == Y->getDeclName() && "Declaration name mismatch!");
3011 // Must be in the same context.
3013 // Note that we can't use DeclContext::Equals here, because the DeclContexts
3014 // could be two different declarations of the same function. (We will fix the
3015 // semantic DC to refer to the primary definition after merging.)
3016 if (!declaresSameEntity(cast<Decl>(X->getDeclContext()->getRedeclContext()),
3017 cast<Decl>(Y->getDeclContext()->getRedeclContext())))
3020 // Two typedefs refer to the same entity if they have the same underlying
3022 if (const auto *TypedefX = dyn_cast<TypedefNameDecl>(X))
3023 if (const auto *TypedefY = dyn_cast<TypedefNameDecl>(Y))
3024 return X->getASTContext().hasSameType(TypedefX->getUnderlyingType(),
3025 TypedefY->getUnderlyingType());
3027 // Must have the same kind.
3028 if (X->getKind() != Y->getKind())
3031 // Objective-C classes and protocols with the same name always match.
3032 if (isa<ObjCInterfaceDecl>(X) || isa<ObjCProtocolDecl>(X))
3035 if (isa<ClassTemplateSpecializationDecl>(X)) {
3036 // No need to handle these here: we merge them when adding them to the
3041 // Compatible tags match.
3042 if (const auto *TagX = dyn_cast<TagDecl>(X)) {
3043 const auto *TagY = cast<TagDecl>(Y);
3044 return (TagX->getTagKind() == TagY->getTagKind()) ||
3045 ((TagX->getTagKind() == TTK_Struct || TagX->getTagKind() == TTK_Class ||
3046 TagX->getTagKind() == TTK_Interface) &&
3047 (TagY->getTagKind() == TTK_Struct || TagY->getTagKind() == TTK_Class ||
3048 TagY->getTagKind() == TTK_Interface));
3051 // Functions with the same type and linkage match.
3052 // FIXME: This needs to cope with merging of prototyped/non-prototyped
3054 if (const auto *FuncX = dyn_cast<FunctionDecl>(X)) {
3055 const auto *FuncY = cast<FunctionDecl>(Y);
3056 if (const auto *CtorX = dyn_cast<CXXConstructorDecl>(X)) {
3057 const auto *CtorY = cast<CXXConstructorDecl>(Y);
3058 if (CtorX->getInheritedConstructor() &&
3059 !isSameEntity(CtorX->getInheritedConstructor().getConstructor(),
3060 CtorY->getInheritedConstructor().getConstructor()))
3064 if (FuncX->isMultiVersion() != FuncY->isMultiVersion())
3067 // Multiversioned functions with different feature strings are represented
3068 // as separate declarations.
3069 if (FuncX->isMultiVersion()) {
3070 const auto *TAX = FuncX->getAttr<TargetAttr>();
3071 const auto *TAY = FuncY->getAttr<TargetAttr>();
3072 assert(TAX && TAY && "Multiversion Function without target attribute");
3074 if (TAX->getFeaturesStr() != TAY->getFeaturesStr())
3078 ASTContext &C = FuncX->getASTContext();
3079 auto GetTypeAsWritten = [](const FunctionDecl *FD) {
3080 // Map to the first declaration that we've already merged into this one.
3081 // The TSI of redeclarations might not match (due to calling conventions
3082 // being inherited onto the type but not the TSI), but the TSI type of
3083 // the first declaration of the function should match across modules.
3084 FD = FD->getCanonicalDecl();
3085 return FD->getTypeSourceInfo() ? FD->getTypeSourceInfo()->getType()
3088 QualType XT = GetTypeAsWritten(FuncX), YT = GetTypeAsWritten(FuncY);
3089 if (!C.hasSameType(XT, YT)) {
3090 // We can get functions with different types on the redecl chain in C++17
3091 // if they have differing exception specifications and at least one of
3092 // the excpetion specs is unresolved.
3093 auto *XFPT = XT->getAs<FunctionProtoType>();
3094 auto *YFPT = YT->getAs<FunctionProtoType>();
3095 if (C.getLangOpts().CPlusPlus17 && XFPT && YFPT &&
3096 (isUnresolvedExceptionSpec(XFPT->getExceptionSpecType()) ||
3097 isUnresolvedExceptionSpec(YFPT->getExceptionSpecType())) &&
3098 C.hasSameFunctionTypeIgnoringExceptionSpec(XT, YT))
3102 return FuncX->getLinkageInternal() == FuncY->getLinkageInternal() &&
3103 hasSameOverloadableAttrs(FuncX, FuncY);
3106 // Variables with the same type and linkage match.
3107 if (const auto *VarX = dyn_cast<VarDecl>(X)) {
3108 const auto *VarY = cast<VarDecl>(Y);
3109 if (VarX->getLinkageInternal() == VarY->getLinkageInternal()) {
3110 ASTContext &C = VarX->getASTContext();
3111 if (C.hasSameType(VarX->getType(), VarY->getType()))
3114 // We can get decls with different types on the redecl chain. Eg.
3115 // template <typename T> struct S { static T Var[]; }; // #1
3116 // template <typename T> T S<T>::Var[sizeof(T)]; // #2
3117 // Only? happens when completing an incomplete array type. In this case
3118 // when comparing #1 and #2 we should go through their element type.
3119 const ArrayType *VarXTy = C.getAsArrayType(VarX->getType());
3120 const ArrayType *VarYTy = C.getAsArrayType(VarY->getType());
3121 if (!VarXTy || !VarYTy)
3123 if (VarXTy->isIncompleteArrayType() || VarYTy->isIncompleteArrayType())
3124 return C.hasSameType(VarXTy->getElementType(), VarYTy->getElementType());
3129 // Namespaces with the same name and inlinedness match.
3130 if (const auto *NamespaceX = dyn_cast<NamespaceDecl>(X)) {
3131 const auto *NamespaceY = cast<NamespaceDecl>(Y);
3132 return NamespaceX->isInline() == NamespaceY->isInline();
3135 // Identical template names and kinds match if their template parameter lists
3136 // and patterns match.
3137 if (const auto *TemplateX = dyn_cast<TemplateDecl>(X)) {
3138 const auto *TemplateY = cast<TemplateDecl>(Y);
3139 return isSameEntity(TemplateX->getTemplatedDecl(),
3140 TemplateY->getTemplatedDecl()) &&
3141 isSameTemplateParameterList(TemplateX->getTemplateParameters(),
3142 TemplateY->getTemplateParameters());
3145 // Fields with the same name and the same type match.
3146 if (const auto *FDX = dyn_cast<FieldDecl>(X)) {
3147 const auto *FDY = cast<FieldDecl>(Y);
3148 // FIXME: Also check the bitwidth is odr-equivalent, if any.
3149 return X->getASTContext().hasSameType(FDX->getType(), FDY->getType());
3152 // Indirect fields with the same target field match.
3153 if (const auto *IFDX = dyn_cast<IndirectFieldDecl>(X)) {
3154 const auto *IFDY = cast<IndirectFieldDecl>(Y);
3155 return IFDX->getAnonField()->getCanonicalDecl() ==
3156 IFDY->getAnonField()->getCanonicalDecl();
3159 // Enumerators with the same name match.
3160 if (isa<EnumConstantDecl>(X))
3161 // FIXME: Also check the value is odr-equivalent.
3164 // Using shadow declarations with the same target match.
3165 if (const auto *USX = dyn_cast<UsingShadowDecl>(X)) {
3166 const auto *USY = cast<UsingShadowDecl>(Y);
3167 return USX->getTargetDecl() == USY->getTargetDecl();
3170 // Using declarations with the same qualifier match. (We already know that
3171 // the name matches.)
3172 if (const auto *UX = dyn_cast<UsingDecl>(X)) {
3173 const auto *UY = cast<UsingDecl>(Y);
3174 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
3175 UX->hasTypename() == UY->hasTypename() &&
3176 UX->isAccessDeclaration() == UY->isAccessDeclaration();
3178 if (const auto *UX = dyn_cast<UnresolvedUsingValueDecl>(X)) {
3179 const auto *UY = cast<UnresolvedUsingValueDecl>(Y);
3180 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
3181 UX->isAccessDeclaration() == UY->isAccessDeclaration();
3183 if (const auto *UX = dyn_cast<UnresolvedUsingTypenameDecl>(X))
3184 return isSameQualifier(
3186 cast<UnresolvedUsingTypenameDecl>(Y)->getQualifier());
3188 // Namespace alias definitions with the same target match.
3189 if (const auto *NAX = dyn_cast<NamespaceAliasDecl>(X)) {
3190 const auto *NAY = cast<NamespaceAliasDecl>(Y);
3191 return NAX->getNamespace()->Equals(NAY->getNamespace());
3197 /// Find the context in which we should search for previous declarations when
3198 /// looking for declarations to merge.
3199 DeclContext *ASTDeclReader::getPrimaryContextForMerging(ASTReader &Reader,
3201 if (auto *ND = dyn_cast<NamespaceDecl>(DC))
3202 return ND->getOriginalNamespace();
3204 if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) {
3205 // Try to dig out the definition.
3206 auto *DD = RD->DefinitionData;
3208 DD = RD->getCanonicalDecl()->DefinitionData;
3210 // If there's no definition yet, then DC's definition is added by an update
3211 // record, but we've not yet loaded that update record. In this case, we
3212 // commit to DC being the canonical definition now, and will fix this when
3213 // we load the update record.
3215 DD = new (Reader.getContext()) struct CXXRecordDecl::DefinitionData(RD);
3216 RD->setCompleteDefinition(true);
3217 RD->DefinitionData = DD;
3218 RD->getCanonicalDecl()->DefinitionData = DD;
3220 // Track that we did this horrible thing so that we can fix it later.
3221 Reader.PendingFakeDefinitionData.insert(
3222 std::make_pair(DD, ASTReader::PendingFakeDefinitionKind::Fake));
3225 return DD->Definition;
3228 if (auto *ED = dyn_cast<EnumDecl>(DC))
3229 return ED->getASTContext().getLangOpts().CPlusPlus? ED->getDefinition()
3232 // We can see the TU here only if we have no Sema object. In that case,
3233 // there's no TU scope to look in, so using the DC alone is sufficient.
3234 if (auto *TU = dyn_cast<TranslationUnitDecl>(DC))
3240 ASTDeclReader::FindExistingResult::~FindExistingResult() {
3241 // Record that we had a typedef name for linkage whether or not we merge
3242 // with that declaration.
3243 if (TypedefNameForLinkage) {
3244 DeclContext *DC = New->getDeclContext()->getRedeclContext();
3245 Reader.ImportedTypedefNamesForLinkage.insert(
3246 std::make_pair(std::make_pair(DC, TypedefNameForLinkage), New));
3250 if (!AddResult || Existing)
3253 DeclarationName Name = New->getDeclName();
3254 DeclContext *DC = New->getDeclContext()->getRedeclContext();
3255 if (needsAnonymousDeclarationNumber(New)) {
3256 setAnonymousDeclForMerging(Reader, New->getLexicalDeclContext(),
3257 AnonymousDeclNumber, New);
3258 } else if (DC->isTranslationUnit() &&
3259 !Reader.getContext().getLangOpts().CPlusPlus) {
3260 if (Reader.getIdResolver().tryAddTopLevelDecl(New, Name))
3261 Reader.PendingFakeLookupResults[Name.getAsIdentifierInfo()]
3263 } else if (DeclContext *MergeDC = getPrimaryContextForMerging(Reader, DC)) {
3264 // Add the declaration to its redeclaration context so later merging
3265 // lookups will find it.
3266 MergeDC->makeDeclVisibleInContextImpl(New, /*Internal*/true);
3270 /// Find the declaration that should be merged into, given the declaration found
3271 /// by name lookup. If we're merging an anonymous declaration within a typedef,
3272 /// we need a matching typedef, and we merge with the type inside it.
3273 static NamedDecl *getDeclForMerging(NamedDecl *Found,
3274 bool IsTypedefNameForLinkage) {
3275 if (!IsTypedefNameForLinkage)
3278 // If we found a typedef declaration that gives a name to some other
3279 // declaration, then we want that inner declaration. Declarations from
3280 // AST files are handled via ImportedTypedefNamesForLinkage.
3281 if (Found->isFromASTFile())
3284 if (auto *TND = dyn_cast<TypedefNameDecl>(Found))
3285 return TND->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
3290 /// Find the declaration to use to populate the anonymous declaration table
3291 /// for the given lexical DeclContext. We only care about finding local
3292 /// definitions of the context; we'll merge imported ones as we go.
3294 ASTDeclReader::getPrimaryDCForAnonymousDecl(DeclContext *LexicalDC) {
3295 // For classes, we track the definition as we merge.
3296 if (auto *RD = dyn_cast<CXXRecordDecl>(LexicalDC)) {
3297 auto *DD = RD->getCanonicalDecl()->DefinitionData;
3298 return DD ? DD->Definition : nullptr;
3301 // For anything else, walk its merged redeclarations looking for a definition.
3302 // Note that we can't just call getDefinition here because the redeclaration
3303 // chain isn't wired up.
3304 for (auto *D : merged_redecls(cast<Decl>(LexicalDC))) {
3305 if (auto *FD = dyn_cast<FunctionDecl>(D))
3306 if (FD->isThisDeclarationADefinition())
3308 if (auto *MD = dyn_cast<ObjCMethodDecl>(D))
3309 if (MD->isThisDeclarationADefinition())
3313 // No merged definition yet.
3317 NamedDecl *ASTDeclReader::getAnonymousDeclForMerging(ASTReader &Reader,
3320 // If the lexical context has been merged, look into the now-canonical
3322 auto *CanonDC = cast<Decl>(DC)->getCanonicalDecl();
3324 // If we've seen this before, return the canonical declaration.
3325 auto &Previous = Reader.AnonymousDeclarationsForMerging[CanonDC];
3326 if (Index < Previous.size() && Previous[Index])
3327 return Previous[Index];
3329 // If this is the first time, but we have parsed a declaration of the context,
3330 // build the anonymous declaration list from the parsed declaration.
3331 auto *PrimaryDC = getPrimaryDCForAnonymousDecl(DC);
3332 if (PrimaryDC && !cast<Decl>(PrimaryDC)->isFromASTFile()) {
3333 numberAnonymousDeclsWithin(PrimaryDC, [&](NamedDecl *ND, unsigned Number) {
3334 if (Previous.size() == Number)
3335 Previous.push_back(cast<NamedDecl>(ND->getCanonicalDecl()));
3337 Previous[Number] = cast<NamedDecl>(ND->getCanonicalDecl());
3341 return Index < Previous.size() ? Previous[Index] : nullptr;
3344 void ASTDeclReader::setAnonymousDeclForMerging(ASTReader &Reader,
3345 DeclContext *DC, unsigned Index,
3347 auto *CanonDC = cast<Decl>(DC)->getCanonicalDecl();
3349 auto &Previous = Reader.AnonymousDeclarationsForMerging[CanonDC];
3350 if (Index >= Previous.size())
3351 Previous.resize(Index + 1);
3352 if (!Previous[Index])
3353 Previous[Index] = D;
3356 ASTDeclReader::FindExistingResult ASTDeclReader::findExisting(NamedDecl *D) {
3357 DeclarationName Name = TypedefNameForLinkage ? TypedefNameForLinkage
3360 if (!Name && !needsAnonymousDeclarationNumber(D)) {
3361 // Don't bother trying to find unnamed declarations that are in
3362 // unmergeable contexts.
3363 FindExistingResult Result(Reader, D, /*Existing=*/nullptr,
3364 AnonymousDeclNumber, TypedefNameForLinkage);
3369 DeclContext *DC = D->getDeclContext()->getRedeclContext();
3370 if (TypedefNameForLinkage) {
3371 auto It = Reader.ImportedTypedefNamesForLinkage.find(
3372 std::make_pair(DC, TypedefNameForLinkage));
3373 if (It != Reader.ImportedTypedefNamesForLinkage.end())
3374 if (isSameEntity(It->second, D))
3375 return FindExistingResult(Reader, D, It->second, AnonymousDeclNumber,
3376 TypedefNameForLinkage);
3377 // Go on to check in other places in case an existing typedef name
3378 // was not imported.
3381 if (needsAnonymousDeclarationNumber(D)) {
3382 // This is an anonymous declaration that we may need to merge. Look it up
3383 // in its context by number.
3384 if (auto *Existing = getAnonymousDeclForMerging(
3385 Reader, D->getLexicalDeclContext(), AnonymousDeclNumber))
3386 if (isSameEntity(Existing, D))
3387 return FindExistingResult(Reader, D, Existing, AnonymousDeclNumber,
3388 TypedefNameForLinkage);
3389 } else if (DC->isTranslationUnit() &&
3390 !Reader.getContext().getLangOpts().CPlusPlus) {
3391 IdentifierResolver &IdResolver = Reader.getIdResolver();
3393 // Temporarily consider the identifier to be up-to-date. We don't want to
3394 // cause additional lookups here.
3395 class UpToDateIdentifierRAII {
3397 bool WasOutToDate = false;
3400 explicit UpToDateIdentifierRAII(IdentifierInfo *II) : II(II) {
3402 WasOutToDate = II->isOutOfDate();
3404 II->setOutOfDate(false);
3408 ~UpToDateIdentifierRAII() {
3410 II->setOutOfDate(true);
3412 } UpToDate(Name.getAsIdentifierInfo());
3414 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
3415 IEnd = IdResolver.end();
3417 if (NamedDecl *Existing = getDeclForMerging(*I, TypedefNameForLinkage))
3418 if (isSameEntity(Existing, D))
3419 return FindExistingResult(Reader, D, Existing, AnonymousDeclNumber,
3420 TypedefNameForLinkage);
3422 } else if (DeclContext *MergeDC = getPrimaryContextForMerging(Reader, DC)) {
3423 DeclContext::lookup_result R = MergeDC->noload_lookup(Name);
3424 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
3425 if (NamedDecl *Existing = getDeclForMerging(*I, TypedefNameForLinkage))
3426 if (isSameEntity(Existing, D))
3427 return FindExistingResult(Reader, D, Existing, AnonymousDeclNumber,
3428 TypedefNameForLinkage);
3431 // Not in a mergeable context.
3432 return FindExistingResult(Reader);
3435 // If this declaration is from a merged context, make a note that we need to
3436 // check that the canonical definition of that context contains the decl.
3438 // FIXME: We should do something similar if we merge two definitions of the
3439 // same template specialization into the same CXXRecordDecl.
3440 auto MergedDCIt = Reader.MergedDeclContexts.find(D->getLexicalDeclContext());
3441 if (MergedDCIt != Reader.MergedDeclContexts.end() &&
3442 MergedDCIt->second == D->getDeclContext())
3443 Reader.PendingOdrMergeChecks.push_back(D);
3445 return FindExistingResult(Reader, D, /*Existing=*/nullptr,
3446 AnonymousDeclNumber, TypedefNameForLinkage);
3449 template<typename DeclT>
3450 Decl *ASTDeclReader::getMostRecentDeclImpl(Redeclarable<DeclT> *D) {
3451 return D->RedeclLink.getLatestNotUpdated();
3454 Decl *ASTDeclReader::getMostRecentDeclImpl(...) {
3455 llvm_unreachable("getMostRecentDecl on non-redeclarable declaration");
3458 Decl *ASTDeclReader::getMostRecentDecl(Decl *D) {
3461 switch (D->getKind()) {
3462 #define ABSTRACT_DECL(TYPE)
3463 #define DECL(TYPE, BASE) \
3465 return getMostRecentDeclImpl(cast<TYPE##Decl>(D));
3466 #include "clang/AST/DeclNodes.inc"
3468 llvm_unreachable("unknown decl kind");
3471 Decl *ASTReader::getMostRecentExistingDecl(Decl *D) {
3472 return ASTDeclReader::getMostRecentDecl(D->getCanonicalDecl());
3475 template<typename DeclT>
3476 void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader,
3477 Redeclarable<DeclT> *D,
3478 Decl *Previous, Decl *Canon) {
3479 D->RedeclLink.setPrevious(cast<DeclT>(Previous));
3480 D->First = cast<DeclT>(Previous)->First;
3486 void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader,
3487 Redeclarable<VarDecl> *D,
3488 Decl *Previous, Decl *Canon) {
3489 auto *VD = static_cast<VarDecl *>(D);
3490 auto *PrevVD = cast<VarDecl>(Previous);
3491 D->RedeclLink.setPrevious(PrevVD);
3492 D->First = PrevVD->First;
3494 // We should keep at most one definition on the chain.
3495 // FIXME: Cache the definition once we've found it. Building a chain with
3496 // N definitions currently takes O(N^2) time here.
3497 if (VD->isThisDeclarationADefinition() == VarDecl::Definition) {
3498 for (VarDecl *CurD = PrevVD; CurD; CurD = CurD->getPreviousDecl()) {
3499 if (CurD->isThisDeclarationADefinition() == VarDecl::Definition) {
3500 Reader.mergeDefinitionVisibility(CurD, VD);
3501 VD->demoteThisDefinitionToDeclaration();
3508 static bool isUndeducedReturnType(QualType T) {
3509 auto *DT = T->getContainedDeducedType();
3510 return DT && !DT->isDeduced();
3514 void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader,
3515 Redeclarable<FunctionDecl> *D,
3516 Decl *Previous, Decl *Canon) {
3517 auto *FD = static_cast<FunctionDecl *>(D);
3518 auto *PrevFD = cast<FunctionDecl>(Previous);
3520 FD->RedeclLink.setPrevious(PrevFD);
3521 FD->First = PrevFD->First;
3523 // If the previous declaration is an inline function declaration, then this
3524 // declaration is too.
3525 if (PrevFD->isInlined() != FD->isInlined()) {
3526 // FIXME: [dcl.fct.spec]p4:
3527 // If a function with external linkage is declared inline in one
3528 // translation unit, it shall be declared inline in all translation
3529 // units in which it appears.
3531 // Be careful of this case:
3534 // template<typename T> struct X { void f(); };
3535 // template<typename T> inline void X<T>::f() {}
3537 // module B instantiates the declaration of X<int>::f
3538 // module C instantiates the definition of X<int>::f
3540 // If module B and C are merged, we do not have a violation of this rule.
3541 FD->setImplicitlyInline(true);
3544 auto *FPT = FD->getType()->getAs<FunctionProtoType>();
3545 auto *PrevFPT = PrevFD->getType()->getAs<FunctionProtoType>();
3546 if (FPT && PrevFPT) {
3547 // If we need to propagate an exception specification along the redecl
3548 // chain, make a note of that so that we can do so later.
3549 bool IsUnresolved = isUnresolvedExceptionSpec(FPT->getExceptionSpecType());
3550 bool WasUnresolved =
3551 isUnresolvedExceptionSpec(PrevFPT->getExceptionSpecType());
3552 if (IsUnresolved != WasUnresolved)
3553 Reader.PendingExceptionSpecUpdates.insert(
3554 {Canon, IsUnresolved ? PrevFD : FD});
3556 // If we need to propagate a deduced return type along the redecl chain,
3557 // make a note of that so that we can do it later.
3558 bool IsUndeduced = isUndeducedReturnType(FPT->getReturnType());
3559 bool WasUndeduced = isUndeducedReturnType(PrevFPT->getReturnType());
3560 if (IsUndeduced != WasUndeduced)
3561 Reader.PendingDeducedTypeUpdates.insert(
3562 {cast<FunctionDecl>(Canon),
3563 (IsUndeduced ? PrevFPT : FPT)->getReturnType()});
3567 } // namespace clang
3569 void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader, ...) {
3570 llvm_unreachable("attachPreviousDecl on non-redeclarable declaration");
3573 /// Inherit the default template argument from \p From to \p To. Returns
3574 /// \c false if there is no default template for \p From.
3575 template <typename ParmDecl>
3576 static bool inheritDefaultTemplateArgument(ASTContext &Context, ParmDecl *From,
3578 auto *To = cast<ParmDecl>(ToD);
3579 if (!From->hasDefaultArgument())
3581 To->setInheritedDefaultArgument(Context, From);
3585 static void inheritDefaultTemplateArguments(ASTContext &Context,
3588 auto *FromTP = From->getTemplateParameters();
3589 auto *ToTP = To->getTemplateParameters();
3590 assert(FromTP->size() == ToTP->size() && "merged mismatched templates?");
3592 for (unsigned I = 0, N = FromTP->size(); I != N; ++I) {
3593 NamedDecl *FromParam = FromTP->getParam(I);
3594 NamedDecl *ToParam = ToTP->getParam(I);
3596 if (auto *FTTP = dyn_cast<TemplateTypeParmDecl>(FromParam))
3597 inheritDefaultTemplateArgument(Context, FTTP, ToParam);
3598 else if (auto *FNTTP = dyn_cast<NonTypeTemplateParmDecl>(FromParam))
3599 inheritDefaultTemplateArgument(Context, FNTTP, ToParam);
3601 inheritDefaultTemplateArgument(
3602 Context, cast<TemplateTemplateParmDecl>(FromParam), ToParam);
3606 void ASTDeclReader::attachPreviousDecl(ASTReader &Reader, Decl *D,
3607 Decl *Previous, Decl *Canon) {
3608 assert(D && Previous);
3610 switch (D->getKind()) {
3611 #define ABSTRACT_DECL(TYPE)
3612 #define DECL(TYPE, BASE) \
3614 attachPreviousDeclImpl(Reader, cast<TYPE##Decl>(D), Previous, Canon); \
3616 #include "clang/AST/DeclNodes.inc"
3619 // If the declaration was visible in one module, a redeclaration of it in
3620 // another module remains visible even if it wouldn't be visible by itself.
3622 // FIXME: In this case, the declaration should only be visible if a module
3623 // that makes it visible has been imported.
3624 D->IdentifierNamespace |=
3625 Previous->IdentifierNamespace &
3626 (Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Type);
3628 // If the declaration declares a template, it may inherit default arguments
3629 // from the previous declaration.
3630 if (auto *TD = dyn_cast<TemplateDecl>(D))
3631 inheritDefaultTemplateArguments(Reader.getContext(),
3632 cast<TemplateDecl>(Previous), TD);
3635 template<typename DeclT>
3636 void ASTDeclReader::attachLatestDeclImpl(Redeclarable<DeclT> *D, Decl *Latest) {
3637 D->RedeclLink.setLatest(cast<DeclT>(Latest));
3640 void ASTDeclReader::attachLatestDeclImpl(...) {
3641 llvm_unreachable("attachLatestDecl on non-redeclarable declaration");
3644 void ASTDeclReader::attachLatestDecl(Decl *D, Decl *Latest) {
3645 assert(D && Latest);
3647 switch (D->getKind()) {
3648 #define ABSTRACT_DECL(TYPE)
3649 #define DECL(TYPE, BASE) \
3651 attachLatestDeclImpl(cast<TYPE##Decl>(D), Latest); \
3653 #include "clang/AST/DeclNodes.inc"
3657 template<typename DeclT>
3658 void ASTDeclReader::markIncompleteDeclChainImpl(Redeclarable<DeclT> *D) {
3659 D->RedeclLink.markIncomplete();
3662 void ASTDeclReader::markIncompleteDeclChainImpl(...) {
3663 llvm_unreachable("markIncompleteDeclChain on non-redeclarable declaration");
3666 void ASTReader::markIncompleteDeclChain(Decl *D) {
3667 switch (D->getKind()) {
3668 #define ABSTRACT_DECL(TYPE)
3669 #define DECL(TYPE, BASE) \
3671 ASTDeclReader::markIncompleteDeclChainImpl(cast<TYPE##Decl>(D)); \
3673 #include "clang/AST/DeclNodes.inc"
3677 /// Read the declaration at the given offset from the AST file.
3678 Decl *ASTReader::ReadDeclRecord(DeclID ID) {
3679 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
3680 SourceLocation DeclLoc;
3681 RecordLocation Loc = DeclCursorForID(ID, DeclLoc);
3682 llvm::BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
3683 // Keep track of where we are in the stream, then jump back there
3684 // after reading this declaration.
3685 SavedStreamPosition SavedPosition(DeclsCursor);
3687 ReadingKindTracker ReadingKind(Read_Decl, *this);
3689 // Note that we are loading a declaration record.
3690 Deserializing ADecl(this);
3692 auto Fail = [](const char *what, llvm::Error &&Err) {
3693 llvm::report_fatal_error(Twine("ASTReader::ReadDeclRecord failed ") + what +
3694 ": " + toString(std::move(Err)));
3697 if (llvm::Error JumpFailed = DeclsCursor.JumpToBit(Loc.Offset))
3698 Fail("jumping", std::move(JumpFailed));
3699 ASTRecordReader Record(*this, *Loc.F);
3700 ASTDeclReader Reader(*this, Record, Loc, ID, DeclLoc);
3701 Expected<unsigned> MaybeCode = DeclsCursor.ReadCode();
3703 Fail("reading code", MaybeCode.takeError());
3704 unsigned Code = MaybeCode.get();
3706 ASTContext &Context = getContext();
3708 Expected<unsigned> MaybeDeclCode = Record.readRecord(DeclsCursor, Code);
3710 llvm::report_fatal_error(
3711 "ASTReader::ReadDeclRecord failed reading decl code: " +
3712 toString(MaybeDeclCode.takeError()));
3713 switch ((DeclCode)MaybeDeclCode.get()) {
3714 case DECL_CONTEXT_LEXICAL:
3715 case DECL_CONTEXT_VISIBLE:
3716 llvm_unreachable("Record cannot be de-serialized with ReadDeclRecord");
3718 D = TypedefDecl::CreateDeserialized(Context, ID);
3720 case DECL_TYPEALIAS:
3721 D = TypeAliasDecl::CreateDeserialized(Context, ID);
3724 D = EnumDecl::CreateDeserialized(Context, ID);
3727 D = RecordDecl::CreateDeserialized(Context, ID);
3729 case DECL_ENUM_CONSTANT:
3730 D = EnumConstantDecl::CreateDeserialized(Context, ID);
3733 D = FunctionDecl::CreateDeserialized(Context, ID);
3735 case DECL_LINKAGE_SPEC:
3736 D = LinkageSpecDecl::CreateDeserialized(Context, ID);
3739 D = ExportDecl::CreateDeserialized(Context, ID);
3742 D = LabelDecl::CreateDeserialized(Context, ID);
3744 case DECL_NAMESPACE:
3745 D = NamespaceDecl::CreateDeserialized(Context, ID);
3747 case DECL_NAMESPACE_ALIAS:
3748 D = NamespaceAliasDecl::CreateDeserialized(Context, ID);
3751 D = UsingDecl::CreateDeserialized(Context, ID);
3753 case DECL_USING_PACK:
3754 D = UsingPackDecl::CreateDeserialized(Context, ID, Record.readInt());
3756 case DECL_USING_SHADOW:
3757 D = UsingShadowDecl::CreateDeserialized(Context, ID);
3759 case DECL_CONSTRUCTOR_USING_SHADOW:
3760 D = ConstructorUsingShadowDecl::CreateDeserialized(Context, ID);
3762 case DECL_USING_DIRECTIVE:
3763 D = UsingDirectiveDecl::CreateDeserialized(Context, ID);
3765 case DECL_UNRESOLVED_USING_VALUE:
3766 D = UnresolvedUsingValueDecl::CreateDeserialized(Context, ID);
3768 case DECL_UNRESOLVED_USING_TYPENAME:
3769 D = UnresolvedUsingTypenameDecl::CreateDeserialized(Context, ID);
3771 case DECL_CXX_RECORD:
3772 D = CXXRecordDecl::CreateDeserialized(Context, ID);
3774 case DECL_CXX_DEDUCTION_GUIDE:
3775 D = CXXDeductionGuideDecl::CreateDeserialized(Context, ID);
3777 case DECL_CXX_METHOD:
3778 D = CXXMethodDecl::CreateDeserialized(Context, ID);
3780 case DECL_CXX_CONSTRUCTOR:
3781 D = CXXConstructorDecl::CreateDeserialized(Context, ID, Record.readInt());
3783 case DECL_CXX_DESTRUCTOR:
3784 D = CXXDestructorDecl::CreateDeserialized(Context, ID);
3786 case DECL_CXX_CONVERSION:
3787 D = CXXConversionDecl::CreateDeserialized(Context, ID);
3789 case DECL_ACCESS_SPEC:
3790 D = AccessSpecDecl::CreateDeserialized(Context, ID);
3793 D = FriendDecl::CreateDeserialized(Context, ID, Record.readInt());
3795 case DECL_FRIEND_TEMPLATE:
3796 D = FriendTemplateDecl::CreateDeserialized(Context, ID);
3798 case DECL_CLASS_TEMPLATE:
3799 D = ClassTemplateDecl::CreateDeserialized(Context, ID);
3801 case DECL_CLASS_TEMPLATE_SPECIALIZATION:
3802 D = ClassTemplateSpecializationDecl::CreateDeserialized(Context, ID);
3804 case DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION:
3805 D = ClassTemplatePartialSpecializationDecl::CreateDeserialized(Context, ID);
3807 case DECL_VAR_TEMPLATE:
3808 D = VarTemplateDecl::CreateDeserialized(Context, ID);
3810 case DECL_VAR_TEMPLATE_SPECIALIZATION:
3811 D = VarTemplateSpecializationDecl::CreateDeserialized(Context, ID);
3813 case DECL_VAR_TEMPLATE_PARTIAL_SPECIALIZATION:
3814 D = VarTemplatePartialSpecializationDecl::CreateDeserialized(Context, ID);
3816 case DECL_CLASS_SCOPE_FUNCTION_SPECIALIZATION:
3817 D = ClassScopeFunctionSpecializationDecl::CreateDeserialized(Context, ID);
3819 case DECL_FUNCTION_TEMPLATE:
3820 D = FunctionTemplateDecl::CreateDeserialized(Context, ID);
3822 case DECL_TEMPLATE_TYPE_PARM:
3823 D = TemplateTypeParmDecl::CreateDeserialized(Context, ID);
3825 case DECL_NON_TYPE_TEMPLATE_PARM:
3826 D = NonTypeTemplateParmDecl::CreateDeserialized(Context, ID);
3828 case DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK:
3829 D = NonTypeTemplateParmDecl::CreateDeserialized(Context, ID,
3832 case DECL_TEMPLATE_TEMPLATE_PARM:
3833 D = TemplateTemplateParmDecl::CreateDeserialized(Context, ID);
3835 case DECL_EXPANDED_TEMPLATE_TEMPLATE_PARM_PACK:
3836 D = TemplateTemplateParmDecl::CreateDeserialized(Context, ID,
3839 case DECL_TYPE_ALIAS_TEMPLATE:
3840 D = TypeAliasTemplateDecl::CreateDeserialized(Context, ID);
3843 D = ConceptDecl::CreateDeserialized(Context, ID);
3845 case DECL_STATIC_ASSERT:
3846 D = StaticAssertDecl::CreateDeserialized(Context, ID);
3848 case DECL_OBJC_METHOD:
3849 D = ObjCMethodDecl::CreateDeserialized(Context, ID);
3851 case DECL_OBJC_INTERFACE:
3852 D = ObjCInterfaceDecl::CreateDeserialized(Context, ID);
3854 case DECL_OBJC_IVAR:
3855 D = ObjCIvarDecl::CreateDeserialized(Context, ID);
3857 case DECL_OBJC_PROTOCOL:
3858 D = ObjCProtocolDecl::CreateDeserialized(Context, ID);
3860 case DECL_OBJC_AT_DEFS_FIELD:
3861 D = ObjCAtDefsFieldDecl::CreateDeserialized(Context, ID);
3863 case DECL_OBJC_CATEGORY:
3864 D = ObjCCategoryDecl::CreateDeserialized(Context, ID);
3866 case DECL_OBJC_CATEGORY_IMPL:
3867 D = ObjCCategoryImplDecl::CreateDeserialized(Context, ID);
3869 case DECL_OBJC_IMPLEMENTATION:
3870 D = ObjCImplementationDecl::CreateDeserialized(Context, ID);
3872 case DECL_OBJC_COMPATIBLE_ALIAS:
3873 D = ObjCCompatibleAliasDecl::CreateDeserialized(Context, ID);
3875 case DECL_OBJC_PROPERTY:
3876 D = ObjCPropertyDecl::CreateDeserialized(Context, ID);
3878 case DECL_OBJC_PROPERTY_IMPL:
3879 D = ObjCPropertyImplDecl::CreateDeserialized(Context, ID);
3882 D = FieldDecl::CreateDeserialized(Context, ID);
3884 case DECL_INDIRECTFIELD:
3885 D = IndirectFieldDecl::CreateDeserialized(Context, ID);
3888 D = VarDecl::CreateDeserialized(Context, ID);
3890 case DECL_IMPLICIT_PARAM:
3891 D = ImplicitParamDecl::CreateDeserialized(Context, ID);
3894 D = ParmVarDecl::CreateDeserialized(Context, ID);
3896 case DECL_DECOMPOSITION:
3897 D = DecompositionDecl::CreateDeserialized(Context, ID, Record.readInt());
3900 D = BindingDecl::CreateDeserialized(Context, ID);
3902 case DECL_FILE_SCOPE_ASM:
3903 D = FileScopeAsmDecl::CreateDeserialized(Context, ID);
3906 D = BlockDecl::CreateDeserialized(Context, ID);
3908 case DECL_MS_PROPERTY:
3909 D = MSPropertyDecl::CreateDeserialized(Context, ID);
3912 D = CapturedDecl::CreateDeserialized(Context, ID, Record.readInt());
3914 case DECL_CXX_BASE_SPECIFIERS:
3915 Error("attempt to read a C++ base-specifier record as a declaration");
3917 case DECL_CXX_CTOR_INITIALIZERS:
3918 Error("attempt to read a C++ ctor initializer record as a declaration");
3921 // Note: last entry of the ImportDecl record is the number of stored source
3923 D = ImportDecl::CreateDeserialized(Context, ID, Record.back());
3925 case DECL_OMP_THREADPRIVATE:
3926 D = OMPThreadPrivateDecl::CreateDeserialized(Context, ID, Record.readInt());
3928 case DECL_OMP_ALLOCATE: {
3929 unsigned NumVars = Record.readInt();
3930 unsigned NumClauses = Record.readInt();
3931 D = OMPAllocateDecl::CreateDeserialized(Context, ID, NumVars, NumClauses);
3934 case DECL_OMP_REQUIRES:
3935 D = OMPRequiresDecl::CreateDeserialized(Context, ID, Record.readInt());
3937 case DECL_OMP_DECLARE_REDUCTION:
3938 D = OMPDeclareReductionDecl::CreateDeserialized(Context, ID);
3940 case DECL_OMP_DECLARE_MAPPER:
3941 D = OMPDeclareMapperDecl::CreateDeserialized(Context, ID, Record.readInt());
3943 case DECL_OMP_CAPTUREDEXPR:
3944 D = OMPCapturedExprDecl::CreateDeserialized(Context, ID);
3946 case DECL_PRAGMA_COMMENT:
3947 D = PragmaCommentDecl::CreateDeserialized(Context, ID, Record.readInt());
3949 case DECL_PRAGMA_DETECT_MISMATCH:
3950 D = PragmaDetectMismatchDecl::CreateDeserialized(Context, ID,
3954 D = EmptyDecl::CreateDeserialized(Context, ID);
3956 case DECL_OBJC_TYPE_PARAM:
3957 D = ObjCTypeParamDecl::CreateDeserialized(Context, ID);
3961 assert(D && "Unknown declaration reading AST file");
3962 LoadedDecl(Index, D);
3963 // Set the DeclContext before doing any deserialization, to make sure internal
3964 // calls to Decl::getASTContext() by Decl's methods will find the
3965 // TranslationUnitDecl without crashing.
3966 D->setDeclContext(Context.getTranslationUnitDecl());
3969 // If this declaration is also a declaration context, get the
3970 // offsets for its tables of lexical and visible declarations.
3971 if (auto *DC = dyn_cast<DeclContext>(D)) {
3972 std::pair<uint64_t, uint64_t> Offsets = Reader.VisitDeclContext(DC);
3973 if (Offsets.first &&
3974 ReadLexicalDeclContextStorage(*Loc.F, DeclsCursor, Offsets.first, DC))
3976 if (Offsets.second &&
3977 ReadVisibleDeclContextStorage(*Loc.F, DeclsCursor, Offsets.second, ID))
3980 assert(Record.getIdx() == Record.size());
3982 // Load any relevant update records.
3983 PendingUpdateRecords.push_back(
3984 PendingUpdateRecord(ID, D, /*JustLoaded=*/true));
3986 // Load the categories after recursive loading is finished.
3987 if (auto *Class = dyn_cast<ObjCInterfaceDecl>(D))
3988 // If we already have a definition when deserializing the ObjCInterfaceDecl,
3989 // we put the Decl in PendingDefinitions so we can pull the categories here.
3990 if (Class->isThisDeclarationADefinition() ||
3991 PendingDefinitions.count(Class))
3992 loadObjCCategories(ID, Class);
3994 // If we have deserialized a declaration that has a definition the
3995 // AST consumer might need to know about, queue it.
3996 // We don't pass it to the consumer immediately because we may be in recursive
3997 // loading, and some declarations may still be initializing.
3998 PotentiallyInterestingDecls.push_back(
3999 InterestingDecl(D, Reader.hasPendingBody()));
4004 void ASTReader::PassInterestingDeclsToConsumer() {
4007 if (PassingDeclsToConsumer)
4010 // Guard variable to avoid recursively redoing the process of passing
4011 // decls to consumer.
4012 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
4015 // Ensure that we've loaded all potentially-interesting declarations
4016 // that need to be eagerly loaded.
4017 for (auto ID : EagerlyDeserializedDecls)
4019 EagerlyDeserializedDecls.clear();
4021 while (!PotentiallyInterestingDecls.empty()) {
4022 InterestingDecl D = PotentiallyInterestingDecls.front();
4023 PotentiallyInterestingDecls.pop_front();
4024 if (isConsumerInterestedIn(getContext(), D.getDecl(), D.hasPendingBody()))
4025 PassInterestingDeclToConsumer(D.getDecl());
4029 void ASTReader::loadDeclUpdateRecords(PendingUpdateRecord &Record) {
4030 // The declaration may have been modified by files later in the chain.
4031 // If this is the case, read the record containing the updates from each file
4032 // and pass it to ASTDeclReader to make the modifications.
4033 serialization::GlobalDeclID ID = Record.ID;
4035 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
4036 DeclUpdateOffsetsMap::iterator UpdI = DeclUpdateOffsets.find(ID);
4038 SmallVector<serialization::DeclID, 8> PendingLazySpecializationIDs;
4040 if (UpdI != DeclUpdateOffsets.end()) {
4041 auto UpdateOffsets = std::move(UpdI->second);
4042 DeclUpdateOffsets.erase(UpdI);
4044 // Check if this decl was interesting to the consumer. If we just loaded
4045 // the declaration, then we know it was interesting and we skip the call
4046 // to isConsumerInterestedIn because it is unsafe to call in the
4047 // current ASTReader state.
4048 bool WasInteresting =
4049 Record.JustLoaded || isConsumerInterestedIn(getContext(), D, false);
4050 for (auto &FileAndOffset : UpdateOffsets) {
4051 ModuleFile *F = FileAndOffset.first;
4052 uint64_t Offset = FileAndOffset.second;
4053 llvm::BitstreamCursor &Cursor = F->DeclsCursor;
4054 SavedStreamPosition SavedPosition(Cursor);
4055 if (llvm::Error JumpFailed = Cursor.JumpToBit(Offset))
4056 // FIXME don't do a fatal error.
4057 llvm::report_fatal_error(
4058 "ASTReader::loadDeclUpdateRecords failed jumping: " +
4059 toString(std::move(JumpFailed)));
4060 Expected<unsigned> MaybeCode = Cursor.ReadCode();
4062 llvm::report_fatal_error(
4063 "ASTReader::loadDeclUpdateRecords failed reading code: " +
4064 toString(MaybeCode.takeError()));
4065 unsigned Code = MaybeCode.get();
4066 ASTRecordReader Record(*this, *F);
4067 if (Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code))
4068 assert(MaybeRecCode.get() == DECL_UPDATES &&
4069 "Expected DECL_UPDATES record!");
4071 llvm::report_fatal_error(
4072 "ASTReader::loadDeclUpdateRecords failed reading rec code: " +
4073 toString(MaybeCode.takeError()));
4075 ASTDeclReader Reader(*this, Record, RecordLocation(F, Offset), ID,
4077 Reader.UpdateDecl(D, PendingLazySpecializationIDs);
4079 // We might have made this declaration interesting. If so, remember that
4080 // we need to hand it off to the consumer.
4081 if (!WasInteresting &&
4082 isConsumerInterestedIn(getContext(), D, Reader.hasPendingBody())) {
4083 PotentiallyInterestingDecls.push_back(
4084 InterestingDecl(D, Reader.hasPendingBody()));
4085 WasInteresting = true;
4089 // Add the lazy specializations to the template.
4090 assert((PendingLazySpecializationIDs.empty() || isa<ClassTemplateDecl>(D) ||
4091 isa<FunctionTemplateDecl>(D) || isa<VarTemplateDecl>(D)) &&
4092 "Must not have pending specializations");
4093 if (auto *CTD = dyn_cast<ClassTemplateDecl>(D))
4094 ASTDeclReader::AddLazySpecializations(CTD, PendingLazySpecializationIDs);
4095 else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
4096 ASTDeclReader::AddLazySpecializations(FTD, PendingLazySpecializationIDs);
4097 else if (auto *VTD = dyn_cast<VarTemplateDecl>(D))
4098 ASTDeclReader::AddLazySpecializations(VTD, PendingLazySpecializationIDs);
4099 PendingLazySpecializationIDs.clear();
4101 // Load the pending visible updates for this decl context, if it has any.
4102 auto I = PendingVisibleUpdates.find(ID);
4103 if (I != PendingVisibleUpdates.end()) {
4104 auto VisibleUpdates = std::move(I->second);
4105 PendingVisibleUpdates.erase(I);
4107 auto *DC = cast<DeclContext>(D)->getPrimaryContext();
4108 for (const auto &Update : VisibleUpdates)
4109 Lookups[DC].Table.add(
4110 Update.Mod, Update.Data,
4111 reader::ASTDeclContextNameLookupTrait(*this, *Update.Mod));
4112 DC->setHasExternalVisibleStorage(true);
4116 void ASTReader::loadPendingDeclChain(Decl *FirstLocal, uint64_t LocalOffset) {
4117 // Attach FirstLocal to the end of the decl chain.
4118 Decl *CanonDecl = FirstLocal->getCanonicalDecl();
4119 if (FirstLocal != CanonDecl) {
4120 Decl *PrevMostRecent = ASTDeclReader::getMostRecentDecl(CanonDecl);
4121 ASTDeclReader::attachPreviousDecl(
4122 *this, FirstLocal, PrevMostRecent ? PrevMostRecent : CanonDecl,
4127 ASTDeclReader::attachLatestDecl(CanonDecl, FirstLocal);
4131 // Load the list of other redeclarations from this module file.
4132 ModuleFile *M = getOwningModuleFile(FirstLocal);
4133 assert(M && "imported decl from no module file");
4135 llvm::BitstreamCursor &Cursor = M->DeclsCursor;
4136 SavedStreamPosition SavedPosition(Cursor);
4137 if (llvm::Error JumpFailed = Cursor.JumpToBit(LocalOffset))
4138 llvm::report_fatal_error(
4139 "ASTReader::loadPendingDeclChain failed jumping: " +
4140 toString(std::move(JumpFailed)));
4143 Expected<unsigned> MaybeCode = Cursor.ReadCode();
4145 llvm::report_fatal_error(
4146 "ASTReader::loadPendingDeclChain failed reading code: " +
4147 toString(MaybeCode.takeError()));
4148 unsigned Code = MaybeCode.get();
4149 if (Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record))
4150 assert(MaybeRecCode.get() == LOCAL_REDECLARATIONS &&
4151 "expected LOCAL_REDECLARATIONS record!");
4153 llvm::report_fatal_error(
4154 "ASTReader::loadPendingDeclChain failed reading rec code: " +
4155 toString(MaybeCode.takeError()));
4157 // FIXME: We have several different dispatches on decl kind here; maybe
4158 // we should instead generate one loop per kind and dispatch up-front?
4159 Decl *MostRecent = FirstLocal;
4160 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
4161 auto *D = GetLocalDecl(*M, Record[N - I - 1]);
4162 ASTDeclReader::attachPreviousDecl(*this, D, MostRecent, CanonDecl);
4165 ASTDeclReader::attachLatestDecl(CanonDecl, MostRecent);
4170 /// Given an ObjC interface, goes through the modules and links to the
4171 /// interface all the categories for it.
4172 class ObjCCategoriesVisitor {
4174 ObjCInterfaceDecl *Interface;
4175 llvm::SmallPtrSetImpl<ObjCCategoryDecl *> &Deserialized;
4176 ObjCCategoryDecl *Tail = nullptr;
4177 llvm::DenseMap<DeclarationName, ObjCCategoryDecl *> NameCategoryMap;
4178 serialization::GlobalDeclID InterfaceID;
4179 unsigned PreviousGeneration;
4181 void add(ObjCCategoryDecl *Cat) {
4182 // Only process each category once.
4183 if (!Deserialized.erase(Cat))
4186 // Check for duplicate categories.
4187 if (Cat->getDeclName()) {
4188 ObjCCategoryDecl *&Existing = NameCategoryMap[Cat->getDeclName()];
4190 Reader.getOwningModuleFile(Existing)
4191 != Reader.getOwningModuleFile(Cat)) {
4192 // FIXME: We should not warn for duplicates in diamond:
4200 // If there are duplicates in ML/MR, there will be warning when
4201 // creating MB *and* when importing MB. We should not warn when
4203 Reader.Diag(Cat->getLocation(), diag::warn_dup_category_def)
4204 << Interface->getDeclName() << Cat->getDeclName();
4205 Reader.Diag(Existing->getLocation(), diag::note_previous_definition);
4206 } else if (!Existing) {
4207 // Record this category.
4212 // Add this category to the end of the chain.
4214 ASTDeclReader::setNextObjCCategory(Tail, Cat);
4216 Interface->setCategoryListRaw(Cat);
4221 ObjCCategoriesVisitor(ASTReader &Reader,
4222 ObjCInterfaceDecl *Interface,
4223 llvm::SmallPtrSetImpl<ObjCCategoryDecl *> &Deserialized,
4224 serialization::GlobalDeclID InterfaceID,
4225 unsigned PreviousGeneration)
4226 : Reader(Reader), Interface(Interface), Deserialized(Deserialized),
4227 InterfaceID(InterfaceID), PreviousGeneration(PreviousGeneration) {
4228 // Populate the name -> category map with the set of known categories.
4229 for (auto *Cat : Interface->known_categories()) {
4230 if (Cat->getDeclName())
4231 NameCategoryMap[Cat->getDeclName()] = Cat;
4233 // Keep track of the tail of the category list.
4238 bool operator()(ModuleFile &M) {
4239 // If we've loaded all of the category information we care about from
4240 // this module file, we're done.
4241 if (M.Generation <= PreviousGeneration)
4244 // Map global ID of the definition down to the local ID used in this
4245 // module file. If there is no such mapping, we'll find nothing here
4246 // (or in any module it imports).
4247 DeclID LocalID = Reader.mapGlobalIDToModuleFileGlobalID(M, InterfaceID);
4251 // Perform a binary search to find the local redeclarations for this
4252 // declaration (if any).
4253 const ObjCCategoriesInfo Compare = { LocalID, 0 };
4254 const ObjCCategoriesInfo *Result
4255 = std::lower_bound(M.ObjCCategoriesMap,
4256 M.ObjCCategoriesMap + M.LocalNumObjCCategoriesInMap,
4258 if (Result == M.ObjCCategoriesMap + M.LocalNumObjCCategoriesInMap ||
4259 Result->DefinitionID != LocalID) {
4260 // We didn't find anything. If the class definition is in this module
4261 // file, then the module files it depends on cannot have any categories,
4262 // so suppress further lookup.
4263 return Reader.isDeclIDFromModule(InterfaceID, M);
4266 // We found something. Dig out all of the categories.
4267 unsigned Offset = Result->Offset;
4268 unsigned N = M.ObjCCategories[Offset];
4269 M.ObjCCategories[Offset++] = 0; // Don't try to deserialize again
4270 for (unsigned I = 0; I != N; ++I)
4271 add(cast_or_null<ObjCCategoryDecl>(
4272 Reader.GetLocalDecl(M, M.ObjCCategories[Offset++])));
4279 void ASTReader::loadObjCCategories(serialization::GlobalDeclID ID,
4280 ObjCInterfaceDecl *D,
4281 unsigned PreviousGeneration) {
4282 ObjCCategoriesVisitor Visitor(*this, D, CategoriesDeserialized, ID,
4283 PreviousGeneration);
4284 ModuleMgr.visit(Visitor);
4287 template<typename DeclT, typename Fn>
4288 static void forAllLaterRedecls(DeclT *D, Fn F) {
4291 // Check whether we've already merged D into its redeclaration chain.
4292 // MostRecent may or may not be nullptr if D has not been merged. If
4293 // not, walk the merged redecl chain and see if it's there.
4294 auto *MostRecent = D->getMostRecentDecl();
4296 for (auto *Redecl = MostRecent; Redecl && !Found;
4297 Redecl = Redecl->getPreviousDecl())
4298 Found = (Redecl == D);
4300 // If this declaration is merged, apply the functor to all later decls.
4302 for (auto *Redecl = MostRecent; Redecl != D;
4303 Redecl = Redecl->getPreviousDecl())
4308 void ASTDeclReader::UpdateDecl(Decl *D,
4309 llvm::SmallVectorImpl<serialization::DeclID> &PendingLazySpecializationIDs) {
4310 while (Record.getIdx() < Record.size()) {
4311 switch ((DeclUpdateKind)Record.readInt()) {
4312 case UPD_CXX_ADDED_IMPLICIT_MEMBER: {
4313 auto *RD = cast<CXXRecordDecl>(D);
4314 // FIXME: If we also have an update record for instantiating the
4315 // definition of D, we need that to happen before we get here.
4316 Decl *MD = Record.readDecl();
4317 assert(MD && "couldn't read decl from update record");
4318 // FIXME: We should call addHiddenDecl instead, to add the member
4319 // to its DeclContext.
4320 RD->addedMember(MD);
4324 case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
4325 // It will be added to the template's lazy specialization set.
4326 PendingLazySpecializationIDs.push_back(ReadDeclID());
4329 case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE: {
4330 auto *Anon = ReadDeclAs<NamespaceDecl>();
4332 // Each module has its own anonymous namespace, which is disjoint from
4333 // any other module's anonymous namespaces, so don't attach the anonymous
4334 // namespace at all.
4335 if (!Record.isModule()) {
4336 if (auto *TU = dyn_cast<TranslationUnitDecl>(D))
4337 TU->setAnonymousNamespace(Anon);
4339 cast<NamespaceDecl>(D)->setAnonymousNamespace(Anon);
4344 case UPD_CXX_ADDED_VAR_DEFINITION: {
4345 auto *VD = cast<VarDecl>(D);
4346 VD->NonParmVarDeclBits.IsInline = Record.readInt();
4347 VD->NonParmVarDeclBits.IsInlineSpecified = Record.readInt();
4348 uint64_t Val = Record.readInt();
4349 if (Val && !VD->getInit()) {
4350 VD->setInit(Record.readExpr());
4351 if (Val > 1) { // IsInitKnownICE = 1, IsInitNotICE = 2, IsInitICE = 3
4352 EvaluatedStmt *Eval = VD->ensureEvaluatedStmt();
4353 Eval->CheckedICE = true;
4354 Eval->IsICE = Val == 3;
4360 case UPD_CXX_POINT_OF_INSTANTIATION: {
4361 SourceLocation POI = Record.readSourceLocation();
4362 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D)) {
4363 VTSD->setPointOfInstantiation(POI);
4364 } else if (auto *VD = dyn_cast<VarDecl>(D)) {
4365 VD->getMemberSpecializationInfo()->setPointOfInstantiation(POI);
4367 auto *FD = cast<FunctionDecl>(D);
4368 if (auto *FTSInfo = FD->TemplateOrSpecialization
4369 .dyn_cast<FunctionTemplateSpecializationInfo *>())
4370 FTSInfo->setPointOfInstantiation(POI);
4372 FD->TemplateOrSpecialization.get<MemberSpecializationInfo *>()
4373 ->setPointOfInstantiation(POI);
4378 case UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT: {
4379 auto *Param = cast<ParmVarDecl>(D);
4381 // We have to read the default argument regardless of whether we use it
4382 // so that hypothetical further update records aren't messed up.
4383 // TODO: Add a function to skip over the next expr record.
4384 auto *DefaultArg = Record.readExpr();
4386 // Only apply the update if the parameter still has an uninstantiated
4387 // default argument.
4388 if (Param->hasUninstantiatedDefaultArg())
4389 Param->setDefaultArg(DefaultArg);
4393 case UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER: {
4394 auto *FD = cast<FieldDecl>(D);
4395 auto *DefaultInit = Record.readExpr();
4397 // Only apply the update if the field still has an uninstantiated
4398 // default member initializer.
4399 if (FD->hasInClassInitializer() && !FD->getInClassInitializer()) {
4401 FD->setInClassInitializer(DefaultInit);
4403 // Instantiation failed. We can get here if we serialized an AST for
4404 // an invalid program.
4405 FD->removeInClassInitializer();
4410 case UPD_CXX_ADDED_FUNCTION_DEFINITION: {
4411 auto *FD = cast<FunctionDecl>(D);
4412 if (Reader.PendingBodies[FD]) {
4413 // FIXME: Maybe check for ODR violations.
4414 // It's safe to stop now because this update record is always last.
4418 if (Record.readInt()) {
4419 // Maintain AST consistency: any later redeclarations of this function
4420 // are inline if this one is. (We might have merged another declaration
4422 forAllLaterRedecls(FD, [](FunctionDecl *FD) {
4423 FD->setImplicitlyInline();
4426 FD->setInnerLocStart(ReadSourceLocation());
4427 ReadFunctionDefinition(FD);
4428 assert(Record.getIdx() == Record.size() && "lazy body must be last");
4432 case UPD_CXX_INSTANTIATED_CLASS_DEFINITION: {
4433 auto *RD = cast<CXXRecordDecl>(D);
4434 auto *OldDD = RD->getCanonicalDecl()->DefinitionData;
4435 bool HadRealDefinition =
4436 OldDD && (OldDD->Definition != RD ||
4437 !Reader.PendingFakeDefinitionData.count(OldDD));
4438 RD->setParamDestroyedInCallee(Record.readInt());
4439 RD->setArgPassingRestrictions(
4440 (RecordDecl::ArgPassingKind)Record.readInt());
4441 ReadCXXRecordDefinition(RD, /*Update*/true);
4443 // Visible update is handled separately.
4444 uint64_t LexicalOffset = ReadLocalOffset();
4445 if (!HadRealDefinition && LexicalOffset) {
4446 Record.readLexicalDeclContextStorage(LexicalOffset, RD);
4447 Reader.PendingFakeDefinitionData.erase(OldDD);
4450 auto TSK = (TemplateSpecializationKind)Record.readInt();
4451 SourceLocation POI = ReadSourceLocation();
4452 if (MemberSpecializationInfo *MSInfo =
4453 RD->getMemberSpecializationInfo()) {
4454 MSInfo->setTemplateSpecializationKind(TSK);
4455 MSInfo->setPointOfInstantiation(POI);
4457 auto *Spec = cast<ClassTemplateSpecializationDecl>(RD);
4458 Spec->setTemplateSpecializationKind(TSK);
4459 Spec->setPointOfInstantiation(POI);
4461 if (Record.readInt()) {
4463 ReadDeclAs<ClassTemplatePartialSpecializationDecl>();
4464 SmallVector<TemplateArgument, 8> TemplArgs;
4465 Record.readTemplateArgumentList(TemplArgs);
4466 auto *TemplArgList = TemplateArgumentList::CreateCopy(
4467 Reader.getContext(), TemplArgs);
4469 // FIXME: If we already have a partial specialization set,
4470 // check that it matches.
4471 if (!Spec->getSpecializedTemplateOrPartial()
4472 .is<ClassTemplatePartialSpecializationDecl *>())
4473 Spec->setInstantiationOf(PartialSpec, TemplArgList);
4477 RD->setTagKind((TagTypeKind)Record.readInt());
4478 RD->setLocation(ReadSourceLocation());
4479 RD->setLocStart(ReadSourceLocation());
4480 RD->setBraceRange(ReadSourceRange());
4482 if (Record.readInt()) {
4484 Record.readAttributes(Attrs);
4485 // If the declaration already has attributes, we assume that some other
4486 // AST file already loaded them.
4488 D->setAttrsImpl(Attrs, Reader.getContext());
4493 case UPD_CXX_RESOLVED_DTOR_DELETE: {
4494 // Set the 'operator delete' directly to avoid emitting another update
4496 auto *Del = ReadDeclAs<FunctionDecl>();
4497 auto *First = cast<CXXDestructorDecl>(D->getCanonicalDecl());
4498 auto *ThisArg = Record.readExpr();
4499 // FIXME: Check consistency if we have an old and new operator delete.
4500 if (!First->OperatorDelete) {
4501 First->OperatorDelete = Del;
4502 First->OperatorDeleteThisArg = ThisArg;
4507 case UPD_CXX_RESOLVED_EXCEPTION_SPEC: {
4508 FunctionProtoType::ExceptionSpecInfo ESI;
4509 SmallVector<QualType, 8> ExceptionStorage;
4510 Record.readExceptionSpec(ExceptionStorage, ESI);
4512 // Update this declaration's exception specification, if needed.
4513 auto *FD = cast<FunctionDecl>(D);
4514 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
4515 // FIXME: If the exception specification is already present, check that it
4517 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
4518 FD->setType(Reader.getContext().getFunctionType(
4519 FPT->getReturnType(), FPT->getParamTypes(),
4520 FPT->getExtProtoInfo().withExceptionSpec(ESI)));
4522 // When we get to the end of deserializing, see if there are other decls
4523 // that we need to propagate this exception specification onto.
4524 Reader.PendingExceptionSpecUpdates.insert(
4525 std::make_pair(FD->getCanonicalDecl(), FD));
4530 case UPD_CXX_DEDUCED_RETURN_TYPE: {
4531 auto *FD = cast<FunctionDecl>(D);
4532 QualType DeducedResultType = Record.readType();
4533 Reader.PendingDeducedTypeUpdates.insert(
4534 {FD->getCanonicalDecl(), DeducedResultType});
4538 case UPD_DECL_MARKED_USED:
4539 // Maintain AST consistency: any later redeclarations are used too.
4540 D->markUsed(Reader.getContext());
4543 case UPD_MANGLING_NUMBER:
4544 Reader.getContext().setManglingNumber(cast<NamedDecl>(D),
4548 case UPD_STATIC_LOCAL_NUMBER:
4549 Reader.getContext().setStaticLocalNumber(cast<VarDecl>(D),
4553 case UPD_DECL_MARKED_OPENMP_THREADPRIVATE:
4554 D->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(Reader.getContext(),
4555 ReadSourceRange()));
4558 case UPD_DECL_MARKED_OPENMP_ALLOCATE: {
4559 auto AllocatorKind =
4560 static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(Record.readInt());
4561 Expr *Allocator = Record.readExpr();
4562 SourceRange SR = ReadSourceRange();
4563 D->addAttr(OMPAllocateDeclAttr::CreateImplicit(
4564 Reader.getContext(), AllocatorKind, Allocator, SR));
4568 case UPD_DECL_EXPORTED: {
4569 unsigned SubmoduleID = readSubmoduleID();
4570 auto *Exported = cast<NamedDecl>(D);
4571 Module *Owner = SubmoduleID ? Reader.getSubmodule(SubmoduleID) : nullptr;
4572 Reader.getContext().mergeDefinitionIntoModule(Exported, Owner);
4573 Reader.PendingMergedDefinitionsToDeduplicate.insert(Exported);
4577 case UPD_DECL_MARKED_OPENMP_DECLARETARGET:
4578 D->addAttr(OMPDeclareTargetDeclAttr::CreateImplicit(
4579 Reader.getContext(),
4580 static_cast<OMPDeclareTargetDeclAttr::MapTypeTy>(Record.readInt()),
4581 ReadSourceRange()));
4584 case UPD_ADDED_ATTR_TO_RECORD:
4586 Record.readAttributes(Attrs);
4587 assert(Attrs.size() == 1);
4588 D->addAttr(Attrs[0]);