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