Bug Summary

File:clang/lib/AST/DeclCXX.cpp
Warning:line 1537, column 9
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name DeclCXX.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-12/lib/clang/12.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/build-llvm/tools/clang/lib/AST -I /build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/AST -I /build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/include -I /build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/build-llvm/include -I /build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-12/lib/clang/12.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/build-llvm/tools/clang/lib/AST -fdebug-prefix-map=/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-11-24-172238-38865-1 -x c++ /build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/AST/DeclCXX.cpp

/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/AST/DeclCXX.cpp

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

/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/include/clang/AST/DeclCXX.h

1//===- DeclCXX.h - Classes for representing C++ declarations --*- C++ -*-=====//
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/// \file
10/// Defines the C++ Decl subclasses, other than those for templates
11/// (found in DeclTemplate.h) and friends (in DeclFriend.h).
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_CLANG_AST_DECLCXX_H
16#define LLVM_CLANG_AST_DECLCXX_H
17
18#include "clang/AST/ASTUnresolvedSet.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/DeclBase.h"
21#include "clang/AST/DeclarationName.h"
22#include "clang/AST/Expr.h"
23#include "clang/AST/ExternalASTSource.h"
24#include "clang/AST/LambdaCapture.h"
25#include "clang/AST/NestedNameSpecifier.h"
26#include "clang/AST/Redeclarable.h"
27#include "clang/AST/Stmt.h"
28#include "clang/AST/Type.h"
29#include "clang/AST/TypeLoc.h"
30#include "clang/AST/UnresolvedSet.h"
31#include "clang/Basic/LLVM.h"
32#include "clang/Basic/Lambda.h"
33#include "clang/Basic/LangOptions.h"
34#include "clang/Basic/OperatorKinds.h"
35#include "clang/Basic/SourceLocation.h"
36#include "clang/Basic/Specifiers.h"
37#include "llvm/ADT/ArrayRef.h"
38#include "llvm/ADT/DenseMap.h"
39#include "llvm/ADT/PointerIntPair.h"
40#include "llvm/ADT/PointerUnion.h"
41#include "llvm/ADT/STLExtras.h"
42#include "llvm/ADT/TinyPtrVector.h"
43#include "llvm/ADT/iterator_range.h"
44#include "llvm/Support/Casting.h"
45#include "llvm/Support/Compiler.h"
46#include "llvm/Support/PointerLikeTypeTraits.h"
47#include "llvm/Support/TrailingObjects.h"
48#include <cassert>
49#include <cstddef>
50#include <iterator>
51#include <memory>
52#include <vector>
53
54namespace clang {
55
56class ASTContext;
57class ClassTemplateDecl;
58class ConstructorUsingShadowDecl;
59class CXXBasePath;
60class CXXBasePaths;
61class CXXConstructorDecl;
62class CXXDestructorDecl;
63class CXXFinalOverriderMap;
64class CXXIndirectPrimaryBaseSet;
65class CXXMethodDecl;
66class DecompositionDecl;
67class DiagnosticBuilder;
68class FriendDecl;
69class FunctionTemplateDecl;
70class IdentifierInfo;
71class MemberSpecializationInfo;
72class TemplateDecl;
73class TemplateParameterList;
74class UsingDecl;
75
76/// Represents an access specifier followed by colon ':'.
77///
78/// An objects of this class represents sugar for the syntactic occurrence
79/// of an access specifier followed by a colon in the list of member
80/// specifiers of a C++ class definition.
81///
82/// Note that they do not represent other uses of access specifiers,
83/// such as those occurring in a list of base specifiers.
84/// Also note that this class has nothing to do with so-called
85/// "access declarations" (C++98 11.3 [class.access.dcl]).
86class AccessSpecDecl : public Decl {
87 /// The location of the ':'.
88 SourceLocation ColonLoc;
89
90 AccessSpecDecl(AccessSpecifier AS, DeclContext *DC,
91 SourceLocation ASLoc, SourceLocation ColonLoc)
92 : Decl(AccessSpec, DC, ASLoc), ColonLoc(ColonLoc) {
93 setAccess(AS);
94 }
95
96 AccessSpecDecl(EmptyShell Empty) : Decl(AccessSpec, Empty) {}
97
98 virtual void anchor();
99
100public:
101 /// The location of the access specifier.
102 SourceLocation getAccessSpecifierLoc() const { return getLocation(); }
103
104 /// Sets the location of the access specifier.
105 void setAccessSpecifierLoc(SourceLocation ASLoc) { setLocation(ASLoc); }
106
107 /// The location of the colon following the access specifier.
108 SourceLocation getColonLoc() const { return ColonLoc; }
109
110 /// Sets the location of the colon.
111 void setColonLoc(SourceLocation CLoc) { ColonLoc = CLoc; }
112
113 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
114 return SourceRange(getAccessSpecifierLoc(), getColonLoc());
115 }
116
117 static AccessSpecDecl *Create(ASTContext &C, AccessSpecifier AS,
118 DeclContext *DC, SourceLocation ASLoc,
119 SourceLocation ColonLoc) {
120 return new (C, DC) AccessSpecDecl(AS, DC, ASLoc, ColonLoc);
121 }
122
123 static AccessSpecDecl *CreateDeserialized(ASTContext &C, unsigned ID);
124
125 // Implement isa/cast/dyncast/etc.
126 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
127 static bool classofKind(Kind K) { return K == AccessSpec; }
128};
129
130/// Represents a base class of a C++ class.
131///
132/// Each CXXBaseSpecifier represents a single, direct base class (or
133/// struct) of a C++ class (or struct). It specifies the type of that
134/// base class, whether it is a virtual or non-virtual base, and what
135/// level of access (public, protected, private) is used for the
136/// derivation. For example:
137///
138/// \code
139/// class A { };
140/// class B { };
141/// class C : public virtual A, protected B { };
142/// \endcode
143///
144/// In this code, C will have two CXXBaseSpecifiers, one for "public
145/// virtual A" and the other for "protected B".
146class CXXBaseSpecifier {
147 /// The source code range that covers the full base
148 /// specifier, including the "virtual" (if present) and access
149 /// specifier (if present).
150 SourceRange Range;
151
152 /// The source location of the ellipsis, if this is a pack
153 /// expansion.
154 SourceLocation EllipsisLoc;
155
156 /// Whether this is a virtual base class or not.
157 unsigned Virtual : 1;
158
159 /// Whether this is the base of a class (true) or of a struct (false).
160 ///
161 /// This determines the mapping from the access specifier as written in the
162 /// source code to the access specifier used for semantic analysis.
163 unsigned BaseOfClass : 1;
164
165 /// Access specifier as written in the source code (may be AS_none).
166 ///
167 /// The actual type of data stored here is an AccessSpecifier, but we use
168 /// "unsigned" here to work around a VC++ bug.
169 unsigned Access : 2;
170
171 /// Whether the class contains a using declaration
172 /// to inherit the named class's constructors.
173 unsigned InheritConstructors : 1;
174
175 /// The type of the base class.
176 ///
177 /// This will be a class or struct (or a typedef of such). The source code
178 /// range does not include the \c virtual or the access specifier.
179 TypeSourceInfo *BaseTypeInfo;
180
181public:
182 CXXBaseSpecifier() = default;
183 CXXBaseSpecifier(SourceRange R, bool V, bool BC, AccessSpecifier A,
184 TypeSourceInfo *TInfo, SourceLocation EllipsisLoc)
185 : Range(R), EllipsisLoc(EllipsisLoc), Virtual(V), BaseOfClass(BC),
186 Access(A), InheritConstructors(false), BaseTypeInfo(TInfo) {}
187
188 /// Retrieves the source range that contains the entire base specifier.
189 SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) { return Range; }
190 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return Range.getBegin(); }
191 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return Range.getEnd(); }
192
193 /// Get the location at which the base class type was written.
194 SourceLocation getBaseTypeLoc() const LLVM_READONLY__attribute__((__pure__)) {
195 return BaseTypeInfo->getTypeLoc().getBeginLoc();
196 }
197
198 /// Determines whether the base class is a virtual base class (or not).
199 bool isVirtual() const { return Virtual; }
200
201 /// Determine whether this base class is a base of a class declared
202 /// with the 'class' keyword (vs. one declared with the 'struct' keyword).
203 bool isBaseOfClass() const { return BaseOfClass; }
204
205 /// Determine whether this base specifier is a pack expansion.
206 bool isPackExpansion() const { return EllipsisLoc.isValid(); }
207
208 /// Determine whether this base class's constructors get inherited.
209 bool getInheritConstructors() const { return InheritConstructors; }
210
211 /// Set that this base class's constructors should be inherited.
212 void setInheritConstructors(bool Inherit = true) {
213 InheritConstructors = Inherit;
214 }
215
216 /// For a pack expansion, determine the location of the ellipsis.
217 SourceLocation getEllipsisLoc() const {
218 return EllipsisLoc;
219 }
220
221 /// Returns the access specifier for this base specifier.
222 ///
223 /// This is the actual base specifier as used for semantic analysis, so
224 /// the result can never be AS_none. To retrieve the access specifier as
225 /// written in the source code, use getAccessSpecifierAsWritten().
226 AccessSpecifier getAccessSpecifier() const {
227 if ((AccessSpecifier)Access == AS_none)
228 return BaseOfClass? AS_private : AS_public;
229 else
230 return (AccessSpecifier)Access;
231 }
232
233 /// Retrieves the access specifier as written in the source code
234 /// (which may mean that no access specifier was explicitly written).
235 ///
236 /// Use getAccessSpecifier() to retrieve the access specifier for use in
237 /// semantic analysis.
238 AccessSpecifier getAccessSpecifierAsWritten() const {
239 return (AccessSpecifier)Access;
240 }
241
242 /// Retrieves the type of the base class.
243 ///
244 /// This type will always be an unqualified class type.
245 QualType getType() const {
246 return BaseTypeInfo->getType().getUnqualifiedType();
247 }
248
249 /// Retrieves the type and source location of the base class.
250 TypeSourceInfo *getTypeSourceInfo() const { return BaseTypeInfo; }
251};
252
253/// Represents a C++ struct/union/class.
254class CXXRecordDecl : public RecordDecl {
255 friend class ASTDeclReader;
256 friend class ASTDeclWriter;
257 friend class ASTNodeImporter;
258 friend class ASTReader;
259 friend class ASTRecordWriter;
260 friend class ASTWriter;
261 friend class DeclContext;
262 friend class LambdaExpr;
263
264 friend void FunctionDecl::setPure(bool);
265 friend void TagDecl::startDefinition();
266
267 /// Values used in DefinitionData fields to represent special members.
268 enum SpecialMemberFlags {
269 SMF_DefaultConstructor = 0x1,
270 SMF_CopyConstructor = 0x2,
271 SMF_MoveConstructor = 0x4,
272 SMF_CopyAssignment = 0x8,
273 SMF_MoveAssignment = 0x10,
274 SMF_Destructor = 0x20,
275 SMF_All = 0x3f
276 };
277
278 struct DefinitionData {
279 #define FIELD(Name, Width, Merge) \
280 unsigned Name : Width;
281 #include "CXXRecordDeclDefinitionBits.def"
282
283 /// Whether this class describes a C++ lambda.
284 unsigned IsLambda : 1;
285
286 /// Whether we are currently parsing base specifiers.
287 unsigned IsParsingBaseSpecifiers : 1;
288
289 /// True when visible conversion functions are already computed
290 /// and are available.
291 unsigned ComputedVisibleConversions : 1;
292
293 unsigned HasODRHash : 1;
294
295 /// A hash of parts of the class to help in ODR checking.
296 unsigned ODRHash = 0;
297
298 /// The number of base class specifiers in Bases.
299 unsigned NumBases = 0;
300
301 /// The number of virtual base class specifiers in VBases.
302 unsigned NumVBases = 0;
303
304 /// Base classes of this class.
305 ///
306 /// FIXME: This is wasted space for a union.
307 LazyCXXBaseSpecifiersPtr Bases;
308
309 /// direct and indirect virtual base classes of this class.
310 LazyCXXBaseSpecifiersPtr VBases;
311
312 /// The conversion functions of this C++ class (but not its
313 /// inherited conversion functions).
314 ///
315 /// Each of the entries in this overload set is a CXXConversionDecl.
316 LazyASTUnresolvedSet Conversions;
317
318 /// The conversion functions of this C++ class and all those
319 /// inherited conversion functions that are visible in this class.
320 ///
321 /// Each of the entries in this overload set is a CXXConversionDecl or a
322 /// FunctionTemplateDecl.
323 LazyASTUnresolvedSet VisibleConversions;
324
325 /// The declaration which defines this record.
326 CXXRecordDecl *Definition;
327
328 /// The first friend declaration in this class, or null if there
329 /// aren't any.
330 ///
331 /// This is actually currently stored in reverse order.
332 LazyDeclPtr FirstFriend;
333
334 DefinitionData(CXXRecordDecl *D);
335
336 /// Retrieve the set of direct base classes.
337 CXXBaseSpecifier *getBases() const {
338 if (!Bases.isOffset())
339 return Bases.get(nullptr);
340 return getBasesSlowCase();
341 }
342
343 /// Retrieve the set of virtual base classes.
344 CXXBaseSpecifier *getVBases() const {
345 if (!VBases.isOffset())
346 return VBases.get(nullptr);
347 return getVBasesSlowCase();
348 }
349
350 ArrayRef<CXXBaseSpecifier> bases() const {
351 return llvm::makeArrayRef(getBases(), NumBases);
352 }
353
354 ArrayRef<CXXBaseSpecifier> vbases() const {
355 return llvm::makeArrayRef(getVBases(), NumVBases);
356 }
357
358 private:
359 CXXBaseSpecifier *getBasesSlowCase() const;
360 CXXBaseSpecifier *getVBasesSlowCase() const;
361 };
362
363 struct DefinitionData *DefinitionData;
364
365 /// Describes a C++ closure type (generated by a lambda expression).
366 struct LambdaDefinitionData : public DefinitionData {
367 using Capture = LambdaCapture;
368
369 /// Whether this lambda is known to be dependent, even if its
370 /// context isn't dependent.
371 ///
372 /// A lambda with a non-dependent context can be dependent if it occurs
373 /// within the default argument of a function template, because the
374 /// lambda will have been created with the enclosing context as its
375 /// declaration context, rather than function. This is an unfortunate
376 /// artifact of having to parse the default arguments before.
377 unsigned Dependent : 1;
378
379 /// Whether this lambda is a generic lambda.
380 unsigned IsGenericLambda : 1;
381
382 /// The Default Capture.
383 unsigned CaptureDefault : 2;
384
385 /// The number of captures in this lambda is limited 2^NumCaptures.
386 unsigned NumCaptures : 15;
387
388 /// The number of explicit captures in this lambda.
389 unsigned NumExplicitCaptures : 13;
390
391 /// Has known `internal` linkage.
392 unsigned HasKnownInternalLinkage : 1;
393
394 /// The number used to indicate this lambda expression for name
395 /// mangling in the Itanium C++ ABI.
396 unsigned ManglingNumber : 31;
397
398 /// The declaration that provides context for this lambda, if the
399 /// actual DeclContext does not suffice. This is used for lambdas that
400 /// occur within default arguments of function parameters within the class
401 /// or within a data member initializer.
402 LazyDeclPtr ContextDecl;
403
404 /// The list of captures, both explicit and implicit, for this
405 /// lambda.
406 Capture *Captures = nullptr;
407
408 /// The type of the call method.
409 TypeSourceInfo *MethodTyInfo;
410
411 LambdaDefinitionData(CXXRecordDecl *D, TypeSourceInfo *Info, bool Dependent,
412 bool IsGeneric, LambdaCaptureDefault CaptureDefault)
413 : DefinitionData(D), Dependent(Dependent), IsGenericLambda(IsGeneric),
414 CaptureDefault(CaptureDefault), NumCaptures(0),
415 NumExplicitCaptures(0), HasKnownInternalLinkage(0), ManglingNumber(0),
416 MethodTyInfo(Info) {
417 IsLambda = true;
418
419 // C++1z [expr.prim.lambda]p4:
420 // This class type is not an aggregate type.
421 Aggregate = false;
422 PlainOldData = false;
423 }
424 };
425
426 struct DefinitionData *dataPtr() const {
427 // Complete the redecl chain (if necessary).
428 getMostRecentDecl();
429 return DefinitionData;
430 }
431
432 struct DefinitionData &data() const {
433 auto *DD = dataPtr();
434 assert(DD && "queried property of class with no definition")((DD && "queried property of class with no definition"
) ? static_cast<void> (0) : __assert_fail ("DD && \"queried property of class with no definition\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/include/clang/AST/DeclCXX.h"
, 434, __PRETTY_FUNCTION__))
;
435 return *DD;
436 }
437
438 struct LambdaDefinitionData &getLambdaData() const {
439 // No update required: a merged definition cannot change any lambda
440 // properties.
441 auto *DD = DefinitionData;
442 assert(DD && DD->IsLambda && "queried lambda property of non-lambda class")((DD && DD->IsLambda && "queried lambda property of non-lambda class"
) ? static_cast<void> (0) : __assert_fail ("DD && DD->IsLambda && \"queried lambda property of non-lambda class\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/include/clang/AST/DeclCXX.h"
, 442, __PRETTY_FUNCTION__))
;
443 return static_cast<LambdaDefinitionData&>(*DD);
444 }
445
446 /// The template or declaration that this declaration
447 /// describes or was instantiated from, respectively.
448 ///
449 /// For non-templates, this value will be null. For record
450 /// declarations that describe a class template, this will be a
451 /// pointer to a ClassTemplateDecl. For member
452 /// classes of class template specializations, this will be the
453 /// MemberSpecializationInfo referring to the member class that was
454 /// instantiated or specialized.
455 llvm::PointerUnion<ClassTemplateDecl *, MemberSpecializationInfo *>
456 TemplateOrInstantiation;
457
458 /// Called from setBases and addedMember to notify the class that a
459 /// direct or virtual base class or a member of class type has been added.
460 void addedClassSubobject(CXXRecordDecl *Base);
461
462 /// Notify the class that member has been added.
463 ///
464 /// This routine helps maintain information about the class based on which
465 /// members have been added. It will be invoked by DeclContext::addDecl()
466 /// whenever a member is added to this record.
467 void addedMember(Decl *D);
468
469 void markedVirtualFunctionPure();
470
471 /// Get the head of our list of friend declarations, possibly
472 /// deserializing the friends from an external AST source.
473 FriendDecl *getFirstFriend() const;
474
475 /// Determine whether this class has an empty base class subobject of type X
476 /// or of one of the types that might be at offset 0 within X (per the C++
477 /// "standard layout" rules).
478 bool hasSubobjectAtOffsetZeroOfEmptyBaseType(ASTContext &Ctx,
479 const CXXRecordDecl *X);
480
481protected:
482 CXXRecordDecl(Kind K, TagKind TK, const ASTContext &C, DeclContext *DC,
483 SourceLocation StartLoc, SourceLocation IdLoc,
484 IdentifierInfo *Id, CXXRecordDecl *PrevDecl);
485
486public:
487 /// Iterator that traverses the base classes of a class.
488 using base_class_iterator = CXXBaseSpecifier *;
489
490 /// Iterator that traverses the base classes of a class.
491 using base_class_const_iterator = const CXXBaseSpecifier *;
492
493 CXXRecordDecl *getCanonicalDecl() override {
494 return cast<CXXRecordDecl>(RecordDecl::getCanonicalDecl());
495 }
496
497 const CXXRecordDecl *getCanonicalDecl() const {
498 return const_cast<CXXRecordDecl*>(this)->getCanonicalDecl();
499 }
500
501 CXXRecordDecl *getPreviousDecl() {
502 return cast_or_null<CXXRecordDecl>(
503 static_cast<RecordDecl *>(this)->getPreviousDecl());
504 }
505
506 const CXXRecordDecl *getPreviousDecl() const {
507 return const_cast<CXXRecordDecl*>(this)->getPreviousDecl();
508 }
509
510 CXXRecordDecl *getMostRecentDecl() {
511 return cast<CXXRecordDecl>(
512 static_cast<RecordDecl *>(this)->getMostRecentDecl());
513 }
514
515 const CXXRecordDecl *getMostRecentDecl() const {
516 return const_cast<CXXRecordDecl*>(this)->getMostRecentDecl();
517 }
518
519 CXXRecordDecl *getMostRecentNonInjectedDecl() {
520 CXXRecordDecl *Recent =
521 static_cast<CXXRecordDecl *>(this)->getMostRecentDecl();
522 while (Recent->isInjectedClassName()) {
523 // FIXME: Does injected class name need to be in the redeclarations chain?
524 assert(Recent->getPreviousDecl())((Recent->getPreviousDecl()) ? static_cast<void> (0)
: __assert_fail ("Recent->getPreviousDecl()", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/include/clang/AST/DeclCXX.h"
, 524, __PRETTY_FUNCTION__))
;
525 Recent = Recent->getPreviousDecl();
526 }
527 return Recent;
528 }
529
530 const CXXRecordDecl *getMostRecentNonInjectedDecl() const {
531 return const_cast<CXXRecordDecl*>(this)->getMostRecentNonInjectedDecl();
532 }
533
534 CXXRecordDecl *getDefinition() const {
535 // We only need an update if we don't already know which
536 // declaration is the definition.
537 auto *DD = DefinitionData ? DefinitionData : dataPtr();
538 return DD ? DD->Definition : nullptr;
539 }
540
541 bool hasDefinition() const { return DefinitionData || dataPtr(); }
542
543 static CXXRecordDecl *Create(const ASTContext &C, TagKind TK, DeclContext *DC,
544 SourceLocation StartLoc, SourceLocation IdLoc,
545 IdentifierInfo *Id,
546 CXXRecordDecl *PrevDecl = nullptr,
547 bool DelayTypeCreation = false);
548 static CXXRecordDecl *CreateLambda(const ASTContext &C, DeclContext *DC,
549 TypeSourceInfo *Info, SourceLocation Loc,
550 bool DependentLambda, bool IsGeneric,
551 LambdaCaptureDefault CaptureDefault);
552 static CXXRecordDecl *CreateDeserialized(const ASTContext &C, unsigned ID);
553
554 bool isDynamicClass() const {
555 return data().Polymorphic || data().NumVBases != 0;
556 }
557
558 /// @returns true if class is dynamic or might be dynamic because the
559 /// definition is incomplete of dependent.
560 bool mayBeDynamicClass() const {
561 return !hasDefinition() || isDynamicClass() || hasAnyDependentBases();
562 }
563
564 /// @returns true if class is non dynamic or might be non dynamic because the
565 /// definition is incomplete of dependent.
566 bool mayBeNonDynamicClass() const {
567 return !hasDefinition() || !isDynamicClass() || hasAnyDependentBases();
568 }
569
570 void setIsParsingBaseSpecifiers() { data().IsParsingBaseSpecifiers = true; }
571
572 bool isParsingBaseSpecifiers() const {
573 return data().IsParsingBaseSpecifiers;
574 }
575
576 unsigned getODRHash() const;
577
578 /// Sets the base classes of this struct or class.
579 void setBases(CXXBaseSpecifier const * const *Bases, unsigned NumBases);
580
581 /// Retrieves the number of base classes of this class.
582 unsigned getNumBases() const { return data().NumBases; }
583
584 using base_class_range = llvm::iterator_range<base_class_iterator>;
585 using base_class_const_range =
586 llvm::iterator_range<base_class_const_iterator>;
587
588 base_class_range bases() {
589 return base_class_range(bases_begin(), bases_end());
590 }
591 base_class_const_range bases() const {
592 return base_class_const_range(bases_begin(), bases_end());
593 }
594
595 base_class_iterator bases_begin() { return data().getBases(); }
596 base_class_const_iterator bases_begin() const { return data().getBases(); }
597 base_class_iterator bases_end() { return bases_begin() + data().NumBases; }
598 base_class_const_iterator bases_end() const {
599 return bases_begin() + data().NumBases;
600 }
601
602 /// Retrieves the number of virtual base classes of this class.
603 unsigned getNumVBases() const { return data().NumVBases; }
604
605 base_class_range vbases() {
606 return base_class_range(vbases_begin(), vbases_end());
607 }
608 base_class_const_range vbases() const {
609 return base_class_const_range(vbases_begin(), vbases_end());
610 }
611
612 base_class_iterator vbases_begin() { return data().getVBases(); }
613 base_class_const_iterator vbases_begin() const { return data().getVBases(); }
614 base_class_iterator vbases_end() { return vbases_begin() + data().NumVBases; }
615 base_class_const_iterator vbases_end() const {
616 return vbases_begin() + data().NumVBases;
617 }
618
619 /// Determine whether this class has any dependent base classes which
620 /// are not the current instantiation.
621 bool hasAnyDependentBases() const;
622
623 /// Iterator access to method members. The method iterator visits
624 /// all method members of the class, including non-instance methods,
625 /// special methods, etc.
626 using method_iterator = specific_decl_iterator<CXXMethodDecl>;
627 using method_range =
628 llvm::iterator_range<specific_decl_iterator<CXXMethodDecl>>;
629
630 method_range methods() const {
631 return method_range(method_begin(), method_end());
632 }
633
634 /// Method begin iterator. Iterates in the order the methods
635 /// were declared.
636 method_iterator method_begin() const {
637 return method_iterator(decls_begin());
638 }
639
640 /// Method past-the-end iterator.
641 method_iterator method_end() const {
642 return method_iterator(decls_end());
643 }
644
645 /// Iterator access to constructor members.
646 using ctor_iterator = specific_decl_iterator<CXXConstructorDecl>;
647 using ctor_range =
648 llvm::iterator_range<specific_decl_iterator<CXXConstructorDecl>>;
649
650 ctor_range ctors() const { return ctor_range(ctor_begin(), ctor_end()); }
651
652 ctor_iterator ctor_begin() const {
653 return ctor_iterator(decls_begin());
654 }
655
656 ctor_iterator ctor_end() const {
657 return ctor_iterator(decls_end());
658 }
659
660 /// An iterator over friend declarations. All of these are defined
661 /// in DeclFriend.h.
662 class friend_iterator;
663 using friend_range = llvm::iterator_range<friend_iterator>;
664
665 friend_range friends() const;
666 friend_iterator friend_begin() const;
667 friend_iterator friend_end() const;
668 void pushFriendDecl(FriendDecl *FD);
669
670 /// Determines whether this record has any friends.
671 bool hasFriends() const {
672 return data().FirstFriend.isValid();
673 }
674
675 /// \c true if a defaulted copy constructor for this class would be
676 /// deleted.
677 bool defaultedCopyConstructorIsDeleted() const {
678 assert((!needsOverloadResolutionForCopyConstructor() ||(((!needsOverloadResolutionForCopyConstructor() || (data().DeclaredSpecialMembers
& SMF_CopyConstructor)) && "this property has not yet been computed by Sema"
) ? static_cast<void> (0) : __assert_fail ("(!needsOverloadResolutionForCopyConstructor() || (data().DeclaredSpecialMembers & SMF_CopyConstructor)) && \"this property has not yet been computed by Sema\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/include/clang/AST/DeclCXX.h"
, 680, __PRETTY_FUNCTION__))
679 (data().DeclaredSpecialMembers & SMF_CopyConstructor)) &&(((!needsOverloadResolutionForCopyConstructor() || (data().DeclaredSpecialMembers
& SMF_CopyConstructor)) && "this property has not yet been computed by Sema"
) ? static_cast<void> (0) : __assert_fail ("(!needsOverloadResolutionForCopyConstructor() || (data().DeclaredSpecialMembers & SMF_CopyConstructor)) && \"this property has not yet been computed by Sema\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/include/clang/AST/DeclCXX.h"
, 680, __PRETTY_FUNCTION__))
680 "this property has not yet been computed by Sema")(((!needsOverloadResolutionForCopyConstructor() || (data().DeclaredSpecialMembers
& SMF_CopyConstructor)) && "this property has not yet been computed by Sema"
) ? static_cast<void> (0) : __assert_fail ("(!needsOverloadResolutionForCopyConstructor() || (data().DeclaredSpecialMembers & SMF_CopyConstructor)) && \"this property has not yet been computed by Sema\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/include/clang/AST/DeclCXX.h"
, 680, __PRETTY_FUNCTION__))
;
681 return data().DefaultedCopyConstructorIsDeleted;
682 }
683
684 /// \c true if a defaulted move constructor for this class would be
685 /// deleted.
686 bool defaultedMoveConstructorIsDeleted() const {
687 assert((!needsOverloadResolutionForMoveConstructor() ||(((!needsOverloadResolutionForMoveConstructor() || (data().DeclaredSpecialMembers
& SMF_MoveConstructor)) && "this property has not yet been computed by Sema"
) ? static_cast<void> (0) : __assert_fail ("(!needsOverloadResolutionForMoveConstructor() || (data().DeclaredSpecialMembers & SMF_MoveConstructor)) && \"this property has not yet been computed by Sema\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/include/clang/AST/DeclCXX.h"
, 689, __PRETTY_FUNCTION__))
688 (data().DeclaredSpecialMembers & SMF_MoveConstructor)) &&(((!needsOverloadResolutionForMoveConstructor() || (data().DeclaredSpecialMembers
& SMF_MoveConstructor)) && "this property has not yet been computed by Sema"
) ? static_cast<void> (0) : __assert_fail ("(!needsOverloadResolutionForMoveConstructor() || (data().DeclaredSpecialMembers & SMF_MoveConstructor)) && \"this property has not yet been computed by Sema\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/include/clang/AST/DeclCXX.h"
, 689, __PRETTY_FUNCTION__))
689 "this property has not yet been computed by Sema")(((!needsOverloadResolutionForMoveConstructor() || (data().DeclaredSpecialMembers
& SMF_MoveConstructor)) && "this property has not yet been computed by Sema"
) ? static_cast<void> (0) : __assert_fail ("(!needsOverloadResolutionForMoveConstructor() || (data().DeclaredSpecialMembers & SMF_MoveConstructor)) && \"this property has not yet been computed by Sema\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/include/clang/AST/DeclCXX.h"
, 689, __PRETTY_FUNCTION__))
;
690 return data().DefaultedMoveConstructorIsDeleted;
691 }
692
693 /// \c true if a defaulted destructor for this class would be deleted.
694 bool defaultedDestructorIsDeleted() const {
695 assert((!needsOverloadResolutionForDestructor() ||(((!needsOverloadResolutionForDestructor() || (data().DeclaredSpecialMembers
& SMF_Destructor)) && "this property has not yet been computed by Sema"
) ? static_cast<void> (0) : __assert_fail ("(!needsOverloadResolutionForDestructor() || (data().DeclaredSpecialMembers & SMF_Destructor)) && \"this property has not yet been computed by Sema\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/include/clang/AST/DeclCXX.h"
, 697, __PRETTY_FUNCTION__))
696 (data().DeclaredSpecialMembers & SMF_Destructor)) &&(((!needsOverloadResolutionForDestructor() || (data().DeclaredSpecialMembers
& SMF_Destructor)) && "this property has not yet been computed by Sema"
) ? static_cast<void> (0) : __assert_fail ("(!needsOverloadResolutionForDestructor() || (data().DeclaredSpecialMembers & SMF_Destructor)) && \"this property has not yet been computed by Sema\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/include/clang/AST/DeclCXX.h"
, 697, __PRETTY_FUNCTION__))
697 "this property has not yet been computed by Sema")(((!needsOverloadResolutionForDestructor() || (data().DeclaredSpecialMembers
& SMF_Destructor)) && "this property has not yet been computed by Sema"
) ? static_cast<void> (0) : __assert_fail ("(!needsOverloadResolutionForDestructor() || (data().DeclaredSpecialMembers & SMF_Destructor)) && \"this property has not yet been computed by Sema\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/include/clang/AST/DeclCXX.h"
, 697, __PRETTY_FUNCTION__))
;
698 return data().DefaultedDestructorIsDeleted;
699 }
700
701 /// \c true if we know for sure that this class has a single,
702 /// accessible, unambiguous copy constructor that is not deleted.
703 bool hasSimpleCopyConstructor() const {
704 return !hasUserDeclaredCopyConstructor() &&
705 !data().DefaultedCopyConstructorIsDeleted;
706 }
707
708 /// \c true if we know for sure that this class has a single,
709 /// accessible, unambiguous move constructor that is not deleted.
710 bool hasSimpleMoveConstructor() const {
711 return !hasUserDeclaredMoveConstructor() && hasMoveConstructor() &&
712 !data().DefaultedMoveConstructorIsDeleted;
713 }
714
715 /// \c true if we know for sure that this class has a single,
716 /// accessible, unambiguous copy assignment operator that is not deleted.
717 bool hasSimpleCopyAssignment() const {
718 return !hasUserDeclaredCopyAssignment() &&
719 !data().DefaultedCopyAssignmentIsDeleted;
720 }
721
722 /// \c true if we know for sure that this class has a single,
723 /// accessible, unambiguous move assignment operator that is not deleted.
724 bool hasSimpleMoveAssignment() const {
725 return !hasUserDeclaredMoveAssignment() && hasMoveAssignment() &&
726 !data().DefaultedMoveAssignmentIsDeleted;
727 }
728
729 /// \c true if we know for sure that this class has an accessible
730 /// destructor that is not deleted.
731 bool hasSimpleDestructor() const {
732 return !hasUserDeclaredDestructor() &&
733 !data().DefaultedDestructorIsDeleted;
734 }
735
736 /// Determine whether this class has any default constructors.
737 bool hasDefaultConstructor() const {
738 return (data().DeclaredSpecialMembers & SMF_DefaultConstructor) ||
739 needsImplicitDefaultConstructor();
740 }
741
742 /// Determine if we need to declare a default constructor for
743 /// this class.
744 ///
745 /// This value is used for lazy creation of default constructors.
746 bool needsImplicitDefaultConstructor() const {
747 return !data().UserDeclaredConstructor &&
748 !(data().DeclaredSpecialMembers & SMF_DefaultConstructor) &&
749 (!isLambda() || lambdaIsDefaultConstructibleAndAssignable());
750 }
751
752 /// Determine whether this class has any user-declared constructors.
753 ///
754 /// When true, a default constructor will not be implicitly declared.
755 bool hasUserDeclaredConstructor() const {
756 return data().UserDeclaredConstructor;
757 }
758
759 /// Whether this class has a user-provided default constructor
760 /// per C++11.
761 bool hasUserProvidedDefaultConstructor() const {
762 return data().UserProvidedDefaultConstructor;
763 }
764
765 /// Determine whether this class has a user-declared copy constructor.
766 ///
767 /// When false, a copy constructor will be implicitly declared.
768 bool hasUserDeclaredCopyConstructor() const {
769 return data().UserDeclaredSpecialMembers & SMF_CopyConstructor;
770 }
771
772 /// Determine whether this class needs an implicit copy
773 /// constructor to be lazily declared.
774 bool needsImplicitCopyConstructor() const {
775 return !(data().DeclaredSpecialMembers & SMF_CopyConstructor);
776 }
777
778 /// Determine whether we need to eagerly declare a defaulted copy
779 /// constructor for this class.
780 bool needsOverloadResolutionForCopyConstructor() const {
781 // C++17 [class.copy.ctor]p6:
782 // If the class definition declares a move constructor or move assignment
783 // operator, the implicitly declared copy constructor is defined as
784 // deleted.
785 // In MSVC mode, sometimes a declared move assignment does not delete an
786 // implicit copy constructor, so defer this choice to Sema.
787 if (data().UserDeclaredSpecialMembers &
788 (SMF_MoveConstructor | SMF_MoveAssignment))
789 return true;
790 return data().NeedOverloadResolutionForCopyConstructor;
791 }
792
793 /// Determine whether an implicit copy constructor for this type
794 /// would have a parameter with a const-qualified reference type.
795 bool implicitCopyConstructorHasConstParam() const {
796 return data().ImplicitCopyConstructorCanHaveConstParamForNonVBase &&
797 (isAbstract() ||
798 data().ImplicitCopyConstructorCanHaveConstParamForVBase);
799 }
800
801 /// Determine whether this class has a copy constructor with
802 /// a parameter type which is a reference to a const-qualified type.
803 bool hasCopyConstructorWithConstParam() const {
804 return data().HasDeclaredCopyConstructorWithConstParam ||
805 (needsImplicitCopyConstructor() &&
806 implicitCopyConstructorHasConstParam());
807 }
808
809 /// Whether this class has a user-declared move constructor or
810 /// assignment operator.
811 ///
812 /// When false, a move constructor and assignment operator may be
813 /// implicitly declared.
814 bool hasUserDeclaredMoveOperation() const {
815 return data().UserDeclaredSpecialMembers &
816 (SMF_MoveConstructor | SMF_MoveAssignment);
817 }
818
819 /// Determine whether this class has had a move constructor
820 /// declared by the user.
821 bool hasUserDeclaredMoveConstructor() const {
822 return data().UserDeclaredSpecialMembers & SMF_MoveConstructor;
823 }
824
825 /// Determine whether this class has a move constructor.
826 bool hasMoveConstructor() const {
827 return (data().DeclaredSpecialMembers & SMF_MoveConstructor) ||
828 needsImplicitMoveConstructor();
829 }
830
831 /// Set that we attempted to declare an implicit copy
832 /// constructor, but overload resolution failed so we deleted it.
833 void setImplicitCopyConstructorIsDeleted() {
834 assert((data().DefaultedCopyConstructorIsDeleted ||(((data().DefaultedCopyConstructorIsDeleted || needsOverloadResolutionForCopyConstructor
()) && "Copy constructor should not be deleted") ? static_cast
<void> (0) : __assert_fail ("(data().DefaultedCopyConstructorIsDeleted || needsOverloadResolutionForCopyConstructor()) && \"Copy constructor should not be deleted\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/include/clang/AST/DeclCXX.h"
, 836, __PRETTY_FUNCTION__))
835 needsOverloadResolutionForCopyConstructor()) &&(((data().DefaultedCopyConstructorIsDeleted || needsOverloadResolutionForCopyConstructor
()) && "Copy constructor should not be deleted") ? static_cast
<void> (0) : __assert_fail ("(data().DefaultedCopyConstructorIsDeleted || needsOverloadResolutionForCopyConstructor()) && \"Copy constructor should not be deleted\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/include/clang/AST/DeclCXX.h"
, 836, __PRETTY_FUNCTION__))
836 "Copy constructor should not be deleted")(((data().DefaultedCopyConstructorIsDeleted || needsOverloadResolutionForCopyConstructor
()) && "Copy constructor should not be deleted") ? static_cast
<void> (0) : __assert_fail ("(data().DefaultedCopyConstructorIsDeleted || needsOverloadResolutionForCopyConstructor()) && \"Copy constructor should not be deleted\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/include/clang/AST/DeclCXX.h"
, 836, __PRETTY_FUNCTION__))
;
837 data().DefaultedCopyConstructorIsDeleted = true;
838 }
839
840 /// Set that we attempted to declare an implicit move
841 /// constructor, but overload resolution failed so we deleted it.
842 void setImplicitMoveConstructorIsDeleted() {
843 assert((data().DefaultedMoveConstructorIsDeleted ||(((data().DefaultedMoveConstructorIsDeleted || needsOverloadResolutionForMoveConstructor
()) && "move constructor should not be deleted") ? static_cast
<void> (0) : __assert_fail ("(data().DefaultedMoveConstructorIsDeleted || needsOverloadResolutionForMoveConstructor()) && \"move constructor should not be deleted\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/include/clang/AST/DeclCXX.h"
, 845, __PRETTY_FUNCTION__))
844 needsOverloadResolutionForMoveConstructor()) &&(((data().DefaultedMoveConstructorIsDeleted || needsOverloadResolutionForMoveConstructor
()) && "move constructor should not be deleted") ? static_cast
<void> (0) : __assert_fail ("(data().DefaultedMoveConstructorIsDeleted || needsOverloadResolutionForMoveConstructor()) && \"move constructor should not be deleted\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/include/clang/AST/DeclCXX.h"
, 845, __PRETTY_FUNCTION__))
845 "move constructor should not be deleted")(((data().DefaultedMoveConstructorIsDeleted || needsOverloadResolutionForMoveConstructor
()) && "move constructor should not be deleted") ? static_cast
<void> (0) : __assert_fail ("(data().DefaultedMoveConstructorIsDeleted || needsOverloadResolutionForMoveConstructor()) && \"move constructor should not be deleted\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/include/clang/AST/DeclCXX.h"
, 845, __PRETTY_FUNCTION__))
;
846 data().DefaultedMoveConstructorIsDeleted = true;
847 }
848
849 /// Set that we attempted to declare an implicit destructor,
850 /// but overload resolution failed so we deleted it.
851 void setImplicitDestructorIsDeleted() {
852 assert((data().DefaultedDestructorIsDeleted ||(((data().DefaultedDestructorIsDeleted || needsOverloadResolutionForDestructor
()) && "destructor should not be deleted") ? static_cast
<void> (0) : __assert_fail ("(data().DefaultedDestructorIsDeleted || needsOverloadResolutionForDestructor()) && \"destructor should not be deleted\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/include/clang/AST/DeclCXX.h"
, 854, __PRETTY_FUNCTION__))
853 needsOverloadResolutionForDestructor()) &&(((data().DefaultedDestructorIsDeleted || needsOverloadResolutionForDestructor
()) && "destructor should not be deleted") ? static_cast
<void> (0) : __assert_fail ("(data().DefaultedDestructorIsDeleted || needsOverloadResolutionForDestructor()) && \"destructor should not be deleted\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/include/clang/AST/DeclCXX.h"
, 854, __PRETTY_FUNCTION__))
854 "destructor should not be deleted")(((data().DefaultedDestructorIsDeleted || needsOverloadResolutionForDestructor
()) && "destructor should not be deleted") ? static_cast
<void> (0) : __assert_fail ("(data().DefaultedDestructorIsDeleted || needsOverloadResolutionForDestructor()) && \"destructor should not be deleted\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/include/clang/AST/DeclCXX.h"
, 854, __PRETTY_FUNCTION__))
;
855 data().DefaultedDestructorIsDeleted = true;
856 }
857
858 /// Determine whether this class should get an implicit move
859 /// constructor or if any existing special member function inhibits this.
860 bool needsImplicitMoveConstructor() const {
861 return !(data().DeclaredSpecialMembers & SMF_MoveConstructor) &&
862 !hasUserDeclaredCopyConstructor() &&
863 !hasUserDeclaredCopyAssignment() &&
864 !hasUserDeclaredMoveAssignment() &&
865 !hasUserDeclaredDestructor();
866 }
867
868 /// Determine whether we need to eagerly declare a defaulted move
869 /// constructor for this class.
870 bool needsOverloadResolutionForMoveConstructor() const {
871 return data().NeedOverloadResolutionForMoveConstructor;
872 }
873
874 /// Determine whether this class has a user-declared copy assignment
875 /// operator.
876 ///
877 /// When false, a copy assignment operator will be implicitly declared.
878 bool hasUserDeclaredCopyAssignment() const {
879 return data().UserDeclaredSpecialMembers & SMF_CopyAssignment;
880 }
881
882 /// Set that we attempted to declare an implicit copy assignment
883 /// operator, but overload resolution failed so we deleted it.
884 void setImplicitCopyAssignmentIsDeleted() {
885 assert((data().DefaultedCopyAssignmentIsDeleted ||(((data().DefaultedCopyAssignmentIsDeleted || needsOverloadResolutionForCopyAssignment
()) && "copy assignment should not be deleted") ? static_cast
<void> (0) : __assert_fail ("(data().DefaultedCopyAssignmentIsDeleted || needsOverloadResolutionForCopyAssignment()) && \"copy assignment should not be deleted\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/include/clang/AST/DeclCXX.h"
, 887, __PRETTY_FUNCTION__))
886 needsOverloadResolutionForCopyAssignment()) &&(((data().DefaultedCopyAssignmentIsDeleted || needsOverloadResolutionForCopyAssignment
()) && "copy assignment should not be deleted") ? static_cast
<void> (0) : __assert_fail ("(data().DefaultedCopyAssignmentIsDeleted || needsOverloadResolutionForCopyAssignment()) && \"copy assignment should not be deleted\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/include/clang/AST/DeclCXX.h"
, 887, __PRETTY_FUNCTION__))
887 "copy assignment should not be deleted")(((data().DefaultedCopyAssignmentIsDeleted || needsOverloadResolutionForCopyAssignment
()) && "copy assignment should not be deleted") ? static_cast
<void> (0) : __assert_fail ("(data().DefaultedCopyAssignmentIsDeleted || needsOverloadResolutionForCopyAssignment()) && \"copy assignment should not be deleted\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/include/clang/AST/DeclCXX.h"
, 887, __PRETTY_FUNCTION__))
;
888 data().DefaultedCopyAssignmentIsDeleted = true;
889 }
890
891 /// Determine whether this class needs an implicit copy
892 /// assignment operator to be lazily declared.
893 bool needsImplicitCopyAssignment() const {
894 return !(data().DeclaredSpecialMembers & SMF_CopyAssignment);
895 }
896
897 /// Determine whether we need to eagerly declare a defaulted copy
898 /// assignment operator for this class.
899 bool needsOverloadResolutionForCopyAssignment() const {
900 // C++20 [class.copy.assign]p2:
901 // If the class definition declares a move constructor or move assignment
902 // operator, the implicitly declared copy assignment operator is defined
903 // as deleted.
904 // In MSVC mode, sometimes a declared move constructor does not delete an
905 // implicit copy assignment, so defer this choice to Sema.
906 if (data().UserDeclaredSpecialMembers &
907 (SMF_MoveConstructor | SMF_MoveAssignment))
908 return true;
909 return data().NeedOverloadResolutionForCopyAssignment;
910 }
911
912 /// Determine whether an implicit copy assignment operator for this
913 /// type would have a parameter with a const-qualified reference type.
914 bool implicitCopyAssignmentHasConstParam() const {
915 return data().ImplicitCopyAssignmentHasConstParam;
916 }
917
918 /// Determine whether this class has a copy assignment operator with
919 /// a parameter type which is a reference to a const-qualified type or is not
920 /// a reference.
921 bool hasCopyAssignmentWithConstParam() const {
922 return data().HasDeclaredCopyAssignmentWithConstParam ||
923 (needsImplicitCopyAssignment() &&
924 implicitCopyAssignmentHasConstParam());
925 }
926
927 /// Determine whether this class has had a move assignment
928 /// declared by the user.
929 bool hasUserDeclaredMoveAssignment() const {
930 return data().UserDeclaredSpecialMembers & SMF_MoveAssignment;
931 }
932
933 /// Determine whether this class has a move assignment operator.
934 bool hasMoveAssignment() const {
935 return (data().DeclaredSpecialMembers & SMF_MoveAssignment) ||
936 needsImplicitMoveAssignment();
937 }
938
939 /// Set that we attempted to declare an implicit move assignment
940 /// operator, but overload resolution failed so we deleted it.
941 void setImplicitMoveAssignmentIsDeleted() {
942 assert((data().DefaultedMoveAssignmentIsDeleted ||(((data().DefaultedMoveAssignmentIsDeleted || needsOverloadResolutionForMoveAssignment
()) && "move assignment should not be deleted") ? static_cast
<void> (0) : __assert_fail ("(data().DefaultedMoveAssignmentIsDeleted || needsOverloadResolutionForMoveAssignment()) && \"move assignment should not be deleted\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/include/clang/AST/DeclCXX.h"
, 944, __PRETTY_FUNCTION__))
943 needsOverloadResolutionForMoveAssignment()) &&(((data().DefaultedMoveAssignmentIsDeleted || needsOverloadResolutionForMoveAssignment
()) && "move assignment should not be deleted") ? static_cast
<void> (0) : __assert_fail ("(data().DefaultedMoveAssignmentIsDeleted || needsOverloadResolutionForMoveAssignment()) && \"move assignment should not be deleted\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/include/clang/AST/DeclCXX.h"
, 944, __PRETTY_FUNCTION__))
944 "move assignment should not be deleted")(((data().DefaultedMoveAssignmentIsDeleted || needsOverloadResolutionForMoveAssignment
()) && "move assignment should not be deleted") ? static_cast
<void> (0) : __assert_fail ("(data().DefaultedMoveAssignmentIsDeleted || needsOverloadResolutionForMoveAssignment()) && \"move assignment should not be deleted\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/include/clang/AST/DeclCXX.h"
, 944, __PRETTY_FUNCTION__))
;
945 data().DefaultedMoveAssignmentIsDeleted = true;
946 }
947
948 /// Determine whether this class should get an implicit move
949 /// assignment operator or if any existing special member function inhibits
950 /// this.
951 bool needsImplicitMoveAssignment() const {
952 return !(data().DeclaredSpecialMembers & SMF_MoveAssignment) &&
953 !hasUserDeclaredCopyConstructor() &&
954 !hasUserDeclaredCopyAssignment() &&
955 !hasUserDeclaredMoveConstructor() &&
956 !hasUserDeclaredDestructor() &&
957 (!isLambda() || lambdaIsDefaultConstructibleAndAssignable());
958 }
959
960 /// Determine whether we need to eagerly declare a move assignment
961 /// operator for this class.
962 bool needsOverloadResolutionForMoveAssignment() const {
963 return data().NeedOverloadResolutionForMoveAssignment;
964 }
965
966 /// Determine whether this class has a user-declared destructor.
967 ///
968 /// When false, a destructor will be implicitly declared.
969 bool hasUserDeclaredDestructor() const {
970 return data().UserDeclaredSpecialMembers & SMF_Destructor;
971 }
972
973 /// Determine whether this class needs an implicit destructor to
974 /// be lazily declared.
975 bool needsImplicitDestructor() const {
976 return !(data().DeclaredSpecialMembers & SMF_Destructor);
977 }
978
979 /// Determine whether we need to eagerly declare a destructor for this
980 /// class.
981 bool needsOverloadResolutionForDestructor() const {
982 return data().NeedOverloadResolutionForDestructor;
983 }
984
985 /// Determine whether this class describes a lambda function object.
986 bool isLambda() const {
987 // An update record can't turn a non-lambda into a lambda.
988 auto *DD = DefinitionData;
989 return DD && DD->IsLambda;
4
Assuming 'DD' is non-null
5
Returning value, which participates in a condition later
990 }
991
992 /// Determine whether this class describes a generic
993 /// lambda function object (i.e. function call operator is
994 /// a template).
995 bool isGenericLambda() const;
996
997 /// Determine whether this lambda should have an implicit default constructor
998 /// and copy and move assignment operators.
999 bool lambdaIsDefaultConstructibleAndAssignable() const;
1000
1001 /// Retrieve the lambda call operator of the closure type
1002 /// if this is a closure type.
1003 CXXMethodDecl *getLambdaCallOperator() const;
1004
1005 /// Retrieve the dependent lambda call operator of the closure type
1006 /// if this is a templated closure type.
1007 FunctionTemplateDecl *getDependentLambdaCallOperator() const;
1008
1009 /// Retrieve the lambda static invoker, the address of which
1010 /// is returned by the conversion operator, and the body of which
1011 /// is forwarded to the lambda call operator. The version that does not
1012 /// take a calling convention uses the 'default' calling convention for free
1013 /// functions if the Lambda's calling convention was not modified via
1014 /// attribute. Otherwise, it will return the calling convention specified for
1015 /// the lambda.
1016 CXXMethodDecl *getLambdaStaticInvoker() const;
1017 CXXMethodDecl *getLambdaStaticInvoker(CallingConv CC) const;
1018
1019 /// Retrieve the generic lambda's template parameter list.
1020 /// Returns null if the class does not represent a lambda or a generic
1021 /// lambda.
1022 TemplateParameterList *getGenericLambdaTemplateParameterList() const;
1023
1024 /// Retrieve the lambda template parameters that were specified explicitly.
1025 ArrayRef<NamedDecl *> getLambdaExplicitTemplateParameters() const;
1026
1027 LambdaCaptureDefault getLambdaCaptureDefault() const {
1028 assert(isLambda())((isLambda()) ? static_cast<void> (0) : __assert_fail (
"isLambda()", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/include/clang/AST/DeclCXX.h"
, 1028, __PRETTY_FUNCTION__))
;
1029 return static_cast<LambdaCaptureDefault>(getLambdaData().CaptureDefault);
1030 }
1031
1032 /// Set the captures for this lambda closure type.
1033 void setCaptures(ASTContext &Context, ArrayRef<LambdaCapture> Captures);
1034
1035 /// For a closure type, retrieve the mapping from captured
1036 /// variables and \c this to the non-static data members that store the
1037 /// values or references of the captures.
1038 ///
1039 /// \param Captures Will be populated with the mapping from captured
1040 /// variables to the corresponding fields.
1041 ///
1042 /// \param ThisCapture Will be set to the field declaration for the
1043 /// \c this capture.
1044 ///
1045 /// \note No entries will be added for init-captures, as they do not capture
1046 /// variables.
1047 void getCaptureFields(llvm::DenseMap<const VarDecl *, FieldDecl *> &Captures,
1048 FieldDecl *&ThisCapture) const;
1049
1050 using capture_const_iterator = const LambdaCapture *;
1051 using capture_const_range = llvm::iterator_range<capture_const_iterator>;
1052
1053 capture_const_range captures() const {
1054 return capture_const_range(captures_begin(), captures_end());
1055 }
1056
1057 capture_const_iterator captures_begin() const {
1058 return isLambda() ? getLambdaData().Captures : nullptr;
1059 }
1060
1061 capture_const_iterator captures_end() const {
1062 return isLambda() ? captures_begin() + getLambdaData().NumCaptures
1063 : nullptr;
1064 }
1065
1066 unsigned capture_size() const { return getLambdaData().NumCaptures; }
1067
1068 using conversion_iterator = UnresolvedSetIterator;
1069
1070 conversion_iterator conversion_begin() const {
1071 return data().Conversions.get(getASTContext()).begin();
1072 }
1073
1074 conversion_iterator conversion_end() const {
1075 return data().Conversions.get(getASTContext()).end();
1076 }
1077
1078 /// Removes a conversion function from this class. The conversion
1079 /// function must currently be a member of this class. Furthermore,
1080 /// this class must currently be in the process of being defined.
1081 void removeConversion(const NamedDecl *Old);
1082
1083 /// Get all conversion functions visible in current class,
1084 /// including conversion function templates.
1085 llvm::iterator_range<conversion_iterator>
1086 getVisibleConversionFunctions() const;
1087
1088 /// Determine whether this class is an aggregate (C++ [dcl.init.aggr]),
1089 /// which is a class with no user-declared constructors, no private
1090 /// or protected non-static data members, no base classes, and no virtual
1091 /// functions (C++ [dcl.init.aggr]p1).
1092 bool isAggregate() const { return data().Aggregate; }
1093
1094 /// Whether this class has any in-class initializers
1095 /// for non-static data members (including those in anonymous unions or
1096 /// structs).
1097 bool hasInClassInitializer() const { return data().HasInClassInitializer; }
1098
1099 /// Whether this class or any of its subobjects has any members of
1100 /// reference type which would make value-initialization ill-formed.
1101 ///
1102 /// Per C++03 [dcl.init]p5:
1103 /// - if T is a non-union class type without a user-declared constructor,
1104 /// then every non-static data member and base-class component of T is
1105 /// value-initialized [...] A program that calls for [...]
1106 /// value-initialization of an entity of reference type is ill-formed.
1107 bool hasUninitializedReferenceMember() const {
1108 return !isUnion() && !hasUserDeclaredConstructor() &&
1109 data().HasUninitializedReferenceMember;
1110 }
1111
1112 /// Whether this class is a POD-type (C++ [class]p4)
1113 ///
1114 /// For purposes of this function a class is POD if it is an aggregate
1115 /// that has no non-static non-POD data members, no reference data
1116 /// members, no user-defined copy assignment operator and no
1117 /// user-defined destructor.
1118 ///
1119 /// Note that this is the C++ TR1 definition of POD.
1120 bool isPOD() const { return data().PlainOldData; }
1121
1122 /// True if this class is C-like, without C++-specific features, e.g.
1123 /// it contains only public fields, no bases, tag kind is not 'class', etc.
1124 bool isCLike() const;
1125
1126 /// Determine whether this is an empty class in the sense of
1127 /// (C++11 [meta.unary.prop]).
1128 ///
1129 /// The CXXRecordDecl is a class type, but not a union type,
1130 /// with no non-static data members other than bit-fields of length 0,
1131 /// no virtual member functions, no virtual base classes,
1132 /// and no base class B for which is_empty<B>::value is false.
1133 ///
1134 /// \note This does NOT include a check for union-ness.
1135 bool isEmpty() const { return data().Empty; }
1136
1137 bool hasPrivateFields() const {
1138 return data().HasPrivateFields;
1139 }
1140
1141 bool hasProtectedFields() const {
1142 return data().HasProtectedFields;
1143 }
1144
1145 /// Determine whether this class has direct non-static data members.
1146 bool hasDirectFields() const {
1147 auto &D = data();
1148 return D.HasPublicFields || D.HasProtectedFields || D.HasPrivateFields;
1149 }
1150
1151 /// Whether this class is polymorphic (C++ [class.virtual]),
1152 /// which means that the class contains or inherits a virtual function.
1153 bool isPolymorphic() const { return data().Polymorphic; }
1154
1155 /// Determine whether this class has a pure virtual function.
1156 ///
1157 /// The class is is abstract per (C++ [class.abstract]p2) if it declares
1158 /// a pure virtual function or inherits a pure virtual function that is
1159 /// not overridden.
1160 bool isAbstract() const { return data().Abstract; }
1161
1162 /// Determine whether this class is standard-layout per
1163 /// C++ [class]p7.
1164 bool isStandardLayout() const { return data().IsStandardLayout; }
1165
1166 /// Determine whether this class was standard-layout per
1167 /// C++11 [class]p7, specifically using the C++11 rules without any DRs.
1168 bool isCXX11StandardLayout() const { return data().IsCXX11StandardLayout; }
1169
1170 /// Determine whether this class, or any of its class subobjects,
1171 /// contains a mutable field.
1172 bool hasMutableFields() const { return data().HasMutableFields; }
1173
1174 /// Determine whether this class has any variant members.
1175 bool hasVariantMembers() const { return data().HasVariantMembers; }
1176
1177 /// Determine whether this class has a trivial default constructor
1178 /// (C++11 [class.ctor]p5).
1179 bool hasTrivialDefaultConstructor() const {
1180 return hasDefaultConstructor() &&
1181 (data().HasTrivialSpecialMembers & SMF_DefaultConstructor);
1182 }
1183
1184 /// Determine whether this class has a non-trivial default constructor
1185 /// (C++11 [class.ctor]p5).
1186 bool hasNonTrivialDefaultConstructor() const {
1187 return (data().DeclaredNonTrivialSpecialMembers & SMF_DefaultConstructor) ||
1188 (needsImplicitDefaultConstructor() &&
1189 !(data().HasTrivialSpecialMembers & SMF_DefaultConstructor));
1190 }
1191
1192 /// Determine whether this class has at least one constexpr constructor
1193 /// other than the copy or move constructors.
1194 bool hasConstexprNonCopyMoveConstructor() const {
1195 return data().HasConstexprNonCopyMoveConstructor ||
1196 (needsImplicitDefaultConstructor() &&
1197 defaultedDefaultConstructorIsConstexpr());
1198 }
1199
1200 /// Determine whether a defaulted default constructor for this class
1201 /// would be constexpr.
1202 bool defaultedDefaultConstructorIsConstexpr() const {
1203 return data().DefaultedDefaultConstructorIsConstexpr &&
1204 (!isUnion() || hasInClassInitializer() || !hasVariantMembers() ||
1205 getLangOpts().CPlusPlus20);
1206 }
1207
1208 /// Determine whether this class has a constexpr default constructor.
1209 bool hasConstexprDefaultConstructor() const {
1210 return data().HasConstexprDefaultConstructor ||
1211 (needsImplicitDefaultConstructor() &&
1212 defaultedDefaultConstructorIsConstexpr());
1213 }
1214
1215 /// Determine whether this class has a trivial copy constructor
1216 /// (C++ [class.copy]p6, C++11 [class.copy]p12)
1217 bool hasTrivialCopyConstructor() const {
1218 return data().HasTrivialSpecialMembers & SMF_CopyConstructor;
1219 }
1220
1221 bool hasTrivialCopyConstructorForCall() const {
1222 return data().HasTrivialSpecialMembersForCall & SMF_CopyConstructor;
1223 }
1224
1225 /// Determine whether this class has a non-trivial copy constructor
1226 /// (C++ [class.copy]p6, C++11 [class.copy]p12)
1227 bool hasNonTrivialCopyConstructor() const {
1228 return data().DeclaredNonTrivialSpecialMembers & SMF_CopyConstructor ||
1229 !hasTrivialCopyConstructor();
1230 }
1231
1232 bool hasNonTrivialCopyConstructorForCall() const {
1233 return (data().DeclaredNonTrivialSpecialMembersForCall &
1234 SMF_CopyConstructor) ||
1235 !hasTrivialCopyConstructorForCall();
1236 }
1237
1238 /// Determine whether this class has a trivial move constructor
1239 /// (C++11 [class.copy]p12)
1240 bool hasTrivialMoveConstructor() const {
1241 return hasMoveConstructor() &&
1242 (data().HasTrivialSpecialMembers & SMF_MoveConstructor);
1243 }
1244
1245 bool hasTrivialMoveConstructorForCall() const {
1246 return hasMoveConstructor() &&
1247 (data().HasTrivialSpecialMembersForCall & SMF_MoveConstructor);
1248 }
1249
1250 /// Determine whether this class has a non-trivial move constructor
1251 /// (C++11 [class.copy]p12)
1252 bool hasNonTrivialMoveConstructor() const {
1253 return (data().DeclaredNonTrivialSpecialMembers & SMF_MoveConstructor) ||
1254 (needsImplicitMoveConstructor() &&
1255 !(data().HasTrivialSpecialMembers & SMF_MoveConstructor));
1256 }
1257
1258 bool hasNonTrivialMoveConstructorForCall() const {
1259 return (data().DeclaredNonTrivialSpecialMembersForCall &
1260 SMF_MoveConstructor) ||
1261 (needsImplicitMoveConstructor() &&
1262 !(data().HasTrivialSpecialMembersForCall & SMF_MoveConstructor));
1263 }
1264
1265 /// Determine whether this class has a trivial copy assignment operator
1266 /// (C++ [class.copy]p11, C++11 [class.copy]p25)
1267 bool hasTrivialCopyAssignment() const {
1268 return data().HasTrivialSpecialMembers & SMF_CopyAssignment;
1269 }
1270
1271 /// Determine whether this class has a non-trivial copy assignment
1272 /// operator (C++ [class.copy]p11, C++11 [class.copy]p25)
1273 bool hasNonTrivialCopyAssignment() const {
1274 return data().DeclaredNonTrivialSpecialMembers & SMF_CopyAssignment ||
1275 !hasTrivialCopyAssignment();
1276 }
1277
1278 /// Determine whether this class has a trivial move assignment operator
1279 /// (C++11 [class.copy]p25)
1280 bool hasTrivialMoveAssignment() const {
1281 return hasMoveAssignment() &&
1282 (data().HasTrivialSpecialMembers & SMF_MoveAssignment);
1283 }
1284
1285 /// Determine whether this class has a non-trivial move assignment
1286 /// operator (C++11 [class.copy]p25)
1287 bool hasNonTrivialMoveAssignment() const {
1288 return (data().DeclaredNonTrivialSpecialMembers & SMF_MoveAssignment) ||
1289 (needsImplicitMoveAssignment() &&
1290 !(data().HasTrivialSpecialMembers & SMF_MoveAssignment));
1291 }
1292
1293 /// Determine whether a defaulted default constructor for this class
1294 /// would be constexpr.
1295 bool defaultedDestructorIsConstexpr() const {
1296 return data().DefaultedDestructorIsConstexpr &&
1297 getLangOpts().CPlusPlus20;
1298 }
1299
1300 /// Determine whether this class has a constexpr destructor.
1301 bool hasConstexprDestructor() const;
1302
1303 /// Determine whether this class has a trivial destructor
1304 /// (C++ [class.dtor]p3)
1305 bool hasTrivialDestructor() const {
1306 return data().HasTrivialSpecialMembers & SMF_Destructor;
1307 }
1308
1309 bool hasTrivialDestructorForCall() const {
1310 return data().HasTrivialSpecialMembersForCall & SMF_Destructor;
1311 }
1312
1313 /// Determine whether this class has a non-trivial destructor
1314 /// (C++ [class.dtor]p3)
1315 bool hasNonTrivialDestructor() const {
1316 return !(data().HasTrivialSpecialMembers & SMF_Destructor);
1317 }
1318
1319 bool hasNonTrivialDestructorForCall() const {
1320 return !(data().HasTrivialSpecialMembersForCall & SMF_Destructor);
1321 }
1322
1323 void setHasTrivialSpecialMemberForCall() {
1324 data().HasTrivialSpecialMembersForCall =
1325 (SMF_CopyConstructor | SMF_MoveConstructor | SMF_Destructor);
1326 }
1327
1328 /// Determine whether declaring a const variable with this type is ok
1329 /// per core issue 253.
1330 bool allowConstDefaultInit() const {
1331 return !data().HasUninitializedFields ||
1332 !(data().HasDefaultedDefaultConstructor ||
1333 needsImplicitDefaultConstructor());
1334 }
1335
1336 /// Determine whether this class has a destructor which has no
1337 /// semantic effect.
1338 ///
1339 /// Any such destructor will be trivial, public, defaulted and not deleted,
1340 /// and will call only irrelevant destructors.
1341 bool hasIrrelevantDestructor() const {
1342 return data().HasIrrelevantDestructor;
1343 }
1344
1345 /// Determine whether this class has a non-literal or/ volatile type
1346 /// non-static data member or base class.
1347 bool hasNonLiteralTypeFieldsOrBases() const {
1348 return data().HasNonLiteralTypeFieldsOrBases;
1349 }
1350
1351 /// Determine whether this class has a using-declaration that names
1352 /// a user-declared base class constructor.
1353 bool hasInheritedConstructor() const {
1354 return data().HasInheritedConstructor;
1355 }
1356
1357 /// Determine whether this class has a using-declaration that names
1358 /// a base class assignment operator.
1359 bool hasInheritedAssignment() const {
1360 return data().HasInheritedAssignment;
1361 }
1362
1363 /// Determine whether this class is considered trivially copyable per
1364 /// (C++11 [class]p6).
1365 bool isTriviallyCopyable() const;
1366
1367 /// Determine whether this class is considered trivial.
1368 ///
1369 /// C++11 [class]p6:
1370 /// "A trivial class is a class that has a trivial default constructor and
1371 /// is trivially copyable."
1372 bool isTrivial() const {
1373 return isTriviallyCopyable() && hasTrivialDefaultConstructor();
1374 }
1375
1376 /// Determine whether this class is a literal type.
1377 ///
1378 /// C++11 [basic.types]p10:
1379 /// A class type that has all the following properties:
1380 /// - it has a trivial destructor
1381 /// - every constructor call and full-expression in the
1382 /// brace-or-equal-intializers for non-static data members (if any) is
1383 /// a constant expression.
1384 /// - it is an aggregate type or has at least one constexpr constructor
1385 /// or constructor template that is not a copy or move constructor, and
1386 /// - all of its non-static data members and base classes are of literal
1387 /// types
1388 ///
1389 /// We resolve DR1361 by ignoring the second bullet. We resolve DR1452 by
1390 /// treating types with trivial default constructors as literal types.
1391 ///
1392 /// Only in C++17 and beyond, are lambdas literal types.
1393 bool isLiteral() const {
1394 const LangOptions &LangOpts = getLangOpts();
1395 return (LangOpts.CPlusPlus20 ? hasConstexprDestructor()
1396 : hasTrivialDestructor()) &&
1397 (!isLambda() || LangOpts.CPlusPlus17) &&
1398 !hasNonLiteralTypeFieldsOrBases() &&
1399 (isAggregate() || isLambda() ||
1400 hasConstexprNonCopyMoveConstructor() ||
1401 hasTrivialDefaultConstructor());
1402 }
1403
1404 /// Determine whether this is a structural type.
1405 bool isStructural() const {
1406 return isLiteral() && data().StructuralIfLiteral;
1407 }
1408
1409 /// If this record is an instantiation of a member class,
1410 /// retrieves the member class from which it was instantiated.
1411 ///
1412 /// This routine will return non-null for (non-templated) member
1413 /// classes of class templates. For example, given:
1414 ///
1415 /// \code
1416 /// template<typename T>
1417 /// struct X {
1418 /// struct A { };
1419 /// };
1420 /// \endcode
1421 ///
1422 /// The declaration for X<int>::A is a (non-templated) CXXRecordDecl
1423 /// whose parent is the class template specialization X<int>. For
1424 /// this declaration, getInstantiatedFromMemberClass() will return
1425 /// the CXXRecordDecl X<T>::A. When a complete definition of
1426 /// X<int>::A is required, it will be instantiated from the
1427 /// declaration returned by getInstantiatedFromMemberClass().
1428 CXXRecordDecl *getInstantiatedFromMemberClass() const;
1429
1430 /// If this class is an instantiation of a member class of a
1431 /// class template specialization, retrieves the member specialization
1432 /// information.
1433 MemberSpecializationInfo *getMemberSpecializationInfo() const;
1434
1435 /// Specify that this record is an instantiation of the
1436 /// member class \p RD.
1437 void setInstantiationOfMemberClass(CXXRecordDecl *RD,
1438 TemplateSpecializationKind TSK);
1439
1440 /// Retrieves the class template that is described by this
1441 /// class declaration.
1442 ///
1443 /// Every class template is represented as a ClassTemplateDecl and a
1444 /// CXXRecordDecl. The former contains template properties (such as
1445 /// the template parameter lists) while the latter contains the
1446 /// actual description of the template's
1447 /// contents. ClassTemplateDecl::getTemplatedDecl() retrieves the
1448 /// CXXRecordDecl that from a ClassTemplateDecl, while
1449 /// getDescribedClassTemplate() retrieves the ClassTemplateDecl from
1450 /// a CXXRecordDecl.
1451 ClassTemplateDecl *getDescribedClassTemplate() const;
1452
1453 void setDescribedClassTemplate(ClassTemplateDecl *Template);
1454
1455 /// Determine whether this particular class is a specialization or
1456 /// instantiation of a class template or member class of a class template,
1457 /// and how it was instantiated or specialized.
1458 TemplateSpecializationKind getTemplateSpecializationKind() const;
1459
1460 /// Set the kind of specialization or template instantiation this is.
1461 void setTemplateSpecializationKind(TemplateSpecializationKind TSK);
1462
1463 /// Retrieve the record declaration from which this record could be
1464 /// instantiated. Returns null if this class is not a template instantiation.
1465 const CXXRecordDecl *getTemplateInstantiationPattern() const;
1466
1467 CXXRecordDecl *getTemplateInstantiationPattern() {
1468 return const_cast<CXXRecordDecl *>(const_cast<const CXXRecordDecl *>(this)
1469 ->getTemplateInstantiationPattern());
1470 }
1471
1472 /// Returns the destructor decl for this class.
1473 CXXDestructorDecl *getDestructor() const;
1474
1475 /// Returns true if the class destructor, or any implicitly invoked
1476 /// destructors are marked noreturn.
1477 bool isAnyDestructorNoReturn() const;
1478
1479 /// If the class is a local class [class.local], returns
1480 /// the enclosing function declaration.
1481 const FunctionDecl *isLocalClass() const {
1482 if (const auto *RD = dyn_cast<CXXRecordDecl>(getDeclContext()))
1483 return RD->isLocalClass();
1484
1485 return dyn_cast<FunctionDecl>(getDeclContext());
1486 }
1487
1488 FunctionDecl *isLocalClass() {
1489 return const_cast<FunctionDecl*>(
1490 const_cast<const CXXRecordDecl*>(this)->isLocalClass());
1491 }
1492
1493 /// Determine whether this dependent class is a current instantiation,
1494 /// when viewed from within the given context.
1495 bool isCurrentInstantiation(const DeclContext *CurContext) const;
1496
1497 /// Determine whether this class is derived from the class \p Base.
1498 ///
1499 /// This routine only determines whether this class is derived from \p Base,
1500 /// but does not account for factors that may make a Derived -> Base class
1501 /// ill-formed, such as private/protected inheritance or multiple, ambiguous
1502 /// base class subobjects.
1503 ///
1504 /// \param Base the base class we are searching for.
1505 ///
1506 /// \returns true if this class is derived from Base, false otherwise.
1507 bool isDerivedFrom(const CXXRecordDecl *Base) const;
1508
1509 /// Determine whether this class is derived from the type \p Base.
1510 ///
1511 /// This routine only determines whether this class is derived from \p Base,
1512 /// but does not account for factors that may make a Derived -> Base class
1513 /// ill-formed, such as private/protected inheritance or multiple, ambiguous
1514 /// base class subobjects.
1515 ///
1516 /// \param Base the base class we are searching for.
1517 ///
1518 /// \param Paths will contain the paths taken from the current class to the
1519 /// given \p Base class.
1520 ///
1521 /// \returns true if this class is derived from \p Base, false otherwise.
1522 ///
1523 /// \todo add a separate parameter to configure IsDerivedFrom, rather than
1524 /// tangling input and output in \p Paths
1525 bool isDerivedFrom(const CXXRecordDecl *Base, CXXBasePaths &Paths) const;
1526
1527 /// Determine whether this class is virtually derived from
1528 /// the class \p Base.
1529 ///
1530 /// This routine only determines whether this class is virtually
1531 /// derived from \p Base, but does not account for factors that may
1532 /// make a Derived -> Base class ill-formed, such as
1533 /// private/protected inheritance or multiple, ambiguous base class
1534 /// subobjects.
1535 ///
1536 /// \param Base the base class we are searching for.
1537 ///
1538 /// \returns true if this class is virtually derived from Base,
1539 /// false otherwise.
1540 bool isVirtuallyDerivedFrom(const CXXRecordDecl *Base) const;
1541
1542 /// Determine whether this class is provably not derived from
1543 /// the type \p Base.
1544 bool isProvablyNotDerivedFrom(const CXXRecordDecl *Base) const;
1545
1546 /// Function type used by forallBases() as a callback.
1547 ///
1548 /// \param BaseDefinition the definition of the base class
1549 ///
1550 /// \returns true if this base matched the search criteria
1551 using ForallBasesCallback =
1552 llvm::function_ref<bool(const CXXRecordDecl *BaseDefinition)>;
1553
1554 /// Determines if the given callback holds for all the direct
1555 /// or indirect base classes of this type.
1556 ///
1557 /// The class itself does not count as a base class. This routine
1558 /// returns false if the class has non-computable base classes.
1559 ///
1560 /// \param BaseMatches Callback invoked for each (direct or indirect) base
1561 /// class of this type until a call returns false.
1562 bool forallBases(ForallBasesCallback BaseMatches) const;
1563
1564 /// Function type used by lookupInBases() to determine whether a
1565 /// specific base class subobject matches the lookup criteria.
1566 ///
1567 /// \param Specifier the base-class specifier that describes the inheritance
1568 /// from the base class we are trying to match.
1569 ///
1570 /// \param Path the current path, from the most-derived class down to the
1571 /// base named by the \p Specifier.
1572 ///
1573 /// \returns true if this base matched the search criteria, false otherwise.
1574 using BaseMatchesCallback =
1575 llvm::function_ref<bool(const CXXBaseSpecifier *Specifier,
1576 CXXBasePath &Path)>;
1577
1578 /// Look for entities within the base classes of this C++ class,
1579 /// transitively searching all base class subobjects.
1580 ///
1581 /// This routine uses the callback function \p BaseMatches to find base
1582 /// classes meeting some search criteria, walking all base class subobjects
1583 /// and populating the given \p Paths structure with the paths through the
1584 /// inheritance hierarchy that resulted in a match. On a successful search,
1585 /// the \p Paths structure can be queried to retrieve the matching paths and
1586 /// to determine if there were any ambiguities.
1587 ///
1588 /// \param BaseMatches callback function used to determine whether a given
1589 /// base matches the user-defined search criteria.
1590 ///
1591 /// \param Paths used to record the paths from this class to its base class
1592 /// subobjects that match the search criteria.
1593 ///
1594 /// \param LookupInDependent can be set to true to extend the search to
1595 /// dependent base classes.
1596 ///
1597 /// \returns true if there exists any path from this class to a base class
1598 /// subobject that matches the search criteria.
1599 bool lookupInBases(BaseMatchesCallback BaseMatches, CXXBasePaths &Paths,
1600 bool LookupInDependent = false) const;
1601
1602 /// Base-class lookup callback that determines whether the given
1603 /// base class specifier refers to a specific class declaration.
1604 ///
1605 /// This callback can be used with \c lookupInBases() to determine whether
1606 /// a given derived class has is a base class subobject of a particular type.
1607 /// The base record pointer should refer to the canonical CXXRecordDecl of the
1608 /// base class that we are searching for.
1609 static bool FindBaseClass(const CXXBaseSpecifier *Specifier,
1610 CXXBasePath &Path, const CXXRecordDecl *BaseRecord);
1611
1612 /// Base-class lookup callback that determines whether the
1613 /// given base class specifier refers to a specific class
1614 /// declaration and describes virtual derivation.
1615 ///
1616 /// This callback can be used with \c lookupInBases() to determine
1617 /// whether a given derived class has is a virtual base class
1618 /// subobject of a particular type. The base record pointer should
1619 /// refer to the canonical CXXRecordDecl of the base class that we
1620 /// are searching for.
1621 static bool FindVirtualBaseClass(const CXXBaseSpecifier *Specifier,
1622 CXXBasePath &Path,
1623 const CXXRecordDecl *BaseRecord);
1624
1625 /// Base-class lookup callback that determines whether there exists
1626 /// a tag with the given name.
1627 ///
1628 /// This callback can be used with \c lookupInBases() to find tag members
1629 /// of the given name within a C++ class hierarchy.
1630 static bool FindTagMember(const CXXBaseSpecifier *Specifier,
1631 CXXBasePath &Path, DeclarationName Name);
1632
1633 /// Base-class lookup callback that determines whether there exists
1634 /// a member with the given name.
1635 ///
1636 /// This callback can be used with \c lookupInBases() to find members
1637 /// of the given name within a C++ class hierarchy.
1638 static bool FindOrdinaryMember(const CXXBaseSpecifier *Specifier,
1639 CXXBasePath &Path, DeclarationName Name);
1640
1641 /// Base-class lookup callback that determines whether there exists
1642 /// a member with the given name.
1643 ///
1644 /// This callback can be used with \c lookupInBases() to find members
1645 /// of the given name within a C++ class hierarchy, including dependent
1646 /// classes.
1647 static bool
1648 FindOrdinaryMemberInDependentClasses(const CXXBaseSpecifier *Specifier,
1649 CXXBasePath &Path, DeclarationName Name);
1650
1651 /// Base-class lookup callback that determines whether there exists
1652 /// an OpenMP declare reduction member with the given name.
1653 ///
1654 /// This callback can be used with \c lookupInBases() to find members
1655 /// of the given name within a C++ class hierarchy.
1656 static bool FindOMPReductionMember(const CXXBaseSpecifier *Specifier,
1657 CXXBasePath &Path, DeclarationName Name);
1658
1659 /// Base-class lookup callback that determines whether there exists
1660 /// an OpenMP declare mapper member with the given name.
1661 ///
1662 /// This callback can be used with \c lookupInBases() to find members
1663 /// of the given name within a C++ class hierarchy.
1664 static bool FindOMPMapperMember(const CXXBaseSpecifier *Specifier,
1665 CXXBasePath &Path, DeclarationName Name);
1666
1667 /// Base-class lookup callback that determines whether there exists
1668 /// a member with the given name that can be used in a nested-name-specifier.
1669 ///
1670 /// This callback can be used with \c lookupInBases() to find members of
1671 /// the given name within a C++ class hierarchy that can occur within
1672 /// nested-name-specifiers.
1673 static bool FindNestedNameSpecifierMember(const CXXBaseSpecifier *Specifier,
1674 CXXBasePath &Path,
1675 DeclarationName Name);
1676
1677 /// Retrieve the final overriders for each virtual member
1678 /// function in the class hierarchy where this class is the
1679 /// most-derived class in the class hierarchy.
1680 void getFinalOverriders(CXXFinalOverriderMap &FinaOverriders) const;
1681
1682 /// Get the indirect primary bases for this class.
1683 void getIndirectPrimaryBases(CXXIndirectPrimaryBaseSet& Bases) const;
1684
1685 /// Performs an imprecise lookup of a dependent name in this class.
1686 ///
1687 /// This function does not follow strict semantic rules and should be used
1688 /// only when lookup rules can be relaxed, e.g. indexing.
1689 std::vector<const NamedDecl *>
1690 lookupDependentName(const DeclarationName &Name,
1691 llvm::function_ref<bool(const NamedDecl *ND)> Filter);
1692
1693 /// Renders and displays an inheritance diagram
1694 /// for this C++ class and all of its base classes (transitively) using
1695 /// GraphViz.
1696 void viewInheritance(ASTContext& Context) const;
1697
1698 /// Calculates the access of a decl that is reached
1699 /// along a path.
1700 static AccessSpecifier MergeAccess(AccessSpecifier PathAccess,
1701 AccessSpecifier DeclAccess) {
1702 assert(DeclAccess != AS_none)((DeclAccess != AS_none) ? static_cast<void> (0) : __assert_fail
("DeclAccess != AS_none", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/include/clang/AST/DeclCXX.h"
, 1702, __PRETTY_FUNCTION__))
;
1703 if (DeclAccess == AS_private) return AS_none;
1704 return (PathAccess > DeclAccess ? PathAccess : DeclAccess);
1705 }
1706
1707 /// Indicates that the declaration of a defaulted or deleted special
1708 /// member function is now complete.
1709 void finishedDefaultedOrDeletedMember(CXXMethodDecl *MD);
1710
1711 void setTrivialForCallFlags(CXXMethodDecl *MD);
1712
1713 /// Indicates that the definition of this class is now complete.
1714 void completeDefinition() override;
1715
1716 /// Indicates that the definition of this class is now complete,
1717 /// and provides a final overrider map to help determine
1718 ///
1719 /// \param FinalOverriders The final overrider map for this class, which can
1720 /// be provided as an optimization for abstract-class checking. If NULL,
1721 /// final overriders will be computed if they are needed to complete the
1722 /// definition.
1723 void completeDefinition(CXXFinalOverriderMap *FinalOverriders);
1724
1725 /// Determine whether this class may end up being abstract, even though
1726 /// it is not yet known to be abstract.
1727 ///
1728 /// \returns true if this class is not known to be abstract but has any
1729 /// base classes that are abstract. In this case, \c completeDefinition()
1730 /// will need to compute final overriders to determine whether the class is
1731 /// actually abstract.
1732 bool mayBeAbstract() const;
1733
1734 /// Determine whether it's impossible for a class to be derived from this
1735 /// class. This is best-effort, and may conservatively return false.
1736 bool isEffectivelyFinal() const;
1737
1738 /// If this is the closure type of a lambda expression, retrieve the
1739 /// number to be used for name mangling in the Itanium C++ ABI.
1740 ///
1741 /// Zero indicates that this closure type has internal linkage, so the
1742 /// mangling number does not matter, while a non-zero value indicates which
1743 /// lambda expression this is in this particular context.
1744 unsigned getLambdaManglingNumber() const {
1745 assert(isLambda() && "Not a lambda closure type!")((isLambda() && "Not a lambda closure type!") ? static_cast
<void> (0) : __assert_fail ("isLambda() && \"Not a lambda closure type!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/include/clang/AST/DeclCXX.h"
, 1745, __PRETTY_FUNCTION__))
;
1746 return getLambdaData().ManglingNumber;
1747 }
1748
1749 /// The lambda is known to has internal linkage no matter whether it has name
1750 /// mangling number.
1751 bool hasKnownLambdaInternalLinkage() const {
1752 assert(isLambda() && "Not a lambda closure type!")((isLambda() && "Not a lambda closure type!") ? static_cast
<void> (0) : __assert_fail ("isLambda() && \"Not a lambda closure type!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/include/clang/AST/DeclCXX.h"
, 1752, __PRETTY_FUNCTION__))
;
1753 return getLambdaData().HasKnownInternalLinkage;
1754 }
1755
1756 /// Retrieve the declaration that provides additional context for a
1757 /// lambda, when the normal declaration context is not specific enough.
1758 ///
1759 /// Certain contexts (default arguments of in-class function parameters and
1760 /// the initializers of data members) have separate name mangling rules for
1761 /// lambdas within the Itanium C++ ABI. For these cases, this routine provides
1762 /// the declaration in which the lambda occurs, e.g., the function parameter
1763 /// or the non-static data member. Otherwise, it returns NULL to imply that
1764 /// the declaration context suffices.
1765 Decl *getLambdaContextDecl() const;
1766
1767 /// Set the mangling number and context declaration for a lambda
1768 /// class.
1769 void setLambdaMangling(unsigned ManglingNumber, Decl *ContextDecl,
1770 bool HasKnownInternalLinkage = false) {
1771 assert(isLambda() && "Not a lambda closure type!")((isLambda() && "Not a lambda closure type!") ? static_cast
<void> (0) : __assert_fail ("isLambda() && \"Not a lambda closure type!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/include/clang/AST/DeclCXX.h"
, 1771, __PRETTY_FUNCTION__))
;
1772 getLambdaData().ManglingNumber = ManglingNumber;
1773 getLambdaData().ContextDecl = ContextDecl;
1774 getLambdaData().HasKnownInternalLinkage = HasKnownInternalLinkage;
1775 }
1776
1777 /// Returns the inheritance model used for this record.
1778 MSInheritanceModel getMSInheritanceModel() const;
1779
1780 /// Calculate what the inheritance model would be for this class.
1781 MSInheritanceModel calculateInheritanceModel() const;
1782
1783 /// In the Microsoft C++ ABI, use zero for the field offset of a null data
1784 /// member pointer if we can guarantee that zero is not a valid field offset,
1785 /// or if the member pointer has multiple fields. Polymorphic classes have a
1786 /// vfptr at offset zero, so we can use zero for null. If there are multiple
1787 /// fields, we can use zero even if it is a valid field offset because
1788 /// null-ness testing will check the other fields.
1789 bool nullFieldOffsetIsZero() const;
1790
1791 /// Controls when vtordisps will be emitted if this record is used as a
1792 /// virtual base.
1793 MSVtorDispMode getMSVtorDispMode() const;
1794
1795 /// Determine whether this lambda expression was known to be dependent
1796 /// at the time it was created, even if its context does not appear to be
1797 /// dependent.
1798 ///
1799 /// This flag is a workaround for an issue with parsing, where default
1800 /// arguments are parsed before their enclosing function declarations have
1801 /// been created. This means that any lambda expressions within those
1802 /// default arguments will have as their DeclContext the context enclosing
1803 /// the function declaration, which may be non-dependent even when the
1804 /// function declaration itself is dependent. This flag indicates when we
1805 /// know that the lambda is dependent despite that.
1806 bool isDependentLambda() const {
1807 return isLambda() && getLambdaData().Dependent;
1808 }
1809
1810 TypeSourceInfo *getLambdaTypeInfo() const {
1811 return getLambdaData().MethodTyInfo;
1812 }
1813
1814 // Determine whether this type is an Interface Like type for
1815 // __interface inheritance purposes.
1816 bool isInterfaceLike() const;
1817
1818 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1819 static bool classofKind(Kind K) {
1820 return K >= firstCXXRecord && K <= lastCXXRecord;
1821 }
1822};
1823
1824/// Store information needed for an explicit specifier.
1825/// Used by CXXDeductionGuideDecl, CXXConstructorDecl and CXXConversionDecl.
1826class ExplicitSpecifier {
1827 llvm::PointerIntPair<Expr *, 2, ExplicitSpecKind> ExplicitSpec{
1828 nullptr, ExplicitSpecKind::ResolvedFalse};
1829
1830public:
1831 ExplicitSpecifier() = default;
1832 ExplicitSpecifier(Expr *Expression, ExplicitSpecKind Kind)
1833 : ExplicitSpec(Expression, Kind) {}
1834 ExplicitSpecKind getKind() const { return ExplicitSpec.getInt(); }
1835 const Expr *getExpr() const { return ExplicitSpec.getPointer(); }
1836 Expr *getExpr() { return ExplicitSpec.getPointer(); }
1837
1838 /// Determine if the declaration had an explicit specifier of any kind.
1839 bool isSpecified() const {
1840 return ExplicitSpec.getInt() != ExplicitSpecKind::ResolvedFalse ||
1841 ExplicitSpec.getPointer();
1842 }
1843
1844 /// Check for equivalence of explicit specifiers.
1845 /// \return true if the explicit specifier are equivalent, false otherwise.
1846 bool isEquivalent(const ExplicitSpecifier Other) const;
1847 /// Determine whether this specifier is known to correspond to an explicit
1848 /// declaration. Returns false if the specifier is absent or has an
1849 /// expression that is value-dependent or evaluates to false.
1850 bool isExplicit() const {
1851 return ExplicitSpec.getInt() == ExplicitSpecKind::ResolvedTrue;
1852 }
1853 /// Determine if the explicit specifier is invalid.
1854 /// This state occurs after a substitution failures.
1855 bool isInvalid() const {
1856 return ExplicitSpec.getInt() == ExplicitSpecKind::Unresolved &&
1857 !ExplicitSpec.getPointer();
1858 }
1859 void setKind(ExplicitSpecKind Kind) { ExplicitSpec.setInt(Kind); }
1860 void setExpr(Expr *E) { ExplicitSpec.setPointer(E); }
1861 // Retrieve the explicit specifier in the given declaration, if any.
1862 static ExplicitSpecifier getFromDecl(FunctionDecl *Function);
1863 static const ExplicitSpecifier getFromDecl(const FunctionDecl *Function) {
1864 return getFromDecl(const_cast<FunctionDecl *>(Function));
1865 }
1866 static ExplicitSpecifier Invalid() {
1867 return ExplicitSpecifier(nullptr, ExplicitSpecKind::Unresolved);
1868 }
1869};
1870
1871/// Represents a C++ deduction guide declaration.
1872///
1873/// \code
1874/// template<typename T> struct A { A(); A(T); };
1875/// A() -> A<int>;
1876/// \endcode
1877///
1878/// In this example, there will be an explicit deduction guide from the
1879/// second line, and implicit deduction guide templates synthesized from
1880/// the constructors of \c A.
1881class CXXDeductionGuideDecl : public FunctionDecl {
1882 void anchor() override;
1883
1884private:
1885 CXXDeductionGuideDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1886 ExplicitSpecifier ES,
1887 const DeclarationNameInfo &NameInfo, QualType T,
1888 TypeSourceInfo *TInfo, SourceLocation EndLocation)
1889 : FunctionDecl(CXXDeductionGuide, C, DC, StartLoc, NameInfo, T, TInfo,
1890 SC_None, false, ConstexprSpecKind::Unspecified),
1891 ExplicitSpec(ES) {
1892 if (EndLocation.isValid())
1893 setRangeEnd(EndLocation);
1894 setIsCopyDeductionCandidate(false);
1895 }
1896
1897 ExplicitSpecifier ExplicitSpec;
1898 void setExplicitSpecifier(ExplicitSpecifier ES) { ExplicitSpec = ES; }
1899
1900public:
1901 friend class ASTDeclReader;
1902 friend class ASTDeclWriter;
1903
1904 static CXXDeductionGuideDecl *
1905 Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1906 ExplicitSpecifier ES, const DeclarationNameInfo &NameInfo, QualType T,
1907 TypeSourceInfo *TInfo, SourceLocation EndLocation);
1908
1909 static CXXDeductionGuideDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1910
1911 ExplicitSpecifier getExplicitSpecifier() { return ExplicitSpec; }
1912 const ExplicitSpecifier getExplicitSpecifier() const { return ExplicitSpec; }
1913
1914 /// Return true if the declartion is already resolved to be explicit.
1915 bool isExplicit() const { return ExplicitSpec.isExplicit(); }
1916
1917 /// Get the template for which this guide performs deduction.
1918 TemplateDecl *getDeducedTemplate() const {
1919 return getDeclName().getCXXDeductionGuideTemplate();
1920 }
1921
1922 void setIsCopyDeductionCandidate(bool isCDC = true) {
1923 FunctionDeclBits.IsCopyDeductionCandidate = isCDC;
1924 }
1925
1926 bool isCopyDeductionCandidate() const {
1927 return FunctionDeclBits.IsCopyDeductionCandidate;
1928 }
1929
1930 // Implement isa/cast/dyncast/etc.
1931 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1932 static bool classofKind(Kind K) { return K == CXXDeductionGuide; }
1933};
1934
1935/// \brief Represents the body of a requires-expression.
1936///
1937/// This decl exists merely to serve as the DeclContext for the local
1938/// parameters of the requires expression as well as other declarations inside
1939/// it.
1940///
1941/// \code
1942/// template<typename T> requires requires (T t) { {t++} -> regular; }
1943/// \endcode
1944///
1945/// In this example, a RequiresExpr object will be generated for the expression,
1946/// and a RequiresExprBodyDecl will be created to hold the parameter t and the
1947/// template argument list imposed by the compound requirement.
1948class RequiresExprBodyDecl : public Decl, public DeclContext {
1949 RequiresExprBodyDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc)
1950 : Decl(RequiresExprBody, DC, StartLoc), DeclContext(RequiresExprBody) {}
1951
1952public:
1953 friend class ASTDeclReader;
1954 friend class ASTDeclWriter;
1955
1956 static RequiresExprBodyDecl *Create(ASTContext &C, DeclContext *DC,
1957 SourceLocation StartLoc);
1958
1959 static RequiresExprBodyDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1960
1961 // Implement isa/cast/dyncast/etc.
1962 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1963 static bool classofKind(Kind K) { return K == RequiresExprBody; }
1964};
1965
1966/// Represents a static or instance method of a struct/union/class.
1967///
1968/// In the terminology of the C++ Standard, these are the (static and
1969/// non-static) member functions, whether virtual or not.
1970class CXXMethodDecl : public FunctionDecl {
1971 void anchor() override;
1972
1973protected:
1974 CXXMethodDecl(Kind DK, ASTContext &C, CXXRecordDecl *RD,
1975 SourceLocation StartLoc, const DeclarationNameInfo &NameInfo,
1976 QualType T, TypeSourceInfo *TInfo, StorageClass SC,
1977 bool isInline, ConstexprSpecKind ConstexprKind,
1978 SourceLocation EndLocation,
1979 Expr *TrailingRequiresClause = nullptr)
1980 : FunctionDecl(DK, C, RD, StartLoc, NameInfo, T, TInfo, SC, isInline,
1981 ConstexprKind, TrailingRequiresClause) {
1982 if (EndLocation.isValid())
1983 setRangeEnd(EndLocation);
1984 }
1985
1986public:
1987 static CXXMethodDecl *Create(ASTContext &C, CXXRecordDecl *RD,
1988 SourceLocation StartLoc,
1989 const DeclarationNameInfo &NameInfo, QualType T,
1990 TypeSourceInfo *TInfo, StorageClass SC,
1991 bool isInline, ConstexprSpecKind ConstexprKind,
1992 SourceLocation EndLocation,
1993 Expr *TrailingRequiresClause = nullptr);
1994
1995 static CXXMethodDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1996
1997 bool isStatic() const;
1998 bool isInstance() const { return !isStatic(); }
1999
2000 /// Returns true if the given operator is implicitly static in a record
2001 /// context.
2002 static bool isStaticOverloadedOperator(OverloadedOperatorKind OOK) {
2003 // [class.free]p1:
2004 // Any allocation function for a class T is a static member
2005 // (even if not explicitly declared static).
2006 // [class.free]p6 Any deallocation function for a class X is a static member
2007 // (even if not explicitly declared static).
2008 return OOK == OO_New || OOK == OO_Array_New || OOK == OO_Delete ||
2009 OOK == OO_Array_Delete;
2010 }
2011
2012 bool isConst() const { return getType()->castAs<FunctionType>()->isConst(); }
2013 bool isVolatile() const { return getType()->castAs<FunctionType>()->isVolatile(); }
2014
2015 bool isVirtual() const {
2016 CXXMethodDecl *CD = const_cast<CXXMethodDecl*>(this)->getCanonicalDecl();
2017
2018 // Member function is virtual if it is marked explicitly so, or if it is
2019 // declared in __interface -- then it is automatically pure virtual.
2020 if (CD->isVirtualAsWritten() || CD->isPure())
2021 return true;
2022
2023 return CD->size_overridden_methods() != 0;
2024 }
2025
2026 /// If it's possible to devirtualize a call to this method, return the called
2027 /// function. Otherwise, return null.
2028
2029 /// \param Base The object on which this virtual function is called.
2030 /// \param IsAppleKext True if we are compiling for Apple kext.
2031 CXXMethodDecl *getDevirtualizedMethod(const Expr *Base, bool IsAppleKext);
2032
2033 const CXXMethodDecl *getDevirtualizedMethod(const Expr *Base,
2034 bool IsAppleKext) const {
2035 return const_cast<CXXMethodDecl *>(this)->getDevirtualizedMethod(
2036 Base, IsAppleKext);
2037 }
2038
2039 /// Determine whether this is a usual deallocation function (C++
2040 /// [basic.stc.dynamic.deallocation]p2), which is an overloaded delete or
2041 /// delete[] operator with a particular signature. Populates \p PreventedBy
2042 /// with the declarations of the functions of the same kind if they were the
2043 /// reason for this function returning false. This is used by
2044 /// Sema::isUsualDeallocationFunction to reconsider the answer based on the
2045 /// context.
2046 bool isUsualDeallocationFunction(
2047 SmallVectorImpl<const FunctionDecl *> &PreventedBy) const;
2048
2049 /// Determine whether this is a copy-assignment operator, regardless
2050 /// of whether it was declared implicitly or explicitly.
2051 bool isCopyAssignmentOperator() const;
2052
2053 /// Determine whether this is a move assignment operator.
2054 bool isMoveAssignmentOperator() const;
2055
2056 CXXMethodDecl *getCanonicalDecl() override {
2057 return cast<CXXMethodDecl>(FunctionDecl::getCanonicalDecl());
2058 }
2059 const CXXMethodDecl *getCanonicalDecl() const {
2060 return const_cast<CXXMethodDecl*>(this)->getCanonicalDecl();
2061 }
2062
2063 CXXMethodDecl *getMostRecentDecl() {
2064 return cast<CXXMethodDecl>(
2065 static_cast<FunctionDecl *>(this)->getMostRecentDecl());
2066 }
2067 const CXXMethodDecl *getMostRecentDecl() const {
2068 return const_cast<CXXMethodDecl*>(this)->getMostRecentDecl();
2069 }
2070
2071 void addOverriddenMethod(const CXXMethodDecl *MD);
2072
2073 using method_iterator = const CXXMethodDecl *const *;
2074
2075 method_iterator begin_overridden_methods() const;
2076 method_iterator end_overridden_methods() const;
2077 unsigned size_overridden_methods() const;
2078
2079 using overridden_method_range = llvm::iterator_range<
2080 llvm::TinyPtrVector<const CXXMethodDecl *>::const_iterator>;
2081
2082 overridden_method_range overridden_methods() const;
2083
2084 /// Return the parent of this method declaration, which
2085 /// is the class in which this method is defined.
2086 const CXXRecordDecl *getParent() const {
2087 return cast<CXXRecordDecl>(FunctionDecl::getParent());
2088 }
2089
2090 /// Return the parent of this method declaration, which
2091 /// is the class in which this method is defined.
2092 CXXRecordDecl *getParent() {
2093 return const_cast<CXXRecordDecl *>(
2094 cast<CXXRecordDecl>(FunctionDecl::getParent()));
2095 }
2096
2097 /// Return the type of the \c this pointer.
2098 ///
2099 /// Should only be called for instance (i.e., non-static) methods. Note
2100 /// that for the call operator of a lambda closure type, this returns the
2101 /// desugared 'this' type (a pointer to the closure type), not the captured
2102 /// 'this' type.
2103 QualType getThisType() const;
2104
2105 /// Return the type of the object pointed by \c this.
2106 ///
2107 /// See getThisType() for usage restriction.
2108 QualType getThisObjectType() const;
2109
2110 static QualType getThisType(const FunctionProtoType *FPT,
2111 const CXXRecordDecl *Decl);
2112
2113 static QualType getThisObjectType(const FunctionProtoType *FPT,
2114 const CXXRecordDecl *Decl);
2115
2116 Qualifiers getMethodQualifiers() const {
2117 return getType()->castAs<FunctionProtoType>()->getMethodQuals();
2118 }
2119
2120 /// Retrieve the ref-qualifier associated with this method.
2121 ///
2122 /// In the following example, \c f() has an lvalue ref-qualifier, \c g()
2123 /// has an rvalue ref-qualifier, and \c h() has no ref-qualifier.
2124 /// @code
2125 /// struct X {
2126 /// void f() &;
2127 /// void g() &&;
2128 /// void h();
2129 /// };
2130 /// @endcode
2131 RefQualifierKind getRefQualifier() const {
2132 return getType()->castAs<FunctionProtoType>()->getRefQualifier();
2133 }
2134
2135 bool hasInlineBody() const;
2136
2137 /// Determine whether this is a lambda closure type's static member
2138 /// function that is used for the result of the lambda's conversion to
2139 /// function pointer (for a lambda with no captures).
2140 ///
2141 /// The function itself, if used, will have a placeholder body that will be
2142 /// supplied by IR generation to either forward to the function call operator
2143 /// or clone the function call operator.
2144 bool isLambdaStaticInvoker() const;
2145
2146 /// Find the method in \p RD that corresponds to this one.
2147 ///
2148 /// Find if \p RD or one of the classes it inherits from override this method.
2149 /// If so, return it. \p RD is assumed to be a subclass of the class defining
2150 /// this method (or be the class itself), unless \p MayBeBase is set to true.
2151 CXXMethodDecl *
2152 getCorrespondingMethodInClass(const CXXRecordDecl *RD,
2153 bool MayBeBase = false);
2154
2155 const CXXMethodDecl *
2156 getCorrespondingMethodInClass(const CXXRecordDecl *RD,
2157 bool MayBeBase = false) const {
2158 return const_cast<CXXMethodDecl *>(this)
2159 ->getCorrespondingMethodInClass(RD, MayBeBase);
2160 }
2161
2162 /// Find if \p RD declares a function that overrides this function, and if so,
2163 /// return it. Does not search base classes.
2164 CXXMethodDecl *getCorrespondingMethodDeclaredInClass(const CXXRecordDecl *RD,
2165 bool MayBeBase = false);
2166 const CXXMethodDecl *
2167 getCorrespondingMethodDeclaredInClass(const CXXRecordDecl *RD,
2168 bool MayBeBase = false) const {
2169 return const_cast<CXXMethodDecl *>(this)
2170 ->getCorrespondingMethodDeclaredInClass(RD, MayBeBase);
2171 }
2172
2173 // Implement isa/cast/dyncast/etc.
2174 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2175 static bool classofKind(Kind K) {
2176 return K >= firstCXXMethod && K <= lastCXXMethod;
2177 }
2178};
2179
2180/// Represents a C++ base or member initializer.
2181///
2182/// This is part of a constructor initializer that
2183/// initializes one non-static member variable or one base class. For
2184/// example, in the following, both 'A(a)' and 'f(3.14159)' are member
2185/// initializers:
2186///
2187/// \code
2188/// class A { };
2189/// class B : public A {
2190/// float f;
2191/// public:
2192/// B(A& a) : A(a), f(3.14159) { }
2193/// };
2194/// \endcode
2195class CXXCtorInitializer final {
2196 /// Either the base class name/delegating constructor type (stored as
2197 /// a TypeSourceInfo*), an normal field (FieldDecl), or an anonymous field
2198 /// (IndirectFieldDecl*) being initialized.
2199 llvm::PointerUnion<TypeSourceInfo *, FieldDecl *, IndirectFieldDecl *>
2200 Initializee;
2201
2202 /// The source location for the field name or, for a base initializer
2203 /// pack expansion, the location of the ellipsis.
2204 ///
2205 /// In the case of a delegating
2206 /// constructor, it will still include the type's source location as the
2207 /// Initializee points to the CXXConstructorDecl (to allow loop detection).
2208 SourceLocation MemberOrEllipsisLocation;
2209
2210 /// The argument used to initialize the base or member, which may
2211 /// end up constructing an object (when multiple arguments are involved).
2212 Stmt *Init;
2213
2214 /// Location of the left paren of the ctor-initializer.
2215 SourceLocation LParenLoc;
2216
2217 /// Location of the right paren of the ctor-initializer.
2218 SourceLocation RParenLoc;
2219
2220 /// If the initializee is a type, whether that type makes this
2221 /// a delegating initialization.
2222 unsigned IsDelegating : 1;
2223
2224 /// If the initializer is a base initializer, this keeps track
2225 /// of whether the base is virtual or not.
2226 unsigned IsVirtual : 1;
2227
2228 /// Whether or not the initializer is explicitly written
2229 /// in the sources.
2230 unsigned IsWritten : 1;
2231
2232 /// If IsWritten is true, then this number keeps track of the textual order
2233 /// of this initializer in the original sources, counting from 0.
2234 unsigned SourceOrder : 13;
2235
2236public:
2237 /// Creates a new base-class initializer.
2238 explicit
2239 CXXCtorInitializer(ASTContext &Context, TypeSourceInfo *TInfo, bool IsVirtual,
2240 SourceLocation L, Expr *Init, SourceLocation R,
2241 SourceLocation EllipsisLoc);
2242
2243 /// Creates a new member initializer.
2244 explicit
2245 CXXCtorInitializer(ASTContext &Context, FieldDecl *Member,
2246 SourceLocation MemberLoc, SourceLocation L, Expr *Init,
2247 SourceLocation R);
2248
2249 /// Creates a new anonymous field initializer.
2250 explicit
2251 CXXCtorInitializer(ASTContext &Context, IndirectFieldDecl *Member,
2252 SourceLocation MemberLoc, SourceLocation L, Expr *Init,
2253 SourceLocation R);
2254
2255 /// Creates a new delegating initializer.
2256 explicit
2257 CXXCtorInitializer(ASTContext &Context, TypeSourceInfo *TInfo,
2258 SourceLocation L, Expr *Init, SourceLocation R);
2259
2260 /// \return Unique reproducible object identifier.
2261 int64_t getID(const ASTContext &Context) const;
2262
2263 /// Determine whether this initializer is initializing a base class.
2264 bool isBaseInitializer() const {
2265 return Initializee.is<TypeSourceInfo*>() && !IsDelegating;
2266 }
2267
2268 /// Determine whether this initializer is initializing a non-static
2269 /// data member.
2270 bool isMemberInitializer() const { return Initializee.is<FieldDecl*>(); }
2271
2272 bool isAnyMemberInitializer() const {
2273 return isMemberInitializer() || isIndirectMemberInitializer();
2274 }
2275
2276 bool isIndirectMemberInitializer() const {
2277 return Initializee.is<IndirectFieldDecl*>();
2278 }
2279
2280 /// Determine whether this initializer is an implicit initializer
2281 /// generated for a field with an initializer defined on the member
2282 /// declaration.
2283 ///
2284 /// In-class member initializers (also known as "non-static data member
2285 /// initializations", NSDMIs) were introduced in C++11.
2286 bool isInClassMemberInitializer() const {
2287 return Init->getStmtClass() == Stmt::CXXDefaultInitExprClass;
2288 }
2289
2290 /// Determine whether this initializer is creating a delegating
2291 /// constructor.
2292 bool isDelegatingInitializer() const {
2293 return Initializee.is<TypeSourceInfo*>() && IsDelegating;
2294 }
2295
2296 /// Determine whether this initializer is a pack expansion.
2297 bool isPackExpansion() const {
2298 return isBaseInitializer() && MemberOrEllipsisLocation.isValid();
2299 }
2300
2301 // For a pack expansion, returns the location of the ellipsis.
2302 SourceLocation getEllipsisLoc() const {
2303 assert(isPackExpansion() && "Initializer is not a pack expansion")((isPackExpansion() && "Initializer is not a pack expansion"
) ? static_cast<void> (0) : __assert_fail ("isPackExpansion() && \"Initializer is not a pack expansion\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/include/clang/AST/DeclCXX.h"
, 2303, __PRETTY_FUNCTION__))
;
2304 return MemberOrEllipsisLocation;
2305 }
2306
2307 /// If this is a base class initializer, returns the type of the
2308 /// base class with location information. Otherwise, returns an NULL
2309 /// type location.
2310 TypeLoc getBaseClassLoc() const;
2311
2312 /// If this is a base class initializer, returns the type of the base class.
2313 /// Otherwise, returns null.
2314 const Type *getBaseClass() const;
2315
2316 /// Returns whether the base is virtual or not.
2317 bool isBaseVirtual() const {
2318 assert(isBaseInitializer() && "Must call this on base initializer!")((isBaseInitializer() && "Must call this on base initializer!"
) ? static_cast<void> (0) : __assert_fail ("isBaseInitializer() && \"Must call this on base initializer!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/include/clang/AST/DeclCXX.h"
, 2318, __PRETTY_FUNCTION__))
;
2319
2320 return IsVirtual;
2321 }
2322
2323 /// Returns the declarator information for a base class or delegating
2324 /// initializer.
2325 TypeSourceInfo *getTypeSourceInfo() const {
2326 return Initializee.dyn_cast<TypeSourceInfo *>();
2327 }
2328
2329 /// If this is a member initializer, returns the declaration of the
2330 /// non-static data member being initialized. Otherwise, returns null.
2331 FieldDecl *getMember() const {
2332 if (isMemberInitializer())
2333 return Initializee.get<FieldDecl*>();
2334 return nullptr;
2335 }
2336
2337 FieldDecl *getAnyMember() const {
2338 if (isMemberInitializer())
2339 return Initializee.get<FieldDecl*>();
2340 if (isIndirectMemberInitializer())
2341 return Initializee.get<IndirectFieldDecl*>()->getAnonField();
2342 return nullptr;
2343 }
2344
2345 IndirectFieldDecl *getIndirectMember() const {
2346 if (isIndirectMemberInitializer())
2347 return Initializee.get<IndirectFieldDecl*>();
2348 return nullptr;
2349 }
2350
2351 SourceLocation getMemberLocation() const {
2352 return MemberOrEllipsisLocation;
2353 }
2354
2355 /// Determine the source location of the initializer.
2356 SourceLocation getSourceLocation() const;
2357
2358 /// Determine the source range covering the entire initializer.
2359 SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__));
2360
2361 /// Determine whether this initializer is explicitly written
2362 /// in the source code.
2363 bool isWritten() const { return IsWritten; }
2364
2365 /// Return the source position of the initializer, counting from 0.
2366 /// If the initializer was implicit, -1 is returned.
2367 int getSourceOrder() const {
2368 return IsWritten ? static_cast<int>(SourceOrder) : -1;
2369 }
2370
2371 /// Set the source order of this initializer.
2372 ///
2373 /// This can only be called once for each initializer; it cannot be called
2374 /// on an initializer having a positive number of (implicit) array indices.
2375 ///
2376 /// This assumes that the initializer was written in the source code, and
2377 /// ensures that isWritten() returns true.
2378 void setSourceOrder(int Pos) {
2379 assert(!IsWritten &&((!IsWritten && "setSourceOrder() used on implicit initializer"
) ? static_cast<void> (0) : __assert_fail ("!IsWritten && \"setSourceOrder() used on implicit initializer\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/include/clang/AST/DeclCXX.h"
, 2380, __PRETTY_FUNCTION__))
2380 "setSourceOrder() used on implicit initializer")((!IsWritten && "setSourceOrder() used on implicit initializer"
) ? static_cast<void> (0) : __assert_fail ("!IsWritten && \"setSourceOrder() used on implicit initializer\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/include/clang/AST/DeclCXX.h"
, 2380, __PRETTY_FUNCTION__))
;
2381 assert(SourceOrder == 0 &&((SourceOrder == 0 && "calling twice setSourceOrder() on the same initializer"
) ? static_cast<void> (0) : __assert_fail ("SourceOrder == 0 && \"calling twice setSourceOrder() on the same initializer\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/include/clang/AST/DeclCXX.h"
, 2382, __PRETTY_FUNCTION__))
2382 "calling twice setSourceOrder() on the same initializer")((SourceOrder == 0 && "calling twice setSourceOrder() on the same initializer"
) ? static_cast<void> (0) : __assert_fail ("SourceOrder == 0 && \"calling twice setSourceOrder() on the same initializer\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/include/clang/AST/DeclCXX.h"
, 2382, __PRETTY_FUNCTION__))
;
2383 assert(Pos >= 0 &&((Pos >= 0 && "setSourceOrder() used to make an initializer implicit"
) ? static_cast<void> (0) : __assert_fail ("Pos >= 0 && \"setSourceOrder() used to make an initializer implicit\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/include/clang/AST/DeclCXX.h"
, 2384, __PRETTY_FUNCTION__))
2384 "setSourceOrder() used to make an initializer implicit")((Pos >= 0 && "setSourceOrder() used to make an initializer implicit"
) ? static_cast<void> (0) : __assert_fail ("Pos >= 0 && \"setSourceOrder() used to make an initializer implicit\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/include/clang/AST/DeclCXX.h"
, 2384, __PRETTY_FUNCTION__))
;
2385 IsWritten = true;
2386 SourceOrder = static_cast<unsigned>(Pos);
2387 }
2388
2389 SourceLocation getLParenLoc() const { return LParenLoc; }
2390 SourceLocation getRParenLoc() const { return RParenLoc; }
2391
2392 /// Get the initializer.
2393 Expr *getInit() const { return static_cast<Expr *>(Init); }
2394};
2395
2396/// Description of a constructor that was inherited from a base class.
2397class InheritedConstructor {
2398 ConstructorUsingShadowDecl *Shadow = nullptr;
2399 CXXConstructorDecl *BaseCtor = nullptr;
2400
2401public:
2402 InheritedConstructor() = default;
2403 InheritedConstructor(ConstructorUsingShadowDecl *Shadow,
2404 CXXConstructorDecl *BaseCtor)
2405 : Shadow(Shadow), BaseCtor(BaseCtor) {}
2406
2407 explicit operator bool() const { return Shadow; }
2408
2409 ConstructorUsingShadowDecl *getShadowDecl() const { return Shadow; }
2410 CXXConstructorDecl *getConstructor() const { return BaseCtor; }
2411};
2412
2413/// Represents a C++ constructor within a class.
2414///
2415/// For example:
2416///
2417/// \code
2418/// class X {
2419/// public:
2420/// explicit X(int); // represented by a CXXConstructorDecl.
2421/// };
2422/// \endcode
2423class CXXConstructorDecl final
2424 : public CXXMethodDecl,
2425 private llvm::TrailingObjects<CXXConstructorDecl, InheritedConstructor,
2426 ExplicitSpecifier> {
2427 // This class stores some data in DeclContext::CXXConstructorDeclBits
2428 // to save some space. Use the provided accessors to access it.
2429
2430 /// \name Support for base and member initializers.
2431 /// \{
2432 /// The arguments used to initialize the base or member.
2433 LazyCXXCtorInitializersPtr CtorInitializers;
2434
2435 CXXConstructorDecl(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2436 const DeclarationNameInfo &NameInfo, QualType T,
2437 TypeSourceInfo *TInfo, ExplicitSpecifier ES, bool isInline,
2438 bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind,
2439 InheritedConstructor Inherited,
2440 Expr *TrailingRequiresClause);
2441
2442 void anchor() override;
2443
2444 size_t numTrailingObjects(OverloadToken<InheritedConstructor>) const {
2445 return CXXConstructorDeclBits.IsInheritingConstructor;
2446 }
2447 size_t numTrailingObjects(OverloadToken<ExplicitSpecifier>) const {
2448 return CXXConstructorDeclBits.HasTrailingExplicitSpecifier;
2449 }
2450
2451 ExplicitSpecifier getExplicitSpecifierInternal() const {
2452 if (CXXConstructorDeclBits.HasTrailingExplicitSpecifier)
2453 return *getTrailingObjects<ExplicitSpecifier>();
2454 return ExplicitSpecifier(
2455 nullptr, CXXConstructorDeclBits.IsSimpleExplicit
2456 ? ExplicitSpecKind::ResolvedTrue
2457