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

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