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 VisitIndirectFieldDecl(IndirectFieldDecl *FD);
369 RedeclarableResult VisitVarDeclImpl(VarDecl *D);
370 void VisitVarDecl(VarDecl *VD) { VisitVarDeclImpl(VD); }
371 void VisitImplicitParamDecl(ImplicitParamDecl *PD);
372 void VisitParmVarDecl(ParmVarDecl *PD);
373 void VisitDecompositionDecl(DecompositionDecl *DD);
374 void VisitBindingDecl(BindingDecl *BD);
375 void VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
376 DeclID VisitTemplateDecl(TemplateDecl *D);
377 void VisitConceptDecl(ConceptDecl *D);
378 void VisitRequiresExprBodyDecl(RequiresExprBodyDecl *D);
379 RedeclarableResult VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D);
380 void VisitClassTemplateDecl(ClassTemplateDecl *D);
381 void VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D);
382 void VisitVarTemplateDecl(VarTemplateDecl *D);
383 void VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
384 void VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
385 void VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D);
386 void VisitUsingDecl(UsingDecl *D);
387 void VisitUsingPackDecl(UsingPackDecl *D);
388 void VisitUsingShadowDecl(UsingShadowDecl *D);
389 void VisitConstructorUsingShadowDecl(ConstructorUsingShadowDecl *D);
390 void VisitLinkageSpecDecl(LinkageSpecDecl *D);
391 void VisitExportDecl(ExportDecl *D);
392 void VisitFileScopeAsmDecl(FileScopeAsmDecl *AD);
393 void VisitImportDecl(ImportDecl *D);
394 void VisitAccessSpecDecl(AccessSpecDecl *D);
395 void VisitFriendDecl(FriendDecl *D);
396 void VisitFriendTemplateDecl(FriendTemplateDecl *D);
397 void VisitStaticAssertDecl(StaticAssertDecl *D);
398 void VisitBlockDecl(BlockDecl *BD);
399 void VisitCapturedDecl(CapturedDecl *CD);
400 void VisitEmptyDecl(EmptyDecl *D);
401 void VisitLifetimeExtendedTemporaryDecl(LifetimeExtendedTemporaryDecl *D);
403 std::pair<uint64_t, uint64_t> VisitDeclContext(DeclContext *DC);
406 RedeclarableResult VisitRedeclarable(Redeclarable<T> *D);
409 void mergeRedeclarable(Redeclarable<T> *D, RedeclarableResult &Redecl,
410 DeclID TemplatePatternID = 0);
413 void mergeRedeclarable(Redeclarable<T> *D, T *Existing,
414 RedeclarableResult &Redecl,
415 DeclID TemplatePatternID = 0);
418 void mergeMergeable(Mergeable<T> *D);
420 void mergeMergeable(LifetimeExtendedTemporaryDecl *D);
422 void mergeTemplatePattern(RedeclarableTemplateDecl *D,
423 RedeclarableTemplateDecl *Existing,
424 DeclID DsID, bool IsKeyDecl);
426 ObjCTypeParamList *ReadObjCTypeParamList();
428 // FIXME: Reorder according to DeclNodes.td?
429 void VisitObjCMethodDecl(ObjCMethodDecl *D);
430 void VisitObjCTypeParamDecl(ObjCTypeParamDecl *D);
431 void VisitObjCContainerDecl(ObjCContainerDecl *D);
432 void VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
433 void VisitObjCIvarDecl(ObjCIvarDecl *D);
434 void VisitObjCProtocolDecl(ObjCProtocolDecl *D);
435 void VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D);
436 void VisitObjCCategoryDecl(ObjCCategoryDecl *D);
437 void VisitObjCImplDecl(ObjCImplDecl *D);
438 void VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
439 void VisitObjCImplementationDecl(ObjCImplementationDecl *D);
440 void VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *D);
441 void VisitObjCPropertyDecl(ObjCPropertyDecl *D);
442 void VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D);
443 void VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D);
444 void VisitOMPAllocateDecl(OMPAllocateDecl *D);
445 void VisitOMPDeclareReductionDecl(OMPDeclareReductionDecl *D);
446 void VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D);
447 void VisitOMPRequiresDecl(OMPRequiresDecl *D);
448 void VisitOMPCapturedExprDecl(OMPCapturedExprDecl *D);
455 /// Iterator over the redeclarations of a declaration that have already
456 /// been merged into the same redeclaration chain.
457 template<typename DeclT>
458 class MergedRedeclIterator {
460 DeclT *Canonical = nullptr;
461 DeclT *Current = nullptr;
464 MergedRedeclIterator() = default;
465 MergedRedeclIterator(DeclT *Start) : Start(Start), Current(Start) {}
467 DeclT *operator*() { return Current; }
469 MergedRedeclIterator &operator++() {
470 if (Current->isFirstDecl()) {
472 Current = Current->getMostRecentDecl();
474 Current = Current->getPreviousDecl();
476 // If we started in the merged portion, we'll reach our start position
477 // eventually. Otherwise, we'll never reach it, but the second declaration
478 // we reached was the canonical declaration, so stop when we see that one
480 if (Current == Start || Current == Canonical)
485 friend bool operator!=(const MergedRedeclIterator &A,
486 const MergedRedeclIterator &B) {
487 return A.Current != B.Current;
493 template <typename DeclT>
494 static llvm::iterator_range<MergedRedeclIterator<DeclT>>
495 merged_redecls(DeclT *D) {
496 return llvm::make_range(MergedRedeclIterator<DeclT>(D),
497 MergedRedeclIterator<DeclT>());
500 uint64_t ASTDeclReader::GetCurrentCursorOffset() {
501 return Loc.F->DeclsCursor.GetCurrentBitNo() + Loc.F->GlobalBitOffset;
504 void ASTDeclReader::ReadFunctionDefinition(FunctionDecl *FD) {
505 if (Record.readInt()) {
506 Reader.DefinitionSource[FD] = Loc.F->Kind == ModuleKind::MK_MainFile;
507 if (Reader.getContext().getLangOpts().BuildingPCHWithObjectFile &&
508 Reader.DeclIsFromPCHWithObjectFile(FD))
509 Reader.DefinitionSource[FD] = true;
511 if (auto *CD = dyn_cast<CXXConstructorDecl>(FD)) {
512 CD->setNumCtorInitializers(Record.readInt());
513 if (CD->getNumCtorInitializers())
514 CD->CtorInitializers = ReadGlobalOffset();
516 // Store the offset of the body so we can lazily load it later.
517 Reader.PendingBodies[FD] = GetCurrentCursorOffset();
518 HasPendingBody = true;
521 void ASTDeclReader::Visit(Decl *D) {
522 DeclVisitor<ASTDeclReader, void>::Visit(D);
524 // At this point we have deserialized and merged the decl and it is safe to
525 // update its canonical decl to signal that the entire entity is used.
526 D->getCanonicalDecl()->Used |= IsDeclMarkedUsed;
527 IsDeclMarkedUsed = false;
529 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
530 if (auto *TInfo = DD->getTypeSourceInfo())
531 Record.readTypeLoc(TInfo->getTypeLoc());
534 if (auto *TD = dyn_cast<TypeDecl>(D)) {
535 // We have a fully initialized TypeDecl. Read its type now.
536 TD->setTypeForDecl(Reader.GetType(DeferredTypeID).getTypePtrOrNull());
538 // If this is a tag declaration with a typedef name for linkage, it's safe
539 // to load that typedef now.
540 if (NamedDeclForTagDecl)
541 cast<TagDecl>(D)->TypedefNameDeclOrQualifier =
542 cast<TypedefNameDecl>(Reader.GetDecl(NamedDeclForTagDecl));
543 } else if (auto *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
544 // if we have a fully initialized TypeDecl, we can safely read its type now.
545 ID->TypeForDecl = Reader.GetType(DeferredTypeID).getTypePtrOrNull();
546 } else if (auto *FD = dyn_cast<FunctionDecl>(D)) {
547 // FunctionDecl's body was written last after all other Stmts/Exprs.
548 // We only read it if FD doesn't already have a body (e.g., from another
550 // FIXME: Can we diagnose ODR violations somehow?
551 if (Record.readInt())
552 ReadFunctionDefinition(FD);
556 void ASTDeclReader::VisitDecl(Decl *D) {
557 if (D->isTemplateParameter() || D->isTemplateParameterPack() ||
558 isa<ParmVarDecl>(D) || isa<ObjCTypeParamDecl>(D)) {
559 // We don't want to deserialize the DeclContext of a template
560 // parameter or of a parameter of a function template immediately. These
561 // entities might be used in the formulation of its DeclContext (for
562 // example, a function parameter can be used in decltype() in trailing
563 // return type of the function). Use the translation unit DeclContext as a
565 GlobalDeclID SemaDCIDForTemplateParmDecl = readDeclID();
566 GlobalDeclID LexicalDCIDForTemplateParmDecl = readDeclID();
567 if (!LexicalDCIDForTemplateParmDecl)
568 LexicalDCIDForTemplateParmDecl = SemaDCIDForTemplateParmDecl;
569 Reader.addPendingDeclContextInfo(D,
570 SemaDCIDForTemplateParmDecl,
571 LexicalDCIDForTemplateParmDecl);
572 D->setDeclContext(Reader.getContext().getTranslationUnitDecl());
574 auto *SemaDC = readDeclAs<DeclContext>();
575 auto *LexicalDC = readDeclAs<DeclContext>();
578 DeclContext *MergedSemaDC = Reader.MergedDeclContexts.lookup(SemaDC);
579 // Avoid calling setLexicalDeclContext() directly because it uses
580 // Decl::getASTContext() internally which is unsafe during derialization.
581 D->setDeclContextsImpl(MergedSemaDC ? MergedSemaDC : SemaDC, LexicalDC,
582 Reader.getContext());
584 D->setLocation(ThisDeclLoc);
585 D->setInvalidDecl(Record.readInt());
586 if (Record.readInt()) { // hasAttrs
588 Record.readAttributes(Attrs);
589 // Avoid calling setAttrs() directly because it uses Decl::getASTContext()
590 // internally which is unsafe during derialization.
591 D->setAttrsImpl(Attrs, Reader.getContext());
593 D->setImplicit(Record.readInt());
594 D->Used = Record.readInt();
595 IsDeclMarkedUsed |= D->Used;
596 D->setReferenced(Record.readInt());
597 D->setTopLevelDeclInObjCContainer(Record.readInt());
598 D->setAccess((AccessSpecifier)Record.readInt());
599 D->FromASTFile = true;
600 bool ModulePrivate = Record.readInt();
602 // Determine whether this declaration is part of a (sub)module. If so, it
603 // may not yet be visible.
604 if (unsigned SubmoduleID = readSubmoduleID()) {
605 // Store the owning submodule ID in the declaration.
606 D->setModuleOwnershipKind(
607 ModulePrivate ? Decl::ModuleOwnershipKind::ModulePrivate
608 : Decl::ModuleOwnershipKind::VisibleWhenImported);
609 D->setOwningModuleID(SubmoduleID);
612 // Module-private declarations are never visible, so there is no work to
614 } else if (Reader.getContext().getLangOpts().ModulesLocalVisibility) {
615 // If local visibility is being tracked, this declaration will become
616 // hidden and visible as the owning module does.
617 } else if (Module *Owner = Reader.getSubmodule(SubmoduleID)) {
618 // Mark the declaration as visible when its owning module becomes visible.
619 if (Owner->NameVisibility == Module::AllVisible)
620 D->setVisibleDespiteOwningModule();
622 Reader.HiddenNamesMap[Owner].push_back(D);
624 } else if (ModulePrivate) {
625 D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate);
629 void ASTDeclReader::VisitPragmaCommentDecl(PragmaCommentDecl *D) {
631 D->setLocation(readSourceLocation());
632 D->CommentKind = (PragmaMSCommentKind)Record.readInt();
633 std::string Arg = readString();
634 memcpy(D->getTrailingObjects<char>(), Arg.data(), Arg.size());
635 D->getTrailingObjects<char>()[Arg.size()] = '\0';
638 void ASTDeclReader::VisitPragmaDetectMismatchDecl(PragmaDetectMismatchDecl *D) {
640 D->setLocation(readSourceLocation());
641 std::string Name = readString();
642 memcpy(D->getTrailingObjects<char>(), Name.data(), Name.size());
643 D->getTrailingObjects<char>()[Name.size()] = '\0';
645 D->ValueStart = Name.size() + 1;
646 std::string Value = readString();
647 memcpy(D->getTrailingObjects<char>() + D->ValueStart, Value.data(),
649 D->getTrailingObjects<char>()[D->ValueStart + Value.size()] = '\0';
652 void ASTDeclReader::VisitTranslationUnitDecl(TranslationUnitDecl *TU) {
653 llvm_unreachable("Translation units are not serialized");
656 void ASTDeclReader::VisitNamedDecl(NamedDecl *ND) {
658 ND->setDeclName(Record.readDeclarationName());
659 AnonymousDeclNumber = Record.readInt();
662 void ASTDeclReader::VisitTypeDecl(TypeDecl *TD) {
664 TD->setLocStart(readSourceLocation());
665 // Delay type reading until after we have fully initialized the decl.
666 DeferredTypeID = Record.getGlobalTypeID(Record.readInt());
669 ASTDeclReader::RedeclarableResult
670 ASTDeclReader::VisitTypedefNameDecl(TypedefNameDecl *TD) {
671 RedeclarableResult Redecl = VisitRedeclarable(TD);
673 TypeSourceInfo *TInfo = readTypeSourceInfo();
674 if (Record.readInt()) { // isModed
675 QualType modedT = Record.readType();
676 TD->setModedTypeSourceInfo(TInfo, modedT);
678 TD->setTypeSourceInfo(TInfo);
679 // Read and discard the declaration for which this is a typedef name for
680 // linkage, if it exists. We cannot rely on our type to pull in this decl,
681 // because it might have been merged with a type from another module and
682 // thus might not refer to our version of the declaration.
687 void ASTDeclReader::VisitTypedefDecl(TypedefDecl *TD) {
688 RedeclarableResult Redecl = VisitTypedefNameDecl(TD);
689 mergeRedeclarable(TD, Redecl);
692 void ASTDeclReader::VisitTypeAliasDecl(TypeAliasDecl *TD) {
693 RedeclarableResult Redecl = VisitTypedefNameDecl(TD);
694 if (auto *Template = readDeclAs<TypeAliasTemplateDecl>())
695 // Merged when we merge the template.
696 TD->setDescribedAliasTemplate(Template);
698 mergeRedeclarable(TD, Redecl);
701 ASTDeclReader::RedeclarableResult ASTDeclReader::VisitTagDecl(TagDecl *TD) {
702 RedeclarableResult Redecl = VisitRedeclarable(TD);
705 TD->IdentifierNamespace = Record.readInt();
706 TD->setTagKind((TagDecl::TagKind)Record.readInt());
707 if (!isa<CXXRecordDecl>(TD))
708 TD->setCompleteDefinition(Record.readInt());
709 TD->setEmbeddedInDeclarator(Record.readInt());
710 TD->setFreeStanding(Record.readInt());
711 TD->setCompleteDefinitionRequired(Record.readInt());
712 TD->setBraceRange(readSourceRange());
714 switch (Record.readInt()) {
718 auto *Info = new (Reader.getContext()) TagDecl::ExtInfo();
719 Record.readQualifierInfo(*Info);
720 TD->TypedefNameDeclOrQualifier = Info;
723 case 2: // TypedefNameForAnonDecl
724 NamedDeclForTagDecl = readDeclID();
725 TypedefNameForLinkage = Record.readIdentifier();
728 llvm_unreachable("unexpected tag info kind");
731 if (!isa<CXXRecordDecl>(TD))
732 mergeRedeclarable(TD, Redecl);
736 void ASTDeclReader::VisitEnumDecl(EnumDecl *ED) {
738 if (TypeSourceInfo *TI = readTypeSourceInfo())
739 ED->setIntegerTypeSourceInfo(TI);
741 ED->setIntegerType(Record.readType());
742 ED->setPromotionType(Record.readType());
743 ED->setNumPositiveBits(Record.readInt());
744 ED->setNumNegativeBits(Record.readInt());
745 ED->setScoped(Record.readInt());
746 ED->setScopedUsingClassTag(Record.readInt());
747 ED->setFixed(Record.readInt());
749 ED->setHasODRHash(true);
750 ED->ODRHash = Record.readInt();
752 // If this is a definition subject to the ODR, and we already have a
753 // definition, merge this one into it.
754 if (ED->isCompleteDefinition() &&
755 Reader.getContext().getLangOpts().Modules &&
756 Reader.getContext().getLangOpts().CPlusPlus) {
757 EnumDecl *&OldDef = Reader.EnumDefinitions[ED->getCanonicalDecl()];
759 // This is the first time we've seen an imported definition. Look for a
760 // local definition before deciding that we are the first definition.
761 for (auto *D : merged_redecls(ED->getCanonicalDecl())) {
762 if (!D->isFromASTFile() && D->isCompleteDefinition()) {
769 Reader.MergedDeclContexts.insert(std::make_pair(ED, OldDef));
770 ED->setCompleteDefinition(false);
771 Reader.mergeDefinitionVisibility(OldDef, ED);
772 if (OldDef->getODRHash() != ED->getODRHash())
773 Reader.PendingEnumOdrMergeFailures[OldDef].push_back(ED);
779 if (auto *InstED = readDeclAs<EnumDecl>()) {
780 auto TSK = (TemplateSpecializationKind)Record.readInt();
781 SourceLocation POI = readSourceLocation();
782 ED->setInstantiationOfMemberEnum(Reader.getContext(), InstED, TSK);
783 ED->getMemberSpecializationInfo()->setPointOfInstantiation(POI);
787 ASTDeclReader::RedeclarableResult
788 ASTDeclReader::VisitRecordDeclImpl(RecordDecl *RD) {
789 RedeclarableResult Redecl = VisitTagDecl(RD);
790 RD->setHasFlexibleArrayMember(Record.readInt());
791 RD->setAnonymousStructOrUnion(Record.readInt());
792 RD->setHasObjectMember(Record.readInt());
793 RD->setHasVolatileMember(Record.readInt());
794 RD->setNonTrivialToPrimitiveDefaultInitialize(Record.readInt());
795 RD->setNonTrivialToPrimitiveCopy(Record.readInt());
796 RD->setNonTrivialToPrimitiveDestroy(Record.readInt());
797 RD->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(Record.readInt());
798 RD->setHasNonTrivialToPrimitiveDestructCUnion(Record.readInt());
799 RD->setHasNonTrivialToPrimitiveCopyCUnion(Record.readInt());
800 RD->setParamDestroyedInCallee(Record.readInt());
801 RD->setArgPassingRestrictions((RecordDecl::ArgPassingKind)Record.readInt());
805 void ASTDeclReader::VisitValueDecl(ValueDecl *VD) {
807 // For function declarations, defer reading the type in case the function has
808 // a deduced return type that references an entity declared within the
810 if (isa<FunctionDecl>(VD))
811 DeferredTypeID = Record.getGlobalTypeID(Record.readInt());
813 VD->setType(Record.readType());
816 void ASTDeclReader::VisitEnumConstantDecl(EnumConstantDecl *ECD) {
818 if (Record.readInt())
819 ECD->setInitExpr(Record.readExpr());
820 ECD->setInitVal(Record.readAPSInt());
824 void ASTDeclReader::VisitDeclaratorDecl(DeclaratorDecl *DD) {
826 DD->setInnerLocStart(readSourceLocation());
827 if (Record.readInt()) { // hasExtInfo
828 auto *Info = new (Reader.getContext()) DeclaratorDecl::ExtInfo();
829 Record.readQualifierInfo(*Info);
830 Info->TrailingRequiresClause = Record.readExpr();
833 QualType TSIType = Record.readType();
834 DD->setTypeSourceInfo(
835 TSIType.isNull() ? nullptr
836 : Reader.getContext().CreateTypeSourceInfo(TSIType));
839 void ASTDeclReader::VisitFunctionDecl(FunctionDecl *FD) {
840 RedeclarableResult Redecl = VisitRedeclarable(FD);
841 VisitDeclaratorDecl(FD);
843 // Attach a type to this function. Use the real type if possible, but fall
844 // back to the type as written if it involves a deduced return type.
845 if (FD->getTypeSourceInfo() &&
846 FD->getTypeSourceInfo()->getType()->castAs<FunctionType>()
847 ->getReturnType()->getContainedAutoType()) {
848 // We'll set up the real type in Visit, once we've finished loading the
850 FD->setType(FD->getTypeSourceInfo()->getType());
851 Reader.PendingFunctionTypes.push_back({FD, DeferredTypeID});
853 FD->setType(Reader.GetType(DeferredTypeID));
857 FD->DNLoc = Record.readDeclarationNameLoc(FD->getDeclName());
858 FD->IdentifierNamespace = Record.readInt();
860 // FunctionDecl's body is handled last at ASTDeclReader::Visit,
861 // after everything else is read.
863 FD->setStorageClass(static_cast<StorageClass>(Record.readInt()));
864 FD->setInlineSpecified(Record.readInt());
865 FD->setImplicitlyInline(Record.readInt());
866 FD->setVirtualAsWritten(Record.readInt());
867 FD->setPure(Record.readInt());
868 FD->setHasInheritedPrototype(Record.readInt());
869 FD->setHasWrittenPrototype(Record.readInt());
870 FD->setDeletedAsWritten(Record.readInt());
871 FD->setTrivial(Record.readInt());
872 FD->setTrivialForCall(Record.readInt());
873 FD->setDefaulted(Record.readInt());
874 FD->setExplicitlyDefaulted(Record.readInt());
875 FD->setHasImplicitReturnZero(Record.readInt());
876 FD->setConstexprKind(static_cast<ConstexprSpecKind>(Record.readInt()));
877 FD->setUsesSEHTry(Record.readInt());
878 FD->setHasSkippedBody(Record.readInt());
879 FD->setIsMultiVersion(Record.readInt());
880 FD->setLateTemplateParsed(Record.readInt());
882 FD->setCachedLinkage(static_cast<Linkage>(Record.readInt()));
883 FD->EndRangeLoc = readSourceLocation();
885 FD->ODRHash = Record.readInt();
886 FD->setHasODRHash(true);
887 FD->setUsesFPIntrin(Record.readInt());
889 if (FD->isDefaulted()) {
890 if (unsigned NumLookups = Record.readInt()) {
891 SmallVector<DeclAccessPair, 8> Lookups;
892 for (unsigned I = 0; I != NumLookups; ++I) {
893 NamedDecl *ND = Record.readDeclAs<NamedDecl>();
894 AccessSpecifier AS = (AccessSpecifier)Record.readInt();
895 Lookups.push_back(DeclAccessPair::make(ND, AS));
897 FD->setDefaultedFunctionInfo(FunctionDecl::DefaultedFunctionInfo::Create(
898 Reader.getContext(), Lookups));
902 switch ((FunctionDecl::TemplatedKind)Record.readInt()) {
903 case FunctionDecl::TK_NonTemplate:
904 mergeRedeclarable(FD, Redecl);
906 case FunctionDecl::TK_FunctionTemplate:
907 // Merged when we merge the template.
908 FD->setDescribedFunctionTemplate(readDeclAs<FunctionTemplateDecl>());
910 case FunctionDecl::TK_MemberSpecialization: {
911 auto *InstFD = readDeclAs<FunctionDecl>();
912 auto TSK = (TemplateSpecializationKind)Record.readInt();
913 SourceLocation POI = readSourceLocation();
914 FD->setInstantiationOfMemberFunction(Reader.getContext(), InstFD, TSK);
915 FD->getMemberSpecializationInfo()->setPointOfInstantiation(POI);
916 mergeRedeclarable(FD, Redecl);
919 case FunctionDecl::TK_FunctionTemplateSpecialization: {
920 auto *Template = readDeclAs<FunctionTemplateDecl>();
921 auto TSK = (TemplateSpecializationKind)Record.readInt();
923 // Template arguments.
924 SmallVector<TemplateArgument, 8> TemplArgs;
925 Record.readTemplateArgumentList(TemplArgs, /*Canonicalize*/ true);
927 // Template args as written.
928 SmallVector<TemplateArgumentLoc, 8> TemplArgLocs;
929 SourceLocation LAngleLoc, RAngleLoc;
930 bool HasTemplateArgumentsAsWritten = Record.readInt();
931 if (HasTemplateArgumentsAsWritten) {
932 unsigned NumTemplateArgLocs = Record.readInt();
933 TemplArgLocs.reserve(NumTemplateArgLocs);
934 for (unsigned i = 0; i != NumTemplateArgLocs; ++i)
935 TemplArgLocs.push_back(Record.readTemplateArgumentLoc());
937 LAngleLoc = readSourceLocation();
938 RAngleLoc = readSourceLocation();
941 SourceLocation POI = readSourceLocation();
943 ASTContext &C = Reader.getContext();
944 TemplateArgumentList *TemplArgList
945 = TemplateArgumentList::CreateCopy(C, TemplArgs);
946 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
947 for (unsigned i = 0, e = TemplArgLocs.size(); i != e; ++i)
948 TemplArgsInfo.addArgument(TemplArgLocs[i]);
950 MemberSpecializationInfo *MSInfo = nullptr;
951 if (Record.readInt()) {
952 auto *FD = readDeclAs<FunctionDecl>();
953 auto TSK = (TemplateSpecializationKind)Record.readInt();
954 SourceLocation POI = readSourceLocation();
956 MSInfo = new (C) MemberSpecializationInfo(FD, TSK);
957 MSInfo->setPointOfInstantiation(POI);
960 FunctionTemplateSpecializationInfo *FTInfo =
961 FunctionTemplateSpecializationInfo::Create(
962 C, FD, Template, TSK, TemplArgList,
963 HasTemplateArgumentsAsWritten ? &TemplArgsInfo : nullptr, POI,
965 FD->TemplateOrSpecialization = FTInfo;
967 if (FD->isCanonicalDecl()) { // if canonical add to template's set.
968 // The template that contains the specializations set. It's not safe to
969 // use getCanonicalDecl on Template since it may still be initializing.
970 auto *CanonTemplate = readDeclAs<FunctionTemplateDecl>();
971 // Get the InsertPos by FindNodeOrInsertPos() instead of calling
972 // InsertNode(FTInfo) directly to avoid the getASTContext() call in
973 // FunctionTemplateSpecializationInfo's Profile().
974 // We avoid getASTContext because a decl in the parent hierarchy may
976 llvm::FoldingSetNodeID ID;
977 FunctionTemplateSpecializationInfo::Profile(ID, TemplArgs, C);
978 void *InsertPos = nullptr;
979 FunctionTemplateDecl::Common *CommonPtr = CanonTemplate->getCommonPtr();
980 FunctionTemplateSpecializationInfo *ExistingInfo =
981 CommonPtr->Specializations.FindNodeOrInsertPos(ID, InsertPos);
983 CommonPtr->Specializations.InsertNode(FTInfo, InsertPos);
985 assert(Reader.getContext().getLangOpts().Modules &&
986 "already deserialized this template specialization");
987 mergeRedeclarable(FD, ExistingInfo->getFunction(), Redecl);
992 case FunctionDecl::TK_DependentFunctionTemplateSpecialization: {
994 UnresolvedSet<8> TemplDecls;
995 unsigned NumTemplates = Record.readInt();
996 while (NumTemplates--)
997 TemplDecls.addDecl(readDeclAs<NamedDecl>());
1000 TemplateArgumentListInfo TemplArgs;
1001 unsigned NumArgs = Record.readInt();
1003 TemplArgs.addArgument(Record.readTemplateArgumentLoc());
1004 TemplArgs.setLAngleLoc(readSourceLocation());
1005 TemplArgs.setRAngleLoc(readSourceLocation());
1007 FD->setDependentTemplateSpecialization(Reader.getContext(),
1008 TemplDecls, TemplArgs);
1009 // These are not merged; we don't need to merge redeclarations of dependent
1010 // template friends.
1015 // Read in the parameters.
1016 unsigned NumParams = Record.readInt();
1017 SmallVector<ParmVarDecl *, 16> Params;
1018 Params.reserve(NumParams);
1019 for (unsigned I = 0; I != NumParams; ++I)
1020 Params.push_back(readDeclAs<ParmVarDecl>());
1021 FD->setParams(Reader.getContext(), Params);
1024 void ASTDeclReader::VisitObjCMethodDecl(ObjCMethodDecl *MD) {
1026 if (Record.readInt()) {
1027 // Load the body on-demand. Most clients won't care, because method
1028 // definitions rarely show up in headers.
1029 Reader.PendingBodies[MD] = GetCurrentCursorOffset();
1030 HasPendingBody = true;
1032 MD->setSelfDecl(readDeclAs<ImplicitParamDecl>());
1033 MD->setCmdDecl(readDeclAs<ImplicitParamDecl>());
1034 MD->setInstanceMethod(Record.readInt());
1035 MD->setVariadic(Record.readInt());
1036 MD->setPropertyAccessor(Record.readInt());
1037 MD->setSynthesizedAccessorStub(Record.readInt());
1038 MD->setDefined(Record.readInt());
1039 MD->setOverriding(Record.readInt());
1040 MD->setHasSkippedBody(Record.readInt());
1042 MD->setIsRedeclaration(Record.readInt());
1043 MD->setHasRedeclaration(Record.readInt());
1044 if (MD->hasRedeclaration())
1045 Reader.getContext().setObjCMethodRedeclaration(MD,
1046 readDeclAs<ObjCMethodDecl>());
1048 MD->setDeclImplementation((ObjCMethodDecl::ImplementationControl)Record.readInt());
1049 MD->setObjCDeclQualifier((Decl::ObjCDeclQualifier)Record.readInt());
1050 MD->setRelatedResultType(Record.readInt());
1051 MD->setReturnType(Record.readType());
1052 MD->setReturnTypeSourceInfo(readTypeSourceInfo());
1053 MD->DeclEndLoc = readSourceLocation();
1054 unsigned NumParams = Record.readInt();
1055 SmallVector<ParmVarDecl *, 16> Params;
1056 Params.reserve(NumParams);
1057 for (unsigned I = 0; I != NumParams; ++I)
1058 Params.push_back(readDeclAs<ParmVarDecl>());
1060 MD->setSelLocsKind((SelectorLocationsKind)Record.readInt());
1061 unsigned NumStoredSelLocs = Record.readInt();
1062 SmallVector<SourceLocation, 16> SelLocs;
1063 SelLocs.reserve(NumStoredSelLocs);
1064 for (unsigned i = 0; i != NumStoredSelLocs; ++i)
1065 SelLocs.push_back(readSourceLocation());
1067 MD->setParamsAndSelLocs(Reader.getContext(), Params, SelLocs);
1070 void ASTDeclReader::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
1071 VisitTypedefNameDecl(D);
1073 D->Variance = Record.readInt();
1074 D->Index = Record.readInt();
1075 D->VarianceLoc = readSourceLocation();
1076 D->ColonLoc = readSourceLocation();
1079 void ASTDeclReader::VisitObjCContainerDecl(ObjCContainerDecl *CD) {
1081 CD->setAtStartLoc(readSourceLocation());
1082 CD->setAtEndRange(readSourceRange());
1085 ObjCTypeParamList *ASTDeclReader::ReadObjCTypeParamList() {
1086 unsigned numParams = Record.readInt();
1090 SmallVector<ObjCTypeParamDecl *, 4> typeParams;
1091 typeParams.reserve(numParams);
1092 for (unsigned i = 0; i != numParams; ++i) {
1093 auto *typeParam = readDeclAs<ObjCTypeParamDecl>();
1097 typeParams.push_back(typeParam);
1100 SourceLocation lAngleLoc = readSourceLocation();
1101 SourceLocation rAngleLoc = readSourceLocation();
1103 return ObjCTypeParamList::create(Reader.getContext(), lAngleLoc,
1104 typeParams, rAngleLoc);
1107 void ASTDeclReader::ReadObjCDefinitionData(
1108 struct ObjCInterfaceDecl::DefinitionData &Data) {
1109 // Read the superclass.
1110 Data.SuperClassTInfo = readTypeSourceInfo();
1112 Data.EndLoc = readSourceLocation();
1113 Data.HasDesignatedInitializers = Record.readInt();
1115 // Read the directly referenced protocols and their SourceLocations.
1116 unsigned NumProtocols = Record.readInt();
1117 SmallVector<ObjCProtocolDecl *, 16> Protocols;
1118 Protocols.reserve(NumProtocols);
1119 for (unsigned I = 0; I != NumProtocols; ++I)
1120 Protocols.push_back(readDeclAs<ObjCProtocolDecl>());
1121 SmallVector<SourceLocation, 16> ProtoLocs;
1122 ProtoLocs.reserve(NumProtocols);
1123 for (unsigned I = 0; I != NumProtocols; ++I)
1124 ProtoLocs.push_back(readSourceLocation());
1125 Data.ReferencedProtocols.set(Protocols.data(), NumProtocols, ProtoLocs.data(),
1126 Reader.getContext());
1128 // Read the transitive closure of protocols referenced by this class.
1129 NumProtocols = Record.readInt();
1131 Protocols.reserve(NumProtocols);
1132 for (unsigned I = 0; I != NumProtocols; ++I)
1133 Protocols.push_back(readDeclAs<ObjCProtocolDecl>());
1134 Data.AllReferencedProtocols.set(Protocols.data(), NumProtocols,
1135 Reader.getContext());
1138 void ASTDeclReader::MergeDefinitionData(ObjCInterfaceDecl *D,
1139 struct ObjCInterfaceDecl::DefinitionData &&NewDD) {
1140 // FIXME: odr checking?
1143 void ASTDeclReader::VisitObjCInterfaceDecl(ObjCInterfaceDecl *ID) {
1144 RedeclarableResult Redecl = VisitRedeclarable(ID);
1145 VisitObjCContainerDecl(ID);
1146 DeferredTypeID = Record.getGlobalTypeID(Record.readInt());
1147 mergeRedeclarable(ID, Redecl);
1149 ID->TypeParamList = ReadObjCTypeParamList();
1150 if (Record.readInt()) {
1151 // Read the definition.
1152 ID->allocateDefinitionData();
1154 ReadObjCDefinitionData(ID->data());
1155 ObjCInterfaceDecl *Canon = ID->getCanonicalDecl();
1156 if (Canon->Data.getPointer()) {
1157 // If we already have a definition, keep the definition invariant and
1159 MergeDefinitionData(Canon, std::move(ID->data()));
1160 ID->Data = Canon->Data;
1162 // Set the definition data of the canonical declaration, so other
1163 // redeclarations will see it.
1164 ID->getCanonicalDecl()->Data = ID->Data;
1166 // We will rebuild this list lazily.
1167 ID->setIvarList(nullptr);
1170 // Note that we have deserialized a definition.
1171 Reader.PendingDefinitions.insert(ID);
1173 // Note that we've loaded this Objective-C class.
1174 Reader.ObjCClassesLoaded.push_back(ID);
1176 ID->Data = ID->getCanonicalDecl()->Data;
1180 void ASTDeclReader::VisitObjCIvarDecl(ObjCIvarDecl *IVD) {
1181 VisitFieldDecl(IVD);
1182 IVD->setAccessControl((ObjCIvarDecl::AccessControl)Record.readInt());
1183 // This field will be built lazily.
1184 IVD->setNextIvar(nullptr);
1185 bool synth = Record.readInt();
1186 IVD->setSynthesize(synth);
1189 void ASTDeclReader::ReadObjCDefinitionData(
1190 struct ObjCProtocolDecl::DefinitionData &Data) {
1191 unsigned NumProtoRefs = Record.readInt();
1192 SmallVector<ObjCProtocolDecl *, 16> ProtoRefs;
1193 ProtoRefs.reserve(NumProtoRefs);
1194 for (unsigned I = 0; I != NumProtoRefs; ++I)
1195 ProtoRefs.push_back(readDeclAs<ObjCProtocolDecl>());
1196 SmallVector<SourceLocation, 16> ProtoLocs;
1197 ProtoLocs.reserve(NumProtoRefs);
1198 for (unsigned I = 0; I != NumProtoRefs; ++I)
1199 ProtoLocs.push_back(readSourceLocation());
1200 Data.ReferencedProtocols.set(ProtoRefs.data(), NumProtoRefs,
1201 ProtoLocs.data(), Reader.getContext());
1204 void ASTDeclReader::MergeDefinitionData(ObjCProtocolDecl *D,
1205 struct ObjCProtocolDecl::DefinitionData &&NewDD) {
1206 // FIXME: odr checking?
1209 void ASTDeclReader::VisitObjCProtocolDecl(ObjCProtocolDecl *PD) {
1210 RedeclarableResult Redecl = VisitRedeclarable(PD);
1211 VisitObjCContainerDecl(PD);
1212 mergeRedeclarable(PD, Redecl);
1214 if (Record.readInt()) {
1215 // Read the definition.
1216 PD->allocateDefinitionData();
1218 ReadObjCDefinitionData(PD->data());
1220 ObjCProtocolDecl *Canon = PD->getCanonicalDecl();
1221 if (Canon->Data.getPointer()) {
1222 // If we already have a definition, keep the definition invariant and
1224 MergeDefinitionData(Canon, std::move(PD->data()));
1225 PD->Data = Canon->Data;
1227 // Set the definition data of the canonical declaration, so other
1228 // redeclarations will see it.
1229 PD->getCanonicalDecl()->Data = PD->Data;
1231 // Note that we have deserialized a definition.
1232 Reader.PendingDefinitions.insert(PD);
1234 PD->Data = PD->getCanonicalDecl()->Data;
1238 void ASTDeclReader::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *FD) {
1242 void ASTDeclReader::VisitObjCCategoryDecl(ObjCCategoryDecl *CD) {
1243 VisitObjCContainerDecl(CD);
1244 CD->setCategoryNameLoc(readSourceLocation());
1245 CD->setIvarLBraceLoc(readSourceLocation());
1246 CD->setIvarRBraceLoc(readSourceLocation());
1248 // Note that this category has been deserialized. We do this before
1249 // deserializing the interface declaration, so that it will consider this
1251 Reader.CategoriesDeserialized.insert(CD);
1253 CD->ClassInterface = readDeclAs<ObjCInterfaceDecl>();
1254 CD->TypeParamList = ReadObjCTypeParamList();
1255 unsigned NumProtoRefs = Record.readInt();
1256 SmallVector<ObjCProtocolDecl *, 16> ProtoRefs;
1257 ProtoRefs.reserve(NumProtoRefs);
1258 for (unsigned I = 0; I != NumProtoRefs; ++I)
1259 ProtoRefs.push_back(readDeclAs<ObjCProtocolDecl>());
1260 SmallVector<SourceLocation, 16> ProtoLocs;
1261 ProtoLocs.reserve(NumProtoRefs);
1262 for (unsigned I = 0; I != NumProtoRefs; ++I)
1263 ProtoLocs.push_back(readSourceLocation());
1264 CD->setProtocolList(ProtoRefs.data(), NumProtoRefs, ProtoLocs.data(),
1265 Reader.getContext());
1267 // Protocols in the class extension belong to the class.
1268 if (NumProtoRefs > 0 && CD->ClassInterface && CD->IsClassExtension())
1269 CD->ClassInterface->mergeClassExtensionProtocolList(
1270 (ObjCProtocolDecl *const *)ProtoRefs.data(), NumProtoRefs,
1271 Reader.getContext());
1274 void ASTDeclReader::VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *CAD) {
1275 VisitNamedDecl(CAD);
1276 CAD->setClassInterface(readDeclAs<ObjCInterfaceDecl>());
1279 void ASTDeclReader::VisitObjCPropertyDecl(ObjCPropertyDecl *D) {
1281 D->setAtLoc(readSourceLocation());
1282 D->setLParenLoc(readSourceLocation());
1283 QualType T = Record.readType();
1284 TypeSourceInfo *TSI = readTypeSourceInfo();
1286 D->setPropertyAttributes(
1287 (ObjCPropertyDecl::PropertyAttributeKind)Record.readInt());
1288 D->setPropertyAttributesAsWritten(
1289 (ObjCPropertyDecl::PropertyAttributeKind)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::VisitIndirectFieldDecl(IndirectFieldDecl *FD) {
1368 FD->ChainingSize = Record.readInt();
1369 assert(FD->ChainingSize >= 2 && "Anonymous chaining must be >= 2");
1370 FD->Chaining = new (Reader.getContext())NamedDecl*[FD->ChainingSize];
1372 for (unsigned I = 0; I != FD->ChainingSize; ++I)
1373 FD->Chaining[I] = readDeclAs<NamedDecl>();
1378 ASTDeclReader::RedeclarableResult ASTDeclReader::VisitVarDeclImpl(VarDecl *VD) {
1379 RedeclarableResult Redecl = VisitRedeclarable(VD);
1380 VisitDeclaratorDecl(VD);
1382 VD->VarDeclBits.SClass = (StorageClass)Record.readInt();
1383 VD->VarDeclBits.TSCSpec = Record.readInt();
1384 VD->VarDeclBits.InitStyle = Record.readInt();
1385 VD->VarDeclBits.ARCPseudoStrong = Record.readInt();
1386 if (!isa<ParmVarDecl>(VD)) {
1387 VD->NonParmVarDeclBits.IsThisDeclarationADemotedDefinition =
1389 VD->NonParmVarDeclBits.ExceptionVar = Record.readInt();
1390 VD->NonParmVarDeclBits.NRVOVariable = Record.readInt();
1391 VD->NonParmVarDeclBits.CXXForRangeDecl = Record.readInt();
1392 VD->NonParmVarDeclBits.ObjCForDecl = Record.readInt();
1393 VD->NonParmVarDeclBits.IsInline = Record.readInt();
1394 VD->NonParmVarDeclBits.IsInlineSpecified = Record.readInt();
1395 VD->NonParmVarDeclBits.IsConstexpr = Record.readInt();
1396 VD->NonParmVarDeclBits.IsInitCapture = Record.readInt();
1397 VD->NonParmVarDeclBits.PreviousDeclInSameBlockScope = Record.readInt();
1398 VD->NonParmVarDeclBits.ImplicitParamKind = Record.readInt();
1399 VD->NonParmVarDeclBits.EscapingByref = Record.readInt();
1401 auto VarLinkage = Linkage(Record.readInt());
1402 VD->setCachedLinkage(VarLinkage);
1404 // Reconstruct the one piece of the IdentifierNamespace that we need.
1405 if (VD->getStorageClass() == SC_Extern && VarLinkage != NoLinkage &&
1406 VD->getLexicalDeclContext()->isFunctionOrMethod())
1407 VD->setLocalExternDecl();
1409 if (uint64_t Val = Record.readInt()) {
1410 VD->setInit(Record.readExpr());
1412 EvaluatedStmt *Eval = VD->ensureEvaluatedStmt();
1413 Eval->CheckedICE = true;
1414 Eval->IsICE = (Val & 1) != 0;
1415 Eval->HasConstantDestruction = (Val & 4) != 0;
1419 if (VD->hasAttr<BlocksAttr>() && VD->getType()->getAsCXXRecordDecl()) {
1420 Expr *CopyExpr = Record.readExpr();
1422 Reader.getContext().setBlockVarCopyInit(VD, CopyExpr, Record.readInt());
1425 if (VD->getStorageDuration() == SD_Static && Record.readInt()) {
1426 Reader.DefinitionSource[VD] = Loc.F->Kind == ModuleKind::MK_MainFile;
1427 if (Reader.getContext().getLangOpts().BuildingPCHWithObjectFile &&
1428 Reader.DeclIsFromPCHWithObjectFile(VD))
1429 Reader.DefinitionSource[VD] = true;
1433 VarNotTemplate = 0, VarTemplate, StaticDataMemberSpecialization
1435 switch ((VarKind)Record.readInt()) {
1436 case VarNotTemplate:
1437 // Only true variables (not parameters or implicit parameters) can be
1438 // merged; the other kinds are not really redeclarable at all.
1439 if (!isa<ParmVarDecl>(VD) && !isa<ImplicitParamDecl>(VD) &&
1440 !isa<VarTemplateSpecializationDecl>(VD))
1441 mergeRedeclarable(VD, Redecl);
1444 // Merged when we merge the template.
1445 VD->setDescribedVarTemplate(readDeclAs<VarTemplateDecl>());
1447 case StaticDataMemberSpecialization: { // HasMemberSpecializationInfo.
1448 auto *Tmpl = readDeclAs<VarDecl>();
1449 auto TSK = (TemplateSpecializationKind)Record.readInt();
1450 SourceLocation POI = readSourceLocation();
1451 Reader.getContext().setInstantiatedFromStaticDataMember(VD, Tmpl, TSK,POI);
1452 mergeRedeclarable(VD, Redecl);
1460 void ASTDeclReader::VisitImplicitParamDecl(ImplicitParamDecl *PD) {
1464 void ASTDeclReader::VisitParmVarDecl(ParmVarDecl *PD) {
1466 unsigned isObjCMethodParam = Record.readInt();
1467 unsigned scopeDepth = Record.readInt();
1468 unsigned scopeIndex = Record.readInt();
1469 unsigned declQualifier = Record.readInt();
1470 if (isObjCMethodParam) {
1471 assert(scopeDepth == 0);
1472 PD->setObjCMethodScopeInfo(scopeIndex);
1473 PD->ParmVarDeclBits.ScopeDepthOrObjCQuals = declQualifier;
1475 PD->setScopeInfo(scopeDepth, scopeIndex);
1477 PD->ParmVarDeclBits.IsKNRPromoted = Record.readInt();
1478 PD->ParmVarDeclBits.HasInheritedDefaultArg = Record.readInt();
1479 if (Record.readInt()) // hasUninstantiatedDefaultArg.
1480 PD->setUninstantiatedDefaultArg(Record.readExpr());
1482 // FIXME: If this is a redeclaration of a function from another module, handle
1483 // inheritance of default arguments.
1486 void ASTDeclReader::VisitDecompositionDecl(DecompositionDecl *DD) {
1488 auto **BDs = DD->getTrailingObjects<BindingDecl *>();
1489 for (unsigned I = 0; I != DD->NumBindings; ++I) {
1490 BDs[I] = readDeclAs<BindingDecl>();
1491 BDs[I]->setDecomposedDecl(DD);
1495 void ASTDeclReader::VisitBindingDecl(BindingDecl *BD) {
1497 BD->Binding = Record.readExpr();
1500 void ASTDeclReader::VisitFileScopeAsmDecl(FileScopeAsmDecl *AD) {
1502 AD->setAsmString(cast<StringLiteral>(Record.readExpr()));
1503 AD->setRParenLoc(readSourceLocation());
1506 void ASTDeclReader::VisitBlockDecl(BlockDecl *BD) {
1508 BD->setBody(cast_or_null<CompoundStmt>(Record.readStmt()));
1509 BD->setSignatureAsWritten(readTypeSourceInfo());
1510 unsigned NumParams = Record.readInt();
1511 SmallVector<ParmVarDecl *, 16> Params;
1512 Params.reserve(NumParams);
1513 for (unsigned I = 0; I != NumParams; ++I)
1514 Params.push_back(readDeclAs<ParmVarDecl>());
1515 BD->setParams(Params);
1517 BD->setIsVariadic(Record.readInt());
1518 BD->setBlockMissingReturnType(Record.readInt());
1519 BD->setIsConversionFromLambda(Record.readInt());
1520 BD->setDoesNotEscape(Record.readInt());
1521 BD->setCanAvoidCopyToHeap(Record.readInt());
1523 bool capturesCXXThis = Record.readInt();
1524 unsigned numCaptures = Record.readInt();
1525 SmallVector<BlockDecl::Capture, 16> captures;
1526 captures.reserve(numCaptures);
1527 for (unsigned i = 0; i != numCaptures; ++i) {
1528 auto *decl = readDeclAs<VarDecl>();
1529 unsigned flags = Record.readInt();
1530 bool byRef = (flags & 1);
1531 bool nested = (flags & 2);
1532 Expr *copyExpr = ((flags & 4) ? Record.readExpr() : nullptr);
1534 captures.push_back(BlockDecl::Capture(decl, byRef, nested, copyExpr));
1536 BD->setCaptures(Reader.getContext(), captures, capturesCXXThis);
1539 void ASTDeclReader::VisitCapturedDecl(CapturedDecl *CD) {
1541 unsigned ContextParamPos = Record.readInt();
1542 CD->setNothrow(Record.readInt() != 0);
1543 // Body is set by VisitCapturedStmt.
1544 for (unsigned I = 0; I < CD->NumParams; ++I) {
1545 if (I != ContextParamPos)
1546 CD->setParam(I, readDeclAs<ImplicitParamDecl>());
1548 CD->setContextParam(I, readDeclAs<ImplicitParamDecl>());
1552 void ASTDeclReader::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1554 D->setLanguage((LinkageSpecDecl::LanguageIDs)Record.readInt());
1555 D->setExternLoc(readSourceLocation());
1556 D->setRBraceLoc(readSourceLocation());
1559 void ASTDeclReader::VisitExportDecl(ExportDecl *D) {
1561 D->RBraceLoc = readSourceLocation();
1564 void ASTDeclReader::VisitLabelDecl(LabelDecl *D) {
1566 D->setLocStart(readSourceLocation());
1569 void ASTDeclReader::VisitNamespaceDecl(NamespaceDecl *D) {
1570 RedeclarableResult Redecl = VisitRedeclarable(D);
1572 D->setInline(Record.readInt());
1573 D->LocStart = readSourceLocation();
1574 D->RBraceLoc = readSourceLocation();
1576 // Defer loading the anonymous namespace until we've finished merging
1577 // this namespace; loading it might load a later declaration of the
1578 // same namespace, and we have an invariant that older declarations
1579 // get merged before newer ones try to merge.
1580 GlobalDeclID AnonNamespace = 0;
1581 if (Redecl.getFirstID() == ThisDeclID) {
1582 AnonNamespace = readDeclID();
1584 // Link this namespace back to the first declaration, which has already
1585 // been deserialized.
1586 D->AnonOrFirstNamespaceAndInline.setPointer(D->getFirstDecl());
1589 mergeRedeclarable(D, Redecl);
1591 if (AnonNamespace) {
1592 // Each module has its own anonymous namespace, which is disjoint from
1593 // any other module's anonymous namespaces, so don't attach the anonymous
1594 // namespace at all.
1595 auto *Anon = cast<NamespaceDecl>(Reader.GetDecl(AnonNamespace));
1596 if (!Record.isModule())
1597 D->setAnonymousNamespace(Anon);
1601 void ASTDeclReader::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1602 RedeclarableResult Redecl = VisitRedeclarable(D);
1604 D->NamespaceLoc = readSourceLocation();
1605 D->IdentLoc = readSourceLocation();
1606 D->QualifierLoc = Record.readNestedNameSpecifierLoc();
1607 D->Namespace = readDeclAs<NamedDecl>();
1608 mergeRedeclarable(D, Redecl);
1611 void ASTDeclReader::VisitUsingDecl(UsingDecl *D) {
1613 D->setUsingLoc(readSourceLocation());
1614 D->QualifierLoc = Record.readNestedNameSpecifierLoc();
1615 D->DNLoc = Record.readDeclarationNameLoc(D->getDeclName());
1616 D->FirstUsingShadow.setPointer(readDeclAs<UsingShadowDecl>());
1617 D->setTypename(Record.readInt());
1618 if (auto *Pattern = readDeclAs<NamedDecl>())
1619 Reader.getContext().setInstantiatedFromUsingDecl(D, Pattern);
1623 void ASTDeclReader::VisitUsingPackDecl(UsingPackDecl *D) {
1625 D->InstantiatedFrom = readDeclAs<NamedDecl>();
1626 auto **Expansions = D->getTrailingObjects<NamedDecl *>();
1627 for (unsigned I = 0; I != D->NumExpansions; ++I)
1628 Expansions[I] = readDeclAs<NamedDecl>();
1632 void ASTDeclReader::VisitUsingShadowDecl(UsingShadowDecl *D) {
1633 RedeclarableResult Redecl = VisitRedeclarable(D);
1635 D->Underlying = readDeclAs<NamedDecl>();
1636 D->IdentifierNamespace = Record.readInt();
1637 D->UsingOrNextShadow = readDeclAs<NamedDecl>();
1638 auto *Pattern = readDeclAs<UsingShadowDecl>();
1640 Reader.getContext().setInstantiatedFromUsingShadowDecl(D, Pattern);
1641 mergeRedeclarable(D, Redecl);
1644 void ASTDeclReader::VisitConstructorUsingShadowDecl(
1645 ConstructorUsingShadowDecl *D) {
1646 VisitUsingShadowDecl(D);
1647 D->NominatedBaseClassShadowDecl = readDeclAs<ConstructorUsingShadowDecl>();
1648 D->ConstructedBaseClassShadowDecl = readDeclAs<ConstructorUsingShadowDecl>();
1649 D->IsVirtual = Record.readInt();
1652 void ASTDeclReader::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1654 D->UsingLoc = readSourceLocation();
1655 D->NamespaceLoc = readSourceLocation();
1656 D->QualifierLoc = Record.readNestedNameSpecifierLoc();
1657 D->NominatedNamespace = readDeclAs<NamedDecl>();
1658 D->CommonAncestor = readDeclAs<DeclContext>();
1661 void ASTDeclReader::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1663 D->setUsingLoc(readSourceLocation());
1664 D->QualifierLoc = Record.readNestedNameSpecifierLoc();
1665 D->DNLoc = Record.readDeclarationNameLoc(D->getDeclName());
1666 D->EllipsisLoc = readSourceLocation();
1670 void ASTDeclReader::VisitUnresolvedUsingTypenameDecl(
1671 UnresolvedUsingTypenameDecl *D) {
1673 D->TypenameLocation = readSourceLocation();
1674 D->QualifierLoc = Record.readNestedNameSpecifierLoc();
1675 D->EllipsisLoc = readSourceLocation();
1679 void ASTDeclReader::ReadCXXDefinitionData(
1680 struct CXXRecordDecl::DefinitionData &Data, const CXXRecordDecl *D) {
1681 #define FIELD(Name, Width, Merge) \
1682 Data.Name = Record.readInt();
1683 #include "clang/AST/CXXRecordDeclDefinitionBits.def"
1685 // Note: the caller has deserialized the IsLambda bit already.
1686 Data.ODRHash = Record.readInt();
1687 Data.HasODRHash = true;
1689 if (Record.readInt()) {
1690 Reader.DefinitionSource[D] = Loc.F->Kind == ModuleKind::MK_MainFile;
1691 if (Reader.getContext().getLangOpts().BuildingPCHWithObjectFile &&
1692 Reader.DeclIsFromPCHWithObjectFile(D))
1693 Reader.DefinitionSource[D] = true;
1696 Data.NumBases = Record.readInt();
1698 Data.Bases = ReadGlobalOffset();
1699 Data.NumVBases = Record.readInt();
1701 Data.VBases = ReadGlobalOffset();
1703 Record.readUnresolvedSet(Data.Conversions);
1704 Data.ComputedVisibleConversions = Record.readInt();
1705 if (Data.ComputedVisibleConversions)
1706 Record.readUnresolvedSet(Data.VisibleConversions);
1707 assert(Data.Definition && "Data.Definition should be already set!");
1708 Data.FirstFriend = readDeclID();
1710 if (Data.IsLambda) {
1711 using Capture = LambdaCapture;
1713 auto &Lambda = static_cast<CXXRecordDecl::LambdaDefinitionData &>(Data);
1714 Lambda.Dependent = Record.readInt();
1715 Lambda.IsGenericLambda = Record.readInt();
1716 Lambda.CaptureDefault = Record.readInt();
1717 Lambda.NumCaptures = Record.readInt();
1718 Lambda.NumExplicitCaptures = Record.readInt();
1719 Lambda.HasKnownInternalLinkage = Record.readInt();
1720 Lambda.ManglingNumber = Record.readInt();
1721 Lambda.ContextDecl = readDeclID();
1722 Lambda.Captures = (Capture *)Reader.getContext().Allocate(
1723 sizeof(Capture) * Lambda.NumCaptures);
1724 Capture *ToCapture = Lambda.Captures;
1725 Lambda.MethodTyInfo = readTypeSourceInfo();
1726 for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) {
1727 SourceLocation Loc = readSourceLocation();
1728 bool IsImplicit = Record.readInt();
1729 auto Kind = static_cast<LambdaCaptureKind>(Record.readInt());
1734 *ToCapture++ = Capture(Loc, IsImplicit, Kind, nullptr,SourceLocation());
1738 auto *Var = readDeclAs<VarDecl>();
1739 SourceLocation EllipsisLoc = readSourceLocation();
1740 *ToCapture++ = Capture(Loc, IsImplicit, Kind, Var, EllipsisLoc);
1747 void ASTDeclReader::MergeDefinitionData(
1748 CXXRecordDecl *D, struct CXXRecordDecl::DefinitionData &&MergeDD) {
1749 assert(D->DefinitionData &&
1750 "merging class definition into non-definition");
1751 auto &DD = *D->DefinitionData;
1753 if (DD.Definition != MergeDD.Definition) {
1754 // Track that we merged the definitions.
1755 Reader.MergedDeclContexts.insert(std::make_pair(MergeDD.Definition,
1757 Reader.PendingDefinitions.erase(MergeDD.Definition);
1758 MergeDD.Definition->setCompleteDefinition(false);
1759 Reader.mergeDefinitionVisibility(DD.Definition, MergeDD.Definition);
1760 assert(Reader.Lookups.find(MergeDD.Definition) == Reader.Lookups.end() &&
1761 "already loaded pending lookups for merged definition");
1764 auto PFDI = Reader.PendingFakeDefinitionData.find(&DD);
1765 if (PFDI != Reader.PendingFakeDefinitionData.end() &&
1766 PFDI->second == ASTReader::PendingFakeDefinitionKind::Fake) {
1767 // We faked up this definition data because we found a class for which we'd
1768 // not yet loaded the definition. Replace it with the real thing now.
1769 assert(!DD.IsLambda && !MergeDD.IsLambda && "faked up lambda definition?");
1770 PFDI->second = ASTReader::PendingFakeDefinitionKind::FakeLoaded;
1772 // Don't change which declaration is the definition; that is required
1773 // to be invariant once we select it.
1774 auto *Def = DD.Definition;
1775 DD = std::move(MergeDD);
1776 DD.Definition = Def;
1780 bool DetectedOdrViolation = false;
1782 #define FIELD(Name, Width, Merge) Merge(Name)
1783 #define MERGE_OR(Field) DD.Field |= MergeDD.Field;
1784 #define NO_MERGE(Field) \
1785 DetectedOdrViolation |= DD.Field != MergeDD.Field; \
1787 #include "clang/AST/CXXRecordDeclDefinitionBits.def"
1792 if (DD.NumBases != MergeDD.NumBases || DD.NumVBases != MergeDD.NumVBases)
1793 DetectedOdrViolation = true;
1794 // FIXME: Issue a diagnostic if the base classes don't match when we come
1795 // to lazily load them.
1797 // FIXME: Issue a diagnostic if the list of conversion functions doesn't
1798 // match when we come to lazily load them.
1799 if (MergeDD.ComputedVisibleConversions && !DD.ComputedVisibleConversions) {
1800 DD.VisibleConversions = std::move(MergeDD.VisibleConversions);
1801 DD.ComputedVisibleConversions = true;
1804 // FIXME: Issue a diagnostic if FirstFriend doesn't match when we come to
1808 // FIXME: ODR-checking for merging lambdas (this happens, for instance,
1809 // when they occur within the body of a function template specialization).
1812 if (D->getODRHash() != MergeDD.ODRHash) {
1813 DetectedOdrViolation = true;
1816 if (DetectedOdrViolation)
1817 Reader.PendingOdrMergeFailures[DD.Definition].push_back(
1818 {MergeDD.Definition, &MergeDD});
1821 void ASTDeclReader::ReadCXXRecordDefinition(CXXRecordDecl *D, bool Update) {
1822 struct CXXRecordDecl::DefinitionData *DD;
1823 ASTContext &C = Reader.getContext();
1825 // Determine whether this is a lambda closure type, so that we can
1826 // allocate the appropriate DefinitionData structure.
1827 bool IsLambda = Record.readInt();
1829 DD = new (C) CXXRecordDecl::LambdaDefinitionData(D, nullptr, false, false,
1832 DD = new (C) struct CXXRecordDecl::DefinitionData(D);
1834 CXXRecordDecl *Canon = D->getCanonicalDecl();
1835 // Set decl definition data before reading it, so that during deserialization
1836 // when we read CXXRecordDecl, it already has definition data and we don't
1838 if (!Canon->DefinitionData)
1839 Canon->DefinitionData = DD;
1840 D->DefinitionData = Canon->DefinitionData;
1841 ReadCXXDefinitionData(*DD, D);
1843 // We might already have a different definition for this record. This can
1844 // happen either because we're reading an update record, or because we've
1845 // already done some merging. Either way, just merge into it.
1846 if (Canon->DefinitionData != DD) {
1847 MergeDefinitionData(Canon, std::move(*DD));
1851 // Mark this declaration as being a definition.
1852 D->setCompleteDefinition(true);
1854 // If this is not the first declaration or is an update record, we can have
1855 // other redeclarations already. Make a note that we need to propagate the
1856 // DefinitionData pointer onto them.
1857 if (Update || Canon != D)
1858 Reader.PendingDefinitions.insert(D);
1861 ASTDeclReader::RedeclarableResult
1862 ASTDeclReader::VisitCXXRecordDeclImpl(CXXRecordDecl *D) {
1863 RedeclarableResult Redecl = VisitRecordDeclImpl(D);
1865 ASTContext &C = Reader.getContext();
1868 CXXRecNotTemplate = 0, CXXRecTemplate, CXXRecMemberSpecialization
1870 switch ((CXXRecKind)Record.readInt()) {
1871 case CXXRecNotTemplate:
1872 // Merged when we merge the folding set entry in the primary template.
1873 if (!isa<ClassTemplateSpecializationDecl>(D))
1874 mergeRedeclarable(D, Redecl);
1876 case CXXRecTemplate: {
1877 // Merged when we merge the template.
1878 auto *Template = readDeclAs<ClassTemplateDecl>();
1879 D->TemplateOrInstantiation = Template;
1880 if (!Template->getTemplatedDecl()) {
1881 // We've not actually loaded the ClassTemplateDecl yet, because we're
1882 // currently being loaded as its pattern. Rely on it to set up our
1883 // TypeForDecl (see VisitClassTemplateDecl).
1885 // Beware: we do not yet know our canonical declaration, and may still
1886 // get merged once the surrounding class template has got off the ground.
1891 case CXXRecMemberSpecialization: {
1892 auto *RD = readDeclAs<CXXRecordDecl>();
1893 auto TSK = (TemplateSpecializationKind)Record.readInt();
1894 SourceLocation POI = readSourceLocation();
1895 MemberSpecializationInfo *MSI = new (C) MemberSpecializationInfo(RD, TSK);
1896 MSI->setPointOfInstantiation(POI);
1897 D->TemplateOrInstantiation = MSI;
1898 mergeRedeclarable(D, Redecl);
1903 bool WasDefinition = Record.readInt();
1905 ReadCXXRecordDefinition(D, /*Update*/false);
1907 // Propagate DefinitionData pointer from the canonical declaration.
1908 D->DefinitionData = D->getCanonicalDecl()->DefinitionData;
1910 // Lazily load the key function to avoid deserializing every method so we can
1912 if (WasDefinition) {
1913 DeclID KeyFn = readDeclID();
1914 if (KeyFn && D->isCompleteDefinition())
1915 // FIXME: This is wrong for the ARM ABI, where some other module may have
1916 // made this function no longer be a key function. We need an update
1917 // record or similar for that case.
1918 C.KeyFunctions[D] = KeyFn;
1924 void ASTDeclReader::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) {
1925 D->setExplicitSpecifier(Record.readExplicitSpec());
1926 VisitFunctionDecl(D);
1927 D->setIsCopyDeductionCandidate(Record.readInt());
1930 void ASTDeclReader::VisitCXXMethodDecl(CXXMethodDecl *D) {
1931 VisitFunctionDecl(D);
1933 unsigned NumOverridenMethods = Record.readInt();
1934 if (D->isCanonicalDecl()) {
1935 while (NumOverridenMethods--) {
1936 // Avoid invariant checking of CXXMethodDecl::addOverriddenMethod,
1937 // MD may be initializing.
1938 if (auto *MD = readDeclAs<CXXMethodDecl>())
1939 Reader.getContext().addOverriddenMethod(D, MD->getCanonicalDecl());
1942 // We don't care about which declarations this used to override; we get
1943 // the relevant information from the canonical declaration.
1944 Record.skipInts(NumOverridenMethods);
1948 void ASTDeclReader::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
1949 // We need the inherited constructor information to merge the declaration,
1950 // so we have to read it before we call VisitCXXMethodDecl.
1951 D->setExplicitSpecifier(Record.readExplicitSpec());
1952 if (D->isInheritingConstructor()) {
1953 auto *Shadow = readDeclAs<ConstructorUsingShadowDecl>();
1954 auto *Ctor = readDeclAs<CXXConstructorDecl>();
1955 *D->getTrailingObjects<InheritedConstructor>() =
1956 InheritedConstructor(Shadow, Ctor);
1959 VisitCXXMethodDecl(D);
1962 void ASTDeclReader::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
1963 VisitCXXMethodDecl(D);
1965 if (auto *OperatorDelete = readDeclAs<FunctionDecl>()) {
1966 CXXDestructorDecl *Canon = D->getCanonicalDecl();
1967 auto *ThisArg = Record.readExpr();
1968 // FIXME: Check consistency if we have an old and new operator delete.
1969 if (!Canon->OperatorDelete) {
1970 Canon->OperatorDelete = OperatorDelete;
1971 Canon->OperatorDeleteThisArg = ThisArg;
1976 void ASTDeclReader::VisitCXXConversionDecl(CXXConversionDecl *D) {
1977 D->setExplicitSpecifier(Record.readExplicitSpec());
1978 VisitCXXMethodDecl(D);
1981 void ASTDeclReader::VisitImportDecl(ImportDecl *D) {
1983 D->ImportedAndComplete.setPointer(readModule());
1984 D->ImportedAndComplete.setInt(Record.readInt());
1985 auto *StoredLocs = D->getTrailingObjects<SourceLocation>();
1986 for (unsigned I = 0, N = Record.back(); I != N; ++I)
1987 StoredLocs[I] = readSourceLocation();
1988 Record.skipInts(1); // The number of stored source locations.
1991 void ASTDeclReader::VisitAccessSpecDecl(AccessSpecDecl *D) {
1993 D->setColonLoc(readSourceLocation());
1996 void ASTDeclReader::VisitFriendDecl(FriendDecl *D) {
1998 if (Record.readInt()) // hasFriendDecl
1999 D->Friend = readDeclAs<NamedDecl>();
2001 D->Friend = readTypeSourceInfo();
2002 for (unsigned i = 0; i != D->NumTPLists; ++i)
2003 D->getTrailingObjects<TemplateParameterList *>()[i] =
2004 Record.readTemplateParameterList();
2005 D->NextFriend = readDeclID();
2006 D->UnsupportedFriend = (Record.readInt() != 0);
2007 D->FriendLoc = readSourceLocation();
2010 void ASTDeclReader::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
2012 unsigned NumParams = Record.readInt();
2013 D->NumParams = NumParams;
2014 D->Params = new TemplateParameterList*[NumParams];
2015 for (unsigned i = 0; i != NumParams; ++i)
2016 D->Params[i] = Record.readTemplateParameterList();
2017 if (Record.readInt()) // HasFriendDecl
2018 D->Friend = readDeclAs<NamedDecl>();
2020 D->Friend = readTypeSourceInfo();
2021 D->FriendLoc = readSourceLocation();
2024 DeclID ASTDeclReader::VisitTemplateDecl(TemplateDecl *D) {
2027 DeclID PatternID = readDeclID();
2028 auto *TemplatedDecl = cast_or_null<NamedDecl>(Reader.GetDecl(PatternID));
2029 TemplateParameterList *TemplateParams = Record.readTemplateParameterList();
2030 D->init(TemplatedDecl, TemplateParams);
2035 void ASTDeclReader::VisitConceptDecl(ConceptDecl *D) {
2036 VisitTemplateDecl(D);
2037 D->ConstraintExpr = Record.readExpr();
2041 void ASTDeclReader::VisitRequiresExprBodyDecl(RequiresExprBodyDecl *D) {
2044 ASTDeclReader::RedeclarableResult
2045 ASTDeclReader::VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D) {
2046 RedeclarableResult Redecl = VisitRedeclarable(D);
2048 // Make sure we've allocated the Common pointer first. We do this before
2049 // VisitTemplateDecl so that getCommonPtr() can be used during initialization.
2050 RedeclarableTemplateDecl *CanonD = D->getCanonicalDecl();
2051 if (!CanonD->Common) {
2052 CanonD->Common = CanonD->newCommon(Reader.getContext());
2053 Reader.PendingDefinitions.insert(CanonD);
2055 D->Common = CanonD->Common;
2057 // If this is the first declaration of the template, fill in the information
2058 // for the 'common' pointer.
2059 if (ThisDeclID == Redecl.getFirstID()) {
2060 if (auto *RTD = readDeclAs<RedeclarableTemplateDecl>()) {
2061 assert(RTD->getKind() == D->getKind() &&
2062 "InstantiatedFromMemberTemplate kind mismatch");
2063 D->setInstantiatedFromMemberTemplate(RTD);
2064 if (Record.readInt())
2065 D->setMemberSpecialization();
2069 DeclID PatternID = VisitTemplateDecl(D);
2070 D->IdentifierNamespace = Record.readInt();
2072 mergeRedeclarable(D, Redecl, PatternID);
2074 // If we merged the template with a prior declaration chain, merge the common
2076 // FIXME: Actually merge here, don't just overwrite.
2077 D->Common = D->getCanonicalDecl()->Common;
2082 void ASTDeclReader::VisitClassTemplateDecl(ClassTemplateDecl *D) {
2083 RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
2085 if (ThisDeclID == Redecl.getFirstID()) {
2086 // This ClassTemplateDecl owns a CommonPtr; read it to keep track of all of
2087 // the specializations.
2088 SmallVector<serialization::DeclID, 32> SpecIDs;
2089 readDeclIDList(SpecIDs);
2090 ASTDeclReader::AddLazySpecializations(D, SpecIDs);
2093 if (D->getTemplatedDecl()->TemplateOrInstantiation) {
2094 // We were loaded before our templated declaration was. We've not set up
2095 // its corresponding type yet (see VisitCXXRecordDeclImpl), so reconstruct
2097 Reader.getContext().getInjectedClassNameType(
2098 D->getTemplatedDecl(), D->getInjectedClassNameSpecialization());
2102 void ASTDeclReader::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) {
2103 llvm_unreachable("BuiltinTemplates are not serialized");
2106 /// TODO: Unify with ClassTemplateDecl version?
2107 /// May require unifying ClassTemplateDecl and
2108 /// VarTemplateDecl beyond TemplateDecl...
2109 void ASTDeclReader::VisitVarTemplateDecl(VarTemplateDecl *D) {
2110 RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
2112 if (ThisDeclID == Redecl.getFirstID()) {
2113 // This VarTemplateDecl owns a CommonPtr; read it to keep track of all of
2114 // the specializations.
2115 SmallVector<serialization::DeclID, 32> SpecIDs;
2116 readDeclIDList(SpecIDs);
2117 ASTDeclReader::AddLazySpecializations(D, SpecIDs);
2121 ASTDeclReader::RedeclarableResult
2122 ASTDeclReader::VisitClassTemplateSpecializationDeclImpl(
2123 ClassTemplateSpecializationDecl *D) {
2124 RedeclarableResult Redecl = VisitCXXRecordDeclImpl(D);
2126 ASTContext &C = Reader.getContext();
2127 if (Decl *InstD = readDecl()) {
2128 if (auto *CTD = dyn_cast<ClassTemplateDecl>(InstD)) {
2129 D->SpecializedTemplate = CTD;
2131 SmallVector<TemplateArgument, 8> TemplArgs;
2132 Record.readTemplateArgumentList(TemplArgs);
2133 TemplateArgumentList *ArgList
2134 = TemplateArgumentList::CreateCopy(C, TemplArgs);
2136 new (C) ClassTemplateSpecializationDecl::
2137 SpecializedPartialSpecialization();
2138 PS->PartialSpecialization
2139 = cast<ClassTemplatePartialSpecializationDecl>(InstD);
2140 PS->TemplateArgs = ArgList;
2141 D->SpecializedTemplate = PS;
2145 SmallVector<TemplateArgument, 8> TemplArgs;
2146 Record.readTemplateArgumentList(TemplArgs, /*Canonicalize*/ true);
2147 D->TemplateArgs = TemplateArgumentList::CreateCopy(C, TemplArgs);
2148 D->PointOfInstantiation = readSourceLocation();
2149 D->SpecializationKind = (TemplateSpecializationKind)Record.readInt();
2151 bool writtenAsCanonicalDecl = Record.readInt();
2152 if (writtenAsCanonicalDecl) {
2153 auto *CanonPattern = readDeclAs<ClassTemplateDecl>();
2154 if (D->isCanonicalDecl()) { // It's kept in the folding set.
2155 // Set this as, or find, the canonical declaration for this specialization
2156 ClassTemplateSpecializationDecl *CanonSpec;
2157 if (auto *Partial = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) {
2158 CanonSpec = CanonPattern->getCommonPtr()->PartialSpecializations
2159 .GetOrInsertNode(Partial);
2162 CanonPattern->getCommonPtr()->Specializations.GetOrInsertNode(D);
2164 // If there was already a canonical specialization, merge into it.
2165 if (CanonSpec != D) {
2166 mergeRedeclarable<TagDecl>(D, CanonSpec, Redecl);
2168 // This declaration might be a definition. Merge with any existing
2170 if (auto *DDD = D->DefinitionData) {
2171 if (CanonSpec->DefinitionData)
2172 MergeDefinitionData(CanonSpec, std::move(*DDD));
2174 CanonSpec->DefinitionData = D->DefinitionData;
2176 D->DefinitionData = CanonSpec->DefinitionData;
2182 if (TypeSourceInfo *TyInfo = readTypeSourceInfo()) {
2183 auto *ExplicitInfo =
2184 new (C) ClassTemplateSpecializationDecl::ExplicitSpecializationInfo;
2185 ExplicitInfo->TypeAsWritten = TyInfo;
2186 ExplicitInfo->ExternLoc = readSourceLocation();
2187 ExplicitInfo->TemplateKeywordLoc = readSourceLocation();
2188 D->ExplicitInfo = ExplicitInfo;
2194 void ASTDeclReader::VisitClassTemplatePartialSpecializationDecl(
2195 ClassTemplatePartialSpecializationDecl *D) {
2196 // We need to read the template params first because redeclarable is going to
2197 // need them for profiling
2198 TemplateParameterList *Params = Record.readTemplateParameterList();
2199 D->TemplateParams = Params;
2200 D->ArgsAsWritten = Record.readASTTemplateArgumentListInfo();
2202 RedeclarableResult Redecl = VisitClassTemplateSpecializationDeclImpl(D);
2204 // These are read/set from/to the first declaration.
2205 if (ThisDeclID == Redecl.getFirstID()) {
2206 D->InstantiatedFromMember.setPointer(
2207 readDeclAs<ClassTemplatePartialSpecializationDecl>());
2208 D->InstantiatedFromMember.setInt(Record.readInt());
2212 void ASTDeclReader::VisitClassScopeFunctionSpecializationDecl(
2213 ClassScopeFunctionSpecializationDecl *D) {
2215 D->Specialization = readDeclAs<CXXMethodDecl>();
2216 if (Record.readInt())
2217 D->TemplateArgs = Record.readASTTemplateArgumentListInfo();
2220 void ASTDeclReader::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
2221 RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
2223 if (ThisDeclID == Redecl.getFirstID()) {
2224 // This FunctionTemplateDecl owns a CommonPtr; read it.
2225 SmallVector<serialization::DeclID, 32> SpecIDs;
2226 readDeclIDList(SpecIDs);
2227 ASTDeclReader::AddLazySpecializations(D, SpecIDs);
2231 /// TODO: Unify with ClassTemplateSpecializationDecl version?
2232 /// May require unifying ClassTemplate(Partial)SpecializationDecl and
2233 /// VarTemplate(Partial)SpecializationDecl with a new data
2234 /// structure Template(Partial)SpecializationDecl, and
2235 /// using Template(Partial)SpecializationDecl as input type.
2236 ASTDeclReader::RedeclarableResult
2237 ASTDeclReader::VisitVarTemplateSpecializationDeclImpl(
2238 VarTemplateSpecializationDecl *D) {
2239 RedeclarableResult Redecl = VisitVarDeclImpl(D);
2241 ASTContext &C = Reader.getContext();
2242 if (Decl *InstD = readDecl()) {
2243 if (auto *VTD = dyn_cast<VarTemplateDecl>(InstD)) {
2244 D->SpecializedTemplate = VTD;
2246 SmallVector<TemplateArgument, 8> TemplArgs;
2247 Record.readTemplateArgumentList(TemplArgs);
2248 TemplateArgumentList *ArgList = TemplateArgumentList::CreateCopy(
2252 VarTemplateSpecializationDecl::SpecializedPartialSpecialization();
2253 PS->PartialSpecialization =
2254 cast<VarTemplatePartialSpecializationDecl>(InstD);
2255 PS->TemplateArgs = ArgList;
2256 D->SpecializedTemplate = PS;
2261 if (TypeSourceInfo *TyInfo = readTypeSourceInfo()) {
2262 auto *ExplicitInfo =
2263 new (C) VarTemplateSpecializationDecl::ExplicitSpecializationInfo;
2264 ExplicitInfo->TypeAsWritten = TyInfo;
2265 ExplicitInfo->ExternLoc = readSourceLocation();
2266 ExplicitInfo->TemplateKeywordLoc = readSourceLocation();
2267 D->ExplicitInfo = ExplicitInfo;
2270 SmallVector<TemplateArgument, 8> TemplArgs;
2271 Record.readTemplateArgumentList(TemplArgs, /*Canonicalize*/ true);
2272 D->TemplateArgs = TemplateArgumentList::CreateCopy(C, TemplArgs);
2273 D->PointOfInstantiation = readSourceLocation();
2274 D->SpecializationKind = (TemplateSpecializationKind)Record.readInt();
2275 D->IsCompleteDefinition = Record.readInt();
2277 bool writtenAsCanonicalDecl = Record.readInt();
2278 if (writtenAsCanonicalDecl) {
2279 auto *CanonPattern = readDeclAs<VarTemplateDecl>();
2280 if (D->isCanonicalDecl()) { // It's kept in the folding set.
2281 // FIXME: If it's already present, merge it.
2282 if (auto *Partial = dyn_cast<VarTemplatePartialSpecializationDecl>(D)) {
2283 CanonPattern->getCommonPtr()->PartialSpecializations
2284 .GetOrInsertNode(Partial);
2286 CanonPattern->getCommonPtr()->Specializations.GetOrInsertNode(D);
2294 /// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
2295 /// May require unifying ClassTemplate(Partial)SpecializationDecl and
2296 /// VarTemplate(Partial)SpecializationDecl with a new data
2297 /// structure Template(Partial)SpecializationDecl, and
2298 /// using Template(Partial)SpecializationDecl as input type.
2299 void ASTDeclReader::VisitVarTemplatePartialSpecializationDecl(
2300 VarTemplatePartialSpecializationDecl *D) {
2301 TemplateParameterList *Params = Record.readTemplateParameterList();
2302 D->TemplateParams = Params;
2303 D->ArgsAsWritten = Record.readASTTemplateArgumentListInfo();
2305 RedeclarableResult Redecl = VisitVarTemplateSpecializationDeclImpl(D);
2307 // These are read/set from/to the first declaration.
2308 if (ThisDeclID == Redecl.getFirstID()) {
2309 D->InstantiatedFromMember.setPointer(
2310 readDeclAs<VarTemplatePartialSpecializationDecl>());
2311 D->InstantiatedFromMember.setInt(Record.readInt());
2315 void ASTDeclReader::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
2318 D->setDeclaredWithTypename(Record.readInt());
2320 if (Record.readBool()) {
2321 NestedNameSpecifierLoc NNS = Record.readNestedNameSpecifierLoc();
2322 DeclarationNameInfo DN = Record.readDeclarationNameInfo();
2323 ConceptDecl *NamedConcept = Record.readDeclAs<ConceptDecl>();
2324 const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr;
2325 if (Record.readBool())
2326 ArgsAsWritten = Record.readASTTemplateArgumentListInfo();
2327 Expr *ImmediatelyDeclaredConstraint = Record.readExpr();
2328 D->setTypeConstraint(NNS, DN, /*FoundDecl=*/nullptr, NamedConcept,
2329 ArgsAsWritten, ImmediatelyDeclaredConstraint);
2330 if ((D->ExpandedParameterPack = Record.readInt()))
2331 D->NumExpanded = Record.readInt();
2334 if (Record.readInt())
2335 D->setDefaultArgument(readTypeSourceInfo());
2338 void ASTDeclReader::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
2339 VisitDeclaratorDecl(D);
2340 // TemplateParmPosition.
2341 D->setDepth(Record.readInt());
2342 D->setPosition(Record.readInt());
2343 if (D->hasPlaceholderTypeConstraint())
2344 D->setPlaceholderTypeConstraint(Record.readExpr());
2345 if (D->isExpandedParameterPack()) {
2346 auto TypesAndInfos =
2347 D->getTrailingObjects<std::pair<QualType, TypeSourceInfo *>>();
2348 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
2349 new (&TypesAndInfos[I].first) QualType(Record.readType());
2350 TypesAndInfos[I].second = readTypeSourceInfo();
2353 // Rest of NonTypeTemplateParmDecl.
2354 D->ParameterPack = Record.readInt();
2355 if (Record.readInt())
2356 D->setDefaultArgument(Record.readExpr());
2360 void ASTDeclReader::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
2361 VisitTemplateDecl(D);
2362 // TemplateParmPosition.
2363 D->setDepth(Record.readInt());
2364 D->setPosition(Record.readInt());
2365 if (D->isExpandedParameterPack()) {
2366 auto **Data = D->getTrailingObjects<TemplateParameterList *>();
2367 for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
2369 Data[I] = Record.readTemplateParameterList();
2371 // Rest of TemplateTemplateParmDecl.
2372 D->ParameterPack = Record.readInt();
2373 if (Record.readInt())
2374 D->setDefaultArgument(Reader.getContext(),
2375 Record.readTemplateArgumentLoc());
2379 void ASTDeclReader::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
2380 VisitRedeclarableTemplateDecl(D);
2383 void ASTDeclReader::VisitStaticAssertDecl(StaticAssertDecl *D) {
2385 D->AssertExprAndFailed.setPointer(Record.readExpr());
2386 D->AssertExprAndFailed.setInt(Record.readInt());
2387 D->Message = cast_or_null<StringLiteral>(Record.readExpr());
2388 D->RParenLoc = readSourceLocation();
2391 void ASTDeclReader::VisitEmptyDecl(EmptyDecl *D) {
2395 void ASTDeclReader::VisitLifetimeExtendedTemporaryDecl(
2396 LifetimeExtendedTemporaryDecl *D) {
2398 D->ExtendingDecl = readDeclAs<ValueDecl>();
2399 D->ExprWithTemporary = Record.readStmt();
2400 if (Record.readInt())
2401 D->Value = new (D->getASTContext()) APValue(Record.readAPValue());
2402 D->ManglingNumber = Record.readInt();
2406 std::pair<uint64_t, uint64_t>
2407 ASTDeclReader::VisitDeclContext(DeclContext *DC) {
2408 uint64_t LexicalOffset = ReadLocalOffset();
2409 uint64_t VisibleOffset = ReadLocalOffset();
2410 return std::make_pair(LexicalOffset, VisibleOffset);
2413 template <typename T>
2414 ASTDeclReader::RedeclarableResult
2415 ASTDeclReader::VisitRedeclarable(Redeclarable<T> *D) {
2416 DeclID FirstDeclID = readDeclID();
2417 Decl *MergeWith = nullptr;
2419 bool IsKeyDecl = ThisDeclID == FirstDeclID;
2420 bool IsFirstLocalDecl = false;
2422 uint64_t RedeclOffset = 0;
2424 // 0 indicates that this declaration was the only declaration of its entity,
2425 // and is used for space optimization.
2426 if (FirstDeclID == 0) {
2427 FirstDeclID = ThisDeclID;
2429 IsFirstLocalDecl = true;
2430 } else if (unsigned N = Record.readInt()) {
2431 // This declaration was the first local declaration, but may have imported
2432 // other declarations.
2434 IsFirstLocalDecl = true;
2436 // We have some declarations that must be before us in our redeclaration
2437 // chain. Read them now, and remember that we ought to merge with one of
2439 // FIXME: Provide a known merge target to the second and subsequent such
2441 for (unsigned I = 0; I != N - 1; ++I)
2442 MergeWith = readDecl();
2444 RedeclOffset = ReadLocalOffset();
2446 // This declaration was not the first local declaration. Read the first
2447 // local declaration now, to trigger the import of other redeclarations.
2451 auto *FirstDecl = cast_or_null<T>(Reader.GetDecl(FirstDeclID));
2452 if (FirstDecl != D) {
2453 // We delay loading of the redeclaration chain to avoid deeply nested calls.
2454 // We temporarily set the first (canonical) declaration as the previous one
2455 // which is the one that matters and mark the real previous DeclID to be
2456 // loaded & attached later on.
2457 D->RedeclLink = Redeclarable<T>::PreviousDeclLink(FirstDecl);
2458 D->First = FirstDecl->getCanonicalDecl();
2461 auto *DAsT = static_cast<T *>(D);
2463 // Note that we need to load local redeclarations of this decl and build a
2464 // decl chain for them. This must happen *after* we perform the preloading
2465 // above; this ensures that the redeclaration chain is built in the correct
2467 if (IsFirstLocalDecl)
2468 Reader.PendingDeclChains.push_back(std::make_pair(DAsT, RedeclOffset));
2470 return RedeclarableResult(MergeWith, FirstDeclID, IsKeyDecl);
2473 /// Attempts to merge the given declaration (D) with another declaration
2474 /// of the same entity.
2475 template<typename T>
2476 void ASTDeclReader::mergeRedeclarable(Redeclarable<T> *DBase,
2477 RedeclarableResult &Redecl,
2478 DeclID TemplatePatternID) {
2479 // If modules are not available, there is no reason to perform this merge.
2480 if (!Reader.getContext().getLangOpts().Modules)
2483 // If we're not the canonical declaration, we don't need to merge.
2484 if (!DBase->isFirstDecl())
2487 auto *D = static_cast<T *>(DBase);
2489 if (auto *Existing = Redecl.getKnownMergeTarget())
2490 // We already know of an existing declaration we should merge with.
2491 mergeRedeclarable(D, cast<T>(Existing), Redecl, TemplatePatternID);
2492 else if (FindExistingResult ExistingRes = findExisting(D))
2493 if (T *Existing = ExistingRes)
2494 mergeRedeclarable(D, Existing, Redecl, TemplatePatternID);
2497 /// "Cast" to type T, asserting if we don't have an implicit conversion.
2498 /// We use this to put code in a template that will only be valid for certain
2500 template<typename T> static T assert_cast(T t) { return t; }
2501 template<typename T> static T assert_cast(...) {
2502 llvm_unreachable("bad assert_cast");
2505 /// Merge together the pattern declarations from two template
2507 void ASTDeclReader::mergeTemplatePattern(RedeclarableTemplateDecl *D,
2508 RedeclarableTemplateDecl *Existing,
2509 DeclID DsID, bool IsKeyDecl) {
2510 auto *DPattern = D->getTemplatedDecl();
2511 auto *ExistingPattern = Existing->getTemplatedDecl();
2512 RedeclarableResult Result(/*MergeWith*/ ExistingPattern,
2513 DPattern->getCanonicalDecl()->getGlobalID(),
2516 if (auto *DClass = dyn_cast<CXXRecordDecl>(DPattern)) {
2517 // Merge with any existing definition.
2518 // FIXME: This is duplicated in several places. Refactor.
2519 auto *ExistingClass =
2520 cast<CXXRecordDecl>(ExistingPattern)->getCanonicalDecl();
2521 if (auto *DDD = DClass->DefinitionData) {
2522 if (ExistingClass->DefinitionData) {
2523 MergeDefinitionData(ExistingClass, std::move(*DDD));
2525 ExistingClass->DefinitionData = DClass->DefinitionData;
2526 // We may have skipped this before because we thought that DClass
2527 // was the canonical declaration.
2528 Reader.PendingDefinitions.insert(DClass);
2531 DClass->DefinitionData = ExistingClass->DefinitionData;
2533 return mergeRedeclarable(DClass, cast<TagDecl>(ExistingPattern),
2536 if (auto *DFunction = dyn_cast<FunctionDecl>(DPattern))
2537 return mergeRedeclarable(DFunction, cast<FunctionDecl>(ExistingPattern),
2539 if (auto *DVar = dyn_cast<VarDecl>(DPattern))
2540 return mergeRedeclarable(DVar, cast<VarDecl>(ExistingPattern), Result);
2541 if (auto *DAlias = dyn_cast<TypeAliasDecl>(DPattern))
2542 return mergeRedeclarable(DAlias, cast<TypedefNameDecl>(ExistingPattern),
2544 llvm_unreachable("merged an unknown kind of redeclarable template");
2547 /// Attempts to merge the given declaration (D) with another declaration
2548 /// of the same entity.
2549 template<typename T>
2550 void ASTDeclReader::mergeRedeclarable(Redeclarable<T> *DBase, T *Existing,
2551 RedeclarableResult &Redecl,
2552 DeclID TemplatePatternID) {
2553 auto *D = static_cast<T *>(DBase);
2554 T *ExistingCanon = Existing->getCanonicalDecl();
2555 T *DCanon = D->getCanonicalDecl();
2556 if (ExistingCanon != DCanon) {
2557 assert(DCanon->getGlobalID() == Redecl.getFirstID() &&
2558 "already merged this declaration");
2560 // Have our redeclaration link point back at the canonical declaration
2561 // of the existing declaration, so that this declaration has the
2562 // appropriate canonical declaration.
2563 D->RedeclLink = Redeclarable<T>::PreviousDeclLink(ExistingCanon);
2564 D->First = ExistingCanon;
2565 ExistingCanon->Used |= D->Used;
2568 // When we merge a namespace, update its pointer to the first namespace.
2569 // We cannot have loaded any redeclarations of this declaration yet, so
2570 // there's nothing else that needs to be updated.
2571 if (auto *Namespace = dyn_cast<NamespaceDecl>(D))
2572 Namespace->AnonOrFirstNamespaceAndInline.setPointer(
2573 assert_cast<NamespaceDecl*>(ExistingCanon));
2575 // When we merge a template, merge its pattern.
2576 if (auto *DTemplate = dyn_cast<RedeclarableTemplateDecl>(D))
2577 mergeTemplatePattern(
2578 DTemplate, assert_cast<RedeclarableTemplateDecl*>(ExistingCanon),
2579 TemplatePatternID, Redecl.isKeyDecl());
2581 // If this declaration is a key declaration, make a note of that.
2582 if (Redecl.isKeyDecl())
2583 Reader.KeyDecls[ExistingCanon].push_back(Redecl.getFirstID());
2587 /// ODR-like semantics for C/ObjC allow us to merge tag types and a structural
2588 /// check in Sema guarantees the types can be merged (see C11 6.2.7/1 or C89
2589 /// 6.1.2.6/1). Although most merging is done in Sema, we need to guarantee
2590 /// that some types are mergeable during deserialization, otherwise name
2591 /// lookup fails. This is the case for EnumConstantDecl.
2592 static bool allowODRLikeMergeInC(NamedDecl *ND) {
2595 // TODO: implement merge for other necessary decls.
2596 if (isa<EnumConstantDecl>(ND))
2601 /// Attempts to merge LifetimeExtendedTemporaryDecl with
2602 /// identical class definitions from two different modules.
2603 void ASTDeclReader::mergeMergeable(LifetimeExtendedTemporaryDecl *D) {
2604 // If modules are not available, there is no reason to perform this merge.
2605 if (!Reader.getContext().getLangOpts().Modules)
2608 LifetimeExtendedTemporaryDecl *LETDecl = D;
2610 LifetimeExtendedTemporaryDecl *&LookupResult =
2611 Reader.LETemporaryForMerging[std::make_pair(
2612 LETDecl->getExtendingDecl(), LETDecl->getManglingNumber())];
2614 Reader.getContext().setPrimaryMergedDecl(LETDecl,
2615 LookupResult->getCanonicalDecl());
2617 LookupResult = LETDecl;
2620 /// Attempts to merge the given declaration (D) with another declaration
2621 /// of the same entity, for the case where the entity is not actually
2622 /// redeclarable. This happens, for instance, when merging the fields of
2623 /// identical class definitions from two different modules.
2624 template<typename T>
2625 void ASTDeclReader::mergeMergeable(Mergeable<T> *D) {
2626 // If modules are not available, there is no reason to perform this merge.
2627 if (!Reader.getContext().getLangOpts().Modules)
2630 // ODR-based merging is performed in C++ and in some cases (tag types) in C.
2631 // Note that C identically-named things in different translation units are
2632 // not redeclarations, but may still have compatible types, where ODR-like
2633 // semantics may apply.
2634 if (!Reader.getContext().getLangOpts().CPlusPlus &&
2635 !allowODRLikeMergeInC(dyn_cast<NamedDecl>(static_cast<T*>(D))))
2638 if (FindExistingResult ExistingRes = findExisting(static_cast<T*>(D)))
2639 if (T *Existing = ExistingRes)
2640 Reader.getContext().setPrimaryMergedDecl(static_cast<T *>(D),
2641 Existing->getCanonicalDecl());
2644 void ASTDeclReader::VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D) {
2646 unsigned NumVars = D->varlist_size();
2647 SmallVector<Expr *, 16> Vars;
2648 Vars.reserve(NumVars);
2649 for (unsigned i = 0; i != NumVars; ++i) {
2650 Vars.push_back(Record.readExpr());
2655 void ASTDeclReader::VisitOMPAllocateDecl(OMPAllocateDecl *D) {
2657 unsigned NumVars = D->varlist_size();
2658 unsigned NumClauses = D->clauselist_size();
2659 SmallVector<Expr *, 16> Vars;
2660 Vars.reserve(NumVars);
2661 for (unsigned i = 0; i != NumVars; ++i) {
2662 Vars.push_back(Record.readExpr());
2665 SmallVector<OMPClause *, 8> Clauses;
2666 Clauses.reserve(NumClauses);
2667 for (unsigned I = 0; I != NumClauses; ++I)
2668 Clauses.push_back(Record.readOMPClause());
2669 D->setClauses(Clauses);
2672 void ASTDeclReader::VisitOMPRequiresDecl(OMPRequiresDecl * D) {
2674 unsigned NumClauses = D->clauselist_size();
2675 SmallVector<OMPClause *, 8> Clauses;
2676 Clauses.reserve(NumClauses);
2677 for (unsigned I = 0; I != NumClauses; ++I)
2678 Clauses.push_back(Record.readOMPClause());
2679 D->setClauses(Clauses);
2682 void ASTDeclReader::VisitOMPDeclareReductionDecl(OMPDeclareReductionDecl *D) {
2684 D->setLocation(readSourceLocation());
2685 Expr *In = Record.readExpr();
2686 Expr *Out = Record.readExpr();
2687 D->setCombinerData(In, Out);
2688 Expr *Combiner = Record.readExpr();
2689 D->setCombiner(Combiner);
2690 Expr *Orig = Record.readExpr();
2691 Expr *Priv = Record.readExpr();
2692 D->setInitializerData(Orig, Priv);
2693 Expr *Init = Record.readExpr();
2694 auto IK = static_cast<OMPDeclareReductionDecl::InitKind>(Record.readInt());
2695 D->setInitializer(Init, IK);
2696 D->PrevDeclInScope = readDeclID();
2699 void ASTDeclReader::VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D) {
2701 D->setLocation(readSourceLocation());
2702 Expr *MapperVarRefE = Record.readExpr();
2703 D->setMapperVarRef(MapperVarRefE);
2704 D->VarName = Record.readDeclarationName();
2705 D->PrevDeclInScope = readDeclID();
2706 unsigned NumClauses = D->clauselist_size();
2707 SmallVector<OMPClause *, 8> Clauses;
2708 Clauses.reserve(NumClauses);
2709 for (unsigned I = 0; I != NumClauses; ++I)
2710 Clauses.push_back(Record.readOMPClause());
2711 D->setClauses(Clauses);
2714 void ASTDeclReader::VisitOMPCapturedExprDecl(OMPCapturedExprDecl *D) {
2718 //===----------------------------------------------------------------------===//
2719 // Attribute Reading
2720 //===----------------------------------------------------------------------===//
2724 ASTRecordReader &Reader;
2727 AttrReader(ASTRecordReader &Reader) : Reader(Reader) {}
2729 uint64_t readInt() {
2730 return Reader.readInt();
2733 SourceRange readSourceRange() {
2734 return Reader.readSourceRange();
2737 SourceLocation readSourceLocation() {
2738 return Reader.readSourceLocation();
2741 Expr *readExpr() { return Reader.readExpr(); }
2743 std::string readString() {
2744 return Reader.readString();
2747 TypeSourceInfo *readTypeSourceInfo() {
2748 return Reader.readTypeSourceInfo();
2751 IdentifierInfo *readIdentifier() {
2752 return Reader.readIdentifier();
2755 VersionTuple readVersionTuple() {
2756 return Reader.readVersionTuple();
2759 template <typename T> T *GetLocalDeclAs(uint32_t LocalID) {
2760 return Reader.GetLocalDeclAs<T>(LocalID);
2765 Attr *ASTRecordReader::readAttr() {
2766 AttrReader Record(*this);
2767 auto V = Record.readInt();
2771 Attr *New = nullptr;
2772 // Kind is stored as a 1-based integer because 0 is used to indicate a null
2774 auto Kind = static_cast<attr::Kind>(V - 1);
2775 ASTContext &Context = getContext();
2777 IdentifierInfo *AttrName = Record.readIdentifier();
2778 IdentifierInfo *ScopeName = Record.readIdentifier();
2779 SourceRange AttrRange = Record.readSourceRange();
2780 SourceLocation ScopeLoc = Record.readSourceLocation();
2781 unsigned ParsedKind = Record.readInt();
2782 unsigned Syntax = Record.readInt();
2783 unsigned SpellingIndex = Record.readInt();
2785 AttributeCommonInfo Info(AttrName, ScopeName, AttrRange, ScopeLoc,
2786 AttributeCommonInfo::Kind(ParsedKind),
2787 AttributeCommonInfo::Syntax(Syntax), SpellingIndex);
2789 #include "clang/Serialization/AttrPCHRead.inc"
2791 assert(New && "Unable to decode attribute?");
2795 /// Reads attributes from the current stream position.
2796 void ASTRecordReader::readAttributes(AttrVec &Attrs) {
2797 for (unsigned I = 0, E = readInt(); I != E; ++I)
2798 Attrs.push_back(readAttr());
2801 //===----------------------------------------------------------------------===//
2802 // ASTReader Implementation
2803 //===----------------------------------------------------------------------===//
2805 /// Note that we have loaded the declaration with the given
2808 /// This routine notes that this declaration has already been loaded,
2809 /// so that future GetDecl calls will return this declaration rather
2810 /// than trying to load a new declaration.
2811 inline void ASTReader::LoadedDecl(unsigned Index, Decl *D) {
2812 assert(!DeclsLoaded[Index] && "Decl loaded twice?");
2813 DeclsLoaded[Index] = D;
2816 /// Determine whether the consumer will be interested in seeing
2817 /// this declaration (via HandleTopLevelDecl).
2819 /// This routine should return true for anything that might affect
2820 /// code generation, e.g., inline function definitions, Objective-C
2821 /// declarations with metadata, etc.
2822 static bool isConsumerInterestedIn(ASTContext &Ctx, Decl *D, bool HasBody) {
2823 // An ObjCMethodDecl is never considered as "interesting" because its
2824 // implementation container always is.
2826 // An ImportDecl or VarDecl imported from a module map module will get
2827 // emitted when we import the relevant module.
2828 if (isPartOfPerModuleInitializer(D)) {
2829 auto *M = D->getImportedOwningModule();
2830 if (M && M->Kind == Module::ModuleMapModule &&
2831 Ctx.DeclMustBeEmitted(D))
2835 if (isa<FileScopeAsmDecl>(D) ||
2836 isa<ObjCProtocolDecl>(D) ||
2837 isa<ObjCImplDecl>(D) ||
2838 isa<ImportDecl>(D) ||
2839 isa<PragmaCommentDecl>(D) ||
2840 isa<PragmaDetectMismatchDecl>(D))
2842 if (isa<OMPThreadPrivateDecl>(D) || isa<OMPDeclareReductionDecl>(D) ||
2843 isa<OMPDeclareMapperDecl>(D) || isa<OMPAllocateDecl>(D))
2844 return !D->getDeclContext()->isFunctionOrMethod();
2845 if (const auto *Var = dyn_cast<VarDecl>(D))
2846 return Var->isFileVarDecl() &&
2847 (Var->isThisDeclarationADefinition() == VarDecl::Definition ||
2848 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Var));
2849 if (const auto *Func = dyn_cast<FunctionDecl>(D))
2850 return Func->doesThisDeclarationHaveABody() || HasBody;
2852 if (auto *ES = D->getASTContext().getExternalSource())
2853 if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
2859 /// Get the correct cursor and offset for loading a declaration.
2860 ASTReader::RecordLocation
2861 ASTReader::DeclCursorForID(DeclID ID, SourceLocation &Loc) {
2862 GlobalDeclMapType::iterator I = GlobalDeclMap.find(ID);
2863 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
2864 ModuleFile *M = I->second;
2865 const DeclOffset &DOffs =
2866 M->DeclOffsets[ID - M->BaseDeclID - NUM_PREDEF_DECL_IDS];
2867 Loc = TranslateSourceLocation(*M, DOffs.getLocation());
2868 return RecordLocation(M, DOffs.BitOffset);
2871 ASTReader::RecordLocation ASTReader::getLocalBitOffset(uint64_t GlobalOffset) {
2872 auto I = GlobalBitOffsetsMap.find(GlobalOffset);
2874 assert(I != GlobalBitOffsetsMap.end() && "Corrupted global bit offsets map");
2875 return RecordLocation(I->second, GlobalOffset - I->second->GlobalBitOffset);
2878 uint64_t ASTReader::getGlobalBitOffset(ModuleFile &M, uint32_t LocalOffset) {
2879 return LocalOffset + M.GlobalBitOffset;
2882 static bool isSameTemplateParameterList(const TemplateParameterList *X,
2883 const TemplateParameterList *Y);
2885 /// Determine whether two template parameters are similar enough
2886 /// that they may be used in declarations of the same template.
2887 static bool isSameTemplateParameter(const NamedDecl *X,
2888 const NamedDecl *Y) {
2889 if (X->getKind() != Y->getKind())
2892 if (const auto *TX = dyn_cast<TemplateTypeParmDecl>(X)) {
2893 const auto *TY = cast<TemplateTypeParmDecl>(Y);
2894 return TX->isParameterPack() == TY->isParameterPack();
2897 if (const auto *TX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
2898 const auto *TY = cast<NonTypeTemplateParmDecl>(Y);
2899 return TX->isParameterPack() == TY->isParameterPack() &&
2900 TX->getASTContext().hasSameType(TX->getType(), TY->getType());
2903 const auto *TX = cast<TemplateTemplateParmDecl>(X);
2904 const auto *TY = cast<TemplateTemplateParmDecl>(Y);
2905 return TX->isParameterPack() == TY->isParameterPack() &&
2906 isSameTemplateParameterList(TX->getTemplateParameters(),
2907 TY->getTemplateParameters());
2910 static NamespaceDecl *getNamespace(const NestedNameSpecifier *X) {
2911 if (auto *NS = X->getAsNamespace())
2913 if (auto *NAS = X->getAsNamespaceAlias())
2914 return NAS->getNamespace();
2918 static bool isSameQualifier(const NestedNameSpecifier *X,
2919 const NestedNameSpecifier *Y) {
2920 if (auto *NSX = getNamespace(X)) {
2921 auto *NSY = getNamespace(Y);
2922 if (!NSY || NSX->getCanonicalDecl() != NSY->getCanonicalDecl())
2924 } else if (X->getKind() != Y->getKind())
2927 // FIXME: For namespaces and types, we're permitted to check that the entity
2928 // is named via the same tokens. We should probably do so.
2929 switch (X->getKind()) {
2930 case NestedNameSpecifier::Identifier:
2931 if (X->getAsIdentifier() != Y->getAsIdentifier())
2934 case NestedNameSpecifier::Namespace:
2935 case NestedNameSpecifier::NamespaceAlias:
2936 // We've already checked that we named the same namespace.
2938 case NestedNameSpecifier::TypeSpec:
2939 case NestedNameSpecifier::TypeSpecWithTemplate:
2940 if (X->getAsType()->getCanonicalTypeInternal() !=
2941 Y->getAsType()->getCanonicalTypeInternal())
2944 case NestedNameSpecifier::Global:
2945 case NestedNameSpecifier::Super:
2949 // Recurse into earlier portion of NNS, if any.
2950 auto *PX = X->getPrefix();
2951 auto *PY = Y->getPrefix();
2953 return isSameQualifier(PX, PY);
2957 /// Determine whether two template parameter lists are similar enough
2958 /// that they may be used in declarations of the same template.
2959 static bool isSameTemplateParameterList(const TemplateParameterList *X,
2960 const TemplateParameterList *Y) {
2961 if (X->size() != Y->size())
2964 for (unsigned I = 0, N = X->size(); I != N; ++I)
2965 if (!isSameTemplateParameter(X->getParam(I), Y->getParam(I)))
2971 /// Determine whether the attributes we can overload on are identical for A and
2972 /// B. Will ignore any overloadable attrs represented in the type of A and B.
2973 static bool hasSameOverloadableAttrs(const FunctionDecl *A,
2974 const FunctionDecl *B) {
2975 // Note that pass_object_size attributes are represented in the function's
2976 // ExtParameterInfo, so we don't need to check them here.
2978 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
2979 auto AEnableIfAttrs = A->specific_attrs<EnableIfAttr>();
2980 auto BEnableIfAttrs = B->specific_attrs<EnableIfAttr>();
2982 for (auto Pair : zip_longest(AEnableIfAttrs, BEnableIfAttrs)) {
2983 Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
2984 Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
2986 // Return false if the number of enable_if attributes is different.
2987 if (!Cand1A || !Cand2A)
2993 (*Cand1A)->getCond()->Profile(Cand1ID, A->getASTContext(), true);
2994 (*Cand2A)->getCond()->Profile(Cand2ID, B->getASTContext(), true);
2996 // Return false if any of the enable_if expressions of A and B are
2998 if (Cand1ID != Cand2ID)
3004 /// Determine whether the two declarations refer to the same entity.
3005 static bool isSameEntity(NamedDecl *X, NamedDecl *Y) {
3006 assert(X->getDeclName() == Y->getDeclName() && "Declaration name mismatch!");
3011 // Must be in the same context.
3013 // Note that we can't use DeclContext::Equals here, because the DeclContexts
3014 // could be two different declarations of the same function. (We will fix the
3015 // semantic DC to refer to the primary definition after merging.)
3016 if (!declaresSameEntity(cast<Decl>(X->getDeclContext()->getRedeclContext()),
3017 cast<Decl>(Y->getDeclContext()->getRedeclContext())))
3020 // Two typedefs refer to the same entity if they have the same underlying
3022 if (const auto *TypedefX = dyn_cast<TypedefNameDecl>(X))
3023 if (const auto *TypedefY = dyn_cast<TypedefNameDecl>(Y))
3024 return X->getASTContext().hasSameType(TypedefX->getUnderlyingType(),
3025 TypedefY->getUnderlyingType());
3027 // Must have the same kind.
3028 if (X->getKind() != Y->getKind())
3031 // Objective-C classes and protocols with the same name always match.
3032 if (isa<ObjCInterfaceDecl>(X) || isa<ObjCProtocolDecl>(X))
3035 if (isa<ClassTemplateSpecializationDecl>(X)) {
3036 // No need to handle these here: we merge them when adding them to the
3041 // Compatible tags match.
3042 if (const auto *TagX = dyn_cast<TagDecl>(X)) {
3043 const auto *TagY = cast<TagDecl>(Y);
3044 return (TagX->getTagKind() == TagY->getTagKind()) ||
3045 ((TagX->getTagKind() == TTK_Struct || TagX->getTagKind() == TTK_Class ||
3046 TagX->getTagKind() == TTK_Interface) &&
3047 (TagY->getTagKind() == TTK_Struct || TagY->getTagKind() == TTK_Class ||
3048 TagY->getTagKind() == TTK_Interface));
3051 // Functions with the same type and linkage match.
3052 // FIXME: This needs to cope with merging of prototyped/non-prototyped
3054 if (const auto *FuncX = dyn_cast<FunctionDecl>(X)) {
3055 const auto *FuncY = cast<FunctionDecl>(Y);
3056 if (const auto *CtorX = dyn_cast<CXXConstructorDecl>(X)) {
3057 const auto *CtorY = cast<CXXConstructorDecl>(Y);
3058 if (CtorX->getInheritedConstructor() &&
3059 !isSameEntity(CtorX->getInheritedConstructor().getConstructor(),
3060 CtorY->getInheritedConstructor().getConstructor()))
3064 if (FuncX->isMultiVersion() != FuncY->isMultiVersion())
3067 // Multiversioned functions with different feature strings are represented
3068 // as separate declarations.
3069 if (FuncX->isMultiVersion()) {
3070 const auto *TAX = FuncX->getAttr<TargetAttr>();
3071 const auto *TAY = FuncY->getAttr<TargetAttr>();
3072 assert(TAX && TAY && "Multiversion Function without target attribute");
3074 if (TAX->getFeaturesStr() != TAY->getFeaturesStr())
3078 ASTContext &C = FuncX->getASTContext();
3079 auto GetTypeAsWritten = [](const FunctionDecl *FD) {
3080 // Map to the first declaration that we've already merged into this one.
3081 // The TSI of redeclarations might not match (due to calling conventions
3082 // being inherited onto the type but not the TSI), but the TSI type of
3083 // the first declaration of the function should match across modules.
3084 FD = FD->getCanonicalDecl();
3085 return FD->getTypeSourceInfo() ? FD->getTypeSourceInfo()->getType()
3088 QualType XT = GetTypeAsWritten(FuncX), YT = GetTypeAsWritten(FuncY);
3089 if (!C.hasSameType(XT, YT)) {
3090 // We can get functions with different types on the redecl chain in C++17
3091 // if they have differing exception specifications and at least one of
3092 // the excpetion specs is unresolved.
3093 auto *XFPT = XT->getAs<FunctionProtoType>();
3094 auto *YFPT = YT->getAs<FunctionProtoType>();
3095 if (C.getLangOpts().CPlusPlus17 && XFPT && YFPT &&
3096 (isUnresolvedExceptionSpec(XFPT->getExceptionSpecType()) ||
3097 isUnresolvedExceptionSpec(YFPT->getExceptionSpecType())) &&
3098 C.hasSameFunctionTypeIgnoringExceptionSpec(XT, YT))
3102 return FuncX->getLinkageInternal() == FuncY->getLinkageInternal() &&
3103 hasSameOverloadableAttrs(FuncX, FuncY);
3106 // Variables with the same type and linkage match.
3107 if (const auto *VarX = dyn_cast<VarDecl>(X)) {
3108 const auto *VarY = cast<VarDecl>(Y);
3109 if (VarX->getLinkageInternal() == VarY->getLinkageInternal()) {
3110 ASTContext &C = VarX->getASTContext();
3111 if (C.hasSameType(VarX->getType(), VarY->getType()))
3114 // We can get decls with different types on the redecl chain. Eg.
3115 // template <typename T> struct S { static T Var[]; }; // #1
3116 // template <typename T> T S<T>::Var[sizeof(T)]; // #2
3117 // Only? happens when completing an incomplete array type. In this case
3118 // when comparing #1 and #2 we should go through their element type.
3119 const ArrayType *VarXTy = C.getAsArrayType(VarX->getType());
3120 const ArrayType *VarYTy = C.getAsArrayType(VarY->getType());
3121 if (!VarXTy || !VarYTy)
3123 if (VarXTy->isIncompleteArrayType() || VarYTy->isIncompleteArrayType())
3124 return C.hasSameType(VarXTy->getElementType(), VarYTy->getElementType());
3129 // Namespaces with the same name and inlinedness match.
3130 if (const auto *NamespaceX = dyn_cast<NamespaceDecl>(X)) {
3131 const auto *NamespaceY = cast<NamespaceDecl>(Y);
3132 return NamespaceX->isInline() == NamespaceY->isInline();
3135 // Identical template names and kinds match if their template parameter lists
3136 // and patterns match.
3137 if (const auto *TemplateX = dyn_cast<TemplateDecl>(X)) {
3138 const auto *TemplateY = cast<TemplateDecl>(Y);
3139 return isSameEntity(TemplateX->getTemplatedDecl(),
3140 TemplateY->getTemplatedDecl()) &&
3141 isSameTemplateParameterList(TemplateX->getTemplateParameters(),
3142 TemplateY->getTemplateParameters());
3145 // Fields with the same name and the same type match.
3146 if (const auto *FDX = dyn_cast<FieldDecl>(X)) {
3147 const auto *FDY = cast<FieldDecl>(Y);
3148 // FIXME: Also check the bitwidth is odr-equivalent, if any.
3149 return X->getASTContext().hasSameType(FDX->getType(), FDY->getType());
3152 // Indirect fields with the same target field match.
3153 if (const auto *IFDX = dyn_cast<IndirectFieldDecl>(X)) {
3154 const auto *IFDY = cast<IndirectFieldDecl>(Y);
3155 return IFDX->getAnonField()->getCanonicalDecl() ==
3156 IFDY->getAnonField()->getCanonicalDecl();
3159 // Enumerators with the same name match.
3160 if (isa<EnumConstantDecl>(X))
3161 // FIXME: Also check the value is odr-equivalent.
3164 // Using shadow declarations with the same target match.
3165 if (const auto *USX = dyn_cast<UsingShadowDecl>(X)) {
3166 const auto *USY = cast<UsingShadowDecl>(Y);
3167 return USX->getTargetDecl() == USY->getTargetDecl();
3170 // Using declarations with the same qualifier match. (We already know that
3171 // the name matches.)
3172 if (const auto *UX = dyn_cast<UsingDecl>(X)) {
3173 const auto *UY = cast<UsingDecl>(Y);
3174 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
3175 UX->hasTypename() == UY->hasTypename() &&
3176 UX->isAccessDeclaration() == UY->isAccessDeclaration();
3178 if (const auto *UX = dyn_cast<UnresolvedUsingValueDecl>(X)) {
3179 const auto *UY = cast<UnresolvedUsingValueDecl>(Y);
3180 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
3181 UX->isAccessDeclaration() == UY->isAccessDeclaration();
3183 if (const auto *UX = dyn_cast<UnresolvedUsingTypenameDecl>(X))
3184 return isSameQualifier(
3186 cast<UnresolvedUsingTypenameDecl>(Y)->getQualifier());
3188 // Namespace alias definitions with the same target match.
3189 if (const auto *NAX = dyn_cast<NamespaceAliasDecl>(X)) {
3190 const auto *NAY = cast<NamespaceAliasDecl>(Y);
3191 return NAX->getNamespace()->Equals(NAY->getNamespace());
3197 /// Find the context in which we should search for previous declarations when
3198 /// looking for declarations to merge.
3199 DeclContext *ASTDeclReader::getPrimaryContextForMerging(ASTReader &Reader,
3201 if (auto *ND = dyn_cast<NamespaceDecl>(DC))
3202 return ND->getOriginalNamespace();
3204 if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) {
3205 // Try to dig out the definition.
3206 auto *DD = RD->DefinitionData;
3208 DD = RD->getCanonicalDecl()->DefinitionData;
3210 // If there's no definition yet, then DC's definition is added by an update
3211 // record, but we've not yet loaded that update record. In this case, we
3212 // commit to DC being the canonical definition now, and will fix this when
3213 // we load the update record.
3215 DD = new (Reader.getContext()) struct CXXRecordDecl::DefinitionData(RD);
3216 RD->setCompleteDefinition(true);
3217 RD->DefinitionData = DD;
3218 RD->getCanonicalDecl()->DefinitionData = DD;
3220 // Track that we did this horrible thing so that we can fix it later.
3221 Reader.PendingFakeDefinitionData.insert(
3222 std::make_pair(DD, ASTReader::PendingFakeDefinitionKind::Fake));
3225 return DD->Definition;
3228 if (auto *ED = dyn_cast<EnumDecl>(DC))
3229 return ED->getASTContext().getLangOpts().CPlusPlus? ED->getDefinition()
3232 // We can see the TU here only if we have no Sema object. In that case,
3233 // there's no TU scope to look in, so using the DC alone is sufficient.
3234 if (auto *TU = dyn_cast<TranslationUnitDecl>(DC))
3240 ASTDeclReader::FindExistingResult::~FindExistingResult() {
3241 // Record that we had a typedef name for linkage whether or not we merge
3242 // with that declaration.
3243 if (TypedefNameForLinkage) {
3244 DeclContext *DC = New->getDeclContext()->getRedeclContext();
3245 Reader.ImportedTypedefNamesForLinkage.insert(
3246 std::make_pair(std::make_pair(DC, TypedefNameForLinkage), New));
3250 if (!AddResult || Existing)
3253 DeclarationName Name = New->getDeclName();
3254 DeclContext *DC = New->getDeclContext()->getRedeclContext();
3255 if (needsAnonymousDeclarationNumber(New)) {
3256 setAnonymousDeclForMerging(Reader, New->getLexicalDeclContext(),
3257 AnonymousDeclNumber, New);
3258 } else if (DC->isTranslationUnit() &&
3259 !Reader.getContext().getLangOpts().CPlusPlus) {
3260 if (Reader.getIdResolver().tryAddTopLevelDecl(New, Name))
3261 Reader.PendingFakeLookupResults[Name.getAsIdentifierInfo()]
3263 } else if (DeclContext *MergeDC = getPrimaryContextForMerging(Reader, DC)) {
3264 // Add the declaration to its redeclaration context so later merging
3265 // lookups will find it.
3266 MergeDC->makeDeclVisibleInContextImpl(New, /*Internal*/true);
3270 /// Find the declaration that should be merged into, given the declaration found
3271 /// by name lookup. If we're merging an anonymous declaration within a typedef,
3272 /// we need a matching typedef, and we merge with the type inside it.
3273 static NamedDecl *getDeclForMerging(NamedDecl *Found,
3274 bool IsTypedefNameForLinkage) {
3275 if (!IsTypedefNameForLinkage)
3278 // If we found a typedef declaration that gives a name to some other
3279 // declaration, then we want that inner declaration. Declarations from
3280 // AST files are handled via ImportedTypedefNamesForLinkage.
3281 if (Found->isFromASTFile())
3284 if (auto *TND = dyn_cast<TypedefNameDecl>(Found))
3285 return TND->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
3290 /// Find the declaration to use to populate the anonymous declaration table
3291 /// for the given lexical DeclContext. We only care about finding local
3292 /// definitions of the context; we'll merge imported ones as we go.
3294 ASTDeclReader::getPrimaryDCForAnonymousDecl(DeclContext *LexicalDC) {
3295 // For classes, we track the definition as we merge.
3296 if (auto *RD = dyn_cast<CXXRecordDecl>(LexicalDC)) {
3297 auto *DD = RD->getCanonicalDecl()->DefinitionData;
3298 return DD ? DD->Definition : nullptr;
3301 // For anything else, walk its merged redeclarations looking for a definition.
3302 // Note that we can't just call getDefinition here because the redeclaration
3303 // chain isn't wired up.
3304 for (auto *D : merged_redecls(cast<Decl>(LexicalDC))) {
3305 if (auto *FD = dyn_cast<FunctionDecl>(D))
3306 if (FD->isThisDeclarationADefinition())
3308 if (auto *MD = dyn_cast<ObjCMethodDecl>(D))
3309 if (MD->isThisDeclarationADefinition())
3313 // No merged definition yet.
3317 NamedDecl *ASTDeclReader::getAnonymousDeclForMerging(ASTReader &Reader,
3320 // If the lexical context has been merged, look into the now-canonical
3322 auto *CanonDC = cast<Decl>(DC)->getCanonicalDecl();
3324 // If we've seen this before, return the canonical declaration.
3325 auto &Previous = Reader.AnonymousDeclarationsForMerging[CanonDC];
3326 if (Index < Previous.size() && Previous[Index])
3327 return Previous[Index];
3329 // If this is the first time, but we have parsed a declaration of the context,
3330 // build the anonymous declaration list from the parsed declaration.
3331 auto *PrimaryDC = getPrimaryDCForAnonymousDecl(DC);
3332 if (PrimaryDC && !cast<Decl>(PrimaryDC)->isFromASTFile()) {
3333 numberAnonymousDeclsWithin(PrimaryDC, [&](NamedDecl *ND, unsigned Number) {
3334 if (Previous.size() == Number)
3335 Previous.push_back(cast<NamedDecl>(ND->getCanonicalDecl()));
3337 Previous[Number] = cast<NamedDecl>(ND->getCanonicalDecl());
3341 return Index < Previous.size() ? Previous[Index] : nullptr;
3344 void ASTDeclReader::setAnonymousDeclForMerging(ASTReader &Reader,
3345 DeclContext *DC, unsigned Index,
3347 auto *CanonDC = cast<Decl>(DC)->getCanonicalDecl();
3349 auto &Previous = Reader.AnonymousDeclarationsForMerging[CanonDC];
3350 if (Index >= Previous.size())
3351 Previous.resize(Index + 1);
3352 if (!Previous[Index])
3353 Previous[Index] = D;
3356 ASTDeclReader::FindExistingResult ASTDeclReader::findExisting(NamedDecl *D) {
3357 DeclarationName Name = TypedefNameForLinkage ? TypedefNameForLinkage
3360 if (!Name && !needsAnonymousDeclarationNumber(D)) {
3361 // Don't bother trying to find unnamed declarations that are in
3362 // unmergeable contexts.
3363 FindExistingResult Result(Reader, D, /*Existing=*/nullptr,
3364 AnonymousDeclNumber, TypedefNameForLinkage);
3369 DeclContext *DC = D->getDeclContext()->getRedeclContext();
3370 if (TypedefNameForLinkage) {
3371 auto It = Reader.ImportedTypedefNamesForLinkage.find(
3372 std::make_pair(DC, TypedefNameForLinkage));
3373 if (It != Reader.ImportedTypedefNamesForLinkage.end())
3374 if (isSameEntity(It->second, D))
3375 return FindExistingResult(Reader, D, It->second, AnonymousDeclNumber,
3376 TypedefNameForLinkage);
3377 // Go on to check in other places in case an existing typedef name
3378 // was not imported.
3381 if (needsAnonymousDeclarationNumber(D)) {
3382 // This is an anonymous declaration that we may need to merge. Look it up
3383 // in its context by number.
3384 if (auto *Existing = getAnonymousDeclForMerging(
3385 Reader, D->getLexicalDeclContext(), AnonymousDeclNumber))
3386 if (isSameEntity(Existing, D))
3387 return FindExistingResult(Reader, D, Existing, AnonymousDeclNumber,
3388 TypedefNameForLinkage);
3389 } else if (DC->isTranslationUnit() &&
3390 !Reader.getContext().getLangOpts().CPlusPlus) {
3391 IdentifierResolver &IdResolver = Reader.getIdResolver();
3393 // Temporarily consider the identifier to be up-to-date. We don't want to
3394 // cause additional lookups here.
3395 class UpToDateIdentifierRAII {
3397 bool WasOutToDate = false;
3400 explicit UpToDateIdentifierRAII(IdentifierInfo *II) : II(II) {
3402 WasOutToDate = II->isOutOfDate();
3404 II->setOutOfDate(false);
3408 ~UpToDateIdentifierRAII() {
3410 II->setOutOfDate(true);
3412 } UpToDate(Name.getAsIdentifierInfo());
3414 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
3415 IEnd = IdResolver.end();
3417 if (NamedDecl *Existing = getDeclForMerging(*I, TypedefNameForLinkage))
3418 if (isSameEntity(Existing, D))
3419 return FindExistingResult(Reader, D, Existing, AnonymousDeclNumber,
3420 TypedefNameForLinkage);
3422 } else if (DeclContext *MergeDC = getPrimaryContextForMerging(Reader, DC)) {
3423 DeclContext::lookup_result R = MergeDC->noload_lookup(Name);
3424 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
3425 if (NamedDecl *Existing = getDeclForMerging(*I, TypedefNameForLinkage))
3426 if (isSameEntity(Existing, D))
3427 return FindExistingResult(Reader, D, Existing, AnonymousDeclNumber,
3428 TypedefNameForLinkage);
3431 // Not in a mergeable context.
3432 return FindExistingResult(Reader);
3435 // If this declaration is from a merged context, make a note that we need to
3436 // check that the canonical definition of that context contains the decl.
3438 // FIXME: We should do something similar if we merge two definitions of the
3439 // same template specialization into the same CXXRecordDecl.
3440 auto MergedDCIt = Reader.MergedDeclContexts.find(D->getLexicalDeclContext());
3441 if (MergedDCIt != Reader.MergedDeclContexts.end() &&
3442 MergedDCIt->second == D->getDeclContext())
3443 Reader.PendingOdrMergeChecks.push_back(D);
3445 return FindExistingResult(Reader, D, /*Existing=*/nullptr,
3446 AnonymousDeclNumber, TypedefNameForLinkage);
3449 template<typename DeclT>
3450 Decl *ASTDeclReader::getMostRecentDeclImpl(Redeclarable<DeclT> *D) {
3451 return D->RedeclLink.getLatestNotUpdated();
3454 Decl *ASTDeclReader::getMostRecentDeclImpl(...) {
3455 llvm_unreachable("getMostRecentDecl on non-redeclarable declaration");
3458 Decl *ASTDeclReader::getMostRecentDecl(Decl *D) {
3461 switch (D->getKind()) {
3462 #define ABSTRACT_DECL(TYPE)
3463 #define DECL(TYPE, BASE) \
3465 return getMostRecentDeclImpl(cast<TYPE##Decl>(D));
3466 #include "clang/AST/DeclNodes.inc"
3468 llvm_unreachable("unknown decl kind");
3471 Decl *ASTReader::getMostRecentExistingDecl(Decl *D) {
3472 return ASTDeclReader::getMostRecentDecl(D->getCanonicalDecl());
3475 template<typename DeclT>
3476 void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader,
3477 Redeclarable<DeclT> *D,
3478 Decl *Previous, Decl *Canon) {
3479 D->RedeclLink.setPrevious(cast<DeclT>(Previous));
3480 D->First = cast<DeclT>(Previous)->First;
3486 void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader,
3487 Redeclarable<VarDecl> *D,
3488 Decl *Previous, Decl *Canon) {
3489 auto *VD = static_cast<VarDecl *>(D);
3490 auto *PrevVD = cast<VarDecl>(Previous);
3491 D->RedeclLink.setPrevious(PrevVD);
3492 D->First = PrevVD->First;
3494 // We should keep at most one definition on the chain.
3495 // FIXME: Cache the definition once we've found it. Building a chain with
3496 // N definitions currently takes O(N^2) time here.
3497 if (VD->isThisDeclarationADefinition() == VarDecl::Definition) {
3498 for (VarDecl *CurD = PrevVD; CurD; CurD = CurD->getPreviousDecl()) {
3499 if (CurD->isThisDeclarationADefinition() == VarDecl::Definition) {
3500 Reader.mergeDefinitionVisibility(CurD, VD);
3501 VD->demoteThisDefinitionToDeclaration();
3508 static bool isUndeducedReturnType(QualType T) {
3509 auto *DT = T->getContainedDeducedType();
3510 return DT && !DT->isDeduced();
3514 void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader,
3515 Redeclarable<FunctionDecl> *D,
3516 Decl *Previous, Decl *Canon) {
3517 auto *FD = static_cast<FunctionDecl *>(D);
3518 auto *PrevFD = cast<FunctionDecl>(Previous);
3520 FD->RedeclLink.setPrevious(PrevFD);
3521 FD->First = PrevFD->First;
3523 // If the previous declaration is an inline function declaration, then this
3524 // declaration is too.
3525 if (PrevFD->isInlined() != FD->isInlined()) {
3526 // FIXME: [dcl.fct.spec]p4:
3527 // If a function with external linkage is declared inline in one
3528 // translation unit, it shall be declared inline in all translation
3529 // units in which it appears.
3531 // Be careful of this case:
3534 // template<typename T> struct X { void f(); };
3535 // template<typename T> inline void X<T>::f() {}
3537 // module B instantiates the declaration of X<int>::f
3538 // module C instantiates the definition of X<int>::f
3540 // If module B and C are merged, we do not have a violation of this rule.
3541 FD->setImplicitlyInline(true);
3544 auto *FPT = FD->getType()->getAs<FunctionProtoType>();
3545 auto *PrevFPT = PrevFD->getType()->getAs<FunctionProtoType>();
3546 if (FPT && PrevFPT) {
3547 // If we need to propagate an exception specification along the redecl
3548 // chain, make a note of that so that we can do so later.
3549 bool IsUnresolved = isUnresolvedExceptionSpec(FPT->getExceptionSpecType());
3550 bool WasUnresolved =
3551 isUnresolvedExceptionSpec(PrevFPT->getExceptionSpecType());
3552 if (IsUnresolved != WasUnresolved)
3553 Reader.PendingExceptionSpecUpdates.insert(
3554 {Canon, IsUnresolved ? PrevFD : FD});
3556 // If we need to propagate a deduced return type along the redecl chain,
3557 // make a note of that so that we can do it later.
3558 bool IsUndeduced = isUndeducedReturnType(FPT->getReturnType());
3559 bool WasUndeduced = isUndeducedReturnType(PrevFPT->getReturnType());
3560 if (IsUndeduced != WasUndeduced)
3561 Reader.PendingDeducedTypeUpdates.insert(
3562 {cast<FunctionDecl>(Canon),
3563 (IsUndeduced ? PrevFPT : FPT)->getReturnType()});
3567 } // namespace clang
3569 void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader, ...) {
3570 llvm_unreachable("attachPreviousDecl on non-redeclarable declaration");
3573 /// Inherit the default template argument from \p From to \p To. Returns
3574 /// \c false if there is no default template for \p From.
3575 template <typename ParmDecl>
3576 static bool inheritDefaultTemplateArgument(ASTContext &Context, ParmDecl *From,
3578 auto *To = cast<ParmDecl>(ToD);
3579 if (!From->hasDefaultArgument())
3581 To->setInheritedDefaultArgument(Context, From);
3585 static void inheritDefaultTemplateArguments(ASTContext &Context,
3588 auto *FromTP = From->getTemplateParameters();
3589 auto *ToTP = To->getTemplateParameters();
3590 assert(FromTP->size() == ToTP->size() && "merged mismatched templates?");
3592 for (unsigned I = 0, N = FromTP->size(); I != N; ++I) {
3593 NamedDecl *FromParam = FromTP->getParam(I);
3594 NamedDecl *ToParam = ToTP->getParam(I);
3596 if (auto *FTTP = dyn_cast<TemplateTypeParmDecl>(FromParam))
3597 inheritDefaultTemplateArgument(Context, FTTP, ToParam);
3598 else if (auto *FNTTP = dyn_cast<NonTypeTemplateParmDecl>(FromParam))
3599 inheritDefaultTemplateArgument(Context, FNTTP, ToParam);
3601 inheritDefaultTemplateArgument(
3602 Context, cast<TemplateTemplateParmDecl>(FromParam), ToParam);
3606 void ASTDeclReader::attachPreviousDecl(ASTReader &Reader, Decl *D,
3607 Decl *Previous, Decl *Canon) {
3608 assert(D && Previous);
3610 switch (D->getKind()) {
3611 #define ABSTRACT_DECL(TYPE)
3612 #define DECL(TYPE, BASE) \
3614 attachPreviousDeclImpl(Reader, cast<TYPE##Decl>(D), Previous, Canon); \
3616 #include "clang/AST/DeclNodes.inc"
3619 // If the declaration was visible in one module, a redeclaration of it in
3620 // another module remains visible even if it wouldn't be visible by itself.
3622 // FIXME: In this case, the declaration should only be visible if a module
3623 // that makes it visible has been imported.
3624 D->IdentifierNamespace |=
3625 Previous->IdentifierNamespace &
3626 (Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Type);
3628 // If the declaration declares a template, it may inherit default arguments
3629 // from the previous declaration.
3630 if (auto *TD = dyn_cast<TemplateDecl>(D))
3631 inheritDefaultTemplateArguments(Reader.getContext(),
3632 cast<TemplateDecl>(Previous), TD);
3635 template<typename DeclT>
3636 void ASTDeclReader::attachLatestDeclImpl(Redeclarable<DeclT> *D, Decl *Latest) {
3637 D->RedeclLink.setLatest(cast<DeclT>(Latest));
3640 void ASTDeclReader::attachLatestDeclImpl(...) {
3641 llvm_unreachable("attachLatestDecl on non-redeclarable declaration");
3644 void ASTDeclReader::attachLatestDecl(Decl *D, Decl *Latest) {
3645 assert(D && Latest);
3647 switch (D->getKind()) {
3648 #define ABSTRACT_DECL(TYPE)
3649 #define DECL(TYPE, BASE) \
3651 attachLatestDeclImpl(cast<TYPE##Decl>(D), Latest); \
3653 #include "clang/AST/DeclNodes.inc"
3657 template<typename DeclT>
3658 void ASTDeclReader::markIncompleteDeclChainImpl(Redeclarable<DeclT> *D) {
3659 D->RedeclLink.markIncomplete();
3662 void ASTDeclReader::markIncompleteDeclChainImpl(...) {
3663 llvm_unreachable("markIncompleteDeclChain on non-redeclarable declaration");
3666 void ASTReader::markIncompleteDeclChain(Decl *D) {
3667 switch (D->getKind()) {
3668 #define ABSTRACT_DECL(TYPE)
3669 #define DECL(TYPE, BASE) \
3671 ASTDeclReader::markIncompleteDeclChainImpl(cast<TYPE##Decl>(D)); \
3673 #include "clang/AST/DeclNodes.inc"
3677 /// Read the declaration at the given offset from the AST file.
3678 Decl *ASTReader::ReadDeclRecord(DeclID ID) {
3679 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
3680 SourceLocation DeclLoc;
3681 RecordLocation Loc = DeclCursorForID(ID, DeclLoc);
3682 llvm::BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
3683 // Keep track of where we are in the stream, then jump back there
3684 // after reading this declaration.
3685 SavedStreamPosition SavedPosition(DeclsCursor);
3687 ReadingKindTracker ReadingKind(Read_Decl, *this);
3689 // Note that we are loading a declaration record.
3690 Deserializing ADecl(this);
3692 auto Fail = [](const char *what, llvm::Error &&Err) {
3693 llvm::report_fatal_error(Twine("ASTReader::readDeclRecord failed ") + what +
3694 ": " + toString(std::move(Err)));
3697 if (llvm::Error JumpFailed = DeclsCursor.JumpToBit(Loc.Offset))
3698 Fail("jumping", std::move(JumpFailed));
3699 ASTRecordReader Record(*this, *Loc.F);
3700 ASTDeclReader Reader(*this, Record, Loc, ID, DeclLoc);
3701 Expected<unsigned> MaybeCode = DeclsCursor.ReadCode();
3703 Fail("reading code", MaybeCode.takeError());
3704 unsigned Code = MaybeCode.get();
3706 ASTContext &Context = getContext();
3708 Expected<unsigned> MaybeDeclCode = Record.readRecord(DeclsCursor, Code);
3710 llvm::report_fatal_error(
3711 "ASTReader::readDeclRecord failed reading decl code: " +
3712 toString(MaybeDeclCode.takeError()));
3713 switch ((DeclCode)MaybeDeclCode.get()) {
3714 case DECL_CONTEXT_LEXICAL:
3715 case DECL_CONTEXT_VISIBLE:
3716 llvm_unreachable("Record cannot be de-serialized with readDeclRecord");
3718 D = TypedefDecl::CreateDeserialized(Context, ID);
3720 case DECL_TYPEALIAS:
3721 D = TypeAliasDecl::CreateDeserialized(Context, ID);
3724 D = EnumDecl::CreateDeserialized(Context, ID);
3727 D = RecordDecl::CreateDeserialized(Context, ID);
3729 case DECL_ENUM_CONSTANT:
3730 D = EnumConstantDecl::CreateDeserialized(Context, ID);
3733 D = FunctionDecl::CreateDeserialized(Context, ID);
3735 case DECL_LINKAGE_SPEC:
3736 D = LinkageSpecDecl::CreateDeserialized(Context, ID);
3739 D = ExportDecl::CreateDeserialized(Context, ID);
3742 D = LabelDecl::CreateDeserialized(Context, ID);
3744 case DECL_NAMESPACE:
3745 D = NamespaceDecl::CreateDeserialized(Context, ID);
3747 case DECL_NAMESPACE_ALIAS:
3748 D = NamespaceAliasDecl::CreateDeserialized(Context, ID);
3751 D = UsingDecl::CreateDeserialized(Context, ID);
3753 case DECL_USING_PACK:
3754 D = UsingPackDecl::CreateDeserialized(Context, ID, Record.readInt());
3756 case DECL_USING_SHADOW:
3757 D = UsingShadowDecl::CreateDeserialized(Context, ID);
3759 case DECL_CONSTRUCTOR_USING_SHADOW:
3760 D = ConstructorUsingShadowDecl::CreateDeserialized(Context, ID);
3762 case DECL_USING_DIRECTIVE:
3763 D = UsingDirectiveDecl::CreateDeserialized(Context, ID);
3765 case DECL_UNRESOLVED_USING_VALUE:
3766 D = UnresolvedUsingValueDecl::CreateDeserialized(Context, ID);
3768 case DECL_UNRESOLVED_USING_TYPENAME:
3769 D = UnresolvedUsingTypenameDecl::CreateDeserialized(Context, ID);
3771 case DECL_CXX_RECORD:
3772 D = CXXRecordDecl::CreateDeserialized(Context, ID);
3774 case DECL_CXX_DEDUCTION_GUIDE:
3775 D = CXXDeductionGuideDecl::CreateDeserialized(Context, ID);
3777 case DECL_CXX_METHOD:
3778 D = CXXMethodDecl::CreateDeserialized(Context, ID);
3780 case DECL_CXX_CONSTRUCTOR:
3781 D = CXXConstructorDecl::CreateDeserialized(Context, ID, Record.readInt());
3783 case DECL_CXX_DESTRUCTOR:
3784 D = CXXDestructorDecl::CreateDeserialized(Context, ID);
3786 case DECL_CXX_CONVERSION:
3787 D = CXXConversionDecl::CreateDeserialized(Context, ID);
3789 case DECL_ACCESS_SPEC:
3790 D = AccessSpecDecl::CreateDeserialized(Context, ID);
3793 D = FriendDecl::CreateDeserialized(Context, ID, Record.readInt());
3795 case DECL_FRIEND_TEMPLATE:
3796 D = FriendTemplateDecl::CreateDeserialized(Context, ID);
3798 case DECL_CLASS_TEMPLATE:
3799 D = ClassTemplateDecl::CreateDeserialized(Context, ID);
3801 case DECL_CLASS_TEMPLATE_SPECIALIZATION:
3802 D = ClassTemplateSpecializationDecl::CreateDeserialized(Context, ID);
3804 case DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION:
3805 D = ClassTemplatePartialSpecializationDecl::CreateDeserialized(Context, ID);
3807 case DECL_VAR_TEMPLATE:
3808 D = VarTemplateDecl::CreateDeserialized(Context, ID);
3810 case DECL_VAR_TEMPLATE_SPECIALIZATION:
3811 D = VarTemplateSpecializationDecl::CreateDeserialized(Context, ID);
3813 case DECL_VAR_TEMPLATE_PARTIAL_SPECIALIZATION:
3814 D = VarTemplatePartialSpecializationDecl::CreateDeserialized(Context, ID);
3816 case DECL_CLASS_SCOPE_FUNCTION_SPECIALIZATION:
3817 D = ClassScopeFunctionSpecializationDecl::CreateDeserialized(Context, ID);
3819 case DECL_FUNCTION_TEMPLATE:
3820 D = FunctionTemplateDecl::CreateDeserialized(Context, ID);
3822 case DECL_TEMPLATE_TYPE_PARM: {
3823 bool HasTypeConstraint = Record.readInt();
3824 D = TemplateTypeParmDecl::CreateDeserialized(Context, ID,
3828 case DECL_NON_TYPE_TEMPLATE_PARM: {
3829 bool HasTypeConstraint = Record.readInt();
3830 D = NonTypeTemplateParmDecl::CreateDeserialized(Context, ID,
3834 case DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK: {
3835 bool HasTypeConstraint = Record.readInt();
3836 D = NonTypeTemplateParmDecl::CreateDeserialized(Context, ID,
3841 case DECL_TEMPLATE_TEMPLATE_PARM:
3842 D = TemplateTemplateParmDecl::CreateDeserialized(Context, ID);
3844 case DECL_EXPANDED_TEMPLATE_TEMPLATE_PARM_PACK:
3845 D = TemplateTemplateParmDecl::CreateDeserialized(Context, ID,
3848 case DECL_TYPE_ALIAS_TEMPLATE:
3849 D = TypeAliasTemplateDecl::CreateDeserialized(Context, ID);
3852 D = ConceptDecl::CreateDeserialized(Context, ID);
3854 case DECL_REQUIRES_EXPR_BODY:
3855 D = RequiresExprBodyDecl::CreateDeserialized(Context, ID);
3857 case DECL_STATIC_ASSERT:
3858 D = StaticAssertDecl::CreateDeserialized(Context, ID);
3860 case DECL_OBJC_METHOD:
3861 D = ObjCMethodDecl::CreateDeserialized(Context, ID);
3863 case DECL_OBJC_INTERFACE:
3864 D = ObjCInterfaceDecl::CreateDeserialized(Context, ID);
3866 case DECL_OBJC_IVAR:
3867 D = ObjCIvarDecl::CreateDeserialized(Context, ID);
3869 case DECL_OBJC_PROTOCOL:
3870 D = ObjCProtocolDecl::CreateDeserialized(Context, ID);
3872 case DECL_OBJC_AT_DEFS_FIELD:
3873 D = ObjCAtDefsFieldDecl::CreateDeserialized(Context, ID);
3875 case DECL_OBJC_CATEGORY:
3876 D = ObjCCategoryDecl::CreateDeserialized(Context, ID);
3878 case DECL_OBJC_CATEGORY_IMPL:
3879 D = ObjCCategoryImplDecl::CreateDeserialized(Context, ID);
3881 case DECL_OBJC_IMPLEMENTATION:
3882 D = ObjCImplementationDecl::CreateDeserialized(Context, ID);
3884 case DECL_OBJC_COMPATIBLE_ALIAS:
3885 D = ObjCCompatibleAliasDecl::CreateDeserialized(Context, ID);
3887 case DECL_OBJC_PROPERTY:
3888 D = ObjCPropertyDecl::CreateDeserialized(Context, ID);
3890 case DECL_OBJC_PROPERTY_IMPL:
3891 D = ObjCPropertyImplDecl::CreateDeserialized(Context, ID);
3894 D = FieldDecl::CreateDeserialized(Context, ID);
3896 case DECL_INDIRECTFIELD:
3897 D = IndirectFieldDecl::CreateDeserialized(Context, ID);
3900 D = VarDecl::CreateDeserialized(Context, ID);
3902 case DECL_IMPLICIT_PARAM:
3903 D = ImplicitParamDecl::CreateDeserialized(Context, ID);
3906 D = ParmVarDecl::CreateDeserialized(Context, ID);
3908 case DECL_DECOMPOSITION:
3909 D = DecompositionDecl::CreateDeserialized(Context, ID, Record.readInt());
3912 D = BindingDecl::CreateDeserialized(Context, ID);
3914 case DECL_FILE_SCOPE_ASM:
3915 D = FileScopeAsmDecl::CreateDeserialized(Context, ID);
3918 D = BlockDecl::CreateDeserialized(Context, ID);
3920 case DECL_MS_PROPERTY:
3921 D = MSPropertyDecl::CreateDeserialized(Context, ID);
3924 D = CapturedDecl::CreateDeserialized(Context, ID, Record.readInt());
3926 case DECL_CXX_BASE_SPECIFIERS:
3927 Error("attempt to read a C++ base-specifier record as a declaration");
3929 case DECL_CXX_CTOR_INITIALIZERS:
3930 Error("attempt to read a C++ ctor initializer record as a declaration");
3933 // Note: last entry of the ImportDecl record is the number of stored source
3935 D = ImportDecl::CreateDeserialized(Context, ID, Record.back());
3937 case DECL_OMP_THREADPRIVATE:
3938 D = OMPThreadPrivateDecl::CreateDeserialized(Context, ID, Record.readInt());
3940 case DECL_OMP_ALLOCATE: {
3941 unsigned NumVars = Record.readInt();
3942 unsigned NumClauses = Record.readInt();
3943 D = OMPAllocateDecl::CreateDeserialized(Context, ID, NumVars, NumClauses);
3946 case DECL_OMP_REQUIRES:
3947 D = OMPRequiresDecl::CreateDeserialized(Context, ID, Record.readInt());
3949 case DECL_OMP_DECLARE_REDUCTION:
3950 D = OMPDeclareReductionDecl::CreateDeserialized(Context, ID);
3952 case DECL_OMP_DECLARE_MAPPER:
3953 D = OMPDeclareMapperDecl::CreateDeserialized(Context, ID, Record.readInt());
3955 case DECL_OMP_CAPTUREDEXPR:
3956 D = OMPCapturedExprDecl::CreateDeserialized(Context, ID);
3958 case DECL_PRAGMA_COMMENT:
3959 D = PragmaCommentDecl::CreateDeserialized(Context, ID, Record.readInt());
3961 case DECL_PRAGMA_DETECT_MISMATCH:
3962 D = PragmaDetectMismatchDecl::CreateDeserialized(Context, ID,
3966 D = EmptyDecl::CreateDeserialized(Context, ID);
3968 case DECL_LIFETIME_EXTENDED_TEMPORARY:
3969 D = LifetimeExtendedTemporaryDecl::CreateDeserialized(Context, ID);
3971 case DECL_OBJC_TYPE_PARAM:
3972 D = ObjCTypeParamDecl::CreateDeserialized(Context, ID);
3976 assert(D && "Unknown declaration reading AST file");
3977 LoadedDecl(Index, D);
3978 // Set the DeclContext before doing any deserialization, to make sure internal
3979 // calls to Decl::getASTContext() by Decl's methods will find the
3980 // TranslationUnitDecl without crashing.
3981 D->setDeclContext(Context.getTranslationUnitDecl());
3984 // If this declaration is also a declaration context, get the
3985 // offsets for its tables of lexical and visible declarations.
3986 if (auto *DC = dyn_cast<DeclContext>(D)) {
3987 std::pair<uint64_t, uint64_t> Offsets = Reader.VisitDeclContext(DC);
3988 if (Offsets.first &&
3989 ReadLexicalDeclContextStorage(*Loc.F, DeclsCursor, Offsets.first, DC))
3991 if (Offsets.second &&
3992 ReadVisibleDeclContextStorage(*Loc.F, DeclsCursor, Offsets.second, ID))
3995 assert(Record.getIdx() == Record.size());
3997 // Load any relevant update records.
3998 PendingUpdateRecords.push_back(
3999 PendingUpdateRecord(ID, D, /*JustLoaded=*/true));
4001 // Load the categories after recursive loading is finished.
4002 if (auto *Class = dyn_cast<ObjCInterfaceDecl>(D))
4003 // If we already have a definition when deserializing the ObjCInterfaceDecl,
4004 // we put the Decl in PendingDefinitions so we can pull the categories here.
4005 if (Class->isThisDeclarationADefinition() ||
4006 PendingDefinitions.count(Class))
4007 loadObjCCategories(ID, Class);
4009 // If we have deserialized a declaration that has a definition the
4010 // AST consumer might need to know about, queue it.
4011 // We don't pass it to the consumer immediately because we may be in recursive
4012 // loading, and some declarations may still be initializing.
4013 PotentiallyInterestingDecls.push_back(
4014 InterestingDecl(D, Reader.hasPendingBody()));
4019 void ASTReader::PassInterestingDeclsToConsumer() {
4022 if (PassingDeclsToConsumer)
4025 // Guard variable to avoid recursively redoing the process of passing
4026 // decls to consumer.
4027 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
4030 // Ensure that we've loaded all potentially-interesting declarations
4031 // that need to be eagerly loaded.
4032 for (auto ID : EagerlyDeserializedDecls)
4034 EagerlyDeserializedDecls.clear();
4036 while (!PotentiallyInterestingDecls.empty()) {
4037 InterestingDecl D = PotentiallyInterestingDecls.front();
4038 PotentiallyInterestingDecls.pop_front();
4039 if (isConsumerInterestedIn(getContext(), D.getDecl(), D.hasPendingBody()))
4040 PassInterestingDeclToConsumer(D.getDecl());
4044 void ASTReader::loadDeclUpdateRecords(PendingUpdateRecord &Record) {
4045 // The declaration may have been modified by files later in the chain.
4046 // If this is the case, read the record containing the updates from each file
4047 // and pass it to ASTDeclReader to make the modifications.
4048 serialization::GlobalDeclID ID = Record.ID;
4050 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
4051 DeclUpdateOffsetsMap::iterator UpdI = DeclUpdateOffsets.find(ID);
4053 SmallVector<serialization::DeclID, 8> PendingLazySpecializationIDs;
4055 if (UpdI != DeclUpdateOffsets.end()) {
4056 auto UpdateOffsets = std::move(UpdI->second);
4057 DeclUpdateOffsets.erase(UpdI);
4059 // Check if this decl was interesting to the consumer. If we just loaded
4060 // the declaration, then we know it was interesting and we skip the call
4061 // to isConsumerInterestedIn because it is unsafe to call in the
4062 // current ASTReader state.
4063 bool WasInteresting =
4064 Record.JustLoaded || isConsumerInterestedIn(getContext(), D, false);
4065 for (auto &FileAndOffset : UpdateOffsets) {
4066 ModuleFile *F = FileAndOffset.first;
4067 uint64_t Offset = FileAndOffset.second;
4068 llvm::BitstreamCursor &Cursor = F->DeclsCursor;
4069 SavedStreamPosition SavedPosition(Cursor);
4070 if (llvm::Error JumpFailed = Cursor.JumpToBit(Offset))
4071 // FIXME don't do a fatal error.
4072 llvm::report_fatal_error(
4073 "ASTReader::loadDeclUpdateRecords failed jumping: " +
4074 toString(std::move(JumpFailed)));
4075 Expected<unsigned> MaybeCode = Cursor.ReadCode();
4077 llvm::report_fatal_error(
4078 "ASTReader::loadDeclUpdateRecords failed reading code: " +
4079 toString(MaybeCode.takeError()));
4080 unsigned Code = MaybeCode.get();
4081 ASTRecordReader Record(*this, *F);
4082 if (Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code))
4083 assert(MaybeRecCode.get() == DECL_UPDATES &&
4084 "Expected DECL_UPDATES record!");
4086 llvm::report_fatal_error(
4087 "ASTReader::loadDeclUpdateRecords failed reading rec code: " +
4088 toString(MaybeCode.takeError()));
4090 ASTDeclReader Reader(*this, Record, RecordLocation(F, Offset), ID,
4092 Reader.UpdateDecl(D, PendingLazySpecializationIDs);
4094 // We might have made this declaration interesting. If so, remember that
4095 // we need to hand it off to the consumer.
4096 if (!WasInteresting &&
4097 isConsumerInterestedIn(getContext(), D, Reader.hasPendingBody())) {
4098 PotentiallyInterestingDecls.push_back(
4099 InterestingDecl(D, Reader.hasPendingBody()));
4100 WasInteresting = true;
4104 // Add the lazy specializations to the template.
4105 assert((PendingLazySpecializationIDs.empty() || isa<ClassTemplateDecl>(D) ||
4106 isa<FunctionTemplateDecl>(D) || isa<VarTemplateDecl>(D)) &&
4107 "Must not have pending specializations");
4108 if (auto *CTD = dyn_cast<ClassTemplateDecl>(D))
4109 ASTDeclReader::AddLazySpecializations(CTD, PendingLazySpecializationIDs);
4110 else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
4111 ASTDeclReader::AddLazySpecializations(FTD, PendingLazySpecializationIDs);
4112 else if (auto *VTD = dyn_cast<VarTemplateDecl>(D))
4113 ASTDeclReader::AddLazySpecializations(VTD, PendingLazySpecializationIDs);
4114 PendingLazySpecializationIDs.clear();
4116 // Load the pending visible updates for this decl context, if it has any.
4117 auto I = PendingVisibleUpdates.find(ID);
4118 if (I != PendingVisibleUpdates.end()) {
4119 auto VisibleUpdates = std::move(I->second);
4120 PendingVisibleUpdates.erase(I);
4122 auto *DC = cast<DeclContext>(D)->getPrimaryContext();
4123 for (const auto &Update : VisibleUpdates)
4124 Lookups[DC].Table.add(
4125 Update.Mod, Update.Data,
4126 reader::ASTDeclContextNameLookupTrait(*this, *Update.Mod));
4127 DC->setHasExternalVisibleStorage(true);
4131 void ASTReader::loadPendingDeclChain(Decl *FirstLocal, uint64_t LocalOffset) {
4132 // Attach FirstLocal to the end of the decl chain.
4133 Decl *CanonDecl = FirstLocal->getCanonicalDecl();
4134 if (FirstLocal != CanonDecl) {
4135 Decl *PrevMostRecent = ASTDeclReader::getMostRecentDecl(CanonDecl);
4136 ASTDeclReader::attachPreviousDecl(
4137 *this, FirstLocal, PrevMostRecent ? PrevMostRecent : CanonDecl,
4142 ASTDeclReader::attachLatestDecl(CanonDecl, FirstLocal);
4146 // Load the list of other redeclarations from this module file.
4147 ModuleFile *M = getOwningModuleFile(FirstLocal);
4148 assert(M && "imported decl from no module file");
4150 llvm::BitstreamCursor &Cursor = M->DeclsCursor;
4151 SavedStreamPosition SavedPosition(Cursor);
4152 if (llvm::Error JumpFailed = Cursor.JumpToBit(LocalOffset))
4153 llvm::report_fatal_error(
4154 "ASTReader::loadPendingDeclChain failed jumping: " +
4155 toString(std::move(JumpFailed)));
4158 Expected<unsigned> MaybeCode = Cursor.ReadCode();
4160 llvm::report_fatal_error(
4161 "ASTReader::loadPendingDeclChain failed reading code: " +
4162 toString(MaybeCode.takeError()));
4163 unsigned Code = MaybeCode.get();
4164 if (Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record))
4165 assert(MaybeRecCode.get() == LOCAL_REDECLARATIONS &&
4166 "expected LOCAL_REDECLARATIONS record!");
4168 llvm::report_fatal_error(
4169 "ASTReader::loadPendingDeclChain failed reading rec code: " +
4170 toString(MaybeCode.takeError()));
4172 // FIXME: We have several different dispatches on decl kind here; maybe
4173 // we should instead generate one loop per kind and dispatch up-front?
4174 Decl *MostRecent = FirstLocal;
4175 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
4176 auto *D = GetLocalDecl(*M, Record[N - I - 1]);
4177 ASTDeclReader::attachPreviousDecl(*this, D, MostRecent, CanonDecl);
4180 ASTDeclReader::attachLatestDecl(CanonDecl, MostRecent);
4185 /// Given an ObjC interface, goes through the modules and links to the
4186 /// interface all the categories for it.
4187 class ObjCCategoriesVisitor {
4189 ObjCInterfaceDecl *Interface;
4190 llvm::SmallPtrSetImpl<ObjCCategoryDecl *> &Deserialized;
4191 ObjCCategoryDecl *Tail = nullptr;
4192 llvm::DenseMap<DeclarationName, ObjCCategoryDecl *> NameCategoryMap;
4193 serialization::GlobalDeclID InterfaceID;
4194 unsigned PreviousGeneration;
4196 void add(ObjCCategoryDecl *Cat) {
4197 // Only process each category once.
4198 if (!Deserialized.erase(Cat))
4201 // Check for duplicate categories.
4202 if (Cat->getDeclName()) {
4203 ObjCCategoryDecl *&Existing = NameCategoryMap[Cat->getDeclName()];
4205 Reader.getOwningModuleFile(Existing)
4206 != Reader.getOwningModuleFile(Cat)) {
4207 // FIXME: We should not warn for duplicates in diamond:
4215 // If there are duplicates in ML/MR, there will be warning when
4216 // creating MB *and* when importing MB. We should not warn when
4218 Reader.Diag(Cat->getLocation(), diag::warn_dup_category_def)
4219 << Interface->getDeclName() << Cat->getDeclName();
4220 Reader.Diag(Existing->getLocation(), diag::note_previous_definition);
4221 } else if (!Existing) {
4222 // Record this category.
4227 // Add this category to the end of the chain.
4229 ASTDeclReader::setNextObjCCategory(Tail, Cat);
4231 Interface->setCategoryListRaw(Cat);
4236 ObjCCategoriesVisitor(ASTReader &Reader,
4237 ObjCInterfaceDecl *Interface,
4238 llvm::SmallPtrSetImpl<ObjCCategoryDecl *> &Deserialized,
4239 serialization::GlobalDeclID InterfaceID,
4240 unsigned PreviousGeneration)
4241 : Reader(Reader), Interface(Interface), Deserialized(Deserialized),
4242 InterfaceID(InterfaceID), PreviousGeneration(PreviousGeneration) {
4243 // Populate the name -> category map with the set of known categories.
4244 for (auto *Cat : Interface->known_categories()) {
4245 if (Cat->getDeclName())
4246 NameCategoryMap[Cat->getDeclName()] = Cat;
4248 // Keep track of the tail of the category list.
4253 bool operator()(ModuleFile &M) {
4254 // If we've loaded all of the category information we care about from
4255 // this module file, we're done.
4256 if (M.Generation <= PreviousGeneration)
4259 // Map global ID of the definition down to the local ID used in this
4260 // module file. If there is no such mapping, we'll find nothing here
4261 // (or in any module it imports).
4262 DeclID LocalID = Reader.mapGlobalIDToModuleFileGlobalID(M, InterfaceID);
4266 // Perform a binary search to find the local redeclarations for this
4267 // declaration (if any).
4268 const ObjCCategoriesInfo Compare = { LocalID, 0 };
4269 const ObjCCategoriesInfo *Result
4270 = std::lower_bound(M.ObjCCategoriesMap,
4271 M.ObjCCategoriesMap + M.LocalNumObjCCategoriesInMap,
4273 if (Result == M.ObjCCategoriesMap + M.LocalNumObjCCategoriesInMap ||
4274 Result->DefinitionID != LocalID) {
4275 // We didn't find anything. If the class definition is in this module
4276 // file, then the module files it depends on cannot have any categories,
4277 // so suppress further lookup.
4278 return Reader.isDeclIDFromModule(InterfaceID, M);
4281 // We found something. Dig out all of the categories.
4282 unsigned Offset = Result->Offset;
4283 unsigned N = M.ObjCCategories[Offset];
4284 M.ObjCCategories[Offset++] = 0; // Don't try to deserialize again
4285 for (unsigned I = 0; I != N; ++I)
4286 add(cast_or_null<ObjCCategoryDecl>(
4287 Reader.GetLocalDecl(M, M.ObjCCategories[Offset++])));
4294 void ASTReader::loadObjCCategories(serialization::GlobalDeclID ID,
4295 ObjCInterfaceDecl *D,
4296 unsigned PreviousGeneration) {
4297 ObjCCategoriesVisitor Visitor(*this, D, CategoriesDeserialized, ID,
4298 PreviousGeneration);
4299 ModuleMgr.visit(Visitor);
4302 template<typename DeclT, typename Fn>
4303 static void forAllLaterRedecls(DeclT *D, Fn F) {
4306 // Check whether we've already merged D into its redeclaration chain.
4307 // MostRecent may or may not be nullptr if D has not been merged. If
4308 // not, walk the merged redecl chain and see if it's there.
4309 auto *MostRecent = D->getMostRecentDecl();
4311 for (auto *Redecl = MostRecent; Redecl && !Found;
4312 Redecl = Redecl->getPreviousDecl())
4313 Found = (Redecl == D);
4315 // If this declaration is merged, apply the functor to all later decls.
4317 for (auto *Redecl = MostRecent; Redecl != D;
4318 Redecl = Redecl->getPreviousDecl())
4323 void ASTDeclReader::UpdateDecl(Decl *D,
4324 llvm::SmallVectorImpl<serialization::DeclID> &PendingLazySpecializationIDs) {
4325 while (Record.getIdx() < Record.size()) {
4326 switch ((DeclUpdateKind)Record.readInt()) {
4327 case UPD_CXX_ADDED_IMPLICIT_MEMBER: {
4328 auto *RD = cast<CXXRecordDecl>(D);
4329 // FIXME: If we also have an update record for instantiating the
4330 // definition of D, we need that to happen before we get here.
4331 Decl *MD = Record.readDecl();
4332 assert(MD && "couldn't read decl from update record");
4333 // FIXME: We should call addHiddenDecl instead, to add the member
4334 // to its DeclContext.
4335 RD->addedMember(MD);
4339 case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
4340 // It will be added to the template's lazy specialization set.
4341 PendingLazySpecializationIDs.push_back(readDeclID());
4344 case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE: {
4345 auto *Anon = readDeclAs<NamespaceDecl>();
4347 // Each module has its own anonymous namespace, which is disjoint from
4348 // any other module's anonymous namespaces, so don't attach the anonymous
4349 // namespace at all.
4350 if (!Record.isModule()) {
4351 if (auto *TU = dyn_cast<TranslationUnitDecl>(D))
4352 TU->setAnonymousNamespace(Anon);
4354 cast<NamespaceDecl>(D)->setAnonymousNamespace(Anon);
4359 case UPD_CXX_ADDED_VAR_DEFINITION: {
4360 auto *VD = cast<VarDecl>(D);
4361 VD->NonParmVarDeclBits.IsInline = Record.readInt();
4362 VD->NonParmVarDeclBits.IsInlineSpecified = Record.readInt();
4363 uint64_t Val = Record.readInt();
4364 if (Val && !VD->getInit()) {
4365 VD->setInit(Record.readExpr());
4366 if (Val > 1) { // IsInitKnownICE = 1, IsInitNotICE = 2, IsInitICE = 3
4367 EvaluatedStmt *Eval = VD->ensureEvaluatedStmt();
4368 Eval->CheckedICE = true;
4369 Eval->IsICE = Val == 3;
4375 case UPD_CXX_POINT_OF_INSTANTIATION: {
4376 SourceLocation POI = Record.readSourceLocation();
4377 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D)) {
4378 VTSD->setPointOfInstantiation(POI);
4379 } else if (auto *VD = dyn_cast<VarDecl>(D)) {
4380 VD->getMemberSpecializationInfo()->setPointOfInstantiation(POI);
4382 auto *FD = cast<FunctionDecl>(D);
4383 if (auto *FTSInfo = FD->TemplateOrSpecialization
4384 .dyn_cast<FunctionTemplateSpecializationInfo *>())
4385 FTSInfo->setPointOfInstantiation(POI);
4387 FD->TemplateOrSpecialization.get<MemberSpecializationInfo *>()
4388 ->setPointOfInstantiation(POI);
4393 case UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT: {
4394 auto *Param = cast<ParmVarDecl>(D);
4396 // We have to read the default argument regardless of whether we use it
4397 // so that hypothetical further update records aren't messed up.
4398 // TODO: Add a function to skip over the next expr record.
4399 auto *DefaultArg = Record.readExpr();
4401 // Only apply the update if the parameter still has an uninstantiated
4402 // default argument.
4403 if (Param->hasUninstantiatedDefaultArg())
4404 Param->setDefaultArg(DefaultArg);
4408 case UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER: {
4409 auto *FD = cast<FieldDecl>(D);
4410 auto *DefaultInit = Record.readExpr();
4412 // Only apply the update if the field still has an uninstantiated
4413 // default member initializer.
4414 if (FD->hasInClassInitializer() && !FD->getInClassInitializer()) {
4416 FD->setInClassInitializer(DefaultInit);
4418 // Instantiation failed. We can get here if we serialized an AST for
4419 // an invalid program.
4420 FD->removeInClassInitializer();
4425 case UPD_CXX_ADDED_FUNCTION_DEFINITION: {
4426 auto *FD = cast<FunctionDecl>(D);
4427 if (Reader.PendingBodies[FD]) {
4428 // FIXME: Maybe check for ODR violations.
4429 // It's safe to stop now because this update record is always last.
4433 if (Record.readInt()) {
4434 // Maintain AST consistency: any later redeclarations of this function
4435 // are inline if this one is. (We might have merged another declaration
4437 forAllLaterRedecls(FD, [](FunctionDecl *FD) {
4438 FD->setImplicitlyInline();
4441 FD->setInnerLocStart(readSourceLocation());
4442 ReadFunctionDefinition(FD);
4443 assert(Record.getIdx() == Record.size() && "lazy body must be last");
4447 case UPD_CXX_INSTANTIATED_CLASS_DEFINITION: {
4448 auto *RD = cast<CXXRecordDecl>(D);
4449 auto *OldDD = RD->getCanonicalDecl()->DefinitionData;
4450 bool HadRealDefinition =
4451 OldDD && (OldDD->Definition != RD ||
4452 !Reader.PendingFakeDefinitionData.count(OldDD));
4453 RD->setParamDestroyedInCallee(Record.readInt());
4454 RD->setArgPassingRestrictions(
4455 (RecordDecl::ArgPassingKind)Record.readInt());
4456 ReadCXXRecordDefinition(RD, /*Update*/true);
4458 // Visible update is handled separately.
4459 uint64_t LexicalOffset = ReadLocalOffset();
4460 if (!HadRealDefinition && LexicalOffset) {
4461 Record.readLexicalDeclContextStorage(LexicalOffset, RD);
4462 Reader.PendingFakeDefinitionData.erase(OldDD);
4465 auto TSK = (TemplateSpecializationKind)Record.readInt();
4466 SourceLocation POI = readSourceLocation();
4467 if (MemberSpecializationInfo *MSInfo =
4468 RD->getMemberSpecializationInfo()) {
4469 MSInfo->setTemplateSpecializationKind(TSK);
4470 MSInfo->setPointOfInstantiation(POI);
4472 auto *Spec = cast<ClassTemplateSpecializationDecl>(RD);
4473 Spec->setTemplateSpecializationKind(TSK);
4474 Spec->setPointOfInstantiation(POI);
4476 if (Record.readInt()) {
4478 readDeclAs<ClassTemplatePartialSpecializationDecl>();
4479 SmallVector<TemplateArgument, 8> TemplArgs;
4480 Record.readTemplateArgumentList(TemplArgs);
4481 auto *TemplArgList = TemplateArgumentList::CreateCopy(
4482 Reader.getContext(), TemplArgs);
4484 // FIXME: If we already have a partial specialization set,
4485 // check that it matches.
4486 if (!Spec->getSpecializedTemplateOrPartial()
4487 .is<ClassTemplatePartialSpecializationDecl *>())
4488 Spec->setInstantiationOf(PartialSpec, TemplArgList);
4492 RD->setTagKind((TagTypeKind)Record.readInt());
4493 RD->setLocation(readSourceLocation());
4494 RD->setLocStart(readSourceLocation());
4495 RD->setBraceRange(readSourceRange());
4497 if (Record.readInt()) {
4499 Record.readAttributes(Attrs);
4500 // If the declaration already has attributes, we assume that some other
4501 // AST file already loaded them.
4503 D->setAttrsImpl(Attrs, Reader.getContext());
4508 case UPD_CXX_RESOLVED_DTOR_DELETE: {
4509 // Set the 'operator delete' directly to avoid emitting another update
4511 auto *Del = readDeclAs<FunctionDecl>();
4512 auto *First = cast<CXXDestructorDecl>(D->getCanonicalDecl());
4513 auto *ThisArg = Record.readExpr();
4514 // FIXME: Check consistency if we have an old and new operator delete.
4515 if (!First->OperatorDelete) {
4516 First->OperatorDelete = Del;
4517 First->OperatorDeleteThisArg = ThisArg;
4522 case UPD_CXX_RESOLVED_EXCEPTION_SPEC: {
4523 SmallVector<QualType, 8> ExceptionStorage;
4524 auto ESI = Record.readExceptionSpecInfo(ExceptionStorage);
4526 // Update this declaration's exception specification, if needed.
4527 auto *FD = cast<FunctionDecl>(D);
4528 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
4529 // FIXME: If the exception specification is already present, check that it
4531 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
4532 FD->setType(Reader.getContext().getFunctionType(
4533 FPT->getReturnType(), FPT->getParamTypes(),
4534 FPT->getExtProtoInfo().withExceptionSpec(ESI)));
4536 // When we get to the end of deserializing, see if there are other decls
4537 // that we need to propagate this exception specification onto.
4538 Reader.PendingExceptionSpecUpdates.insert(
4539 std::make_pair(FD->getCanonicalDecl(), FD));
4544 case UPD_CXX_DEDUCED_RETURN_TYPE: {
4545 auto *FD = cast<FunctionDecl>(D);
4546 QualType DeducedResultType = Record.readType();
4547 Reader.PendingDeducedTypeUpdates.insert(
4548 {FD->getCanonicalDecl(), DeducedResultType});
4552 case UPD_DECL_MARKED_USED:
4553 // Maintain AST consistency: any later redeclarations are used too.
4554 D->markUsed(Reader.getContext());
4557 case UPD_MANGLING_NUMBER:
4558 Reader.getContext().setManglingNumber(cast<NamedDecl>(D),
4562 case UPD_STATIC_LOCAL_NUMBER:
4563 Reader.getContext().setStaticLocalNumber(cast<VarDecl>(D),
4567 case UPD_DECL_MARKED_OPENMP_THREADPRIVATE:
4568 D->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
4569 Reader.getContext(), readSourceRange(),
4570 AttributeCommonInfo::AS_Pragma));
4573 case UPD_DECL_MARKED_OPENMP_ALLOCATE: {
4574 auto AllocatorKind =
4575 static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(Record.readInt());
4576 Expr *Allocator = Record.readExpr();
4577 SourceRange SR = readSourceRange();
4578 D->addAttr(OMPAllocateDeclAttr::CreateImplicit(
4579 Reader.getContext(), AllocatorKind, Allocator, SR,
4580 AttributeCommonInfo::AS_Pragma));
4584 case UPD_DECL_EXPORTED: {
4585 unsigned SubmoduleID = readSubmoduleID();
4586 auto *Exported = cast<NamedDecl>(D);
4587 Module *Owner = SubmoduleID ? Reader.getSubmodule(SubmoduleID) : nullptr;
4588 Reader.getContext().mergeDefinitionIntoModule(Exported, Owner);
4589 Reader.PendingMergedDefinitionsToDeduplicate.insert(Exported);
4593 case UPD_DECL_MARKED_OPENMP_DECLARETARGET: {
4594 OMPDeclareTargetDeclAttr::MapTypeTy MapType =
4595 static_cast<OMPDeclareTargetDeclAttr::MapTypeTy>(Record.readInt());
4596 OMPDeclareTargetDeclAttr::DevTypeTy DevType =
4597 static_cast<OMPDeclareTargetDeclAttr::DevTypeTy>(Record.readInt());
4598 D->addAttr(OMPDeclareTargetDeclAttr::CreateImplicit(
4599 Reader.getContext(), MapType, DevType, readSourceRange(),
4600 AttributeCommonInfo::AS_Pragma));
4604 case UPD_ADDED_ATTR_TO_RECORD:
4606 Record.readAttributes(Attrs);
4607 assert(Attrs.size() == 1);
4608 D->addAttr(Attrs[0]);