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