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/ASTRecordReader.h"
52 #include "clang/Serialization/ContinuousRangeMap.h"
53 #include "clang/Serialization/ModuleFile.h"
54 #include "llvm/ADT/DenseMap.h"
55 #include "llvm/ADT/FoldingSet.h"
56 #include "llvm/ADT/STLExtras.h"
57 #include "llvm/ADT/SmallPtrSet.h"
58 #include "llvm/ADT/SmallVector.h"
59 #include "llvm/ADT/iterator_range.h"
60 #include "llvm/Bitstream/BitstreamReader.h"
61 #include "llvm/Support/Casting.h"
62 #include "llvm/Support/ErrorHandling.h"
63 #include "llvm/Support/SaveAndRestore.h"
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 *readTypeSourceInfo() {
123 return Record.readTypeSourceInfo();
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 serialization::SubmoduleID readSubmoduleID() {
149 if (Record.getIdx() == Record.size())
152 return Record.getGlobalSubmoduleID(Record.readInt());
155 Module *readModule() {
156 return Record.getSubmodule(readSubmoduleID());
159 void ReadCXXRecordDefinition(CXXRecordDecl *D, bool Update);
160 void ReadCXXDefinitionData(struct CXXRecordDecl::DefinitionData &Data,
161 const CXXRecordDecl *D);
162 void MergeDefinitionData(CXXRecordDecl *D,
163 struct CXXRecordDecl::DefinitionData &&NewDD);
164 void ReadObjCDefinitionData(struct ObjCInterfaceDecl::DefinitionData &Data);
165 void MergeDefinitionData(ObjCInterfaceDecl *D,
166 struct ObjCInterfaceDecl::DefinitionData &&NewDD);
167 void ReadObjCDefinitionData(struct ObjCProtocolDecl::DefinitionData &Data);
168 void MergeDefinitionData(ObjCProtocolDecl *D,
169 struct ObjCProtocolDecl::DefinitionData &&NewDD);
171 static DeclContext *getPrimaryDCForAnonymousDecl(DeclContext *LexicalDC);
173 static NamedDecl *getAnonymousDeclForMerging(ASTReader &Reader,
176 static void setAnonymousDeclForMerging(ASTReader &Reader, DeclContext *DC,
177 unsigned Index, NamedDecl *D);
179 /// Results from loading a RedeclarableDecl.
180 class RedeclarableResult {
182 GlobalDeclID FirstID;
186 RedeclarableResult(Decl *MergeWith, GlobalDeclID FirstID, bool IsKeyDecl)
187 : MergeWith(MergeWith), FirstID(FirstID), IsKeyDecl(IsKeyDecl) {}
189 /// Retrieve the first ID.
190 GlobalDeclID getFirstID() const { return FirstID; }
192 /// Is this declaration a key declaration?
193 bool isKeyDecl() const { return IsKeyDecl; }
195 /// Get a known declaration that this should be merged with, if
197 Decl *getKnownMergeTarget() const { return MergeWith; }
200 /// Class used to capture the result of searching for an existing
201 /// declaration of a specific kind and name, along with the ability
202 /// to update the place where this result was found (the declaration
203 /// chain hanging off an identifier or the DeclContext we searched in)
205 class FindExistingResult {
207 NamedDecl *New = nullptr;
208 NamedDecl *Existing = nullptr;
209 bool AddResult = false;
210 unsigned AnonymousDeclNumber = 0;
211 IdentifierInfo *TypedefNameForLinkage = nullptr;
214 FindExistingResult(ASTReader &Reader) : Reader(Reader) {}
216 FindExistingResult(ASTReader &Reader, NamedDecl *New, NamedDecl *Existing,
217 unsigned AnonymousDeclNumber,
218 IdentifierInfo *TypedefNameForLinkage)
219 : Reader(Reader), New(New), Existing(Existing), AddResult(true),
220 AnonymousDeclNumber(AnonymousDeclNumber),
221 TypedefNameForLinkage(TypedefNameForLinkage) {}
223 FindExistingResult(FindExistingResult &&Other)
224 : Reader(Other.Reader), New(Other.New), Existing(Other.Existing),
225 AddResult(Other.AddResult),
226 AnonymousDeclNumber(Other.AnonymousDeclNumber),
227 TypedefNameForLinkage(Other.TypedefNameForLinkage) {
228 Other.AddResult = false;
231 FindExistingResult &operator=(FindExistingResult &&) = delete;
232 ~FindExistingResult();
234 /// Suppress the addition of this result into the known set of
236 void suppress() { AddResult = false; }
238 operator NamedDecl*() const { return Existing; }
241 operator T*() const { return dyn_cast_or_null<T>(Existing); }
244 static DeclContext *getPrimaryContextForMerging(ASTReader &Reader,
246 FindExistingResult findExisting(NamedDecl *D);
249 ASTDeclReader(ASTReader &Reader, ASTRecordReader &Record,
250 ASTReader::RecordLocation Loc,
251 DeclID thisDeclID, SourceLocation ThisDeclLoc)
252 : Reader(Reader), Record(Record), Loc(Loc), ThisDeclID(thisDeclID),
253 ThisDeclLoc(ThisDeclLoc) {}
255 template <typename T> static
256 void AddLazySpecializations(T *D,
257 SmallVectorImpl<serialization::DeclID>& IDs) {
261 // FIXME: We should avoid this pattern of getting the ASTContext.
262 ASTContext &C = D->getASTContext();
264 auto *&LazySpecializations = D->getCommonPtr()->LazySpecializations;
266 if (auto &Old = LazySpecializations) {
267 IDs.insert(IDs.end(), Old + 1, Old + 1 + Old[0]);
269 IDs.erase(std::unique(IDs.begin(), IDs.end()), IDs.end());
272 auto *Result = new (C) serialization::DeclID[1 + IDs.size()];
273 *Result = IDs.size();
274 std::copy(IDs.begin(), IDs.end(), Result + 1);
276 LazySpecializations = Result;
279 template <typename DeclT>
280 static Decl *getMostRecentDeclImpl(Redeclarable<DeclT> *D);
281 static Decl *getMostRecentDeclImpl(...);
282 static Decl *getMostRecentDecl(Decl *D);
284 template <typename DeclT>
285 static void attachPreviousDeclImpl(ASTReader &Reader,
286 Redeclarable<DeclT> *D, Decl *Previous,
288 static void attachPreviousDeclImpl(ASTReader &Reader, ...);
289 static void attachPreviousDecl(ASTReader &Reader, Decl *D, Decl *Previous,
292 template <typename DeclT>
293 static void attachLatestDeclImpl(Redeclarable<DeclT> *D, Decl *Latest);
294 static void attachLatestDeclImpl(...);
295 static void attachLatestDecl(Decl *D, Decl *latest);
297 template <typename DeclT>
298 static void markIncompleteDeclChainImpl(Redeclarable<DeclT> *D);
299 static void markIncompleteDeclChainImpl(...);
301 /// Determine whether this declaration has a pending body.
302 bool hasPendingBody() const { return HasPendingBody; }
304 void ReadFunctionDefinition(FunctionDecl *FD);
307 void UpdateDecl(Decl *D, SmallVectorImpl<serialization::DeclID> &);
309 static void setNextObjCCategory(ObjCCategoryDecl *Cat,
310 ObjCCategoryDecl *Next) {
311 Cat->NextClassCategory = Next;
314 void VisitDecl(Decl *D);
315 void VisitPragmaCommentDecl(PragmaCommentDecl *D);
316 void VisitPragmaDetectMismatchDecl(PragmaDetectMismatchDecl *D);
317 void VisitTranslationUnitDecl(TranslationUnitDecl *TU);
318 void VisitNamedDecl(NamedDecl *ND);
319 void VisitLabelDecl(LabelDecl *LD);
320 void VisitNamespaceDecl(NamespaceDecl *D);
321 void VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
322 void VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
323 void VisitTypeDecl(TypeDecl *TD);
324 RedeclarableResult VisitTypedefNameDecl(TypedefNameDecl *TD);
325 void VisitTypedefDecl(TypedefDecl *TD);
326 void VisitTypeAliasDecl(TypeAliasDecl *TD);
327 void VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
328 RedeclarableResult VisitTagDecl(TagDecl *TD);
329 void VisitEnumDecl(EnumDecl *ED);
330 RedeclarableResult VisitRecordDeclImpl(RecordDecl *RD);
331 void VisitRecordDecl(RecordDecl *RD) { VisitRecordDeclImpl(RD); }
332 RedeclarableResult VisitCXXRecordDeclImpl(CXXRecordDecl *D);
333 void VisitCXXRecordDecl(CXXRecordDecl *D) { VisitCXXRecordDeclImpl(D); }
334 RedeclarableResult VisitClassTemplateSpecializationDeclImpl(
335 ClassTemplateSpecializationDecl *D);
337 void VisitClassTemplateSpecializationDecl(
338 ClassTemplateSpecializationDecl *D) {
339 VisitClassTemplateSpecializationDeclImpl(D);
342 void VisitClassTemplatePartialSpecializationDecl(
343 ClassTemplatePartialSpecializationDecl *D);
344 void VisitClassScopeFunctionSpecializationDecl(
345 ClassScopeFunctionSpecializationDecl *D);
347 VisitVarTemplateSpecializationDeclImpl(VarTemplateSpecializationDecl *D);
349 void VisitVarTemplateSpecializationDecl(VarTemplateSpecializationDecl *D) {
350 VisitVarTemplateSpecializationDeclImpl(D);
353 void VisitVarTemplatePartialSpecializationDecl(
354 VarTemplatePartialSpecializationDecl *D);
355 void VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
356 void VisitValueDecl(ValueDecl *VD);
357 void VisitEnumConstantDecl(EnumConstantDecl *ECD);
358 void VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
359 void VisitDeclaratorDecl(DeclaratorDecl *DD);
360 void VisitFunctionDecl(FunctionDecl *FD);
361 void VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *GD);
362 void VisitCXXMethodDecl(CXXMethodDecl *D);
363 void VisitCXXConstructorDecl(CXXConstructorDecl *D);
364 void VisitCXXDestructorDecl(CXXDestructorDecl *D);
365 void VisitCXXConversionDecl(CXXConversionDecl *D);
366 void VisitFieldDecl(FieldDecl *FD);
367 void VisitMSPropertyDecl(MSPropertyDecl *FD);
368 void VisitMSGuidDecl(MSGuidDecl *D);
369 void VisitIndirectFieldDecl(IndirectFieldDecl *FD);
370 RedeclarableResult VisitVarDeclImpl(VarDecl *D);
371 void VisitVarDecl(VarDecl *VD) { VisitVarDeclImpl(VD); }
372 void VisitImplicitParamDecl(ImplicitParamDecl *PD);
373 void VisitParmVarDecl(ParmVarDecl *PD);
374 void VisitDecompositionDecl(DecompositionDecl *DD);
375 void VisitBindingDecl(BindingDecl *BD);
376 void VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
377 DeclID VisitTemplateDecl(TemplateDecl *D);
378 void VisitConceptDecl(ConceptDecl *D);
379 void VisitRequiresExprBodyDecl(RequiresExprBodyDecl *D);
380 RedeclarableResult VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D);
381 void VisitClassTemplateDecl(ClassTemplateDecl *D);
382 void VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D);
383 void VisitVarTemplateDecl(VarTemplateDecl *D);
384 void VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
385 void VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
386 void VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D);
387 void VisitUsingDecl(UsingDecl *D);
388 void VisitUsingPackDecl(UsingPackDecl *D);
389 void VisitUsingShadowDecl(UsingShadowDecl *D);
390 void VisitConstructorUsingShadowDecl(ConstructorUsingShadowDecl *D);
391 void VisitLinkageSpecDecl(LinkageSpecDecl *D);
392 void VisitExportDecl(ExportDecl *D);
393 void VisitFileScopeAsmDecl(FileScopeAsmDecl *AD);
394 void VisitImportDecl(ImportDecl *D);
395 void VisitAccessSpecDecl(AccessSpecDecl *D);
396 void VisitFriendDecl(FriendDecl *D);
397 void VisitFriendTemplateDecl(FriendTemplateDecl *D);
398 void VisitStaticAssertDecl(StaticAssertDecl *D);
399 void VisitBlockDecl(BlockDecl *BD);
400 void VisitCapturedDecl(CapturedDecl *CD);
401 void VisitEmptyDecl(EmptyDecl *D);
402 void VisitLifetimeExtendedTemporaryDecl(LifetimeExtendedTemporaryDecl *D);
404 std::pair<uint64_t, uint64_t> VisitDeclContext(DeclContext *DC);
407 RedeclarableResult VisitRedeclarable(Redeclarable<T> *D);
410 void mergeRedeclarable(Redeclarable<T> *D, RedeclarableResult &Redecl,
411 DeclID TemplatePatternID = 0);
414 void mergeRedeclarable(Redeclarable<T> *D, T *Existing,
415 RedeclarableResult &Redecl,
416 DeclID TemplatePatternID = 0);
419 void mergeMergeable(Mergeable<T> *D);
421 void mergeMergeable(LifetimeExtendedTemporaryDecl *D);
423 void mergeTemplatePattern(RedeclarableTemplateDecl *D,
424 RedeclarableTemplateDecl *Existing,
425 DeclID DsID, bool IsKeyDecl);
427 ObjCTypeParamList *ReadObjCTypeParamList();
429 // FIXME: Reorder according to DeclNodes.td?
430 void VisitObjCMethodDecl(ObjCMethodDecl *D);
431 void VisitObjCTypeParamDecl(ObjCTypeParamDecl *D);
432 void VisitObjCContainerDecl(ObjCContainerDecl *D);
433 void VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
434 void VisitObjCIvarDecl(ObjCIvarDecl *D);
435 void VisitObjCProtocolDecl(ObjCProtocolDecl *D);
436 void VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D);
437 void VisitObjCCategoryDecl(ObjCCategoryDecl *D);
438 void VisitObjCImplDecl(ObjCImplDecl *D);
439 void VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
440 void VisitObjCImplementationDecl(ObjCImplementationDecl *D);
441 void VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *D);
442 void VisitObjCPropertyDecl(ObjCPropertyDecl *D);
443 void VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D);
444 void VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D);
445 void VisitOMPAllocateDecl(OMPAllocateDecl *D);
446 void VisitOMPDeclareReductionDecl(OMPDeclareReductionDecl *D);
447 void VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D);
448 void VisitOMPRequiresDecl(OMPRequiresDecl *D);
449 void VisitOMPCapturedExprDecl(OMPCapturedExprDecl *D);
456 /// Iterator over the redeclarations of a declaration that have already
457 /// been merged into the same redeclaration chain.
458 template<typename DeclT>
459 class MergedRedeclIterator {
461 DeclT *Canonical = nullptr;
462 DeclT *Current = nullptr;
465 MergedRedeclIterator() = default;
466 MergedRedeclIterator(DeclT *Start) : Start(Start), Current(Start) {}
468 DeclT *operator*() { return Current; }
470 MergedRedeclIterator &operator++() {
471 if (Current->isFirstDecl()) {
473 Current = Current->getMostRecentDecl();
475 Current = Current->getPreviousDecl();
477 // If we started in the merged portion, we'll reach our start position
478 // eventually. Otherwise, we'll never reach it, but the second declaration
479 // we reached was the canonical declaration, so stop when we see that one
481 if (Current == Start || Current == Canonical)
486 friend bool operator!=(const MergedRedeclIterator &A,
487 const MergedRedeclIterator &B) {
488 return A.Current != B.Current;
494 template <typename DeclT>
495 static llvm::iterator_range<MergedRedeclIterator<DeclT>>
496 merged_redecls(DeclT *D) {
497 return llvm::make_range(MergedRedeclIterator<DeclT>(D),
498 MergedRedeclIterator<DeclT>());
501 uint64_t ASTDeclReader::GetCurrentCursorOffset() {
502 return Loc.F->DeclsCursor.GetCurrentBitNo() + Loc.F->GlobalBitOffset;
505 void ASTDeclReader::ReadFunctionDefinition(FunctionDecl *FD) {
506 if (Record.readInt()) {
507 Reader.DefinitionSource[FD] = Loc.F->Kind == ModuleKind::MK_MainFile;
508 if (Reader.getContext().getLangOpts().BuildingPCHWithObjectFile &&
509 Reader.DeclIsFromPCHWithObjectFile(FD))
510 Reader.DefinitionSource[FD] = true;
512 if (auto *CD = dyn_cast<CXXConstructorDecl>(FD)) {
513 CD->setNumCtorInitializers(Record.readInt());
514 if (CD->getNumCtorInitializers())
515 CD->CtorInitializers = ReadGlobalOffset();
517 // Store the offset of the body so we can lazily load it later.
518 Reader.PendingBodies[FD] = GetCurrentCursorOffset();
519 HasPendingBody = true;
522 void ASTDeclReader::Visit(Decl *D) {
523 DeclVisitor<ASTDeclReader, void>::Visit(D);
525 // At this point we have deserialized and merged the decl and it is safe to
526 // update its canonical decl to signal that the entire entity is used.
527 D->getCanonicalDecl()->Used |= IsDeclMarkedUsed;
528 IsDeclMarkedUsed = false;
530 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
531 if (auto *TInfo = DD->getTypeSourceInfo())
532 Record.readTypeLoc(TInfo->getTypeLoc());
535 if (auto *TD = dyn_cast<TypeDecl>(D)) {
536 // We have a fully initialized TypeDecl. Read its type now.
537 TD->setTypeForDecl(Reader.GetType(DeferredTypeID).getTypePtrOrNull());
539 // If this is a tag declaration with a typedef name for linkage, it's safe
540 // to load that typedef now.
541 if (NamedDeclForTagDecl)
542 cast<TagDecl>(D)->TypedefNameDeclOrQualifier =
543 cast<TypedefNameDecl>(Reader.GetDecl(NamedDeclForTagDecl));
544 } else if (auto *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
545 // if we have a fully initialized TypeDecl, we can safely read its type now.
546 ID->TypeForDecl = Reader.GetType(DeferredTypeID).getTypePtrOrNull();
547 } else if (auto *FD = dyn_cast<FunctionDecl>(D)) {
548 // FunctionDecl's body was written last after all other Stmts/Exprs.
549 // We only read it if FD doesn't already have a body (e.g., from another
551 // FIXME: Can we diagnose ODR violations somehow?
552 if (Record.readInt())
553 ReadFunctionDefinition(FD);
557 void ASTDeclReader::VisitDecl(Decl *D) {
558 if (D->isTemplateParameter() || D->isTemplateParameterPack() ||
559 isa<ParmVarDecl>(D) || isa<ObjCTypeParamDecl>(D)) {
560 // We don't want to deserialize the DeclContext of a template
561 // parameter or of a parameter of a function template immediately. These
562 // entities might be used in the formulation of its DeclContext (for
563 // example, a function parameter can be used in decltype() in trailing
564 // return type of the function). Use the translation unit DeclContext as a
566 GlobalDeclID SemaDCIDForTemplateParmDecl = readDeclID();
567 GlobalDeclID LexicalDCIDForTemplateParmDecl = readDeclID();
568 if (!LexicalDCIDForTemplateParmDecl)
569 LexicalDCIDForTemplateParmDecl = SemaDCIDForTemplateParmDecl;
570 Reader.addPendingDeclContextInfo(D,
571 SemaDCIDForTemplateParmDecl,
572 LexicalDCIDForTemplateParmDecl);
573 D->setDeclContext(Reader.getContext().getTranslationUnitDecl());
575 auto *SemaDC = readDeclAs<DeclContext>();
576 auto *LexicalDC = readDeclAs<DeclContext>();
579 DeclContext *MergedSemaDC = Reader.MergedDeclContexts.lookup(SemaDC);
580 // Avoid calling setLexicalDeclContext() directly because it uses
581 // Decl::getASTContext() internally which is unsafe during derialization.
582 D->setDeclContextsImpl(MergedSemaDC ? MergedSemaDC : SemaDC, LexicalDC,
583 Reader.getContext());
585 D->setLocation(ThisDeclLoc);
586 D->InvalidDecl = Record.readInt();
587 if (Record.readInt()) { // hasAttrs
589 Record.readAttributes(Attrs);
590 // Avoid calling setAttrs() directly because it uses Decl::getASTContext()
591 // internally which is unsafe during derialization.
592 D->setAttrsImpl(Attrs, Reader.getContext());
594 D->setImplicit(Record.readInt());
595 D->Used = Record.readInt();
596 IsDeclMarkedUsed |= D->Used;
597 D->setReferenced(Record.readInt());
598 D->setTopLevelDeclInObjCContainer(Record.readInt());
599 D->setAccess((AccessSpecifier)Record.readInt());
600 D->FromASTFile = true;
601 bool ModulePrivate = Record.readInt();
603 // Determine whether this declaration is part of a (sub)module. If so, it
604 // may not yet be visible.
605 if (unsigned SubmoduleID = readSubmoduleID()) {
606 // Store the owning submodule ID in the declaration.
607 D->setModuleOwnershipKind(
608 ModulePrivate ? Decl::ModuleOwnershipKind::ModulePrivate
609 : Decl::ModuleOwnershipKind::VisibleWhenImported);
610 D->setOwningModuleID(SubmoduleID);
613 // Module-private declarations are never visible, so there is no work to
615 } else if (Reader.getContext().getLangOpts().ModulesLocalVisibility) {
616 // If local visibility is being tracked, this declaration will become
617 // hidden and visible as the owning module does.
618 } else if (Module *Owner = Reader.getSubmodule(SubmoduleID)) {
619 // Mark the declaration as visible when its owning module becomes visible.
620 if (Owner->NameVisibility == Module::AllVisible)
621 D->setVisibleDespiteOwningModule();
623 Reader.HiddenNamesMap[Owner].push_back(D);
625 } else if (ModulePrivate) {
626 D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate);
630 void ASTDeclReader::VisitPragmaCommentDecl(PragmaCommentDecl *D) {
632 D->setLocation(readSourceLocation());
633 D->CommentKind = (PragmaMSCommentKind)Record.readInt();
634 std::string Arg = readString();
635 memcpy(D->getTrailingObjects<char>(), Arg.data(), Arg.size());
636 D->getTrailingObjects<char>()[Arg.size()] = '\0';
639 void ASTDeclReader::VisitPragmaDetectMismatchDecl(PragmaDetectMismatchDecl *D) {
641 D->setLocation(readSourceLocation());
642 std::string Name = readString();
643 memcpy(D->getTrailingObjects<char>(), Name.data(), Name.size());
644 D->getTrailingObjects<char>()[Name.size()] = '\0';
646 D->ValueStart = Name.size() + 1;
647 std::string Value = readString();
648 memcpy(D->getTrailingObjects<char>() + D->ValueStart, Value.data(),
650 D->getTrailingObjects<char>()[D->ValueStart + Value.size()] = '\0';
653 void ASTDeclReader::VisitTranslationUnitDecl(TranslationUnitDecl *TU) {
654 llvm_unreachable("Translation units are not serialized");
657 void ASTDeclReader::VisitNamedDecl(NamedDecl *ND) {
659 ND->setDeclName(Record.readDeclarationName());
660 AnonymousDeclNumber = Record.readInt();
663 void ASTDeclReader::VisitTypeDecl(TypeDecl *TD) {
665 TD->setLocStart(readSourceLocation());
666 // Delay type reading until after we have fully initialized the decl.
667 DeferredTypeID = Record.getGlobalTypeID(Record.readInt());
670 ASTDeclReader::RedeclarableResult
671 ASTDeclReader::VisitTypedefNameDecl(TypedefNameDecl *TD) {
672 RedeclarableResult Redecl = VisitRedeclarable(TD);
674 TypeSourceInfo *TInfo = readTypeSourceInfo();
675 if (Record.readInt()) { // isModed
676 QualType modedT = Record.readType();
677 TD->setModedTypeSourceInfo(TInfo, modedT);
679 TD->setTypeSourceInfo(TInfo);
680 // Read and discard the declaration for which this is a typedef name for
681 // linkage, if it exists. We cannot rely on our type to pull in this decl,
682 // because it might have been merged with a type from another module and
683 // thus might not refer to our version of the declaration.
688 void ASTDeclReader::VisitTypedefDecl(TypedefDecl *TD) {
689 RedeclarableResult Redecl = VisitTypedefNameDecl(TD);
690 mergeRedeclarable(TD, Redecl);
693 void ASTDeclReader::VisitTypeAliasDecl(TypeAliasDecl *TD) {
694 RedeclarableResult Redecl = VisitTypedefNameDecl(TD);
695 if (auto *Template = readDeclAs<TypeAliasTemplateDecl>())
696 // Merged when we merge the template.
697 TD->setDescribedAliasTemplate(Template);
699 mergeRedeclarable(TD, Redecl);
702 ASTDeclReader::RedeclarableResult ASTDeclReader::VisitTagDecl(TagDecl *TD) {
703 RedeclarableResult Redecl = VisitRedeclarable(TD);
706 TD->IdentifierNamespace = Record.readInt();
707 TD->setTagKind((TagDecl::TagKind)Record.readInt());
708 if (!isa<CXXRecordDecl>(TD))
709 TD->setCompleteDefinition(Record.readInt());
710 TD->setEmbeddedInDeclarator(Record.readInt());
711 TD->setFreeStanding(Record.readInt());
712 TD->setCompleteDefinitionRequired(Record.readInt());
713 TD->setBraceRange(readSourceRange());
715 switch (Record.readInt()) {
719 auto *Info = new (Reader.getContext()) TagDecl::ExtInfo();
720 Record.readQualifierInfo(*Info);
721 TD->TypedefNameDeclOrQualifier = Info;
724 case 2: // TypedefNameForAnonDecl
725 NamedDeclForTagDecl = readDeclID();
726 TypedefNameForLinkage = Record.readIdentifier();
729 llvm_unreachable("unexpected tag info kind");
732 if (!isa<CXXRecordDecl>(TD))
733 mergeRedeclarable(TD, Redecl);
737 void ASTDeclReader::VisitEnumDecl(EnumDecl *ED) {
739 if (TypeSourceInfo *TI = readTypeSourceInfo())
740 ED->setIntegerTypeSourceInfo(TI);
742 ED->setIntegerType(Record.readType());
743 ED->setPromotionType(Record.readType());
744 ED->setNumPositiveBits(Record.readInt());
745 ED->setNumNegativeBits(Record.readInt());
746 ED->setScoped(Record.readInt());
747 ED->setScopedUsingClassTag(Record.readInt());
748 ED->setFixed(Record.readInt());
750 ED->setHasODRHash(true);
751 ED->ODRHash = Record.readInt();
753 // If this is a definition subject to the ODR, and we already have a
754 // definition, merge this one into it.
755 if (ED->isCompleteDefinition() &&
756 Reader.getContext().getLangOpts().Modules &&
757 Reader.getContext().getLangOpts().CPlusPlus) {
758 EnumDecl *&OldDef = Reader.EnumDefinitions[ED->getCanonicalDecl()];
760 // This is the first time we've seen an imported definition. Look for a
761 // local definition before deciding that we are the first definition.
762 for (auto *D : merged_redecls(ED->getCanonicalDecl())) {
763 if (!D->isFromASTFile() && D->isCompleteDefinition()) {
770 Reader.MergedDeclContexts.insert(std::make_pair(ED, OldDef));
771 ED->setCompleteDefinition(false);
772 Reader.mergeDefinitionVisibility(OldDef, ED);
773 if (OldDef->getODRHash() != ED->getODRHash())
774 Reader.PendingEnumOdrMergeFailures[OldDef].push_back(ED);
780 if (auto *InstED = readDeclAs<EnumDecl>()) {
781 auto TSK = (TemplateSpecializationKind)Record.readInt();
782 SourceLocation POI = readSourceLocation();
783 ED->setInstantiationOfMemberEnum(Reader.getContext(), InstED, TSK);
784 ED->getMemberSpecializationInfo()->setPointOfInstantiation(POI);
788 ASTDeclReader::RedeclarableResult
789 ASTDeclReader::VisitRecordDeclImpl(RecordDecl *RD) {
790 RedeclarableResult Redecl = VisitTagDecl(RD);
791 RD->setHasFlexibleArrayMember(Record.readInt());
792 RD->setAnonymousStructOrUnion(Record.readInt());
793 RD->setHasObjectMember(Record.readInt());
794 RD->setHasVolatileMember(Record.readInt());
795 RD->setNonTrivialToPrimitiveDefaultInitialize(Record.readInt());
796 RD->setNonTrivialToPrimitiveCopy(Record.readInt());
797 RD->setNonTrivialToPrimitiveDestroy(Record.readInt());
798 RD->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(Record.readInt());
799 RD->setHasNonTrivialToPrimitiveDestructCUnion(Record.readInt());
800 RD->setHasNonTrivialToPrimitiveCopyCUnion(Record.readInt());
801 RD->setParamDestroyedInCallee(Record.readInt());
802 RD->setArgPassingRestrictions((RecordDecl::ArgPassingKind)Record.readInt());
806 void ASTDeclReader::VisitValueDecl(ValueDecl *VD) {
808 // For function declarations, defer reading the type in case the function has
809 // a deduced return type that references an entity declared within the
811 if (isa<FunctionDecl>(VD))
812 DeferredTypeID = Record.getGlobalTypeID(Record.readInt());
814 VD->setType(Record.readType());
817 void ASTDeclReader::VisitEnumConstantDecl(EnumConstantDecl *ECD) {
819 if (Record.readInt())
820 ECD->setInitExpr(Record.readExpr());
821 ECD->setInitVal(Record.readAPSInt());
825 void ASTDeclReader::VisitDeclaratorDecl(DeclaratorDecl *DD) {
827 DD->setInnerLocStart(readSourceLocation());
828 if (Record.readInt()) { // hasExtInfo
829 auto *Info = new (Reader.getContext()) DeclaratorDecl::ExtInfo();
830 Record.readQualifierInfo(*Info);
831 Info->TrailingRequiresClause = Record.readExpr();
834 QualType TSIType = Record.readType();
835 DD->setTypeSourceInfo(
836 TSIType.isNull() ? nullptr
837 : Reader.getContext().CreateTypeSourceInfo(TSIType));
840 void ASTDeclReader::VisitFunctionDecl(FunctionDecl *FD) {
841 RedeclarableResult Redecl = VisitRedeclarable(FD);
842 VisitDeclaratorDecl(FD);
844 // Attach a type to this function. Use the real type if possible, but fall
845 // back to the type as written if it involves a deduced return type.
846 if (FD->getTypeSourceInfo() &&
847 FD->getTypeSourceInfo()->getType()->castAs<FunctionType>()
848 ->getReturnType()->getContainedAutoType()) {
849 // We'll set up the real type in Visit, once we've finished loading the
851 FD->setType(FD->getTypeSourceInfo()->getType());
852 Reader.PendingFunctionTypes.push_back({FD, DeferredTypeID});
854 FD->setType(Reader.GetType(DeferredTypeID));
858 FD->DNLoc = Record.readDeclarationNameLoc(FD->getDeclName());
859 FD->IdentifierNamespace = Record.readInt();
861 // FunctionDecl's body is handled last at ASTDeclReader::Visit,
862 // after everything else is read.
864 FD->setStorageClass(static_cast<StorageClass>(Record.readInt()));
865 FD->setInlineSpecified(Record.readInt());
866 FD->setImplicitlyInline(Record.readInt());
867 FD->setVirtualAsWritten(Record.readInt());
868 FD->setPure(Record.readInt());
869 FD->setHasInheritedPrototype(Record.readInt());
870 FD->setHasWrittenPrototype(Record.readInt());
871 FD->setDeletedAsWritten(Record.readInt());
872 FD->setTrivial(Record.readInt());
873 FD->setTrivialForCall(Record.readInt());
874 FD->setDefaulted(Record.readInt());
875 FD->setExplicitlyDefaulted(Record.readInt());
876 FD->setHasImplicitReturnZero(Record.readInt());
877 FD->setConstexprKind(static_cast<ConstexprSpecKind>(Record.readInt()));
878 FD->setUsesSEHTry(Record.readInt());
879 FD->setHasSkippedBody(Record.readInt());
880 FD->setIsMultiVersion(Record.readInt());
881 FD->setLateTemplateParsed(Record.readInt());
883 FD->setCachedLinkage(static_cast<Linkage>(Record.readInt()));
884 FD->EndRangeLoc = readSourceLocation();
886 FD->ODRHash = Record.readInt();
887 FD->setHasODRHash(true);
888 FD->setUsesFPIntrin(Record.readInt());
890 if (FD->isDefaulted()) {
891 if (unsigned NumLookups = Record.readInt()) {
892 SmallVector<DeclAccessPair, 8> Lookups;
893 for (unsigned I = 0; I != NumLookups; ++I) {
894 NamedDecl *ND = Record.readDeclAs<NamedDecl>();
895 AccessSpecifier AS = (AccessSpecifier)Record.readInt();
896 Lookups.push_back(DeclAccessPair::make(ND, AS));
898 FD->setDefaultedFunctionInfo(FunctionDecl::DefaultedFunctionInfo::Create(
899 Reader.getContext(), Lookups));
903 switch ((FunctionDecl::TemplatedKind)Record.readInt()) {
904 case FunctionDecl::TK_NonTemplate:
905 mergeRedeclarable(FD, Redecl);
907 case FunctionDecl::TK_FunctionTemplate:
908 // Merged when we merge the template.
909 FD->setDescribedFunctionTemplate(readDeclAs<FunctionTemplateDecl>());
911 case FunctionDecl::TK_MemberSpecialization: {
912 auto *InstFD = readDeclAs<FunctionDecl>();
913 auto TSK = (TemplateSpecializationKind)Record.readInt();
914 SourceLocation POI = readSourceLocation();
915 FD->setInstantiationOfMemberFunction(Reader.getContext(), InstFD, TSK);
916 FD->getMemberSpecializationInfo()->setPointOfInstantiation(POI);
917 mergeRedeclarable(FD, Redecl);
920 case FunctionDecl::TK_FunctionTemplateSpecialization: {
921 auto *Template = readDeclAs<FunctionTemplateDecl>();
922 auto TSK = (TemplateSpecializationKind)Record.readInt();
924 // Template arguments.
925 SmallVector<TemplateArgument, 8> TemplArgs;
926 Record.readTemplateArgumentList(TemplArgs, /*Canonicalize*/ true);
928 // Template args as written.
929 SmallVector<TemplateArgumentLoc, 8> TemplArgLocs;
930 SourceLocation LAngleLoc, RAngleLoc;
931 bool HasTemplateArgumentsAsWritten = Record.readInt();
932 if (HasTemplateArgumentsAsWritten) {
933 unsigned NumTemplateArgLocs = Record.readInt();
934 TemplArgLocs.reserve(NumTemplateArgLocs);
935 for (unsigned i = 0; i != NumTemplateArgLocs; ++i)
936 TemplArgLocs.push_back(Record.readTemplateArgumentLoc());
938 LAngleLoc = readSourceLocation();
939 RAngleLoc = readSourceLocation();
942 SourceLocation POI = readSourceLocation();
944 ASTContext &C = Reader.getContext();
945 TemplateArgumentList *TemplArgList
946 = TemplateArgumentList::CreateCopy(C, TemplArgs);
947 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
948 for (unsigned i = 0, e = TemplArgLocs.size(); i != e; ++i)
949 TemplArgsInfo.addArgument(TemplArgLocs[i]);
951 MemberSpecializationInfo *MSInfo = nullptr;
952 if (Record.readInt()) {
953 auto *FD = readDeclAs<FunctionDecl>();
954 auto TSK = (TemplateSpecializationKind)Record.readInt();
955 SourceLocation POI = readSourceLocation();
957 MSInfo = new (C) MemberSpecializationInfo(FD, TSK);
958 MSInfo->setPointOfInstantiation(POI);
961 FunctionTemplateSpecializationInfo *FTInfo =
962 FunctionTemplateSpecializationInfo::Create(
963 C, FD, Template, TSK, TemplArgList,
964 HasTemplateArgumentsAsWritten ? &TemplArgsInfo : nullptr, POI,
966 FD->TemplateOrSpecialization = FTInfo;
968 if (FD->isCanonicalDecl()) { // if canonical add to template's set.
969 // The template that contains the specializations set. It's not safe to
970 // use getCanonicalDecl on Template since it may still be initializing.
971 auto *CanonTemplate = readDeclAs<FunctionTemplateDecl>();
972 // Get the InsertPos by FindNodeOrInsertPos() instead of calling
973 // InsertNode(FTInfo) directly to avoid the getASTContext() call in
974 // FunctionTemplateSpecializationInfo's Profile().
975 // We avoid getASTContext because a decl in the parent hierarchy may
977 llvm::FoldingSetNodeID ID;
978 FunctionTemplateSpecializationInfo::Profile(ID, TemplArgs, C);
979 void *InsertPos = nullptr;
980 FunctionTemplateDecl::Common *CommonPtr = CanonTemplate->getCommonPtr();
981 FunctionTemplateSpecializationInfo *ExistingInfo =
982 CommonPtr->Specializations.FindNodeOrInsertPos(ID, InsertPos);
984 CommonPtr->Specializations.InsertNode(FTInfo, InsertPos);
986 assert(Reader.getContext().getLangOpts().Modules &&
987 "already deserialized this template specialization");
988 mergeRedeclarable(FD, ExistingInfo->getFunction(), Redecl);
993 case FunctionDecl::TK_DependentFunctionTemplateSpecialization: {
995 UnresolvedSet<8> TemplDecls;
996 unsigned NumTemplates = Record.readInt();
997 while (NumTemplates--)
998 TemplDecls.addDecl(readDeclAs<NamedDecl>());
1001 TemplateArgumentListInfo TemplArgs;
1002 unsigned NumArgs = Record.readInt();
1004 TemplArgs.addArgument(Record.readTemplateArgumentLoc());
1005 TemplArgs.setLAngleLoc(readSourceLocation());
1006 TemplArgs.setRAngleLoc(readSourceLocation());
1008 FD->setDependentTemplateSpecialization(Reader.getContext(),
1009 TemplDecls, TemplArgs);
1010 // These are not merged; we don't need to merge redeclarations of dependent
1011 // template friends.
1016 // Read in the parameters.
1017 unsigned NumParams = Record.readInt();
1018 SmallVector<ParmVarDecl *, 16> Params;
1019 Params.reserve(NumParams);
1020 for (unsigned I = 0; I != NumParams; ++I)
1021 Params.push_back(readDeclAs<ParmVarDecl>());
1022 FD->setParams(Reader.getContext(), Params);
1025 void ASTDeclReader::VisitObjCMethodDecl(ObjCMethodDecl *MD) {
1027 if (Record.readInt()) {
1028 // Load the body on-demand. Most clients won't care, because method
1029 // definitions rarely show up in headers.
1030 Reader.PendingBodies[MD] = GetCurrentCursorOffset();
1031 HasPendingBody = true;
1033 MD->setSelfDecl(readDeclAs<ImplicitParamDecl>());
1034 MD->setCmdDecl(readDeclAs<ImplicitParamDecl>());
1035 MD->setInstanceMethod(Record.readInt());
1036 MD->setVariadic(Record.readInt());
1037 MD->setPropertyAccessor(Record.readInt());
1038 MD->setSynthesizedAccessorStub(Record.readInt());
1039 MD->setDefined(Record.readInt());
1040 MD->setOverriding(Record.readInt());
1041 MD->setHasSkippedBody(Record.readInt());
1043 MD->setIsRedeclaration(Record.readInt());
1044 MD->setHasRedeclaration(Record.readInt());
1045 if (MD->hasRedeclaration())
1046 Reader.getContext().setObjCMethodRedeclaration(MD,
1047 readDeclAs<ObjCMethodDecl>());
1049 MD->setDeclImplementation((ObjCMethodDecl::ImplementationControl)Record.readInt());
1050 MD->setObjCDeclQualifier((Decl::ObjCDeclQualifier)Record.readInt());
1051 MD->setRelatedResultType(Record.readInt());
1052 MD->setReturnType(Record.readType());
1053 MD->setReturnTypeSourceInfo(readTypeSourceInfo());
1054 MD->DeclEndLoc = readSourceLocation();
1055 unsigned NumParams = Record.readInt();
1056 SmallVector<ParmVarDecl *, 16> Params;
1057 Params.reserve(NumParams);
1058 for (unsigned I = 0; I != NumParams; ++I)
1059 Params.push_back(readDeclAs<ParmVarDecl>());
1061 MD->setSelLocsKind((SelectorLocationsKind)Record.readInt());
1062 unsigned NumStoredSelLocs = Record.readInt();
1063 SmallVector<SourceLocation, 16> SelLocs;
1064 SelLocs.reserve(NumStoredSelLocs);
1065 for (unsigned i = 0; i != NumStoredSelLocs; ++i)
1066 SelLocs.push_back(readSourceLocation());
1068 MD->setParamsAndSelLocs(Reader.getContext(), Params, SelLocs);
1071 void ASTDeclReader::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
1072 VisitTypedefNameDecl(D);
1074 D->Variance = Record.readInt();
1075 D->Index = Record.readInt();
1076 D->VarianceLoc = readSourceLocation();
1077 D->ColonLoc = readSourceLocation();
1080 void ASTDeclReader::VisitObjCContainerDecl(ObjCContainerDecl *CD) {
1082 CD->setAtStartLoc(readSourceLocation());
1083 CD->setAtEndRange(readSourceRange());
1086 ObjCTypeParamList *ASTDeclReader::ReadObjCTypeParamList() {
1087 unsigned numParams = Record.readInt();
1091 SmallVector<ObjCTypeParamDecl *, 4> typeParams;
1092 typeParams.reserve(numParams);
1093 for (unsigned i = 0; i != numParams; ++i) {
1094 auto *typeParam = readDeclAs<ObjCTypeParamDecl>();
1098 typeParams.push_back(typeParam);
1101 SourceLocation lAngleLoc = readSourceLocation();
1102 SourceLocation rAngleLoc = readSourceLocation();
1104 return ObjCTypeParamList::create(Reader.getContext(), lAngleLoc,
1105 typeParams, rAngleLoc);
1108 void ASTDeclReader::ReadObjCDefinitionData(
1109 struct ObjCInterfaceDecl::DefinitionData &Data) {
1110 // Read the superclass.
1111 Data.SuperClassTInfo = readTypeSourceInfo();
1113 Data.EndLoc = readSourceLocation();
1114 Data.HasDesignatedInitializers = Record.readInt();
1116 // Read the directly referenced protocols and their SourceLocations.
1117 unsigned NumProtocols = Record.readInt();
1118 SmallVector<ObjCProtocolDecl *, 16> Protocols;
1119 Protocols.reserve(NumProtocols);
1120 for (unsigned I = 0; I != NumProtocols; ++I)
1121 Protocols.push_back(readDeclAs<ObjCProtocolDecl>());
1122 SmallVector<SourceLocation, 16> ProtoLocs;
1123 ProtoLocs.reserve(NumProtocols);
1124 for (unsigned I = 0; I != NumProtocols; ++I)
1125 ProtoLocs.push_back(readSourceLocation());
1126 Data.ReferencedProtocols.set(Protocols.data(), NumProtocols, ProtoLocs.data(),
1127 Reader.getContext());
1129 // Read the transitive closure of protocols referenced by this class.
1130 NumProtocols = Record.readInt();
1132 Protocols.reserve(NumProtocols);
1133 for (unsigned I = 0; I != NumProtocols; ++I)
1134 Protocols.push_back(readDeclAs<ObjCProtocolDecl>());
1135 Data.AllReferencedProtocols.set(Protocols.data(), NumProtocols,
1136 Reader.getContext());
1139 void ASTDeclReader::MergeDefinitionData(ObjCInterfaceDecl *D,
1140 struct ObjCInterfaceDecl::DefinitionData &&NewDD) {
1141 // FIXME: odr checking?
1144 void ASTDeclReader::VisitObjCInterfaceDecl(ObjCInterfaceDecl *ID) {
1145 RedeclarableResult Redecl = VisitRedeclarable(ID);
1146 VisitObjCContainerDecl(ID);
1147 DeferredTypeID = Record.getGlobalTypeID(Record.readInt());
1148 mergeRedeclarable(ID, Redecl);
1150 ID->TypeParamList = ReadObjCTypeParamList();
1151 if (Record.readInt()) {
1152 // Read the definition.
1153 ID->allocateDefinitionData();
1155 ReadObjCDefinitionData(ID->data());
1156 ObjCInterfaceDecl *Canon = ID->getCanonicalDecl();
1157 if (Canon->Data.getPointer()) {
1158 // If we already have a definition, keep the definition invariant and
1160 MergeDefinitionData(Canon, std::move(ID->data()));
1161 ID->Data = Canon->Data;
1163 // Set the definition data of the canonical declaration, so other
1164 // redeclarations will see it.
1165 ID->getCanonicalDecl()->Data = ID->Data;
1167 // We will rebuild this list lazily.
1168 ID->setIvarList(nullptr);
1171 // Note that we have deserialized a definition.
1172 Reader.PendingDefinitions.insert(ID);
1174 // Note that we've loaded this Objective-C class.
1175 Reader.ObjCClassesLoaded.push_back(ID);
1177 ID->Data = ID->getCanonicalDecl()->Data;
1181 void ASTDeclReader::VisitObjCIvarDecl(ObjCIvarDecl *IVD) {
1182 VisitFieldDecl(IVD);
1183 IVD->setAccessControl((ObjCIvarDecl::AccessControl)Record.readInt());
1184 // This field will be built lazily.
1185 IVD->setNextIvar(nullptr);
1186 bool synth = Record.readInt();
1187 IVD->setSynthesize(synth);
1190 void ASTDeclReader::ReadObjCDefinitionData(
1191 struct ObjCProtocolDecl::DefinitionData &Data) {
1192 unsigned NumProtoRefs = Record.readInt();
1193 SmallVector<ObjCProtocolDecl *, 16> ProtoRefs;
1194 ProtoRefs.reserve(NumProtoRefs);
1195 for (unsigned I = 0; I != NumProtoRefs; ++I)
1196 ProtoRefs.push_back(readDeclAs<ObjCProtocolDecl>());
1197 SmallVector<SourceLocation, 16> ProtoLocs;
1198 ProtoLocs.reserve(NumProtoRefs);
1199 for (unsigned I = 0; I != NumProtoRefs; ++I)
1200 ProtoLocs.push_back(readSourceLocation());
1201 Data.ReferencedProtocols.set(ProtoRefs.data(), NumProtoRefs,
1202 ProtoLocs.data(), Reader.getContext());
1205 void ASTDeclReader::MergeDefinitionData(ObjCProtocolDecl *D,
1206 struct ObjCProtocolDecl::DefinitionData &&NewDD) {
1207 // FIXME: odr checking?
1210 void ASTDeclReader::VisitObjCProtocolDecl(ObjCProtocolDecl *PD) {
1211 RedeclarableResult Redecl = VisitRedeclarable(PD);
1212 VisitObjCContainerDecl(PD);
1213 mergeRedeclarable(PD, Redecl);
1215 if (Record.readInt()) {
1216 // Read the definition.
1217 PD->allocateDefinitionData();
1219 ReadObjCDefinitionData(PD->data());
1221 ObjCProtocolDecl *Canon = PD->getCanonicalDecl();
1222 if (Canon->Data.getPointer()) {
1223 // If we already have a definition, keep the definition invariant and
1225 MergeDefinitionData(Canon, std::move(PD->data()));
1226 PD->Data = Canon->Data;
1228 // Set the definition data of the canonical declaration, so other
1229 // redeclarations will see it.
1230 PD->getCanonicalDecl()->Data = PD->Data;
1232 // Note that we have deserialized a definition.
1233 Reader.PendingDefinitions.insert(PD);
1235 PD->Data = PD->getCanonicalDecl()->Data;
1239 void ASTDeclReader::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *FD) {
1243 void ASTDeclReader::VisitObjCCategoryDecl(ObjCCategoryDecl *CD) {
1244 VisitObjCContainerDecl(CD);
1245 CD->setCategoryNameLoc(readSourceLocation());
1246 CD->setIvarLBraceLoc(readSourceLocation());
1247 CD->setIvarRBraceLoc(readSourceLocation());
1249 // Note that this category has been deserialized. We do this before
1250 // deserializing the interface declaration, so that it will consider this
1252 Reader.CategoriesDeserialized.insert(CD);
1254 CD->ClassInterface = readDeclAs<ObjCInterfaceDecl>();
1255 CD->TypeParamList = ReadObjCTypeParamList();
1256 unsigned NumProtoRefs = Record.readInt();
1257 SmallVector<ObjCProtocolDecl *, 16> ProtoRefs;
1258 ProtoRefs.reserve(NumProtoRefs);
1259 for (unsigned I = 0; I != NumProtoRefs; ++I)
1260 ProtoRefs.push_back(readDeclAs<ObjCProtocolDecl>());
1261 SmallVector<SourceLocation, 16> ProtoLocs;
1262 ProtoLocs.reserve(NumProtoRefs);
1263 for (unsigned I = 0; I != NumProtoRefs; ++I)
1264 ProtoLocs.push_back(readSourceLocation());
1265 CD->setProtocolList(ProtoRefs.data(), NumProtoRefs, ProtoLocs.data(),
1266 Reader.getContext());
1268 // Protocols in the class extension belong to the class.
1269 if (NumProtoRefs > 0 && CD->ClassInterface && CD->IsClassExtension())
1270 CD->ClassInterface->mergeClassExtensionProtocolList(
1271 (ObjCProtocolDecl *const *)ProtoRefs.data(), NumProtoRefs,
1272 Reader.getContext());
1275 void ASTDeclReader::VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *CAD) {
1276 VisitNamedDecl(CAD);
1277 CAD->setClassInterface(readDeclAs<ObjCInterfaceDecl>());
1280 void ASTDeclReader::VisitObjCPropertyDecl(ObjCPropertyDecl *D) {
1282 D->setAtLoc(readSourceLocation());
1283 D->setLParenLoc(readSourceLocation());
1284 QualType T = Record.readType();
1285 TypeSourceInfo *TSI = readTypeSourceInfo();
1287 D->setPropertyAttributes((ObjCPropertyAttribute::Kind)Record.readInt());
1288 D->setPropertyAttributesAsWritten(
1289 (ObjCPropertyAttribute::Kind)Record.readInt());
1290 D->setPropertyImplementation(
1291 (ObjCPropertyDecl::PropertyControl)Record.readInt());
1292 DeclarationName GetterName = Record.readDeclarationName();
1293 SourceLocation GetterLoc = readSourceLocation();
1294 D->setGetterName(GetterName.getObjCSelector(), GetterLoc);
1295 DeclarationName SetterName = Record.readDeclarationName();
1296 SourceLocation SetterLoc = readSourceLocation();
1297 D->setSetterName(SetterName.getObjCSelector(), SetterLoc);
1298 D->setGetterMethodDecl(readDeclAs<ObjCMethodDecl>());
1299 D->setSetterMethodDecl(readDeclAs<ObjCMethodDecl>());
1300 D->setPropertyIvarDecl(readDeclAs<ObjCIvarDecl>());
1303 void ASTDeclReader::VisitObjCImplDecl(ObjCImplDecl *D) {
1304 VisitObjCContainerDecl(D);
1305 D->setClassInterface(readDeclAs<ObjCInterfaceDecl>());
1308 void ASTDeclReader::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
1309 VisitObjCImplDecl(D);
1310 D->CategoryNameLoc = readSourceLocation();
1313 void ASTDeclReader::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1314 VisitObjCImplDecl(D);
1315 D->setSuperClass(readDeclAs<ObjCInterfaceDecl>());
1316 D->SuperLoc = readSourceLocation();
1317 D->setIvarLBraceLoc(readSourceLocation());
1318 D->setIvarRBraceLoc(readSourceLocation());
1319 D->setHasNonZeroConstructors(Record.readInt());
1320 D->setHasDestructors(Record.readInt());
1321 D->NumIvarInitializers = Record.readInt();
1322 if (D->NumIvarInitializers)
1323 D->IvarInitializers = ReadGlobalOffset();
1326 void ASTDeclReader::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) {
1328 D->setAtLoc(readSourceLocation());
1329 D->setPropertyDecl(readDeclAs<ObjCPropertyDecl>());
1330 D->PropertyIvarDecl = readDeclAs<ObjCIvarDecl>();
1331 D->IvarLoc = readSourceLocation();
1332 D->setGetterMethodDecl(readDeclAs<ObjCMethodDecl>());
1333 D->setSetterMethodDecl(readDeclAs<ObjCMethodDecl>());
1334 D->setGetterCXXConstructor(Record.readExpr());
1335 D->setSetterCXXAssignment(Record.readExpr());
1338 void ASTDeclReader::VisitFieldDecl(FieldDecl *FD) {
1339 VisitDeclaratorDecl(FD);
1340 FD->Mutable = Record.readInt();
1342 if (auto ISK = static_cast<FieldDecl::InitStorageKind>(Record.readInt())) {
1343 FD->InitStorage.setInt(ISK);
1344 FD->InitStorage.setPointer(ISK == FieldDecl::ISK_CapturedVLAType
1345 ? Record.readType().getAsOpaquePtr()
1346 : Record.readExpr());
1349 if (auto *BW = Record.readExpr())
1350 FD->setBitWidth(BW);
1352 if (!FD->getDeclName()) {
1353 if (auto *Tmpl = readDeclAs<FieldDecl>())
1354 Reader.getContext().setInstantiatedFromUnnamedFieldDecl(FD, Tmpl);
1359 void ASTDeclReader::VisitMSPropertyDecl(MSPropertyDecl *PD) {
1360 VisitDeclaratorDecl(PD);
1361 PD->GetterId = Record.readIdentifier();
1362 PD->SetterId = Record.readIdentifier();
1365 void ASTDeclReader::VisitMSGuidDecl(MSGuidDecl *D) {
1367 D->PartVal.Part1 = Record.readInt();
1368 D->PartVal.Part2 = Record.readInt();
1369 D->PartVal.Part3 = Record.readInt();
1370 for (auto &C : D->PartVal.Part4And5)
1371 C = Record.readInt();
1373 // Add this GUID to the AST context's lookup structure, and merge if needed.
1374 if (MSGuidDecl *Existing = Reader.getContext().MSGuidDecls.GetOrInsertNode(D))
1375 Reader.getContext().setPrimaryMergedDecl(D, Existing->getCanonicalDecl());
1378 void ASTDeclReader::VisitIndirectFieldDecl(IndirectFieldDecl *FD) {
1381 FD->ChainingSize = Record.readInt();
1382 assert(FD->ChainingSize >= 2 && "Anonymous chaining must be >= 2");
1383 FD->Chaining = new (Reader.getContext())NamedDecl*[FD->ChainingSize];
1385 for (unsigned I = 0; I != FD->ChainingSize; ++I)
1386 FD->Chaining[I] = readDeclAs<NamedDecl>();
1391 ASTDeclReader::RedeclarableResult ASTDeclReader::VisitVarDeclImpl(VarDecl *VD) {
1392 RedeclarableResult Redecl = VisitRedeclarable(VD);
1393 VisitDeclaratorDecl(VD);
1395 VD->VarDeclBits.SClass = (StorageClass)Record.readInt();
1396 VD->VarDeclBits.TSCSpec = Record.readInt();
1397 VD->VarDeclBits.InitStyle = Record.readInt();
1398 VD->VarDeclBits.ARCPseudoStrong = Record.readInt();
1399 if (!isa<ParmVarDecl>(VD)) {
1400 VD->NonParmVarDeclBits.IsThisDeclarationADemotedDefinition =
1402 VD->NonParmVarDeclBits.ExceptionVar = Record.readInt();
1403 VD->NonParmVarDeclBits.NRVOVariable = Record.readInt();
1404 VD->NonParmVarDeclBits.CXXForRangeDecl = Record.readInt();
1405 VD->NonParmVarDeclBits.ObjCForDecl = Record.readInt();
1406 VD->NonParmVarDeclBits.IsInline = Record.readInt();
1407 VD->NonParmVarDeclBits.IsInlineSpecified = Record.readInt();
1408 VD->NonParmVarDeclBits.IsConstexpr = Record.readInt();
1409 VD->NonParmVarDeclBits.IsInitCapture = Record.readInt();
1410 VD->NonParmVarDeclBits.PreviousDeclInSameBlockScope = Record.readInt();
1411 VD->NonParmVarDeclBits.ImplicitParamKind = Record.readInt();
1412 VD->NonParmVarDeclBits.EscapingByref = Record.readInt();
1414 auto VarLinkage = Linkage(Record.readInt());
1415 VD->setCachedLinkage(VarLinkage);
1417 // Reconstruct the one piece of the IdentifierNamespace that we need.
1418 if (VD->getStorageClass() == SC_Extern && VarLinkage != NoLinkage &&
1419 VD->getLexicalDeclContext()->isFunctionOrMethod())
1420 VD->setLocalExternDecl();
1422 if (uint64_t Val = Record.readInt()) {
1423 VD->setInit(Record.readExpr());
1425 EvaluatedStmt *Eval = VD->ensureEvaluatedStmt();
1426 Eval->CheckedICE = true;
1427 Eval->IsICE = (Val & 1) != 0;
1428 Eval->HasConstantDestruction = (Val & 4) != 0;
1432 if (VD->hasAttr<BlocksAttr>() && VD->getType()->getAsCXXRecordDecl()) {
1433 Expr *CopyExpr = Record.readExpr();
1435 Reader.getContext().setBlockVarCopyInit(VD, CopyExpr, Record.readInt());
1438 if (VD->getStorageDuration() == SD_Static && Record.readInt()) {
1439 Reader.DefinitionSource[VD] = Loc.F->Kind == ModuleKind::MK_MainFile;
1440 if (Reader.getContext().getLangOpts().BuildingPCHWithObjectFile &&
1441 Reader.DeclIsFromPCHWithObjectFile(VD))
1442 Reader.DefinitionSource[VD] = true;
1446 VarNotTemplate = 0, VarTemplate, StaticDataMemberSpecialization
1448 switch ((VarKind)Record.readInt()) {
1449 case VarNotTemplate:
1450 // Only true variables (not parameters or implicit parameters) can be
1451 // merged; the other kinds are not really redeclarable at all.
1452 if (!isa<ParmVarDecl>(VD) && !isa<ImplicitParamDecl>(VD) &&
1453 !isa<VarTemplateSpecializationDecl>(VD))
1454 mergeRedeclarable(VD, Redecl);
1457 // Merged when we merge the template.
1458 VD->setDescribedVarTemplate(readDeclAs<VarTemplateDecl>());
1460 case StaticDataMemberSpecialization: { // HasMemberSpecializationInfo.
1461 auto *Tmpl = readDeclAs<VarDecl>();
1462 auto TSK = (TemplateSpecializationKind)Record.readInt();
1463 SourceLocation POI = readSourceLocation();
1464 Reader.getContext().setInstantiatedFromStaticDataMember(VD, Tmpl, TSK,POI);
1465 mergeRedeclarable(VD, Redecl);
1473 void ASTDeclReader::VisitImplicitParamDecl(ImplicitParamDecl *PD) {
1477 void ASTDeclReader::VisitParmVarDecl(ParmVarDecl *PD) {
1479 unsigned isObjCMethodParam = Record.readInt();
1480 unsigned scopeDepth = Record.readInt();
1481 unsigned scopeIndex = Record.readInt();
1482 unsigned declQualifier = Record.readInt();
1483 if (isObjCMethodParam) {
1484 assert(scopeDepth == 0);
1485 PD->setObjCMethodScopeInfo(scopeIndex);
1486 PD->ParmVarDeclBits.ScopeDepthOrObjCQuals = declQualifier;
1488 PD->setScopeInfo(scopeDepth, scopeIndex);
1490 PD->ParmVarDeclBits.IsKNRPromoted = Record.readInt();
1491 PD->ParmVarDeclBits.HasInheritedDefaultArg = Record.readInt();
1492 if (Record.readInt()) // hasUninstantiatedDefaultArg.
1493 PD->setUninstantiatedDefaultArg(Record.readExpr());
1495 // FIXME: If this is a redeclaration of a function from another module, handle
1496 // inheritance of default arguments.
1499 void ASTDeclReader::VisitDecompositionDecl(DecompositionDecl *DD) {
1501 auto **BDs = DD->getTrailingObjects<BindingDecl *>();
1502 for (unsigned I = 0; I != DD->NumBindings; ++I) {
1503 BDs[I] = readDeclAs<BindingDecl>();
1504 BDs[I]->setDecomposedDecl(DD);
1508 void ASTDeclReader::VisitBindingDecl(BindingDecl *BD) {
1510 BD->Binding = Record.readExpr();
1513 void ASTDeclReader::VisitFileScopeAsmDecl(FileScopeAsmDecl *AD) {
1515 AD->setAsmString(cast<StringLiteral>(Record.readExpr()));
1516 AD->setRParenLoc(readSourceLocation());
1519 void ASTDeclReader::VisitBlockDecl(BlockDecl *BD) {
1521 BD->setBody(cast_or_null<CompoundStmt>(Record.readStmt()));
1522 BD->setSignatureAsWritten(readTypeSourceInfo());
1523 unsigned NumParams = Record.readInt();
1524 SmallVector<ParmVarDecl *, 16> Params;
1525 Params.reserve(NumParams);
1526 for (unsigned I = 0; I != NumParams; ++I)
1527 Params.push_back(readDeclAs<ParmVarDecl>());
1528 BD->setParams(Params);
1530 BD->setIsVariadic(Record.readInt());
1531 BD->setBlockMissingReturnType(Record.readInt());
1532 BD->setIsConversionFromLambda(Record.readInt());
1533 BD->setDoesNotEscape(Record.readInt());
1534 BD->setCanAvoidCopyToHeap(Record.readInt());
1536 bool capturesCXXThis = Record.readInt();
1537 unsigned numCaptures = Record.readInt();
1538 SmallVector<BlockDecl::Capture, 16> captures;
1539 captures.reserve(numCaptures);
1540 for (unsigned i = 0; i != numCaptures; ++i) {
1541 auto *decl = readDeclAs<VarDecl>();
1542 unsigned flags = Record.readInt();
1543 bool byRef = (flags & 1);
1544 bool nested = (flags & 2);
1545 Expr *copyExpr = ((flags & 4) ? Record.readExpr() : nullptr);
1547 captures.push_back(BlockDecl::Capture(decl, byRef, nested, copyExpr));
1549 BD->setCaptures(Reader.getContext(), captures, capturesCXXThis);
1552 void ASTDeclReader::VisitCapturedDecl(CapturedDecl *CD) {
1554 unsigned ContextParamPos = Record.readInt();
1555 CD->setNothrow(Record.readInt() != 0);
1556 // Body is set by VisitCapturedStmt.
1557 for (unsigned I = 0; I < CD->NumParams; ++I) {
1558 if (I != ContextParamPos)
1559 CD->setParam(I, readDeclAs<ImplicitParamDecl>());
1561 CD->setContextParam(I, readDeclAs<ImplicitParamDecl>());
1565 void ASTDeclReader::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1567 D->setLanguage((LinkageSpecDecl::LanguageIDs)Record.readInt());
1568 D->setExternLoc(readSourceLocation());
1569 D->setRBraceLoc(readSourceLocation());
1572 void ASTDeclReader::VisitExportDecl(ExportDecl *D) {
1574 D->RBraceLoc = readSourceLocation();
1577 void ASTDeclReader::VisitLabelDecl(LabelDecl *D) {
1579 D->setLocStart(readSourceLocation());
1582 void ASTDeclReader::VisitNamespaceDecl(NamespaceDecl *D) {
1583 RedeclarableResult Redecl = VisitRedeclarable(D);
1585 D->setInline(Record.readInt());
1586 D->LocStart = readSourceLocation();
1587 D->RBraceLoc = readSourceLocation();
1589 // Defer loading the anonymous namespace until we've finished merging
1590 // this namespace; loading it might load a later declaration of the
1591 // same namespace, and we have an invariant that older declarations
1592 // get merged before newer ones try to merge.
1593 GlobalDeclID AnonNamespace = 0;
1594 if (Redecl.getFirstID() == ThisDeclID) {
1595 AnonNamespace = readDeclID();
1597 // Link this namespace back to the first declaration, which has already
1598 // been deserialized.
1599 D->AnonOrFirstNamespaceAndInline.setPointer(D->getFirstDecl());
1602 mergeRedeclarable(D, Redecl);
1604 if (AnonNamespace) {
1605 // Each module has its own anonymous namespace, which is disjoint from
1606 // any other module's anonymous namespaces, so don't attach the anonymous
1607 // namespace at all.
1608 auto *Anon = cast<NamespaceDecl>(Reader.GetDecl(AnonNamespace));
1609 if (!Record.isModule())
1610 D->setAnonymousNamespace(Anon);
1614 void ASTDeclReader::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1615 RedeclarableResult Redecl = VisitRedeclarable(D);
1617 D->NamespaceLoc = readSourceLocation();
1618 D->IdentLoc = readSourceLocation();
1619 D->QualifierLoc = Record.readNestedNameSpecifierLoc();
1620 D->Namespace = readDeclAs<NamedDecl>();
1621 mergeRedeclarable(D, Redecl);
1624 void ASTDeclReader::VisitUsingDecl(UsingDecl *D) {
1626 D->setUsingLoc(readSourceLocation());
1627 D->QualifierLoc = Record.readNestedNameSpecifierLoc();
1628 D->DNLoc = Record.readDeclarationNameLoc(D->getDeclName());
1629 D->FirstUsingShadow.setPointer(readDeclAs<UsingShadowDecl>());
1630 D->setTypename(Record.readInt());
1631 if (auto *Pattern = readDeclAs<NamedDecl>())
1632 Reader.getContext().setInstantiatedFromUsingDecl(D, Pattern);
1636 void ASTDeclReader::VisitUsingPackDecl(UsingPackDecl *D) {
1638 D->InstantiatedFrom = readDeclAs<NamedDecl>();
1639 auto **Expansions = D->getTrailingObjects<NamedDecl *>();
1640 for (unsigned I = 0; I != D->NumExpansions; ++I)
1641 Expansions[I] = readDeclAs<NamedDecl>();
1645 void ASTDeclReader::VisitUsingShadowDecl(UsingShadowDecl *D) {
1646 RedeclarableResult Redecl = VisitRedeclarable(D);
1648 D->Underlying = readDeclAs<NamedDecl>();
1649 D->IdentifierNamespace = Record.readInt();
1650 D->UsingOrNextShadow = readDeclAs<NamedDecl>();
1651 auto *Pattern = readDeclAs<UsingShadowDecl>();
1653 Reader.getContext().setInstantiatedFromUsingShadowDecl(D, Pattern);
1654 mergeRedeclarable(D, Redecl);
1657 void ASTDeclReader::VisitConstructorUsingShadowDecl(
1658 ConstructorUsingShadowDecl *D) {
1659 VisitUsingShadowDecl(D);
1660 D->NominatedBaseClassShadowDecl = readDeclAs<ConstructorUsingShadowDecl>();
1661 D->ConstructedBaseClassShadowDecl = readDeclAs<ConstructorUsingShadowDecl>();
1662 D->IsVirtual = Record.readInt();
1665 void ASTDeclReader::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1667 D->UsingLoc = readSourceLocation();
1668 D->NamespaceLoc = readSourceLocation();
1669 D->QualifierLoc = Record.readNestedNameSpecifierLoc();
1670 D->NominatedNamespace = readDeclAs<NamedDecl>();
1671 D->CommonAncestor = readDeclAs<DeclContext>();
1674 void ASTDeclReader::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1676 D->setUsingLoc(readSourceLocation());
1677 D->QualifierLoc = Record.readNestedNameSpecifierLoc();
1678 D->DNLoc = Record.readDeclarationNameLoc(D->getDeclName());
1679 D->EllipsisLoc = readSourceLocation();
1683 void ASTDeclReader::VisitUnresolvedUsingTypenameDecl(
1684 UnresolvedUsingTypenameDecl *D) {
1686 D->TypenameLocation = readSourceLocation();
1687 D->QualifierLoc = Record.readNestedNameSpecifierLoc();
1688 D->EllipsisLoc = readSourceLocation();
1692 void ASTDeclReader::ReadCXXDefinitionData(
1693 struct CXXRecordDecl::DefinitionData &Data, const CXXRecordDecl *D) {
1694 #define FIELD(Name, Width, Merge) \
1695 Data.Name = Record.readInt();
1696 #include "clang/AST/CXXRecordDeclDefinitionBits.def"
1698 // Note: the caller has deserialized the IsLambda bit already.
1699 Data.ODRHash = Record.readInt();
1700 Data.HasODRHash = true;
1702 if (Record.readInt()) {
1703 Reader.DefinitionSource[D] = Loc.F->Kind == ModuleKind::MK_MainFile;
1704 if (Reader.getContext().getLangOpts().BuildingPCHWithObjectFile &&
1705 Reader.DeclIsFromPCHWithObjectFile(D))
1706 Reader.DefinitionSource[D] = true;
1709 Data.NumBases = Record.readInt();
1711 Data.Bases = ReadGlobalOffset();
1712 Data.NumVBases = Record.readInt();
1714 Data.VBases = ReadGlobalOffset();
1716 Record.readUnresolvedSet(Data.Conversions);
1717 Data.ComputedVisibleConversions = Record.readInt();
1718 if (Data.ComputedVisibleConversions)
1719 Record.readUnresolvedSet(Data.VisibleConversions);
1720 assert(Data.Definition && "Data.Definition should be already set!");
1721 Data.FirstFriend = readDeclID();
1723 if (Data.IsLambda) {
1724 using Capture = LambdaCapture;
1726 auto &Lambda = static_cast<CXXRecordDecl::LambdaDefinitionData &>(Data);
1727 Lambda.Dependent = Record.readInt();
1728 Lambda.IsGenericLambda = Record.readInt();
1729 Lambda.CaptureDefault = Record.readInt();
1730 Lambda.NumCaptures = Record.readInt();
1731 Lambda.NumExplicitCaptures = Record.readInt();
1732 Lambda.HasKnownInternalLinkage = Record.readInt();
1733 Lambda.ManglingNumber = Record.readInt();
1734 Lambda.ContextDecl = readDeclID();
1735 Lambda.Captures = (Capture *)Reader.getContext().Allocate(
1736 sizeof(Capture) * Lambda.NumCaptures);
1737 Capture *ToCapture = Lambda.Captures;
1738 Lambda.MethodTyInfo = readTypeSourceInfo();
1739 for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) {
1740 SourceLocation Loc = readSourceLocation();
1741 bool IsImplicit = Record.readInt();
1742 auto Kind = static_cast<LambdaCaptureKind>(Record.readInt());
1747 *ToCapture++ = Capture(Loc, IsImplicit, Kind, nullptr,SourceLocation());
1751 auto *Var = readDeclAs<VarDecl>();
1752 SourceLocation EllipsisLoc = readSourceLocation();
1753 *ToCapture++ = Capture(Loc, IsImplicit, Kind, Var, EllipsisLoc);
1760 void ASTDeclReader::MergeDefinitionData(
1761 CXXRecordDecl *D, struct CXXRecordDecl::DefinitionData &&MergeDD) {
1762 assert(D->DefinitionData &&
1763 "merging class definition into non-definition");
1764 auto &DD = *D->DefinitionData;
1766 if (DD.Definition != MergeDD.Definition) {
1767 // Track that we merged the definitions.
1768 Reader.MergedDeclContexts.insert(std::make_pair(MergeDD.Definition,
1770 Reader.PendingDefinitions.erase(MergeDD.Definition);
1771 MergeDD.Definition->setCompleteDefinition(false);
1772 Reader.mergeDefinitionVisibility(DD.Definition, MergeDD.Definition);
1773 assert(Reader.Lookups.find(MergeDD.Definition) == Reader.Lookups.end() &&
1774 "already loaded pending lookups for merged definition");
1777 auto PFDI = Reader.PendingFakeDefinitionData.find(&DD);
1778 if (PFDI != Reader.PendingFakeDefinitionData.end() &&
1779 PFDI->second == ASTReader::PendingFakeDefinitionKind::Fake) {
1780 // We faked up this definition data because we found a class for which we'd
1781 // not yet loaded the definition. Replace it with the real thing now.
1782 assert(!DD.IsLambda && !MergeDD.IsLambda && "faked up lambda definition?");
1783 PFDI->second = ASTReader::PendingFakeDefinitionKind::FakeLoaded;
1785 // Don't change which declaration is the definition; that is required
1786 // to be invariant once we select it.
1787 auto *Def = DD.Definition;
1788 DD = std::move(MergeDD);
1789 DD.Definition = Def;
1793 bool DetectedOdrViolation = false;
1795 #define FIELD(Name, Width, Merge) Merge(Name)
1796 #define MERGE_OR(Field) DD.Field |= MergeDD.Field;
1797 #define NO_MERGE(Field) \
1798 DetectedOdrViolation |= DD.Field != MergeDD.Field; \
1800 #include "clang/AST/CXXRecordDeclDefinitionBits.def"
1805 if (DD.NumBases != MergeDD.NumBases || DD.NumVBases != MergeDD.NumVBases)
1806 DetectedOdrViolation = true;
1807 // FIXME: Issue a diagnostic if the base classes don't match when we come
1808 // to lazily load them.
1810 // FIXME: Issue a diagnostic if the list of conversion functions doesn't
1811 // match when we come to lazily load them.
1812 if (MergeDD.ComputedVisibleConversions && !DD.ComputedVisibleConversions) {
1813 DD.VisibleConversions = std::move(MergeDD.VisibleConversions);
1814 DD.ComputedVisibleConversions = true;
1817 // FIXME: Issue a diagnostic if FirstFriend doesn't match when we come to
1821 // FIXME: ODR-checking for merging lambdas (this happens, for instance,
1822 // when they occur within the body of a function template specialization).
1825 if (D->getODRHash() != MergeDD.ODRHash) {
1826 DetectedOdrViolation = true;
1829 if (DetectedOdrViolation)
1830 Reader.PendingOdrMergeFailures[DD.Definition].push_back(
1831 {MergeDD.Definition, &MergeDD});
1834 void ASTDeclReader::ReadCXXRecordDefinition(CXXRecordDecl *D, bool Update) {
1835 struct CXXRecordDecl::DefinitionData *DD;
1836 ASTContext &C = Reader.getContext();
1838 // Determine whether this is a lambda closure type, so that we can
1839 // allocate the appropriate DefinitionData structure.
1840 bool IsLambda = Record.readInt();
1842 DD = new (C) CXXRecordDecl::LambdaDefinitionData(D, nullptr, false, false,
1845 DD = new (C) struct CXXRecordDecl::DefinitionData(D);
1847 CXXRecordDecl *Canon = D->getCanonicalDecl();
1848 // Set decl definition data before reading it, so that during deserialization
1849 // when we read CXXRecordDecl, it already has definition data and we don't
1851 if (!Canon->DefinitionData)
1852 Canon->DefinitionData = DD;
1853 D->DefinitionData = Canon->DefinitionData;
1854 ReadCXXDefinitionData(*DD, D);
1856 // We might already have a different definition for this record. This can
1857 // happen either because we're reading an update record, or because we've
1858 // already done some merging. Either way, just merge into it.
1859 if (Canon->DefinitionData != DD) {
1860 MergeDefinitionData(Canon, std::move(*DD));
1864 // Mark this declaration as being a definition.
1865 D->setCompleteDefinition(true);
1867 // If this is not the first declaration or is an update record, we can have
1868 // other redeclarations already. Make a note that we need to propagate the
1869 // DefinitionData pointer onto them.
1870 if (Update || Canon != D)
1871 Reader.PendingDefinitions.insert(D);
1874 ASTDeclReader::RedeclarableResult
1875 ASTDeclReader::VisitCXXRecordDeclImpl(CXXRecordDecl *D) {
1876 RedeclarableResult Redecl = VisitRecordDeclImpl(D);
1878 ASTContext &C = Reader.getContext();
1881 CXXRecNotTemplate = 0, CXXRecTemplate, CXXRecMemberSpecialization
1883 switch ((CXXRecKind)Record.readInt()) {
1884 case CXXRecNotTemplate:
1885 // Merged when we merge the folding set entry in the primary template.
1886 if (!isa<ClassTemplateSpecializationDecl>(D))
1887 mergeRedeclarable(D, Redecl);
1889 case CXXRecTemplate: {
1890 // Merged when we merge the template.
1891 auto *Template = readDeclAs<ClassTemplateDecl>();
1892 D->TemplateOrInstantiation = Template;
1893 if (!Template->getTemplatedDecl()) {
1894 // We've not actually loaded the ClassTemplateDecl yet, because we're
1895 // currently being loaded as its pattern. Rely on it to set up our
1896 // TypeForDecl (see VisitClassTemplateDecl).
1898 // Beware: we do not yet know our canonical declaration, and may still
1899 // get merged once the surrounding class template has got off the ground.
1904 case CXXRecMemberSpecialization: {
1905 auto *RD = readDeclAs<CXXRecordDecl>();
1906 auto TSK = (TemplateSpecializationKind)Record.readInt();
1907 SourceLocation POI = readSourceLocation();
1908 MemberSpecializationInfo *MSI = new (C) MemberSpecializationInfo(RD, TSK);
1909 MSI->setPointOfInstantiation(POI);
1910 D->TemplateOrInstantiation = MSI;
1911 mergeRedeclarable(D, Redecl);
1916 bool WasDefinition = Record.readInt();
1918 ReadCXXRecordDefinition(D, /*Update*/false);
1920 // Propagate DefinitionData pointer from the canonical declaration.
1921 D->DefinitionData = D->getCanonicalDecl()->DefinitionData;
1923 // Lazily load the key function to avoid deserializing every method so we can
1925 if (WasDefinition) {
1926 DeclID KeyFn = readDeclID();
1927 if (KeyFn && D->isCompleteDefinition())
1928 // FIXME: This is wrong for the ARM ABI, where some other module may have
1929 // made this function no longer be a key function. We need an update
1930 // record or similar for that case.
1931 C.KeyFunctions[D] = KeyFn;
1937 void ASTDeclReader::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) {
1938 D->setExplicitSpecifier(Record.readExplicitSpec());
1939 VisitFunctionDecl(D);
1940 D->setIsCopyDeductionCandidate(Record.readInt());
1943 void ASTDeclReader::VisitCXXMethodDecl(CXXMethodDecl *D) {
1944 VisitFunctionDecl(D);
1946 unsigned NumOverridenMethods = Record.readInt();
1947 if (D->isCanonicalDecl()) {
1948 while (NumOverridenMethods--) {
1949 // Avoid invariant checking of CXXMethodDecl::addOverriddenMethod,
1950 // MD may be initializing.
1951 if (auto *MD = readDeclAs<CXXMethodDecl>())
1952 Reader.getContext().addOverriddenMethod(D, MD->getCanonicalDecl());
1955 // We don't care about which declarations this used to override; we get
1956 // the relevant information from the canonical declaration.
1957 Record.skipInts(NumOverridenMethods);
1961 void ASTDeclReader::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
1962 // We need the inherited constructor information to merge the declaration,
1963 // so we have to read it before we call VisitCXXMethodDecl.
1964 D->setExplicitSpecifier(Record.readExplicitSpec());
1965 if (D->isInheritingConstructor()) {
1966 auto *Shadow = readDeclAs<ConstructorUsingShadowDecl>();
1967 auto *Ctor = readDeclAs<CXXConstructorDecl>();
1968 *D->getTrailingObjects<InheritedConstructor>() =
1969 InheritedConstructor(Shadow, Ctor);
1972 VisitCXXMethodDecl(D);
1975 void ASTDeclReader::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
1976 VisitCXXMethodDecl(D);
1978 if (auto *OperatorDelete = readDeclAs<FunctionDecl>()) {
1979 CXXDestructorDecl *Canon = D->getCanonicalDecl();
1980 auto *ThisArg = Record.readExpr();
1981 // FIXME: Check consistency if we have an old and new operator delete.
1982 if (!Canon->OperatorDelete) {
1983 Canon->OperatorDelete = OperatorDelete;
1984 Canon->OperatorDeleteThisArg = ThisArg;
1989 void ASTDeclReader::VisitCXXConversionDecl(CXXConversionDecl *D) {
1990 D->setExplicitSpecifier(Record.readExplicitSpec());
1991 VisitCXXMethodDecl(D);
1994 void ASTDeclReader::VisitImportDecl(ImportDecl *D) {
1996 D->ImportedModule = readModule();
1997 D->setImportComplete(Record.readInt());
1998 auto *StoredLocs = D->getTrailingObjects<SourceLocation>();
1999 for (unsigned I = 0, N = Record.back(); I != N; ++I)
2000 StoredLocs[I] = readSourceLocation();
2001 Record.skipInts(1); // The number of stored source locations.
2004 void ASTDeclReader::VisitAccessSpecDecl(AccessSpecDecl *D) {
2006 D->setColonLoc(readSourceLocation());
2009 void ASTDeclReader::VisitFriendDecl(FriendDecl *D) {
2011 if (Record.readInt()) // hasFriendDecl
2012 D->Friend = readDeclAs<NamedDecl>();
2014 D->Friend = readTypeSourceInfo();
2015 for (unsigned i = 0; i != D->NumTPLists; ++i)
2016 D->getTrailingObjects<TemplateParameterList *>()[i] =
2017 Record.readTemplateParameterList();
2018 D->NextFriend = readDeclID();
2019 D->UnsupportedFriend = (Record.readInt() != 0);
2020 D->FriendLoc = readSourceLocation();
2023 void ASTDeclReader::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
2025 unsigned NumParams = Record.readInt();
2026 D->NumParams = NumParams;
2027 D->Params = new TemplateParameterList*[NumParams];
2028 for (unsigned i = 0; i != NumParams; ++i)
2029 D->Params[i] = Record.readTemplateParameterList();
2030 if (Record.readInt()) // HasFriendDecl
2031 D->Friend = readDeclAs<NamedDecl>();
2033 D->Friend = readTypeSourceInfo();
2034 D->FriendLoc = readSourceLocation();
2037 DeclID ASTDeclReader::VisitTemplateDecl(TemplateDecl *D) {
2040 DeclID PatternID = readDeclID();
2041 auto *TemplatedDecl = cast_or_null<NamedDecl>(Reader.GetDecl(PatternID));
2042 TemplateParameterList *TemplateParams = Record.readTemplateParameterList();
2043 D->init(TemplatedDecl, TemplateParams);
2048 void ASTDeclReader::VisitConceptDecl(ConceptDecl *D) {
2049 VisitTemplateDecl(D);
2050 D->ConstraintExpr = Record.readExpr();
2054 void ASTDeclReader::VisitRequiresExprBodyDecl(RequiresExprBodyDecl *D) {
2057 ASTDeclReader::RedeclarableResult
2058 ASTDeclReader::VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D) {
2059 RedeclarableResult Redecl = VisitRedeclarable(D);
2061 // Make sure we've allocated the Common pointer first. We do this before
2062 // VisitTemplateDecl so that getCommonPtr() can be used during initialization.
2063 RedeclarableTemplateDecl *CanonD = D->getCanonicalDecl();
2064 if (!CanonD->Common) {
2065 CanonD->Common = CanonD->newCommon(Reader.getContext());
2066 Reader.PendingDefinitions.insert(CanonD);
2068 D->Common = CanonD->Common;
2070 // If this is the first declaration of the template, fill in the information
2071 // for the 'common' pointer.
2072 if (ThisDeclID == Redecl.getFirstID()) {
2073 if (auto *RTD = readDeclAs<RedeclarableTemplateDecl>()) {
2074 assert(RTD->getKind() == D->getKind() &&
2075 "InstantiatedFromMemberTemplate kind mismatch");
2076 D->setInstantiatedFromMemberTemplate(RTD);
2077 if (Record.readInt())
2078 D->setMemberSpecialization();
2082 DeclID PatternID = VisitTemplateDecl(D);
2083 D->IdentifierNamespace = Record.readInt();
2085 mergeRedeclarable(D, Redecl, PatternID);
2087 // If we merged the template with a prior declaration chain, merge the common
2089 // FIXME: Actually merge here, don't just overwrite.
2090 D->Common = D->getCanonicalDecl()->Common;
2095 void ASTDeclReader::VisitClassTemplateDecl(ClassTemplateDecl *D) {
2096 RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
2098 if (ThisDeclID == Redecl.getFirstID()) {
2099 // This ClassTemplateDecl owns a CommonPtr; read it to keep track of all of
2100 // the specializations.
2101 SmallVector<serialization::DeclID, 32> SpecIDs;
2102 readDeclIDList(SpecIDs);
2103 ASTDeclReader::AddLazySpecializations(D, SpecIDs);
2106 if (D->getTemplatedDecl()->TemplateOrInstantiation) {
2107 // We were loaded before our templated declaration was. We've not set up
2108 // its corresponding type yet (see VisitCXXRecordDeclImpl), so reconstruct
2110 Reader.getContext().getInjectedClassNameType(
2111 D->getTemplatedDecl(), D->getInjectedClassNameSpecialization());
2115 void ASTDeclReader::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) {
2116 llvm_unreachable("BuiltinTemplates are not serialized");
2119 /// TODO: Unify with ClassTemplateDecl version?
2120 /// May require unifying ClassTemplateDecl and
2121 /// VarTemplateDecl beyond TemplateDecl...
2122 void ASTDeclReader::VisitVarTemplateDecl(VarTemplateDecl *D) {
2123 RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
2125 if (ThisDeclID == Redecl.getFirstID()) {
2126 // This VarTemplateDecl owns a CommonPtr; read it to keep track of all of
2127 // the specializations.
2128 SmallVector<serialization::DeclID, 32> SpecIDs;
2129 readDeclIDList(SpecIDs);
2130 ASTDeclReader::AddLazySpecializations(D, SpecIDs);
2134 ASTDeclReader::RedeclarableResult
2135 ASTDeclReader::VisitClassTemplateSpecializationDeclImpl(
2136 ClassTemplateSpecializationDecl *D) {
2137 RedeclarableResult Redecl = VisitCXXRecordDeclImpl(D);
2139 ASTContext &C = Reader.getContext();
2140 if (Decl *InstD = readDecl()) {
2141 if (auto *CTD = dyn_cast<ClassTemplateDecl>(InstD)) {
2142 D->SpecializedTemplate = CTD;
2144 SmallVector<TemplateArgument, 8> TemplArgs;
2145 Record.readTemplateArgumentList(TemplArgs);
2146 TemplateArgumentList *ArgList
2147 = TemplateArgumentList::CreateCopy(C, TemplArgs);
2149 new (C) ClassTemplateSpecializationDecl::
2150 SpecializedPartialSpecialization();
2151 PS->PartialSpecialization
2152 = cast<ClassTemplatePartialSpecializationDecl>(InstD);
2153 PS->TemplateArgs = ArgList;
2154 D->SpecializedTemplate = PS;
2158 SmallVector<TemplateArgument, 8> TemplArgs;
2159 Record.readTemplateArgumentList(TemplArgs, /*Canonicalize*/ true);
2160 D->TemplateArgs = TemplateArgumentList::CreateCopy(C, TemplArgs);
2161 D->PointOfInstantiation = readSourceLocation();
2162 D->SpecializationKind = (TemplateSpecializationKind)Record.readInt();
2164 bool writtenAsCanonicalDecl = Record.readInt();
2165 if (writtenAsCanonicalDecl) {
2166 auto *CanonPattern = readDeclAs<ClassTemplateDecl>();
2167 if (D->isCanonicalDecl()) { // It's kept in the folding set.
2168 // Set this as, or find, the canonical declaration for this specialization
2169 ClassTemplateSpecializationDecl *CanonSpec;
2170 if (auto *Partial = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) {
2171 CanonSpec = CanonPattern->getCommonPtr()->PartialSpecializations
2172 .GetOrInsertNode(Partial);
2175 CanonPattern->getCommonPtr()->Specializations.GetOrInsertNode(D);
2177 // If there was already a canonical specialization, merge into it.
2178 if (CanonSpec != D) {
2179 mergeRedeclarable<TagDecl>(D, CanonSpec, Redecl);
2181 // This declaration might be a definition. Merge with any existing
2183 if (auto *DDD = D->DefinitionData) {
2184 if (CanonSpec->DefinitionData)
2185 MergeDefinitionData(CanonSpec, std::move(*DDD));
2187 CanonSpec->DefinitionData = D->DefinitionData;
2189 D->DefinitionData = CanonSpec->DefinitionData;
2195 if (TypeSourceInfo *TyInfo = readTypeSourceInfo()) {
2196 auto *ExplicitInfo =
2197 new (C) ClassTemplateSpecializationDecl::ExplicitSpecializationInfo;
2198 ExplicitInfo->TypeAsWritten = TyInfo;
2199 ExplicitInfo->ExternLoc = readSourceLocation();
2200 ExplicitInfo->TemplateKeywordLoc = readSourceLocation();
2201 D->ExplicitInfo = ExplicitInfo;
2207 void ASTDeclReader::VisitClassTemplatePartialSpecializationDecl(
2208 ClassTemplatePartialSpecializationDecl *D) {
2209 // We need to read the template params first because redeclarable is going to
2210 // need them for profiling
2211 TemplateParameterList *Params = Record.readTemplateParameterList();
2212 D->TemplateParams = Params;
2213 D->ArgsAsWritten = Record.readASTTemplateArgumentListInfo();
2215 RedeclarableResult Redecl = VisitClassTemplateSpecializationDeclImpl(D);
2217 // These are read/set from/to the first declaration.
2218 if (ThisDeclID == Redecl.getFirstID()) {
2219 D->InstantiatedFromMember.setPointer(
2220 readDeclAs<ClassTemplatePartialSpecializationDecl>());
2221 D->InstantiatedFromMember.setInt(Record.readInt());
2225 void ASTDeclReader::VisitClassScopeFunctionSpecializationDecl(
2226 ClassScopeFunctionSpecializationDecl *D) {
2228 D->Specialization = readDeclAs<CXXMethodDecl>();
2229 if (Record.readInt())
2230 D->TemplateArgs = Record.readASTTemplateArgumentListInfo();
2233 void ASTDeclReader::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
2234 RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
2236 if (ThisDeclID == Redecl.getFirstID()) {
2237 // This FunctionTemplateDecl owns a CommonPtr; read it.
2238 SmallVector<serialization::DeclID, 32> SpecIDs;
2239 readDeclIDList(SpecIDs);
2240 ASTDeclReader::AddLazySpecializations(D, SpecIDs);
2244 /// TODO: Unify with ClassTemplateSpecializationDecl version?
2245 /// May require unifying ClassTemplate(Partial)SpecializationDecl and
2246 /// VarTemplate(Partial)SpecializationDecl with a new data
2247 /// structure Template(Partial)SpecializationDecl, and
2248 /// using Template(Partial)SpecializationDecl as input type.
2249 ASTDeclReader::RedeclarableResult
2250 ASTDeclReader::VisitVarTemplateSpecializationDeclImpl(
2251 VarTemplateSpecializationDecl *D) {
2252 RedeclarableResult Redecl = VisitVarDeclImpl(D);
2254 ASTContext &C = Reader.getContext();
2255 if (Decl *InstD = readDecl()) {
2256 if (auto *VTD = dyn_cast<VarTemplateDecl>(InstD)) {
2257 D->SpecializedTemplate = VTD;
2259 SmallVector<TemplateArgument, 8> TemplArgs;
2260 Record.readTemplateArgumentList(TemplArgs);
2261 TemplateArgumentList *ArgList = TemplateArgumentList::CreateCopy(
2265 VarTemplateSpecializationDecl::SpecializedPartialSpecialization();
2266 PS->PartialSpecialization =
2267 cast<VarTemplatePartialSpecializationDecl>(InstD);
2268 PS->TemplateArgs = ArgList;
2269 D->SpecializedTemplate = PS;
2274 if (TypeSourceInfo *TyInfo = readTypeSourceInfo()) {
2275 auto *ExplicitInfo =
2276 new (C) VarTemplateSpecializationDecl::ExplicitSpecializationInfo;
2277 ExplicitInfo->TypeAsWritten = TyInfo;
2278 ExplicitInfo->ExternLoc = readSourceLocation();
2279 ExplicitInfo->TemplateKeywordLoc = readSourceLocation();
2280 D->ExplicitInfo = ExplicitInfo;
2283 SmallVector<TemplateArgument, 8> TemplArgs;
2284 Record.readTemplateArgumentList(TemplArgs, /*Canonicalize*/ true);
2285 D->TemplateArgs = TemplateArgumentList::CreateCopy(C, TemplArgs);
2286 D->PointOfInstantiation = readSourceLocation();
2287 D->SpecializationKind = (TemplateSpecializationKind)Record.readInt();
2288 D->IsCompleteDefinition = Record.readInt();
2290 bool writtenAsCanonicalDecl = Record.readInt();
2291 if (writtenAsCanonicalDecl) {
2292 auto *CanonPattern = readDeclAs<VarTemplateDecl>();
2293 if (D->isCanonicalDecl()) { // It's kept in the folding set.
2294 // FIXME: If it's already present, merge it.
2295 if (auto *Partial = dyn_cast<VarTemplatePartialSpecializationDecl>(D)) {
2296 CanonPattern->getCommonPtr()->PartialSpecializations
2297 .GetOrInsertNode(Partial);
2299 CanonPattern->getCommonPtr()->Specializations.GetOrInsertNode(D);
2307 /// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
2308 /// May require unifying ClassTemplate(Partial)SpecializationDecl and
2309 /// VarTemplate(Partial)SpecializationDecl with a new data
2310 /// structure Template(Partial)SpecializationDecl, and
2311 /// using Template(Partial)SpecializationDecl as input type.
2312 void ASTDeclReader::VisitVarTemplatePartialSpecializationDecl(
2313 VarTemplatePartialSpecializationDecl *D) {
2314 TemplateParameterList *Params = Record.readTemplateParameterList();
2315 D->TemplateParams = Params;
2316 D->ArgsAsWritten = Record.readASTTemplateArgumentListInfo();
2318 RedeclarableResult Redecl = VisitVarTemplateSpecializationDeclImpl(D);
2320 // These are read/set from/to the first declaration.
2321 if (ThisDeclID == Redecl.getFirstID()) {
2322 D->InstantiatedFromMember.setPointer(
2323 readDeclAs<VarTemplatePartialSpecializationDecl>());
2324 D->InstantiatedFromMember.setInt(Record.readInt());
2328 void ASTDeclReader::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
2331 D->setDeclaredWithTypename(Record.readInt());
2333 if (Record.readBool()) {
2334 NestedNameSpecifierLoc NNS = Record.readNestedNameSpecifierLoc();
2335 DeclarationNameInfo DN = Record.readDeclarationNameInfo();
2336 ConceptDecl *NamedConcept = Record.readDeclAs<ConceptDecl>();
2337 const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr;
2338 if (Record.readBool())
2339 ArgsAsWritten = Record.readASTTemplateArgumentListInfo();
2340 Expr *ImmediatelyDeclaredConstraint = Record.readExpr();
2341 D->setTypeConstraint(NNS, DN, /*FoundDecl=*/nullptr, NamedConcept,
2342 ArgsAsWritten, ImmediatelyDeclaredConstraint);
2343 if ((D->ExpandedParameterPack = Record.readInt()))
2344 D->NumExpanded = Record.readInt();
2347 if (Record.readInt())
2348 D->setDefaultArgument(readTypeSourceInfo());
2351 void ASTDeclReader::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
2352 VisitDeclaratorDecl(D);
2353 // TemplateParmPosition.
2354 D->setDepth(Record.readInt());
2355 D->setPosition(Record.readInt());
2356 if (D->hasPlaceholderTypeConstraint())
2357 D->setPlaceholderTypeConstraint(Record.readExpr());
2358 if (D->isExpandedParameterPack()) {
2359 auto TypesAndInfos =
2360 D->getTrailingObjects<std::pair<QualType, TypeSourceInfo *>>();
2361 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
2362 new (&TypesAndInfos[I].first) QualType(Record.readType());
2363 TypesAndInfos[I].second = readTypeSourceInfo();
2366 // Rest of NonTypeTemplateParmDecl.
2367 D->ParameterPack = Record.readInt();
2368 if (Record.readInt())
2369 D->setDefaultArgument(Record.readExpr());
2373 void ASTDeclReader::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
2374 VisitTemplateDecl(D);
2375 // TemplateParmPosition.
2376 D->setDepth(Record.readInt());
2377 D->setPosition(Record.readInt());
2378 if (D->isExpandedParameterPack()) {
2379 auto **Data = D->getTrailingObjects<TemplateParameterList *>();
2380 for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
2382 Data[I] = Record.readTemplateParameterList();
2384 // Rest of TemplateTemplateParmDecl.
2385 D->ParameterPack = Record.readInt();
2386 if (Record.readInt())
2387 D->setDefaultArgument(Reader.getContext(),
2388 Record.readTemplateArgumentLoc());
2392 void ASTDeclReader::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
2393 VisitRedeclarableTemplateDecl(D);
2396 void ASTDeclReader::VisitStaticAssertDecl(StaticAssertDecl *D) {
2398 D->AssertExprAndFailed.setPointer(Record.readExpr());
2399 D->AssertExprAndFailed.setInt(Record.readInt());
2400 D->Message = cast_or_null<StringLiteral>(Record.readExpr());
2401 D->RParenLoc = readSourceLocation();
2404 void ASTDeclReader::VisitEmptyDecl(EmptyDecl *D) {
2408 void ASTDeclReader::VisitLifetimeExtendedTemporaryDecl(
2409 LifetimeExtendedTemporaryDecl *D) {
2411 D->ExtendingDecl = readDeclAs<ValueDecl>();
2412 D->ExprWithTemporary = Record.readStmt();
2413 if (Record.readInt())
2414 D->Value = new (D->getASTContext()) APValue(Record.readAPValue());
2415 D->ManglingNumber = Record.readInt();
2419 std::pair<uint64_t, uint64_t>
2420 ASTDeclReader::VisitDeclContext(DeclContext *DC) {
2421 uint64_t LexicalOffset = ReadLocalOffset();
2422 uint64_t VisibleOffset = ReadLocalOffset();
2423 return std::make_pair(LexicalOffset, VisibleOffset);
2426 template <typename T>
2427 ASTDeclReader::RedeclarableResult
2428 ASTDeclReader::VisitRedeclarable(Redeclarable<T> *D) {
2429 DeclID FirstDeclID = readDeclID();
2430 Decl *MergeWith = nullptr;
2432 bool IsKeyDecl = ThisDeclID == FirstDeclID;
2433 bool IsFirstLocalDecl = false;
2435 uint64_t RedeclOffset = 0;
2437 // 0 indicates that this declaration was the only declaration of its entity,
2438 // and is used for space optimization.
2439 if (FirstDeclID == 0) {
2440 FirstDeclID = ThisDeclID;
2442 IsFirstLocalDecl = true;
2443 } else if (unsigned N = Record.readInt()) {
2444 // This declaration was the first local declaration, but may have imported
2445 // other declarations.
2447 IsFirstLocalDecl = true;
2449 // We have some declarations that must be before us in our redeclaration
2450 // chain. Read them now, and remember that we ought to merge with one of
2452 // FIXME: Provide a known merge target to the second and subsequent such
2454 for (unsigned I = 0; I != N - 1; ++I)
2455 MergeWith = readDecl();
2457 RedeclOffset = ReadLocalOffset();
2459 // This declaration was not the first local declaration. Read the first
2460 // local declaration now, to trigger the import of other redeclarations.
2464 auto *FirstDecl = cast_or_null<T>(Reader.GetDecl(FirstDeclID));
2465 if (FirstDecl != D) {
2466 // We delay loading of the redeclaration chain to avoid deeply nested calls.
2467 // We temporarily set the first (canonical) declaration as the previous one
2468 // which is the one that matters and mark the real previous DeclID to be
2469 // loaded & attached later on.
2470 D->RedeclLink = Redeclarable<T>::PreviousDeclLink(FirstDecl);
2471 D->First = FirstDecl->getCanonicalDecl();
2474 auto *DAsT = static_cast<T *>(D);
2476 // Note that we need to load local redeclarations of this decl and build a
2477 // decl chain for them. This must happen *after* we perform the preloading
2478 // above; this ensures that the redeclaration chain is built in the correct
2480 if (IsFirstLocalDecl)
2481 Reader.PendingDeclChains.push_back(std::make_pair(DAsT, RedeclOffset));
2483 return RedeclarableResult(MergeWith, FirstDeclID, IsKeyDecl);
2486 /// Attempts to merge the given declaration (D) with another declaration
2487 /// of the same entity.
2488 template<typename T>
2489 void ASTDeclReader::mergeRedeclarable(Redeclarable<T> *DBase,
2490 RedeclarableResult &Redecl,
2491 DeclID TemplatePatternID) {
2492 // If modules are not available, there is no reason to perform this merge.
2493 if (!Reader.getContext().getLangOpts().Modules)
2496 // If we're not the canonical declaration, we don't need to merge.
2497 if (!DBase->isFirstDecl())
2500 auto *D = static_cast<T *>(DBase);
2502 if (auto *Existing = Redecl.getKnownMergeTarget())
2503 // We already know of an existing declaration we should merge with.
2504 mergeRedeclarable(D, cast<T>(Existing), Redecl, TemplatePatternID);
2505 else if (FindExistingResult ExistingRes = findExisting(D))
2506 if (T *Existing = ExistingRes)
2507 mergeRedeclarable(D, Existing, Redecl, TemplatePatternID);
2510 /// "Cast" to type T, asserting if we don't have an implicit conversion.
2511 /// We use this to put code in a template that will only be valid for certain
2513 template<typename T> static T assert_cast(T t) { return t; }
2514 template<typename T> static T assert_cast(...) {
2515 llvm_unreachable("bad assert_cast");
2518 /// Merge together the pattern declarations from two template
2520 void ASTDeclReader::mergeTemplatePattern(RedeclarableTemplateDecl *D,
2521 RedeclarableTemplateDecl *Existing,
2522 DeclID DsID, bool IsKeyDecl) {
2523 auto *DPattern = D->getTemplatedDecl();
2524 auto *ExistingPattern = Existing->getTemplatedDecl();
2525 RedeclarableResult Result(/*MergeWith*/ ExistingPattern,
2526 DPattern->getCanonicalDecl()->getGlobalID(),
2529 if (auto *DClass = dyn_cast<CXXRecordDecl>(DPattern)) {
2530 // Merge with any existing definition.
2531 // FIXME: This is duplicated in several places. Refactor.
2532 auto *ExistingClass =
2533 cast<CXXRecordDecl>(ExistingPattern)->getCanonicalDecl();
2534 if (auto *DDD = DClass->DefinitionData) {
2535 if (ExistingClass->DefinitionData) {
2536 MergeDefinitionData(ExistingClass, std::move(*DDD));
2538 ExistingClass->DefinitionData = DClass->DefinitionData;
2539 // We may have skipped this before because we thought that DClass
2540 // was the canonical declaration.
2541 Reader.PendingDefinitions.insert(DClass);
2544 DClass->DefinitionData = ExistingClass->DefinitionData;
2546 return mergeRedeclarable(DClass, cast<TagDecl>(ExistingPattern),
2549 if (auto *DFunction = dyn_cast<FunctionDecl>(DPattern))
2550 return mergeRedeclarable(DFunction, cast<FunctionDecl>(ExistingPattern),
2552 if (auto *DVar = dyn_cast<VarDecl>(DPattern))
2553 return mergeRedeclarable(DVar, cast<VarDecl>(ExistingPattern), Result);
2554 if (auto *DAlias = dyn_cast<TypeAliasDecl>(DPattern))
2555 return mergeRedeclarable(DAlias, cast<TypedefNameDecl>(ExistingPattern),
2557 llvm_unreachable("merged an unknown kind of redeclarable template");
2560 /// Attempts to merge the given declaration (D) with another declaration
2561 /// of the same entity.
2562 template<typename T>
2563 void ASTDeclReader::mergeRedeclarable(Redeclarable<T> *DBase, T *Existing,
2564 RedeclarableResult &Redecl,
2565 DeclID TemplatePatternID) {
2566 auto *D = static_cast<T *>(DBase);
2567 T *ExistingCanon = Existing->getCanonicalDecl();
2568 T *DCanon = D->getCanonicalDecl();
2569 if (ExistingCanon != DCanon) {
2570 assert(DCanon->getGlobalID() == Redecl.getFirstID() &&
2571 "already merged this declaration");
2573 // Have our redeclaration link point back at the canonical declaration
2574 // of the existing declaration, so that this declaration has the
2575 // appropriate canonical declaration.
2576 D->RedeclLink = Redeclarable<T>::PreviousDeclLink(ExistingCanon);
2577 D->First = ExistingCanon;
2578 ExistingCanon->Used |= D->Used;
2581 // When we merge a namespace, update its pointer to the first namespace.
2582 // We cannot have loaded any redeclarations of this declaration yet, so
2583 // there's nothing else that needs to be updated.
2584 if (auto *Namespace = dyn_cast<NamespaceDecl>(D))
2585 Namespace->AnonOrFirstNamespaceAndInline.setPointer(
2586 assert_cast<NamespaceDecl*>(ExistingCanon));
2588 // When we merge a template, merge its pattern.
2589 if (auto *DTemplate = dyn_cast<RedeclarableTemplateDecl>(D))
2590 mergeTemplatePattern(
2591 DTemplate, assert_cast<RedeclarableTemplateDecl*>(ExistingCanon),
2592 TemplatePatternID, Redecl.isKeyDecl());
2594 // If this declaration is a key declaration, make a note of that.
2595 if (Redecl.isKeyDecl())
2596 Reader.KeyDecls[ExistingCanon].push_back(Redecl.getFirstID());
2600 /// ODR-like semantics for C/ObjC allow us to merge tag types and a structural
2601 /// check in Sema guarantees the types can be merged (see C11 6.2.7/1 or C89
2602 /// 6.1.2.6/1). Although most merging is done in Sema, we need to guarantee
2603 /// that some types are mergeable during deserialization, otherwise name
2604 /// lookup fails. This is the case for EnumConstantDecl.
2605 static bool allowODRLikeMergeInC(NamedDecl *ND) {
2608 // TODO: implement merge for other necessary decls.
2609 if (isa<EnumConstantDecl>(ND))
2614 /// Attempts to merge LifetimeExtendedTemporaryDecl with
2615 /// identical class definitions from two different modules.
2616 void ASTDeclReader::mergeMergeable(LifetimeExtendedTemporaryDecl *D) {
2617 // If modules are not available, there is no reason to perform this merge.
2618 if (!Reader.getContext().getLangOpts().Modules)
2621 LifetimeExtendedTemporaryDecl *LETDecl = D;
2623 LifetimeExtendedTemporaryDecl *&LookupResult =
2624 Reader.LETemporaryForMerging[std::make_pair(
2625 LETDecl->getExtendingDecl(), LETDecl->getManglingNumber())];
2627 Reader.getContext().setPrimaryMergedDecl(LETDecl,
2628 LookupResult->getCanonicalDecl());
2630 LookupResult = LETDecl;
2633 /// Attempts to merge the given declaration (D) with another declaration
2634 /// of the same entity, for the case where the entity is not actually
2635 /// redeclarable. This happens, for instance, when merging the fields of
2636 /// identical class definitions from two different modules.
2637 template<typename T>
2638 void ASTDeclReader::mergeMergeable(Mergeable<T> *D) {
2639 // If modules are not available, there is no reason to perform this merge.
2640 if (!Reader.getContext().getLangOpts().Modules)
2643 // ODR-based merging is performed in C++ and in some cases (tag types) in C.
2644 // Note that C identically-named things in different translation units are
2645 // not redeclarations, but may still have compatible types, where ODR-like
2646 // semantics may apply.
2647 if (!Reader.getContext().getLangOpts().CPlusPlus &&
2648 !allowODRLikeMergeInC(dyn_cast<NamedDecl>(static_cast<T*>(D))))
2651 if (FindExistingResult ExistingRes = findExisting(static_cast<T*>(D)))
2652 if (T *Existing = ExistingRes)
2653 Reader.getContext().setPrimaryMergedDecl(static_cast<T *>(D),
2654 Existing->getCanonicalDecl());
2657 void ASTDeclReader::VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D) {
2659 unsigned NumVars = D->varlist_size();
2660 SmallVector<Expr *, 16> Vars;
2661 Vars.reserve(NumVars);
2662 for (unsigned i = 0; i != NumVars; ++i) {
2663 Vars.push_back(Record.readExpr());
2668 void ASTDeclReader::VisitOMPAllocateDecl(OMPAllocateDecl *D) {
2670 unsigned NumVars = D->varlist_size();
2671 unsigned NumClauses = D->clauselist_size();
2672 SmallVector<Expr *, 16> Vars;
2673 Vars.reserve(NumVars);
2674 for (unsigned i = 0; i != NumVars; ++i) {
2675 Vars.push_back(Record.readExpr());
2678 SmallVector<OMPClause *, 8> Clauses;
2679 Clauses.reserve(NumClauses);
2680 for (unsigned I = 0; I != NumClauses; ++I)
2681 Clauses.push_back(Record.readOMPClause());
2682 D->setClauses(Clauses);
2685 void ASTDeclReader::VisitOMPRequiresDecl(OMPRequiresDecl * D) {
2687 unsigned NumClauses = D->clauselist_size();
2688 SmallVector<OMPClause *, 8> Clauses;
2689 Clauses.reserve(NumClauses);
2690 for (unsigned I = 0; I != NumClauses; ++I)
2691 Clauses.push_back(Record.readOMPClause());
2692 D->setClauses(Clauses);
2695 void ASTDeclReader::VisitOMPDeclareReductionDecl(OMPDeclareReductionDecl *D) {
2697 D->setLocation(readSourceLocation());
2698 Expr *In = Record.readExpr();
2699 Expr *Out = Record.readExpr();
2700 D->setCombinerData(In, Out);
2701 Expr *Combiner = Record.readExpr();
2702 D->setCombiner(Combiner);
2703 Expr *Orig = Record.readExpr();
2704 Expr *Priv = Record.readExpr();
2705 D->setInitializerData(Orig, Priv);
2706 Expr *Init = Record.readExpr();
2707 auto IK = static_cast<OMPDeclareReductionDecl::InitKind>(Record.readInt());
2708 D->setInitializer(Init, IK);
2709 D->PrevDeclInScope = readDeclID();
2712 void ASTDeclReader::VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D) {
2714 D->setLocation(readSourceLocation());
2715 Expr *MapperVarRefE = Record.readExpr();
2716 D->setMapperVarRef(MapperVarRefE);
2717 D->VarName = Record.readDeclarationName();
2718 D->PrevDeclInScope = readDeclID();
2719 unsigned NumClauses = D->clauselist_size();
2720 SmallVector<OMPClause *, 8> Clauses;
2721 Clauses.reserve(NumClauses);
2722 for (unsigned I = 0; I != NumClauses; ++I)
2723 Clauses.push_back(Record.readOMPClause());
2724 D->setClauses(Clauses);
2727 void ASTDeclReader::VisitOMPCapturedExprDecl(OMPCapturedExprDecl *D) {
2731 //===----------------------------------------------------------------------===//
2732 // Attribute Reading
2733 //===----------------------------------------------------------------------===//
2737 ASTRecordReader &Reader;
2740 AttrReader(ASTRecordReader &Reader) : Reader(Reader) {}
2742 uint64_t readInt() {
2743 return Reader.readInt();
2746 SourceRange readSourceRange() {
2747 return Reader.readSourceRange();
2750 SourceLocation readSourceLocation() {
2751 return Reader.readSourceLocation();
2754 Expr *readExpr() { return Reader.readExpr(); }
2756 std::string readString() {
2757 return Reader.readString();
2760 TypeSourceInfo *readTypeSourceInfo() {
2761 return Reader.readTypeSourceInfo();
2764 IdentifierInfo *readIdentifier() {
2765 return Reader.readIdentifier();
2768 VersionTuple readVersionTuple() {
2769 return Reader.readVersionTuple();
2772 OMPTraitInfo *readOMPTraitInfo() { return Reader.readOMPTraitInfo(); }
2774 template <typename T> T *GetLocalDeclAs(uint32_t LocalID) {
2775 return Reader.GetLocalDeclAs<T>(LocalID);
2780 Attr *ASTRecordReader::readAttr() {
2781 AttrReader Record(*this);
2782 auto V = Record.readInt();
2786 Attr *New = nullptr;
2787 // Kind is stored as a 1-based integer because 0 is used to indicate a null
2789 auto Kind = static_cast<attr::Kind>(V - 1);
2790 ASTContext &Context = getContext();
2792 IdentifierInfo *AttrName = Record.readIdentifier();
2793 IdentifierInfo *ScopeName = Record.readIdentifier();
2794 SourceRange AttrRange = Record.readSourceRange();
2795 SourceLocation ScopeLoc = Record.readSourceLocation();
2796 unsigned ParsedKind = Record.readInt();
2797 unsigned Syntax = Record.readInt();
2798 unsigned SpellingIndex = Record.readInt();
2800 AttributeCommonInfo Info(AttrName, ScopeName, AttrRange, ScopeLoc,
2801 AttributeCommonInfo::Kind(ParsedKind),
2802 AttributeCommonInfo::Syntax(Syntax), SpellingIndex);
2804 #include "clang/Serialization/AttrPCHRead.inc"
2806 assert(New && "Unable to decode attribute?");
2810 /// Reads attributes from the current stream position.
2811 void ASTRecordReader::readAttributes(AttrVec &Attrs) {
2812 for (unsigned I = 0, E = readInt(); I != E; ++I)
2813 Attrs.push_back(readAttr());
2816 //===----------------------------------------------------------------------===//
2817 // ASTReader Implementation
2818 //===----------------------------------------------------------------------===//
2820 /// Note that we have loaded the declaration with the given
2823 /// This routine notes that this declaration has already been loaded,
2824 /// so that future GetDecl calls will return this declaration rather
2825 /// than trying to load a new declaration.
2826 inline void ASTReader::LoadedDecl(unsigned Index, Decl *D) {
2827 assert(!DeclsLoaded[Index] && "Decl loaded twice?");
2828 DeclsLoaded[Index] = D;
2831 /// Determine whether the consumer will be interested in seeing
2832 /// this declaration (via HandleTopLevelDecl).
2834 /// This routine should return true for anything that might affect
2835 /// code generation, e.g., inline function definitions, Objective-C
2836 /// declarations with metadata, etc.
2837 static bool isConsumerInterestedIn(ASTContext &Ctx, Decl *D, bool HasBody) {
2838 // An ObjCMethodDecl is never considered as "interesting" because its
2839 // implementation container always is.
2841 // An ImportDecl or VarDecl imported from a module map module will get
2842 // emitted when we import the relevant module.
2843 if (isPartOfPerModuleInitializer(D)) {
2844 auto *M = D->getImportedOwningModule();
2845 if (M && M->Kind == Module::ModuleMapModule &&
2846 Ctx.DeclMustBeEmitted(D))
2850 if (isa<FileScopeAsmDecl>(D) ||
2851 isa<ObjCProtocolDecl>(D) ||
2852 isa<ObjCImplDecl>(D) ||
2853 isa<ImportDecl>(D) ||
2854 isa<PragmaCommentDecl>(D) ||
2855 isa<PragmaDetectMismatchDecl>(D))
2857 if (isa<OMPThreadPrivateDecl>(D) || isa<OMPDeclareReductionDecl>(D) ||
2858 isa<OMPDeclareMapperDecl>(D) || isa<OMPAllocateDecl>(D) ||
2859 isa<OMPRequiresDecl>(D))
2860 return !D->getDeclContext()->isFunctionOrMethod();
2861 if (const auto *Var = dyn_cast<VarDecl>(D))
2862 return Var->isFileVarDecl() &&
2863 (Var->isThisDeclarationADefinition() == VarDecl::Definition ||
2864 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Var));
2865 if (const auto *Func = dyn_cast<FunctionDecl>(D))
2866 return Func->doesThisDeclarationHaveABody() || HasBody;
2868 if (auto *ES = D->getASTContext().getExternalSource())
2869 if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
2875 /// Get the correct cursor and offset for loading a declaration.
2876 ASTReader::RecordLocation
2877 ASTReader::DeclCursorForID(DeclID ID, SourceLocation &Loc) {
2878 GlobalDeclMapType::iterator I = GlobalDeclMap.find(ID);
2879 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
2880 ModuleFile *M = I->second;
2881 const DeclOffset &DOffs =
2882 M->DeclOffsets[ID - M->BaseDeclID - NUM_PREDEF_DECL_IDS];
2883 Loc = TranslateSourceLocation(*M, DOffs.getLocation());
2884 return RecordLocation(M, DOffs.getBitOffset(M->DeclsBlockStartOffset));
2887 ASTReader::RecordLocation ASTReader::getLocalBitOffset(uint64_t GlobalOffset) {
2888 auto I = GlobalBitOffsetsMap.find(GlobalOffset);
2890 assert(I != GlobalBitOffsetsMap.end() && "Corrupted global bit offsets map");
2891 return RecordLocation(I->second, GlobalOffset - I->second->GlobalBitOffset);
2894 uint64_t ASTReader::getGlobalBitOffset(ModuleFile &M, uint64_t LocalOffset) {
2895 return LocalOffset + M.GlobalBitOffset;
2898 static bool isSameTemplateParameterList(const ASTContext &C,
2899 const TemplateParameterList *X,
2900 const TemplateParameterList *Y);
2902 /// Determine whether two template parameters are similar enough
2903 /// that they may be used in declarations of the same template.
2904 static bool isSameTemplateParameter(const NamedDecl *X,
2905 const NamedDecl *Y) {
2906 if (X->getKind() != Y->getKind())
2909 if (const auto *TX = dyn_cast<TemplateTypeParmDecl>(X)) {
2910 const auto *TY = cast<TemplateTypeParmDecl>(Y);
2911 if (TX->isParameterPack() != TY->isParameterPack())
2913 if (TX->hasTypeConstraint() != TY->hasTypeConstraint())
2915 const TypeConstraint *TXTC = TX->getTypeConstraint();
2916 const TypeConstraint *TYTC = TY->getTypeConstraint();
2920 if (TXTC->getNamedConcept() != TYTC->getNamedConcept())
2922 if (TXTC->hasExplicitTemplateArgs() != TYTC->hasExplicitTemplateArgs())
2924 if (TXTC->hasExplicitTemplateArgs()) {
2925 const auto *TXTCArgs = TXTC->getTemplateArgsAsWritten();
2926 const auto *TYTCArgs = TYTC->getTemplateArgsAsWritten();
2927 if (TXTCArgs->NumTemplateArgs != TYTCArgs->NumTemplateArgs)
2929 llvm::FoldingSetNodeID XID, YID;
2930 for (const auto &ArgLoc : TXTCArgs->arguments())
2931 ArgLoc.getArgument().Profile(XID, X->getASTContext());
2932 for (const auto &ArgLoc : TYTCArgs->arguments())
2933 ArgLoc.getArgument().Profile(YID, Y->getASTContext());
2941 if (const auto *TX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
2942 const auto *TY = cast<NonTypeTemplateParmDecl>(Y);
2943 return TX->isParameterPack() == TY->isParameterPack() &&
2944 TX->getASTContext().hasSameType(TX->getType(), TY->getType());
2947 const auto *TX = cast<TemplateTemplateParmDecl>(X);
2948 const auto *TY = cast<TemplateTemplateParmDecl>(Y);
2949 return TX->isParameterPack() == TY->isParameterPack() &&
2950 isSameTemplateParameterList(TX->getASTContext(),
2951 TX->getTemplateParameters(),
2952 TY->getTemplateParameters());
2955 static NamespaceDecl *getNamespace(const NestedNameSpecifier *X) {
2956 if (auto *NS = X->getAsNamespace())
2958 if (auto *NAS = X->getAsNamespaceAlias())
2959 return NAS->getNamespace();
2963 static bool isSameQualifier(const NestedNameSpecifier *X,
2964 const NestedNameSpecifier *Y) {
2965 if (auto *NSX = getNamespace(X)) {
2966 auto *NSY = getNamespace(Y);
2967 if (!NSY || NSX->getCanonicalDecl() != NSY->getCanonicalDecl())
2969 } else if (X->getKind() != Y->getKind())
2972 // FIXME: For namespaces and types, we're permitted to check that the entity
2973 // is named via the same tokens. We should probably do so.
2974 switch (X->getKind()) {
2975 case NestedNameSpecifier::Identifier:
2976 if (X->getAsIdentifier() != Y->getAsIdentifier())
2979 case NestedNameSpecifier::Namespace:
2980 case NestedNameSpecifier::NamespaceAlias:
2981 // We've already checked that we named the same namespace.
2983 case NestedNameSpecifier::TypeSpec:
2984 case NestedNameSpecifier::TypeSpecWithTemplate:
2985 if (X->getAsType()->getCanonicalTypeInternal() !=
2986 Y->getAsType()->getCanonicalTypeInternal())
2989 case NestedNameSpecifier::Global:
2990 case NestedNameSpecifier::Super:
2994 // Recurse into earlier portion of NNS, if any.
2995 auto *PX = X->getPrefix();
2996 auto *PY = Y->getPrefix();
2998 return isSameQualifier(PX, PY);
3002 /// Determine whether two template parameter lists are similar enough
3003 /// that they may be used in declarations of the same template.
3004 static bool isSameTemplateParameterList(const ASTContext &C,
3005 const TemplateParameterList *X,
3006 const TemplateParameterList *Y) {
3007 if (X->size() != Y->size())
3010 for (unsigned I = 0, N = X->size(); I != N; ++I)
3011 if (!isSameTemplateParameter(X->getParam(I), Y->getParam(I)))
3014 const Expr *XRC = X->getRequiresClause();
3015 const Expr *YRC = Y->getRequiresClause();
3019 llvm::FoldingSetNodeID XRCID, YRCID;
3020 XRC->Profile(XRCID, C, /*Canonical=*/true);
3021 YRC->Profile(YRCID, C, /*Canonical=*/true);
3029 /// Determine whether the attributes we can overload on are identical for A and
3030 /// B. Will ignore any overloadable attrs represented in the type of A and B.
3031 static bool hasSameOverloadableAttrs(const FunctionDecl *A,
3032 const FunctionDecl *B) {
3033 // Note that pass_object_size attributes are represented in the function's
3034 // ExtParameterInfo, so we don't need to check them here.
3036 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
3037 auto AEnableIfAttrs = A->specific_attrs<EnableIfAttr>();
3038 auto BEnableIfAttrs = B->specific_attrs<EnableIfAttr>();
3040 for (auto Pair : zip_longest(AEnableIfAttrs, BEnableIfAttrs)) {
3041 Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
3042 Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
3044 // Return false if the number of enable_if attributes is different.
3045 if (!Cand1A || !Cand2A)
3051 (*Cand1A)->getCond()->Profile(Cand1ID, A->getASTContext(), true);
3052 (*Cand2A)->getCond()->Profile(Cand2ID, B->getASTContext(), true);
3054 // Return false if any of the enable_if expressions of A and B are
3056 if (Cand1ID != Cand2ID)
3062 /// Determine whether the two declarations refer to the same entity.pr
3063 static bool isSameEntity(NamedDecl *X, NamedDecl *Y) {
3064 assert(X->getDeclName() == Y->getDeclName() && "Declaration name mismatch!");
3069 // Must be in the same context.
3071 // Note that we can't use DeclContext::Equals here, because the DeclContexts
3072 // could be two different declarations of the same function. (We will fix the
3073 // semantic DC to refer to the primary definition after merging.)
3074 if (!declaresSameEntity(cast<Decl>(X->getDeclContext()->getRedeclContext()),
3075 cast<Decl>(Y->getDeclContext()->getRedeclContext())))
3078 // Two typedefs refer to the same entity if they have the same underlying
3080 if (const auto *TypedefX = dyn_cast<TypedefNameDecl>(X))
3081 if (const auto *TypedefY = dyn_cast<TypedefNameDecl>(Y))
3082 return X->getASTContext().hasSameType(TypedefX->getUnderlyingType(),
3083 TypedefY->getUnderlyingType());
3085 // Must have the same kind.
3086 if (X->getKind() != Y->getKind())
3089 // Objective-C classes and protocols with the same name always match.
3090 if (isa<ObjCInterfaceDecl>(X) || isa<ObjCProtocolDecl>(X))
3093 if (isa<ClassTemplateSpecializationDecl>(X)) {
3094 // No need to handle these here: we merge them when adding them to the
3099 // Compatible tags match.
3100 if (const auto *TagX = dyn_cast<TagDecl>(X)) {
3101 const auto *TagY = cast<TagDecl>(Y);
3102 return (TagX->getTagKind() == TagY->getTagKind()) ||
3103 ((TagX->getTagKind() == TTK_Struct || TagX->getTagKind() == TTK_Class ||
3104 TagX->getTagKind() == TTK_Interface) &&
3105 (TagY->getTagKind() == TTK_Struct || TagY->getTagKind() == TTK_Class ||
3106 TagY->getTagKind() == TTK_Interface));
3109 // Functions with the same type and linkage match.
3110 // FIXME: This needs to cope with merging of prototyped/non-prototyped
3112 if (const auto *FuncX = dyn_cast<FunctionDecl>(X)) {
3113 const auto *FuncY = cast<FunctionDecl>(Y);
3114 if (const auto *CtorX = dyn_cast<CXXConstructorDecl>(X)) {
3115 const auto *CtorY = cast<CXXConstructorDecl>(Y);
3116 if (CtorX->getInheritedConstructor() &&
3117 !isSameEntity(CtorX->getInheritedConstructor().getConstructor(),
3118 CtorY->getInheritedConstructor().getConstructor()))
3122 if (FuncX->isMultiVersion() != FuncY->isMultiVersion())
3125 // Multiversioned functions with different feature strings are represented
3126 // as separate declarations.
3127 if (FuncX->isMultiVersion()) {
3128 const auto *TAX = FuncX->getAttr<TargetAttr>();
3129 const auto *TAY = FuncY->getAttr<TargetAttr>();
3130 assert(TAX && TAY && "Multiversion Function without target attribute");
3132 if (TAX->getFeaturesStr() != TAY->getFeaturesStr())
3136 ASTContext &C = FuncX->getASTContext();
3138 const Expr *XRC = FuncX->getTrailingRequiresClause();
3139 const Expr *YRC = FuncY->getTrailingRequiresClause();
3143 llvm::FoldingSetNodeID XRCID, YRCID;
3144 XRC->Profile(XRCID, C, /*Canonical=*/true);
3145 YRC->Profile(YRCID, C, /*Canonical=*/true);
3150 auto GetTypeAsWritten = [](const FunctionDecl *FD) {
3151 // Map to the first declaration that we've already merged into this one.
3152 // The TSI of redeclarations might not match (due to calling conventions
3153 // being inherited onto the type but not the TSI), but the TSI type of
3154 // the first declaration of the function should match across modules.
3155 FD = FD->getCanonicalDecl();
3156 return FD->getTypeSourceInfo() ? FD->getTypeSourceInfo()->getType()
3159 QualType XT = GetTypeAsWritten(FuncX), YT = GetTypeAsWritten(FuncY);
3160 if (!C.hasSameType(XT, YT)) {
3161 // We can get functions with different types on the redecl chain in C++17
3162 // if they have differing exception specifications and at least one of
3163 // the excpetion specs is unresolved.
3164 auto *XFPT = XT->getAs<FunctionProtoType>();
3165 auto *YFPT = YT->getAs<FunctionProtoType>();
3166 if (C.getLangOpts().CPlusPlus17 && XFPT && YFPT &&
3167 (isUnresolvedExceptionSpec(XFPT->getExceptionSpecType()) ||
3168 isUnresolvedExceptionSpec(YFPT->getExceptionSpecType())) &&
3169 C.hasSameFunctionTypeIgnoringExceptionSpec(XT, YT))
3174 return FuncX->getLinkageInternal() == FuncY->getLinkageInternal() &&
3175 hasSameOverloadableAttrs(FuncX, FuncY);
3178 // Variables with the same type and linkage match.
3179 if (const auto *VarX = dyn_cast<VarDecl>(X)) {
3180 const auto *VarY = cast<VarDecl>(Y);
3181 if (VarX->getLinkageInternal() == VarY->getLinkageInternal()) {
3182 ASTContext &C = VarX->getASTContext();
3183 if (C.hasSameType(VarX->getType(), VarY->getType()))
3186 // We can get decls with different types on the redecl chain. Eg.
3187 // template <typename T> struct S { static T Var[]; }; // #1
3188 // template <typename T> T S<T>::Var[sizeof(T)]; // #2
3189 // Only? happens when completing an incomplete array type. In this case
3190 // when comparing #1 and #2 we should go through their element type.
3191 const ArrayType *VarXTy = C.getAsArrayType(VarX->getType());
3192 const ArrayType *VarYTy = C.getAsArrayType(VarY->getType());
3193 if (!VarXTy || !VarYTy)
3195 if (VarXTy->isIncompleteArrayType() || VarYTy->isIncompleteArrayType())
3196 return C.hasSameType(VarXTy->getElementType(), VarYTy->getElementType());
3201 // Namespaces with the same name and inlinedness match.
3202 if (const auto *NamespaceX = dyn_cast<NamespaceDecl>(X)) {
3203 const auto *NamespaceY = cast<NamespaceDecl>(Y);
3204 return NamespaceX->isInline() == NamespaceY->isInline();
3207 // Identical template names and kinds match if their template parameter lists
3208 // and patterns match.
3209 if (const auto *TemplateX = dyn_cast<TemplateDecl>(X)) {
3210 const auto *TemplateY = cast<TemplateDecl>(Y);
3211 return isSameEntity(TemplateX->getTemplatedDecl(),
3212 TemplateY->getTemplatedDecl()) &&
3213 isSameTemplateParameterList(TemplateX->getASTContext(),
3214 TemplateX->getTemplateParameters(),
3215 TemplateY->getTemplateParameters());
3218 // Fields with the same name and the same type match.
3219 if (const auto *FDX = dyn_cast<FieldDecl>(X)) {
3220 const auto *FDY = cast<FieldDecl>(Y);
3221 // FIXME: Also check the bitwidth is odr-equivalent, if any.
3222 return X->getASTContext().hasSameType(FDX->getType(), FDY->getType());
3225 // Indirect fields with the same target field match.
3226 if (const auto *IFDX = dyn_cast<IndirectFieldDecl>(X)) {
3227 const auto *IFDY = cast<IndirectFieldDecl>(Y);
3228 return IFDX->getAnonField()->getCanonicalDecl() ==
3229 IFDY->getAnonField()->getCanonicalDecl();
3232 // Enumerators with the same name match.
3233 if (isa<EnumConstantDecl>(X))
3234 // FIXME: Also check the value is odr-equivalent.
3237 // Using shadow declarations with the same target match.
3238 if (const auto *USX = dyn_cast<UsingShadowDecl>(X)) {
3239 const auto *USY = cast<UsingShadowDecl>(Y);
3240 return USX->getTargetDecl() == USY->getTargetDecl();
3243 // Using declarations with the same qualifier match. (We already know that
3244 // the name matches.)
3245 if (const auto *UX = dyn_cast<UsingDecl>(X)) {
3246 const auto *UY = cast<UsingDecl>(Y);
3247 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
3248 UX->hasTypename() == UY->hasTypename() &&
3249 UX->isAccessDeclaration() == UY->isAccessDeclaration();
3251 if (const auto *UX = dyn_cast<UnresolvedUsingValueDecl>(X)) {
3252 const auto *UY = cast<UnresolvedUsingValueDecl>(Y);
3253 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
3254 UX->isAccessDeclaration() == UY->isAccessDeclaration();
3256 if (const auto *UX = dyn_cast<UnresolvedUsingTypenameDecl>(X))
3257 return isSameQualifier(
3259 cast<UnresolvedUsingTypenameDecl>(Y)->getQualifier());
3261 // Namespace alias definitions with the same target match.
3262 if (const auto *NAX = dyn_cast<NamespaceAliasDecl>(X)) {
3263 const auto *NAY = cast<NamespaceAliasDecl>(Y);
3264 return NAX->getNamespace()->Equals(NAY->getNamespace());
3270 /// Find the context in which we should search for previous declarations when
3271 /// looking for declarations to merge.
3272 DeclContext *ASTDeclReader::getPrimaryContextForMerging(ASTReader &Reader,
3274 if (auto *ND = dyn_cast<NamespaceDecl>(DC))
3275 return ND->getOriginalNamespace();
3277 if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) {
3278 // Try to dig out the definition.
3279 auto *DD = RD->DefinitionData;
3281 DD = RD->getCanonicalDecl()->DefinitionData;
3283 // If there's no definition yet, then DC's definition is added by an update
3284 // record, but we've not yet loaded that update record. In this case, we
3285 // commit to DC being the canonical definition now, and will fix this when
3286 // we load the update record.
3288 DD = new (Reader.getContext()) struct CXXRecordDecl::DefinitionData(RD);
3289 RD->setCompleteDefinition(true);
3290 RD->DefinitionData = DD;
3291 RD->getCanonicalDecl()->DefinitionData = DD;
3293 // Track that we did this horrible thing so that we can fix it later.
3294 Reader.PendingFakeDefinitionData.insert(
3295 std::make_pair(DD, ASTReader::PendingFakeDefinitionKind::Fake));
3298 return DD->Definition;
3301 if (auto *ED = dyn_cast<EnumDecl>(DC))
3302 return ED->getASTContext().getLangOpts().CPlusPlus? ED->getDefinition()
3305 // We can see the TU here only if we have no Sema object. In that case,
3306 // there's no TU scope to look in, so using the DC alone is sufficient.
3307 if (auto *TU = dyn_cast<TranslationUnitDecl>(DC))
3313 ASTDeclReader::FindExistingResult::~FindExistingResult() {
3314 // Record that we had a typedef name for linkage whether or not we merge
3315 // with that declaration.
3316 if (TypedefNameForLinkage) {
3317 DeclContext *DC = New->getDeclContext()->getRedeclContext();
3318 Reader.ImportedTypedefNamesForLinkage.insert(
3319 std::make_pair(std::make_pair(DC, TypedefNameForLinkage), New));
3323 if (!AddResult || Existing)
3326 DeclarationName Name = New->getDeclName();
3327 DeclContext *DC = New->getDeclContext()->getRedeclContext();
3328 if (needsAnonymousDeclarationNumber(New)) {
3329 setAnonymousDeclForMerging(Reader, New->getLexicalDeclContext(),
3330 AnonymousDeclNumber, New);
3331 } else if (DC->isTranslationUnit() &&
3332 !Reader.getContext().getLangOpts().CPlusPlus) {
3333 if (Reader.getIdResolver().tryAddTopLevelDecl(New, Name))
3334 Reader.PendingFakeLookupResults[Name.getAsIdentifierInfo()]
3336 } else if (DeclContext *MergeDC = getPrimaryContextForMerging(Reader, DC)) {
3337 // Add the declaration to its redeclaration context so later merging
3338 // lookups will find it.
3339 MergeDC->makeDeclVisibleInContextImpl(New, /*Internal*/true);
3343 /// Find the declaration that should be merged into, given the declaration found
3344 /// by name lookup. If we're merging an anonymous declaration within a typedef,
3345 /// we need a matching typedef, and we merge with the type inside it.
3346 static NamedDecl *getDeclForMerging(NamedDecl *Found,
3347 bool IsTypedefNameForLinkage) {
3348 if (!IsTypedefNameForLinkage)
3351 // If we found a typedef declaration that gives a name to some other
3352 // declaration, then we want that inner declaration. Declarations from
3353 // AST files are handled via ImportedTypedefNamesForLinkage.
3354 if (Found->isFromASTFile())
3357 if (auto *TND = dyn_cast<TypedefNameDecl>(Found))
3358 return TND->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
3363 /// Find the declaration to use to populate the anonymous declaration table
3364 /// for the given lexical DeclContext. We only care about finding local
3365 /// definitions of the context; we'll merge imported ones as we go.
3367 ASTDeclReader::getPrimaryDCForAnonymousDecl(DeclContext *LexicalDC) {
3368 // For classes, we track the definition as we merge.
3369 if (auto *RD = dyn_cast<CXXRecordDecl>(LexicalDC)) {
3370 auto *DD = RD->getCanonicalDecl()->DefinitionData;
3371 return DD ? DD->Definition : nullptr;
3374 // For anything else, walk its merged redeclarations looking for a definition.
3375 // Note that we can't just call getDefinition here because the redeclaration
3376 // chain isn't wired up.
3377 for (auto *D : merged_redecls(cast<Decl>(LexicalDC))) {
3378 if (auto *FD = dyn_cast<FunctionDecl>(D))
3379 if (FD->isThisDeclarationADefinition())
3381 if (auto *MD = dyn_cast<ObjCMethodDecl>(D))
3382 if (MD->isThisDeclarationADefinition())
3386 // No merged definition yet.
3390 NamedDecl *ASTDeclReader::getAnonymousDeclForMerging(ASTReader &Reader,
3393 // If the lexical context has been merged, look into the now-canonical
3395 auto *CanonDC = cast<Decl>(DC)->getCanonicalDecl();
3397 // If we've seen this before, return the canonical declaration.
3398 auto &Previous = Reader.AnonymousDeclarationsForMerging[CanonDC];
3399 if (Index < Previous.size() && Previous[Index])
3400 return Previous[Index];
3402 // If this is the first time, but we have parsed a declaration of the context,
3403 // build the anonymous declaration list from the parsed declaration.
3404 auto *PrimaryDC = getPrimaryDCForAnonymousDecl(DC);
3405 if (PrimaryDC && !cast<Decl>(PrimaryDC)->isFromASTFile()) {
3406 numberAnonymousDeclsWithin(PrimaryDC, [&](NamedDecl *ND, unsigned Number) {
3407 if (Previous.size() == Number)
3408 Previous.push_back(cast<NamedDecl>(ND->getCanonicalDecl()));
3410 Previous[Number] = cast<NamedDecl>(ND->getCanonicalDecl());
3414 return Index < Previous.size() ? Previous[Index] : nullptr;
3417 void ASTDeclReader::setAnonymousDeclForMerging(ASTReader &Reader,
3418 DeclContext *DC, unsigned Index,
3420 auto *CanonDC = cast<Decl>(DC)->getCanonicalDecl();
3422 auto &Previous = Reader.AnonymousDeclarationsForMerging[CanonDC];
3423 if (Index >= Previous.size())
3424 Previous.resize(Index + 1);
3425 if (!Previous[Index])
3426 Previous[Index] = D;
3429 ASTDeclReader::FindExistingResult ASTDeclReader::findExisting(NamedDecl *D) {
3430 DeclarationName Name = TypedefNameForLinkage ? TypedefNameForLinkage
3433 if (!Name && !needsAnonymousDeclarationNumber(D)) {
3434 // Don't bother trying to find unnamed declarations that are in
3435 // unmergeable contexts.
3436 FindExistingResult Result(Reader, D, /*Existing=*/nullptr,
3437 AnonymousDeclNumber, TypedefNameForLinkage);
3442 DeclContext *DC = D->getDeclContext()->getRedeclContext();
3443 if (TypedefNameForLinkage) {
3444 auto It = Reader.ImportedTypedefNamesForLinkage.find(
3445 std::make_pair(DC, TypedefNameForLinkage));
3446 if (It != Reader.ImportedTypedefNamesForLinkage.end())
3447 if (isSameEntity(It->second, D))
3448 return FindExistingResult(Reader, D, It->second, AnonymousDeclNumber,
3449 TypedefNameForLinkage);
3450 // Go on to check in other places in case an existing typedef name
3451 // was not imported.
3454 if (needsAnonymousDeclarationNumber(D)) {
3455 // This is an anonymous declaration that we may need to merge. Look it up
3456 // in its context by number.
3457 if (auto *Existing = getAnonymousDeclForMerging(
3458 Reader, D->getLexicalDeclContext(), AnonymousDeclNumber))
3459 if (isSameEntity(Existing, D))
3460 return FindExistingResult(Reader, D, Existing, AnonymousDeclNumber,
3461 TypedefNameForLinkage);
3462 } else if (DC->isTranslationUnit() &&
3463 !Reader.getContext().getLangOpts().CPlusPlus) {
3464 IdentifierResolver &IdResolver = Reader.getIdResolver();
3466 // Temporarily consider the identifier to be up-to-date. We don't want to
3467 // cause additional lookups here.
3468 class UpToDateIdentifierRAII {
3470 bool WasOutToDate = false;
3473 explicit UpToDateIdentifierRAII(IdentifierInfo *II) : II(II) {
3475 WasOutToDate = II->isOutOfDate();
3477 II->setOutOfDate(false);
3481 ~UpToDateIdentifierRAII() {
3483 II->setOutOfDate(true);
3485 } UpToDate(Name.getAsIdentifierInfo());
3487 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
3488 IEnd = IdResolver.end();
3490 if (NamedDecl *Existing = getDeclForMerging(*I, TypedefNameForLinkage))
3491 if (isSameEntity(Existing, D))
3492 return FindExistingResult(Reader, D, Existing, AnonymousDeclNumber,
3493 TypedefNameForLinkage);
3495 } else if (DeclContext *MergeDC = getPrimaryContextForMerging(Reader, DC)) {
3496 DeclContext::lookup_result R = MergeDC->noload_lookup(Name);
3497 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
3498 if (NamedDecl *Existing = getDeclForMerging(*I, TypedefNameForLinkage))
3499 if (isSameEntity(Existing, D))
3500 return FindExistingResult(Reader, D, Existing, AnonymousDeclNumber,
3501 TypedefNameForLinkage);
3504 // Not in a mergeable context.
3505 return FindExistingResult(Reader);
3508 // If this declaration is from a merged context, make a note that we need to
3509 // check that the canonical definition of that context contains the decl.
3511 // FIXME: We should do something similar if we merge two definitions of the
3512 // same template specialization into the same CXXRecordDecl.
3513 auto MergedDCIt = Reader.MergedDeclContexts.find(D->getLexicalDeclContext());
3514 if (MergedDCIt != Reader.MergedDeclContexts.end() &&
3515 MergedDCIt->second == D->getDeclContext())
3516 Reader.PendingOdrMergeChecks.push_back(D);
3518 return FindExistingResult(Reader, D, /*Existing=*/nullptr,
3519 AnonymousDeclNumber, TypedefNameForLinkage);
3522 template<typename DeclT>
3523 Decl *ASTDeclReader::getMostRecentDeclImpl(Redeclarable<DeclT> *D) {
3524 return D->RedeclLink.getLatestNotUpdated();
3527 Decl *ASTDeclReader::getMostRecentDeclImpl(...) {
3528 llvm_unreachable("getMostRecentDecl on non-redeclarable declaration");
3531 Decl *ASTDeclReader::getMostRecentDecl(Decl *D) {
3534 switch (D->getKind()) {
3535 #define ABSTRACT_DECL(TYPE)
3536 #define DECL(TYPE, BASE) \
3538 return getMostRecentDeclImpl(cast<TYPE##Decl>(D));
3539 #include "clang/AST/DeclNodes.inc"
3541 llvm_unreachable("unknown decl kind");
3544 Decl *ASTReader::getMostRecentExistingDecl(Decl *D) {
3545 return ASTDeclReader::getMostRecentDecl(D->getCanonicalDecl());
3548 template<typename DeclT>
3549 void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader,
3550 Redeclarable<DeclT> *D,
3551 Decl *Previous, Decl *Canon) {
3552 D->RedeclLink.setPrevious(cast<DeclT>(Previous));
3553 D->First = cast<DeclT>(Previous)->First;
3559 void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader,
3560 Redeclarable<VarDecl> *D,
3561 Decl *Previous, Decl *Canon) {
3562 auto *VD = static_cast<VarDecl *>(D);
3563 auto *PrevVD = cast<VarDecl>(Previous);
3564 D->RedeclLink.setPrevious(PrevVD);
3565 D->First = PrevVD->First;
3567 // We should keep at most one definition on the chain.
3568 // FIXME: Cache the definition once we've found it. Building a chain with
3569 // N definitions currently takes O(N^2) time here.
3570 if (VD->isThisDeclarationADefinition() == VarDecl::Definition) {
3571 for (VarDecl *CurD = PrevVD; CurD; CurD = CurD->getPreviousDecl()) {
3572 if (CurD->isThisDeclarationADefinition() == VarDecl::Definition) {
3573 Reader.mergeDefinitionVisibility(CurD, VD);
3574 VD->demoteThisDefinitionToDeclaration();
3581 static bool isUndeducedReturnType(QualType T) {
3582 auto *DT = T->getContainedDeducedType();
3583 return DT && !DT->isDeduced();
3587 void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader,
3588 Redeclarable<FunctionDecl> *D,
3589 Decl *Previous, Decl *Canon) {
3590 auto *FD = static_cast<FunctionDecl *>(D);
3591 auto *PrevFD = cast<FunctionDecl>(Previous);
3593 FD->RedeclLink.setPrevious(PrevFD);
3594 FD->First = PrevFD->First;
3596 // If the previous declaration is an inline function declaration, then this
3597 // declaration is too.
3598 if (PrevFD->isInlined() != FD->isInlined()) {
3599 // FIXME: [dcl.fct.spec]p4:
3600 // If a function with external linkage is declared inline in one
3601 // translation unit, it shall be declared inline in all translation
3602 // units in which it appears.
3604 // Be careful of this case:
3607 // template<typename T> struct X { void f(); };
3608 // template<typename T> inline void X<T>::f() {}
3610 // module B instantiates the declaration of X<int>::f
3611 // module C instantiates the definition of X<int>::f
3613 // If module B and C are merged, we do not have a violation of this rule.
3614 FD->setImplicitlyInline(true);
3617 auto *FPT = FD->getType()->getAs<FunctionProtoType>();
3618 auto *PrevFPT = PrevFD->getType()->getAs<FunctionProtoType>();
3619 if (FPT && PrevFPT) {
3620 // If we need to propagate an exception specification along the redecl
3621 // chain, make a note of that so that we can do so later.
3622 bool IsUnresolved = isUnresolvedExceptionSpec(FPT->getExceptionSpecType());
3623 bool WasUnresolved =
3624 isUnresolvedExceptionSpec(PrevFPT->getExceptionSpecType());
3625 if (IsUnresolved != WasUnresolved)
3626 Reader.PendingExceptionSpecUpdates.insert(
3627 {Canon, IsUnresolved ? PrevFD : FD});
3629 // If we need to propagate a deduced return type along the redecl chain,
3630 // make a note of that so that we can do it later.
3631 bool IsUndeduced = isUndeducedReturnType(FPT->getReturnType());
3632 bool WasUndeduced = isUndeducedReturnType(PrevFPT->getReturnType());
3633 if (IsUndeduced != WasUndeduced)
3634 Reader.PendingDeducedTypeUpdates.insert(
3635 {cast<FunctionDecl>(Canon),
3636 (IsUndeduced ? PrevFPT : FPT)->getReturnType()});
3640 } // namespace clang
3642 void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader, ...) {
3643 llvm_unreachable("attachPreviousDecl on non-redeclarable declaration");
3646 /// Inherit the default template argument from \p From to \p To. Returns
3647 /// \c false if there is no default template for \p From.
3648 template <typename ParmDecl>
3649 static bool inheritDefaultTemplateArgument(ASTContext &Context, ParmDecl *From,
3651 auto *To = cast<ParmDecl>(ToD);
3652 if (!From->hasDefaultArgument())
3654 To->setInheritedDefaultArgument(Context, From);
3658 static void inheritDefaultTemplateArguments(ASTContext &Context,
3661 auto *FromTP = From->getTemplateParameters();
3662 auto *ToTP = To->getTemplateParameters();
3663 assert(FromTP->size() == ToTP->size() && "merged mismatched templates?");
3665 for (unsigned I = 0, N = FromTP->size(); I != N; ++I) {
3666 NamedDecl *FromParam = FromTP->getParam(I);
3667 NamedDecl *ToParam = ToTP->getParam(I);
3669 if (auto *FTTP = dyn_cast<TemplateTypeParmDecl>(FromParam))
3670 inheritDefaultTemplateArgument(Context, FTTP, ToParam);
3671 else if (auto *FNTTP = dyn_cast<NonTypeTemplateParmDecl>(FromParam))
3672 inheritDefaultTemplateArgument(Context, FNTTP, ToParam);
3674 inheritDefaultTemplateArgument(
3675 Context, cast<TemplateTemplateParmDecl>(FromParam), ToParam);
3679 void ASTDeclReader::attachPreviousDecl(ASTReader &Reader, Decl *D,
3680 Decl *Previous, Decl *Canon) {
3681 assert(D && Previous);
3683 switch (D->getKind()) {
3684 #define ABSTRACT_DECL(TYPE)
3685 #define DECL(TYPE, BASE) \
3687 attachPreviousDeclImpl(Reader, cast<TYPE##Decl>(D), Previous, Canon); \
3689 #include "clang/AST/DeclNodes.inc"
3692 // If the declaration was visible in one module, a redeclaration of it in
3693 // another module remains visible even if it wouldn't be visible by itself.
3695 // FIXME: In this case, the declaration should only be visible if a module
3696 // that makes it visible has been imported.
3697 D->IdentifierNamespace |=
3698 Previous->IdentifierNamespace &
3699 (Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Type);
3701 // If the declaration declares a template, it may inherit default arguments
3702 // from the previous declaration.
3703 if (auto *TD = dyn_cast<TemplateDecl>(D))
3704 inheritDefaultTemplateArguments(Reader.getContext(),
3705 cast<TemplateDecl>(Previous), TD);
3708 template<typename DeclT>
3709 void ASTDeclReader::attachLatestDeclImpl(Redeclarable<DeclT> *D, Decl *Latest) {
3710 D->RedeclLink.setLatest(cast<DeclT>(Latest));
3713 void ASTDeclReader::attachLatestDeclImpl(...) {
3714 llvm_unreachable("attachLatestDecl on non-redeclarable declaration");
3717 void ASTDeclReader::attachLatestDecl(Decl *D, Decl *Latest) {
3718 assert(D && Latest);
3720 switch (D->getKind()) {
3721 #define ABSTRACT_DECL(TYPE)
3722 #define DECL(TYPE, BASE) \
3724 attachLatestDeclImpl(cast<TYPE##Decl>(D), Latest); \
3726 #include "clang/AST/DeclNodes.inc"
3730 template<typename DeclT>
3731 void ASTDeclReader::markIncompleteDeclChainImpl(Redeclarable<DeclT> *D) {
3732 D->RedeclLink.markIncomplete();
3735 void ASTDeclReader::markIncompleteDeclChainImpl(...) {
3736 llvm_unreachable("markIncompleteDeclChain on non-redeclarable declaration");
3739 void ASTReader::markIncompleteDeclChain(Decl *D) {
3740 switch (D->getKind()) {
3741 #define ABSTRACT_DECL(TYPE)
3742 #define DECL(TYPE, BASE) \
3744 ASTDeclReader::markIncompleteDeclChainImpl(cast<TYPE##Decl>(D)); \
3746 #include "clang/AST/DeclNodes.inc"
3750 /// Read the declaration at the given offset from the AST file.
3751 Decl *ASTReader::ReadDeclRecord(DeclID ID) {
3752 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
3753 SourceLocation DeclLoc;
3754 RecordLocation Loc = DeclCursorForID(ID, DeclLoc);
3755 llvm::BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
3756 // Keep track of where we are in the stream, then jump back there
3757 // after reading this declaration.
3758 SavedStreamPosition SavedPosition(DeclsCursor);
3760 ReadingKindTracker ReadingKind(Read_Decl, *this);
3762 // Note that we are loading a declaration record.
3763 Deserializing ADecl(this);
3765 auto Fail = [](const char *what, llvm::Error &&Err) {
3766 llvm::report_fatal_error(Twine("ASTReader::readDeclRecord failed ") + what +
3767 ": " + toString(std::move(Err)));
3770 if (llvm::Error JumpFailed = DeclsCursor.JumpToBit(Loc.Offset))
3771 Fail("jumping", std::move(JumpFailed));
3772 ASTRecordReader Record(*this, *Loc.F);
3773 ASTDeclReader Reader(*this, Record, Loc, ID, DeclLoc);
3774 Expected<unsigned> MaybeCode = DeclsCursor.ReadCode();
3776 Fail("reading code", MaybeCode.takeError());
3777 unsigned Code = MaybeCode.get();
3779 ASTContext &Context = getContext();
3781 Expected<unsigned> MaybeDeclCode = Record.readRecord(DeclsCursor, Code);
3783 llvm::report_fatal_error(
3784 "ASTReader::readDeclRecord failed reading decl code: " +
3785 toString(MaybeDeclCode.takeError()));
3786 switch ((DeclCode)MaybeDeclCode.get()) {
3787 case DECL_CONTEXT_LEXICAL:
3788 case DECL_CONTEXT_VISIBLE:
3789 llvm_unreachable("Record cannot be de-serialized with readDeclRecord");
3791 D = TypedefDecl::CreateDeserialized(Context, ID);
3793 case DECL_TYPEALIAS:
3794 D = TypeAliasDecl::CreateDeserialized(Context, ID);
3797 D = EnumDecl::CreateDeserialized(Context, ID);
3800 D = RecordDecl::CreateDeserialized(Context, ID);
3802 case DECL_ENUM_CONSTANT:
3803 D = EnumConstantDecl::CreateDeserialized(Context, ID);
3806 D = FunctionDecl::CreateDeserialized(Context, ID);
3808 case DECL_LINKAGE_SPEC:
3809 D = LinkageSpecDecl::CreateDeserialized(Context, ID);
3812 D = ExportDecl::CreateDeserialized(Context, ID);
3815 D = LabelDecl::CreateDeserialized(Context, ID);
3817 case DECL_NAMESPACE:
3818 D = NamespaceDecl::CreateDeserialized(Context, ID);
3820 case DECL_NAMESPACE_ALIAS:
3821 D = NamespaceAliasDecl::CreateDeserialized(Context, ID);
3824 D = UsingDecl::CreateDeserialized(Context, ID);
3826 case DECL_USING_PACK:
3827 D = UsingPackDecl::CreateDeserialized(Context, ID, Record.readInt());
3829 case DECL_USING_SHADOW:
3830 D = UsingShadowDecl::CreateDeserialized(Context, ID);
3832 case DECL_CONSTRUCTOR_USING_SHADOW:
3833 D = ConstructorUsingShadowDecl::CreateDeserialized(Context, ID);
3835 case DECL_USING_DIRECTIVE:
3836 D = UsingDirectiveDecl::CreateDeserialized(Context, ID);
3838 case DECL_UNRESOLVED_USING_VALUE:
3839 D = UnresolvedUsingValueDecl::CreateDeserialized(Context, ID);
3841 case DECL_UNRESOLVED_USING_TYPENAME:
3842 D = UnresolvedUsingTypenameDecl::CreateDeserialized(Context, ID);
3844 case DECL_CXX_RECORD:
3845 D = CXXRecordDecl::CreateDeserialized(Context, ID);
3847 case DECL_CXX_DEDUCTION_GUIDE:
3848 D = CXXDeductionGuideDecl::CreateDeserialized(Context, ID);
3850 case DECL_CXX_METHOD:
3851 D = CXXMethodDecl::CreateDeserialized(Context, ID);
3853 case DECL_CXX_CONSTRUCTOR:
3854 D = CXXConstructorDecl::CreateDeserialized(Context, ID, Record.readInt());
3856 case DECL_CXX_DESTRUCTOR:
3857 D = CXXDestructorDecl::CreateDeserialized(Context, ID);
3859 case DECL_CXX_CONVERSION:
3860 D = CXXConversionDecl::CreateDeserialized(Context, ID);
3862 case DECL_ACCESS_SPEC:
3863 D = AccessSpecDecl::CreateDeserialized(Context, ID);
3866 D = FriendDecl::CreateDeserialized(Context, ID, Record.readInt());
3868 case DECL_FRIEND_TEMPLATE:
3869 D = FriendTemplateDecl::CreateDeserialized(Context, ID);
3871 case DECL_CLASS_TEMPLATE:
3872 D = ClassTemplateDecl::CreateDeserialized(Context, ID);
3874 case DECL_CLASS_TEMPLATE_SPECIALIZATION:
3875 D = ClassTemplateSpecializationDecl::CreateDeserialized(Context, ID);
3877 case DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION:
3878 D = ClassTemplatePartialSpecializationDecl::CreateDeserialized(Context, ID);
3880 case DECL_VAR_TEMPLATE:
3881 D = VarTemplateDecl::CreateDeserialized(Context, ID);
3883 case DECL_VAR_TEMPLATE_SPECIALIZATION:
3884 D = VarTemplateSpecializationDecl::CreateDeserialized(Context, ID);
3886 case DECL_VAR_TEMPLATE_PARTIAL_SPECIALIZATION:
3887 D = VarTemplatePartialSpecializationDecl::CreateDeserialized(Context, ID);
3889 case DECL_CLASS_SCOPE_FUNCTION_SPECIALIZATION:
3890 D = ClassScopeFunctionSpecializationDecl::CreateDeserialized(Context, ID);
3892 case DECL_FUNCTION_TEMPLATE:
3893 D = FunctionTemplateDecl::CreateDeserialized(Context, ID);
3895 case DECL_TEMPLATE_TYPE_PARM: {
3896 bool HasTypeConstraint = Record.readInt();
3897 D = TemplateTypeParmDecl::CreateDeserialized(Context, ID,
3901 case DECL_NON_TYPE_TEMPLATE_PARM: {
3902 bool HasTypeConstraint = Record.readInt();
3903 D = NonTypeTemplateParmDecl::CreateDeserialized(Context, ID,
3907 case DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK: {
3908 bool HasTypeConstraint = Record.readInt();
3909 D = NonTypeTemplateParmDecl::CreateDeserialized(Context, ID,
3914 case DECL_TEMPLATE_TEMPLATE_PARM:
3915 D = TemplateTemplateParmDecl::CreateDeserialized(Context, ID);
3917 case DECL_EXPANDED_TEMPLATE_TEMPLATE_PARM_PACK:
3918 D = TemplateTemplateParmDecl::CreateDeserialized(Context, ID,
3921 case DECL_TYPE_ALIAS_TEMPLATE:
3922 D = TypeAliasTemplateDecl::CreateDeserialized(Context, ID);
3925 D = ConceptDecl::CreateDeserialized(Context, ID);
3927 case DECL_REQUIRES_EXPR_BODY:
3928 D = RequiresExprBodyDecl::CreateDeserialized(Context, ID);
3930 case DECL_STATIC_ASSERT:
3931 D = StaticAssertDecl::CreateDeserialized(Context, ID);
3933 case DECL_OBJC_METHOD:
3934 D = ObjCMethodDecl::CreateDeserialized(Context, ID);
3936 case DECL_OBJC_INTERFACE:
3937 D = ObjCInterfaceDecl::CreateDeserialized(Context, ID);
3939 case DECL_OBJC_IVAR:
3940 D = ObjCIvarDecl::CreateDeserialized(Context, ID);
3942 case DECL_OBJC_PROTOCOL:
3943 D = ObjCProtocolDecl::CreateDeserialized(Context, ID);
3945 case DECL_OBJC_AT_DEFS_FIELD:
3946 D = ObjCAtDefsFieldDecl::CreateDeserialized(Context, ID);
3948 case DECL_OBJC_CATEGORY:
3949 D = ObjCCategoryDecl::CreateDeserialized(Context, ID);
3951 case DECL_OBJC_CATEGORY_IMPL:
3952 D = ObjCCategoryImplDecl::CreateDeserialized(Context, ID);
3954 case DECL_OBJC_IMPLEMENTATION:
3955 D = ObjCImplementationDecl::CreateDeserialized(Context, ID);
3957 case DECL_OBJC_COMPATIBLE_ALIAS:
3958 D = ObjCCompatibleAliasDecl::CreateDeserialized(Context, ID);
3960 case DECL_OBJC_PROPERTY:
3961 D = ObjCPropertyDecl::CreateDeserialized(Context, ID);
3963 case DECL_OBJC_PROPERTY_IMPL:
3964 D = ObjCPropertyImplDecl::CreateDeserialized(Context, ID);
3967 D = FieldDecl::CreateDeserialized(Context, ID);
3969 case DECL_INDIRECTFIELD:
3970 D = IndirectFieldDecl::CreateDeserialized(Context, ID);
3973 D = VarDecl::CreateDeserialized(Context, ID);
3975 case DECL_IMPLICIT_PARAM:
3976 D = ImplicitParamDecl::CreateDeserialized(Context, ID);
3979 D = ParmVarDecl::CreateDeserialized(Context, ID);
3981 case DECL_DECOMPOSITION:
3982 D = DecompositionDecl::CreateDeserialized(Context, ID, Record.readInt());
3985 D = BindingDecl::CreateDeserialized(Context, ID);
3987 case DECL_FILE_SCOPE_ASM:
3988 D = FileScopeAsmDecl::CreateDeserialized(Context, ID);
3991 D = BlockDecl::CreateDeserialized(Context, ID);
3993 case DECL_MS_PROPERTY:
3994 D = MSPropertyDecl::CreateDeserialized(Context, ID);
3997 D = MSGuidDecl::CreateDeserialized(Context, ID);
4000 D = CapturedDecl::CreateDeserialized(Context, ID, Record.readInt());
4002 case DECL_CXX_BASE_SPECIFIERS:
4003 Error("attempt to read a C++ base-specifier record as a declaration");
4005 case DECL_CXX_CTOR_INITIALIZERS:
4006 Error("attempt to read a C++ ctor initializer record as a declaration");
4009 // Note: last entry of the ImportDecl record is the number of stored source
4011 D = ImportDecl::CreateDeserialized(Context, ID, Record.back());
4013 case DECL_OMP_THREADPRIVATE:
4014 D = OMPThreadPrivateDecl::CreateDeserialized(Context, ID, Record.readInt());
4016 case DECL_OMP_ALLOCATE: {
4017 unsigned NumVars = Record.readInt();
4018 unsigned NumClauses = Record.readInt();
4019 D = OMPAllocateDecl::CreateDeserialized(Context, ID, NumVars, NumClauses);
4022 case DECL_OMP_REQUIRES:
4023 D = OMPRequiresDecl::CreateDeserialized(Context, ID, Record.readInt());
4025 case DECL_OMP_DECLARE_REDUCTION:
4026 D = OMPDeclareReductionDecl::CreateDeserialized(Context, ID);
4028 case DECL_OMP_DECLARE_MAPPER:
4029 D = OMPDeclareMapperDecl::CreateDeserialized(Context, ID, Record.readInt());
4031 case DECL_OMP_CAPTUREDEXPR:
4032 D = OMPCapturedExprDecl::CreateDeserialized(Context, ID);
4034 case DECL_PRAGMA_COMMENT:
4035 D = PragmaCommentDecl::CreateDeserialized(Context, ID, Record.readInt());
4037 case DECL_PRAGMA_DETECT_MISMATCH:
4038 D = PragmaDetectMismatchDecl::CreateDeserialized(Context, ID,
4042 D = EmptyDecl::CreateDeserialized(Context, ID);
4044 case DECL_LIFETIME_EXTENDED_TEMPORARY:
4045 D = LifetimeExtendedTemporaryDecl::CreateDeserialized(Context, ID);
4047 case DECL_OBJC_TYPE_PARAM:
4048 D = ObjCTypeParamDecl::CreateDeserialized(Context, ID);
4052 assert(D && "Unknown declaration reading AST file");
4053 LoadedDecl(Index, D);
4054 // Set the DeclContext before doing any deserialization, to make sure internal
4055 // calls to Decl::getASTContext() by Decl's methods will find the
4056 // TranslationUnitDecl without crashing.
4057 D->setDeclContext(Context.getTranslationUnitDecl());
4060 // If this declaration is also a declaration context, get the
4061 // offsets for its tables of lexical and visible declarations.
4062 if (auto *DC = dyn_cast<DeclContext>(D)) {
4063 std::pair<uint64_t, uint64_t> Offsets = Reader.VisitDeclContext(DC);
4064 if (Offsets.first &&
4065 ReadLexicalDeclContextStorage(*Loc.F, DeclsCursor, Offsets.first, DC))
4067 if (Offsets.second &&
4068 ReadVisibleDeclContextStorage(*Loc.F, DeclsCursor, Offsets.second, ID))
4071 assert(Record.getIdx() == Record.size());
4073 // Load any relevant update records.
4074 PendingUpdateRecords.push_back(
4075 PendingUpdateRecord(ID, D, /*JustLoaded=*/true));
4077 // Load the categories after recursive loading is finished.
4078 if (auto *Class = dyn_cast<ObjCInterfaceDecl>(D))
4079 // If we already have a definition when deserializing the ObjCInterfaceDecl,
4080 // we put the Decl in PendingDefinitions so we can pull the categories here.
4081 if (Class->isThisDeclarationADefinition() ||
4082 PendingDefinitions.count(Class))
4083 loadObjCCategories(ID, Class);
4085 // If we have deserialized a declaration that has a definition the
4086 // AST consumer might need to know about, queue it.
4087 // We don't pass it to the consumer immediately because we may be in recursive
4088 // loading, and some declarations may still be initializing.
4089 PotentiallyInterestingDecls.push_back(
4090 InterestingDecl(D, Reader.hasPendingBody()));
4095 void ASTReader::PassInterestingDeclsToConsumer() {
4098 if (PassingDeclsToConsumer)
4101 // Guard variable to avoid recursively redoing the process of passing
4102 // decls to consumer.
4103 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
4106 // Ensure that we've loaded all potentially-interesting declarations
4107 // that need to be eagerly loaded.
4108 for (auto ID : EagerlyDeserializedDecls)
4110 EagerlyDeserializedDecls.clear();
4112 while (!PotentiallyInterestingDecls.empty()) {
4113 InterestingDecl D = PotentiallyInterestingDecls.front();
4114 PotentiallyInterestingDecls.pop_front();
4115 if (isConsumerInterestedIn(getContext(), D.getDecl(), D.hasPendingBody()))
4116 PassInterestingDeclToConsumer(D.getDecl());
4120 void ASTReader::loadDeclUpdateRecords(PendingUpdateRecord &Record) {
4121 // The declaration may have been modified by files later in the chain.
4122 // If this is the case, read the record containing the updates from each file
4123 // and pass it to ASTDeclReader to make the modifications.
4124 serialization::GlobalDeclID ID = Record.ID;
4126 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
4127 DeclUpdateOffsetsMap::iterator UpdI = DeclUpdateOffsets.find(ID);
4129 SmallVector<serialization::DeclID, 8> PendingLazySpecializationIDs;
4131 if (UpdI != DeclUpdateOffsets.end()) {
4132 auto UpdateOffsets = std::move(UpdI->second);
4133 DeclUpdateOffsets.erase(UpdI);
4135 // Check if this decl was interesting to the consumer. If we just loaded
4136 // the declaration, then we know it was interesting and we skip the call
4137 // to isConsumerInterestedIn because it is unsafe to call in the
4138 // current ASTReader state.
4139 bool WasInteresting =
4140 Record.JustLoaded || isConsumerInterestedIn(getContext(), D, false);
4141 for (auto &FileAndOffset : UpdateOffsets) {
4142 ModuleFile *F = FileAndOffset.first;
4143 uint64_t Offset = FileAndOffset.second;
4144 llvm::BitstreamCursor &Cursor = F->DeclsCursor;
4145 SavedStreamPosition SavedPosition(Cursor);
4146 if (llvm::Error JumpFailed = Cursor.JumpToBit(Offset))
4147 // FIXME don't do a fatal error.
4148 llvm::report_fatal_error(
4149 "ASTReader::loadDeclUpdateRecords failed jumping: " +
4150 toString(std::move(JumpFailed)));
4151 Expected<unsigned> MaybeCode = Cursor.ReadCode();
4153 llvm::report_fatal_error(
4154 "ASTReader::loadDeclUpdateRecords failed reading code: " +
4155 toString(MaybeCode.takeError()));
4156 unsigned Code = MaybeCode.get();
4157 ASTRecordReader Record(*this, *F);
4158 if (Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code))
4159 assert(MaybeRecCode.get() == DECL_UPDATES &&
4160 "Expected DECL_UPDATES record!");
4162 llvm::report_fatal_error(
4163 "ASTReader::loadDeclUpdateRecords failed reading rec code: " +
4164 toString(MaybeCode.takeError()));
4166 ASTDeclReader Reader(*this, Record, RecordLocation(F, Offset), ID,
4168 Reader.UpdateDecl(D, PendingLazySpecializationIDs);
4170 // We might have made this declaration interesting. If so, remember that
4171 // we need to hand it off to the consumer.
4172 if (!WasInteresting &&
4173 isConsumerInterestedIn(getContext(), D, Reader.hasPendingBody())) {
4174 PotentiallyInterestingDecls.push_back(
4175 InterestingDecl(D, Reader.hasPendingBody()));
4176 WasInteresting = true;
4180 // Add the lazy specializations to the template.
4181 assert((PendingLazySpecializationIDs.empty() || isa<ClassTemplateDecl>(D) ||
4182 isa<FunctionTemplateDecl>(D) || isa<VarTemplateDecl>(D)) &&
4183 "Must not have pending specializations");
4184 if (auto *CTD = dyn_cast<ClassTemplateDecl>(D))
4185 ASTDeclReader::AddLazySpecializations(CTD, PendingLazySpecializationIDs);
4186 else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
4187 ASTDeclReader::AddLazySpecializations(FTD, PendingLazySpecializationIDs);
4188 else if (auto *VTD = dyn_cast<VarTemplateDecl>(D))
4189 ASTDeclReader::AddLazySpecializations(VTD, PendingLazySpecializationIDs);
4190 PendingLazySpecializationIDs.clear();
4192 // Load the pending visible updates for this decl context, if it has any.
4193 auto I = PendingVisibleUpdates.find(ID);
4194 if (I != PendingVisibleUpdates.end()) {
4195 auto VisibleUpdates = std::move(I->second);
4196 PendingVisibleUpdates.erase(I);
4198 auto *DC = cast<DeclContext>(D)->getPrimaryContext();
4199 for (const auto &Update : VisibleUpdates)
4200 Lookups[DC].Table.add(
4201 Update.Mod, Update.Data,
4202 reader::ASTDeclContextNameLookupTrait(*this, *Update.Mod));
4203 DC->setHasExternalVisibleStorage(true);
4207 void ASTReader::loadPendingDeclChain(Decl *FirstLocal, uint64_t LocalOffset) {
4208 // Attach FirstLocal to the end of the decl chain.
4209 Decl *CanonDecl = FirstLocal->getCanonicalDecl();
4210 if (FirstLocal != CanonDecl) {
4211 Decl *PrevMostRecent = ASTDeclReader::getMostRecentDecl(CanonDecl);
4212 ASTDeclReader::attachPreviousDecl(
4213 *this, FirstLocal, PrevMostRecent ? PrevMostRecent : CanonDecl,
4218 ASTDeclReader::attachLatestDecl(CanonDecl, FirstLocal);
4222 // Load the list of other redeclarations from this module file.
4223 ModuleFile *M = getOwningModuleFile(FirstLocal);
4224 assert(M && "imported decl from no module file");
4226 llvm::BitstreamCursor &Cursor = M->DeclsCursor;
4227 SavedStreamPosition SavedPosition(Cursor);
4228 if (llvm::Error JumpFailed = Cursor.JumpToBit(LocalOffset))
4229 llvm::report_fatal_error(
4230 "ASTReader::loadPendingDeclChain failed jumping: " +
4231 toString(std::move(JumpFailed)));
4234 Expected<unsigned> MaybeCode = Cursor.ReadCode();
4236 llvm::report_fatal_error(
4237 "ASTReader::loadPendingDeclChain failed reading code: " +
4238 toString(MaybeCode.takeError()));
4239 unsigned Code = MaybeCode.get();
4240 if (Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record))
4241 assert(MaybeRecCode.get() == LOCAL_REDECLARATIONS &&
4242 "expected LOCAL_REDECLARATIONS record!");
4244 llvm::report_fatal_error(
4245 "ASTReader::loadPendingDeclChain failed reading rec code: " +
4246 toString(MaybeCode.takeError()));
4248 // FIXME: We have several different dispatches on decl kind here; maybe
4249 // we should instead generate one loop per kind and dispatch up-front?
4250 Decl *MostRecent = FirstLocal;
4251 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
4252 auto *D = GetLocalDecl(*M, Record[N - I - 1]);
4253 ASTDeclReader::attachPreviousDecl(*this, D, MostRecent, CanonDecl);
4256 ASTDeclReader::attachLatestDecl(CanonDecl, MostRecent);
4261 /// Given an ObjC interface, goes through the modules and links to the
4262 /// interface all the categories for it.
4263 class ObjCCategoriesVisitor {
4265 ObjCInterfaceDecl *Interface;
4266 llvm::SmallPtrSetImpl<ObjCCategoryDecl *> &Deserialized;
4267 ObjCCategoryDecl *Tail = nullptr;
4268 llvm::DenseMap<DeclarationName, ObjCCategoryDecl *> NameCategoryMap;
4269 serialization::GlobalDeclID InterfaceID;
4270 unsigned PreviousGeneration;
4272 void add(ObjCCategoryDecl *Cat) {
4273 // Only process each category once.
4274 if (!Deserialized.erase(Cat))
4277 // Check for duplicate categories.
4278 if (Cat->getDeclName()) {
4279 ObjCCategoryDecl *&Existing = NameCategoryMap[Cat->getDeclName()];
4281 Reader.getOwningModuleFile(Existing)
4282 != Reader.getOwningModuleFile(Cat)) {
4283 // FIXME: We should not warn for duplicates in diamond:
4291 // If there are duplicates in ML/MR, there will be warning when
4292 // creating MB *and* when importing MB. We should not warn when
4294 Reader.Diag(Cat->getLocation(), diag::warn_dup_category_def)
4295 << Interface->getDeclName() << Cat->getDeclName();
4296 Reader.Diag(Existing->getLocation(), diag::note_previous_definition);
4297 } else if (!Existing) {
4298 // Record this category.
4303 // Add this category to the end of the chain.
4305 ASTDeclReader::setNextObjCCategory(Tail, Cat);
4307 Interface->setCategoryListRaw(Cat);
4312 ObjCCategoriesVisitor(ASTReader &Reader,
4313 ObjCInterfaceDecl *Interface,
4314 llvm::SmallPtrSetImpl<ObjCCategoryDecl *> &Deserialized,
4315 serialization::GlobalDeclID InterfaceID,
4316 unsigned PreviousGeneration)
4317 : Reader(Reader), Interface(Interface), Deserialized(Deserialized),
4318 InterfaceID(InterfaceID), PreviousGeneration(PreviousGeneration) {
4319 // Populate the name -> category map with the set of known categories.
4320 for (auto *Cat : Interface->known_categories()) {
4321 if (Cat->getDeclName())
4322 NameCategoryMap[Cat->getDeclName()] = Cat;
4324 // Keep track of the tail of the category list.
4329 bool operator()(ModuleFile &M) {
4330 // If we've loaded all of the category information we care about from
4331 // this module file, we're done.
4332 if (M.Generation <= PreviousGeneration)
4335 // Map global ID of the definition down to the local ID used in this
4336 // module file. If there is no such mapping, we'll find nothing here
4337 // (or in any module it imports).
4338 DeclID LocalID = Reader.mapGlobalIDToModuleFileGlobalID(M, InterfaceID);
4342 // Perform a binary search to find the local redeclarations for this
4343 // declaration (if any).
4344 const ObjCCategoriesInfo Compare = { LocalID, 0 };
4345 const ObjCCategoriesInfo *Result
4346 = std::lower_bound(M.ObjCCategoriesMap,
4347 M.ObjCCategoriesMap + M.LocalNumObjCCategoriesInMap,
4349 if (Result == M.ObjCCategoriesMap + M.LocalNumObjCCategoriesInMap ||
4350 Result->DefinitionID != LocalID) {
4351 // We didn't find anything. If the class definition is in this module
4352 // file, then the module files it depends on cannot have any categories,
4353 // so suppress further lookup.
4354 return Reader.isDeclIDFromModule(InterfaceID, M);
4357 // We found something. Dig out all of the categories.
4358 unsigned Offset = Result->Offset;
4359 unsigned N = M.ObjCCategories[Offset];
4360 M.ObjCCategories[Offset++] = 0; // Don't try to deserialize again
4361 for (unsigned I = 0; I != N; ++I)
4362 add(cast_or_null<ObjCCategoryDecl>(
4363 Reader.GetLocalDecl(M, M.ObjCCategories[Offset++])));
4370 void ASTReader::loadObjCCategories(serialization::GlobalDeclID ID,
4371 ObjCInterfaceDecl *D,
4372 unsigned PreviousGeneration) {
4373 ObjCCategoriesVisitor Visitor(*this, D, CategoriesDeserialized, ID,
4374 PreviousGeneration);
4375 ModuleMgr.visit(Visitor);
4378 template<typename DeclT, typename Fn>
4379 static void forAllLaterRedecls(DeclT *D, Fn F) {
4382 // Check whether we've already merged D into its redeclaration chain.
4383 // MostRecent may or may not be nullptr if D has not been merged. If
4384 // not, walk the merged redecl chain and see if it's there.
4385 auto *MostRecent = D->getMostRecentDecl();
4387 for (auto *Redecl = MostRecent; Redecl && !Found;
4388 Redecl = Redecl->getPreviousDecl())
4389 Found = (Redecl == D);
4391 // If this declaration is merged, apply the functor to all later decls.
4393 for (auto *Redecl = MostRecent; Redecl != D;
4394 Redecl = Redecl->getPreviousDecl())
4399 void ASTDeclReader::UpdateDecl(Decl *D,
4400 llvm::SmallVectorImpl<serialization::DeclID> &PendingLazySpecializationIDs) {
4401 while (Record.getIdx() < Record.size()) {
4402 switch ((DeclUpdateKind)Record.readInt()) {
4403 case UPD_CXX_ADDED_IMPLICIT_MEMBER: {
4404 auto *RD = cast<CXXRecordDecl>(D);
4405 // FIXME: If we also have an update record for instantiating the
4406 // definition of D, we need that to happen before we get here.
4407 Decl *MD = Record.readDecl();
4408 assert(MD && "couldn't read decl from update record");
4409 // FIXME: We should call addHiddenDecl instead, to add the member
4410 // to its DeclContext.
4411 RD->addedMember(MD);
4415 case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
4416 // It will be added to the template's lazy specialization set.
4417 PendingLazySpecializationIDs.push_back(readDeclID());
4420 case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE: {
4421 auto *Anon = readDeclAs<NamespaceDecl>();
4423 // Each module has its own anonymous namespace, which is disjoint from
4424 // any other module's anonymous namespaces, so don't attach the anonymous
4425 // namespace at all.
4426 if (!Record.isModule()) {
4427 if (auto *TU = dyn_cast<TranslationUnitDecl>(D))
4428 TU->setAnonymousNamespace(Anon);
4430 cast<NamespaceDecl>(D)->setAnonymousNamespace(Anon);
4435 case UPD_CXX_ADDED_VAR_DEFINITION: {
4436 auto *VD = cast<VarDecl>(D);
4437 VD->NonParmVarDeclBits.IsInline = Record.readInt();
4438 VD->NonParmVarDeclBits.IsInlineSpecified = Record.readInt();
4439 uint64_t Val = Record.readInt();
4440 if (Val && !VD->getInit()) {
4441 VD->setInit(Record.readExpr());
4442 if (Val > 1) { // IsInitKnownICE = 1, IsInitNotICE = 2, IsInitICE = 3
4443 EvaluatedStmt *Eval = VD->ensureEvaluatedStmt();
4444 Eval->CheckedICE = true;
4445 Eval->IsICE = Val == 3;
4451 case UPD_CXX_POINT_OF_INSTANTIATION: {
4452 SourceLocation POI = Record.readSourceLocation();
4453 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D)) {
4454 VTSD->setPointOfInstantiation(POI);
4455 } else if (auto *VD = dyn_cast<VarDecl>(D)) {
4456 VD->getMemberSpecializationInfo()->setPointOfInstantiation(POI);
4458 auto *FD = cast<FunctionDecl>(D);
4459 if (auto *FTSInfo = FD->TemplateOrSpecialization
4460 .dyn_cast<FunctionTemplateSpecializationInfo *>())
4461 FTSInfo->setPointOfInstantiation(POI);
4463 FD->TemplateOrSpecialization.get<MemberSpecializationInfo *>()
4464 ->setPointOfInstantiation(POI);
4469 case UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT: {
4470 auto *Param = cast<ParmVarDecl>(D);
4472 // We have to read the default argument regardless of whether we use it
4473 // so that hypothetical further update records aren't messed up.
4474 // TODO: Add a function to skip over the next expr record.
4475 auto *DefaultArg = Record.readExpr();
4477 // Only apply the update if the parameter still has an uninstantiated
4478 // default argument.
4479 if (Param->hasUninstantiatedDefaultArg())
4480 Param->setDefaultArg(DefaultArg);
4484 case UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER: {
4485 auto *FD = cast<FieldDecl>(D);
4486 auto *DefaultInit = Record.readExpr();
4488 // Only apply the update if the field still has an uninstantiated
4489 // default member initializer.
4490 if (FD->hasInClassInitializer() && !FD->getInClassInitializer()) {
4492 FD->setInClassInitializer(DefaultInit);
4494 // Instantiation failed. We can get here if we serialized an AST for
4495 // an invalid program.
4496 FD->removeInClassInitializer();
4501 case UPD_CXX_ADDED_FUNCTION_DEFINITION: {
4502 auto *FD = cast<FunctionDecl>(D);
4503 if (Reader.PendingBodies[FD]) {
4504 // FIXME: Maybe check for ODR violations.
4505 // It's safe to stop now because this update record is always last.
4509 if (Record.readInt()) {
4510 // Maintain AST consistency: any later redeclarations of this function
4511 // are inline if this one is. (We might have merged another declaration
4513 forAllLaterRedecls(FD, [](FunctionDecl *FD) {
4514 FD->setImplicitlyInline();
4517 FD->setInnerLocStart(readSourceLocation());
4518 ReadFunctionDefinition(FD);
4519 assert(Record.getIdx() == Record.size() && "lazy body must be last");
4523 case UPD_CXX_INSTANTIATED_CLASS_DEFINITION: {
4524 auto *RD = cast<CXXRecordDecl>(D);
4525 auto *OldDD = RD->getCanonicalDecl()->DefinitionData;
4526 bool HadRealDefinition =
4527 OldDD && (OldDD->Definition != RD ||
4528 !Reader.PendingFakeDefinitionData.count(OldDD));
4529 RD->setParamDestroyedInCallee(Record.readInt());
4530 RD->setArgPassingRestrictions(
4531 (RecordDecl::ArgPassingKind)Record.readInt());
4532 ReadCXXRecordDefinition(RD, /*Update*/true);
4534 // Visible update is handled separately.
4535 uint64_t LexicalOffset = ReadLocalOffset();
4536 if (!HadRealDefinition && LexicalOffset) {
4537 Record.readLexicalDeclContextStorage(LexicalOffset, RD);
4538 Reader.PendingFakeDefinitionData.erase(OldDD);
4541 auto TSK = (TemplateSpecializationKind)Record.readInt();
4542 SourceLocation POI = readSourceLocation();
4543 if (MemberSpecializationInfo *MSInfo =
4544 RD->getMemberSpecializationInfo()) {
4545 MSInfo->setTemplateSpecializationKind(TSK);
4546 MSInfo->setPointOfInstantiation(POI);
4548 auto *Spec = cast<ClassTemplateSpecializationDecl>(RD);
4549 Spec->setTemplateSpecializationKind(TSK);
4550 Spec->setPointOfInstantiation(POI);
4552 if (Record.readInt()) {
4554 readDeclAs<ClassTemplatePartialSpecializationDecl>();
4555 SmallVector<TemplateArgument, 8> TemplArgs;
4556 Record.readTemplateArgumentList(TemplArgs);
4557 auto *TemplArgList = TemplateArgumentList::CreateCopy(
4558 Reader.getContext(), TemplArgs);
4560 // FIXME: If we already have a partial specialization set,
4561 // check that it matches.
4562 if (!Spec->getSpecializedTemplateOrPartial()
4563 .is<ClassTemplatePartialSpecializationDecl *>())
4564 Spec->setInstantiationOf(PartialSpec, TemplArgList);
4568 RD->setTagKind((TagTypeKind)Record.readInt());
4569 RD->setLocation(readSourceLocation());
4570 RD->setLocStart(readSourceLocation());
4571 RD->setBraceRange(readSourceRange());
4573 if (Record.readInt()) {
4575 Record.readAttributes(Attrs);
4576 // If the declaration already has attributes, we assume that some other
4577 // AST file already loaded them.
4579 D->setAttrsImpl(Attrs, Reader.getContext());
4584 case UPD_CXX_RESOLVED_DTOR_DELETE: {
4585 // Set the 'operator delete' directly to avoid emitting another update
4587 auto *Del = readDeclAs<FunctionDecl>();
4588 auto *First = cast<CXXDestructorDecl>(D->getCanonicalDecl());
4589 auto *ThisArg = Record.readExpr();
4590 // FIXME: Check consistency if we have an old and new operator delete.
4591 if (!First->OperatorDelete) {
4592 First->OperatorDelete = Del;
4593 First->OperatorDeleteThisArg = ThisArg;
4598 case UPD_CXX_RESOLVED_EXCEPTION_SPEC: {
4599 SmallVector<QualType, 8> ExceptionStorage;
4600 auto ESI = Record.readExceptionSpecInfo(ExceptionStorage);
4602 // Update this declaration's exception specification, if needed.
4603 auto *FD = cast<FunctionDecl>(D);
4604 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
4605 // FIXME: If the exception specification is already present, check that it
4607 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
4608 FD->setType(Reader.getContext().getFunctionType(
4609 FPT->getReturnType(), FPT->getParamTypes(),
4610 FPT->getExtProtoInfo().withExceptionSpec(ESI)));
4612 // When we get to the end of deserializing, see if there are other decls
4613 // that we need to propagate this exception specification onto.
4614 Reader.PendingExceptionSpecUpdates.insert(
4615 std::make_pair(FD->getCanonicalDecl(), FD));
4620 case UPD_CXX_DEDUCED_RETURN_TYPE: {
4621 auto *FD = cast<FunctionDecl>(D);
4622 QualType DeducedResultType = Record.readType();
4623 Reader.PendingDeducedTypeUpdates.insert(
4624 {FD->getCanonicalDecl(), DeducedResultType});
4628 case UPD_DECL_MARKED_USED:
4629 // Maintain AST consistency: any later redeclarations are used too.
4630 D->markUsed(Reader.getContext());
4633 case UPD_MANGLING_NUMBER:
4634 Reader.getContext().setManglingNumber(cast<NamedDecl>(D),
4638 case UPD_STATIC_LOCAL_NUMBER:
4639 Reader.getContext().setStaticLocalNumber(cast<VarDecl>(D),
4643 case UPD_DECL_MARKED_OPENMP_THREADPRIVATE:
4644 D->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
4645 Reader.getContext(), readSourceRange(),
4646 AttributeCommonInfo::AS_Pragma));
4649 case UPD_DECL_MARKED_OPENMP_ALLOCATE: {
4650 auto AllocatorKind =
4651 static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(Record.readInt());
4652 Expr *Allocator = Record.readExpr();
4653 SourceRange SR = readSourceRange();
4654 D->addAttr(OMPAllocateDeclAttr::CreateImplicit(
4655 Reader.getContext(), AllocatorKind, Allocator, SR,
4656 AttributeCommonInfo::AS_Pragma));
4660 case UPD_DECL_EXPORTED: {
4661 unsigned SubmoduleID = readSubmoduleID();
4662 auto *Exported = cast<NamedDecl>(D);
4663 Module *Owner = SubmoduleID ? Reader.getSubmodule(SubmoduleID) : nullptr;
4664 Reader.getContext().mergeDefinitionIntoModule(Exported, Owner);
4665 Reader.PendingMergedDefinitionsToDeduplicate.insert(Exported);
4669 case UPD_DECL_MARKED_OPENMP_DECLARETARGET: {
4670 OMPDeclareTargetDeclAttr::MapTypeTy MapType =
4671 static_cast<OMPDeclareTargetDeclAttr::MapTypeTy>(Record.readInt());
4672 OMPDeclareTargetDeclAttr::DevTypeTy DevType =
4673 static_cast<OMPDeclareTargetDeclAttr::DevTypeTy>(Record.readInt());
4674 D->addAttr(OMPDeclareTargetDeclAttr::CreateImplicit(
4675 Reader.getContext(), MapType, DevType, readSourceRange(),
4676 AttributeCommonInfo::AS_Pragma));
4680 case UPD_ADDED_ATTR_TO_RECORD:
4682 Record.readAttributes(Attrs);
4683 assert(Attrs.size() == 1);
4684 D->addAttr(Attrs[0]);