1//===- DeclCXX.cpp - C++ Declaration AST Node Implementation --------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the C++ related Decl classes.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/AST/DeclCXX.h"
14#include "clang/AST/ASTContext.h"
15#include "clang/AST/ASTLambda.h"
16#include "clang/AST/ASTMutationListener.h"
17#include "clang/AST/ASTUnresolvedSet.h"
18#include "clang/AST/Attr.h"
19#include "clang/AST/CXXInheritance.h"
20#include "clang/AST/DeclBase.h"
21#include "clang/AST/DeclTemplate.h"
22#include "clang/AST/DeclarationName.h"
23#include "clang/AST/Expr.h"
24#include "clang/AST/ExprCXX.h"
25#include "clang/AST/LambdaCapture.h"
26#include "clang/AST/NestedNameSpecifier.h"
27#include "clang/AST/ODRHash.h"
28#include "clang/AST/Type.h"
29#include "clang/AST/TypeLoc.h"
30#include "clang/AST/UnresolvedSet.h"
31#include "clang/Basic/Diagnostic.h"
32#include "clang/Basic/DiagnosticAST.h"
33#include "clang/Basic/IdentifierTable.h"
34#include "clang/Basic/LLVM.h"
35#include "clang/Basic/LangOptions.h"
36#include "clang/Basic/OperatorKinds.h"
37#include "clang/Basic/SourceLocation.h"
38#include "clang/Basic/Specifiers.h"
39#include "clang/Basic/TargetInfo.h"
40#include "llvm/ADT/SmallPtrSet.h"
41#include "llvm/ADT/SmallVector.h"
42#include "llvm/ADT/iterator_range.h"
43#include "llvm/Support/Casting.h"
44#include "llvm/Support/ErrorHandling.h"
45#include "llvm/Support/Format.h"
46#include "llvm/Support/raw_ostream.h"
47#include <algorithm>
48#include <cassert>
49#include <cstddef>
50#include <cstdint>
51
52using namespace clang;
53
54//===----------------------------------------------------------------------===//
55// Decl Allocation/Deallocation Method Implementations
56//===----------------------------------------------------------------------===//
57
58void AccessSpecDecl::anchor() {}
59
60AccessSpecDecl *AccessSpecDecl::CreateDeserialized(ASTContext &C,
61 GlobalDeclID ID) {
62 return new (C, ID) AccessSpecDecl(EmptyShell());
63}
64
65void LazyASTUnresolvedSet::getFromExternalSource(ASTContext &C) const {
66 ExternalASTSource *Source = C.getExternalSource();
67 assert(Impl.Decls.isLazy() && "getFromExternalSource for non-lazy set");
68 assert(Source && "getFromExternalSource with no external source");
69
70 for (ASTUnresolvedSet::iterator I = Impl.begin(); I != Impl.end(); ++I)
71 I.setDecl(
72 cast<NamedDecl>(Val: Source->GetExternalDecl(ID: GlobalDeclID(I.getDeclID()))));
73 Impl.Decls.setLazy(false);
74}
75
76CXXRecordDecl::DefinitionData::DefinitionData(CXXRecordDecl *D)
77 : UserDeclaredConstructor(false), UserDeclaredSpecialMembers(0),
78 Aggregate(true), PlainOldData(true), Empty(true), Polymorphic(false),
79 Abstract(false), IsStandardLayout(true), IsCXX11StandardLayout(true),
80 HasBasesWithFields(false), HasBasesWithNonStaticDataMembers(false),
81 HasPrivateFields(false), HasProtectedFields(false),
82 HasPublicFields(false), HasMutableFields(false), HasVariantMembers(false),
83 HasOnlyCMembers(true), HasInitMethod(false), HasInClassInitializer(false),
84 HasUninitializedReferenceMember(false), HasUninitializedFields(false),
85 HasInheritedConstructor(false), HasInheritedDefaultConstructor(false),
86 HasInheritedAssignment(false),
87 NeedOverloadResolutionForCopyConstructor(false),
88 NeedOverloadResolutionForMoveConstructor(false),
89 NeedOverloadResolutionForCopyAssignment(false),
90 NeedOverloadResolutionForMoveAssignment(false),
91 NeedOverloadResolutionForDestructor(false),
92 DefaultedCopyConstructorIsDeleted(false),
93 DefaultedMoveConstructorIsDeleted(false),
94 DefaultedCopyAssignmentIsDeleted(false),
95 DefaultedMoveAssignmentIsDeleted(false),
96 DefaultedDestructorIsDeleted(false), HasTrivialSpecialMembers(SMF_All),
97 HasTrivialSpecialMembersForCall(SMF_All),
98 DeclaredNonTrivialSpecialMembers(0),
99 DeclaredNonTrivialSpecialMembersForCall(0), HasIrrelevantDestructor(true),
100 HasConstexprNonCopyMoveConstructor(false),
101 HasDefaultedDefaultConstructor(false),
102 DefaultedDefaultConstructorIsConstexpr(true),
103 HasConstexprDefaultConstructor(false),
104 DefaultedDestructorIsConstexpr(true),
105 HasNonLiteralTypeFieldsOrBases(false), StructuralIfLiteral(true),
106 UserProvidedDefaultConstructor(false), DeclaredSpecialMembers(0),
107 ImplicitCopyConstructorCanHaveConstParamForVBase(true),
108 ImplicitCopyConstructorCanHaveConstParamForNonVBase(true),
109 ImplicitCopyAssignmentHasConstParam(true),
110 HasDeclaredCopyConstructorWithConstParam(false),
111 HasDeclaredCopyAssignmentWithConstParam(false),
112 IsAnyDestructorNoReturn(false), IsHLSLIntangible(false), IsLambda(false),
113 IsParsingBaseSpecifiers(false), ComputedVisibleConversions(false),
114 HasODRHash(false), Definition(D) {}
115
116CXXBaseSpecifier *CXXRecordDecl::DefinitionData::getBasesSlowCase() const {
117 return Bases.get(Source: Definition->getASTContext().getExternalSource());
118}
119
120CXXBaseSpecifier *CXXRecordDecl::DefinitionData::getVBasesSlowCase() const {
121 return VBases.get(Source: Definition->getASTContext().getExternalSource());
122}
123
124CXXRecordDecl::CXXRecordDecl(Kind K, TagKind TK, const ASTContext &C,
125 DeclContext *DC, SourceLocation StartLoc,
126 SourceLocation IdLoc, IdentifierInfo *Id,
127 CXXRecordDecl *PrevDecl)
128 : RecordDecl(K, TK, C, DC, StartLoc, IdLoc, Id, PrevDecl),
129 DefinitionData(PrevDecl ? PrevDecl->DefinitionData
130 : nullptr) {}
131
132CXXRecordDecl *CXXRecordDecl::Create(const ASTContext &C, TagKind TK,
133 DeclContext *DC, SourceLocation StartLoc,
134 SourceLocation IdLoc, IdentifierInfo *Id,
135 CXXRecordDecl *PrevDecl,
136 bool DelayTypeCreation) {
137 auto *R = new (C, DC) CXXRecordDecl(CXXRecord, TK, C, DC, StartLoc, IdLoc, Id,
138 PrevDecl);
139 R->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
140
141 // FIXME: DelayTypeCreation seems like such a hack
142 if (!DelayTypeCreation)
143 C.getTypeDeclType(Decl: R, PrevDecl);
144 return R;
145}
146
147CXXRecordDecl *
148CXXRecordDecl::CreateLambda(const ASTContext &C, DeclContext *DC,
149 TypeSourceInfo *Info, SourceLocation Loc,
150 unsigned DependencyKind, bool IsGeneric,
151 LambdaCaptureDefault CaptureDefault) {
152 auto *R = new (C, DC) CXXRecordDecl(CXXRecord, TagTypeKind::Class, C, DC, Loc,
153 Loc, nullptr, nullptr);
154 R->setBeingDefined(true);
155 R->DefinitionData = new (C) struct LambdaDefinitionData(
156 R, Info, DependencyKind, IsGeneric, CaptureDefault);
157 R->setMayHaveOutOfDateDef(false);
158 R->setImplicit(true);
159
160 C.getTypeDeclType(Decl: R, /*PrevDecl=*/nullptr);
161 return R;
162}
163
164CXXRecordDecl *CXXRecordDecl::CreateDeserialized(const ASTContext &C,
165 GlobalDeclID ID) {
166 auto *R = new (C, ID)
167 CXXRecordDecl(CXXRecord, TagTypeKind::Struct, C, nullptr,
168 SourceLocation(), SourceLocation(), nullptr, nullptr);
169 R->setMayHaveOutOfDateDef(false);
170 return R;
171}
172
173/// Determine whether a class has a repeated base class. This is intended for
174/// use when determining if a class is standard-layout, so makes no attempt to
175/// handle virtual bases.
176static bool hasRepeatedBaseClass(const CXXRecordDecl *StartRD) {
177 llvm::SmallPtrSet<const CXXRecordDecl*, 8> SeenBaseTypes;
178 SmallVector<const CXXRecordDecl*, 8> WorkList = {StartRD};
179 while (!WorkList.empty()) {
180 const CXXRecordDecl *RD = WorkList.pop_back_val();
181 if (RD->getTypeForDecl()->isDependentType())
182 continue;
183 for (const CXXBaseSpecifier &BaseSpec : RD->bases()) {
184 if (const CXXRecordDecl *B = BaseSpec.getType()->getAsCXXRecordDecl()) {
185 if (!SeenBaseTypes.insert(Ptr: B).second)
186 return true;
187 WorkList.push_back(Elt: B);
188 }
189 }
190 }
191 return false;
192}
193
194void
195CXXRecordDecl::setBases(CXXBaseSpecifier const * const *Bases,
196 unsigned NumBases) {
197 ASTContext &C = getASTContext();
198
199 if (!data().Bases.isOffset() && data().NumBases > 0)
200 C.Deallocate(Ptr: data().getBases());
201
202 if (NumBases) {
203 if (!C.getLangOpts().CPlusPlus17) {
204 // C++ [dcl.init.aggr]p1:
205 // An aggregate is [...] a class with [...] no base classes [...].
206 data().Aggregate = false;
207 }
208
209 // C++ [class]p4:
210 // A POD-struct is an aggregate class...
211 data().PlainOldData = false;
212 }
213
214 // The set of seen virtual base types.
215 llvm::SmallPtrSet<CanQualType, 8> SeenVBaseTypes;
216
217 // The virtual bases of this class.
218 SmallVector<const CXXBaseSpecifier *, 8> VBases;
219
220 data().Bases = new(C) CXXBaseSpecifier [NumBases];
221 data().NumBases = NumBases;
222 for (unsigned i = 0; i < NumBases; ++i) {
223 data().getBases()[i] = *Bases[i];
224 // Keep track of inherited vbases for this base class.
225 const CXXBaseSpecifier *Base = Bases[i];
226 QualType BaseType = Base->getType();
227 // Skip dependent types; we can't do any checking on them now.
228 if (BaseType->isDependentType())
229 continue;
230 auto *BaseClassDecl =
231 cast<CXXRecordDecl>(Val: BaseType->castAs<RecordType>()->getDecl());
232
233 // C++2a [class]p7:
234 // A standard-layout class is a class that:
235 // [...]
236 // -- has all non-static data members and bit-fields in the class and
237 // its base classes first declared in the same class
238 if (BaseClassDecl->data().HasBasesWithFields ||
239 !BaseClassDecl->field_empty()) {
240 if (data().HasBasesWithFields)
241 // Two bases have members or bit-fields: not standard-layout.
242 data().IsStandardLayout = false;
243 data().HasBasesWithFields = true;
244 }
245
246 // C++11 [class]p7:
247 // A standard-layout class is a class that:
248 // -- [...] has [...] at most one base class with non-static data
249 // members
250 if (BaseClassDecl->data().HasBasesWithNonStaticDataMembers ||
251 BaseClassDecl->hasDirectFields()) {
252 if (data().HasBasesWithNonStaticDataMembers)
253 data().IsCXX11StandardLayout = false;
254 data().HasBasesWithNonStaticDataMembers = true;
255 }
256
257 if (!BaseClassDecl->isEmpty()) {
258 // C++14 [meta.unary.prop]p4:
259 // T is a class type [...] with [...] no base class B for which
260 // is_empty<B>::value is false.
261 data().Empty = false;
262 }
263
264 // C++1z [dcl.init.agg]p1:
265 // An aggregate is a class with [...] no private or protected base classes
266 if (Base->getAccessSpecifier() != AS_public) {
267 data().Aggregate = false;
268
269 // C++20 [temp.param]p7:
270 // A structural type is [...] a literal class type with [...] all base
271 // classes [...] public
272 data().StructuralIfLiteral = false;
273 }
274
275 // C++ [class.virtual]p1:
276 // A class that declares or inherits a virtual function is called a
277 // polymorphic class.
278 if (BaseClassDecl->isPolymorphic()) {
279 data().Polymorphic = true;
280
281 // An aggregate is a class with [...] no virtual functions.
282 data().Aggregate = false;
283 }
284
285 // C++0x [class]p7:
286 // A standard-layout class is a class that: [...]
287 // -- has no non-standard-layout base classes
288 if (!BaseClassDecl->isStandardLayout())
289 data().IsStandardLayout = false;
290 if (!BaseClassDecl->isCXX11StandardLayout())
291 data().IsCXX11StandardLayout = false;
292
293 // Record if this base is the first non-literal field or base.
294 if (!hasNonLiteralTypeFieldsOrBases() && !BaseType->isLiteralType(Ctx: C))
295 data().HasNonLiteralTypeFieldsOrBases = true;
296
297 // Now go through all virtual bases of this base and add them.
298 for (const auto &VBase : BaseClassDecl->vbases()) {
299 // Add this base if it's not already in the list.
300 if (SeenVBaseTypes.insert(Ptr: C.getCanonicalType(T: VBase.getType())).second) {
301 VBases.push_back(Elt: &VBase);
302
303 // C++11 [class.copy]p8:
304 // The implicitly-declared copy constructor for a class X will have
305 // the form 'X::X(const X&)' if each [...] virtual base class B of X
306 // has a copy constructor whose first parameter is of type
307 // 'const B&' or 'const volatile B&' [...]
308 if (CXXRecordDecl *VBaseDecl = VBase.getType()->getAsCXXRecordDecl())
309 if (!VBaseDecl->hasCopyConstructorWithConstParam())
310 data().ImplicitCopyConstructorCanHaveConstParamForVBase = false;
311
312 // C++1z [dcl.init.agg]p1:
313 // An aggregate is a class with [...] no virtual base classes
314 data().Aggregate = false;
315 }
316 }
317
318 if (Base->isVirtual()) {
319 // Add this base if it's not already in the list.
320 if (SeenVBaseTypes.insert(Ptr: C.getCanonicalType(T: BaseType)).second)
321 VBases.push_back(Elt: Base);
322
323 // C++14 [meta.unary.prop] is_empty:
324 // T is a class type, but not a union type, with ... no virtual base
325 // classes
326 data().Empty = false;
327
328 // C++1z [dcl.init.agg]p1:
329 // An aggregate is a class with [...] no virtual base classes
330 data().Aggregate = false;
331
332 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
333 // A [default constructor, copy/move constructor, or copy/move assignment
334 // operator for a class X] is trivial [...] if:
335 // -- class X has [...] no virtual base classes
336 data().HasTrivialSpecialMembers &= SMF_Destructor;
337 data().HasTrivialSpecialMembersForCall &= SMF_Destructor;
338
339 // C++0x [class]p7:
340 // A standard-layout class is a class that: [...]
341 // -- has [...] no virtual base classes
342 data().IsStandardLayout = false;
343 data().IsCXX11StandardLayout = false;
344
345 // C++20 [dcl.constexpr]p3:
346 // In the definition of a constexpr function [...]
347 // -- if the function is a constructor or destructor,
348 // its class shall not have any virtual base classes
349 data().DefaultedDefaultConstructorIsConstexpr = false;
350 data().DefaultedDestructorIsConstexpr = false;
351
352 // C++1z [class.copy]p8:
353 // The implicitly-declared copy constructor for a class X will have
354 // the form 'X::X(const X&)' if each potentially constructed subobject
355 // has a copy constructor whose first parameter is of type
356 // 'const B&' or 'const volatile B&' [...]
357 if (!BaseClassDecl->hasCopyConstructorWithConstParam())
358 data().ImplicitCopyConstructorCanHaveConstParamForVBase = false;
359 } else {
360 // C++ [class.ctor]p5:
361 // A default constructor is trivial [...] if:
362 // -- all the direct base classes of its class have trivial default
363 // constructors.
364 if (!BaseClassDecl->hasTrivialDefaultConstructor())
365 data().HasTrivialSpecialMembers &= ~SMF_DefaultConstructor;
366
367 // C++0x [class.copy]p13:
368 // A copy/move constructor for class X is trivial if [...]
369 // [...]
370 // -- the constructor selected to copy/move each direct base class
371 // subobject is trivial, and
372 if (!BaseClassDecl->hasTrivialCopyConstructor())
373 data().HasTrivialSpecialMembers &= ~SMF_CopyConstructor;
374
375 if (!BaseClassDecl->hasTrivialCopyConstructorForCall())
376 data().HasTrivialSpecialMembersForCall &= ~SMF_CopyConstructor;
377
378 // If the base class doesn't have a simple move constructor, we'll eagerly
379 // declare it and perform overload resolution to determine which function
380 // it actually calls. If it does have a simple move constructor, this
381 // check is correct.
382 if (!BaseClassDecl->hasTrivialMoveConstructor())
383 data().HasTrivialSpecialMembers &= ~SMF_MoveConstructor;
384
385 if (!BaseClassDecl->hasTrivialMoveConstructorForCall())
386 data().HasTrivialSpecialMembersForCall &= ~SMF_MoveConstructor;
387
388 // C++0x [class.copy]p27:
389 // A copy/move assignment operator for class X is trivial if [...]
390 // [...]
391 // -- the assignment operator selected to copy/move each direct base
392 // class subobject is trivial, and
393 if (!BaseClassDecl->hasTrivialCopyAssignment())
394 data().HasTrivialSpecialMembers &= ~SMF_CopyAssignment;
395 // If the base class doesn't have a simple move assignment, we'll eagerly
396 // declare it and perform overload resolution to determine which function
397 // it actually calls. If it does have a simple move assignment, this
398 // check is correct.
399 if (!BaseClassDecl->hasTrivialMoveAssignment())
400 data().HasTrivialSpecialMembers &= ~SMF_MoveAssignment;
401
402 // C++11 [class.ctor]p6:
403 // If that user-written default constructor would satisfy the
404 // requirements of a constexpr constructor/function(C++23), the
405 // implicitly-defined default constructor is constexpr.
406 if (!BaseClassDecl->hasConstexprDefaultConstructor())
407 data().DefaultedDefaultConstructorIsConstexpr =
408 C.getLangOpts().CPlusPlus23;
409
410 // C++1z [class.copy]p8:
411 // The implicitly-declared copy constructor for a class X will have
412 // the form 'X::X(const X&)' if each potentially constructed subobject
413 // has a copy constructor whose first parameter is of type
414 // 'const B&' or 'const volatile B&' [...]
415 if (!BaseClassDecl->hasCopyConstructorWithConstParam())
416 data().ImplicitCopyConstructorCanHaveConstParamForNonVBase = false;
417 }
418
419 // C++ [class.ctor]p3:
420 // A destructor is trivial if all the direct base classes of its class
421 // have trivial destructors.
422 if (!BaseClassDecl->hasTrivialDestructor())
423 data().HasTrivialSpecialMembers &= ~SMF_Destructor;
424
425 if (!BaseClassDecl->hasTrivialDestructorForCall())
426 data().HasTrivialSpecialMembersForCall &= ~SMF_Destructor;
427
428 if (!BaseClassDecl->hasIrrelevantDestructor())
429 data().HasIrrelevantDestructor = false;
430
431 if (BaseClassDecl->isAnyDestructorNoReturn())
432 data().IsAnyDestructorNoReturn = true;
433
434 if (BaseClassDecl->isHLSLIntangible())
435 data().IsHLSLIntangible = true;
436
437 // C++11 [class.copy]p18:
438 // The implicitly-declared copy assignment operator for a class X will
439 // have the form 'X& X::operator=(const X&)' if each direct base class B
440 // of X has a copy assignment operator whose parameter is of type 'const
441 // B&', 'const volatile B&', or 'B' [...]
442 if (!BaseClassDecl->hasCopyAssignmentWithConstParam())
443 data().ImplicitCopyAssignmentHasConstParam = false;
444
445 // A class has an Objective-C object member if... or any of its bases
446 // has an Objective-C object member.
447 if (BaseClassDecl->hasObjectMember())
448 setHasObjectMember(true);
449
450 if (BaseClassDecl->hasVolatileMember())
451 setHasVolatileMember(true);
452
453 if (BaseClassDecl->getArgPassingRestrictions() ==
454 RecordArgPassingKind::CanNeverPassInRegs)
455 setArgPassingRestrictions(RecordArgPassingKind::CanNeverPassInRegs);
456
457 // Keep track of the presence of mutable fields.
458 if (BaseClassDecl->hasMutableFields())
459 data().HasMutableFields = true;
460
461 if (BaseClassDecl->hasUninitializedExplicitInitFields() &&
462 BaseClassDecl->isAggregate())
463 setHasUninitializedExplicitInitFields(true);
464
465 if (BaseClassDecl->hasUninitializedReferenceMember())
466 data().HasUninitializedReferenceMember = true;
467
468 if (!BaseClassDecl->allowConstDefaultInit())
469 data().HasUninitializedFields = true;
470
471 addedClassSubobject(Base: BaseClassDecl);
472 }
473
474 // C++2a [class]p7:
475 // A class S is a standard-layout class if it:
476 // -- has at most one base class subobject of any given type
477 //
478 // Note that we only need to check this for classes with more than one base
479 // class. If there's only one base class, and it's standard layout, then
480 // we know there are no repeated base classes.
481 if (data().IsStandardLayout && NumBases > 1 && hasRepeatedBaseClass(StartRD: this))
482 data().IsStandardLayout = false;
483
484 if (VBases.empty()) {
485 data().IsParsingBaseSpecifiers = false;
486 return;
487 }
488
489 // Create base specifier for any direct or indirect virtual bases.
490 data().VBases = new (C) CXXBaseSpecifier[VBases.size()];
491 data().NumVBases = VBases.size();
492 for (int I = 0, E = VBases.size(); I != E; ++I) {
493 QualType Type = VBases[I]->getType();
494 if (!Type->isDependentType())
495 addedClassSubobject(Base: Type->getAsCXXRecordDecl());
496 data().getVBases()[I] = *VBases[I];
497 }
498
499 data().IsParsingBaseSpecifiers = false;
500}
501
502unsigned CXXRecordDecl::getODRHash() const {
503 assert(hasDefinition() && "ODRHash only for records with definitions");
504
505 // Previously calculated hash is stored in DefinitionData.
506 if (DefinitionData->HasODRHash)
507 return DefinitionData->ODRHash;
508
509 // Only calculate hash on first call of getODRHash per record.
510 ODRHash Hash;
511 Hash.AddCXXRecordDecl(Record: getDefinition());
512 DefinitionData->HasODRHash = true;
513 DefinitionData->ODRHash = Hash.CalculateHash();
514
515 return DefinitionData->ODRHash;
516}
517
518void CXXRecordDecl::addedClassSubobject(CXXRecordDecl *Subobj) {
519 // C++11 [class.copy]p11:
520 // A defaulted copy/move constructor for a class X is defined as
521 // deleted if X has:
522 // -- a direct or virtual base class B that cannot be copied/moved [...]
523 // -- a non-static data member of class type M (or array thereof)
524 // that cannot be copied or moved [...]
525 if (!Subobj->hasSimpleCopyConstructor())
526 data().NeedOverloadResolutionForCopyConstructor = true;
527 if (!Subobj->hasSimpleMoveConstructor())
528 data().NeedOverloadResolutionForMoveConstructor = true;
529
530 // C++11 [class.copy]p23:
531 // A defaulted copy/move assignment operator for a class X is defined as
532 // deleted if X has:
533 // -- a direct or virtual base class B that cannot be copied/moved [...]
534 // -- a non-static data member of class type M (or array thereof)
535 // that cannot be copied or moved [...]
536 if (!Subobj->hasSimpleCopyAssignment())
537 data().NeedOverloadResolutionForCopyAssignment = true;
538 if (!Subobj->hasSimpleMoveAssignment())
539 data().NeedOverloadResolutionForMoveAssignment = true;
540
541 // C++11 [class.ctor]p5, C++11 [class.copy]p11, C++11 [class.dtor]p5:
542 // A defaulted [ctor or dtor] for a class X is defined as
543 // deleted if X has:
544 // -- any direct or virtual base class [...] has a type with a destructor
545 // that is deleted or inaccessible from the defaulted [ctor or dtor].
546 // -- any non-static data member has a type with a destructor
547 // that is deleted or inaccessible from the defaulted [ctor or dtor].
548 if (!Subobj->hasSimpleDestructor()) {
549 data().NeedOverloadResolutionForCopyConstructor = true;
550 data().NeedOverloadResolutionForMoveConstructor = true;
551 data().NeedOverloadResolutionForDestructor = true;
552 }
553
554 // C++20 [dcl.constexpr]p5:
555 // The definition of a constexpr destructor whose function-body is not
556 // = delete shall additionally satisfy the following requirement:
557 // -- for every subobject of class type or (possibly multi-dimensional)
558 // array thereof, that class type shall have a constexpr destructor
559 if (!Subobj->hasConstexprDestructor())
560 data().DefaultedDestructorIsConstexpr =
561 getASTContext().getLangOpts().CPlusPlus23;
562
563 // C++20 [temp.param]p7:
564 // A structural type is [...] a literal class type [for which] the types
565 // of all base classes and non-static data members are structural types or
566 // (possibly multi-dimensional) array thereof
567 if (!Subobj->data().StructuralIfLiteral)
568 data().StructuralIfLiteral = false;
569}
570
571const CXXRecordDecl *CXXRecordDecl::getStandardLayoutBaseWithFields() const {
572 assert(
573 isStandardLayout() &&
574 "getStandardLayoutBaseWithFields called on a non-standard-layout type");
575#ifdef EXPENSIVE_CHECKS
576 {
577 unsigned NumberOfBasesWithFields = 0;
578 if (!field_empty())
579 ++NumberOfBasesWithFields;
580 llvm::SmallPtrSet<const CXXRecordDecl *, 8> UniqueBases;
581 forallBases([&](const CXXRecordDecl *Base) -> bool {
582 if (!Base->field_empty())
583 ++NumberOfBasesWithFields;
584 assert(
585 UniqueBases.insert(Base->getCanonicalDecl()).second &&
586 "Standard layout struct has multiple base classes of the same type");
587 return true;
588 });
589 assert(NumberOfBasesWithFields <= 1 &&
590 "Standard layout struct has fields declared in more than one class");
591 }
592#endif
593 if (!field_empty())
594 return this;
595 const CXXRecordDecl *Result = this;
596 forallBases(BaseMatches: [&](const CXXRecordDecl *Base) -> bool {
597 if (!Base->field_empty()) {
598 // This is the base where the fields are declared; return early
599 Result = Base;
600 return false;
601 }
602 return true;
603 });
604 return Result;
605}
606
607bool CXXRecordDecl::hasConstexprDestructor() const {
608 auto *Dtor = getDestructor();
609 return Dtor ? Dtor->isConstexpr() : defaultedDestructorIsConstexpr();
610}
611
612bool CXXRecordDecl::hasAnyDependentBases() const {
613 if (!isDependentContext())
614 return false;
615
616 return !forallBases(BaseMatches: [](const CXXRecordDecl *) { return true; });
617}
618
619bool CXXRecordDecl::isTriviallyCopyable() const {
620 // C++0x [class]p5:
621 // A trivially copyable class is a class that:
622 // -- has no non-trivial copy constructors,
623 if (hasNonTrivialCopyConstructor()) return false;
624 // -- has no non-trivial move constructors,
625 if (hasNonTrivialMoveConstructor()) return false;
626 // -- has no non-trivial copy assignment operators,
627 if (hasNonTrivialCopyAssignment()) return false;
628 // -- has no non-trivial move assignment operators, and
629 if (hasNonTrivialMoveAssignment()) return false;
630 // -- has a trivial destructor.
631 if (!hasTrivialDestructor()) return false;
632
633 return true;
634}
635
636bool CXXRecordDecl::isTriviallyCopyConstructible() const {
637
638 // A trivially copy constructible class is a class that:
639 // -- has no non-trivial copy constructors,
640 if (hasNonTrivialCopyConstructor())
641 return false;
642 // -- has a trivial destructor.
643 if (!hasTrivialDestructor())
644 return false;
645
646 return true;
647}
648
649void CXXRecordDecl::markedVirtualFunctionPure() {
650 // C++ [class.abstract]p2:
651 // A class is abstract if it has at least one pure virtual function.
652 data().Abstract = true;
653}
654
655bool CXXRecordDecl::hasSubobjectAtOffsetZeroOfEmptyBaseType(
656 ASTContext &Ctx, const CXXRecordDecl *XFirst) {
657 if (!getNumBases())
658 return false;
659
660 llvm::SmallPtrSet<const CXXRecordDecl*, 8> Bases;
661 llvm::SmallPtrSet<const CXXRecordDecl*, 8> M;
662 SmallVector<const CXXRecordDecl*, 8> WorkList;
663
664 // Visit a type that we have determined is an element of M(S).
665 auto Visit = [&](const CXXRecordDecl *RD) -> bool {
666 RD = RD->getCanonicalDecl();
667
668 // C++2a [class]p8:
669 // A class S is a standard-layout class if it [...] has no element of the
670 // set M(S) of types as a base class.
671 //
672 // If we find a subobject of an empty type, it might also be a base class,
673 // so we'll need to walk the base classes to check.
674 if (!RD->data().HasBasesWithFields) {
675 // Walk the bases the first time, stopping if we find the type. Build a
676 // set of them so we don't need to walk them again.
677 if (Bases.empty()) {
678 bool RDIsBase = !forallBases(BaseMatches: [&](const CXXRecordDecl *Base) -> bool {
679 Base = Base->getCanonicalDecl();
680 if (RD == Base)
681 return false;
682 Bases.insert(Ptr: Base);
683 return true;
684 });
685 if (RDIsBase)
686 return true;
687 } else {
688 if (Bases.count(Ptr: RD))
689 return true;
690 }
691 }
692
693 if (M.insert(Ptr: RD).second)
694 WorkList.push_back(Elt: RD);
695 return false;
696 };
697
698 if (Visit(XFirst))
699 return true;
700
701 while (!WorkList.empty()) {
702 const CXXRecordDecl *X = WorkList.pop_back_val();
703
704 // FIXME: We don't check the bases of X. That matches the standard, but
705 // that sure looks like a wording bug.
706
707 // -- If X is a non-union class type with a non-static data member
708 // [recurse to each field] that is either of zero size or is the
709 // first non-static data member of X
710 // -- If X is a union type, [recurse to union members]
711 bool IsFirstField = true;
712 for (auto *FD : X->fields()) {
713 // FIXME: Should we really care about the type of the first non-static
714 // data member of a non-union if there are preceding unnamed bit-fields?
715 if (FD->isUnnamedBitField())
716 continue;
717
718 if (!IsFirstField && !FD->isZeroSize(Ctx))
719 continue;
720
721 if (FD->isInvalidDecl())
722 continue;
723
724 // -- If X is n array type, [visit the element type]
725 QualType T = Ctx.getBaseElementType(FD->getType());
726 if (auto *RD = T->getAsCXXRecordDecl())
727 if (Visit(RD))
728 return true;
729
730 if (!X->isUnion())
731 IsFirstField = false;
732 }
733 }
734
735 return false;
736}
737
738bool CXXRecordDecl::lambdaIsDefaultConstructibleAndAssignable() const {
739 assert(isLambda() && "not a lambda");
740
741 // C++2a [expr.prim.lambda.capture]p11:
742 // The closure type associated with a lambda-expression has no default
743 // constructor if the lambda-expression has a lambda-capture and a
744 // defaulted default constructor otherwise. It has a deleted copy
745 // assignment operator if the lambda-expression has a lambda-capture and
746 // defaulted copy and move assignment operators otherwise.
747 //
748 // C++17 [expr.prim.lambda]p21:
749 // The closure type associated with a lambda-expression has no default
750 // constructor and a deleted copy assignment operator.
751 if (!isCapturelessLambda())
752 return false;
753 return getASTContext().getLangOpts().CPlusPlus20;
754}
755
756void CXXRecordDecl::addedMember(Decl *D) {
757 if (!D->isImplicit() && !isa<FieldDecl>(Val: D) && !isa<IndirectFieldDecl>(Val: D) &&
758 (!isa<TagDecl>(Val: D) ||
759 cast<TagDecl>(Val: D)->getTagKind() == TagTypeKind::Class ||
760 cast<TagDecl>(Val: D)->getTagKind() == TagTypeKind::Interface))
761 data().HasOnlyCMembers = false;
762
763 // Ignore friends and invalid declarations.
764 if (D->getFriendObjectKind() || D->isInvalidDecl())
765 return;
766
767 auto *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: D);
768 if (FunTmpl)
769 D = FunTmpl->getTemplatedDecl();
770
771 // FIXME: Pass NamedDecl* to addedMember?
772 Decl *DUnderlying = D;
773 if (auto *ND = dyn_cast<NamedDecl>(Val: DUnderlying)) {
774 DUnderlying = ND->getUnderlyingDecl();
775 if (auto *UnderlyingFunTmpl = dyn_cast<FunctionTemplateDecl>(Val: DUnderlying))
776 DUnderlying = UnderlyingFunTmpl->getTemplatedDecl();
777 }
778
779 if (const auto *Method = dyn_cast<CXXMethodDecl>(Val: D)) {
780 if (Method->isVirtual()) {
781 // C++ [dcl.init.aggr]p1:
782 // An aggregate is an array or a class with [...] no virtual functions.
783 data().Aggregate = false;
784
785 // C++ [class]p4:
786 // A POD-struct is an aggregate class...
787 data().PlainOldData = false;
788
789 // C++14 [meta.unary.prop]p4:
790 // T is a class type [...] with [...] no virtual member functions...
791 data().Empty = false;
792
793 // C++ [class.virtual]p1:
794 // A class that declares or inherits a virtual function is called a
795 // polymorphic class.
796 data().Polymorphic = true;
797
798 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
799 // A [default constructor, copy/move constructor, or copy/move
800 // assignment operator for a class X] is trivial [...] if:
801 // -- class X has no virtual functions [...]
802 data().HasTrivialSpecialMembers &= SMF_Destructor;
803 data().HasTrivialSpecialMembersForCall &= SMF_Destructor;
804
805 // C++0x [class]p7:
806 // A standard-layout class is a class that: [...]
807 // -- has no virtual functions
808 data().IsStandardLayout = false;
809 data().IsCXX11StandardLayout = false;
810 }
811 }
812
813 // Notify the listener if an implicit member was added after the definition
814 // was completed.
815 if (!isBeingDefined() && D->isImplicit())
816 if (ASTMutationListener *L = getASTMutationListener())
817 L->AddedCXXImplicitMember(RD: data().Definition, D);
818
819 // The kind of special member this declaration is, if any.
820 unsigned SMKind = 0;
821
822 // Handle constructors.
823 if (const auto *Constructor = dyn_cast<CXXConstructorDecl>(Val: D)) {
824 if (Constructor->isInheritingConstructor()) {
825 // Ignore constructor shadow declarations. They are lazily created and
826 // so shouldn't affect any properties of the class.
827 } else {
828 if (!Constructor->isImplicit()) {
829 // Note that we have a user-declared constructor.
830 data().UserDeclaredConstructor = true;
831
832 const TargetInfo &TI = getASTContext().getTargetInfo();
833 if ((!Constructor->isDeleted() && !Constructor->isDefaulted()) ||
834 !TI.areDefaultedSMFStillPOD(getLangOpts())) {
835 // C++ [class]p4:
836 // A POD-struct is an aggregate class [...]
837 // Since the POD bit is meant to be C++03 POD-ness, clear it even if
838 // the type is technically an aggregate in C++0x since it wouldn't be
839 // in 03.
840 data().PlainOldData = false;
841 }
842 }
843
844 if (Constructor->isDefaultConstructor()) {
845 SMKind |= SMF_DefaultConstructor;
846
847 if (Constructor->isUserProvided())
848 data().UserProvidedDefaultConstructor = true;
849 if (Constructor->isConstexpr())
850 data().HasConstexprDefaultConstructor = true;
851 if (Constructor->isDefaulted())
852 data().HasDefaultedDefaultConstructor = true;
853 }
854
855 if (!FunTmpl) {
856 unsigned Quals;
857 if (Constructor->isCopyConstructor(TypeQuals&: Quals)) {
858 SMKind |= SMF_CopyConstructor;
859
860 if (Quals & Qualifiers::Const)
861 data().HasDeclaredCopyConstructorWithConstParam = true;
862 } else if (Constructor->isMoveConstructor())
863 SMKind |= SMF_MoveConstructor;
864 }
865
866 // C++11 [dcl.init.aggr]p1: DR1518
867 // An aggregate is an array or a class with no user-provided [or]
868 // explicit [...] constructors
869 // C++20 [dcl.init.aggr]p1:
870 // An aggregate is an array or a class with no user-declared [...]
871 // constructors
872 if (getASTContext().getLangOpts().CPlusPlus20
873 ? !Constructor->isImplicit()
874 : (Constructor->isUserProvided() || Constructor->isExplicit()))
875 data().Aggregate = false;
876 }
877 }
878
879 // Handle constructors, including those inherited from base classes.
880 if (const auto *Constructor = dyn_cast<CXXConstructorDecl>(Val: DUnderlying)) {
881 // Record if we see any constexpr constructors which are neither copy
882 // nor move constructors.
883 // C++1z [basic.types]p10:
884 // [...] has at least one constexpr constructor or constructor template
885 // (possibly inherited from a base class) that is not a copy or move
886 // constructor [...]
887 if (Constructor->isConstexpr() && !Constructor->isCopyOrMoveConstructor())
888 data().HasConstexprNonCopyMoveConstructor = true;
889 if (!isa<CXXConstructorDecl>(Val: D) && Constructor->isDefaultConstructor())
890 data().HasInheritedDefaultConstructor = true;
891 }
892
893 // Handle member functions.
894 if (const auto *Method = dyn_cast<CXXMethodDecl>(Val: D)) {
895 if (isa<CXXDestructorDecl>(Val: D))
896 SMKind |= SMF_Destructor;
897
898 if (Method->isCopyAssignmentOperator()) {
899 SMKind |= SMF_CopyAssignment;
900
901 const auto *ParamTy =
902 Method->getNonObjectParameter(0)->getType()->getAs<ReferenceType>();
903 if (!ParamTy || ParamTy->getPointeeType().isConstQualified())
904 data().HasDeclaredCopyAssignmentWithConstParam = true;
905 }
906
907 if (Method->isMoveAssignmentOperator())
908 SMKind |= SMF_MoveAssignment;
909
910 // Keep the list of conversion functions up-to-date.
911 if (auto *Conversion = dyn_cast<CXXConversionDecl>(Val: D)) {
912 // FIXME: We use the 'unsafe' accessor for the access specifier here,
913 // because Sema may not have set it yet. That's really just a misdesign
914 // in Sema. However, LLDB *will* have set the access specifier correctly,
915 // and adds declarations after the class is technically completed,
916 // so completeDefinition()'s overriding of the access specifiers doesn't
917 // work.
918 AccessSpecifier AS = Conversion->getAccessUnsafe();
919
920 if (Conversion->getPrimaryTemplate()) {
921 // We don't record specializations.
922 } else {
923 ASTContext &Ctx = getASTContext();
924 ASTUnresolvedSet &Conversions = data().Conversions.get(C&: Ctx);
925 NamedDecl *Primary =
926 FunTmpl ? cast<NamedDecl>(Val: FunTmpl) : cast<NamedDecl>(Val: Conversion);
927 if (Primary->getPreviousDecl())
928 Conversions.replace(Old: cast<NamedDecl>(Primary->getPreviousDecl()),
929 New: Primary, AS);
930 else
931 Conversions.addDecl(C&: Ctx, D: Primary, AS);
932 }
933 }
934
935 if (SMKind) {
936 // If this is the first declaration of a special member, we no longer have
937 // an implicit trivial special member.
938 data().HasTrivialSpecialMembers &=
939 data().DeclaredSpecialMembers | ~SMKind;
940 data().HasTrivialSpecialMembersForCall &=
941 data().DeclaredSpecialMembers | ~SMKind;
942
943 // Note when we have declared a declared special member, and suppress the
944 // implicit declaration of this special member.
945 data().DeclaredSpecialMembers |= SMKind;
946 if (!Method->isImplicit()) {
947 data().UserDeclaredSpecialMembers |= SMKind;
948
949 const TargetInfo &TI = getASTContext().getTargetInfo();
950 if ((!Method->isDeleted() && !Method->isDefaulted() &&
951 SMKind != SMF_MoveAssignment) ||
952 !TI.areDefaultedSMFStillPOD(getLangOpts())) {
953 // C++03 [class]p4:
954 // A POD-struct is an aggregate class that has [...] no user-defined
955 // copy assignment operator and no user-defined destructor.
956 //
957 // Since the POD bit is meant to be C++03 POD-ness, and in C++03,
958 // aggregates could not have any constructors, clear it even for an
959 // explicitly defaulted or deleted constructor.
960 // type is technically an aggregate in C++0x since it wouldn't be in
961 // 03.
962 //
963 // Also, a user-declared move assignment operator makes a class
964 // non-POD. This is an extension in C++03.
965 data().PlainOldData = false;
966 }
967 }
968 // When instantiating a class, we delay updating the destructor and
969 // triviality properties of the class until selecting a destructor and
970 // computing the eligibility of its special member functions. This is
971 // because there might be function constraints that we need to evaluate
972 // and compare later in the instantiation.
973 if (!Method->isIneligibleOrNotSelected()) {
974 addedEligibleSpecialMemberFunction(MD: Method, SMKind);
975 }
976 }
977
978 return;
979 }
980
981 // Handle non-static data members.
982 if (const auto *Field = dyn_cast<FieldDecl>(Val: D)) {
983 ASTContext &Context = getASTContext();
984
985 // C++2a [class]p7:
986 // A standard-layout class is a class that:
987 // [...]
988 // -- has all non-static data members and bit-fields in the class and
989 // its base classes first declared in the same class
990 if (data().HasBasesWithFields)
991 data().IsStandardLayout = false;
992
993 // C++ [class.bit]p2:
994 // A declaration for a bit-field that omits the identifier declares an
995 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
996 // initialized.
997 if (Field->isUnnamedBitField()) {
998 // C++ [meta.unary.prop]p4: [LWG2358]
999 // T is a class type [...] with [...] no unnamed bit-fields of non-zero
1000 // length
1001 if (data().Empty && !Field->isZeroLengthBitField() &&
1002 Context.getLangOpts().getClangABICompat() >
1003 LangOptions::ClangABI::Ver6)
1004 data().Empty = false;
1005 return;
1006 }
1007
1008 // C++11 [class]p7:
1009 // A standard-layout class is a class that:
1010 // -- either has no non-static data members in the most derived class
1011 // [...] or has no base classes with non-static data members
1012 if (data().HasBasesWithNonStaticDataMembers)
1013 data().IsCXX11StandardLayout = false;
1014
1015 // C++ [dcl.init.aggr]p1:
1016 // An aggregate is an array or a class (clause 9) with [...] no
1017 // private or protected non-static data members (clause 11).
1018 //
1019 // A POD must be an aggregate.
1020 if (D->getAccess() == AS_private || D->getAccess() == AS_protected) {
1021 data().Aggregate = false;
1022 data().PlainOldData = false;
1023
1024 // C++20 [temp.param]p7:
1025 // A structural type is [...] a literal class type [for which] all
1026 // non-static data members are public
1027 data().StructuralIfLiteral = false;
1028 }
1029
1030 // Track whether this is the first field. We use this when checking
1031 // whether the class is standard-layout below.
1032 bool IsFirstField = !data().HasPrivateFields &&
1033 !data().HasProtectedFields && !data().HasPublicFields;
1034
1035 // C++0x [class]p7:
1036 // A standard-layout class is a class that:
1037 // [...]
1038 // -- has the same access control for all non-static data members,
1039 switch (D->getAccess()) {
1040 case AS_private: data().HasPrivateFields = true; break;
1041 case AS_protected: data().HasProtectedFields = true; break;
1042 case AS_public: data().HasPublicFields = true; break;
1043 case AS_none: llvm_unreachable("Invalid access specifier");
1044 };
1045 if ((data().HasPrivateFields + data().HasProtectedFields +
1046 data().HasPublicFields) > 1) {
1047 data().IsStandardLayout = false;
1048 data().IsCXX11StandardLayout = false;
1049 }
1050
1051 // Keep track of the presence of mutable fields.
1052 if (Field->isMutable()) {
1053 data().HasMutableFields = true;
1054
1055 // C++20 [temp.param]p7:
1056 // A structural type is [...] a literal class type [for which] all
1057 // non-static data members are public
1058 data().StructuralIfLiteral = false;
1059 }
1060
1061 // C++11 [class.union]p8, DR1460:
1062 // If X is a union, a non-static data member of X that is not an anonymous
1063 // union is a variant member of X.
1064 if (isUnion() && !Field->isAnonymousStructOrUnion())
1065 data().HasVariantMembers = true;
1066
1067 if (isUnion() && IsFirstField)
1068 data().HasUninitializedFields = true;
1069
1070 // C++0x [class]p9:
1071 // A POD struct is a class that is both a trivial class and a
1072 // standard-layout class, and has no non-static data members of type
1073 // non-POD struct, non-POD union (or array of such types).
1074 //
1075 // Automatic Reference Counting: the presence of a member of Objective-C pointer type
1076 // that does not explicitly have no lifetime makes the class a non-POD.
1077 QualType T = Context.getBaseElementType(Field->getType());
1078 if (T->isObjCRetainableType() || T.isObjCGCStrong()) {
1079 if (T.hasNonTrivialObjCLifetime()) {
1080 // Objective-C Automatic Reference Counting:
1081 // If a class has a non-static data member of Objective-C pointer
1082 // type (or array thereof), it is a non-POD type and its
1083 // default constructor (if any), copy constructor, move constructor,
1084 // copy assignment operator, move assignment operator, and destructor are
1085 // non-trivial.
1086 setHasObjectMember(true);
1087 struct DefinitionData &Data = data();
1088 Data.PlainOldData = false;
1089 Data.HasTrivialSpecialMembers = 0;
1090
1091 // __strong or __weak fields do not make special functions non-trivial
1092 // for the purpose of calls.
1093 Qualifiers::ObjCLifetime LT = T.getQualifiers().getObjCLifetime();
1094 if (LT != Qualifiers::OCL_Strong && LT != Qualifiers::OCL_Weak)
1095 data().HasTrivialSpecialMembersForCall = 0;
1096
1097 // Structs with __weak fields should never be passed directly.
1098 if (LT == Qualifiers::OCL_Weak)
1099 setArgPassingRestrictions(RecordArgPassingKind::CanNeverPassInRegs);
1100
1101 Data.HasIrrelevantDestructor = false;
1102
1103 if (isUnion()) {
1104 data().DefaultedCopyConstructorIsDeleted = true;
1105 data().DefaultedMoveConstructorIsDeleted = true;
1106 data().DefaultedCopyAssignmentIsDeleted = true;
1107 data().DefaultedMoveAssignmentIsDeleted = true;
1108 data().DefaultedDestructorIsDeleted = true;
1109 data().NeedOverloadResolutionForCopyConstructor = true;
1110 data().NeedOverloadResolutionForMoveConstructor = true;
1111 data().NeedOverloadResolutionForCopyAssignment = true;
1112 data().NeedOverloadResolutionForMoveAssignment = true;
1113 data().NeedOverloadResolutionForDestructor = true;
1114 }
1115 } else if (!Context.getLangOpts().ObjCAutoRefCount) {
1116 setHasObjectMember(true);
1117 }
1118 } else if (!T.isCXX98PODType(Context))
1119 data().PlainOldData = false;
1120
1121 // If a class has an address-discriminated signed pointer member, it is a
1122 // non-POD type and its copy constructor, move constructor, copy assignment
1123 // operator, move assignment operator are non-trivial.
1124 if (PointerAuthQualifier Q = T.getPointerAuth()) {
1125 if (Q.isAddressDiscriminated()) {
1126 struct DefinitionData &Data = data();
1127 Data.PlainOldData = false;
1128 Data.HasTrivialSpecialMembers &=
1129 ~(SMF_CopyConstructor | SMF_MoveConstructor | SMF_CopyAssignment |
1130 SMF_MoveAssignment);
1131 setArgPassingRestrictions(RecordArgPassingKind::CanNeverPassInRegs);
1132
1133 // Copy/move constructors/assignment operators of a union are deleted by
1134 // default if it has an address-discriminated ptrauth field.
1135 if (isUnion()) {
1136 data().DefaultedCopyConstructorIsDeleted = true;
1137 data().DefaultedMoveConstructorIsDeleted = true;
1138 data().DefaultedCopyAssignmentIsDeleted = true;
1139 data().DefaultedMoveAssignmentIsDeleted = true;
1140 data().NeedOverloadResolutionForCopyConstructor = true;
1141 data().NeedOverloadResolutionForMoveConstructor = true;
1142 data().NeedOverloadResolutionForCopyAssignment = true;
1143 data().NeedOverloadResolutionForMoveAssignment = true;
1144 }
1145 }
1146 }
1147
1148 if (Field->hasAttr<ExplicitInitAttr>())
1149 setHasUninitializedExplicitInitFields(true);
1150
1151 if (T->isReferenceType()) {
1152 if (!Field->hasInClassInitializer())
1153 data().HasUninitializedReferenceMember = true;
1154
1155 // C++0x [class]p7:
1156 // A standard-layout class is a class that:
1157 // -- has no non-static data members of type [...] reference,
1158 data().IsStandardLayout = false;
1159 data().IsCXX11StandardLayout = false;
1160
1161 // C++1z [class.copy.ctor]p10:
1162 // A defaulted copy constructor for a class X is defined as deleted if X has:
1163 // -- a non-static data member of rvalue reference type
1164 if (T->isRValueReferenceType())
1165 data().DefaultedCopyConstructorIsDeleted = true;
1166 }
1167
1168 if (isUnion() && !Field->isMutable()) {
1169 if (Field->hasInClassInitializer())
1170 data().HasUninitializedFields = false;
1171 } else if (!Field->hasInClassInitializer() && !Field->isMutable()) {
1172 if (CXXRecordDecl *FieldType = T->getAsCXXRecordDecl()) {
1173 if (FieldType->hasDefinition() && !FieldType->allowConstDefaultInit())
1174 data().HasUninitializedFields = true;
1175 } else {
1176 data().HasUninitializedFields = true;
1177 }
1178 }
1179
1180 // Record if this field is the first non-literal or volatile field or base.
1181 if (!T->isLiteralType(Ctx: Context) || T.isVolatileQualified())
1182 data().HasNonLiteralTypeFieldsOrBases = true;
1183
1184 if (Field->hasInClassInitializer() ||
1185 (Field->isAnonymousStructOrUnion() &&
1186 Field->getType()->getAsCXXRecordDecl()->hasInClassInitializer())) {
1187 data().HasInClassInitializer = true;
1188
1189 // C++11 [class]p5:
1190 // A default constructor is trivial if [...] no non-static data member
1191 // of its class has a brace-or-equal-initializer.
1192 data().HasTrivialSpecialMembers &= ~SMF_DefaultConstructor;
1193
1194 // C++11 [dcl.init.aggr]p1:
1195 // An aggregate is a [...] class with [...] no
1196 // brace-or-equal-initializers for non-static data members.
1197 //
1198 // This rule was removed in C++14.
1199 if (!getASTContext().getLangOpts().CPlusPlus14)
1200 data().Aggregate = false;
1201
1202 // C++11 [class]p10:
1203 // A POD struct is [...] a trivial class.
1204 data().PlainOldData = false;
1205 }
1206
1207 // C++11 [class.copy]p23:
1208 // A defaulted copy/move assignment operator for a class X is defined
1209 // as deleted if X has:
1210 // -- a non-static data member of reference type
1211 if (T->isReferenceType()) {
1212 data().DefaultedCopyAssignmentIsDeleted = true;
1213 data().DefaultedMoveAssignmentIsDeleted = true;
1214 }
1215
1216 // Bitfields of length 0 are also zero-sized, but we already bailed out for
1217 // those because they are always unnamed.
1218 bool IsZeroSize = Field->isZeroSize(Ctx: Context);
1219
1220 if (const auto *RecordTy = T->getAs<RecordType>()) {
1221 auto *FieldRec = cast<CXXRecordDecl>(RecordTy->getDecl());
1222 if (FieldRec->getDefinition()) {
1223 addedClassSubobject(Subobj: FieldRec);
1224
1225 // We may need to perform overload resolution to determine whether a
1226 // field can be moved if it's const or volatile qualified.
1227 if (T.getCVRQualifiers() & (Qualifiers::Const | Qualifiers::Volatile)) {
1228 // We need to care about 'const' for the copy constructor because an
1229 // implicit copy constructor might be declared with a non-const
1230 // parameter.
1231 data().NeedOverloadResolutionForCopyConstructor = true;
1232 data().NeedOverloadResolutionForMoveConstructor = true;
1233 data().NeedOverloadResolutionForCopyAssignment = true;
1234 data().NeedOverloadResolutionForMoveAssignment = true;
1235 }
1236
1237 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
1238 // A defaulted [special member] for a class X is defined as
1239 // deleted if:
1240 // -- X is a union-like class that has a variant member with a
1241 // non-trivial [corresponding special member]
1242 if (isUnion()) {
1243 if (FieldRec->hasNonTrivialCopyConstructor())
1244 data().DefaultedCopyConstructorIsDeleted = true;
1245 if (FieldRec->hasNonTrivialMoveConstructor())
1246 data().DefaultedMoveConstructorIsDeleted = true;
1247 if (FieldRec->hasNonTrivialCopyAssignment())
1248 data().DefaultedCopyAssignmentIsDeleted = true;
1249 if (FieldRec->hasNonTrivialMoveAssignment())
1250 data().DefaultedMoveAssignmentIsDeleted = true;
1251 if (FieldRec->hasNonTrivialDestructor()) {
1252 data().DefaultedDestructorIsDeleted = true;
1253 // C++20 [dcl.constexpr]p5:
1254 // The definition of a constexpr destructor whose function-body is
1255 // not = delete shall additionally satisfy...
1256 data().DefaultedDestructorIsConstexpr = true;
1257 }
1258 }
1259
1260 // For an anonymous union member, our overload resolution will perform
1261 // overload resolution for its members.
1262 if (Field->isAnonymousStructOrUnion()) {
1263 data().NeedOverloadResolutionForCopyConstructor |=
1264 FieldRec->data().NeedOverloadResolutionForCopyConstructor;
1265 data().NeedOverloadResolutionForMoveConstructor |=
1266 FieldRec->data().NeedOverloadResolutionForMoveConstructor;
1267 data().NeedOverloadResolutionForCopyAssignment |=
1268 FieldRec->data().NeedOverloadResolutionForCopyAssignment;
1269 data().NeedOverloadResolutionForMoveAssignment |=
1270 FieldRec->data().NeedOverloadResolutionForMoveAssignment;
1271 data().NeedOverloadResolutionForDestructor |=
1272 FieldRec->data().NeedOverloadResolutionForDestructor;
1273 }
1274
1275 // C++0x [class.ctor]p5:
1276 // A default constructor is trivial [...] if:
1277 // -- for all the non-static data members of its class that are of
1278 // class type (or array thereof), each such class has a trivial
1279 // default constructor.
1280 if (!FieldRec->hasTrivialDefaultConstructor())
1281 data().HasTrivialSpecialMembers &= ~SMF_DefaultConstructor;
1282
1283 // C++0x [class.copy]p13:
1284 // A copy/move constructor for class X is trivial if [...]
1285 // [...]
1286 // -- for each non-static data member of X that is of class type (or
1287 // an array thereof), the constructor selected to copy/move that
1288 // member is trivial;
1289 if (!FieldRec->hasTrivialCopyConstructor())
1290 data().HasTrivialSpecialMembers &= ~SMF_CopyConstructor;
1291
1292 if (!FieldRec->hasTrivialCopyConstructorForCall())
1293 data().HasTrivialSpecialMembersForCall &= ~SMF_CopyConstructor;
1294
1295 // If the field doesn't have a simple move constructor, we'll eagerly
1296 // declare the move constructor for this class and we'll decide whether
1297 // it's trivial then.
1298 if (!FieldRec->hasTrivialMoveConstructor())
1299 data().HasTrivialSpecialMembers &= ~SMF_MoveConstructor;
1300
1301 if (!FieldRec->hasTrivialMoveConstructorForCall())
1302 data().HasTrivialSpecialMembersForCall &= ~SMF_MoveConstructor;
1303
1304 // C++0x [class.copy]p27:
1305 // A copy/move assignment operator for class X is trivial if [...]
1306 // [...]
1307 // -- for each non-static data member of X that is of class type (or
1308 // an array thereof), the assignment operator selected to
1309 // copy/move that member is trivial;
1310 if (!FieldRec->hasTrivialCopyAssignment())
1311 data().HasTrivialSpecialMembers &= ~SMF_CopyAssignment;
1312 // If the field doesn't have a simple move assignment, we'll eagerly
1313 // declare the move assignment for this class and we'll decide whether
1314 // it's trivial then.
1315 if (!FieldRec->hasTrivialMoveAssignment())
1316 data().HasTrivialSpecialMembers &= ~SMF_MoveAssignment;
1317
1318 if (!FieldRec->hasTrivialDestructor())
1319 data().HasTrivialSpecialMembers &= ~SMF_Destructor;
1320 if (!FieldRec->hasTrivialDestructorForCall())
1321 data().HasTrivialSpecialMembersForCall &= ~SMF_Destructor;
1322 if (!FieldRec->hasIrrelevantDestructor())
1323 data().HasIrrelevantDestructor = false;
1324 if (FieldRec->isAnyDestructorNoReturn())
1325 data().IsAnyDestructorNoReturn = true;
1326 if (FieldRec->hasObjectMember())
1327 setHasObjectMember(true);
1328 if (FieldRec->hasVolatileMember())
1329 setHasVolatileMember(true);
1330 if (FieldRec->getArgPassingRestrictions() ==
1331 RecordArgPassingKind::CanNeverPassInRegs)
1332 setArgPassingRestrictions(RecordArgPassingKind::CanNeverPassInRegs);
1333
1334 // C++0x [class]p7:
1335 // A standard-layout class is a class that:
1336 // -- has no non-static data members of type non-standard-layout
1337 // class (or array of such types) [...]
1338 if (!FieldRec->isStandardLayout())
1339 data().IsStandardLayout = false;
1340 if (!FieldRec->isCXX11StandardLayout())
1341 data().IsCXX11StandardLayout = false;
1342
1343 // C++2a [class]p7:
1344 // A standard-layout class is a class that:
1345 // [...]
1346 // -- has no element of the set M(S) of types as a base class.
1347 if (data().IsStandardLayout &&
1348 (isUnion() || IsFirstField || IsZeroSize) &&
1349 hasSubobjectAtOffsetZeroOfEmptyBaseType(Ctx&: Context, XFirst: FieldRec))
1350 data().IsStandardLayout = false;
1351
1352 // C++11 [class]p7:
1353 // A standard-layout class is a class that:
1354 // -- has no base classes of the same type as the first non-static
1355 // data member
1356 if (data().IsCXX11StandardLayout && IsFirstField) {
1357 // FIXME: We should check all base classes here, not just direct
1358 // base classes.
1359 for (const auto &BI : bases()) {
1360 if (Context.hasSameUnqualifiedType(T1: BI.getType(), T2: T)) {
1361 data().IsCXX11StandardLayout = false;
1362 break;
1363 }
1364 }
1365 }
1366
1367 // Keep track of the presence of mutable fields.
1368 if (FieldRec->hasMutableFields())
1369 data().HasMutableFields = true;
1370
1371 if (Field->isMutable()) {
1372 // Our copy constructor/assignment might call something other than
1373 // the subobject's copy constructor/assignment if it's mutable and of
1374 // class type.
1375 data().NeedOverloadResolutionForCopyConstructor = true;
1376 data().NeedOverloadResolutionForCopyAssignment = true;
1377 }
1378
1379 // C++11 [class.copy]p13:
1380 // If the implicitly-defined constructor would satisfy the
1381 // requirements of a constexpr constructor, the implicitly-defined
1382 // constructor is constexpr.
1383 // C++11 [dcl.constexpr]p4:
1384 // -- every constructor involved in initializing non-static data
1385 // members [...] shall be a constexpr constructor
1386 if (!Field->hasInClassInitializer() &&
1387 !FieldRec->hasConstexprDefaultConstructor() && !isUnion())
1388 // The standard requires any in-class initializer to be a constant
1389 // expression. We consider this to be a defect.
1390 data().DefaultedDefaultConstructorIsConstexpr =
1391 Context.getLangOpts().CPlusPlus23;
1392
1393 // C++11 [class.copy]p8:
1394 // The implicitly-declared copy constructor for a class X will have
1395 // the form 'X::X(const X&)' if each potentially constructed subobject
1396 // of a class type M (or array thereof) has a copy constructor whose
1397 // first parameter is of type 'const M&' or 'const volatile M&'.
1398 if (!FieldRec->hasCopyConstructorWithConstParam())
1399 data().ImplicitCopyConstructorCanHaveConstParamForNonVBase = false;
1400
1401 // C++11 [class.copy]p18:
1402 // The implicitly-declared copy assignment oeprator for a class X will
1403 // have the form 'X& X::operator=(const X&)' if [...] for all the
1404 // non-static data members of X that are of a class type M (or array
1405 // thereof), each such class type has a copy assignment operator whose
1406 // parameter is of type 'const M&', 'const volatile M&' or 'M'.
1407 if (!FieldRec->hasCopyAssignmentWithConstParam())
1408 data().ImplicitCopyAssignmentHasConstParam = false;
1409
1410 if (FieldRec->hasUninitializedExplicitInitFields() &&
1411 FieldRec->isAggregate())
1412 setHasUninitializedExplicitInitFields(true);
1413
1414 if (FieldRec->hasUninitializedReferenceMember() &&
1415 !Field->hasInClassInitializer())
1416 data().HasUninitializedReferenceMember = true;
1417
1418 // C++11 [class.union]p8, DR1460:
1419 // a non-static data member of an anonymous union that is a member of
1420 // X is also a variant member of X.
1421 if (FieldRec->hasVariantMembers() &&
1422 Field->isAnonymousStructOrUnion())
1423 data().HasVariantMembers = true;
1424 }
1425 } else {
1426 // Base element type of field is a non-class type.
1427 if (!T->isLiteralType(Ctx: Context) ||
1428 (!Field->hasInClassInitializer() && !isUnion() &&
1429 !Context.getLangOpts().CPlusPlus20))
1430 data().DefaultedDefaultConstructorIsConstexpr = false;
1431
1432 // C++11 [class.copy]p23:
1433 // A defaulted copy/move assignment operator for a class X is defined
1434 // as deleted if X has:
1435 // -- a non-static data member of const non-class type (or array
1436 // thereof)
1437 if (T.isConstQualified()) {
1438 data().DefaultedCopyAssignmentIsDeleted = true;
1439 data().DefaultedMoveAssignmentIsDeleted = true;
1440 }
1441
1442 // C++20 [temp.param]p7:
1443 // A structural type is [...] a literal class type [for which] the
1444 // types of all non-static data members are structural types or
1445 // (possibly multidimensional) array thereof
1446 // We deal with class types elsewhere.
1447 if (!T->isStructuralType())
1448 data().StructuralIfLiteral = false;
1449 }
1450
1451 // C++14 [meta.unary.prop]p4:
1452 // T is a class type [...] with [...] no non-static data members other
1453 // than subobjects of zero size
1454 if (data().Empty && !IsZeroSize)
1455 data().Empty = false;
1456
1457 if (getLangOpts().HLSL) {
1458 const Type *Ty = Field->getType()->getUnqualifiedDesugaredType();
1459 while (isa<ConstantArrayType>(Val: Ty))
1460 Ty = Ty->getArrayElementTypeNoTypeQual();
1461
1462 Ty = Ty->getUnqualifiedDesugaredType();
1463 if (const RecordType *RT = dyn_cast<RecordType>(Val: Ty))
1464 data().IsHLSLIntangible |= RT->getAsCXXRecordDecl()->isHLSLIntangible();
1465 else
1466 data().IsHLSLIntangible |= (Ty->isHLSLAttributedResourceType() ||
1467 Ty->isHLSLBuiltinIntangibleType());
1468 }
1469 }
1470
1471 // Handle using declarations of conversion functions.
1472 if (auto *Shadow = dyn_cast<UsingShadowDecl>(Val: D)) {
1473 if (Shadow->getDeclName().getNameKind()
1474 == DeclarationName::CXXConversionFunctionName) {
1475 ASTContext &Ctx = getASTContext();
1476 data().Conversions.get(C&: Ctx).addDecl(C&: Ctx, D: Shadow, AS: Shadow->getAccess());
1477 }
1478 }
1479
1480 if (const auto *Using = dyn_cast<UsingDecl>(Val: D)) {
1481 if (Using->getDeclName().getNameKind() ==
1482 DeclarationName::CXXConstructorName) {
1483 data().HasInheritedConstructor = true;
1484 // C++1z [dcl.init.aggr]p1:
1485 // An aggregate is [...] a class [...] with no inherited constructors
1486 data().Aggregate = false;
1487 }
1488
1489 if (Using->getDeclName().getCXXOverloadedOperator() == OO_Equal)
1490 data().HasInheritedAssignment = true;
1491 }
1492
1493 // HLSL: All user-defined data types are aggregates and use aggregate
1494 // initialization, meanwhile most, but not all built-in types behave like
1495 // aggregates. Resource types, and some other HLSL types that wrap handles
1496 // don't behave like aggregates. We can identify these as different because we
1497 // implicitly define "special" member functions, which aren't spellable in
1498 // HLSL. This all _needs_ to change in the future. There are two
1499 // relevant HLSL feature proposals that will depend on this changing:
1500 // * 0005-strict-initializer-lists.md
1501 // * https://github.com/microsoft/hlsl-specs/pull/325
1502 if (getLangOpts().HLSL)
1503 data().Aggregate = data().UserDeclaredSpecialMembers == 0;
1504}
1505
1506bool CXXRecordDecl::isLiteral() const {
1507 const LangOptions &LangOpts = getLangOpts();
1508 if (!(LangOpts.CPlusPlus20 ? hasConstexprDestructor()
1509 : hasTrivialDestructor()))
1510 return false;
1511
1512 if (hasNonLiteralTypeFieldsOrBases()) {
1513 // CWG2598
1514 // is an aggregate union type that has either no variant
1515 // members or at least one variant member of non-volatile literal type,
1516 if (!isUnion())
1517 return false;
1518 bool HasAtLeastOneLiteralMember =
1519 fields().empty() || any_of(fields(), [this](const FieldDecl *D) {
1520 return !D->getType().isVolatileQualified() &&
1521 D->getType()->isLiteralType(getASTContext());
1522 });
1523 if (!HasAtLeastOneLiteralMember)
1524 return false;
1525 }
1526
1527 return isAggregate() || (isLambda() && LangOpts.CPlusPlus17) ||
1528 hasConstexprNonCopyMoveConstructor() || hasTrivialDefaultConstructor();
1529}
1530
1531void CXXRecordDecl::addedSelectedDestructor(CXXDestructorDecl *DD) {
1532 DD->setIneligibleOrNotSelected(false);
1533 addedEligibleSpecialMemberFunction(DD, SMF_Destructor);
1534}
1535
1536void CXXRecordDecl::addedEligibleSpecialMemberFunction(const CXXMethodDecl *MD,
1537 unsigned SMKind) {
1538 // FIXME: We shouldn't change DeclaredNonTrivialSpecialMembers if `MD` is
1539 // a function template, but this needs CWG attention before we break ABI.
1540 // See https://github.com/llvm/llvm-project/issues/59206
1541
1542 if (const auto *DD = dyn_cast<CXXDestructorDecl>(Val: MD)) {
1543 if (DD->isUserProvided())
1544 data().HasIrrelevantDestructor = false;
1545 // If the destructor is explicitly defaulted and not trivial or not public
1546 // or if the destructor is deleted, we clear HasIrrelevantDestructor in
1547 // finishedDefaultedOrDeletedMember.
1548
1549 // C++11 [class.dtor]p5:
1550 // A destructor is trivial if [...] the destructor is not virtual.
1551 if (DD->isVirtual()) {
1552 data().HasTrivialSpecialMembers &= ~SMF_Destructor;
1553 data().HasTrivialSpecialMembersForCall &= ~SMF_Destructor;
1554 }
1555
1556 if (DD->isNoReturn())
1557 data().IsAnyDestructorNoReturn = true;
1558 }
1559 if (!MD->isImplicit() && !MD->isUserProvided()) {
1560 // This method is user-declared but not user-provided. We can't work
1561 // out whether it's trivial yet (not until we get to the end of the
1562 // class). We'll handle this method in
1563 // finishedDefaultedOrDeletedMember.
1564 } else if (MD->isTrivial()) {
1565 data().HasTrivialSpecialMembers |= SMKind;
1566 data().HasTrivialSpecialMembersForCall |= SMKind;
1567 } else if (MD->isTrivialForCall()) {
1568 data().HasTrivialSpecialMembersForCall |= SMKind;
1569 data().DeclaredNonTrivialSpecialMembers |= SMKind;
1570 } else {
1571 data().DeclaredNonTrivialSpecialMembers |= SMKind;
1572 // If this is a user-provided function, do not set
1573 // DeclaredNonTrivialSpecialMembersForCall here since we don't know
1574 // yet whether the method would be considered non-trivial for the
1575 // purpose of calls (attribute "trivial_abi" can be dropped from the
1576 // class later, which can change the special method's triviality).
1577 if (!MD->isUserProvided())
1578 data().DeclaredNonTrivialSpecialMembersForCall |= SMKind;
1579 }
1580}
1581
1582void CXXRecordDecl::finishedDefaultedOrDeletedMember(CXXMethodDecl *D) {
1583 assert(!D->isImplicit() && !D->isUserProvided());
1584
1585 // The kind of special member this declaration is, if any.
1586 unsigned SMKind = 0;
1587
1588 if (const auto *Constructor = dyn_cast<CXXConstructorDecl>(Val: D)) {
1589 if (Constructor->isDefaultConstructor()) {
1590 SMKind |= SMF_DefaultConstructor;
1591 if (Constructor->isConstexpr())
1592 data().HasConstexprDefaultConstructor = true;
1593 }
1594 if (Constructor->isCopyConstructor())
1595 SMKind |= SMF_CopyConstructor;
1596 else if (Constructor->isMoveConstructor())
1597 SMKind |= SMF_MoveConstructor;
1598 else if (Constructor->isConstexpr())
1599 // We may now know that the constructor is constexpr.
1600 data().HasConstexprNonCopyMoveConstructor = true;
1601 } else if (isa<CXXDestructorDecl>(Val: D)) {
1602 SMKind |= SMF_Destructor;
1603 if (!D->isTrivial() || D->getAccess() != AS_public || D->isDeleted())
1604 data().HasIrrelevantDestructor = false;
1605 } else if (D->isCopyAssignmentOperator())
1606 SMKind |= SMF_CopyAssignment;
1607 else if (D->isMoveAssignmentOperator())
1608 SMKind |= SMF_MoveAssignment;
1609
1610 // Update which trivial / non-trivial special members we have.
1611 // addedMember will have skipped this step for this member.
1612 if (!D->isIneligibleOrNotSelected()) {
1613 if (D->isTrivial())
1614 data().HasTrivialSpecialMembers |= SMKind;
1615 else
1616 data().DeclaredNonTrivialSpecialMembers |= SMKind;
1617 }
1618}
1619
1620void CXXRecordDecl::LambdaDefinitionData::AddCaptureList(ASTContext &Ctx,
1621 Capture *CaptureList) {
1622 Captures.push_back(NewVal: CaptureList);
1623 if (Captures.size() == 2) {
1624 // The TinyPtrVector member now needs destruction.
1625 Ctx.addDestruction(Ptr: &Captures);
1626 }
1627}
1628
1629void CXXRecordDecl::setCaptures(ASTContext &Context,
1630 ArrayRef<LambdaCapture> Captures) {
1631 CXXRecordDecl::LambdaDefinitionData &Data = getLambdaData();
1632
1633 // Copy captures.
1634 Data.NumCaptures = Captures.size();
1635 Data.NumExplicitCaptures = 0;
1636 auto *ToCapture = (LambdaCapture *)Context.Allocate(Size: sizeof(LambdaCapture) *
1637 Captures.size());
1638 Data.AddCaptureList(Ctx&: Context, CaptureList: ToCapture);
1639 for (const LambdaCapture &C : Captures) {
1640 if (C.isExplicit())
1641 ++Data.NumExplicitCaptures;
1642
1643 new (ToCapture) LambdaCapture(C);
1644 ToCapture++;
1645 }
1646
1647 if (!lambdaIsDefaultConstructibleAndAssignable())
1648 Data.DefaultedCopyAssignmentIsDeleted = true;
1649}
1650
1651void CXXRecordDecl::setTrivialForCallFlags(CXXMethodDecl *D) {
1652 unsigned SMKind = 0;
1653
1654 if (const auto *Constructor = dyn_cast<CXXConstructorDecl>(Val: D)) {
1655 if (Constructor->isCopyConstructor())
1656 SMKind = SMF_CopyConstructor;
1657 else if (Constructor->isMoveConstructor())
1658 SMKind = SMF_MoveConstructor;
1659 } else if (isa<CXXDestructorDecl>(Val: D))
1660 SMKind = SMF_Destructor;
1661
1662 if (D->isTrivialForCall())
1663 data().HasTrivialSpecialMembersForCall |= SMKind;
1664 else
1665 data().DeclaredNonTrivialSpecialMembersForCall |= SMKind;
1666}
1667
1668bool CXXRecordDecl::isCLike() const {
1669 if (getTagKind() == TagTypeKind::Class ||
1670 getTagKind() == TagTypeKind::Interface ||
1671 !TemplateOrInstantiation.isNull())
1672 return false;
1673 if (!hasDefinition())
1674 return true;
1675
1676 return isPOD() && data().HasOnlyCMembers;
1677}
1678
1679bool CXXRecordDecl::isGenericLambda() const {
1680 if (!isLambda()) return false;
1681 return getLambdaData().IsGenericLambda;
1682}
1683
1684#ifndef NDEBUG
1685static bool allLookupResultsAreTheSame(const DeclContext::lookup_result &R) {
1686 return llvm::all_of(Range: R, P: [&](NamedDecl *D) {
1687 return D->isInvalidDecl() || declaresSameEntity(D, R.front());
1688 });
1689}
1690#endif
1691
1692static NamedDecl* getLambdaCallOperatorHelper(const CXXRecordDecl &RD) {
1693 if (!RD.isLambda()) return nullptr;
1694 DeclarationName Name =
1695 RD.getASTContext().DeclarationNames.getCXXOperatorName(OO_Call);
1696
1697 DeclContext::lookup_result Calls = RD.lookup(Name);
1698
1699 // This can happen while building the lambda.
1700 if (Calls.empty())
1701 return nullptr;
1702
1703 assert(allLookupResultsAreTheSame(Calls) &&
1704 "More than one lambda call operator!");
1705
1706 // FIXME: If we have multiple call operators, we might be in a situation
1707 // where we merged this lambda with one from another module; in that
1708 // case, return our method (instead of that of the other lambda).
1709 //
1710 // This avoids situations where, given two modules A and B, if we
1711 // try to instantiate A's call operator in a function in B, anything
1712 // in the call operator that relies on local decls in the surrounding
1713 // function will crash because it tries to find A's decls, but we only
1714 // instantiated B's:
1715 //
1716 // template <typename>
1717 // void f() {
1718 // using T = int; // We only instantiate B's version of this.
1719 // auto L = [](T) { }; // But A's call operator would want A's here.
1720 // }
1721 //
1722 // Walk the call operator’s redecl chain to find the one that belongs
1723 // to this module.
1724 //
1725 // TODO: We need to fix this properly (see
1726 // https://github.com/llvm/llvm-project/issues/90154).
1727 Module *M = RD.getOwningModule();
1728 for (Decl *D : Calls.front()->redecls()) {
1729 auto *MD = cast<NamedDecl>(D);
1730 if (MD->getOwningModule() == M)
1731 return MD;
1732 }
1733
1734 llvm_unreachable("Couldn't find our call operator!");
1735}
1736
1737FunctionTemplateDecl* CXXRecordDecl::getDependentLambdaCallOperator() const {
1738 NamedDecl *CallOp = getLambdaCallOperatorHelper(RD: *this);
1739 return dyn_cast_or_null<FunctionTemplateDecl>(Val: CallOp);
1740}
1741
1742CXXMethodDecl *CXXRecordDecl::getLambdaCallOperator() const {
1743 NamedDecl *CallOp = getLambdaCallOperatorHelper(RD: *this);
1744
1745 if (CallOp == nullptr)
1746 return nullptr;
1747
1748 if (const auto *CallOpTmpl = dyn_cast<FunctionTemplateDecl>(Val: CallOp))
1749 return cast<CXXMethodDecl>(Val: CallOpTmpl->getTemplatedDecl());
1750
1751 return cast<CXXMethodDecl>(Val: CallOp);
1752}
1753
1754CXXMethodDecl* CXXRecordDecl::getLambdaStaticInvoker() const {
1755 CXXMethodDecl *CallOp = getLambdaCallOperator();
1756 assert(CallOp && "null call operator");
1757 CallingConv CC = CallOp->getType()->castAs<FunctionType>()->getCallConv();
1758 return getLambdaStaticInvoker(CC);
1759}
1760
1761static DeclContext::lookup_result
1762getLambdaStaticInvokers(const CXXRecordDecl &RD) {
1763 assert(RD.isLambda() && "Must be a lambda");
1764 DeclarationName Name =
1765 &RD.getASTContext().Idents.get(getLambdaStaticInvokerName());
1766 return RD.lookup(Name);
1767}
1768
1769static CXXMethodDecl *getInvokerAsMethod(NamedDecl *ND) {
1770 if (const auto *InvokerTemplate = dyn_cast<FunctionTemplateDecl>(Val: ND))
1771 return cast<CXXMethodDecl>(Val: InvokerTemplate->getTemplatedDecl());
1772 return cast<CXXMethodDecl>(Val: ND);
1773}
1774
1775CXXMethodDecl *CXXRecordDecl::getLambdaStaticInvoker(CallingConv CC) const {
1776 if (!isLambda())
1777 return nullptr;
1778 DeclContext::lookup_result Invoker = getLambdaStaticInvokers(RD: *this);
1779
1780 for (NamedDecl *ND : Invoker) {
1781 const auto *FTy =
1782 cast<ValueDecl>(ND->getAsFunction())->getType()->castAs<FunctionType>();
1783 if (FTy->getCallConv() == CC)
1784 return getInvokerAsMethod(ND);
1785 }
1786
1787 return nullptr;
1788}
1789
1790void CXXRecordDecl::getCaptureFields(
1791 llvm::DenseMap<const ValueDecl *, FieldDecl *> &Captures,
1792 FieldDecl *&ThisCapture) const {
1793 Captures.clear();
1794 ThisCapture = nullptr;
1795
1796 LambdaDefinitionData &Lambda = getLambdaData();
1797 for (const LambdaCapture *List : Lambda.Captures) {
1798 RecordDecl::field_iterator Field = field_begin();
1799 for (const LambdaCapture *C = List, *CEnd = C + Lambda.NumCaptures;
1800 C != CEnd; ++C, ++Field) {
1801 if (C->capturesThis())
1802 ThisCapture = *Field;
1803 else if (C->capturesVariable())
1804 Captures[C->getCapturedVar()] = *Field;
1805 }
1806 assert(Field == field_end());
1807 }
1808}
1809
1810TemplateParameterList *
1811CXXRecordDecl::getGenericLambdaTemplateParameterList() const {
1812 if (!isGenericLambda()) return nullptr;
1813 CXXMethodDecl *CallOp = getLambdaCallOperator();
1814 if (FunctionTemplateDecl *Tmpl = CallOp->getDescribedFunctionTemplate())
1815 return Tmpl->getTemplateParameters();
1816 return nullptr;
1817}
1818
1819ArrayRef<NamedDecl *>
1820CXXRecordDecl::getLambdaExplicitTemplateParameters() const {
1821 TemplateParameterList *List = getGenericLambdaTemplateParameterList();
1822 if (!List)
1823 return {};
1824
1825 assert(std::is_partitioned(List->begin(), List->end(),
1826 [](const NamedDecl *D) { return !D->isImplicit(); })
1827 && "Explicit template params should be ordered before implicit ones");
1828
1829 const auto ExplicitEnd = llvm::partition_point(
1830 Range&: *List, P: [](const NamedDecl *D) { return !D->isImplicit(); });
1831 return llvm::ArrayRef(List->begin(), ExplicitEnd);
1832}
1833
1834Decl *CXXRecordDecl::getLambdaContextDecl() const {
1835 assert(isLambda() && "Not a lambda closure type!");
1836 ExternalASTSource *Source = getParentASTContext().getExternalSource();
1837 return getLambdaData().ContextDecl.get(Source);
1838}
1839
1840void CXXRecordDecl::setLambdaNumbering(LambdaNumbering Numbering) {
1841 assert(isLambda() && "Not a lambda closure type!");
1842 getLambdaData().ManglingNumber = Numbering.ManglingNumber;
1843 if (Numbering.DeviceManglingNumber)
1844 getASTContext().DeviceLambdaManglingNumbers[this] =
1845 Numbering.DeviceManglingNumber;
1846 getLambdaData().IndexInContext = Numbering.IndexInContext;
1847 getLambdaData().ContextDecl = Numbering.ContextDecl;
1848 getLambdaData().HasKnownInternalLinkage = Numbering.HasKnownInternalLinkage;
1849}
1850
1851unsigned CXXRecordDecl::getDeviceLambdaManglingNumber() const {
1852 assert(isLambda() && "Not a lambda closure type!");
1853 return getASTContext().DeviceLambdaManglingNumbers.lookup(this);
1854}
1855
1856static CanQualType GetConversionType(ASTContext &Context, NamedDecl *Conv) {
1857 QualType T =
1858 cast<CXXConversionDecl>(Conv->getUnderlyingDecl()->getAsFunction())
1859 ->getConversionType();
1860 return Context.getCanonicalType(T);
1861}
1862
1863/// Collect the visible conversions of a base class.
1864///
1865/// \param Record a base class of the class we're considering
1866/// \param InVirtual whether this base class is a virtual base (or a base
1867/// of a virtual base)
1868/// \param Access the access along the inheritance path to this base
1869/// \param ParentHiddenTypes the conversions provided by the inheritors
1870/// of this base
1871/// \param Output the set to which to add conversions from non-virtual bases
1872/// \param VOutput the set to which to add conversions from virtual bases
1873/// \param HiddenVBaseCs the set of conversions which were hidden in a
1874/// virtual base along some inheritance path
1875static void CollectVisibleConversions(
1876 ASTContext &Context, const CXXRecordDecl *Record, bool InVirtual,
1877 AccessSpecifier Access,
1878 const llvm::SmallPtrSet<CanQualType, 8> &ParentHiddenTypes,
1879 ASTUnresolvedSet &Output, UnresolvedSetImpl &VOutput,
1880 llvm::SmallPtrSet<NamedDecl *, 8> &HiddenVBaseCs) {
1881 // The set of types which have conversions in this class or its
1882 // subclasses. As an optimization, we don't copy the derived set
1883 // unless it might change.
1884 const llvm::SmallPtrSet<CanQualType, 8> *HiddenTypes = &ParentHiddenTypes;
1885 llvm::SmallPtrSet<CanQualType, 8> HiddenTypesBuffer;
1886
1887 // Collect the direct conversions and figure out which conversions
1888 // will be hidden in the subclasses.
1889 CXXRecordDecl::conversion_iterator ConvI = Record->conversion_begin();
1890 CXXRecordDecl::conversion_iterator ConvE = Record->conversion_end();
1891 if (ConvI != ConvE) {
1892 HiddenTypesBuffer = ParentHiddenTypes;
1893 HiddenTypes = &HiddenTypesBuffer;
1894
1895 for (CXXRecordDecl::conversion_iterator I = ConvI; I != ConvE; ++I) {
1896 CanQualType ConvType(GetConversionType(Context, Conv: I.getDecl()));
1897 bool Hidden = ParentHiddenTypes.count(Ptr: ConvType);
1898 if (!Hidden)
1899 HiddenTypesBuffer.insert(Ptr: ConvType);
1900
1901 // If this conversion is hidden and we're in a virtual base,
1902 // remember that it's hidden along some inheritance path.
1903 if (Hidden && InVirtual)
1904 HiddenVBaseCs.insert(cast<NamedDecl>(I.getDecl()->getCanonicalDecl()));
1905
1906 // If this conversion isn't hidden, add it to the appropriate output.
1907 else if (!Hidden) {
1908 AccessSpecifier IAccess
1909 = CXXRecordDecl::MergeAccess(PathAccess: Access, DeclAccess: I.getAccess());
1910
1911 if (InVirtual)
1912 VOutput.addDecl(D: I.getDecl(), AS: IAccess);
1913 else
1914 Output.addDecl(C&: Context, D: I.getDecl(), AS: IAccess);
1915 }
1916 }
1917 }
1918
1919 // Collect information recursively from any base classes.
1920 for (const auto &I : Record->bases()) {
1921 const auto *RT = I.getType()->getAs<RecordType>();
1922 if (!RT) continue;
1923
1924 AccessSpecifier BaseAccess
1925 = CXXRecordDecl::MergeAccess(PathAccess: Access, DeclAccess: I.getAccessSpecifier());
1926 bool BaseInVirtual = InVirtual || I.isVirtual();
1927
1928 auto *Base = cast<CXXRecordDecl>(Val: RT->getDecl());
1929 CollectVisibleConversions(Context, Record: Base, InVirtual: BaseInVirtual, Access: BaseAccess,
1930 ParentHiddenTypes: *HiddenTypes, Output, VOutput, HiddenVBaseCs);
1931 }
1932}
1933
1934/// Collect the visible conversions of a class.
1935///
1936/// This would be extremely straightforward if it weren't for virtual
1937/// bases. It might be worth special-casing that, really.
1938static void CollectVisibleConversions(ASTContext &Context,
1939 const CXXRecordDecl *Record,
1940 ASTUnresolvedSet &Output) {
1941 // The collection of all conversions in virtual bases that we've
1942 // found. These will be added to the output as long as they don't
1943 // appear in the hidden-conversions set.
1944 UnresolvedSet<8> VBaseCs;
1945
1946 // The set of conversions in virtual bases that we've determined to
1947 // be hidden.
1948 llvm::SmallPtrSet<NamedDecl*, 8> HiddenVBaseCs;
1949
1950 // The set of types hidden by classes derived from this one.
1951 llvm::SmallPtrSet<CanQualType, 8> HiddenTypes;
1952
1953 // Go ahead and collect the direct conversions and add them to the
1954 // hidden-types set.
1955 CXXRecordDecl::conversion_iterator ConvI = Record->conversion_begin();
1956 CXXRecordDecl::conversion_iterator ConvE = Record->conversion_end();
1957 Output.append(C&: Context, I: ConvI, E: ConvE);
1958 for (; ConvI != ConvE; ++ConvI)
1959 HiddenTypes.insert(Ptr: GetConversionType(Context, Conv: ConvI.getDecl()));
1960
1961 // Recursively collect conversions from base classes.
1962 for (const auto &I : Record->bases()) {
1963 const auto *RT = I.getType()->getAs<RecordType>();
1964 if (!RT) continue;
1965
1966 CollectVisibleConversions(Context, Record: cast<CXXRecordDecl>(Val: RT->getDecl()),
1967 InVirtual: I.isVirtual(), Access: I.getAccessSpecifier(),
1968 ParentHiddenTypes: HiddenTypes, Output, VOutput&: VBaseCs, HiddenVBaseCs);
1969 }
1970
1971 // Add any unhidden conversions provided by virtual bases.
1972 for (UnresolvedSetIterator I = VBaseCs.begin(), E = VBaseCs.end();
1973 I != E; ++I) {
1974 if (!HiddenVBaseCs.count(Ptr: cast<NamedDecl>(I.getDecl()->getCanonicalDecl())))
1975 Output.addDecl(C&: Context, D: I.getDecl(), AS: I.getAccess());
1976 }
1977}
1978
1979/// getVisibleConversionFunctions - get all conversion functions visible
1980/// in current class; including conversion function templates.
1981llvm::iterator_range<CXXRecordDecl::conversion_iterator>
1982CXXRecordDecl::getVisibleConversionFunctions() const {
1983 ASTContext &Ctx = getASTContext();
1984
1985 ASTUnresolvedSet *Set;
1986 if (bases_begin() == bases_end()) {
1987 // If root class, all conversions are visible.
1988 Set = &data().Conversions.get(C&: Ctx);
1989 } else {
1990 Set = &data().VisibleConversions.get(C&: Ctx);
1991 // If visible conversion list is not evaluated, evaluate it.
1992 if (!data().ComputedVisibleConversions) {
1993 CollectVisibleConversions(Context&: Ctx, Record: this, Output&: *Set);
1994 data().ComputedVisibleConversions = true;
1995 }
1996 }
1997 return llvm::make_range(x: Set->begin(), y: Set->end());
1998}
1999
2000void CXXRecordDecl::removeConversion(const NamedDecl *ConvDecl) {
2001 // This operation is O(N) but extremely rare. Sema only uses it to
2002 // remove UsingShadowDecls in a class that were followed by a direct
2003 // declaration, e.g.:
2004 // class A : B {
2005 // using B::operator int;
2006 // operator int();
2007 // };
2008 // This is uncommon by itself and even more uncommon in conjunction
2009 // with sufficiently large numbers of directly-declared conversions
2010 // that asymptotic behavior matters.
2011
2012 ASTUnresolvedSet &Convs = data().Conversions.get(C&: getASTContext());
2013 for (unsigned I = 0, E = Convs.size(); I != E; ++I) {
2014 if (Convs[I].getDecl() == ConvDecl) {
2015 Convs.erase(I);
2016 assert(!llvm::is_contained(Convs, ConvDecl) &&
2017 "conversion was found multiple times in unresolved set");
2018 return;
2019 }
2020 }
2021
2022 llvm_unreachable("conversion not found in set!");
2023}
2024
2025CXXRecordDecl *CXXRecordDecl::getInstantiatedFromMemberClass() const {
2026 if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo())
2027 return cast<CXXRecordDecl>(Val: MSInfo->getInstantiatedFrom());
2028
2029 return nullptr;
2030}
2031
2032MemberSpecializationInfo *CXXRecordDecl::getMemberSpecializationInfo() const {
2033 return dyn_cast_if_present<MemberSpecializationInfo *>(
2034 Val: TemplateOrInstantiation);
2035}
2036
2037void
2038CXXRecordDecl::setInstantiationOfMemberClass(CXXRecordDecl *RD,
2039 TemplateSpecializationKind TSK) {
2040 assert(TemplateOrInstantiation.isNull() &&
2041 "Previous template or instantiation?");
2042 assert(!isa<ClassTemplatePartialSpecializationDecl>(this));
2043 TemplateOrInstantiation
2044 = new (getASTContext()) MemberSpecializationInfo(RD, TSK);
2045}
2046
2047ClassTemplateDecl *CXXRecordDecl::getDescribedClassTemplate() const {
2048 return dyn_cast_if_present<ClassTemplateDecl *>(Val: TemplateOrInstantiation);
2049}
2050
2051void CXXRecordDecl::setDescribedClassTemplate(ClassTemplateDecl *Template) {
2052 TemplateOrInstantiation = Template;
2053}
2054
2055TemplateSpecializationKind CXXRecordDecl::getTemplateSpecializationKind() const{
2056 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(Val: this))
2057 return Spec->getSpecializationKind();
2058
2059 if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo())
2060 return MSInfo->getTemplateSpecializationKind();
2061
2062 return TSK_Undeclared;
2063}
2064
2065void
2066CXXRecordDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK) {
2067 if (auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(Val: this)) {
2068 Spec->setSpecializationKind(TSK);
2069 return;
2070 }
2071
2072 if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) {
2073 MSInfo->setTemplateSpecializationKind(TSK);
2074 return;
2075 }
2076
2077 llvm_unreachable("Not a class template or member class specialization");
2078}
2079
2080const CXXRecordDecl *CXXRecordDecl::getTemplateInstantiationPattern() const {
2081 auto GetDefinitionOrSelf =
2082 [](const CXXRecordDecl *D) -> const CXXRecordDecl * {
2083 if (auto *Def = D->getDefinition())
2084 return Def;
2085 return D;
2086 };
2087
2088 // If it's a class template specialization, find the template or partial
2089 // specialization from which it was instantiated.
2090 if (auto *TD = dyn_cast<ClassTemplateSpecializationDecl>(Val: this)) {
2091 auto From = TD->getInstantiatedFrom();
2092 if (auto *CTD = dyn_cast_if_present<ClassTemplateDecl *>(Val&: From)) {
2093 while (auto *NewCTD = CTD->getInstantiatedFromMemberTemplate()) {
2094 if (NewCTD->isMemberSpecialization())
2095 break;
2096 CTD = NewCTD;
2097 }
2098 return GetDefinitionOrSelf(CTD->getTemplatedDecl());
2099 }
2100 if (auto *CTPSD =
2101 dyn_cast_if_present<ClassTemplatePartialSpecializationDecl *>(
2102 Val&: From)) {
2103 while (auto *NewCTPSD = CTPSD->getInstantiatedFromMember()) {
2104 if (NewCTPSD->isMemberSpecialization())
2105 break;
2106 CTPSD = NewCTPSD;
2107 }
2108 return GetDefinitionOrSelf(CTPSD);
2109 }
2110 }
2111
2112 if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) {
2113 if (isTemplateInstantiation(Kind: MSInfo->getTemplateSpecializationKind())) {
2114 const CXXRecordDecl *RD = this;
2115 while (auto *NewRD = RD->getInstantiatedFromMemberClass())
2116 RD = NewRD;
2117 return GetDefinitionOrSelf(RD);
2118 }
2119 }
2120
2121 assert(!isTemplateInstantiation(this->getTemplateSpecializationKind()) &&
2122 "couldn't find pattern for class template instantiation");
2123 return nullptr;
2124}
2125
2126CXXDestructorDecl *CXXRecordDecl::getDestructor() const {
2127 ASTContext &Context = getASTContext();
2128 QualType ClassType = Context.getTypeDeclType(this);
2129
2130 DeclarationName Name
2131 = Context.DeclarationNames.getCXXDestructorName(
2132 Ty: Context.getCanonicalType(T: ClassType));
2133
2134 DeclContext::lookup_result R = lookup(Name);
2135
2136 // If a destructor was marked as not selected, we skip it. We don't always
2137 // have a selected destructor: dependent types, unnamed structs.
2138 for (auto *Decl : R) {
2139 auto* DD = dyn_cast<CXXDestructorDecl>(Decl);
2140 if (DD && !DD->isIneligibleOrNotSelected())
2141 return DD;
2142 }
2143 return nullptr;
2144}
2145
2146bool CXXRecordDecl::hasDeletedDestructor() const {
2147 if (const CXXDestructorDecl *D = getDestructor())
2148 return D->isDeleted();
2149 return false;
2150}
2151
2152static bool isDeclContextInNamespace(const DeclContext *DC) {
2153 while (!DC->isTranslationUnit()) {
2154 if (DC->isNamespace())
2155 return true;
2156 DC = DC->getParent();
2157 }
2158 return false;
2159}
2160
2161bool CXXRecordDecl::isInterfaceLike() const {
2162 assert(hasDefinition() && "checking for interface-like without a definition");
2163 // All __interfaces are inheritently interface-like.
2164 if (isInterface())
2165 return true;
2166
2167 // Interface-like types cannot have a user declared constructor, destructor,
2168 // friends, VBases, conversion functions, or fields. Additionally, lambdas
2169 // cannot be interface types.
2170 if (isLambda() || hasUserDeclaredConstructor() ||
2171 hasUserDeclaredDestructor() || !field_empty() || hasFriends() ||
2172 getNumVBases() > 0 || conversion_end() - conversion_begin() > 0)
2173 return false;
2174
2175 // No interface-like type can have a method with a definition.
2176 for (const auto *const Method : methods())
2177 if (Method->isDefined() && !Method->isImplicit())
2178 return false;
2179
2180 // Check "Special" types.
2181 const auto *Uuid = getAttr<UuidAttr>();
2182 // MS SDK declares IUnknown/IDispatch both in the root of a TU, or in an
2183 // extern C++ block directly in the TU. These are only valid if in one
2184 // of these two situations.
2185 if (Uuid && isStruct() && !getDeclContext()->isExternCContext() &&
2186 !isDeclContextInNamespace(getDeclContext()) &&
2187 ((getName() == "IUnknown" &&
2188 Uuid->getGuid() == "00000000-0000-0000-C000-000000000046") ||
2189 (getName() == "IDispatch" &&
2190 Uuid->getGuid() == "00020400-0000-0000-C000-000000000046"))) {
2191 if (getNumBases() > 0)
2192 return false;
2193 return true;
2194 }
2195
2196 // FIXME: Any access specifiers is supposed to make this no longer interface
2197 // like.
2198
2199 // If this isn't a 'special' type, it must have a single interface-like base.
2200 if (getNumBases() != 1)
2201 return false;
2202
2203 const auto BaseSpec = *bases_begin();
2204 if (BaseSpec.isVirtual() || BaseSpec.getAccessSpecifier() != AS_public)
2205 return false;
2206 const auto *Base = BaseSpec.getType()->getAsCXXRecordDecl();
2207 if (Base->isInterface() || !Base->isInterfaceLike())
2208 return false;
2209 return true;
2210}
2211
2212void CXXRecordDecl::completeDefinition() {
2213 completeDefinition(FinalOverriders: nullptr);
2214}
2215
2216static bool hasPureVirtualFinalOverrider(
2217 const CXXRecordDecl &RD, const CXXFinalOverriderMap *FinalOverriders) {
2218 if (!FinalOverriders) {
2219 CXXFinalOverriderMap MyFinalOverriders;
2220 RD.getFinalOverriders(FinaOverriders&: MyFinalOverriders);
2221 return hasPureVirtualFinalOverrider(RD, FinalOverriders: &MyFinalOverriders);
2222 }
2223
2224 for (const CXXFinalOverriderMap::value_type &
2225 OverridingMethodsEntry : *FinalOverriders) {
2226 for (const auto &[_, SubobjOverrides] : OverridingMethodsEntry.second) {
2227 assert(SubobjOverrides.size() > 0 &&
2228 "All virtual functions have overriding virtual functions");
2229
2230 if (SubobjOverrides.front().Method->isPureVirtual())
2231 return true;
2232 }
2233 }
2234 return false;
2235}
2236
2237void CXXRecordDecl::completeDefinition(CXXFinalOverriderMap *FinalOverriders) {
2238 RecordDecl::completeDefinition();
2239
2240 // If the class may be abstract (but hasn't been marked as such), check for
2241 // any pure final overriders.
2242 //
2243 // C++ [class.abstract]p4:
2244 // A class is abstract if it contains or inherits at least one
2245 // pure virtual function for which the final overrider is pure
2246 // virtual.
2247 if (mayBeAbstract() && hasPureVirtualFinalOverrider(RD: *this, FinalOverriders))
2248 markAbstract();
2249
2250 // Set access bits correctly on the directly-declared conversions.
2251 for (conversion_iterator I = conversion_begin(), E = conversion_end();
2252 I != E; ++I)
2253 I.setAccess((*I)->getAccess());
2254
2255 ASTContext &Context = getASTContext();
2256
2257 if (isAggregate() && hasUserDeclaredConstructor() &&
2258 !Context.getLangOpts().CPlusPlus20) {
2259 // Diagnose any aggregate behavior changes in C++20
2260 for (const FieldDecl *FD : fields()) {
2261 if (const auto *AT = FD->getAttr<ExplicitInitAttr>())
2262 Context.getDiagnostics().Report(
2263 AT->getLocation(),
2264 diag::warn_cxx20_compat_requires_explicit_init_non_aggregate)
2265 << AT << FD << Context.getRecordType(this);
2266 }
2267 }
2268
2269 if (!isAggregate() && hasUninitializedExplicitInitFields()) {
2270 // Diagnose any fields that required explicit initialization in a
2271 // non-aggregate type. (Note that the fields may not be directly in this
2272 // type, but in a subobject. In such cases we don't emit diagnoses here.)
2273 for (const FieldDecl *FD : fields()) {
2274 if (const auto *AT = FD->getAttr<ExplicitInitAttr>())
2275 Context.getDiagnostics().Report(AT->getLocation(),
2276 diag::warn_attribute_needs_aggregate)
2277 << AT << Context.getRecordType(this);
2278 }
2279 setHasUninitializedExplicitInitFields(false);
2280 }
2281}
2282
2283bool CXXRecordDecl::mayBeAbstract() const {
2284 if (data().Abstract || isInvalidDecl() || !data().Polymorphic ||
2285 isDependentContext())
2286 return false;
2287
2288 for (const auto &B : bases()) {
2289 const auto *BaseDecl =
2290 cast<CXXRecordDecl>(Val: B.getType()->castAs<RecordType>()->getDecl());
2291 if (BaseDecl->isAbstract())
2292 return true;
2293 }
2294
2295 return false;
2296}
2297
2298bool CXXRecordDecl::isEffectivelyFinal() const {
2299 auto *Def = getDefinition();
2300 if (!Def)
2301 return false;
2302 if (Def->hasAttr<FinalAttr>())
2303 return true;
2304 if (const auto *Dtor = Def->getDestructor())
2305 if (Dtor->hasAttr<FinalAttr>())
2306 return true;
2307 return false;
2308}
2309
2310void CXXDeductionGuideDecl::anchor() {}
2311
2312bool ExplicitSpecifier::isEquivalent(const ExplicitSpecifier Other) const {
2313 if ((getKind() != Other.getKind() ||
2314 getKind() == ExplicitSpecKind::Unresolved)) {
2315 if (getKind() == ExplicitSpecKind::Unresolved &&
2316 Other.getKind() == ExplicitSpecKind::Unresolved) {
2317 ODRHash SelfHash, OtherHash;
2318 SelfHash.AddStmt(getExpr());
2319 OtherHash.AddStmt(Other.getExpr());
2320 return SelfHash.CalculateHash() == OtherHash.CalculateHash();
2321 } else
2322 return false;
2323 }
2324 return true;
2325}
2326
2327ExplicitSpecifier ExplicitSpecifier::getFromDecl(FunctionDecl *Function) {
2328 switch (Function->getDeclKind()) {
2329 case Decl::Kind::CXXConstructor:
2330 return cast<CXXConstructorDecl>(Val: Function)->getExplicitSpecifier();
2331 case Decl::Kind::CXXConversion:
2332 return cast<CXXConversionDecl>(Val: Function)->getExplicitSpecifier();
2333 case Decl::Kind::CXXDeductionGuide:
2334 return cast<CXXDeductionGuideDecl>(Val: Function)->getExplicitSpecifier();
2335 default:
2336 return {};
2337 }
2338}
2339
2340CXXDeductionGuideDecl *CXXDeductionGuideDecl::Create(
2341 ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
2342 ExplicitSpecifier ES, const DeclarationNameInfo &NameInfo, QualType T,
2343 TypeSourceInfo *TInfo, SourceLocation EndLocation, CXXConstructorDecl *Ctor,
2344 DeductionCandidate Kind, const AssociatedConstraint &TrailingRequiresClause,
2345 const CXXDeductionGuideDecl *GeneratedFrom,
2346 SourceDeductionGuideKind SourceKind) {
2347 return new (C, DC) CXXDeductionGuideDecl(
2348 C, DC, StartLoc, ES, NameInfo, T, TInfo, EndLocation, Ctor, Kind,
2349 TrailingRequiresClause, GeneratedFrom, SourceKind);
2350}
2351
2352CXXDeductionGuideDecl *
2353CXXDeductionGuideDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {
2354 return new (C, ID) CXXDeductionGuideDecl(
2355 C, /*DC=*/nullptr, SourceLocation(), ExplicitSpecifier(),
2356 DeclarationNameInfo(), QualType(), /*TInfo=*/nullptr, SourceLocation(),
2357 /*Ctor=*/nullptr, DeductionCandidate::Normal,
2358 /*TrailingRequiresClause=*/{},
2359 /*GeneratedFrom=*/nullptr, SourceDeductionGuideKind::None);
2360}
2361
2362RequiresExprBodyDecl *RequiresExprBodyDecl::Create(
2363 ASTContext &C, DeclContext *DC, SourceLocation StartLoc) {
2364 return new (C, DC) RequiresExprBodyDecl(C, DC, StartLoc);
2365}
2366
2367RequiresExprBodyDecl *
2368RequiresExprBodyDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {
2369 return new (C, ID) RequiresExprBodyDecl(C, nullptr, SourceLocation());
2370}
2371
2372void CXXMethodDecl::anchor() {}
2373
2374bool CXXMethodDecl::isStatic() const {
2375 const CXXMethodDecl *MD = getCanonicalDecl();
2376
2377 if (MD->getStorageClass() == SC_Static)
2378 return true;
2379
2380 OverloadedOperatorKind OOK = getDeclName().getCXXOverloadedOperator();
2381 return isStaticOverloadedOperator(OOK);
2382}
2383
2384static bool recursivelyOverrides(const CXXMethodDecl *DerivedMD,
2385 const CXXMethodDecl *BaseMD) {
2386 for (const CXXMethodDecl *MD : DerivedMD->overridden_methods()) {
2387 if (MD->getCanonicalDecl() == BaseMD->getCanonicalDecl())
2388 return true;
2389 if (recursivelyOverrides(DerivedMD: MD, BaseMD))
2390 return true;
2391 }
2392 return false;
2393}
2394
2395CXXMethodDecl *
2396CXXMethodDecl::getCorrespondingMethodDeclaredInClass(const CXXRecordDecl *RD,
2397 bool MayBeBase) {
2398 if (this->getParent()->getCanonicalDecl() == RD->getCanonicalDecl())
2399 return this;
2400
2401 // Lookup doesn't work for destructors, so handle them separately.
2402 if (isa<CXXDestructorDecl>(Val: this)) {
2403 CXXMethodDecl *MD = RD->getDestructor();
2404 if (MD) {
2405 if (recursivelyOverrides(DerivedMD: MD, BaseMD: this))
2406 return MD;
2407 if (MayBeBase && recursivelyOverrides(DerivedMD: this, BaseMD: MD))
2408 return MD;
2409 }
2410 return nullptr;
2411 }
2412
2413 for (auto *ND : RD->lookup(getDeclName())) {
2414 auto *MD = dyn_cast<CXXMethodDecl>(ND);
2415 if (!MD)
2416 continue;
2417 if (recursivelyOverrides(MD, this))
2418 return MD;
2419 if (MayBeBase && recursivelyOverrides(this, MD))
2420 return MD;
2421 }
2422
2423 return nullptr;
2424}
2425
2426CXXMethodDecl *
2427CXXMethodDecl::getCorrespondingMethodInClass(const CXXRecordDecl *RD,
2428 bool MayBeBase) {
2429 if (auto *MD = getCorrespondingMethodDeclaredInClass(RD, MayBeBase))
2430 return MD;
2431
2432 llvm::SmallVector<CXXMethodDecl*, 4> FinalOverriders;
2433 auto AddFinalOverrider = [&](CXXMethodDecl *D) {
2434 // If this function is overridden by a candidate final overrider, it is not
2435 // a final overrider.
2436 for (CXXMethodDecl *OtherD : FinalOverriders) {
2437 if (declaresSameEntity(D, OtherD) || recursivelyOverrides(DerivedMD: OtherD, BaseMD: D))
2438 return;
2439 }
2440
2441 // Other candidate final overriders might be overridden by this function.
2442 llvm::erase_if(C&: FinalOverriders, P: [&](CXXMethodDecl *OtherD) {
2443 return recursivelyOverrides(DerivedMD: D, BaseMD: OtherD);
2444 });
2445
2446 FinalOverriders.push_back(Elt: D);
2447 };
2448
2449 for (const auto &I : RD->bases()) {
2450 const RecordType *RT = I.getType()->getAs<RecordType>();
2451 if (!RT)
2452 continue;
2453 const auto *Base = cast<CXXRecordDecl>(Val: RT->getDecl());
2454 if (CXXMethodDecl *D = this->getCorrespondingMethodInClass(RD: Base))
2455 AddFinalOverrider(D);
2456 }
2457
2458 return FinalOverriders.size() == 1 ? FinalOverriders.front() : nullptr;
2459}
2460
2461CXXMethodDecl *
2462CXXMethodDecl::Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2463 const DeclarationNameInfo &NameInfo, QualType T,
2464 TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin,
2465 bool isInline, ConstexprSpecKind ConstexprKind,
2466 SourceLocation EndLocation,
2467 const AssociatedConstraint &TrailingRequiresClause) {
2468 return new (C, RD) CXXMethodDecl(
2469 CXXMethod, C, RD, StartLoc, NameInfo, T, TInfo, SC, UsesFPIntrin,
2470 isInline, ConstexprKind, EndLocation, TrailingRequiresClause);
2471}
2472
2473CXXMethodDecl *CXXMethodDecl::CreateDeserialized(ASTContext &C,
2474 GlobalDeclID ID) {
2475 return new (C, ID)
2476 CXXMethodDecl(CXXMethod, C, nullptr, SourceLocation(),
2477 DeclarationNameInfo(), QualType(), nullptr, SC_None, false,
2478 false, ConstexprSpecKind::Unspecified, SourceLocation(),
2479 /*TrailingRequiresClause=*/{});
2480}
2481
2482CXXMethodDecl *CXXMethodDecl::getDevirtualizedMethod(const Expr *Base,
2483 bool IsAppleKext) {
2484 assert(isVirtual() && "this method is expected to be virtual");
2485
2486 // When building with -fapple-kext, all calls must go through the vtable since
2487 // the kernel linker can do runtime patching of vtables.
2488 if (IsAppleKext)
2489 return nullptr;
2490
2491 // If the member function is marked 'final', we know that it can't be
2492 // overridden and can therefore devirtualize it unless it's pure virtual.
2493 if (hasAttr<FinalAttr>())
2494 return isPureVirtual() ? nullptr : this;
2495
2496 // If Base is unknown, we cannot devirtualize.
2497 if (!Base)
2498 return nullptr;
2499
2500 // If the base expression (after skipping derived-to-base conversions) is a
2501 // class prvalue, then we can devirtualize.
2502 Base = Base->getBestDynamicClassTypeExpr();
2503 if (Base->isPRValue() && Base->getType()->isRecordType())
2504 return this;
2505
2506 // If we don't even know what we would call, we can't devirtualize.
2507 const CXXRecordDecl *BestDynamicDecl = Base->getBestDynamicClassType();
2508 if (!BestDynamicDecl)
2509 return nullptr;
2510
2511 // There may be a method corresponding to MD in a derived class.
2512 CXXMethodDecl *DevirtualizedMethod =
2513 getCorrespondingMethodInClass(RD: BestDynamicDecl);
2514
2515 // If there final overrider in the dynamic type is ambiguous, we can't
2516 // devirtualize this call.
2517 if (!DevirtualizedMethod)
2518 return nullptr;
2519
2520 // If that method is pure virtual, we can't devirtualize. If this code is
2521 // reached, the result would be UB, not a direct call to the derived class
2522 // function, and we can't assume the derived class function is defined.
2523 if (DevirtualizedMethod->isPureVirtual())
2524 return nullptr;
2525
2526 // If that method is marked final, we can devirtualize it.
2527 if (DevirtualizedMethod->hasAttr<FinalAttr>())
2528 return DevirtualizedMethod;
2529
2530 // Similarly, if the class itself or its destructor is marked 'final',
2531 // the class can't be derived from and we can therefore devirtualize the
2532 // member function call.
2533 if (BestDynamicDecl->isEffectivelyFinal())
2534 return DevirtualizedMethod;
2535
2536 if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: Base)) {
2537 if (const auto *VD = dyn_cast<VarDecl>(Val: DRE->getDecl()))
2538 if (VD->getType()->isRecordType())
2539 // This is a record decl. We know the type and can devirtualize it.
2540 return DevirtualizedMethod;
2541
2542 return nullptr;
2543 }
2544
2545 // We can devirtualize calls on an object accessed by a class member access
2546 // expression, since by C++11 [basic.life]p6 we know that it can't refer to
2547 // a derived class object constructed in the same location.
2548 if (const auto *ME = dyn_cast<MemberExpr>(Val: Base)) {
2549 const ValueDecl *VD = ME->getMemberDecl();
2550 return VD->getType()->isRecordType() ? DevirtualizedMethod : nullptr;
2551 }
2552
2553 // Likewise for calls on an object accessed by a (non-reference) pointer to
2554 // member access.
2555 if (auto *BO = dyn_cast<BinaryOperator>(Val: Base)) {
2556 if (BO->isPtrMemOp()) {
2557 auto *MPT = BO->getRHS()->getType()->castAs<MemberPointerType>();
2558 if (MPT->getPointeeType()->isRecordType())
2559 return DevirtualizedMethod;
2560 }
2561 }
2562
2563 // We can't devirtualize the call.
2564 return nullptr;
2565}
2566
2567bool CXXMethodDecl::isUsualDeallocationFunction(
2568 SmallVectorImpl<const FunctionDecl *> &PreventedBy) const {
2569 assert(PreventedBy.empty() && "PreventedBy is expected to be empty");
2570 if (!getDeclName().isAnyOperatorDelete())
2571 return false;
2572
2573 if (isTypeAwareOperatorNewOrDelete()) {
2574 // A variadic type aware allocation function is not a usual deallocation
2575 // function
2576 if (isVariadic())
2577 return false;
2578
2579 // Type aware deallocation functions are only usual if they only accept the
2580 // mandatory arguments
2581 if (getNumParams() != FunctionDecl::RequiredTypeAwareDeleteParameterCount)
2582 return false;
2583
2584 FunctionTemplateDecl *PrimaryTemplate = getPrimaryTemplate();
2585 if (!PrimaryTemplate)
2586 return true;
2587
2588 // A template instance is is only a usual deallocation function if it has a
2589 // type-identity parameter, the type-identity parameter is a dependent type
2590 // (i.e. the type-identity parameter is of type std::type_identity<U> where
2591 // U shall be a dependent type), and the type-identity parameter is the only
2592 // dependent parameter, and there are no template packs in the parameter
2593 // list.
2594 FunctionDecl *SpecializedDecl = PrimaryTemplate->getTemplatedDecl();
2595 if (!SpecializedDecl->getParamDecl(i: 0)->getType()->isDependentType())
2596 return false;
2597 for (unsigned Idx = 1; Idx < getNumParams(); ++Idx) {
2598 if (SpecializedDecl->getParamDecl(i: Idx)->getType()->isDependentType())
2599 return false;
2600 }
2601 return true;
2602 }
2603
2604 // C++ [basic.stc.dynamic.deallocation]p2:
2605 // A template instance is never a usual deallocation function,
2606 // regardless of its signature.
2607 // Post-P2719 adoption:
2608 // A template instance is is only a usual deallocation function if it has a
2609 // type-identity parameter
2610 if (getPrimaryTemplate())
2611 return false;
2612
2613 // C++ [basic.stc.dynamic.deallocation]p2:
2614 // If a class T has a member deallocation function named operator delete
2615 // with exactly one parameter, then that function is a usual (non-placement)
2616 // deallocation function. [...]
2617 if (getNumParams() == 1)
2618 return true;
2619 unsigned UsualParams = 1;
2620
2621 // C++ P0722:
2622 // A destroying operator delete is a usual deallocation function if
2623 // removing the std::destroying_delete_t parameter and changing the
2624 // first parameter type from T* to void* results in the signature of
2625 // a usual deallocation function.
2626 if (isDestroyingOperatorDelete())
2627 ++UsualParams;
2628
2629 // C++ <=14 [basic.stc.dynamic.deallocation]p2:
2630 // [...] If class T does not declare such an operator delete but does
2631 // declare a member deallocation function named operator delete with
2632 // exactly two parameters, the second of which has type std::size_t (18.1),
2633 // then this function is a usual deallocation function.
2634 //
2635 // C++17 says a usual deallocation function is one with the signature
2636 // (void* [, size_t] [, std::align_val_t] [, ...])
2637 // and all such functions are usual deallocation functions. It's not clear
2638 // that allowing varargs functions was intentional.
2639 ASTContext &Context = getASTContext();
2640 if (UsualParams < getNumParams() &&
2641 Context.hasSameUnqualifiedType(T1: getParamDecl(UsualParams)->getType(),
2642 T2: Context.getSizeType()))
2643 ++UsualParams;
2644
2645 if (UsualParams < getNumParams() &&
2646 getParamDecl(UsualParams)->getType()->isAlignValT())
2647 ++UsualParams;
2648
2649 if (UsualParams != getNumParams())
2650 return false;
2651
2652 // In C++17 onwards, all potential usual deallocation functions are actual
2653 // usual deallocation functions. Honor this behavior when post-C++14
2654 // deallocation functions are offered as extensions too.
2655 // FIXME(EricWF): Destroying Delete should be a language option. How do we
2656 // handle when destroying delete is used prior to C++17?
2657 if (Context.getLangOpts().CPlusPlus17 ||
2658 Context.getLangOpts().AlignedAllocation ||
2659 isDestroyingOperatorDelete())
2660 return true;
2661
2662 // This function is a usual deallocation function if there are no
2663 // single-parameter deallocation functions of the same kind.
2664 DeclContext::lookup_result R = getDeclContext()->lookup(getDeclName());
2665 bool Result = true;
2666 for (const auto *D : R) {
2667 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
2668 if (FD->getNumParams() == 1) {
2669 PreventedBy.push_back(FD);
2670 Result = false;
2671 }
2672 }
2673 }
2674 return Result;
2675}
2676
2677bool CXXMethodDecl::isExplicitObjectMemberFunction() const {
2678 // C++2b [dcl.fct]p6:
2679 // An explicit object member function is a non-static member
2680 // function with an explicit object parameter
2681 return !isStatic() && hasCXXExplicitFunctionObjectParameter();
2682}
2683
2684bool CXXMethodDecl::isImplicitObjectMemberFunction() const {
2685 return !isStatic() && !hasCXXExplicitFunctionObjectParameter();
2686}
2687
2688bool CXXMethodDecl::isCopyAssignmentOperator() const {
2689 // C++0x [class.copy]p17:
2690 // A user-declared copy assignment operator X::operator= is a non-static
2691 // non-template member function of class X with exactly one parameter of
2692 // type X, X&, const X&, volatile X& or const volatile X&.
2693 if (/*operator=*/getOverloadedOperator() != OO_Equal ||
2694 /*non-static*/ isStatic() ||
2695
2696 /*non-template*/ getPrimaryTemplate() || getDescribedFunctionTemplate() ||
2697 getNumExplicitParams() != 1)
2698 return false;
2699
2700 QualType ParamType = getNonObjectParameter(0)->getType();
2701 if (const auto *Ref = ParamType->getAs<LValueReferenceType>())
2702 ParamType = Ref->getPointeeType();
2703
2704 ASTContext &Context = getASTContext();
2705 QualType ClassType
2706 = Context.getCanonicalType(T: Context.getTypeDeclType(getParent()));
2707 return Context.hasSameUnqualifiedType(T1: ClassType, T2: ParamType);
2708}
2709
2710bool CXXMethodDecl::isMoveAssignmentOperator() const {
2711 // C++0x [class.copy]p19:
2712 // A user-declared move assignment operator X::operator= is a non-static
2713 // non-template member function of class X with exactly one parameter of type
2714 // X&&, const X&&, volatile X&&, or const volatile X&&.
2715 if (getOverloadedOperator() != OO_Equal || isStatic() ||
2716 getPrimaryTemplate() || getDescribedFunctionTemplate() ||
2717 getNumExplicitParams() != 1)
2718 return false;
2719
2720 QualType ParamType = getNonObjectParameter(0)->getType();
2721 if (!ParamType->isRValueReferenceType())
2722 return false;
2723 ParamType = ParamType->getPointeeType();
2724
2725 ASTContext &Context = getASTContext();
2726 QualType ClassType
2727 = Context.getCanonicalType(T: Context.getTypeDeclType(getParent()));
2728 return Context.hasSameUnqualifiedType(T1: ClassType, T2: ParamType);
2729}
2730
2731void CXXMethodDecl::addOverriddenMethod(const CXXMethodDecl *MD) {
2732 assert(MD->isCanonicalDecl() && "Method is not canonical!");
2733 assert(MD->isVirtual() && "Method is not virtual!");
2734
2735 getASTContext().addOverriddenMethod(this, MD);
2736}
2737
2738CXXMethodDecl::method_iterator CXXMethodDecl::begin_overridden_methods() const {
2739 if (isa<CXXConstructorDecl>(Val: this)) return nullptr;
2740 return getASTContext().overridden_methods_begin(this);
2741}
2742
2743CXXMethodDecl::method_iterator CXXMethodDecl::end_overridden_methods() const {
2744 if (isa<CXXConstructorDecl>(Val: this)) return nullptr;
2745 return getASTContext().overridden_methods_end(this);
2746}
2747
2748unsigned CXXMethodDecl::size_overridden_methods() const {
2749 if (isa<CXXConstructorDecl>(Val: this)) return 0;
2750 return getASTContext().overridden_methods_size(this);
2751}
2752
2753CXXMethodDecl::overridden_method_range
2754CXXMethodDecl::overridden_methods() const {
2755 if (isa<CXXConstructorDecl>(Val: this))
2756 return overridden_method_range(nullptr, nullptr);
2757 return getASTContext().overridden_methods(this);
2758}
2759
2760static QualType getThisObjectType(ASTContext &C, const FunctionProtoType *FPT,
2761 const CXXRecordDecl *Decl) {
2762 QualType ClassTy = C.getTypeDeclType(Decl);
2763 return C.getQualifiedType(T: ClassTy, Qs: FPT->getMethodQuals());
2764}
2765
2766QualType CXXMethodDecl::getThisType(const FunctionProtoType *FPT,
2767 const CXXRecordDecl *Decl) {
2768 ASTContext &C = Decl->getASTContext();
2769 QualType ObjectTy = ::getThisObjectType(C, FPT, Decl);
2770
2771 // Unlike 'const' and 'volatile', a '__restrict' qualifier must be
2772 // attached to the pointer type, not the pointee.
2773 bool Restrict = FPT->getMethodQuals().hasRestrict();
2774 if (Restrict)
2775 ObjectTy.removeLocalRestrict();
2776
2777 ObjectTy = C.getLangOpts().HLSL ? C.getLValueReferenceType(T: ObjectTy)
2778 : C.getPointerType(T: ObjectTy);
2779
2780 if (Restrict)
2781 ObjectTy.addRestrict();
2782 return ObjectTy;
2783}
2784
2785QualType CXXMethodDecl::getThisType() const {
2786 // C++ 9.3.2p1: The type of this in a member function of a class X is X*.
2787 // If the member function is declared const, the type of this is const X*,
2788 // if the member function is declared volatile, the type of this is
2789 // volatile X*, and if the member function is declared const volatile,
2790 // the type of this is const volatile X*.
2791 assert(isInstance() && "No 'this' for static methods!");
2792 return CXXMethodDecl::getThisType(getType()->castAs<FunctionProtoType>(),
2793 getParent());
2794}
2795
2796QualType CXXMethodDecl::getFunctionObjectParameterReferenceType() const {
2797 if (isExplicitObjectMemberFunction())
2798 return parameters()[0]->getType();
2799
2800 ASTContext &C = getParentASTContext();
2801 const FunctionProtoType *FPT = getType()->castAs<FunctionProtoType>();
2802 QualType Type = ::getThisObjectType(C, FPT, Decl: getParent());
2803 RefQualifierKind RK = FPT->getRefQualifier();
2804 if (RK == RefQualifierKind::RQ_RValue)
2805 return C.getRValueReferenceType(T: Type);
2806 return C.getLValueReferenceType(T: Type);
2807}
2808
2809bool CXXMethodDecl::hasInlineBody() const {
2810 // If this function is a template instantiation, look at the template from
2811 // which it was instantiated.
2812 const FunctionDecl *CheckFn = getTemplateInstantiationPattern();
2813 if (!CheckFn)
2814 CheckFn = this;
2815
2816 const FunctionDecl *fn;
2817 return CheckFn->isDefined(Definition&: fn) && !fn->isOutOfLine() &&
2818 (fn->doesThisDeclarationHaveABody() || fn->willHaveBody());
2819}
2820
2821bool CXXMethodDecl::isLambdaStaticInvoker() const {
2822 const CXXRecordDecl *P = getParent();
2823 return P->isLambda() && getDeclName().isIdentifier() &&
2824 getName() == getLambdaStaticInvokerName();
2825}
2826
2827CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context,
2828 TypeSourceInfo *TInfo, bool IsVirtual,
2829 SourceLocation L, Expr *Init,
2830 SourceLocation R,
2831 SourceLocation EllipsisLoc)
2832 : Initializee(TInfo), Init(Init), MemberOrEllipsisLocation(EllipsisLoc),
2833 LParenLoc(L), RParenLoc(R), IsDelegating(false), IsVirtual(IsVirtual),
2834 IsWritten(false), SourceOrder(0) {}
2835
2836CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context, FieldDecl *Member,
2837 SourceLocation MemberLoc,
2838 SourceLocation L, Expr *Init,
2839 SourceLocation R)
2840 : Initializee(Member), Init(Init), MemberOrEllipsisLocation(MemberLoc),
2841 LParenLoc(L), RParenLoc(R), IsDelegating(false), IsVirtual(false),
2842 IsWritten(false), SourceOrder(0) {}
2843
2844CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context,
2845 IndirectFieldDecl *Member,
2846 SourceLocation MemberLoc,
2847 SourceLocation L, Expr *Init,
2848 SourceLocation R)
2849 : Initializee(Member), Init(Init), MemberOrEllipsisLocation(MemberLoc),
2850 LParenLoc(L), RParenLoc(R), IsDelegating(false), IsVirtual(false),
2851 IsWritten(false), SourceOrder(0) {}
2852
2853CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context,
2854 TypeSourceInfo *TInfo,
2855 SourceLocation L, Expr *Init,
2856 SourceLocation R)
2857 : Initializee(TInfo), Init(Init), LParenLoc(L), RParenLoc(R),
2858 IsDelegating(true), IsVirtual(false), IsWritten(false), SourceOrder(0) {}
2859
2860int64_t CXXCtorInitializer::getID(const ASTContext &Context) const {
2861 return Context.getAllocator()
2862 .identifyKnownAlignedObject<CXXCtorInitializer>(Ptr: this);
2863}
2864
2865TypeLoc CXXCtorInitializer::getBaseClassLoc() const {
2866 if (isBaseInitializer())
2867 return cast<TypeSourceInfo *>(Val: Initializee)->getTypeLoc();
2868 else
2869 return {};
2870}
2871
2872const Type *CXXCtorInitializer::getBaseClass() const {
2873 if (isBaseInitializer())
2874 return cast<TypeSourceInfo *>(Val: Initializee)->getType().getTypePtr();
2875 else
2876 return nullptr;
2877}
2878
2879SourceLocation CXXCtorInitializer::getSourceLocation() const {
2880 if (isInClassMemberInitializer())
2881 return getAnyMember()->getLocation();
2882
2883 if (isAnyMemberInitializer())
2884 return getMemberLocation();
2885
2886 if (const auto *TSInfo = cast<TypeSourceInfo *>(Val: Initializee))
2887 return TSInfo->getTypeLoc().getBeginLoc();
2888
2889 return {};
2890}
2891
2892SourceRange CXXCtorInitializer::getSourceRange() const {
2893 if (isInClassMemberInitializer()) {
2894 FieldDecl *D = getAnyMember();
2895 if (Expr *I = D->getInClassInitializer())
2896 return I->getSourceRange();
2897 return {};
2898 }
2899
2900 return SourceRange(getSourceLocation(), getRParenLoc());
2901}
2902
2903CXXConstructorDecl::CXXConstructorDecl(
2904 ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2905 const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo,
2906 ExplicitSpecifier ES, bool UsesFPIntrin, bool isInline,
2907 bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind,
2908 InheritedConstructor Inherited,
2909 const AssociatedConstraint &TrailingRequiresClause)
2910 : CXXMethodDecl(CXXConstructor, C, RD, StartLoc, NameInfo, T, TInfo,
2911 SC_None, UsesFPIntrin, isInline, ConstexprKind,
2912 SourceLocation(), TrailingRequiresClause) {
2913 setNumCtorInitializers(0);
2914 setInheritingConstructor(static_cast<bool>(Inherited));
2915 setImplicit(isImplicitlyDeclared);
2916 CXXConstructorDeclBits.HasTrailingExplicitSpecifier = ES.getExpr() ? 1 : 0;
2917 if (Inherited)
2918 *getTrailingObjects<InheritedConstructor>() = Inherited;
2919 setExplicitSpecifier(ES);
2920}
2921
2922void CXXConstructorDecl::anchor() {}
2923
2924CXXConstructorDecl *CXXConstructorDecl::CreateDeserialized(ASTContext &C,
2925 GlobalDeclID ID,
2926 uint64_t AllocKind) {
2927 bool hasTrailingExplicit = static_cast<bool>(AllocKind & TAKHasTailExplicit);
2928 bool isInheritingConstructor =
2929 static_cast<bool>(AllocKind & TAKInheritsConstructor);
2930 unsigned Extra =
2931 additionalSizeToAlloc<InheritedConstructor, ExplicitSpecifier>(
2932 Counts: isInheritingConstructor, Counts: hasTrailingExplicit);
2933 auto *Result = new (C, ID, Extra) CXXConstructorDecl(
2934 C, nullptr, SourceLocation(), DeclarationNameInfo(), QualType(), nullptr,
2935 ExplicitSpecifier(), false, false, false, ConstexprSpecKind::Unspecified,
2936 InheritedConstructor(), /*TrailingRequiresClause=*/{});
2937 Result->setInheritingConstructor(isInheritingConstructor);
2938 Result->CXXConstructorDeclBits.HasTrailingExplicitSpecifier =
2939 hasTrailingExplicit;
2940 Result->setExplicitSpecifier(ExplicitSpecifier());
2941 return Result;
2942}
2943
2944CXXConstructorDecl *CXXConstructorDecl::Create(
2945 ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2946 const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo,
2947 ExplicitSpecifier ES, bool UsesFPIntrin, bool isInline,
2948 bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind,
2949 InheritedConstructor Inherited,
2950 const AssociatedConstraint &TrailingRequiresClause) {
2951 assert(NameInfo.getName().getNameKind()
2952 == DeclarationName::CXXConstructorName &&
2953 "Name must refer to a constructor");
2954 unsigned Extra =
2955 additionalSizeToAlloc<InheritedConstructor, ExplicitSpecifier>(
2956 Counts: Inherited ? 1 : 0, Counts: ES.getExpr() ? 1 : 0);
2957 return new (C, RD, Extra) CXXConstructorDecl(
2958 C, RD, StartLoc, NameInfo, T, TInfo, ES, UsesFPIntrin, isInline,
2959 isImplicitlyDeclared, ConstexprKind, Inherited, TrailingRequiresClause);
2960}
2961
2962CXXConstructorDecl::init_const_iterator CXXConstructorDecl::init_begin() const {
2963 return CtorInitializers.get(Source: getASTContext().getExternalSource());
2964}
2965
2966CXXConstructorDecl *CXXConstructorDecl::getTargetConstructor() const {
2967 assert(isDelegatingConstructor() && "Not a delegating constructor!");
2968 Expr *E = (*init_begin())->getInit()->IgnoreImplicit();
2969 if (const auto *Construct = dyn_cast<CXXConstructExpr>(Val: E))
2970 return Construct->getConstructor();
2971
2972 return nullptr;
2973}
2974
2975bool CXXConstructorDecl::isDefaultConstructor() const {
2976 // C++ [class.default.ctor]p1:
2977 // A default constructor for a class X is a constructor of class X for
2978 // which each parameter that is not a function parameter pack has a default
2979 // argument (including the case of a constructor with no parameters)
2980 return getMinRequiredArguments() == 0;
2981}
2982
2983bool
2984CXXConstructorDecl::isCopyConstructor(unsigned &TypeQuals) const {
2985 return isCopyOrMoveConstructor(TypeQuals) &&
2986 getParamDecl(0)->getType()->isLValueReferenceType();
2987}
2988
2989bool CXXConstructorDecl::isMoveConstructor(unsigned &TypeQuals) const {
2990 return isCopyOrMoveConstructor(TypeQuals) &&
2991 getParamDecl(0)->getType()->isRValueReferenceType();
2992}
2993
2994/// Determine whether this is a copy or move constructor.
2995bool CXXConstructorDecl::isCopyOrMoveConstructor(unsigned &TypeQuals) const {
2996 // C++ [class.copy]p2:
2997 // A non-template constructor for class X is a copy constructor
2998 // if its first parameter is of type X&, const X&, volatile X& or
2999 // const volatile X&, and either there are no other parameters
3000 // or else all other parameters have default arguments (8.3.6).
3001 // C++0x [class.copy]p3:
3002 // A non-template constructor for class X is a move constructor if its
3003 // first parameter is of type X&&, const X&&, volatile X&&, or
3004 // const volatile X&&, and either there are no other parameters or else
3005 // all other parameters have default arguments.
3006 if (!hasOneParamOrDefaultArgs() || getPrimaryTemplate() != nullptr ||
3007 getDescribedFunctionTemplate() != nullptr)
3008 return false;
3009
3010 const ParmVarDecl *Param = getParamDecl(0);
3011
3012 // Do we have a reference type?
3013 const auto *ParamRefType = Param->getType()->getAs<ReferenceType>();
3014 if (!ParamRefType)
3015 return false;
3016
3017 // Is it a reference to our class type?
3018 ASTContext &Context = getASTContext();
3019
3020 CanQualType PointeeType
3021 = Context.getCanonicalType(ParamRefType->getPointeeType());
3022 CanQualType ClassTy
3023 = Context.getCanonicalType(Context.getTagDeclType(Decl: getParent()));
3024 if (PointeeType.getUnqualifiedType() != ClassTy)
3025 return false;
3026
3027 // FIXME: other qualifiers?
3028
3029 // We have a copy or move constructor.
3030 TypeQuals = PointeeType.getCVRQualifiers();
3031 return true;
3032}
3033
3034bool CXXConstructorDecl::isConvertingConstructor(bool AllowExplicit) const {
3035 // C++ [class.conv.ctor]p1:
3036 // A constructor declared without the function-specifier explicit
3037 // that can be called with a single parameter specifies a
3038 // conversion from the type of its first parameter to the type of
3039 // its class. Such a constructor is called a converting
3040 // constructor.
3041 if (isExplicit() && !AllowExplicit)
3042 return false;
3043
3044 // FIXME: This has nothing to do with the definition of converting
3045 // constructor, but is convenient for how we use this function in overload
3046 // resolution.
3047 return getNumParams() == 0
3048 ? getType()->castAs<FunctionProtoType>()->isVariadic()
3049 : getMinRequiredArguments() <= 1;
3050}
3051
3052bool CXXConstructorDecl::isSpecializationCopyingObject() const {
3053 if (!hasOneParamOrDefaultArgs() || getDescribedFunctionTemplate() != nullptr)
3054 return false;
3055
3056 const ParmVarDecl *Param = getParamDecl(0);
3057
3058 ASTContext &Context = getASTContext();
3059 CanQualType ParamType = Context.getCanonicalType(Param->getType());
3060
3061 // Is it the same as our class type?
3062 CanQualType ClassTy
3063 = Context.getCanonicalType(Context.getTagDeclType(Decl: getParent()));
3064 if (ParamType.getUnqualifiedType() != ClassTy)
3065 return false;
3066
3067 return true;
3068}
3069
3070void CXXDestructorDecl::anchor() {}
3071
3072CXXDestructorDecl *CXXDestructorDecl::CreateDeserialized(ASTContext &C,
3073 GlobalDeclID ID) {
3074 return new (C, ID) CXXDestructorDecl(
3075 C, nullptr, SourceLocation(), DeclarationNameInfo(), QualType(), nullptr,
3076 false, false, false, ConstexprSpecKind::Unspecified,
3077 /*TrailingRequiresClause=*/{});
3078}
3079
3080CXXDestructorDecl *CXXDestructorDecl::Create(
3081 ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
3082 const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo,
3083 bool UsesFPIntrin, bool isInline, bool isImplicitlyDeclared,
3084 ConstexprSpecKind ConstexprKind,
3085 const AssociatedConstraint &TrailingRequiresClause) {
3086 assert(NameInfo.getName().getNameKind()
3087 == DeclarationName::CXXDestructorName &&
3088 "Name must refer to a destructor");
3089 return new (C, RD) CXXDestructorDecl(
3090 C, RD, StartLoc, NameInfo, T, TInfo, UsesFPIntrin, isInline,
3091 isImplicitlyDeclared, ConstexprKind, TrailingRequiresClause);
3092}
3093
3094void CXXDestructorDecl::setOperatorDelete(FunctionDecl *OD, Expr *ThisArg) {
3095 auto *First = cast<CXXDestructorDecl>(getFirstDecl());
3096 if (OD && !First->OperatorDelete) {
3097 First->OperatorDelete = OD;
3098 First->OperatorDeleteThisArg = ThisArg;
3099 if (auto *L = getASTMutationListener())
3100 L->ResolvedOperatorDelete(First, OD, ThisArg);
3101 }
3102}
3103
3104bool CXXDestructorDecl::isCalledByDelete(const FunctionDecl *OpDel) const {
3105 // C++20 [expr.delete]p6: If the value of the operand of the delete-
3106 // expression is not a null pointer value and the selected deallocation
3107 // function (see below) is not a destroying operator delete, the delete-
3108 // expression will invoke the destructor (if any) for the object or the
3109 // elements of the array being deleted.
3110 //
3111 // This means we should not look at the destructor for a destroying
3112 // delete operator, as that destructor is never called, unless the
3113 // destructor is virtual (see [expr.delete]p8.1) because then the
3114 // selected operator depends on the dynamic type of the pointer.
3115 const FunctionDecl *SelectedOperatorDelete = OpDel ? OpDel : OperatorDelete;
3116 if (!SelectedOperatorDelete)
3117 return true;
3118
3119 if (!SelectedOperatorDelete->isDestroyingOperatorDelete())
3120 return true;
3121
3122 // We have a destroying operator delete, so it depends on the dtor.
3123 return isVirtual();
3124}
3125
3126void CXXConversionDecl::anchor() {}
3127
3128CXXConversionDecl *CXXConversionDecl::CreateDeserialized(ASTContext &C,
3129 GlobalDeclID ID) {
3130 return new (C, ID) CXXConversionDecl(
3131 C, nullptr, SourceLocation(), DeclarationNameInfo(), QualType(), nullptr,
3132 false, false, ExplicitSpecifier(), ConstexprSpecKind::Unspecified,
3133 SourceLocation(), /*TrailingRequiresClause=*/{});
3134}
3135
3136CXXConversionDecl *CXXConversionDecl::Create(
3137 ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
3138 const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo,
3139 bool UsesFPIntrin, bool isInline, ExplicitSpecifier ES,
3140 ConstexprSpecKind ConstexprKind, SourceLocation EndLocation,
3141 const AssociatedConstraint &TrailingRequiresClause) {
3142 assert(NameInfo.getName().getNameKind()
3143 == DeclarationName::CXXConversionFunctionName &&
3144 "Name must refer to a conversion function");
3145 return new (C, RD) CXXConversionDecl(
3146 C, RD, StartLoc, NameInfo, T, TInfo, UsesFPIntrin, isInline, ES,
3147 ConstexprKind, EndLocation, TrailingRequiresClause);
3148}
3149
3150bool CXXConversionDecl::isLambdaToBlockPointerConversion() const {
3151 return isImplicit() && getParent()->isLambda() &&
3152 getConversionType()->isBlockPointerType();
3153}
3154
3155LinkageSpecDecl::LinkageSpecDecl(DeclContext *DC, SourceLocation ExternLoc,
3156 SourceLocation LangLoc,
3157 LinkageSpecLanguageIDs lang, bool HasBraces)
3158 : Decl(LinkageSpec, DC, LangLoc), DeclContext(LinkageSpec),
3159 ExternLoc(ExternLoc), RBraceLoc(SourceLocation()) {
3160 setLanguage(lang);
3161 LinkageSpecDeclBits.HasBraces = HasBraces;
3162}
3163
3164void LinkageSpecDecl::anchor() {}
3165
3166LinkageSpecDecl *LinkageSpecDecl::Create(ASTContext &C, DeclContext *DC,
3167 SourceLocation ExternLoc,
3168 SourceLocation LangLoc,
3169 LinkageSpecLanguageIDs Lang,
3170 bool HasBraces) {
3171 return new (C, DC) LinkageSpecDecl(DC, ExternLoc, LangLoc, Lang, HasBraces);
3172}
3173
3174LinkageSpecDecl *LinkageSpecDecl::CreateDeserialized(ASTContext &C,
3175 GlobalDeclID ID) {
3176 return new (C, ID)
3177 LinkageSpecDecl(nullptr, SourceLocation(), SourceLocation(),
3178 LinkageSpecLanguageIDs::C, false);
3179}
3180
3181void UsingDirectiveDecl::anchor() {}
3182
3183UsingDirectiveDecl *UsingDirectiveDecl::Create(ASTContext &C, DeclContext *DC,
3184 SourceLocation L,
3185 SourceLocation NamespaceLoc,
3186 NestedNameSpecifierLoc QualifierLoc,
3187 SourceLocation IdentLoc,
3188 NamedDecl *Used,
3189 DeclContext *CommonAncestor) {
3190 if (auto *NS = dyn_cast_or_null<NamespaceDecl>(Val: Used))
3191 Used = NS->getFirstDecl();
3192 return new (C, DC) UsingDirectiveDecl(DC, L, NamespaceLoc, QualifierLoc,
3193 IdentLoc, Used, CommonAncestor);
3194}
3195
3196UsingDirectiveDecl *UsingDirectiveDecl::CreateDeserialized(ASTContext &C,
3197 GlobalDeclID ID) {
3198 return new (C, ID) UsingDirectiveDecl(nullptr, SourceLocation(),
3199 SourceLocation(),
3200 NestedNameSpecifierLoc(),
3201 SourceLocation(), nullptr, nullptr);
3202}
3203
3204NamespaceDecl *UsingDirectiveDecl::getNominatedNamespace() {
3205 if (auto *NA = dyn_cast_or_null<NamespaceAliasDecl>(Val: NominatedNamespace))
3206 return NA->getNamespace();
3207 return cast_or_null<NamespaceDecl>(Val: NominatedNamespace);
3208}
3209
3210NamespaceDecl::NamespaceDecl(ASTContext &C, DeclContext *DC, bool Inline,
3211 SourceLocation StartLoc, SourceLocation IdLoc,
3212 IdentifierInfo *Id, NamespaceDecl *PrevDecl,
3213 bool Nested)
3214 : NamedDecl(Namespace, DC, IdLoc, Id), DeclContext(Namespace),
3215 redeclarable_base(C), LocStart(StartLoc) {
3216 setInline(Inline);
3217 setNested(Nested);
3218 setPreviousDecl(PrevDecl);
3219}
3220
3221NamespaceDecl *NamespaceDecl::Create(ASTContext &C, DeclContext *DC,
3222 bool Inline, SourceLocation StartLoc,
3223 SourceLocation IdLoc, IdentifierInfo *Id,
3224 NamespaceDecl *PrevDecl, bool Nested) {
3225 return new (C, DC)
3226 NamespaceDecl(C, DC, Inline, StartLoc, IdLoc, Id, PrevDecl, Nested);
3227}
3228
3229NamespaceDecl *NamespaceDecl::CreateDeserialized(ASTContext &C,
3230 GlobalDeclID ID) {
3231 return new (C, ID) NamespaceDecl(C, nullptr, false, SourceLocation(),
3232 SourceLocation(), nullptr, nullptr, false);
3233}
3234
3235NamespaceDecl *NamespaceDecl::getNextRedeclarationImpl() {
3236 return getNextRedeclaration();
3237}
3238
3239NamespaceDecl *NamespaceDecl::getPreviousDeclImpl() {
3240 return getPreviousDecl();
3241}
3242
3243NamespaceDecl *NamespaceDecl::getMostRecentDeclImpl() {
3244 return getMostRecentDecl();
3245}
3246
3247void NamespaceAliasDecl::anchor() {}
3248
3249NamespaceAliasDecl *NamespaceAliasDecl::getNextRedeclarationImpl() {
3250 return getNextRedeclaration();
3251}
3252
3253NamespaceAliasDecl *NamespaceAliasDecl::getPreviousDeclImpl() {
3254 return getPreviousDecl();
3255}
3256
3257NamespaceAliasDecl *NamespaceAliasDecl::getMostRecentDeclImpl() {
3258 return getMostRecentDecl();
3259}
3260
3261NamespaceAliasDecl *NamespaceAliasDecl::Create(ASTContext &C, DeclContext *DC,
3262 SourceLocation UsingLoc,
3263 SourceLocation AliasLoc,
3264 IdentifierInfo *Alias,
3265 NestedNameSpecifierLoc QualifierLoc,
3266 SourceLocation IdentLoc,
3267 NamedDecl *Namespace) {
3268 // FIXME: Preserve the aliased namespace as written.
3269 if (auto *NS = dyn_cast_or_null<NamespaceDecl>(Val: Namespace))
3270 Namespace = NS->getFirstDecl();
3271 return new (C, DC) NamespaceAliasDecl(C, DC, UsingLoc, AliasLoc, Alias,
3272 QualifierLoc, IdentLoc, Namespace);
3273}
3274
3275NamespaceAliasDecl *NamespaceAliasDecl::CreateDeserialized(ASTContext &C,
3276 GlobalDeclID ID) {
3277 return new (C, ID) NamespaceAliasDecl(C, nullptr, SourceLocation(),
3278 SourceLocation(), nullptr,
3279 NestedNameSpecifierLoc(),
3280 SourceLocation(), nullptr);
3281}
3282
3283void LifetimeExtendedTemporaryDecl::anchor() {}
3284
3285/// Retrieve the storage duration for the materialized temporary.
3286StorageDuration LifetimeExtendedTemporaryDecl::getStorageDuration() const {
3287 const ValueDecl *ExtendingDecl = getExtendingDecl();
3288 if (!ExtendingDecl)
3289 return SD_FullExpression;
3290 // FIXME: This is not necessarily correct for a temporary materialized
3291 // within a default initializer.
3292 if (isa<FieldDecl>(Val: ExtendingDecl))
3293 return SD_Automatic;
3294 // FIXME: This only works because storage class specifiers are not allowed
3295 // on decomposition declarations.
3296 if (isa<BindingDecl>(Val: ExtendingDecl))
3297 return ExtendingDecl->getDeclContext()->isFunctionOrMethod() ? SD_Automatic
3298 : SD_Static;
3299 return cast<VarDecl>(Val: ExtendingDecl)->getStorageDuration();
3300}
3301
3302APValue *LifetimeExtendedTemporaryDecl::getOrCreateValue(bool MayCreate) const {
3303 assert(getStorageDuration() == SD_Static &&
3304 "don't need to cache the computed value for this temporary");
3305 if (MayCreate && !Value) {
3306 Value = (new (getASTContext()) APValue);
3307 getASTContext().addDestruction(Value);
3308 }
3309 assert(Value && "may not be null");
3310 return Value;
3311}
3312
3313void UsingShadowDecl::anchor() {}
3314
3315UsingShadowDecl::UsingShadowDecl(Kind K, ASTContext &C, DeclContext *DC,
3316 SourceLocation Loc, DeclarationName Name,
3317 BaseUsingDecl *Introducer, NamedDecl *Target)
3318 : NamedDecl(K, DC, Loc, Name), redeclarable_base(C),
3319 UsingOrNextShadow(Introducer) {
3320 if (Target) {
3321 assert(!isa<UsingShadowDecl>(Target));
3322 setTargetDecl(Target);
3323 }
3324 setImplicit();
3325}
3326
3327UsingShadowDecl::UsingShadowDecl(Kind K, ASTContext &C, EmptyShell Empty)
3328 : NamedDecl(K, nullptr, SourceLocation(), DeclarationName()),
3329 redeclarable_base(C) {}
3330
3331UsingShadowDecl *UsingShadowDecl::CreateDeserialized(ASTContext &C,
3332 GlobalDeclID ID) {
3333 return new (C, ID) UsingShadowDecl(UsingShadow, C, EmptyShell());
3334}
3335
3336BaseUsingDecl *UsingShadowDecl::getIntroducer() const {
3337 const UsingShadowDecl *Shadow = this;
3338 while (const auto *NextShadow =
3339 dyn_cast<UsingShadowDecl>(Val: Shadow->UsingOrNextShadow))
3340 Shadow = NextShadow;
3341 return cast<BaseUsingDecl>(Val: Shadow->UsingOrNextShadow);
3342}
3343
3344void ConstructorUsingShadowDecl::anchor() {}
3345
3346ConstructorUsingShadowDecl *
3347ConstructorUsingShadowDecl::Create(ASTContext &C, DeclContext *DC,
3348 SourceLocation Loc, UsingDecl *Using,
3349 NamedDecl *Target, bool IsVirtual) {
3350 return new (C, DC) ConstructorUsingShadowDecl(C, DC, Loc, Using, Target,
3351 IsVirtual);
3352}
3353
3354ConstructorUsingShadowDecl *
3355ConstructorUsingShadowDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {
3356 return new (C, ID) ConstructorUsingShadowDecl(C, EmptyShell());
3357}
3358
3359CXXRecordDecl *ConstructorUsingShadowDecl::getNominatedBaseClass() const {
3360 return getIntroducer()->getQualifier()->getAsRecordDecl();
3361}
3362
3363void BaseUsingDecl::anchor() {}
3364
3365void BaseUsingDecl::addShadowDecl(UsingShadowDecl *S) {
3366 assert(!llvm::is_contained(shadows(), S) && "declaration already in set");
3367 assert(S->getIntroducer() == this);
3368
3369 if (FirstUsingShadow.getPointer())
3370 S->UsingOrNextShadow = FirstUsingShadow.getPointer();
3371 FirstUsingShadow.setPointer(S);
3372}
3373
3374void BaseUsingDecl::removeShadowDecl(UsingShadowDecl *S) {
3375 assert(llvm::is_contained(shadows(), S) && "declaration not in set");
3376 assert(S->getIntroducer() == this);
3377
3378 // Remove S from the shadow decl chain. This is O(n) but hopefully rare.
3379
3380 if (FirstUsingShadow.getPointer() == S) {
3381 FirstUsingShadow.setPointer(
3382 dyn_cast<UsingShadowDecl>(Val: S->UsingOrNextShadow));
3383 S->UsingOrNextShadow = this;
3384 return;
3385 }
3386
3387 UsingShadowDecl *Prev = FirstUsingShadow.getPointer();
3388 while (Prev->UsingOrNextShadow != S)
3389 Prev = cast<UsingShadowDecl>(Val: Prev->UsingOrNextShadow);
3390 Prev->UsingOrNextShadow = S->UsingOrNextShadow;
3391 S->UsingOrNextShadow = this;
3392}
3393
3394void UsingDecl::anchor() {}
3395
3396UsingDecl *UsingDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation UL,
3397 NestedNameSpecifierLoc QualifierLoc,
3398 const DeclarationNameInfo &NameInfo,
3399 bool HasTypename) {
3400 return new (C, DC) UsingDecl(DC, UL, QualifierLoc, NameInfo, HasTypename);
3401}
3402
3403UsingDecl *UsingDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {
3404 return new (C, ID) UsingDecl(nullptr, SourceLocation(),
3405 NestedNameSpecifierLoc(), DeclarationNameInfo(),
3406 false);
3407}
3408
3409SourceRange UsingDecl::getSourceRange() const {
3410 SourceLocation Begin = isAccessDeclaration()
3411 ? getQualifierLoc().getBeginLoc() : UsingLocation;
3412 return SourceRange(Begin, getNameInfo().getEndLoc());
3413}
3414
3415void UsingEnumDecl::anchor() {}
3416
3417UsingEnumDecl *UsingEnumDecl::Create(ASTContext &C, DeclContext *DC,
3418 SourceLocation UL,
3419 SourceLocation EL,
3420 SourceLocation NL,
3421 TypeSourceInfo *EnumType) {
3422 assert(isa<EnumDecl>(EnumType->getType()->getAsTagDecl()));
3423 return new (C, DC)
3424 UsingEnumDecl(DC, EnumType->getType()->getAsTagDecl()->getDeclName(), UL, EL, NL, EnumType);
3425}
3426
3427UsingEnumDecl *UsingEnumDecl::CreateDeserialized(ASTContext &C,
3428 GlobalDeclID ID) {
3429 return new (C, ID)
3430 UsingEnumDecl(nullptr, DeclarationName(), SourceLocation(),
3431 SourceLocation(), SourceLocation(), nullptr);
3432}
3433
3434SourceRange UsingEnumDecl::getSourceRange() const {
3435 return SourceRange(UsingLocation, EnumType->getTypeLoc().getEndLoc());
3436}
3437
3438void UsingPackDecl::anchor() {}
3439
3440UsingPackDecl *UsingPackDecl::Create(ASTContext &C, DeclContext *DC,
3441 NamedDecl *InstantiatedFrom,
3442 ArrayRef<NamedDecl *> UsingDecls) {
3443 size_t Extra = additionalSizeToAlloc<NamedDecl *>(Counts: UsingDecls.size());
3444 return new (C, DC, Extra) UsingPackDecl(DC, InstantiatedFrom, UsingDecls);
3445}
3446
3447UsingPackDecl *UsingPackDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID,
3448 unsigned NumExpansions) {
3449 size_t Extra = additionalSizeToAlloc<NamedDecl *>(Counts: NumExpansions);
3450 auto *Result = new (C, ID, Extra) UsingPackDecl(nullptr, nullptr, {});
3451 Result->NumExpansions = NumExpansions;
3452 auto *Trail = Result->getTrailingObjects();
3453 std::uninitialized_fill_n(Trail, NumExpansions, nullptr);
3454 return Result;
3455}
3456
3457void UnresolvedUsingValueDecl::anchor() {}
3458
3459UnresolvedUsingValueDecl *
3460UnresolvedUsingValueDecl::Create(ASTContext &C, DeclContext *DC,
3461 SourceLocation UsingLoc,
3462 NestedNameSpecifierLoc QualifierLoc,
3463 const DeclarationNameInfo &NameInfo,
3464 SourceLocation EllipsisLoc) {
3465 return new (C, DC) UnresolvedUsingValueDecl(DC, C.DependentTy, UsingLoc,
3466 QualifierLoc, NameInfo,
3467 EllipsisLoc);
3468}
3469
3470UnresolvedUsingValueDecl *
3471UnresolvedUsingValueDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {
3472 return new (C, ID) UnresolvedUsingValueDecl(nullptr, QualType(),
3473 SourceLocation(),
3474 NestedNameSpecifierLoc(),
3475 DeclarationNameInfo(),
3476 SourceLocation());
3477}
3478
3479SourceRange UnresolvedUsingValueDecl::getSourceRange() const {
3480 SourceLocation Begin = isAccessDeclaration()
3481 ? getQualifierLoc().getBeginLoc() : UsingLocation;
3482 return SourceRange(Begin, getNameInfo().getEndLoc());
3483}
3484
3485void UnresolvedUsingTypenameDecl::anchor() {}
3486
3487UnresolvedUsingTypenameDecl *
3488UnresolvedUsingTypenameDecl::Create(ASTContext &C, DeclContext *DC,
3489 SourceLocation UsingLoc,
3490 SourceLocation TypenameLoc,
3491 NestedNameSpecifierLoc QualifierLoc,
3492 SourceLocation TargetNameLoc,
3493 DeclarationName TargetName,
3494 SourceLocation EllipsisLoc) {
3495 return new (C, DC) UnresolvedUsingTypenameDecl(
3496 DC, UsingLoc, TypenameLoc, QualifierLoc, TargetNameLoc,
3497 TargetName.getAsIdentifierInfo(), EllipsisLoc);
3498}
3499
3500UnresolvedUsingTypenameDecl *
3501UnresolvedUsingTypenameDecl::CreateDeserialized(ASTContext &C,
3502 GlobalDeclID ID) {
3503 return new (C, ID) UnresolvedUsingTypenameDecl(
3504 nullptr, SourceLocation(), SourceLocation(), NestedNameSpecifierLoc(),
3505 SourceLocation(), nullptr, SourceLocation());
3506}
3507
3508UnresolvedUsingIfExistsDecl *
3509UnresolvedUsingIfExistsDecl::Create(ASTContext &Ctx, DeclContext *DC,
3510 SourceLocation Loc, DeclarationName Name) {
3511 return new (Ctx, DC) UnresolvedUsingIfExistsDecl(DC, Loc, Name);
3512}
3513
3514UnresolvedUsingIfExistsDecl *
3515UnresolvedUsingIfExistsDecl::CreateDeserialized(ASTContext &Ctx,
3516 GlobalDeclID ID) {
3517 return new (Ctx, ID)
3518 UnresolvedUsingIfExistsDecl(nullptr, SourceLocation(), DeclarationName());
3519}
3520
3521UnresolvedUsingIfExistsDecl::UnresolvedUsingIfExistsDecl(DeclContext *DC,
3522 SourceLocation Loc,
3523 DeclarationName Name)
3524 : NamedDecl(Decl::UnresolvedUsingIfExists, DC, Loc, Name) {}
3525
3526void UnresolvedUsingIfExistsDecl::anchor() {}
3527
3528void StaticAssertDecl::anchor() {}
3529
3530StaticAssertDecl *StaticAssertDecl::Create(ASTContext &C, DeclContext *DC,
3531 SourceLocation StaticAssertLoc,
3532 Expr *AssertExpr, Expr *Message,
3533 SourceLocation RParenLoc,
3534 bool Failed) {
3535 return new (C, DC) StaticAssertDecl(DC, StaticAssertLoc, AssertExpr, Message,
3536 RParenLoc, Failed);
3537}
3538
3539StaticAssertDecl *StaticAssertDecl::CreateDeserialized(ASTContext &C,
3540 GlobalDeclID ID) {
3541 return new (C, ID) StaticAssertDecl(nullptr, SourceLocation(), nullptr,
3542 nullptr, SourceLocation(), false);
3543}
3544
3545VarDecl *ValueDecl::getPotentiallyDecomposedVarDecl() {
3546 assert((isa<VarDecl, BindingDecl>(this)) &&
3547 "expected a VarDecl or a BindingDecl");
3548 if (auto *Var = llvm::dyn_cast<VarDecl>(Val: this))
3549 return Var;
3550 if (auto *BD = llvm::dyn_cast<BindingDecl>(Val: this))
3551 return llvm::dyn_cast_if_present<VarDecl>(Val: BD->getDecomposedDecl());
3552 return nullptr;
3553}
3554
3555void BindingDecl::anchor() {}
3556
3557BindingDecl *BindingDecl::Create(ASTContext &C, DeclContext *DC,
3558 SourceLocation IdLoc, IdentifierInfo *Id,
3559 QualType T) {
3560 return new (C, DC) BindingDecl(DC, IdLoc, Id, T);
3561}
3562
3563BindingDecl *BindingDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {
3564 return new (C, ID)
3565 BindingDecl(nullptr, SourceLocation(), nullptr, QualType());
3566}
3567
3568VarDecl *BindingDecl::getHoldingVar() const {
3569 Expr *B = getBinding();
3570 if (!B)
3571 return nullptr;
3572 auto *DRE = dyn_cast<DeclRefExpr>(Val: B->IgnoreImplicit());
3573 if (!DRE)
3574 return nullptr;
3575
3576 auto *VD = cast<VarDecl>(Val: DRE->getDecl());
3577 assert(VD->isImplicit() && "holding var for binding decl not implicit");
3578 return VD;
3579}
3580
3581llvm::ArrayRef<BindingDecl *> BindingDecl::getBindingPackDecls() const {
3582 assert(Binding && "expecting a pack expr");
3583 auto *FP = cast<FunctionParmPackExpr>(Val: Binding);
3584 ValueDecl *const *First = FP->getNumExpansions() > 0 ? FP->begin() : nullptr;
3585 assert((!First || isa<BindingDecl>(*First)) && "expecting a BindingDecl");
3586 return llvm::ArrayRef<BindingDecl *>(
3587 reinterpret_cast<BindingDecl *const *>(First), FP->getNumExpansions());
3588}
3589
3590void DecompositionDecl::anchor() {}
3591
3592DecompositionDecl *DecompositionDecl::Create(ASTContext &C, DeclContext *DC,
3593 SourceLocation StartLoc,
3594 SourceLocation LSquareLoc,
3595 QualType T, TypeSourceInfo *TInfo,
3596 StorageClass SC,
3597 ArrayRef<BindingDecl *> Bindings) {
3598 size_t Extra = additionalSizeToAlloc<BindingDecl *>(Counts: Bindings.size());
3599 return new (C, DC, Extra)
3600 DecompositionDecl(C, DC, StartLoc, LSquareLoc, T, TInfo, SC, Bindings);
3601}
3602
3603DecompositionDecl *DecompositionDecl::CreateDeserialized(ASTContext &C,
3604 GlobalDeclID ID,
3605 unsigned NumBindings) {
3606 size_t Extra = additionalSizeToAlloc<BindingDecl *>(Counts: NumBindings);
3607 auto *Result = new (C, ID, Extra)
3608 DecompositionDecl(C, nullptr, SourceLocation(), SourceLocation(),
3609 QualType(), nullptr, StorageClass(), {});
3610 // Set up and clean out the bindings array.
3611 Result->NumBindings = NumBindings;
3612 auto *Trail = Result->getTrailingObjects();
3613 std::uninitialized_fill_n(Trail, NumBindings, nullptr);
3614 return Result;
3615}
3616
3617void DecompositionDecl::printName(llvm::raw_ostream &OS,
3618 const PrintingPolicy &Policy) const {
3619 OS << '[';
3620 bool Comma = false;
3621 for (const auto *B : bindings()) {
3622 if (Comma)
3623 OS << ", ";
3624 B->printName(OS, Policy);
3625 Comma = true;
3626 }
3627 OS << ']';
3628}
3629
3630void MSPropertyDecl::anchor() {}
3631
3632MSPropertyDecl *MSPropertyDecl::Create(ASTContext &C, DeclContext *DC,
3633 SourceLocation L, DeclarationName N,
3634 QualType T, TypeSourceInfo *TInfo,
3635 SourceLocation StartL,
3636 IdentifierInfo *Getter,
3637 IdentifierInfo *Setter) {
3638 return new (C, DC) MSPropertyDecl(DC, L, N, T, TInfo, StartL, Getter, Setter);
3639}
3640
3641MSPropertyDecl *MSPropertyDecl::CreateDeserialized(ASTContext &C,
3642 GlobalDeclID ID) {
3643 return new (C, ID) MSPropertyDecl(nullptr, SourceLocation(),
3644 DeclarationName(), QualType(), nullptr,
3645 SourceLocation(), nullptr, nullptr);
3646}
3647
3648void MSGuidDecl::anchor() {}
3649
3650MSGuidDecl::MSGuidDecl(DeclContext *DC, QualType T, Parts P)
3651 : ValueDecl(Decl::MSGuid, DC, SourceLocation(), DeclarationName(), T),
3652 PartVal(P) {}
3653
3654MSGuidDecl *MSGuidDecl::Create(const ASTContext &C, QualType T, Parts P) {
3655 DeclContext *DC = C.getTranslationUnitDecl();
3656 return new (C, DC) MSGuidDecl(DC, T, P);
3657}
3658
3659MSGuidDecl *MSGuidDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {
3660 return new (C, ID) MSGuidDecl(nullptr, QualType(), Parts());
3661}
3662
3663void MSGuidDecl::printName(llvm::raw_ostream &OS,
3664 const PrintingPolicy &) const {
3665 OS << llvm::format(Fmt: "GUID{%08" PRIx32 "-%04" PRIx16 "-%04" PRIx16 "-",
3666 Vals: PartVal.Part1, Vals: PartVal.Part2, Vals: PartVal.Part3);
3667 unsigned I = 0;
3668 for (uint8_t Byte : PartVal.Part4And5) {
3669 OS << llvm::format(Fmt: "%02" PRIx8, Vals: Byte);
3670 if (++I == 2)
3671 OS << '-';
3672 }
3673 OS << '}';
3674}
3675
3676/// Determine if T is a valid 'struct _GUID' of the shape that we expect.
3677static bool isValidStructGUID(ASTContext &Ctx, QualType T) {
3678 // FIXME: We only need to check this once, not once each time we compute a
3679 // GUID APValue.
3680 using MatcherRef = llvm::function_ref<bool(QualType)>;
3681
3682 auto IsInt = [&Ctx](unsigned N) {
3683 return [&Ctx, N](QualType T) {
3684 return T->isUnsignedIntegerOrEnumerationType() &&
3685 Ctx.getIntWidth(T) == N;
3686 };
3687 };
3688
3689 auto IsArray = [&Ctx](MatcherRef Elem, unsigned N) {
3690 return [&Ctx, Elem, N](QualType T) {
3691 const ConstantArrayType *CAT = Ctx.getAsConstantArrayType(T);
3692 return CAT && CAT->getSize() == N && Elem(CAT->getElementType());
3693 };
3694 };
3695
3696 auto IsStruct = [](std::initializer_list<MatcherRef> Fields) {
3697 return [Fields](QualType T) {
3698 const RecordDecl *RD = T->getAsRecordDecl();
3699 if (!RD || RD->isUnion())
3700 return false;
3701 RD = RD->getDefinition();
3702 if (!RD)
3703 return false;
3704 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: RD))
3705 if (CXXRD->getNumBases())
3706 return false;
3707 auto MatcherIt = Fields.begin();
3708 for (const FieldDecl *FD : RD->fields()) {
3709 if (FD->isUnnamedBitField())
3710 continue;
3711 if (FD->isBitField() || MatcherIt == Fields.end() ||
3712 !(*MatcherIt)(FD->getType()))
3713 return false;
3714 ++MatcherIt;
3715 }
3716 return MatcherIt == Fields.end();
3717 };
3718 };
3719
3720 // We expect an {i32, i16, i16, [8 x i8]}.
3721 return IsStruct({IsInt(32), IsInt(16), IsInt(16), IsArray(IsInt(8), 8)})(T);
3722}
3723
3724APValue &MSGuidDecl::getAsAPValue() const {
3725 if (APVal.isAbsent() && isValidStructGUID(getASTContext(), getType())) {
3726 using llvm::APInt;
3727 using llvm::APSInt;
3728 APVal = APValue(APValue::UninitStruct(), 0, 4);
3729 APVal.getStructField(i: 0) = APValue(APSInt(APInt(32, PartVal.Part1), true));
3730 APVal.getStructField(i: 1) = APValue(APSInt(APInt(16, PartVal.Part2), true));
3731 APVal.getStructField(i: 2) = APValue(APSInt(APInt(16, PartVal.Part3), true));
3732 APValue &Arr = APVal.getStructField(i: 3) =
3733 APValue(APValue::UninitArray(), 8, 8);
3734 for (unsigned I = 0; I != 8; ++I) {
3735 Arr.getArrayInitializedElt(I) =
3736 APValue(APSInt(APInt(8, PartVal.Part4And5[I]), true));
3737 }
3738 // Register this APValue to be destroyed if necessary. (Note that the
3739 // MSGuidDecl destructor is never run.)
3740 getASTContext().addDestruction(&APVal);
3741 }
3742
3743 return APVal;
3744}
3745
3746void UnnamedGlobalConstantDecl::anchor() {}
3747
3748UnnamedGlobalConstantDecl::UnnamedGlobalConstantDecl(const ASTContext &C,
3749 DeclContext *DC,
3750 QualType Ty,
3751 const APValue &Val)
3752 : ValueDecl(Decl::UnnamedGlobalConstant, DC, SourceLocation(),
3753 DeclarationName(), Ty),
3754 Value(Val) {
3755 // Cleanup the embedded APValue if required (note that our destructor is never
3756 // run)
3757 if (Value.needsCleanup())
3758 C.addDestruction(Ptr: &Value);
3759}
3760
3761UnnamedGlobalConstantDecl *
3762UnnamedGlobalConstantDecl::Create(const ASTContext &C, QualType T,
3763 const APValue &Value) {
3764 DeclContext *DC = C.getTranslationUnitDecl();
3765 return new (C, DC) UnnamedGlobalConstantDecl(C, DC, T, Value);
3766}
3767
3768UnnamedGlobalConstantDecl *
3769UnnamedGlobalConstantDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {
3770 return new (C, ID)
3771 UnnamedGlobalConstantDecl(C, nullptr, QualType(), APValue());
3772}
3773
3774void UnnamedGlobalConstantDecl::printName(llvm::raw_ostream &OS,
3775 const PrintingPolicy &) const {
3776 OS << "unnamed-global-constant";
3777}
3778
3779static const char *getAccessName(AccessSpecifier AS) {
3780 switch (AS) {
3781 case AS_none:
3782 llvm_unreachable("Invalid access specifier!");
3783 case AS_public:
3784 return "public";
3785 case AS_private:
3786 return "private";
3787 case AS_protected:
3788 return "protected";
3789 }
3790 llvm_unreachable("Invalid access specifier!");
3791}
3792
3793const StreamingDiagnostic &clang::operator<<(const StreamingDiagnostic &DB,
3794 AccessSpecifier AS) {
3795 return DB << getAccessName(AS);
3796}
3797

Provided by KDAB

Privacy Policy
Update your C++ knowledge – Modern C++11/14/17 Training
Find out more

source code of clang/lib/AST/DeclCXX.cpp