1 //===--- ASTReaderDecl.cpp - Decl Deserialization ---------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the ASTReader::ReadDeclRecord method, which is the
11 // entrypoint for loading a decl.
13 //===----------------------------------------------------------------------===//
15 #include "clang/Serialization/ASTReader.h"
16 #include "ASTCommon.h"
17 #include "ASTReaderInternals.h"
18 #include "clang/AST/ASTConsumer.h"
19 #include "clang/AST/ASTContext.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclGroup.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/DeclVisitor.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/Sema/IdentifierResolver.h"
26 #include "clang/Sema/Sema.h"
27 #include "clang/Sema/SemaDiagnostic.h"
28 #include "llvm/Support/SaveAndRestore.h"
29 using namespace clang;
30 using namespace clang::serialization;
32 //===----------------------------------------------------------------------===//
33 // Declaration deserialization
34 //===----------------------------------------------------------------------===//
37 class ASTDeclReader : public DeclVisitor<ASTDeclReader, void> {
40 const DeclID ThisDeclID;
41 const unsigned RawLocation;
42 typedef ASTReader::RecordData RecordData;
43 const RecordData &Record;
45 TypeID TypeIDForTypeDecl;
46 unsigned AnonymousDeclNumber;
47 GlobalDeclID NamedDeclForTagDecl;
48 IdentifierInfo *TypedefNameForLinkage;
52 uint64_t GetCurrentCursorOffset();
54 SourceLocation ReadSourceLocation(const RecordData &R, unsigned &I) {
55 return Reader.ReadSourceLocation(F, R, I);
58 SourceRange ReadSourceRange(const RecordData &R, unsigned &I) {
59 return Reader.ReadSourceRange(F, R, I);
62 TypeSourceInfo *GetTypeSourceInfo(const RecordData &R, unsigned &I) {
63 return Reader.GetTypeSourceInfo(F, R, I);
66 serialization::DeclID ReadDeclID(const RecordData &R, unsigned &I) {
67 return Reader.ReadDeclID(F, R, I);
70 void ReadDeclIDList(SmallVectorImpl<DeclID> &IDs) {
71 for (unsigned I = 0, Size = Record[Idx++]; I != Size; ++I)
72 IDs.push_back(ReadDeclID(Record, Idx));
75 Decl *ReadDecl(const RecordData &R, unsigned &I) {
76 return Reader.ReadDecl(F, R, I);
80 T *ReadDeclAs(const RecordData &R, unsigned &I) {
81 return Reader.ReadDeclAs<T>(F, R, I);
84 void ReadQualifierInfo(QualifierInfo &Info,
85 const RecordData &R, unsigned &I) {
86 Reader.ReadQualifierInfo(F, Info, R, I);
89 void ReadDeclarationNameLoc(DeclarationNameLoc &DNLoc, DeclarationName Name,
90 const RecordData &R, unsigned &I) {
91 Reader.ReadDeclarationNameLoc(F, DNLoc, Name, R, I);
94 void ReadDeclarationNameInfo(DeclarationNameInfo &NameInfo,
95 const RecordData &R, unsigned &I) {
96 Reader.ReadDeclarationNameInfo(F, NameInfo, R, I);
99 serialization::SubmoduleID readSubmoduleID(const RecordData &R,
104 return Reader.getGlobalSubmoduleID(F, R[I++]);
107 Module *readModule(const RecordData &R, unsigned &I) {
108 return Reader.getSubmodule(readSubmoduleID(R, I));
111 void ReadCXXRecordDefinition(CXXRecordDecl *D, bool Update);
112 void ReadCXXDefinitionData(struct CXXRecordDecl::DefinitionData &Data,
113 const RecordData &R, unsigned &I);
114 void MergeDefinitionData(CXXRecordDecl *D,
115 struct CXXRecordDecl::DefinitionData &&NewDD);
117 static NamedDecl *getAnonymousDeclForMerging(ASTReader &Reader,
120 static void setAnonymousDeclForMerging(ASTReader &Reader, DeclContext *DC,
121 unsigned Index, NamedDecl *D);
123 /// \brief RAII class used to capture the first ID within a redeclaration
124 /// chain and to introduce it into the list of pending redeclaration chains
126 class RedeclarableResult {
128 GlobalDeclID FirstID;
133 void operator=(RedeclarableResult &) = delete;
136 RedeclarableResult(ASTReader &Reader, GlobalDeclID FirstID,
137 Decl *MergeWith, Decl::Kind DeclKind)
138 : Reader(Reader), FirstID(FirstID), MergeWith(MergeWith),
139 Owning(true), DeclKind(DeclKind) {}
141 RedeclarableResult(RedeclarableResult &&Other)
142 : Reader(Other.Reader), FirstID(Other.FirstID),
143 MergeWith(Other.MergeWith), Owning(Other.Owning),
144 DeclKind(Other.DeclKind) {
145 Other.Owning = false;
148 ~RedeclarableResult() {
149 if (FirstID && Owning && isRedeclarableDeclKind(DeclKind)) {
150 auto Canon = Reader.GetDecl(FirstID)->getCanonicalDecl();
151 if (Reader.PendingDeclChainsKnown.insert(Canon).second)
152 Reader.PendingDeclChains.push_back(Canon);
156 /// \brief Retrieve the first ID.
157 GlobalDeclID getFirstID() const { return FirstID; }
159 /// \brief Get a known declaration that this should be merged with, if
161 Decl *getKnownMergeTarget() const { return MergeWith; }
164 /// \brief Class used to capture the result of searching for an existing
165 /// declaration of a specific kind and name, along with the ability
166 /// to update the place where this result was found (the declaration
167 /// chain hanging off an identifier or the DeclContext we searched in)
169 class FindExistingResult {
173 mutable bool AddResult;
175 unsigned AnonymousDeclNumber;
176 IdentifierInfo *TypedefNameForLinkage;
178 void operator=(FindExistingResult&) = delete;
181 FindExistingResult(ASTReader &Reader)
182 : Reader(Reader), New(nullptr), Existing(nullptr), AddResult(false),
183 AnonymousDeclNumber(0), TypedefNameForLinkage(0) {}
185 FindExistingResult(ASTReader &Reader, NamedDecl *New, NamedDecl *Existing,
186 unsigned AnonymousDeclNumber,
187 IdentifierInfo *TypedefNameForLinkage)
188 : Reader(Reader), New(New), Existing(Existing), AddResult(true),
189 AnonymousDeclNumber(AnonymousDeclNumber),
190 TypedefNameForLinkage(TypedefNameForLinkage) {}
192 FindExistingResult(const FindExistingResult &Other)
193 : Reader(Other.Reader), New(Other.New), Existing(Other.Existing),
194 AddResult(Other.AddResult),
195 AnonymousDeclNumber(Other.AnonymousDeclNumber),
196 TypedefNameForLinkage(Other.TypedefNameForLinkage) {
197 Other.AddResult = false;
200 ~FindExistingResult();
202 /// \brief Suppress the addition of this result into the known set of
204 void suppress() { AddResult = false; }
206 operator NamedDecl*() const { return Existing; }
209 operator T*() const { return dyn_cast_or_null<T>(Existing); }
212 static DeclContext *getPrimaryContextForMerging(ASTReader &Reader,
214 FindExistingResult findExisting(NamedDecl *D);
217 ASTDeclReader(ASTReader &Reader, ModuleFile &F, DeclID thisDeclID,
218 unsigned RawLocation, const RecordData &Record, unsigned &Idx)
219 : Reader(Reader), F(F), ThisDeclID(thisDeclID),
220 RawLocation(RawLocation), Record(Record), Idx(Idx),
221 TypeIDForTypeDecl(0), NamedDeclForTagDecl(0),
222 TypedefNameForLinkage(nullptr), HasPendingBody(false) {}
224 template <typename DeclT>
225 static Decl *getMostRecentDeclImpl(Redeclarable<DeclT> *D);
226 static Decl *getMostRecentDeclImpl(...);
227 static Decl *getMostRecentDecl(Decl *D);
229 template <typename DeclT>
230 static void attachPreviousDeclImpl(ASTReader &Reader,
231 Redeclarable<DeclT> *D, Decl *Previous,
233 static void attachPreviousDeclImpl(ASTReader &Reader, ...);
234 static void attachPreviousDecl(ASTReader &Reader, Decl *D, Decl *Previous,
237 template <typename DeclT>
238 static void attachLatestDeclImpl(Redeclarable<DeclT> *D, Decl *Latest);
239 static void attachLatestDeclImpl(...);
240 static void attachLatestDecl(Decl *D, Decl *latest);
242 template <typename DeclT>
243 static void markIncompleteDeclChainImpl(Redeclarable<DeclT> *D);
244 static void markIncompleteDeclChainImpl(...);
246 /// \brief Determine whether this declaration has a pending body.
247 bool hasPendingBody() const { return HasPendingBody; }
251 void UpdateDecl(Decl *D, ModuleFile &ModuleFile,
252 const RecordData &Record);
254 static void setNextObjCCategory(ObjCCategoryDecl *Cat,
255 ObjCCategoryDecl *Next) {
256 Cat->NextClassCategory = Next;
259 void VisitDecl(Decl *D);
260 void VisitTranslationUnitDecl(TranslationUnitDecl *TU);
261 void VisitNamedDecl(NamedDecl *ND);
262 void VisitLabelDecl(LabelDecl *LD);
263 void VisitNamespaceDecl(NamespaceDecl *D);
264 void VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
265 void VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
266 void VisitTypeDecl(TypeDecl *TD);
267 RedeclarableResult VisitTypedefNameDecl(TypedefNameDecl *TD);
268 void VisitTypedefDecl(TypedefDecl *TD);
269 void VisitTypeAliasDecl(TypeAliasDecl *TD);
270 void VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
271 RedeclarableResult VisitTagDecl(TagDecl *TD);
272 void VisitEnumDecl(EnumDecl *ED);
273 RedeclarableResult VisitRecordDeclImpl(RecordDecl *RD);
274 void VisitRecordDecl(RecordDecl *RD) { VisitRecordDeclImpl(RD); }
275 RedeclarableResult VisitCXXRecordDeclImpl(CXXRecordDecl *D);
276 void VisitCXXRecordDecl(CXXRecordDecl *D) { VisitCXXRecordDeclImpl(D); }
277 RedeclarableResult VisitClassTemplateSpecializationDeclImpl(
278 ClassTemplateSpecializationDecl *D);
279 void VisitClassTemplateSpecializationDecl(
280 ClassTemplateSpecializationDecl *D) {
281 VisitClassTemplateSpecializationDeclImpl(D);
283 void VisitClassTemplatePartialSpecializationDecl(
284 ClassTemplatePartialSpecializationDecl *D);
285 void VisitClassScopeFunctionSpecializationDecl(
286 ClassScopeFunctionSpecializationDecl *D);
288 VisitVarTemplateSpecializationDeclImpl(VarTemplateSpecializationDecl *D);
289 void VisitVarTemplateSpecializationDecl(VarTemplateSpecializationDecl *D) {
290 VisitVarTemplateSpecializationDeclImpl(D);
292 void VisitVarTemplatePartialSpecializationDecl(
293 VarTemplatePartialSpecializationDecl *D);
294 void VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
295 void VisitValueDecl(ValueDecl *VD);
296 void VisitEnumConstantDecl(EnumConstantDecl *ECD);
297 void VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
298 void VisitDeclaratorDecl(DeclaratorDecl *DD);
299 void VisitFunctionDecl(FunctionDecl *FD);
300 void VisitCXXMethodDecl(CXXMethodDecl *D);
301 void VisitCXXConstructorDecl(CXXConstructorDecl *D);
302 void VisitCXXDestructorDecl(CXXDestructorDecl *D);
303 void VisitCXXConversionDecl(CXXConversionDecl *D);
304 void VisitFieldDecl(FieldDecl *FD);
305 void VisitMSPropertyDecl(MSPropertyDecl *FD);
306 void VisitIndirectFieldDecl(IndirectFieldDecl *FD);
307 RedeclarableResult VisitVarDeclImpl(VarDecl *D);
308 void VisitVarDecl(VarDecl *VD) { VisitVarDeclImpl(VD); }
309 void VisitImplicitParamDecl(ImplicitParamDecl *PD);
310 void VisitParmVarDecl(ParmVarDecl *PD);
311 void VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
312 DeclID VisitTemplateDecl(TemplateDecl *D);
313 RedeclarableResult VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D);
314 void VisitClassTemplateDecl(ClassTemplateDecl *D);
315 void VisitVarTemplateDecl(VarTemplateDecl *D);
316 void VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
317 void VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
318 void VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D);
319 void VisitUsingDecl(UsingDecl *D);
320 void VisitUsingShadowDecl(UsingShadowDecl *D);
321 void VisitLinkageSpecDecl(LinkageSpecDecl *D);
322 void VisitFileScopeAsmDecl(FileScopeAsmDecl *AD);
323 void VisitImportDecl(ImportDecl *D);
324 void VisitAccessSpecDecl(AccessSpecDecl *D);
325 void VisitFriendDecl(FriendDecl *D);
326 void VisitFriendTemplateDecl(FriendTemplateDecl *D);
327 void VisitStaticAssertDecl(StaticAssertDecl *D);
328 void VisitBlockDecl(BlockDecl *BD);
329 void VisitCapturedDecl(CapturedDecl *CD);
330 void VisitEmptyDecl(EmptyDecl *D);
332 std::pair<uint64_t, uint64_t> VisitDeclContext(DeclContext *DC);
335 RedeclarableResult VisitRedeclarable(Redeclarable<T> *D);
338 void mergeRedeclarable(Redeclarable<T> *D, RedeclarableResult &Redecl,
339 DeclID TemplatePatternID = 0);
342 void mergeRedeclarable(Redeclarable<T> *D, T *Existing,
343 RedeclarableResult &Redecl,
344 DeclID TemplatePatternID = 0);
347 void mergeMergeable(Mergeable<T> *D);
349 void mergeTemplatePattern(RedeclarableTemplateDecl *D,
350 RedeclarableTemplateDecl *Existing,
353 // FIXME: Reorder according to DeclNodes.td?
354 void VisitObjCMethodDecl(ObjCMethodDecl *D);
355 void VisitObjCContainerDecl(ObjCContainerDecl *D);
356 void VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
357 void VisitObjCIvarDecl(ObjCIvarDecl *D);
358 void VisitObjCProtocolDecl(ObjCProtocolDecl *D);
359 void VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D);
360 void VisitObjCCategoryDecl(ObjCCategoryDecl *D);
361 void VisitObjCImplDecl(ObjCImplDecl *D);
362 void VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
363 void VisitObjCImplementationDecl(ObjCImplementationDecl *D);
364 void VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *D);
365 void VisitObjCPropertyDecl(ObjCPropertyDecl *D);
366 void VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D);
367 void VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D);
371 uint64_t ASTDeclReader::GetCurrentCursorOffset() {
372 return F.DeclsCursor.GetCurrentBitNo() + F.GlobalBitOffset;
375 void ASTDeclReader::Visit(Decl *D) {
376 DeclVisitor<ASTDeclReader, void>::Visit(D);
378 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
380 DeclaratorDecl::ExtInfo *Info =
381 DD->DeclInfo.get<DeclaratorDecl::ExtInfo *>();
383 GetTypeSourceInfo(Record, Idx);
386 DD->DeclInfo = GetTypeSourceInfo(Record, Idx);
390 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
391 // We have a fully initialized TypeDecl. Read its type now.
392 TD->setTypeForDecl(Reader.GetType(TypeIDForTypeDecl).getTypePtrOrNull());
394 // If this is a tag declaration with a typedef name for linkage, it's safe
395 // to load that typedef now.
396 if (NamedDeclForTagDecl)
397 cast<TagDecl>(D)->NamedDeclOrQualifier =
398 cast<NamedDecl>(Reader.GetDecl(NamedDeclForTagDecl));
399 } else if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
400 // if we have a fully initialized TypeDecl, we can safely read its type now.
401 ID->TypeForDecl = Reader.GetType(TypeIDForTypeDecl).getTypePtrOrNull();
402 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
403 // FunctionDecl's body was written last after all other Stmts/Exprs.
404 // We only read it if FD doesn't already have a body (e.g., from another
406 // FIXME: Can we diagnose ODR violations somehow?
408 if (auto *CD = dyn_cast<CXXConstructorDecl>(FD)) {
409 CD->NumCtorInitializers = Record[Idx++];
410 if (CD->NumCtorInitializers)
411 CD->CtorInitializers =
412 Reader.ReadCXXCtorInitializersRef(F, Record, Idx);
414 Reader.PendingBodies[FD] = GetCurrentCursorOffset();
415 HasPendingBody = true;
420 void ASTDeclReader::VisitDecl(Decl *D) {
421 if (D->isTemplateParameter() || D->isTemplateParameterPack() ||
422 isa<ParmVarDecl>(D)) {
423 // We don't want to deserialize the DeclContext of a template
424 // parameter or of a parameter of a function template immediately. These
425 // entities might be used in the formulation of its DeclContext (for
426 // example, a function parameter can be used in decltype() in trailing
427 // return type of the function). Use the translation unit DeclContext as a
429 GlobalDeclID SemaDCIDForTemplateParmDecl = ReadDeclID(Record, Idx);
430 GlobalDeclID LexicalDCIDForTemplateParmDecl = ReadDeclID(Record, Idx);
431 Reader.addPendingDeclContextInfo(D,
432 SemaDCIDForTemplateParmDecl,
433 LexicalDCIDForTemplateParmDecl);
434 D->setDeclContext(Reader.getContext().getTranslationUnitDecl());
436 DeclContext *SemaDC = ReadDeclAs<DeclContext>(Record, Idx);
437 DeclContext *LexicalDC = ReadDeclAs<DeclContext>(Record, Idx);
438 DeclContext *MergedSemaDC = Reader.MergedDeclContexts.lookup(SemaDC);
439 // Avoid calling setLexicalDeclContext() directly because it uses
440 // Decl::getASTContext() internally which is unsafe during derialization.
441 D->setDeclContextsImpl(MergedSemaDC ? MergedSemaDC : SemaDC, LexicalDC,
442 Reader.getContext());
444 D->setLocation(Reader.ReadSourceLocation(F, RawLocation));
445 D->setInvalidDecl(Record[Idx++]);
446 if (Record[Idx++]) { // hasAttrs
448 Reader.ReadAttributes(F, Attrs, Record, Idx);
449 // Avoid calling setAttrs() directly because it uses Decl::getASTContext()
450 // internally which is unsafe during derialization.
451 D->setAttrsImpl(Attrs, Reader.getContext());
453 D->setImplicit(Record[Idx++]);
454 D->Used = Record[Idx++];
455 D->setReferenced(Record[Idx++]);
456 D->setTopLevelDeclInObjCContainer(Record[Idx++]);
457 D->setAccess((AccessSpecifier)Record[Idx++]);
458 D->FromASTFile = true;
459 D->setModulePrivate(Record[Idx++]);
460 D->Hidden = D->isModulePrivate();
462 // Determine whether this declaration is part of a (sub)module. If so, it
463 // may not yet be visible.
464 if (unsigned SubmoduleID = readSubmoduleID(Record, Idx)) {
465 // Store the owning submodule ID in the declaration.
466 D->setOwningModuleID(SubmoduleID);
469 // Module-private declarations are never visible, so there is no work to do.
470 } else if (Reader.getContext().getLangOpts().ModulesLocalVisibility) {
471 // If local visibility is being tracked, this declaration will become
472 // hidden and visible as the owning module does. Inform Sema that this
473 // declaration might not be visible.
475 } else if (Module *Owner = Reader.getSubmodule(SubmoduleID)) {
476 if (Owner->NameVisibility != Module::AllVisible) {
477 // The owning module is not visible. Mark this declaration as hidden.
480 // Note that this declaration was hidden because its owning module is
482 Reader.HiddenNamesMap[Owner].push_back(D);
488 void ASTDeclReader::VisitTranslationUnitDecl(TranslationUnitDecl *TU) {
489 llvm_unreachable("Translation units are not serialized");
492 void ASTDeclReader::VisitNamedDecl(NamedDecl *ND) {
494 ND->setDeclName(Reader.ReadDeclarationName(F, Record, Idx));
495 AnonymousDeclNumber = Record[Idx++];
498 void ASTDeclReader::VisitTypeDecl(TypeDecl *TD) {
500 TD->setLocStart(ReadSourceLocation(Record, Idx));
501 // Delay type reading until after we have fully initialized the decl.
502 TypeIDForTypeDecl = Reader.getGlobalTypeID(F, Record[Idx++]);
505 ASTDeclReader::RedeclarableResult
506 ASTDeclReader::VisitTypedefNameDecl(TypedefNameDecl *TD) {
507 RedeclarableResult Redecl = VisitRedeclarable(TD);
509 TypeSourceInfo *TInfo = GetTypeSourceInfo(Record, Idx);
510 if (Record[Idx++]) { // isModed
511 QualType modedT = Reader.readType(F, Record, Idx);
512 TD->setModedTypeSourceInfo(TInfo, modedT);
514 TD->setTypeSourceInfo(TInfo);
518 void ASTDeclReader::VisitTypedefDecl(TypedefDecl *TD) {
519 RedeclarableResult Redecl = VisitTypedefNameDecl(TD);
520 mergeRedeclarable(TD, Redecl);
523 void ASTDeclReader::VisitTypeAliasDecl(TypeAliasDecl *TD) {
524 RedeclarableResult Redecl = VisitTypedefNameDecl(TD);
525 if (auto *Template = ReadDeclAs<TypeAliasTemplateDecl>(Record, Idx))
526 // Merged when we merge the template.
527 TD->setDescribedAliasTemplate(Template);
529 mergeRedeclarable(TD, Redecl);
532 ASTDeclReader::RedeclarableResult ASTDeclReader::VisitTagDecl(TagDecl *TD) {
533 RedeclarableResult Redecl = VisitRedeclarable(TD);
536 TD->IdentifierNamespace = Record[Idx++];
537 TD->setTagKind((TagDecl::TagKind)Record[Idx++]);
538 if (!isa<CXXRecordDecl>(TD))
539 TD->setCompleteDefinition(Record[Idx++]);
540 TD->setEmbeddedInDeclarator(Record[Idx++]);
541 TD->setFreeStanding(Record[Idx++]);
542 TD->setCompleteDefinitionRequired(Record[Idx++]);
543 TD->setRBraceLoc(ReadSourceLocation(Record, Idx));
545 switch (Record[Idx++]) {
549 TagDecl::ExtInfo *Info = new (Reader.getContext()) TagDecl::ExtInfo();
550 ReadQualifierInfo(*Info, Record, Idx);
551 TD->NamedDeclOrQualifier = Info;
554 case 2: // TypedefNameForAnonDecl
555 NamedDeclForTagDecl = ReadDeclID(Record, Idx);
556 TypedefNameForLinkage = Reader.GetIdentifierInfo(F, Record, Idx);
558 case 3: // DeclaratorForAnonDecl
559 NamedDeclForTagDecl = ReadDeclID(Record, Idx);
562 llvm_unreachable("unexpected tag info kind");
565 if (!isa<CXXRecordDecl>(TD))
566 mergeRedeclarable(TD, Redecl);
570 void ASTDeclReader::VisitEnumDecl(EnumDecl *ED) {
572 if (TypeSourceInfo *TI = Reader.GetTypeSourceInfo(F, Record, Idx))
573 ED->setIntegerTypeSourceInfo(TI);
575 ED->setIntegerType(Reader.readType(F, Record, Idx));
576 ED->setPromotionType(Reader.readType(F, Record, Idx));
577 ED->setNumPositiveBits(Record[Idx++]);
578 ED->setNumNegativeBits(Record[Idx++]);
579 ED->IsScoped = Record[Idx++];
580 ED->IsScopedUsingClassTag = Record[Idx++];
581 ED->IsFixed = Record[Idx++];
583 // If this is a definition subject to the ODR, and we already have a
584 // definition, merge this one into it.
585 if (ED->IsCompleteDefinition &&
586 Reader.getContext().getLangOpts().Modules &&
587 Reader.getContext().getLangOpts().CPlusPlus) {
588 if (EnumDecl *&OldDef = Reader.EnumDefinitions[ED->getCanonicalDecl()]) {
589 Reader.MergedDeclContexts.insert(std::make_pair(ED, OldDef));
590 ED->IsCompleteDefinition = false;
596 if (EnumDecl *InstED = ReadDeclAs<EnumDecl>(Record, Idx)) {
597 TemplateSpecializationKind TSK = (TemplateSpecializationKind)Record[Idx++];
598 SourceLocation POI = ReadSourceLocation(Record, Idx);
599 ED->setInstantiationOfMemberEnum(Reader.getContext(), InstED, TSK);
600 ED->getMemberSpecializationInfo()->setPointOfInstantiation(POI);
604 ASTDeclReader::RedeclarableResult
605 ASTDeclReader::VisitRecordDeclImpl(RecordDecl *RD) {
606 RedeclarableResult Redecl = VisitTagDecl(RD);
607 RD->setHasFlexibleArrayMember(Record[Idx++]);
608 RD->setAnonymousStructOrUnion(Record[Idx++]);
609 RD->setHasObjectMember(Record[Idx++]);
610 RD->setHasVolatileMember(Record[Idx++]);
614 void ASTDeclReader::VisitValueDecl(ValueDecl *VD) {
616 VD->setType(Reader.readType(F, Record, Idx));
619 void ASTDeclReader::VisitEnumConstantDecl(EnumConstantDecl *ECD) {
622 ECD->setInitExpr(Reader.ReadExpr(F));
623 ECD->setInitVal(Reader.ReadAPSInt(Record, Idx));
627 void ASTDeclReader::VisitDeclaratorDecl(DeclaratorDecl *DD) {
629 DD->setInnerLocStart(ReadSourceLocation(Record, Idx));
630 if (Record[Idx++]) { // hasExtInfo
631 DeclaratorDecl::ExtInfo *Info
632 = new (Reader.getContext()) DeclaratorDecl::ExtInfo();
633 ReadQualifierInfo(*Info, Record, Idx);
638 void ASTDeclReader::VisitFunctionDecl(FunctionDecl *FD) {
639 RedeclarableResult Redecl = VisitRedeclarable(FD);
640 VisitDeclaratorDecl(FD);
642 ReadDeclarationNameLoc(FD->DNLoc, FD->getDeclName(), Record, Idx);
643 FD->IdentifierNamespace = Record[Idx++];
645 // FunctionDecl's body is handled last at ASTDeclReader::Visit,
646 // after everything else is read.
648 FD->SClass = (StorageClass)Record[Idx++];
649 FD->IsInline = Record[Idx++];
650 FD->IsInlineSpecified = Record[Idx++];
651 FD->IsVirtualAsWritten = Record[Idx++];
652 FD->IsPure = Record[Idx++];
653 FD->HasInheritedPrototype = Record[Idx++];
654 FD->HasWrittenPrototype = Record[Idx++];
655 FD->IsDeleted = Record[Idx++];
656 FD->IsTrivial = Record[Idx++];
657 FD->IsDefaulted = Record[Idx++];
658 FD->IsExplicitlyDefaulted = Record[Idx++];
659 FD->HasImplicitReturnZero = Record[Idx++];
660 FD->IsConstexpr = Record[Idx++];
661 FD->HasSkippedBody = Record[Idx++];
662 FD->IsLateTemplateParsed = Record[Idx++];
663 FD->setCachedLinkage(Linkage(Record[Idx++]));
664 FD->EndRangeLoc = ReadSourceLocation(Record, Idx);
666 switch ((FunctionDecl::TemplatedKind)Record[Idx++]) {
667 case FunctionDecl::TK_NonTemplate:
668 mergeRedeclarable(FD, Redecl);
670 case FunctionDecl::TK_FunctionTemplate:
671 // Merged when we merge the template.
672 FD->setDescribedFunctionTemplate(ReadDeclAs<FunctionTemplateDecl>(Record,
675 case FunctionDecl::TK_MemberSpecialization: {
676 FunctionDecl *InstFD = ReadDeclAs<FunctionDecl>(Record, Idx);
677 TemplateSpecializationKind TSK = (TemplateSpecializationKind)Record[Idx++];
678 SourceLocation POI = ReadSourceLocation(Record, Idx);
679 FD->setInstantiationOfMemberFunction(Reader.getContext(), InstFD, TSK);
680 FD->getMemberSpecializationInfo()->setPointOfInstantiation(POI);
681 mergeRedeclarable(FD, Redecl);
684 case FunctionDecl::TK_FunctionTemplateSpecialization: {
685 FunctionTemplateDecl *Template = ReadDeclAs<FunctionTemplateDecl>(Record,
687 TemplateSpecializationKind TSK = (TemplateSpecializationKind)Record[Idx++];
689 // Template arguments.
690 SmallVector<TemplateArgument, 8> TemplArgs;
691 Reader.ReadTemplateArgumentList(TemplArgs, F, Record, Idx);
693 // Template args as written.
694 SmallVector<TemplateArgumentLoc, 8> TemplArgLocs;
695 SourceLocation LAngleLoc, RAngleLoc;
696 bool HasTemplateArgumentsAsWritten = Record[Idx++];
697 if (HasTemplateArgumentsAsWritten) {
698 unsigned NumTemplateArgLocs = Record[Idx++];
699 TemplArgLocs.reserve(NumTemplateArgLocs);
700 for (unsigned i=0; i != NumTemplateArgLocs; ++i)
701 TemplArgLocs.push_back(
702 Reader.ReadTemplateArgumentLoc(F, Record, Idx));
704 LAngleLoc = ReadSourceLocation(Record, Idx);
705 RAngleLoc = ReadSourceLocation(Record, Idx);
708 SourceLocation POI = ReadSourceLocation(Record, Idx);
710 ASTContext &C = Reader.getContext();
711 TemplateArgumentList *TemplArgList
712 = TemplateArgumentList::CreateCopy(C, TemplArgs.data(), TemplArgs.size());
713 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
714 for (unsigned i=0, e = TemplArgLocs.size(); i != e; ++i)
715 TemplArgsInfo.addArgument(TemplArgLocs[i]);
716 FunctionTemplateSpecializationInfo *FTInfo
717 = FunctionTemplateSpecializationInfo::Create(C, FD, Template, TSK,
719 HasTemplateArgumentsAsWritten ? &TemplArgsInfo
722 FD->TemplateOrSpecialization = FTInfo;
724 if (FD->isCanonicalDecl()) { // if canonical add to template's set.
725 // The template that contains the specializations set. It's not safe to
726 // use getCanonicalDecl on Template since it may still be initializing.
727 FunctionTemplateDecl *CanonTemplate
728 = ReadDeclAs<FunctionTemplateDecl>(Record, Idx);
729 // Get the InsertPos by FindNodeOrInsertPos() instead of calling
730 // InsertNode(FTInfo) directly to avoid the getASTContext() call in
731 // FunctionTemplateSpecializationInfo's Profile().
732 // We avoid getASTContext because a decl in the parent hierarchy may
734 llvm::FoldingSetNodeID ID;
735 FunctionTemplateSpecializationInfo::Profile(ID, TemplArgs, C);
736 void *InsertPos = nullptr;
737 FunctionTemplateDecl::Common *CommonPtr = CanonTemplate->getCommonPtr();
738 CommonPtr->Specializations.FindNodeOrInsertPos(ID, InsertPos);
740 CommonPtr->Specializations.InsertNode(FTInfo, InsertPos);
742 assert(Reader.getContext().getLangOpts().Modules &&
743 "already deserialized this template specialization");
744 // FIXME: This specialization is a redeclaration of one from another
750 case FunctionDecl::TK_DependentFunctionTemplateSpecialization: {
752 UnresolvedSet<8> TemplDecls;
753 unsigned NumTemplates = Record[Idx++];
754 while (NumTemplates--)
755 TemplDecls.addDecl(ReadDeclAs<NamedDecl>(Record, Idx));
758 TemplateArgumentListInfo TemplArgs;
759 unsigned NumArgs = Record[Idx++];
761 TemplArgs.addArgument(Reader.ReadTemplateArgumentLoc(F, Record, Idx));
762 TemplArgs.setLAngleLoc(ReadSourceLocation(Record, Idx));
763 TemplArgs.setRAngleLoc(ReadSourceLocation(Record, Idx));
765 FD->setDependentTemplateSpecialization(Reader.getContext(),
766 TemplDecls, TemplArgs);
773 // Read in the parameters.
774 unsigned NumParams = Record[Idx++];
775 SmallVector<ParmVarDecl *, 16> Params;
776 Params.reserve(NumParams);
777 for (unsigned I = 0; I != NumParams; ++I)
778 Params.push_back(ReadDeclAs<ParmVarDecl>(Record, Idx));
779 FD->setParams(Reader.getContext(), Params);
782 void ASTDeclReader::VisitObjCMethodDecl(ObjCMethodDecl *MD) {
785 // Load the body on-demand. Most clients won't care, because method
786 // definitions rarely show up in headers.
787 Reader.PendingBodies[MD] = GetCurrentCursorOffset();
788 HasPendingBody = true;
789 MD->setSelfDecl(ReadDeclAs<ImplicitParamDecl>(Record, Idx));
790 MD->setCmdDecl(ReadDeclAs<ImplicitParamDecl>(Record, Idx));
792 MD->setInstanceMethod(Record[Idx++]);
793 MD->setVariadic(Record[Idx++]);
794 MD->setPropertyAccessor(Record[Idx++]);
795 MD->setDefined(Record[Idx++]);
796 MD->IsOverriding = Record[Idx++];
797 MD->HasSkippedBody = Record[Idx++];
799 MD->IsRedeclaration = Record[Idx++];
800 MD->HasRedeclaration = Record[Idx++];
801 if (MD->HasRedeclaration)
802 Reader.getContext().setObjCMethodRedeclaration(MD,
803 ReadDeclAs<ObjCMethodDecl>(Record, Idx));
805 MD->setDeclImplementation((ObjCMethodDecl::ImplementationControl)Record[Idx++]);
806 MD->setObjCDeclQualifier((Decl::ObjCDeclQualifier)Record[Idx++]);
807 MD->SetRelatedResultType(Record[Idx++]);
808 MD->setReturnType(Reader.readType(F, Record, Idx));
809 MD->setReturnTypeSourceInfo(GetTypeSourceInfo(Record, Idx));
810 MD->DeclEndLoc = ReadSourceLocation(Record, Idx);
811 unsigned NumParams = Record[Idx++];
812 SmallVector<ParmVarDecl *, 16> Params;
813 Params.reserve(NumParams);
814 for (unsigned I = 0; I != NumParams; ++I)
815 Params.push_back(ReadDeclAs<ParmVarDecl>(Record, Idx));
817 MD->SelLocsKind = Record[Idx++];
818 unsigned NumStoredSelLocs = Record[Idx++];
819 SmallVector<SourceLocation, 16> SelLocs;
820 SelLocs.reserve(NumStoredSelLocs);
821 for (unsigned i = 0; i != NumStoredSelLocs; ++i)
822 SelLocs.push_back(ReadSourceLocation(Record, Idx));
824 MD->setParamsAndSelLocs(Reader.getContext(), Params, SelLocs);
827 void ASTDeclReader::VisitObjCContainerDecl(ObjCContainerDecl *CD) {
829 CD->setAtStartLoc(ReadSourceLocation(Record, Idx));
830 CD->setAtEndRange(ReadSourceRange(Record, Idx));
833 void ASTDeclReader::VisitObjCInterfaceDecl(ObjCInterfaceDecl *ID) {
834 RedeclarableResult Redecl = VisitRedeclarable(ID);
835 VisitObjCContainerDecl(ID);
836 TypeIDForTypeDecl = Reader.getGlobalTypeID(F, Record[Idx++]);
837 mergeRedeclarable(ID, Redecl);
840 // Read the definition.
841 ID->allocateDefinitionData();
843 // Set the definition data of the canonical declaration, so other
844 // redeclarations will see it.
845 ID->getCanonicalDecl()->Data = ID->Data;
847 ObjCInterfaceDecl::DefinitionData &Data = ID->data();
849 // Read the superclass.
850 Data.SuperClass = ReadDeclAs<ObjCInterfaceDecl>(Record, Idx);
851 Data.SuperClassLoc = ReadSourceLocation(Record, Idx);
853 Data.EndLoc = ReadSourceLocation(Record, Idx);
854 Data.HasDesignatedInitializers = Record[Idx++];
856 // Read the directly referenced protocols and their SourceLocations.
857 unsigned NumProtocols = Record[Idx++];
858 SmallVector<ObjCProtocolDecl *, 16> Protocols;
859 Protocols.reserve(NumProtocols);
860 for (unsigned I = 0; I != NumProtocols; ++I)
861 Protocols.push_back(ReadDeclAs<ObjCProtocolDecl>(Record, Idx));
862 SmallVector<SourceLocation, 16> ProtoLocs;
863 ProtoLocs.reserve(NumProtocols);
864 for (unsigned I = 0; I != NumProtocols; ++I)
865 ProtoLocs.push_back(ReadSourceLocation(Record, Idx));
866 ID->setProtocolList(Protocols.data(), NumProtocols, ProtoLocs.data(),
867 Reader.getContext());
869 // Read the transitive closure of protocols referenced by this class.
870 NumProtocols = Record[Idx++];
872 Protocols.reserve(NumProtocols);
873 for (unsigned I = 0; I != NumProtocols; ++I)
874 Protocols.push_back(ReadDeclAs<ObjCProtocolDecl>(Record, Idx));
875 ID->data().AllReferencedProtocols.set(Protocols.data(), NumProtocols,
876 Reader.getContext());
878 // We will rebuild this list lazily.
879 ID->setIvarList(nullptr);
881 // Note that we have deserialized a definition.
882 Reader.PendingDefinitions.insert(ID);
884 // Note that we've loaded this Objective-C class.
885 Reader.ObjCClassesLoaded.push_back(ID);
887 ID->Data = ID->getCanonicalDecl()->Data;
891 void ASTDeclReader::VisitObjCIvarDecl(ObjCIvarDecl *IVD) {
893 IVD->setAccessControl((ObjCIvarDecl::AccessControl)Record[Idx++]);
894 // This field will be built lazily.
895 IVD->setNextIvar(nullptr);
896 bool synth = Record[Idx++];
897 IVD->setSynthesize(synth);
900 void ASTDeclReader::VisitObjCProtocolDecl(ObjCProtocolDecl *PD) {
901 RedeclarableResult Redecl = VisitRedeclarable(PD);
902 VisitObjCContainerDecl(PD);
903 mergeRedeclarable(PD, Redecl);
906 // Read the definition.
907 PD->allocateDefinitionData();
909 // Set the definition data of the canonical declaration, so other
910 // redeclarations will see it.
911 PD->getCanonicalDecl()->Data = PD->Data;
913 unsigned NumProtoRefs = Record[Idx++];
914 SmallVector<ObjCProtocolDecl *, 16> ProtoRefs;
915 ProtoRefs.reserve(NumProtoRefs);
916 for (unsigned I = 0; I != NumProtoRefs; ++I)
917 ProtoRefs.push_back(ReadDeclAs<ObjCProtocolDecl>(Record, Idx));
918 SmallVector<SourceLocation, 16> ProtoLocs;
919 ProtoLocs.reserve(NumProtoRefs);
920 for (unsigned I = 0; I != NumProtoRefs; ++I)
921 ProtoLocs.push_back(ReadSourceLocation(Record, Idx));
922 PD->setProtocolList(ProtoRefs.data(), NumProtoRefs, ProtoLocs.data(),
923 Reader.getContext());
925 // Note that we have deserialized a definition.
926 Reader.PendingDefinitions.insert(PD);
928 PD->Data = PD->getCanonicalDecl()->Data;
932 void ASTDeclReader::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *FD) {
936 void ASTDeclReader::VisitObjCCategoryDecl(ObjCCategoryDecl *CD) {
937 VisitObjCContainerDecl(CD);
938 CD->setCategoryNameLoc(ReadSourceLocation(Record, Idx));
939 CD->setIvarLBraceLoc(ReadSourceLocation(Record, Idx));
940 CD->setIvarRBraceLoc(ReadSourceLocation(Record, Idx));
942 // Note that this category has been deserialized. We do this before
943 // deserializing the interface declaration, so that it will consider this
945 Reader.CategoriesDeserialized.insert(CD);
947 CD->ClassInterface = ReadDeclAs<ObjCInterfaceDecl>(Record, Idx);
948 unsigned NumProtoRefs = Record[Idx++];
949 SmallVector<ObjCProtocolDecl *, 16> ProtoRefs;
950 ProtoRefs.reserve(NumProtoRefs);
951 for (unsigned I = 0; I != NumProtoRefs; ++I)
952 ProtoRefs.push_back(ReadDeclAs<ObjCProtocolDecl>(Record, Idx));
953 SmallVector<SourceLocation, 16> ProtoLocs;
954 ProtoLocs.reserve(NumProtoRefs);
955 for (unsigned I = 0; I != NumProtoRefs; ++I)
956 ProtoLocs.push_back(ReadSourceLocation(Record, Idx));
957 CD->setProtocolList(ProtoRefs.data(), NumProtoRefs, ProtoLocs.data(),
958 Reader.getContext());
961 void ASTDeclReader::VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *CAD) {
963 CAD->setClassInterface(ReadDeclAs<ObjCInterfaceDecl>(Record, Idx));
966 void ASTDeclReader::VisitObjCPropertyDecl(ObjCPropertyDecl *D) {
968 D->setAtLoc(ReadSourceLocation(Record, Idx));
969 D->setLParenLoc(ReadSourceLocation(Record, Idx));
970 D->setType(GetTypeSourceInfo(Record, Idx));
971 // FIXME: stable encoding
972 D->setPropertyAttributes(
973 (ObjCPropertyDecl::PropertyAttributeKind)Record[Idx++]);
974 D->setPropertyAttributesAsWritten(
975 (ObjCPropertyDecl::PropertyAttributeKind)Record[Idx++]);
976 // FIXME: stable encoding
977 D->setPropertyImplementation(
978 (ObjCPropertyDecl::PropertyControl)Record[Idx++]);
979 D->setGetterName(Reader.ReadDeclarationName(F,Record, Idx).getObjCSelector());
980 D->setSetterName(Reader.ReadDeclarationName(F,Record, Idx).getObjCSelector());
981 D->setGetterMethodDecl(ReadDeclAs<ObjCMethodDecl>(Record, Idx));
982 D->setSetterMethodDecl(ReadDeclAs<ObjCMethodDecl>(Record, Idx));
983 D->setPropertyIvarDecl(ReadDeclAs<ObjCIvarDecl>(Record, Idx));
986 void ASTDeclReader::VisitObjCImplDecl(ObjCImplDecl *D) {
987 VisitObjCContainerDecl(D);
988 D->setClassInterface(ReadDeclAs<ObjCInterfaceDecl>(Record, Idx));
991 void ASTDeclReader::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
992 VisitObjCImplDecl(D);
993 D->setIdentifier(Reader.GetIdentifierInfo(F, Record, Idx));
994 D->CategoryNameLoc = ReadSourceLocation(Record, Idx);
997 void ASTDeclReader::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
998 VisitObjCImplDecl(D);
999 D->setSuperClass(ReadDeclAs<ObjCInterfaceDecl>(Record, Idx));
1000 D->SuperLoc = ReadSourceLocation(Record, Idx);
1001 D->setIvarLBraceLoc(ReadSourceLocation(Record, Idx));
1002 D->setIvarRBraceLoc(ReadSourceLocation(Record, Idx));
1003 D->setHasNonZeroConstructors(Record[Idx++]);
1004 D->setHasDestructors(Record[Idx++]);
1005 D->NumIvarInitializers = Record[Idx++];
1006 if (D->NumIvarInitializers)
1007 D->IvarInitializers = Reader.ReadCXXCtorInitializersRef(F, Record, Idx);
1011 void ASTDeclReader::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) {
1013 D->setAtLoc(ReadSourceLocation(Record, Idx));
1014 D->setPropertyDecl(ReadDeclAs<ObjCPropertyDecl>(Record, Idx));
1015 D->PropertyIvarDecl = ReadDeclAs<ObjCIvarDecl>(Record, Idx);
1016 D->IvarLoc = ReadSourceLocation(Record, Idx);
1017 D->setGetterCXXConstructor(Reader.ReadExpr(F));
1018 D->setSetterCXXAssignment(Reader.ReadExpr(F));
1021 void ASTDeclReader::VisitFieldDecl(FieldDecl *FD) {
1022 VisitDeclaratorDecl(FD);
1023 FD->Mutable = Record[Idx++];
1024 if (int BitWidthOrInitializer = Record[Idx++]) {
1025 FD->InitStorage.setInt(
1026 static_cast<FieldDecl::InitStorageKind>(BitWidthOrInitializer - 1));
1027 if (FD->InitStorage.getInt() == FieldDecl::ISK_CapturedVLAType) {
1028 // Read captured variable length array.
1029 FD->InitStorage.setPointer(
1030 Reader.readType(F, Record, Idx).getAsOpaquePtr());
1032 FD->InitStorage.setPointer(Reader.ReadExpr(F));
1035 if (!FD->getDeclName()) {
1036 if (FieldDecl *Tmpl = ReadDeclAs<FieldDecl>(Record, Idx))
1037 Reader.getContext().setInstantiatedFromUnnamedFieldDecl(FD, Tmpl);
1042 void ASTDeclReader::VisitMSPropertyDecl(MSPropertyDecl *PD) {
1043 VisitDeclaratorDecl(PD);
1044 PD->GetterId = Reader.GetIdentifierInfo(F, Record, Idx);
1045 PD->SetterId = Reader.GetIdentifierInfo(F, Record, Idx);
1048 void ASTDeclReader::VisitIndirectFieldDecl(IndirectFieldDecl *FD) {
1051 FD->ChainingSize = Record[Idx++];
1052 assert(FD->ChainingSize >= 2 && "Anonymous chaining must be >= 2");
1053 FD->Chaining = new (Reader.getContext())NamedDecl*[FD->ChainingSize];
1055 for (unsigned I = 0; I != FD->ChainingSize; ++I)
1056 FD->Chaining[I] = ReadDeclAs<NamedDecl>(Record, Idx);
1059 ASTDeclReader::RedeclarableResult ASTDeclReader::VisitVarDeclImpl(VarDecl *VD) {
1060 RedeclarableResult Redecl = VisitRedeclarable(VD);
1061 VisitDeclaratorDecl(VD);
1063 VD->VarDeclBits.SClass = (StorageClass)Record[Idx++];
1064 VD->VarDeclBits.TSCSpec = Record[Idx++];
1065 VD->VarDeclBits.InitStyle = Record[Idx++];
1066 if (!isa<ParmVarDecl>(VD)) {
1067 VD->NonParmVarDeclBits.ExceptionVar = Record[Idx++];
1068 VD->NonParmVarDeclBits.NRVOVariable = Record[Idx++];
1069 VD->NonParmVarDeclBits.CXXForRangeDecl = Record[Idx++];
1070 VD->NonParmVarDeclBits.ARCPseudoStrong = Record[Idx++];
1071 VD->NonParmVarDeclBits.IsConstexpr = Record[Idx++];
1072 VD->NonParmVarDeclBits.IsInitCapture = Record[Idx++];
1073 VD->NonParmVarDeclBits.PreviousDeclInSameBlockScope = Record[Idx++];
1075 Linkage VarLinkage = Linkage(Record[Idx++]);
1076 VD->setCachedLinkage(VarLinkage);
1078 // Reconstruct the one piece of the IdentifierNamespace that we need.
1079 if (VD->getStorageClass() == SC_Extern && VarLinkage != NoLinkage &&
1080 VD->getLexicalDeclContext()->isFunctionOrMethod())
1081 VD->setLocalExternDecl();
1083 if (uint64_t Val = Record[Idx++]) {
1084 VD->setInit(Reader.ReadExpr(F));
1086 EvaluatedStmt *Eval = VD->ensureEvaluatedStmt();
1087 Eval->CheckedICE = true;
1088 Eval->IsICE = Val == 3;
1093 VarNotTemplate = 0, VarTemplate, StaticDataMemberSpecialization
1095 switch ((VarKind)Record[Idx++]) {
1096 case VarNotTemplate:
1097 // Only true variables (not parameters or implicit parameters) can be merged
1098 if (VD->getKind() != Decl::ParmVar && VD->getKind() != Decl::ImplicitParam &&
1099 !isa<VarTemplateSpecializationDecl>(VD))
1100 mergeRedeclarable(VD, Redecl);
1103 // Merged when we merge the template.
1104 VD->setDescribedVarTemplate(ReadDeclAs<VarTemplateDecl>(Record, Idx));
1106 case StaticDataMemberSpecialization: { // HasMemberSpecializationInfo.
1107 VarDecl *Tmpl = ReadDeclAs<VarDecl>(Record, Idx);
1108 TemplateSpecializationKind TSK = (TemplateSpecializationKind)Record[Idx++];
1109 SourceLocation POI = ReadSourceLocation(Record, Idx);
1110 Reader.getContext().setInstantiatedFromStaticDataMember(VD, Tmpl, TSK,POI);
1111 mergeRedeclarable(VD, Redecl);
1119 void ASTDeclReader::VisitImplicitParamDecl(ImplicitParamDecl *PD) {
1123 void ASTDeclReader::VisitParmVarDecl(ParmVarDecl *PD) {
1125 unsigned isObjCMethodParam = Record[Idx++];
1126 unsigned scopeDepth = Record[Idx++];
1127 unsigned scopeIndex = Record[Idx++];
1128 unsigned declQualifier = Record[Idx++];
1129 if (isObjCMethodParam) {
1130 assert(scopeDepth == 0);
1131 PD->setObjCMethodScopeInfo(scopeIndex);
1132 PD->ParmVarDeclBits.ScopeDepthOrObjCQuals = declQualifier;
1134 PD->setScopeInfo(scopeDepth, scopeIndex);
1136 PD->ParmVarDeclBits.IsKNRPromoted = Record[Idx++];
1137 PD->ParmVarDeclBits.HasInheritedDefaultArg = Record[Idx++];
1138 if (Record[Idx++]) // hasUninstantiatedDefaultArg.
1139 PD->setUninstantiatedDefaultArg(Reader.ReadExpr(F));
1141 // FIXME: If this is a redeclaration of a function from another module, handle
1142 // inheritance of default arguments.
1145 void ASTDeclReader::VisitFileScopeAsmDecl(FileScopeAsmDecl *AD) {
1147 AD->setAsmString(cast<StringLiteral>(Reader.ReadExpr(F)));
1148 AD->setRParenLoc(ReadSourceLocation(Record, Idx));
1151 void ASTDeclReader::VisitBlockDecl(BlockDecl *BD) {
1153 BD->setBody(cast_or_null<CompoundStmt>(Reader.ReadStmt(F)));
1154 BD->setSignatureAsWritten(GetTypeSourceInfo(Record, Idx));
1155 unsigned NumParams = Record[Idx++];
1156 SmallVector<ParmVarDecl *, 16> Params;
1157 Params.reserve(NumParams);
1158 for (unsigned I = 0; I != NumParams; ++I)
1159 Params.push_back(ReadDeclAs<ParmVarDecl>(Record, Idx));
1160 BD->setParams(Params);
1162 BD->setIsVariadic(Record[Idx++]);
1163 BD->setBlockMissingReturnType(Record[Idx++]);
1164 BD->setIsConversionFromLambda(Record[Idx++]);
1166 bool capturesCXXThis = Record[Idx++];
1167 unsigned numCaptures = Record[Idx++];
1168 SmallVector<BlockDecl::Capture, 16> captures;
1169 captures.reserve(numCaptures);
1170 for (unsigned i = 0; i != numCaptures; ++i) {
1171 VarDecl *decl = ReadDeclAs<VarDecl>(Record, Idx);
1172 unsigned flags = Record[Idx++];
1173 bool byRef = (flags & 1);
1174 bool nested = (flags & 2);
1175 Expr *copyExpr = ((flags & 4) ? Reader.ReadExpr(F) : nullptr);
1177 captures.push_back(BlockDecl::Capture(decl, byRef, nested, copyExpr));
1179 BD->setCaptures(Reader.getContext(), captures.begin(),
1180 captures.end(), capturesCXXThis);
1183 void ASTDeclReader::VisitCapturedDecl(CapturedDecl *CD) {
1185 unsigned ContextParamPos = Record[Idx++];
1186 CD->setNothrow(Record[Idx++] != 0);
1187 // Body is set by VisitCapturedStmt.
1188 for (unsigned I = 0; I < CD->NumParams; ++I) {
1189 if (I != ContextParamPos)
1190 CD->setParam(I, ReadDeclAs<ImplicitParamDecl>(Record, Idx));
1192 CD->setContextParam(I, ReadDeclAs<ImplicitParamDecl>(Record, Idx));
1196 void ASTDeclReader::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1198 D->setLanguage((LinkageSpecDecl::LanguageIDs)Record[Idx++]);
1199 D->setExternLoc(ReadSourceLocation(Record, Idx));
1200 D->setRBraceLoc(ReadSourceLocation(Record, Idx));
1203 void ASTDeclReader::VisitLabelDecl(LabelDecl *D) {
1205 D->setLocStart(ReadSourceLocation(Record, Idx));
1209 void ASTDeclReader::VisitNamespaceDecl(NamespaceDecl *D) {
1210 RedeclarableResult Redecl = VisitRedeclarable(D);
1212 D->setInline(Record[Idx++]);
1213 D->LocStart = ReadSourceLocation(Record, Idx);
1214 D->RBraceLoc = ReadSourceLocation(Record, Idx);
1216 // Defer loading the anonymous namespace until we've finished merging
1217 // this namespace; loading it might load a later declaration of the
1218 // same namespace, and we have an invariant that older declarations
1219 // get merged before newer ones try to merge.
1220 GlobalDeclID AnonNamespace = 0;
1221 if (Redecl.getFirstID() == ThisDeclID) {
1222 AnonNamespace = ReadDeclID(Record, Idx);
1224 // Link this namespace back to the first declaration, which has already
1225 // been deserialized.
1226 D->AnonOrFirstNamespaceAndInline.setPointer(D->getFirstDecl());
1229 mergeRedeclarable(D, Redecl);
1231 if (AnonNamespace) {
1232 // Each module has its own anonymous namespace, which is disjoint from
1233 // any other module's anonymous namespaces, so don't attach the anonymous
1234 // namespace at all.
1235 NamespaceDecl *Anon = cast<NamespaceDecl>(Reader.GetDecl(AnonNamespace));
1236 if (F.Kind != MK_ImplicitModule && F.Kind != MK_ExplicitModule)
1237 D->setAnonymousNamespace(Anon);
1241 void ASTDeclReader::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1242 RedeclarableResult Redecl = VisitRedeclarable(D);
1244 D->NamespaceLoc = ReadSourceLocation(Record, Idx);
1245 D->IdentLoc = ReadSourceLocation(Record, Idx);
1246 D->QualifierLoc = Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
1247 D->Namespace = ReadDeclAs<NamedDecl>(Record, Idx);
1248 mergeRedeclarable(D, Redecl);
1251 void ASTDeclReader::VisitUsingDecl(UsingDecl *D) {
1253 D->setUsingLoc(ReadSourceLocation(Record, Idx));
1254 D->QualifierLoc = Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
1255 ReadDeclarationNameLoc(D->DNLoc, D->getDeclName(), Record, Idx);
1256 D->FirstUsingShadow.setPointer(ReadDeclAs<UsingShadowDecl>(Record, Idx));
1257 D->setTypename(Record[Idx++]);
1258 if (NamedDecl *Pattern = ReadDeclAs<NamedDecl>(Record, Idx))
1259 Reader.getContext().setInstantiatedFromUsingDecl(D, Pattern);
1263 void ASTDeclReader::VisitUsingShadowDecl(UsingShadowDecl *D) {
1264 RedeclarableResult Redecl = VisitRedeclarable(D);
1266 D->setTargetDecl(ReadDeclAs<NamedDecl>(Record, Idx));
1267 D->UsingOrNextShadow = ReadDeclAs<NamedDecl>(Record, Idx);
1268 UsingShadowDecl *Pattern = ReadDeclAs<UsingShadowDecl>(Record, Idx);
1270 Reader.getContext().setInstantiatedFromUsingShadowDecl(D, Pattern);
1271 mergeRedeclarable(D, Redecl);
1274 void ASTDeclReader::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1276 D->UsingLoc = ReadSourceLocation(Record, Idx);
1277 D->NamespaceLoc = ReadSourceLocation(Record, Idx);
1278 D->QualifierLoc = Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
1279 D->NominatedNamespace = ReadDeclAs<NamedDecl>(Record, Idx);
1280 D->CommonAncestor = ReadDeclAs<DeclContext>(Record, Idx);
1283 void ASTDeclReader::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1285 D->setUsingLoc(ReadSourceLocation(Record, Idx));
1286 D->QualifierLoc = Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
1287 ReadDeclarationNameLoc(D->DNLoc, D->getDeclName(), Record, Idx);
1291 void ASTDeclReader::VisitUnresolvedUsingTypenameDecl(
1292 UnresolvedUsingTypenameDecl *D) {
1294 D->TypenameLocation = ReadSourceLocation(Record, Idx);
1295 D->QualifierLoc = Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
1299 void ASTDeclReader::ReadCXXDefinitionData(
1300 struct CXXRecordDecl::DefinitionData &Data,
1301 const RecordData &Record, unsigned &Idx) {
1302 // Note: the caller has deserialized the IsLambda bit already.
1303 Data.UserDeclaredConstructor = Record[Idx++];
1304 Data.UserDeclaredSpecialMembers = Record[Idx++];
1305 Data.Aggregate = Record[Idx++];
1306 Data.PlainOldData = Record[Idx++];
1307 Data.Empty = Record[Idx++];
1308 Data.Polymorphic = Record[Idx++];
1309 Data.Abstract = Record[Idx++];
1310 Data.IsStandardLayout = Record[Idx++];
1311 Data.HasNoNonEmptyBases = Record[Idx++];
1312 Data.HasPrivateFields = Record[Idx++];
1313 Data.HasProtectedFields = Record[Idx++];
1314 Data.HasPublicFields = Record[Idx++];
1315 Data.HasMutableFields = Record[Idx++];
1316 Data.HasVariantMembers = Record[Idx++];
1317 Data.HasOnlyCMembers = Record[Idx++];
1318 Data.HasInClassInitializer = Record[Idx++];
1319 Data.HasUninitializedReferenceMember = Record[Idx++];
1320 Data.NeedOverloadResolutionForMoveConstructor = Record[Idx++];
1321 Data.NeedOverloadResolutionForMoveAssignment = Record[Idx++];
1322 Data.NeedOverloadResolutionForDestructor = Record[Idx++];
1323 Data.DefaultedMoveConstructorIsDeleted = Record[Idx++];
1324 Data.DefaultedMoveAssignmentIsDeleted = Record[Idx++];
1325 Data.DefaultedDestructorIsDeleted = Record[Idx++];
1326 Data.HasTrivialSpecialMembers = Record[Idx++];
1327 Data.DeclaredNonTrivialSpecialMembers = Record[Idx++];
1328 Data.HasIrrelevantDestructor = Record[Idx++];
1329 Data.HasConstexprNonCopyMoveConstructor = Record[Idx++];
1330 Data.DefaultedDefaultConstructorIsConstexpr = Record[Idx++];
1331 Data.HasConstexprDefaultConstructor = Record[Idx++];
1332 Data.HasNonLiteralTypeFieldsOrBases = Record[Idx++];
1333 Data.ComputedVisibleConversions = Record[Idx++];
1334 Data.UserProvidedDefaultConstructor = Record[Idx++];
1335 Data.DeclaredSpecialMembers = Record[Idx++];
1336 Data.ImplicitCopyConstructorHasConstParam = Record[Idx++];
1337 Data.ImplicitCopyAssignmentHasConstParam = Record[Idx++];
1338 Data.HasDeclaredCopyConstructorWithConstParam = Record[Idx++];
1339 Data.HasDeclaredCopyAssignmentWithConstParam = Record[Idx++];
1341 Data.NumBases = Record[Idx++];
1343 Data.Bases = Reader.readCXXBaseSpecifiers(F, Record, Idx);
1344 Data.NumVBases = Record[Idx++];
1346 Data.VBases = Reader.readCXXBaseSpecifiers(F, Record, Idx);
1348 Reader.ReadUnresolvedSet(F, Data.Conversions, Record, Idx);
1349 Reader.ReadUnresolvedSet(F, Data.VisibleConversions, Record, Idx);
1350 assert(Data.Definition && "Data.Definition should be already set!");
1351 Data.FirstFriend = ReadDeclID(Record, Idx);
1353 if (Data.IsLambda) {
1354 typedef LambdaCapture Capture;
1355 CXXRecordDecl::LambdaDefinitionData &Lambda
1356 = static_cast<CXXRecordDecl::LambdaDefinitionData &>(Data);
1357 Lambda.Dependent = Record[Idx++];
1358 Lambda.IsGenericLambda = Record[Idx++];
1359 Lambda.CaptureDefault = Record[Idx++];
1360 Lambda.NumCaptures = Record[Idx++];
1361 Lambda.NumExplicitCaptures = Record[Idx++];
1362 Lambda.ManglingNumber = Record[Idx++];
1363 Lambda.ContextDecl = ReadDecl(Record, Idx);
1365 = (Capture*)Reader.Context.Allocate(sizeof(Capture)*Lambda.NumCaptures);
1366 Capture *ToCapture = Lambda.Captures;
1367 Lambda.MethodTyInfo = GetTypeSourceInfo(Record, Idx);
1368 for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) {
1369 SourceLocation Loc = ReadSourceLocation(Record, Idx);
1370 bool IsImplicit = Record[Idx++];
1371 LambdaCaptureKind Kind = static_cast<LambdaCaptureKind>(Record[Idx++]);
1375 *ToCapture++ = Capture(Loc, IsImplicit, Kind, nullptr,SourceLocation());
1379 VarDecl *Var = ReadDeclAs<VarDecl>(Record, Idx);
1380 SourceLocation EllipsisLoc = ReadSourceLocation(Record, Idx);
1381 *ToCapture++ = Capture(Loc, IsImplicit, Kind, Var, EllipsisLoc);
1388 void ASTDeclReader::MergeDefinitionData(
1389 CXXRecordDecl *D, struct CXXRecordDecl::DefinitionData &&MergeDD) {
1390 assert(D->DefinitionData.getNotUpdated() &&
1391 "merging class definition into non-definition");
1392 auto &DD = *D->DefinitionData.getNotUpdated();
1394 // If the new definition has new special members, let the name lookup
1395 // code know that it needs to look in the new definition too.
1397 // FIXME: We only need to do this if the merged definition declares members
1398 // that this definition did not declare, or if it defines members that this
1399 // definition did not define.
1400 if (DD.Definition != MergeDD.Definition) {
1401 Reader.MergedLookups[DD.Definition].push_back(MergeDD.Definition);
1402 DD.Definition->setHasExternalVisibleStorage();
1404 if (DD.Definition->isHidden()) {
1405 // If MergeDD is visible or becomes visible, make the definition visible.
1406 if (!MergeDD.Definition->isHidden())
1407 DD.Definition->Hidden = false;
1408 else if (Reader.getContext().getLangOpts().ModulesLocalVisibility) {
1409 Reader.getContext().mergeDefinitionIntoModule(
1410 DD.Definition, MergeDD.Definition->getImportedOwningModule(),
1411 /*NotifyListeners*/ false);
1412 Reader.PendingMergedDefinitionsToDeduplicate.insert(DD.Definition);
1414 auto SubmoduleID = MergeDD.Definition->getOwningModuleID();
1415 assert(SubmoduleID && "hidden definition in no module");
1416 Reader.HiddenNamesMap[Reader.getSubmodule(SubmoduleID)].push_back(
1422 auto PFDI = Reader.PendingFakeDefinitionData.find(&DD);
1423 if (PFDI != Reader.PendingFakeDefinitionData.end() &&
1424 PFDI->second == ASTReader::PendingFakeDefinitionKind::Fake) {
1425 // We faked up this definition data because we found a class for which we'd
1426 // not yet loaded the definition. Replace it with the real thing now.
1427 assert(!DD.IsLambda && !MergeDD.IsLambda && "faked up lambda definition?");
1428 PFDI->second = ASTReader::PendingFakeDefinitionKind::FakeLoaded;
1430 // Don't change which declaration is the definition; that is required
1431 // to be invariant once we select it.
1432 auto *Def = DD.Definition;
1433 DD = std::move(MergeDD);
1434 DD.Definition = Def;
1438 // FIXME: Move this out into a .def file?
1439 bool DetectedOdrViolation = false;
1440 #define OR_FIELD(Field) DD.Field |= MergeDD.Field;
1441 #define MATCH_FIELD(Field) \
1442 DetectedOdrViolation |= DD.Field != MergeDD.Field; \
1444 MATCH_FIELD(UserDeclaredConstructor)
1445 MATCH_FIELD(UserDeclaredSpecialMembers)
1446 MATCH_FIELD(Aggregate)
1447 MATCH_FIELD(PlainOldData)
1449 MATCH_FIELD(Polymorphic)
1450 MATCH_FIELD(Abstract)
1451 MATCH_FIELD(IsStandardLayout)
1452 MATCH_FIELD(HasNoNonEmptyBases)
1453 MATCH_FIELD(HasPrivateFields)
1454 MATCH_FIELD(HasProtectedFields)
1455 MATCH_FIELD(HasPublicFields)
1456 MATCH_FIELD(HasMutableFields)
1457 MATCH_FIELD(HasVariantMembers)
1458 MATCH_FIELD(HasOnlyCMembers)
1459 MATCH_FIELD(HasInClassInitializer)
1460 MATCH_FIELD(HasUninitializedReferenceMember)
1461 MATCH_FIELD(NeedOverloadResolutionForMoveConstructor)
1462 MATCH_FIELD(NeedOverloadResolutionForMoveAssignment)
1463 MATCH_FIELD(NeedOverloadResolutionForDestructor)
1464 MATCH_FIELD(DefaultedMoveConstructorIsDeleted)
1465 MATCH_FIELD(DefaultedMoveAssignmentIsDeleted)
1466 MATCH_FIELD(DefaultedDestructorIsDeleted)
1467 OR_FIELD(HasTrivialSpecialMembers)
1468 OR_FIELD(DeclaredNonTrivialSpecialMembers)
1469 MATCH_FIELD(HasIrrelevantDestructor)
1470 OR_FIELD(HasConstexprNonCopyMoveConstructor)
1471 MATCH_FIELD(DefaultedDefaultConstructorIsConstexpr)
1472 OR_FIELD(HasConstexprDefaultConstructor)
1473 MATCH_FIELD(HasNonLiteralTypeFieldsOrBases)
1474 // ComputedVisibleConversions is handled below.
1475 MATCH_FIELD(UserProvidedDefaultConstructor)
1476 OR_FIELD(DeclaredSpecialMembers)
1477 MATCH_FIELD(ImplicitCopyConstructorHasConstParam)
1478 MATCH_FIELD(ImplicitCopyAssignmentHasConstParam)
1479 OR_FIELD(HasDeclaredCopyConstructorWithConstParam)
1480 OR_FIELD(HasDeclaredCopyAssignmentWithConstParam)
1481 MATCH_FIELD(IsLambda)
1485 if (DD.NumBases != MergeDD.NumBases || DD.NumVBases != MergeDD.NumVBases)
1486 DetectedOdrViolation = true;
1487 // FIXME: Issue a diagnostic if the base classes don't match when we come
1488 // to lazily load them.
1490 // FIXME: Issue a diagnostic if the list of conversion functions doesn't
1491 // match when we come to lazily load them.
1492 if (MergeDD.ComputedVisibleConversions && !DD.ComputedVisibleConversions) {
1493 DD.VisibleConversions = std::move(MergeDD.VisibleConversions);
1494 DD.ComputedVisibleConversions = true;
1497 // FIXME: Issue a diagnostic if FirstFriend doesn't match when we come to
1501 // FIXME: ODR-checking for merging lambdas (this happens, for instance,
1502 // when they occur within the body of a function template specialization).
1505 if (DetectedOdrViolation)
1506 Reader.PendingOdrMergeFailures[DD.Definition].push_back(MergeDD.Definition);
1509 void ASTDeclReader::ReadCXXRecordDefinition(CXXRecordDecl *D, bool Update) {
1510 struct CXXRecordDecl::DefinitionData *DD;
1511 ASTContext &C = Reader.getContext();
1513 // Determine whether this is a lambda closure type, so that we can
1514 // allocate the appropriate DefinitionData structure.
1515 bool IsLambda = Record[Idx++];
1517 DD = new (C) CXXRecordDecl::LambdaDefinitionData(D, nullptr, false, false,
1520 DD = new (C) struct CXXRecordDecl::DefinitionData(D);
1522 ReadCXXDefinitionData(*DD, Record, Idx);
1524 // We might already have a definition for this record. This can happen either
1525 // because we're reading an update record, or because we've already done some
1526 // merging. Either way, just merge into it.
1527 CXXRecordDecl *Canon = D->getCanonicalDecl();
1528 if (auto *CanonDD = Canon->DefinitionData.getNotUpdated()) {
1529 if (CanonDD->Definition != DD->Definition)
1530 Reader.MergedDeclContexts.insert(
1531 std::make_pair(DD->Definition, CanonDD->Definition));
1532 MergeDefinitionData(Canon, std::move(*DD));
1533 D->DefinitionData = Canon->DefinitionData;
1537 // Propagate the DefinitionData pointer to the canonical declaration, so
1538 // that all other deserialized declarations will see it.
1540 D->DefinitionData = DD;
1541 D->IsCompleteDefinition = true;
1543 // If this is an update record, we can have redeclarations already. Make a
1544 // note that we need to propagate the DefinitionData pointer onto them.
1546 Reader.PendingDefinitions.insert(D);
1547 } else if (auto *CanonDD = Canon->DefinitionData.getNotUpdated()) {
1548 // We have already deserialized a definition of this record. This
1549 // definition is no longer really a definition. Note that the pre-existing
1550 // definition is the *real* definition.
1551 Reader.MergedDeclContexts.insert(
1552 std::make_pair(D, CanonDD->Definition));
1553 D->DefinitionData = Canon->DefinitionData;
1554 D->IsCompleteDefinition = false;
1555 MergeDefinitionData(D, std::move(*DD));
1557 Canon->DefinitionData = DD;
1558 D->DefinitionData = Canon->DefinitionData;
1559 D->IsCompleteDefinition = true;
1561 // Note that we have deserialized a definition. Any declarations
1562 // deserialized before this one will be be given the DefinitionData
1563 // pointer at the end.
1564 Reader.PendingDefinitions.insert(D);
1568 ASTDeclReader::RedeclarableResult
1569 ASTDeclReader::VisitCXXRecordDeclImpl(CXXRecordDecl *D) {
1570 RedeclarableResult Redecl = VisitRecordDeclImpl(D);
1572 ASTContext &C = Reader.getContext();
1575 CXXRecNotTemplate = 0, CXXRecTemplate, CXXRecMemberSpecialization
1577 switch ((CXXRecKind)Record[Idx++]) {
1578 case CXXRecNotTemplate:
1579 // Merged when we merge the folding set entry in the primary template.
1580 if (!isa<ClassTemplateSpecializationDecl>(D))
1581 mergeRedeclarable(D, Redecl);
1583 case CXXRecTemplate: {
1584 // Merged when we merge the template.
1585 ClassTemplateDecl *Template = ReadDeclAs<ClassTemplateDecl>(Record, Idx);
1586 D->TemplateOrInstantiation = Template;
1587 if (!Template->getTemplatedDecl()) {
1588 // We've not actually loaded the ClassTemplateDecl yet, because we're
1589 // currently being loaded as its pattern. Rely on it to set up our
1590 // TypeForDecl (see VisitClassTemplateDecl).
1592 // Beware: we do not yet know our canonical declaration, and may still
1593 // get merged once the surrounding class template has got off the ground.
1594 TypeIDForTypeDecl = 0;
1598 case CXXRecMemberSpecialization: {
1599 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(Record, Idx);
1600 TemplateSpecializationKind TSK = (TemplateSpecializationKind)Record[Idx++];
1601 SourceLocation POI = ReadSourceLocation(Record, Idx);
1602 MemberSpecializationInfo *MSI = new (C) MemberSpecializationInfo(RD, TSK);
1603 MSI->setPointOfInstantiation(POI);
1604 D->TemplateOrInstantiation = MSI;
1605 mergeRedeclarable(D, Redecl);
1610 bool WasDefinition = Record[Idx++];
1612 ReadCXXRecordDefinition(D, /*Update*/false);
1614 // Propagate DefinitionData pointer from the canonical declaration.
1615 D->DefinitionData = D->getCanonicalDecl()->DefinitionData;
1617 // Lazily load the key function to avoid deserializing every method so we can
1619 if (WasDefinition) {
1620 DeclID KeyFn = ReadDeclID(Record, Idx);
1621 if (KeyFn && D->IsCompleteDefinition)
1622 // FIXME: This is wrong for the ARM ABI, where some other module may have
1623 // made this function no longer be a key function. We need an update
1624 // record or similar for that case.
1625 C.KeyFunctions[D] = KeyFn;
1631 void ASTDeclReader::VisitCXXMethodDecl(CXXMethodDecl *D) {
1632 VisitFunctionDecl(D);
1634 unsigned NumOverridenMethods = Record[Idx++];
1635 if (D->isCanonicalDecl()) {
1636 while (NumOverridenMethods--) {
1637 // Avoid invariant checking of CXXMethodDecl::addOverriddenMethod,
1638 // MD may be initializing.
1639 if (CXXMethodDecl *MD = ReadDeclAs<CXXMethodDecl>(Record, Idx))
1640 Reader.getContext().addOverriddenMethod(D, MD->getCanonicalDecl());
1643 // We don't care about which declarations this used to override; we get
1644 // the relevant information from the canonical declaration.
1645 Idx += NumOverridenMethods;
1649 void ASTDeclReader::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
1650 VisitCXXMethodDecl(D);
1652 if (auto *CD = ReadDeclAs<CXXConstructorDecl>(Record, Idx))
1653 if (D->isCanonicalDecl())
1654 D->setInheritedConstructor(CD->getCanonicalDecl());
1655 D->IsExplicitSpecified = Record[Idx++];
1658 void ASTDeclReader::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
1659 VisitCXXMethodDecl(D);
1661 if (auto *OperatorDelete = ReadDeclAs<FunctionDecl>(Record, Idx)) {
1662 auto *Canon = cast<CXXDestructorDecl>(D->getCanonicalDecl());
1663 // FIXME: Check consistency if we have an old and new operator delete.
1664 if (!Canon->OperatorDelete)
1665 Canon->OperatorDelete = OperatorDelete;
1669 void ASTDeclReader::VisitCXXConversionDecl(CXXConversionDecl *D) {
1670 VisitCXXMethodDecl(D);
1671 D->IsExplicitSpecified = Record[Idx++];
1674 void ASTDeclReader::VisitImportDecl(ImportDecl *D) {
1676 D->ImportedAndComplete.setPointer(readModule(Record, Idx));
1677 D->ImportedAndComplete.setInt(Record[Idx++]);
1678 SourceLocation *StoredLocs = reinterpret_cast<SourceLocation *>(D + 1);
1679 for (unsigned I = 0, N = Record.back(); I != N; ++I)
1680 StoredLocs[I] = ReadSourceLocation(Record, Idx);
1681 ++Idx; // The number of stored source locations.
1684 void ASTDeclReader::VisitAccessSpecDecl(AccessSpecDecl *D) {
1686 D->setColonLoc(ReadSourceLocation(Record, Idx));
1689 void ASTDeclReader::VisitFriendDecl(FriendDecl *D) {
1691 if (Record[Idx++]) // hasFriendDecl
1692 D->Friend = ReadDeclAs<NamedDecl>(Record, Idx);
1694 D->Friend = GetTypeSourceInfo(Record, Idx);
1695 for (unsigned i = 0; i != D->NumTPLists; ++i)
1696 D->getTPLists()[i] = Reader.ReadTemplateParameterList(F, Record, Idx);
1697 D->NextFriend = ReadDeclID(Record, Idx);
1698 D->UnsupportedFriend = (Record[Idx++] != 0);
1699 D->FriendLoc = ReadSourceLocation(Record, Idx);
1702 void ASTDeclReader::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
1704 unsigned NumParams = Record[Idx++];
1705 D->NumParams = NumParams;
1706 D->Params = new TemplateParameterList*[NumParams];
1707 for (unsigned i = 0; i != NumParams; ++i)
1708 D->Params[i] = Reader.ReadTemplateParameterList(F, Record, Idx);
1709 if (Record[Idx++]) // HasFriendDecl
1710 D->Friend = ReadDeclAs<NamedDecl>(Record, Idx);
1712 D->Friend = GetTypeSourceInfo(Record, Idx);
1713 D->FriendLoc = ReadSourceLocation(Record, Idx);
1716 DeclID ASTDeclReader::VisitTemplateDecl(TemplateDecl *D) {
1719 DeclID PatternID = ReadDeclID(Record, Idx);
1720 NamedDecl *TemplatedDecl = cast_or_null<NamedDecl>(Reader.GetDecl(PatternID));
1721 TemplateParameterList* TemplateParams
1722 = Reader.ReadTemplateParameterList(F, Record, Idx);
1723 D->init(TemplatedDecl, TemplateParams);
1725 // FIXME: If this is a redeclaration of a template from another module, handle
1726 // inheritance of default template arguments.
1731 ASTDeclReader::RedeclarableResult
1732 ASTDeclReader::VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D) {
1733 RedeclarableResult Redecl = VisitRedeclarable(D);
1735 // Make sure we've allocated the Common pointer first. We do this before
1736 // VisitTemplateDecl so that getCommonPtr() can be used during initialization.
1737 RedeclarableTemplateDecl *CanonD = D->getCanonicalDecl();
1738 if (!CanonD->Common) {
1739 CanonD->Common = CanonD->newCommon(Reader.getContext());
1740 Reader.PendingDefinitions.insert(CanonD);
1742 D->Common = CanonD->Common;
1744 // If this is the first declaration of the template, fill in the information
1745 // for the 'common' pointer.
1746 if (ThisDeclID == Redecl.getFirstID()) {
1747 if (RedeclarableTemplateDecl *RTD
1748 = ReadDeclAs<RedeclarableTemplateDecl>(Record, Idx)) {
1749 assert(RTD->getKind() == D->getKind() &&
1750 "InstantiatedFromMemberTemplate kind mismatch");
1751 D->setInstantiatedFromMemberTemplate(RTD);
1753 D->setMemberSpecialization();
1757 DeclID PatternID = VisitTemplateDecl(D);
1758 D->IdentifierNamespace = Record[Idx++];
1760 mergeRedeclarable(D, Redecl, PatternID);
1762 // If we merged the template with a prior declaration chain, merge the common
1764 // FIXME: Actually merge here, don't just overwrite.
1765 D->Common = D->getCanonicalDecl()->Common;
1770 static DeclID *newDeclIDList(ASTContext &Context, DeclID *Old,
1771 SmallVectorImpl<DeclID> &IDs) {
1772 assert(!IDs.empty() && "no IDs to add to list");
1774 IDs.insert(IDs.end(), Old + 1, Old + 1 + Old[0]);
1775 std::sort(IDs.begin(), IDs.end());
1776 IDs.erase(std::unique(IDs.begin(), IDs.end()), IDs.end());
1779 auto *Result = new (Context) DeclID[1 + IDs.size()];
1780 *Result = IDs.size();
1781 std::copy(IDs.begin(), IDs.end(), Result + 1);
1785 void ASTDeclReader::VisitClassTemplateDecl(ClassTemplateDecl *D) {
1786 RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
1788 if (ThisDeclID == Redecl.getFirstID()) {
1789 // This ClassTemplateDecl owns a CommonPtr; read it to keep track of all of
1790 // the specializations.
1791 SmallVector<serialization::DeclID, 32> SpecIDs;
1792 ReadDeclIDList(SpecIDs);
1794 if (!SpecIDs.empty()) {
1795 auto *CommonPtr = D->getCommonPtr();
1796 CommonPtr->LazySpecializations = newDeclIDList(
1797 Reader.getContext(), CommonPtr->LazySpecializations, SpecIDs);
1801 if (D->getTemplatedDecl()->TemplateOrInstantiation) {
1802 // We were loaded before our templated declaration was. We've not set up
1803 // its corresponding type yet (see VisitCXXRecordDeclImpl), so reconstruct
1805 Reader.Context.getInjectedClassNameType(
1806 D->getTemplatedDecl(), D->getInjectedClassNameSpecialization());
1810 /// TODO: Unify with ClassTemplateDecl version?
1811 /// May require unifying ClassTemplateDecl and
1812 /// VarTemplateDecl beyond TemplateDecl...
1813 void ASTDeclReader::VisitVarTemplateDecl(VarTemplateDecl *D) {
1814 RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
1816 if (ThisDeclID == Redecl.getFirstID()) {
1817 // This VarTemplateDecl owns a CommonPtr; read it to keep track of all of
1818 // the specializations.
1819 SmallVector<serialization::DeclID, 32> SpecIDs;
1820 ReadDeclIDList(SpecIDs);
1822 if (!SpecIDs.empty()) {
1823 auto *CommonPtr = D->getCommonPtr();
1824 CommonPtr->LazySpecializations = newDeclIDList(
1825 Reader.getContext(), CommonPtr->LazySpecializations, SpecIDs);
1830 ASTDeclReader::RedeclarableResult
1831 ASTDeclReader::VisitClassTemplateSpecializationDeclImpl(
1832 ClassTemplateSpecializationDecl *D) {
1833 RedeclarableResult Redecl = VisitCXXRecordDeclImpl(D);
1835 ASTContext &C = Reader.getContext();
1836 if (Decl *InstD = ReadDecl(Record, Idx)) {
1837 if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(InstD)) {
1838 D->SpecializedTemplate = CTD;
1840 SmallVector<TemplateArgument, 8> TemplArgs;
1841 Reader.ReadTemplateArgumentList(TemplArgs, F, Record, Idx);
1842 TemplateArgumentList *ArgList
1843 = TemplateArgumentList::CreateCopy(C, TemplArgs.data(),
1845 ClassTemplateSpecializationDecl::SpecializedPartialSpecialization *PS
1846 = new (C) ClassTemplateSpecializationDecl::
1847 SpecializedPartialSpecialization();
1848 PS->PartialSpecialization
1849 = cast<ClassTemplatePartialSpecializationDecl>(InstD);
1850 PS->TemplateArgs = ArgList;
1851 D->SpecializedTemplate = PS;
1855 SmallVector<TemplateArgument, 8> TemplArgs;
1856 Reader.ReadTemplateArgumentList(TemplArgs, F, Record, Idx);
1857 D->TemplateArgs = TemplateArgumentList::CreateCopy(C, TemplArgs.data(),
1859 D->PointOfInstantiation = ReadSourceLocation(Record, Idx);
1860 D->SpecializationKind = (TemplateSpecializationKind)Record[Idx++];
1862 bool writtenAsCanonicalDecl = Record[Idx++];
1863 if (writtenAsCanonicalDecl) {
1864 ClassTemplateDecl *CanonPattern = ReadDeclAs<ClassTemplateDecl>(Record,Idx);
1865 if (D->isCanonicalDecl()) { // It's kept in the folding set.
1866 // Set this as, or find, the canonical declaration for this specialization
1867 ClassTemplateSpecializationDecl *CanonSpec;
1868 if (ClassTemplatePartialSpecializationDecl *Partial =
1869 dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) {
1870 CanonSpec = CanonPattern->getCommonPtr()->PartialSpecializations
1871 .GetOrInsertNode(Partial);
1874 CanonPattern->getCommonPtr()->Specializations.GetOrInsertNode(D);
1876 // If there was already a canonical specialization, merge into it.
1877 if (CanonSpec != D) {
1878 mergeRedeclarable<TagDecl>(D, CanonSpec, Redecl);
1880 // This declaration might be a definition. Merge with any existing
1882 if (auto *DDD = D->DefinitionData.getNotUpdated()) {
1883 if (auto *CanonDD = CanonSpec->DefinitionData.getNotUpdated()) {
1884 MergeDefinitionData(CanonSpec, std::move(*DDD));
1885 Reader.PendingDefinitions.erase(D);
1886 Reader.MergedDeclContexts.insert(
1887 std::make_pair(D, CanonDD->Definition));
1888 D->IsCompleteDefinition = false;
1890 CanonSpec->DefinitionData = D->DefinitionData;
1893 D->DefinitionData = CanonSpec->DefinitionData;
1899 if (TypeSourceInfo *TyInfo = GetTypeSourceInfo(Record, Idx)) {
1900 ClassTemplateSpecializationDecl::ExplicitSpecializationInfo *ExplicitInfo
1901 = new (C) ClassTemplateSpecializationDecl::ExplicitSpecializationInfo;
1902 ExplicitInfo->TypeAsWritten = TyInfo;
1903 ExplicitInfo->ExternLoc = ReadSourceLocation(Record, Idx);
1904 ExplicitInfo->TemplateKeywordLoc = ReadSourceLocation(Record, Idx);
1905 D->ExplicitInfo = ExplicitInfo;
1911 void ASTDeclReader::VisitClassTemplatePartialSpecializationDecl(
1912 ClassTemplatePartialSpecializationDecl *D) {
1913 RedeclarableResult Redecl = VisitClassTemplateSpecializationDeclImpl(D);
1915 D->TemplateParams = Reader.ReadTemplateParameterList(F, Record, Idx);
1916 D->ArgsAsWritten = Reader.ReadASTTemplateArgumentListInfo(F, Record, Idx);
1918 // These are read/set from/to the first declaration.
1919 if (ThisDeclID == Redecl.getFirstID()) {
1920 D->InstantiatedFromMember.setPointer(
1921 ReadDeclAs<ClassTemplatePartialSpecializationDecl>(Record, Idx));
1922 D->InstantiatedFromMember.setInt(Record[Idx++]);
1926 void ASTDeclReader::VisitClassScopeFunctionSpecializationDecl(
1927 ClassScopeFunctionSpecializationDecl *D) {
1929 D->Specialization = ReadDeclAs<CXXMethodDecl>(Record, Idx);
1932 void ASTDeclReader::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
1933 RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
1935 if (ThisDeclID == Redecl.getFirstID()) {
1936 // This FunctionTemplateDecl owns a CommonPtr; read it.
1937 SmallVector<serialization::DeclID, 32> SpecIDs;
1938 ReadDeclIDList(SpecIDs);
1940 if (!SpecIDs.empty()) {
1941 auto *CommonPtr = D->getCommonPtr();
1942 CommonPtr->LazySpecializations = newDeclIDList(
1943 Reader.getContext(), CommonPtr->LazySpecializations, SpecIDs);
1948 /// TODO: Unify with ClassTemplateSpecializationDecl version?
1949 /// May require unifying ClassTemplate(Partial)SpecializationDecl and
1950 /// VarTemplate(Partial)SpecializationDecl with a new data
1951 /// structure Template(Partial)SpecializationDecl, and
1952 /// using Template(Partial)SpecializationDecl as input type.
1953 ASTDeclReader::RedeclarableResult
1954 ASTDeclReader::VisitVarTemplateSpecializationDeclImpl(
1955 VarTemplateSpecializationDecl *D) {
1956 RedeclarableResult Redecl = VisitVarDeclImpl(D);
1958 ASTContext &C = Reader.getContext();
1959 if (Decl *InstD = ReadDecl(Record, Idx)) {
1960 if (VarTemplateDecl *VTD = dyn_cast<VarTemplateDecl>(InstD)) {
1961 D->SpecializedTemplate = VTD;
1963 SmallVector<TemplateArgument, 8> TemplArgs;
1964 Reader.ReadTemplateArgumentList(TemplArgs, F, Record, Idx);
1965 TemplateArgumentList *ArgList = TemplateArgumentList::CreateCopy(
1966 C, TemplArgs.data(), TemplArgs.size());
1967 VarTemplateSpecializationDecl::SpecializedPartialSpecialization *PS =
1969 VarTemplateSpecializationDecl::SpecializedPartialSpecialization();
1970 PS->PartialSpecialization =
1971 cast<VarTemplatePartialSpecializationDecl>(InstD);
1972 PS->TemplateArgs = ArgList;
1973 D->SpecializedTemplate = PS;
1978 if (TypeSourceInfo *TyInfo = GetTypeSourceInfo(Record, Idx)) {
1979 VarTemplateSpecializationDecl::ExplicitSpecializationInfo *ExplicitInfo =
1980 new (C) VarTemplateSpecializationDecl::ExplicitSpecializationInfo;
1981 ExplicitInfo->TypeAsWritten = TyInfo;
1982 ExplicitInfo->ExternLoc = ReadSourceLocation(Record, Idx);
1983 ExplicitInfo->TemplateKeywordLoc = ReadSourceLocation(Record, Idx);
1984 D->ExplicitInfo = ExplicitInfo;
1987 SmallVector<TemplateArgument, 8> TemplArgs;
1988 Reader.ReadTemplateArgumentList(TemplArgs, F, Record, Idx);
1990 TemplateArgumentList::CreateCopy(C, TemplArgs.data(), TemplArgs.size());
1991 D->PointOfInstantiation = ReadSourceLocation(Record, Idx);
1992 D->SpecializationKind = (TemplateSpecializationKind)Record[Idx++];
1994 bool writtenAsCanonicalDecl = Record[Idx++];
1995 if (writtenAsCanonicalDecl) {
1996 VarTemplateDecl *CanonPattern = ReadDeclAs<VarTemplateDecl>(Record, Idx);
1997 if (D->isCanonicalDecl()) { // It's kept in the folding set.
1998 if (VarTemplatePartialSpecializationDecl *Partial =
1999 dyn_cast<VarTemplatePartialSpecializationDecl>(D)) {
2000 CanonPattern->getCommonPtr()->PartialSpecializations
2001 .GetOrInsertNode(Partial);
2003 CanonPattern->getCommonPtr()->Specializations.GetOrInsertNode(D);
2011 /// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
2012 /// May require unifying ClassTemplate(Partial)SpecializationDecl and
2013 /// VarTemplate(Partial)SpecializationDecl with a new data
2014 /// structure Template(Partial)SpecializationDecl, and
2015 /// using Template(Partial)SpecializationDecl as input type.
2016 void ASTDeclReader::VisitVarTemplatePartialSpecializationDecl(
2017 VarTemplatePartialSpecializationDecl *D) {
2018 RedeclarableResult Redecl = VisitVarTemplateSpecializationDeclImpl(D);
2020 D->TemplateParams = Reader.ReadTemplateParameterList(F, Record, Idx);
2021 D->ArgsAsWritten = Reader.ReadASTTemplateArgumentListInfo(F, Record, Idx);
2023 // These are read/set from/to the first declaration.
2024 if (ThisDeclID == Redecl.getFirstID()) {
2025 D->InstantiatedFromMember.setPointer(
2026 ReadDeclAs<VarTemplatePartialSpecializationDecl>(Record, Idx));
2027 D->InstantiatedFromMember.setInt(Record[Idx++]);
2031 void ASTDeclReader::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
2034 D->setDeclaredWithTypename(Record[Idx++]);
2036 bool Inherited = Record[Idx++];
2037 TypeSourceInfo *DefArg = GetTypeSourceInfo(Record, Idx);
2038 D->setDefaultArgument(DefArg, Inherited);
2041 void ASTDeclReader::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
2042 VisitDeclaratorDecl(D);
2043 // TemplateParmPosition.
2044 D->setDepth(Record[Idx++]);
2045 D->setPosition(Record[Idx++]);
2046 if (D->isExpandedParameterPack()) {
2047 void **Data = reinterpret_cast<void **>(D + 1);
2048 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
2049 Data[2*I] = Reader.readType(F, Record, Idx).getAsOpaquePtr();
2050 Data[2*I + 1] = GetTypeSourceInfo(Record, Idx);
2053 // Rest of NonTypeTemplateParmDecl.
2054 D->ParameterPack = Record[Idx++];
2055 if (Record[Idx++]) {
2056 Expr *DefArg = Reader.ReadExpr(F);
2057 bool Inherited = Record[Idx++];
2058 D->setDefaultArgument(DefArg, Inherited);
2063 void ASTDeclReader::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
2064 VisitTemplateDecl(D);
2065 // TemplateParmPosition.
2066 D->setDepth(Record[Idx++]);
2067 D->setPosition(Record[Idx++]);
2068 if (D->isExpandedParameterPack()) {
2069 void **Data = reinterpret_cast<void **>(D + 1);
2070 for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
2072 Data[I] = Reader.ReadTemplateParameterList(F, Record, Idx);
2074 // Rest of TemplateTemplateParmDecl.
2075 TemplateArgumentLoc Arg = Reader.ReadTemplateArgumentLoc(F, Record, Idx);
2076 bool IsInherited = Record[Idx++];
2077 D->setDefaultArgument(Arg, IsInherited);
2078 D->ParameterPack = Record[Idx++];
2082 void ASTDeclReader::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
2083 VisitRedeclarableTemplateDecl(D);
2086 void ASTDeclReader::VisitStaticAssertDecl(StaticAssertDecl *D) {
2088 D->AssertExprAndFailed.setPointer(Reader.ReadExpr(F));
2089 D->AssertExprAndFailed.setInt(Record[Idx++]);
2090 D->Message = cast<StringLiteral>(Reader.ReadExpr(F));
2091 D->RParenLoc = ReadSourceLocation(Record, Idx);
2094 void ASTDeclReader::VisitEmptyDecl(EmptyDecl *D) {
2098 std::pair<uint64_t, uint64_t>
2099 ASTDeclReader::VisitDeclContext(DeclContext *DC) {
2100 uint64_t LexicalOffset = Record[Idx++];
2101 uint64_t VisibleOffset = Record[Idx++];
2102 return std::make_pair(LexicalOffset, VisibleOffset);
2105 template <typename T>
2106 ASTDeclReader::RedeclarableResult
2107 ASTDeclReader::VisitRedeclarable(Redeclarable<T> *D) {
2108 DeclID FirstDeclID = ReadDeclID(Record, Idx);
2109 Decl *MergeWith = nullptr;
2111 // 0 indicates that this declaration was the only declaration of its entity,
2112 // and is used for space optimization.
2113 if (FirstDeclID == 0)
2114 FirstDeclID = ThisDeclID;
2115 else if (unsigned N = Record[Idx++]) {
2116 // We have some declarations that must be before us in our redeclaration
2117 // chain. Read them now, and remember that we ought to merge with one of
2119 // FIXME: Provide a known merge target to the second and subsequent such
2121 for (unsigned I = 0; I != N; ++I)
2122 MergeWith = ReadDecl(Record, Idx/*, MergeWith*/);
2125 T *FirstDecl = cast_or_null<T>(Reader.GetDecl(FirstDeclID));
2126 if (FirstDecl != D) {
2127 // We delay loading of the redeclaration chain to avoid deeply nested calls.
2128 // We temporarily set the first (canonical) declaration as the previous one
2129 // which is the one that matters and mark the real previous DeclID to be
2130 // loaded & attached later on.
2131 D->RedeclLink = Redeclarable<T>::PreviousDeclLink(FirstDecl);
2132 D->First = FirstDecl->getCanonicalDecl();
2135 // Note that this declaration has been deserialized.
2136 Reader.RedeclsDeserialized.insert(static_cast<T *>(D));
2138 // The result structure takes care to note that we need to load the
2139 // other declaration chains for this ID.
2140 return RedeclarableResult(Reader, FirstDeclID, MergeWith,
2141 static_cast<T *>(D)->getKind());
2144 /// \brief Attempts to merge the given declaration (D) with another declaration
2145 /// of the same entity.
2146 template<typename T>
2147 void ASTDeclReader::mergeRedeclarable(Redeclarable<T> *DBase,
2148 RedeclarableResult &Redecl,
2149 DeclID TemplatePatternID) {
2150 T *D = static_cast<T*>(DBase);
2152 // If modules are not available, there is no reason to perform this merge.
2153 if (!Reader.getContext().getLangOpts().Modules)
2156 // If we're not the canonical declaration, we don't need to merge.
2157 if (!DBase->isFirstDecl())
2160 if (auto *Existing = Redecl.getKnownMergeTarget())
2161 // We already know of an existing declaration we should merge with.
2162 mergeRedeclarable(D, cast<T>(Existing), Redecl, TemplatePatternID);
2163 else if (FindExistingResult ExistingRes = findExisting(D))
2164 if (T *Existing = ExistingRes)
2165 mergeRedeclarable(D, Existing, Redecl, TemplatePatternID);
2168 /// \brief "Cast" to type T, asserting if we don't have an implicit conversion.
2169 /// We use this to put code in a template that will only be valid for certain
2171 template<typename T> static T assert_cast(T t) { return t; }
2172 template<typename T> static T assert_cast(...) {
2173 llvm_unreachable("bad assert_cast");
2176 /// \brief Merge together the pattern declarations from two template
2178 void ASTDeclReader::mergeTemplatePattern(RedeclarableTemplateDecl *D,
2179 RedeclarableTemplateDecl *Existing,
2181 auto *DPattern = D->getTemplatedDecl();
2182 auto *ExistingPattern = Existing->getTemplatedDecl();
2183 RedeclarableResult Result(Reader, DPattern->getCanonicalDecl()->getGlobalID(),
2184 /*MergeWith*/ExistingPattern, DPattern->getKind());
2186 if (auto *DClass = dyn_cast<CXXRecordDecl>(DPattern)) {
2187 // Merge with any existing definition.
2188 // FIXME: This is duplicated in several places. Refactor.
2189 auto *ExistingClass =
2190 cast<CXXRecordDecl>(ExistingPattern)->getCanonicalDecl();
2191 if (auto *DDD = DClass->DefinitionData.getNotUpdated()) {
2192 if (auto *ExistingDD = ExistingClass->DefinitionData.getNotUpdated()) {
2193 MergeDefinitionData(ExistingClass, std::move(*DDD));
2194 Reader.PendingDefinitions.erase(DClass);
2195 Reader.MergedDeclContexts.insert(
2196 std::make_pair(DClass, ExistingDD->Definition));
2197 DClass->IsCompleteDefinition = false;
2199 ExistingClass->DefinitionData = DClass->DefinitionData;
2200 Reader.PendingDefinitions.insert(DClass);
2203 DClass->DefinitionData = ExistingClass->DefinitionData;
2205 return mergeRedeclarable(DClass, cast<TagDecl>(ExistingPattern),
2208 if (auto *DFunction = dyn_cast<FunctionDecl>(DPattern))
2209 return mergeRedeclarable(DFunction, cast<FunctionDecl>(ExistingPattern),
2211 if (auto *DVar = dyn_cast<VarDecl>(DPattern))
2212 return mergeRedeclarable(DVar, cast<VarDecl>(ExistingPattern), Result);
2213 if (auto *DAlias = dyn_cast<TypeAliasDecl>(DPattern))
2214 return mergeRedeclarable(DAlias, cast<TypedefNameDecl>(ExistingPattern),
2216 llvm_unreachable("merged an unknown kind of redeclarable template");
2219 /// \brief Attempts to merge the given declaration (D) with another declaration
2220 /// of the same entity.
2221 template<typename T>
2222 void ASTDeclReader::mergeRedeclarable(Redeclarable<T> *DBase, T *Existing,
2223 RedeclarableResult &Redecl,
2224 DeclID TemplatePatternID) {
2225 T *D = static_cast<T*>(DBase);
2226 T *ExistingCanon = Existing->getCanonicalDecl();
2227 T *DCanon = D->getCanonicalDecl();
2228 if (ExistingCanon != DCanon) {
2229 assert(DCanon->getGlobalID() == Redecl.getFirstID() &&
2230 "already merged this declaration");
2232 // Have our redeclaration link point back at the canonical declaration
2233 // of the existing declaration, so that this declaration has the
2234 // appropriate canonical declaration.
2235 D->RedeclLink = Redeclarable<T>::PreviousDeclLink(ExistingCanon);
2236 D->First = ExistingCanon;
2238 // When we merge a namespace, update its pointer to the first namespace.
2239 // We cannot have loaded any redeclarations of this declaration yet, so
2240 // there's nothing else that needs to be updated.
2241 if (auto *Namespace = dyn_cast<NamespaceDecl>(D))
2242 Namespace->AnonOrFirstNamespaceAndInline.setPointer(
2243 assert_cast<NamespaceDecl*>(ExistingCanon));
2245 // When we merge a template, merge its pattern.
2246 if (auto *DTemplate = dyn_cast<RedeclarableTemplateDecl>(D))
2247 mergeTemplatePattern(
2248 DTemplate, assert_cast<RedeclarableTemplateDecl*>(ExistingCanon),
2251 // If this declaration was the canonical declaration, make a note of that.
2253 Reader.MergedDecls[ExistingCanon].push_back(Redecl.getFirstID());
2254 if (Reader.PendingDeclChainsKnown.insert(ExistingCanon).second)
2255 Reader.PendingDeclChains.push_back(ExistingCanon);
2260 /// \brief Attempts to merge the given declaration (D) with another declaration
2261 /// of the same entity, for the case where the entity is not actually
2262 /// redeclarable. This happens, for instance, when merging the fields of
2263 /// identical class definitions from two different modules.
2264 template<typename T>
2265 void ASTDeclReader::mergeMergeable(Mergeable<T> *D) {
2266 // If modules are not available, there is no reason to perform this merge.
2267 if (!Reader.getContext().getLangOpts().Modules)
2270 // ODR-based merging is only performed in C++. In C, identically-named things
2271 // in different translation units are not redeclarations (but may still have
2272 // compatible types).
2273 if (!Reader.getContext().getLangOpts().CPlusPlus)
2276 if (FindExistingResult ExistingRes = findExisting(static_cast<T*>(D)))
2277 if (T *Existing = ExistingRes)
2278 Reader.Context.setPrimaryMergedDecl(static_cast<T*>(D),
2279 Existing->getCanonicalDecl());
2282 void ASTDeclReader::VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D) {
2284 unsigned NumVars = D->varlist_size();
2285 SmallVector<Expr *, 16> Vars;
2286 Vars.reserve(NumVars);
2287 for (unsigned i = 0; i != NumVars; ++i) {
2288 Vars.push_back(Reader.ReadExpr(F));
2293 //===----------------------------------------------------------------------===//
2294 // Attribute Reading
2295 //===----------------------------------------------------------------------===//
2297 /// \brief Reads attributes from the current stream position.
2298 void ASTReader::ReadAttributes(ModuleFile &F, AttrVec &Attrs,
2299 const RecordData &Record, unsigned &Idx) {
2300 for (unsigned i = 0, e = Record[Idx++]; i != e; ++i) {
2301 Attr *New = nullptr;
2302 attr::Kind Kind = (attr::Kind)Record[Idx++];
2303 SourceRange Range = ReadSourceRange(F, Record, Idx);
2305 #include "clang/Serialization/AttrPCHRead.inc"
2307 assert(New && "Unable to decode attribute?");
2308 Attrs.push_back(New);
2312 //===----------------------------------------------------------------------===//
2313 // ASTReader Implementation
2314 //===----------------------------------------------------------------------===//
2316 /// \brief Note that we have loaded the declaration with the given
2319 /// This routine notes that this declaration has already been loaded,
2320 /// so that future GetDecl calls will return this declaration rather
2321 /// than trying to load a new declaration.
2322 inline void ASTReader::LoadedDecl(unsigned Index, Decl *D) {
2323 assert(!DeclsLoaded[Index] && "Decl loaded twice?");
2324 DeclsLoaded[Index] = D;
2328 /// \brief Determine whether the consumer will be interested in seeing
2329 /// this declaration (via HandleTopLevelDecl).
2331 /// This routine should return true for anything that might affect
2332 /// code generation, e.g., inline function definitions, Objective-C
2333 /// declarations with metadata, etc.
2334 static bool isConsumerInterestedIn(Decl *D, bool HasBody) {
2335 // An ObjCMethodDecl is never considered as "interesting" because its
2336 // implementation container always is.
2338 if (isa<FileScopeAsmDecl>(D) ||
2339 isa<ObjCProtocolDecl>(D) ||
2340 isa<ObjCImplDecl>(D) ||
2341 isa<ImportDecl>(D) ||
2342 isa<OMPThreadPrivateDecl>(D))
2344 if (VarDecl *Var = dyn_cast<VarDecl>(D))
2345 return Var->isFileVarDecl() &&
2346 Var->isThisDeclarationADefinition() == VarDecl::Definition;
2347 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(D))
2348 return Func->doesThisDeclarationHaveABody() || HasBody;
2353 /// \brief Get the correct cursor and offset for loading a declaration.
2354 ASTReader::RecordLocation
2355 ASTReader::DeclCursorForID(DeclID ID, unsigned &RawLocation) {
2356 // See if there's an override.
2357 DeclReplacementMap::iterator It = ReplacedDecls.find(ID);
2358 if (It != ReplacedDecls.end()) {
2359 RawLocation = It->second.RawLoc;
2360 return RecordLocation(It->second.Mod, It->second.Offset);
2363 GlobalDeclMapType::iterator I = GlobalDeclMap.find(ID);
2364 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
2365 ModuleFile *M = I->second;
2367 DOffs = M->DeclOffsets[ID - M->BaseDeclID - NUM_PREDEF_DECL_IDS];
2368 RawLocation = DOffs.Loc;
2369 return RecordLocation(M, DOffs.BitOffset);
2372 ASTReader::RecordLocation ASTReader::getLocalBitOffset(uint64_t GlobalOffset) {
2373 ContinuousRangeMap<uint64_t, ModuleFile*, 4>::iterator I
2374 = GlobalBitOffsetsMap.find(GlobalOffset);
2376 assert(I != GlobalBitOffsetsMap.end() && "Corrupted global bit offsets map");
2377 return RecordLocation(I->second, GlobalOffset - I->second->GlobalBitOffset);
2380 uint64_t ASTReader::getGlobalBitOffset(ModuleFile &M, uint32_t LocalOffset) {
2381 return LocalOffset + M.GlobalBitOffset;
2384 static bool isSameTemplateParameterList(const TemplateParameterList *X,
2385 const TemplateParameterList *Y);
2387 /// \brief Determine whether two template parameters are similar enough
2388 /// that they may be used in declarations of the same template.
2389 static bool isSameTemplateParameter(const NamedDecl *X,
2390 const NamedDecl *Y) {
2391 if (X->getKind() != Y->getKind())
2394 if (const TemplateTypeParmDecl *TX = dyn_cast<TemplateTypeParmDecl>(X)) {
2395 const TemplateTypeParmDecl *TY = cast<TemplateTypeParmDecl>(Y);
2396 return TX->isParameterPack() == TY->isParameterPack();
2399 if (const NonTypeTemplateParmDecl *TX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
2400 const NonTypeTemplateParmDecl *TY = cast<NonTypeTemplateParmDecl>(Y);
2401 return TX->isParameterPack() == TY->isParameterPack() &&
2402 TX->getASTContext().hasSameType(TX->getType(), TY->getType());
2405 const TemplateTemplateParmDecl *TX = cast<TemplateTemplateParmDecl>(X);
2406 const TemplateTemplateParmDecl *TY = cast<TemplateTemplateParmDecl>(Y);
2407 return TX->isParameterPack() == TY->isParameterPack() &&
2408 isSameTemplateParameterList(TX->getTemplateParameters(),
2409 TY->getTemplateParameters());
2412 static NamespaceDecl *getNamespace(const NestedNameSpecifier *X) {
2413 if (auto *NS = X->getAsNamespace())
2415 if (auto *NAS = X->getAsNamespaceAlias())
2416 return NAS->getNamespace();
2420 static bool isSameQualifier(const NestedNameSpecifier *X,
2421 const NestedNameSpecifier *Y) {
2422 if (auto *NSX = getNamespace(X)) {
2423 auto *NSY = getNamespace(Y);
2424 if (!NSY || NSX->getCanonicalDecl() != NSY->getCanonicalDecl())
2426 } else if (X->getKind() != Y->getKind())
2429 // FIXME: For namespaces and types, we're permitted to check that the entity
2430 // is named via the same tokens. We should probably do so.
2431 switch (X->getKind()) {
2432 case NestedNameSpecifier::Identifier:
2433 if (X->getAsIdentifier() != Y->getAsIdentifier())
2436 case NestedNameSpecifier::Namespace:
2437 case NestedNameSpecifier::NamespaceAlias:
2438 // We've already checked that we named the same namespace.
2440 case NestedNameSpecifier::TypeSpec:
2441 case NestedNameSpecifier::TypeSpecWithTemplate:
2442 if (X->getAsType()->getCanonicalTypeInternal() !=
2443 Y->getAsType()->getCanonicalTypeInternal())
2446 case NestedNameSpecifier::Global:
2447 case NestedNameSpecifier::Super:
2451 // Recurse into earlier portion of NNS, if any.
2452 auto *PX = X->getPrefix();
2453 auto *PY = Y->getPrefix();
2455 return isSameQualifier(PX, PY);
2459 /// \brief Determine whether two template parameter lists are similar enough
2460 /// that they may be used in declarations of the same template.
2461 static bool isSameTemplateParameterList(const TemplateParameterList *X,
2462 const TemplateParameterList *Y) {
2463 if (X->size() != Y->size())
2466 for (unsigned I = 0, N = X->size(); I != N; ++I)
2467 if (!isSameTemplateParameter(X->getParam(I), Y->getParam(I)))
2473 /// \brief Determine whether the two declarations refer to the same entity.
2474 static bool isSameEntity(NamedDecl *X, NamedDecl *Y) {
2475 assert(X->getDeclName() == Y->getDeclName() && "Declaration name mismatch!");
2480 // Must be in the same context.
2481 if (!X->getDeclContext()->getRedeclContext()->Equals(
2482 Y->getDeclContext()->getRedeclContext()))
2485 // Two typedefs refer to the same entity if they have the same underlying
2487 if (TypedefNameDecl *TypedefX = dyn_cast<TypedefNameDecl>(X))
2488 if (TypedefNameDecl *TypedefY = dyn_cast<TypedefNameDecl>(Y))
2489 return X->getASTContext().hasSameType(TypedefX->getUnderlyingType(),
2490 TypedefY->getUnderlyingType());
2492 // Must have the same kind.
2493 if (X->getKind() != Y->getKind())
2496 // Objective-C classes and protocols with the same name always match.
2497 if (isa<ObjCInterfaceDecl>(X) || isa<ObjCProtocolDecl>(X))
2500 if (isa<ClassTemplateSpecializationDecl>(X)) {
2501 // No need to handle these here: we merge them when adding them to the
2506 // Compatible tags match.
2507 if (TagDecl *TagX = dyn_cast<TagDecl>(X)) {
2508 TagDecl *TagY = cast<TagDecl>(Y);
2509 return (TagX->getTagKind() == TagY->getTagKind()) ||
2510 ((TagX->getTagKind() == TTK_Struct || TagX->getTagKind() == TTK_Class ||
2511 TagX->getTagKind() == TTK_Interface) &&
2512 (TagY->getTagKind() == TTK_Struct || TagY->getTagKind() == TTK_Class ||
2513 TagY->getTagKind() == TTK_Interface));
2516 // Functions with the same type and linkage match.
2517 // FIXME: This needs to cope with merging of prototyped/non-prototyped
2519 if (FunctionDecl *FuncX = dyn_cast<FunctionDecl>(X)) {
2520 FunctionDecl *FuncY = cast<FunctionDecl>(Y);
2521 return (FuncX->getLinkageInternal() == FuncY->getLinkageInternal()) &&
2522 FuncX->getASTContext().hasSameType(FuncX->getType(), FuncY->getType());
2525 // Variables with the same type and linkage match.
2526 if (VarDecl *VarX = dyn_cast<VarDecl>(X)) {
2527 VarDecl *VarY = cast<VarDecl>(Y);
2528 return (VarX->getLinkageInternal() == VarY->getLinkageInternal()) &&
2529 VarX->getASTContext().hasSameType(VarX->getType(), VarY->getType());
2532 // Namespaces with the same name and inlinedness match.
2533 if (NamespaceDecl *NamespaceX = dyn_cast<NamespaceDecl>(X)) {
2534 NamespaceDecl *NamespaceY = cast<NamespaceDecl>(Y);
2535 return NamespaceX->isInline() == NamespaceY->isInline();
2538 // Identical template names and kinds match if their template parameter lists
2539 // and patterns match.
2540 if (TemplateDecl *TemplateX = dyn_cast<TemplateDecl>(X)) {
2541 TemplateDecl *TemplateY = cast<TemplateDecl>(Y);
2542 return isSameEntity(TemplateX->getTemplatedDecl(),
2543 TemplateY->getTemplatedDecl()) &&
2544 isSameTemplateParameterList(TemplateX->getTemplateParameters(),
2545 TemplateY->getTemplateParameters());
2548 // Fields with the same name and the same type match.
2549 if (FieldDecl *FDX = dyn_cast<FieldDecl>(X)) {
2550 FieldDecl *FDY = cast<FieldDecl>(Y);
2551 // FIXME: Also check the bitwidth is odr-equivalent, if any.
2552 return X->getASTContext().hasSameType(FDX->getType(), FDY->getType());
2555 // Enumerators with the same name match.
2556 if (isa<EnumConstantDecl>(X))
2557 // FIXME: Also check the value is odr-equivalent.
2560 // Using shadow declarations with the same target match.
2561 if (UsingShadowDecl *USX = dyn_cast<UsingShadowDecl>(X)) {
2562 UsingShadowDecl *USY = cast<UsingShadowDecl>(Y);
2563 return USX->getTargetDecl() == USY->getTargetDecl();
2566 // Using declarations with the same qualifier match. (We already know that
2567 // the name matches.)
2568 if (auto *UX = dyn_cast<UsingDecl>(X)) {
2569 auto *UY = cast<UsingDecl>(Y);
2570 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
2571 UX->hasTypename() == UY->hasTypename() &&
2572 UX->isAccessDeclaration() == UY->isAccessDeclaration();
2574 if (auto *UX = dyn_cast<UnresolvedUsingValueDecl>(X)) {
2575 auto *UY = cast<UnresolvedUsingValueDecl>(Y);
2576 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
2577 UX->isAccessDeclaration() == UY->isAccessDeclaration();
2579 if (auto *UX = dyn_cast<UnresolvedUsingTypenameDecl>(X))
2580 return isSameQualifier(
2582 cast<UnresolvedUsingTypenameDecl>(Y)->getQualifier());
2584 // Namespace alias definitions with the same target match.
2585 if (auto *NAX = dyn_cast<NamespaceAliasDecl>(X)) {
2586 auto *NAY = cast<NamespaceAliasDecl>(Y);
2587 return NAX->getNamespace()->Equals(NAY->getNamespace());
2590 // FIXME: Many other cases to implement.
2594 /// Find the context in which we should search for previous declarations when
2595 /// looking for declarations to merge.
2596 DeclContext *ASTDeclReader::getPrimaryContextForMerging(ASTReader &Reader,
2598 if (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC))
2599 return ND->getOriginalNamespace();
2601 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
2602 // Try to dig out the definition.
2603 auto *DD = RD->DefinitionData.getNotUpdated();
2605 DD = RD->getCanonicalDecl()->DefinitionData.getNotUpdated();
2607 // If there's no definition yet, then DC's definition is added by an update
2608 // record, but we've not yet loaded that update record. In this case, we
2609 // commit to DC being the canonical definition now, and will fix this when
2610 // we load the update record.
2612 DD = new (Reader.Context) struct CXXRecordDecl::DefinitionData(RD);
2613 RD->IsCompleteDefinition = true;
2614 RD->DefinitionData = DD;
2615 RD->getCanonicalDecl()->DefinitionData = DD;
2617 // Track that we did this horrible thing so that we can fix it later.
2618 Reader.PendingFakeDefinitionData.insert(
2619 std::make_pair(DD, ASTReader::PendingFakeDefinitionKind::Fake));
2622 return DD->Definition;
2625 if (EnumDecl *ED = dyn_cast<EnumDecl>(DC))
2626 return ED->getASTContext().getLangOpts().CPlusPlus? ED->getDefinition()
2629 // We can see the TU here only if we have no Sema object. In that case,
2630 // there's no TU scope to look in, so using the DC alone is sufficient.
2631 if (auto *TU = dyn_cast<TranslationUnitDecl>(DC))
2637 ASTDeclReader::FindExistingResult::~FindExistingResult() {
2638 // Record that we had a typedef name for linkage whether or not we merge
2639 // with that declaration.
2640 if (TypedefNameForLinkage) {
2641 DeclContext *DC = New->getDeclContext()->getRedeclContext();
2642 Reader.ImportedTypedefNamesForLinkage.insert(
2643 std::make_pair(std::make_pair(DC, TypedefNameForLinkage), New));
2647 if (!AddResult || Existing)
2650 DeclarationName Name = New->getDeclName();
2651 DeclContext *DC = New->getDeclContext()->getRedeclContext();
2652 if (needsAnonymousDeclarationNumber(New)) {
2653 setAnonymousDeclForMerging(Reader, New->getLexicalDeclContext(),
2654 AnonymousDeclNumber, New);
2655 } else if (DC->isTranslationUnit() && Reader.SemaObj &&
2656 !Reader.getContext().getLangOpts().CPlusPlus) {
2657 if (Reader.SemaObj->IdResolver.tryAddTopLevelDecl(New, Name))
2658 Reader.PendingFakeLookupResults[Name.getAsIdentifierInfo()]
2660 } else if (DeclContext *MergeDC = getPrimaryContextForMerging(Reader, DC)) {
2661 // Add the declaration to its redeclaration context so later merging
2662 // lookups will find it.
2663 MergeDC->makeDeclVisibleInContextImpl(New, /*Internal*/true);
2667 /// Find the declaration that should be merged into, given the declaration found
2668 /// by name lookup. If we're merging an anonymous declaration within a typedef,
2669 /// we need a matching typedef, and we merge with the type inside it.
2670 static NamedDecl *getDeclForMerging(NamedDecl *Found,
2671 bool IsTypedefNameForLinkage) {
2672 if (!IsTypedefNameForLinkage)
2675 // If we found a typedef declaration that gives a name to some other
2676 // declaration, then we want that inner declaration. Declarations from
2677 // AST files are handled via ImportedTypedefNamesForLinkage.
2678 if (Found->isFromASTFile())
2681 if (auto *TND = dyn_cast<TypedefNameDecl>(Found))
2682 return TND->getAnonDeclWithTypedefName();
2687 NamedDecl *ASTDeclReader::getAnonymousDeclForMerging(ASTReader &Reader,
2690 // If the lexical context has been merged, look into the now-canonical
2692 if (auto *Merged = Reader.MergedDeclContexts.lookup(DC))
2695 // If we've seen this before, return the canonical declaration.
2696 auto &Previous = Reader.AnonymousDeclarationsForMerging[DC];
2697 if (Index < Previous.size() && Previous[Index])
2698 return Previous[Index];
2700 // If this is the first time, but we have parsed a declaration of the context,
2701 // build the anonymous declaration list from the parsed declaration.
2702 if (!cast<Decl>(DC)->isFromASTFile()) {
2703 numberAnonymousDeclsWithin(DC, [&](NamedDecl *ND, unsigned Number) {
2704 if (Previous.size() == Number)
2705 Previous.push_back(cast<NamedDecl>(ND->getCanonicalDecl()));
2707 Previous[Number] = cast<NamedDecl>(ND->getCanonicalDecl());
2711 return Index < Previous.size() ? Previous[Index] : nullptr;
2714 void ASTDeclReader::setAnonymousDeclForMerging(ASTReader &Reader,
2715 DeclContext *DC, unsigned Index,
2717 if (auto *Merged = Reader.MergedDeclContexts.lookup(DC))
2720 auto &Previous = Reader.AnonymousDeclarationsForMerging[DC];
2721 if (Index >= Previous.size())
2722 Previous.resize(Index + 1);
2723 if (!Previous[Index])
2724 Previous[Index] = D;
2727 ASTDeclReader::FindExistingResult ASTDeclReader::findExisting(NamedDecl *D) {
2728 DeclarationName Name = TypedefNameForLinkage ? TypedefNameForLinkage
2731 if (!Name && !needsAnonymousDeclarationNumber(D)) {
2732 // Don't bother trying to find unnamed declarations that are in
2733 // unmergeable contexts.
2734 FindExistingResult Result(Reader, D, /*Existing=*/nullptr,
2735 AnonymousDeclNumber, TypedefNameForLinkage);
2740 // FIXME: Bail out for non-canonical declarations. We will have performed any
2741 // necessary merging already.
2743 DeclContext *DC = D->getDeclContext()->getRedeclContext();
2744 if (TypedefNameForLinkage) {
2745 auto It = Reader.ImportedTypedefNamesForLinkage.find(
2746 std::make_pair(DC, TypedefNameForLinkage));
2747 if (It != Reader.ImportedTypedefNamesForLinkage.end())
2748 if (isSameEntity(It->second, D))
2749 return FindExistingResult(Reader, D, It->second, AnonymousDeclNumber,
2750 TypedefNameForLinkage);
2751 // Go on to check in other places in case an existing typedef name
2752 // was not imported.
2755 if (needsAnonymousDeclarationNumber(D)) {
2756 // This is an anonymous declaration that we may need to merge. Look it up
2757 // in its context by number.
2758 if (auto *Existing = getAnonymousDeclForMerging(
2759 Reader, D->getLexicalDeclContext(), AnonymousDeclNumber))
2760 if (isSameEntity(Existing, D))
2761 return FindExistingResult(Reader, D, Existing, AnonymousDeclNumber,
2762 TypedefNameForLinkage);
2763 } else if (DC->isTranslationUnit() && Reader.SemaObj &&
2764 !Reader.getContext().getLangOpts().CPlusPlus) {
2765 IdentifierResolver &IdResolver = Reader.SemaObj->IdResolver;
2767 // Temporarily consider the identifier to be up-to-date. We don't want to
2768 // cause additional lookups here.
2769 class UpToDateIdentifierRAII {
2774 explicit UpToDateIdentifierRAII(IdentifierInfo *II)
2775 : II(II), WasOutToDate(false)
2778 WasOutToDate = II->isOutOfDate();
2780 II->setOutOfDate(false);
2784 ~UpToDateIdentifierRAII() {
2786 II->setOutOfDate(true);
2788 } UpToDate(Name.getAsIdentifierInfo());
2790 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
2791 IEnd = IdResolver.end();
2793 if (NamedDecl *Existing = getDeclForMerging(*I, TypedefNameForLinkage))
2794 if (isSameEntity(Existing, D))
2795 return FindExistingResult(Reader, D, Existing, AnonymousDeclNumber,
2796 TypedefNameForLinkage);
2798 } else if (DeclContext *MergeDC = getPrimaryContextForMerging(Reader, DC)) {
2799 DeclContext::lookup_result R = MergeDC->noload_lookup(Name);
2800 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
2801 if (NamedDecl *Existing = getDeclForMerging(*I, TypedefNameForLinkage))
2802 if (isSameEntity(Existing, D))
2803 return FindExistingResult(Reader, D, Existing, AnonymousDeclNumber,
2804 TypedefNameForLinkage);
2807 // Not in a mergeable context.
2808 return FindExistingResult(Reader);
2811 // If this declaration is from a merged context, make a note that we need to
2812 // check that the canonical definition of that context contains the decl.
2814 // FIXME: We should do something similar if we merge two definitions of the
2815 // same template specialization into the same CXXRecordDecl.
2816 auto MergedDCIt = Reader.MergedDeclContexts.find(D->getLexicalDeclContext());
2817 if (MergedDCIt != Reader.MergedDeclContexts.end() &&
2818 MergedDCIt->second == D->getDeclContext())
2819 Reader.PendingOdrMergeChecks.push_back(D);
2821 return FindExistingResult(Reader, D, /*Existing=*/nullptr,
2822 AnonymousDeclNumber, TypedefNameForLinkage);
2825 template<typename DeclT>
2826 Decl *ASTDeclReader::getMostRecentDeclImpl(Redeclarable<DeclT> *D) {
2827 return D->RedeclLink.getLatestNotUpdated();
2829 Decl *ASTDeclReader::getMostRecentDeclImpl(...) {
2830 llvm_unreachable("getMostRecentDecl on non-redeclarable declaration");
2833 Decl *ASTDeclReader::getMostRecentDecl(Decl *D) {
2836 switch (D->getKind()) {
2837 #define ABSTRACT_DECL(TYPE)
2838 #define DECL(TYPE, BASE) \
2840 return getMostRecentDeclImpl(cast<TYPE##Decl>(D));
2841 #include "clang/AST/DeclNodes.inc"
2843 llvm_unreachable("unknown decl kind");
2846 Decl *ASTReader::getMostRecentExistingDecl(Decl *D) {
2847 return ASTDeclReader::getMostRecentDecl(D->getCanonicalDecl());
2850 template<typename DeclT>
2851 void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader,
2852 Redeclarable<DeclT> *D,
2853 Decl *Previous, Decl *Canon) {
2854 D->RedeclLink.setPrevious(cast<DeclT>(Previous));
2855 D->First = cast<DeclT>(Previous)->First;
2859 void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader,
2860 Redeclarable<FunctionDecl> *D,
2861 Decl *Previous, Decl *Canon) {
2862 FunctionDecl *FD = static_cast<FunctionDecl*>(D);
2863 FunctionDecl *PrevFD = cast<FunctionDecl>(Previous);
2865 FD->RedeclLink.setPrevious(PrevFD);
2866 FD->First = PrevFD->First;
2868 // If the previous declaration is an inline function declaration, then this
2869 // declaration is too.
2870 if (PrevFD->IsInline != FD->IsInline) {
2871 // FIXME: [dcl.fct.spec]p4:
2872 // If a function with external linkage is declared inline in one
2873 // translation unit, it shall be declared inline in all translation
2874 // units in which it appears.
2876 // Be careful of this case:
2879 // template<typename T> struct X { void f(); };
2880 // template<typename T> inline void X<T>::f() {}
2882 // module B instantiates the declaration of X<int>::f
2883 // module C instantiates the definition of X<int>::f
2885 // If module B and C are merged, we do not have a violation of this rule.
2886 FD->IsInline = true;
2889 // If we need to propagate an exception specification along the redecl
2890 // chain, make a note of that so that we can do so later.
2891 auto *FPT = FD->getType()->getAs<FunctionProtoType>();
2892 auto *PrevFPT = PrevFD->getType()->getAs<FunctionProtoType>();
2893 if (FPT && PrevFPT) {
2894 bool IsUnresolved = isUnresolvedExceptionSpec(FPT->getExceptionSpecType());
2895 bool WasUnresolved =
2896 isUnresolvedExceptionSpec(PrevFPT->getExceptionSpecType());
2897 if (IsUnresolved != WasUnresolved)
2898 Reader.PendingExceptionSpecUpdates.insert(
2899 std::make_pair(Canon, IsUnresolved ? PrevFD : FD));
2903 void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader, ...) {
2904 llvm_unreachable("attachPreviousDecl on non-redeclarable declaration");
2907 void ASTDeclReader::attachPreviousDecl(ASTReader &Reader, Decl *D,
2908 Decl *Previous, Decl *Canon) {
2909 assert(D && Previous);
2911 switch (D->getKind()) {
2912 #define ABSTRACT_DECL(TYPE)
2913 #define DECL(TYPE, BASE) \
2915 attachPreviousDeclImpl(Reader, cast<TYPE##Decl>(D), Previous, Canon); \
2917 #include "clang/AST/DeclNodes.inc"
2920 // If the declaration was visible in one module, a redeclaration of it in
2921 // another module remains visible even if it wouldn't be visible by itself.
2923 // FIXME: In this case, the declaration should only be visible if a module
2924 // that makes it visible has been imported.
2925 D->IdentifierNamespace |=
2926 Previous->IdentifierNamespace &
2927 (Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Type);
2929 // If the previous declaration is marked as used, then this declaration should
2935 template<typename DeclT>
2936 void ASTDeclReader::attachLatestDeclImpl(Redeclarable<DeclT> *D, Decl *Latest) {
2937 D->RedeclLink.setLatest(cast<DeclT>(Latest));
2939 void ASTDeclReader::attachLatestDeclImpl(...) {
2940 llvm_unreachable("attachLatestDecl on non-redeclarable declaration");
2943 void ASTDeclReader::attachLatestDecl(Decl *D, Decl *Latest) {
2944 assert(D && Latest);
2946 switch (D->getKind()) {
2947 #define ABSTRACT_DECL(TYPE)
2948 #define DECL(TYPE, BASE) \
2950 attachLatestDeclImpl(cast<TYPE##Decl>(D), Latest); \
2952 #include "clang/AST/DeclNodes.inc"
2956 template<typename DeclT>
2957 void ASTDeclReader::markIncompleteDeclChainImpl(Redeclarable<DeclT> *D) {
2958 D->RedeclLink.markIncomplete();
2960 void ASTDeclReader::markIncompleteDeclChainImpl(...) {
2961 llvm_unreachable("markIncompleteDeclChain on non-redeclarable declaration");
2964 void ASTReader::markIncompleteDeclChain(Decl *D) {
2965 switch (D->getKind()) {
2966 #define ABSTRACT_DECL(TYPE)
2967 #define DECL(TYPE, BASE) \
2969 ASTDeclReader::markIncompleteDeclChainImpl(cast<TYPE##Decl>(D)); \
2971 #include "clang/AST/DeclNodes.inc"
2975 /// \brief Read the declaration at the given offset from the AST file.
2976 Decl *ASTReader::ReadDeclRecord(DeclID ID) {
2977 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
2978 unsigned RawLocation = 0;
2979 RecordLocation Loc = DeclCursorForID(ID, RawLocation);
2980 llvm::BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
2981 // Keep track of where we are in the stream, then jump back there
2982 // after reading this declaration.
2983 SavedStreamPosition SavedPosition(DeclsCursor);
2985 ReadingKindTracker ReadingKind(Read_Decl, *this);
2987 // Note that we are loading a declaration record.
2988 Deserializing ADecl(this);
2990 DeclsCursor.JumpToBit(Loc.Offset);
2992 unsigned Code = DeclsCursor.ReadCode();
2994 ASTDeclReader Reader(*this, *Loc.F, ID, RawLocation, Record,Idx);
2997 switch ((DeclCode)DeclsCursor.readRecord(Code, Record)) {
2998 case DECL_CONTEXT_LEXICAL:
2999 case DECL_CONTEXT_VISIBLE:
3000 llvm_unreachable("Record cannot be de-serialized with ReadDeclRecord");
3002 D = TypedefDecl::CreateDeserialized(Context, ID);
3004 case DECL_TYPEALIAS:
3005 D = TypeAliasDecl::CreateDeserialized(Context, ID);
3008 D = EnumDecl::CreateDeserialized(Context, ID);
3011 D = RecordDecl::CreateDeserialized(Context, ID);
3013 case DECL_ENUM_CONSTANT:
3014 D = EnumConstantDecl::CreateDeserialized(Context, ID);
3017 D = FunctionDecl::CreateDeserialized(Context, ID);
3019 case DECL_LINKAGE_SPEC:
3020 D = LinkageSpecDecl::CreateDeserialized(Context, ID);
3023 D = LabelDecl::CreateDeserialized(Context, ID);
3025 case DECL_NAMESPACE:
3026 D = NamespaceDecl::CreateDeserialized(Context, ID);
3028 case DECL_NAMESPACE_ALIAS:
3029 D = NamespaceAliasDecl::CreateDeserialized(Context, ID);
3032 D = UsingDecl::CreateDeserialized(Context, ID);
3034 case DECL_USING_SHADOW:
3035 D = UsingShadowDecl::CreateDeserialized(Context, ID);
3037 case DECL_USING_DIRECTIVE:
3038 D = UsingDirectiveDecl::CreateDeserialized(Context, ID);
3040 case DECL_UNRESOLVED_USING_VALUE:
3041 D = UnresolvedUsingValueDecl::CreateDeserialized(Context, ID);
3043 case DECL_UNRESOLVED_USING_TYPENAME:
3044 D = UnresolvedUsingTypenameDecl::CreateDeserialized(Context, ID);
3046 case DECL_CXX_RECORD:
3047 D = CXXRecordDecl::CreateDeserialized(Context, ID);
3049 case DECL_CXX_METHOD:
3050 D = CXXMethodDecl::CreateDeserialized(Context, ID);
3052 case DECL_CXX_CONSTRUCTOR:
3053 D = CXXConstructorDecl::CreateDeserialized(Context, ID);
3055 case DECL_CXX_DESTRUCTOR:
3056 D = CXXDestructorDecl::CreateDeserialized(Context, ID);
3058 case DECL_CXX_CONVERSION:
3059 D = CXXConversionDecl::CreateDeserialized(Context, ID);
3061 case DECL_ACCESS_SPEC:
3062 D = AccessSpecDecl::CreateDeserialized(Context, ID);
3065 D = FriendDecl::CreateDeserialized(Context, ID, Record[Idx++]);
3067 case DECL_FRIEND_TEMPLATE:
3068 D = FriendTemplateDecl::CreateDeserialized(Context, ID);
3070 case DECL_CLASS_TEMPLATE:
3071 D = ClassTemplateDecl::CreateDeserialized(Context, ID);
3073 case DECL_CLASS_TEMPLATE_SPECIALIZATION:
3074 D = ClassTemplateSpecializationDecl::CreateDeserialized(Context, ID);
3076 case DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION:
3077 D = ClassTemplatePartialSpecializationDecl::CreateDeserialized(Context, ID);
3079 case DECL_VAR_TEMPLATE:
3080 D = VarTemplateDecl::CreateDeserialized(Context, ID);
3082 case DECL_VAR_TEMPLATE_SPECIALIZATION:
3083 D = VarTemplateSpecializationDecl::CreateDeserialized(Context, ID);
3085 case DECL_VAR_TEMPLATE_PARTIAL_SPECIALIZATION:
3086 D = VarTemplatePartialSpecializationDecl::CreateDeserialized(Context, ID);
3088 case DECL_CLASS_SCOPE_FUNCTION_SPECIALIZATION:
3089 D = ClassScopeFunctionSpecializationDecl::CreateDeserialized(Context, ID);
3091 case DECL_FUNCTION_TEMPLATE:
3092 D = FunctionTemplateDecl::CreateDeserialized(Context, ID);
3094 case DECL_TEMPLATE_TYPE_PARM:
3095 D = TemplateTypeParmDecl::CreateDeserialized(Context, ID);
3097 case DECL_NON_TYPE_TEMPLATE_PARM:
3098 D = NonTypeTemplateParmDecl::CreateDeserialized(Context, ID);
3100 case DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK:
3101 D = NonTypeTemplateParmDecl::CreateDeserialized(Context, ID, Record[Idx++]);
3103 case DECL_TEMPLATE_TEMPLATE_PARM:
3104 D = TemplateTemplateParmDecl::CreateDeserialized(Context, ID);
3106 case DECL_EXPANDED_TEMPLATE_TEMPLATE_PARM_PACK:
3107 D = TemplateTemplateParmDecl::CreateDeserialized(Context, ID,
3110 case DECL_TYPE_ALIAS_TEMPLATE:
3111 D = TypeAliasTemplateDecl::CreateDeserialized(Context, ID);
3113 case DECL_STATIC_ASSERT:
3114 D = StaticAssertDecl::CreateDeserialized(Context, ID);
3116 case DECL_OBJC_METHOD:
3117 D = ObjCMethodDecl::CreateDeserialized(Context, ID);
3119 case DECL_OBJC_INTERFACE:
3120 D = ObjCInterfaceDecl::CreateDeserialized(Context, ID);
3122 case DECL_OBJC_IVAR:
3123 D = ObjCIvarDecl::CreateDeserialized(Context, ID);
3125 case DECL_OBJC_PROTOCOL:
3126 D = ObjCProtocolDecl::CreateDeserialized(Context, ID);
3128 case DECL_OBJC_AT_DEFS_FIELD:
3129 D = ObjCAtDefsFieldDecl::CreateDeserialized(Context, ID);
3131 case DECL_OBJC_CATEGORY:
3132 D = ObjCCategoryDecl::CreateDeserialized(Context, ID);
3134 case DECL_OBJC_CATEGORY_IMPL:
3135 D = ObjCCategoryImplDecl::CreateDeserialized(Context, ID);
3137 case DECL_OBJC_IMPLEMENTATION:
3138 D = ObjCImplementationDecl::CreateDeserialized(Context, ID);
3140 case DECL_OBJC_COMPATIBLE_ALIAS:
3141 D = ObjCCompatibleAliasDecl::CreateDeserialized(Context, ID);
3143 case DECL_OBJC_PROPERTY:
3144 D = ObjCPropertyDecl::CreateDeserialized(Context, ID);
3146 case DECL_OBJC_PROPERTY_IMPL:
3147 D = ObjCPropertyImplDecl::CreateDeserialized(Context, ID);
3150 D = FieldDecl::CreateDeserialized(Context, ID);
3152 case DECL_INDIRECTFIELD:
3153 D = IndirectFieldDecl::CreateDeserialized(Context, ID);
3156 D = VarDecl::CreateDeserialized(Context, ID);
3158 case DECL_IMPLICIT_PARAM:
3159 D = ImplicitParamDecl::CreateDeserialized(Context, ID);
3162 D = ParmVarDecl::CreateDeserialized(Context, ID);
3164 case DECL_FILE_SCOPE_ASM:
3165 D = FileScopeAsmDecl::CreateDeserialized(Context, ID);
3168 D = BlockDecl::CreateDeserialized(Context, ID);
3170 case DECL_MS_PROPERTY:
3171 D = MSPropertyDecl::CreateDeserialized(Context, ID);
3174 D = CapturedDecl::CreateDeserialized(Context, ID, Record[Idx++]);
3176 case DECL_CXX_BASE_SPECIFIERS:
3177 Error("attempt to read a C++ base-specifier record as a declaration");
3179 case DECL_CXX_CTOR_INITIALIZERS:
3180 Error("attempt to read a C++ ctor initializer record as a declaration");
3183 // Note: last entry of the ImportDecl record is the number of stored source
3185 D = ImportDecl::CreateDeserialized(Context, ID, Record.back());
3187 case DECL_OMP_THREADPRIVATE:
3188 D = OMPThreadPrivateDecl::CreateDeserialized(Context, ID, Record[Idx++]);
3191 D = EmptyDecl::CreateDeserialized(Context, ID);
3195 assert(D && "Unknown declaration reading AST file");
3196 LoadedDecl(Index, D);
3197 // Set the DeclContext before doing any deserialization, to make sure internal
3198 // calls to Decl::getASTContext() by Decl's methods will find the
3199 // TranslationUnitDecl without crashing.
3200 D->setDeclContext(Context.getTranslationUnitDecl());
3203 // If this declaration is also a declaration context, get the
3204 // offsets for its tables of lexical and visible declarations.
3205 if (DeclContext *DC = dyn_cast<DeclContext>(D)) {
3206 // FIXME: This should really be
3207 // DeclContext *LookupDC = DC->getPrimaryContext();
3208 // but that can walk the redeclaration chain, which might not work yet.
3209 DeclContext *LookupDC = DC;
3210 if (isa<NamespaceDecl>(DC))
3211 LookupDC = DC->getPrimaryContext();
3212 std::pair<uint64_t, uint64_t> Offsets = Reader.VisitDeclContext(DC);
3213 if (Offsets.first || Offsets.second) {
3214 if (Offsets.first != 0)
3215 DC->setHasExternalLexicalStorage(true);
3216 if (Offsets.second != 0)
3217 LookupDC->setHasExternalVisibleStorage(true);
3218 if (ReadDeclContextStorage(*Loc.F, DeclsCursor, Offsets,
3219 Loc.F->DeclContextInfos[DC]))
3223 // Now add the pending visible updates for this decl context, if it has any.
3224 DeclContextVisibleUpdatesPending::iterator I =
3225 PendingVisibleUpdates.find(ID);
3226 if (I != PendingVisibleUpdates.end()) {
3227 // There are updates. This means the context has external visible
3228 // storage, even if the original stored version didn't.
3229 LookupDC->setHasExternalVisibleStorage(true);
3230 for (const auto &Update : I->second) {
3231 DeclContextInfo &Info = Update.second->DeclContextInfos[DC];
3232 delete Info.NameLookupTableData;
3233 Info.NameLookupTableData = Update.first;
3235 PendingVisibleUpdates.erase(I);
3238 assert(Idx == Record.size());
3240 // Load any relevant update records.
3241 PendingUpdateRecords.push_back(std::make_pair(ID, D));
3243 // Load the categories after recursive loading is finished.
3244 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3245 if (Class->isThisDeclarationADefinition())
3246 loadObjCCategories(ID, Class);
3248 // If we have deserialized a declaration that has a definition the
3249 // AST consumer might need to know about, queue it.
3250 // We don't pass it to the consumer immediately because we may be in recursive
3251 // loading, and some declarations may still be initializing.
3252 if (isConsumerInterestedIn(D, Reader.hasPendingBody()))
3253 InterestingDecls.push_back(D);
3258 void ASTReader::loadDeclUpdateRecords(serialization::DeclID ID, Decl *D) {
3259 // The declaration may have been modified by files later in the chain.
3260 // If this is the case, read the record containing the updates from each file
3261 // and pass it to ASTDeclReader to make the modifications.
3262 DeclUpdateOffsetsMap::iterator UpdI = DeclUpdateOffsets.find(ID);
3263 if (UpdI != DeclUpdateOffsets.end()) {
3264 FileOffsetsTy &UpdateOffsets = UpdI->second;
3265 bool WasInteresting = isConsumerInterestedIn(D, false);
3266 for (FileOffsetsTy::iterator
3267 I = UpdateOffsets.begin(), E = UpdateOffsets.end(); I != E; ++I) {
3268 ModuleFile *F = I->first;
3269 uint64_t Offset = I->second;
3270 llvm::BitstreamCursor &Cursor = F->DeclsCursor;
3271 SavedStreamPosition SavedPosition(Cursor);
3272 Cursor.JumpToBit(Offset);
3274 unsigned Code = Cursor.ReadCode();
3275 unsigned RecCode = Cursor.readRecord(Code, Record);
3277 assert(RecCode == DECL_UPDATES && "Expected DECL_UPDATES record!");
3280 ASTDeclReader Reader(*this, *F, ID, 0, Record, Idx);
3281 Reader.UpdateDecl(D, *F, Record);
3283 // We might have made this declaration interesting. If so, remember that
3284 // we need to hand it off to the consumer.
3285 if (!WasInteresting &&
3286 isConsumerInterestedIn(D, Reader.hasPendingBody())) {
3287 InterestingDecls.push_back(D);
3288 WasInteresting = true;
3295 /// \brief Module visitor class that finds all of the redeclarations of a
3296 /// redeclarable declaration.
3297 class RedeclChainVisitor {
3299 SmallVectorImpl<DeclID> &SearchDecls;
3300 llvm::SmallPtrSetImpl<Decl *> &Deserialized;
3301 GlobalDeclID CanonID;
3302 SmallVector<Decl *, 4> Chain;
3305 RedeclChainVisitor(ASTReader &Reader, SmallVectorImpl<DeclID> &SearchDecls,
3306 llvm::SmallPtrSetImpl<Decl *> &Deserialized,
3307 GlobalDeclID CanonID)
3308 : Reader(Reader), SearchDecls(SearchDecls), Deserialized(Deserialized),
3310 // Ensure that the canonical ID goes at the start of the chain.
3311 addToChain(Reader.GetDecl(CanonID));
3314 static ModuleManager::DFSPreorderControl
3315 visitPreorder(ModuleFile &M, void *UserData) {
3316 return static_cast<RedeclChainVisitor *>(UserData)->visitPreorder(M);
3319 static bool visitPostorder(ModuleFile &M, void *UserData) {
3320 return static_cast<RedeclChainVisitor *>(UserData)->visitPostorder(M);
3323 void addToChain(Decl *D) {
3327 if (Deserialized.erase(D))
3331 void searchForID(ModuleFile &M, GlobalDeclID GlobalID) {
3332 // Map global ID of the first declaration down to the local ID
3333 // used in this module file.
3334 DeclID ID = Reader.mapGlobalIDToModuleFileGlobalID(M, GlobalID);
3338 // If the search decl was from this module, add it to the chain before any
3339 // of its redeclarations in this module or users of it, and after any from
3340 // imported modules.
3341 if (CanonID != GlobalID && Reader.isDeclIDFromModule(GlobalID, M))
3342 addToChain(Reader.GetDecl(GlobalID));
3344 // Perform a binary search to find the local redeclarations for this
3345 // declaration (if any).
3346 const LocalRedeclarationsInfo Compare = { ID, 0 };
3347 const LocalRedeclarationsInfo *Result
3348 = std::lower_bound(M.RedeclarationsMap,
3349 M.RedeclarationsMap + M.LocalNumRedeclarationsInMap,
3351 if (Result == M.RedeclarationsMap + M.LocalNumRedeclarationsInMap ||
3352 Result->FirstID != ID) {
3353 // If we have a previously-canonical singleton declaration that was
3354 // merged into another redeclaration chain, create a trivial chain
3355 // for this single declaration so that it will get wired into the
3356 // complete redeclaration chain.
3357 if (GlobalID != CanonID &&
3358 GlobalID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
3359 GlobalID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls) {
3360 addToChain(Reader.GetDecl(GlobalID));
3366 // Dig out all of the redeclarations.
3367 unsigned Offset = Result->Offset;
3368 unsigned N = M.RedeclarationChains[Offset];
3369 M.RedeclarationChains[Offset++] = 0; // Don't try to deserialize again
3370 for (unsigned I = 0; I != N; ++I)
3371 addToChain(Reader.GetLocalDecl(M, M.RedeclarationChains[Offset++]));
3374 bool needsToVisitImports(ModuleFile &M, GlobalDeclID GlobalID) {
3375 DeclID ID = Reader.mapGlobalIDToModuleFileGlobalID(M, GlobalID);
3379 const LocalRedeclarationsInfo Compare = {ID, 0};
3380 const LocalRedeclarationsInfo *Result = std::lower_bound(
3381 M.RedeclarationsMap,
3382 M.RedeclarationsMap + M.LocalNumRedeclarationsInMap, Compare);
3383 if (Result == M.RedeclarationsMap + M.LocalNumRedeclarationsInMap ||
3384 Result->FirstID != ID) {
3387 unsigned Offset = Result->Offset;
3388 unsigned N = M.RedeclarationChains[Offset];
3389 // We don't need to visit a module or any of its imports if we've already
3390 // deserialized the redecls from this module.
3394 ModuleManager::DFSPreorderControl visitPreorder(ModuleFile &M) {
3395 for (unsigned I = 0, N = SearchDecls.size(); I != N; ++I) {
3396 if (needsToVisitImports(M, SearchDecls[I]))
3397 return ModuleManager::Continue;
3399 return ModuleManager::SkipImports;
3402 bool visitPostorder(ModuleFile &M) {
3403 // Visit each of the declarations.
3404 for (unsigned I = 0, N = SearchDecls.size(); I != N; ++I)
3405 searchForID(M, SearchDecls[I]);
3406 // FIXME: If none of the SearchDecls had local IDs in this module, can
3407 // we avoid searching any ancestor module files?
3411 ArrayRef<Decl *> getChain() const {
3417 void ASTReader::loadPendingDeclChain(Decl *CanonDecl) {
3418 // The decl might have been merged into something else after being added to
3419 // our list. If it was, just skip it.
3420 if (!CanonDecl->isCanonicalDecl())
3423 // Determine the set of declaration IDs we'll be searching for.
3424 SmallVector<DeclID, 16> SearchDecls;
3425 GlobalDeclID CanonID = CanonDecl->getGlobalID();
3427 SearchDecls.push_back(CanonDecl->getGlobalID()); // Always first.
3428 MergedDeclsMap::iterator MergedPos = MergedDecls.find(CanonDecl);
3429 if (MergedPos != MergedDecls.end())
3430 SearchDecls.append(MergedPos->second.begin(), MergedPos->second.end());
3432 // Build up the list of redeclarations.
3433 RedeclChainVisitor Visitor(*this, SearchDecls, RedeclsDeserialized, CanonID);
3434 ModuleMgr.visitDepthFirst(&RedeclChainVisitor::visitPreorder,
3435 &RedeclChainVisitor::visitPostorder, &Visitor);
3437 // Retrieve the chains.
3438 ArrayRef<Decl *> Chain = Visitor.getChain();
3439 if (Chain.empty() || (Chain.size() == 1 && Chain[0] == CanonDecl))
3442 // Hook up the chains.
3444 // FIXME: We have three different dispatches on decl kind here; maybe
3445 // we should instead generate one loop per kind and dispatch up-front?
3446 Decl *MostRecent = ASTDeclReader::getMostRecentDecl(CanonDecl);
3448 MostRecent = CanonDecl;
3449 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
3450 if (Chain[I] == CanonDecl)
3453 ASTDeclReader::attachPreviousDecl(*this, Chain[I], MostRecent, CanonDecl);
3454 MostRecent = Chain[I];
3456 ASTDeclReader::attachLatestDecl(CanonDecl, MostRecent);
3460 /// \brief Given an ObjC interface, goes through the modules and links to the
3461 /// interface all the categories for it.
3462 class ObjCCategoriesVisitor {
3464 serialization::GlobalDeclID InterfaceID;
3465 ObjCInterfaceDecl *Interface;
3466 llvm::SmallPtrSetImpl<ObjCCategoryDecl *> &Deserialized;
3467 unsigned PreviousGeneration;
3468 ObjCCategoryDecl *Tail;
3469 llvm::DenseMap<DeclarationName, ObjCCategoryDecl *> NameCategoryMap;
3471 void add(ObjCCategoryDecl *Cat) {
3472 // Only process each category once.
3473 if (!Deserialized.erase(Cat))
3476 // Check for duplicate categories.
3477 if (Cat->getDeclName()) {
3478 ObjCCategoryDecl *&Existing = NameCategoryMap[Cat->getDeclName()];
3480 Reader.getOwningModuleFile(Existing)
3481 != Reader.getOwningModuleFile(Cat)) {
3482 // FIXME: We should not warn for duplicates in diamond:
3490 // If there are duplicates in ML/MR, there will be warning when
3491 // creating MB *and* when importing MB. We should not warn when
3493 Reader.Diag(Cat->getLocation(), diag::warn_dup_category_def)
3494 << Interface->getDeclName() << Cat->getDeclName();
3495 Reader.Diag(Existing->getLocation(), diag::note_previous_definition);
3496 } else if (!Existing) {
3497 // Record this category.
3502 // Add this category to the end of the chain.
3504 ASTDeclReader::setNextObjCCategory(Tail, Cat);
3506 Interface->setCategoryListRaw(Cat);
3511 ObjCCategoriesVisitor(ASTReader &Reader,
3512 serialization::GlobalDeclID InterfaceID,
3513 ObjCInterfaceDecl *Interface,
3514 llvm::SmallPtrSetImpl<ObjCCategoryDecl *> &Deserialized,
3515 unsigned PreviousGeneration)
3516 : Reader(Reader), InterfaceID(InterfaceID), Interface(Interface),
3517 Deserialized(Deserialized), PreviousGeneration(PreviousGeneration),
3520 // Populate the name -> category map with the set of known categories.
3521 for (auto *Cat : Interface->known_categories()) {
3522 if (Cat->getDeclName())
3523 NameCategoryMap[Cat->getDeclName()] = Cat;
3525 // Keep track of the tail of the category list.
3530 static bool visit(ModuleFile &M, void *UserData) {
3531 return static_cast<ObjCCategoriesVisitor *>(UserData)->visit(M);
3534 bool visit(ModuleFile &M) {
3535 // If we've loaded all of the category information we care about from
3536 // this module file, we're done.
3537 if (M.Generation <= PreviousGeneration)
3540 // Map global ID of the definition down to the local ID used in this
3541 // module file. If there is no such mapping, we'll find nothing here
3542 // (or in any module it imports).
3543 DeclID LocalID = Reader.mapGlobalIDToModuleFileGlobalID(M, InterfaceID);
3547 // Perform a binary search to find the local redeclarations for this
3548 // declaration (if any).
3549 const ObjCCategoriesInfo Compare = { LocalID, 0 };
3550 const ObjCCategoriesInfo *Result
3551 = std::lower_bound(M.ObjCCategoriesMap,
3552 M.ObjCCategoriesMap + M.LocalNumObjCCategoriesInMap,
3554 if (Result == M.ObjCCategoriesMap + M.LocalNumObjCCategoriesInMap ||
3555 Result->DefinitionID != LocalID) {
3556 // We didn't find anything. If the class definition is in this module
3557 // file, then the module files it depends on cannot have any categories,
3558 // so suppress further lookup.
3559 return Reader.isDeclIDFromModule(InterfaceID, M);
3562 // We found something. Dig out all of the categories.
3563 unsigned Offset = Result->Offset;
3564 unsigned N = M.ObjCCategories[Offset];
3565 M.ObjCCategories[Offset++] = 0; // Don't try to deserialize again
3566 for (unsigned I = 0; I != N; ++I)
3567 add(cast_or_null<ObjCCategoryDecl>(
3568 Reader.GetLocalDecl(M, M.ObjCCategories[Offset++])));
3574 void ASTReader::loadObjCCategories(serialization::GlobalDeclID ID,
3575 ObjCInterfaceDecl *D,
3576 unsigned PreviousGeneration) {
3577 ObjCCategoriesVisitor Visitor(*this, ID, D, CategoriesDeserialized,
3578 PreviousGeneration);
3579 ModuleMgr.visit(ObjCCategoriesVisitor::visit, &Visitor);
3583 /// Iterator over the redeclarations of a declaration that have already
3584 /// been merged into the same redeclaration chain.
3585 template<typename DeclT>
3586 class MergedRedeclIterator {
3587 DeclT *Start, *Canonical, *Current;
3589 MergedRedeclIterator() : Current(nullptr) {}
3590 MergedRedeclIterator(DeclT *Start)
3591 : Start(Start), Canonical(nullptr), Current(Start) {}
3593 DeclT *operator*() { return Current; }
3595 MergedRedeclIterator &operator++() {
3596 if (Current->isFirstDecl()) {
3597 Canonical = Current;
3598 Current = Current->getMostRecentDecl();
3600 Current = Current->getPreviousDecl();
3602 // If we started in the merged portion, we'll reach our start position
3603 // eventually. Otherwise, we'll never reach it, but the second declaration
3604 // we reached was the canonical declaration, so stop when we see that one
3606 if (Current == Start || Current == Canonical)
3611 friend bool operator!=(const MergedRedeclIterator &A,
3612 const MergedRedeclIterator &B) {
3613 return A.Current != B.Current;
3617 template<typename DeclT>
3618 llvm::iterator_range<MergedRedeclIterator<DeclT>> merged_redecls(DeclT *D) {
3619 return llvm::iterator_range<MergedRedeclIterator<DeclT>>(
3620 MergedRedeclIterator<DeclT>(D),
3621 MergedRedeclIterator<DeclT>());
3624 template<typename DeclT, typename Fn>
3625 static void forAllLaterRedecls(DeclT *D, Fn F) {
3628 // Check whether we've already merged D into its redeclaration chain.
3629 // MostRecent may or may not be nullptr if D has not been merged. If
3630 // not, walk the merged redecl chain and see if it's there.
3631 auto *MostRecent = D->getMostRecentDecl();
3633 for (auto *Redecl = MostRecent; Redecl && !Found;
3634 Redecl = Redecl->getPreviousDecl())
3635 Found = (Redecl == D);
3637 // If this declaration is merged, apply the functor to all later decls.
3639 for (auto *Redecl = MostRecent; Redecl != D;
3640 Redecl = Redecl->getPreviousDecl())
3645 void ASTDeclReader::UpdateDecl(Decl *D, ModuleFile &ModuleFile,
3646 const RecordData &Record) {
3647 while (Idx < Record.size()) {
3648 switch ((DeclUpdateKind)Record[Idx++]) {
3649 case UPD_CXX_ADDED_IMPLICIT_MEMBER: {
3650 auto *RD = cast<CXXRecordDecl>(D);
3651 // FIXME: If we also have an update record for instantiating the
3652 // definition of D, we need that to happen before we get here.
3653 Decl *MD = Reader.ReadDecl(ModuleFile, Record, Idx);
3654 assert(MD && "couldn't read decl from update record");
3655 // FIXME: We should call addHiddenDecl instead, to add the member
3656 // to its DeclContext.
3657 RD->addedMember(MD);
3659 // If we've added a new special member to a class definition that is not
3660 // the canonical definition, then we need special member lookups in the
3661 // canonical definition to also look into our class.
3662 auto *DD = RD->DefinitionData.getNotUpdated();
3663 if (DD && DD->Definition != RD) {
3664 auto &Merged = Reader.MergedLookups[DD->Definition];
3665 // FIXME: Avoid the linear-time scan here.
3666 if (std::find(Merged.begin(), Merged.end(), RD) == Merged.end())
3667 Merged.push_back(RD);
3672 case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
3673 // It will be added to the template's specializations set when loaded.
3674 (void)Reader.ReadDecl(ModuleFile, Record, Idx);
3677 case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE: {
3679 = Reader.ReadDeclAs<NamespaceDecl>(ModuleFile, Record, Idx);
3681 // Each module has its own anonymous namespace, which is disjoint from
3682 // any other module's anonymous namespaces, so don't attach the anonymous
3683 // namespace at all.
3684 if (ModuleFile.Kind != MK_ImplicitModule &&
3685 ModuleFile.Kind != MK_ExplicitModule) {
3686 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(D))
3687 TU->setAnonymousNamespace(Anon);
3689 cast<NamespaceDecl>(D)->setAnonymousNamespace(Anon);
3694 case UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER:
3695 cast<VarDecl>(D)->getMemberSpecializationInfo()->setPointOfInstantiation(
3696 Reader.ReadSourceLocation(ModuleFile, Record, Idx));
3699 case UPD_CXX_ADDED_FUNCTION_DEFINITION: {
3700 FunctionDecl *FD = cast<FunctionDecl>(D);
3701 if (Reader.PendingBodies[FD]) {
3702 // FIXME: Maybe check for ODR violations.
3703 // It's safe to stop now because this update record is always last.
3707 if (Record[Idx++]) {
3708 // Maintain AST consistency: any later redeclarations of this function
3709 // are inline if this one is. (We might have merged another declaration
3711 forAllLaterRedecls(FD, [](FunctionDecl *FD) {
3712 FD->setImplicitlyInline();
3715 FD->setInnerLocStart(Reader.ReadSourceLocation(ModuleFile, Record, Idx));
3716 if (auto *CD = dyn_cast<CXXConstructorDecl>(FD)) {
3717 CD->NumCtorInitializers = Record[Idx++];
3718 if (CD->NumCtorInitializers)
3719 CD->CtorInitializers =
3720 Reader.ReadCXXCtorInitializersRef(F, Record, Idx);
3722 // Store the offset of the body so we can lazily load it later.
3723 Reader.PendingBodies[FD] = GetCurrentCursorOffset();
3724 HasPendingBody = true;
3725 assert(Idx == Record.size() && "lazy body must be last");
3729 case UPD_CXX_INSTANTIATED_CLASS_DEFINITION: {
3730 auto *RD = cast<CXXRecordDecl>(D);
3731 auto *OldDD = RD->DefinitionData.getNotUpdated();
3732 bool HadRealDefinition =
3733 OldDD && (OldDD->Definition != RD ||
3734 !Reader.PendingFakeDefinitionData.count(OldDD));
3735 ReadCXXRecordDefinition(RD, /*Update*/true);
3737 // Visible update is handled separately.
3738 uint64_t LexicalOffset = Record[Idx++];
3739 if (!HadRealDefinition && LexicalOffset) {
3740 RD->setHasExternalLexicalStorage(true);
3741 Reader.ReadDeclContextStorage(ModuleFile, ModuleFile.DeclsCursor,
3742 std::make_pair(LexicalOffset, 0),
3743 ModuleFile.DeclContextInfos[RD]);
3744 Reader.PendingFakeDefinitionData.erase(OldDD);
3747 auto TSK = (TemplateSpecializationKind)Record[Idx++];
3748 SourceLocation POI = Reader.ReadSourceLocation(ModuleFile, Record, Idx);
3749 if (MemberSpecializationInfo *MSInfo =
3750 RD->getMemberSpecializationInfo()) {
3751 MSInfo->setTemplateSpecializationKind(TSK);
3752 MSInfo->setPointOfInstantiation(POI);
3754 ClassTemplateSpecializationDecl *Spec =
3755 cast<ClassTemplateSpecializationDecl>(RD);
3756 Spec->setTemplateSpecializationKind(TSK);
3757 Spec->setPointOfInstantiation(POI);
3759 if (Record[Idx++]) {
3761 ReadDeclAs<ClassTemplatePartialSpecializationDecl>(Record, Idx);
3762 SmallVector<TemplateArgument, 8> TemplArgs;
3763 Reader.ReadTemplateArgumentList(TemplArgs, F, Record, Idx);
3764 auto *TemplArgList = TemplateArgumentList::CreateCopy(
3765 Reader.getContext(), TemplArgs.data(), TemplArgs.size());
3767 // FIXME: If we already have a partial specialization set,
3768 // check that it matches.
3769 if (!Spec->getSpecializedTemplateOrPartial()
3770 .is<ClassTemplatePartialSpecializationDecl *>())
3771 Spec->setInstantiationOf(PartialSpec, TemplArgList);
3775 RD->setTagKind((TagTypeKind)Record[Idx++]);
3776 RD->setLocation(Reader.ReadSourceLocation(ModuleFile, Record, Idx));
3777 RD->setLocStart(Reader.ReadSourceLocation(ModuleFile, Record, Idx));
3778 RD->setRBraceLoc(Reader.ReadSourceLocation(ModuleFile, Record, Idx));
3780 if (Record[Idx++]) {
3782 Reader.ReadAttributes(F, Attrs, Record, Idx);
3783 D->setAttrsImpl(Attrs, Reader.getContext());
3788 case UPD_CXX_RESOLVED_DTOR_DELETE: {
3789 // Set the 'operator delete' directly to avoid emitting another update
3791 auto *Del = Reader.ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
3792 auto *First = cast<CXXDestructorDecl>(D->getCanonicalDecl());
3793 // FIXME: Check consistency if we have an old and new operator delete.
3794 if (!First->OperatorDelete)
3795 First->OperatorDelete = Del;
3799 case UPD_CXX_RESOLVED_EXCEPTION_SPEC: {
3800 FunctionProtoType::ExceptionSpecInfo ESI;
3801 SmallVector<QualType, 8> ExceptionStorage;
3802 Reader.readExceptionSpec(ModuleFile, ExceptionStorage, ESI, Record, Idx);
3804 // Update this declaration's exception specification, if needed.
3805 auto *FD = cast<FunctionDecl>(D);
3806 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
3807 // FIXME: If the exception specification is already present, check that it
3809 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
3810 FD->setType(Reader.Context.getFunctionType(
3811 FPT->getReturnType(), FPT->getParamTypes(),
3812 FPT->getExtProtoInfo().withExceptionSpec(ESI)));
3814 // When we get to the end of deserializing, see if there are other decls
3815 // that we need to propagate this exception specification onto.
3816 Reader.PendingExceptionSpecUpdates.insert(
3817 std::make_pair(FD->getCanonicalDecl(), FD));
3822 case UPD_CXX_DEDUCED_RETURN_TYPE: {
3823 // FIXME: Also do this when merging redecls.
3824 QualType DeducedResultType = Reader.readType(ModuleFile, Record, Idx);
3825 for (auto *Redecl : merged_redecls(D)) {
3826 // FIXME: If the return type is already deduced, check that it matches.
3827 FunctionDecl *FD = cast<FunctionDecl>(Redecl);
3828 Reader.Context.adjustDeducedFunctionResultType(FD, DeducedResultType);
3833 case UPD_DECL_MARKED_USED: {
3834 // FIXME: This doesn't send the right notifications if there are
3835 // ASTMutationListeners other than an ASTWriter.
3837 // Maintain AST consistency: any later redeclarations are used too.
3838 forAllLaterRedecls(D, [](Decl *D) { D->Used = true; });
3842 case UPD_MANGLING_NUMBER:
3843 Reader.Context.setManglingNumber(cast<NamedDecl>(D), Record[Idx++]);
3846 case UPD_STATIC_LOCAL_NUMBER:
3847 Reader.Context.setStaticLocalNumber(cast<VarDecl>(D), Record[Idx++]);
3850 case UPD_DECL_MARKED_OPENMP_THREADPRIVATE:
3851 D->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
3852 Reader.Context, ReadSourceRange(Record, Idx)));
3855 case UPD_DECL_EXPORTED:
3856 unsigned SubmoduleID = readSubmoduleID(Record, Idx);
3857 Module *Owner = SubmoduleID ? Reader.getSubmodule(SubmoduleID) : nullptr;
3858 if (Reader.getContext().getLangOpts().ModulesLocalVisibility) {
3859 // FIXME: This doesn't send the right notifications if there are
3860 // ASTMutationListeners other than an ASTWriter.
3861 Reader.getContext().mergeDefinitionIntoModule(cast<NamedDecl>(D), Owner,
3862 /*NotifyListeners*/false);
3863 Reader.PendingMergedDefinitionsToDeduplicate.insert(cast<NamedDecl>(D));
3864 } else if (Owner && Owner->NameVisibility != Module::AllVisible) {
3865 // If Owner is made visible at some later point, make this declaration
3867 Reader.HiddenNamesMap[Owner].push_back(D);
3869 // The declaration is now visible.